Opponent prep: the desktop screen (dialog, report, engine run)

The «Prepare against…» entry points in the library (the filter panel's button
when a player is set, the game row's context menu, Ctrl+Shift+P), the dialog
(database, the player's spellings with the similar names apart, colour, book)
and the report screen in the stack between the library and the game: the
repertoire tree with transpositions, opening names, scores and the book
column, the openings table by family and variation, the errors tab (repeated
errors and by opening), the board of the chosen position with the line under
it, and the games of the selection, which open in the game screen at that move
with «⬅ Back to preparation».

The engine run reuses the game analysis job over the distinct opening
positions of the chosen colour: the launch dialog shares the engine picker and
the quality/threads/memory grid with review.rs (quality «Fast» by default, its
own setting), marks appear as positions are evaluated, «Stop» keeps what was
done, the evaluations and the report are cached under <cache>/prep. One engine
job per program: game analysis and the live engine are blocked meanwhile.

Core: targets and counts by colour (`targets_for`, `missing_for`), the book
step keeps its per-position counts (`book_counts`) for the tree column.
Narrow windows: the board stacks over the lists under 804 px and folds into a
button under 720 px of height; the right column is split explicitly (a nested
bottom panel is not reserved from the content above it in egui).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 15:43:15 +03:00
parent d54f207889
commit f02f140394
14 changed files with 6072 additions and 102 deletions

View file

@ -13,6 +13,7 @@ license.workspace = true
chess-core.workspace = true
maia.workspace = true
game-review.workspace = true
prep.workspace = true
chess-import.workspace = true
shakmaty.workspace = true
uci.workspace = true

View file

@ -13,6 +13,7 @@ use crate::analysis::Analysis;
use crate::assets::Sound;
use crate::game_view::{GameAction, GameSource, GameView};
use crate::library::{Library, LibraryAction};
use crate::prep_ui::{DialogOutcome, PrepAction, PrepDialog, PrepScreen};
use crate::own_db::{
self, Answer, ChooserFor, ChooserOutcome, EditorMode, EditorOutcome, NewBaseOutcome,
QuestionKind,
@ -244,6 +245,10 @@ pub struct App {
restart_to: Option<PathBuf>,
/// The reference tab of games (kept across games: its results stay cached).
reference: crate::reference::Reference,
/// Preparing against an opponent: the dialog, and the report screen in the stack
/// between the library and the game (opponent-prep.md §3.1).
prep_dialog: Option<PrepDialog>,
prep: Option<PrepScreen>,
allow_quit: bool,
applied_dark: Option<bool>,
debug: DebugStartup,
@ -279,6 +284,9 @@ struct DebugStartup {
next_key: f64,
/// `CP_TYPE=<text>`: typed into the field that has the keyboard, 2.5 s after start.
typed: Option<String>,
/// `CP_PREP=<name>`: «Prepare against…» for this name in the first database
/// (`CP_PREP_OPEN=1` presses «Open report», `CP_PREP_TAB`, `CP_PREP_ENGINE=1`).
prep: Option<String>,
}
impl DebugStartup {
@ -321,6 +329,7 @@ impl DebugStartup {
.collect(),
next_key: 2.0,
typed: std::env::var("CP_TYPE").ok(),
prep: std::env::var("CP_PREP").ok(),
}
}
}
@ -410,6 +419,8 @@ impl App {
update_ui: crate::update_ui::UpdateDialog::from_env(),
restart_to: None,
reference: Default::default(),
prep_dialog: None,
prep: None,
engine_offer: crate::engine_offer::EngineOffer::new(),
offer_hook_done: false,
online_probe: crate::online::Probe::start(ctx),
@ -642,6 +653,23 @@ impl App {
}
fn debug_step(&mut self, ctx: &egui::Context) {
if self.debug.prep.is_some()
&& let Some(path) = self.settings.databases.first().cloned()
&& self.library.database(&path).is_some()
{
let query = self.debug.prep.take().unwrap_or_default();
let side = match std::env::var("CP_PREP_COLOR").as_deref() {
Ok("white") => chess_import::chessbase::base::Side::White,
Ok("black") => chess_import::chessbase::base::Side::Black,
_ => chess_import::chessbase::base::Side::Any,
};
let entry = crate::prep_ui::PrepEntry {
query,
exact: None,
side,
};
self.prep_dialog = Some(PrepDialog::new(path, entry, &self.settings));
}
let Some(index) = self.debug.open else { return };
let Some(path) = self.settings.databases.first().cloned() else {
return;
@ -736,6 +764,134 @@ impl App {
self.toast_for(ctx, msg, 3.5);
}
/// The shelf as the reference tab and the preparation see it.
fn shelf_dbs(&self) -> Vec<crate::reference::RefDb> {
self.settings
.databases
.iter()
.filter(|p| self.library.files.exists(p))
.map(|p| crate::reference::RefDb {
path: p.clone(),
name: p
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
db: self.library.database(p),
failed: self.library.failure(p).map(str::to_owned),
bytes: self.library.file_size(p),
})
.collect()
}
// ----- preparing against an opponent (docs/design/opponent-prep.md) ------------
/// «Open report»: the report of the same player as it was, else a new one.
fn open_prep(&mut self, ctx: &egui::Context, start: crate::prep_ui::PrepStart) {
let Some(db) = self.library.database(&start.path) else {
return;
};
if let Some(p) = self.prep.as_mut()
&& p.matches(&start.path, &start.player)
{
p.shown = true;
return;
}
if let Some(mut old) = self.prep.take() {
old.save();
}
self.prep = Some(PrepScreen::new(start, db, &self.settings, ctx));
}
/// The preparation's dialog, when it is open.
fn prep_dialog(&mut self, ctx: &egui::Context) {
if self.prep_dialog.is_none() {
return;
}
let dbs = self.shelf_dbs();
let Some(d) = self.prep_dialog.as_mut() else {
return;
};
d.dbs = dbs;
let outcome = d.show(ctx, &mut self.settings);
match outcome {
Some(DialogOutcome::Open(start)) => {
self.prep_dialog = None;
self.settings_dirty = true;
self.open_prep(ctx, start);
}
Some(DialogOutcome::Cancel) => self.prep_dialog = None,
Some(DialogOutcome::LoadDb(p))
if !self.library.loading(&p) && self.library.database(&p).is_none() =>
{
self.library.load(&p, ctx);
}
Some(DialogOutcome::LoadDb(_)) | None => {}
}
}
fn prep_actions(&mut self, ctx: &egui::Context, actions: Vec<PrepAction>) {
for a in actions {
match a {
PrepAction::Back => {
if let Some(p) = self.prep.as_mut() {
p.shown = false;
p.save();
}
}
PrepAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open,
PrepAction::OpenGame { path, index, ply } => {
let title = self.prep.as_ref().map(|p| p.title());
self.open_game(ctx, path, index, None);
if let Some(g) = self.game.as_mut() {
g.previous = title;
g.previous_prep = true;
g.goto_ply(ply);
}
}
PrepAction::LoadDb(p) => {
if !self.library.loading(&p) && self.library.database(&p).is_none() {
self.library.load(&p, ctx);
}
}
// One engine job for the whole program: the live engine is off while
// the report is on the screen anyway (no game is open then).
PrepAction::EngineStarted => {
self.analysis.stop();
self.live_paused = false;
}
PrepAction::EngineEnded => {}
PrepAction::NeedEngine => self
.engine_offer
.ask(crate::engine_offer::Pending::OpeningErrors, &self.settings),
PrepAction::EngineSwitch | PrepAction::SettingsChanged => self.settings_dirty = true,
PrepAction::OpenEngines => {
self.settings_ui.open = true;
self.settings_ui.tab = Tab::Engines;
}
PrepAction::Toast(m) => self.toast(ctx, m),
PrepAction::CopyText(text, msg) => {
ctx.copy_text(text);
self.toast(ctx, msg);
}
PrepAction::OpenPgn(text) => {
let title = self.prep.as_ref().map(|p| p.title());
self.open_pgn_text(ctx, text, true);
if let Some(g) = self.game.as_mut() {
g.previous = title;
g.previous_prep = true;
}
}
PrepAction::FindPosition(path, start, line, flipped) => {
if let Some(p) = self.prep.as_mut() {
p.shown = false;
}
self.library.show_position(&path, start, line, flipped, ctx);
}
PrepAction::PlayFrom(from) => self.play_new(ctx, PlayNext::Dialog(Some(from))),
}
}
}
/// A message said once and seldom (a database made for the player): longer in view.
fn toast_for(&mut self, ctx: &egui::Context, msg: impl Into<String>, secs: f64) {
self.toast = Some(Toast {
@ -2351,6 +2507,9 @@ impl App {
return;
}
self.previous_games.clear();
if let Some(p) = self.prep.as_mut() {
p.shown = false;
}
if let Some(g) = closed
&& let Some(src) = g.source
{
@ -2401,6 +2560,13 @@ impl App {
fn toggle_engine(&mut self, ctx: &egui::Context) {
self.live_paused = false;
if self.prep.as_ref().is_some_and(|p| p.running()) && !self.analysis.is_on() {
self.toast(
ctx,
tr("Opening errors are being searched — wait or stop it in the report"),
);
return;
}
if self.analysis.is_on() {
self.analysis.stop();
return;
@ -2454,6 +2620,13 @@ impl App {
}
}
}
Some(crate::engine_offer::Pending::OpeningErrors) => {
let actions = match self.prep.as_mut() {
Some(p) => p.start_after_engine(&self.settings, ctx),
None => Vec::new(),
};
self.prep_actions(ctx, actions);
}
None => {}
}
}
@ -2723,27 +2896,18 @@ impl eframe::App for App {
// A new game's target base that left the shelf or stopped taking games is
// dropped before the game is drawn (its header names the target).
let _ = self.current_target();
let shelf = self.shelf_dbs();
if let Some(game) = &mut self.game {
let input_enabled = self.confirm_close.is_none();
// A database opened for the reference tab arrives here (the library is
// not drawn while a game is shown).
self.library.poll();
self.reference.dbs = self
.settings
.databases
.iter()
.filter(|p| self.library.files.exists(p))
.map(|p| crate::reference::RefDb {
path: p.clone(),
name: p
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default(),
db: self.library.database(p),
failed: self.library.failure(p).map(str::to_owned),
bytes: self.library.file_size(p),
})
.collect();
self.reference.dbs = shelf;
// The preparation's engine goes on under the game; no game analysis meanwhile.
game.engine_busy = self.prep.as_ref().is_some_and(|p| p.running());
if let Some(p) = self.prep.as_mut() {
p.poll_quietly(&ctx, &self.settings);
}
let review = self.settings.review.clone();
let actions = game.show(
ui,
@ -2794,7 +2958,9 @@ impl eframe::App for App {
}
GameAction::OpenUpdate => self.update_ui.open = true,
GameAction::ReturnToPrevious => {
if !self.previous_games.is_empty() {
if !self.previous_games.is_empty()
|| self.prep.as_ref().is_some_and(|p| p.shown)
{
self.request_close(&ctx, CloseIntent::ReturnToPrevious);
}
}
@ -2923,8 +3089,37 @@ impl eframe::App for App {
}
}
}
} else if self.prep.as_ref().is_some_and(|p| p.shown) {
// A database opened for the book arrives here (the library is not drawn).
self.library.poll();
let actions = match self.prep.as_mut() {
Some(p) => {
p.dbs = shelf;
p.show(ui, &mut self.settings)
}
None => Vec::new(),
};
self.prep_actions(&ctx, actions);
} else {
let dbs = self.settings.databases.clone();
if let Some(p) = self.prep.as_mut() {
p.poll_quietly(&ctx, &self.settings);
}
// Ctrl+Shift+P: «Prepare against…» with the player of the filter.
if ctx.input_mut(|i| {
i.consume_shortcut(&KeyboardShortcut::new(
Modifiers::COMMAND | Modifiers::SHIFT,
Key::P,
))
}) && self.prep_dialog.is_none()
&& let Some((path, entry)) = self.library.prep_entry()
{
self.prep_dialog = Some(PrepDialog::new(
path,
entry.unwrap_or_default(),
&self.settings,
));
}
self.online_probe.poll();
self.library.online = self.online_probe.any();
self.library.online_busy = self.online.busy();
@ -2992,6 +3187,9 @@ impl eframe::App for App {
self.open_game(&ctx, path, index, None);
self.edit_game_data();
}
LibraryAction::PrepareAgainst { path, entry } => {
self.prep_dialog = Some(PrepDialog::new(path, entry, &self.settings));
}
}
}
}
@ -3132,6 +3330,7 @@ impl eframe::App for App {
self.confirm_dialog(&ctx);
self.own_dialogs(&ctx);
self.prep_dialog(&ctx);
// Whether the database the dialog names is there, as last found.
if let Some(d) = self.play_dialog.as_mut() {
d.target_there = d
@ -3227,6 +3426,9 @@ impl eframe::App for App {
fn on_exit(&mut self) {
self.analysis.stop();
if let Some(p) = self.prep.as_mut() {
p.save();
}
// Downloads of online games stop and save what they got; a new database goes on
// the shelf with it (the next download continues it).
for p in self.online.stop_all() {

View file

@ -19,6 +19,8 @@ pub const DOWNLOAD_INDICATOR: &str = "download_indicator";
pub enum Pending {
LiveAnalysis,
GameAnalysis,
/// The opponent preparation's search for opening errors.
OpeningErrors,
}
/// What the owner should do.
@ -129,6 +131,9 @@ impl EngineOffer {
Some(Pending::LiveAnalysis) => {
tr("Stockfish installed — analysis is on")
}
Some(Pending::OpeningErrors) => {
tr("Stockfish installed — the search for opening errors started")
}
None => tr("Stockfish installed"),
}
.to_string(),
@ -328,6 +333,9 @@ impl EngineOffer {
Some(Pending::GameAnalysis) => {
tr("Game analysis will start by itself when the download finishes.")
}
Some(Pending::OpeningErrors) => {
tr("The search for opening errors will start by itself when the download finishes.")
}
_ => tr("Analysis will start by itself when the download finishes."),
};
ui.label(RichText::new(after).weak());

View file

@ -95,6 +95,11 @@ pub struct GameView {
side_tab: SideTab,
/// The game this one was opened from (reference tab): the title for "← back to".
pub previous: Option<String>,
/// The game was opened from the opponent preparation: «⬅ Back to preparation».
pub previous_prep: bool,
/// The engine is busy with the opponent preparation: no game analysis meanwhile
/// (one engine job for the whole program, opponent-prep.md §4.3).
pub engine_busy: bool,
/// The game's data were asked once (on its first add); not again.
pub data_asked: bool,
/// A newer version to offer (its number), next to Settings.
@ -204,6 +209,8 @@ impl GameView {
SideTab::Notation
},
previous: None,
previous_prep: false,
engine_busy: false,
data_asked: false,
target: None,
update: None,
@ -776,7 +783,11 @@ impl GameView {
// «Analyse»: at once with the options chosen before, else the dialog first.
if std::mem::take(&mut self.review_asked) {
if settings.review.chosen {
if self.engine_busy {
actions.push(GameAction::Toast(
tr("Opening errors are being searched — wait or stop it in the report").to_owned(),
));
} else if settings.review.chosen {
self.start_review(settings, true, ui.ctx(), &mut actions);
} else {
self.review.dialog_open = true;
@ -889,10 +900,13 @@ impl GameView {
"Report: show or hide the evaluation graph and the report (Shift+A)",
));
} else if ui
.button(big("📈"))
.add_enabled(!self.engine_busy, egui::Button::new(big("📈")))
.on_hover_text(tr(
"Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)",
))
.on_disabled_hover_text(tr(
"Opening errors are being searched — wait or stop it in the report",
))
.clicked()
{
self.review_asked = true;
@ -935,10 +949,13 @@ impl GameView {
RichText::new(format!("ℹ {}", self.diagnostics.len())).weak()
}
});
let back_to = self
.previous
.as_ref()
.map(|t| trf("⬅ Back to {game}", &[("game", t)]));
let back_to = self.previous.as_ref().map(|t| {
if self.previous_prep {
tr("⬅ Back to preparation").to_owned()
} else {
trf("⬅ Back to {game}", &[("game", t)])
}
});
// The buttons are measured first: the title gets what they leave (shortened with
// "…"; the result always shows). When it would get under 160 pt, the buttons
// around it give up their words for their icons (the words go to the tooltips).
@ -2125,6 +2142,19 @@ impl GameView {
Some((start, line, self.flipped))
}
/// The cursor on move `ply` of the main line (0: the start; past the end: the
/// last move).
pub fn goto_ply(&mut self, ply: usize) {
let mut at = self.game.root();
for _ in 0..ply {
match self.game.main_child(at) {
Some(n) => at = n,
None => break,
}
}
self.goto(at);
}
pub fn debug_advance(&mut self, plies: usize) {
for _ in 0..plies {
match self.game.main_child(self.cursor) {

File diff suppressed because it is too large Load diff

View file

@ -22,6 +22,7 @@ use shakmaty::uci::UciMove;
use crate::board_search::{self, Background, BoardEvent, SearchBoard};
use crate::i18n::{tr, trf};
use crate::library::LibraryAction;
use crate::prep_ui::PrepEntry;
use crate::settings::Settings;
use crate::viewed::{self, Viewed};
@ -335,6 +336,9 @@ pub struct LargeView {
drawer_top: f32,
/// The quick search has the keyboard (arrows and Enter go to the table).
search_focused: bool,
/// «Prepare against…» was asked (the panel's button, a row's menu): the library
/// takes it (docs/design/opponent-prep.md §2.1).
pub prepare: Option<PrepEntry>,
}
impl LargeView {
@ -419,6 +423,7 @@ impl LargeView {
drawer_open: drawer,
drawer_asked: false,
drawer_top: 0.0,
prepare: None,
}
}
@ -1297,9 +1302,36 @@ impl LargeView {
.response
.on_disabled_hover_text(tr("Enter a player first"));
});
// Preparing against the player: with the name picked from the list, else the
// dialog offers the names that match the text (opponent-prep.md §2.1).
if player_set {
let label = match self.form.player.exact {
Some(_) => trf("♟ Prepare against {name}…", &[("name", &self.form.player.text)]),
None => tr("♟ Prepare against an opponent…").to_owned(),
};
if ui
.add(egui::Button::new(label).truncate())
.on_hover_text(tr(
"The player's openings by colour, with names, and the opening errors the engine finds (Ctrl+Shift+P)",
))
.clicked()
{
self.prepare = self.prep_entry();
}
}
self.name_field(ui, db, NameField::Opponent, tr("Opponent"));
}
/// «Prepare against…» for the player of the filter: the name picked from the list
/// (or the text typed) and the colour of the filter.
pub fn prep_entry(&self) -> Option<PrepEntry> {
self.form.player.is_set().then(|| PrepEntry {
query: self.form.player.text.trim().to_owned(),
exact: self.form.player.exact,
side: self.form.side,
})
}
fn event_group(&mut self, ui: &mut Ui, db: &Arc<Database>) {
let count = usize::from(self.form.event.is_set())
+ usize::from(!self.form.annotator.trim().is_empty());
@ -2216,6 +2248,25 @@ impl LargeView {
opened = Some(index);
ui.close();
}
// One item per player of the game (the same name once).
let mut players: Vec<&str> = vec![r.white.as_str(), r.black.as_str()];
players.dedup();
for name in players {
if name.trim().is_empty() || name == "?" {
continue;
}
if ui
.button(trf("♟ Prepare against {name}…", &[("name", &name)]))
.clicked()
{
self.prepare = Some(PrepEntry {
query: name.to_owned(),
exact: None,
side: Side::Any,
});
ui.close();
}
}
if ui.button(tr("Game data… (F2)")).clicked() {
actions.push(LibraryAction::EditGameData { path: path.to_path_buf(), index });
ui.close();

View file

@ -73,6 +73,11 @@ pub enum LibraryAction {
path: PathBuf,
index: usize,
},
/// «Prepare against…» for a player of this database (opponent-prep.md §2).
PrepareAgainst {
path: PathBuf,
entry: crate::prep_ui::PrepEntry,
},
}
/// How a database was imported, and what is worth knowing about it.
@ -630,10 +635,26 @@ impl Library {
{
ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
}
if let Some(path) = self.selected_db.clone()
&& let Some(view) = self.large.get_mut(&path)
&& let Some(entry) = view.prepare.take()
{
actions.push(LibraryAction::PrepareAgainst { path, entry });
}
self.notes_window(ui.ctx());
actions
}
/// Ctrl+Shift+P: the chosen database (when it is read) and the player of its
/// filter, if one is set.
pub fn prep_entry(&self) -> Option<(PathBuf, Option<crate::prep_ui::PrepEntry>)> {
let path = self.selected_db.clone()?;
if !matches!(self.slots.get(&path), Some(Slot::Ready(_))) {
return None;
}
Some((path.clone(), self.large.get(&path).and_then(|v| v.prep_entry())))
}
fn notes_window(&mut self, ctx: &egui::Context) {
let Some(path) = self.notes_open.clone() else {
return;

View file

@ -26,6 +26,7 @@ mod online_ui;
mod own_db;
mod play;
mod player_games;
mod prep_ui;
mod reference;
mod review;
mod rodent4_download;

4288
apps/desktop/src/prep_ui.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -719,79 +719,26 @@ impl Review {
.weak(),
);
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.label(tr("Engine"));
let current = settings
.active_engine()
.map(|e| e.name.clone())
.unwrap_or_else(|| tr("not selected").into());
egui::ComboBox::from_id_salt("review_engine")
.selected_text(current)
.width(ui.available_width() - 8.0)
.show_ui(ui, |ui| {
for i in 0..settings.engines.len() {
let selected = settings.active_engine == Some(i);
if ui
.selectable_label(selected, &settings.engines[i].name)
.clicked()
&& !selected
{
settings.active_engine = Some(i);
action = Some(DialogAction::EngineSwitch);
}
}
ui.separator();
if ui.button(tr("Add or edit engines…")).clicked() {
action = Some(DialogAction::OpenEngines);
}
});
});
if let Some(a) = engine_picker(ui, settings, "review_engine") {
action = Some(a);
}
ui.add_space(4.0);
let rs = &mut settings.review;
let cores = std::thread::available_parallelism()
.map(|n| n.get() as u32)
.unwrap_or(1);
let hash_steps = crate::game_view::hash_steps();
ui.spacing_mut().slider_width = 200.0;
egui::Grid::new("review_grid")
.num_columns(3)
.spacing(vec2(12.0, 8.0))
.show(ui, |ui| {
ui.label(tr("Quality"));
let mut q = rs.quality.min(REVIEW_QUALITY.len() - 1);
crate::game_view::index_slider(ui, &mut q, REVIEW_QUALITY.len());
rs.quality = q;
ui.label(trf(
"{quality} · {nodes} nodes",
&[
("quality", &tr(REVIEW_QUALITY[q].0)),
("nodes", &format_count(REVIEW_QUALITY[q].1)),
],
));
ui.end_row();
ui.label(tr("Threads"));
let mut th = rs.threads.clamp(1, cores) as usize - 1;
crate::game_view::index_slider(ui, &mut th, cores as usize);
rs.threads = th as u32 + 1;
ui.label(format!("{} / {cores}", rs.threads));
ui.end_row();
ui.label(tr("Memory"));
let mut h = hash_steps
.iter()
.position(|m| *m >= rs.hash_mb)
.unwrap_or(hash_steps.len() - 1);
crate::game_view::index_slider(ui, &mut h, hash_steps.len());
rs.hash_mb = hash_steps[h];
ui.label(crate::game_view::format_mb(rs.hash_mb));
ui.end_row();
});
let mut quality = rs.quality;
options_grid(
ui,
"review_grid",
&mut quality,
&mut rs.threads,
&mut rs.hash_mb,
None,
);
rs.quality = quality;
ui.add_space(6.0);
let positions = self.analysis.positions();
let per_thread = self.nps_per_thread.unwrap_or(700_000.0);
let per_thread = self.nps_per_thread.unwrap_or(DEFAULT_NPS);
let searches = self.analysis.searches();
let secs = searches as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads));
let secs = estimate_secs(searches, rs.nodes(), per_thread, rs.threads);
ui.label(trf(
"{n} positions, about {time}",
&[("n", &positions), ("time", &format_duration(secs))],
@ -841,6 +788,102 @@ impl Drop for Review {
}
}
/// Nodes per second and thread assumed until an engine was measured.
pub const DEFAULT_NPS: f64 = 700_000.0;
/// Seconds `searches` of `nodes` take at `per_thread` nodes per second on `threads`.
pub fn estimate_secs(searches: usize, nodes: u64, per_thread: f64, threads: u32) -> f64 {
searches as f64 * nodes as f64 / (per_thread * f64::from(threads.max(1)))
}
/// The «Engine» row of a launch dialog: the active engine, the others to switch to,
/// «Add or edit engines…».
pub fn engine_picker(ui: &mut Ui, settings: &mut Settings, id: &str) -> Option<DialogAction> {
let mut action = None;
ui.horizontal(|ui| {
ui.label(tr("Engine"));
let current = settings
.active_engine()
.map(|e| e.name.clone())
.unwrap_or_else(|| tr("not selected").into());
egui::ComboBox::from_id_salt(id)
.selected_text(current)
.width(ui.available_width() - 8.0)
.show_ui(ui, |ui| {
for i in 0..settings.engines.len() {
let selected = settings.active_engine == Some(i);
if ui
.selectable_label(selected, &settings.engines[i].name)
.clicked()
&& !selected
{
settings.active_engine = Some(i);
action = Some(DialogAction::EngineSwitch);
}
}
ui.separator();
if ui.button(tr("Add or edit engines…")).clicked() {
action = Some(DialogAction::OpenEngines);
}
});
});
action
}
/// The «Quality · Threads · Memory» grid of a launch dialog; `quality` indexes
/// [`REVIEW_QUALITY`]. `quality_hint`: a tooltip on the quality slider.
pub fn options_grid(
ui: &mut Ui,
id: &str,
quality: &mut usize,
threads: &mut u32,
hash_mb: &mut u32,
quality_hint: Option<&str>,
) {
let cores = std::thread::available_parallelism()
.map(|n| n.get() as u32)
.unwrap_or(1);
let hash_steps = crate::game_view::hash_steps();
ui.spacing_mut().slider_width = 200.0;
egui::Grid::new(id)
.num_columns(3)
.spacing(vec2(12.0, 8.0))
.show(ui, |ui| {
ui.label(tr("Quality"));
let mut q = (*quality).min(REVIEW_QUALITY.len() - 1);
crate::game_view::index_slider(ui, &mut q, REVIEW_QUALITY.len());
*quality = q;
let label = ui.label(trf(
"{quality} · {nodes} nodes",
&[
("quality", &tr(REVIEW_QUALITY[q].0)),
("nodes", &format_count(REVIEW_QUALITY[q].1)),
],
));
if let Some(hint) = quality_hint {
label.on_hover_text(hint);
}
ui.end_row();
ui.label(tr("Threads"));
let mut th = (*threads).clamp(1, cores) as usize - 1;
crate::game_view::index_slider(ui, &mut th, cores as usize);
*threads = th as u32 + 1;
ui.label(format!("{} / {cores}", *threads));
ui.end_row();
ui.label(tr("Memory"));
let mut h = hash_steps
.iter()
.position(|m| *m >= *hash_mb)
.unwrap_or(hash_steps.len() - 1);
crate::game_view::index_slider(ui, &mut h, hash_steps.len());
*hash_mb = hash_steps[h];
ui.label(crate::game_view::format_mb(*hash_mb));
ui.end_row();
});
}
/// Removes `[%eval …]` commands from a comment.
fn strip_eval(c: &str) -> String {
let mut out = String::new();
@ -929,7 +972,7 @@ fn percent(a: f64) -> String {
}
/// 250 000 → "250k", 1 000 000 → "1M".
fn format_count(n: u64) -> String {
pub fn format_count(n: u64) -> String {
if n >= 1_000_000 && n.is_multiple_of(100_000) {
let m = n as f64 / 1e6;
if n.is_multiple_of(1_000_000) {
@ -944,7 +987,7 @@ fn format_count(n: u64) -> String {
}
}
fn format_duration(secs: f64) -> String {
pub fn format_duration(secs: f64) -> String {
let s = secs.ceil().max(1.0) as u64;
if s < 60 {
trf("{n} s", &[("n", &s)])

View file

@ -149,6 +149,42 @@ pub struct Settings {
pub record_games: bool,
/// Who played on this computer, the last first (`player_games.rs`).
pub players: Vec<crate::player_games::Player>,
/// Preparing against an opponent (docs/design/opponent-prep.md).
pub prep: PrepSettings,
}
/// Options of the opponent preparation; threads and memory are the game analysis's.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrepSettings {
/// Index into [`REVIEW_QUALITY`]; «Fast» is enough for opening errors.
pub quality: usize,
/// The book (`None`: the largest database on the shelf; `Some("")`: no book).
pub book: Option<PathBuf>,
/// Plies of the opening the report looks at.
pub plies: usize,
/// Moves with fewer games fold into «other moves».
pub branches_from: u32,
/// The engine was started from the dialog once: the button starts it at once.
pub chosen: bool,
}
impl Default for PrepSettings {
fn default() -> Self {
Self {
quality: 0,
book: None,
plies: 20,
branches_from: 3,
chosen: false,
}
}
}
impl PrepSettings {
pub fn nodes(&self) -> u64 {
REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1
}
}
/// Options of the whole-game analysis (the engine is the active one).
@ -233,6 +269,7 @@ impl Default for Settings {
players: Vec::new(),
rating: None,
play: Default::default(),
prep: PrepSettings::default(),
}
}
}

View file

@ -38,15 +38,16 @@ impl Default for BookOptions {
}
/// Fills in [`GameInfo::book`] of every game; `progress` counts the games done.
/// Returns how many games left the book within their line. `None` when cancelled
/// (or when the book cannot be searched: a PGN book without memory for its table).
/// Returns how many games left the book within their line, and the book's count of
/// every position looked at (by key). `None` when cancelled (or when the book cannot
/// be searched: a PGN book without memory for its table).
pub(crate) fn find_exits(
games: &mut [GameInfo],
book: &Database,
options: &BookOptions,
progress: &AtomicUsize,
cancel: &AtomicBool,
) -> Option<u32> {
) -> Option<(u32, HashMap<u64, u32>)> {
let exclude: HashSet<u32> = if options.same_database {
games.iter().map(|g| g.index).collect()
} else {
@ -98,5 +99,5 @@ pub(crate) fn find_exits(
}
});
}
Some(left)
Some((left, counts))
}

View file

@ -138,7 +138,7 @@ pub struct BookInfo {
pub left: u32,
}
const REPORT_VERSION: u32 = 1;
const REPORT_VERSION: u32 = 2;
/// Everything the preparation knows about the player.
#[derive(Clone, Debug, Serialize, Deserialize)]
@ -160,6 +160,10 @@ pub struct PrepReport {
pub white: ColorReport,
pub black: ColorReport,
pub book: Option<BookInfo>,
/// The book's number of games in every position the book step looked at (by
/// key): the first plies of every line, then the positions around each exit.
#[serde(default)]
pub book_counts: HashMap<u64, u32>,
pub engine: Option<EngineInfo>,
/// Engine evaluations by position key.
pub evals: HashMap<u64, PositionEval>,
@ -263,6 +267,7 @@ pub fn build(
white,
black,
book: None,
book_counts: HashMap::new(),
engine: None,
evals,
};
@ -356,13 +361,14 @@ impl PrepReport {
cancel: &AtomicBool,
) -> Option<()> {
let mut games = self.games.clone();
let left = book::find_exits(&mut games, book, options, progress, cancel)?;
let (left, counts) = book::find_exits(&mut games, book, options, progress, cancel)?;
self.games = games;
self.book = Some(BookInfo {
fingerprint: fingerprint(book),
threshold: options.threshold,
left,
});
self.book_counts = counts;
Some(())
}
@ -371,9 +377,17 @@ impl PrepReport {
/// Every distinct position of the lines (the one after the last move included),
/// first met first; those without legal moves left out.
fn positions(&self) -> Vec<(u64, &GameInfo, usize)> {
self.positions_for(Side::Any)
}
/// [`PrepReport::positions`] of the games the player had `side` in.
fn positions_for(&self, side: Side) -> Vec<(u64, &GameInfo, usize)> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for g in &self.games {
if (side == Side::White && !g.white) || (side == Side::Black && g.white) {
continue;
}
for (i, &k) in g.keys.iter().enumerate() {
if self.evals.get(&k).is_some_and(|e| e.nodes == EXACT) {
continue;
@ -391,9 +405,19 @@ impl PrepReport {
self.positions().len()
}
/// Distinct positions of the games the player had `side` in.
pub fn distinct_positions_for(&self, side: Side) -> usize {
self.positions_for(side).len()
}
/// Positions without an evaluation of at least `nodes`.
pub fn missing(&self, nodes: u64) -> usize {
self.positions()
self.missing_for(nodes, Side::Any)
}
/// [`PrepReport::missing`] among the games the player had `side` in.
pub fn missing_for(&self, nodes: u64, side: Side) -> usize {
self.positions_for(side)
.iter()
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
.count()
@ -423,7 +447,13 @@ impl PrepReport {
/// search each, no second search for !! and !). Their keys are the position keys
/// in hexadecimal, as [`PrepReport::apply`] reads them.
pub fn targets(&self, nodes: u64) -> Vec<Target> {
self.positions()
self.targets_for(nodes, Side::Any)
}
/// [`PrepReport::targets`] of the games the player had `side` in (the dialog's
/// «Black — 133 games» halves the work).
pub fn targets_for(&self, nodes: u64, side: Side) -> Vec<Target> {
self.positions_for(side)
.into_iter()
.filter(|(k, _, _)| !self.evals.get(k).is_some_and(|e| e.nodes >= nodes))
.map(|(k, g, i)| Target {
@ -794,6 +824,12 @@ mod tests {
assert_eq!(exits[3].map(|b| (b.ply, b.by_player)), Some((1, true)), "1.d4 is his own");
assert_eq!(report.book.as_ref().map(|b| (b.threshold, b.left)), Some((2, 4)));
assert_eq!(report.white.book_exits(&report.games), (1, 2));
// The counts of the positions looked at: the start (4 games), 1.e4 c5 2.Nf3
// (3), the rare 3...g6 (1).
let g = &report.games[0];
assert_eq!(report.book_counts.get(&g.keys[0]), Some(&4));
assert_eq!(report.book_counts.get(&g.keys[3]), Some(&3));
assert_eq!(report.book_counts.get(&g.keys[6]), Some(&1));
// The player's own games excluded: everything is out of the book at once.
let own = BookOptions {
threshold: 1,
@ -820,6 +856,12 @@ mod tests {
assert_eq!(total, 27 - 10);
let targets = report.targets(1000);
assert_eq!(targets.len(), total);
// One colour: the positions of its games only (the start position is in both).
let black = report.targets_for(1000, Side::Black);
assert_eq!(black.len(), report.games[1].keys.len());
assert_eq!(report.distinct_positions_for(Side::Black), black.len());
assert!(report.distinct_positions_for(Side::White) < total);
assert_eq!(report.missing_for(1000, Side::Black), black.len());
assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0]));
assert!(targets[0].pos.moves.is_empty());
assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]);

File diff suppressed because one or more lines are too long