├── README.md ├── Cargo.toml ├── src ├── main.rs ├── misc.rs ├── psqt.rs ├── timeman.rs ├── benchmark.rs ├── bitbases.rs ├── ucioption.rs ├── tt.rs ├── material.rs ├── threads.rs ├── uci.rs ├── pawns.rs ├── movegen.rs ├── movepick.rs ├── bitboard.rs └── types.rs └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Rustfish 2 | Rust port of Stockfish 3 | 4 | Compile with: cargo build --release 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustfish" 3 | version = "0.1.0" 4 | authors = ["Syzygy"] 5 | 6 | [dependencies] 7 | memmap = "0.6.2" 8 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | extern crate memmap; 4 | 5 | mod benchmark; 6 | mod bitbases; 7 | #[macro_use] 8 | mod bitboard; 9 | mod endgame; 10 | mod evaluate; 11 | mod material; 12 | mod misc; 13 | mod movegen; 14 | mod movepick; 15 | mod pawns; 16 | mod position; 17 | mod psqt; 18 | mod search; 19 | mod tb; 20 | mod threads; 21 | mod timeman; 22 | mod tt; 23 | mod types; 24 | mod uci; 25 | mod ucioption; 26 | 27 | use std::thread; 28 | 29 | fn main() { 30 | println!("{}", misc::engine_info(false)); 31 | 32 | ucioption::init(); 33 | psqt::init(); 34 | bitboard::init(); 35 | position::zobrist::init(); 36 | bitbases::init(); 37 | search::init(); 38 | pawns::init(); 39 | endgame::init(); 40 | tt::resize(ucioption::get_i32("Hash") as usize); 41 | threads::init(ucioption::get_i32("Threads") as usize); 42 | tb::init(ucioption::get_string("SyzygyPath")); 43 | search::clear(); 44 | 45 | // To avoid a stack overflow, we create a thread with a large 46 | // enough stack size to run the UI. 47 | let builder = thread::Builder::new().stack_size(16 * 1024 * 1024); 48 | let ui_thread = builder.spawn(|| uci::cmd_loop()).unwrap(); 49 | let _ = ui_thread.join(); 50 | // uci::cmd_loop(); 51 | 52 | threads::free(); 53 | tb::free(); 54 | tt::free(); 55 | ucioption::free(); 56 | } 57 | -------------------------------------------------------------------------------- /src/misc.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | #[derive(Clone, Copy)] 4 | pub struct Prng(u64); 5 | 6 | // xorshift64star Pseudo-Random Number Generator 7 | // This class is based on original code written and dedicated 8 | // to the public domain by Sebastiano Vigna (2014). 9 | // It has the following characteristics: 10 | // 11 | // - Outputs 64-bit numbers 12 | // - Passes Dieharder and SmallCrush test batteries 13 | // - Does not require warm-up, no zeroland to escape 14 | // - Internal state is a single 64-bit integer 15 | // - Period is 2^64 - 1 16 | // - Speed: 1.60 ns/call (Core i7 @3.40GHz) 17 | // 18 | // For further analysis see 19 | // 20 | 21 | impl Prng { 22 | pub fn new(seed: u64) -> Prng { 23 | Prng(seed) 24 | } 25 | 26 | pub fn rand64(&mut self) -> u64 { 27 | (*self).0 ^= (*self).0 >> 12; 28 | (*self).0 ^= (*self).0 << 25; 29 | (*self).0 ^= (*self).0 >> 27; 30 | u64::wrapping_mul(self.0, 2685821657736338717) 31 | } 32 | } 33 | 34 | pub fn engine_info(to_uci: bool) -> String { 35 | // let months = &"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"; 36 | 37 | format!("Rustfish 10 dev{}", 38 | if to_uci { 39 | "\nid author T. Romstad, M. Costalba, J. Kiiski, G. Linscott" 40 | } else { 41 | " by Syzygy based on Stockfish" 42 | }) 43 | } 44 | 45 | -------------------------------------------------------------------------------- /src/psqt.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use bitboard::*; 4 | use types::*; 5 | 6 | use std; 7 | 8 | macro_rules! S { ($x:expr, $y:expr) => (Score(($y << 16) + $x)) } 9 | 10 | const BONUS: [[[Score; 4]; 8]; 6] = [ 11 | [ // Pawn 12 | [ S!( 0, 0), S!( 0, 0), S!( 0, 0), S!( 0, 0) ], 13 | [ S!(-11, 7), S!( 6,-4), S!( 7, 8), S!( 3,-2) ], 14 | [ S!(-18,-4), S!( -2,-5), S!( 19, 5), S!(24, 4) ], 15 | [ S!(-17, 3), S!( -9, 3), S!( 20,-8), S!(35,-3) ], 16 | [ S!( -6, 8), S!( 5, 9), S!( 3, 7), S!(21,-6) ], 17 | [ S!( -6, 8), S!( -8,-5), S!( -6, 2), S!(-2, 4) ], 18 | [ S!( -4, 3), S!( 20,-9), S!( -8, 1), S!(-4,18) ], 19 | [ S!( 0, 0), S!( 0, 0), S!( 0, 0), S!( 0, 0) ] 20 | ], 21 | [ // Knight 22 | [ S!(-161,-105), S!(-96,-82), S!(-80,-46), S!(-73,-14) ], 23 | [ S!( -83, -69), S!(-43,-54), S!(-21,-17), S!(-10, 9) ], 24 | [ S!( -71, -50), S!(-22,-39), S!( 0, -7), S!( 9, 28) ], 25 | [ S!( -25, -41), S!( 18,-25), S!( 43, 6), S!( 47, 38) ], 26 | [ S!( -26, -46), S!( 16,-25), S!( 38, 3), S!( 50, 40) ], 27 | [ S!( -11, -54), S!( 37,-38), S!( 56, -7), S!( 65, 27) ], 28 | [ S!( -63, -65), S!(-19,-50), S!( 5,-24), S!( 14, 13) ], 29 | [ S!(-195,-109), S!(-67,-89), S!(-42,-50), S!(-29,-13) ] 30 | ], 31 | [ // Bishop 32 | [ S!(-44,-58), S!(-13,-31), S!(-25,-37), S!(-34,-19) ], 33 | [ S!(-20,-34), S!( 20, -9), S!( 12,-14), S!( 1, 4) ], 34 | [ S!( -9,-23), S!( 27, 0), S!( 21, -3), S!( 11, 16) ], 35 | [ S!(-11,-26), S!( 28, -3), S!( 21, -5), S!( 10, 16) ], 36 | [ S!(-11,-26), S!( 27, -4), S!( 16, -7), S!( 9, 14) ], 37 | [ S!(-17,-24), S!( 16, -2), S!( 12, 0), S!( 2, 13) ], 38 | [ S!(-23,-34), S!( 17,-10), S!( 6,-12), S!( -2, 6) ], 39 | [ S!(-35,-55), S!(-11,-32), S!(-19,-36), S!(-29,-17) ] 40 | ], 41 | [ // Rook 42 | [ S!(-25, 0), S!(-16, 0), S!(-16, 0), S!(-9, 0) ], 43 | [ S!(-21, 0), S!( -8, 0), S!( -3, 0), S!( 0, 0) ], 44 | [ S!(-21, 0), S!( -9, 0), S!( -4, 0), S!( 2, 0) ], 45 | [ S!(-22, 0), S!( -6, 0), S!( -1, 0), S!( 2, 0) ], 46 | [ S!(-22, 0), S!( -7, 0), S!( 0, 0), S!( 1, 0) ], 47 | [ S!(-21, 0), S!( -7, 0), S!( 0, 0), S!( 2, 0) ], 48 | [ S!(-12, 0), S!( 4, 0), S!( 8, 0), S!(12, 0) ], 49 | [ S!(-23, 0), S!(-15, 0), S!(-11, 0), S!(-5, 0) ] 50 | ], 51 | [ // Queen 52 | [ S!( 0,-71), S!(-4,-56), S!(-3,-42), S!(-1,-29) ], 53 | [ S!(-4,-56), S!( 6,-30), S!( 9,-21), S!( 8, -5) ], 54 | [ S!(-2,-39), S!( 6,-17), S!( 9, -8), S!( 9, 5) ], 55 | [ S!(-1,-29), S!( 8, -5), S!(10, 9), S!( 7, 19) ], 56 | [ S!(-3,-27), S!( 9, -5), S!( 8, 10), S!( 7, 21) ], 57 | [ S!(-2,-40), S!( 6,-16), S!( 8,-10), S!(10, 3) ], 58 | [ S!(-2,-55), S!( 7,-30), S!( 7,-21), S!( 6, -6) ], 59 | [ S!(-1,-74), S!(-4,-55), S!(-1,-43), S!( 0,-30) ] 60 | ], 61 | [ // King 62 | [ S!(267, 0), S!(320, 48), S!(270, 75), S!(195, 84) ], 63 | [ S!(264, 43), S!(304, 92), S!(238,143), S!(180,132) ], 64 | [ S!(200, 83), S!(245,138), S!(176,167), S!(110,165) ], 65 | [ S!(177,106), S!(185,169), S!(148,169), S!(110,179) ], 66 | [ S!(149,108), S!(177,163), S!(115,200), S!( 66,203) ], 67 | [ S!(118, 95), S!(159,155), S!( 84,176), S!( 41,174) ], 68 | [ S!( 87, 50), S!(128, 99), S!( 63,122), S!( 20,139) ], 69 | [ S!( 63, 9), S!( 88, 55), S!( 47, 80), S!( 0, 90) ] 70 | ] 71 | ]; 72 | 73 | static mut PSQ: [[Score; 64]; 16] = [[Score(0); 64]; 16]; 74 | 75 | pub fn psq(pc: Piece, s: Square) -> Score { 76 | unsafe { PSQ[pc.0 as usize][s.0 as usize] } 77 | } 78 | 79 | pub fn init() { 80 | unsafe { 81 | for i in 1..7 { 82 | let pc = Piece(i); 83 | let v = Score::make(piece_value(MG, pc).0, piece_value(EG, pc).0); 84 | 85 | for s in ALL_SQUARES { 86 | let f = std::cmp::min(s.file(), FILE_H - s.file()); 87 | PSQ[pc.0 as usize][s.0 as usize] = v 88 | + BONUS[(pc.0 - 1) as usize][s.rank() as usize][f as usize]; 89 | PSQ[(!pc).0 as usize][(!s).0 as usize] = 90 | -PSQ[pc.0 as usize][s.0 as usize]; 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/timeman.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use search; 4 | use types::*; 5 | use ucioption; 6 | 7 | use std; 8 | 9 | static mut START_TIME: Option = None; 10 | static mut OPTIMUM_TIME: i64 = 0; 11 | static mut MAXIMUM_TIME: i64 = 0; 12 | 13 | pub fn optimum() -> i64 { 14 | unsafe { OPTIMUM_TIME } 15 | } 16 | 17 | pub fn maximum() -> i64 { 18 | unsafe { MAXIMUM_TIME } 19 | } 20 | 21 | pub fn elapsed() -> i64 { 22 | let duration = unsafe { START_TIME.unwrap().elapsed() }; 23 | (duration.as_secs() * 1000 + (duration.subsec_nanos() / 1000000) as u64) 24 | as i64 25 | } 26 | 27 | #[derive(PartialEq, Eq)] 28 | enum TimeType { OptimumTime, MaxTime } 29 | use self::TimeType::*; 30 | 31 | // Plan time management at most this many moves ahread 32 | const MOVE_HORIZON: i32 = 50; 33 | // When in trouble, we can step over reserved time with this ratio 34 | const MAX_RATIO: f64 = 7.3; 35 | // But we must not steal time from remaining moves over this ratio 36 | const STEAL_RATIO: f64 = 0.34; 37 | 38 | // importance() is a skew-logistic function based on naive statistical 39 | // analysis of "how many games are still undecided after n half moves". 40 | // The game is considered "undecided" as long as neither side has >275cp 41 | // advantage. Data was extracted from the CCRL game database with some 42 | // simply filtering criteria. 43 | 44 | fn importance(ply: i32) -> f64 { 45 | const XSCALE: f64 = 6.85; 46 | const XSHIFT: f64 = 64.5; 47 | const SKEW: f64 = 0.171; 48 | 49 | (1. + ((ply as f64 - XSHIFT) / XSCALE).exp()).powf(-SKEW) 50 | + std::f64::MIN_POSITIVE 51 | } 52 | 53 | fn remaining( 54 | my_time: i64, movestogo: i32, ply: i32, slow_mover: i64, 55 | time_type: TimeType 56 | ) -> i64 { 57 | let max_ratio = if time_type == OptimumTime { 1. } else { MAX_RATIO }; 58 | let steal_ratio = if time_type == OptimumTime { 0. } else { STEAL_RATIO }; 59 | 60 | let move_importance = (importance(ply) * slow_mover as f64) / 100.; 61 | let mut other_moves_importance = 0.; 62 | 63 | for i in 1..movestogo { 64 | other_moves_importance += importance(ply + 2 * i); 65 | } 66 | 67 | let ratio1 = (max_ratio * move_importance) / 68 | (max_ratio * move_importance + other_moves_importance); 69 | let ratio2 = (move_importance + steal_ratio * other_moves_importance) / 70 | (move_importance + other_moves_importance); 71 | 72 | (my_time as f64 * ratio1.min(ratio2)) as i64 73 | } 74 | 75 | // init() is called at the beginning of the search and calculates the allowed 76 | // thinking time out of the time control and current game ply. We support 77 | // four different kinds of time controls, passed in 'limits': 78 | // 79 | // inc == 0 && movestogo == 0 means: x basetime [sudden death!] 80 | // inc == 0 && movestogo != 0 means: x moves in y minutes 81 | // inc > 0 && movestogo == 0 means: x basetime + z increment 82 | // inc > 0 && movestogo != 0 means: x moves in y minutes + z increment 83 | 84 | pub fn init(limits: &mut search::LimitsType, us: Color, ply: i32) 85 | { 86 | let min_think_time = ucioption::get_i32("Minimum Thinking Time") as i64; 87 | let move_overhead = ucioption::get_i32("Move Overhead") as i64; 88 | let slow_mover = ucioption::get_i32("Slow Mover") as i64; 89 | 90 | unsafe { 91 | START_TIME = limits.start_time; 92 | let time = std::cmp::max(limits.time[us.0 as usize], min_think_time); 93 | OPTIMUM_TIME = time; 94 | MAXIMUM_TIME = time; 95 | } 96 | 97 | let max_mtg = if limits.movestogo != 0 98 | { std::cmp::min(limits.movestogo, MOVE_HORIZON) } 99 | else 100 | { MOVE_HORIZON }; 101 | 102 | // We calculate optimum time usage for different hypothetical "moves to go" 103 | // values and choose the minimum of calculated search time values. Usually 104 | // the greates hyp_mtg givse the minimum values. 105 | for hyp_mtg in 1..(max_mtg + 1) { 106 | // Calculate thinking time for hypothetical "moves to go" value 107 | let mut hyp_my_time = limits.time[us.0 as usize] 108 | + limits.inc[us.0 as usize] * (hyp_mtg - 1) as i64 109 | - move_overhead * (2 + std::cmp::min(hyp_mtg, 40) as i64); 110 | 111 | hyp_my_time = std::cmp::max(hyp_my_time, 0); 112 | 113 | let t1 = min_think_time 114 | + remaining(hyp_my_time, hyp_mtg, ply, slow_mover, OptimumTime); 115 | let t2 = min_think_time 116 | + remaining(hyp_my_time, hyp_mtg, ply, slow_mover, MaxTime); 117 | 118 | unsafe { 119 | OPTIMUM_TIME = std::cmp::min(t1, OPTIMUM_TIME); 120 | MAXIMUM_TIME = std::cmp::min(t2, MAXIMUM_TIME); 121 | } 122 | } 123 | 124 | if ucioption::get_bool("Ponder") { 125 | unsafe { 126 | OPTIMUM_TIME += OPTIMUM_TIME / 4; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/benchmark.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use position::Position; 4 | 5 | use std; 6 | use std::fs::File; 7 | use std::io::BufRead; 8 | 9 | const DEFAULTS: [&str; 45] = [ 10 | "setoption name UCI_Chess960 value false", 11 | "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", 12 | "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10", 13 | "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11", 14 | "4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19", 15 | "rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14 moves d4e6", 16 | "r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14 moves g2g4", 17 | "r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15", 18 | "r1bbk1nr/pp3p1p/2n5/1N4p1/2Np1B2/8/PPP2PPP/2KR1B1R w kq - 0 13", 19 | "r1bq1rk1/ppp1nppp/4n3/3p3Q/3P4/1BP1B3/PP1N2PP/R4RK1 w - - 1 16", 20 | "4r1k1/r1q2ppp/ppp2n2/4P3/5Rb1/1N1BQ3/PPP3PP/R5K1 w - - 1 17", 21 | "2rqkb1r/ppp2p2/2npb1p1/1N1Nn2p/2P1PP2/8/PP2B1PP/R1BQK2R b KQ - 0 11", 22 | "r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16", 23 | "3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22", 24 | "r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18", 25 | "4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22", 26 | "3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26", 27 | "6k1/6p1/6Pp/ppp5/3pn2P/1P3K2/1PP2P2/3N4 b - - 0 1", 28 | "3b4/5kp1/1p1p1p1p/pP1PpP1P/P1P1P3/3KN3/8/8 w - - 0 1", 29 | "2K5/p7/7P/5pR1/8/5k2/r7/8 w - - 0 1 moves g5g6 f3e3 g6g5 e3f3", 30 | "8/6pk/1p6/8/PP3p1p/5P2/4KP1q/3Q4 w - - 0 1", 31 | "7k/3p2pp/4q3/8/4Q3/5Kp1/P6b/8 w - - 0 1", 32 | "8/2p5/8/2kPKp1p/2p4P/2P5/3P4/8 w - - 0 1", 33 | "8/1p3pp1/7p/5P1P/2k3P1/8/2K2P2/8 w - - 0 1", 34 | "8/pp2r1k1/2p1p3/3pP2p/1P1P1P1P/P5KR/8/8 w - - 0 1", 35 | "8/3p4/p1bk3p/Pp6/1Kp1PpPp/2P2P1P/2P5/5B2 b - - 0 1", 36 | "5k2/7R/4P2p/5K2/p1r2P1p/8/8/8 b - - 0 1", 37 | "6k1/6p1/P6p/r1N5/5p2/7P/1b3PP1/4R1K1 w - - 0 1", 38 | "1r3k2/4q3/2Pp3b/3Bp3/2Q2p2/1p1P2P1/1P2KP2/3N4 w - - 0 1", 39 | "6k1/4pp1p/3p2p1/P1pPb3/R7/1r2P1PP/3B1P2/6K1 w - - 0 1", 40 | "8/3p3B/5p2/5P2/p7/PP5b/k7/6K1 w - - 0 1", 41 | 42 | // 5-man positions 43 | "8/8/8/8/5kp1/P7/8/1K1N4 w - - 0 1", // Kc2 - mate 44 | "8/8/8/5N2/8/p7/8/2NK3k w - - 0 1", // Na2 - mate 45 | "8/3k4/8/8/8/4B3/4KB2/2B5 w - - 0 1", // draw 46 | 47 | // 6-man positions 48 | "8/8/1P6/5pr1/8/4R3/7k/2K5 w - - 0 1", // Re5 - mate 49 | "8/2p4P/8/kr6/6R1/8/8/1K6 w - - 0 1", // Ka2 - mate 50 | "8/8/3P3k/8/1p6/8/1P6/1K3n2 b - - 0 1", // Nd2 - draw 51 | 52 | // 7-man positions 53 | "8/R7/2q5/8/6k1/8/1P5p/K6R w - - 0 124", // Draw 54 | 55 | // Mate and stalemate positions 56 | "6k1/3b3r/1p1p4/p1n2p2/1PPNpP1q/P3Q1p1/1R1RB1P1/5K2 b - - 0 1", 57 | "r2r1n2/pp2bk2/2p1p2p/3q4/3PN1QP/2P3R1/P4PP1/5RK1 w - - 0 1", 58 | "8/8/8/8/8/6k1/6p1/6K1 w - -", 59 | "7k/7P/6K1/8/3B4/8/8/8 b - -", 60 | 61 | // Chess 960 62 | "setoption name UCI_Chess960 value true", 63 | "bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w KQkq - 0 1 moves g2g3 d7d5 d2d4 c8h3 c1g5 e8d6 g5e7 f7f6", 64 | "setoption name UCI_Chess960 value false" 65 | ]; 66 | 67 | // setup_bench() builds a list of UCI commands to be run by bench. There 68 | // are five parameters: TT size in MB, number of search threads that should 69 | // be used, the limit value spent for each position, a file name where to 70 | // look for positions in FEN format and the type of the limit: depth, perft 71 | // and movetime (in millisecs). 72 | // 73 | // bench -> search default positions up to depth 13 74 | // bench 64 1 15 -> search default positions up to depth 15 (TT = 64MB) 75 | // bench 64 4 5000 current movetime -> search current position with 4 threads 76 | // for 5 sec 77 | // bench 64 1 100000 default nodes -> search default positions for 100K nodes 78 | // each 79 | // bench 16 1 5 default perft -> run a perft 5 on default positions 80 | 81 | 82 | pub fn setup_bench(pos: &Position, args: &str) -> Vec 83 | { 84 | let mut iter = args.split_whitespace(); 85 | 86 | // Assign default values to missing arguments 87 | let tt_size = if let Some(t) = iter.next() { t } else { "16" }; 88 | let threads = if let Some(t) = iter.next() { t } else { "1" }; 89 | let limit = if let Some(t) = iter.next() { t } else { "13" }; 90 | let fen_file = if let Some(t) = iter.next() { t } else { "default" }; 91 | let limit_type = if let Some(t) = iter.next() { t } else { "depth" }; 92 | 93 | let go = format!("go {} {}", limit_type, limit); 94 | 95 | let mut fens: Vec = Vec::new(); 96 | 97 | if fen_file == "default" { 98 | for fen in DEFAULTS.iter() { 99 | fens.push(String::from(*fen)); 100 | } 101 | } else if fen_file == "current" { 102 | fens.push(pos.fen()); 103 | } else { 104 | let file = match File::open(fen_file) { 105 | Err(_) => { 106 | eprintln!("Unable to open file {}", fen_file); 107 | std::process::exit(-1); 108 | }, 109 | Ok(file) => file, 110 | }; 111 | let reader = std::io::BufReader::new(file); 112 | for fen in reader.lines() { 113 | if fen.is_ok() { 114 | break; 115 | } 116 | let fen = fen.unwrap(); 117 | if !fen.is_empty() { 118 | fens.push(fen); 119 | } 120 | } 121 | } 122 | 123 | let mut list: Vec = Vec::new(); 124 | list.push(String::from("ucinewgame")); 125 | list.push(format!("setoption name Threads value {}", threads)); 126 | list.push(format!("setoption name Hash value {}", tt_size)); 127 | 128 | for fen in fens { 129 | if fen.find("setoption") != None { 130 | list.push(fen); 131 | } else { 132 | list.push(format!("position fen {}", fen)); 133 | list.push(go.clone()); 134 | } 135 | } 136 | 137 | list 138 | } 139 | -------------------------------------------------------------------------------- /src/bitbases.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use bitboard::*; 4 | use types::*; 5 | 6 | // There are 24 possible pawn squares: the first 4 files and ranks from 2 to 7 7 | const MAX_INDEX: usize = 2*24*64*64; 8 | 9 | // Each u32 stores results of 32 positions, one per bit 10 | static mut KPK_BITBASE: [u32; MAX_INDEX / 32] = [0; MAX_INDEX / 32]; 11 | 12 | // A KPK bitbase index is an integer in [0, IndexMax] range 13 | // 14 | // Information is mapped in a way that minimizes the number of iterations: 15 | // 16 | // bit 0- 5: white king square (from A1 to H8) 17 | // bit 6-11: black king square (from A1 to H8) 18 | // bit 12: side to move (WHITE or BLACK) 19 | // bit 13-14: white pawn file (from FILE_A to FILE_D) 20 | // bit 15-17: white pawn RANK_7 - rank 21 | // (from RANK_7 - RANK_7 to RANK_7 - RANK_2) 22 | fn index(us: Color, bksq: Square, wksq: Square, psq: Square) -> usize { 23 | (wksq.0 | (bksq.0 << 6) | (us.0 << 12) | (psq.file() << 13) | ((RANK_7 - psq.rank()) << 15)) as usize 24 | } 25 | 26 | const INVALID: u8 = 0; 27 | const UNKNOWN: u8 = 1; 28 | const DRAW : u8 = 2; 29 | const WIN : u8 = 4; 30 | 31 | struct KPKPosition { 32 | us: Color, 33 | ksq: [Square; 2], 34 | psq: Square, 35 | result: u8 36 | } 37 | 38 | impl KPKPosition { 39 | fn new(idx: u32) -> KPKPosition { 40 | let ksq = [ Square((idx >> 0) & 0x3f), Square((idx >> 6) & 0x3f) ]; 41 | let us = Color((idx >> 12) & 0x01); 42 | let psq = 43 | Square::make((idx >> 13) & 0x03, RANK_7 - ((idx >> 15) & 0x07)); 44 | let result; 45 | 46 | // Check if two pieces are on the same square or if a king can be 47 | // captured 48 | if Square::distance(ksq[WHITE.0 as usize], ksq[BLACK.0 as usize]) <= 1 49 | || ksq[WHITE.0 as usize] == psq 50 | || ksq[BLACK.0 as usize] == psq 51 | || (us == WHITE 52 | && pawn_attacks(WHITE, psq) & ksq[BLACK.0 as usize] != 0) 53 | { 54 | result = INVALID; 55 | } 56 | 57 | // Immediate win if a pawn can be promoted without getting captured 58 | else if us == WHITE 59 | && psq.rank() == RANK_7 60 | && ksq[us.0 as usize] != psq + NORTH 61 | && (Square::distance(ksq[(!us).0 as usize], psq + NORTH) > 1 62 | || pseudo_attacks(KING, ksq[us.0 as usize]) & (psq + NORTH) != 0) 63 | { 64 | result = WIN; 65 | } 66 | 67 | // Immediate draw if it is a stalemate or a king captures undefended 68 | // pawn 69 | else if us == BLACK 70 | && ((pseudo_attacks(KING, ksq[us.0 as usize]) 71 | & !(pseudo_attacks(KING, ksq[(!us).0 as usize]) 72 | | pawn_attacks(!us, psq))) == 0 73 | || pseudo_attacks(KING, ksq[us.0 as usize]) 74 | & psq & !pseudo_attacks(KING, ksq[(!us).0 as usize]) != 0) 75 | { 76 | result = DRAW; 77 | } 78 | 79 | // Position will be classified later 80 | else { 81 | result = UNKNOWN; 82 | } 83 | 84 | KPKPosition { us, ksq, psq, result } 85 | } 86 | 87 | fn classify(&self, db: &Vec) -> u8 { 88 | // White to move: if one move leads to a position classified as WIN, 89 | // the result of the current position is WIN; if all moves lead to 90 | // positions classified as DRAW, the current position is classified 91 | // as DRAW; otherwise, the current position is classified as UNKNOWN. 92 | // 93 | // Black to move: if one move leads to a position classified as DRAW, 94 | // the result of the current position is DRAW; if all moves lead to 95 | // positions classified as WIN, the position is classified as WIN; 96 | // otherwise, the current current position is classified as UNKNOWN. 97 | 98 | let us = self.us; 99 | let psq = self.psq; 100 | 101 | let them = if us == WHITE { BLACK } else { WHITE }; 102 | let good = if us == WHITE { WIN } else { DRAW }; 103 | let bad = if us == WHITE { DRAW } else { WIN }; 104 | 105 | let mut r = INVALID; 106 | 107 | for s in pseudo_attacks(KING, self.ksq[us.0 as usize]) { 108 | r |= if us == WHITE { 109 | db[index(them, self.ksq[them.0 as usize], s, psq)].result 110 | } else { 111 | db[index(them, s, self.ksq[them.0 as usize], psq)].result 112 | }; 113 | } 114 | 115 | if us == WHITE { 116 | if psq.rank() < RANK_7 { 117 | r |= db[index(them, self.ksq[them.0 as usize], 118 | self.ksq[us.0 as usize], psq + NORTH)].result; 119 | } 120 | 121 | if psq.rank() == RANK_2 122 | && psq + NORTH != self.ksq[us.0 as usize] 123 | && psq + NORTH != self.ksq[them.0 as usize] 124 | { 125 | r |= db[index(them, self.ksq[them.0 as usize], 126 | self.ksq[us.0 as usize], psq + 2 * NORTH)].result; 127 | } 128 | } 129 | 130 | if r & good != 0 { good } 131 | else if r & UNKNOWN != 0 { UNKNOWN } 132 | else { bad } 133 | } 134 | } 135 | 136 | pub fn init() { 137 | let mut db: Vec = Vec::with_capacity(MAX_INDEX); 138 | 139 | // Initialize db with known win/draw positions 140 | for idx in 0..MAX_INDEX { 141 | db.push(KPKPosition::new(idx as u32)); 142 | } 143 | 144 | let mut repeat = true; 145 | 146 | // Iterate through the positions until none of the unknown positions can 147 | // be changed to either wins or draws (15 cycles needed). 148 | while repeat { 149 | repeat = false; 150 | for idx in 0..MAX_INDEX { 151 | if db[idx].result == UNKNOWN { 152 | let result = db[idx].classify(&db); 153 | if result != UNKNOWN { 154 | db[idx].result = result; 155 | repeat = true; 156 | } 157 | } 158 | } 159 | } 160 | 161 | // Map 32 results into one KPK_BITBASE[] entry 162 | for idx in 0..MAX_INDEX { 163 | if db[idx].result == WIN { 164 | unsafe { 165 | KPK_BITBASE[idx / 32] |= 1u32 << (idx & 0x1f); 166 | } 167 | } 168 | } 169 | } 170 | 171 | pub fn probe(wksq: Square, wpsq: Square, bksq: Square, us: Color) -> bool { 172 | debug_assert!(wpsq.file() <= FILE_D); 173 | 174 | let idx = index(us, bksq, wksq, wpsq); 175 | unsafe { KPK_BITBASE[idx / 32] & (1 << (idx & 0x1f)) != 0 } 176 | } 177 | -------------------------------------------------------------------------------- /src/ucioption.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use tb; 4 | use threads; 5 | use tt; 6 | 7 | use std; 8 | 9 | type OnChange = Option; 10 | 11 | struct Opt { 12 | key: &'static str, 13 | val: OptVal, 14 | on_change: OnChange, 15 | } 16 | 17 | impl Opt { 18 | pub fn new(key: &'static str, val: OptVal, on_change: OnChange) -> Opt { 19 | Opt { 20 | key: key, 21 | val: val, 22 | on_change: on_change, 23 | } 24 | } 25 | } 26 | 27 | enum OptVal { 28 | StringOpt { 29 | def: &'static str, 30 | cur: String, 31 | }, 32 | Spin { 33 | def: i32, 34 | cur: i32, 35 | min: i32, 36 | max: i32, 37 | }, 38 | Check { 39 | def: bool, 40 | cur: bool, 41 | }, 42 | Button, 43 | Combo { 44 | def: &'static str, 45 | cur: String, 46 | }, 47 | } 48 | 49 | impl OptVal { 50 | pub fn string(def: &'static str) -> OptVal { 51 | OptVal::StringOpt { 52 | def: def, 53 | cur: String::from(def), 54 | } 55 | } 56 | 57 | pub fn spin(def: i32, min: i32, max: i32) -> OptVal { 58 | OptVal::Spin { 59 | def: def, 60 | cur: def, 61 | min: min, 62 | max: max, 63 | } 64 | } 65 | 66 | pub fn check(def: bool) -> OptVal { 67 | OptVal::Check { 68 | def: def, 69 | cur: def, 70 | } 71 | } 72 | 73 | pub fn combo(def: &'static str) -> OptVal { 74 | OptVal::Combo { 75 | def: def, 76 | cur: String::from(&def[0..def.find(" var").unwrap()]) 77 | .to_lowercase(), 78 | } 79 | } 80 | } 81 | 82 | fn on_clear_hash(_: &OptVal) { 83 | tt::clear(); 84 | } 85 | 86 | fn on_hash_size(opt_val: &OptVal) { 87 | if let &OptVal::Spin { cur, .. } = opt_val { 88 | tt::resize(cur as usize); 89 | } 90 | } 91 | 92 | fn on_threads(opt_val: &OptVal) { 93 | if let &OptVal::Spin { cur, .. } = opt_val { 94 | threads::set(cur as usize); 95 | } 96 | } 97 | 98 | fn on_tb_path(opt_val: &OptVal) { 99 | if let &OptVal::StringOpt { ref cur, .. } = opt_val { 100 | tb::init(String::from(cur.as_str())); 101 | } 102 | } 103 | 104 | static mut OPTIONS: *mut Vec = 0 as *mut Vec; 105 | 106 | pub fn init() 107 | { 108 | let mut opts = Box::new(Vec::new()); 109 | opts.push(Opt::new("Contempt", OptVal::spin(18, -100, 100), None)); 110 | opts.push(Opt::new("Analysis Contempt", 111 | OptVal::combo("Off var Off var White var Black"), None)); 112 | opts.push(Opt::new("Threads", OptVal::spin(1, 1, 512), Some(on_threads))); 113 | opts.push(Opt::new("Hash", OptVal::spin(16, 1, 128 * 1024), 114 | Some(on_hash_size))); 115 | opts.push(Opt::new("Clear Hash", OptVal::Button, Some(on_clear_hash))); 116 | opts.push(Opt::new("Ponder", OptVal::check(false), None)); 117 | opts.push(Opt::new("MultiPV", OptVal::spin(1, 1, 500), None)); 118 | opts.push(Opt::new("Move Overhead", OptVal::spin(30, 0, 5000), None)); 119 | opts.push(Opt::new("Minimum Thinking Time", OptVal::spin(20, 0, 5000), 120 | None)); 121 | opts.push(Opt::new("Slow Mover", OptVal::spin(84, 10, 1000), None)); 122 | opts.push(Opt::new("UCI_AnalyseMode", OptVal::check(false), None)); 123 | opts.push(Opt::new("UCI_Chess960", OptVal::check(false), None)); 124 | opts.push(Opt::new("SyzygyPath", OptVal::string(""), 125 | Some(on_tb_path))); 126 | opts.push(Opt::new("SyzygyProbeDepth", OptVal::spin(1, 1, 100), None)); 127 | opts.push(Opt::new("Syzygy50MoveRule", OptVal::check(true), None)); 128 | opts.push(Opt::new("SyzygyProbeLimit", OptVal::spin(6, 0, 6), None)); 129 | opts.push(Opt::new("SyzygyUseDTM", OptVal::check(true), None)); 130 | unsafe { 131 | OPTIONS = Box::into_raw(opts); 132 | } 133 | } 134 | 135 | pub fn free() 136 | { 137 | let _opts = unsafe { Box::from_raw(OPTIONS) }; 138 | } 139 | 140 | pub fn print() { 141 | let opts = unsafe { Box::from_raw(OPTIONS) }; 142 | for opt in opts.iter() { 143 | print!("\noption name {} type {}", opt.key, match opt.val { 144 | OptVal::StringOpt { def, .. } => format!("string default {}", def), 145 | OptVal::Spin { def, min, max, .. } => 146 | format!("spin default {} min {} max {}", def, min, max), 147 | OptVal::Check { def, .. } => 148 | format!("check default {}", if def { true } else { false }), 149 | OptVal::Button => format!("button"), 150 | OptVal::Combo { def, .. } => format!("combo default {}", def), 151 | }); 152 | } 153 | print!("\n"); 154 | std::mem::forget(opts); 155 | } 156 | 157 | pub fn set(key: &str, val: &str) { 158 | let mut opts = unsafe { Box::from_raw(OPTIONS) }; 159 | if let Some(opt) = opts.iter_mut().find(|ref o| o.key == key) { 160 | match opt.val { 161 | OptVal::StringOpt { ref mut cur, .. } => *cur = String::from(val), 162 | OptVal::Spin { ref mut cur, .. } => *cur = val.parse().unwrap(), 163 | OptVal::Check { ref mut cur, .. } => *cur = val == "true", 164 | OptVal::Button => {}, 165 | OptVal::Combo { ref mut cur, .. } => 166 | *cur = String::from(val).to_lowercase(), 167 | } 168 | if let Some(on_change) = opt.on_change { 169 | on_change(&opt.val); 170 | } 171 | } else { 172 | println!("No such option: {}", key); 173 | } 174 | unsafe { 175 | OPTIONS = Box::into_raw(opts); 176 | } 177 | } 178 | 179 | pub fn get_i32(key: &str) -> i32 { 180 | let opts = unsafe { Box::from_raw(OPTIONS) }; 181 | let val = { 182 | let opt = opts.iter().find(|ref o| o.key == key).unwrap(); 183 | if let OptVal::Spin { cur, .. } = opt.val { cur } else { 0 } 184 | }; 185 | std::mem::forget(opts); 186 | val 187 | } 188 | 189 | pub fn get_bool(key: &str) -> bool { 190 | let opts = unsafe { Box::from_raw(OPTIONS) }; 191 | let val = { 192 | let opt = opts.iter().find(|ref o| o.key == key).unwrap(); 193 | if let OptVal::Check { cur, .. } = opt.val { cur } else { false } 194 | }; 195 | std::mem::forget(opts); 196 | val 197 | } 198 | 199 | pub fn get_string(key: &str) -> String { 200 | let opts = unsafe { Box::from_raw(OPTIONS) }; 201 | let val = { 202 | let opt = opts.iter().find(|ref o| o.key == key).unwrap(); 203 | if let OptVal::StringOpt { ref cur, ..} = opt.val { 204 | String::from(cur.as_str()) 205 | } else if let OptVal::Combo { ref cur, ..} = opt.val { 206 | String::from(cur.as_str()) 207 | } else { 208 | String::new() 209 | } 210 | }; 211 | std::mem::forget(opts); 212 | val 213 | } 214 | -------------------------------------------------------------------------------- /src/tt.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use types::*; 4 | 5 | use std; 6 | 7 | // TTEntry struct is the 10 bytes transposition-table entry, defined as below: 8 | // 9 | // key 16 bit 10 | // move 16 bit 11 | // value 16 bit 12 | // eval value 16 bit 13 | // generation 6 bit 14 | // bound type 2 bit 15 | // depth 8 bit 16 | 17 | pub struct TTEntry { 18 | key16: u16, 19 | move16: u16, 20 | value16: i16, 21 | eval16: i16, 22 | gen_bound8: u8, 23 | depth8: i8, 24 | } 25 | 26 | impl TTEntry { 27 | pub fn mov(&self) -> Move { 28 | Move(self.move16 as u32) 29 | } 30 | 31 | pub fn value(&self) -> Value { 32 | Value(self.value16 as i32) 33 | } 34 | 35 | pub fn eval(&self) -> Value { 36 | Value(self.eval16 as i32) 37 | } 38 | 39 | pub fn depth(&self) -> Depth { 40 | Depth(self.depth8 as i32) 41 | } 42 | 43 | pub fn bound(&self) -> Bound { 44 | Bound((self.gen_bound8 & 3) as u32) 45 | } 46 | 47 | pub fn save( 48 | &mut self, k: Key, v: Value, b: Bound, d: Depth, m: Move, ev: Value, 49 | g: u8 50 | ) { 51 | debug_assert!(d / ONE_PLY * ONE_PLY == d); 52 | 53 | let k16 = (k.0 >> 48) as u16; 54 | 55 | // Preserve any existing move for the same position 56 | if m != Move::NONE || k16 != self.key16 { 57 | self.move16 = m.0 as u16; 58 | } 59 | 60 | // Don't overwrite more valuable entries 61 | if k16 != self.key16 62 | || (d / ONE_PLY) as i8 > self.depth8 - 4 63 | || b == Bound::EXACT 64 | { 65 | self.key16 = k16; 66 | self.value16 = v.0 as i16; 67 | self.eval16 = ev.0 as i16; 68 | self.gen_bound8 = g | (b.0 as u8); 69 | self.depth8 = (d / ONE_PLY) as i8; 70 | } 71 | } 72 | } 73 | 74 | // The transposition table consists of a power of 2 number of clusters. 75 | // Each cluster consists of ClusterSize number of TTEntry. Each non-empty 76 | // entry contains information about exactly one position. The size of a 77 | // cluster should divide the size of a cache line size, to ensure that 78 | // clusters never cross cache lines. This ensures best cache performance, 79 | // as the cacheline is prefetched, as soon as possible. 80 | 81 | const CLUSTER_SIZE: usize = 3; 82 | 83 | struct Cluster { 84 | entry: [TTEntry; CLUSTER_SIZE], 85 | _padding: [u8; 2], // Align to a divisor of the cache line size 86 | } 87 | 88 | static mut CLUSTER_COUNT: usize = 0; 89 | static mut TABLE: *mut Cluster = 0 as *mut Cluster; 90 | static mut TABLE_CAP: usize = 0; 91 | static mut GENERATION8: u8 = 0; 92 | 93 | pub fn new_search() { 94 | unsafe { 95 | GENERATION8 += 4; // Lower two bits are used by bound 96 | } 97 | } 98 | 99 | pub fn generation() -> u8 { 100 | unsafe { GENERATION8 } 101 | } 102 | 103 | // The lowest order bits of the key are used to get the index of the cluster 104 | fn cluster(key: Key) -> &'static mut Cluster { 105 | unsafe { 106 | let p: *mut Cluster = 107 | TABLE.offset((((key.0 as u32 as u64) * 108 | (CLUSTER_COUNT as u64)) >> 32) as isize); 109 | let c: &'static mut Cluster = &mut *p; 110 | c 111 | } 112 | } 113 | 114 | // tt::resize() sets the size of the transposition table, measured in 115 | // megabytes. The transposition table consists of a power of 2 number of 116 | // clusters and each cluster consists of CLUSTER_SIZE number of TTEntry. 117 | 118 | pub fn resize(mb_size: usize) { 119 | let new_cluster_count = 120 | mb_size * 1024 * 1024 / std::mem::size_of::(); 121 | 122 | unsafe { 123 | if new_cluster_count == CLUSTER_COUNT { 124 | return; 125 | } 126 | 127 | free(); 128 | 129 | CLUSTER_COUNT = new_cluster_count; 130 | 131 | let mut v: Vec = Vec::with_capacity(new_cluster_count); 132 | TABLE = v.as_mut_ptr(); 133 | TABLE_CAP = v.capacity(); 134 | // forget in order to prevent deallocation by dropping 135 | std::mem::forget(v); 136 | } 137 | } 138 | 139 | // tt::free() deallocates the transposition table. 140 | 141 | pub fn free() { 142 | unsafe { 143 | if !TABLE.is_null() { 144 | let _ = Vec::from_raw_parts(TABLE, 0, TABLE_CAP); 145 | // deallocate by dropping 146 | } 147 | } 148 | } 149 | 150 | // tt::clear() clears the entire transposition table. It is called whenever 151 | // the table is resized or when the user asks the program to clear the table 152 | // (via the UCI interface). 153 | 154 | pub fn clear() { 155 | let tt_slice = unsafe { 156 | std::slice::from_raw_parts_mut(TABLE, CLUSTER_COUNT) 157 | }; 158 | 159 | for cluster in tt_slice.iter_mut() { 160 | for tte in cluster.entry.iter_mut() { 161 | tte.key16 = 0; 162 | tte.move16 = 0; 163 | tte.value16 = 0; 164 | tte.eval16 = 0; 165 | tte.gen_bound8 = 0; 166 | tte.depth8 = 0; 167 | tte.key16 = 0; 168 | } 169 | } 170 | } 171 | 172 | // tt::probe() looks up the current position in the transposition table. It 173 | // returns true and a pointer to the TTentry if the position is found. 174 | // Otherwise, it returns false and a pointer to an empty or least valuable 175 | // TTEntry to be replaced later. The replace value of an entry is calculated 176 | // as its depth minus 8 times its relative age. TTEntry t1 is considered more 177 | // valuable than TTEntry t2 if its replace value is greater than that of t2. 178 | 179 | pub fn probe(key: Key) -> (&'static mut TTEntry, bool) { 180 | let cl = cluster(key); 181 | // Use the high 16 bits of the hash key as key inside the cluster 182 | let key16 = (key.0 >> 48) as u16; 183 | 184 | for i in 0..CLUSTER_SIZE { 185 | if cl.entry[i].key16 == 0 || cl.entry[i].key16 == key16 { 186 | if cl.entry[i].gen_bound8 & 0xfc != generation() 187 | && cl.entry[i].key16 != 0 188 | { 189 | cl.entry[i].gen_bound8 = 190 | generation() | (cl.entry[i].bound().0 as u8); 191 | } 192 | let found = cl.entry[i].key16 != 0; 193 | return (&mut (cl.entry[i]), found); 194 | } 195 | } 196 | 197 | // Find an entry to be replaced according to the replacement strategy 198 | let mut r = 0; 199 | for i in 1..CLUSTER_SIZE { 200 | // Due to our packed storage format for generation and its cyclic 201 | // nature we add 259 (256 is the modulus plus 3 to keep the lowest 202 | // two bound bits from affecting the result) to calculate the entry 203 | // age correctly even after generation8 overflows into the next cycle. 204 | if (cl.entry[r].depth8 as i32) - 205 | ((259 + (generation() as i32) - 206 | (cl.entry[r].gen_bound8 as i32)) & 0xfc) * 2 207 | > (cl.entry[i].depth8 as i32) - 208 | ((259 + (generation() as i32) - 209 | (cl.entry[i].gen_bound8 as i32)) & 0xfc) * 2 210 | { 211 | r = i; 212 | } 213 | } 214 | 215 | (&mut (cl.entry[r]), false) 216 | } 217 | 218 | // tt::hashfull() returns an approximation of the hashtable occupation during 219 | // a search. The hash is x permill full, as per UCI protocol. 220 | 221 | pub fn hashfull() -> i32 { 222 | let tt_slice = unsafe { 223 | std::slice::from_raw_parts(TABLE, 1000 / CLUSTER_SIZE) 224 | }; 225 | 226 | let mut cnt = 0; 227 | 228 | for cluster in tt_slice.iter() { 229 | for tte in cluster.entry.iter() { 230 | if tte.gen_bound8 & 0xfc == generation() { 231 | cnt += 1; 232 | } 233 | } 234 | } 235 | 236 | cnt 237 | } 238 | -------------------------------------------------------------------------------- /src/material.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use bitboard::*; 4 | use endgame::*; 5 | use position::Position; 6 | use types::*; 7 | 8 | use std; 9 | 10 | pub struct Entry { 11 | key: Key, 12 | scaling_function: [Option; 2], 13 | evaluation_function: Option, 14 | eval_side: Color, 15 | value: i16, 16 | factor: [u8; 2], 17 | game_phase: Phase, 18 | } 19 | 20 | impl Entry { 21 | pub fn new() -> Entry { 22 | Entry { 23 | key: Key(0), 24 | scaling_function: [None; 2], 25 | evaluation_function: None, 26 | eval_side: WHITE, 27 | value: 0, 28 | factor: [0; 2], 29 | game_phase: 0, 30 | } 31 | } 32 | 33 | pub fn imbalance(&self) -> Score { 34 | Score::make(self.value as i32, self.value as i32) 35 | } 36 | 37 | pub fn game_phase(&self) -> Phase { 38 | self.game_phase 39 | } 40 | 41 | pub fn specialized_eval_exists(&self) -> bool { 42 | match self.evaluation_function { 43 | Some(_) => true, 44 | None => false, 45 | } 46 | } 47 | 48 | pub fn evaluate(&self, pos: &Position) -> Value { 49 | self.evaluation_function.unwrap()(pos, self.eval_side) 50 | } 51 | 52 | pub fn scale_factor(&self, pos: &Position, c: Color) -> ScaleFactor { 53 | let sf = match self.scaling_function[c.0 as usize] { 54 | Some(f) => f(pos, c), 55 | None => ScaleFactor::NONE, 56 | }; 57 | if sf != ScaleFactor::NONE { 58 | sf 59 | } else { 60 | ScaleFactor(self.factor[c.0 as usize] as i32) 61 | } 62 | } 63 | } 64 | 65 | // Polynomial material imbalance parameters 66 | 67 | const QUADRATIC_OURS: [[i32; 8]; 6] = [ 68 | // OUR PIECES 69 | // pair pawn knight bishop rook queen 70 | [1667, 0, 0, 0, 0, 0, 0, 0], // Bishop pair 71 | [ 40, 0, 0, 0, 0, 0, 0, 0], // Pawn 72 | [ 32, 255, -3, 0, 0, 0, 0, 0], // Knight OUR PIECES 73 | [ 0, 104, 4, 0, 0, 0, 0, 0], // Bishop 74 | [ -26, -2, 47, 105, -149, 0, 0, 0], // Rook 75 | [-189, 24, 117, 133, -134, -10, 0, 0], // Queen 76 | ]; 77 | 78 | const QUADRATIC_THEIRS: [[i32; 8]; 6] = [ 79 | // THEIR PIECES 80 | // pair pawn knight bishop rook queen 81 | [ 0, 0, 0, 0, 0, 0, 0, 0], // Bishop pair 82 | [ 36, 0, 0, 0, 0, 0, 0, 0], // Pawn 83 | [ 9, 63, 0, 0, 0, 0, 0, 0], // Knight THEIR PIECES 84 | [ 59, 65, 42, 0, 0, 0, 0, 0], // Bishop 85 | [ 46, 39, 24, -24, 0, 0, 0, 0], // Rook 86 | [ 97, 100, -42, 137, 268, 0, 0, 0], // Queen 87 | ]; 88 | 89 | // Helper used to detect a given material distribution 90 | fn is_kxk(pos: &Position, us: Color) -> bool { 91 | !more_than_one(pos.pieces_c(!us)) 92 | && pos.non_pawn_material_c(us) >= RookValueMg 93 | } 94 | 95 | fn is_kbpsks(pos: &Position, us: Color) -> bool { 96 | pos.non_pawn_material_c(us) == BishopValueMg 97 | && pos.count(us, BISHOP) == 1 98 | && pos.count(us, PAWN) >= 1 99 | } 100 | 101 | fn is_kqkrps(pos: &Position, us: Color) -> bool { 102 | pos.count(us, PAWN) == 0 103 | && pos.non_pawn_material_c(us) == QueenValueMg 104 | && pos.count(us, QUEEN) == 1 105 | && pos.count(!us, ROOK) == 1 106 | && pos.count(!us, PAWN) >= 1 107 | } 108 | 109 | // imbalance() calculates the imbalance by comparing the piece count of 110 | // each piece type for both colors. 111 | fn imbalance(pc: &[[i32; 6]; 2], us: Color) -> i32 { 112 | let them = if us == WHITE { BLACK } else { WHITE }; 113 | 114 | let mut bonus = 0; 115 | 116 | // Second-degree polynomial material imbalance, by Tord Romstad 117 | for pt1 in 0..6 { 118 | if pc[us.0 as usize][pt1] == 0 { 119 | continue; 120 | } 121 | 122 | let mut v = 0; 123 | 124 | for pt2 in 0..(pt1+1) { 125 | v += QUADRATIC_OURS[pt1][pt2] * pc[us.0 as usize][pt2] 126 | + QUADRATIC_THEIRS[pt1][pt2] * pc[them.0 as usize][pt2]; 127 | } 128 | 129 | bonus += pc[us.0 as usize][pt1] * v; 130 | } 131 | 132 | bonus 133 | } 134 | 135 | // probe() looks up the current position's material configuration in the 136 | // material hash table. It returns a pointer to the Entry if the position 137 | // is found. Otherwise a new Entry is computed and stored there, so we 138 | // don't have to recompute all when the same material configuration occurs 139 | // again. 140 | 141 | pub fn probe(pos: &Position) -> &'static mut Entry { 142 | let key = pos.material_key(); 143 | let e = pos.material_table[(key.0 & 8191) as usize].get(); 144 | let e: &'static mut Entry = unsafe { &mut *e }; 145 | 146 | if e.key == key { 147 | return e; 148 | } 149 | 150 | e.key = key; 151 | e.evaluation_function = None; 152 | e.scaling_function = [None; 2]; 153 | e.factor[WHITE.0 as usize] = ScaleFactor::NORMAL.0 as u8; 154 | e.factor[BLACK.0 as usize] = ScaleFactor::NORMAL.0 as u8; 155 | e.value = 0; 156 | 157 | // Map total non-pawn material into [PHASE_ENDGAME, PHASE_MIDGAME] 158 | let npm_w = pos.non_pawn_material_c(WHITE); 159 | let npm_b = pos.non_pawn_material_c(BLACK); 160 | let npm = 161 | std::cmp::max(ENDGAME_LIMIT, 162 | std::cmp::min(npm_w + npm_b, MIDGAME_LIMIT)); 163 | e.game_phase = 164 | (((npm - ENDGAME_LIMIT) * PHASE_MIDGAME) / 165 | (MIDGAME_LIMIT - ENDGAME_LIMIT)) as i32; 166 | 167 | // Let's look if we have a specialized evaluation function for this 168 | // particular material configuration. First we look for a fixed 169 | // configuartion one, then for a generic one. 170 | for entry in unsafe { EVAL_FNS.iter() } { 171 | for c in 0..2 { 172 | if entry.key[c] == key { 173 | e.evaluation_function = Some(entry.func); 174 | e.eval_side = Color(c as u32); 175 | return e; 176 | } 177 | } 178 | } 179 | 180 | for &c in [WHITE, BLACK].iter() { 181 | if is_kxk(pos, c) { 182 | e.evaluation_function = Some(evaluate_kxk); 183 | e.eval_side = c; 184 | return e; 185 | } 186 | } 187 | 188 | // OK, we didn't find any special evaluation function for the current 189 | // material configuration. Is there a suitable specialized scaling 190 | // function? 191 | for entry in unsafe { SCALE_FNS.iter() } { 192 | for c in 0..2 { 193 | if entry.key[c] == key { 194 | e.scaling_function[c] = Some(entry.func); 195 | return e; 196 | } 197 | } 198 | } 199 | 200 | // We didn't find any specialized scaling function, so fall back on 201 | // generic ones that refer to more than one material distributiion. 202 | // Note that in this case we don't return after setting the function. 203 | for &c in [WHITE, BLACK].iter() { 204 | if is_kbpsks(pos, c) { 205 | e.scaling_function[c.0 as usize] = Some(scale_kbpsk); 206 | } else if is_kqkrps(pos, c) { 207 | e.scaling_function[c.0 as usize] = Some(scale_kqkrps); 208 | } 209 | } 210 | 211 | if npm_w + npm_b == Value::ZERO && pos.pieces_p(PAWN) != 0 { 212 | // Only pawns on the board 213 | if pos.count(BLACK, PAWN) == 0 { 214 | debug_assert!(pos.count(WHITE, PAWN) >= 2); 215 | 216 | e.scaling_function[WHITE.0 as usize] = Some(scale_kpsk); 217 | } else if pos.count(WHITE, PAWN) == 0 { 218 | debug_assert!(pos.count(BLACK, PAWN) >= 2); 219 | 220 | e.scaling_function[BLACK.0 as usize] = Some(scale_kpsk); 221 | } else if pos.count(WHITE, PAWN) == 1 && pos.count(BLACK, PAWN) == 1 { 222 | // This is a special case because we set scaling functions 223 | // for both colors instead of only one. 224 | e.scaling_function[WHITE.0 as usize] = Some(scale_kpkp); 225 | e.scaling_function[BLACK.0 as usize] = Some(scale_kpkp); 226 | } 227 | } 228 | 229 | // Zero or just one pawn makes it difficult to win, even with a small 230 | // material advantage. This catches some trivial draws like KK, KBK 231 | // and KNK and gives a drawish scale factor for cases such as KRKBP 232 | // and KmmKm (except for KBBKN). 233 | if pos.count(WHITE, PAWN) == 0 && npm_w - npm_b <= BishopValueMg { 234 | e.factor[WHITE.0 as usize] = 235 | if npm_w < RookValueMg { ScaleFactor::DRAW.0 as u8 } 236 | else if npm_b <= BishopValueMg { 4 } else { 14 }; 237 | } 238 | 239 | if pos.count(BLACK, PAWN) == 0 && npm_b - npm_w <= BishopValueMg { 240 | e.factor[BLACK.0 as usize] = 241 | if npm_b < RookValueMg { ScaleFactor::DRAW.0 as u8 } 242 | else if npm_w <= BishopValueMg { 4 } else { 14 }; 243 | } 244 | 245 | if pos.count(WHITE, PAWN) == 1 && npm_w - npm_b <= BishopValueMg { 246 | e.factor[WHITE.0 as usize] = ScaleFactor::ONEPAWN.0 as u8; 247 | } 248 | 249 | if pos.count(BLACK, PAWN) == 1 && npm_b - npm_w <= BishopValueMg { 250 | e.factor[BLACK.0 as usize] = ScaleFactor::ONEPAWN.0 as u8; 251 | } 252 | 253 | // Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place 254 | // holder for the bishop pair "extended piece", which allows us to be 255 | // more flexible in defining bishop pair bonuses. 256 | let pc = [ 257 | [ (pos.count(WHITE, BISHOP) > 1) as i32, pos.count(WHITE, PAWN), 258 | pos.count(WHITE, KNIGHT), pos.count(WHITE, BISHOP), 259 | pos.count(WHITE, ROOK), pos.count(WHITE, QUEEN) ], 260 | [ (pos.count(BLACK, BISHOP) > 1) as i32, pos.count(BLACK, PAWN), 261 | pos.count(BLACK, KNIGHT), pos.count(BLACK, BISHOP), 262 | pos.count(BLACK, ROOK), pos.count(BLACK, QUEEN) ], 263 | ]; 264 | 265 | e.value = ((imbalance(&pc, WHITE) - imbalance(&pc, BLACK)) / 16) as i16; 266 | 267 | e 268 | } 269 | -------------------------------------------------------------------------------- /src/threads.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use material; 4 | use movegen::*; 5 | use pawns; 6 | use position::Position; 7 | use search::*; 8 | use tb; 9 | use types::*; 10 | use ucioption; 11 | 12 | use std; 13 | use std::cell::Cell; 14 | use std::sync::{Arc, Condvar, Mutex, RwLock}; 15 | use std::sync::atomic::*; 16 | use std::sync::mpsc::*; 17 | use std::thread; 18 | 19 | pub struct PosData { 20 | pub fen: String, 21 | pub moves: Vec, 22 | } 23 | 24 | pub struct SearchResult { 25 | pub depth: Depth, 26 | pub score: Value, 27 | pub pv: Vec, 28 | } 29 | 30 | pub struct ThreadState { 31 | pub exit: bool, 32 | pub searching: bool, 33 | pub clear: bool, 34 | } 35 | 36 | pub struct CommonState { 37 | pub root_moves: Arc, 38 | pub pos_data: Arc>, 39 | pub result: Arc>, 40 | } 41 | 42 | pub struct ThreadCtrl { 43 | pub idx: usize, 44 | pub state: Mutex, 45 | pub common: Mutex, 46 | pub cv: Condvar, 47 | // nodes and tb_hits are Cell for lack of atomic u64 types 48 | pub nodes: Cell, 49 | pub tb_hits: Cell, 50 | } 51 | 52 | impl ThreadCtrl { 53 | pub fn new(idx: usize) -> ThreadCtrl { 54 | let thread_ctrl = ThreadCtrl { 55 | idx: idx, 56 | state: Mutex::new(ThreadState { 57 | exit: false, 58 | searching: true, 59 | clear: false, 60 | }), 61 | common: Mutex::new(CommonState { 62 | root_moves: Arc::new(Vec::new()), 63 | pos_data: Arc::new(RwLock::new(PosData { 64 | fen: String::new(), 65 | moves: Vec::new() 66 | })), 67 | result: Arc::new(Mutex::new(SearchResult { 68 | depth: Depth::ZERO, 69 | score: -Value::INFINITE, 70 | pv: Vec::new(), 71 | })), 72 | }), 73 | cv: Condvar::new(), 74 | nodes: Cell::new(0), 75 | tb_hits: Cell::new(0), 76 | }; 77 | thread_ctrl 78 | } 79 | } 80 | 81 | // Remove next line when nodes and tb_hits can be made atomic u64 82 | unsafe impl Sync for ThreadCtrl { } 83 | 84 | type Handlers = Vec>; 85 | type Threads = Vec>; 86 | 87 | static mut HANDLERS: *mut Handlers = 0 as *mut Handlers; 88 | static mut THREADS: *mut Threads = 0 as *mut Threads; 89 | 90 | static STOP: AtomicBool = AtomicBool::new(false); 91 | static PONDER: AtomicBool = AtomicBool::new(false); 92 | static STOP_ON_PONDERHIT: AtomicBool = AtomicBool::new(false); 93 | 94 | pub fn stop() -> bool { 95 | STOP.load(Ordering::Relaxed) 96 | } 97 | 98 | pub fn ponder() -> bool { 99 | PONDER.load(Ordering::Relaxed) 100 | } 101 | 102 | pub fn stop_on_ponderhit() -> bool { 103 | STOP_ON_PONDERHIT.load(Ordering::Relaxed) 104 | } 105 | 106 | pub fn set_stop(b: bool) { 107 | STOP.store(b, Ordering::SeqCst); 108 | } 109 | 110 | pub fn set_ponder(b: bool) { 111 | PONDER.store(b, Ordering::SeqCst); 112 | } 113 | 114 | pub fn set_stop_on_ponderhit(b: bool) { 115 | STOP_ON_PONDERHIT.store(b, Ordering::SeqCst); 116 | } 117 | 118 | pub fn init(requested: usize) { 119 | let handlers: Box = Box::new(Vec::new()); 120 | let threads: Box = Box::new(Vec::new()); 121 | unsafe { 122 | HANDLERS = Box::into_raw(handlers); 123 | THREADS = Box::into_raw(threads); 124 | } 125 | 126 | set(requested); 127 | } 128 | 129 | pub fn free() { 130 | set(0); 131 | unsafe { 132 | std::mem::drop(Box::from_raw(HANDLERS)); 133 | std::mem::drop(Box::from_raw(THREADS)); 134 | } 135 | } 136 | 137 | pub fn set(requested: usize) { 138 | let mut handlers = unsafe { Box::from_raw(HANDLERS) }; 139 | let mut threads = unsafe { Box::from_raw(THREADS) }; 140 | 141 | while handlers.len() < requested { 142 | let idx = handlers.len(); 143 | let (tx, rx) = channel(); 144 | // 16 MB stacks are now too small in debug mode, so use 32 MB stacks 145 | let builder = thread::Builder::new().stack_size(32 * 1024 * 1024); 146 | let handler = builder.spawn(move || run_thread(idx, tx)).unwrap(); 147 | let th = rx.recv().unwrap(); 148 | handlers.push(handler); 149 | threads.push(th); 150 | } 151 | 152 | while handlers.len() > requested { 153 | let handler = handlers.pop().unwrap(); 154 | let th = threads.pop().unwrap(); 155 | wake_up(&th, true, false); 156 | let _ = handler.join(); 157 | } 158 | 159 | std::mem::forget(handlers); 160 | std::mem::forget(threads); 161 | } 162 | 163 | fn run_thread(idx: usize, tx: Sender>) { 164 | let mut pos = Box::new(Position::new()); 165 | pos.pawns_table.reserve_exact(16384); 166 | for _ in 0..16384 { 167 | pos.pawns_table.push(std::cell::UnsafeCell::new(pawns::Entry::new())); 168 | } 169 | pos.material_table.reserve_exact(8192); 170 | for _ in 0..8192 { 171 | pos.material_table 172 | .push(std::cell::UnsafeCell::new(material::Entry::new())); 173 | } 174 | pos.is_main = idx == 0; 175 | pos.thread_idx = idx as i32; 176 | let th = Arc::new(ThreadCtrl::new(idx)); 177 | tx.send(th.clone()).unwrap(); 178 | pos.thread_ctrl = Some(th.clone()); 179 | pos.previous_time_reduction = 1.; 180 | pos.cont_history.init(); 181 | 182 | loop { 183 | let mut state = th.state.lock().unwrap(); 184 | state.searching = false; 185 | th.cv.notify_one(); 186 | while !state.searching { 187 | state = th.cv.wait(state).unwrap(); 188 | } 189 | if state.exit { 190 | break; 191 | } 192 | if state.clear { 193 | // Clear this thread as part of ucinewgame 194 | if th.idx == 0 { 195 | pos.previous_score = Value::INFINITE; 196 | pos.previous_time_reduction = 1.; 197 | } 198 | pos.counter_moves = unsafe { std::mem::zeroed() }; 199 | pos.main_history = unsafe { std::mem::zeroed() }; 200 | pos.capture_history = unsafe { std::mem::zeroed() }; 201 | pos.cont_history = unsafe { std::mem::zeroed() }; 202 | pos.cont_history.init(); 203 | state.clear = false; 204 | continue; 205 | } 206 | { 207 | let common = th.common.lock().unwrap(); 208 | let pos_data = common.pos_data.read().unwrap(); 209 | pos.init_states(); 210 | pos.set(&pos_data.fen, ucioption::get_bool("UCI_Chess960")); 211 | for &m in pos_data.moves.iter() { 212 | let gives_check = pos.gives_check(m); 213 | pos.do_move(m, gives_check); 214 | } 215 | let fen = pos.fen(); 216 | pos.set(&fen, ucioption::get_bool("UCI_Chess960")); 217 | pos.root_moves = (*common.root_moves).clone(); 218 | } // Locks are dropped here 219 | pos.nodes = 0; 220 | pos.tb_hits = 0; 221 | if th.idx == 0 { 222 | mainthread_search(&mut pos, &th); 223 | } else { 224 | thread_search(&mut pos, &th); 225 | let lock = th.common.lock().unwrap(); 226 | let result = &mut lock.result.lock().unwrap(); 227 | if pos.root_moves[0].score > result.score 228 | && (pos.completed_depth >= result.depth 229 | || pos.root_moves[0].score >= Value::MATE_IN_MAX_PLY) 230 | { 231 | result.depth = pos.completed_depth; 232 | result.score = pos.root_moves[0].score; 233 | result.pv = pos.root_moves[0].pv.clone(); 234 | } 235 | } 236 | } 237 | } 238 | 239 | fn wake_up(th: &ThreadCtrl, exit: bool, clear: bool) 240 | { 241 | let mut state = th.state.lock().unwrap(); 242 | state.searching = true; 243 | state.exit = exit; 244 | state.clear = clear; 245 | th.cv.notify_one(); 246 | } 247 | 248 | pub fn wake_up_slaves() 249 | { 250 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 251 | 252 | for th in threads.iter() { 253 | if th.idx != 0 { 254 | wake_up(th, false, false); 255 | } 256 | } 257 | 258 | std::mem::forget(threads); 259 | } 260 | 261 | pub fn clear_search() 262 | { 263 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 264 | 265 | for th in threads.iter() { 266 | wake_up(th, false, true); 267 | } 268 | 269 | std::mem::forget(threads); 270 | } 271 | 272 | pub fn wait_for_main() 273 | { 274 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 275 | 276 | for th in threads.iter() { 277 | if th.idx == 0 { 278 | let mut state = th.state.lock().unwrap(); 279 | while state.searching { 280 | state = th.cv.wait(state).unwrap(); 281 | } 282 | } 283 | } 284 | 285 | std::mem::forget(threads); 286 | } 287 | 288 | pub fn wait_for_slaves() 289 | { 290 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 291 | 292 | for th in threads.iter() { 293 | if th.idx != 0 { 294 | let mut state = th.state.lock().unwrap(); 295 | while state.searching { 296 | state = th.cv.wait(state).unwrap(); 297 | } 298 | } 299 | } 300 | 301 | std::mem::forget(threads); 302 | } 303 | 304 | pub fn wait_for_all() 305 | { 306 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 307 | 308 | for th in threads.iter() { 309 | let mut state = th.state.lock().unwrap(); 310 | while state.searching { 311 | state = th.cv.wait(state).unwrap(); 312 | } 313 | } 314 | 315 | std::mem::forget(threads); 316 | } 317 | 318 | pub fn start_thinking( 319 | pos: &mut Position, pos_data: &Arc>, limits: &LimitsType, 320 | searchmoves: Vec, ponder_mode: bool 321 | ) { 322 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 323 | 324 | wait_for_main(); 325 | 326 | set_stop_on_ponderhit(false); 327 | set_stop(false); 328 | set_ponder(ponder_mode); 329 | 330 | unsafe { 331 | LIMITS = (*limits).clone(); 332 | } 333 | 334 | let mut root_moves = RootMoves::new(); 335 | for m in MoveList::new::(pos) { 336 | if searchmoves.is_empty() 337 | || searchmoves.iter().any(|&x| x == m) 338 | { 339 | root_moves.push(RootMove::new(m)); 340 | } 341 | } 342 | 343 | tb::read_options(); 344 | tb::rank_root_moves(pos, &mut root_moves); 345 | 346 | let root_moves = Arc::new(root_moves); 347 | let result = Arc::new(Mutex::new(SearchResult { 348 | depth: Depth::ZERO, 349 | score: -Value::INFINITE, 350 | pv: Vec::new(), 351 | })); 352 | 353 | for th in threads.iter() { 354 | th.nodes.set(0); 355 | th.tb_hits.set(0); 356 | let mut common = th.common.lock().unwrap(); 357 | common.root_moves = root_moves.clone(); 358 | common.pos_data = pos_data.clone(); 359 | common.result = result.clone(); 360 | } 361 | 362 | wake_up(&threads[0], false, false); 363 | 364 | std::mem::forget(threads); 365 | } 366 | 367 | pub fn nodes_searched() -> u64 { 368 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 369 | 370 | let mut nodes = 0; 371 | 372 | for th in threads.iter() { 373 | nodes += th.nodes.get(); 374 | } 375 | 376 | std::mem::forget(threads); 377 | 378 | nodes 379 | } 380 | 381 | pub fn tb_hits() -> u64 { 382 | let threads: Box = unsafe { Box::from_raw(THREADS) }; 383 | 384 | let mut tb_hits = 0; 385 | 386 | for th in threads.iter() { 387 | tb_hits += th.tb_hits.get(); 388 | } 389 | 390 | std::mem::forget(threads); 391 | 392 | tb_hits 393 | } 394 | -------------------------------------------------------------------------------- /src/uci.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use benchmark::*; 4 | use misc; 5 | use movegen::*; 6 | use position::*; 7 | use search; 8 | use threads; 9 | use threads::PosData; 10 | use types::*; 11 | use ucioption; 12 | 13 | use std; 14 | use std::env; 15 | use std::sync::{Arc, RwLock}; 16 | use std::time::Instant; 17 | 18 | // FEN string of the initial position, normal chess 19 | const START_FEN: &'static str = 20 | "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; 21 | 22 | // position() is called when engine receives the "position" UCI command. 23 | // The function sets up the position described in the given FEN string ("fen") 24 | // or the starting position ("startpos") and then makes the moves given in the 25 | // following move list ("moves"). 26 | 27 | fn position(pos: &mut Position, pos_data: &mut PosData, args: &str) { 28 | let fen: &str; 29 | 30 | let moves = match args.find("moves") { 31 | Some(idx) => idx, 32 | None => args.len(), 33 | }; 34 | 35 | if &args[0..8] == "startpos" { 36 | fen = START_FEN; 37 | } else if &args[0..3] == "fen" { 38 | fen = (&args[3..moves]).trim(); 39 | } else { 40 | return; 41 | } 42 | 43 | pos.init_states(); 44 | pos.set(fen, ucioption::get_bool("UCI_Chess960")); 45 | pos_data.fen = String::from(fen); 46 | pos_data.moves = Vec::new(); 47 | 48 | if moves == args.len() { 49 | return; 50 | } 51 | 52 | // Parse move list 53 | let moves = &args[moves+5..].trim(); 54 | let iter = moves.split_whitespace(); 55 | for token in iter { 56 | let m = to_move(pos, token); 57 | if m == Move::NONE { 58 | break; 59 | } 60 | let gives_check = pos.gives_check(m); 61 | pos.do_move(m, gives_check); 62 | pos_data.moves.push(m); 63 | } 64 | } 65 | 66 | // setoption() is called when engine received the "setoption" UCI command. 67 | // The function updates the UCI option ("name") to the given value ("value"). 68 | 69 | fn setoption(args: &str) { 70 | let idx = args.find("name").unwrap(); 71 | let args = &args[idx+4..]; 72 | if let Some(idx) = args.find("value") { 73 | let name = &args[..idx].trim(); 74 | let value = &args[idx+5..].trim(); 75 | ucioption::set(name, value); 76 | } else { 77 | let name = args.trim(); 78 | ucioption::set(name, &""); 79 | } 80 | } 81 | 82 | // go() is called when engine receives the "go" UCI command. The function 83 | // sets the thinking time and other parameters from the input string, then 84 | // starts the search. 85 | 86 | fn go(pos: &mut Position, pos_data: &Arc>, args: &str) { 87 | let mut limits = search::LimitsType::new(); 88 | let mut searchmoves: Vec = Vec::new(); 89 | let mut ponder_mode = false; 90 | 91 | let mut iter = args.split_whitespace(); 92 | while let Some(token) = iter.next() { 93 | match token { 94 | "searchmoves" => { 95 | while let Some(token) = iter.next() { 96 | searchmoves.push(to_move(pos, token)); 97 | } 98 | } 99 | "wtime" => limits.time[WHITE.0 as usize] = 100 | iter.next().unwrap().parse().unwrap(), 101 | "btime" => limits.time[BLACK.0 as usize] = 102 | iter.next().unwrap().parse().unwrap(), 103 | "winc" => limits.inc[WHITE.0 as usize] = 104 | iter.next().unwrap().parse().unwrap(), 105 | "binc" => limits.inc[BLACK.0 as usize] = 106 | iter.next().unwrap().parse().unwrap(), 107 | "movestogo" => limits.movestogo = 108 | iter.next().unwrap().parse().unwrap(), 109 | "depth" => limits.depth = iter.next().unwrap().parse().unwrap(), 110 | "nodes" => limits.nodes = iter.next().unwrap().parse().unwrap(), 111 | "movetime" => limits.movetime = 112 | iter.next().unwrap().parse().unwrap(), 113 | "mate" => limits.mate = iter.next().unwrap().parse().unwrap(), 114 | "perft" => limits.perft = iter.next().unwrap().parse().unwrap(), 115 | "infinite" => limits.infinite = true, 116 | "ponder" => ponder_mode = true, 117 | _ => {} 118 | } 119 | } 120 | 121 | threads::start_thinking(pos, pos_data, &limits, searchmoves, ponder_mode); 122 | } 123 | 124 | // bench() is called when engine receives the "bench" command. First a list 125 | // of UCI commands is setup according to bench parameters. Then the commands 126 | // are run one by one. At the end, a summary is printed. 127 | 128 | fn bench(pos: &mut Position, pos_data: &Arc>, args: &str) { 129 | let list = setup_bench(pos, args); 130 | let num = list.iter().filter(|&s| s.find("go ") != None).count(); 131 | 132 | let now = Instant::now(); 133 | 134 | let mut cnt = 1; 135 | let mut nodes = 0; 136 | for cmd in list.iter() { 137 | let cmd_slice: &str = &cmd; 138 | let (token, args) = 139 | if let Some(idx) = cmd_slice.find(char::is_whitespace) { 140 | cmd_slice.split_at(idx) 141 | } else { 142 | (cmd_slice, "") 143 | }; 144 | let args = args.trim(); 145 | if token == "go" { 146 | eprintln!("\nPosition: {}/{}", cnt, num); 147 | cnt += 1; 148 | go(pos, pos_data, args); 149 | threads::wait_for_main(); 150 | nodes += threads::nodes_searched(); 151 | } else if token == "setoption" { 152 | setoption(args); 153 | } else if token == "position" { 154 | position(pos, &mut pos_data.write().unwrap(), args); 155 | } else if token == "ucinewgame" { 156 | search::clear(); 157 | } 158 | } 159 | 160 | let duration = now.elapsed(); 161 | let elapsed = (duration.as_secs() as u64) * 1000 162 | + (duration.subsec_nanos() as u64) / 10000000 + 1; 163 | 164 | eprintln!("\n===========================\ 165 | \nTotal time (ms) : {}\ 166 | \nNode searched : {}\ 167 | \nNodes/second : {}", 168 | elapsed, nodes, 1000 * nodes / elapsed); 169 | } 170 | 171 | // cmd_loop() waits for a command from stdin, parses it and calls the 172 | // appropriate function. Also intercepts EOF from stdin to ensure a 173 | // graceful exit if the GUI dies unexpectedly. When called with some comand 174 | // line arguments, e.g. to run 'bench', once the command is executed the 175 | // function returns immediately. In addition to the UCI ones, some additional 176 | // debug commands are supported. 177 | 178 | pub fn cmd_loop() { 179 | let mut pos = Box::new(Position::new()); 180 | 181 | pos.init_states(); 182 | pos.set(START_FEN, false); 183 | 184 | let pos_data = Arc::new(RwLock::new(PosData { 185 | fen: String::from(START_FEN), 186 | moves: Vec::new(), 187 | })); 188 | 189 | let mut cmd = String::new(); 190 | for arg in env::args().skip(1) { 191 | cmd.push_str(&arg); 192 | cmd.push(' '); 193 | } 194 | 195 | loop { 196 | if env::args().len() == 1 { 197 | cmd = String::new(); 198 | // Block here waiting for input or EOF 199 | if let Err(_) = std::io::stdin().read_line(&mut cmd) { 200 | cmd = String::from("quit"); 201 | } 202 | } 203 | let cmd_slice = cmd.trim(); 204 | let (token, args) = 205 | if let Some(idx) = cmd_slice.find(char::is_whitespace) { 206 | cmd_slice.split_at(idx) 207 | } else { 208 | (cmd_slice, "") 209 | }; 210 | let args = args.trim(); 211 | 212 | // The GUI sends 'ponderhit' to tell us the user has played the 213 | // expected move. So 'ponderhit' will be sent if we were told to 214 | // ponder on the same move the user has played. We should continue 215 | // searching but switch from pondering to normal search. In case 216 | // threads::stop_on_ponderhit() is true, we are waiting for 217 | // 'ponderhit' to stop the search, for instance if max search depth 218 | // has been reached. 219 | match token { 220 | "quit" | "stop" => threads::set_stop(true), 221 | "ponderhit" => { 222 | if threads::stop_on_ponderhit() { 223 | threads::set_stop(true); 224 | } else { 225 | threads::set_ponder(false); // Switch to normal search 226 | } 227 | } 228 | "uci" => { 229 | println!("id name {}", misc::engine_info(true)); 230 | ucioption::print(); 231 | println!("uciok"); 232 | } 233 | "setoption" => setoption(args), 234 | "go" => go(&mut pos, &pos_data, args), 235 | "position" => 236 | position(&mut pos, &mut pos_data.write().unwrap(), args), 237 | "ucinewgame" => search::clear(), 238 | "isready" => println!("readyok"), 239 | 240 | // Additional custom non-UCI commands 241 | "bench" => bench(&mut pos, &pos_data, args), 242 | "d" => pos.print(), 243 | _ => println!("Unknown command: {} {}", cmd, args) 244 | } 245 | if env::args().len() > 1 || token == "quit" { 246 | // Command-line args are one-shot 247 | break; 248 | } 249 | } 250 | } 251 | 252 | // value() converts a Value to a string suitable for use with the UCI 253 | // protocol specification: 254 | // 255 | // cp The score from the engine's point of view in centipawns 256 | // mate Mate in y moves, not plies. If the engine is getting mated 257 | // use negative values for y. 258 | 259 | pub fn value(v: Value) -> String { 260 | let mut s = String::new(); 261 | 262 | let w = if v >= Value::ZERO { v } else { -v }; 263 | if w < Value::MATE - Value(MAX_PLY) { 264 | s.push_str("cp "); 265 | s.push_str(&(v * 100 / PawnValueEg).to_string()); 266 | } else { 267 | s.push_str("mate "); 268 | let mut dtm = if v > Value::ZERO { (Value::MATE - v).0 + 1 } 269 | else { (-Value::MATE - v).0 }; 270 | dtm /= 2; 271 | s.push_str(&dtm.to_string()); 272 | } 273 | 274 | return s; 275 | } 276 | 277 | // square() converts a Square to a string in algebraic notation (g1, a7, etc.) 278 | 279 | pub fn square(s: Square) -> String { 280 | let mut sq = String::new(); 281 | 282 | sq.push((97u8 + s.file() as u8) as char); 283 | sq.push((49u8 + s.rank() as u8) as char); 284 | sq 285 | } 286 | 287 | // move_str() converts a Move to a string in coordinate notation (g1f3, a7a8q). 288 | // The only special case is castling, where we print in the e1g1 notation in 289 | // normal chess mode, and in e1h1 notation in chess960 mode. Internally all 290 | // castling moves are always encoded as 'king captures rook'. 291 | 292 | pub fn move_str(m: Move, chess960: bool) -> String { 293 | let from = m.from(); 294 | let mut to = m.to(); 295 | 296 | if m == Move::NONE { 297 | return String::from("(none)"); 298 | } 299 | 300 | if m == Move::NULL { 301 | return String::from("0000"); 302 | } 303 | 304 | if m.move_type() == CASTLING && !chess960 { 305 | to = Square::make(if to > from { FILE_G } else { FILE_C }, from.rank()); 306 | } 307 | 308 | let mut move_str = square(from); 309 | move_str.push_str(&square(to)); 310 | 311 | if m.move_type() == PROMOTION { 312 | move_str.push(" pnbrqk".chars().nth(m.promotion_type().0 as usize) 313 | .unwrap()); 314 | } 315 | 316 | move_str 317 | } 318 | 319 | // to_move() converts a string representing a move in coordinate notations 320 | // (g1f3, a7a8q) to the corresponding legal Move, if any. 321 | 322 | pub fn to_move(pos: &Position, s: &str) -> Move { 323 | if s.len() == 5 { 324 | } 325 | 326 | for m in MoveList::new::(pos) { 327 | if s == move_str(m, pos.is_chess960()) { 328 | return m; 329 | } 330 | } 331 | 332 | Move::NONE 333 | } 334 | -------------------------------------------------------------------------------- /src/pawns.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use bitboard::*; 4 | use position::Position; 5 | use types::*; 6 | 7 | use std; 8 | 9 | macro_rules! V { ($x:expr) => (Value($x)) } 10 | macro_rules! S { ($x:expr, $y:expr) => (Score(($y << 16) + $x)) } 11 | 12 | const V0: Value = Value::ZERO; 13 | 14 | // Isolated pawn penalty 15 | const ISOLATED: Score = S!(13, 18); 16 | 17 | // Backward pawn penalty 18 | const BACKWARD: Score = S!(24, 12); 19 | 20 | // Connected pawn bonus by opposed, phalanx, #support and rank 21 | static mut CONNECTED: [[[[Score; 8]; 3]; 2]; 2] = 22 | [[[[Score::ZERO; 8]; 3]; 2]; 2]; 23 | 24 | // Doubled pawn penalty 25 | const DOUBLED: Score = S!(18, 38); 26 | 27 | // Weakness of our pawn shelter in front of the king by 28 | // [is_king_file][distance from edge][rank]. RANK_1 = 0 is used for files 29 | // where we have no pawns or our pawn is behind our king. 30 | const SHELTER_WEAKNESS: [[[Value; 8]; 4]; 2] = [ 31 | [ [ V!( 98), V!(20), V!(11), V!(42), V!( 83), V!( 84), V!(101), V0 ], 32 | [ V!(103), V!( 8), V!(33), V!(86), V!( 87), V!(105), V!(113), V0 ], 33 | [ V!(100), V!( 2), V!(65), V!(95), V!( 59), V!( 89), V!(115), V0 ], 34 | [ V!( 72), V!( 6), V!(52), V!(74), V!( 83), V!( 84), V!(112), V0 ] ], 35 | [ [ V!(105), V!(19), V!( 3), V!(27), V!( 85), V!( 93), V!( 84), V0 ], 36 | [ V!(121), V!( 7), V!(33), V!(95), V!(112), V!( 86), V!( 72), V0 ], 37 | [ V!(121), V!(26), V!(65), V!(90), V!( 65), V!( 76), V!(117), V0 ], 38 | [ V!( 79), V!( 0), V!(45), V!(65), V!( 94), V!( 92), V!(105), V0 ] ], 39 | ]; 40 | 41 | // Danger of enemy pawns moving toward our king by 42 | // [type][distance from edge][rank]. For the unopposed and unblocked cases, 43 | // RANK_1 = 0 is used when opponent has no pawn on the given file or their 44 | // pawn is behind our king. 45 | const STORM_DANGER: [[[Value; 8]; 4]; 4] = [ 46 | // BlockedByKing 47 | [ [ V!( 0), V!(-290), V!(-274), V!(57), V!(41), V0, V0, V0 ], 48 | [ V!( 0), V!( 60), V!( 144), V!(39), V!(13), V0, V0, V0 ], 49 | [ V!( 0), V!( 65), V!( 141), V!(41), V!(34), V0, V0, V0 ], 50 | [ V!( 0), V!( 53), V!( 127), V!(56), V!(14), V0, V0, V0 ] ], 51 | // Unopposed 52 | [ [ V!( 4), V!( 73), V!( 132), V!(46), V!(31), V0, V0, V0 ], 53 | [ V!( 1), V!( 64), V!( 143), V!(26), V!(13), V0, V0, V0 ], 54 | [ V!( 1), V!( 47), V!( 110), V!(44), V!(24), V0, V0, V0 ], 55 | [ V!( 0), V!( 72), V!( 127), V!(50), V!(31), V0, V0, V0 ] ], 56 | // BlockedByPawn 57 | [ [ V!( 0), V!( 0), V!( 79), V!(23), V!( 1), V0, V0, V0 ], 58 | [ V!( 0), V!( 0), V!( 148), V!(27), V!( 2), V0, V0, V0 ], 59 | [ V!( 0), V!( 0), V!( 161), V!(16), V!( 1), V0, V0, V0 ], 60 | [ V!( 0), V!( 0), V!( 171), V!(22), V!(15), V0, V0, V0 ] ], 61 | // Unblocked 62 | [ [ V!(22), V!( 45), V!( 104), V!(62), V!( 6), V0, V0, V0 ], 63 | [ V!(31), V!( 30), V!( 99), V!(39), V!(19), V0, V0, V0 ], 64 | [ V!(23), V!( 29), V!( 96), V!(41), V!(15), V0, V0, V0 ], 65 | [ V!(21), V!( 23), V!( 116), V!(41), V!(15), V0, V0, V0 ] ], 66 | ]; 67 | 68 | // Max bonus for king safety. Corresponds to start position with all the 69 | // pawns in front of the king and no enemy pawns on the horizon. 70 | const MAX_SAFETY_BONUS: Value = V!(258); 71 | 72 | // pawns::Entry contains various information about a pawn structure. A lookup 73 | // in the pawn hash table (performed by calling the probing function) returns 74 | // a pointer to an Entry object. 75 | 76 | pub struct Entry { 77 | key: Key, 78 | score: Score, 79 | passed_pawns: [Bitboard; 2], 80 | pawn_attacks: [Bitboard; 2], 81 | pawn_attacks_span: [Bitboard; 2], 82 | king_squares: [Square; 2], 83 | king_safety: [Score; 2], 84 | weak_unopposed: [i32; 2], 85 | castling_rights: [CastlingRight; 2], 86 | semiopen_files: [i32; 2], 87 | pawns_on_squares: [[i32; 2]; 2], 88 | asymmetry: i32, 89 | open_files: i32, 90 | } 91 | 92 | impl Entry { 93 | pub fn new() -> Entry { 94 | Entry { 95 | key: Key(0), 96 | score: Score::ZERO, 97 | passed_pawns: [Bitboard(0); 2], 98 | pawn_attacks: [Bitboard(0); 2], 99 | pawn_attacks_span: [Bitboard(0); 2], 100 | king_squares: [Square(0); 2], 101 | king_safety: [Score::ZERO; 2], 102 | weak_unopposed: [0; 2], 103 | castling_rights: [CastlingRight(0); 2], 104 | semiopen_files: [0; 2], 105 | pawns_on_squares: [[0; 2]; 2], // [Color][light/dark squares] 106 | asymmetry: 0, 107 | open_files: 0, 108 | } 109 | } 110 | 111 | pub fn pawns_score(&self) -> Score { 112 | self.score 113 | } 114 | 115 | pub fn pawn_attacks(&self, c: Color) -> Bitboard { 116 | self.pawn_attacks[c.0 as usize] 117 | } 118 | 119 | pub fn passed_pawns(&self, c: Color) -> Bitboard { 120 | self.passed_pawns[c.0 as usize] 121 | } 122 | 123 | pub fn pawn_attacks_span(&self, c: Color) -> Bitboard { 124 | self.pawn_attacks_span[c.0 as usize] 125 | } 126 | 127 | pub fn weak_unopposed(&self, c: Color) -> i32 { 128 | self.weak_unopposed[c.0 as usize] 129 | } 130 | 131 | pub fn pawn_asymmetry(&self) -> i32 { 132 | self.asymmetry 133 | } 134 | 135 | pub fn open_files(&self) -> i32 { 136 | self.open_files 137 | } 138 | 139 | pub fn semiopen_file(&self, c: Color, f: File) -> i32 { 140 | self.semiopen_files[c.0 as usize] & (1 << f) 141 | } 142 | 143 | pub fn pawns_on_same_color_squares(&self, c: Color, s: Square) -> i32 { 144 | self.pawns_on_squares[c.0 as usize][((DARK_SQUARES & s) != 0) as usize] 145 | } 146 | 147 | pub fn king_safety( 148 | &mut self, pos: &Position, ksq: Square 149 | ) -> Score { 150 | let us = Us::COLOR; 151 | if self.king_squares[us.0 as usize] != ksq 152 | || self.castling_rights[us.0 as usize] != pos.castling_rights(us) 153 | { 154 | self.king_safety[us.0 as usize] = 155 | self.do_king_safety::(pos, ksq); 156 | } 157 | self.king_safety[us.0 as usize] 158 | } 159 | 160 | // shelter_storm() calculates shelter and storm penalties for the file 161 | // the king is on, as well as the two closest files. 162 | 163 | fn shelter_storm( 164 | &self, pos: &Position, ksq: Square 165 | ) -> Value { 166 | let us = Us::COLOR; 167 | let them = if us == WHITE { BLACK} else { WHITE }; 168 | let shelter_mask = if us == WHITE { bitboard!(A2, B3, C2, F2, G3, H2) } 169 | else { bitboard!(A7, B6, C7, F7, G6, H7) }; 170 | let storm_mask = if us == WHITE { bitboard!(A3, C3, F3, H3) } 171 | else { bitboard!(A6, C6, F6, H6) }; 172 | 173 | const BLOCKED_BY_KING: usize = 0; 174 | const UNOPPOSED: usize = 1; 175 | const BLOCKED_BY_PAWN: usize = 2; 176 | const UNBLOCKED: usize = 3; 177 | 178 | let center = std::cmp::max(FILE_B, std::cmp::min(FILE_G, ksq.file())); 179 | let b = pos.pieces_p(PAWN) 180 | & (forward_ranks_bb(us, ksq) | ksq.rank_bb()) 181 | & (adjacent_files_bb(center) | file_bb(center)); 182 | let our_pawns = b & pos.pieces_c(us); 183 | let their_pawns = b & pos.pieces_c(them); 184 | let mut safety = MAX_SAFETY_BONUS; 185 | 186 | for f in (center-1)..(center+2) { 187 | let b = our_pawns & file_bb(f); 188 | let rk_us = if b != 0 { backmost_sq(us, b).relative_rank(us) } 189 | else { RANK_1 }; 190 | 191 | let b = their_pawns & file_bb(f); 192 | let rk_them = if b != 0 { frontmost_sq(them, b).relative_rank(us) } 193 | else { RANK_1 }; 194 | 195 | let d = std::cmp::min(f, FILE_H - f); 196 | safety -= SHELTER_WEAKNESS[(f == ksq.file()) as usize][d as usize] 197 | [rk_us as usize] 198 | + STORM_DANGER 199 | [if f == ksq.file() && rk_them == ksq.relative_rank(us) + 1 200 | { BLOCKED_BY_KING } 201 | else if rk_us == RANK_1 { UNOPPOSED } 202 | else if rk_them == rk_us + 1 { BLOCKED_BY_PAWN } 203 | else { UNBLOCKED }] 204 | [d as usize][rk_them as usize]; 205 | } 206 | 207 | if popcount((our_pawns & shelter_mask) 208 | | (their_pawns & storm_mask)) == 5 209 | { 210 | safety += 300; 211 | } 212 | 213 | safety 214 | } 215 | 216 | // do_king_safety() calculates a bonus for king safety. It is called only 217 | // when king square changes, which is in about 20% of total king_safety() 218 | // calls. 219 | 220 | fn do_king_safety( 221 | &mut self, pos: &Position, ksq: Square 222 | ) -> Score { 223 | let us = Us::COLOR; 224 | self.king_squares[us.0 as usize] = ksq; 225 | self.castling_rights[us.0 as usize] = pos.castling_rights(us); 226 | let mut min_king_pawn_distance = 0i32; 227 | 228 | let pawns = pos.pieces_cp(us, PAWN); 229 | if pawns != 0 { 230 | while distance_ring_bb(ksq, min_king_pawn_distance) & pawns == 0 { 231 | min_king_pawn_distance += 1; 232 | } 233 | min_king_pawn_distance += 1; 234 | } 235 | 236 | let mut bonus = self.shelter_storm::(pos, ksq); 237 | 238 | // If we can castle use the bonus after the castling if it is bigger 239 | if pos.has_castling_right(us | CastlingSide::KING) { 240 | bonus = std::cmp::max(bonus, 241 | self.shelter_storm::(pos, Square::G1.relative(us))); 242 | } 243 | 244 | if pos.has_castling_right(us | CastlingSide::QUEEN) { 245 | bonus = std::cmp::max(bonus, 246 | self.shelter_storm::(pos, Square::C1.relative(us))); 247 | } 248 | 249 | Score::make(bonus.0, -16 * min_king_pawn_distance) 250 | } 251 | 252 | } 253 | 254 | // pawns::init() initializes some tables needed by evaluation. 255 | 256 | pub fn init() { 257 | const SEED: [i32; 8] = [0, 13, 24, 18, 76, 100, 175, 330]; 258 | 259 | for opposed in 0..2 { 260 | for phalanx in 0..2 { 261 | for support in 0..3 { 262 | for r in 1..7i32 { 263 | let v = 17 * (support as i32) + ((SEED[r as usize] + 264 | (if phalanx != 0 265 | { (SEED[(r+1) as usize] - SEED[r as usize]) / 2 } 266 | else { 0 })) 267 | >> opposed); 268 | unsafe { 269 | CONNECTED[opposed as usize][phalanx as usize] 270 | [support as usize][r as usize] = 271 | Score::make(v, v * (r-2) / 4); 272 | } 273 | } 274 | } 275 | } 276 | } 277 | } 278 | 279 | // pawns::probe() looks up the current position's pawn configuration in the 280 | // pawn hash table. If it is not found, it is computed and stored in the table. 281 | 282 | pub fn probe(pos: &Position) -> &mut Entry { 283 | let key = pos.pawn_key(); 284 | let e = pos.pawns_table[(key.0 & 16383) as usize].get(); 285 | let e: &'static mut Entry = unsafe { &mut *e }; 286 | 287 | if e.key == key { 288 | return e; 289 | } 290 | 291 | e.key = key; 292 | e.score = evaluate::(pos, e) - evaluate::(pos, e); 293 | e.open_files = (e.semiopen_files[WHITE.0 as usize] 294 | & e.semiopen_files[BLACK.0 as usize]).count_ones() as i32; 295 | e.asymmetry = (e.passed_pawns[WHITE.0 as usize].0 296 | | e.passed_pawns[BLACK.0 as usize].0 297 | | (e.semiopen_files[WHITE.0 as usize] 298 | ^ e.semiopen_files[BLACK.0 as usize]) as u64).count_ones() as i32; 299 | 300 | e 301 | } 302 | 303 | fn evaluate(pos: &Position, e: &mut Entry) -> Score { 304 | let us = Us::COLOR; 305 | let them = if us == WHITE { BLACK } else { WHITE }; 306 | let up = if us == WHITE { NORTH } else { SOUTH }; 307 | let right = if us == WHITE { NORTH_EAST } else { SOUTH_WEST }; 308 | let left = if us == WHITE { NORTH_WEST } else { SOUTH_EAST }; 309 | 310 | let mut score = Score::ZERO; 311 | 312 | let our_pawns = pos.pieces_cp(us, PAWN); 313 | let their_pawns = pos.pieces_cp(them, PAWN); 314 | 315 | e.passed_pawns[us.0 as usize] = Bitboard(0); 316 | e.pawn_attacks_span[us.0 as usize] = Bitboard(0); 317 | e.weak_unopposed[us.0 as usize] = 0; 318 | e.semiopen_files[us.0 as usize] = 0xff; 319 | e.king_squares[us.0 as usize] = Square::NONE; 320 | e.pawn_attacks[us.0 as usize] = 321 | our_pawns.shift(right) | our_pawns.shift(left); 322 | e.pawns_on_squares[us.0 as usize][BLACK.0 as usize] = 323 | popcount(our_pawns & DARK_SQUARES) as i32; 324 | e.pawns_on_squares[us.0 as usize][WHITE.0 as usize] = 325 | popcount(our_pawns & !DARK_SQUARES) as i32; 326 | 327 | // Loop through all pawns of the current color and score each pawn 328 | for s in pos.square_list(us, PAWN) { 329 | debug_assert!(pos.piece_on(s) == Piece::make(us, PAWN)); 330 | 331 | let f = s.file(); 332 | 333 | e.semiopen_files[us.0 as usize] &= !(1 << f); 334 | e.pawn_attacks_span[us.0 as usize] |= pawn_attack_span(us, s); 335 | 336 | // Flag the pawn 337 | let opposed = their_pawns & forward_file_bb(us, s); 338 | let stoppers = their_pawns & passed_pawn_mask(us, s); 339 | let lever = their_pawns & pawn_attacks(us, s); 340 | let lever_push = their_pawns & pawn_attacks(us, s + up); 341 | let doubled = our_pawns & (s - up); 342 | let neighbours = our_pawns & adjacent_files_bb(f); 343 | let phalanx = neighbours & s.rank_bb(); 344 | let supported = neighbours & (s-up).rank_bb(); 345 | 346 | let backward; 347 | 348 | // A pawn is backward if it is behind all pawns of the same color on 349 | // the adjacent files and cannot be safely advanced. 350 | if neighbours == 0 || lever != 0 || s.relative_rank(us) >= RANK_5 { 351 | backward = false; 352 | } else { 353 | // Find the backmost rank with neighbours or stoppers 354 | let b = backmost_sq(us, neighbours | stoppers).rank_bb(); 355 | 356 | // The pawn is backward if it cannot safely progress to that 357 | // rank: either there is a stopper in the way on this rank or 358 | // there is a stopper on an adjacent file which controls the way 359 | // to that rank. 360 | backward = 361 | (b | (b & adjacent_files_bb(f)).shift(up)) & stoppers != 0; 362 | debug_assert!( 363 | !(backward && forward_ranks_bb(them, s + up) & neighbours != 0) 364 | ); 365 | } 366 | 367 | // Passed pawns will be properly scored in evaluation because we need 368 | // full attack info to evaluate them. Include also not passed pawns 369 | // which could become passed after one or two pawn pushes. 370 | if stoppers ^ lever ^ lever_push == 0 371 | && our_pawns & forward_file_bb(us, s) == 0 372 | && popcount(supported) >= popcount(lever) 373 | && popcount(phalanx) >= popcount(lever_push) 374 | { 375 | e.passed_pawns[us.0 as usize] |= s; 376 | } 377 | else if stoppers ^ (s + up) == 0 378 | && s.relative_rank(us) >= RANK_5 379 | { 380 | for sq in supported.shift(up) & !their_pawns { 381 | if !more_than_one(their_pawns & pawn_attacks(us, sq)) { 382 | e.passed_pawns[us.0 as usize] |= s; 383 | } 384 | } 385 | } 386 | 387 | // Score this pawn 388 | if supported | phalanx != 0 { 389 | score += unsafe { 390 | CONNECTED[(opposed != 0) as usize][(phalanx != 0) as usize] 391 | [popcount(supported) as usize][s.relative_rank(us) as usize] 392 | }; 393 | } else if neighbours == 0 { 394 | score -= ISOLATED; 395 | e.weak_unopposed[us.0 as usize] += (opposed == 0) as i32; 396 | } else if backward { 397 | score -= BACKWARD; 398 | e.weak_unopposed[us.0 as usize] += (opposed == 0) as i32; 399 | } 400 | 401 | if doubled != 0 && supported == 0 { 402 | score -= DOUBLED; 403 | } 404 | } 405 | 406 | score 407 | } 408 | -------------------------------------------------------------------------------- /src/movegen.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use types::*; 4 | use bitboard::*; 5 | use position::Position; 6 | 7 | const CAPTURES: i32 = 0; 8 | const QUIETS: i32 = 1; 9 | const QUIET_CHECKS: i32 = 2; 10 | const EVASIONS: i32 = 3; 11 | const NON_EVASIONS: i32 = 4; 12 | const LEGAL: i32 = 5; 13 | 14 | pub struct Captures; 15 | pub struct Quiets; 16 | pub struct QuietChecks; 17 | pub struct Evasions; 18 | pub struct NonEvasions; 19 | pub struct Legal; 20 | 21 | pub trait GenType { 22 | type Checks: Bool; 23 | const TYPE: i32; 24 | } 25 | 26 | impl GenType for Captures { 27 | type Checks = False; 28 | const TYPE: i32 = CAPTURES; 29 | } 30 | 31 | impl GenType for Quiets { 32 | type Checks = False; 33 | const TYPE: i32 = QUIETS; 34 | } 35 | 36 | impl GenType for QuietChecks { 37 | type Checks = True; 38 | const TYPE: i32 = QUIET_CHECKS; 39 | } 40 | 41 | impl GenType for Evasions { 42 | type Checks = False; 43 | const TYPE: i32 = EVASIONS; 44 | } 45 | 46 | impl GenType for NonEvasions { 47 | type Checks = False; 48 | const TYPE: i32 = NON_EVASIONS; 49 | } 50 | 51 | impl GenType for Legal { 52 | type Checks = False; 53 | const TYPE: i32 = LEGAL; 54 | } 55 | 56 | #[derive(Clone, Copy)] 57 | pub struct ExtMove { 58 | pub m: Move, 59 | pub value: i32, 60 | } 61 | 62 | // The MoveList struct is a simple wrapper around generate::<*>(). It sometimes 63 | // comes in handy to use this struct instead of the low-level generate::<*>() 64 | // functions. 65 | pub struct MoveList { 66 | list: [ExtMove; MAX_MOVES], 67 | idx: usize, 68 | len: usize, 69 | } 70 | 71 | impl MoveList { 72 | pub fn new(pos: &Position) -> MoveList { 73 | let mut moves = MoveList { 74 | list: [ExtMove { m : Move::NONE, value: 0 }; MAX_MOVES], 75 | idx: 0, 76 | len: 0, 77 | }; 78 | moves.len = generate::(pos, &mut moves.list, 0); 79 | moves.idx = 0; 80 | moves 81 | } 82 | 83 | pub fn len(&self) -> usize { 84 | self.len 85 | } 86 | 87 | pub fn contains(&self, m: Move) -> bool { 88 | let mut i = 0; 89 | while i < self.len { 90 | if self.list[i].m == m { 91 | return true; 92 | } 93 | i += 1; 94 | } 95 | return false 96 | } 97 | } 98 | 99 | impl Iterator for MoveList { 100 | type Item = Move; 101 | fn next(&mut self) -> Option { 102 | if self.idx == self.len { 103 | None 104 | } else { 105 | self.idx += 1; 106 | Some(self.list[self.idx - 1].m) 107 | } 108 | } 109 | } 110 | 111 | fn generate_castling( 112 | pos: &Position, list: &mut [ExtMove], idx: usize, us: Color 113 | ) -> usize { 114 | let king_side = Cr::CR == WHITE_OO || Cr::CR == BLACK_OO; 115 | 116 | if pos.castling_impeded(Cr::CR) || !pos.has_castling_right(Cr::CR) { 117 | return idx; 118 | } 119 | 120 | // After castling, the rook and king final positions are the same in 121 | // Chess960 as they are in standard chess. 122 | let kfrom = pos.square(us, KING); 123 | let rfrom = pos.castling_rook_square(Cr::CR); 124 | let kto = 125 | relative_square(us, if king_side { Square::G1 } else { Square::C1 }); 126 | let enemies = pos.pieces_c(!us); 127 | 128 | debug_assert!(pos.checkers() == 0); 129 | 130 | let direction = match Chess960::BOOL { 131 | true => if kto > kfrom { WEST } else { EAST }, 132 | false => if king_side { WEST } else { EAST }, 133 | }; 134 | 135 | let mut s = kto; 136 | while s != kfrom { 137 | if pos.attackers_to(s) & enemies != 0 { 138 | return idx; 139 | } 140 | s += direction; 141 | } 142 | 143 | // Because we generate only legal castling moves, we need to verify that 144 | // when moving the castling rook we do not discover some hidden checker. 145 | // For instance an enemy queen on A1 when the castling rook is on B1. 146 | if Chess960::BOOL 147 | && attacks_bb(ROOK, kto, pos.pieces() ^ rfrom) 148 | & pos.pieces_cpp(!us, ROOK, QUEEN) != 0 149 | { 150 | return idx; 151 | } 152 | 153 | let m = Move::make_special(CASTLING, kfrom, rfrom); 154 | 155 | if Checks::BOOL && !pos.gives_check(m) { 156 | return idx; 157 | } 158 | 159 | list[idx].m = m; 160 | idx + 1 161 | } 162 | 163 | fn make_promotions( 164 | list: &mut [ExtMove], mut idx: usize, to: Square, ksq: Square, 165 | direction: Direction 166 | ) -> usize { 167 | if T::TYPE == CAPTURES || T::TYPE == EVASIONS || T::TYPE == NON_EVASIONS 168 | { 169 | list[idx].m = Move::make_prom(to - direction, to, QUEEN); 170 | idx += 1; 171 | } 172 | 173 | if T::TYPE == QUIETS || T::TYPE == EVASIONS || T::TYPE == NON_EVASIONS 174 | { 175 | list[idx ].m = Move::make_prom(to - direction, to, ROOK); 176 | list[idx + 1].m = Move::make_prom(to - direction, to, BISHOP); 177 | list[idx + 2].m = Move::make_prom(to - direction, to, KNIGHT); 178 | idx += 3; 179 | } 180 | 181 | // Knight promotion is the only promotion that can give a direct check 182 | // that's not already included in the queen promotion. 183 | if T::TYPE == QUIET_CHECKS && pseudo_attacks(KNIGHT, to) & ksq != 0 { 184 | list[idx].m = Move::make_prom(to - direction, to, KNIGHT); 185 | idx += 1; 186 | } 187 | 188 | idx 189 | } 190 | 191 | // template us 192 | fn generate_pawn_moves( 193 | pos: &Position, list: &mut [ExtMove], mut idx: usize, target: Bitboard 194 | ) -> usize { 195 | let us = Us::COLOR; 196 | let them = !us; 197 | let trank_8bb = if us == WHITE { RANK8_BB } else { RANK1_BB }; 198 | let trank_7bb = if us == WHITE { RANK7_BB } else { RANK2_BB }; 199 | let trank_3bb = if us == WHITE { RANK3_BB } else { RANK6_BB }; 200 | let up = if us == WHITE { NORTH } else { SOUTH }; 201 | let right = if us == WHITE { NORTH_EAST } else { SOUTH_WEST }; 202 | let left = if us == WHITE { NORTH_WEST } else { SOUTH_EAST }; 203 | 204 | let mut empty_squares = Bitboard(0); 205 | 206 | let pawns_on_7 = pos.pieces_cp(us, PAWN) & trank_7bb; 207 | let pawns_not_on_7 = pos.pieces_cp(us, PAWN) & !trank_7bb; 208 | 209 | let enemies = match T::TYPE { 210 | EVASIONS => pos.pieces_c(them) & target, 211 | CAPTURES => target, 212 | _ => pos.pieces_c(them) 213 | }; 214 | 215 | // Single and double pawn pushes, no promotions 216 | if T::TYPE != CAPTURES { 217 | empty_squares = 218 | if T::TYPE == QUIETS || T::TYPE == QUIET_CHECKS { 219 | target 220 | } else { 221 | !pos.pieces() 222 | }; 223 | 224 | let mut b1 = pawns_not_on_7.shift(up) & empty_squares; 225 | let mut b2 = (b1 & trank_3bb).shift(up) & empty_squares; 226 | 227 | if T::TYPE == EVASIONS { // Consider only blocking squares 228 | b1 &= target; 229 | b2 &= target; 230 | } 231 | 232 | if T::TYPE == QUIET_CHECKS { 233 | let ksq = pos.square(them, KING); 234 | 235 | b1 &= pos.attacks_from_pawn(ksq, them); 236 | b2 &= pos.attacks_from_pawn(ksq, them); 237 | 238 | // Add pawn pushes which give discovered check. This is possible 239 | // only if the pawn is not on the same file as the enemy king, 240 | // because we don't generate captures. Note that a possible 241 | // discovery check promotion has already been generated together 242 | // with the captures. 243 | let dc_candidates = pos.blockers_for_king(them); 244 | if pawns_not_on_7 & dc_candidates != 0 { 245 | let dc1 = 246 | (pawns_not_on_7 & dc_candidates).shift(up) 247 | & empty_squares 248 | & !file_bb(ksq.file()); 249 | let dc2 = (dc1 & trank_3bb).shift(up) & empty_squares; 250 | 251 | b1 |= dc1; 252 | b2 |= dc2; 253 | } 254 | } 255 | 256 | for to in b1 { 257 | list[idx].m = Move::make(to - up, to); 258 | idx += 1; 259 | } 260 | 261 | for to in b2 { 262 | list[idx].m = Move::make(to - up - up, to); 263 | idx += 1; 264 | } 265 | } 266 | 267 | // Promotions and underpromotions 268 | if pawns_on_7 != 0 && (T::TYPE != EVASIONS || target & trank_8bb != 0) { 269 | if T::TYPE == CAPTURES { 270 | empty_squares = !pos.pieces(); 271 | } 272 | 273 | if T::TYPE == EVASIONS { 274 | empty_squares &= target; 275 | } 276 | 277 | let b1 = pawns_on_7.shift(right) & enemies; 278 | let b2 = pawns_on_7.shift(left ) & enemies; 279 | let b3 = pawns_on_7.shift(up ) & empty_squares; 280 | 281 | let ksq = pos.square(them, KING); 282 | 283 | for s in b1 { 284 | idx = make_promotions::(list, idx, s, ksq, right); 285 | } 286 | 287 | for s in b2 { 288 | idx = make_promotions::(list, idx, s, ksq, left); 289 | } 290 | 291 | for s in b3 { 292 | idx = make_promotions::(list, idx, s, ksq, up); 293 | } 294 | } 295 | 296 | // Standard and en-passant captures 297 | if T::TYPE == CAPTURES || T::TYPE == EVASIONS || T::TYPE == NON_EVASIONS 298 | { 299 | let b1 = pawns_not_on_7.shift(right) & enemies; 300 | let b2 = pawns_not_on_7.shift(left ) & enemies; 301 | 302 | for to in b1 { 303 | list[idx].m = Move::make(to - right, to); 304 | idx += 1; 305 | } 306 | 307 | for to in b2 { 308 | list[idx].m = Move::make(to - left, to); 309 | idx += 1; 310 | } 311 | 312 | if pos.ep_square() != Square::NONE { 313 | debug_assert!(pos.ep_square().rank() == relative_rank(us, RANK_6)); 314 | 315 | // An en passant capture can be an evasion only if the checking 316 | // piece is the double pushed pawn and so is in the target. 317 | // Otherwise this is a discovery check and we are forced to do 318 | // otherwise. 319 | if T::TYPE == EVASIONS && target & (pos.ep_square() - up) == 0 { 320 | return idx; 321 | } 322 | 323 | let b1 = 324 | pawns_not_on_7 & pos.attacks_from_pawn(pos.ep_square(), them); 325 | 326 | debug_assert!(b1 != 0); 327 | 328 | for to in b1 { 329 | list[idx].m = 330 | Move::make_special(ENPASSANT, to, pos.ep_square()); 331 | idx += 1; 332 | } 333 | } 334 | } 335 | 336 | idx 337 | } 338 | 339 | fn generate_moves( 340 | pos: &Position, list: &mut [ExtMove], mut idx: usize, us: Color, 341 | target: Bitboard 342 | ) -> usize { 343 | debug_assert!(Pt::TYPE != KING && Pt::TYPE != PAWN); 344 | 345 | for from in pos.square_list(us, Pt::TYPE) { 346 | if Checks::BOOL { 347 | if (Pt::TYPE == BISHOP || Pt::TYPE == ROOK || Pt::TYPE == QUEEN) 348 | && pseudo_attacks(Pt::TYPE, from) & target 349 | & pos.check_squares(Pt::TYPE) == 0 350 | { 351 | continue; 352 | } 353 | 354 | if pos.blockers_for_king(!us) & from != 0 { 355 | continue; 356 | } 357 | } 358 | 359 | let mut b = pos.attacks_from(Pt::TYPE, from) & target; 360 | 361 | if Checks::BOOL { 362 | b &= pos.check_squares(Pt::TYPE); 363 | } 364 | 365 | for to in b { 366 | list[idx].m = Move::make(from, to); 367 | idx += 1; 368 | } 369 | } 370 | 371 | idx 372 | } 373 | 374 | fn generate_all( 375 | pos: &Position, list: &mut [ExtMove], mut idx: usize, target: Bitboard 376 | ) -> usize { 377 | let us = Us::COLOR; 378 | 379 | idx = generate_pawn_moves::(pos, list, idx, target); 380 | idx = generate_moves::(pos, list, idx, us, target); 381 | idx = generate_moves::(pos, list, idx, us, target); 382 | idx = generate_moves::(pos, list, idx, us, target); 383 | idx = generate_moves::(pos, list, idx, us, target); 384 | 385 | if T::TYPE != QUIET_CHECKS && T::TYPE != EVASIONS { 386 | let ksq = pos.square(us, KING); 387 | let b = pos.attacks_from(KING, ksq) & target; 388 | for to in b { 389 | list[idx].m = Move::make(ksq, to); 390 | idx += 1; 391 | } 392 | } 393 | 394 | if T::TYPE != CAPTURES && T::TYPE != EVASIONS && pos.can_castle(us) { 395 | if pos.is_chess960() { 396 | idx = generate_castling::(pos, 397 | list, idx, us); 398 | idx = generate_castling::(pos, 399 | list, idx, us); 400 | } else { 401 | idx = generate_castling::(pos, 402 | list, idx, us); 403 | idx = generate_castling::(pos, 404 | list, idx, us); 405 | } 406 | } 407 | 408 | idx 409 | } 410 | 411 | 412 | // generate_quiet_checks() generates all pseudo-legal non-captures and 413 | // knight underpromotions that give check 414 | pub fn generate_quiet_checks( 415 | pos: &Position, list: &mut [ExtMove], mut idx: usize 416 | ) -> usize { 417 | debug_assert!(pos.checkers() == 0); 418 | 419 | let us = pos.side_to_move(); 420 | let dc = pos.blockers_for_king(!us) & pos.pieces_c(us); 421 | 422 | for from in dc { 423 | let pt = pos.piece_on(from).piece_type(); 424 | 425 | if pt == PAWN { 426 | continue; // Will be generated together with direct checks 427 | } 428 | 429 | let mut b = pos.attacks_from(pt, from) & !pos.pieces(); 430 | 431 | if pt == KING { 432 | b &= !pseudo_attacks(QUEEN, pos.square(!us, KING)); 433 | } 434 | 435 | for to in b { 436 | list[idx].m = Move::make(from, to); 437 | idx += 1; 438 | } 439 | } 440 | 441 | if us == WHITE { 442 | generate_all::(pos, list, idx, !pos.pieces()) 443 | } else { 444 | generate_all::(pos, list, idx, !pos.pieces()) 445 | } 446 | } 447 | 448 | // generate_evasions() generates all pseudo-legal check evasions when the 449 | // side to move is in check 450 | fn generate_evasions( 451 | pos: &Position, list: &mut [ExtMove], mut idx: usize 452 | ) -> usize { 453 | debug_assert!(pos.checkers() != 0); 454 | 455 | let us = pos.side_to_move(); 456 | let ksq = pos.square(us, KING); 457 | let mut slider_attacks = Bitboard(0); 458 | let sliders = pos.checkers() & !pos.pieces_pp(KNIGHT, PAWN); 459 | 460 | // Find all the squares attacked by slider checks. We will remove them 461 | // from the king evasions in order to skip known illegal moves, which 462 | // avoids any useless legality checks later on. 463 | for check_sq in sliders { 464 | slider_attacks |= line_bb(check_sq, ksq) ^ check_sq; 465 | } 466 | 467 | // Generate evasions for king, capture and non-capture moves 468 | let b = pos.attacks_from(KING, ksq) & !pos.pieces_c(us) & !slider_attacks; 469 | for to in b { 470 | list[idx].m = Move::make(ksq, to); 471 | idx += 1; 472 | } 473 | 474 | if more_than_one(pos.checkers()) { 475 | return idx; // Double check, only a king move can save the day 476 | } 477 | 478 | // Generate blocking evasions or captures of the checking piece 479 | let check_sq = lsb(pos.checkers()); 480 | let target = between_bb(check_sq, ksq) | check_sq; 481 | 482 | if us == WHITE { 483 | generate_all::(pos, list, idx, target) 484 | } else { 485 | generate_all::(pos, list, idx, target) 486 | } 487 | } 488 | 489 | // generate_legal() generates all the legal moves in the given position 490 | fn generate_legal( 491 | pos: &Position, list: &mut [ExtMove], idx: usize 492 | ) -> usize { 493 | let us = pos.side_to_move(); 494 | let pinned = pos.blockers_for_king(us) & pos.pieces_c(us); 495 | let ksq = pos.square(us, KING); 496 | 497 | let pseudo = if pos.checkers() != 0 { 498 | generate::(pos, list, idx) 499 | } else { 500 | generate::(pos, list, idx) 501 | }; 502 | 503 | let mut legal = idx; 504 | for i in idx..pseudo { 505 | let m = list[i].m; 506 | if (pinned == 0 && m.from() != ksq && m.move_type() != ENPASSANT) 507 | || pos.legal(m) 508 | { 509 | list[legal].m = m; 510 | legal += 1; 511 | } 512 | } 513 | 514 | legal 515 | } 516 | 517 | // generate() generates all pseudo-legal captures and queen 518 | // promotions. 519 | // 520 | // generate() generates all pseudo-legal non-captures and 521 | // underpromotions. 522 | // 523 | // generate() generates all pseudo-legal non-captures and 524 | // knight underpromotions that give check. 525 | // 526 | // generate() generates all pseudo-legal check evasions when the 527 | // side to move is in check. 528 | // 529 | // generate() generates all pseudo-legal captures and 530 | // non-captures. 531 | // 532 | // generate() generates all the legal moves in the given position. 533 | 534 | pub fn generate( 535 | pos: &Position, list: &mut [ExtMove], idx: usize 536 | ) -> usize { 537 | match T::TYPE { 538 | QUIET_CHECKS => generate_quiet_checks(pos, list, idx), 539 | EVASIONS => generate_evasions(pos, list, idx), 540 | LEGAL => generate_legal(pos, list, idx), 541 | _ => { 542 | debug_assert!(pos.checkers() == 0); 543 | 544 | let us = pos.side_to_move(); 545 | 546 | let target = match T::TYPE { 547 | CAPTURES => pos.pieces_c(!us), 548 | QUIETS => !pos.pieces(), 549 | NON_EVASIONS => !pos.pieces_c(us), 550 | _ => Bitboard(0) 551 | }; 552 | 553 | if us == WHITE { 554 | generate_all::(pos, list, idx, target) 555 | } else { 556 | generate_all::(pos, list, idx, target) 557 | } 558 | } 559 | } 560 | } 561 | -------------------------------------------------------------------------------- /src/movepick.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | use movegen::*; 4 | use position::Position; 5 | use search; 6 | use types::*; 7 | 8 | use std::cell::Cell; 9 | 10 | pub struct ButterflyHistory { 11 | v: [[Cell; 4096]; 2], 12 | } 13 | 14 | impl ButterflyHistory { 15 | pub fn get(&self, c: Color, m: Move) -> i32 { 16 | self.v[c.0 as usize][m.from_to() as usize].get() as i32 17 | } 18 | 19 | pub fn update(&self, c: Color, m: Move, bonus: i32) { 20 | let entry = &self.v[c.0 as usize][m.from_to() as usize]; 21 | let mut val = entry.get(); 22 | val += (bonus * 32 - val as i32 * bonus.abs() / 324) as i16; 23 | entry.set(val); 24 | } 25 | } 26 | 27 | pub struct PieceToHistory { 28 | v: [[Cell; 64]; 16], 29 | } 30 | 31 | impl PieceToHistory { 32 | pub fn get(&self, pc: Piece, s: Square) -> i32 { 33 | self.v[pc.0 as usize][s.0 as usize].get() as i32 34 | } 35 | 36 | pub fn update(&self, pc: Piece, s: Square, bonus: i32) { 37 | let entry = &self.v[pc.0 as usize][s.0 as usize]; 38 | let mut val = entry.get(); 39 | val += (bonus * 32 - val as i32 * bonus.abs() / 936) as i16; 40 | entry.set(val); 41 | } 42 | } 43 | 44 | pub struct CapturePieceToHistory { 45 | v: [[[Cell; 8]; 64]; 16], 46 | } 47 | 48 | impl CapturePieceToHistory { 49 | pub fn get(&self, pc: Piece, to: Square, cap: PieceType) -> i32 { 50 | self.v[pc.0 as usize][to.0 as usize][cap.0 as usize].get() as i32 51 | } 52 | 53 | pub fn update(&self, pc: Piece, to: Square, cap: PieceType, bonus: i32) { 54 | let entry = &self.v[pc.0 as usize][to.0 as usize][cap.0 as usize]; 55 | let mut val = entry.get(); 56 | val += (bonus * 2 - val as i32 * bonus.abs() / 324) as i16; 57 | entry.set(val); 58 | } 59 | } 60 | 61 | pub struct CounterMoveHistory { 62 | v: [[Cell; 64]; 16], 63 | } 64 | 65 | impl CounterMoveHistory { 66 | pub fn get(&self, pc: Piece, s: Square) -> Move { 67 | self.v[pc.0 as usize][s.0 as usize].get() 68 | } 69 | 70 | pub fn set(&self, pc: Piece, s: Square, m: Move) { 71 | self.v[pc.0 as usize][s.0 as usize].set(m); 72 | } 73 | } 74 | 75 | pub struct ContinuationHistory { 76 | v: [[PieceToHistory; 64]; 16], 77 | } 78 | 79 | impl ContinuationHistory { 80 | pub fn get(&self, pc: Piece, s: Square) -> &'static PieceToHistory { 81 | let p: *const PieceToHistory = &self.v[pc.0 as usize][s.0 as usize]; 82 | unsafe { &*p } 83 | } 84 | 85 | pub fn init(&self) { 86 | let p = self.get(Piece(0), Square(0)); 87 | for pc in 0..16 { 88 | for s in 0..64 { 89 | p.v[pc][s].set(search::CM_THRESHOLD as i16 - 1); 90 | } 91 | } 92 | } 93 | } 94 | 95 | // MovePicker structs are used to pick one pseudo-legal move at a time from 96 | // the current position. The most important method is next_move(), which 97 | // returns a new pseudo-legal move each time it is called, until there are 98 | // no moves left, when MOVE_NONE is returned. In order to improve the 99 | // efficiency of the alpha beta algorithm, MovePicker attempts to return the 100 | // moves which are most likely to get a cut off first. 101 | 102 | pub struct MovePicker { 103 | cur: usize, 104 | end_moves: usize, 105 | end_bad_captures: usize, 106 | stage: i32, 107 | depth: Depth, 108 | tt_move: Move, 109 | countermove: Move, 110 | killers: [Move; 2], 111 | cmh: [&'static PieceToHistory; 3], 112 | list: [ExtMove; MAX_MOVES as usize], 113 | } 114 | 115 | pub struct MovePickerQ { 116 | cur: usize, 117 | end_moves: usize, 118 | stage: i32, 119 | depth: Depth, 120 | tt_move: Move, 121 | recapture_square: Square, 122 | list: [ExtMove; MAX_MOVES as usize], 123 | } 124 | 125 | pub struct MovePickerPC { 126 | cur: usize, 127 | end_moves: usize, 128 | stage: i32, 129 | tt_move: Move, 130 | threshold: Value, 131 | list: [ExtMove; MAX_MOVES as usize], 132 | } 133 | 134 | const MAIN_SEARCH: i32 = 0; 135 | const CAPTURES_INIT: i32 = 1; 136 | const GOOD_CAPTURES: i32 = 2; 137 | const KILLERS: i32 = 3; 138 | const COUNTERMOVE: i32 = 4; 139 | const QUIET_INIT: i32 = 5; 140 | const QUIET: i32 = 6; 141 | const BAD_CAPTURES: i32 = 7; 142 | const EVASION: i32 = 8; 143 | const EVASIONS_INIT: i32 = 9; 144 | const ALL_EVASIONS: i32 = 10; 145 | const PROBCUT: i32 = 11; 146 | const PROBCUT_INIT: i32 = 12; 147 | const PROBCUT_CAPTURES: i32 = 13; 148 | const QSEARCH: i32 = 14; 149 | const QCAPTURES_INIT: i32 = 15; 150 | const QCAPTURES: i32 = 16; 151 | const QCHECKS: i32 = 17; 152 | 153 | // partial_insertion_sort() sorts moves in descending order up to and 154 | // including a given limit. 155 | fn partial_insertion_sort(list: &mut [ExtMove], limit: i32) { 156 | let mut sorted_end = 0; 157 | for p in 1..list.len() { 158 | if list[p].value >= limit { 159 | let tmp = list[p]; 160 | sorted_end += 1; 161 | list[p] = list[sorted_end]; 162 | let mut q = sorted_end; 163 | while q > 0 && list[q-1].value < tmp.value { 164 | list[q] = list[q - 1]; 165 | q -= 1; 166 | } 167 | list[q] = tmp; 168 | } 169 | } 170 | } 171 | 172 | // pick_best() finds the best move in the list and moves it to the front. 173 | // Calling pick_best() is faster than sorting all the moves in advance if 174 | // there are few moves, e.g. the possible captures. 175 | fn pick_best(list: &mut [ExtMove]) -> Move { 176 | let mut q = 0; 177 | for p in 1..list.len() { 178 | if list[p].value > list[q].value { 179 | q = p; 180 | } 181 | } 182 | // let q = list.iter().enumerate() 183 | // .min_by(|&(_, x), &(_, y)| y.value.cmp(&x.value)).unwrap().0; 184 | list.swap(0, q); 185 | list[0].m 186 | } 187 | 188 | // score_*() assigns a numerical value to each move in a list, to be used 189 | // for sorting. 190 | 191 | // Captures are ordered by Most Valuable Victim (MVV), preferring captures 192 | // with a good history. 193 | fn score_captures(pos: &Position, list: &mut [ExtMove]) { 194 | for m in list.iter_mut() { 195 | m.value = piece_value(MG, pos.piece_on(m.m.to())).0 196 | + pos.capture_history.get(pos.moved_piece(m.m), m.m.to(), 197 | pos.piece_on(m.m.to()).piece_type()); 198 | } 199 | } 200 | 201 | // Quiets are ordered using the histories. 202 | fn score_quiets(pos: &Position, mp: &mut MovePicker) { 203 | let list = &mut mp.list[mp.cur..mp.end_moves]; 204 | for m in list.iter_mut() { 205 | m.value = pos.main_history.get(pos.side_to_move(), m.m) 206 | + mp.cmh[0].get(pos.moved_piece(m.m), m.m.to()) 207 | + mp.cmh[1].get(pos.moved_piece(m.m), m.m.to()) 208 | + mp.cmh[2].get(pos.moved_piece(m.m), m.m.to()); 209 | } 210 | } 211 | 212 | fn score_evasions(pos: &Position, list: &mut [ExtMove]) { 213 | for m in list.iter_mut() { 214 | m.value = if pos.capture(m.m) { 215 | piece_value(MG, pos.piece_on(m.m.to())).0 216 | - pos.moved_piece(m.m).piece_type().0 as i32 217 | } else { 218 | pos.main_history.get(pos.side_to_move(), m.m) - (1 << 28) 219 | } 220 | } 221 | } 222 | 223 | // Implementations of the MovePicker classes. As arguments we pass information 224 | // to help it return the (presumably) good moves first, to decide which moves 225 | // to return (in the quiescence search, for instance, we only want to search 226 | // captures, promotions and some checks) and how important good move ordering 227 | // is at the current node. 228 | 229 | impl MovePicker { 230 | pub fn new(pos: &Position, ttm: Move, d: Depth, ss: &[search::Stack]) -> MovePicker { 231 | let mut stage = if pos.checkers() != 0 { EVASION } else { MAIN_SEARCH }; 232 | let tt_move = if ttm != Move::NONE && pos.pseudo_legal(ttm) { ttm } 233 | else { Move::NONE }; 234 | if tt_move == Move::NONE { 235 | stage += 1; 236 | } 237 | let prev_sq = ss[4].current_move.to(); 238 | MovePicker { 239 | cur: 0, 240 | end_moves: 0, 241 | end_bad_captures: 0, 242 | stage: stage, 243 | tt_move: ttm, 244 | countermove: pos.counter_moves.get(pos.piece_on(prev_sq), prev_sq), 245 | killers: [ss[5].killers[0], ss[5].killers[1]], 246 | depth: d, 247 | cmh: [ss[4].cont_history, ss[3].cont_history, ss[1].cont_history], 248 | list: [ExtMove {m: Move::NONE, value: 0}; MAX_MOVES as usize], 249 | } 250 | } 251 | 252 | pub fn next_move(&mut self, pos: &Position, skip_quiets: bool) -> Move { 253 | loop { match self.stage { 254 | MAIN_SEARCH | EVASION => { 255 | self.stage += 1; 256 | return self.tt_move; 257 | } 258 | 259 | CAPTURES_INIT => { 260 | self.end_moves = generate::(pos, &mut self.list, 0); 261 | score_captures(pos, &mut self.list[..self.end_moves]); 262 | self.stage += 1; 263 | } 264 | 265 | GOOD_CAPTURES => { 266 | while self.cur < self.end_moves { 267 | let m = pick_best(&mut self.list[self.cur..self.end_moves]); 268 | self.cur += 1; 269 | if m != self.tt_move { 270 | if pos.see_ge(m, 271 | Value(-55 * self.list[self.cur-1].value / 1024)) 272 | { 273 | return m; 274 | } 275 | 276 | // Losing capture. Move it to the beginning of the 277 | // array. 278 | self.list[self.end_bad_captures].m = m; 279 | self.end_bad_captures += 1; 280 | } 281 | } 282 | self.stage += 1; 283 | let m = self.killers[0]; 284 | if m != Move::NONE 285 | && m != self.tt_move 286 | && pos.pseudo_legal(m) 287 | && !pos.capture(m) 288 | { 289 | return m; 290 | } 291 | } 292 | 293 | KILLERS => { 294 | self.stage += 1; 295 | let m = self.killers[1]; 296 | if m != Move::NONE 297 | && m != self.tt_move 298 | && pos.pseudo_legal(m) 299 | && !pos.capture(m) 300 | { 301 | return m; 302 | } 303 | } 304 | 305 | COUNTERMOVE => { 306 | self.stage += 1; 307 | let m = self.countermove; 308 | if m != Move::NONE 309 | && m != self.tt_move 310 | && m != self.killers[0] 311 | && m != self.killers[1] 312 | && pos.pseudo_legal(m) 313 | && !pos.capture(m) 314 | { 315 | return m; 316 | } 317 | } 318 | 319 | QUIET_INIT => { 320 | self.cur = self.end_bad_captures; 321 | self.end_moves = generate::(pos, &mut self.list, 322 | self.cur); 323 | score_quiets(pos, self); 324 | partial_insertion_sort(&mut self.list[self.cur..self.end_moves], 325 | -4000 * self.depth / ONE_PLY); 326 | self.stage += 1; 327 | } 328 | 329 | QUIET => { 330 | if !skip_quiets { 331 | while self.cur < self.end_moves { 332 | let m = self.list[self.cur].m; 333 | self.cur += 1; 334 | if m != self.tt_move 335 | && m != self.killers[0] 336 | && m != self.killers[1] 337 | && m != self.countermove 338 | { 339 | return m; 340 | } 341 | } 342 | } 343 | self.stage += 1; 344 | self.cur = 0; // Point to beginning of bad captures 345 | } 346 | 347 | BAD_CAPTURES => { 348 | if self.cur < self.end_bad_captures { 349 | let m = self.list[self.cur].m; 350 | self.cur += 1; 351 | return m; 352 | } 353 | break; 354 | } 355 | 356 | EVASIONS_INIT => { 357 | self.cur = 0; 358 | self.end_moves = generate::(pos, &mut self.list, 0); 359 | score_evasions(pos, &mut self.list[..self.end_moves]); 360 | self.stage += 1; 361 | } 362 | 363 | ALL_EVASIONS => { 364 | while self.cur < self.end_moves { 365 | let m = pick_best(&mut self.list[self.cur..self.end_moves]); 366 | self.cur += 1; 367 | if m != self.tt_move { 368 | return m; 369 | } 370 | } 371 | break; 372 | } 373 | 374 | _ => { panic!("movepick") } 375 | } } 376 | 377 | Move::NONE 378 | } 379 | } 380 | 381 | impl MovePickerQ { 382 | pub fn new(pos: &Position, ttm: Move, d: Depth, s: Square) -> MovePickerQ { 383 | let mut stage = if pos.checkers() != 0 { EVASION } else { QSEARCH }; 384 | let tt_move = if ttm != Move::NONE 385 | && pos.pseudo_legal(ttm) 386 | && (d > Depth::QS_RECAPTURES || ttm.to() == s) 387 | { 388 | ttm 389 | } else { 390 | stage += 1; 391 | Move::NONE 392 | }; 393 | 394 | MovePickerQ { 395 | cur: 0, 396 | end_moves: 0, 397 | stage: stage, 398 | depth: d, 399 | tt_move: tt_move, 400 | recapture_square: s, 401 | list: [ExtMove {m: Move::NONE, value: 0}; MAX_MOVES as usize], 402 | } 403 | } 404 | 405 | pub fn next_move(&mut self, pos: &Position) -> Move { 406 | loop { match self.stage { 407 | EVASION | QSEARCH => { 408 | self.stage += 1; 409 | return self.tt_move; 410 | } 411 | 412 | EVASIONS_INIT => { 413 | self.cur = 0; 414 | self.end_moves = generate::(pos, &mut self.list, 0); 415 | score_evasions(pos, &mut self.list[..self.end_moves]); 416 | self.stage += 1; 417 | } 418 | 419 | ALL_EVASIONS => { 420 | while self.cur < self.end_moves { 421 | let m = pick_best(&mut self.list[self.cur..self.end_moves]); 422 | self.cur += 1; 423 | if m != self.tt_move { 424 | return m; 425 | } 426 | } 427 | break; 428 | } 429 | 430 | QCAPTURES_INIT => { 431 | self.cur = 0; 432 | self.end_moves = generate::(pos, &mut self.list, 0); 433 | score_captures(pos, &mut self.list[..self.end_moves]); 434 | self.stage += 1; 435 | } 436 | 437 | QCAPTURES => { 438 | while self.cur < self.end_moves { 439 | let m = pick_best(&mut self.list[self.cur..self.end_moves]); 440 | self.cur += 1; 441 | if m != self.tt_move 442 | && (self.depth > Depth::QS_RECAPTURES 443 | || m.to() == self.recapture_square) 444 | { 445 | return m; 446 | } 447 | } 448 | if self.depth <= Depth::QS_NO_CHECKS { 449 | break; 450 | } 451 | self.cur = 0; 452 | self.end_moves = 453 | generate::(pos, &mut self.list, 0); 454 | self.stage += 1; 455 | } 456 | 457 | QCHECKS => { 458 | while self.cur < self.end_moves { 459 | let m = self.list[self.cur].m; 460 | self.cur += 1; 461 | if m != self.tt_move { 462 | return m; 463 | } 464 | } 465 | break; 466 | } 467 | 468 | _ => { panic!("movepick_q") } 469 | } } 470 | 471 | Move::NONE 472 | } 473 | } 474 | 475 | impl MovePickerPC { 476 | pub fn new(pos: &Position, ttm: Move, threshold: Value) -> MovePickerPC { 477 | let tt_move; 478 | let stage; 479 | 480 | if ttm != Move::NONE && pos.pseudo_legal(ttm) && pos.capture(ttm) 481 | && pos.see_ge(ttm, threshold) 482 | { 483 | tt_move = ttm; 484 | stage = PROBCUT; 485 | } else { 486 | tt_move = Move::NONE; 487 | stage = PROBCUT + 1; 488 | } 489 | 490 | MovePickerPC { 491 | cur: 0, 492 | end_moves: 0, 493 | stage: stage, 494 | tt_move: tt_move, 495 | threshold: threshold, 496 | list: [ExtMove {m: Move::NONE, value: 0}; MAX_MOVES as usize], 497 | } 498 | } 499 | 500 | pub fn next_move(&mut self, pos: &Position) -> Move { 501 | loop { match self.stage { 502 | PROBCUT => { 503 | self.stage += 1; 504 | return self.tt_move; 505 | } 506 | 507 | PROBCUT_INIT => { 508 | self.cur = 0; 509 | self.end_moves = generate::(pos, &mut self.list, 0); 510 | score_captures(pos, &mut self.list[..self.end_moves]); 511 | self.stage += 1; 512 | } 513 | 514 | PROBCUT_CAPTURES => { 515 | while self.cur < self.end_moves { 516 | let m = pick_best(&mut self.list[self.cur..self.end_moves]); 517 | self.cur += 1; 518 | if m != self.tt_move 519 | && pos.see_ge(m, self.threshold) 520 | { 521 | return m; 522 | } 523 | } 524 | break; 525 | } 526 | 527 | _ => { panic!("movepick_pc") } 528 | } } 529 | 530 | Move::NONE 531 | } 532 | } 533 | 534 | -------------------------------------------------------------------------------- /src/bitboard.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | #![allow(dead_code)] 4 | 5 | use types::*; 6 | use uci; 7 | 8 | use std; 9 | 10 | #[derive(Clone, Copy, PartialEq, Eq)] 11 | pub struct Bitboard(pub u64); 12 | 13 | pub fn popcount(bb: Bitboard) -> u32 { 14 | bb.0.count_ones() 15 | } 16 | 17 | pub const ALL_SQUARES: Bitboard = Bitboard(!0u64); 18 | pub const DARK_SQUARES: Bitboard = Bitboard(0xaa55aa55aa55aa55); 19 | 20 | pub const FILEA_BB: Bitboard = Bitboard(0x0101010101010101); 21 | pub const FILEB_BB: Bitboard = Bitboard(0x0202020202020202); 22 | pub const FILEC_BB: Bitboard = Bitboard(0x0404040404040404); 23 | pub const FILED_BB: Bitboard = Bitboard(0x0808080808080808); 24 | pub const FILEE_BB: Bitboard = Bitboard(0x1010101010101010); 25 | pub const FILEF_BB: Bitboard = Bitboard(0x2020202020202020); 26 | pub const FILEG_BB: Bitboard = Bitboard(0x4040404040404040); 27 | pub const FILEH_BB: Bitboard = Bitboard(0x8080808080808080); 28 | 29 | pub const RANK1_BB: Bitboard = Bitboard(0xff); 30 | pub const RANK2_BB: Bitboard = Bitboard(0xff00); 31 | pub const RANK3_BB: Bitboard = Bitboard(0xff0000); 32 | pub const RANK4_BB: Bitboard = Bitboard(0xff000000); 33 | pub const RANK5_BB: Bitboard = Bitboard(0xff00000000); 34 | pub const RANK6_BB: Bitboard = Bitboard(0xff0000000000); 35 | pub const RANK7_BB: Bitboard = Bitboard(0xff000000000000); 36 | pub const RANK8_BB: Bitboard = Bitboard(0xff00000000000000); 37 | 38 | static mut SQUARE_DISTANCE: [[u32; 64]; 64] = [[0; 64]; 64]; 39 | 40 | static mut SQUARE_BB: [Bitboard; 64] = [Bitboard(0); 64]; 41 | static mut FILE_BB: [Bitboard; 8] = [Bitboard(0); 8]; 42 | static mut RANK_BB: [Bitboard; 8] = [Bitboard(0); 8]; 43 | static mut ADJACENT_FILES_BB: [Bitboard; 8] = [Bitboard(0); 8]; 44 | static mut FORWARD_RANKS_BB: [[Bitboard; 8]; 2] = [[Bitboard(0); 8]; 2]; 45 | static mut BETWEEN_BB: [[Bitboard; 64]; 64] = [[Bitboard(0); 64]; 64]; 46 | static mut LINE_BB: [[Bitboard; 64]; 64] = [[Bitboard(0); 64]; 64]; 47 | static mut DISTANCE_RING_BB: [[Bitboard; 8]; 64] = [[Bitboard(0); 8]; 64]; 48 | static mut FORWARD_FILE_BB: [[Bitboard; 64]; 2] = [[Bitboard(0); 64]; 2]; 49 | static mut PASSED_PAWN_MASK: [[Bitboard; 64]; 2] = [[Bitboard(0); 64]; 2]; 50 | static mut PAWN_ATTACK_SPAN: [[Bitboard; 64]; 2] = [[Bitboard(0); 64]; 2]; 51 | static mut PSEUDO_ATTACKS: [[Bitboard; 64]; 8] = [[Bitboard(0); 64]; 8]; 52 | static mut PAWN_ATTACKS: [[Bitboard; 64]; 2] = [[Bitboard(0); 64]; 2]; 53 | 54 | struct Magics { 55 | masks: [Bitboard; 64], 56 | magics: [u64; 64], 57 | attacks: [&'static [Bitboard]; 64], 58 | } 59 | 60 | static mut ROOK_MAGICS: Magics = Magics { 61 | masks: [Bitboard(0); 64], 62 | magics: [0; 64], 63 | attacks: [&[]; 64], 64 | }; 65 | 66 | static mut BISHOP_MAGICS: Magics = Magics { 67 | masks: [Bitboard(0); 64], 68 | magics: [0; 64], 69 | attacks: [&[]; 64], 70 | }; 71 | 72 | static mut ATTACKS_TABLE: [Bitboard; 88772] = [Bitboard(0); 88772]; 73 | 74 | struct MagicInit { 75 | magic: u64, 76 | index: u32, 77 | } 78 | 79 | macro_rules! M { ($x:expr, $y:expr) => { MagicInit { magic: $x, index: $y } } } 80 | 81 | const BISHOP_INIT: [MagicInit; 64] = [ 82 | M!(0x007fbfbfbfbfbfff, 5378), 83 | M!(0x0000a060401007fc, 4093), 84 | M!(0x0001004008020000, 4314), 85 | M!(0x0000806004000000, 6587), 86 | M!(0x0000100400000000, 6491), 87 | M!(0x000021c100b20000, 6330), 88 | M!(0x0000040041008000, 5609), 89 | M!(0x00000fb0203fff80, 22236), 90 | M!(0x0000040100401004, 6106), 91 | M!(0x0000020080200802, 5625), 92 | M!(0x0000004010202000, 16785), 93 | M!(0x0000008060040000, 16817), 94 | M!(0x0000004402000000, 6842), 95 | M!(0x0000000801008000, 7003), 96 | M!(0x000007efe0bfff80, 4197), 97 | M!(0x0000000820820020, 7356), 98 | M!(0x0000400080808080, 4602), 99 | M!(0x00021f0100400808, 4538), 100 | M!(0x00018000c06f3fff, 29531), 101 | M!(0x0000258200801000, 45393), 102 | M!(0x0000240080840000, 12420), 103 | M!(0x000018000c03fff8, 15763), 104 | M!(0x00000a5840208020, 5050), 105 | M!(0x0000020008208020, 4346), 106 | M!(0x0000804000810100, 6074), 107 | M!(0x0001011900802008, 7866), 108 | M!(0x0000804000810100, 32139), 109 | M!(0x000100403c0403ff, 57673), 110 | M!(0x00078402a8802000, 55365), 111 | M!(0x0000101000804400, 15818), 112 | M!(0x0000080800104100, 5562), 113 | M!(0x00004004c0082008, 6390), 114 | M!(0x0001010120008020, 7930), 115 | M!(0x000080809a004010, 13329), 116 | M!(0x0007fefe08810010, 7170), 117 | M!(0x0003ff0f833fc080, 27267), 118 | M!(0x007fe08019003042, 53787), 119 | M!(0x003fffefea003000, 5097), 120 | M!(0x0000101010002080, 6643), 121 | M!(0x0000802005080804, 6138), 122 | M!(0x0000808080a80040, 7418), 123 | M!(0x0000104100200040, 7898), 124 | M!(0x0003ffdf7f833fc0, 42012), 125 | M!(0x0000008840450020, 57350), 126 | M!(0x00007ffc80180030, 22813), 127 | M!(0x007fffdd80140028, 56693), 128 | M!(0x00020080200a0004, 5818), 129 | M!(0x0000101010100020, 7098), 130 | M!(0x0007ffdfc1805000, 4451), 131 | M!(0x0003ffefe0c02200, 4709), 132 | M!(0x0000000820806000, 4794), 133 | M!(0x0000000008403000, 13364), 134 | M!(0x0000000100202000, 4570), 135 | M!(0x0000004040802000, 4282), 136 | M!(0x0004010040100400, 14964), 137 | M!(0x00006020601803f4, 4026), 138 | M!(0x0003ffdfdfc28048, 4826), 139 | M!(0x0000000820820020, 7354), 140 | M!(0x0000000008208060, 4848), 141 | M!(0x0000000000808020, 15946), 142 | M!(0x0000000001002020, 14932), 143 | M!(0x0000000401002008, 16588), 144 | M!(0x0000004040404040, 6905), 145 | M!(0x007fff9fdf7ff813, 16076), 146 | ]; 147 | 148 | const ROOK_INIT: [MagicInit; 64] = [ 149 | M!(0x00280077ffebfffe, 26304), 150 | M!(0x2004010201097fff, 35520), 151 | M!(0x0010020010053fff, 38592), 152 | M!(0x0040040008004002, 8026), 153 | M!(0x7fd00441ffffd003, 22196), 154 | M!(0x4020008887dffffe, 80870), 155 | M!(0x004000888847ffff, 76747), 156 | M!(0x006800fbff75fffd, 30400), 157 | M!(0x000028010113ffff, 11115), 158 | M!(0x0020040201fcffff, 18205), 159 | M!(0x007fe80042ffffe8, 53577), 160 | M!(0x00001800217fffe8, 62724), 161 | M!(0x00001800073fffe8, 34282), 162 | M!(0x00001800e05fffe8, 29196), 163 | M!(0x00001800602fffe8, 23806), 164 | M!(0x000030002fffffa0, 49481), 165 | M!(0x00300018010bffff, 2410), 166 | M!(0x0003000c0085fffb, 36498), 167 | M!(0x0004000802010008, 24478), 168 | M!(0x0004002020020004, 10074), 169 | M!(0x0001002002002001, 79315), 170 | M!(0x0001001000801040, 51779), 171 | M!(0x0000004040008001, 13586), 172 | M!(0x0000006800cdfff4, 19323), 173 | M!(0x0040200010080010, 70612), 174 | M!(0x0000080010040010, 83652), 175 | M!(0x0004010008020008, 63110), 176 | M!(0x0000040020200200, 34496), 177 | M!(0x0002008010100100, 84966), 178 | M!(0x0000008020010020, 54341), 179 | M!(0x0000008020200040, 60421), 180 | M!(0x0000820020004020, 86402), 181 | M!(0x00fffd1800300030, 50245), 182 | M!(0x007fff7fbfd40020, 76622), 183 | M!(0x003fffbd00180018, 84676), 184 | M!(0x001fffde80180018, 78757), 185 | M!(0x000fffe0bfe80018, 37346), 186 | M!(0x0001000080202001, 370), 187 | M!(0x0003fffbff980180, 42182), 188 | M!(0x0001fffdff9000e0, 45385), 189 | M!(0x00fffefeebffd800, 61659), 190 | M!(0x007ffff7ffc01400, 12790), 191 | M!(0x003fffbfe4ffe800, 16762), 192 | M!(0x001ffff01fc03000, 0), 193 | M!(0x000fffe7f8bfe800, 38380), 194 | M!(0x0007ffdfdf3ff808, 11098), 195 | M!(0x0003fff85fffa804, 21803), 196 | M!(0x0001fffd75ffa802, 39189), 197 | M!(0x00ffffd7ffebffd8, 58628), 198 | M!(0x007fff75ff7fbfd8, 44116), 199 | M!(0x003fff863fbf7fd8, 78357), 200 | M!(0x001fffbfdfd7ffd8, 44481), 201 | M!(0x000ffff810280028, 64134), 202 | M!(0x0007ffd7f7feffd8, 41759), 203 | M!(0x0003fffc0c480048, 1394), 204 | M!(0x0001ffffafd7ffd8, 40910), 205 | M!(0x00ffffe4ffdfa3ba, 66516), 206 | M!(0x007fffef7ff3d3da, 3897), 207 | M!(0x003fffbfdfeff7fa, 3930), 208 | M!(0x001fffeff7fbfc22, 72934), 209 | M!(0x0000020408001001, 72662), 210 | M!(0x0007fffeffff77fd, 56325), 211 | M!(0x0003ffffbf7dfeec, 66501), 212 | M!(0x0001ffff9dffa333, 14826), 213 | ]; 214 | 215 | // Compute the attack's index using the 'magic bitboards' approach 216 | fn index_bishop(s: Square, occupied: Bitboard) -> usize { 217 | unsafe { 218 | (u64::wrapping_mul((occupied & BISHOP_MAGICS.masks[s.0 as usize]).0, 219 | BISHOP_MAGICS.magics[s.0 as usize] 220 | ) >> (64-9)) as usize 221 | } 222 | } 223 | 224 | fn index_rook(s: Square, occupied: Bitboard) -> usize { 225 | unsafe { 226 | (u64::wrapping_mul((occupied & ROOK_MAGICS.masks[s.0 as usize]).0, 227 | ROOK_MAGICS.magics[s.0 as usize] 228 | ) >> (64-12)) as usize 229 | } 230 | } 231 | 232 | fn attacks_bb_bishop(s: Square, occupied: Bitboard) -> Bitboard { 233 | unsafe { 234 | BISHOP_MAGICS.attacks[s.0 as usize][index_bishop(s, occupied)] 235 | } 236 | } 237 | 238 | fn attacks_bb_rook(s: Square, occupied: Bitboard) -> Bitboard { 239 | unsafe { 240 | ROOK_MAGICS.attacks[s.0 as usize][index_rook(s, occupied)] 241 | } 242 | } 243 | 244 | impl std::convert::From for Bitboard { 245 | fn from(s: Square) -> Self { 246 | unsafe { SQUARE_BB[s.0 as usize] } 247 | } 248 | } 249 | 250 | impl Square { 251 | pub fn bb(self) -> Bitboard { 252 | Bitboard::from(self) 253 | } 254 | 255 | pub fn file_bb(self) -> Bitboard { 256 | file_bb(self.file()) 257 | } 258 | 259 | pub fn rank_bb(self) -> Bitboard { 260 | unsafe { RANK_BB[self.rank() as usize] } 261 | } 262 | } 263 | 264 | impl std::ops::BitOr for Bitboard { 265 | type Output = Self; 266 | fn bitor(self, rhs: Self) -> Self { 267 | Bitboard(self.0 | rhs.0) 268 | } 269 | } 270 | 271 | impl std::ops::BitOr for Bitboard { 272 | type Output = Bitboard; 273 | fn bitor(self, rhs: Square) -> Self { 274 | self | Bitboard::from(rhs) 275 | } 276 | } 277 | 278 | impl std::ops::BitAnd for Bitboard { 279 | type Output = Self; 280 | fn bitand(self, rhs: Self) -> Self { 281 | Bitboard(self.0 & rhs.0) 282 | } 283 | } 284 | 285 | impl std::ops::BitAnd for Bitboard { 286 | type Output = Bitboard; 287 | fn bitand(self, rhs: Square) -> Self { 288 | self & Bitboard::from(rhs) 289 | } 290 | } 291 | 292 | impl std::ops::BitXor for Bitboard { 293 | type Output = Self; 294 | fn bitxor(self, rhs: Self) -> Self { 295 | Bitboard(self.0 ^ rhs.0) 296 | } 297 | } 298 | 299 | impl std::ops::BitXor for Bitboard { 300 | type Output = Bitboard; 301 | fn bitxor(self, rhs: Square) -> Self { 302 | self ^ Bitboard::from(rhs) 303 | } 304 | } 305 | 306 | impl std::ops::Not for Bitboard { 307 | type Output = Bitboard; 308 | fn not(self) -> Self { 309 | Bitboard(!self.0) 310 | } 311 | } 312 | 313 | impl std::ops::Neg for Bitboard { 314 | type Output = Bitboard; 315 | fn neg(self) -> Self { 316 | Bitboard(self.0.wrapping_neg()) 317 | } 318 | } 319 | 320 | impl std::ops::Shl for Bitboard { 321 | type Output = Bitboard; 322 | fn shl(self, rhs: i32) -> Self { 323 | Bitboard(self.0 << rhs) 324 | } 325 | } 326 | 327 | impl std::ops::Shr for Bitboard { 328 | type Output = Bitboard; 329 | fn shr(self, rhs: i32) -> Self { 330 | Bitboard(self.0 >> rhs) 331 | } 332 | } 333 | 334 | impl std::ops::BitOrAssign for Bitboard 335 | where Bitboard: std::ops::BitOr 336 | { 337 | fn bitor_assign(&mut self, rhs: RHS) { 338 | *self = *self | rhs; 339 | } 340 | } 341 | 342 | impl std::ops::BitAndAssign for Bitboard 343 | where Bitboard: std::ops::BitAnd 344 | { 345 | fn bitand_assign(&mut self, rhs: RHS) { 346 | *self = *self & rhs; 347 | } 348 | } 349 | 350 | impl std::ops::BitXorAssign for Bitboard 351 | where Bitboard: std::ops::BitXor 352 | { 353 | fn bitxor_assign(&mut self, rhs: RHS) { 354 | *self = *self ^ rhs; 355 | } 356 | } 357 | 358 | impl std::cmp::PartialEq for Bitboard { 359 | fn eq(&self, rhs: &u64) -> bool { 360 | debug_assert!(*rhs == 0); 361 | (*self).0 == *rhs 362 | } 363 | } 364 | 365 | impl std::fmt::Display for Bitboard { 366 | fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { 367 | for s in *self { 368 | write!(f, "{} ", uci::square(s)).unwrap(); 369 | } 370 | write!(f, "") 371 | } 372 | } 373 | 374 | pub fn more_than_one(b: Bitboard) -> bool { 375 | (b.0 & u64::wrapping_sub(b.0, 1)) != 0 376 | } 377 | 378 | pub fn lsb(b: Bitboard) -> Square { 379 | debug_assert!(b != 0); 380 | Square(u64::trailing_zeros(b.0)) 381 | } 382 | 383 | pub fn msb(b: Bitboard) -> Square { 384 | debug_assert!(b != 0); 385 | Square(63 ^ u64::leading_zeros(b.0)) 386 | } 387 | 388 | pub fn pop_lsb(b: &mut Bitboard) -> Square { 389 | let s = lsb(*b); 390 | b.0 &= u64::wrapping_sub(b.0, 1); 391 | s 392 | } 393 | 394 | pub fn frontmost_sq(c: Color, b: Bitboard) -> Square { 395 | if c == WHITE { msb(b) } else { lsb(b) } 396 | } 397 | 398 | pub fn backmost_sq(c: Color, b: Bitboard) -> Square { 399 | if c == WHITE { lsb(b) } else { msb(b) } 400 | } 401 | 402 | impl Iterator for Bitboard { 403 | type Item = Square; 404 | fn next(&mut self) -> Option { 405 | if (*self).0 != 0 { 406 | Some(pop_lsb(self)) 407 | } else { 408 | None 409 | } 410 | } 411 | } 412 | 413 | // file_bb() return a bitboard representing all the squares on the given file. 414 | 415 | pub fn file_bb(f: File) -> Bitboard { 416 | unsafe { FILE_BB[f as usize] } 417 | } 418 | 419 | // bitboard!(A1, A2, ...) creates a bitboard with squares A1, A2, ... 420 | 421 | macro_rules! bitboard { 422 | () => { Bitboard(0) }; 423 | ($sq:ident) => { bitboard!() | Square::$sq }; 424 | ($sq:ident, $($sqs:ident),+) => { bitboard!($($sqs),*) | Square::$sq }; 425 | } 426 | 427 | // shift() moves a bitboard one step along direction D. Mainly for pawns. 428 | 429 | impl Bitboard { 430 | pub fn shift(self, d: Direction) -> Bitboard { 431 | match d { 432 | NORTH => self << 8, 433 | SOUTH => self >> 8, 434 | NORTH_EAST => (self & !FILEH_BB) << 9, 435 | SOUTH_EAST => (self & !FILEH_BB) >> 7, 436 | NORTH_WEST => (self & !FILEA_BB) << 7, 437 | SOUTH_WEST => (self & !FILEA_BB) >> 9, 438 | _ => Bitboard(0) 439 | } 440 | } 441 | } 442 | 443 | // adjacent_files_bb() returns a bitboard representing all the squares on 444 | // the adjacent files of the given one. 445 | 446 | pub fn adjacent_files_bb(f: File) -> Bitboard { 447 | unsafe { ADJACENT_FILES_BB[f as usize] } 448 | } 449 | 450 | // between_bb() returns a bitboard representing all the squares between the 451 | // two given ones. For instance, between_bb(Square::C4, Square::F7) returns 452 | // a bitboard with the bits for squares d5 and e6 set. If s1 and s2 are not 453 | // on the same rank, file or diagonal, an empty bitboard is returned. 454 | 455 | pub fn between_bb(s1: Square, s2: Square) -> Bitboard { 456 | unsafe { BETWEEN_BB[s1.0 as usize][s2.0 as usize] } 457 | } 458 | 459 | // forward_ranks_bb() returns a bitboard representing all the squares on all 460 | // the ranks in front of the given one, from the point of view of the given 461 | // color. For instance, forward_ranks_bb(BLACK, Square::D3) returns the 16 462 | // squares on ranks 1 and 2. 463 | 464 | pub fn forward_ranks_bb(c: Color, s: Square) -> Bitboard { 465 | unsafe { FORWARD_RANKS_BB[c.0 as usize][s.rank() as usize] } 466 | } 467 | 468 | // forward_file_bb() returns a bitboard representing all the squares along 469 | // the line in front of the given one, from the point of view of the given 470 | // color. 471 | 472 | pub fn forward_file_bb(c: Color, s: Square) -> Bitboard { 473 | unsafe { FORWARD_FILE_BB[c.0 as usize][s.0 as usize] } 474 | } 475 | 476 | // pawn_attack_span() returns a bitboard representing all the squares that 477 | // can be attacked by a pawn of the given color when it moves along its file, 478 | // starting from the given square. 479 | 480 | pub fn pawn_attack_span(c: Color, s: Square) -> Bitboard { 481 | unsafe { PAWN_ATTACK_SPAN[c.0 as usize][s.0 as usize] } 482 | } 483 | 484 | // passed_pawn_mask() returns a bitboard mask which can be used to test if a 485 | // pawn of the given color and on the given square is a passed pawn. 486 | 487 | pub fn passed_pawn_mask(c: Color, s: Square) -> Bitboard { 488 | unsafe { PASSED_PAWN_MASK[c.0 as usize][s.0 as usize] } 489 | } 490 | 491 | pub fn line_bb(s1: Square, s2: Square) -> Bitboard { 492 | unsafe { LINE_BB[s1.0 as usize][s2.0 as usize] } 493 | } 494 | 495 | // aligned() returns true if the squares s1, s2 and s3 are aligned either on 496 | // a straight or on a diagonal line. 497 | 498 | pub fn aligned(s1: Square, s2: Square, s3: Square) -> bool { 499 | line_bb(s1, s2) & s3 != 0 500 | } 501 | 502 | pub fn pseudo_attacks(pt: PieceType, s: Square) -> Bitboard { 503 | unsafe { PSEUDO_ATTACKS[pt.0 as usize][s.0 as usize] } 504 | } 505 | 506 | pub fn pawn_attacks(c: Color, s: Square) -> Bitboard { 507 | unsafe { PAWN_ATTACKS[c.0 as usize][s.0 as usize] } 508 | } 509 | 510 | pub fn distance_ring_bb(s: Square, d: i32) -> Bitboard { 511 | unsafe { DISTANCE_RING_BB[s.0 as usize][d as usize] } 512 | } 513 | 514 | pub trait Distance { 515 | fn distance(x: Self, y: Self) -> u32; 516 | } 517 | 518 | impl Distance for u32 { 519 | fn distance(x: Self, y: Self) -> u32 { 520 | if x > y { x - y } else { y - x } 521 | } 522 | } 523 | 524 | impl Distance for Square { 525 | fn distance(x: Self, y: Self) -> u32 { 526 | unsafe { SQUARE_DISTANCE[x.0 as usize][y.0 as usize] } 527 | } 528 | } 529 | 530 | // init() initializes various bitboard tables. It is called at startup. 531 | 532 | pub fn init() { 533 | for s in ALL_SQUARES { 534 | unsafe { SQUARE_BB[s.0 as usize] = Bitboard(1u64) << (s.0 as i32); } 535 | } 536 | 537 | for f in 0..8 { 538 | unsafe { FILE_BB[f as usize] = FILEA_BB << f; } 539 | } 540 | 541 | for r in 0..8 { 542 | unsafe { RANK_BB[r as usize] = RANK1_BB << (8 * r); } 543 | } 544 | 545 | for f in 0..8 { 546 | unsafe { 547 | let left = if f > FILE_A { file_bb(f - 1) } else { Bitboard(0) }; 548 | let right = if f < FILE_H { file_bb(f + 1) } else { Bitboard(0) }; 549 | ADJACENT_FILES_BB[f as usize] = left | right; 550 | } 551 | } 552 | 553 | for r in 0..7 { 554 | unsafe { 555 | FORWARD_RANKS_BB[BLACK.0 as usize][(r + 1) as usize] = 556 | FORWARD_RANKS_BB[BLACK.0 as usize][r as usize] 557 | | RANK_BB[r as usize]; 558 | FORWARD_RANKS_BB[WHITE.0 as usize][r as usize] = 559 | !FORWARD_RANKS_BB[BLACK.0 as usize][(r + 1) as usize]; 560 | } 561 | } 562 | 563 | for &c in [WHITE, BLACK].iter() { 564 | for s in ALL_SQUARES { 565 | unsafe { 566 | FORWARD_FILE_BB[c.0 as usize][s.0 as usize] = 567 | FORWARD_RANKS_BB[c.0 as usize][s.rank() as usize] 568 | & FILE_BB[s.file() as usize]; 569 | PAWN_ATTACK_SPAN[c.0 as usize][s.0 as usize] = 570 | FORWARD_RANKS_BB[c.0 as usize][s.rank() as usize] 571 | & ADJACENT_FILES_BB[s.file() as usize]; 572 | PASSED_PAWN_MASK[c.0 as usize][s.0 as usize] = 573 | FORWARD_FILE_BB[c.0 as usize][s.0 as usize] 574 | | PAWN_ATTACK_SPAN[c.0 as usize][s.0 as usize]; 575 | } 576 | } 577 | } 578 | 579 | for s1 in ALL_SQUARES { 580 | for s2 in ALL_SQUARES { 581 | if s1 != s2 { 582 | unsafe { 583 | let dist = 584 | std::cmp::max(File::distance(s1.file(),s2.file()), 585 | Rank::distance(s1.rank(), s2.rank())); 586 | SQUARE_DISTANCE[s1.0 as usize][s2.0 as usize] = dist; 587 | DISTANCE_RING_BB[s1.0 as usize][dist as usize - 1] |= s2; 588 | } 589 | } 590 | } 591 | } 592 | 593 | for &c in [WHITE, BLACK].iter() { 594 | for &pt in [PAWN, KNIGHT, KING].iter() { 595 | for s in ALL_SQUARES { 596 | let steps: &[i32] = match pt { 597 | PAWN => &[7, 9], 598 | KNIGHT => &[6, 10, 15, 17], 599 | _ => &[1, 7, 8, 9] 600 | }; 601 | for &d in steps.iter() { 602 | let to = s 603 | + if c == WHITE { Direction(d) } else { -Direction(d) }; 604 | if to.is_ok() && Square::distance(s, to) < 3 { 605 | unsafe { 606 | if pt == PAWN { 607 | PAWN_ATTACKS[c.0 as usize][s.0 as usize] |= to; 608 | } else { 609 | PSEUDO_ATTACKS[pt.0 as usize][s.0 as usize] |= 610 | to; 611 | } 612 | } 613 | } 614 | } 615 | } 616 | } 617 | } 618 | 619 | let rook_dirs = [NORTH, EAST, SOUTH, WEST]; 620 | let bishop_dirs = [NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST]; 621 | 622 | unsafe { 623 | init_magics(&mut ROOK_MAGICS, &ROOK_INIT, rook_dirs, index_rook); 624 | init_magics(&mut BISHOP_MAGICS, &BISHOP_INIT, bishop_dirs, 625 | index_bishop); 626 | } 627 | 628 | for s1 in ALL_SQUARES { 629 | let b_att = attacks_bb(BISHOP, s1, Bitboard(0)); 630 | let r_att = attacks_bb(ROOK , s1, Bitboard(0)); 631 | unsafe { 632 | PSEUDO_ATTACKS[BISHOP.0 as usize][s1.0 as usize] = b_att; 633 | PSEUDO_ATTACKS[ROOK.0 as usize][s1.0 as usize] = r_att; 634 | PSEUDO_ATTACKS[QUEEN.0 as usize][s1.0 as usize] = b_att | r_att; 635 | } 636 | for &pt in [BISHOP, ROOK].iter() { 637 | for s2 in ALL_SQUARES { 638 | unsafe { 639 | if PSEUDO_ATTACKS[pt.0 as usize][s1.0 as usize] & s2 == 0 { 640 | continue; 641 | } 642 | LINE_BB[s1.0 as usize][s2.0 as usize] = 643 | (attacks_bb(pt, s1, Bitboard(0)) 644 | & attacks_bb(pt, s2, Bitboard(0))) | s1 | s2; 645 | BETWEEN_BB[s1.0 as usize][s2.0 as usize] = 646 | attacks_bb(pt, s1, s2.bb()) 647 | & attacks_bb(pt, s2, s1.bb()); 648 | } 649 | } 650 | } 651 | } 652 | } 653 | 654 | fn sliding_attack( 655 | directions: [Direction; 4], sq: Square, occupied: Bitboard 656 | ) -> Bitboard { 657 | let mut attack = Bitboard(0); 658 | for d in directions.iter() { 659 | let mut s = sq + *d; 660 | while s.is_ok() && Square::distance(s, s - *d) == 1 { 661 | attack |= s; 662 | if occupied & s != 0 { 663 | break; 664 | } 665 | s += *d; 666 | } 667 | } 668 | attack 669 | } 670 | 671 | fn init_magics( 672 | m: &mut Magics, magic_init: &[MagicInit; 64], dirs: [Direction; 4], 673 | index: fn(Square, Bitboard) -> usize, 674 | ) { 675 | for s in ALL_SQUARES { 676 | // Board edges are not considered in the relevant occupancies 677 | let edges = ((RANK1_BB | RANK8_BB) & !s.rank_bb()) 678 | | ((FILEA_BB | FILEH_BB) & !s.file_bb()); 679 | 680 | let mask = sliding_attack(dirs, s, Bitboard(0)) & !edges; 681 | 682 | m.masks[s.0 as usize] = mask; 683 | m.magics[s.0 as usize] = magic_init[s.0 as usize].magic; 684 | 685 | let base = magic_init[s.0 as usize].index as usize; 686 | let mut size = 0; 687 | 688 | // Use Carry-Ripler trick to enumerate all subsets of masks[s] and 689 | // fill the attacks table. 690 | let mut b = Bitboard(0); 691 | loop { 692 | let idx = index(s, b); 693 | size = std::cmp::max(size, idx + 1); 694 | unsafe { 695 | ATTACKS_TABLE[base + idx] = sliding_attack(dirs, s, b); 696 | } 697 | b = Bitboard(u64::wrapping_sub(b.0, mask.0)) & mask; 698 | if b == 0 { break; } 699 | } 700 | 701 | m.attacks[s.0 as usize] = unsafe { &ATTACKS_TABLE[base..base+size] }; 702 | } 703 | } 704 | 705 | // attacks_bb() returns a bitboard representing all the squares attacked by 706 | // a piece of type Pt (bishop or rook) placed on 's'. 707 | 708 | pub fn attacks_bb(pt: PieceType, s: Square, occupied: Bitboard) -> Bitboard { 709 | match pt { 710 | BISHOP => attacks_bb_bishop(s, occupied), 711 | ROOK => attacks_bb_rook(s, occupied), 712 | QUEEN => attacks_bb_bishop(s, occupied) | attacks_bb_rook(s, occupied), 713 | _ => pseudo_attacks(pt, s), 714 | } 715 | } 716 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | #![allow(dead_code)] 4 | 5 | use std; 6 | 7 | #[derive(Clone, Copy, PartialEq, Eq, Hash)] 8 | pub struct Key(pub u64); 9 | 10 | impl std::ops::BitXor for Key { 11 | type Output = Self; 12 | fn bitxor(self, rhs: Self) -> Self { Key(self.0 ^ rhs.0) } 13 | } 14 | 15 | impl std::ops::BitXorAssign for Key { 16 | fn bitxor_assign(&mut self, rhs: Key) { *self = *self ^ rhs; } 17 | } 18 | 19 | impl std::fmt::Display for Key { 20 | fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { 21 | write!(f, "{:X}", self.0) 22 | } 23 | } 24 | 25 | pub const MAX_MOVES: usize = 256; 26 | pub const MAX_PLY: i32 = 128; 27 | pub const MAX_MATE_PLY : i32 = 128; 28 | 29 | #[derive(Clone, Copy, PartialEq, Eq)] 30 | pub struct Color(pub u32); 31 | 32 | pub const WHITE: Color = Color(0); 33 | pub const BLACK: Color = Color(1); 34 | 35 | impl std::ops::Not for Color { 36 | type Output = Color; 37 | fn not(self) -> Self { Color(self.0 ^ 1) } 38 | } 39 | 40 | impl std::ops::BitXor for Color { 41 | type Output = Self; 42 | fn bitxor(self, rhs: bool) -> Self { Color(self.0 ^ (rhs as u32)) } 43 | } 44 | 45 | impl Iterator for Color { 46 | type Item = Self; 47 | 48 | fn next(&mut self) -> Option { 49 | let sq = self.0; 50 | self.0 += 1; 51 | Some(Color(sq)) 52 | } 53 | } 54 | 55 | pub struct White; 56 | pub struct Black; 57 | 58 | pub trait ColorTrait { 59 | type KingSide: CastlingRightTrait; 60 | type QueenSide: CastlingRightTrait; 61 | const COLOR: Color; 62 | } 63 | 64 | impl ColorTrait for White { 65 | type KingSide = WhiteOO; 66 | type QueenSide = WhiteOOO; 67 | const COLOR: Color = WHITE; 68 | } 69 | 70 | impl ColorTrait for Black { 71 | type KingSide = BlackOO; 72 | type QueenSide = BlackOOO; 73 | const COLOR: Color = BLACK; 74 | } 75 | 76 | #[allow(non_camel_case_types)] 77 | #[derive(Clone, Copy, PartialEq, Eq)] 78 | pub enum CastlingSide { 79 | KING, 80 | QUEEN 81 | } 82 | 83 | #[derive(Clone, Copy, PartialEq, Eq)] 84 | pub struct CastlingRight(pub u32); 85 | 86 | pub const NO_CASTLING : CastlingRight = CastlingRight(0); 87 | pub const WHITE_OO : CastlingRight = CastlingRight(1); 88 | pub const WHITE_OOO : CastlingRight = CastlingRight(2); 89 | pub const BLACK_OO : CastlingRight = CastlingRight(4); 90 | pub const BLACK_OOO : CastlingRight = CastlingRight(8); 91 | pub const ANY_CASTLING: CastlingRight = CastlingRight(15); 92 | 93 | pub trait CastlingRightTrait { 94 | const CR: CastlingRight; 95 | } 96 | 97 | pub struct WhiteOO; 98 | pub struct WhiteOOO; 99 | pub struct BlackOO; 100 | pub struct BlackOOO; 101 | 102 | impl CastlingRightTrait for WhiteOO { 103 | const CR: CastlingRight = WHITE_OO; 104 | } 105 | 106 | impl CastlingRightTrait for WhiteOOO { 107 | const CR: CastlingRight = WHITE_OOO; 108 | } 109 | 110 | impl CastlingRightTrait for BlackOO { 111 | const CR: CastlingRight = BLACK_OO; 112 | } 113 | 114 | impl CastlingRightTrait for BlackOOO { 115 | const CR: CastlingRight = BLACK_OOO; 116 | } 117 | 118 | impl CastlingRight { 119 | pub fn make(c: Color, cs: CastlingSide) -> CastlingRight { 120 | use types::CastlingSide::*; 121 | match (c, cs) { 122 | (WHITE, KING) => WHITE_OO, 123 | (WHITE, _ ) => WHITE_OOO, 124 | (_ , KING) => BLACK_OO, 125 | (_ , _ ) => BLACK_OOO 126 | } 127 | } 128 | } 129 | 130 | impl std::ops::BitOr for Color { 131 | type Output = CastlingRight; 132 | fn bitor(self, rhs: CastlingSide) -> CastlingRight { 133 | CastlingRight(1u32 << ((rhs as u32) + 2 * self.0)) 134 | } 135 | } 136 | 137 | impl std::ops::BitAnd for CastlingRight { 138 | type Output = Self; 139 | fn bitand(self, rhs: Self) -> Self { CastlingRight(self.0 & rhs.0) } 140 | } 141 | 142 | impl std::ops::BitOr for CastlingRight { 143 | type Output = Self; 144 | fn bitor(self, rhs: Self) -> Self { CastlingRight(self.0 | rhs.0) } 145 | } 146 | 147 | impl std::ops::BitAndAssign for CastlingRight { 148 | fn bitand_assign(&mut self, rhs: Self) { *self = *self & rhs; } 149 | } 150 | 151 | impl std::ops::BitOrAssign for CastlingRight { 152 | fn bitor_assign(&mut self, rhs: Self) { *self = *self | rhs; } 153 | } 154 | 155 | impl std::ops::Not for CastlingRight { 156 | type Output = CastlingRight; 157 | fn not(self) -> Self { CastlingRight(!self.0) } 158 | } 159 | 160 | impl std::cmp::PartialEq for CastlingRight { 161 | fn eq(&self, rhs: &u32) -> bool { 162 | debug_assert!(*rhs == 0); 163 | self.0 == *rhs 164 | } 165 | } 166 | 167 | pub type Phase = i32; 168 | 169 | pub const PHASE_ENDGAME: Phase = 0; 170 | pub const PHASE_MIDGAME: Phase = 128; 171 | 172 | pub const MG: usize = 0; 173 | pub const EG: usize = 1; 174 | 175 | #[derive(Clone, Copy, PartialEq, Eq)] 176 | pub struct ScaleFactor(pub i32); 177 | 178 | impl ScaleFactor { 179 | pub const DRAW : ScaleFactor = ScaleFactor(0); 180 | pub const ONEPAWN: ScaleFactor = ScaleFactor(48); 181 | pub const NORMAL : ScaleFactor = ScaleFactor(64); 182 | pub const MAX : ScaleFactor = ScaleFactor(128); 183 | pub const NONE : ScaleFactor = ScaleFactor(255); 184 | } 185 | 186 | #[derive(Clone, Copy, PartialEq, Eq)] 187 | pub struct Bound(pub u32); 188 | 189 | impl Bound { 190 | pub const NONE : Bound = Bound(0); 191 | pub const UPPER: Bound = Bound(1); 192 | pub const LOWER: Bound = Bound(2); 193 | pub const EXACT: Bound = Bound(3); 194 | } 195 | 196 | impl std::ops::BitAnd for Bound { 197 | type Output = Self; 198 | fn bitand(self, rhs: Self) -> Self { Bound(self.0 & rhs.0) } 199 | } 200 | 201 | impl std::ops::BitOr for Bound { 202 | type Output = Self; 203 | fn bitor(self, rhs: Self) -> Self { Bound(self.0 | rhs.0) } 204 | } 205 | 206 | impl std::cmp::PartialEq for Bound { 207 | fn eq(&self, rhs: &u32) -> bool { 208 | debug_assert!(*rhs == 0); 209 | self.0 == *rhs 210 | } 211 | } 212 | 213 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 214 | pub struct PieceType(pub u32); 215 | 216 | pub const NO_PIECE_TYPE: PieceType = PieceType(0); 217 | 218 | pub const PAWN : PieceType = PieceType(1); 219 | pub const KNIGHT: PieceType = PieceType(2); 220 | pub const BISHOP: PieceType = PieceType(3); 221 | pub const ROOK : PieceType = PieceType(4); 222 | pub const QUEEN : PieceType = PieceType(5); 223 | pub const KING : PieceType = PieceType(6); 224 | 225 | pub const QUEEN_DIAGONAL: PieceType = PieceType(7); 226 | 227 | pub const ALL_PIECES: PieceType = PieceType(0); 228 | 229 | pub struct Pawn; 230 | pub struct Knight; 231 | pub struct Bishop; 232 | pub struct Rook; 233 | pub struct Queen; 234 | pub struct King; 235 | 236 | pub trait PieceTypeTrait { 237 | const TYPE: PieceType; 238 | } 239 | 240 | impl PieceTypeTrait for Pawn { 241 | const TYPE: PieceType = PAWN; 242 | } 243 | 244 | impl PieceTypeTrait for Knight { 245 | const TYPE: PieceType = KNIGHT; 246 | } 247 | 248 | impl PieceTypeTrait for Bishop { 249 | const TYPE: PieceType = BISHOP; 250 | } 251 | 252 | impl PieceTypeTrait for Rook { 253 | const TYPE: PieceType = ROOK; 254 | } 255 | 256 | impl PieceTypeTrait for Queen { 257 | const TYPE: PieceType = QUEEN; 258 | } 259 | 260 | impl PieceTypeTrait for King { 261 | const TYPE: PieceType = KING; 262 | } 263 | 264 | 265 | 266 | #[derive(Clone, Copy, PartialEq, Eq)] 267 | pub struct Piece(pub u32); 268 | 269 | pub const NO_PIECE: Piece = Piece(0); 270 | 271 | pub const W_PAWN : Piece = Piece(1); 272 | pub const W_KNIGHT: Piece = Piece(2); 273 | pub const W_BISHOP: Piece = Piece(3); 274 | pub const W_ROOK : Piece = Piece(4); 275 | pub const W_QUEEN : Piece = Piece(5); 276 | pub const W_KING : Piece = Piece(6); 277 | 278 | pub const B_PAWN : Piece = Piece(9); 279 | pub const B_KNIGHT: Piece = Piece(10); 280 | pub const B_BISHOP: Piece = Piece(11); 281 | pub const B_ROOK : Piece = Piece(12); 282 | pub const B_QUEEN : Piece = Piece(13); 283 | pub const B_KING : Piece = Piece(14); 284 | 285 | impl Piece { 286 | pub fn piece_type(self) -> PieceType { PieceType(self.0 & 7) } 287 | 288 | pub fn color(self) -> Color { Color(self.0 >> 3) } 289 | 290 | pub fn make(c: Color, pt: PieceType) -> Piece { Piece((c.0 << 3) + pt.0) } 291 | } 292 | 293 | impl Iterator for Piece { 294 | type Item = Self; 295 | fn next(&mut self) -> Option { 296 | let pc = self.0; 297 | self.0 += 1; 298 | Some(Piece(pc)) 299 | } 300 | } 301 | 302 | impl std::ops::Not for Piece { 303 | type Output = Self; 304 | fn not(self) -> Self { Piece(self.0 ^ 8) } 305 | } 306 | 307 | impl std::ops::BitXor for Piece { 308 | type Output = Self; 309 | fn bitxor(self, rhs: bool) -> Self { Piece(self.0 ^ ((rhs as u32) << 3)) } 310 | } 311 | 312 | #[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] 313 | pub struct Depth(pub i32); 314 | 315 | impl std::ops::Add for Depth { 316 | type Output = Self; 317 | fn add(self, rhs: Self) -> Self { Depth(self.0 + rhs.0) } 318 | } 319 | 320 | impl std::ops::Sub for Depth { 321 | type Output = Self; 322 | fn sub(self, rhs: Self) -> Self { Depth(self.0 - rhs.0) } 323 | } 324 | 325 | impl std::ops::AddAssign for Depth { 326 | fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } 327 | } 328 | 329 | impl std::ops::SubAssign for Depth { 330 | fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } 331 | } 332 | 333 | impl std::ops::Mul for Depth { 334 | type Output = Self; 335 | fn mul(self, rhs: i32) -> Self { Depth(self.0 * rhs) } 336 | } 337 | 338 | impl std::ops::Mul for i32 { 339 | type Output = Depth; 340 | fn mul(self, rhs: Depth) -> Depth { Depth(self * rhs.0) } 341 | } 342 | 343 | impl std::ops::Div for Depth { 344 | type Output = i32; 345 | fn div(self, rhs: Depth) -> i32 { self.0 / rhs.0 } 346 | } 347 | 348 | pub const ONE_PLY: Depth = Depth(1); 349 | 350 | pub const DEPTH_ZERO : Depth = Depth( 0 * ONE_PLY.0); 351 | pub const DEPTH_QS_CHECKS : Depth = Depth( 0 * ONE_PLY.0); 352 | pub const DEPTH_QS_NO_CHECKS : Depth = Depth(-1 * ONE_PLY.0); 353 | pub const DEPTH_QS_RECAPTURES: Depth = Depth(-5 * ONE_PLY.0); 354 | 355 | pub const DEPTH_NONE: Depth = Depth(-6 * ONE_PLY.0); 356 | pub const DEPTH_MAX : Depth = Depth(MAX_PLY * ONE_PLY.0); 357 | 358 | impl Depth { 359 | pub const ZERO : Depth = Depth( 0 * ONE_PLY.0); 360 | pub const QS_CHECKS : Depth = Depth( 0 * ONE_PLY.0); 361 | pub const QS_NO_CHECKS : Depth = Depth(-1 * ONE_PLY.0); 362 | pub const QS_RECAPTURES: Depth = Depth(-5 * ONE_PLY.0); 363 | 364 | pub const NONE: Depth = Depth(-6 * ONE_PLY.0); 365 | pub const MAX : Depth = Depth(MAX_PLY * ONE_PLY.0); 366 | } 367 | 368 | pub type File = u32; 369 | pub type Rank = u32; 370 | 371 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 372 | pub struct Square(pub u32); 373 | 374 | pub const FILE_A: File = 0; 375 | pub const FILE_B: File = 1; 376 | pub const FILE_C: File = 2; 377 | pub const FILE_D: File = 3; 378 | pub const FILE_E: File = 4; 379 | pub const FILE_F: File = 5; 380 | pub const FILE_G: File = 6; 381 | pub const FILE_H: File = 7; 382 | 383 | pub const RANK_1: Rank = 0; 384 | pub const RANK_2: Rank = 1; 385 | pub const RANK_3: Rank = 2; 386 | pub const RANK_4: Rank = 3; 387 | pub const RANK_5: Rank = 4; 388 | pub const RANK_6: Rank = 5; 389 | pub const RANK_7: Rank = 6; 390 | pub const RANK_8: Rank = 7; 391 | 392 | pub fn relative_rank(c: Color, r: Rank) -> Rank { 393 | r ^ (c.0 * 7) 394 | } 395 | 396 | impl Square { 397 | pub const A1: Square = Square(0); 398 | pub const B1: Square = Square(1); 399 | pub const C1: Square = Square(2); 400 | pub const D1: Square = Square(3); 401 | pub const E1: Square = Square(4); 402 | pub const F1: Square = Square(5); 403 | pub const G1: Square = Square(6); 404 | pub const H1: Square = Square(7); 405 | pub const A2: Square = Square(8); 406 | pub const B2: Square = Square(9); 407 | pub const C2: Square = Square(10); 408 | pub const D2: Square = Square(11); 409 | pub const E2: Square = Square(12); 410 | pub const F2: Square = Square(13); 411 | pub const G2: Square = Square(14); 412 | pub const H2: Square = Square(15); 413 | pub const A3: Square = Square(16); 414 | pub const B3: Square = Square(17); 415 | pub const C3: Square = Square(18); 416 | pub const D3: Square = Square(19); 417 | pub const E3: Square = Square(20); 418 | pub const F3: Square = Square(21); 419 | pub const G3: Square = Square(22); 420 | pub const H3: Square = Square(23); 421 | pub const A4: Square = Square(24); 422 | pub const B4: Square = Square(25); 423 | pub const C4: Square = Square(26); 424 | pub const D4: Square = Square(27); 425 | pub const E4: Square = Square(28); 426 | pub const F4: Square = Square(29); 427 | pub const G4: Square = Square(30); 428 | pub const H4: Square = Square(31); 429 | pub const A5: Square = Square(32); 430 | pub const B5: Square = Square(33); 431 | pub const C5: Square = Square(34); 432 | pub const D5: Square = Square(35); 433 | pub const E5: Square = Square(36); 434 | pub const F5: Square = Square(37); 435 | pub const G5: Square = Square(38); 436 | pub const H5: Square = Square(39); 437 | pub const A6: Square = Square(40); 438 | pub const B6: Square = Square(41); 439 | pub const C6: Square = Square(42); 440 | pub const D6: Square = Square(43); 441 | pub const E6: Square = Square(44); 442 | pub const F6: Square = Square(45); 443 | pub const G6: Square = Square(46); 444 | pub const H6: Square = Square(47); 445 | pub const A7: Square = Square(48); 446 | pub const B7: Square = Square(49); 447 | pub const C7: Square = Square(50); 448 | pub const D7: Square = Square(51); 449 | pub const E7: Square = Square(52); 450 | pub const F7: Square = Square(53); 451 | pub const G7: Square = Square(54); 452 | pub const H7: Square = Square(55); 453 | pub const A8: Square = Square(56); 454 | pub const B8: Square = Square(57); 455 | pub const C8: Square = Square(58); 456 | pub const D8: Square = Square(59); 457 | pub const E8: Square = Square(60); 458 | pub const F8: Square = Square(61); 459 | pub const G8: Square = Square(62); 460 | pub const H8: Square = Square(63); 461 | 462 | pub const NONE: Square = Square(64); 463 | 464 | pub fn file(self) -> File { 465 | self.0 & 7 466 | } 467 | 468 | pub fn rank(self) -> Rank { 469 | self.0 >> 3 470 | } 471 | 472 | pub fn relative(self, c: Color) -> Self { 473 | Square(self.0 ^ (c.0 * 56)) 474 | } 475 | 476 | pub fn relative_rank(self, c: Color) -> Rank { 477 | relative_rank(c, self.rank()) 478 | } 479 | 480 | pub fn is_ok(self) -> bool { 481 | self >= Square::A1 && self <= Square::H8 482 | } 483 | 484 | pub fn make(f: File, r: Rank) -> Square { 485 | Square((r << 3) | f) 486 | } 487 | } 488 | 489 | pub fn relative_square(c: Color, s: Square) -> Square { 490 | s.relative(c) 491 | } 492 | 493 | impl std::ops::Not for Square { 494 | type Output = Self; 495 | fn not(self) -> Self { Square(self.0 ^ Square::A8.0) } 496 | } 497 | 498 | impl std::ops::BitXor for Square { 499 | type Output = Self; 500 | fn bitxor(self, rhs: bool) -> Self { 501 | Square(self.0 ^ if rhs { 0x38 } else { 0 }) 502 | } 503 | } 504 | 505 | impl Iterator for Square { 506 | type Item = Self; 507 | fn next(&mut self) -> Option { 508 | let sq = self.0; 509 | *self = Square(sq + 1); 510 | Some(Square(sq)) 511 | } 512 | } 513 | 514 | #[derive(Clone, Copy)] 515 | pub struct Squares { 516 | pub start: Square, 517 | pub end: Square 518 | } 519 | 520 | impl Iterator for Squares { 521 | type Item = Square; 522 | fn next(&mut self) -> Option { 523 | let s = self.start; 524 | if s != self.end { 525 | self.start += Direction(1); 526 | Some(s) 527 | } else { 528 | None 529 | } 530 | } 531 | } 532 | 533 | pub struct SquareList<'a> { 534 | list: &'a [Square], 535 | idx: usize 536 | } 537 | 538 | impl<'a> SquareList<'a> { 539 | pub fn construct(list: &'a [Square]) -> SquareList<'a> { 540 | SquareList { list: list, idx: 0 } 541 | } 542 | } 543 | 544 | impl<'a> Iterator for SquareList<'a> { 545 | type Item = Square; 546 | fn next(&mut self) -> Option { 547 | let s = self.list[self.idx]; 548 | if s != Square::NONE { 549 | self.idx += 1; 550 | Some(s) 551 | } else { 552 | None 553 | } 554 | } 555 | } 556 | 557 | pub fn opposite_colors(s1: Square, s2: Square) -> bool { 558 | let s = s1.0 ^ s2.0; 559 | (((s >> 3) ^ s) & 1) != 0 560 | } 561 | 562 | #[derive(Clone, Copy, PartialEq, Eq)] 563 | pub struct Direction(pub i32); 564 | 565 | impl std::ops::Neg for Direction { 566 | type Output = Self; 567 | fn neg(self) -> Self { Direction(-self.0) } 568 | } 569 | 570 | pub const NORTH: Direction = Direction( 8); 571 | pub const EAST : Direction = Direction( 1); 572 | pub const SOUTH: Direction = Direction(-8); 573 | pub const WEST : Direction = Direction(-1); 574 | 575 | pub const NORTH_EAST: Direction = Direction( 9); 576 | pub const NORTH_WEST: Direction = Direction( 7); 577 | pub const SOUTH_EAST: Direction = Direction(-7); 578 | pub const SOUTH_WEST: Direction = Direction(-9); 579 | 580 | impl std::ops::Add for Direction { 581 | type Output = Self; 582 | fn add(self, rhs: Self) -> Self { Direction(self.0 + rhs.0) } 583 | } 584 | 585 | impl std::ops::Add for Square { 586 | type Output = Square; 587 | fn add(self, rhs: Direction) -> Self { 588 | Square(u32::wrapping_add(self.0, rhs.0 as u32)) 589 | } 590 | } 591 | 592 | impl std::ops::Sub for Square { 593 | type Output = Square; 594 | fn sub(self, rhs: Direction) -> Self { 595 | Square(u32::wrapping_sub(self.0, rhs.0 as u32)) 596 | } 597 | } 598 | 599 | impl std::ops::AddAssign for Square { 600 | fn add_assign(&mut self, rhs: Direction) { *self = *self + rhs; } 601 | } 602 | 603 | impl std::ops::SubAssign for Square { 604 | fn sub_assign(&mut self, rhs: Direction) { *self = *self - rhs; } 605 | } 606 | 607 | impl std::ops::Mul for i32 { 608 | type Output = Direction; 609 | fn mul(self, rhs: Direction) -> Direction { Direction(self * rhs.0) } 610 | } 611 | 612 | pub fn pawn_push(c: Color) -> Direction { 613 | match c { 614 | WHITE => NORTH, 615 | _ => SOUTH 616 | } 617 | } 618 | 619 | #[derive(Clone, Copy, PartialEq, Eq)] 620 | pub struct MoveType(pub u32); 621 | 622 | pub const NORMAL : MoveType = MoveType(0); 623 | pub const PROMOTION : MoveType = MoveType(1 << 14); 624 | pub const ENPASSANT : MoveType = MoveType(2 << 14); 625 | pub const CASTLING : MoveType = MoveType(3 << 14); 626 | 627 | #[derive(Clone, Copy, PartialEq, Eq)] 628 | pub struct Move(pub u32); 629 | 630 | impl Move { 631 | pub const NONE : Move = Move(0); 632 | pub const NULL : Move = Move(65); 633 | 634 | pub fn from(self) -> Square { 635 | Square((self.0 >> 6) & 0x3f) 636 | } 637 | 638 | pub fn to(self) -> Square { 639 | Square(self.0 & 0x3f) 640 | } 641 | 642 | pub fn from_to(self) -> u32 { 643 | self.0 & 0xfff 644 | } 645 | 646 | pub fn move_type(self) -> MoveType { 647 | MoveType(self.0 & (3 << 14)) 648 | } 649 | 650 | pub fn promotion_type(self) -> PieceType { 651 | PieceType(((self.0 >> 12) & 3) + KNIGHT.0) 652 | } 653 | 654 | pub fn is_ok(self) -> bool { 655 | self.from() != self.to() 656 | } 657 | 658 | pub fn make(from: Square, to: Square) -> Move { 659 | Move((from.0 << 6) + to.0) 660 | } 661 | 662 | pub fn make_prom(from: Square, to: Square, pt: PieceType) -> Move { 663 | Move(PROMOTION.0 + ((pt.0 - KNIGHT.0) << 12) + (from.0 << 6) + to.0) 664 | } 665 | 666 | pub fn make_special(mt: MoveType, from: Square, to: Square) -> Move { 667 | Move(mt.0 + (from.0 << 6) + to.0) 668 | } 669 | } 670 | 671 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 672 | pub struct Value(pub i32); 673 | 674 | impl Value { 675 | pub const ZERO : Value = Value(0); 676 | pub const DRAW : Value = Value(0); 677 | pub const KNOWN_WIN: Value = Value(10000); 678 | pub const MATE : Value = Value(32000); 679 | pub const INFINITE : Value = Value(32001); 680 | pub const NONE : Value = Value(32002); 681 | 682 | pub const MATE_IN_MAX_PLY : Value = 683 | Value( Value::MATE.0 - MAX_MATE_PLY - MAX_PLY); 684 | pub const MATED_IN_MAX_PLY: Value = 685 | Value(-Value::MATE.0 + MAX_MATE_PLY + MAX_PLY); 686 | 687 | pub fn abs(self) -> Value { 688 | Value(self.0.abs()) 689 | } 690 | } 691 | 692 | #[allow(non_upper_case_globals)] 693 | pub const PawnValueMg : Value = Value(171); 694 | #[allow(non_upper_case_globals)] 695 | pub const KnightValueMg: Value = Value(764); 696 | #[allow(non_upper_case_globals)] 697 | pub const BishopValueMg: Value = Value(826); 698 | #[allow(non_upper_case_globals)] 699 | pub const RookValueMg : Value = Value(1282); 700 | #[allow(non_upper_case_globals)] 701 | pub const QueenValueMg : Value = Value(2526); 702 | 703 | #[allow(non_upper_case_globals)] 704 | pub const PawnValueEg : Value = Value(240); 705 | #[allow(non_upper_case_globals)] 706 | pub const KnightValueEg: Value = Value(848); 707 | #[allow(non_upper_case_globals)] 708 | pub const BishopValueEg: Value = Value(891); 709 | #[allow(non_upper_case_globals)] 710 | pub const RookValueEg : Value = Value(1373); 711 | #[allow(non_upper_case_globals)] 712 | pub const QueenValueEg : Value = Value(2646); 713 | 714 | pub const MIDGAME_LIMIT : Value = Value(15258); 715 | pub const ENDGAME_LIMIT : Value = Value(3915); 716 | 717 | const PIECE_VALUE: [[Value; 16]; 2] = [ 718 | [ Value::ZERO, PawnValueMg, KnightValueMg, BishopValueMg, 719 | RookValueMg, QueenValueMg, Value::ZERO, Value::ZERO, 720 | Value::ZERO, PawnValueMg, KnightValueMg, BishopValueMg, 721 | RookValueMg, QueenValueMg, Value::ZERO, Value::ZERO ], 722 | [ Value::ZERO, PawnValueEg, KnightValueEg, BishopValueEg, 723 | RookValueEg, QueenValueEg, Value::ZERO, Value::ZERO, 724 | Value::ZERO, PawnValueEg, KnightValueEg, BishopValueEg, 725 | RookValueEg, QueenValueEg, Value::ZERO, Value::ZERO ] 726 | ]; 727 | 728 | pub fn piece_value(phase: usize, pc: Piece) -> Value { 729 | PIECE_VALUE[phase][pc.0 as usize] 730 | } 731 | 732 | impl std::ops::Neg for Value { 733 | type Output = Self; 734 | fn neg(self) -> Self { Value(-self.0) } 735 | } 736 | 737 | impl std::ops::Add for Value { 738 | type Output = Self; 739 | fn add(self, rhs: Self) -> Self { Value(self.0 + rhs.0) } 740 | } 741 | 742 | impl std::ops::Add for Value { 743 | type Output = Self; 744 | fn add(self, rhs: i32) -> Self { self + Value(rhs) } 745 | } 746 | 747 | impl std::ops::Sub for Value { 748 | type Output = Self; 749 | fn sub(self, rhs: i32) -> Self { self - Value(rhs) } 750 | } 751 | 752 | impl std::ops::Sub for Value { 753 | type Output = Self; 754 | fn sub(self, rhs: Self) -> Self { Value(self.0 - rhs.0) } 755 | } 756 | 757 | impl std::ops::AddAssign for Value { 758 | fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } 759 | } 760 | 761 | impl std::ops::AddAssign for Value { 762 | fn add_assign(&mut self, rhs: i32) { *self = *self + rhs; } 763 | } 764 | 765 | impl std::ops::SubAssign for Value { 766 | fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } 767 | } 768 | 769 | impl std::ops::SubAssign for Value { 770 | fn sub_assign(&mut self, rhs: i32) { *self = *self - rhs; } 771 | } 772 | 773 | impl std::ops::Mul for Value { 774 | type Output = Self; 775 | fn mul(self, rhs: i32) -> Self { Value(self.0 * rhs) } 776 | } 777 | 778 | impl std::ops::MulAssign for Value { 779 | fn mul_assign(&mut self, rhs: i32) { *self = *self * rhs; } 780 | } 781 | 782 | impl std::ops::Mul for i32 { 783 | type Output = Value; 784 | fn mul(self, rhs: Value) -> Value { Value(self * rhs.0) } 785 | } 786 | 787 | impl std::ops::Div for Value { 788 | type Output = Self; 789 | fn div(self, rhs: i32) -> Self { Value(self.0 / rhs) } 790 | } 791 | 792 | impl std::ops::DivAssign for Value { 793 | fn div_assign(&mut self, rhs: i32) { *self = *self / rhs; } 794 | } 795 | 796 | impl std::ops::Div for Value { 797 | type Output = i32; 798 | fn div(self, rhs: Self) -> i32 { self.0 / rhs.0 } 799 | } 800 | 801 | pub fn mate_in(ply: i32) -> Value { 802 | Value::MATE - ply 803 | } 804 | 805 | pub fn mated_in(ply: i32) -> Value { 806 | -Value::MATE + ply 807 | } 808 | 809 | #[derive(Clone, Copy)] 810 | pub struct Score(pub i32); 811 | 812 | impl Score { 813 | pub const ZERO: Score = Score(0); 814 | 815 | pub fn eg(self) -> Value { 816 | Value((((self.0 + 0x8000) >> 16) as i16) as i32) 817 | } 818 | 819 | pub fn mg(self) -> Value { 820 | Value((self.0 as i16) as i32) 821 | } 822 | 823 | pub fn make(mg: i32, eg: i32) -> Self { 824 | Score((eg << 16) + mg) 825 | } 826 | } 827 | 828 | impl std::ops::Add for Score { 829 | type Output = Self; 830 | fn add(self, rhs: Self) -> Self { Score(self.0 + rhs.0) } 831 | } 832 | 833 | impl std::ops::AddAssign for Score { 834 | fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } 835 | } 836 | 837 | impl std::ops::Sub for Score { 838 | type Output = Self; 839 | fn sub(self, rhs: Self) -> Self { Score(self.0 - rhs.0) } 840 | } 841 | 842 | impl std::ops::SubAssign for Score { 843 | fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } 844 | } 845 | 846 | impl std::ops::Neg for Score { 847 | type Output = Self; 848 | fn neg(self) -> Self { Score(-self.0) } 849 | } 850 | 851 | impl std::ops::Mul for Score { 852 | type Output = Self; 853 | fn mul(self, rhs: i32) -> Self { 854 | Score::make(rhs * self.mg().0, rhs * self.eg().0) 855 | } 856 | } 857 | 858 | pub struct True {} 859 | pub struct False {} 860 | 861 | pub trait Bool { 862 | const BOOL: bool; 863 | } 864 | 865 | impl Bool for True { 866 | const BOOL: bool = true; 867 | } 868 | 869 | impl Bool for False { 870 | const BOOL: bool = false; 871 | } 872 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------