gigachess 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +142 -54
  2. package/dist/attacks.d.ts +18 -7
  3. package/dist/attacks.d.ts.map +1 -1
  4. package/dist/attacks.js +197 -89
  5. package/dist/bishopSplit32Blob.d.ts +2 -0
  6. package/dist/bishopSplit32Blob.d.ts.map +1 -0
  7. package/dist/bishopSplit32Blob.js +2 -0
  8. package/dist/castling.d.ts +2 -0
  9. package/dist/castling.d.ts.map +1 -1
  10. package/dist/castling.js +27 -12
  11. package/dist/chess960.d.ts +2 -9
  12. package/dist/chess960.d.ts.map +1 -1
  13. package/dist/chess960.js +2 -18
  14. package/dist/chessjs.d.ts +1 -1
  15. package/dist/chessjs.d.ts.map +1 -1
  16. package/dist/chessjs.js +1 -1
  17. package/dist/chessops/board.d.ts +1 -1
  18. package/dist/chessops/board.d.ts.map +1 -1
  19. package/dist/chessops/board.js +1 -1
  20. package/dist/chessops/chess.d.ts +6 -10
  21. package/dist/chessops/chess.d.ts.map +1 -1
  22. package/dist/chessops/chess.js +73 -97
  23. package/dist/chessops/convert.d.ts +1 -1
  24. package/dist/chessops/convert.d.ts.map +1 -1
  25. package/dist/chessops/convert.js +1 -1
  26. package/dist/chessops/debug.d.ts.map +1 -1
  27. package/dist/chessops/debug.js +7 -0
  28. package/dist/chessops/fen.d.ts.map +1 -1
  29. package/dist/chessops/fen.js +13 -2
  30. package/dist/chessops/fenInternal.d.ts +1 -1
  31. package/dist/chessops/fenInternal.d.ts.map +1 -1
  32. package/dist/chessops/fenInternal.js +1 -1
  33. package/dist/chessops/nativeBridge.d.ts +14 -0
  34. package/dist/chessops/nativeBridge.d.ts.map +1 -0
  35. package/dist/chessops/nativeBridge.js +87 -0
  36. package/dist/chessops/san.d.ts.map +1 -1
  37. package/dist/chessops/san.js +12 -10
  38. package/dist/chesstree.d.ts.map +1 -1
  39. package/dist/chesstree.js +23 -62
  40. package/dist/core.d.ts +6 -8
  41. package/dist/core.d.ts.map +1 -1
  42. package/dist/core.js +5 -10
  43. package/dist/fast/bishopSplit32Blob-NOHWZEWR.js +1 -0
  44. package/dist/fast/index.js +1 -0
  45. package/dist/fast/rookSplit32Blob-C3ANUNTJ.js +1 -0
  46. package/dist/fast/zobristBlob-HIMMLZLJ.js +1 -0
  47. package/dist/fast.d.ts +2 -0
  48. package/dist/fast.d.ts.map +1 -0
  49. package/dist/fast.js +2 -0
  50. package/dist/index.d.ts +1 -14
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +2 -19
  53. package/dist/native96.d.ts +16 -0
  54. package/dist/native96.d.ts.map +1 -0
  55. package/dist/native96.js +6 -0
  56. package/dist/nativeBoard96.d.ts +118 -0
  57. package/dist/nativeBoard96.d.ts.map +1 -0
  58. package/dist/nativeBoard96.js +1077 -0
  59. package/dist/nativeChess.d.ts +97 -0
  60. package/dist/nativeChess.d.ts.map +1 -0
  61. package/dist/nativeChess.js +201 -0
  62. package/dist/nativeMovegen96.d.ts +2 -0
  63. package/dist/nativeMovegen96.d.ts.map +1 -0
  64. package/dist/nativeMovegen96.js +282 -0
  65. package/dist/nativePublicTypes.d.ts +3 -0
  66. package/dist/nativePublicTypes.d.ts.map +1 -0
  67. package/dist/nativePublicTypes.js +1 -0
  68. package/dist/perftCompact.d.ts +10 -0
  69. package/dist/perftCompact.d.ts.map +1 -0
  70. package/dist/perftCompact.js +420 -0
  71. package/dist/pgn.d.ts +2 -3
  72. package/dist/pgn.d.ts.map +1 -1
  73. package/dist/pgn.js +2 -5
  74. package/dist/rookSplit32Blob.d.ts +2 -0
  75. package/dist/rookSplit32Blob.d.ts.map +1 -0
  76. package/dist/rookSplit32Blob.js +2 -0
  77. package/dist/setupBoard.d.ts +54 -0
  78. package/dist/setupBoard.d.ts.map +1 -0
  79. package/dist/setupBoard.js +249 -0
  80. package/dist/{fen.d.ts → setupFen.d.ts} +1 -1
  81. package/dist/setupFen.d.ts.map +1 -0
  82. package/dist/{fen.js → setupFen.js} +140 -125
  83. package/dist/squareSet.d.ts +2 -0
  84. package/dist/squareSet.d.ts.map +1 -1
  85. package/dist/squareSet.js +6 -1
  86. package/dist/types.d.ts +1 -1
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/zobrist.d.ts +2 -2
  89. package/dist/zobrist.d.ts.map +1 -1
  90. package/dist/zobrist.js +17 -15
  91. package/package.json +18 -6
  92. package/dist/bishopMagicBlob.d.ts +0 -2
  93. package/dist/bishopMagicBlob.d.ts.map +0 -1
  94. package/dist/bishopMagicBlob.js +0 -11
  95. package/dist/board.d.ts +0 -216
  96. package/dist/board.d.ts.map +0 -1
  97. package/dist/board.js +0 -1088
  98. package/dist/chess.d.ts +0 -252
  99. package/dist/chess.d.ts.map +0 -1
  100. package/dist/chess.js +0 -1930
  101. package/dist/fen.d.ts.map +0 -1
  102. package/dist/rookMagicBlob.d.ts +0 -2
  103. package/dist/rookMagicBlob.d.ts.map +0 -1
  104. package/dist/rookMagicBlob.js +0 -11
  105. package/dist/san.d.ts +0 -38
  106. package/dist/san.d.ts.map +0 -1
  107. package/dist/san.js +0 -549
@@ -0,0 +1,1077 @@
1
+ // MIT GigaChess. Direct full-state Board96 candidate; Rust v0.2.0 wire order.
2
+ // Direct native FEN, moves, legal generation and notation; no legacy Board
3
+ // materialization. Shared helpers operate on primitive split32 bitboards.
4
+ import * as a from "./attacks.js";
5
+ import * as z from "./zobrist.js";
6
+ import { popcountParts } from "./squareSet.js";
7
+ import { CASTLE_PATH_LO, CASTLE_PATH_HI } from "./castling.js";
8
+ import { nativeMovesInto } from "./nativeMovegen96.js";
9
+ import { compactPerft96 } from "./perftCompact.js";
10
+ export const BOARD96_SIZE = 96;
11
+ export const BOARD96_VERSION = 1;
12
+ export const NativeColor = { Black: 0, White: 1 };
13
+ const P = 0, N = 2, B = 4, R = 6, Q = 8, K = 10, O = 12, H = 20, C = 22;
14
+ const rightsClear = new Uint8Array(64).fill(15);
15
+ rightsClear[0] = 13;
16
+ rightsClear[4] = 12;
17
+ rightsClear[7] = 14;
18
+ rightsClear[56] = 7;
19
+ rightsClear[60] = 3;
20
+ rightsClear[63] = 11;
21
+ const lo = Int32Array.from({ length: 64 }, (_, s) => s < 32 ? 1 << s : 0);
22
+ const hi = Int32Array.from({ length: 64 }, (_, s) => s >= 32 ? 1 << (s - 32) : 0);
23
+ const alg = (s) => String.fromCharCode(97 + (s & 7), 49 + (s >>> 3));
24
+ const nativeLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
25
+ function byte(w, i) { return (w[i >>> 2] >>> ((i & 3) * 8)) & 255; }
26
+ function setByte(w, i, n) { const j = i >>> 2, shift = (i & 3) * 8; w[j] = (w[j] & ~(255 << shift)) | (n << shift); }
27
+ const startWords = Uint32Array.of(0x0000ff00, 0x00ff0000, 0x42, 0x42000000, 0x24, 0x24000000, 0x81, 0x81000000, 8, 0x08000000, 16, 0x10000000, 0, 0xffff0000, 0xffff, 0, 0x0007043c, 0x0f01383f, 255, 1, 0x1691fc9c, 0x463b9618, 0, 0);
28
+ export const INITIAL_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
29
+ const minClock = (n) => Math.min(65535, n);
30
+ const legacyColor = (c) => (1 - c);
31
+ const hit = (bb, s) => !!((bb.lo & lo[s]) | (bb.hi & hi[s]));
32
+ function roleAt(w, s) {
33
+ const h = s >>> 5, b = 1 << (s & 31);
34
+ if (!((w[O + h] | w[O + 2 + h]) & b))
35
+ return -1;
36
+ return w[P + h] & b ? 0 : w[N + h] & b ? 1 : w[B + h] & b ? 2 : w[R + h] & b ? 3 : w[Q + h] & b ? 4 : 5;
37
+ }
38
+ function clear(w, i, s) { w[i] &= ~lo[s]; w[i + 1] &= ~hi[s]; }
39
+ function put(w, i, s) { w[i] |= lo[s]; w[i + 1] |= hi[s]; }
40
+ function move(w, i, f, t) { w[i] ^= lo[f] | lo[t]; w[i + 1] ^= hi[f] | hi[t]; }
41
+ function occ(w) { return { lo: w[O] | w[O + 2], hi: w[O + 1] | w[O + 3] }; }
42
+ function attackers(w, ks, side, o, removed = -1) {
43
+ const e = O + side * 2, el = w[e] & ~(lo[removed] || 0), eh = w[e + 1] & ~(hi[removed] || 0);
44
+ const p = a.pawnAttacks(side, ks), n = a.knightAttacks(ks), k = a.kingAttacks(ks);
45
+ let l = (p.lo & w[P]) | (n.lo & w[N]) | (k.lo & w[K]), h = (p.hi & w[P + 1]) | (n.hi & w[N + 1]) | (k.hi & w[K + 1]);
46
+ const bl = (w[B] | w[Q]) & el, bh = (w[B + 1] | w[Q + 1]) & eh, rl = (w[R] | w[Q]) & el, rh = (w[R + 1] | w[Q + 1]) & eh;
47
+ if ((bl & a.emptyBishopRays[ks].lo) | (bh & a.emptyBishopRays[ks].hi)) {
48
+ const x = a.bishopAttacks(ks, o);
49
+ l |= x.lo & bl;
50
+ h |= x.hi & bh;
51
+ }
52
+ if ((rl & a.emptyRookRays[ks].lo) | (rh & a.emptyRookRays[ks].hi)) {
53
+ const x = a.rookAttacks(ks, o);
54
+ l |= x.lo & rl;
55
+ h |= x.hi & rh;
56
+ }
57
+ return { lo: (l & el) >>> 0, hi: (h & eh) >>> 0 };
58
+ }
59
+ const attacked = (w, ks, side, o, removed = -1) => { const x = attackers(w, ks, side, o, removed); return !!(x.lo | x.hi); };
60
+ function epHashable(w, ep, side) {
61
+ if (ep === 255)
62
+ return false;
63
+ const p = a.pawnAttacks(side, ep), c = O + 2 * side;
64
+ return !!((p.lo & w[P] & w[c]) | (p.hi & w[P + 1] & w[c + 1]));
65
+ }
66
+ function xorKey(w, i) { w[H] ^= z.keyLo[i]; w[H + 1] ^= z.keyHi[i]; }
67
+ function xorPiece(w, c, r, s) { xorKey(w, (2 * r + c) * 64 + s); }
68
+ function xorCastle(w, i, r) { const k = (i < 2 ? 8 : 0) | (r & 7); w[H] ^= z.castleKeyLo[k]; w[H + 1] ^= z.castleKeyHi[k]; }
69
+ function computeHash(w, m) {
70
+ let l = 0, h = 0;
71
+ const kl = z.keyLo, kh = z.keyHi;
72
+ for (let c = 0; c < 2; c++)
73
+ for (let r = 0; r < 6; r++)
74
+ for (let half = 0; half < 2; half++) {
75
+ let bits = w[r * 2 + half] & w[O + c * 2 + half];
76
+ const base = (2 * r + c) * 64 + 32 * half;
77
+ while (bits) {
78
+ const idx = base + 31 - Math.clz32(bits & -bits);
79
+ l ^= kl[idx];
80
+ h ^= kh[idx];
81
+ bits &= bits - 1;
82
+ }
83
+ }
84
+ const rights = byte(m, 71), side = byte(m, 70), ep = byte(m, 72);
85
+ for (let i = 0; i < 4; i++)
86
+ if (rights & (1 << i)) {
87
+ const k = (i < 2 ? 8 : 0) | (byte(m, 66 + i) & 7);
88
+ l ^= z.castleKeyLo[k];
89
+ h ^= z.castleKeyHi[k];
90
+ }
91
+ if (epHashable(w, ep, side)) {
92
+ l ^= kl[z.IDX_EP + (ep & 7)];
93
+ h ^= kh[z.IDX_EP + (ep & 7)];
94
+ }
95
+ if (side) {
96
+ l ^= kl[z.IDX_SIDE];
97
+ h ^= kh[z.IDX_SIDE];
98
+ }
99
+ return { lo: l >>> 0, hi: h >>> 0 };
100
+ }
101
+ function castleIndex(m, side, from, to) {
102
+ if (from !== byte(m, 64 + side))
103
+ return -1;
104
+ const base = side ? 0 : 2, rights = byte(m, 71);
105
+ for (let i = base; i < base + 2; i++)
106
+ if ((rights & (1 << i)) && byte(m, 66 + i) === to)
107
+ return i;
108
+ return -1;
109
+ }
110
+ export function castleLegal(w, m, side, from, to, i) {
111
+ if (w[C] | w[C + 1])
112
+ return false;
113
+ const rank = side ? 0 : 56, kt = rank + (i % 2 ? 2 : 6), rt = rank + (i % 2 ? 3 : 5), o = occ(w);
114
+ if ((from >>> 3) !== (rank >>> 3) || (to >>> 3) !== (rank >>> 3))
115
+ return false;
116
+ const path = (side ? 0 : 64) | ((from & 7) << 3) | (to & 7);
117
+ if ((o.lo & CASTLE_PATH_LO[path]) | (o.hi & CASTLE_PATH_HI[path]))
118
+ return false;
119
+ // Intermediate king squares: original rook remains until the final
120
+ // simultaneous placement. At destination use both relocated pieces.
121
+ const transit = { lo: o.lo & ~lo[from], hi: o.hi & ~hi[from] };
122
+ if (from !== kt) {
123
+ const step = kt > from ? 1 : -1;
124
+ for (let s = from + step; s !== kt; s += step)
125
+ if (attacked(w, s, 1 - side, transit))
126
+ return false;
127
+ }
128
+ const final = { lo: (o.lo & ~(lo[from] | lo[to])) | lo[rt] | lo[kt], hi: (o.hi & ~(hi[from] | hi[to])) | hi[rt] | hi[kt] };
129
+ return !attacked(w, kt, 1 - side, final);
130
+ }
131
+ function legal(w, m, word, knownRole = -1) {
132
+ if (!Number.isInteger(word) || word < 0 || word > 65535)
133
+ return false;
134
+ if (word === 65535)
135
+ return !(w[C] | w[C + 1]);
136
+ const side = byte(m, 70), enemy = 1 - side, own = O + 2 * side, opp = O + 2 * enemy, from = word & 63, to = (word >>> 6) & 63, promo = word >>> 12;
137
+ if (from === to || promo > 4 || !((w[own] & lo[from]) | (w[own + 1] & hi[from])))
138
+ return false;
139
+ const role = knownRole < 0 ? roleAt(w, from) : knownRole, ks = byte(m, 64 + side);
140
+ if (role < 0 || (promo !== 0) !== (role === 0 && (to >>> 3) === (side ? 7 : 0)))
141
+ return false;
142
+ if (role === 5) {
143
+ const i = castleIndex(m, side, from, to);
144
+ if (i >= 0)
145
+ return castleLegal(w, m, side, from, to, i);
146
+ }
147
+ if ((w[own] & lo[to]) | (w[own + 1] & hi[to]) | (w[opp] & w[K] & lo[to]) | (w[opp + 1] & w[K + 1] & hi[to]))
148
+ return false;
149
+ const o = occ(w);
150
+ let removed = to, ep = false;
151
+ if (role === 0) {
152
+ const step = side ? 8 : -8;
153
+ if ((from & 7) === (to & 7)) {
154
+ if (hit(o, to))
155
+ return false;
156
+ if (to - from !== step && (to - from !== 2 * step || (from >>> 3) !== (side ? 1 : 6) || hit(o, from + step)))
157
+ return false;
158
+ }
159
+ else {
160
+ if (!hit(a.pawnAttacks(legacyColor(side), from), to))
161
+ return false;
162
+ if (!hit(o, to)) {
163
+ if (to !== byte(m, 72))
164
+ return false;
165
+ removed = to - step;
166
+ ep = true;
167
+ if (!((w[opp] & w[P] & lo[removed]) | (w[opp + 1] & w[P + 1] & hi[removed])))
168
+ return false;
169
+ }
170
+ }
171
+ }
172
+ else {
173
+ const at = role === 1 ? a.knightAttacks(from) : role === 2 ? a.bishopAttacks(from, o) : role === 3 ? a.rookAttacks(from, o) : role === 4 ? a.queenAttacks(from, o) : a.kingAttacks(from);
174
+ if (!hit(at, to))
175
+ return false;
176
+ }
177
+ if (role !== 5 && !ep && !(w[C] | w[C + 1])) {
178
+ const i = (ks << 6) | from;
179
+ if (!(a.LINE_RAY_LO[i] | a.LINE_RAY_HI[i]))
180
+ return true;
181
+ }
182
+ return !attacked(w, role === 5 ? to : ks, enemy, { lo: (o.lo & ~(lo[from] | lo[removed])) | lo[to], hi: (o.hi & ~(hi[from] | hi[removed])) | hi[to] }, removed);
183
+ }
184
+ const ownedMoveScratch96 = new Uint16Array(256);
185
+ export class Board96 {
186
+ constructor(source) {
187
+ this.hashReady = false;
188
+ this.words = source ? new Uint32Array(source) : new Uint32Array(24);
189
+ }
190
+ static fromFen(fen = INITIAL_FEN, chess960 = false) {
191
+ const b = new Board96(), w = b.words;
192
+ if (fen === INITIAL_FEN) {
193
+ w.set(startWords);
194
+ if (chess960)
195
+ w[19] |= 0x10000;
196
+ b.hashReady = true;
197
+ return b;
198
+ }
199
+ // Avoid allocating a split array on ordinary ASCII six-field FENs.
200
+ // Other whitespace and four/five-field EPD use the exact generic grammar.
201
+ let placement, turn, castling, ep, half, full;
202
+ const p1 = fen.indexOf(" "), p2 = p1 + 2, p3 = fen.indexOf(" ", p2 + 1), p4 = fen.indexOf(" ", p3 + 1), p5 = fen.indexOf(" ", p4 + 1);
203
+ if (p1 > 0 && !/[^!-~ ]/.test(fen) && p3 > p2 + 1 && p4 > p3 + 1 && p5 > p4 + 1 && p5 + 1 < fen.length && fen.charCodeAt(p2) === 32 && fen.indexOf(" ", p5 + 1) < 0) {
204
+ placement = fen.slice(0, p1);
205
+ turn = fen[p1 + 1];
206
+ castling = fen.slice(p2 + 1, p3);
207
+ ep = fen.slice(p3 + 1, p4);
208
+ half = fen.slice(p4 + 1, p5);
209
+ full = fen.slice(p5 + 1);
210
+ }
211
+ else {
212
+ const fields = fen.trim().split(/\s+/);
213
+ if (fields.length < 4 || fields.length > 6)
214
+ throw Error("Board96 FEN fields");
215
+ [placement, turn, castling, ep, half = "0", full = "1"] = fields;
216
+ }
217
+ if (turn !== "w" && turn !== "b")
218
+ throw Error("Board96 Turn");
219
+ if (!/^\d+$/.test(half) || !/^\d+$/.test(full) || +half > 65535 || +full < 1 || +full > 65535)
220
+ throw Error("Board96 clocks");
221
+ let rank = 7, file = 0, hashLo = 0, hashHi = 0;
222
+ const hashing = z.zobristTablesLoaded(), kl = z.keyLo, kh = z.keyHi;
223
+ let wl = 0, wh = 0, bl = 0, bh = 0, pl = 0, ph = 0, nl = 0, nh = 0, il = 0, ih = 0, rl = 0, rh = 0, ql = 0, qh = 0, kll = 0, khi = 0, bk = 255, wk = 255;
224
+ for (let i = 0; i < placement.length; i++) {
225
+ const ch = placement.charCodeAt(i);
226
+ if (ch === 47) {
227
+ if (file !== 8 || rank === 0)
228
+ throw Error("Board96 FEN rank");
229
+ rank--;
230
+ file = 0;
231
+ continue;
232
+ }
233
+ if (ch >= 49 && ch <= 56) {
234
+ file += ch - 48;
235
+ if (file > 8)
236
+ throw Error("Board96 FEN rank");
237
+ continue;
238
+ }
239
+ if (file >= 8)
240
+ throw Error("Board96 FEN piece");
241
+ const sq = rank * 8 + file++, c = ch < 97 ? 1 : 0, bit = 1 << (sq & 31);
242
+ let role;
243
+ if (sq >= 32) {
244
+ switch (ch | 32) {
245
+ case 112:
246
+ ph |= bit;
247
+ role = 0;
248
+ break;
249
+ case 110:
250
+ nh |= bit;
251
+ role = 1;
252
+ break;
253
+ case 98:
254
+ ih |= bit;
255
+ role = 2;
256
+ break;
257
+ case 114:
258
+ rh |= bit;
259
+ role = 3;
260
+ break;
261
+ case 113:
262
+ qh |= bit;
263
+ role = 4;
264
+ break;
265
+ case 107:
266
+ khi |= bit;
267
+ role = 5;
268
+ if (c)
269
+ wk = sq;
270
+ else
271
+ bk = sq;
272
+ break;
273
+ default: throw Error("Board96 FEN piece");
274
+ }
275
+ if (c)
276
+ wh |= bit;
277
+ else
278
+ bh |= bit;
279
+ }
280
+ else {
281
+ switch (ch | 32) {
282
+ case 112:
283
+ pl |= bit;
284
+ role = 0;
285
+ break;
286
+ case 110:
287
+ nl |= bit;
288
+ role = 1;
289
+ break;
290
+ case 98:
291
+ il |= bit;
292
+ role = 2;
293
+ break;
294
+ case 114:
295
+ rl |= bit;
296
+ role = 3;
297
+ break;
298
+ case 113:
299
+ ql |= bit;
300
+ role = 4;
301
+ break;
302
+ case 107:
303
+ kll |= bit;
304
+ role = 5;
305
+ if (c)
306
+ wk = sq;
307
+ else
308
+ bk = sq;
309
+ break;
310
+ default: throw Error("Board96 FEN piece");
311
+ }
312
+ if (c)
313
+ wl |= bit;
314
+ else
315
+ bl |= bit;
316
+ }
317
+ if (hashing) {
318
+ const idx = (2 * role + c) * 64 + sq;
319
+ hashLo ^= kl[idx];
320
+ hashHi ^= kh[idx];
321
+ }
322
+ }
323
+ if (rank !== 0 || file !== 8)
324
+ throw Error("Board96 FEN rank");
325
+ w[P] = pl;
326
+ w[P + 1] = ph;
327
+ w[N] = nl;
328
+ w[N + 1] = nh;
329
+ w[B] = il;
330
+ w[B + 1] = ih;
331
+ w[R] = rl;
332
+ w[R + 1] = rh;
333
+ w[Q] = ql;
334
+ w[Q + 1] = qh;
335
+ w[K] = kll;
336
+ w[K + 1] = khi;
337
+ w[O] = bl;
338
+ w[O + 1] = bh;
339
+ w[O + 2] = wl;
340
+ w[O + 3] = wh;
341
+ w[16] = bk | (wk << 8);
342
+ setByte(w, 70, turn === "w" ? 1 : 0);
343
+ let rights = 0, variant = false;
344
+ if (castling !== "-")
345
+ for (const ch of castling) {
346
+ const c = ch === ch.toUpperCase() ? 1 : 0, k = byte(w, 64 + c), base = c ? 0 : 56, lower = ch.toLowerCase();
347
+ let rook = -1;
348
+ if (lower === "k" || lower === "q") {
349
+ const kingSide = lower === "k";
350
+ const standardRook = base + (kingSide ? 7 : 0);
351
+ if (byte(w, 64) === 60 && byte(w, 65) === 4 && /^[KQkq]+$/.test(castling) &&
352
+ ((w[O + 2 * c] & w[R] & lo[standardRook]) | (w[O + 2 * c + 1] & w[R + 1] & hi[standardRook]))) {
353
+ rook = standardRook;
354
+ }
355
+ else {
356
+ const step = kingSide ? -1 : 1;
357
+ for (let f = kingSide ? 7 : 0; kingSide ? f > (k & 7) : f < (k & 7); f += step) {
358
+ const sq = base + f;
359
+ if ((w[O + 2 * c] & w[R] & lo[sq]) | (w[O + 2 * c + 1] & w[R + 1] & hi[sq])) {
360
+ rook = sq;
361
+ break;
362
+ }
363
+ }
364
+ }
365
+ }
366
+ else if (lower >= "a" && lower <= "h")
367
+ rook = base + lower.charCodeAt(0) - 97;
368
+ if (rook < 0 || rook === k)
369
+ throw Error("Board96 Castling");
370
+ const i = (c ? 0 : 2) + ((rook & 7) > (k & 7) ? 0 : 1);
371
+ if (rights & (1 << i))
372
+ throw Error("Board96 Castling duplicate");
373
+ rights |= 1 << i;
374
+ setByte(w, 66 + i, rook);
375
+ if (hashing) {
376
+ const idx = (c ? 8 : 0) | (rook & 7);
377
+ hashLo ^= z.castleKeyLo[idx];
378
+ hashHi ^= z.castleKeyHi[idx];
379
+ }
380
+ if (rook !== [7, 0, 63, 56][i] || k !== base + 4)
381
+ variant = true;
382
+ }
383
+ if (rights && (byte(w, 64) !== 60 || byte(w, 65) !== 4))
384
+ variant = true;
385
+ let epsq = 255;
386
+ if (ep !== "-") {
387
+ if (!/^[a-h][1-8]$/.test(ep))
388
+ throw Error("Board96 EnPassant");
389
+ epsq = (ep.charCodeAt(1) - 49) * 8 + ep.charCodeAt(0) - 97;
390
+ }
391
+ setByte(w, 71, rights);
392
+ w[18] = epsq | (+half << 16);
393
+ w[19] = +full | (+Boolean(variant || chess960) << 16);
394
+ // The scanner proves a disjoint complete partition, but all playable
395
+ // metadata, king cardinality, pawn and reachability checks still apply.
396
+ b.validate(false, true);
397
+ const side = byte(w, 70), x = attackers(w, byte(w, 64 + side), 1 - side, occ(w));
398
+ w[C] = x.lo;
399
+ w[C + 1] = x.hi;
400
+ if (hashing) {
401
+ if (epHashable(w, epsq, side)) {
402
+ hashLo ^= kl[z.IDX_EP + (epsq & 7)];
403
+ hashHi ^= kh[z.IDX_EP + (epsq & 7)];
404
+ }
405
+ if (side) {
406
+ hashLo ^= kl[z.IDX_SIDE];
407
+ hashHi ^= kh[z.IDX_SIDE];
408
+ }
409
+ w[H] = hashLo;
410
+ w[H + 1] = hashHi;
411
+ b.hashReady = true;
412
+ }
413
+ return b;
414
+ }
415
+ /** Construct from owned logical setup values without FEN or wire serialization.
416
+ * Checks the complete playable-position contract and derives kings/caches.
417
+ * Empty and invalid editor setups must remain outside the playable Board.
418
+ */
419
+ static fromFields(fields) {
420
+ const { bitboards, turn, castleRooks, epSquare, halfmove, fullmove, isChess960 } = fields;
421
+ if (!(bitboards instanceof Uint32Array) || bitboards.length !== 16)
422
+ throw Error("Board96 Fields masks");
423
+ if (turn !== 0 && turn !== 1)
424
+ throw Error("Board96 Turn");
425
+ if (typeof isChess960 !== "boolean" || castleRooks.length !== 4)
426
+ throw Error("Board96 Fields metadata");
427
+ if (!Number.isInteger(halfmove) || halfmove < 0 || halfmove > 65535 || !Number.isInteger(fullmove) || fullmove < 1 || fullmove > 65535)
428
+ throw Error("Board96 clocks");
429
+ if (epSquare !== null && (!Number.isInteger(epSquare) || epSquare < 0 || epSquare > 63))
430
+ throw Error("Board96 EnPassant");
431
+ const b = new Board96(), w = b.words;
432
+ w.set(bitboards);
433
+ for (let c = 0; c < 2; c++) {
434
+ const l = w[K] & w[O + 2 * c], h = w[K + 1] & w[O + 2 * c + 1];
435
+ if (popcountParts(l, h) !== 1)
436
+ throw Error("Board96 Kings");
437
+ setByte(w, 64 + c, l ? 31 - Math.clz32(l & -l) : 63 - Math.clz32(h & -h));
438
+ }
439
+ let rights = 0;
440
+ for (let i = 0; i < 4; i++) {
441
+ const r = castleRooks[i];
442
+ if (r === undefined)
443
+ continue;
444
+ if (!Number.isInteger(r) || r < 0 || r > 63)
445
+ throw Error("Board96 Castling");
446
+ rights |= 1 << i;
447
+ setByte(w, 66 + i, r);
448
+ }
449
+ setByte(w, 70, turn);
450
+ setByte(w, 71, rights);
451
+ w[18] = (epSquare ?? 255) | (halfmove << 16);
452
+ w[19] = fullmove | (+isChess960 << 16);
453
+ b.validate(false);
454
+ b.refresh();
455
+ return b;
456
+ }
457
+ /** Caller-owned logical mask projection. Never exposes writable backing storage. */
458
+ readBitboardsInto(out) {
459
+ if (!(out instanceof Uint32Array) || out.length !== 16)
460
+ throw Error("Board96 Fields masks");
461
+ for (let i = 0; i < 16; i++)
462
+ out[i] = this.words[i];
463
+ }
464
+ checkersMask() { return { lo: this.words[C], hi: this.words[C + 1] }; }
465
+ refresh() {
466
+ const w = this.words, m = this.words, side = byte(m, 70), x = attackers(w, byte(m, 64 + side), 1 - side, occ(w));
467
+ w[C] = x.lo;
468
+ w[C + 1] = x.hi;
469
+ if (z.zobristTablesLoaded()) {
470
+ const h = computeHash(w, m);
471
+ w[H] = h.lo;
472
+ w[H + 1] = h.hi;
473
+ this.hashReady = true;
474
+ }
475
+ }
476
+ ensureHash() {
477
+ if (!this.hashReady && !z.zobristTablesLoaded())
478
+ throw Error("Board96 hash tables not loaded");
479
+ if (!this.hashReady) {
480
+ const h = computeHash(this.words, this.words);
481
+ this.words[H] = h.lo;
482
+ this.words[H + 1] = h.hi;
483
+ this.hashReady = true;
484
+ }
485
+ }
486
+ validate(cache, partitionKnown = false) {
487
+ const w = this.words, m = this.words;
488
+ let l = 0, h = 0;
489
+ if (byte(m, 73) || byte(m, 79))
490
+ throw Error("Board96 Reserved");
491
+ const side = byte(m, 70), rights = byte(m, 71), ep = byte(m, 72), variant = byte(m, 78);
492
+ if (side > 1 || variant > 1 || rights > 15 || (m[19] & 65535) === 0)
493
+ throw Error("Board96 metadata");
494
+ if (!partitionKnown) {
495
+ for (let r = 0; r < 12; r += 2) {
496
+ if ((l & w[r]) | (h & w[r + 1]))
497
+ throw Error("Board96 Masks");
498
+ l |= w[r];
499
+ h |= w[r + 1];
500
+ }
501
+ if ((w[O] & w[O + 2]) || (w[O + 1] & w[O + 3]) || l !== (w[O] | w[O + 2]) || h !== (w[O + 1] | w[O + 3]))
502
+ throw Error("Board96 Masks");
503
+ }
504
+ for (let c = 0; c < 2; c++) {
505
+ const k = byte(m, 64 + c), o = O + 2 * c;
506
+ if (k >= 64 || (w[K] & w[o]) !== lo[k] || (w[K + 1] & w[o + 1]) !== hi[k])
507
+ throw Error("Board96 Kings");
508
+ }
509
+ const bk = byte(m, 64), wk = byte(m, 65);
510
+ if (hit(a.kingAttacks(bk), wk))
511
+ throw Error("Board96 Kings");
512
+ if ((w[P] & 255) || (w[P + 1] & 0xff000000))
513
+ throw Error("Board96 Pawns");
514
+ for (let i = 0; i < 4; i++) {
515
+ const r = byte(m, 66 + i), c = i < 2 ? 1 : 0, k = byte(m, 64 + c), rank = c ? 0 : 7, o = O + 2 * c;
516
+ if (!(rights & (1 << i))) {
517
+ if (r !== 0)
518
+ throw Error("Board96 Castling");
519
+ continue;
520
+ }
521
+ if (r >= 64 || (r >>> 3) !== rank || (k >>> 3) !== rank || r === k || ((r & 7) > (k & 7)) !== (i % 2 === 0) || !((w[o] & w[R] & lo[r]) | (w[o + 1] & w[R + 1] & hi[r])) || (!variant && (r !== [7, 0, 63, 56][i] || k !== rank * 8 + 4)))
522
+ throw Error("Board96 Castling");
523
+ }
524
+ const o = occ(w);
525
+ if (ep !== 255) {
526
+ const cap = ep + (side ? -8 : 8), e = O + 2 * (1 - side);
527
+ if (ep >= 64 || (ep >>> 3) !== (side ? 5 : 2) || hit(o, ep) || !((w[e] & w[P] & lo[cap]) | (w[e + 1] & w[P + 1] & hi[cap])))
528
+ throw Error("Board96 EnPassant");
529
+ }
530
+ if (attacked(w, byte(m, 64 + 1 - side), side, o))
531
+ throw Error("Board96 Kings");
532
+ if (cache) {
533
+ if (!z.zobristTablesLoaded())
534
+ throw Error("Board96 hash tables not loaded");
535
+ const x = attackers(w, byte(m, 64 + side), 1 - side, o), key = computeHash(w, m);
536
+ if (w[C] !== x.lo || w[C + 1] !== x.hi)
537
+ throw Error("Board96 Checkers");
538
+ if (w[H] !== key.lo || w[H + 1] !== key.hi)
539
+ throw Error("Board96 Hash");
540
+ }
541
+ }
542
+ static fromBinary(bytes) {
543
+ if (bytes.byteLength !== 96)
544
+ throw Error("Board96 Length");
545
+ const b = new Board96();
546
+ if (nativeLE)
547
+ new Uint8Array(b.words.buffer).set(bytes);
548
+ else {
549
+ const view = new DataView(bytes.buffer, bytes.byteOffset, 96);
550
+ for (let i = 0; i < 24; i++)
551
+ b.words[i] = view.getUint32(i * 4, true);
552
+ }
553
+ b.validate(true);
554
+ b.hashReady = true;
555
+ return b;
556
+ }
557
+ encodeInto(out) {
558
+ if (out.byteLength !== 96)
559
+ throw Error("Board96 Length");
560
+ this.ensureHash();
561
+ this.validate(true);
562
+ if (nativeLE)
563
+ out.set(new Uint8Array(this.words.buffer));
564
+ else {
565
+ const view = new DataView(out.buffer, out.byteOffset, 96);
566
+ for (let i = 0; i < 24; i++)
567
+ view.setUint32(i * 4, this.words[i], true);
568
+ }
569
+ }
570
+ toBinary() { const b = new Uint8Array(96); this.encodeInto(b); return b; }
571
+ /** Checked, transactional replacement; a failed parse leaves this board unchanged. */
572
+ loadFen(fen) { Board96.fromFen(fen).copyInto(this); }
573
+ pieceAt(square) {
574
+ const color = this.colorAt(square);
575
+ return color === undefined ? undefined : { role: this.roleAt(square), color };
576
+ }
577
+ isSeventyFiveMoveDraw() { return this.halfmove >= 150; }
578
+ clone() { const b = new Board96(this.words); b.hashReady = this.hashReady; return b; }
579
+ copyInto(target) { target.words.set(this.words); target.hashReady = this.hashReady; }
580
+ get turn() { return byte(this.words, 70); }
581
+ get castlingRights() { return this.words[17] >>> 24; }
582
+ castleRookSquare(right) { return Number.isInteger(right) && right >= 0 && right < 4 && (this.castlingRights & (1 << right)) ? byte(this.words, 66 + right) : undefined; }
583
+ get epSquare() { const ep = this.words[18] & 255; return ep === 255 ? null : ep; }
584
+ get isChess960() { return !!(this.words[19] & 0x10000); }
585
+ kingSquare(color) { return byte(this.words, 64 + color); }
586
+ zobrist() { this.ensureHash(); return { lo: this.words[H], hi: this.words[H + 1] }; }
587
+ get zobristLo() { this.ensureHash(); return this.words[H]; }
588
+ get zobristHi() { this.ensureHash(); return this.words[H + 1]; }
589
+ /** Read-only value, never a live mutable alias. */
590
+ roleMask(role) {
591
+ if (!Number.isInteger(role) || role < 0 || role > 5)
592
+ throw Error("Board96 role");
593
+ return { lo: this.words[role * 2], hi: this.words[role * 2 + 1] };
594
+ }
595
+ /** Caller-owned projection for board renderers. 0=empty, 1..6 white,
596
+ * 7..12 black, role order P,N,B,R,Q,K. */
597
+ readPieces(out) {
598
+ if (out.length !== 64)
599
+ throw Error("Board96 piece buffer length");
600
+ out.fill(0);
601
+ const w = this.words;
602
+ for (let r = 0; r < 6; r++)
603
+ for (let h = 0; h < 2; h++) {
604
+ let bits = w[2 * r + h], white = w[O + 2 + h];
605
+ while (bits) {
606
+ const bit = bits & -bits;
607
+ out[32 * h + 31 - Math.clz32(bit)] = r + 1 + (white & bit ? 0 : 6);
608
+ bits &= bits - 1;
609
+ }
610
+ }
611
+ }
612
+ isCheckmate() { return this.inCheck() && this.countLegalMoves() === 0; }
613
+ isStalemate() { return !this.inCheck() && this.countLegalMoves() === 0; }
614
+ isFiftyMoveDraw() { return this.halfmove >= 100; }
615
+ isInsufficientMaterial() {
616
+ const w = this.words;
617
+ if (w[P] | w[P + 1] | w[R] | w[R + 1] | w[Q] | w[Q + 1])
618
+ return false;
619
+ const n = popcountParts(w[N], w[N + 1]), b = popcountParts(w[B], w[B + 1]);
620
+ if (n + b <= 1)
621
+ return true;
622
+ // All bishops on one square color, no knights. Matches FIDE dead
623
+ // material including extra same-color promoted bishops.
624
+ return n === 0 && (!((w[B] & 0x55aa55aa) | (w[B + 1] & 0x55aa55aa)) || !((w[B] & 0xaa55aa55) | (w[B + 1] & 0xaa55aa55)));
625
+ }
626
+ hasLegalEp() {
627
+ const w = this.words, ep = this.epSquare, side = this.turn;
628
+ if (ep === null)
629
+ return false;
630
+ const step = side ? 8 : -8;
631
+ for (const f of [ep - step - 1, ep - step + 1])
632
+ if (f >= 0 && f < 64 && Math.abs((f & 7) - (ep & 7)) === 1 && roleAt(w, f) === 0 && this.colorAt(f) === side && legal(w, w, f | (ep << 6)))
633
+ return true;
634
+ return false;
635
+ }
636
+ equalsForRepetition(other) {
637
+ const w = this.words, v = other.words;
638
+ for (let i = 0; i < 16; i++)
639
+ if (w[i] !== v[i])
640
+ return false;
641
+ if (this.turn !== other.turn || this.castlingRights !== other.castlingRights)
642
+ return false;
643
+ for (let i = 0; i < 4; i++)
644
+ if (this.castleRookSquare(i) !== other.castleRookSquare(i))
645
+ return false;
646
+ const ep = this.hasLegalEp() ? this.epSquare : null, otherEp = other.hasLegalEp() ? other.epSquare : null;
647
+ return ep === otherEp;
648
+ }
649
+ get halfmove() { return (this.words[18] >>> 16); }
650
+ get fullmove() { return (this.words[19] & 65535); }
651
+ inCheck() { return !!(this.words[C] | this.words[C + 1]); }
652
+ zobristBigInt() { this.ensureHash(); return (BigInt(this.words[H + 1]) << 32n) | BigInt(this.words[H]); }
653
+ zobristHex() { this.ensureHash(); return this.words[H + 1].toString(16).padStart(8, "0") + this.words[H].toString(16).padStart(8, "0"); }
654
+ roleAt(s) { return Number.isInteger(s) && s >= 0 && s < 64 ? roleAt(this.words, s) : -1; }
655
+ colorAt(s) { if (!Number.isInteger(s) || s < 0 || s > 63)
656
+ return undefined; const w = this.words; return (w[O] & lo[s]) | (w[O + 1] & hi[s]) ? 0 : (w[O + 2] & lo[s]) | (w[O + 3] & hi[s]) ? 1 : undefined; }
657
+ isLegal(word) { return legal(this.words, this.words, word); }
658
+ /** Checked transition, no mutation on illegal input. */
659
+ play(word) { if (!this.isLegal(word))
660
+ return false; this.playTrusted(word); return true; }
661
+ /** Only for canonical legal moves2 words from trusted sources. */
662
+ playTrusted(word) { this.transition(word, -1); }
663
+ transition(word, knownRole) {
664
+ const w = this.words, m = this.words, side = byte(m, 70), enemy = 1 - side, own = O + side * 2, opp = O + enemy * 2, rights = byte(m, 71), ep = byte(m, 72), hash = z.zobristTablesLoaded();
665
+ if (hash && !this.hashReady)
666
+ this.ensureHash();
667
+ if (!hash)
668
+ this.hashReady = false;
669
+ if (hash && ep !== 255 && epHashable(w, ep, side))
670
+ xorKey(w, z.IDX_EP + (ep & 7));
671
+ let nextRights = rights, newEp = 255, half = minClock(this.halfmove + 1), full = this.fullmove;
672
+ if (word === 65535) {
673
+ full = minClock(full + 1);
674
+ }
675
+ else {
676
+ const from = word & 63, to = (word >>> 6) & 63, promo = word >>> 12, role = knownRole < 0 ? roleAt(w, from) : knownRole, i = role === 5 ? castleIndex(m, side, from, to) : -1;
677
+ if (hash)
678
+ xorPiece(w, side, role, from);
679
+ if (i >= 0) {
680
+ const rank = side ? 0 : 56, kt = rank + (i % 2 ? 2 : 6), rt = rank + (i % 2 ? 3 : 5);
681
+ // Remove both origins before placing either destination: all 960 overlaps.
682
+ clear(w, K, from);
683
+ clear(w, R, to);
684
+ clear(w, own, from);
685
+ clear(w, own, to);
686
+ put(w, K, kt);
687
+ put(w, R, rt);
688
+ put(w, own, kt);
689
+ put(w, own, rt);
690
+ setByte(m, 64 + side, kt);
691
+ if (hash) {
692
+ xorPiece(w, side, 5, kt);
693
+ xorPiece(w, side, 3, to);
694
+ xorPiece(w, side, 3, rt);
695
+ }
696
+ }
697
+ else {
698
+ const cap = role === 0 && to === ep && (from & 7) !== (to & 7) ? to + (side ? -8 : 8) : to;
699
+ if ((w[opp] & lo[cap]) | (w[opp + 1] & hi[cap])) {
700
+ const cr = roleAt(w, cap);
701
+ clear(w, cr * 2, cap);
702
+ clear(w, opp, cap);
703
+ half = 0;
704
+ if (hash)
705
+ xorPiece(w, enemy, cr, cap);
706
+ }
707
+ if (promo) {
708
+ clear(w, P, from);
709
+ put(w, promo * 2, to);
710
+ }
711
+ else
712
+ move(w, role * 2, from, to);
713
+ move(w, own, from, to);
714
+ if (hash)
715
+ xorPiece(w, side, promo || role, to);
716
+ if (role === 0) {
717
+ half = 0;
718
+ if (Math.abs(to - from) === 16)
719
+ newEp = (from + to) >>> 1;
720
+ }
721
+ if (role === 5)
722
+ setByte(m, 64 + side, to);
723
+ }
724
+ if (role === 5)
725
+ nextRights &= side ? 12 : 3;
726
+ if (nextRights) {
727
+ if (!(w[19] & 0x10000)) {
728
+ // Standard rights geometry is fixed; any live right always
729
+ // belongs to the original corner rook and king.
730
+ nextRights &= rightsClear[from] & rightsClear[to];
731
+ }
732
+ else
733
+ for (let j = 0; j < 4; j++)
734
+ if ((nextRights & (1 << j)) && (byte(m, 66 + j) === from || byte(m, 66 + j) === to))
735
+ nextRights &= ~(1 << j);
736
+ }
737
+ if (!side)
738
+ full = minClock(full + 1);
739
+ }
740
+ if (rights !== nextRights)
741
+ for (let i = 0; i < 4; i++)
742
+ if ((rights ^ nextRights) & (1 << i)) {
743
+ if (hash)
744
+ xorCastle(w, i, byte(m, 66 + i));
745
+ setByte(m, 66 + i, 0);
746
+ }
747
+ m[17] = (m[17] & 65535) | (enemy << 16) | (nextRights << 24);
748
+ m[18] = newEp | (half << 16);
749
+ m[19] = (m[19] & 0xffff0000) | full;
750
+ if (hash) {
751
+ if (newEp !== 255 && epHashable(w, newEp, enemy))
752
+ xorKey(w, z.IDX_EP + (newEp & 7));
753
+ xorKey(w, z.IDX_SIDE);
754
+ }
755
+ const x = attackers(w, byte(m, 64 + enemy), side, occ(w));
756
+ w[C] = x.lo;
757
+ w[C + 1] = x.hi;
758
+ }
759
+ static fromMoves2Checked(input, fen, chess960 = false) { return Board96.fromMoves2(input, fen, true, chess960); }
760
+ static fromMoves2Trusted(input, fen, chess960 = false) { return Board96.fromMoves2(input, fen, false, chess960); }
761
+ static fromMoves2(input, fen, checked = true, chess960 = false) {
762
+ let words;
763
+ if (input instanceof Uint16Array)
764
+ words = input;
765
+ else {
766
+ if (input.byteLength & 1)
767
+ throw Error("moves2: truncated 16-bit word");
768
+ if (nativeLE && !(input.byteOffset & 1))
769
+ words = new Uint16Array(input.buffer, input.byteOffset, input.byteLength >>> 1);
770
+ else {
771
+ words = new Uint16Array(input.byteLength >>> 1);
772
+ const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
773
+ for (let i = 0; i < words.length; i++)
774
+ words[i] = view.getUint16(i * 2, true);
775
+ }
776
+ }
777
+ const b = Board96.fromFen(fen, chess960);
778
+ const w = b.words;
779
+ if (checked) {
780
+ for (let i = 0; i < words.length; i++) {
781
+ const word = words[i], role = word === 65535 ? -1 : roleAt(w, word & 63);
782
+ if (!legal(w, w, word, role))
783
+ throw Error("moves2: illegal move at ply " + (i + 1));
784
+ b.transition(word, role);
785
+ }
786
+ }
787
+ else
788
+ for (let i = 0; i < words.length; i++)
789
+ b.transition(words[i], -1);
790
+ return b;
791
+ }
792
+ /** Initial direct generator: piece targets followed by exact targeted
793
+ * legality. Optimize fused geometry in subsequent A/B rounds. */
794
+ legalMovesIntoReference(out) {
795
+ const w = this.words, m = this.words, side = this.turn, own = O + 2 * side, o = occ(w);
796
+ let n = 0;
797
+ const emit = (from, to, role) => {
798
+ const base = from | (to << 6);
799
+ if (role === 0 && (to >>> 3) === (side ? 7 : 0)) {
800
+ for (let p = 1; p <= 4; p++) {
801
+ const word = base | (p << 12);
802
+ if (legal(w, m, word)) {
803
+ if (n >= out.length)
804
+ throw Error("move buffer too small");
805
+ out[n++] = word;
806
+ }
807
+ }
808
+ }
809
+ else if (legal(w, m, base)) {
810
+ if (n >= out.length)
811
+ throw Error("move buffer too small");
812
+ out[n++] = base;
813
+ }
814
+ };
815
+ for (let role = 0; role < 6; role++)
816
+ for (let half = 0; half < 2; half++) {
817
+ let pieces = w[role * 2 + half] & w[own + half];
818
+ while (pieces) {
819
+ const from = half * 32 + 31 - Math.clz32(pieces & -pieces);
820
+ pieces &= pieces - 1;
821
+ let at;
822
+ if (role === 0) {
823
+ at = a.pawnAttacks(legacyColor(side), from);
824
+ const step = side ? 8 : -8;
825
+ if (from + step >= 0 && from + step < 64)
826
+ emit(from, from + step, role);
827
+ if ((from >>> 3) === (side ? 1 : 6))
828
+ emit(from, from + 2 * step, role);
829
+ }
830
+ else
831
+ at = role === 1 ? a.knightAttacks(from) : role === 2 ? a.bishopAttacks(from, o) : role === 3 ? a.rookAttacks(from, o) : role === 4 ? a.queenAttacks(from, o) : a.kingAttacks(from);
832
+ for (let h = 0; h < 2; h++) {
833
+ let dest = (h ? at.hi : at.lo) & ~w[own + h];
834
+ while (dest) {
835
+ const to = h * 32 + 31 - Math.clz32(dest & -dest);
836
+ dest &= dest - 1;
837
+ emit(from, to, role);
838
+ }
839
+ }
840
+ if (role === 5) {
841
+ const base = side ? 0 : 2;
842
+ for (let i = base; i < base + 2; i++)
843
+ if (byte(m, 71) & (1 << i))
844
+ emit(from, byte(m, 66 + i), role);
845
+ }
846
+ }
847
+ }
848
+ return n;
849
+ }
850
+ legalMovesInto(out) {
851
+ if (out.length < 256)
852
+ throw Error("Board96 move buffer requires 256 words");
853
+ const w = this.words, m = this.words, side = this.turn;
854
+ return nativeMovesInto(w, out);
855
+ }
856
+ countLegalMoves() { return nativeMovesInto(this.words, null); }
857
+ /** Caller owns a reusable prior state; no Undo allocation. */
858
+ makeMove(word, prior) {
859
+ if (prior === this)
860
+ throw Error("Board96 undo aliases board");
861
+ this.copyInto(prior);
862
+ this.playTrusted(word);
863
+ }
864
+ unmakeMove(prior) { if (prior === this)
865
+ throw Error("Board96 undo aliases board"); prior.copyInto(this); }
866
+ perft(depth) {
867
+ if (!Number.isInteger(depth) || depth < 0)
868
+ throw Error("Board96 perft depth");
869
+ if (depth === 0)
870
+ return 1;
871
+ if (depth === 1)
872
+ return this.countLegalMoves();
873
+ const compact = compactPerft96(this.words, depth);
874
+ if (compact !== undefined)
875
+ return compact;
876
+ const boards = Array.from({ length: depth }, () => this.clone()), moves = Array.from({ length: depth }, () => new Uint16Array(256));
877
+ const visit = (b, ply) => {
878
+ const out = moves[ply], n = b.legalMovesInto(out);
879
+ if (ply === depth - 1)
880
+ return n;
881
+ const child = boards[ply];
882
+ let nodes = 0;
883
+ for (let i = 0; i < n; i++) {
884
+ b.copyInto(child);
885
+ child.playTrusted(out[i]);
886
+ nodes += visit(child, ply + 1);
887
+ }
888
+ return nodes;
889
+ };
890
+ return visit(this, 0);
891
+ }
892
+ forEachLegalMove(fn) {
893
+ // Independent owned list: user callbacks can reenter or modify a board.
894
+ for (const word of this.legalMoves())
895
+ fn(word);
896
+ }
897
+ legalMoves() { const n = this.legalMovesInto(ownedMoveScratch96); return ownedMoveScratch96.slice(0, n); }
898
+ toUci(word) {
899
+ if (word === 65535)
900
+ return "0000";
901
+ return alg(word & 63) + alg((word >>> 6) & 63) + (" nbrq"[word >>> 12] ?? "").trim();
902
+ }
903
+ parseUci(s) {
904
+ if (s === "0000")
905
+ return this.isLegal(65535) ? 65535 : null;
906
+ if (s.length !== 4 && s.length !== 5)
907
+ return null;
908
+ const f = s.charCodeAt(0) - 97, fr = s.charCodeAt(1) - 49, t = s.charCodeAt(2) - 97, tr = s.charCodeAt(3) - 49;
909
+ if ((f | fr | t | tr) < 0 || f > 7 || fr > 7 || t > 7 || tr > 7)
910
+ return null;
911
+ const promo = s.length === 5 ? " nbrq".indexOf(s[4].toLowerCase()) : 0;
912
+ if (promo < 0 || s.length === 5 && promo === 0)
913
+ return null;
914
+ const word = (fr * 8 + f) | ((tr * 8 + t) << 6) | (promo << 12);
915
+ if (this.isLegal(word))
916
+ return word;
917
+ if (!promo && !this.isChess960 && this.roleAt(fr * 8 + f) === 5 && fr * 8 + f === this.kingSquare(this.turn) && fr === tr && Math.abs(t - f) === 2) {
918
+ const i = (this.turn ? 0 : 2) + (t < f ? 1 : 0), rook = this.castleRookSquare(i);
919
+ if (rook !== undefined) {
920
+ const canonical = (word & 63) | (rook << 6);
921
+ if (this.isLegal(canonical))
922
+ return canonical;
923
+ }
924
+ }
925
+ return null;
926
+ }
927
+ toSan(word) {
928
+ if (word === 65535)
929
+ return "--";
930
+ const w = this.words, m = this.words, side = this.turn, from = word & 63, to = (word >>> 6) & 63, role = roleAt(w, from), promo = word >>> 12;
931
+ let san = "";
932
+ const castle = role === 5 ? castleIndex(m, side, from, to) : -1;
933
+ if (castle >= 0)
934
+ san = castle % 2 ? "O-O-O" : "O-O";
935
+ else {
936
+ const capture = this.colorAt(to) === 1 - side || (role === 0 && to === byte(m, 72) && (from & 7) !== (to & 7));
937
+ if (role === 0) {
938
+ if (capture)
939
+ san = alg(from)[0];
940
+ }
941
+ else {
942
+ san = "PNBRQK"[role];
943
+ const other = O + side * 2;
944
+ let sameFile = false, sameRank = false, amb = false;
945
+ for (let h = 0; h < 2; h++) {
946
+ let bits = w[2 * role + h] & w[other + h];
947
+ while (bits) {
948
+ const f = h * 32 + 31 - Math.clz32(bits & -bits);
949
+ bits &= bits - 1;
950
+ if (f !== from && legal(w, m, f | (to << 6))) {
951
+ amb = true;
952
+ if ((f & 7) === (from & 7))
953
+ sameFile = true;
954
+ if ((f >>> 3) === (from >>> 3))
955
+ sameRank = true;
956
+ }
957
+ }
958
+ }
959
+ if (amb)
960
+ san += !sameFile ? alg(from)[0] : !sameRank ? alg(from)[1] : alg(from);
961
+ }
962
+ if (capture)
963
+ san += "x";
964
+ san += alg(to);
965
+ if (promo)
966
+ san += "=" + " NBRQ"[promo];
967
+ }
968
+ const targetKing = byte(m, 64 + 1 - side);
969
+ if (castle < 0 && !promo && !(role === 0 && to === byte(m, 72)) &&
970
+ !(a.LINE_RAY_LO[(targetKing << 6) | from] | a.LINE_RAY_HI[(targetKing << 6) | from])) {
971
+ const mask = role === 0 ? a.pawnAttacks(side, targetKing) : role === 1 ? a.knightAttacks(targetKing) : role === 2 ? a.emptyBishopRays[targetKing] : role === 3 ? a.emptyRookRays[targetKing] : role === 4 ? { lo: a.emptyBishopRays[targetKing].lo | a.emptyRookRays[targetKing].lo, hi: a.emptyBishopRays[targetKing].hi | a.emptyRookRays[targetKing].hi } : a.kingAttacks(targetKing);
972
+ if (!hit(mask, to))
973
+ return san;
974
+ }
975
+ const child = this.clone();
976
+ child.playTrusted(word);
977
+ if (child.inCheck())
978
+ san += child.countLegalMoves() ? "+" : "#";
979
+ return san;
980
+ }
981
+ parseSanCandidates(san, strictCapture = true) {
982
+ const token = san.trim().replace(/0/g, "O").replace(/[!?+#]+$/, "");
983
+ if (token === "--" || token === "ZO")
984
+ return this.isLegal(65535) ? Uint16Array.of(65535) : new Uint16Array(0);
985
+ const w = this.words, side = this.turn, own = O + 2 * side, rights = byte(w, 71);
986
+ if (token === "O-O" || token === "O-O-O") {
987
+ const i = (side ? 0 : 2) + (token === "O-O-O" ? 1 : 0);
988
+ if (!(rights & (1 << i)))
989
+ return new Uint16Array(0);
990
+ const word = byte(w, 64 + side) | (byte(w, 66 + i) << 6);
991
+ return legal(w, w, word) ? Uint16Array.of(word) : new Uint16Array(0);
992
+ }
993
+ const match = /^([NBRQK])?([a-h])?([1-8])?(x)?([a-h])([1-8])(?:=?([NBRQ]))?$/.exec(token);
994
+ if (!match)
995
+ return new Uint16Array(0);
996
+ const [, piece, file, rank, capture, dFile, dRank, prom] = match, role = piece ? "PNBRQK".indexOf(piece) : 0, promo = prom ? " NBRQ".indexOf(prom) : 0;
997
+ if (role !== 0 && promo || role === 0 && rank || role === 0 && !!file !== !!capture)
998
+ return new Uint16Array(0);
999
+ const to = (dRank.charCodeAt(0) - 49) * 8 + dFile.charCodeAt(0) - 97, ep = byte(w, 72);
1000
+ const actualCapture = this.colorAt(to) === 1 - side || (role === 0 && to === ep && !!file);
1001
+ if (strictCapture && !!capture !== actualCapture)
1002
+ return new Uint16Array(0);
1003
+ const o = occ(w), at = role === 0 ? { lo: ~0, hi: ~0 } : role === 1 ? a.knightAttacks(to) : role === 2 ? a.bishopAttacks(to, o) : role === 3 ? a.rookAttacks(to, o) : role === 4 ? a.queenAttacks(to, o) : a.kingAttacks(to);
1004
+ const matches = [];
1005
+ for (let h = 0; h < 2; h++) {
1006
+ let bits = w[role * 2 + h] & w[own + h] & (h ? at.hi : at.lo);
1007
+ while (bits) {
1008
+ const from = h * 32 + 31 - Math.clz32(bits & -bits);
1009
+ bits &= bits - 1;
1010
+ if (file && (from & 7) !== file.charCodeAt(0) - 97 || rank && (from >>> 3) !== rank.charCodeAt(0) - 49)
1011
+ continue;
1012
+ const word = from | (to << 6) | (promo << 12);
1013
+ if (legal(w, w, word))
1014
+ matches.push(word);
1015
+ }
1016
+ }
1017
+ return Uint16Array.from(matches);
1018
+ }
1019
+ parseSan(san, strictCapture = true) { const candidates = this.parseSanCandidates(san, strictCapture); return candidates.length === 1 ? candidates[0] : null; }
1020
+ parseSanResult(san) {
1021
+ const candidates = this.parseSanCandidates(san);
1022
+ return candidates.length === 1 ? { ok: true, moveWord: candidates[0] } : { ok: false, code: candidates.length ? "san/ambiguous" : "san/noLegalMove", candidates };
1023
+ }
1024
+ /** Allocation-free iteration over a caller-owned move workspace. The
1025
+ * caller must not reuse that workspace in a nested visitor. */
1026
+ forEachLegalMoveInto(out, fn) {
1027
+ const n = this.legalMovesInto(out);
1028
+ for (let i = 0; i < n; i++)
1029
+ fn(out[i]);
1030
+ return n;
1031
+ }
1032
+ repetitionKeyHex() {
1033
+ this.ensureHash();
1034
+ const w = this.words, m = this.words, ep = byte(m, 72), side = this.turn;
1035
+ if (!epHashable(w, ep, side))
1036
+ return this.zobristHex();
1037
+ const step = side ? 8 : -8;
1038
+ for (const f of [ep - step - 1, ep - step + 1]) {
1039
+ if (f >= 0 && f < 64 && Math.abs((f & 7) - (ep & 7)) === 1 && roleAt(w, f) === 0 && this.colorAt(f) === side && legal(w, m, f | (ep << 6)))
1040
+ return this.zobristHex();
1041
+ }
1042
+ const i = z.IDX_EP + (ep & 7), l = (w[H] ^ z.keyLo[i]) >>> 0, h = (w[H + 1] ^ z.keyHi[i]) >>> 0;
1043
+ return h.toString(16).padStart(8, "0") + l.toString(16).padStart(8, "0");
1044
+ }
1045
+ toFen() {
1046
+ const w = this.words;
1047
+ let s = "";
1048
+ for (let rank = 7; rank >= 0; rank--) {
1049
+ const h = rank >>> 2, shift = (rank & 3) * 8, occupied = w[O + h] | w[O + 2 + h], white = w[O + 2 + h];
1050
+ let bits = (occupied >>> shift) & 255, prev = 0;
1051
+ while (bits) {
1052
+ const bit = bits & -bits, f = 31 - Math.clz32(bit), mask = bit << shift;
1053
+ if (f > prev)
1054
+ s += f - prev;
1055
+ const r = w[P + h] & mask ? 0 : w[N + h] & mask ? 1 : w[B + h] & mask ? 2 : w[R + h] & mask ? 3 : w[Q + h] & mask ? 4 : 5;
1056
+ s += (white & mask ? "PNBRQK" : "pnbrqk")[r];
1057
+ prev = f + 1;
1058
+ bits &= bits - 1;
1059
+ }
1060
+ if (prev < 8)
1061
+ s += 8 - prev;
1062
+ if (rank)
1063
+ s += "/";
1064
+ }
1065
+ const m = this.words, rights = byte(m, 71), ep = byte(m, 72);
1066
+ let castle = "";
1067
+ for (let i = 0; i < 4; i++)
1068
+ if (rights & (1 << i)) {
1069
+ const c = i < 2 ? 1 : 0, rook = byte(w, 66 + i), h = c ? 0 : 1, shift = c ? 0 : 24;
1070
+ const rankRooks = ((w[R + h] & w[O + c * 2 + h]) >>> shift) & 255;
1071
+ const outer = i % 2 ? 31 - Math.clz32(rankRooks & -rankRooks) : 31 - Math.clz32(rankRooks);
1072
+ castle += outer !== (rook & 7) ? String.fromCharCode((c ? 65 : 97) + (rook & 7)) : "KQkq"[i];
1073
+ }
1074
+ const alg = ep === 255 ? "-" : String.fromCharCode(97 + (ep & 7), 49 + (ep >>> 3));
1075
+ return s + " " + (this.turn ? "w" : "b") + " " + (castle || "-") + " " + alg + " " + this.halfmove + " " + this.fullmove;
1076
+ }
1077
+ }