rshogi-core 0.1.6

A high-performance shogi engine core library with NNUE evaluation
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! BonaPiece - 駒の種類と位置を一意に表現するインデックス
//!
//! YaneuraOu の NNUE 実装で用いられる BonaPiece に準拠した定義。
//! - `PieceType` / 升 / 手番(視点)により一意なインデックスに写像する。
//! - 玉は特徴量に含めないため、BonaPiece としては常に `ZERO` を返す。
//!
//! ## YaneuraOu BonaPiece定義 (DISTINGUISH_GOLDS無効時)
//!
//! ### 手駒 (1〜89)
//! - f_hand_pawn = 1, e_hand_pawn = 20 (各18枚分)
//! - f_hand_lance = 39, e_hand_lance = 44 (各4枚分)
//! - f_hand_knight = 49, e_hand_knight = 54 (各4枚分)
//! - f_hand_silver = 59, e_hand_silver = 64 (各4枚分)
//! - f_hand_gold = 69, e_hand_gold = 74 (各4枚分)
//! - f_hand_bishop = 79, e_hand_bishop = 82 (各2枚分)
//! - f_hand_rook = 85, e_hand_rook = 88 (各2枚分)
//! - fe_hand_end = 90
//!
//! ### 盤上駒 (90〜1547)
//! - f_pawn = 90, e_pawn = 171
//! - f_lance = 252, e_lance = 333
//! - f_knight = 414, e_knight = 495
//! - f_silver = 576, e_silver = 657
//! - f_gold = 738, e_gold = 819
//! - f_bishop = 900, e_bishop = 981
//! - f_horse = 1062, e_horse = 1143
//! - f_rook = 1224, e_rook = 1305
//! - f_dragon = 1386, e_dragon = 1467
//! - fe_end = 1548

use crate::types::{Color, Piece, PieceType, Square};

// =============================================================================
// YaneuraOu形式の手駒BonaPiece定数
// =============================================================================

/// 手駒領域の終端
pub const FE_HAND_END: usize = 90;

// 先手の手駒ベースオフセット
pub const F_HAND_PAWN: u16 = 1;
pub const F_HAND_LANCE: u16 = 39;
pub const F_HAND_KNIGHT: u16 = 49;
pub const F_HAND_SILVER: u16 = 59;
pub const F_HAND_GOLD: u16 = 69;
pub const F_HAND_BISHOP: u16 = 79;
pub const F_HAND_ROOK: u16 = 85;

// 後手の手駒ベースオフセット
pub const E_HAND_PAWN: u16 = 20;
pub const E_HAND_LANCE: u16 = 44;
pub const E_HAND_KNIGHT: u16 = 54;
pub const E_HAND_SILVER: u16 = 64;
pub const E_HAND_GOLD: u16 = 74;
pub const E_HAND_BISHOP: u16 = 82;
pub const E_HAND_ROOK: u16 = 88;

// =============================================================================
// YaneuraOu形式の盤上駒BonaPiece定数
// =============================================================================

pub const F_PAWN: u16 = 90;
pub const E_PAWN: u16 = 171;
pub const F_LANCE: u16 = 252;
pub const E_LANCE: u16 = 333;
pub const F_KNIGHT: u16 = 414;
pub const E_KNIGHT: u16 = 495;
pub const F_SILVER: u16 = 576;
pub const E_SILVER: u16 = 657;
pub const F_GOLD: u16 = 738;
pub const E_GOLD: u16 = 819;
pub const F_BISHOP: u16 = 900;
pub const E_BISHOP: u16 = 981;
pub const F_HORSE: u16 = 1062;
pub const E_HORSE: u16 = 1143;
pub const F_ROOK: u16 = 1224;
pub const E_ROOK: u16 = 1305;
pub const F_DRAGON: u16 = 1386;
pub const E_DRAGON: u16 = 1467;

/// 駒種・is_friend に対する base offset テーブル(盤上駒用)
/// `[piece_type as usize][is_friend as usize]` -> base offset
/// is_friend: 0=enemy, 1=friend
///
/// PieceType は 1 始まり(Pawn=1, ..., Dragon=14)なので index 0 はダミー。
pub const PIECE_BASE: [[u16; 2]; 15] = [
    // index 0: 未使用(ダミー)
    [0, 0],
    // PieceType::Pawn = 1
    [E_PAWN, F_PAWN], // [enemy, friend]
    // PieceType::Lance = 2
    [E_LANCE, F_LANCE],
    // PieceType::Knight = 3
    [E_KNIGHT, F_KNIGHT],
    // PieceType::Silver = 4
    [E_SILVER, F_SILVER],
    // PieceType::Bishop = 5
    [E_BISHOP, F_BISHOP],
    // PieceType::Rook = 6
    [E_ROOK, F_ROOK],
    // PieceType::Gold = 7 (成駒と同じ)
    [E_GOLD, F_GOLD],
    // PieceType::King = 8 (使用しない、0埋め)
    [0, 0],
    // PieceType::ProPawn = 9 (Gold と同じ)
    [E_GOLD, F_GOLD],
    // PieceType::ProLance = 10 (Gold と同じ)
    [E_GOLD, F_GOLD],
    // PieceType::ProKnight = 11 (Gold と同じ)
    [E_GOLD, F_GOLD],
    // PieceType::ProSilver = 12 (Gold と同じ)
    [E_GOLD, F_GOLD],
    // PieceType::Horse = 13
    [E_HORSE, F_HORSE],
    // PieceType::Dragon = 14
    [E_DRAGON, F_DRAGON],
];

// コンパイル時の静的検証: PIECE_BASE テーブルの整合性チェック
// 手動定義のミスを防ぐため、各駒種のbaseオフセットが正しいことを検証
const _: () = {
    use crate::types::PieceType;

    // 生駒のチェック
    assert!(PIECE_BASE[PieceType::Pawn as usize][0] == E_PAWN);
    assert!(PIECE_BASE[PieceType::Pawn as usize][1] == F_PAWN);
    assert!(PIECE_BASE[PieceType::Lance as usize][0] == E_LANCE);
    assert!(PIECE_BASE[PieceType::Lance as usize][1] == F_LANCE);
    assert!(PIECE_BASE[PieceType::Knight as usize][0] == E_KNIGHT);
    assert!(PIECE_BASE[PieceType::Knight as usize][1] == F_KNIGHT);
    assert!(PIECE_BASE[PieceType::Silver as usize][0] == E_SILVER);
    assert!(PIECE_BASE[PieceType::Silver as usize][1] == F_SILVER);
    assert!(PIECE_BASE[PieceType::Bishop as usize][0] == E_BISHOP);
    assert!(PIECE_BASE[PieceType::Bishop as usize][1] == F_BISHOP);
    assert!(PIECE_BASE[PieceType::Rook as usize][0] == E_ROOK);
    assert!(PIECE_BASE[PieceType::Rook as usize][1] == F_ROOK);
    assert!(PIECE_BASE[PieceType::Gold as usize][0] == E_GOLD);
    assert!(PIECE_BASE[PieceType::Gold as usize][1] == F_GOLD);

    // 成駒のチェック(すべてGOLDと同じ扱い)
    assert!(PIECE_BASE[PieceType::ProPawn as usize][0] == E_GOLD);
    assert!(PIECE_BASE[PieceType::ProPawn as usize][1] == F_GOLD);
    assert!(PIECE_BASE[PieceType::ProLance as usize][0] == E_GOLD);
    assert!(PIECE_BASE[PieceType::ProLance as usize][1] == F_GOLD);
    assert!(PIECE_BASE[PieceType::ProKnight as usize][0] == E_GOLD);
    assert!(PIECE_BASE[PieceType::ProKnight as usize][1] == F_GOLD);
    assert!(PIECE_BASE[PieceType::ProSilver as usize][0] == E_GOLD);
    assert!(PIECE_BASE[PieceType::ProSilver as usize][1] == F_GOLD);

    // 馬・龍のチェック
    assert!(PIECE_BASE[PieceType::Horse as usize][0] == E_HORSE);
    assert!(PIECE_BASE[PieceType::Horse as usize][1] == F_HORSE);
    assert!(PIECE_BASE[PieceType::Dragon as usize][0] == E_DRAGON);
    assert!(PIECE_BASE[PieceType::Dragon as usize][1] == F_DRAGON);

    // Kingは使用しない(0埋め)
    assert!(PIECE_BASE[PieceType::King as usize][0] == 0);
    assert!(PIECE_BASE[PieceType::King as usize][1] == 0);
};

/// base offset から直接 BonaPiece を生成(高速パス用)
///
/// # Safety
/// - `sq_index` は 0..=80 の範囲内であること
/// - `base` は PIECE_BASE テーブルから取得した有効な値であること
#[inline]
pub fn bona_piece_from_base(sq_index: usize, base: u16) -> BonaPiece {
    debug_assert!(sq_index <= 80, "sq_index out of range: {sq_index}");
    debug_assert!((F_PAWN..=E_DRAGON).contains(&base), "base out of range: {base}");
    BonaPiece::new(base + sq_index as u16)
}

/// fe_end: BonaPieceの最大値
///
/// YaneuraOu の HalfKP 用定義に基づく。
/// fe_end = e_dragon + 81 = 1467 + 81 = 1548
pub const FE_END: usize = 1548;

/// BonaPieceの定義
/// 駒の種類と位置を一意に表現するインデックス
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(transparent)]
pub struct BonaPiece(pub u16);

impl BonaPiece {
    /// ゼロ(無効値)
    pub const ZERO: BonaPiece = BonaPiece(0);

    /// 新しいBonaPieceを作成
    #[inline]
    pub const fn new(value: u16) -> Self {
        Self(value)
    }

    /// 値を取得
    #[inline]
    pub const fn value(self) -> u16 {
        self.0
    }

    /// 盤上の駒からBonaPieceを計算
    ///
    /// YaneuraOuの定義に従う(evaluate.h参照)
    /// 視点(perspective)に応じて駒の位置とインデックスを変換
    pub fn from_piece_square(piece: Piece, sq: Square, perspective: Color) -> BonaPiece {
        if piece.is_none() {
            return BonaPiece::ZERO;
        }

        let pt = piece.piece_type();
        let pc_color = piece.color();

        // 視点に応じてマスを変換
        let sq_index = if perspective == Color::Black {
            sq.index()
        } else {
            sq.inverse().index()
        };

        // 駒の色が視点と同じかどうか
        let is_friend = pc_color == perspective;

        // 基本オフセット(YaneuraOuの定義に準拠)
        // 盤上駒は fe_hand_end (90) から始まる
        let base = match pt {
            PieceType::Pawn => {
                if is_friend {
                    F_PAWN
                } else {
                    E_PAWN
                }
            }
            PieceType::Lance => {
                if is_friend {
                    F_LANCE
                } else {
                    E_LANCE
                }
            }
            PieceType::Knight => {
                if is_friend {
                    F_KNIGHT
                } else {
                    E_KNIGHT
                }
            }
            PieceType::Silver => {
                if is_friend {
                    F_SILVER
                } else {
                    E_SILVER
                }
            }
            PieceType::Gold
            | PieceType::ProPawn
            | PieceType::ProLance
            | PieceType::ProKnight
            | PieceType::ProSilver => {
                // 金と成駒(金の動き)は同じカテゴリ
                if is_friend {
                    F_GOLD
                } else {
                    E_GOLD
                }
            }
            PieceType::Bishop => {
                if is_friend {
                    F_BISHOP
                } else {
                    E_BISHOP
                }
            }
            PieceType::Rook => {
                if is_friend {
                    F_ROOK
                } else {
                    E_ROOK
                }
            }
            PieceType::Horse => {
                if is_friend {
                    F_HORSE
                } else {
                    E_HORSE
                }
            }
            PieceType::Dragon => {
                if is_friend {
                    F_DRAGON
                } else {
                    E_DRAGON
                }
            }
            PieceType::King => {
                // 玉は特徴量に含めない
                return BonaPiece::ZERO;
            }
        };

        BonaPiece::new(base + sq_index as u16)
    }

    /// 手駒からBonaPieceを計算
    ///
    /// YaneuraOuの手駒BonaPiece定義に従う。
    /// 手駒は (駒種, 枚数) でインデックスが決まる。
    /// 枚数が増えると新しいBonaPieceになる(0→1枚でbase, 1→2枚でbase+1, ...)
    ///
    /// 注意: countは「現在の枚数」であり、「追加する枚数」ではない。
    /// count=1 のとき base が返る(1枚目のBonaPiece)。
    pub fn from_hand_piece(
        perspective: Color,
        owner: Color,
        pt: PieceType,
        count: u8,
    ) -> BonaPiece {
        if count == 0 {
            return BonaPiece::ZERO;
        }

        let is_friend = owner == perspective;

        // YaneuraOu形式の手駒オフセット(1から始まる)
        // 手駒は盤上駒より前に配置されている
        let base = match pt {
            PieceType::Pawn => {
                if is_friend {
                    F_HAND_PAWN
                } else {
                    E_HAND_PAWN
                }
            }
            PieceType::Lance => {
                if is_friend {
                    F_HAND_LANCE
                } else {
                    E_HAND_LANCE
                }
            }
            PieceType::Knight => {
                if is_friend {
                    F_HAND_KNIGHT
                } else {
                    E_HAND_KNIGHT
                }
            }
            PieceType::Silver => {
                if is_friend {
                    F_HAND_SILVER
                } else {
                    E_HAND_SILVER
                }
            }
            PieceType::Gold => {
                if is_friend {
                    F_HAND_GOLD
                } else {
                    E_HAND_GOLD
                }
            }
            PieceType::Bishop => {
                if is_friend {
                    F_HAND_BISHOP
                } else {
                    E_HAND_BISHOP
                }
            }
            PieceType::Rook => {
                if is_friend {
                    F_HAND_ROOK
                } else {
                    E_HAND_ROOK
                }
            }
            _ => return BonaPiece::ZERO,
        };

        // countに応じてオフセット
        // count=1 のとき base, count=2 のとき base+1, ...
        let bp = BonaPiece::new(base + count as u16 - 1);

        // 手駒のBonaPieceは必ずFE_HAND_END未満
        debug_assert!(
            (bp.0 as usize) < FE_HAND_END,
            "Hand piece BonaPiece {} exceeds FE_HAND_END {}",
            bp.0,
            FE_HAND_END
        );

        bp
    }
}

/// HalfKP特徴量のインデックスを計算
#[inline]
pub fn halfkp_index(king_sq: Square, bona_piece: BonaPiece) -> usize {
    king_sq.index() * FE_END + bona_piece.0 as usize
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{File, Rank};

    #[test]
    fn test_bona_piece_zero() {
        assert_eq!(BonaPiece::ZERO.value(), 0);
    }

    #[test]
    fn test_bona_piece_from_piece_square() {
        let sq = Square::new(File::File7, Rank::Rank7);
        let piece = Piece::new(Color::Black, PieceType::Pawn);

        let bp = BonaPiece::from_piece_square(piece, sq, Color::Black);
        assert_ne!(bp, BonaPiece::ZERO);
    }

    #[test]
    fn test_bona_piece_king_returns_zero() {
        let sq = Square::new(File::File5, Rank::Rank9);
        let piece = Piece::new(Color::Black, PieceType::King);

        let bp = BonaPiece::from_piece_square(piece, sq, Color::Black);
        assert_eq!(bp, BonaPiece::ZERO);
    }

    #[test]
    fn test_halfkp_index() {
        let king_sq = Square::new(File::File5, Rank::Rank9);
        let bp = BonaPiece::new(100);

        let index = halfkp_index(king_sq, bp);
        assert_eq!(index, king_sq.index() * FE_END + 100);
    }

    #[test]
    fn test_piece_base_table_consistency() {
        // 全駒種について、PIECE_BASEテーブルとfrom_piece_square()の結果が一致することを確認
        let all_piece_types = [
            PieceType::Pawn,
            PieceType::Lance,
            PieceType::Knight,
            PieceType::Silver,
            PieceType::Gold,
            PieceType::Bishop,
            PieceType::Rook,
            PieceType::ProPawn,
            PieceType::ProLance,
            PieceType::ProKnight,
            PieceType::ProSilver,
            PieceType::Horse,
            PieceType::Dragon,
        ];

        let sq = Square::from_u8(0).unwrap();
        let perspective = Color::Black;

        for pt in all_piece_types {
            for &color in &[Color::Black, Color::White] {
                let is_friend = color == perspective;
                let piece = Piece::new(color, pt);

                // from_piece_square() の結果
                let bp_old = BonaPiece::from_piece_square(piece, sq, perspective);

                // PIECE_BASE テーブルからの結果
                let base = PIECE_BASE[pt as usize][is_friend as usize];
                let bp_new = bona_piece_from_base(0, base);

                assert_eq!(
                    bp_old, bp_new,
                    "Mismatch for {:?}, color={:?}, is_friend={}",
                    pt, color, is_friend
                );
            }
        }
    }
}