Game analysis: whole-game engine review with graph, report and notation marks
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

- Separate background engine job over the main line (go nodes N), live engine
  paused meanwhile; header button with progress/cancel, Shift+A.
- Lichess-method metrics: win %, move/game accuracy, inaccuracy/mistake/blunder,
  ACPL, accuracy per game phase.
- Evaluation graph under the board, Report tab, engine badges and better lines
  in the notation (preview on click), launch dialog with quality/threads/memory
  and time estimate.
- Results cached in ~/.cache/chesspenguin/analysis; [%eval] read from PGN.
- Write analysis to the game as one undo step (chess-core: Game::annotate,
  Game::edit_group).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubel 2026-10-18 11:03:23 +03:00
parent 5364f06ba6
commit 808382966f
17 changed files with 2831 additions and 36 deletions

View file

@ -2,6 +2,14 @@
All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
- Game analysis (Shift+A): background evaluation of the whole main line with its own engine process,
evaluation graph under the board, report tab with accuracy, inaccuracies, mistakes, blunders,
average centipawn loss and accuracy per game phase; engine marks and better lines in the notation;
"Write analysis to the game" (NAGs, comments, `[%eval]`, one undo step). Results are cached;
`[%eval]` comments of a PGN are used without an engine.
## [0.1.0] — 2026-10-18
First public release.

View file

@ -26,6 +26,9 @@
mouse and keyboard navigation.
- **Engine analysis** — any UCI engine, up to 5 lines, best-move arrows, evaluation bar;
search time, threads and memory are set right in the analysis panel.
- **Game analysis** — evaluate the whole game in the background: evaluation graph under the board,
accuracy, inaccuracies, mistakes and blunders per player and per game phase (Lichess method),
better moves in the notation; write it into the game as NAGs, comments and `[%eval]` (undoable).
- **Engine lines on the board** — step through a line without touching the game, add it as a
variation with one click (undoable).
- **Editing** — enter moves and variations, promote or delete lines, undo/redo,
@ -69,7 +72,7 @@ cargo run --release -p chesspenguin -- examples/classics.pgn
| Where | Keys |
| --- | --- |
| Library | ↑/↓ select · Enter open · Ctrl+O add PGN · Ctrl+N new game · Ctrl+F search |
| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Esc leave preview |
| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Shift+A game analysis · Esc leave preview |
| Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save as · Ctrl+W back to library |
## Project layout

View file

@ -16,6 +16,9 @@
навигация мышью и клавиатурой.
- **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки;
время, потоки и память настраиваются прямо в панели анализа.
- **Анализ партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки
и зевки каждого игрока и по стадиям партии (методика Lichess), лучшие ходы в нотации;
запись анализа в партию знаками, комментариями и `[%eval]` (с отменой).
- **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой).
- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор,
копирование PGN/FEN, сохранение партии в новый файл.

View file

@ -251,16 +251,7 @@ impl Analysis {
self.engine = None;
self.current = None;
self.lines.clear();
self.status = Status::Failed(match reason {
TerminationReason::Hung { .. } => {
tr("The engine hung and was stopped").into()
}
TerminationReason::Exited { status }
| TerminationReason::Quit { status } => match status {
Some(s) => trf("The engine exited ({s})", &[("s", &s)]),
None => tr("The engine exited").into(),
},
});
self.status = Status::Failed(termination_message(&reason));
return;
}
_ => {}
@ -284,6 +275,17 @@ impl Drop for Analysis {
}
}
/// Human-readable reason of an engine process ending.
pub fn termination_message(reason: &TerminationReason) -> String {
match reason {
TerminationReason::Hung { .. } => tr("The engine hung and was stopped").into(),
TerminationReason::Exited { status } | TerminationReason::Quit { status } => match status {
Some(s) => trf("The engine exited ({s})", &[("s", s)]),
None => tr("The engine exited").into(),
},
}
}
fn side(c: Color) -> Side {
match c {
Color::White => Side::White,

View file

@ -38,6 +38,8 @@ pub struct App {
library: Library,
game: Option<GameView>,
analysis: Analysis,
/// The live engine was stopped for a whole-game analysis and resumes after it.
live_paused: bool,
settings_ui: SettingsWindow,
toast: Option<(String, f64)>,
tx: Sender<Async>,
@ -52,7 +54,8 @@ pub struct App {
/// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md):
/// `CP_OPEN=<game index>` opens a game from the first database, `CP_PLY=<n>` steps
/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings.
/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings,
/// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog).
#[derive(Default)]
struct DebugStartup {
open: Option<usize>,
@ -113,6 +116,7 @@ impl App {
library,
game: None,
analysis: Analysis::new(),
live_paused: false,
settings_ui: SettingsWindow::new(),
toast: None,
tx,
@ -191,6 +195,10 @@ impl App {
if std::env::var("CP_ENGINE_PANEL").is_ok() {
g.debug_open_engine_settings();
}
// CP_REVIEW=dialog opens the game-analysis dialog, any other value starts the analysis.
if let Ok(v) = std::env::var("CP_REVIEW") {
g.debug_review(&self.settings, ctx, v != "dialog");
}
}
if self.debug.analyze {
self.toggle_engine(ctx);
@ -385,6 +393,7 @@ impl App {
fn finish_close(&mut self, ctx: &egui::Context, intent: CloseIntent) {
self.analysis.stop();
self.live_paused = false;
if let Some(g) = self.game.take()
&& let Some(src) = g.source
{
@ -397,6 +406,7 @@ impl App {
}
fn toggle_engine(&mut self, ctx: &egui::Context) {
self.live_paused = false;
if self.analysis.is_on() {
self.analysis.stop();
return;
@ -557,6 +567,19 @@ impl eframe::App for App {
GameAction::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open,
GameAction::Toast(m) => self.toast(&ctx, m),
GameAction::PauseLive => {
if self.analysis.is_on() {
self.analysis.stop();
self.live_paused = true;
}
}
GameAction::ResumeLive => {
if std::mem::take(&mut self.live_paused)
&& let Some(cfg) = self.settings.active_engine().cloned()
{
self.analysis.start(&cfg, &ctx);
}
}
}
}
} else {

View file

@ -14,6 +14,7 @@ use crate::analysis::{self, Analysis, PvLine, Status};
use crate::assets::Sound;
use crate::board::{self, Arrow, BoardState, BoardView};
use crate::notation::{Notation, NotationCommand};
use crate::review::{DialogAction, ReportAction, Review};
use crate::settings::Settings;
/// Where an opened game came from (to return to the same library row).
@ -53,6 +54,14 @@ pub struct GameView {
scroll_to_cursor: bool,
show_diagnostics: bool,
engine_settings_open: bool,
review: Review,
side_tab: SideTab,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum SideTab {
Notation,
Report,
}
pub enum GameAction {
@ -69,11 +78,16 @@ pub enum GameAction {
OpenSettings,
Quit,
Toast(String),
/// A whole-game analysis started: pause the live engine (they would share the CPU).
PauseLive,
/// The whole-game analysis ended: resume the live engine if it was paused.
ResumeLive,
}
impl GameView {
pub fn new(game: Game, source: Option<GameSource>, diagnostics: Vec<Diagnostic>) -> Self {
let flipped = false;
let review = Review::new(&game);
Self {
game,
source,
@ -85,6 +99,8 @@ impl GameView {
scroll_to_cursor: true,
show_diagnostics: false,
engine_settings_open: false,
review,
side_tab: SideTab::Notation,
}
}
@ -141,7 +157,19 @@ impl GameView {
input_enabled: bool,
) -> Vec<GameAction> {
let mut actions = Vec::new();
if input_enabled {
if self.review.poll() {
actions.push(GameAction::ResumeLive);
if let Some(e) = &self.review.error {
actions.push(GameAction::Toast(e.clone()));
}
}
self.review.refresh(&self.game);
if analysis.status == Status::Running
&& let Some(e) = settings.active_engine()
{
self.review.note_live_speed(analysis.nps, e.threads);
}
if input_enabled && !self.review.dialog_open {
self.keyboard(ui, &mut actions);
}
@ -163,6 +191,13 @@ impl GameView {
});
self.sync_analysis(analysis);
match self.review.dialog(ui.ctx(), settings) {
Some(DialogAction::Start) => self.start_review(settings, true, ui.ctx(), &mut actions),
Some(DialogAction::EngineSwitch) => actions.push(GameAction::EngineSwitch),
Some(DialogAction::OpenEngines) => actions.push(GameAction::OpenEngineSettings),
None => {}
}
if self.show_diagnostics {
let mut open = true;
egui::Window::new(tr("PGN compatibility"))
@ -196,6 +231,64 @@ impl GameView {
actions
}
fn start_review(
&mut self,
settings: &Settings,
full: bool,
ctx: &egui::Context,
actions: &mut Vec<GameAction>,
) {
let Some(engine) = settings.active_engine().cloned() else {
self.review.dialog_open = true;
return;
};
if self
.review
.start(&self.game, &engine, &settings.review, full, ctx)
{
actions.push(GameAction::PauseLive);
self.side_tab = SideTab::Report;
} else if let Some(e) = &self.review.error {
actions.push(GameAction::Toast(e.clone()));
} else {
actions.push(GameAction::Toast(
tr("Every position is already evaluated").into(),
));
}
}
/// Header button: start, progress with cancel, or show/hide the report.
fn review_button(&mut self, ui: &mut Ui, actions: &mut Vec<GameAction>) {
if let Some((done, total)) = self.review.progress() {
if crate::widgets::small_close_button(ui)
.on_hover_text(tr("Stop the game analysis"))
.clicked()
{
self.review.cancel();
actions.push(GameAction::ResumeLive);
}
ui.add(
egui::ProgressBar::new(done as f32 / total.max(1) as f32)
.desired_width(90.0)
.text(format!("{done}/{total}")),
);
ui.label(tr("Game analysis"));
} else if self.review.has_data() {
ui.toggle_value(&mut self.review.visible, tr("📈 Report"))
.on_hover_text(tr(
"Show or hide the evaluation graph and the report (Shift+A)",
));
} else if ui
.button(tr("📈 Analyse game"))
.on_hover_text(tr(
"Evaluate every move: accuracy, inaccuracies, mistakes, blunders (Shift+A)",
))
.clicked()
{
self.review.dialog_open = true;
}
}
/// Keeps the engine bound to the game cursor (never to the preview). Cheap when unchanged.
fn sync_analysis(&self, analysis: &mut Analysis) {
if !analysis.is_on() {
@ -247,6 +340,7 @@ impl GameView {
{
actions.push(GameAction::OpenSettings);
}
self.review_button(ui, actions);
let warnings = self
.diagnostics
.iter()
@ -330,6 +424,20 @@ impl GameView {
}
}
}
if self.review.visible
&& let Some(sq) = self
.review
.best_move(self.cursor)
.as_ref()
.and_then(move_squares)
{
arrows.push(Arrow {
from: sq.0,
to: sq.1,
color: Color32::from_rgba_unmultiplied(0x2a, 0x8a, 0xd8, 170),
weight: 0.9,
});
}
if settings.show_best_arrow && analysis.best().is_some() {
for (i, line) in analysis.lines.iter().take(3).enumerate() {
if let Some(sq) = line.moves.first().and_then(move_squares) {
@ -350,7 +458,16 @@ impl GameView {
let show_bar = analysis.is_on();
let bar_w = if show_bar { 18.0 } else { 0.0 };
let gap = if show_bar { 8.0 } else { 0.0 };
let side = (area.width() - bar_w - gap).min(area.height()).max(120.0);
let show_graph = self.review.visible && (self.review.has_data() || self.review.running());
let graph_h = if show_graph {
(area.height() * 0.14).clamp(80.0, 130.0)
} else {
0.0
};
let graph_gap = if show_graph { 8.0 } else { 0.0 };
let side = (area.width() - bar_w - gap)
.min(area.height() - graph_h - graph_gap)
.max(120.0);
let total = bar_w + gap + side;
let left = area.left() + ((area.width() - total) / 2.0).max(0.0).floor();
let group = egui::Rect::from_min_size(egui::pos2(left, area.top()), vec2(total, side));
@ -427,6 +544,21 @@ impl GameView {
}
});
});
if show_graph {
let graph_rect = egui::Rect::from_min_size(
egui::pos2(left, area.top() + side + graph_gap),
vec2(total, graph_h),
);
let target = ui
.scope_builder(egui::UiBuilder::new().max_rect(graph_rect), |ui| {
self.review
.graph(ui, graph_rect.size(), self.cursor, &self.game)
})
.inner;
if let Some(id) = target {
self.goto(id);
}
}
}
fn side_panel(
@ -439,7 +571,40 @@ impl GameView {
egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions));
egui::Panel::top("engine_panel")
.show(ui, |ui| self.engine_panel(ui, settings, analysis, actions));
let tabs = self.review.visible && (self.review.has_data() || self.review.running());
if !tabs {
self.side_tab = SideTab::Notation;
}
egui::CentralPanel::default().show(ui, |ui| {
if tabs {
ui.horizontal(|ui| {
ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation"));
ui.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report"));
});
ui.separator();
}
if self.side_tab == SideTab::Report {
let action = egui::ScrollArea::vertical()
.auto_shrink(false)
.show(ui, |ui| self.review.report_ui(ui, &self.game))
.inner;
match action {
Some(ReportAction::Goto(id)) => self.goto(id),
Some(ReportAction::Write) => {
let n = self.review.write_to_game(&mut self.game);
actions.push(GameAction::Toast(trf(
"Analysis written to the game: {n} marked moves (Ctrl+Z to undo)",
&[("n", &n)],
)));
}
Some(ReportAction::Update) => {
self.start_review(settings, false, ui.ctx(), actions)
}
Some(ReportAction::Reanalyse) => self.review.dialog_open = true,
None => {}
}
return;
}
egui::ScrollArea::vertical()
.auto_shrink(false)
.show(ui, |ui| {
@ -447,11 +612,28 @@ impl GameView {
game: &self.game,
cursor: self.cursor,
scroll_to_cursor: self.scroll_to_cursor,
marks: self.review.visible.then_some(&self.review.marks),
}
.show(ui);
if let Some(id) = resp.clicked {
self.goto(id);
}
if let Some(id) = resp.best
&& let Some(mark) = self.review.marks.get(&id)
&& let Some(root) = self.game.position(mark.base)
&& !mark.best.is_empty()
{
self.cursor = mark.base;
self.scroll_to_cursor = false;
self.board.clear();
self.preview = Some(Preview {
base: mark.base,
root: root.clone(),
moves: mark.best.clone(),
san: mark.best_san.clone(),
shown: 1,
});
}
if let Some((id, cmd)) = resp.context {
let result = match cmd {
NotationCommand::Promote => {
@ -545,7 +727,15 @@ impl GameView {
Status::Failed(e) => {
ui.label(RichText::new(e).small().color(ui.visuals().error_fg_color));
}
Status::Off => {}
Status::Off => {
if self.review.running() {
ui.label(
RichText::new(tr("paused: the game is being analysed"))
.small()
.weak(),
);
}
}
}
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@ -760,6 +950,14 @@ impl GameView {
self.engine_settings_open = true;
}
pub fn debug_review(&mut self, settings: &Settings, ctx: &egui::Context, start: bool) {
if start {
self.start_review(settings, false, ctx, &mut Vec::new());
} else {
self.review.dialog_open = true;
}
}
pub fn debug_advance(&mut self, plies: usize) {
for _ in 0..plies {
match self.game.main_child(self.cursor) {
@ -838,6 +1036,9 @@ impl GameView {
if i.consume_shortcut(&ctrl(Key::W)) {
cmds.push("back");
}
if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) {
cmds.push("review");
}
if i.modifiers.is_none() {
for (key, cmd) in [
(Key::ArrowLeft, "back1"),
@ -886,6 +1087,13 @@ impl GameView {
}
"flip" => self.flipped = !self.flipped,
"engine" => actions.push(GameAction::ToggleEngine),
"review" => {
if self.review.has_data() || self.review.running() {
self.review.visible = !self.review.visible;
} else {
self.review.dialog_open = true;
}
}
"esc" => {
if self.preview.is_some() {
self.preview = None;
@ -1007,11 +1215,7 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec<GameA
ui.label(tr("Memory"));
settled |= index_slider(ui, &mut h, hash_steps.len());
e.hash_mb = hash_steps[h];
ui.label(if e.hash_mb >= 1024 {
trf("{n} GB", &[("n", &(e.hash_mb / 1024))])
} else {
trf("{n} MB", &[("n", &e.hash_mb)])
});
ui.label(format_mb(e.hash_mb));
ui.end_row();
});
if settled {
@ -1021,14 +1225,22 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec<GameA
}
/// Slider over `0..len`; returns true when the user finished changing it.
fn index_slider(ui: &mut Ui, idx: &mut usize, len: usize) -> bool {
pub(crate) fn index_slider(ui: &mut Ui, idx: &mut usize, len: usize) -> bool {
let before = *idx;
let r = ui.add(egui::Slider::new(idx, 0..=len.saturating_sub(1)).show_value(false));
r.drag_stopped() || (*idx != before && !r.dragged())
}
pub(crate) fn format_mb(mb: u32) -> String {
if mb >= 1024 {
trf("{n} GB", &[("n", &(mb / 1024))])
} else {
trf("{n} MB", &[("n", &mb)])
}
}
/// Hash sizes from 16 MB up to half of physical memory (powers of two).
fn hash_steps() -> Vec<u32> {
pub(crate) fn hash_steps() -> Vec<u32> {
let total_mb = std::fs::read_to_string("/proc/meminfo")
.ok()
.and_then(|s| {

View file

@ -1039,6 +1039,338 @@ const ROWS: &[[&str; 6]] = &[
"Material insuficiente",
"Materiale insufficiente",
],
// Whole-game analysis
[
"Every position is already evaluated",
"Все позиции уже оценены",
"Toutes les positions sont déjà évaluées",
"Alle Stellungen sind bereits bewertet",
"Todas las posiciones ya están evaluadas",
"Tutte le posizioni sono già valutate",
],
[
"Stop the game analysis",
"Остановить анализ партии",
"Arrêter l'analyse de la partie",
"Partieanalyse abbrechen",
"Detener el análisis de la partida",
"Interrompi l'analisi della partita",
],
[
"Game analysis",
"Анализ партии",
"Analyse de la partie",
"Partieanalyse",
"Análisis de la partida",
"Analisi della partita",
],
[
"📈 Report",
"📈 Отчёт",
"📈 Rapport",
"📈 Bericht",
"📈 Informe",
"📈 Resoconto",
],
[
"Show or hide the evaluation graph and the report (Shift+A)",
"Показать или скрыть график оценки и отчёт (Shift+A)",
"Afficher ou masquer le graphique d'évaluation et le rapport (Maj+A)",
"Bewertungsgrafik und Bericht ein- oder ausblenden (Umschalt+A)",
"Mostrar u ocultar el gráfico de evaluación y el informe (Mayús+A)",
"Mostra o nascondi il grafico di valutazione e il resoconto (Maiusc+A)",
],
[
"📈 Analyse game",
"📈 Анализ партии",
"📈 Analyser la partie",
"📈 Partie analysieren",
"📈 Analizar partida",
"📈 Analizza partita",
],
[
"Evaluate every move: accuracy, inaccuracies, mistakes, blunders (Shift+A)",
"Оценить каждый ход: точность, неточности, ошибки, зевки (Shift+A)",
"Évaluer chaque coup : précision, imprécisions, erreurs, gaffes (Maj+A)",
"Jeden Zug bewerten: Genauigkeit, Ungenauigkeiten, Fehler, grobe Fehler (Umschalt+A)",
"Evaluar cada jugada: precisión, imprecisiones, errores, errores graves (Mayús+A)",
"Valuta ogni mossa: precisione, imprecisioni, errori, svarioni (Maiusc+A)",
],
[
"Notation",
"Нотация",
"Notation",
"Notation",
"Notación",
"Notazione",
],
[
"Report",
"Отчёт",
"Rapport",
"Bericht",
"Informe",
"Resoconto",
],
[
"paused: the game is being analysed",
"пауза: идёт анализ партии",
"en pause : analyse de la partie en cours",
"pausiert: Partie wird analysiert",
"en pausa: se está analizando la partida",
"in pausa: analisi della partita in corso",
],
[
"Analysis written to the game: {n} marked moves (Ctrl+Z to undo)",
"Анализ записан в партию: отмечено ходов — {n} (Ctrl+Z — отменить)",
"Analyse écrite dans la partie : {n} coups marqués (Ctrl+Z pour annuler)",
"Analyse in die Partie geschrieben: {n} markierte Züge (Strg+Z zum Rückgängigmachen)",
"Análisis escrito en la partida: {n} jugadas marcadas (Ctrl+Z para deshacer)",
"Analisi scritta nella partita: {n} mosse segnate (Ctrl+Z per annullare)",
],
[
"Best:",
"Лучше:",
"Meilleur :",
"Besser:",
"Mejor:",
"Meglio:",
],
[
"Show this line on the board",
"Показать этот вариант на доске",
"Afficher cette ligne sur l'échiquier",
"Diese Variante auf dem Brett zeigen",
"Mostrar esta línea en el tablero",
"Mostra questa linea sulla scacchiera",
],
[
"Opening",
"Дебют",
"Ouverture",
"Eröffnung",
"Apertura",
"Apertura",
],
[
"Middlegame",
"Миттельшпиль",
"Milieu de partie",
"Mittelspiel",
"Medio juego",
"Mediogioco",
],
[
"Endgame",
"Эндшпиль",
"Finale",
"Endspiel",
"Final",
"Finale",
],
[
"Start position",
"Начальная позиция",
"Position de départ",
"Ausgangsstellung",
"Posición inicial",
"Posizione iniziale",
],
[
"Evaluations from the PGN ([%eval])",
"Оценки из PGN ([%eval])",
"Évaluations issues du PGN ([%eval])",
"Bewertungen aus der PGN ([%eval])",
"Evaluaciones del PGN ([%eval])",
"Valutazioni dal PGN ([%eval])",
],
[
"Update",
"Дополнить",
"Compléter",
"Ergänzen",
"Completar",
"Completa",
],
[
"Write analysis to the game",
"Записать анализ в партию",
"Écrire l'analyse dans la partie",
"Analyse in die Partie schreiben",
"Escribir el análisis en la partida",
"Scrivi l'analisi nella partita",
],
[
"Adds evaluations, ?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)",
"Добавляет в партию оценки, знаки ?!/?/??, комментарии и лучшие варианты (Ctrl+Z — отменить)",
"Ajoute à la partie les évaluations, les signes ?!/?/??, des commentaires et les meilleures lignes (Ctrl+Z pour annuler)",
"Fügt der Partie Bewertungen, ?!/?/??-Zeichen, Kommentare und bessere Varianten hinzu (Strg+Z zum Rückgängigmachen)",
"Añade a la partida evaluaciones, signos ?!/?/??, comentarios y mejores líneas (Ctrl+Z para deshacer)",
"Aggiunge alla partita valutazioni, segni ?!/?/??, commenti e linee migliori (Ctrl+Z per annullare)",
],
[
"Analyse again…",
"Проанализировать заново…",
"Analyser de nouveau…",
"Erneut analysieren…",
"Analizar de nuevo…",
"Analizza di nuovo…",
],
[
"Go to the next one",
"Перейти к следующей",
"Aller au suivant",
"Zum nächsten",
"Ir al siguiente",
"Vai al successivo",
],
[
"Average centipawn loss",
"Средняя потеря сантипешек",
"Perte moyenne en centipions",
"Durchschnittlicher Centibauernverlust",
"Pérdida media de centipeones",
"Perdita media in centipedoni",
],
[
"Accuracy",
"Точность",
"Précision",
"Genauigkeit",
"Precisión",
"Precisione",
],
[
"The engine evaluates every position of the main line. The game itself is not changed.",
"Движок оценит каждую позицию основной линии. Сама партия не изменится.",
"Le moteur évalue chaque position de la ligne principale. La partie elle-même n'est pas modifiée.",
"Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.",
"El motor evalúa cada posición de la línea principal. La partida en sí no cambia.",
"Il motore valuta ogni posizione della linea principale. La partita non viene modificata.",
],
[
"Quality",
"Качество",
"Qualité",
"Qualität",
"Calidad",
"Qualità",
],
[
"Analyse",
"Анализировать",
"Analyser",
"Analysieren",
"Analizar",
"Analizza",
],
[
"Add an engine first",
"Сначала добавьте движок",
"Ajoutez d'abord un moteur",
"Zuerst eine Engine hinzufügen",
"Primero añade un motor",
"Aggiungi prima un motore",
],
[
"Inaccuracy",
"Неточность",
"Imprécision",
"Ungenauigkeit",
"Imprecisión",
"Imprecisione",
],
["Mistake", "Ошибка", "Erreur", "Fehler", "Error", "Errore"],
[
"Blunder",
"Зевок",
"Gaffe",
"Grober Fehler",
"Error grave",
"Svarione",
],
[
"Inaccuracies",
"Неточности",
"Imprécisions",
"Ungenauigkeiten",
"Imprecisiones",
"Imprecisioni",
],
[
"Mistakes",
"Ошибки",
"Erreurs",
"Fehler",
"Errores",
"Errori",
],
[
"Blunders",
"Зевки",
"Gaffes",
"Grobe Fehler",
"Errores graves",
"Svarioni",
],
[
"{judgement}. {best} was best.",
"{judgement}. Лучше было {best}.",
"{judgement}. {best} était meilleur.",
"{judgement}. Besser war {best}.",
"{judgement}. Era mejor {best}.",
"{judgement}. Era meglio {best}.",
],
[
"{engine} · {nodes} nodes per move",
"{engine} · {nodes} узлов на ход",
"{engine} · {nodes} nœuds par coup",
"{engine} · {nodes} Knoten pro Zug",
"{engine} · {nodes} nodos por jugada",
"{engine} · {nodes} nodi per mossa",
],
[
"Positions without evaluation: {n}",
"Позиций без оценки: {n}",
"Positions sans évaluation : {n}",
"Stellungen ohne Bewertung: {n}",
"Posiciones sin evaluación: {n}",
"Posizioni senza valutazione: {n}",
],
[
"{quality} · {nodes} nodes",
"{quality} · {nodes} узлов",
"{quality} · {nodes} nœuds",
"{quality} · {nodes} Knoten",
"{quality} · {nodes} nodos",
"{quality} · {nodes} nodi",
],
[
"{n} positions, about {time}",
"Позиций: {n}, примерно {time}",
"{n} positions, environ {time}",
"{n} Stellungen, etwa {time}",
"{n} posiciones, unos {time}",
"{n} posizioni, circa {time}",
],
[
"{n} min",
"{n} мин",
"{n} min",
"{n} Min.",
"{n} min",
"{n} min",
],
["Fast", "Быстро", "Rapide", "Schnell", "Rápido", "Veloce"],
["Normal", "Обычно", "Normal", "Normal", "Normal", "Normale"],
[
"Deep",
"Глубоко",
"Approfondi",
"Gründlich",
"Profundo",
"Approfondito",
],
];
#[cfg(test)]
@ -1055,6 +1387,8 @@ mod tests {
include_str!("game_view.rs"),
include_str!("library.rs"),
include_str!("notation.rs"),
include_str!("review.rs"),
include_str!("settings.rs"),
include_str!("settings_ui.rs"),
include_str!("widgets.rs"),
];

View file

@ -9,6 +9,8 @@ mod game_view;
mod i18n;
mod library;
mod notation;
mod report;
mod review;
mod settings;
mod settings_ui;
mod sound;

View file

@ -1,7 +1,10 @@
//! Move list: main line as a two-column table (Lichess style), comments and variations
//! as full-width blocks between rows; nested variations inline in parentheses.
use std::collections::HashMap;
use crate::i18n::tr;
use crate::review::{Mark, judgement_color, judgement_name, judgement_symbol};
use chess_core::shakmaty::Color;
use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment};
use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2};
@ -10,6 +13,8 @@ pub struct Notation<'a> {
pub game: &'a Game,
pub cursor: NodeId,
pub scroll_to_cursor: bool,
/// Engine assessments of main-line moves (whole-game analysis), shown apart from NAGs.
pub marks: Option<&'a HashMap<NodeId, Mark>>,
}
/// Result of a frame of the notation panel.
@ -17,6 +22,8 @@ pub struct Notation<'a> {
pub struct NotationResponse {
pub clicked: Option<NodeId>,
pub context: Option<(NodeId, NotationCommand)>,
/// The better line of this marked move was clicked.
pub best: Option<NodeId>,
}
#[derive(Clone, Copy, Debug)]
@ -63,9 +70,14 @@ impl Notation<'_> {
}
let after = comment_text(n.comments_after());
let vars = game.variations(node);
let interrupted = !after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty();
let mark = self.marks.and_then(|m| m.get(&child));
let interrupted =
!after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty() || mark.is_some();
if interrupted || color == Color::Black {
row.flush(ui, &self, &mut out);
if let Some(mark) = mark {
mark_block(ui, child, mark, &mut out);
}
if !after.is_empty() {
comment_block(ui, &after);
}
@ -126,6 +138,9 @@ impl Row {
Some(id) => {
let resp = ui.interact(cell, ui.id().with(("mv", id.index())), Sense::click());
paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered());
if let Some(mark) = n.marks.and_then(|m| m.get(&id)) {
paint_badge(ui, cell, mark);
}
handle_move_response(ui, &resp, n, id, out);
}
None => {
@ -205,6 +220,72 @@ fn paint_move_cell(
);
}
/// Engine verdict at the right edge of a move cell: a filled pill, unlike the author's NAGs.
fn paint_badge(ui: &Ui, cell: egui::Rect, mark: &Mark) {
let color = judgement_color(mark.judgement);
let font = FontId::proportional(12.0);
let galley = ui.painter().layout_no_wrap(
judgement_symbol(mark.judgement).to_string(),
font,
Color32::WHITE,
);
let size = vec2(galley.size().x + 10.0, 16.0);
let rect = egui::Rect::from_min_size(
egui::pos2(cell.right() - size.x - 6.0, cell.center().y - size.y / 2.0),
size,
);
ui.painter().rect_filled(rect, 8.0, color);
ui.painter()
.galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE);
}
/// "Mistake. Best: 23…Nf6 24.Nd5 …" under a marked main-line move; the line opens as a preview.
fn mark_block(ui: &mut Ui, id: NodeId, mark: &Mark, out: &mut NotationResponse) {
let color = judgement_color(mark.judgement);
egui::Frame::new()
.fill(ui.visuals().extreme_bg_color)
.inner_margin(egui::Margin {
left: 10,
right: 10,
top: 3,
bottom: 3,
})
.stroke(Stroke::new(1.0, color.gamma_multiply(0.6)))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 5.0;
ui.label(
RichText::new(format!("{}.", judgement_name(mark.judgement)))
.color(color)
.strong(),
);
let Some(first) = &mark.best_label else {
return;
};
ui.label(RichText::new(tr("Best:")).weak());
let mut line = first.clone();
for san in mark.best_san.iter().skip(1).take(4) {
line.push(' ');
line.push_str(san);
}
if mark.best_san.len() > 5 {
line.push_str(" …");
}
if ui
.add(
egui::Button::new(RichText::new(line).size(14.5))
.frame_when_inactive(false),
)
.on_hover_text(tr("Show this line on the board"))
.clicked()
{
out.best = Some(id);
}
});
});
}
/// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments.
fn move_glyph(nags: &[Nag]) -> (String, Option<Color32>) {
let mut s = String::new();

569
apps/desktop/src/report.rs Normal file
View file

@ -0,0 +1,569 @@
//! Game review metrics: win percentage, move and game accuracy, inaccuracy/mistake/blunder
//! judgements, average centipawn loss and game phases.
//!
//! The method follows Lichess (lila `WinPercent`, `AccuracyPercent`, `Advice`, and the
//! scalachess `Divider`, see <https://lichess.org/page/accuracy>); this is an independent
//! reimplementation of the published formulas.
use chess_core::shakmaty::{Bitboard, Chess, Color, Position, Rank};
use serde::{Deserialize, Serialize};
/// Engine evaluation from White's point of view.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Eval {
Cp(i32),
/// Forced mate; `moves == 0` in a checkmate position.
Mate {
white: bool,
moves: u32,
},
}
/// Centipawn ceiling: larger advantages (and mates) count as this much.
const CP_CEILING: i32 = 1000;
impl Eval {
pub fn from_white_eval(e: uci::WhiteEval) -> Eval {
match e {
uci::WhiteEval::Cp(cp) => Eval::Cp(cp),
uci::WhiteEval::Mate { winner, moves } => Eval::Mate {
white: winner == uci::Side::White,
moves,
},
}
}
/// Centipawns for `side`, mates folded into the ceiling.
fn cp_for(self, side: Color) -> i32 {
let white = match self {
Eval::Cp(cp) => cp.clamp(-CP_CEILING, CP_CEILING),
Eval::Mate { white: true, .. } => CP_CEILING,
Eval::Mate { white: false, .. } => -CP_CEILING,
};
if side == Color::White { white } else { -white }
}
/// `Some(true)` if `side` has a forced mate, `Some(false)` if it is being mated.
fn mate_for(self, side: Color) -> Option<bool> {
match self {
Eval::Cp(_) => None,
Eval::Mate { white, .. } => Some(white == (side == Color::White)),
}
}
/// Chance of winning for `side`, 0..100.
pub fn win_percent(self, side: Color) -> f64 {
50.0 + 50.0 * winning_chances(self.cp_for(side))
}
/// "+0.35", "−1.20", "#3", "#-2", "1-0".
pub fn format(self) -> String {
match self {
Eval::Cp(cp) => format!("{:+.2}", f64::from(cp) / 100.0),
Eval::Mate { white, moves: 0 } => if white { "1-0" } else { "0-1" }.into(),
Eval::Mate { white: true, moves } => format!("#{moves}"),
Eval::Mate {
white: false,
moves,
} => format!("#-{moves}"),
}
}
/// Value for a PGN `[%eval …]` command (pawns or `#n`).
pub fn pgn(self) -> String {
match self {
Eval::Cp(cp) => format!("{:.2}", f64::from(cp) / 100.0),
Eval::Mate { white, moves } => {
format!("#{}{moves}", if white { "" } else { "-" })
}
}
}
/// Parses a PGN `[%eval …]` payload ("0.35", "-1.2", "#3", "#-2").
pub fn parse_pgn(s: &str) -> Option<Eval> {
let s = s.split([',', ' ']).next()?.trim();
if let Some(m) = s.strip_prefix('#') {
let n: i32 = m.parse().ok()?;
return Some(Eval::Mate {
white: !m.starts_with('-'),
moves: n.unsigned_abs(),
});
}
let pawns: f64 = s.parse().ok()?;
pawns
.is_finite()
.then(|| Eval::Cp((pawns * 100.0).round().clamp(-100_000.0, 100_000.0) as i32))
}
}
/// Lichess winning chances, −1..1.
fn winning_chances(cp: i32) -> f64 {
2.0 / (1.0 + (-0.003_682_08 * f64::from(cp)).exp()) - 1.0
}
/// Accuracy of a move given the mover's win percentage before and after it, 0..100.
fn move_accuracy(before: f64, after: f64) -> f64 {
if after >= before {
return 100.0;
}
let raw = 103.166_810_071_164_9 * (-0.043_544_153_867_539_51 * (before - after)).exp()
- 3.166_924_740_191_411;
// +1: uncertainty bonus for imperfect analysis, as on Lichess.
(raw + 1.0).clamp(0.0, 100.0)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Judgement {
Inaccuracy,
Mistake,
Blunder,
}
/// Judgement of a move from the evaluations before and after it.
fn judge(before: Eval, after: Eval, mover: Color) -> Option<Judgement> {
use Judgement::*;
let (mb, ma) = (before.mate_for(mover), after.mate_for(mover));
if ma == Some(false) && mb != Some(false) {
// The move allows a forced mate.
let cp = before.cp_for(mover);
return Some(if cp < -999 {
Inaccuracy
} else if cp < -700 {
Mistake
} else {
Blunder
});
}
if mb == Some(true) && ma != Some(true) {
// A forced mate was let go.
let cp = after.cp_for(mover);
return Some(if cp > 999 {
Inaccuracy
} else if cp > 700 {
Mistake
} else {
Blunder
});
}
if mb.is_some() || ma.is_some() {
return None;
}
let delta = winning_chances(before.cp_for(mover)) - winning_chances(after.cp_for(mover));
if delta >= 0.3 {
Some(Blunder)
} else if delta >= 0.2 {
Some(Mistake)
} else if delta >= 0.1 {
Some(Inaccuracy)
} else {
None
}
}
/// Game phases as indices of the first position of each phase.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Phases {
pub middlegame: Option<usize>,
pub endgame: Option<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
Opening,
Middlegame,
Endgame,
}
impl Phases {
/// Splits a sequence of positions: the middlegame starts once few pieces are left or
/// a back rank is sparse; the endgame once at most six queens, rooks and minor pieces remain.
pub fn divide(positions: &[Chess]) -> Phases {
let majors_minors = |p: &Chess| {
let b = p.board();
(b.knights() | b.bishops() | b.rooks() | b.queens()).count()
};
let backrank_sparse = |p: &Chess| {
let b = p.board();
(b.by_color(Color::White) & Bitboard::from_rank(Rank::First)).count() < 4
|| (b.by_color(Color::Black) & Bitboard::from_rank(Rank::Eighth)).count() < 4
};
let middlegame = positions
.iter()
.position(|p| majors_minors(p) <= 10 || backrank_sparse(p));
let endgame = middlegame.and_then(|m| {
positions[m..]
.iter()
.position(|p| majors_minors(p) <= 6)
.map(|i| i + m)
});
Phases {
middlegame,
endgame,
}
}
pub fn of(self, position: usize) -> Phase {
if self.endgame.is_some_and(|e| position >= e) {
Phase::Endgame
} else if self.middlegame.is_some_and(|m| position >= m) {
Phase::Middlegame
} else {
Phase::Opening
}
}
}
/// A move of the analysed line.
#[derive(Clone, Copy, Debug)]
pub struct Ply {
pub mover: Color,
/// Teaching null move `--`: not graded.
pub null: bool,
/// The move played equals the engine's best move (never judged as an error).
pub best: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SideStats {
pub inaccuracies: u32,
pub mistakes: u32,
pub blunders: u32,
/// Average centipawn loss.
pub acpl: Option<u32>,
pub accuracy: Option<f64>,
/// Opening, middlegame, endgame.
pub phase_accuracy: [Option<f64>; 3],
}
#[derive(Clone, Debug, Default)]
pub struct Report {
/// Per ply of the line.
pub judgements: Vec<Option<Judgement>>,
pub white: SideStats,
pub black: SideStats,
pub phases: Phases,
/// All positions are evaluated.
pub complete: bool,
}
impl Report {
pub fn side(&self, c: Color) -> &SideStats {
match c {
Color::White => &self.white,
Color::Black => &self.black,
}
}
/// `evals[i]` belongs to the position before ply `i`; `evals.len() == plies.len() + 1`.
pub fn build(evals: &[Option<Eval>], plies: &[Ply], phases: Phases) -> Report {
let n = plies.len().min(evals.len().saturating_sub(1));
let mut report = Report {
judgements: vec![None; plies.len()],
phases,
complete: evals.iter().take(n + 1).all(Option::is_some),
..Report::default()
};
let mut losses: [Vec<i32>; 2] = [Vec::new(), Vec::new()];
for i in 0..n {
let ply = plies[i];
let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else {
continue;
};
if ply.null {
continue;
}
let j = if ply.best {
None
} else {
judge(before, after, ply.mover)
};
report.judgements[i] = j;
let stats = match ply.mover {
Color::White => &mut report.white,
Color::Black => &mut report.black,
};
match j {
Some(Judgement::Inaccuracy) => stats.inaccuracies += 1,
Some(Judgement::Mistake) => stats.mistakes += 1,
Some(Judgement::Blunder) => stats.blunders += 1,
None => {}
}
let loss = (before.cp_for(ply.mover) - after.cp_for(ply.mover)).max(0);
losses[ply.mover as usize].push(loss);
}
for color in [Color::White, Color::Black] {
let l = &losses[color as usize];
if !l.is_empty() {
let avg = l.iter().map(|x| i64::from(*x)).sum::<i64>() as f64 / l.len() as f64;
let stats = match color {
Color::White => &mut report.white,
Color::Black => &mut report.black,
};
stats.acpl = Some(avg.round() as u32);
}
}
if report.complete && n > 0 {
let wp: Vec<f64> = evals[..=n]
.iter()
.map(|e| e.map_or(50.0, |e| e.win_percent(Color::White)))
.collect();
report.fill_accuracy(&wp, &plies[..n]);
}
report
}
/// Lichess game accuracy: mean of the volatility-weighted mean and the harmonic mean
/// of move accuracies.
fn fill_accuracy(&mut self, wp: &[f64], plies: &[Ply]) {
let window = (wp.len() / 10).clamp(2, 8).min(wp.len());
let mut windows: Vec<&[f64]> = vec![&wp[..window]; window.saturating_sub(2)];
windows.extend(wp.windows(window));
let weights: Vec<f64> = windows
.iter()
.map(|w| std_dev(w).clamp(0.5, 12.0))
.collect();
// (color, phase, accuracy, weight)
let mut moves = Vec::new();
for (i, ply) in plies.iter().enumerate() {
if ply.null {
continue;
}
let (before, after) = (wp[i], wp[i + 1]);
let (before, after) = match ply.mover {
Color::White => (before, after),
Color::Black => (100.0 - before, 100.0 - after),
};
let weight = weights.get(i).copied().unwrap_or(0.5);
moves.push((
ply.mover,
self.phases.of(i),
move_accuracy(before, after),
weight,
));
}
for color in [Color::White, Color::Black] {
let all: Vec<(f64, f64)> = moves
.iter()
.filter(|m| m.0 == color)
.map(|m| (m.2, m.3))
.collect();
let phase = |p: Phase| {
let v: Vec<(f64, f64)> = moves
.iter()
.filter(|m| m.0 == color && m.1 == p)
.map(|m| (m.2, m.3))
.collect();
// Too few moves in a phase say nothing about it.
if v.len() >= 3 { mixed_mean(&v) } else { None }
};
let stats = match color {
Color::White => &mut self.white,
Color::Black => &mut self.black,
};
stats.accuracy = mixed_mean(&all);
stats.phase_accuracy = [
phase(Phase::Opening),
phase(Phase::Middlegame),
phase(Phase::Endgame),
];
}
}
}
fn std_dev(xs: &[f64]) -> f64 {
if xs.is_empty() {
return 0.0;
}
let mean = xs.iter().sum::<f64>() / xs.len() as f64;
(xs.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / xs.len() as f64).sqrt()
}
/// Average of the weighted mean and the harmonic mean of `(accuracy, weight)`.
fn mixed_mean(v: &[(f64, f64)]) -> Option<f64> {
if v.is_empty() {
return None;
}
let wsum: f64 = v.iter().map(|x| x.1).sum();
let weighted = v.iter().map(|x| x.0 * x.1).sum::<f64>() / wsum.max(f64::EPSILON);
let harmonic = v.len() as f64 / v.iter().map(|x| 1.0 / x.0.max(1.0)).sum::<f64>();
Some((weighted + harmonic) / 2.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn ply(mover: Color) -> Ply {
Ply {
mover,
null: false,
best: false,
}
}
fn alternating(n: usize) -> Vec<Ply> {
(0..n)
.map(|i| {
ply(if i % 2 == 0 {
Color::White
} else {
Color::Black
})
})
.collect()
}
#[test]
fn win_percent_matches_lichess_curve() {
assert!((Eval::Cp(0).win_percent(Color::White) - 50.0).abs() < 1e-9);
let w = Eval::Cp(100).win_percent(Color::White);
assert!((w - 59.1).abs() < 0.1, "{w}");
assert!((Eval::Cp(100).win_percent(Color::Black) - (100.0 - w)).abs() < 1e-9);
// Mates count as the centipawn ceiling.
let m = Eval::Mate {
white: true,
moves: 3,
};
assert_eq!(
m.win_percent(Color::White),
Eval::Cp(5000).win_percent(Color::White)
);
}
#[test]
fn move_accuracy_bounds() {
assert_eq!(move_accuracy(50.0, 60.0), 100.0);
assert_eq!(move_accuracy(50.0, 50.0), 100.0);
let small = move_accuracy(60.0, 55.0);
let big = move_accuracy(60.0, 20.0);
assert!(small > 75.0 && small < 100.0, "{small}");
assert!(big < 20.0, "{big}");
assert_eq!(move_accuracy(100.0, 0.0), 0.0);
}
#[test]
fn judgements_follow_win_chance_drop() {
let w = Color::White;
assert_eq!(judge(Eval::Cp(0), Eval::Cp(-30), w), None);
assert_eq!(
judge(Eval::Cp(0), Eval::Cp(-60), w),
Some(Judgement::Inaccuracy)
);
assert_eq!(
judge(Eval::Cp(0), Eval::Cp(-150), w),
Some(Judgement::Mistake)
);
assert_eq!(
judge(Eval::Cp(0), Eval::Cp(-500), w),
Some(Judgement::Blunder)
);
// Black's point of view: White's eval going up is Black's loss.
assert_eq!(
judge(Eval::Cp(0), Eval::Cp(500), Color::Black),
Some(Judgement::Blunder)
);
// Already winning by a lot: losing a pawn changes nothing.
assert_eq!(judge(Eval::Cp(900), Eval::Cp(800), w), None);
let mated = Eval::Mate {
white: false,
moves: 4,
};
let mating = Eval::Mate {
white: true,
moves: 4,
};
assert_eq!(judge(Eval::Cp(0), mated, w), Some(Judgement::Blunder));
assert_eq!(
judge(Eval::Cp(-1200), mated, w),
Some(Judgement::Inaccuracy)
);
assert_eq!(judge(mating, Eval::Cp(300), w), Some(Judgement::Blunder));
assert_eq!(
judge(mating, Eval::Cp(1500), w),
Some(Judgement::Inaccuracy)
);
assert_eq!(judge(mating, mating, w), None);
assert_eq!(judge(mated, mated, w), None);
assert_eq!(judge(Eval::Cp(0), mating, w), None);
}
#[test]
fn report_counts_and_accuracy() {
// White blunders on ply 2; everything else is quiet.
let cps = [20, 25, 20, -400, -390, -400, -395];
let evals: Vec<Option<Eval>> = cps.iter().map(|c| Some(Eval::Cp(*c))).collect();
let plies = alternating(cps.len() - 1);
let r = Report::build(&evals, &plies, Phases::default());
assert!(r.complete);
assert_eq!(r.judgements[2], Some(Judgement::Blunder));
assert_eq!(r.white.blunders, 1);
assert_eq!(
r.black.blunders + r.black.mistakes + r.black.inaccuracies,
0
);
let (wa, ba) = (r.white.accuracy.expect("w"), r.black.accuracy.expect("b"));
assert!(wa < ba, "white {wa} black {ba}");
assert!(ba > 90.0);
assert!(r.white.acpl.expect("acpl") > r.black.acpl.expect("acpl"));
}
#[test]
fn partial_and_special_plies() {
let evals = vec![Some(Eval::Cp(0)), Some(Eval::Cp(-500)), None, None];
let mut plies = alternating(3);
let r = Report::build(&evals, &plies, Phases::default());
assert!(!r.complete);
assert_eq!(r.white.blunders, 1);
assert_eq!(r.white.accuracy, None);
// The engine's own best move is never an error; null moves are not graded.
plies[0].best = true;
let r = Report::build(&evals, &plies, Phases::default());
assert_eq!(r.white.blunders, 0);
plies[0].best = false;
plies[0].null = true;
let r = Report::build(&evals, &plies, Phases::default());
assert_eq!(r.white.blunders, 0);
assert_eq!(r.white.acpl, None);
}
#[test]
fn pgn_eval_roundtrip() {
for e in [
Eval::Cp(35),
Eval::Cp(-120),
Eval::Mate {
white: true,
moves: 3,
},
Eval::Mate {
white: false,
moves: 2,
},
] {
assert_eq!(Eval::parse_pgn(&e.pgn()), Some(e));
}
assert_eq!(Eval::parse_pgn("0.17,22"), Some(Eval::Cp(17)));
assert_eq!(Eval::parse_pgn("abc"), None);
}
#[test]
fn phases_of_a_real_game() {
// The Opera Game: queens and rooks stay until the very end, so no endgame.
let game = chess_core::parse_str(
"1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 7. Qb3 Qe7 \
8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 13. Rxd7 Rxd7 \
14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ Nxb8 17. Rd8# 1-0",
)
.game;
let positions: Vec<Chess> = std::iter::once(chess_core::NodeId::ROOT)
.chain(game.mainline())
.filter_map(|n| game.position(n).cloned())
.collect();
assert_eq!(positions.len(), 34);
let p = Phases::divide(&positions);
let mid = p.middlegame.expect("middlegame");
assert!(mid > 4 && mid < 25, "{mid}");
assert_eq!(p.of(0), Phase::Opening);
assert_eq!(p.of(mid), Phase::Middlegame);
}
}

1349
apps/desktop/src/review.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -63,6 +63,41 @@ pub struct Settings {
pub show_best_arrow: bool,
/// Recently opened PGN files, most recent first.
pub databases: Vec<PathBuf>,
/// Whole-game analysis options.
pub review: ReviewSettings,
}
/// Options of the whole-game analysis (the engine is the active one).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct ReviewSettings {
/// Index into [`REVIEW_QUALITY`].
pub quality: usize,
pub threads: u32,
pub hash_mb: u32,
}
impl Default for ReviewSettings {
fn default() -> Self {
Self {
quality: 1,
threads: default_threads(),
hash_mb: default_hash(),
}
}
}
/// Search effort per position: (label, nodes).
pub const REVIEW_QUALITY: [(&str, u64); 3] = [
("Fast", 250_000),
("Normal", 1_000_000),
("Deep", 3_000_000),
];
impl ReviewSettings {
pub fn nodes(&self) -> u64 {
REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1
}
}
impl Default for Settings {
@ -80,6 +115,7 @@ impl Default for Settings {
active_engine: None,
show_best_arrow: true,
databases: Vec::new(),
review: ReviewSettings::default(),
}
}
}
@ -90,6 +126,12 @@ impl Settings {
.map(|d| d.config_dir().to_path_buf())
}
/// `~/.cache/chesspenguin` (derived data that can be deleted at any time).
pub fn cache_dir() -> Option<PathBuf> {
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
.map(|d| d.cache_dir().to_path_buf())
}
fn file() -> Option<PathBuf> {
Self::config_dir().map(|d| d.join("settings.json"))
}

View file

@ -5,7 +5,16 @@ use egui::{Color32, Sense, Stroke, Ui, vec2};
/// Window close button (the app runs undecorated under tiling compositors).
pub fn close_button(ui: &mut Ui) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 28.0), Sense::click());
x_button(ui, vec2(32.0, 28.0), 6.0).on_hover_text(tr("Close the application"))
}
/// Compact ✕ (e.g. to cancel a running task); the caller adds the tooltip.
pub fn small_close_button(ui: &mut Ui) -> egui::Response {
x_button(ui, vec2(22.0, 20.0), 4.5)
}
fn x_button(ui: &mut Ui, size: egui::Vec2, d: f32) -> egui::Response {
let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
if resp.hovered() {
ui.painter()
.rect_filled(rect, 4.0, Color32::from_rgb(0xc4, 0x2b, 0x1c));
@ -16,11 +25,10 @@ pub fn close_button(ui: &mut Ui) -> egui::Response {
ui.visuals().text_color()
};
let c = rect.center();
let d = 6.0;
let stroke = Stroke::new(1.6, color);
ui.painter()
.line_segment([c + vec2(-d, -d), c + vec2(d, d)], stroke);
ui.painter()
.line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke);
resp.on_hover_text(tr("Close the application"))
resp
}

View file

@ -7,6 +7,14 @@
use shakmaty::{CastlingMode, Move, Position, san::SanPlus, uci::UciMove};
use crate::game::{Game, GameMove, MoveKind, NodeId};
use crate::nag::Nag;
/// NAGs and trailing comments of a node (what annotation edits change).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Annotations {
nags: Vec<Nag>,
comments_after: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Command {
@ -25,12 +33,19 @@ pub(crate) enum Command {
from: usize,
to: usize,
},
Annotate {
node: NodeId,
old: Annotations,
new: Annotations,
},
/// Several commands undone and redone as one step.
Group(Vec<Command>),
}
impl Command {
fn inverse(&self) -> Command {
match *self {
Command::Attach {
match self {
&Command::Attach {
parent,
child,
index,
@ -39,7 +54,7 @@ impl Command {
child,
index,
},
Command::Detach {
&Command::Detach {
parent,
child,
index,
@ -48,22 +63,32 @@ impl Command {
child,
index,
},
Command::Reorder { parent, from, to } => Command::Reorder {
&Command::Reorder { parent, from, to } => Command::Reorder {
parent,
from: to,
to: from,
},
Command::Annotate { node, old, new } => Command::Annotate {
node: *node,
old: new.clone(),
new: old.clone(),
},
Command::Group(cmds) => {
Command::Group(cmds.iter().rev().map(Command::inverse).collect())
}
}
}
/// Node the UI should select after this command has been applied.
fn cursor(&self, game: &Game) -> NodeId {
match *self {
Command::Attach { child, .. } => child,
Command::Detach { parent, .. } => parent,
Command::Reorder { parent, to, .. } => {
match self {
&Command::Attach { child, .. } => child,
&Command::Detach { parent, .. } => parent,
&Command::Reorder { parent, to, .. } => {
game.children(parent).get(to).copied().unwrap_or(parent)
}
Command::Annotate { node, .. } => *node,
Command::Group(cmds) => cmds.first().map_or(NodeId::ROOT, |c| c.cursor(game)),
}
}
}
@ -227,6 +252,43 @@ impl Game {
Ok(())
}
/// Replaces the NAGs and trailing comments of `id`. Undoable; no-op if unchanged.
pub fn annotate(
&mut self,
id: NodeId,
nags: Vec<Nag>,
comments_after: Vec<String>,
) -> Result<(), EditError> {
self.check_attached(id)?;
let node = self.node(id).ok_or(EditError::UnknownNode)?;
let old = Annotations {
nags: node.nags.clone(),
comments_after: node.comments_after.clone(),
};
let new = Annotations {
nags,
comments_after,
};
if old != new {
self.record(Command::Annotate { node: id, old, new });
}
Ok(())
}
/// Runs `f` so that all its edits form a single undo step.
pub fn edit_group<R>(&mut self, f: impl FnOnce(&mut Game) -> R) -> R {
let outer = self.group.replace(Vec::new());
let result = f(self);
let cmds = std::mem::replace(&mut self.group, outer).unwrap_or_default();
if !cmds.is_empty() {
match &mut self.group {
Some(parent) => parent.push(Command::Group(cmds)),
None => self.push_undo(Command::Group(cmds)),
}
}
result
}
pub fn can_undo(&self) -> bool {
!self.undo_stack.is_empty()
}
@ -260,6 +322,15 @@ impl Game {
if !matches!(cmd, Command::Attach { .. }) {
self.apply(&cmd);
}
if let Some(group) = &mut self.group {
group.push(cmd);
self.touch();
return;
}
self.push_undo(cmd);
}
fn push_undo(&mut self, cmd: Command) {
if self.saved_depth.is_some_and(|d| d > self.undo_stack.len()) {
// The saved state lived in the redo stack, which is discarded now.
self.saved_depth = None;
@ -270,6 +341,22 @@ impl Game {
}
fn apply(&mut self, cmd: &Command) {
match cmd {
Command::Annotate { node, new, .. } => {
if let Some(n) = self.node_mut(*node) {
n.nags.clone_from(&new.nags);
n.comments_after.clone_from(&new.comments_after);
}
return;
}
Command::Group(cmds) => {
for c in cmds {
self.apply(c);
}
return;
}
_ => {}
}
match *cmd {
Command::Attach {
parent,
@ -299,6 +386,7 @@ impl Game {
p.children.insert(to, c);
}
}
Command::Annotate { .. } | Command::Group(_) => {}
}
}
@ -426,4 +514,60 @@ mod tests {
Err(EditError::RootNotRemovable)
);
}
#[test]
fn annotate_is_undoable() {
let mut g = Game::new();
let e4 = g.add_uci_line(g.root(), &["e2e4"]).expect("e4");
g.mark_saved();
g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()])
.expect("annotate");
assert_eq!(
g.node(e4).map(|n| n.nags().to_vec()),
Some(vec![Nag::GOOD_MOVE])
);
assert!(g.is_modified());
// Unchanged annotations do not create an undo step.
let depth = g.undo_stack.len();
g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()])
.expect("same");
assert_eq!(g.undo_stack.len(), depth);
assert_eq!(g.undo().map(|o| o.cursor), Some(e4));
assert!(
g.node(e4)
.is_some_and(|n| n.nags().is_empty() && n.comments_after().is_empty())
);
assert!(!g.is_modified());
g.redo();
assert_eq!(g.node(e4).map(|n| n.comments_after().len()), Some(1));
}
#[test]
fn edit_group_is_one_undo_step() {
let mut g = Game::new();
let end = g
.add_uci_line(g.root(), &["e2e4", "e7e5", "g1f3"])
.expect("line");
let e4 = g.main_child(g.root()).expect("e4");
let e5 = g.main_child(e4).expect("e5");
let before = g.canonical_tree();
let steps = g.undo_stack.len();
g.edit_group(|g| {
g.annotate(e5, vec![Nag::MISTAKE], vec!["better c5".into()])
.expect("annotate");
g.add_uci_line(e4, &["c7c5", "g1f3"]).expect("variation");
g.edit_group(|g| g.annotate(end, vec![Nag::DUBIOUS_MOVE], Vec::new()))
.expect("nested");
});
assert_eq!(g.undo_stack.len(), steps + 1);
assert_eq!(g.children(e4).len(), 2);
let after = g.canonical_tree();
g.undo();
assert_eq!(g.canonical_tree(), before);
g.redo();
assert_eq!(g.canonical_tree(), after);
// An empty group records nothing.
g.edit_group(|_| ());
assert_eq!(g.undo_stack.len(), steps + 1);
}
}

View file

@ -191,6 +191,8 @@ pub struct Game {
pub(crate) saved_depth: Option<usize>,
/// Changes outside the undo history (tags, result) since the last save.
pub(crate) unsaved_meta: bool,
/// Commands collected by an open [`Game::edit_group`].
pub(crate) group: Option<Vec<Command>>,
}
impl Default for Game {
@ -254,6 +256,7 @@ impl Game {
revision: 0,
saved_depth: Some(0),
unsaved_meta: false,
group: None,
}
}

View file

@ -14,6 +14,15 @@
7. **Название — ChessPenguin** (2026-10-18). Бинарник и пакеты `chesspenguin`, app id `io.github.vrubelroman.chessPenguin`, настройки в `~/.config/chesspenguin` (старые переносятся автоматически).
8. **Публикация** — https://github.com/vrubelroman/chessPenguin, чистая история без `designExample/` (чужие скриншоты остаются только локально). Версии по SemVer, первая — `0.1.0`, тег `v0.1.0`; релизы собирает GitHub Actions по тегу `v*`: deb, rpm, AppImage, Flatpak, Windows zip.
9. **Анализ партии (версия 0.2)** — 2026-10-18, по схеме, предложенной оркестратором и принятой пользователем:
- живой движок (оценка текущей позиции, `L`) и анализ партии целиком — разные процессы и разные кнопки; на время анализа партии живой движок ставится на паузу и затем возобновляется;
- кнопка «📈 Анализ партии» в шапке экрана партии (действие над партией, не над позицией), `Shift+A`; во время работы — прогресс и отмена, после — «📈 Отчёт» скрывает/показывает результаты;
- график оценки — полосой под доской (шкала — шанс на победу, как на Lichess), клик/протяжка переходит к ходу, отмечены стадии партии и ошибки;
- статистика — вкладкой «Отчёт» рядом с нотацией: неточности/ошибки/зевки (клик — к следующей), средняя потеря сантипешек, точность и точность по стадиям; кнопки «разобрать свои ошибки» нет — смотрим чужие партии;
- отметки движка в нотации — отдельным слоем (цветной значок), партия не меняется; «Записать анализ в партию» — отдельное действие с одним шагом отмены (NAG, комментарий, лучший вариант, `[%eval]`);
- анализируется только основная линия; результаты кэшируются в `~/.cache/chesspenguin/analysis/`; при правке основной линии дооцениваются только новые позиции; оценки `[%eval]` из PGN используются без движка;
- методика — опубликованные формулы Lichess (lichess.org/page/accuracy), реализованы заново.
## Следует из исходного ТЗ
- Linux desktop; предпочтение стека Artcraft, подлежащего проверке по исходникам.

View file

@ -12,6 +12,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
| `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках |
| `board.rs` | Виджет доски: клик/drag, превращение, рокировка кликом на поле короля или ладью, стрелки, круги |
| `analysis.rs` | Контроллер анализа поверх `uci`: запуск в фоне, привязка результатов к истории позиции, MultiPV |
| `report.rs` | Метрики анализа партии без UI: шанс на победу, точность хода и партии, неточность/ошибка/зевок, средняя потеря сантипешек, стадии партии (формулы Lichess) |
| `review.rs` | Анализ партии целиком: фоновый поток с собственным процессом движка (`go nodes N`), кэш, `[%eval]` из PGN, график, вкладка «Отчёт», окно запуска, запись анализа в партию |
| `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) |
| `settings.rs`, `settings_ui.rs` | JSON в `$XDG_CONFIG_HOME/chesspenguin/settings.json` (атомарная запись), окно настроек |
@ -20,11 +22,12 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i
- Анализ привязан к курсору партии, не к предпросмотру. Ключ — стартовая позиция + история ходов UCI; события с чужим `SearchId` отбрасываются.
- Предпросмотр PV — снимок линии; документ меняется только кнопкой «Добавить как вариант» (один шаг Undo).
- Исходный PGN не перезаписывается: только «Сохранить партию как…» в отдельный файл.
- Анализ партии не меняет документ. Ключ оценки — та же история позиции, что у живого анализа; кэш — `$XDG_CACHE_HOME/chesspenguin/analysis/<FNV-64 ключей линии>.json`. «Записать анализ в партию» — `Game::edit_group`, один шаг Undo; повторная запись заменяет `[%eval]`, а не дублирует.
## Клавиатура
Библиотека: ↑/↓ — строка, Enter — открыть, Ctrl+O — добавить PGN, Ctrl+N — новая партия, Ctrl+F — поиск.
Партия: ←/→ — ход, ↑/↓ — соседний вариант, Home/End, F — перевернуть, L — движок, Esc — выйти из предпросмотра,
Партия: ←/→ — ход, ↑/↓ — соседний вариант, Home/End, F — перевернуть, L — движок, Shift+A — анализ партии / отчёт, Esc — выйти из предпросмотра,
Ctrl+Z / Ctrl+Y — отмена/повтор, Ctrl+Shift+C — копировать PGN, Ctrl+S — сохранить как, Ctrl+W — в библиотеку, Ctrl+, — настройки.
## Dev-хуки запуска (ручная проверка и скриншоты)
@ -34,7 +37,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe
```
`CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии,
`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки, `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`.
`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки, `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`.
## Языки