1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use cache::Cache;
use gen::legal_moves;
use mv_list::{MoveCounter, MoveVec};
use num_cpus;
use position::Position;
use std::sync::mpsc::channel;
use threadpool::ThreadPool;

pub fn perft(
  position: &mut Position,
  depth: usize,
  multi_threading_enabled: bool,
  cache_bytes_per_thread: usize,
) -> u64 {
  if depth == 0 {
    return 1;
  }

  if depth <= 3 {
    return perft_inner(position, depth);
  }

  if !multi_threading_enabled {
    if cache_bytes_per_thread > 0 {
      let mut cache = Cache::new(cache_bytes_per_thread).unwrap();
      return perft_with_cache_inner(position, depth, &mut cache);
    } else {
      return perft_inner(position, depth);
    }
  }

  let pool = ThreadPool::new(num_cpus::get());
  let (tx, rx) = channel();

  let mut moves = MoveVec::new();
  legal_moves(&position, &mut moves);
  let moves_len = moves.len();

  for &mv in moves.iter() {
    let tx = tx.clone();
    let mut position_local = position.clone();

    pool.execute(move || {
      position_local.make(mv);

      let count: u64;
      if cache_bytes_per_thread > 0 {
        let mut cache = Cache::new(cache_bytes_per_thread).unwrap();
        count = perft_with_cache_inner(&mut position_local, depth - 1, &mut cache);
      } else {
        count = perft_inner(&mut position_local, depth - 1);
      }

      tx.send(count).unwrap();
    });
  }

  return rx.iter().take(moves_len).sum();
}

pub fn perft_inner(position: &mut Position, depth: usize) -> u64 {
  if depth == 1 {
    let mut counter = MoveCounter::new();
    legal_moves(&position, &mut counter);
    return counter.moves;
  }

  let mut moves = MoveVec::new();
  legal_moves(&position, &mut moves);

  let state = position.state().clone();
  let key = position.hash_key();
  let mut count = 0;
  for &mv in moves.iter() {
    let capture = position.make(mv);

    count += perft_inner(position, depth - 1);

    position.unmake(mv, capture, &state, key);
  }

  count
}

fn perft_with_cache_inner(position: &mut Position, depth: usize, cache: &mut Cache) -> u64 {
  let key = position.hash_key();

  let ret = cache.probe(key, depth);
  if ret.is_some() {
    return ret.unwrap();
  }

  let mut count = 0;
  if depth == 1 {
    let mut counter = MoveCounter::new();
    legal_moves(&position, &mut counter);
    count = counter.moves as u64;
  } else {
    let mut moves = MoveVec::new();
    legal_moves(&position, &mut moves);

    let state = position.state().clone();
    let key = position.hash_key();
    for &mv in moves.iter() {
      let capture = position.make(mv);

      count += perft_with_cache_inner(position, depth - 1, cache);

      position.unmake(mv, capture, &state, key);
    }
  }

  cache.save(key, count, depth as i16);

  count
}

pub fn perft_detailed(
  position: &mut Position,
  depth: usize,
  multi_threading_enabled: bool,
) -> MoveCounter {
  if depth == 0 {
    return MoveCounter::new();
  }

  if depth <= 3 {
    return perft_detailed_inner(position, depth);
  }

  if !multi_threading_enabled {
    return perft_detailed_inner(position, depth);
  }

  let pool = ThreadPool::new(num_cpus::get());
  let (tx, rx) = channel();

  let mut moves = MoveVec::new();
  legal_moves(&position, &mut moves);
  let moves_len = moves.len();

  for &mv in moves.iter() {
    let tx = tx.clone();
    let mut position_local = position.clone();

    pool.execute(move || {
      position_local.make(mv);

      let counter: MoveCounter;
      counter = perft_detailed_inner(&mut position_local, depth - 1);

      tx.send(counter).unwrap();
    });
  }

  let mut counter = MoveCounter::new();
  for c in rx.iter().take(moves_len) {
    counter += c;
  }

  return counter
}

pub fn perft_detailed_inner(position: &mut Position, depth: usize) -> MoveCounter {
  let mut counter = MoveCounter::new();

  if depth == 1 {
    legal_moves(&position, &mut counter);
    return counter;
  }

  let mut moves = MoveVec::new();
  legal_moves(&position, &mut moves);

  let state = position.state().clone();
  let key = position.hash_key();
  for &mv in moves.iter() {
    let capture = position.make(mv);

    counter += perft_detailed_inner(position, depth - 1);

    position.unmake(mv, capture, &state, key);
  }

  counter
}

#[cfg(test)]
mod test {
  use super::*;
  use position::{Position, STARTING_POSITION_FEN};
  use test;
  use castle::*;
  use mv::Move;
  use square::*;

  #[test]
  fn perft_test_3() {
    let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap();

    assert_eq!(perft(&mut position, 3, false, 0), 8902);
  }

  #[test]
  fn perft_test_4() {
    let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap();

    assert_eq!(perft(&mut position, 4, false, 0), 197281);
  }

  #[test]
  fn perft_with_cache_test_3() {
    let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap();

    assert_eq!(perft(&mut position, 3, false, 1024 * 1024), 8902);
  }

  #[test]
  fn perft_with_cache_test_4() {
    let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap();

    assert_eq!(perft(&mut position, 4, false, 1024 * 1024), 197281);
  }

  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_2
  fn perft_detailed_position_2_depth_3() {
    let mut position = Position::from_fen("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -").unwrap();
    let counter = perft_detailed(&mut position, 3, true);

    assert_eq!(counter.promotions, 0);
    assert_eq!(counter.castles, 3162);
    assert_eq!(counter.ep_captures, 45);
    assert_eq!(counter.captures, 17102);
    assert_eq!(counter.moves, 97862);
  }

  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_2
  fn perft_detailed_position_2_depth_4() {
    let mut position = Position::from_fen("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -").unwrap();
    let counter = perft_detailed(&mut position, 4, true);

    assert_eq!(counter.promotions, 15172);
    assert_eq!(counter.castles, 128013);
    assert_eq!(counter.ep_captures, 1929);
    assert_eq!(counter.captures, 757163);
    assert_eq!(counter.moves, 4085603);
  }


  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_3
  fn perft_position_3_depth_5() {
    let mut position = Position::from_fen("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -").unwrap();

    assert_eq!(perft(&mut position, 5, true, 1024 * 1024), 674624);
  }

  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_4
  fn perft_position_4_depth_4() {
    let mut position = Position::from_fen("r2q1rk1/pP1p2pp/Q4n2/bbp1p3/Np6/1B3NBn/pPPP1PPP/R3K2R b KQ - 0 1").unwrap();

    assert_eq!(perft(&mut position, 4, true, 1024 * 1024), 422333);
  }

  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_5
  fn perft_position_5_depth_3() {
    let mut position = Position::from_fen("rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8").unwrap();

    assert_eq!(perft(&mut position, 3, true, 1024 * 1024), 62379);
  }

  #[test]
  // https://www.chessprogramming.org/Perft_Results#Position_5
  fn perft_debug_1() {
    let mut position = Position::from_fen("r3k2r/p1pp1pb1/bn2pqp1/3PN3/1p2P3/2N5/PPPBBPpP/R4K1R w kq - 0 1").unwrap();

    assert_eq!(perft(&mut position, 1, false, 0), 3);
  }

  #[bench]
  fn perft_bench_starting_position(b: &mut test::Bencher) {
    let mut position = Position::from_fen(STARTING_POSITION_FEN).unwrap();

    b.iter(|| -> u64 { perft(&mut position, 2, false, 0) });
  }
}