gigachess 0.2.1 → 0.3.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.
package/dist/chess.js CHANGED
@@ -20,11 +20,15 @@ import { opposite, squareFile, squareRank, parseSquare, squareName } from "./uti
20
20
  import { zobristTablesLoaded, zobristAfterMove, calculateZobrist, zobristHex } from "./zobrist.js";
21
21
  import { parseFen, makeFen } from "./fen.js";
22
22
  import { parseSan, makeSan, parseUci, makeUci } from "./san.js";
23
- import { packOf, packedToMoves } from "./packedMove.js";
23
+ import { packOf, packedToMoves, PROMO_NONE, PROMO_KNIGHT, PROMO_BISHOP, PROMO_ROOK, PROMO_QUEEN, } from "./packedMove.js";
24
24
  import { build as buildTreeWrapper, pgnImport as pgnImportData } from "./chesstree.js";
25
25
  import { pieceAt } from "./board.js";
26
+ import { CASTLE_WK, CASTLE_WQ, CASTLE_BK, CASTLE_BQ, CASTLE_CLEAR_STD, CASTLING_RIGHTS_TABLE, PLAN_WHITE_K, PLAN_WHITE_Q, PLAN_BLACK_K, PLAN_BLACK_Q, getCastlingMask, CASTLE_PATH_LO, CASTLE_PATH_HI, CASTLE_TRAVERSAL_WHITE, CASTLE_TRAVERSAL_BLACK, } from "./castling.js";
26
27
  // helpers
27
28
  export function isCheck(pos) {
29
+ if (pos.checkers !== undefined) {
30
+ return ((pos.checkers.lo | pos.checkers.hi) !== 0);
31
+ }
28
32
  const ksq = board.kingSquare(pos.board, pos.turn);
29
33
  if (ksq === undefined)
30
34
  return false;
@@ -163,6 +167,58 @@ function planForDest(plans, to) {
163
167
  * opponent) held castling rights (root cause of the perft parity defect).
164
168
  */
165
169
  export function detectCastling(pos, from, to) {
170
+ if (!pos.isChess960) {
171
+ const mask = pos.castlingMask ?? getCastlingMask(pos);
172
+ if (mask === 0)
173
+ return null;
174
+ if (pos.turn === Color.White) {
175
+ if ((mask & (CASTLE_WK | CASTLE_WQ)) === 0 || from !== 4)
176
+ return null;
177
+ if (to === 7 || to === 6) {
178
+ if ((mask & CASTLE_WK) === 0)
179
+ return null;
180
+ if (to === 6 && board.pieceAt(pos.board, 6))
181
+ return null;
182
+ const rp = board.pieceAt(pos.board, 7);
183
+ if (rp && rp.color === Color.White && rp.role === Role.Rook)
184
+ return PLAN_WHITE_K;
185
+ }
186
+ else if (to === 0 || to === 2) {
187
+ if ((mask & CASTLE_WQ) === 0)
188
+ return null;
189
+ if (to === 2 && board.pieceAt(pos.board, 2))
190
+ return null;
191
+ const rp = board.pieceAt(pos.board, 0);
192
+ if (rp && rp.color === Color.White && rp.role === Role.Rook)
193
+ return PLAN_WHITE_Q;
194
+ }
195
+ return null;
196
+ }
197
+ else {
198
+ if ((mask & (CASTLE_BK | CASTLE_BQ)) === 0 || from !== 60)
199
+ return null;
200
+ if (to === 63 || to === 62) {
201
+ if ((mask & CASTLE_BK) === 0)
202
+ return null;
203
+ if (to === 62 && board.pieceAt(pos.board, 62))
204
+ return null;
205
+ const rp = board.pieceAt(pos.board, 63);
206
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook)
207
+ return PLAN_BLACK_K;
208
+ }
209
+ else if (to === 56 || to === 58) {
210
+ if ((mask & CASTLE_BQ) === 0)
211
+ return null;
212
+ if (to === 58 && board.pieceAt(pos.board, 58))
213
+ return null;
214
+ const rp = board.pieceAt(pos.board, 56);
215
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook)
216
+ return PLAN_BLACK_Q;
217
+ }
218
+ return null;
219
+ }
220
+ }
221
+ // Chess960 fallback
166
222
  if (pos.castling.white.size === 0 && pos.castling.black.size === 0)
167
223
  return null;
168
224
  const piece = board.pieceAt(pos.board, from);
@@ -296,63 +352,68 @@ export function makeMove(pos, move) {
296
352
  applyBoardEdits(nb, pos, from, to, move.to, piece, isEnPassant, plan, isPromotion, move.promotion ?? null, captured);
297
353
  // handle promotion: pawn must promote if reaching back rank
298
354
  // Already handled via move.promotion
299
- // update castling rights — copy a Set ONLY when it actually changes; the
300
- // common case (rights unchanged) shares the existing Set reference. This
301
- // structural sharing is part of the public contract (ADR-012 §4): the
302
- // library never mutates these sets, and the public CastlingRights type
303
- // exposes ReadonlySet so callers cannot mutate shared sub-objects through
304
- // the API either.
305
- let newWhite = pos.castling.white;
306
- let newBlack = pos.castling.black;
307
- // if king moves, remove all rights for that color — a fresh empty set; no
308
- // copy of the old one is needed
309
- if (piece.role === Role.King) {
310
- if (pos.turn === Color.White) {
311
- if (newWhite.size > 0)
312
- newWhite = new Set();
313
- }
314
- else {
315
- if (newBlack.size > 0)
316
- newBlack = new Set();
317
- }
355
+ // update castling rights — standard chess uses 4-bit integer mask and O(1) table lookup
356
+ let newCastling;
357
+ let newMask;
358
+ if (!pos.isChess960) {
359
+ const mask = pos.castlingMask ?? getCastlingMask(pos);
360
+ newMask = (mask & CASTLE_CLEAR_STD[from] & CASTLE_CLEAR_STD[to]) >>> 0;
361
+ newCastling = CASTLING_RIGHTS_TABLE[newMask];
318
362
  }
319
- // if rook moves from origin, remove that right (clone → delete on the
320
- // owned copy — never on the input's set)
321
- if (piece.role === Role.Rook) {
322
- if (pos.turn === Color.White) {
323
- if (newWhite.has(from)) {
324
- const next = new Set(newWhite);
325
- next.delete(from);
326
- newWhite = next;
363
+ else {
364
+ let newWhite = pos.castling.white;
365
+ let newBlack = pos.castling.black;
366
+ if (piece.role === Role.King) {
367
+ if (pos.turn === Color.White) {
368
+ if (newWhite.size > 0)
369
+ newWhite = new Set();
327
370
  }
328
- }
329
- else {
330
- if (newBlack.has(from)) {
331
- const next = new Set(newBlack);
332
- next.delete(from);
333
- newBlack = next;
371
+ else {
372
+ if (newBlack.size > 0)
373
+ newBlack = new Set();
334
374
  }
335
375
  }
336
- }
337
- // if rook captured on origin, remove opponent right
338
- if (captured && captured.role === Role.Rook) {
339
- if (captured.color === Color.White) {
340
- if (newWhite.has(to)) {
341
- const next = new Set(newWhite);
342
- next.delete(to);
343
- newWhite = next;
376
+ if (piece.role === Role.Rook) {
377
+ if (pos.turn === Color.White) {
378
+ if (newWhite.has(from)) {
379
+ const next = new Set(newWhite);
380
+ next.delete(from);
381
+ newWhite = next;
382
+ }
383
+ }
384
+ else {
385
+ if (newBlack.has(from)) {
386
+ const next = new Set(newBlack);
387
+ next.delete(from);
388
+ newBlack = next;
389
+ }
344
390
  }
345
391
  }
346
- else {
347
- if (newBlack.has(to)) {
348
- const next = new Set(newBlack);
349
- next.delete(to);
350
- newBlack = next;
392
+ if (captured && captured.role === Role.Rook) {
393
+ if (captured.color === Color.White) {
394
+ if (newWhite.has(to)) {
395
+ const next = new Set(newWhite);
396
+ next.delete(to);
397
+ newWhite = next;
398
+ }
399
+ }
400
+ else {
401
+ if (newBlack.has(to)) {
402
+ const next = new Set(newBlack);
403
+ next.delete(to);
404
+ newBlack = next;
405
+ }
351
406
  }
352
407
  }
408
+ newCastling = {
409
+ white: newWhite,
410
+ black: newBlack,
411
+ whiteKing: newWhite.has(7),
412
+ whiteQueen: newWhite.has(0),
413
+ blackKing: newBlack.has(63),
414
+ blackQueen: newBlack.has(56),
415
+ };
353
416
  }
354
- // en passant capture already handled (captured pawn not rook, so no)
355
- // if rook moved in castling, its origin already removed, but rook destination not relevant
356
417
  // en passant square for next position
357
418
  let newEp = null;
358
419
  if (piece.role === Role.Pawn && Math.abs(squareRank(to) - squareRank(from)) === 2) {
@@ -367,23 +428,27 @@ export function makeMove(pos, move) {
367
428
  // fullmove
368
429
  const newFull = pos.turn === Color.Black ? (pos.fullmoves ?? pos.fullmove ?? 1) + 1 : (pos.fullmoves ?? pos.fullmove ?? 1);
369
430
  const newTurn = opposite(pos.turn);
370
- const newCastling = {
371
- white: newWhite,
372
- black: newBlack,
373
- whiteKing: newWhite.has(7),
374
- whiteQueen: newWhite.has(0),
375
- blackKing: newBlack.has(63),
376
- blackQueen: newBlack.has(56),
377
- };
431
+ const nextKingSq = pos.kingSq
432
+ ? [pos.kingSq[0], pos.kingSq[1]]
433
+ : [board.kingSquare(pos.board, Color.White) ?? -1, board.kingSquare(pos.board, Color.Black) ?? -1];
434
+ if (piece.role === Role.King) {
435
+ nextKingSq[pos.turn] = to;
436
+ }
437
+ nb.kingSq = nextKingSq;
438
+ const newCheckers = attacks.kingAttackers(nb, newTurn);
378
439
  const newPos = {
379
440
  board: nb,
380
441
  turn: newTurn,
381
442
  castling: newCastling,
443
+ castlingMask: newMask,
444
+ isChess960: pos.isChess960 ?? false,
382
445
  epSquare: newEp,
383
446
  halfmoves: newHalf,
384
447
  fullmoves: newFull,
385
448
  halfmove: newHalf,
386
449
  fullmove: newFull,
450
+ kingSq: nextKingSq,
451
+ checkers: newCheckers,
387
452
  };
388
453
  // Incremental O(1) Zobrist maintenance (design D2). Skipped (positions
389
454
  // carry no zobrist fields) until the Polyglot key tables have loaded via
@@ -400,59 +465,96 @@ export function makeMove(pos, move) {
400
465
  // alias play
401
466
  export const play = makeMove;
402
467
  // ---------- pseudo-legal generation ----------
403
- function pawnPseudoDests(pos, from, color) {
404
- // color passed in (genPseudoDests already looked the piece up) and target
405
- // occupancy tested with raw set membership — zero allocations per target.
406
- const dir = color === Color.White ? 1 : -1;
407
- const rank = squareRank(from);
408
- const file = squareFile(from);
468
+ const P_W_P = { color: Color.White, role: Role.Pawn };
469
+ const P_W_N = { color: Color.White, role: Role.Knight };
470
+ const P_W_B = { color: Color.White, role: Role.Bishop };
471
+ const P_W_R = { color: Color.White, role: Role.Rook };
472
+ const P_W_Q = { color: Color.White, role: Role.Queen };
473
+ const P_W_K = { color: Color.White, role: Role.King };
474
+ const P_B_P = { color: Color.Black, role: Role.Pawn };
475
+ const P_B_N = { color: Color.Black, role: Role.Knight };
476
+ const P_B_B = { color: Color.Black, role: Role.Bishop };
477
+ const P_B_R = { color: Color.Black, role: Role.Rook };
478
+ const P_B_Q = { color: Color.Black, role: Role.Queen };
479
+ const P_B_K = { color: Color.Black, role: Role.King };
480
+ function whitePawnPseudoDests(pos, from) {
409
481
  const occ = pos.board.occupied;
410
- const whiteOcc = pos.board.white;
411
- const isWhite = color === Color.White;
482
+ const them = pos.board.black;
412
483
  let lo = 0, hi = 0;
413
- const add = (sqIdx) => {
414
- if (sqIdx < 32)
415
- lo |= (1 << sqIdx) >>> 0;
484
+ const to1 = from + 8;
485
+ if (!sq.has(occ, to1)) {
486
+ if (to1 < 32)
487
+ lo |= (1 << to1) >>> 0;
416
488
  else
417
- hi |= (1 << (sqIdx - 32)) >>> 0;
418
- };
419
- // forward one
420
- const oneRank = rank + dir;
421
- if (oneRank >= 0 && oneRank < 8) {
422
- const oneSq = oneRank * 8 + file;
423
- if (!sq.has(occ, oneSq)) {
424
- add(oneSq);
425
- // double from starting rank
426
- const startRank = color === Color.White ? 1 : 6;
427
- if (rank === startRank) {
428
- const twoRank = rank + dir * 2;
429
- const twoSq = twoRank * 8 + file;
430
- if (!sq.has(occ, twoSq))
431
- add(twoSq);
489
+ hi |= (1 << (to1 - 32)) >>> 0;
490
+ if (from >= 8 && from <= 15) {
491
+ const to2 = from + 16;
492
+ if (!sq.has(occ, to2)) {
493
+ lo |= (1 << to2) >>> 0;
432
494
  }
433
495
  }
434
496
  }
435
- // captures
436
- for (const df of [-1, 1]) {
437
- const nf = file + df;
438
- const nr = rank + dir;
439
- if (nf < 0 || nf >= 8 || nr < 0 || nr >= 8)
440
- continue;
441
- const capSq = nr * 8 + nf;
442
- if (sq.has(occ, capSq)) {
443
- // target color via color-occupancy membership instead of pieceAt object
444
- if (sq.has(whiteOcc, capSq) !== isWhite)
445
- add(capSq);
497
+ const f = from & 7;
498
+ if (f > 0) {
499
+ const capL = from + 7;
500
+ if (sq.has(them, capL) || pos.epSquare === capL) {
501
+ if (capL < 32)
502
+ lo |= (1 << capL) >>> 0;
503
+ else
504
+ hi |= (1 << (capL - 32)) >>> 0;
505
+ }
506
+ }
507
+ if (f < 7) {
508
+ const capR = from + 9;
509
+ if (sq.has(them, capR) || pos.epSquare === capR) {
510
+ if (capR < 32)
511
+ lo |= (1 << capR) >>> 0;
512
+ else
513
+ hi |= (1 << (capR - 32)) >>> 0;
514
+ }
515
+ }
516
+ return { lo: lo >>> 0, hi: hi >>> 0 };
517
+ }
518
+ function blackPawnPseudoDests(pos, from) {
519
+ const occ = pos.board.occupied;
520
+ const them = pos.board.white;
521
+ let lo = 0, hi = 0;
522
+ const to1 = from - 8;
523
+ if (!sq.has(occ, to1)) {
524
+ if (to1 < 32)
525
+ lo |= (1 << to1) >>> 0;
526
+ else
527
+ hi |= (1 << (to1 - 32)) >>> 0;
528
+ if (from >= 48 && from <= 55) {
529
+ const to2 = from - 16;
530
+ if (!sq.has(occ, to2)) {
531
+ hi |= (1 << (to2 - 32)) >>> 0;
532
+ }
446
533
  }
447
- else if (pos.epSquare !== null && capSq === pos.epSquare) {
448
- // en passant capture destination is epSquare, which is empty but capturable
449
- add(capSq);
534
+ }
535
+ const f = from & 7;
536
+ if (f > 0) {
537
+ const capL = from - 9;
538
+ if (sq.has(them, capL) || pos.epSquare === capL) {
539
+ if (capL < 32)
540
+ lo |= (1 << capL) >>> 0;
541
+ else
542
+ hi |= (1 << (capL - 32)) >>> 0;
543
+ }
544
+ }
545
+ if (f < 7) {
546
+ const capR = from - 7;
547
+ if (sq.has(them, capR) || pos.epSquare === capR) {
548
+ if (capR < 32)
549
+ lo |= (1 << capR) >>> 0;
550
+ else
551
+ hi |= (1 << (capR - 32)) >>> 0;
450
552
  }
451
553
  }
452
554
  return { lo: lo >>> 0, hi: hi >>> 0 };
453
555
  }
454
- function genPseudoDests(pos, from) {
455
- const p = board.pieceAt(pos.board, from);
556
+ function genPseudoDests(pos, from, piece) {
557
+ const p = piece ?? board.pieceAt(pos.board, from);
456
558
  if (!p || p.color !== pos.turn)
457
559
  return sq.empty();
458
560
  const occ = pos.board.occupied;
@@ -460,7 +562,7 @@ function genPseudoDests(pos, from) {
460
562
  let pseudo;
461
563
  switch (p.role) {
462
564
  case Role.Pawn:
463
- pseudo = pawnPseudoDests(pos, from, p.color);
565
+ pseudo = p.color === Color.White ? whitePawnPseudoDests(pos, from) : blackPawnPseudoDests(pos, from);
464
566
  break;
465
567
  case Role.Knight:
466
568
  pseudo = attacks.knightAttacks(from);
@@ -486,76 +588,102 @@ function genPseudoDests(pos, from) {
486
588
  // `from` IS this color's king square by definition (invariant: exactly
487
589
  // one king per color), so no kingSquare lookup is needed here.
488
590
  // Conditions to add castling dest: rights exist, between empty, not in check, traversal not attacked
489
- if (p.color === Color.White) {
490
- // white castling
491
- // king-side to G1 (6)
492
- if (pos.castling.white.size > 0) {
493
- // find rook(s) for each side, check conditions
494
- // We'll check each rook square in white set
495
- for (const rs of pos.castling.white) {
496
- // The right's rook must actually be on its origin square (guards
497
- // against stale rights in hand-written FENs).
498
- const rp = board.pieceAt(pos.board, rs);
499
- if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
500
- continue;
501
- const rookFile = squareFile(rs);
502
- const kingFile = squareFile(ks);
503
- const isKingSide = rookFile > kingFile;
504
- const dest = rs; // king-captures-rook (ADR-013 as amended)
505
- // Only generate dest once per side, but if multiple rooks on same side? For now handle
506
- // Check between empty
507
- const between = attacks.between(ks, rs);
508
- if (!sq.isEmpty(sq.and(between, occ)))
509
- continue;
510
- // Also need squares between king and dest empty? That's subset of between check? For queen-side, dest C1 is between, but need B1 also empty? Between already covers B1-D1 etc, so ok
511
- // Check king not in check
512
- if (isCheck(pos))
513
- continue;
514
- // Check traversal squares not attacked
515
- const traversal = isKingSide ? [5, 6] : [3, 2]; // F1,G1 or D1,C1
516
- let attacked = false;
517
- for (const t of traversal) {
518
- if (attacks.isAttacked(pos.board, t, Color.Black)) {
519
- attacked = true;
520
- break;
591
+ if (!pos.isChess960) {
592
+ const mask = pos.castlingMask ?? getCastlingMask(pos);
593
+ if (p.color === Color.White) {
594
+ if (ks === 4 && (mask & (CASTLE_WK | CASTLE_WQ)) !== 0 && !isCheck(pos)) {
595
+ const occLo = occ.lo;
596
+ if ((mask & CASTLE_WK) !== 0 && (occLo & 0x60) === 0) {
597
+ const rp = board.pieceAt(pos.board, 7);
598
+ if (rp && rp.color === Color.White && rp.role === Role.Rook) {
599
+ if (!attacks.isAttacked(pos.board, 5, Color.Black) && !attacks.isAttacked(pos.board, 6, Color.Black)) {
600
+ pseudo = sq.or(pseudo, sq.singleton(7));
601
+ }
602
+ }
603
+ }
604
+ if ((mask & CASTLE_WQ) !== 0 && (occLo & 0x0E) === 0) {
605
+ const rp = board.pieceAt(pos.board, 0);
606
+ if (rp && rp.color === Color.White && rp.role === Role.Rook) {
607
+ if (!attacks.isAttacked(pos.board, 3, Color.Black) && !attacks.isAttacked(pos.board, 2, Color.Black)) {
608
+ pseudo = sq.or(pseudo, sq.singleton(0));
609
+ }
610
+ }
611
+ }
612
+ }
613
+ }
614
+ else {
615
+ if (ks === 60 && (mask & (CASTLE_BK | CASTLE_BQ)) !== 0 && !isCheck(pos)) {
616
+ const occHi = occ.hi;
617
+ if ((mask & CASTLE_BK) !== 0 && (occHi & 0x60000000) === 0) {
618
+ const rp = board.pieceAt(pos.board, 63);
619
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook) {
620
+ if (!attacks.isAttacked(pos.board, 61, Color.White) && !attacks.isAttacked(pos.board, 62, Color.White)) {
621
+ pseudo = sq.or(pseudo, sq.singleton(63));
622
+ }
623
+ }
624
+ }
625
+ if ((mask & CASTLE_BQ) !== 0 && (occHi & 0x0E000000) === 0) {
626
+ const rp = board.pieceAt(pos.board, 56);
627
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook) {
628
+ if (!attacks.isAttacked(pos.board, 59, Color.White) && !attacks.isAttacked(pos.board, 58, Color.White)) {
629
+ pseudo = sq.or(pseudo, sq.singleton(56));
630
+ }
521
631
  }
522
632
  }
523
- if (attacked)
524
- continue;
525
- // Also need dest not occupied by own? already filtered via own? But G1/C1 between empty ensures not occupied, but check if dest is occupied by opponent capture? Castling destination should be empty, but could be rook capture? No, destination must be empty per between check. For queen-side, B1 may be occupied but dest C1 must be empty; between includes B1,C1,D1, so if B1 occupied, fails. So okay.
526
- // Add dest
527
- const bit = sq.singleton(dest);
528
- pseudo = sq.or(pseudo, bit);
529
633
  }
530
634
  }
531
635
  }
532
- else if (p.color === Color.Black) {
533
- for (const rs of pos.castling.black) {
534
- // The right's rook must actually be on its origin square (guards
535
- // against stale rights in hand-written FENs).
536
- const rp = board.pieceAt(pos.board, rs);
537
- if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
538
- continue;
539
- const rookFile = squareFile(rs);
540
- const kingFile = squareFile(ks);
541
- const isKingSide = rookFile > kingFile;
542
- const dest = rs; // king-captures-rook (ADR-013 as amended)
543
- const between = attacks.between(ks, rs);
544
- if (!sq.isEmpty(sq.and(between, occ)))
545
- continue;
546
- if (isCheck(pos))
547
- continue;
548
- const traversal = isKingSide ? [61, 62] : [59, 58];
549
- let attacked = false;
550
- for (const t of traversal) {
551
- if (attacks.isAttacked(pos.board, t, Color.White)) {
552
- attacked = true;
553
- break;
636
+ else {
637
+ // Chess960 fallback using precomputed CASTLE_PATH and traversal tables
638
+ if (p.color === Color.White) {
639
+ if (pos.castling.white.size > 0 && !isCheck(pos)) {
640
+ const kingFile = ks & 7;
641
+ for (const rs of pos.castling.white) {
642
+ const rp = board.pieceAt(pos.board, rs);
643
+ if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
644
+ continue;
645
+ const rookFile = rs & 7;
646
+ const idx = (kingFile << 3) | rookFile;
647
+ if (((CASTLE_PATH_LO[idx] & occ.lo) | (CASTLE_PATH_HI[idx] & occ.hi)) !== 0)
648
+ continue;
649
+ const trav = CASTLE_TRAVERSAL_WHITE[idx];
650
+ let attacked = false;
651
+ for (let ti = 0; ti < trav.length; ti++) {
652
+ if (attacks.isAttacked(pos.board, trav[ti], Color.Black)) {
653
+ attacked = true;
654
+ break;
655
+ }
656
+ }
657
+ if (attacked)
658
+ continue;
659
+ pseudo = sq.or(pseudo, sq.singleton(rs));
660
+ }
661
+ }
662
+ }
663
+ else {
664
+ if (pos.castling.black.size > 0 && !isCheck(pos)) {
665
+ const kingFile = ks & 7;
666
+ for (const rs of pos.castling.black) {
667
+ const rp = board.pieceAt(pos.board, rs);
668
+ if (!rp || rp.color !== p.color || rp.role !== Role.Rook)
669
+ continue;
670
+ const rookFile = rs & 7;
671
+ const idx = 64 | (kingFile << 3) | rookFile;
672
+ if (((CASTLE_PATH_LO[idx] & occ.lo) | (CASTLE_PATH_HI[idx] & occ.hi)) !== 0)
673
+ continue;
674
+ const trav = CASTLE_TRAVERSAL_BLACK[idx & 63];
675
+ let attacked = false;
676
+ for (let ti = 0; ti < trav.length; ti++) {
677
+ if (attacks.isAttacked(pos.board, trav[ti], Color.White)) {
678
+ attacked = true;
679
+ break;
680
+ }
681
+ }
682
+ if (attacked)
683
+ continue;
684
+ pseudo = sq.or(pseudo, sq.singleton(rs));
554
685
  }
555
686
  }
556
- if (attacked)
557
- continue;
558
- pseudo = sq.or(pseudo, sq.singleton(dest));
559
687
  }
560
688
  }
561
689
  break;
@@ -594,11 +722,6 @@ isPromotion, promotion) {
594
722
  return false;
595
723
  return !attacks.isAttacked(destScratch, ksq, opposite(pos.turn));
596
724
  }
597
- // Module-level scratch, sanctioned by the FP policy for hot loops: owned by
598
- // analyzeCheckContext (a leaf — no re-entrant movegen runs while a context is
599
- // live within one dests/allDests/genLegalMoves call) and cleared before every
600
- // use. Never escapes the enclosing call.
601
- const scratchPinRays = new Map();
602
725
  // Reused castling plan scratch (same ownership discipline): avoids allocating
603
726
  // two plan objects per analyzed position in the perft/movegen hot loop. The
604
727
  // referenced position data is read-only and consumed within the same call.
@@ -608,37 +731,64 @@ const scratchCastlingPlanB = { side: "king", kingFrom: 0, kingTo: 0, rookFrom: 0
608
731
  export function analyzeCheckContext(pos) {
609
732
  const us = pos.turn;
610
733
  const them = opposite(us);
611
- scratchPinRays.clear();
612
734
  const ksq = board.kingSquare(pos.board, us);
613
735
  if (ksq === undefined) {
614
736
  // degenerate (kingless) position: no pins, no masks
615
- return { us, ksq: -1, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinRays: scratchPinRays, castlingPlans: [] };
737
+ return { us, ksq: -1, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinned: sq.EMPTY, castlingPlans: [] };
616
738
  }
617
- const ctx = { us, ksq, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinRays: scratchPinRays, castlingPlans: [] };
739
+ const ctx = { us, ksq, doubleCheck: false, checkMask: sq.FULL, kingSafe: sq.EMPTY, pinned: sq.EMPTY, castlingPlans: [] };
618
740
  // Precompute the position's castling plans once (design D2): the hot loops
619
741
  // (destsFast king branch, genLegalMoves) look them up instead of re-running
620
742
  // the full detectCastling per king move. Plans are written into the reused
621
743
  // scratch array — no allocation in the hot loop.
622
744
  ctx.castlingPlans = scratchCastlingPlans;
623
745
  ctx.castlingPlans.length = 0;
624
- const rights = us === Color.White ? pos.castling.white : pos.castling.black;
625
- if (rights.size > 0) {
626
- for (const rs of rights) {
627
- const rp = board.pieceAt(pos.board, rs);
628
- if (rp && rp.color === us && rp.role === Role.Rook) {
629
- // write into the preallocated scratch slots — no hot-loop allocation
630
- const slot = ctx.castlingPlans.length === 0 ? scratchCastlingPlanA : scratchCastlingPlanB;
631
- const next = castlingPlanFor(us, ksq, rs);
632
- slot.side = next.side;
633
- slot.kingFrom = next.kingFrom;
634
- slot.kingTo = next.kingTo;
635
- slot.rookFrom = next.rookFrom;
636
- slot.rookTo = next.rookTo;
637
- ctx.castlingPlans.push(slot);
746
+ if (!pos.isChess960) {
747
+ const mask = pos.castlingMask ?? getCastlingMask(pos);
748
+ if (us === Color.White) {
749
+ if ((mask & CASTLE_WK) !== 0 && ksq === 4) {
750
+ const rp = board.pieceAt(pos.board, 7);
751
+ if (rp && rp.color === Color.White && rp.role === Role.Rook)
752
+ ctx.castlingPlans.push(PLAN_WHITE_K);
753
+ }
754
+ if ((mask & CASTLE_WQ) !== 0 && ksq === 4) {
755
+ const rp = board.pieceAt(pos.board, 0);
756
+ if (rp && rp.color === Color.White && rp.role === Role.Rook)
757
+ ctx.castlingPlans.push(PLAN_WHITE_Q);
758
+ }
759
+ }
760
+ else {
761
+ if ((mask & CASTLE_BK) !== 0 && ksq === 60) {
762
+ const rp = board.pieceAt(pos.board, 63);
763
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook)
764
+ ctx.castlingPlans.push(PLAN_BLACK_K);
765
+ }
766
+ if ((mask & CASTLE_BQ) !== 0 && ksq === 60) {
767
+ const rp = board.pieceAt(pos.board, 56);
768
+ if (rp && rp.color === Color.Black && rp.role === Role.Rook)
769
+ ctx.castlingPlans.push(PLAN_BLACK_Q);
638
770
  }
639
771
  }
640
772
  }
641
- const checkers = attacks.kingAttackers(pos.board, us);
773
+ else {
774
+ const rights = us === Color.White ? pos.castling.white : pos.castling.black;
775
+ if (rights.size > 0) {
776
+ for (const rs of rights) {
777
+ const rp = board.pieceAt(pos.board, rs);
778
+ if (rp && rp.color === us && rp.role === Role.Rook) {
779
+ const slot = ctx.castlingPlans.length === 0 ? scratchCastlingPlanA : scratchCastlingPlanB;
780
+ const next = castlingPlanFor(us, ksq, rs);
781
+ slot.side = next.side;
782
+ slot.kingFrom = next.kingFrom;
783
+ slot.kingTo = next.kingTo;
784
+ slot.rookFrom = next.rookFrom;
785
+ slot.rookTo = next.rookTo;
786
+ ctx.castlingPlans.push(slot);
787
+ }
788
+ }
789
+ }
790
+ }
791
+ const checkers = pos.checkers ?? attacks.kingAttackers(pos.board, us);
642
792
  const nCheckers = sq.popcount(checkers);
643
793
  if (nCheckers === 1) {
644
794
  const c = sq.first(checkers);
@@ -654,16 +804,45 @@ export function analyzeCheckContext(pos) {
654
804
  const themRQ = sq.or(sq.and(themOcc, pos.board.rook), sq.and(themOcc, pos.board.queen));
655
805
  const noOcc = sq.EMPTY;
656
806
  const snipers = sq.or(sq.and(themRQ, attacks.rookAttacks(ksq, noOcc)), sq.and(themBQ, attacks.bishopAttacks(ksq, noOcc)));
657
- for (const sniper of sq.iter(snipers)) {
807
+ let pinnedLo = 0, pinnedHi = 0;
808
+ let sLo = snipers.lo >>> 0, sHi = snipers.hi >>> 0;
809
+ while (sLo !== 0) {
810
+ const lsb = (sLo & -sLo) >>> 0;
811
+ const sniper = Math.clz32(lsb) ^ 31;
812
+ sLo = (sLo ^ lsb) >>> 0;
658
813
  const b = attacks.between(ksq, sniper);
659
- const blockers = sq.and(b, pos.board.occupied);
660
- if (sq.popcount(blockers) !== 1)
661
- continue;
662
- const blockerSq = sq.first(blockers);
663
- if (sq.has(themOcc, blockerSq))
664
- continue; // enemy blocker: not a pin
665
- scratchPinRays.set(blockerSq, sq.or(b, sq.singleton(sniper)));
814
+ const bLo = (b.lo & pos.board.occupied.lo) >>> 0;
815
+ const bHi = (b.hi & pos.board.occupied.hi) >>> 0;
816
+ const nBlockers = sq.popcount({ lo: bLo, hi: bHi });
817
+ if (nBlockers === 1) {
818
+ const blockerSq = bLo !== 0 ? (Math.clz32((bLo & -bLo) >>> 0) ^ 31) : (32 + (Math.clz32((bHi & -bHi) >>> 0) ^ 31));
819
+ if (!sq.has(themOcc, blockerSq)) {
820
+ if (blockerSq < 32)
821
+ pinnedLo |= (1 << blockerSq) >>> 0;
822
+ else
823
+ pinnedHi |= (1 << (blockerSq - 32)) >>> 0;
824
+ }
825
+ }
826
+ }
827
+ while (sHi !== 0) {
828
+ const lsb = (sHi & -sHi) >>> 0;
829
+ const sniper = 32 + (Math.clz32(lsb) ^ 31);
830
+ sHi = (sHi ^ lsb) >>> 0;
831
+ const b = attacks.between(ksq, sniper);
832
+ const bLo = (b.lo & pos.board.occupied.lo) >>> 0;
833
+ const bHi = (b.hi & pos.board.occupied.hi) >>> 0;
834
+ const nBlockers = sq.popcount({ lo: bLo, hi: bHi });
835
+ if (nBlockers === 1) {
836
+ const blockerSq = bLo !== 0 ? (Math.clz32((bLo & -bLo) >>> 0) ^ 31) : (32 + (Math.clz32((bHi & -bHi) >>> 0) ^ 31));
837
+ if (!sq.has(themOcc, blockerSq)) {
838
+ if (blockerSq < 32)
839
+ pinnedLo |= (1 << blockerSq) >>> 0;
840
+ else
841
+ pinnedHi |= (1 << (blockerSq - 32)) >>> 0;
842
+ }
843
+ }
666
844
  }
845
+ ctx.pinned = { lo: pinnedLo >>> 0, hi: pinnedHi >>> 0 };
667
846
  // King-safe mask: attackedness evaluated with our king removed from the
668
847
  // occupancy, so sliders x-raying the king keep it attacked on the far side.
669
848
  const occWithoutKing = sq.minus(pos.board.occupied, sq.singleton(ksq));
@@ -687,7 +866,7 @@ export function analyzeCheckContext(pos) {
687
866
  * pure set intersection for all cases except the trap cases listed above.
688
867
  */
689
868
  export function destsFast(pos, from, piece, ctx) {
690
- const pseudo = genPseudoDests(pos, from);
869
+ const pseudo = genPseudoDests(pos, from, piece);
691
870
  if (sq.isEmpty(pseudo))
692
871
  return pseudo;
693
872
  if (piece.role === Role.King) {
@@ -732,9 +911,13 @@ export function destsFast(pos, from, piece, ctx) {
732
911
  epLegal = moveLeavesKingSafe(pos, piece, from, epSquare, epSquare, true, null, false, null);
733
912
  }
734
913
  let result = sq.and(nonEp, ctx.checkMask);
735
- const pin = ctx.pinRays.get(from);
736
- if (pin)
737
- result = sq.and(result, pin);
914
+ if (sq.has(ctx.pinned, from)) {
915
+ const pIdx = (ctx.ksq << 6) | from;
916
+ result = {
917
+ lo: (result.lo & attacks.LINE_RAY_LO[pIdx]) >>> 0,
918
+ hi: (result.hi & attacks.LINE_RAY_HI[pIdx]) >>> 0,
919
+ };
920
+ }
738
921
  if (epLegal && epSquare !== null)
739
922
  result = sq.or(result, sq.singleton(epSquare));
740
923
  return result;
@@ -748,15 +931,30 @@ export function dests(pos, from) {
748
931
  export function allDests(pos) {
749
932
  const m = new Map();
750
933
  const ctx = analyzeCheckContext(pos);
751
- const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
752
- sq.forEachSquare(own, (sqIdx) => {
753
- const piece = board.pieceAt(pos.board, sqIdx);
754
- if (!piece)
755
- return;
756
- const d = destsFast(pos, sqIdx, piece, ctx);
934
+ const isWhite = pos.turn === Color.White;
935
+ const own = isWhite ? pos.board.white : pos.board.black;
936
+ // 1. King
937
+ const ksq = ctx.ksq;
938
+ if (ksq >= 0) {
939
+ const kingPiece = isWhite ? P_W_K : P_B_K;
940
+ const d = destsFast(pos, ksq, kingPiece, ctx);
757
941
  if (!sq.isEmpty(d))
758
- m.set(sqIdx, d);
759
- });
942
+ m.set(ksq, d);
943
+ }
944
+ if (ctx.doubleCheck)
945
+ return m;
946
+ const addRole = (roleBB, piece) => {
947
+ sq.forEachSquare(sq.and(own, roleBB), (sqIdx) => {
948
+ const d = destsFast(pos, sqIdx, piece, ctx);
949
+ if (!sq.isEmpty(d))
950
+ m.set(sqIdx, d);
951
+ });
952
+ };
953
+ addRole(pos.board.pawn, isWhite ? P_W_P : P_B_P);
954
+ addRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
955
+ addRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
956
+ addRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
957
+ addRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
760
958
  return m;
761
959
  }
762
960
  export function isLegal(pos, move) {
@@ -784,9 +982,35 @@ export function isLegal(pos, move) {
784
982
  }
785
983
  // helpers for checkmate/stalemate
786
984
  function hasAnyLegalMove(pos) {
985
+ const ctx = analyzeCheckContext(pos);
986
+ const ksq = ctx.ksq;
987
+ if (ksq >= 0) {
988
+ const kd = destsFast(pos, ksq, { color: pos.turn, role: Role.King }, ctx);
989
+ if (!sq.isEmpty(kd))
990
+ return true;
991
+ }
992
+ if (ctx.doubleCheck)
993
+ return false;
787
994
  const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
788
- for (const from of sq.iter(own)) {
789
- const d = dests(pos, from);
995
+ let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
996
+ while (ownLo !== 0 || ownHi !== 0) {
997
+ let from;
998
+ if (ownLo !== 0) {
999
+ const lsb = (ownLo & -ownLo) >>> 0;
1000
+ from = Math.clz32(lsb) ^ 31;
1001
+ ownLo = (ownLo ^ lsb) >>> 0;
1002
+ }
1003
+ else {
1004
+ const lsb = (ownHi & -ownHi) >>> 0;
1005
+ from = 32 + (Math.clz32(lsb) ^ 31);
1006
+ ownHi = (ownHi ^ lsb) >>> 0;
1007
+ }
1008
+ if (from === ksq)
1009
+ continue;
1010
+ const piece = board.pieceAt(pos.board, from);
1011
+ if (!piece)
1012
+ continue;
1013
+ const d = destsFast(pos, from, piece, ctx);
790
1014
  if (!sq.isEmpty(d))
791
1015
  return true;
792
1016
  }
@@ -813,141 +1037,391 @@ export function perft(pos, depth) {
813
1037
  }
814
1038
  return nodes;
815
1039
  }
816
- function countLegalMoves(pos) {
1040
+ export class MoveCounter {
1041
+ constructor() {
1042
+ this.count = 0;
1043
+ }
1044
+ add(set) {
1045
+ this.count += sq.popcount(set);
1046
+ }
1047
+ addPawns(legal, isWhite) {
1048
+ const total = sq.popcount(legal);
1049
+ const promos = isWhite
1050
+ ? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
1051
+ : sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
1052
+ this.count += total + promos * 3;
1053
+ }
1054
+ reset() {
1055
+ this.count = 0;
1056
+ }
1057
+ }
1058
+ export function countLegalMoves(pos) {
1059
+ const ctx = analyzeCheckContext(pos);
1060
+ const us = pos.turn;
1061
+ const isWhite = us === Color.White;
1062
+ const own = isWhite ? pos.board.white : pos.board.black;
1063
+ let count = 0;
1064
+ // 1. King
1065
+ const ksq = ctx.ksq;
1066
+ if (ksq >= 0) {
1067
+ const kingPiece = isWhite ? P_W_K : P_B_K;
1068
+ count += sq.popcount(destsFast(pos, ksq, kingPiece, ctx));
1069
+ }
1070
+ if (ctx.doubleCheck)
1071
+ return count;
1072
+ // 2. Pawns (bulk popcount without inner destination loops)
1073
+ const pawnPiece = isWhite ? P_W_P : P_B_P;
1074
+ let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
1075
+ let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
1076
+ while (pLo !== 0) {
1077
+ const lsb = (pLo & -pLo) >>> 0;
1078
+ const from = Math.clz32(lsb) ^ 31;
1079
+ pLo = (pLo ^ lsb) >>> 0;
1080
+ const legal = destsFast(pos, from, pawnPiece, ctx);
1081
+ const total = sq.popcount(legal);
1082
+ const promos = isWhite
1083
+ ? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
1084
+ : sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
1085
+ count += total + promos * 3;
1086
+ }
1087
+ while (pHi !== 0) {
1088
+ const lsb = (pHi & -pHi) >>> 0;
1089
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1090
+ pHi = (pHi ^ lsb) >>> 0;
1091
+ const legal = destsFast(pos, from, pawnPiece, ctx);
1092
+ const total = sq.popcount(legal);
1093
+ const promos = isWhite
1094
+ ? sq.popcount({ lo: 0, hi: (legal.hi & 0xff000000) >>> 0 })
1095
+ : sq.popcount({ lo: (legal.lo & 0x000000ff) >>> 0, hi: 0 });
1096
+ count += total + promos * 3;
1097
+ }
1098
+ // 3. Knights, Bishops, Rooks, Queens (bulk popcount on legal dests)
1099
+ const countPieces = (roleBB, piece) => {
1100
+ let rLo = (own.lo & roleBB.lo) >>> 0;
1101
+ let rHi = (own.hi & roleBB.hi) >>> 0;
1102
+ while (rLo !== 0) {
1103
+ const lsb = (rLo & -rLo) >>> 0;
1104
+ const from = Math.clz32(lsb) ^ 31;
1105
+ rLo = (rLo ^ lsb) >>> 0;
1106
+ count += sq.popcount(destsFast(pos, from, piece, ctx));
1107
+ }
1108
+ while (rHi !== 0) {
1109
+ const lsb = (rHi & -rHi) >>> 0;
1110
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1111
+ rHi = (rHi ^ lsb) >>> 0;
1112
+ count += sq.popcount(destsFast(pos, from, piece, ctx));
1113
+ }
1114
+ };
1115
+ countPieces(pos.board.knight, isWhite ? P_W_N : P_B_N);
1116
+ countPieces(pos.board.bishop, isWhite ? P_W_B : P_B_B);
1117
+ countPieces(pos.board.rook, isWhite ? P_W_R : P_B_R);
1118
+ countPieces(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
1119
+ return count;
1120
+ }
1121
+ export function legalMovesInto(pos, out) {
817
1122
  let count = 0;
818
1123
  const ctx = analyzeCheckContext(pos);
819
- const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
820
- const isWhite = pos.turn === Color.White;
821
- let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
822
- while (ownLo !== 0 || ownHi !== 0) {
823
- let from;
824
- if (ownLo !== 0) {
825
- const lsb = (ownLo & -ownLo) >>> 0;
826
- from = 31 - Math.clz32(lsb);
827
- ownLo ^= lsb;
1124
+ const us = pos.turn;
1125
+ const isWhite = us === Color.White;
1126
+ const own = isWhite ? pos.board.white : pos.board.black;
1127
+ // 1. King
1128
+ const ksq = ctx.ksq;
1129
+ if (ksq >= 0) {
1130
+ const kingPiece = isWhite ? P_W_K : P_B_K;
1131
+ const kd = destsFast(pos, ksq, kingPiece, ctx);
1132
+ let dLo = kd.lo >>> 0, dHi = kd.hi >>> 0;
1133
+ while (dLo !== 0) {
1134
+ const lsb = (dLo & -dLo) >>> 0;
1135
+ const to = Math.clz32(lsb) ^ 31;
1136
+ dLo = (dLo ^ lsb) >>> 0;
1137
+ out[count++] = (ksq | (to << 6)) >>> 0;
828
1138
  }
829
- else {
830
- const lsb = (ownHi & -ownHi) >>> 0;
831
- from = 32 + (31 - Math.clz32(lsb));
832
- ownHi ^= lsb;
1139
+ while (dHi !== 0) {
1140
+ const lsb = (dHi & -dHi) >>> 0;
1141
+ const to = 32 + (Math.clz32(lsb) ^ 31);
1142
+ dHi = (dHi ^ lsb) >>> 0;
1143
+ out[count++] = (ksq | (to << 6)) >>> 0;
833
1144
  }
834
- const piece = board.pieceAt(pos.board, from);
835
- if (!piece)
836
- continue;
837
- if (piece.role !== Role.King && ctx.doubleCheck)
838
- continue;
839
- const legal = destsFast(pos, from, piece, ctx);
840
- if (legal.lo === 0 && legal.hi === 0)
841
- continue;
842
- if (piece.role === Role.Pawn) {
843
- let lo = legal.lo >>> 0, hi = legal.hi >>> 0;
844
- while (lo !== 0 || hi !== 0) {
845
- let to;
846
- if (lo !== 0) {
847
- const lsb = (lo & -lo) >>> 0;
848
- to = 31 - Math.clz32(lsb);
849
- lo ^= lsb;
850
- }
851
- else {
852
- const lsb = (hi & -hi) >>> 0;
853
- to = 32 + (31 - Math.clz32(lsb));
854
- hi ^= lsb;
855
- }
856
- const destRank = to >> 3;
857
- if ((isWhite && destRank === 7) || (!isWhite && destRank === 0)) {
858
- count += 4;
859
- }
860
- else {
861
- count += 1;
862
- }
1145
+ }
1146
+ if (ctx.doubleCheck)
1147
+ return count;
1148
+ // 2. Pawns
1149
+ const pawnPiece = isWhite ? P_W_P : P_B_P;
1150
+ let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
1151
+ let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
1152
+ const promoRank = isWhite ? 7 : 0;
1153
+ const emitPawnDests = (from) => {
1154
+ const legal = destsFast(pos, from, pawnPiece, ctx);
1155
+ let dLo = legal.lo >>> 0, dHi = legal.hi >>> 0;
1156
+ while (dLo !== 0) {
1157
+ const lsb = (dLo & -dLo) >>> 0;
1158
+ const to = Math.clz32(lsb) ^ 31;
1159
+ dLo = (dLo ^ lsb) >>> 0;
1160
+ if ((to >> 3) === promoRank) {
1161
+ out[count++] = (from | (to << 6) | (PROMO_QUEEN << 12)) >>> 0;
1162
+ out[count++] = (from | (to << 6) | (PROMO_ROOK << 12)) >>> 0;
1163
+ out[count++] = (from | (to << 6) | (PROMO_BISHOP << 12)) >>> 0;
1164
+ out[count++] = (from | (to << 6) | (PROMO_KNIGHT << 12)) >>> 0;
1165
+ }
1166
+ else {
1167
+ out[count++] = (from | (to << 6)) >>> 0;
863
1168
  }
864
1169
  }
865
- else {
866
- count += sq.popcount(legal);
1170
+ while (dHi !== 0) {
1171
+ const lsb = (dHi & -dHi) >>> 0;
1172
+ const to = 32 + (Math.clz32(lsb) ^ 31);
1173
+ dHi = (dHi ^ lsb) >>> 0;
1174
+ if ((to >> 3) === promoRank) {
1175
+ out[count++] = (from | (to << 6) | (PROMO_QUEEN << 12)) >>> 0;
1176
+ out[count++] = (from | (to << 6) | (PROMO_ROOK << 12)) >>> 0;
1177
+ out[count++] = (from | (to << 6) | (PROMO_BISHOP << 12)) >>> 0;
1178
+ out[count++] = (from | (to << 6) | (PROMO_KNIGHT << 12)) >>> 0;
1179
+ }
1180
+ else {
1181
+ out[count++] = (from | (to << 6)) >>> 0;
1182
+ }
867
1183
  }
868
- }
1184
+ };
1185
+ while (pLo !== 0) {
1186
+ const lsb = (pLo & -pLo) >>> 0;
1187
+ const from = Math.clz32(lsb) ^ 31;
1188
+ pLo = (pLo ^ lsb) >>> 0;
1189
+ emitPawnDests(from);
1190
+ }
1191
+ while (pHi !== 0) {
1192
+ const lsb = (pHi & -pHi) >>> 0;
1193
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1194
+ pHi = (pHi ^ lsb) >>> 0;
1195
+ emitPawnDests(from);
1196
+ }
1197
+ // 3. Knights, Bishops, Rooks, Queens
1198
+ const emitRole = (roleBB, piece) => {
1199
+ let rLo = (own.lo & roleBB.lo) >>> 0;
1200
+ let rHi = (own.hi & roleBB.hi) >>> 0;
1201
+ while (rLo !== 0) {
1202
+ const lsb = (rLo & -rLo) >>> 0;
1203
+ const from = Math.clz32(lsb) ^ 31;
1204
+ rLo = (rLo ^ lsb) >>> 0;
1205
+ const d = destsFast(pos, from, piece, ctx);
1206
+ let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
1207
+ while (dLo !== 0) {
1208
+ const lsbD = (dLo & -dLo) >>> 0;
1209
+ const to = Math.clz32(lsbD) ^ 31;
1210
+ dLo = (dLo ^ lsbD) >>> 0;
1211
+ out[count++] = (from | (to << 6)) >>> 0;
1212
+ }
1213
+ while (dHi !== 0) {
1214
+ const lsbD = (dHi & -dHi) >>> 0;
1215
+ const to = 32 + (Math.clz32(lsbD) ^ 31);
1216
+ dHi = (dHi ^ lsbD) >>> 0;
1217
+ out[count++] = (from | (to << 6)) >>> 0;
1218
+ }
1219
+ }
1220
+ while (rHi !== 0) {
1221
+ const lsb = (rHi & -rHi) >>> 0;
1222
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1223
+ rHi = (rHi ^ lsb) >>> 0;
1224
+ const d = destsFast(pos, from, piece, ctx);
1225
+ let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
1226
+ while (dLo !== 0) {
1227
+ const lsbD = (dLo & -dLo) >>> 0;
1228
+ const to = Math.clz32(lsbD) ^ 31;
1229
+ dLo = (dLo ^ lsbD) >>> 0;
1230
+ out[count++] = (from | (to << 6)) >>> 0;
1231
+ }
1232
+ while (dHi !== 0) {
1233
+ const lsbD = (dHi & -dHi) >>> 0;
1234
+ const to = 32 + (Math.clz32(lsbD) ^ 31);
1235
+ dHi = (dHi ^ lsbD) >>> 0;
1236
+ out[count++] = (from | (to << 6)) >>> 0;
1237
+ }
1238
+ }
1239
+ };
1240
+ emitRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
1241
+ emitRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
1242
+ emitRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
1243
+ emitRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
869
1244
  return count;
870
1245
  }
1246
+ export function forEachLegalMove(pos, fn) {
1247
+ const ctx = analyzeCheckContext(pos);
1248
+ const us = pos.turn;
1249
+ const isWhite = us === Color.White;
1250
+ const own = isWhite ? pos.board.white : pos.board.black;
1251
+ // 1. King
1252
+ const ksq = ctx.ksq;
1253
+ if (ksq >= 0) {
1254
+ const kingPiece = isWhite ? P_W_K : P_B_K;
1255
+ const kd = destsFast(pos, ksq, kingPiece, ctx);
1256
+ let dLo = kd.lo >>> 0, dHi = kd.hi >>> 0;
1257
+ while (dLo !== 0) {
1258
+ const lsb = (dLo & -dLo) >>> 0;
1259
+ const to = Math.clz32(lsb) ^ 31;
1260
+ dLo = (dLo ^ lsb) >>> 0;
1261
+ fn(ksq, to, PROMO_NONE);
1262
+ }
1263
+ while (dHi !== 0) {
1264
+ const lsb = (dHi & -dHi) >>> 0;
1265
+ const to = 32 + (Math.clz32(lsb) ^ 31);
1266
+ dHi = (dHi ^ lsb) >>> 0;
1267
+ fn(ksq, to, PROMO_NONE);
1268
+ }
1269
+ }
1270
+ if (ctx.doubleCheck)
1271
+ return;
1272
+ // 2. Pawns
1273
+ const pawnPiece = isWhite ? P_W_P : P_B_P;
1274
+ let pLo = (own.lo & pos.board.pawn.lo) >>> 0;
1275
+ let pHi = (own.hi & pos.board.pawn.hi) >>> 0;
1276
+ const promoRank = isWhite ? 7 : 0;
1277
+ const visitPawnDests = (from) => {
1278
+ const legal = destsFast(pos, from, pawnPiece, ctx);
1279
+ let dLo = legal.lo >>> 0, dHi = legal.hi >>> 0;
1280
+ while (dLo !== 0) {
1281
+ const lsb = (dLo & -dLo) >>> 0;
1282
+ const to = Math.clz32(lsb) ^ 31;
1283
+ dLo = (dLo ^ lsb) >>> 0;
1284
+ if ((to >> 3) === promoRank) {
1285
+ fn(from, to, PROMO_QUEEN);
1286
+ fn(from, to, PROMO_ROOK);
1287
+ fn(from, to, PROMO_BISHOP);
1288
+ fn(from, to, PROMO_KNIGHT);
1289
+ }
1290
+ else {
1291
+ fn(from, to, PROMO_NONE);
1292
+ }
1293
+ }
1294
+ while (dHi !== 0) {
1295
+ const lsb = (dHi & -dHi) >>> 0;
1296
+ const to = 32 + (Math.clz32(lsb) ^ 31);
1297
+ dHi = (dHi ^ lsb) >>> 0;
1298
+ if ((to >> 3) === promoRank) {
1299
+ fn(from, to, PROMO_QUEEN);
1300
+ fn(from, to, PROMO_ROOK);
1301
+ fn(from, to, PROMO_BISHOP);
1302
+ fn(from, to, PROMO_KNIGHT);
1303
+ }
1304
+ else {
1305
+ fn(from, to, PROMO_NONE);
1306
+ }
1307
+ }
1308
+ };
1309
+ while (pLo !== 0) {
1310
+ const lsb = (pLo & -pLo) >>> 0;
1311
+ const from = Math.clz32(lsb) ^ 31;
1312
+ pLo = (pLo ^ lsb) >>> 0;
1313
+ visitPawnDests(from);
1314
+ }
1315
+ while (pHi !== 0) {
1316
+ const lsb = (pHi & -pHi) >>> 0;
1317
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1318
+ pHi = (pHi ^ lsb) >>> 0;
1319
+ visitPawnDests(from);
1320
+ }
1321
+ // 3. Knights, Bishops, Rooks, Queens
1322
+ const visitRole = (roleBB, piece) => {
1323
+ let rLo = (own.lo & roleBB.lo) >>> 0;
1324
+ let rHi = (own.hi & roleBB.hi) >>> 0;
1325
+ while (rLo !== 0) {
1326
+ const lsb = (rLo & -rLo) >>> 0;
1327
+ const from = Math.clz32(lsb) ^ 31;
1328
+ rLo = (rLo ^ lsb) >>> 0;
1329
+ const d = destsFast(pos, from, piece, ctx);
1330
+ let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
1331
+ while (dLo !== 0) {
1332
+ const lsbD = (dLo & -dLo) >>> 0;
1333
+ const to = Math.clz32(lsbD) ^ 31;
1334
+ dLo = (dLo ^ lsbD) >>> 0;
1335
+ fn(from, to, PROMO_NONE);
1336
+ }
1337
+ while (dHi !== 0) {
1338
+ const lsbD = (dHi & -dHi) >>> 0;
1339
+ const to = 32 + (Math.clz32(lsbD) ^ 31);
1340
+ dHi = (dHi ^ lsbD) >>> 0;
1341
+ fn(from, to, PROMO_NONE);
1342
+ }
1343
+ }
1344
+ while (rHi !== 0) {
1345
+ const lsb = (rHi & -rHi) >>> 0;
1346
+ const from = 32 + (Math.clz32(lsb) ^ 31);
1347
+ rHi = (rHi ^ lsb) >>> 0;
1348
+ const d = destsFast(pos, from, piece, ctx);
1349
+ let dLo = d.lo >>> 0, dHi = d.hi >>> 0;
1350
+ while (dLo !== 0) {
1351
+ const lsbD = (dLo & -dLo) >>> 0;
1352
+ const to = Math.clz32(lsbD) ^ 31;
1353
+ dLo = (dLo ^ lsbD) >>> 0;
1354
+ fn(from, to, PROMO_NONE);
1355
+ }
1356
+ while (dHi !== 0) {
1357
+ const lsbD = (dHi & -dHi) >>> 0;
1358
+ const to = 32 + (Math.clz32(lsbD) ^ 31);
1359
+ dHi = (dHi ^ lsbD) >>> 0;
1360
+ fn(from, to, PROMO_NONE);
1361
+ }
1362
+ }
1363
+ };
1364
+ visitRole(pos.board.knight, isWhite ? P_W_N : P_B_N);
1365
+ visitRole(pos.board.bishop, isWhite ? P_W_B : P_B_B);
1366
+ visitRole(pos.board.rook, isWhite ? P_W_R : P_B_R);
1367
+ visitRole(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
1368
+ }
871
1369
  // Promotion pieces in generation order (hoisted module constant — the old
872
1370
  // per-call array literal allocated on every promotion move in the hot loop).
873
1371
  const PROMO_ROLES = [Role.Queen, Role.Rook, Role.Bishop, Role.Knight];
874
1372
  function genLegalMoves(pos) {
875
1373
  const moves = [];
876
- // Per-position check/pin-mask analysis replaces the per-move play-and-test;
877
- // only ep (validated inside destsFast) keeps exact semantics.
878
1374
  const ctx = analyzeCheckContext(pos);
879
- const own = pos.turn === Color.White ? pos.board.white : pos.board.black;
880
- // Direct LSB bit iteration (ascending square order, same as forEachSquare)
881
- // — no closure allocation per piece in this hot loop.
1375
+ const us = pos.turn;
1376
+ const isWhite = us === Color.White;
1377
+ const own = isWhite ? pos.board.white : pos.board.black;
882
1378
  const plans = ctx.castlingPlans;
883
- const isWhite = pos.turn === Color.White;
884
- let ownLo = own.lo >>> 0, ownHi = own.hi >>> 0;
885
- while (ownLo !== 0 || ownHi !== 0) {
886
- let from;
887
- if (ownLo !== 0) {
888
- const lsb = (ownLo & -ownLo) >>> 0;
889
- from = 31 - Math.clz32(lsb);
890
- ownLo ^= lsb;
891
- }
892
- else {
893
- const lsb = (ownHi & -ownHi) >>> 0;
894
- from = 32 + (31 - Math.clz32(lsb));
895
- ownHi ^= lsb;
896
- }
897
- const piece = board.pieceAt(pos.board, from);
898
- if (!piece)
899
- continue;
900
- // A non-king move can never resolve a double check.
901
- if (piece.role !== Role.King && ctx.doubleCheck)
902
- continue;
903
- const legal = destsFast(pos, from, piece, ctx);
904
- const isPawn = piece.role === Role.Pawn;
905
- const isKing = piece.role === Role.King;
906
- let lo = legal.lo >>> 0, hi = legal.hi >>> 0;
907
- while (lo !== 0 || hi !== 0) {
908
- let to;
909
- if (lo !== 0) {
910
- const lsb = (lo & -lo) >>> 0;
911
- to = 31 - Math.clz32(lsb);
912
- lo ^= lsb;
913
- }
914
- else {
915
- const lsb = (hi & -hi) >>> 0;
916
- to = 32 + (31 - Math.clz32(lsb));
917
- hi ^= lsb;
918
- }
1379
+ // 1. King
1380
+ const ksq = ctx.ksq;
1381
+ if (ksq >= 0) {
1382
+ const kingPiece = isWhite ? P_W_K : P_B_K;
1383
+ sq.forEachSquare(destsFast(pos, ksq, kingPiece, ctx), (to) => {
1384
+ const isCastling = plans.length > 0 && planForDest(plans, to) !== null;
1385
+ moves.push({ from: ksq, to, promotion: null, isEnPassant: false, isCastling, isPromotion: false });
1386
+ });
1387
+ }
1388
+ if (ctx.doubleCheck)
1389
+ return moves;
1390
+ // 2. Pawns
1391
+ const pawnPiece = isWhite ? P_W_P : P_B_P;
1392
+ sq.forEachSquare(sq.and(own, pos.board.pawn), (from) => {
1393
+ const legal = destsFast(pos, from, pawnPiece, ctx);
1394
+ sq.forEachSquare(legal, (to) => {
919
1395
  const destRank = to >> 3;
920
- if (isPawn && ((isWhite && destRank === 7) || (!isWhite && destRank === 0))) {
921
- // generate 4 promotions (legality is promotion-independent: every
922
- // promoted piece lands on the same square, so king safety is identical)
1396
+ if ((isWhite && destRank === 7) || (!isWhite && destRank === 0)) {
923
1397
  for (const promo of PROMO_ROLES) {
924
- // promotion capture can't be en passant (ep rank not back rank)
925
1398
  moves.push({ from, to, promotion: promo, isPromotion: true, isEnPassant: false, isCastling: false });
926
1399
  }
927
1400
  }
928
1401
  else {
929
- // determine flags
930
1402
  let isEnPassant = false;
931
- let isCastling = false;
932
- if (isPawn && pos.epSquare !== null && to === pos.epSquare) {
933
- // check if pawn capture to ep square
1403
+ if (pos.epSquare !== null && to === pos.epSquare) {
934
1404
  const fileDiff = Math.abs((to & 7) - (from & 7));
935
1405
  const dir = isWhite ? 1 : -1;
936
1406
  if (fileDiff === 1 && destRank - (from >> 3) === dir)
937
1407
  isEnPassant = true;
938
1408
  }
939
- else if (isKing && plans.length > 0) {
940
- // Precomputed per-position plans (design D2) — replaces the old
941
- // dest-matches-a-right heuristic, which flagged ordinary king steps
942
- // to {6,2,62,58} as castling whenever any color held rights.
943
- isCastling = planForDest(plans, to) !== null;
944
- }
945
- // Legality is already guaranteed by destsFast (exact play-and-test for
946
- // the ep/castling trap cases, check/pin masks otherwise) — no re-test.
947
- moves.push({ from, to, promotion: null, isEnPassant, isCastling, isPromotion: false });
1409
+ moves.push({ from, to, promotion: null, isEnPassant, isCastling: false, isPromotion: false });
948
1410
  }
949
- }
950
- }
1411
+ });
1412
+ });
1413
+ // 3. Knights, Bishops, Rooks, Queens
1414
+ const addPieceMoves = (roleBB, piece) => {
1415
+ sq.forEachSquare(sq.and(own, roleBB), (from) => {
1416
+ sq.forEachSquare(destsFast(pos, from, piece, ctx), (to) => {
1417
+ moves.push({ from, to, promotion: null, isEnPassant: false, isCastling: false, isPromotion: false });
1418
+ });
1419
+ });
1420
+ };
1421
+ addPieceMoves(pos.board.knight, isWhite ? P_W_N : P_B_N);
1422
+ addPieceMoves(pos.board.bishop, isWhite ? P_W_B : P_B_B);
1423
+ addPieceMoves(pos.board.rook, isWhite ? P_W_R : P_B_R);
1424
+ addPieceMoves(pos.board.queen, isWhite ? P_W_Q : P_B_Q);
951
1425
  return moves;
952
1426
  }
953
1427
  // Promotion pieces in generation order (hoisted module constant — the old
@@ -974,21 +1448,6 @@ const PROMO_ORDER = [4, 3, 2, 1]; // Role.Queen, Role.Rook, Role.Bishop, Role.Kn
974
1448
  function colorName(turn) {
975
1449
  return turn === Color.White ? "w" : "b";
976
1450
  }
977
- /** Ascending square iteration over a {lo,hi} pair. */
978
- function* iterSet(set) {
979
- let lo = set.lo >>> 0;
980
- let hi = set.hi >>> 0;
981
- while (lo !== 0) {
982
- const lsb = (lo & -lo) >>> 0;
983
- yield 31 - Math.clz32(lsb);
984
- lo ^= lsb;
985
- }
986
- while (hi !== 0) {
987
- const lsb = (hi & -hi) >>> 0;
988
- yield 32 + (31 - Math.clz32(lsb));
989
- hi ^= lsb;
990
- }
991
- }
992
1451
  /** Expands pawn back-rank destinations into the four promotions. */
993
1452
  function buildMoves(pos, role, from, to) {
994
1453
  const toRank = to >> 3;
@@ -1025,10 +1484,8 @@ function hasLegalEpCapture(pos) {
1025
1484
  const p = pieceAt(pos.board, from);
1026
1485
  if (!p || p.role !== 0)
1027
1486
  continue;
1028
- for (const to of iterSet(set)) {
1029
- if (to === ep)
1030
- return true; // allDests is fully legal, no re-test needed
1031
- }
1487
+ if (sq.has(set, ep))
1488
+ return true;
1032
1489
  }
1033
1490
  return false;
1034
1491
  }
@@ -1123,7 +1580,14 @@ export class Chess {
1123
1580
  const san = makeSan(mv, pos);
1124
1581
  const after = makeMove(pos, mv);
1125
1582
  __classPrivateFieldSet(this, _Chess_pos, after, "f");
1126
- __classPrivateFieldGet(this, _Chess_history, "f").push({ before: pos, after, move: mv, san });
1583
+ __classPrivateFieldGet(this, _Chess_history, "f").push({
1584
+ before: pos,
1585
+ after,
1586
+ move: mv,
1587
+ san,
1588
+ prev_checkers: pos.checkers,
1589
+ prev_zobrist: pos.zobristLo !== undefined && pos.zobristHi !== undefined ? { lo: pos.zobristLo, hi: pos.zobristHi } : undefined,
1590
+ });
1127
1591
  return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, pos, mv, after, san);
1128
1592
  }
1129
1593
  moves(options) {
@@ -1133,7 +1597,7 @@ export class Chess {
1133
1597
  const piece = pieceAt(pos.board, from);
1134
1598
  if (!piece)
1135
1599
  return;
1136
- for (const to of iterSet(set)) {
1600
+ sq.forEachSquare(set, (to) => {
1137
1601
  for (const mv of buildMoves(pos, piece.role, from, to)) {
1138
1602
  const san = makeSan(mv, pos);
1139
1603
  if (options?.verbose)
@@ -1141,7 +1605,7 @@ export class Chess {
1141
1605
  else
1142
1606
  out.push(san);
1143
1607
  }
1144
- }
1608
+ });
1145
1609
  };
1146
1610
  if (options?.square !== undefined) {
1147
1611
  const sqIdx = parseSquare(options.square);
@@ -1170,6 +1634,7 @@ export class Chess {
1170
1634
  return __classPrivateFieldGet(this, _Chess_instances, "m", _Chess_describe).call(this, last.before, last.move, last.after, last.san);
1171
1635
  }
1172
1636
  isCheck() { return isCheck(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1637
+ inCheck() { return isCheck(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1173
1638
  isCheckmate() { return isCheckmate(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1174
1639
  isStalemate() { return isStalemate(__classPrivateFieldGet(this, _Chess_pos, "f")); }
1175
1640
  /** Draw by insufficient material, the fifty-move rule, or threefold repetition. */
@@ -1259,10 +1724,18 @@ export class Chess {
1259
1724
  perft(depth) { return perft(__classPrivateFieldGet(this, _Chess_pos, "f"), depth); }
1260
1725
  /** Applies an engine move in place (immutable core stays pure underneath). */
1261
1726
  play(move) {
1262
- const san = makeSan(move, __classPrivateFieldGet(this, _Chess_pos, "f"));
1263
- const after = makeMove(__classPrivateFieldGet(this, _Chess_pos, "f"), move);
1727
+ const before = __classPrivateFieldGet(this, _Chess_pos, "f");
1728
+ const san = makeSan(move, before);
1729
+ const after = makeMove(before, move);
1264
1730
  __classPrivateFieldSet(this, _Chess_pos, after, "f");
1265
- __classPrivateFieldGet(this, _Chess_history, "f").push({ before: __classPrivateFieldGet(this, _Chess_pos, "f"), after, move, san });
1731
+ __classPrivateFieldGet(this, _Chess_history, "f").push({
1732
+ before,
1733
+ after,
1734
+ move,
1735
+ san,
1736
+ prev_checkers: before.checkers,
1737
+ prev_zobrist: before.zobristLo !== undefined && before.zobristHi !== undefined ? { lo: before.zobristLo, hi: before.zobristHi } : undefined,
1738
+ });
1266
1739
  return this;
1267
1740
  }
1268
1741
  /** Current 64-bit Zobrist key (zero-BigInt {lo, hi} halves). */
@@ -1309,6 +1782,7 @@ export class Chess {
1309
1782
  get startFen() { return __classPrivateFieldGet(this, _Chess_startFen, "f"); }
1310
1783
  /** Live engine position (read-only view over the internal state). */
1311
1784
  get pos() { return __classPrivateFieldGet(this, _Chess_pos, "f"); }
1785
+ get _pos() { return __classPrivateFieldGet(this, _Chess_pos, "f"); }
1312
1786
  /** Internal history log (read-only view; used by toTree). */
1313
1787
  get historyEntries() { return __classPrivateFieldGet(this, _Chess_history, "f"); }
1314
1788
  /**