mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
6
Commits
a5bb1cb670
...
e60c161a3a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e60c161a3a
|
||
|
|
3fadd4397c
|
||
|
|
515196857f
|
||
|
|
ec657c3424
|
||
|
|
ff7adcf308
|
||
|
|
dd060531d3 |
@@ -42,3 +42,9 @@ npm-debug.log
|
|||||||
|
|
||||||
# graft's local graph cache — regenerable, not committed (run `graft build`).
|
# graft's local graph cache — regenerable, not committed (run `graft build`).
|
||||||
/graft/
|
/graft/
|
||||||
|
|
||||||
|
# Rust build artefacts for the Fathom NIF (the source and vendored C are kept).
|
||||||
|
/native/fathom_nif/target/
|
||||||
|
|
||||||
|
# Compiled NIF artefacts (rebuilt from native/ by Rustler).
|
||||||
|
/priv/native/
|
||||||
|
|||||||
@@ -25,10 +25,12 @@ import { LiveSocket } from "phoenix_live_view";
|
|||||||
import { hooks as colocatedHooks } from "phoenix-colocated/chesstrainer";
|
import { hooks as colocatedHooks } from "phoenix-colocated/chesstrainer";
|
||||||
import topbar from "../vendor/topbar";
|
import topbar from "../vendor/topbar";
|
||||||
import { ChessBoard } from "./hooks/chessBoard";
|
import { ChessBoard } from "./hooks/chessBoard";
|
||||||
|
import { CopyFen } from "./hooks/copyFen"
|
||||||
|
|
||||||
let Hooks = {
|
let Hooks = {
|
||||||
...colocatedHooks,
|
...colocatedHooks,
|
||||||
ChessBoard,
|
ChessBoard,
|
||||||
|
CopyFen
|
||||||
};
|
};
|
||||||
|
|
||||||
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
|
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export const CopyFen = {
|
||||||
|
mounted() {
|
||||||
|
this.el.addEventListener("click", e => {
|
||||||
|
e.preventDefault()
|
||||||
|
const fen = this.el.dataset.fen
|
||||||
|
|
||||||
|
navigator.clipboard.writeText(fen).then(() => {
|
||||||
|
const originalHTML = this.el.innerHTML
|
||||||
|
this.el.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-emerald-600 inline" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg> Copied!`
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
this.el.innerHTML = originalHTML
|
||||||
|
}, 2000)
|
||||||
|
}).catch(err => {
|
||||||
|
console.log('Failed to copy FEN: ', err)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,27 +66,35 @@ defmodule Chesstrainer.Endgames.Endgame do
|
|||||||
defp fen_issues(fen) do
|
defp fen_issues(fen) do
|
||||||
case String.split(fen, " ") do
|
case String.split(fen, " ") do
|
||||||
[board, active, _castling, _en_passant, halfmove, fullmove] ->
|
[board, active, _castling, _en_passant, halfmove, fullmove] ->
|
||||||
|
board_valid? = valid_board?(board)
|
||||||
|
pieces = Chesstrainer.FEN.piece_count(fen)
|
||||||
|
|
||||||
issues = []
|
issues = []
|
||||||
|
|
||||||
issues =
|
issues =
|
||||||
if valid_board?(board),
|
if board_valid?,
|
||||||
do: issues,
|
do: issues,
|
||||||
else: ["board must be 8 ranks of 8 squares each"]
|
else: issues ++ ["board must be 8 ranks of 8 squares each"]
|
||||||
|
|
||||||
issues =
|
issues =
|
||||||
if active in ["w", "b"],
|
if active in ["w", "b"],
|
||||||
do: issues,
|
do: issues,
|
||||||
else: ["active color must be 'w' or 'b'"]
|
else: issues ++ ["active color must be 'w' or 'b'"]
|
||||||
|
|
||||||
issues =
|
issues =
|
||||||
if non_negative_integer?(halfmove),
|
if non_negative_integer?(halfmove),
|
||||||
do: issues,
|
do: issues,
|
||||||
else: ["halfmove clock must be a non-negative integer"]
|
else: issues ++ ["halfmove clock must be a non-negative integer"]
|
||||||
|
|
||||||
issues =
|
issues =
|
||||||
if positive_integer?(fullmove),
|
if positive_integer?(fullmove),
|
||||||
do: issues,
|
do: issues,
|
||||||
else: ["fullmove number must be a positive integer"]
|
else: issues ++ ["fullmove number must be a positive integer"]
|
||||||
|
|
||||||
|
issues =
|
||||||
|
if board_valid? and is_integer(pieces) and pieces > 7,
|
||||||
|
do: issues ++ ["positions with more than 7 pieces are not covered by tablebases"],
|
||||||
|
else: issues
|
||||||
|
|
||||||
issues
|
issues
|
||||||
|
|
||||||
|
|||||||
@@ -2,28 +2,28 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
|||||||
@moduledoc """
|
@moduledoc """
|
||||||
All endgame tablebase related functions.
|
All endgame tablebase related functions.
|
||||||
|
|
||||||
|
Lookups are routed by piece count through `Tablebase.Router`, which picks the
|
||||||
|
backend that can answer the position.
|
||||||
|
|
||||||
The cached value carries only what the trainer reads: `category`,
|
The cached value carries only what the trainer reads: `category`,
|
||||||
`checkmate`, and `moves` drive play, while `dtm`/`dtc` are small distance
|
`checkmate`, and `moves`. Cursed-win/blessed-loss are normalised to `:draw` at
|
||||||
hedges. Cursed-win/blessed-loss are normalised to `:draw` at parse time, so
|
parse time, and distance fields (`dtm`/`dtc`/`dtw`) are not kept because the
|
||||||
the raw `dtw`/`dtz`/`insufficient_material` fields are not kept here.
|
local Syzygy backend cannot produce them.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
alias Chesstrainer.Endgames.Tablebase
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
|
alias Chesstrainer.FEN
|
||||||
|
|
||||||
@type result :: :win | :draw | :loss | :unknown
|
@type result :: :win | :draw | :loss | :unknown
|
||||||
|
|
||||||
@type t :: %__MODULE__{
|
@type t :: %__MODULE__{
|
||||||
category: result,
|
category: result,
|
||||||
checkmate: boolean(),
|
checkmate: boolean(),
|
||||||
dtc: integer() | nil,
|
|
||||||
dtm: integer() | nil,
|
|
||||||
moves: [Tablebase.Move.t()]
|
moves: [Tablebase.Move.t()]
|
||||||
}
|
}
|
||||||
|
|
||||||
defstruct category: nil,
|
defstruct category: nil,
|
||||||
checkmate: false,
|
checkmate: false,
|
||||||
dtc: nil,
|
|
||||||
dtm: nil,
|
|
||||||
moves: nil
|
moves: nil
|
||||||
|
|
||||||
@doc """
|
@doc """
|
||||||
@@ -50,12 +50,14 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
|||||||
| {:error, :invalid_endgame}
|
| {:error, :invalid_endgame}
|
||||||
| {:error, term()}
|
| {:error, term()}
|
||||||
def new(fen) do
|
def new(fen) do
|
||||||
case Tablebase.Cache.get(fen) do
|
key = FEN.position_key(fen)
|
||||||
|
|
||||||
|
case Tablebase.Cache.get(key) do
|
||||||
{:ok, tablebase} ->
|
{:ok, tablebase} ->
|
||||||
{:ok, tablebase}
|
{:ok, tablebase}
|
||||||
|
|
||||||
_ ->
|
_ ->
|
||||||
case Tablebase.Parser.from_fen(fen) do
|
case Tablebase.Router.probe(fen) do
|
||||||
{:error, reason} ->
|
{:error, reason} ->
|
||||||
{:error, reason}
|
{:error, reason}
|
||||||
|
|
||||||
@@ -66,7 +68,7 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
|||||||
{:error, :invalid_endgame}
|
{:error, :invalid_endgame}
|
||||||
|
|
||||||
{:ok, tablebase} ->
|
{:ok, tablebase} ->
|
||||||
Tablebase.Cache.put(fen, tablebase)
|
Tablebase.Cache.put(key, tablebase)
|
||||||
{:ok, tablebase}
|
{:ok, tablebase}
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.Backend do
|
||||||
|
@moduledoc """
|
||||||
|
A backend answers a tablebase probe for one position.
|
||||||
|
|
||||||
|
The router chooses a backend by piece count, so the play flow never depends on
|
||||||
|
which one answered. Every backend returns the same shape.
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
|
|
||||||
|
@type result ::
|
||||||
|
{:ok, Tablebase.t()}
|
||||||
|
| {:cooldown, non_neg_integer()}
|
||||||
|
| {:error, term()}
|
||||||
|
|
||||||
|
@callback probe(String.t()) :: result()
|
||||||
|
end
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.Backend.Lichess do
|
||||||
|
@moduledoc """
|
||||||
|
The Lichess tablebase API backend (covers up to seven pieces).
|
||||||
|
"""
|
||||||
|
|
||||||
|
@behaviour Chesstrainer.Endgames.Tablebase.Backend
|
||||||
|
|
||||||
|
alias Chesstrainer.Endgames.Tablebase.Parser
|
||||||
|
|
||||||
|
@impl true
|
||||||
|
def probe(fen), do: Parser.from_fen(fen)
|
||||||
|
end
|
||||||
@@ -1,17 +1,20 @@
|
|||||||
defmodule Chesstrainer.Endgames.Tablebase.Cache do
|
defmodule Chesstrainer.Endgames.Tablebase.Cache do
|
||||||
@moduledoc """
|
@moduledoc """
|
||||||
A cache of tablebases by FEN.
|
A cache of tablebases keyed by position.
|
||||||
|
|
||||||
|
The key is a FEN's position fields (see `Chesstrainer.FEN.position_key/1`), so
|
||||||
|
transpositions and clock-only differences share an entry.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
alias Chesstrainer.Cache
|
alias Chesstrainer.Cache
|
||||||
|
|
||||||
@table :tablebase
|
@table :tablebase
|
||||||
|
|
||||||
def put(fen, tablebase), do: Cache.put(@table, fen, tablebase)
|
def put(key, tablebase), do: Cache.put(@table, key, tablebase)
|
||||||
|
|
||||||
def get(fen), do: Cache.get(@table, fen)
|
def get(key), do: Cache.get(@table, key)
|
||||||
|
|
||||||
def delete(fen), do: Cache.delete(@table, fen)
|
def delete(key), do: Cache.delete(@table, key)
|
||||||
def show, do: Cache.show(@table)
|
def show, do: Cache.show(@table)
|
||||||
def size, do: Cache.size(@table)
|
def size, do: Cache.size(@table)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.Fathom do
|
||||||
|
@moduledoc """
|
||||||
|
Low-level NIF wrapper around [Fathom](https://github.com/jdart1/Fathom), a
|
||||||
|
Syzygy tablebase prober.
|
||||||
|
|
||||||
|
`init/1` points Fathom at a directory of `.rtbw`/`.rtbz` files and returns the
|
||||||
|
largest piece count it found. `probe/1` returns the raw probe result for a
|
||||||
|
FEN. Probes are serialised inside the NIF because Fathom's root probe keeps
|
||||||
|
global state and is not thread safe.
|
||||||
|
|
||||||
|
This module is the probe primitive: mapping the raw result onto
|
||||||
|
`Chesstrainer.Endgames.Tablebase` is the backend's job.
|
||||||
|
"""
|
||||||
|
|
||||||
|
use Rustler, otp_app: :chesstrainer, crate: :fathom_nif
|
||||||
|
|
||||||
|
@typedoc "An encoded move: `{wdl, from, to, promotes, ep, dtz}`."
|
||||||
|
@type move ::
|
||||||
|
{atom(), non_neg_integer(), non_neg_integer(), non_neg_integer(), 0 | 1,
|
||||||
|
non_neg_integer()}
|
||||||
|
|
||||||
|
@typedoc "The root result: an outcome atom or a move tuple."
|
||||||
|
@type root :: :checkmate | :stalemate | :failed | move()
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Initialises Fathom against a tablebase directory.
|
||||||
|
|
||||||
|
Returns the largest piece count available, or `0` when no files were found.
|
||||||
|
"""
|
||||||
|
@spec init(String.t()) :: {:ok, non_neg_integer()} | {:error, String.t()}
|
||||||
|
def init(_path), do: :erlang.nif_error(:nif_not_loaded)
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Probes a FEN and returns `{:ok, {root, moves}}`.
|
||||||
|
"""
|
||||||
|
@spec probe(String.t()) :: {:ok, {root(), [move()]}} | {:error, String.t()}
|
||||||
|
def probe(_fen), do: :erlang.nif_error(:nif_not_loaded)
|
||||||
|
end
|
||||||
@@ -3,25 +3,21 @@ defmodule Chesstrainer.Endgames.Tablebase.Move do
|
|||||||
Moves struct for the tablebase
|
Moves struct for the tablebase
|
||||||
|
|
||||||
Carries only the fields the trainer reads: `category` and `dtz` for grading,
|
Carries only the fields the trainer reads: `category` and `dtz` for grading,
|
||||||
`san`/`uci` for display and matching, and `dtm`/`dtc` as small distance
|
and `san`/`uci` for display and matching. Terminal detection is structural
|
||||||
hedges. Terminal detection is structural (the next position's `checkmate` or
|
(the next position's `checkmate` or its empty `moves`), so no per-move
|
||||||
its empty `moves`), so no per-move terminal flags are kept.
|
terminal flags are kept.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@type result :: :win | :draw | :loss | :unknown
|
@type result :: :win | :draw | :loss | :unknown
|
||||||
|
|
||||||
@type t :: %__MODULE__{
|
@type t :: %__MODULE__{
|
||||||
category: result,
|
category: result,
|
||||||
dtc: integer() | nil,
|
|
||||||
dtm: integer() | nil,
|
|
||||||
dtz: integer() | nil,
|
dtz: integer() | nil,
|
||||||
san: String.t() | nil,
|
san: String.t() | nil,
|
||||||
uci: String.t() | nil
|
uci: String.t() | nil
|
||||||
}
|
}
|
||||||
|
|
||||||
defstruct category: nil,
|
defstruct category: nil,
|
||||||
dtc: nil,
|
|
||||||
dtm: nil,
|
|
||||||
dtz: nil,
|
dtz: nil,
|
||||||
san: nil,
|
san: nil,
|
||||||
uci: nil
|
uci: nil
|
||||||
|
|||||||
@@ -43,8 +43,6 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
|
|||||||
%Tablebase{
|
%Tablebase{
|
||||||
category: Tablebase.normalize_category(map["category"]),
|
category: Tablebase.normalize_category(map["category"]),
|
||||||
checkmate: map["checkmate"],
|
checkmate: map["checkmate"],
|
||||||
dtc: map["dtc"],
|
|
||||||
dtm: map["dtm"],
|
|
||||||
moves: Enum.map(map["moves"], &moves_from_map/1)
|
moves: Enum.map(map["moves"], &moves_from_map/1)
|
||||||
}}
|
}}
|
||||||
end
|
end
|
||||||
@@ -52,8 +50,6 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
|
|||||||
defp moves_from_map(map) do
|
defp moves_from_map(map) do
|
||||||
%Tablebase.Move{
|
%Tablebase.Move{
|
||||||
category: Tablebase.normalize_category(map["category"]),
|
category: Tablebase.normalize_category(map["category"]),
|
||||||
dtc: map["dtc"],
|
|
||||||
dtm: map["dtm"],
|
|
||||||
dtz: map["dtz"],
|
dtz: map["dtz"],
|
||||||
san: map["san"],
|
san: map["san"],
|
||||||
uci: map["uci"]
|
uci: map["uci"]
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.Router do
|
||||||
|
@moduledoc """
|
||||||
|
Chooses a tablebase backend by piece count.
|
||||||
|
|
||||||
|
Positions with five or fewer pieces go to the local slot; six or seven go to
|
||||||
|
the remote slot. The local slot currently points at Lichess until the local
|
||||||
|
Syzygy backend lands, so this ships without changing today's behaviour.
|
||||||
|
|
||||||
|
Positions with eight or more pieces are beyond every tablebase and are
|
||||||
|
rejected without a network call.
|
||||||
|
"""
|
||||||
|
|
||||||
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
|
alias Chesstrainer.Endgames.Tablebase.Backend.Lichess
|
||||||
|
alias Chesstrainer.FEN
|
||||||
|
|
||||||
|
@max_local_pieces 5
|
||||||
|
@max_pieces 7
|
||||||
|
|
||||||
|
# The local Syzygy backend will replace Lichess here once it exists.
|
||||||
|
@local_backend Lichess
|
||||||
|
@remote_backend Lichess
|
||||||
|
|
||||||
|
@spec backend(String.t()) :: {:ok, module()} | {:error, :not_covered | :invalid_endgame}
|
||||||
|
def backend(fen) do
|
||||||
|
case FEN.piece_count(fen) do
|
||||||
|
count when is_integer(count) and count <= @max_local_pieces -> {:ok, @local_backend}
|
||||||
|
count when is_integer(count) and count <= @max_pieces -> {:ok, @remote_backend}
|
||||||
|
count when is_integer(count) -> {:error, :not_covered}
|
||||||
|
_ -> {:error, :invalid_endgame}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@spec probe(String.t()) ::
|
||||||
|
{:ok, Tablebase.t()} | {:cooldown, non_neg_integer()} | {:error, term()}
|
||||||
|
def probe(fen) do
|
||||||
|
case backend(fen) do
|
||||||
|
{:ok, backend} -> backend.probe(fen)
|
||||||
|
{:error, reason} -> {:error, reason}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -40,6 +40,76 @@ defmodule Chesstrainer.FEN do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Returns the position key for a FEN: the board, side to move, castling and
|
||||||
|
en-passant fields, with the halfmove and fullmove clocks dropped.
|
||||||
|
|
||||||
|
A tablebase answer depends only on the position, so two FENs that differ only
|
||||||
|
in their clocks resolve to the same position key and share a cache entry.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
iex> Chesstrainer.FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
|
||||||
|
"8/8/3k4/8/8/3K1R2/8/8 w - -"
|
||||||
|
|
||||||
|
iex> Chesstrainer.FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 w - - 37 99")
|
||||||
|
"8/8/3k4/8/8/3K1R2/8/8 w - -"
|
||||||
|
"""
|
||||||
|
@spec position_key(String.t()) :: String.t()
|
||||||
|
def position_key(fen) when is_binary(fen) do
|
||||||
|
case String.split(fen) do
|
||||||
|
[board, active, castling, en_passant | _] ->
|
||||||
|
Enum.join([board, active, castling, en_passant], " ")
|
||||||
|
|
||||||
|
_ ->
|
||||||
|
String.trim(fen)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
@doc """
|
||||||
|
Counts the pieces on the board, or returns `nil` if the board field is not a
|
||||||
|
well-formed FEN board.
|
||||||
|
|
||||||
|
Kings count as pieces; empty-square digits are ignored. This is the number
|
||||||
|
tablebases are sized by, so a position with more than seven pieces is beyond
|
||||||
|
every tablebase.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
iex> Chesstrainer.FEN.piece_count("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1")
|
||||||
|
3
|
||||||
|
|
||||||
|
iex> Chesstrainer.FEN.piece_count("not a fen")
|
||||||
|
nil
|
||||||
|
"""
|
||||||
|
@spec piece_count(String.t() | nil) :: non_neg_integer() | nil
|
||||||
|
def piece_count(fen) when is_binary(fen) do
|
||||||
|
case String.split(fen, " ") do
|
||||||
|
[board | _] -> board_piece_count(board)
|
||||||
|
_ -> nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def piece_count(_fen), do: nil
|
||||||
|
|
||||||
|
defp board_piece_count(board) do
|
||||||
|
board
|
||||||
|
|> String.graphemes()
|
||||||
|
|> Enum.reduce_while(0, fn
|
||||||
|
"/", acc ->
|
||||||
|
{:cont, acc}
|
||||||
|
|
||||||
|
<<c>>, acc when c in ?1..?8 ->
|
||||||
|
{:cont, acc}
|
||||||
|
|
||||||
|
piece, acc when piece in ~w(p n b r q k P N B R Q K) ->
|
||||||
|
{:cont, acc + 1}
|
||||||
|
|
||||||
|
_other, _acc ->
|
||||||
|
{:halt, nil}
|
||||||
|
end)
|
||||||
|
end
|
||||||
|
|
||||||
defp color_initial_to_color_atom("b"), do: :black
|
defp color_initial_to_color_atom("b"), do: :black
|
||||||
defp color_initial_to_color_atom("w"), do: :white
|
defp color_initial_to_color_atom("w"), do: :white
|
||||||
defp color_initial_to_color_atom(_), do: nil
|
defp color_initial_to_color_atom(_), do: nil
|
||||||
|
|||||||
@@ -13,6 +13,18 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
<:subtitle>
|
<:subtitle>
|
||||||
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted ||
|
{@endgame.color |> Atom.to_string() |> String.capitalize()} to move · Rating: {@endgame.rating} · Attempts: {@endgame.times_attempted ||
|
||||||
0} · Solved: {@endgame.times_solved || 0}
|
0} · Solved: {@endgame.times_solved || 0}
|
||||||
|
<p class="text-xs text-gray-500 flex items-center mt-1">
|
||||||
|
<span>FEN: {@endgame.fen}</span>
|
||||||
|
<button
|
||||||
|
id="copy-fen-btn"
|
||||||
|
phx-hook="CopyFen"
|
||||||
|
data-fen={@endgame.fen}
|
||||||
|
class="inline-flex items-center cursor-pointer"
|
||||||
|
title="Copy FEN to clipboard"
|
||||||
|
>
|
||||||
|
<.icon name="hero-document-duplicate" class="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
</:subtitle>
|
</:subtitle>
|
||||||
<:actions>
|
<:actions>
|
||||||
<.button navigate={~p"/endgames"}>
|
<.button navigate={~p"/endgames"}>
|
||||||
@@ -560,6 +572,10 @@ defmodule ChesstrainerWeb.EndgameLive.Play do
|
|||||||
"This position is not covered by the tablebase."
|
"This position is not covered by the tablebase."
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defp blocked_reason({:error, :not_covered}) do
|
||||||
|
"This position is not covered by the tablebase."
|
||||||
|
end
|
||||||
|
|
||||||
defp blocked_reason({:error, reason}) do
|
defp blocked_reason({:error, reason}) do
|
||||||
"The tablebase is unavailable (#{inspect(reason)})."
|
"The tablebase is unavailable (#{inspect(reason)})."
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ defmodule Chesstrainer.MixProject do
|
|||||||
{:dns_cluster, "~> 0.2.0"},
|
{:dns_cluster, "~> 0.2.0"},
|
||||||
{:bandit, "~> 1.5"},
|
{:bandit, "~> 1.5"},
|
||||||
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"},
|
{:chex, git: "https://github.com/therealowenrees/chex.git", tag: "v0.2.0-alpha.2"},
|
||||||
|
{:rustler, "~> 0.38", runtime: false},
|
||||||
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}
|
{:dialyxir, "~> 1.4", only: [:dev, :test], runtime: false}
|
||||||
]
|
]
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -38,6 +38,7 @@
|
|||||||
"plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"},
|
"plug_crypto": {:hex, :plug_crypto, "2.1.1", "19bda8184399cb24afa10be734f84a16ea0a2bc65054e23a62bb10f06bc89491", [:mix], [], "hexpm", "6470bce6ffe41c8bd497612ffde1a7e4af67f36a15eea5f921af71cf3e11247c"},
|
||||||
"postgrex": {:hex, :postgrex, "0.22.2", "4aec14df2a72722aee92492566edbeeb44e233ecb86b1915d03136297ef1385d", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8946382ddb06294f56026ac4278b3cc212bac8a2c82ed68b4087819ed1abc53b"},
|
"postgrex": {:hex, :postgrex, "0.22.2", "4aec14df2a72722aee92492566edbeeb44e233ecb86b1915d03136297ef1385d", [:mix], [{:db_connection, "~> 2.9", [hex: :db_connection, repo: "hexpm", optional: false]}, {:decimal, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:table, "~> 0.1.0", [hex: :table, repo: "hexpm", optional: true]}], "hexpm", "8946382ddb06294f56026ac4278b3cc212bac8a2c82ed68b4087819ed1abc53b"},
|
||||||
"req": {:hex, :req, "0.6.2", "b9b2024f35bcf60a92cc8cad2eaaf9d4e7aace463ff74be1afe5986830184413", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "cc9cd30a2ddd04989929b887178e1610c940456d962c6c3a52df6146d2eef9bf"},
|
"req": {:hex, :req, "0.6.2", "b9b2024f35bcf60a92cc8cad2eaaf9d4e7aace463ff74be1afe5986830184413", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:ezstd, "~> 1.0", [hex: :ezstd, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "cc9cd30a2ddd04989929b887178e1610c940456d962c6c3a52df6146d2eef9bf"},
|
||||||
|
"rustler": {:hex, :rustler, "0.38.0", "7a8906998ff0d28e3021c0a73264abcda719bda344b2e58307c6805b0f87c9b4", [:mix], [{:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "704c03c1bf66be12b031c5a389347b91c81c5cb819a24b068b0de36fe4a5652a"},
|
||||||
"swoosh": {:hex, :swoosh, "1.26.1", "2989f1089e3cf1a938bbd3908c11d7dba8c8a4fe78801a7762d26f01bdbb32b4", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, ">= 1.9.0 and < 5.0.0", [hex: :hackney, repo: "hexpm", optional: true]}, {:idna, ">= 6.0.0 and < 8.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5.10 or ~> 0.6 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "8ad197c025102bbcbaffcd67c10ff7b390746c32f534ff5158891b149460118e"},
|
"swoosh": {:hex, :swoosh, "1.26.1", "2989f1089e3cf1a938bbd3908c11d7dba8c8a4fe78801a7762d26f01bdbb32b4", [:mix], [{:bandit, ">= 1.0.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:cowboy, "~> 1.1 or ~> 2.4", [hex: :cowboy, repo: "hexpm", optional: true]}, {:ex_aws, "~> 2.1", [hex: :ex_aws, repo: "hexpm", optional: true]}, {:finch, "~> 0.6", [hex: :finch, repo: "hexpm", optional: true]}, {:gen_smtp, "~> 0.13 or ~> 1.0", [hex: :gen_smtp, repo: "hexpm", optional: true]}, {:hackney, ">= 1.9.0 and < 5.0.0", [hex: :hackney, repo: "hexpm", optional: true]}, {:idna, ">= 6.0.0 and < 8.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mail, "~> 0.2", [hex: :mail, repo: "hexpm", optional: true]}, {:mime, "~> 1.1 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mua, "~> 0.2.3", [hex: :mua, repo: "hexpm", optional: true]}, {:multipart, "~> 0.4", [hex: :multipart, repo: "hexpm", optional: true]}, {:plug, "~> 1.9", [hex: :plug, repo: "hexpm", optional: true]}, {:plug_cowboy, ">= 1.0.0", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:req, "~> 0.5.10 or ~> 0.6 or ~> 1.0", [hex: :req, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4.2 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "8ad197c025102bbcbaffcd67c10ff7b390746c32f534ff5158891b149460118e"},
|
||||||
"tailwind": {:hex, :tailwind, "0.5.1", "35435b13158c90d37da11e1cfc808755fca1d7b6c5ab87b1b19c5de87e2f0a10", [:mix], [], "hexpm", "c4e26302a59fec72abc5610ecb6ad2116d9aa31f31aab2d4b8eb6e95d25a689c"},
|
"tailwind": {:hex, :tailwind, "0.5.1", "35435b13158c90d37da11e1cfc808755fca1d7b6c5ab87b1b19c5de87e2f0a10", [:mix], [], "hexpm", "c4e26302a59fec72abc5610ecb6ad2116d9aa31f31aab2d4b8eb6e95d25a689c"},
|
||||||
"telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
|
"telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
|
||||||
|
|||||||
Generated
+149
@@ -0,0 +1,149 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cc"
|
||||||
|
version = "1.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b"
|
||||||
|
dependencies = [
|
||||||
|
"find-msvc-tools",
|
||||||
|
"shlex",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fathom_nif"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"rustler",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "find-msvc-tools"
|
||||||
|
version = "0.1.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "inventory"
|
||||||
|
version = "0.3.25"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c"
|
||||||
|
dependencies = [
|
||||||
|
"rustversion",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.191"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libloading"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.107"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-lite"
|
||||||
|
version = "0.1.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustler"
|
||||||
|
version = "0.38.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "60ac8495cb6091c1f8bd0c3bb816cd4e6f0a073f396d77eb602cb7f0615212de"
|
||||||
|
dependencies = [
|
||||||
|
"inventory",
|
||||||
|
"libc",
|
||||||
|
"libloading",
|
||||||
|
"regex-lite",
|
||||||
|
"rustler_codegen",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustler_codegen"
|
||||||
|
version = "0.38.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "780a2a6b7e3cfac35820473f85cec1cd84d1bdd37ebcb4e24fb126ef0f074838"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"inventory",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustversion"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "shlex"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "2.0.119"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "fathom_nif"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "fathom_nif"
|
||||||
|
crate-type = ["cdylib"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
rustler = "0.38"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
cc = "1"
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
fn main() {
|
||||||
|
for file in [
|
||||||
|
"vendor/fathom/src/tbprobe.c",
|
||||||
|
"vendor/fathom/src/tbchess.c",
|
||||||
|
"vendor/fathom/src/tbprobe.h",
|
||||||
|
"vendor/fathom/src/tbconfig.h",
|
||||||
|
"vendor/fathom/src/stdendian.h",
|
||||||
|
"csrc/wrapper.c",
|
||||||
|
] {
|
||||||
|
println!("cargo:rerun-if-changed={file}");
|
||||||
|
}
|
||||||
|
|
||||||
|
cc::Build::new()
|
||||||
|
.file("vendor/fathom/src/tbprobe.c")
|
||||||
|
.file("csrc/wrapper.c")
|
||||||
|
.include("vendor/fathom/src")
|
||||||
|
.flag_if_supported("-std=gnu99")
|
||||||
|
.flag_if_supported("-O2")
|
||||||
|
.warnings(false)
|
||||||
|
.compile("fathom");
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/*
|
||||||
|
* Thin C shim over Fathom's inline API so Rust can call stable symbols.
|
||||||
|
*/
|
||||||
|
#include <stdbool.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include "tbprobe.h"
|
||||||
|
|
||||||
|
bool fathom_init(const char *path) { return tb_init(path); }
|
||||||
|
|
||||||
|
void fathom_free(void) { tb_free(); }
|
||||||
|
|
||||||
|
unsigned fathom_largest(void) { return TB_LARGEST; }
|
||||||
|
|
||||||
|
unsigned fathom_probe_root(uint64_t white, uint64_t black, uint64_t kings,
|
||||||
|
uint64_t queens, uint64_t rooks, uint64_t bishops,
|
||||||
|
uint64_t knights, uint64_t pawns, unsigned rule50,
|
||||||
|
unsigned castling, unsigned ep, bool turn,
|
||||||
|
unsigned *results) {
|
||||||
|
return tb_probe_root(white, black, kings, queens, rooks, bishops, knights,
|
||||||
|
pawns, rule50, castling, ep, turn, results);
|
||||||
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
use std::ffi::CString;
|
||||||
|
use std::os::raw::c_char;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use rustler::types::tuple::make_tuple;
|
||||||
|
use rustler::{Atom, Encoder, Env, Term};
|
||||||
|
|
||||||
|
mod atoms {
|
||||||
|
rustler::atoms! {
|
||||||
|
win,
|
||||||
|
cursed_win,
|
||||||
|
draw,
|
||||||
|
blessed_loss,
|
||||||
|
loss,
|
||||||
|
checkmate,
|
||||||
|
stalemate,
|
||||||
|
failed,
|
||||||
|
unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fathom WDL codes (see tbprobe.h).
|
||||||
|
const TB_LOSS: u32 = 0;
|
||||||
|
const TB_BLESSED_LOSS: u32 = 1;
|
||||||
|
const TB_DRAW: u32 = 2;
|
||||||
|
const TB_CURSED_WIN: u32 = 3;
|
||||||
|
const TB_WIN: u32 = 4;
|
||||||
|
|
||||||
|
const TB_MAX_MOVES: usize = 192 + 1;
|
||||||
|
|
||||||
|
const TB_RESULT_FAILED: u32 = 0xFFFF_FFFF;
|
||||||
|
const TB_RESULT_CHECKMATE: u32 = 4; // TB_SET_WDL(0, TB_WIN)
|
||||||
|
const TB_RESULT_STALEMATE: u32 = 2; // TB_SET_WDL(0, TB_DRAW)
|
||||||
|
|
||||||
|
extern "C" {
|
||||||
|
fn fathom_init(path: *const c_char) -> bool;
|
||||||
|
fn fathom_largest() -> u32;
|
||||||
|
fn fathom_probe_root(
|
||||||
|
white: u64,
|
||||||
|
black: u64,
|
||||||
|
kings: u64,
|
||||||
|
queens: u64,
|
||||||
|
rooks: u64,
|
||||||
|
bishops: u64,
|
||||||
|
knights: u64,
|
||||||
|
pawns: u64,
|
||||||
|
rule50: u32,
|
||||||
|
castling: u32,
|
||||||
|
ep: u32,
|
||||||
|
turn: bool,
|
||||||
|
results: *mut u32,
|
||||||
|
) -> u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
path: Option<String>,
|
||||||
|
largest: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fathom keeps global probe state and `tb_probe_root` is not thread safe, so
|
||||||
|
// probes are serialised through this lock.
|
||||||
|
static STATE: Mutex<State> = Mutex::new(State {
|
||||||
|
path: None,
|
||||||
|
largest: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Position {
|
||||||
|
white: u64,
|
||||||
|
black: u64,
|
||||||
|
kings: u64,
|
||||||
|
queens: u64,
|
||||||
|
rooks: u64,
|
||||||
|
bishops: u64,
|
||||||
|
knights: u64,
|
||||||
|
pawns: u64,
|
||||||
|
turn: bool,
|
||||||
|
castling: u32,
|
||||||
|
ep: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn square(file: u32, rank: u32) -> u32 {
|
||||||
|
rank * 8 + file
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bit(square: u32) -> u64 {
|
||||||
|
1u64 << square
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_fen(fen: &str) -> Result<Position, String> {
|
||||||
|
let mut fields = fen.split_whitespace();
|
||||||
|
let board = fields.next().ok_or("missing board")?;
|
||||||
|
let active = fields.next().ok_or("missing active colour")?;
|
||||||
|
let castling = fields.next().unwrap_or("-");
|
||||||
|
let en_passant = fields.next().unwrap_or("-");
|
||||||
|
|
||||||
|
let turn = match active {
|
||||||
|
"w" => true,
|
||||||
|
"b" => false,
|
||||||
|
other => return Err(format!("invalid active colour: {other}")),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut pos = Position {
|
||||||
|
turn,
|
||||||
|
..Position::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let ranks: Vec<&str> = board.split('/').collect();
|
||||||
|
if ranks.len() != 8 {
|
||||||
|
return Err(format!("board must have 8 ranks, got {}", ranks.len()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index, rank) in ranks.iter().enumerate() {
|
||||||
|
let rank_index = (7 - index) as u32;
|
||||||
|
let mut file: u32 = 0;
|
||||||
|
|
||||||
|
for piece in rank.chars() {
|
||||||
|
match piece {
|
||||||
|
'1'..='8' => file += piece.to_digit(10).unwrap(),
|
||||||
|
_ => {
|
||||||
|
if file >= 8 {
|
||||||
|
return Err(format!("rank {index} overflows 8 squares"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let square = square(file, rank_index);
|
||||||
|
let b = bit(square);
|
||||||
|
|
||||||
|
match piece.to_ascii_lowercase() {
|
||||||
|
'k' => pos.kings |= b,
|
||||||
|
'q' => pos.queens |= b,
|
||||||
|
'r' => pos.rooks |= b,
|
||||||
|
'b' => pos.bishops |= b,
|
||||||
|
'n' => pos.knights |= b,
|
||||||
|
'p' => pos.pawns |= b,
|
||||||
|
_ => return Err(format!("unexpected character '{piece}' in board")),
|
||||||
|
}
|
||||||
|
|
||||||
|
if piece.is_ascii_uppercase() {
|
||||||
|
pos.white |= b;
|
||||||
|
} else {
|
||||||
|
pos.black |= b;
|
||||||
|
}
|
||||||
|
|
||||||
|
file += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if file > 8 {
|
||||||
|
return Err(format!("rank {index} overflows 8 squares"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if file != 8 {
|
||||||
|
return Err(format!("rank {index} does not sum to 8 squares"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.castling = parse_castling(castling)?;
|
||||||
|
let ep = parse_en_passant(&pos, en_passant)?;
|
||||||
|
pos.ep = ep;
|
||||||
|
|
||||||
|
Ok(pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_castling(field: &str) -> Result<u32, String> {
|
||||||
|
if field == "-" {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut bits = 0u32;
|
||||||
|
for piece in field.chars() {
|
||||||
|
bits |= match piece {
|
||||||
|
'K' => 0x1,
|
||||||
|
'Q' => 0x2,
|
||||||
|
'k' => 0x4,
|
||||||
|
'q' => 0x8,
|
||||||
|
other => return Err(format!("invalid castling field: {other}")),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(bits)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses the en-passant square, dropping it unless a pawn of the side to move
|
||||||
|
/// can actually capture, matching how Syzygy positions are canonicalised.
|
||||||
|
fn parse_en_passant(pos: &Position, field: &str) -> Result<u32, String> {
|
||||||
|
if field == "-" {
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes = field.as_bytes();
|
||||||
|
if bytes.len() != 2 {
|
||||||
|
return Err(format!("invalid en passant field: {field}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let file = match bytes[0] {
|
||||||
|
file @ b'a'..=b'h' => (file - b'a') as u32,
|
||||||
|
_ => return Err(format!("invalid en passant file: {field}")),
|
||||||
|
};
|
||||||
|
let rank = match bytes[1] {
|
||||||
|
rank @ b'1'..=b'8' => (rank - b'1') as u32,
|
||||||
|
_ => return Err(format!("invalid en passant rank: {field}")),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut mask = 0u64;
|
||||||
|
let capturing_pawns = if pos.turn {
|
||||||
|
// White to move: ep on rank 6, white pawns capture from rank 5.
|
||||||
|
if file > 0 {
|
||||||
|
mask |= bit(square(file - 1, 4));
|
||||||
|
}
|
||||||
|
if file < 7 {
|
||||||
|
mask |= bit(square(file + 1, 4));
|
||||||
|
}
|
||||||
|
pos.white & pos.pawns
|
||||||
|
} else {
|
||||||
|
// Black to move: ep on rank 3, black pawns capture from rank 4.
|
||||||
|
if file > 0 {
|
||||||
|
mask |= bit(square(file - 1, 3));
|
||||||
|
}
|
||||||
|
if file < 7 {
|
||||||
|
mask |= bit(square(file + 1, 3));
|
||||||
|
}
|
||||||
|
pos.black & pos.pawns
|
||||||
|
};
|
||||||
|
|
||||||
|
if capturing_pawns & mask == 0 {
|
||||||
|
Ok(0)
|
||||||
|
} else {
|
||||||
|
Ok(square(file, rank))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wdl_atom(wdl: u32) -> Atom {
|
||||||
|
match wdl {
|
||||||
|
TB_LOSS => atoms::loss(),
|
||||||
|
TB_BLESSED_LOSS => atoms::blessed_loss(),
|
||||||
|
TB_DRAW => atoms::draw(),
|
||||||
|
TB_CURSED_WIN => atoms::cursed_win(),
|
||||||
|
TB_WIN => atoms::win(),
|
||||||
|
_ => atoms::unknown(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `{wdl, from, to, promotes, ep, dtz}` for an encoded TB_RESULT.
|
||||||
|
fn move_tuple<'a>(env: Env<'a>, result: u32) -> Result<Term<'a>, String> {
|
||||||
|
let wdl = wdl_atom(result & 0x0000_000F);
|
||||||
|
let from = ((result & 0x0000_FC00) >> 10) as i64;
|
||||||
|
let to = ((result & 0x0000_03F0) >> 4) as i64;
|
||||||
|
let promotes = ((result & 0x0007_0000) >> 16) as i64;
|
||||||
|
let ep = ((result & 0x0008_0000) >> 19) as i64;
|
||||||
|
let dtz = ((result & 0xFFF0_0000) >> 20) as i64;
|
||||||
|
|
||||||
|
Ok(make_tuple(
|
||||||
|
env,
|
||||||
|
&[
|
||||||
|
wdl.encode(env),
|
||||||
|
from.encode(env),
|
||||||
|
to.encode(env),
|
||||||
|
promotes.encode(env),
|
||||||
|
ep.encode(env),
|
||||||
|
dtz.encode(env),
|
||||||
|
],
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialises Fathom against `path` and returns the largest piece count found.
|
||||||
|
#[rustler::nif(schedule = "DirtyIo")]
|
||||||
|
fn init(path: String) -> Result<u32, String> {
|
||||||
|
let mut state = STATE
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "fathom lock poisoned".to_string())?;
|
||||||
|
|
||||||
|
if state.path.as_deref() != Some(path.as_str()) {
|
||||||
|
let c_path = CString::new(path.clone()).map_err(|_| "path contains NUL")?;
|
||||||
|
|
||||||
|
if unsafe { fathom_init(c_path.as_ptr()) } {
|
||||||
|
state.largest = unsafe { fathom_largest() };
|
||||||
|
state.path = Some(path);
|
||||||
|
} else {
|
||||||
|
return Err(format!("fathom failed to initialise from {path}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(state.largest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probes the position and returns `{root, moves}`.
|
||||||
|
///
|
||||||
|
/// `root` is either an outcome atom (`:checkmate`, `:stalemate`, `:failed`) or
|
||||||
|
/// `{wdl, from, to, promotes, ep, dtz}`. `moves` is a list of the same move
|
||||||
|
/// tuples, one per legal move.
|
||||||
|
#[rustler::nif(schedule = "DirtyCpu")]
|
||||||
|
fn probe<'a>(env: Env<'a>, fen: String) -> Result<Term<'a>, String> {
|
||||||
|
let pos = parse_fen(&fen)?;
|
||||||
|
|
||||||
|
let state = STATE
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "fathom lock poisoned".to_string())?;
|
||||||
|
|
||||||
|
if state.path.is_none() {
|
||||||
|
return Err("fathom not initialised".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut results = [0u32; TB_MAX_MOVES];
|
||||||
|
// rule50 is fixed at 0 so the result is position-level, matching the cache.
|
||||||
|
let root = unsafe {
|
||||||
|
fathom_probe_root(
|
||||||
|
pos.white,
|
||||||
|
pos.black,
|
||||||
|
pos.kings,
|
||||||
|
pos.queens,
|
||||||
|
pos.rooks,
|
||||||
|
pos.bishops,
|
||||||
|
pos.knights,
|
||||||
|
pos.pawns,
|
||||||
|
0,
|
||||||
|
pos.castling,
|
||||||
|
pos.ep,
|
||||||
|
pos.turn,
|
||||||
|
results.as_mut_ptr(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let (root_term, moves) = match root {
|
||||||
|
TB_RESULT_FAILED => (atoms::failed().encode(env), Vec::new()),
|
||||||
|
TB_RESULT_CHECKMATE => (atoms::checkmate().encode(env), Vec::new()),
|
||||||
|
TB_RESULT_STALEMATE => (atoms::stalemate().encode(env), Vec::new()),
|
||||||
|
other => {
|
||||||
|
let mut moves = Vec::new();
|
||||||
|
for &result in results.iter() {
|
||||||
|
if result == TB_RESULT_FAILED {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
moves.push(move_tuple(env, result)?);
|
||||||
|
}
|
||||||
|
(move_tuple(env, other)?, moves)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(make_tuple(env, &[root_term, moves.encode(env)]))
|
||||||
|
}
|
||||||
|
|
||||||
|
rustler::init!("Elixir.Chesstrainer.Endgames.Tablebase.Fathom");
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2013-2018 Ronald de Man
|
||||||
|
Copyright (c) 2015 basil00
|
||||||
|
Copyright (c) 2016-2025 by Jon Dart
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
||||||
+286
@@ -0,0 +1,286 @@
|
|||||||
|
#ifndef _STDENDIAN_H_
|
||||||
|
#define _STDENDIAN_H_
|
||||||
|
/* from https://gist.github.com/michaeljclark/3b4fd912f6fa8bb598b3 */
|
||||||
|
/* modified to use functions not macros for bswap */
|
||||||
|
/* and added a fix for Cygwin */
|
||||||
|
/*
|
||||||
|
* stdendian.h
|
||||||
|
*
|
||||||
|
* This header defines the following endian macros as defined here:
|
||||||
|
* http://austingroupbugs.net/view.php?id=162
|
||||||
|
*
|
||||||
|
* BYTE_ORDER this macro shall have a value equal to one
|
||||||
|
* of the *_ENDIAN macros in this header.
|
||||||
|
* LITTLE_ENDIAN if BYTE_ORDER == LITTLE_ENDIAN, the host
|
||||||
|
* byte order is from least significant to
|
||||||
|
* most significant.
|
||||||
|
* BIG_ENDIAN if BYTE_ORDER == BIG_ENDIAN, the host byte
|
||||||
|
* order is from most significant to least
|
||||||
|
* significant.
|
||||||
|
*
|
||||||
|
* The following are defined as macros:
|
||||||
|
*
|
||||||
|
* uint16_t bswap16(uint16_t x);
|
||||||
|
* uint32_t bswap32(uint32_t x);
|
||||||
|
* uint64_t bswap64(uint64_t x);
|
||||||
|
|
||||||
|
* uint16_t htobe16(uint16_t x);
|
||||||
|
* uint16_t htole16(uint16_t x);
|
||||||
|
* uint16_t be16toh(uint16_t x);
|
||||||
|
* uint16_t le16toh(uint16_t x);
|
||||||
|
*
|
||||||
|
* uint32_t htobe32(uint32_t x);
|
||||||
|
* uint32_t htole32(uint32_t x);
|
||||||
|
* uint32_t be32toh(uint32_t x);
|
||||||
|
* uint32_t le32toh(uint32_t x);
|
||||||
|
*
|
||||||
|
* uint64_t htobe64(uint64_t x);
|
||||||
|
* uint64_t htole64(uint64_t x);
|
||||||
|
* uint64_t be64toh(uint64_t x);
|
||||||
|
* uint64_t le64toh(uint64_t x);
|
||||||
|
*
|
||||||
|
* The header defines the following macro for OpenCL compatibility
|
||||||
|
* https://www.khronos.org/registry/cl/sdk/2.0/docs/man/xhtml/preprocessorDirectives.html
|
||||||
|
*
|
||||||
|
* __ENDIAN_LITTLE__ if BYTE_ORDER == LITTLE_ENDIAN then this
|
||||||
|
* macro is present for OpenCL compatibility
|
||||||
|
*
|
||||||
|
* The implementation provides a uniform interface to endian macros using only
|
||||||
|
* system headers on recent Linux, Darwin, FreeBSD, Solaris and Windows systems.
|
||||||
|
*
|
||||||
|
* This approach is intended to avoid the need for preflight configure scripts.
|
||||||
|
* An alternative approach would be to test compiler CPU architecture marcros.
|
||||||
|
*
|
||||||
|
* This header has had *limited* testing on recent C11/C++11 compilers and is
|
||||||
|
* based on the austin bug tracker interface, manpages, and headers present in
|
||||||
|
* Linux, FreeBSD, Windows, Solaris and Darwin.
|
||||||
|
*
|
||||||
|
* The header uses __builtin_bswapXX intrinsic with GCC/Clang (__GNUC__) on
|
||||||
|
* platforms that do not provide bswap16, bswap32, bswap64 (Darwin)
|
||||||
|
*
|
||||||
|
* Public Domain.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* requires C11 or C++11 */
|
||||||
|
#if defined (__cplusplus)
|
||||||
|
#include <cstdint>
|
||||||
|
#elif !defined (__OPENCL_VERSION__)
|
||||||
|
#include <stdint.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Linux / GLIBC */
|
||||||
|
#if defined(__linux__) || defined(__GLIBC__) || defined(__CYGWIN__)
|
||||||
|
#include <endian.h>
|
||||||
|
#include <byteswap.h>
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#define __BSWAP_DEFINED 1
|
||||||
|
#define __HOSTSWAP_DEFINED 1
|
||||||
|
// NDK defines _BYTE_ORDER etc
|
||||||
|
#ifndef _BYTE_ORDER
|
||||||
|
#define _BYTE_ORDER __BYTE_ORDER
|
||||||
|
#define _LITTLE_ENDIAN __LITTLE_ENDIAN
|
||||||
|
#define _BIG_ENDIAN __BIG_ENDIAN
|
||||||
|
#endif
|
||||||
|
#define bswap16(x) bswap_16(x)
|
||||||
|
#define bswap32(x) bswap_32(x)
|
||||||
|
#define bswap64(x) bswap_64(x)
|
||||||
|
#endif /* __linux__ || __GLIBC__ */
|
||||||
|
|
||||||
|
/* BSD */
|
||||||
|
#if defined(__FreeBSD__) || defined(__NetBSD__) || \
|
||||||
|
defined(__DragonFly__) || defined(__OpenBSD__)
|
||||||
|
#include <sys/endian.h>
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#define __BSWAP_DEFINED 1
|
||||||
|
#define __HOSTSWAP_DEFINED 1
|
||||||
|
#endif /* BSD */
|
||||||
|
|
||||||
|
/* Solaris */
|
||||||
|
#if defined (sun)
|
||||||
|
#include <sys/isa_defs.h>
|
||||||
|
/* sun headers don't set a value for _LITTLE_ENDIAN or _BIG_ENDIAN */
|
||||||
|
#if defined(_LITTLE_ENDIAN)
|
||||||
|
#undef _LITTLE_ENDIAN
|
||||||
|
#define _LITTLE_ENDIAN 1234
|
||||||
|
#define _BIG_ENDIAN 4321
|
||||||
|
#define _BYTE_ORDER _LITTLE_ENDIAN
|
||||||
|
#elif defined(_BIG_ENDIAN)
|
||||||
|
#undef _BIG_ENDIAN
|
||||||
|
#define _LITTLE_ENDIAN 1234
|
||||||
|
#define _BIG_ENDIAN 4321
|
||||||
|
#define _BYTE_ORDER _BIG_ENDIAN
|
||||||
|
#endif
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#endif /* sun */
|
||||||
|
|
||||||
|
/* Windows */
|
||||||
|
/* assumes all Microsoft targets are little endian. */
|
||||||
|
/* Emscripten (emcc) also currently assumes little endian. */
|
||||||
|
#if defined(_WIN32) || defined(_MSC_VER) || defined(__EMSCRIPTEN__)
|
||||||
|
#define _LITTLE_ENDIAN 1234
|
||||||
|
#define _BIG_ENDIAN 4321
|
||||||
|
#define _BYTE_ORDER _LITTLE_ENDIAN
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#endif /* _MSC_VER */
|
||||||
|
|
||||||
|
/* OS X */
|
||||||
|
#if defined(__APPLE__)
|
||||||
|
#include <machine/endian.h>
|
||||||
|
#define _BYTE_ORDER BYTE_ORDER
|
||||||
|
#define _LITTLE_ENDIAN LITTLE_ENDIAN
|
||||||
|
#define _BIG_ENDIAN BIG_ENDIAN
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#endif /* __APPLE__ */
|
||||||
|
|
||||||
|
/* OpenCL */
|
||||||
|
#if defined (__OPENCL_VERSION__)
|
||||||
|
#define _LITTLE_ENDIAN 1234
|
||||||
|
#define __BIG_ENDIAN 4321
|
||||||
|
#if defined (__ENDIAN_LITTLE__)
|
||||||
|
#define _BYTE_ORDER _LITTLE_ENDIAN
|
||||||
|
#else
|
||||||
|
#define _BYTE_ORDER _BIG_ENDIAN
|
||||||
|
#endif
|
||||||
|
#define bswap16(x) as_ushort(as_uchar2(ushort(x)).s1s0)
|
||||||
|
#define bswap32(x) as_uint(as_uchar4(uint(x)).s3s2s1s0)
|
||||||
|
#define bswap64(x) as_ulong(as_uchar8(ulong(x)).s7s6s5s4s3s2s1s0)
|
||||||
|
#define __ENDIAN_DEFINED 1
|
||||||
|
#define __BSWAP_DEFINED 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Unknown */
|
||||||
|
#if !__ENDIAN_DEFINED
|
||||||
|
#error Could not determine CPU byte order
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* POSIX - http://austingroupbugs.net/view.php?id=162 */
|
||||||
|
#ifndef BYTE_ORDER
|
||||||
|
#define BYTE_ORDER _BYTE_ORDER
|
||||||
|
#endif
|
||||||
|
#ifndef LITTLE_ENDIAN
|
||||||
|
#define LITTLE_ENDIAN _LITTLE_ENDIAN
|
||||||
|
#endif
|
||||||
|
#ifndef BIG_ENDIAN
|
||||||
|
#define BIG_ENDIAN _BIG_ENDIAN
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* OpenCL compatibility - define __ENDIAN_LITTLE__ on little endian systems */
|
||||||
|
#if _BYTE_ORDER == _LITTLE_ENDIAN
|
||||||
|
#if !defined (__ENDIAN_LITTLE__)
|
||||||
|
#define __ENDIAN_LITTLE__ 1
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Byte swap macros */
|
||||||
|
#if !__BSWAP_DEFINED
|
||||||
|
|
||||||
|
#ifndef bswap16
|
||||||
|
/* handle missing __builtin_bswap16 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52624 */
|
||||||
|
#if defined __GNUC__
|
||||||
|
#define bswap16(x) __builtin_bswap16(x)
|
||||||
|
#else
|
||||||
|
inline uint16_t bswap16(uint16_t x) {
|
||||||
|
return (uint16_t)((((uint16_t) (x) & 0xff00) >> 8) | \
|
||||||
|
(((uint16_t) (x) & 0x00ff) << 8));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef bswap32
|
||||||
|
#if defined __GNUC__
|
||||||
|
#define bswap32(x) __builtin_bswap32(x)
|
||||||
|
#else
|
||||||
|
inline uint32_t bswap32(uint32_t x) {
|
||||||
|
return (( x & 0xff000000) >> 24) | \
|
||||||
|
(( x & 0x00ff0000) >> 8) | \
|
||||||
|
(( x & 0x0000ff00) << 8) | \
|
||||||
|
(( x & 0x000000ff) << 24);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef bswap64
|
||||||
|
#if defined __GNUC__
|
||||||
|
#define bswap64(x) __builtin_bswap64(x)
|
||||||
|
#else
|
||||||
|
inline uint64_t bswap64(uint64_t x) {
|
||||||
|
return (( x & 0xff00000000000000ull) >> 56) | \
|
||||||
|
(( x & 0x00ff000000000000ull) >> 40) | \
|
||||||
|
(( x & 0x0000ff0000000000ull) >> 24) | \
|
||||||
|
(( x & 0x000000ff00000000ull) >> 8) | \
|
||||||
|
(( x & 0x00000000ff000000ull) << 8) | \
|
||||||
|
(( x & 0x0000000000ff0000ull) << 24) | \
|
||||||
|
(( x & 0x000000000000ff00ull) << 40) | \
|
||||||
|
(( x & 0x00000000000000ffull) << 56);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Host swap macros */
|
||||||
|
#ifndef __HOSTSWAP_DEFINED
|
||||||
|
#if __BYTE_ORDER == __LITTLE_ENDIAN
|
||||||
|
#define htobe16(x) bswap16((x))
|
||||||
|
#define htole16(x) ((uint16_t)(x))
|
||||||
|
#define be16toh(x) bswap16((x))
|
||||||
|
#define le16toh(x) ((uint16_t)(x))
|
||||||
|
|
||||||
|
#define htobe32(x) bswap32((x))
|
||||||
|
#define htole32(x) ((uint32_t)(x))
|
||||||
|
#define be32toh(x) bswap32((x))
|
||||||
|
#define le32toh(x) ((uint32_t)(x))
|
||||||
|
|
||||||
|
#define htobe64(x) bswap64((x))
|
||||||
|
#define htole64(x) ((uint64_t)(x))
|
||||||
|
#define be64toh(x) bswap64((x))
|
||||||
|
#define le64toh(x) ((uint64_t)(x))
|
||||||
|
#elif __BYTE_ORDER == __BIG_ENDIAN
|
||||||
|
#define htobe16(x) ((uint16_t)(x))
|
||||||
|
#define htole16(x) bswap16((x))
|
||||||
|
#define be16toh(x) ((uint16_t)(x))
|
||||||
|
#define le16toh(x) bswap16((x))
|
||||||
|
|
||||||
|
#define htobe32(x) ((uint32_t)(x))
|
||||||
|
#define htole32(x) bswap32((x))
|
||||||
|
#define be32toh(x) ((uint32_t)(x))
|
||||||
|
#define le64toh(x) bswap64((x))
|
||||||
|
|
||||||
|
#define htobe64(x) ((uint64_t)(x))
|
||||||
|
#define htole64(x) bswap64((x))
|
||||||
|
#define be64toh(x) ((uint64_t)(x))
|
||||||
|
#define le32toh(x) bswap32((x))
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdendian.h>
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
|
||||||
|
#if BYTE_ORDER == LITTLE_ENDIAN
|
||||||
|
printf("little endian\n");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if BYTE_ORDER == BIG_ENDIAN
|
||||||
|
printf("big endian\n");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
printf("bswap16(%04x) %04x\n", 0xf0e0, bswap16(0xf0e0));
|
||||||
|
printf("htobe16(%04x) %04x\n", 0xf0e0, htobe16(0xf0e0));
|
||||||
|
printf("htole16(%04x) %04x\n", 0xf0e0, htole16(0xf0e0));
|
||||||
|
|
||||||
|
printf("bswap32(%08x) %08x\n", 0xf0e0d0c0, bswap32(0xf0e0d0c0));
|
||||||
|
printf("htobe32(%08x) %08x\n", 0xf0e0d0c0, htobe32(0xf0e0d0c0));
|
||||||
|
printf("htole32(%08x) %08x\n", 0xf0e0d0c0, htole32(0xf0e0d0c0));
|
||||||
|
|
||||||
|
printf("bswap64(%016llx) %016llx\n", 0xf0e0d0c0b0a09080ULL, bswap64(0xf0e0d0c0b0a09080ULL));
|
||||||
|
printf("htobe64(%016llx) %016llx\n", 0xf0e0d0c0b0a09080ULL, htobe64(0xf0e0d0c0b0a09080ULL));
|
||||||
|
printf("htole64(%016llx) %016llx\n", 0xf0e0d0c0b0a09080ULL, htole64(0xf0e0d0c0b0a09080ULL));
|
||||||
|
}
|
||||||
|
|
||||||
|
*/
|
||||||
|
#endif
|
||||||
+1050
File diff suppressed because it is too large
Load Diff
+150
@@ -0,0 +1,150 @@
|
|||||||
|
/*
|
||||||
|
* tbconfig.h
|
||||||
|
* (C) 2015 basil, all rights reserved,
|
||||||
|
* Modifications Copyright 2016-2017 Jon Dart
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
* copy of this software and associated documentation files (the "Software"),
|
||||||
|
* to deal in the Software without restriction, including without limitation
|
||||||
|
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
* and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
* Software is furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
* DEALINGS IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef TBCONFIG_H
|
||||||
|
#define TBCONFIG_H
|
||||||
|
|
||||||
|
/****************************************************************************/
|
||||||
|
/* BUILD CONFIG: */
|
||||||
|
/****************************************************************************/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_CUSTOM_POP_COUNT to override the internal popcount
|
||||||
|
* implementation. To do this supply a macro or function definition
|
||||||
|
* here:
|
||||||
|
*/
|
||||||
|
/* #define TB_CUSTOM_POP_COUNT(x) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_CUSTOM_LSB to override the internal lsb
|
||||||
|
* implementation. To do this supply a macro or function definition
|
||||||
|
* here:
|
||||||
|
*/
|
||||||
|
/* #define TB_CUSTOM_LSB(x) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_NO_STDINT if you do not want to use <stdint.h> or it is not
|
||||||
|
* available.
|
||||||
|
*/
|
||||||
|
/* #define TB_NO_STDINT */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_NO_STDBOOL if you do not want to use <stdbool.h> or it is not
|
||||||
|
* available or unnecessary (e.g. C++).
|
||||||
|
*/
|
||||||
|
/* #define TB_NO_STDBOOL */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_NO_THREADS if your program is not multi-threaded.
|
||||||
|
*/
|
||||||
|
/* #define TB_NO_THREADS */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_NO_HELPER_API if you do not need the helper API.
|
||||||
|
*/
|
||||||
|
/* #define TB_NO_HELPER_API */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_NO_HW_POP_COUNT if there is no hardware popcount instruction.
|
||||||
|
*
|
||||||
|
* Note: if defined, TB_CUSTOM_POP_COUNT is always used in preference
|
||||||
|
* to any built-in popcount functions.
|
||||||
|
*
|
||||||
|
* If no custom popcount function is defined, and if the following
|
||||||
|
* define is not set, the code will attempt to use an available hardware
|
||||||
|
* popcnt (currently supported on x86_64 architecture only) and otherwise
|
||||||
|
* will fall back to a software implementation.
|
||||||
|
*/
|
||||||
|
/* #define TB_NO_HW_POP_COUNT */
|
||||||
|
|
||||||
|
/***************************************************************************/
|
||||||
|
/* SCORING CONSTANTS */
|
||||||
|
/***************************************************************************/
|
||||||
|
/*
|
||||||
|
* Fathom can produce scores for tablebase moves. These depend on the
|
||||||
|
* value of a pawn, and the magnitude of mate scores. The following
|
||||||
|
* constants are representative values but will likely need
|
||||||
|
* modification to adapt to an engine's own internal score values.
|
||||||
|
*/
|
||||||
|
#define TB_VALUE_PAWN 100 /* value of pawn in endgame */
|
||||||
|
#define TB_VALUE_MATE 32000
|
||||||
|
#define TB_VALUE_INFINITE 32767 /* value above all normal score values */
|
||||||
|
#define TB_VALUE_DRAW 0
|
||||||
|
#define TB_MAX_MATE_PLY 255
|
||||||
|
|
||||||
|
/***************************************************************************/
|
||||||
|
/* ENGINE INTEGRATION CONFIG */
|
||||||
|
/***************************************************************************/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* If you are integrating tbprobe into an engine, you can replace some of
|
||||||
|
* tbprobe's built-in functionality with that already provided by the engine.
|
||||||
|
* This is OPTIONAL. If no definition are provided then tbprobe will use its
|
||||||
|
* own internal defaults. That said, for engines it is generally a good idea
|
||||||
|
* to avoid redundancy.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_KING_ATTACKS(square) to return the king attacks bitboard for a
|
||||||
|
* king at `square'.
|
||||||
|
*/
|
||||||
|
/* #define TB_KING_ATTACKS(square) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_KNIGHT_ATTACKS(square) to return the knight attacks bitboard for
|
||||||
|
* a knight at `square'.
|
||||||
|
*/
|
||||||
|
/* #define TB_KNIGHT_ATTACKS(square) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_ROOK_ATTACKS(square, occ) to return the rook attacks bitboard
|
||||||
|
* for a rook at `square' assuming the given `occ' occupancy bitboard.
|
||||||
|
*/
|
||||||
|
/* #define TB_ROOK_ATTACKS(square, occ) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_BISHOP_ATTACKS(square, occ) to return the bishop attacks bitboard
|
||||||
|
* for a bishop at `square' assuming the given `occ' occupancy bitboard.
|
||||||
|
*/
|
||||||
|
/* #define TB_BISHOP_ATTACKS(square, occ) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_QUEEN_ATTACKS(square, occ) to return the queen attacks bitboard
|
||||||
|
* for a queen at `square' assuming the given `occ' occupancy bitboard.
|
||||||
|
* NOTE: If no definition is provided then tbprobe will use:
|
||||||
|
* TB_ROOK_ATTACKS(square, occ) | TB_BISHOP_ATTACKS(square, occ)
|
||||||
|
*/
|
||||||
|
/* #define TB_QUEEN_ATTACKS(square, occ) <DEFINITION> */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Define TB_PAWN_ATTACKS(square, color) to return the pawn attacks bitboard
|
||||||
|
* for a `color' pawn at `square'.
|
||||||
|
* NOTE: This definition must work for pawns on ranks 1 and 8. For example,
|
||||||
|
* a white pawn on e1 attacks d2 and f2. A black pawn on e1 attacks
|
||||||
|
* nothing. Etc.
|
||||||
|
* NOTE: This definition must not include en passant captures.
|
||||||
|
*/
|
||||||
|
/* #define TB_PAWN_ATTACKS(square, color) <DEFINITION> */
|
||||||
|
|
||||||
|
#endif
|
||||||
+2715
File diff suppressed because it is too large
Load Diff
+399
@@ -0,0 +1,399 @@
|
|||||||
|
/*
|
||||||
|
* tbprobe.h
|
||||||
|
* (C) 2015 basil, all rights reserved,
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||||
|
* copy of this software and associated documentation files (the "Software"),
|
||||||
|
* to deal in the Software without restriction, including without limitation
|
||||||
|
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||||
|
* and/or sell copies of the Software, and to permit persons to whom the
|
||||||
|
* Software is furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in
|
||||||
|
* all copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
* DEALINGS IN THE SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef TBPROBE_H
|
||||||
|
#define TBPROBE_H
|
||||||
|
|
||||||
|
#include <tbconfig.h>
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef TB_NO_STDINT
|
||||||
|
#include <stdint.h>
|
||||||
|
#else
|
||||||
|
typedef unsigned char uint8_t;
|
||||||
|
typedef unsigned short uint16_t;
|
||||||
|
typedef unsigned uint32_t;
|
||||||
|
typedef long long unsigned uint64_t;
|
||||||
|
typedef char int8_t;
|
||||||
|
typedef short int16_t;
|
||||||
|
typedef int int32_t;
|
||||||
|
typedef long long int64_t;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef TB_NO_STDBOOL
|
||||||
|
#include <stdbool.h>
|
||||||
|
#else
|
||||||
|
#ifndef __cplusplus
|
||||||
|
typedef uint8_t bool;
|
||||||
|
#define true 1
|
||||||
|
#define false 0
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Internal definitions. Do not call these functions directly.
|
||||||
|
*/
|
||||||
|
extern bool tb_init_impl(const char *_path);
|
||||||
|
extern unsigned tb_probe_wdl_impl(
|
||||||
|
uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn);
|
||||||
|
extern unsigned tb_probe_root_impl(
|
||||||
|
uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _rule50,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn,
|
||||||
|
unsigned *_results);
|
||||||
|
|
||||||
|
/****************************************************************************/
|
||||||
|
/* MAIN API */
|
||||||
|
/****************************************************************************/
|
||||||
|
|
||||||
|
#define TB_MAX_MOVES (192+1)
|
||||||
|
#define TB_MAX_CAPTURES 64
|
||||||
|
#define TB_MAX_PLY 256
|
||||||
|
#define TB_CASTLING_K 0x1 /* White king-side. */
|
||||||
|
#define TB_CASTLING_Q 0x2 /* White queen-side. */
|
||||||
|
#define TB_CASTLING_k 0x4 /* Black king-side. */
|
||||||
|
#define TB_CASTLING_q 0x8 /* Black queen-side. */
|
||||||
|
|
||||||
|
#define TB_LOSS 0 /* LOSS */
|
||||||
|
#define TB_BLESSED_LOSS 1 /* LOSS but 50-move draw */
|
||||||
|
#define TB_DRAW 2 /* DRAW */
|
||||||
|
#define TB_CURSED_WIN 3 /* WIN but 50-move draw */
|
||||||
|
#define TB_WIN 4 /* WIN */
|
||||||
|
|
||||||
|
#define TB_PROMOTES_NONE 0
|
||||||
|
#define TB_PROMOTES_QUEEN 1
|
||||||
|
#define TB_PROMOTES_ROOK 2
|
||||||
|
#define TB_PROMOTES_BISHOP 3
|
||||||
|
#define TB_PROMOTES_KNIGHT 4
|
||||||
|
|
||||||
|
#define TB_RESULT_WDL_MASK 0x0000000F
|
||||||
|
#define TB_RESULT_TO_MASK 0x000003F0
|
||||||
|
#define TB_RESULT_FROM_MASK 0x0000FC00
|
||||||
|
#define TB_RESULT_PROMOTES_MASK 0x00070000
|
||||||
|
#define TB_RESULT_EP_MASK 0x00080000
|
||||||
|
#define TB_RESULT_DTZ_MASK 0xFFF00000
|
||||||
|
#define TB_RESULT_WDL_SHIFT 0
|
||||||
|
#define TB_RESULT_TO_SHIFT 4
|
||||||
|
#define TB_RESULT_FROM_SHIFT 10
|
||||||
|
#define TB_RESULT_PROMOTES_SHIFT 16
|
||||||
|
#define TB_RESULT_EP_SHIFT 19
|
||||||
|
#define TB_RESULT_DTZ_SHIFT 20
|
||||||
|
|
||||||
|
#define TB_GET_WDL(_res) \
|
||||||
|
(((_res) & TB_RESULT_WDL_MASK) >> TB_RESULT_WDL_SHIFT)
|
||||||
|
#define TB_GET_TO(_res) \
|
||||||
|
(((_res) & TB_RESULT_TO_MASK) >> TB_RESULT_TO_SHIFT)
|
||||||
|
#define TB_GET_FROM(_res) \
|
||||||
|
(((_res) & TB_RESULT_FROM_MASK) >> TB_RESULT_FROM_SHIFT)
|
||||||
|
#define TB_GET_PROMOTES(_res) \
|
||||||
|
(((_res) & TB_RESULT_PROMOTES_MASK) >> TB_RESULT_PROMOTES_SHIFT)
|
||||||
|
#define TB_GET_EP(_res) \
|
||||||
|
(((_res) & TB_RESULT_EP_MASK) >> TB_RESULT_EP_SHIFT)
|
||||||
|
#define TB_GET_DTZ(_res) \
|
||||||
|
(((_res) & TB_RESULT_DTZ_MASK) >> TB_RESULT_DTZ_SHIFT)
|
||||||
|
|
||||||
|
#define TB_SET_WDL(_res, _wdl) \
|
||||||
|
(((_res) & ~TB_RESULT_WDL_MASK) | \
|
||||||
|
(((_wdl) << TB_RESULT_WDL_SHIFT) & TB_RESULT_WDL_MASK))
|
||||||
|
#define TB_SET_TO(_res, _to) \
|
||||||
|
(((_res) & ~TB_RESULT_TO_MASK) | \
|
||||||
|
(((_to) << TB_RESULT_TO_SHIFT) & TB_RESULT_TO_MASK))
|
||||||
|
#define TB_SET_FROM(_res, _from) \
|
||||||
|
(((_res) & ~TB_RESULT_FROM_MASK) | \
|
||||||
|
(((_from) << TB_RESULT_FROM_SHIFT) & TB_RESULT_FROM_MASK))
|
||||||
|
#define TB_SET_PROMOTES(_res, _promotes) \
|
||||||
|
(((_res) & ~TB_RESULT_PROMOTES_MASK) | \
|
||||||
|
(((_promotes) << TB_RESULT_PROMOTES_SHIFT) & TB_RESULT_PROMOTES_MASK))
|
||||||
|
#define TB_SET_EP(_res, _ep) \
|
||||||
|
(((_res) & ~TB_RESULT_EP_MASK) | \
|
||||||
|
(((_ep) << TB_RESULT_EP_SHIFT) & TB_RESULT_EP_MASK))
|
||||||
|
#define TB_SET_DTZ(_res, _dtz) \
|
||||||
|
(((_res) & ~TB_RESULT_DTZ_MASK) | \
|
||||||
|
(((_dtz) << TB_RESULT_DTZ_SHIFT) & TB_RESULT_DTZ_MASK))
|
||||||
|
|
||||||
|
#define TB_RESULT_CHECKMATE TB_SET_WDL(0, TB_WIN)
|
||||||
|
#define TB_RESULT_STALEMATE TB_SET_WDL(0, TB_DRAW)
|
||||||
|
#define TB_RESULT_FAILED 0xFFFFFFFF
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The tablebase can be probed for any position where #pieces <= TB_LARGEST.
|
||||||
|
*/
|
||||||
|
extern unsigned TB_LARGEST;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Initialize the tablebase.
|
||||||
|
*
|
||||||
|
* PARAMETERS:
|
||||||
|
* - path:
|
||||||
|
* The tablebase PATH string.
|
||||||
|
*
|
||||||
|
* RETURN:
|
||||||
|
* - true=success, false=failed. The TB_LARGEST global will also be
|
||||||
|
* initialized. If no tablebase files are found, then `true' is returned
|
||||||
|
* and TB_LARGEST is set to zero.
|
||||||
|
*/
|
||||||
|
bool tb_init(const char *_path);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Free any resources allocated by tb_init
|
||||||
|
*/
|
||||||
|
void tb_free(void);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Probe the Win-Draw-Loss (WDL) table.
|
||||||
|
*
|
||||||
|
* PARAMETERS:
|
||||||
|
* - white, black, kings, queens, rooks, bishops, knights, pawns:
|
||||||
|
* The current position (bitboards).
|
||||||
|
* - rule50:
|
||||||
|
* The 50-move half-move clock.
|
||||||
|
* - castling:
|
||||||
|
* Castling rights. Set to zero if no castling is possible.
|
||||||
|
* - ep:
|
||||||
|
* The en passant square (if exists). Set to zero if there is no en passant
|
||||||
|
* square.
|
||||||
|
* - turn:
|
||||||
|
* true=white, false=black
|
||||||
|
*
|
||||||
|
* RETURN:
|
||||||
|
* - One of {TB_LOSS, TB_BLESSED_LOSS, TB_DRAW, TB_CURSED_WIN, TB_WIN}.
|
||||||
|
* Otherwise returns TB_RESULT_FAILED if the probe failed.
|
||||||
|
*
|
||||||
|
* NOTES:
|
||||||
|
* - Engines should use this function during search.
|
||||||
|
* - This function is thread safe assuming TB_NO_THREADS is disabled.
|
||||||
|
*/
|
||||||
|
static inline unsigned tb_probe_wdl(
|
||||||
|
uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _rule50,
|
||||||
|
unsigned _castling,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn)
|
||||||
|
{
|
||||||
|
if (_castling != 0)
|
||||||
|
return TB_RESULT_FAILED;
|
||||||
|
if (_rule50 != 0)
|
||||||
|
return TB_RESULT_FAILED;
|
||||||
|
return tb_probe_wdl_impl(_white, _black, _kings, _queens, _rooks,
|
||||||
|
_bishops, _knights, _pawns, _ep, _turn);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Probe the Distance-To-Zero (DTZ) table.
|
||||||
|
*
|
||||||
|
* PARAMETERS:
|
||||||
|
* - white, black, kings, queens, rooks, bishops, knights, pawns:
|
||||||
|
* The current position (bitboards).
|
||||||
|
* - rule50:
|
||||||
|
* The 50-move half-move clock.
|
||||||
|
* - castling:
|
||||||
|
* Castling rights. Set to zero if no castling is possible.
|
||||||
|
* - ep:
|
||||||
|
* The en passant square (if exists). Set to zero if there is no en passant
|
||||||
|
* square.
|
||||||
|
* - turn:
|
||||||
|
* true=white, false=black
|
||||||
|
* - results (OPTIONAL):
|
||||||
|
* Alternative results, one for each possible legal move. The passed array
|
||||||
|
* must be TB_MAX_MOVES in size.
|
||||||
|
* If alternative results are not desired then set results=NULL.
|
||||||
|
*
|
||||||
|
* RETURN:
|
||||||
|
* - A TB_RESULT value comprising:
|
||||||
|
* 1) The WDL value (TB_GET_WDL)
|
||||||
|
* 2) The suggested move (TB_GET_FROM, TB_GET_TO, TB_GET_PROMOTES, TB_GET_EP)
|
||||||
|
* 3) The DTZ value (TB_GET_DTZ)
|
||||||
|
* The suggested move is guaranteed to preserved the WDL value.
|
||||||
|
*
|
||||||
|
* Otherwise:
|
||||||
|
* 1) TB_RESULT_STALEMATE is returned if the position is in stalemate.
|
||||||
|
* 2) TB_RESULT_CHECKMATE is returned if the position is in checkmate.
|
||||||
|
* 3) TB_RESULT_FAILED is returned if the probe failed.
|
||||||
|
*
|
||||||
|
* If results!=NULL, then a TB_RESULT for each legal move will be generated
|
||||||
|
* and stored in the results array. The results array will be terminated
|
||||||
|
* by TB_RESULT_FAILED.
|
||||||
|
*
|
||||||
|
* NOTES:
|
||||||
|
* - Engines can use this function to probe at the root. This function should
|
||||||
|
* not be used during search.
|
||||||
|
* - DTZ tablebases can suggest unnatural moves, especially for losing
|
||||||
|
* positions. Engines may prefer to traditional search combined with WDL
|
||||||
|
* move filtering using the alternative results array.
|
||||||
|
* - This function is NOT thread safe. For engines this function should only
|
||||||
|
* be called once at the root per search.
|
||||||
|
*/
|
||||||
|
static inline unsigned tb_probe_root(
|
||||||
|
uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _rule50,
|
||||||
|
unsigned _castling,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn,
|
||||||
|
unsigned *_results)
|
||||||
|
{
|
||||||
|
if (_castling != 0)
|
||||||
|
return TB_RESULT_FAILED;
|
||||||
|
return tb_probe_root_impl(_white, _black, _kings, _queens, _rooks,
|
||||||
|
_bishops, _knights, _pawns, _rule50, _ep, _turn, _results);
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef uint16_t TbMove;
|
||||||
|
|
||||||
|
#define TB_MOVE_FROM(move) \
|
||||||
|
(((move) >> 6) & 0x3F)
|
||||||
|
#define TB_MOVE_TO(move) \
|
||||||
|
((move) & 0x3F)
|
||||||
|
#define TB_MOVE_PROMOTES(move) \
|
||||||
|
(((move) >> 12) & 0x7)
|
||||||
|
|
||||||
|
struct TbRootMove {
|
||||||
|
TbMove move;
|
||||||
|
TbMove pv[TB_MAX_PLY];
|
||||||
|
unsigned pvSize;
|
||||||
|
int32_t tbScore, tbRank;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TbRootMoves {
|
||||||
|
unsigned size;
|
||||||
|
struct TbRootMove moves[TB_MAX_MOVES];
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Use the DTZ tables to rank and score all root moves.
|
||||||
|
* INPUT: as for tb_probe_root
|
||||||
|
* OUTPUT: TbRootMoves structure is filled in. This contains
|
||||||
|
* an array of TbRootMove structures.
|
||||||
|
* Each structure instance contains a rank, a score, and a
|
||||||
|
* predicted principal variation.
|
||||||
|
* RETURN VALUE:
|
||||||
|
* non-zero if ok, 0 means not all probes were successful
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
int tb_probe_root_dtz(
|
||||||
|
uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _rule50,
|
||||||
|
unsigned _castling,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn,
|
||||||
|
bool hasRepeated,
|
||||||
|
bool useRule50,
|
||||||
|
struct TbRootMoves *_results);
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Use the WDL tables to rank and score all root moves.
|
||||||
|
// This is a fallback for the case that some or all DTZ tables are missing.
|
||||||
|
* INPUT: as for tb_probe_root
|
||||||
|
* OUTPUT: TbRootMoves structure is filled in. This contains
|
||||||
|
* an array of TbRootMove structures.
|
||||||
|
* Each structure instance contains a rank, a score, and a
|
||||||
|
* predicted principal variation.
|
||||||
|
* RETURN VALUE:
|
||||||
|
* non-zero if ok, 0 means not all probes were successful
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
int tb_probe_root_wdl(uint64_t _white,
|
||||||
|
uint64_t _black,
|
||||||
|
uint64_t _kings,
|
||||||
|
uint64_t _queens,
|
||||||
|
uint64_t _rooks,
|
||||||
|
uint64_t _bishops,
|
||||||
|
uint64_t _knights,
|
||||||
|
uint64_t _pawns,
|
||||||
|
unsigned _rule50,
|
||||||
|
unsigned _castling,
|
||||||
|
unsigned _ep,
|
||||||
|
bool _turn,
|
||||||
|
bool useRule50,
|
||||||
|
struct TbRootMoves *_results);
|
||||||
|
|
||||||
|
/****************************************************************************/
|
||||||
|
/* HELPER API */
|
||||||
|
/****************************************************************************/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The HELPER API provides some useful additional functions. It is optional
|
||||||
|
* and can be disabled by defining TB_NO_HELPER_API. Engines should disable
|
||||||
|
* the HELPER API.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef TB_NO_HELPER_API
|
||||||
|
|
||||||
|
extern unsigned tb_pop_count(uint64_t _bb);
|
||||||
|
extern unsigned tb_lsb(uint64_t _bb);
|
||||||
|
extern uint64_t tb_pop_lsb(uint64_t _bb);
|
||||||
|
extern uint64_t tb_king_attacks(unsigned _square);
|
||||||
|
extern uint64_t tb_queen_attacks(unsigned _square, uint64_t _occ);
|
||||||
|
extern uint64_t tb_rook_attacks(unsigned _square, uint64_t _occ);
|
||||||
|
extern uint64_t tb_bishop_attacks(unsigned _square, uint64_t _occ);
|
||||||
|
extern uint64_t tb_knight_attacks(unsigned _square);
|
||||||
|
extern uint64_t tb_pawn_attacks(unsigned _square, bool _color);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
+10
-26
@@ -10,37 +10,29 @@
|
|||||||
# We recommend using the bang functions (`insert!`, `update!`
|
# We recommend using the bang functions (`insert!`, `update!`
|
||||||
# and so on) as they will fail if something goes wrong.
|
# and so on) as they will fail if something goes wrong.
|
||||||
|
|
||||||
|
Code.require_file("seeds/endgames.ex", __DIR__)
|
||||||
|
Code.require_file("seeds/themes.ex", __DIR__)
|
||||||
|
|
||||||
alias Chesstrainer.Repo
|
alias Chesstrainer.Repo
|
||||||
alias Chesstrainer.Endgames.Endgame
|
alias Chesstrainer.Endgames.Endgame
|
||||||
alias Chesstrainer.Themes.Theme
|
alias Chesstrainer.Themes.Theme
|
||||||
|
alias Chesstrainer.Repo.Seeds.Endgames
|
||||||
|
alias Chesstrainer.Repo.Seeds.Themes
|
||||||
|
|
||||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||||
|
|
||||||
IO.puts("🌱 Seeding basic endgames into DB...")
|
IO.puts("🌱 Seeding basic endgames into DB...")
|
||||||
|
|
||||||
endgames = [
|
endgames = Endgames.all()
|
||||||
%{
|
|
||||||
fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1",
|
|
||||||
color: :white,
|
|
||||||
message: "Rook vs king endgame",
|
|
||||||
notes: "Basic rook endgame",
|
|
||||||
result: :win
|
|
||||||
},
|
|
||||||
%{
|
|
||||||
fen: "6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 1",
|
|
||||||
color: :black,
|
|
||||||
message: "3 pawns vs 2 pawns",
|
|
||||||
notes: "https://www.chessgames.com/perl/chessgame?gid=1017147",
|
|
||||||
result: :win
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
Repo.insert_all(
|
Repo.insert_all(
|
||||||
Endgame,
|
Endgame,
|
||||||
Enum.map(endgames, fn endgame ->
|
Enum.map(endgames, fn endgame ->
|
||||||
{:ok, key} = Chesstrainer.Key.from_fen(endgame.fen)
|
fen = Chesstrainer.FEN.normalize(endgame.fen)
|
||||||
|
{:ok, key} = Chesstrainer.Key.from_fen(fen)
|
||||||
|
|
||||||
endgame
|
endgame
|
||||||
|
|> Map.put(:fen, fen)
|
||||||
|> Map.put(:id, Ecto.UUID.generate())
|
|> Map.put(:id, Ecto.UUID.generate())
|
||||||
|> Map.put(:key, key)
|
|> Map.put(:key, key)
|
||||||
|> Map.merge(%{inserted_at: now, updated_at: now})
|
|> Map.merge(%{inserted_at: now, updated_at: now})
|
||||||
@@ -52,15 +44,7 @@ IO.puts("✅ Done seeding endgames.")
|
|||||||
|
|
||||||
IO.puts("🌱 Seeding endgame themes into DB...")
|
IO.puts("🌱 Seeding endgame themes into DB...")
|
||||||
|
|
||||||
theme_names = [
|
theme_names = Themes.all()
|
||||||
"mate in 2",
|
|
||||||
"mate in 3",
|
|
||||||
"Lucena",
|
|
||||||
"Philidor",
|
|
||||||
"opposition",
|
|
||||||
"promotion",
|
|
||||||
"stalemate"
|
|
||||||
]
|
|
||||||
|
|
||||||
Repo.insert_all(
|
Repo.insert_all(
|
||||||
Theme,
|
Theme,
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
defmodule Chesstrainer.Repo.Seeds.Endgames do
|
||||||
|
def all do
|
||||||
|
[
|
||||||
|
%{
|
||||||
|
fen: "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
message: "Rook vs king endgame",
|
||||||
|
notes: "Basic rook endgame",
|
||||||
|
result: :win
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "r7/4R2P/3p4/3k1K2/2p5/8/8/8 b - - 0 0",
|
||||||
|
color: :black,
|
||||||
|
result: :draw
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "8/8/5p2/1P1K1k2/8/2r5/8/7R w - - 0 0",
|
||||||
|
color: :white,
|
||||||
|
result: :draw
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "5n2/R7/4pk2/8/5PK1/8/8/8 b - - 0 0",
|
||||||
|
color: :black,
|
||||||
|
result: :draw
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "5k2/R7/3K4/4p3/5P2/8/8/5r2 w - - 0 1",
|
||||||
|
color: :white,
|
||||||
|
result: :draw
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "5k2/8/p7/4K1P1/P4R2/6r1/8/8 b - - 0 1",
|
||||||
|
color: :black,
|
||||||
|
result: :draw
|
||||||
|
},
|
||||||
|
%{
|
||||||
|
fen: "8/8/8/1P4p1/5k2/5p2/P6K/8 b - - 0 0",
|
||||||
|
color: :black,
|
||||||
|
result: :win
|
||||||
|
}
|
||||||
|
]
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
defmodule Chesstrainer.Repo.Seeds.Themes do
|
||||||
|
def all do
|
||||||
|
[
|
||||||
|
"mate in 2",
|
||||||
|
"mate in 3",
|
||||||
|
"Lucena",
|
||||||
|
"Philidor",
|
||||||
|
"opposition",
|
||||||
|
"promotion",
|
||||||
|
"stalemate"
|
||||||
|
]
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.FathomTest do
|
||||||
|
# Not async: Fathom keeps global state, and `init/1` points it at one directory.
|
||||||
|
use ExUnit.Case, async: false
|
||||||
|
|
||||||
|
alias Chesstrainer.Endgames.Tablebase.Fathom
|
||||||
|
|
||||||
|
@fixture_path Path.expand("../../../fixtures/tablebase", __DIR__)
|
||||||
|
|
||||||
|
# KRvK, white to move. Fathom CLI reports WDL Win, DTZ 23, 15 legal moves.
|
||||||
|
@krk "4k3/8/8/8/8/8/8/R3K3 w - - 0 1"
|
||||||
|
|
||||||
|
setup_all do
|
||||||
|
assert {:ok, largest} = Fathom.init(@fixture_path)
|
||||||
|
assert largest == 3
|
||||||
|
:ok
|
||||||
|
end
|
||||||
|
|
||||||
|
test "probes a known KRvK position" do
|
||||||
|
assert {:ok, {root, moves}} = Fathom.probe(@krk)
|
||||||
|
|
||||||
|
assert {:win, _from, _to, _promotes, _ep, 23} = root
|
||||||
|
assert length(moves) == 15
|
||||||
|
assert Enum.all?(moves, fn {wdl, _from, _to, _promotes, _ep, _dtz} -> wdl == :win end)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "rejects a malformed FEN" do
|
||||||
|
assert {:error, _reason} = Fathom.probe("not a fen")
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
defmodule Chesstrainer.Endgames.Tablebase.RouterTest do
|
||||||
|
use ExUnit.Case, async: true
|
||||||
|
|
||||||
|
alias Chesstrainer.Endgames.Tablebase.Backend.Lichess
|
||||||
|
alias Chesstrainer.Endgames.Tablebase.Router
|
||||||
|
|
||||||
|
@three "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||||
|
@six "8/8/5p2/1P1K1k2/8/2r5/8/7R w - - 0 0"
|
||||||
|
@seven "6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 1"
|
||||||
|
@ten "3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1"
|
||||||
|
|
||||||
|
describe "backend/1" do
|
||||||
|
test "routes five or fewer pieces to the local slot" do
|
||||||
|
assert Router.backend(@three) == {:ok, Lichess}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "routes six and seven pieces to the remote slot" do
|
||||||
|
assert Router.backend(@six) == {:ok, Lichess}
|
||||||
|
assert Router.backend(@seven) == {:ok, Lichess}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "marks eight or more pieces as not covered" do
|
||||||
|
assert Router.backend(@ten) == {:error, :not_covered}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "marks a malformed FEN as invalid" do
|
||||||
|
assert Router.backend("not a fen") == {:error, :invalid_endgame}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "probe/1" do
|
||||||
|
test "rejects a position with more than seven pieces without a network call" do
|
||||||
|
assert Router.probe(@ten) == {:error, :not_covered}
|
||||||
|
end
|
||||||
|
|
||||||
|
test "rejects a malformed FEN" do
|
||||||
|
assert Router.probe("not a fen") == {:error, :invalid_endgame}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -4,6 +4,7 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
|
|||||||
alias Chesstrainer.Endgames.Tablebase
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
|
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
|
||||||
alias Chesstrainer.Endgames.Tablebase.Parser
|
alias Chesstrainer.Endgames.Tablebase.Parser
|
||||||
|
alias Chesstrainer.FEN
|
||||||
alias Chesstrainer.Ratelimiters
|
alias Chesstrainer.Ratelimiters
|
||||||
|
|
||||||
describe "normalize_category/1" do
|
describe "normalize_category/1" do
|
||||||
@@ -35,12 +36,12 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
|
|||||||
describe "struct shape" do
|
describe "struct shape" do
|
||||||
test "Tablebase carries only the fields the trainer reads" do
|
test "Tablebase carries only the fields the trainer reads" do
|
||||||
assert %Tablebase{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
assert %Tablebase{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
||||||
[:category, :checkmate, :dtc, :dtm, :moves]
|
[:category, :checkmate, :moves]
|
||||||
end
|
end
|
||||||
|
|
||||||
test "Tablebase.Move carries only the fields the trainer reads" do
|
test "Tablebase.Move carries only the fields the trainer reads" do
|
||||||
assert %Tablebase.Move{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
assert %Tablebase.Move{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
||||||
[:category, :dtc, :dtm, :dtz, :san, :uci]
|
[:category, :dtz, :san, :uci]
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -65,9 +66,9 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
|
|||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
assert %Tablebase{category: :draw, checkmate: false, dtc: nil, dtm: 20} = tablebase
|
assert %Tablebase{category: :draw, checkmate: false} = tablebase
|
||||||
|
|
||||||
assert [%Tablebase.Move{category: :draw, dtc: nil, dtm: -19, dtz: -2}] = tablebase.moves
|
assert [%Tablebase.Move{category: :draw, dtz: -2}] = tablebase.moves
|
||||||
assert [%Tablebase.Move{san: "Kd7", uci: "e8d7"}] = tablebase.moves
|
assert [%Tablebase.Move{san: "Kd7", uci: "e8d7"}] = tablebase.moves
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -103,12 +104,12 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
|
|||||||
})
|
})
|
||||||
|
|
||||||
assert %Tablebase{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
assert %Tablebase{} |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
||||||
[:category, :checkmate, :dtc, :dtm, :moves]
|
[:category, :checkmate, :moves]
|
||||||
|
|
||||||
assert [move] = tablebase.moves
|
assert [move] = tablebase.moves
|
||||||
|
|
||||||
assert move |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
assert move |> Map.from_struct() |> Map.keys() |> Enum.sort() ==
|
||||||
[:category, :dtc, :dtm, :dtz, :san, :uci]
|
[:category, :dtz, :san, :uci]
|
||||||
end
|
end
|
||||||
|
|
||||||
test "keeps checkmate and empty moves, which drive terminal detection" do
|
test "keeps checkmate and empty moves, which drive terminal detection" do
|
||||||
@@ -144,11 +145,31 @@ defmodule Chesstrainer.Endgames.TablebaseTest do
|
|||||||
test "returns {:ok, tablebase} on a cache hit" do
|
test "returns {:ok, tablebase} on a cache hit" do
|
||||||
fen = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
fen = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||||
tablebase = %Tablebase{category: :win, moves: []}
|
tablebase = %Tablebase{category: :win, moves: []}
|
||||||
|
key = FEN.position_key(fen)
|
||||||
|
|
||||||
TablebaseCache.put(fen, tablebase)
|
TablebaseCache.put(key, tablebase)
|
||||||
on_exit(fn -> TablebaseCache.delete(fen) end)
|
on_exit(fn -> TablebaseCache.delete(key) end)
|
||||||
|
|
||||||
assert {:ok, ^tablebase} = Tablebase.new(fen)
|
assert {:ok, ^tablebase} = Tablebase.new(fen)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "shares a cache entry for FENs that differ only in the clocks" do
|
||||||
|
fen = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||||
|
other_clock = "8/8/3k4/8/8/3K1R2/8/8 w - - 7 42"
|
||||||
|
tablebase = %Tablebase{category: :win, moves: []}
|
||||||
|
key = FEN.position_key(fen)
|
||||||
|
|
||||||
|
TablebaseCache.put(key, tablebase)
|
||||||
|
on_exit(fn -> TablebaseCache.delete(key) end)
|
||||||
|
|
||||||
|
assert {:ok, ^tablebase} = Tablebase.new(other_clock)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "returns {:error, :not_covered} for a position with more than seven pieces" do
|
||||||
|
fen = "3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1"
|
||||||
|
TablebaseCache.delete(FEN.position_key(fen))
|
||||||
|
|
||||||
|
assert Tablebase.new(fen) == {:error, :not_covered}
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -115,6 +115,30 @@ defmodule Chesstrainer.EndgamesTest do
|
|||||||
assert [msg] = errors_on(changeset).fen
|
assert [msg] = errors_on(changeset).fen
|
||||||
assert msg =~ "active color"
|
assert msg =~ "active color"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "rejects a FEN with more than 7 pieces" do
|
||||||
|
attrs = %{
|
||||||
|
fen: "3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1",
|
||||||
|
color: :black,
|
||||||
|
result: :win,
|
||||||
|
rating: 1500
|
||||||
|
}
|
||||||
|
|
||||||
|
assert {:error, changeset} = Endgames.create_endgame(attrs)
|
||||||
|
assert [msg] = errors_on(changeset).fen
|
||||||
|
assert msg =~ "more than 7 pieces"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "accepts a FEN with exactly 7 pieces" do
|
||||||
|
attrs = %{
|
||||||
|
fen: "6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 1",
|
||||||
|
color: :black,
|
||||||
|
result: :win,
|
||||||
|
rating: 1500
|
||||||
|
}
|
||||||
|
|
||||||
|
assert {:ok, %Endgame{}} = Endgames.create_endgame(attrs)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "themes" do
|
describe "themes" do
|
||||||
|
|||||||
@@ -59,4 +59,59 @@ defmodule Chesstrainer.FENTest do
|
|||||||
assert FEN.normalize(fen) == fen
|
assert FEN.normalize(fen) == fen
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe "position_key/1" do
|
||||||
|
test "drops the halfmove and fullmove clocks" do
|
||||||
|
assert FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1") ==
|
||||||
|
"8/8/3k4/8/8/3K1R2/8/8 w - -"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "shares a key for FENs that differ only in the clocks" do
|
||||||
|
a = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||||
|
b = "8/8/3k4/8/8/3K1R2/8/8 w - - 37 99"
|
||||||
|
|
||||||
|
assert FEN.position_key(a) == FEN.position_key(b)
|
||||||
|
end
|
||||||
|
|
||||||
|
test "keeps board, side to move, castling and en-passant distinct" do
|
||||||
|
base = "8/8/3k4/8/8/3K1R2/8/8 w - - 0 1"
|
||||||
|
|
||||||
|
refute FEN.position_key(base) == FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 b - - 0 1")
|
||||||
|
refute FEN.position_key(base) == FEN.position_key("8/8/3k4/8/8/3K1R3/8/8 w - - 0 1")
|
||||||
|
refute FEN.position_key(base) == FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 w K - 0 1")
|
||||||
|
refute FEN.position_key(base) == FEN.position_key("8/8/3k4/8/8/3K1R2/8/8 w - e3 0 1")
|
||||||
|
end
|
||||||
|
|
||||||
|
test "trims surrounding whitespace" do
|
||||||
|
assert FEN.position_key(" 8/8/3k4/8/8/3K1R2/8/8 w - - 0 1\n") ==
|
||||||
|
"8/8/3k4/8/8/3K1R2/8/8 w - -"
|
||||||
|
end
|
||||||
|
|
||||||
|
test "passes through a non-FEN string" do
|
||||||
|
assert FEN.position_key("not a fen") == "not a fen"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "piece_count/1" do
|
||||||
|
test "counts kings and pieces, ignoring empty squares and slashes" do
|
||||||
|
assert FEN.piece_count("8/8/3k4/8/8/3K1R2/8/8 w - - 0 1") == 3
|
||||||
|
end
|
||||||
|
|
||||||
|
test "counts a full seven-piece position" do
|
||||||
|
assert FEN.piece_count("6k1/5p2/6p1/8/7p/8/6PP/6K1 b - - 0 0") == 7
|
||||||
|
end
|
||||||
|
|
||||||
|
test "counts a position beyond the tablebase range" do
|
||||||
|
assert FEN.piece_count("3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1") == 10
|
||||||
|
end
|
||||||
|
|
||||||
|
test "counts a board field without clocks" do
|
||||||
|
assert FEN.piece_count("8/8/3k4/8/8/3K1R2/8/8") == 3
|
||||||
|
end
|
||||||
|
|
||||||
|
test "returns nil for a malformed board" do
|
||||||
|
assert FEN.piece_count("not a fen") == nil
|
||||||
|
assert FEN.piece_count(nil) == nil
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
defmodule Chesstrainer.SeedsTest do
|
||||||
|
use ExUnit.Case, async: true
|
||||||
|
|
||||||
|
alias Chesstrainer.FEN
|
||||||
|
|
||||||
|
Code.require_file("../../priv/repo/seeds/endgames.ex", __DIR__)
|
||||||
|
|
||||||
|
describe "seed endgames" do
|
||||||
|
test "are normalised and within tablebase range" do
|
||||||
|
for endgame <- Chesstrainer.Repo.Seeds.Endgames.all() do
|
||||||
|
fen = FEN.normalize(endgame.fen)
|
||||||
|
|
||||||
|
assert length(String.split(fen, " ")) == 6,
|
||||||
|
"seed FEN must have 6 fields: #{endgame.fen}"
|
||||||
|
|
||||||
|
refute String.ends_with?(fen, " 0"),
|
||||||
|
"seed FEN keeps fullmove 0 after normalisation: #{endgame.fen}"
|
||||||
|
|
||||||
|
assert FEN.piece_count(fen) <= 7,
|
||||||
|
"seed FEN has more than 7 pieces: #{endgame.fen}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -7,6 +7,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
alias Chesstrainer.Endgames
|
alias Chesstrainer.Endgames
|
||||||
alias Chesstrainer.Endgames.Tablebase
|
alias Chesstrainer.Endgames.Tablebase
|
||||||
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
|
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
|
||||||
|
alias Chesstrainer.FEN
|
||||||
alias Chesstrainer.Ratelimiters
|
alias Chesstrainer.Ratelimiters
|
||||||
|
|
||||||
defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do
|
defp assert_init_board(view, expected_fen, expected_orientation, expected_player_color) do
|
||||||
@@ -27,8 +28,9 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
moves: Keyword.get(opts, :moves, [])
|
moves: Keyword.get(opts, :moves, [])
|
||||||
}
|
}
|
||||||
|
|
||||||
TablebaseCache.put(fen, tablebase)
|
key = FEN.position_key(fen)
|
||||||
on_exit(fn -> TablebaseCache.delete(fen) end)
|
TablebaseCache.put(key, tablebase)
|
||||||
|
on_exit(fn -> TablebaseCache.delete(key) end)
|
||||||
end
|
end
|
||||||
|
|
||||||
defp grading_moves do
|
defp grading_moves do
|
||||||
@@ -57,14 +59,31 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
})
|
})
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# >7-piece positions short-circuit to "not covered" before any backend, but
|
||||||
|
# the changeset now rejects them, so insert one directly to exercise the path.
|
||||||
|
defp insert_out_of_range_endgame do
|
||||||
|
fen = "3k4/2n2B2/1KP5/2B2p2/5b1p/7P/8/8 b - - 0 1"
|
||||||
|
{:ok, key} = Chesstrainer.Key.from_fen(fen)
|
||||||
|
|
||||||
|
Chesstrainer.Repo.insert!(%Chesstrainer.Endgames.Endgame{
|
||||||
|
fen: fen,
|
||||||
|
color: :black,
|
||||||
|
key: key,
|
||||||
|
result: :win,
|
||||||
|
rating: 1500
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
# Plays one optimal move, applies the opponent's reply, then a losing move,
|
# Plays one optimal move, applies the opponent's reply, then a losing move,
|
||||||
# leaving a three-ply failed attempt to review.
|
# leaving a three-ply failed attempt to review.
|
||||||
defp seeded_attempt(conn) do
|
defp seeded_attempt(conn) do
|
||||||
endgame = endgame_fixture()
|
endgame = endgame_fixture()
|
||||||
|
|
||||||
|
# The tablebase cache is keyed by position (clocks ignored), so these must
|
||||||
|
# differ by more than the move clocks to stay distinct cache entries.
|
||||||
after_first = "8/8/8/8/8/8/8/8 b - - 0 1"
|
after_first = "8/8/8/8/8/8/8/8 b - - 0 1"
|
||||||
after_reply = "8/8/8/8/8/8/8/8 w - - 0 1"
|
after_reply = "8/8/8/8/8/8/8/8 w - - 0 1"
|
||||||
after_losing = "8/8/8/8/8/8/8/8 b - - 1 1"
|
after_losing = "8/8/8/8/8/8/8/7K b - - 1 1"
|
||||||
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
|
reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :loss, dtz: -3}
|
||||||
losing_reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :draw, dtz: 0}
|
losing_reply = %Tablebase.Move{uci: "e8e7", san: "Ke7", category: :draw, dtz: 0}
|
||||||
|
|
||||||
@@ -159,7 +178,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
describe "tablebase availability" do
|
describe "tablebase availability" do
|
||||||
test "blocks the attempt when the tablebase is cooling down", %{conn: conn} do
|
test "blocks the attempt when the tablebase is cooling down", %{conn: conn} do
|
||||||
endgame = endgame_fixture()
|
endgame = endgame_fixture()
|
||||||
TablebaseCache.delete(endgame.fen)
|
TablebaseCache.delete(FEN.position_key(endgame.fen))
|
||||||
Ratelimiters.lichess_add_cooldown()
|
Ratelimiters.lichess_add_cooldown()
|
||||||
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
|
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
|
||||||
|
|
||||||
@@ -170,6 +189,16 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
play_move(view, endgame, "d1", "d7", "Qd7+")
|
play_move(view, endgame, "d1", "d7", "Qd7+")
|
||||||
assert render(view) =~ "cannot be graded"
|
assert render(view) =~ "cannot be graded"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
test "blocks an out-of-range endgame as not covered", %{conn: conn} do
|
||||||
|
endgame = insert_out_of_range_endgame()
|
||||||
|
|
||||||
|
{:ok, view, _html} = live(conn, ~p"/endgames/#{endgame}/play")
|
||||||
|
|
||||||
|
html = render(view)
|
||||||
|
assert html =~ "Tablebase unavailable"
|
||||||
|
assert html =~ "not covered by the tablebase"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "chess_fen_invalid" do
|
describe "chess_fen_invalid" do
|
||||||
@@ -710,7 +739,7 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
|
|||||||
test "degrades gracefully and reuses played-position snapshots", %{conn: conn} do
|
test "degrades gracefully and reuses played-position snapshots", %{conn: conn} do
|
||||||
{view, fens} = seeded_attempt(conn)
|
{view, fens} = seeded_attempt(conn)
|
||||||
|
|
||||||
TablebaseCache.delete(fens.after_losing)
|
TablebaseCache.delete(FEN.position_key(fens.after_losing))
|
||||||
Ratelimiters.lichess_add_cooldown()
|
Ratelimiters.lichess_add_cooldown()
|
||||||
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
|
on_exit(fn -> Ratelimiters.lichess_reset_cooldown() end)
|
||||||
|
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Reference in New Issue
Block a user