From 131a55027e993b148275c52943c42957f0f2844e Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:26:47 -0800 Subject: [PATCH 1/4] feat(gpu): expose adapter metadata before runtime startup --- crates/leonida-gpu/src/adapter.rs | 52 ++++++++++++++++++++++++ crates/leonida-gpu/src/lib.rs | 1 + crates/leonida-hle/src/modules/d3d12x.rs | 7 ++++ 3 files changed, 60 insertions(+) create mode 100644 crates/leonida-gpu/src/adapter.rs diff --git a/crates/leonida-gpu/src/adapter.rs b/crates/leonida-gpu/src/adapter.rs new file mode 100644 index 000000000..98b14f9b2 --- /dev/null +++ b/crates/leonida-gpu/src/adapter.rs @@ -0,0 +1,52 @@ +//! Adapter metadata for startup settings, before any GPU switches are cached. + +#[derive(Debug, Clone)] +pub struct Description { + pub name: String, + pub vendor_id: u32, + pub vram_mb: u64, +} + +/// Describes the adapter that `host::create` will use, without making the host +/// device or starting its workers. A failed probe leaves automatic settings +/// limited to profiles that do not require a particular card. +#[cfg(windows)] +pub fn describe() -> Result { + use windows::Win32::Graphics::Dxgi::*; + use windows::core::Interface; + + // RenderDoc must hook DXGI before the first graphics interface is created. + // Profiles cannot change its startup variables or the WARP selection. + #[cfg(feature = "diagnostics")] + crate::renderdoc::load(); + + let probe = || -> windows::core::Result { + // SAFETY: DXGI queries own their returned interfaces; no title pointers + // or D3D12 device state are accessed. + unsafe { + let adapter: IDXGIAdapter1 = if cfg!(feature = "diagnostics") + && std::env::var_os("LEONIDA_D3D12_WARP").is_some_and(|v| v == "1") + { + crate::host::warp_adapter()?.cast()? + } else { + let factory: IDXGIFactory1 = CreateDXGIFactory1()?; + // D3D12CreateDevice(None), used by the host, selects this first + // adapter, not necessarily the one with the most memory. + factory.EnumAdapters(0)?.cast()? + }; + let desc = adapter.GetDesc1()?; + let end = desc.Description.iter().position(|&c| c == 0).unwrap_or(128); + Ok(Description { + name: String::from_utf16_lossy(&desc.Description[..end]), + vendor_id: desc.VendorId, + vram_mb: (desc.DedicatedVideoMemory as u64) >> 20, + }) + } + }; + probe().map_err(|error| error.to_string()) +} + +#[cfg(not(windows))] +pub fn describe() -> Result { + Err("Direct3D adapter discovery requires Windows or Wine".into()) +} diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs index 9c60f4bd8..e09a219dc 100644 --- a/crates/leonida-gpu/src/lib.rs +++ b/crates/leonida-gpu/src/lib.rs @@ -15,6 +15,7 @@ //! share, [`console`] which console model the title sees. Planned: //! `present` (swap chain). +pub mod adapter; #[cfg(all(windows, feature = "diagnostics"))] mod capture; #[cfg(windows)] diff --git a/crates/leonida-hle/src/modules/d3d12x.rs b/crates/leonida-hle/src/modules/d3d12x.rs index f934cc6c8..7b820115d 100644 --- a/crates/leonida-hle/src/modules/d3d12x.rs +++ b/crates/leonida-hle/src/modules/d3d12x.rs @@ -49,6 +49,13 @@ pub fn warm_shader(container: &[u8]) -> Result { } } +pub use leonida_gpu::adapter::Description as GraphicsAdapter; + +/// Describes the default graphics adapter without starting the GPU runtime. +pub fn graphics_adapter() -> Result { + leonida_gpu::adapter::describe() +} + /// See `leonida_gpu::probe_translation_host`. pub fn probe_translation_host() -> bool { #[cfg(windows)] From 3d18f44a6f395248038986b0359f8078f8fa14b2 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:34:58 -0800 Subject: [PATCH 2/4] feat(config): apply native graphics profiles and TOML overrides --- CLAUDE.md | 3 +- Cargo.lock | 28 + Cargo.toml | 1 + README.md | 47 +- TODO.md | 1 - apps/leonida/Cargo.toml | 4 + apps/leonida/src/graphics.rs | 126 +++ apps/leonida/src/main.rs | 12 +- apps/leonida/src/run.rs | 1 + apps/leonida/tests/graphics.rs | 481 +++++++++++ crates/leonida-core/Cargo.toml | 1 + crates/leonida-core/src/config.rs | 35 +- crates/leonida-core/src/graphics.rs | 959 ++++++++++++++++++++++ crates/leonida-core/src/lib.rs | 1 + crates/leonida-gpu/src/adapter.rs | 47 +- crates/leonida-gpu/src/descriptor/host.rs | 12 +- crates/leonida-gpu/src/host.rs | 2 +- docs/fork-notes.md | 33 + gpu-profiles.json | 12 +- leonida.example.toml | 23 + measure-gta6.ps1 | 30 +- run-gta6.ps1 | 11 +- scripts/leonida-settings.ps1 | 195 +++-- scripts/measure-run.ps1 | 17 +- scripts/test-graphics-settings.ps1 | 189 +++++ scripts/test-report.ps1 | 26 +- shot-run.ps1 | 9 +- 27 files changed, 2176 insertions(+), 130 deletions(-) create mode 100644 apps/leonida/src/graphics.rs create mode 100644 apps/leonida/tests/graphics.rs create mode 100644 crates/leonida-core/src/graphics.rs create mode 100644 scripts/test-graphics-settings.ps1 diff --git a/CLAUDE.md b/CLAUDE.md index ebe5fe8de..d07c243bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,7 +68,8 @@ It is a fork of [fxceless/victory-gta6](https://github.com/fxceless/victory-gta6 | `scripts/rename-from-upstream.ps1` | renames code taken from upstream (`victory` to `leonida`) | | `run-gta6.ps1` | builds and starts the game with the frame-rate switches for this PC's graphics card | | `measure-gta6.ps1`, `start-measure.cmd` | the same with the diagnostics build and logs; a double-click start for testers | -| `gpu-profiles.json`, `scripts/leonida-settings.ps1` | the run scripts' switches by graphics card, and the loader that applies them | +| `gpu-profiles.json`, `leonida-core::graphics` | measured profiles embedded in the executable, and native settings resolution | +| `scripts/leonida-settings.ps1` | launcher queries and reports for the native graphics settings | | `scripts/measure-run.ps1`, `scripts/make-view.ps1` | one unattended diagnostics run with frame shots and a summary of its figures; small JPEG copies of shots | | `docs/` | architecture, asset policy, ray tracing, the fork's measurement log | | `.claude/skills/` | agent skills, copied in `.agents/skills/` for other agents; [AGENTS.md](AGENTS.md) lists them. Edit both copies | diff --git a/Cargo.lock b/Cargo.lock index 6fcafa5a9..3702a42f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -236,6 +236,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + [[package]] name = "lazy_static" version = "1.5.1" @@ -256,6 +262,8 @@ dependencies = [ "leonida-pe", "leonida-shader", "memchr", + "serde_json", + "tempfile", "walkdir", ] @@ -265,6 +273,7 @@ version = "0.1.0" dependencies = [ "anyhow", "serde", + "serde_json", "tempfile", "thiserror", "toml", @@ -527,6 +536,19 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "serde_spanned" version = "1.1.3" @@ -903,3 +925,9 @@ name = "zlib-rs" version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index f9e51e05c..a28ab9567 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ clap = { version = "4.6.9", features = ["derive"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0" toml = "1.2.2" object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } windows-sys = "0.61.2" diff --git a/README.md b/README.md index 6d3d95ce7..e47e74fc0 100644 --- a/README.md +++ b/README.md @@ -45,13 +45,13 @@ It is a fork of [victory-gta6](https://github.com/fxceless/victory-gta6), itself **Made for everyone's PC, not just ours.** Many projects like this are tuned on the developer's own machine and nowhere else. Leonida Legacy aims to run as well as it can on your hardware, and to be usable by people who can't -code and don't have an AI assistant to help them. The run scripts pick their settings for your graphics card +code and don't have an AI assistant to help them. The program picks its settings for your graphics card (`gpu-profiles.json`), so a change that helps one card is not forced on everyone. If it runs badly on your PC, tell us your CPU, GPU, driver version and frame rate (see [Contact](#contact)); that is how new cards get a profile. ## Status -**Not playable yet: 2 to 4 frames per second by default, and shadowed areas are black.** Tested on Windows 11 Pro, +**Not playable yet: frame rates are low, and shadowed areas are black.** Tested on Windows 11 Pro, AMD Ryzen 7 7800X3D, NVIDIA RTX 3080 12 GB, 32 GB RAM, Series X profile. The world frame rates below were measured by victory-gta6 on an RTX 4070 and have not been measured again on this machine yet. @@ -62,7 +62,7 @@ by victory-gta6 on an RTX 4070 and have not been measured again on this machine | Saves | the game autosaves a checkpoint and loads it again | | First gameplay scene | renders characters, textures, sky and the sunlit exterior; HUD, pause menu and pad input work | | Light in shadow | missing: ray-traced bounce light and shadows don't run yet, so anything out of direct sun is black | -| Frame rate in the world | 2-4 fps by default; about 10 fps in the first rooms with the newer switches, all off by default | +| Frame rate in the world | Earlier measurements: 2-4 fps without the newer switches, about 10 fps in the first rooms with them; the measured base profile now applies to direct launches too | Known problems: @@ -91,9 +91,9 @@ The first run asks for the folder of your copy of the game (the one with `Micros `leonida.toml`, which git ignores. `leonida config` shows what is set, and `leonida.example.toml` lists the other settings. -`run-gta6.ps1` does the build and the run in one step, with the frame-rate switches measured for your graphics card -(`gpu-profiles.json`; they are off by default in the program). It asks for the game folder too, and whether to -remember it: +`run-gta6.ps1` does the build and the run in one step. The program itself selects the frame-rate settings from +`gpu-profiles.json`, including when launched directly through Wine. It asks for the game folder too, and whether +to remember it: ```powershell powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 @@ -101,7 +101,37 @@ powershell -ExecutionPolicy Bypass -File .\run-gta6.ps1 `measure-gta6.ps1` does the same with the diagnostics build, the frame log and the card meter on, and saves everything the game prints to `%LOCALAPPDATA%\leonida\logs`. `-SpeedSwitches off` runs it without the frame-rate -switches, for a comparison in the same place. +switches or your graphics overrides, for a comparison in the same place. + +### Graphics settings + +The measured base profile is automatic. Experimental profiles such as `card-windows` remain opt-in. +To change a setting, add a `[graphics]` section to your `leonida.toml`; the example file lists every option: + +```toml +[graphics] +async_submit = false +queue2 = 0 +``` + +Only the options you write change. To disable automatic profiles, use `profiles = ["none"]` (or `profiles = []`) +in that section. Other settings you explicitly write still apply. To choose profiles yourself, use a list such +as `profiles = ["base", "my-test"]`; named profiles include the base settings and apply in catalog order. + +Environment overrides take precedence over TOML settings, which take precedence over profiles. For example, +an explicit `LEONIDA_QUEUE2=0` still wins. `LEONIDA_PROFILE` overrides the profile list, except the existing +diagnostics value `1`, which enables the CPU sampler and leaves graphics selection to the config. Run +`leonida config --graphics` to see the selected adapter, profiles, effective values and their sources as JSON; +it needs no game files. The scripts use this same result and leave your environment overrides intact. + +The standard catalog is built into the executable. Put local profiles in `gpu-profiles.local.json` beside +your selected config file (the current folder when no config exists). They apply after the built-in catalog. +Profiles match the adapter used by Direct3D, including Wine's reported adapter identity. If discovery fails, +only profiles without card-specific conditions match. A local profile can cancel an earlier profile value +with `null`, but cannot override an explicit TOML or environment value. Game/cache/data paths, logging, RenderDoc startup +and WARP selection remain separate from graphics profiles. +GPU name patterns support case-insensitive `*`, `?`, `[abc]` and `[a-z]`; malformed patterns and unsupported +backtick escapes or negated character classes report an error. Unknown profile names also report an error. ### Testing for the project, with no programming experience @@ -146,7 +176,8 @@ An experimental optimization reduces GPU work before individual indirect draws. RTX 5090 benchmark by 19.4%; gameplay and other cards are unmeasured, so it stays off by default. [The measurements and limits are here](docs/fork-notes.md#newest-2026-11-26). -To compare it using your configured game, create `gpu-profiles.local.json` with the following content. If +To compare it using your configured game, create `gpu-profiles.local.json` beside your selected config file +(normally in the checkout) with the following content. If the file already exists, add only this profile object to its existing `profiles` array: ```json diff --git a/TODO.md b/TODO.md index 8cff12b9b..07b5b9662 100644 --- a/TODO.md +++ b/TODO.md @@ -64,7 +64,6 @@ The goal: a console-like experience on PC. The game starts straight into play, h |----|------|-------|-------| | U-1 | One step from download to playing: build, warm the cache (P-7) and run, with no terminal knowledge needed. | `run-gta6.ps1` | - | | U-2 | Fullscreen and borderless window, and a choice of output resolution. | `leonida-gpu` | GPU | -| U-3 | The frame-rate switches as settings in `leonida.toml` instead of environment variables, with the tested ones on by default. Since #24 the run scripts pick them by graphics card from `gpu-profiles.json`; this item moves that choice into the program itself. | `leonida-core` (config) | - | | U-4 | Pad first: after launch, the game is playable without touching the keyboard. | `leonida-hle` (input) | game | ## Code health diff --git a/apps/leonida/Cargo.toml b/apps/leonida/Cargo.toml index 1df33b728..75a5bf519 100644 --- a/apps/leonida/Cargo.toml +++ b/apps/leonida/Cargo.toml @@ -20,6 +20,10 @@ memchr.workspace = true clap.workspace = true walkdir.workspace = true +[dev-dependencies] +serde_json.workspace = true +tempfile.workspace = true + [features] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diff --git a/apps/leonida/src/graphics.rs b/apps/leonida/src/graphics.rs new file mode 100644 index 000000000..cf52bd320 --- /dev/null +++ b/apps/leonida/src/graphics.rs @@ -0,0 +1,126 @@ +//! Resolve graphics settings before the runtime caches any switches. + +use anyhow::Result; +use leonida_core::Config; +use leonida_core::graphics::{Adapter, Plan}; + +pub fn plan(config: &Config) -> Result { + let environment = leonida_core::graphics::snapshot_environment()?; + let gpu = match leonida_hle::modules::d3d12x::graphics_adapter() { + Ok(adapter) => Some(Adapter { + name: adapter.name, + vendor: match adapter.vendor_id { + 0x10de => "nvidia", + 0x1002 => "amd", + 0x8086 => "intel", + _ => "other", + } + .into(), + vram_mb: adapter.vram_mb, + }), + Err(error) => { + eprintln!("graphics adapter unavailable ({error}); matching only general profiles"); + None + } + }; + config.graphics_plan(gpu, &environment) +} + +/// The executable calls this before loading a title or creating a translation +/// host. Existing GPU consumers keep reading their switches in one place. +#[cfg(windows)] +pub fn initialize(config: &Config) -> Result<()> { + let plan = plan(config)?; + apply(&plan); + let profiles = if plan.profiles.is_empty() { + "none".to_owned() + } else { + plan.profiles.join(", ") + }; + eprintln!( + "graphics card: {}; profiles: {profiles}", + plan.gpu.as_ref().map_or("unknown", |gpu| gpu.name.as_str()) + ); + Ok(()) +} + +#[cfg(windows)] +fn apply(plan: &Plan) { + for (key, value) in &plan.settings { + // Explicit environment values already have precedence in the plan. + // Leave them alone, including empty values used to disable a switch. + if plan + .sources + .get(key) + .is_some_and(|source| source == "environment") + { + continue; + } + // SAFETY: environment updates are thread-safe on Windows. This bridge + // is Windows-only and runs before the GPU's workers and OnceLocks; the + // resolver rejects NULs and invalid variable names before this point. + unsafe { std::env::set_var(key, value) }; + } +} + +#[cfg(not(windows))] +pub fn initialize(config: &Config) -> Result<()> { + // The native Linux frontend can inspect files but cannot run the Windows + // GPU backend. Validate its settings without mutating a Unix environment. + let _ = plan(config)?; + Ok(()) +} + +#[cfg(all(test, windows))] +mod tests { + use super::*; + use std::process::Command; + + #[test] + fn startup_applies_settings_without_replacing_explicit_values() { + const CHILD: &str = "LEONIDA_GRAPHICS_TEST_CHILD"; + if std::env::var_os(CHILD).is_some() { + let config = Config::load().unwrap(); + initialize(&config).unwrap(); + assert_eq!(std::env::var("LEONIDA_ASYNC_SUBMIT").unwrap(), "0"); + assert_eq!(std::env::var("LEONIDA_QUEUE2").unwrap(), "2"); + assert_eq!(std::env::var("LEONIDA_INDIRECT_GATHER").unwrap(), "1"); + assert_eq!(std::env::var("LEONIDA_JOIN_PARTS").unwrap(), ""); + assert!(std::env::var_os("LEONIDA_CARD_WINDOWS_MB").is_none()); + eprintln!("graphics startup: config, profile and explicit overrides applied"); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("settings.toml"); + std::fs::write(&config, "[graphics]\nasync_submit = false\nqueue2 = 3\n").unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()); + for (key, _) in std::env::vars_os() { + if key + .to_string_lossy() + .to_ascii_uppercase() + .starts_with("LEONIDA_") + { + child.env_remove(key); + } + } + let output = child + .args([ + "--exact", + "graphics::tests::startup_applies_settings_without_replacing_explicit_values", + "--nocapture", + ]) + .env(CHILD, "1") + .env("LEONIDA_CONFIG", config) + .env("LEONIDA_QUEUE2", "2") + .env("LEONIDA_JOIN_PARTS", "") + .current_dir(dir.path()) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stderr}"); + assert!( + stderr.contains("graphics startup: config, profile and explicit overrides applied") + ); + } +} diff --git a/apps/leonida/src/main.rs b/apps/leonida/src/main.rs index f5850cd4b..12720fafd 100644 --- a/apps/leonida/src/main.rs +++ b/apps/leonida/src/main.rs @@ -4,6 +4,7 @@ //! the user's cache directory (outside the repository). mod census; +mod graphics; mod inspect; mod run; mod shader; @@ -120,6 +121,9 @@ enum Command { /// First save this folder as the game folder in leonida.toml. #[arg(long)] game_dir: Option, + /// Print the effective graphics settings as JSON, without running a title. + #[arg(long, conflicts_with = "game_dir")] + graphics: bool, }, } @@ -168,6 +172,7 @@ fn main() -> Result<()> { jobs, warm, } => { + graphics::initialize(&leonida_core::Config::load()?)?; // The warm-up keys its translations on the same host facts a run // gets from the device; the switches below still override them. if warm.is_some() && !leonida_hle::modules::d3d12x::probe_translation_host() { @@ -200,7 +205,12 @@ fn main() -> Result<()> { }; run::run(&exe, unimplemented, strict, execute, console) } - Command::Config { game_dir } => { + Command::Config { game_dir, graphics } => { + if graphics { + let plan = graphics::plan(&leonida_core::Config::load()?)?; + println!("{}", plan.to_json()?); + return Ok(()); + } if let Some(dir) = game_dir { check_game_dir(&dir)?; let saved = leonida_core::Config::save_game_dir(&dir)?; diff --git a/apps/leonida/src/run.rs b/apps/leonida/src/run.rs index 9935a10e4..0643c80a1 100644 --- a/apps/leonida/src/run.rs +++ b/apps/leonida/src/run.rs @@ -33,6 +33,7 @@ fn run_title( // A title that relaunched itself: the old process must be gone first. leonida_hle::modules::lifecycle::wait_for_previous(); let cfg = leonida_core::Config::load()?; + crate::graphics::initialize(&cfg)?; let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let prepared = leonida_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); diff --git a/apps/leonida/tests/graphics.rs b/apps/leonida/tests/graphics.rs new file mode 100644 index 000000000..b067741e8 --- /dev/null +++ b/apps/leonida/tests/graphics.rs @@ -0,0 +1,481 @@ +//! Exercise the public graphics configuration CLI in isolated child processes. +//! Every input is original synthetic data, and all temporary files stay outside the repo. +#![cfg(windows)] + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +const BASE: [&str; 8] = [ + "LEONIDA_ASYNC_SUBMIT", + "LEONIDA_QUEUE2", + "LEONIDA_INDIRECT_WINDOW", + "LEONIDA_COPY_PLAIN", + "LEONIDA_JOIN_PARTS", + "LEONIDA_BACK_OWN_VIEW", + "LEONIDA_INDIRECT_GATHER", + "LEONIDA_CARD_REHASH_RUNS", +]; + +struct Fixture { + root: TempDir, + config: PathBuf, +} + +impl Fixture { + fn new(config: &str) -> Self { + let root = tempfile::tempdir().unwrap(); + leonida_core::ensure_outside_repo(root.path()).unwrap(); + let path = root.path().join("leonida.toml"); + std::fs::write(&path, config).unwrap(); + Self { root, config: path } + } + + fn path(&self, name: &str) -> PathBuf { + self.root.path().join(name) + } + + fn local(&self, value: Value) { + std::fs::write( + self.path("gpu-profiles.local.json"), + serde_json::to_vec(&value).unwrap(), + ) + .unwrap(); + } + + fn command(&self) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_leonida")); + cmd.env_clear(); + // Keep only OS discovery/loading variables; no caller's LEONIDA_* state leaks in. + for name in ["SystemRoot", "WINDIR", "PATH", "TEMP", "TMP", "USERPROFILE"] { + if let Some(value) = std::env::var_os(name) { + cmd.env(name, value); + } + } + cmd.current_dir(self.root.path()) + .env("LOCALAPPDATA", self.path("local-app-data")) + .env("LEONIDA_CONFIG", &self.config) + .env("LEONIDA_CACHE_DIR", self.path("cache")) + .env("LEONIDA_DATA_DIR", self.path("data")); + cmd + } + + fn graphics(&self, env: &[(&str, &str)]) -> Value { + let mut cmd = self.command(); + cmd.args(["config", "--graphics"]); + for (name, value) in env { + cmd.env(name, value); + } + graphics_output(cmd.output().unwrap()) + } +} + +fn graphics_output(output: Output) -> Value { + assert!( + output.status.success(), + "status: {}\nstdout: {}\nstderr: {}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + let value: Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { + panic!( + "graphics stdout is not one JSON document: {error}\n{:?}", + output.stdout + ) + }); + assert!(value["profiles"].is_array(), "{value}"); + let settings = value["settings"].as_object().expect("settings map"); + let sources = value["sources"].as_object().expect("sources map"); + assert_eq!(settings.len(), sources.len(), "{value}"); + for (name, setting) in settings { + assert!(setting.is_string(), "{name}: {setting}"); + assert!(sources.get(name).is_some_and(Value::is_string), "{value}"); + } + if !value["gpu"].is_null() { + assert!(value["gpu"]["name"].is_string(), "{value}"); + assert!(value["gpu"]["vendor"].is_string(), "{value}"); + assert!(value["gpu"]["vram_mb"].is_u64(), "{value}"); + } + value +} + +fn setting(plan: &Value, name: &str, value: &str, source: &str) { + assert_eq!(plan["settings"][name], value, "{plan}"); + assert_eq!(plan["sources"][name], source, "{plan}"); +} + +fn absent(plan: &Value, name: &str) { + assert!(plan["settings"].get(name).is_none(), "{plan}"); + assert!(plan["sources"].get(name).is_none(), "{plan}"); +} + +#[test] +fn graphics_defaults_report_eight_base_settings_without_card_windows() { + let fixture = Fixture::new(""); + let plan = fixture.graphics(&[]); + assert_eq!(plan["profiles"], json!(["base"])); + assert_eq!(plan["settings"].as_object().unwrap().len(), BASE.len()); + for name in BASE { + setting(&plan, name, "1", "profile:base"); + } + for name in [ + "LEONIDA_CARD_WINDOWS_MB", + "LEONIDA_WINDOW_UPLOAD", + "LEONIDA_TEXTURE_ROOM_PERCENT", + ] { + absent(&plan, name); + } +} + +#[test] +fn graphics_sources_report_environment_over_config_over_profiles() { + let fixture = Fixture::new("[graphics]\nasync_submit = false\nqueue2 = 3\n"); + let plan = fixture.graphics(&[("LEONIDA_QUEUE2", "2")]); + setting(&plan, "LEONIDA_ASYNC_SUBMIT", "0", "config"); + setting(&plan, "LEONIDA_QUEUE2", "2", "environment"); + setting(&plan, "LEONIDA_INDIRECT_GATHER", "1", "profile:base"); + absent(&plan, "LEONIDA_CONFIG"); + absent(&plan, "LEONIDA_CACHE_DIR"); +} + +#[test] +fn graphics_none_and_empty_profile_lists_preserve_config_values() { + for selection in ["profiles = []\n", "profiles = [\"none\"]\n"] { + let fixture = Fixture::new(&format!("[graphics]\n{selection}async_submit = false\n")); + let plan = fixture.graphics(&[]); + assert_eq!(plan["profiles"], json!([])); + assert_eq!(plan["settings"].as_object().unwrap().len(), 1); + setting(&plan, "LEONIDA_ASYNC_SUBMIT", "0", "config"); + } + let fixture = Fixture::new("[graphics]\nprofiles = [\"card-windows\"]\nasync_submit = false\n"); + let plan = fixture.graphics(&[("LEONIDA_PROFILE", "none")]); + assert_eq!(plan["profiles"], json!([])); + setting(&plan, "LEONIDA_ASYNC_SUBMIT", "0", "config"); + absent(&plan, "LEONIDA_CARD_WINDOWS_MB"); + absent(&plan, "LEONIDA_QUEUE2"); +} + +#[test] +fn graphics_environment_profile_selection_overrides_config_selection() { + let fixture = Fixture::new("[graphics]\nprofiles = []\ncard_windows_mb = 4096\n"); + let plan = fixture.graphics(&[("LEONIDA_PROFILE", "card-windows")]); + assert_eq!(plan["profiles"], json!(["base", "card-windows"])); + setting(&plan, "LEONIDA_CARD_WINDOWS_MB", "4096", "config"); + setting(&plan, "LEONIDA_WINDOW_UPLOAD", "1", "profile:card-windows"); + setting( + &plan, + "LEONIDA_TEXTURE_ROOM_PERCENT", + "70", + "profile:card-windows", + ); +} + +#[test] +fn graphics_off_preserves_only_explicit_switches() { + let fixture = Fixture::new( + "[graphics]\nprofiles = [\"card-windows\"]\nasync_submit = false\nqueue2 = 3\n", + ); + let plan = fixture.graphics(&[("LEONIDA_GRAPHICS_OFF", "1"), ("LEONIDA_QUEUE2", "2")]); + assert_eq!(plan["profiles"], json!([])); + assert_eq!(plan["settings"], json!({"LEONIDA_QUEUE2": "2"})); + setting(&plan, "LEONIDA_QUEUE2", "2", "environment"); + absent(&plan, "LEONIDA_GRAPHICS_OFF"); +} + +#[test] +fn graphics_local_profiles_follow_catalog_order_and_preserve_user_overrides() { + let fixture = + Fixture::new("[graphics]\nprofiles = [\"last\", \"first\"]\nasync_submit = false\n"); + fixture.local(json!({"profiles": [ + {"name": "first", "opt_in": true, "env": { + "LEONIDA_JOIN_PARTS": "0", "LEONIDA_ASYNC_SUBMIT": "1", "LEONIDA_QUEUE2": "3" + }}, + {"name": "last", "opt_in": true, "env": { + "LEONIDA_JOIN_PARTS": null, "LEONIDA_ASYNC_SUBMIT": null, + "LEONIDA_QUEUE2": null, "LEONIDA_COPY_PLAIN": "0" + }} + ]})); + let plan = fixture.graphics(&[("LEONIDA_QUEUE2", "2")]); + assert_eq!(plan["profiles"], json!(["base", "first", "last"])); + absent(&plan, "LEONIDA_JOIN_PARTS"); + setting(&plan, "LEONIDA_ASYNC_SUBMIT", "0", "config"); + setting(&plan, "LEONIDA_QUEUE2", "2", "environment"); + setting(&plan, "LEONIDA_COPY_PLAIN", "0", "profile:last"); +} + +#[test] +fn graphics_local_catalog_is_relative_to_the_explicit_config() { + let fixture = Fixture::new(""); + let config_dir = fixture.path("configuration"); + std::fs::create_dir(&config_dir).unwrap(); + let config = config_dir.join("settings.toml"); + std::fs::write(&config, "[graphics]\nprofiles = [\"placed\"]\n").unwrap(); + std::fs::write(fixture.path("gpu-profiles.local.json"), "not JSON").unwrap(); + std::fs::write( + config_dir.join("gpu-profiles.local.json"), + serde_json::to_vec(&json!({"profiles": [{ + "name": "placed", "env": {"LEONIDA_COPY_PLAIN": "0"} + }]})) + .unwrap(), + ) + .unwrap(); + let output = fixture + .command() + .args(["config", "--graphics"]) + .env("LEONIDA_CONFIG", &config) + .output() + .unwrap(); + let plan = graphics_output(output); + assert_eq!(plan["profiles"], json!(["base", "placed"])); + setting(&plan, "LEONIDA_COPY_PLAIN", "0", "profile:placed"); +} + +#[test] +fn graphics_local_catalog_uses_cwd_when_no_config_exists() { + let fixture = Fixture::new(""); + std::fs::remove_file(&fixture.config).unwrap(); + fixture.local(json!({"profiles": [{ + "name": "from-cwd", "env": {"LEONIDA_COPY_PLAIN": "0"} + }]})); + let output = fixture + .command() + .args(["config", "--graphics"]) + .env_remove("LEONIDA_CONFIG") + .output() + .unwrap(); + let plan = graphics_output(output); + assert_eq!(plan["profiles"], json!(["base", "from-cwd"])); + setting(&plan, "LEONIDA_COPY_PLAIN", "0", "profile:from-cwd"); +} + +#[test] +fn graphics_disabled_profiles_do_not_parse_a_broken_local_catalog() { + let fixture = Fixture::new("[graphics]\nasync_submit = false\n"); + std::fs::write(fixture.path("gpu-profiles.local.json"), "not JSON").unwrap(); + let none = fixture.graphics(&[("LEONIDA_PROFILE", "none")]); + setting(&none, "LEONIDA_ASYNC_SUBMIT", "0", "config"); + let off = fixture.graphics(&[("LEONIDA_GRAPHICS_OFF", "1")]); + assert_eq!(off["settings"], json!({})); +} + +#[test] +fn graphics_invalid_local_catalog_reports_its_source() { + let fixture = Fixture::new(""); + std::fs::write(fixture.path("gpu-profiles.local.json"), "not JSON").unwrap(); + let output = fixture + .command() + .args(["config", "--graphics"]) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("gpu-profiles.local.json"), "{stderr}"); +} + +#[test] +fn graphics_validation_precedes_run_reads_and_translation_probing() { + let fixture = Fixture::new("[graphics]\nprofiles = [\"missing-profile\"]\n"); + let missing = fixture.path("not-a-title.exe"); + let hashes = fixture.path("not-a-hash-list.txt"); + let commands = [ + vec!["run".as_ref(), missing.as_os_str()], + vec![ + "translate".as_ref(), + missing.as_os_str(), + "--warm".as_ref(), + hashes.as_os_str(), + ], + ]; + for args in commands { + let output = fixture.command().args(args).output().unwrap(); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("unknown graphics profile"), "{stderr}"); + assert!(stderr.contains("missing-profile"), "{stderr}"); + assert!( + !stderr.contains("reading "), + "input was read before graphics validation: {stderr}" + ); + assert!( + !stderr.contains("no host D3D12 device"), + "translation host probed first: {stderr}" + ); + } +} + +#[test] +fn graphics_json_cannot_be_combined_with_saving_a_game_directory() { + let fixture = Fixture::new("# keep this file unchanged\n"); + let before = std::fs::read(&fixture.config).unwrap(); + let output = fixture + .command() + .args(["config", "--graphics", "--game-dir"]) + .arg(fixture.path("not-a-game-directory")) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("--graphics") && stderr.contains("--game-dir"), + "{stderr}" + ); + assert_eq!(std::fs::read(&fixture.config).unwrap(), before); +} + +/// An original AMD64 PE with one import and no title data or compiler subprocess. +/// Its entry returns 73 only if GetEnvironmentVariableA reads the expected one-byte value. +#[cfg(target_arch = "x86_64")] +fn write_environment_probe(path: &Path, expected: u8) { + let mut bytes = vec![0u8; 0x400]; + fn u16_at(bytes: &mut [u8], at: usize, value: u16) { + bytes[at..at + 2].copy_from_slice(&value.to_le_bytes()); + } + fn u32_at(bytes: &mut [u8], at: usize, value: u32) { + bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + fn u64_at(bytes: &mut [u8], at: usize, value: u64) { + bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); + } + bytes[..2].copy_from_slice(b"MZ"); + u32_at(&mut bytes, 0x3c, 0x80); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + u16_at(&mut bytes, 0x84, 0x8664); // AMD64 + u16_at(&mut bytes, 0x86, 1); // one section + u16_at(&mut bytes, 0x94, 0xf0); + u16_at(&mut bytes, 0x96, 0x0022); // executable, large-address-aware + let optional = 0x98; + u16_at(&mut bytes, optional, 0x20b); // PE32+ + u32_at(&mut bytes, optional + 4, 0x200); + u32_at(&mut bytes, optional + 16, 0x1000); // original entry + u32_at(&mut bytes, optional + 20, 0x1000); + u64_at(&mut bytes, optional + 24, 0x1_8000_0000); + u32_at(&mut bytes, optional + 32, 0x1000); + u32_at(&mut bytes, optional + 36, 0x200); + u16_at(&mut bytes, optional + 40, 6); + u16_at(&mut bytes, optional + 48, 6); + u32_at(&mut bytes, optional + 56, 0x2000); + u32_at(&mut bytes, optional + 60, 0x200); + u16_at(&mut bytes, optional + 68, 3); // console subsystem + u16_at(&mut bytes, optional + 70, 0x0140); // ASLR and NX compatible + u64_at(&mut bytes, optional + 72, 0x10_0000); + u64_at(&mut bytes, optional + 80, 0x1000); + u64_at(&mut bytes, optional + 88, 0x10_0000); + u64_at(&mut bytes, optional + 96, 0x1000); + u32_at(&mut bytes, optional + 108, 16); + for (directory, rva, size) in [(1, 0x1080, 40), (5, 0x1100, 12), (12, 0x10d0, 16)] { + u32_at(&mut bytes, optional + 112 + directory * 8, rva); + u32_at(&mut bytes, optional + 116 + directory * 8, size); + } + let section = 0x188; + bytes[section..section + 6].copy_from_slice(b".probe"); + u32_at(&mut bytes, section + 8, 0x200); + u32_at(&mut bytes, section + 12, 0x1000); + u32_at(&mut bytes, section + 16, 0x200); + u32_at(&mut bytes, section + 20, 0x200); + u32_at(&mut bytes, section + 36, 0xe000_0020); // code, read/write/execute + + // Win64 entry: reserve aligned shadow/buffer space, call the sole import, + // check length and value, and return the sentinel while preserving saved registers. + let entry = [ + 0x48, 0x83, 0xec, 0x38, // sub rsp, 56 + 0x48, 0x8d, 0x0d, 0x35, 0, 0, 0, // lea rcx, [environment-name] + 0x48, 0x8d, 0x54, 0x24, 0x20, // lea rdx, [rsp + 32] + 0x41, 0xb8, 2, 0, 0, 0, // mov r8d, 2 + 0xff, 0x15, 0xb4, 0, 0, 0, // call [GetEnvironmentVariableA IAT slot] + 0x83, 0xf8, 1, // cmp eax, 1 + 0x75, 0x11, // jne failure + 0x80, 0x7c, 0x24, 0x20, expected, // cmp byte [rsp + 32], expected + 0x75, 0x0a, // jne failure + 0xb8, 73, 0, 0, 0, // mov eax, 73 + 0x48, 0x83, 0xc4, 0x38, 0xc3, // restore stack; ret + 0x31, 0xc0, // failure: xor eax, eax + 0x48, 0x83, 0xc4, 0x38, 0xc3, // restore stack; ret + ]; + bytes[0x200..0x200 + entry.len()].copy_from_slice(&entry); + for (at, text) in [ + (0x240, b"LEONIDA_QUEUE2\0".as_slice()), + (0x2b0, b"KERNEL32.dll\0".as_slice()), + (0x2e2, b"GetEnvironmentVariableA\0".as_slice()), + ] { + bytes[at..at + text.len()].copy_from_slice(text); + } + // Import descriptor, original lookup thunk and writable IAT thunk. + u32_at(&mut bytes, 0x280, 0x10c0); + u32_at(&mut bytes, 0x28c, 0x10b0); + u32_at(&mut bytes, 0x290, 0x10d0); + u64_at(&mut bytes, 0x2c0, 0x10e0); + u64_at(&mut bytes, 0x2d0, 0x10e0); + // A genuine DIR64 relocation on an unused pointer allows ordinary loader rebasing. + u32_at(&mut bytes, 0x300, 0x1000); + u32_at(&mut bytes, 0x304, 12); + u16_at(&mut bytes, 0x308, 0xa120); + u64_at(&mut bytes, 0x320, 0x1_8000_0000); + std::fs::write(path, bytes).unwrap(); +} + +#[cfg(target_arch = "x86_64")] +#[test] +fn graphics_plan_reaches_the_actual_title_environment() { + let cases: [(&str, &[(&str, &str)], &str, &str); 3] = [ + ("", &[], "1", "profile:base"), + ("[graphics]\nqueue2 = 0\n", &[], "0", "config"), + ( + "[graphics]\nqueue2 = 0\n", + &[("LEONIDA_QUEUE2", "2")], + "2", + "environment", + ), + ]; + for (config, env, expected, source) in cases { + let fixture = Fixture::new(config); + let plan = fixture.graphics(env); + setting(&plan, "LEONIDA_QUEUE2", expected, source); + let probe = fixture.path("graphics-probe.exe"); + write_environment_probe(&probe, expected.as_bytes()[0]); + let mut command = fixture.command(); + command.arg("run").arg(&probe).arg("--execute"); + for (name, value) in env { + command.env(name, value); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "source {source}: {stdout}\n{stderr}" + ); + assert!( + stdout.contains("title exited with 73"), + "source {source}: actual title code did not read the reported setting\n{stdout}\n{stderr}", + ); + } + eprintln!("graphics runtime probe: 3 plans matched the title environment"); +} + +#[cfg(feature = "diagnostics")] +#[test] +fn graphics_warp_presence_never_reports_a_hardware_adapter() { + let fixture = Fixture::new(""); + // The runtime selects WARP by presence, so even the text "0" requests software. + let output = fixture + .command() + .args(["config", "--graphics"]) + .env("LEONIDA_D3D12_WARP", "0") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + let plan = graphics_output(output); + if plan["gpu"].is_null() { + assert!(stderr.contains("graphics adapter unavailable"), "{stderr}"); + } else { + assert_eq!(plan["gpu"]["vendor"], "other", "{plan}"); + let name = plan["gpu"]["name"].as_str().unwrap(); + assert!(name.to_ascii_lowercase().contains("microsoft"), "{plan}"); + } + absent(&plan, "LEONIDA_D3D12_WARP"); +} diff --git a/crates/leonida-core/Cargo.toml b/crates/leonida-core/Cargo.toml index bdbad06e0..149bd6845 100644 --- a/crates/leonida-core/Cargo.toml +++ b/crates/leonida-core/Cargo.toml @@ -11,6 +11,7 @@ publish.workspace = true anyhow.workspace = true thiserror.workspace = true serde.workspace = true +serde_json.workspace = true toml.workspace = true tracing-subscriber.workspace = true diff --git a/crates/leonida-core/src/config.rs b/crates/leonida-core/src/config.rs index 4396e5b2a..d17e202db 100644 --- a/crates/leonida-core/src/config.rs +++ b/crates/leonida-core/src/config.rs @@ -9,6 +9,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::Deserialize; +use crate::graphics::{self, Adapter, Environment, GraphicsSettings, Plan}; use crate::policy::ensure_outside_repo; #[derive(Debug, Default, Clone)] @@ -24,6 +25,8 @@ pub struct Config { pub test_titles: Vec, /// The config file that was read, if any. pub source: Option, + /// Graphics overrides applied before the host device or title starts. + pub graphics: GraphicsSettings, } #[derive(Debug, Default, Deserialize)] @@ -31,6 +34,8 @@ pub struct Config { struct FileConfig { #[serde(default)] paths: FilePaths, + #[serde(default)] + graphics: GraphicsSettings, } #[derive(Debug, Default, Deserialize)] @@ -68,7 +73,10 @@ impl Config { } None => (None, FileConfig::default()), }; - Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) + parsed.graphics.validate()?; + let mut config = Self::resolve(parsed.paths, source, |k| std::env::var_os(k))?; + config.graphics = parsed.graphics; + Ok(config) } fn resolve( @@ -95,9 +103,15 @@ impl Config { data_dir, test_titles, source, + graphics: GraphicsSettings::default(), }) } + /// Resolves graphics settings without changing the process environment. + pub fn graphics_plan(&self, gpu: Option, env: &Environment) -> Result { + graphics::load(&self.graphics, self.source.as_deref(), gpu, env) + } + /// The game directory, or a helpful error if it is not configured. pub fn require_game_dir(&self) -> Result<&Path> { self.game_dir.as_deref().context( @@ -119,6 +133,7 @@ impl Config { let new = with_game_dir(&text, game_dir)?; let parsed: FileConfig = toml::from_str(&new).with_context(|| format!("updating {}", path.display()))?; + parsed.graphics.validate()?; anyhow::ensure!( parsed.paths.game_dir.as_deref() == Some(game_dir), "updating {}: the game folder did not read back", @@ -301,6 +316,24 @@ mod tests { assert_eq!(new, "[paths]\r\ngame_dir = \"y\"\r\n"); } + #[test] + fn game_dir_save_preserves_graphics_and_comments() { + let graphics = "[graphics]\n# Keep the user's choice.\nprofiles = ['none']\nqueue2 = 2\n"; + for text in [ + format!("[paths]\ngame_dir = 'old'\n\n{graphics}"), + format!("{graphics}\n[paths]\ngame_dir = 'old'\n"), + graphics.to_owned(), + ] { + let new = with_game_dir(&text, Path::new("new")).unwrap(); + assert!(new.contains(graphics)); + let parsed: FileConfig = toml::from_str(&new).unwrap(); + assert_eq!(parsed.paths.game_dir, Some(PathBuf::from("new"))); + assert_eq!(parsed.graphics.queue2, Some(2)); + assert_eq!(parsed.graphics.profiles, Some(vec!["none".into()])); + parsed.graphics.validate().unwrap(); + } + } + #[test] fn cache_inside_repo_is_refused() { let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); diff --git a/crates/leonida-core/src/graphics.rs b/crates/leonida-core/src/graphics.rs new file mode 100644 index 000000000..64254f463 --- /dev/null +++ b/crates/leonida-core/src/graphics.rs @@ -0,0 +1,959 @@ +//! Graphics profiles and user overrides, resolved before the GPU reads its switches. +//! +//! Resolution is pure: callers provide the adapter and environment, then apply the +//! returned plan at startup. This module never changes the process environment. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use anyhow::{Context, Result, bail, ensure}; +use serde::{Deserialize, Serialize}; + +const CATALOG: &str = include_str!("../../../gpu-profiles.json"); + +pub type Environment = BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Adapter { + pub name: String, + pub vendor: String, + pub vram_mb: u64, +} + +#[derive(Debug, Default, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GraphicsSettings { + /// Omitted: match the adapter. Empty or containing `none`: apply no profiles. + pub profiles: Option>, + pub async_submit: Option, + pub queue2: Option, + pub indirect_window: Option, + pub copy_plain: Option, + pub join_parts: Option, + pub back_own_view: Option, + pub indirect_gather: Option, + pub card_rehash_runs: Option, + pub window_upload: Option, + pub card_windows_mb: Option, + pub texture_room_percent: Option, +} + +impl GraphicsSettings { + pub fn validate(&self) -> Result<()> { + ensure!( + self.queue2.is_none_or(|n| n <= 3), + "[graphics].queue2 must be between 0 and 3" + ); + ensure!( + self.card_windows_mb.is_none_or(|n| n <= u64::MAX >> 20), + "[graphics].card_windows_mb is too large to convert to bytes" + ); + ensure!( + self.texture_room_percent + .is_none_or(|n| (50..=97).contains(&n)), + "[graphics].texture_room_percent must be between 50 and 97" + ); + if let Some(names) = &self.profiles { + ensure!( + names.iter().all(|name| !name.trim().is_empty()), + "[graphics].profiles contains an empty name; use [] to disable profiles" + ); + } + Ok(()) + } + + fn values(&self) -> Environment { + let mut values = Environment::new(); + for (name, value) in [ + ("ASYNC_SUBMIT", self.async_submit), + ("INDIRECT_WINDOW", self.indirect_window), + ("COPY_PLAIN", self.copy_plain), + ("JOIN_PARTS", self.join_parts), + ("BACK_OWN_VIEW", self.back_own_view), + ("INDIRECT_GATHER", self.indirect_gather), + ("CARD_REHASH_RUNS", self.card_rehash_runs), + ("WINDOW_UPLOAD", self.window_upload), + ] { + if let Some(value) = value { + values.insert(format!("LEONIDA_{name}"), u8::from(value).to_string()); + } + } + for (name, value) in [ + ("QUEUE2", self.queue2.map(u64::from)), + ("CARD_WINDOWS_MB", self.card_windows_mb), + ( + "TEXTURE_ROOM_PERCENT", + self.texture_room_percent.map(u64::from), + ), + ] { + if let Some(value) = value { + values.insert(format!("LEONIDA_{name}"), value.to_string()); + } + } + values + } +} + +/// Effective switches and their origins. Missing switches retain their code defaults. +#[derive(Debug, Clone, Serialize)] +pub struct Plan { + pub gpu: Option, + pub profiles: Vec, + pub settings: Environment, + pub sources: BTreeMap, +} + +impl Plan { + pub fn to_json(&self) -> Result { + serde_json::to_string_pretty(self).context("serializing graphics settings") + } +} + +/// Runtime switches profiles may supply. Paths, selection and early initialization +/// remain under the caller's control; probing an adapter must not change them. +pub fn is_setting_key(name: &str) -> bool { + name.starts_with("LEONIDA_") + && name.len() > "LEONIDA_".len() + && name + .bytes() + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_') + && !name.starts_with("LEONIDA_RENDERDOC") + && !matches!( + name, + "LEONIDA_CONFIG" + | "LEONIDA_GAME_DIR" + | "LEONIDA_CACHE_DIR" + | "LEONIDA_DATA_DIR" + | "LEONIDA_TEST_TITLES" + | "LEONIDA_LOG" + | "LEONIDA_PROFILE" + | "LEONIDA_KEEP_WINDOW" + | "LEONIDA_GRAPHICS_OFF" + | "LEONIDA_D3D12_WARP" + | "LEONIDA_RELAUNCHED_FROM" + | "LEONIDA_AUDIO_CAPTURE_OF" + ) +} + +/// Windows environment keys are case-insensitive. Empty values are explicit too. +/// Refuse non-Unicode switch values instead of replacing them with a profile default. +pub fn snapshot_environment() -> Result { + snapshot_from(std::env::vars_os()) +} + +fn snapshot_from( + vars: impl IntoIterator, +) -> Result { + let mut snapshot = Environment::new(); + for (key, value) in vars { + let name = key.to_string_lossy().to_ascii_uppercase(); + if !name.starts_with("LEONIDA_") { + continue; + } + ensure!( + key.to_str().is_some(), + "a LEONIDA_ variable name is not valid Unicode; unset it" + ); + if is_setting_key(&name) + || matches!(name.as_str(), "LEONIDA_PROFILE" | "LEONIDA_GRAPHICS_OFF") + { + let value = value.into_string().map_err(|_| { + anyhow::anyhow!("{name} is not valid Unicode; unset it or set a text value") + })?; + snapshot.insert(name, value); + } + } + Ok(snapshot) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Catalog { + #[serde(default, rename = "about")] + _about: Vec, + profiles: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Profile { + name: String, + #[serde(default, rename = "measured")] + _measured: Option, + #[serde(default)] + opt_in: bool, + #[serde(default, rename = "match")] + matcher: Matcher, + env: BTreeMap>, +} + +#[derive(Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct Matcher { + vendor: Option, + min_vram_mb: Option, + max_vram_mb: Option, + name: Option, +} + +enum Selection { + Auto, + None, + Named(BTreeSet), +} + +fn selection(settings: &GraphicsSettings, env: &Environment) -> Selection { + let forced = env + .get("LEONIDA_PROFILE") + // This spelling already enables the diagnostics CPU sampling profiler. + // Leave it for that consumer; graphics still use TOML or automatic matching. + .filter(|value| !value.trim().is_empty() && value.as_str() != "1"); + let names = forced + .map(|value| value.split(',').map(str::to_owned).collect::>()) + .or_else(|| settings.profiles.clone()); + match names { + None => Selection::Auto, + Some(names) => { + let names: BTreeSet<_> = names + .iter() + .map(|name| name.trim().to_lowercase()) + .filter(|name| !name.is_empty()) + .collect(); + if names.contains("none") || (names.is_empty() && forced.is_none()) { + Selection::None + } else if names.is_empty() { + Selection::Auto + } else { + Selection::Named(names) + } + } + } +} + +fn normalized(env: &Environment) -> Environment { + env.iter() + .map(|(name, value)| (name.to_ascii_uppercase(), value.clone())) + .collect() +} + +/// Reads only the optional local catalog, next to the selected configuration file. +/// `none` and `LEONIDA_GRAPHICS_OFF=1` also work when that catalog is broken. +pub fn load( + settings: &GraphicsSettings, + source: Option<&Path>, + gpu: Option, + env: &Environment, +) -> Result { + let env = normalized(env); + let disabled = env + .get("LEONIDA_GRAPHICS_OFF") + .is_some_and(|value| value == "1") + || matches!(selection(settings, &env), Selection::None); + let local = if disabled { + None + } else { + let parent = source.and_then(Path::parent).unwrap_or(Path::new(".")); + let path = parent.join("gpu-profiles.local.json"); + match std::fs::read_to_string(&path) { + Ok(text) => Some(text), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error).with_context(|| format!("reading {}", path.display())), + } + }; + resolve(settings, gpu, &env, local.as_deref()) +} + +/// Environment overrides TOML, which overrides profiles in catalog order. +/// A null profile value cancels an earlier profile value, never a user override. +pub fn resolve( + settings: &GraphicsSettings, + gpu: Option, + env: &Environment, + local_json: Option<&str>, +) -> Result { + settings.validate()?; + let env = normalized(env); + let mut plan = Plan { + gpu, + profiles: Vec::new(), + settings: Environment::new(), + sources: BTreeMap::new(), + }; + if !env + .get("LEONIDA_GRAPHICS_OFF") + .is_some_and(|value| value == "1") + { + let selected = selection(settings, &env); + if !matches!(selected, Selection::None) { + let mut profiles = parse_catalog(CATALOG, "built-in gpu-profiles.json")?; + if let Some(local) = local_json { + profiles.extend(parse_catalog(local, "gpu-profiles.local.json")?); + } + if let Selection::Named(names) = &selected { + for name in names { + ensure!( + profiles + .iter() + .any(|profile| profile.name.to_lowercase() == *name), + "unknown graphics profile {name:?}; check [graphics].profiles or LEONIDA_PROFILE" + ); + } + } + for profile in profiles { + let wanted = match &selected { + Selection::Auto => { + !profile.opt_in && profile.matcher.matches(plan.gpu.as_ref())? + } + Selection::Named(names) => { + profile.name.eq_ignore_ascii_case("base") + || names.contains(&profile.name.to_lowercase()) + } + Selection::None => false, + }; + if !wanted { + continue; + } + for (name, value) in profile.env { + if let Some(value) = value { + plan.settings.insert(name.clone(), value); + plan.sources + .insert(name, format!("profile:{}", profile.name)); + } else { + plan.settings.remove(&name); + plan.sources.remove(&name); + } + } + plan.profiles.push(profile.name); + } + } + for (name, value) in settings.values() { + plan.settings.insert(name.clone(), value); + plan.sources.insert(name, "config".into()); + } + } + for (name, value) in env { + if is_setting_key(&name) { + ensure!(!value.contains('\0'), "{name} contains a NUL character"); + plan.settings.insert(name.clone(), value); + plan.sources.insert(name, "environment".into()); + } + } + Ok(plan) +} + +fn parse_catalog(text: &str, source: &str) -> Result> { + let catalog: Catalog = + serde_json::from_str(text).with_context(|| format!("parsing {source}"))?; + for profile in &catalog.profiles { + ensure!( + !profile.name.trim().is_empty() && profile.name.trim() == profile.name, + "{source}: profile names must be nonempty without surrounding whitespace" + ); + for (name, value) in &profile.env { + ensure!( + is_setting_key(name), + "{source}: profile {:?} cannot set {name}", + profile.name + ); + ensure!( + value.as_ref().is_none_or(|value| !value.contains('\0')), + "{source}: {name} contains a NUL character" + ); + } + let matcher = &profile.matcher; + if let Some(vendor) = &matcher.vendor { + ensure!( + matches!( + vendor.to_ascii_lowercase().as_str(), + "nvidia" | "amd" | "intel" | "other" + ), + "{source}: profile {:?} has unknown vendor {vendor:?}", + profile.name + ); + } + if let (Some(min), Some(max)) = (matcher.min_vram_mb, matcher.max_vram_mb) { + ensure!( + min <= max, + "{source}: profile {:?} has reversed VRAM limits", + profile.name + ); + } + if let Some(pattern) = &matcher.name { + pattern_tokens(pattern) + .with_context(|| format!("{source}: profile {:?}", profile.name))?; + } + } + Ok(catalog.profiles) +} + +impl Matcher { + fn matches(&self, gpu: Option<&Adapter>) -> Result { + let Some(gpu) = gpu else { + return Ok(self.vendor.is_none() + && self.min_vram_mb.is_none() + && self.max_vram_mb.is_none() + && self.name.is_none()); + }; + if self + .vendor + .as_ref() + .is_some_and(|vendor| !vendor.eq_ignore_ascii_case(&gpu.vendor)) + || self.min_vram_mb.is_some_and(|min| gpu.vram_mb < min) + || self.max_vram_mb.is_some_and(|max| gpu.vram_mb > max) + { + return Ok(false); + } + match &self.name { + Some(pattern) => wildcard(pattern, &gpu.name), + None => Ok(true), + } + } +} + +enum Token { + Star, + Any, + Literal(char), + Class(Vec<(char, char)>), +} + +/// Case-insensitive `*`, `?` and `[abc]` / `[a-z]`; malformed or unsupported +/// escapes are errors rather than silently matching a different adapter. +fn pattern_tokens(pattern: &str) -> Result> { + let chars: Vec<_> = pattern.to_lowercase().chars().collect(); + let mut tokens = Vec::new(); + let mut at = 0; + while at < chars.len() { + tokens.push(match chars[at] { + '*' => Token::Star, + '?' => Token::Any, + '`' => bail!("GPU name patterns do not support backtick escapes"), + '[' => { + let start = at + 1; + let end = chars[start..] + .iter() + .position(|&c| c == ']') + .map(|n| start + n) + .context("GPU name pattern has an unclosed '['")?; + ensure!(start < end, "GPU name pattern has an empty character class"); + ensure!( + !matches!(chars[start], '!' | '^'), + "GPU name patterns do not support negated character classes" + ); + let mut ranges = Vec::new(); + at = start; + while at < end { + if at + 2 < end && chars[at + 1] == '-' { + ensure!( + chars[at] <= chars[at + 2], + "GPU name pattern has a reversed range" + ); + ranges.push((chars[at], chars[at + 2])); + at += 3; + } else { + ranges.push((chars[at], chars[at])); + at += 1; + } + } + Token::Class(ranges) + } + literal => Token::Literal(literal), + }); + at += 1; + } + Ok(tokens) +} + +fn wildcard(pattern: &str, name: &str) -> Result { + let name: Vec<_> = name.to_lowercase().chars().collect(); + let mut matched = vec![false; name.len() + 1]; + matched[0] = true; + for token in pattern_tokens(pattern)? { + if matches!(token, Token::Star) { + for i in 1..matched.len() { + matched[i] |= matched[i - 1]; + } + } else { + for i in (1..matched.len()).rev() { + let fits = match &token { + Token::Any => true, + Token::Literal(c) => *c == name[i - 1], + Token::Class(ranges) => { + ranges.iter().any(|&(a, b)| (a..=b).contains(&name[i - 1])) + } + Token::Star => unreachable!(), + }; + matched[i] = matched[i - 1] && fits; + } + matched[0] = false; + } + } + Ok(matched[name.len()]) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn env(values: &[(&str, &str)]) -> Environment { + values + .iter() + .map(|&(key, value)| (key.into(), value.into())) + .collect() + } + + fn gpu() -> Option { + Some(Adapter { + name: "NVIDIA GeForce RTX 5090".into(), + vendor: "nvidia".into(), + vram_mb: 32768, + }) + } + + fn local(profiles: serde_json::Value) -> String { + json!({ "profiles": profiles }).to_string() + } + + #[test] + fn automatic_defaults_are_exactly_the_measured_base() { + let expected = env(&[ + ("LEONIDA_ASYNC_SUBMIT", "1"), + ("LEONIDA_QUEUE2", "1"), + ("LEONIDA_INDIRECT_WINDOW", "1"), + ("LEONIDA_COPY_PLAIN", "1"), + ("LEONIDA_JOIN_PARTS", "1"), + ("LEONIDA_BACK_OWN_VIEW", "1"), + ("LEONIDA_INDIRECT_GATHER", "1"), + ("LEONIDA_CARD_REHASH_RUNS", "1"), + ]); + for gpu in [gpu(), None] { + let plan = resolve(&GraphicsSettings::default(), gpu, &env(&[]), None).unwrap(); + assert_eq!(plan.profiles, ["base"]); + assert_eq!(plan.settings, expected); + assert!(plan.sources.values().all(|source| source == "profile:base")); + } + } + + #[test] + fn explicit_profiles_are_case_insensitive_and_include_base() { + let settings = GraphicsSettings { + profiles: Some(vec!["missing".into()]), + ..Default::default() + }; + let plan = resolve( + &settings, + gpu(), + &env(&[("leonida_profile", " CARD-WINDOWS , ")]), + None, + ) + .unwrap(); + assert_eq!(plan.profiles, ["base", "card-windows"]); + assert_eq!(plan.settings["LEONIDA_CARD_WINDOWS_MB"], "3072"); + assert_eq!(plan.settings["LEONIDA_WINDOW_UPLOAD"], "1"); + assert_eq!(plan.settings["LEONIDA_TEXTURE_ROOM_PERCENT"], "70"); + } + + #[test] + fn environment_then_toml_then_profile_and_empty_is_explicit() { + let settings = GraphicsSettings { + async_submit: Some(false), + queue2: Some(2), + copy_plain: Some(false), + ..Default::default() + }; + let plan = resolve( + &settings, + gpu(), + &env(&[ + ("leonida_queue2", "0"), + ("LEONIDA_COPY_PLAIN", ""), + ("LEONIDA_JOIN_PARTS", "alt"), + ("LEONIDA_CAPTURE", "C:/測定/capture"), + ("LEONIDA_CONFIG", "private.toml"), + ("LEONIDA_D3D12_WARP", "1"), + ]), + None, + ) + .unwrap(); + assert_eq!(plan.settings["LEONIDA_ASYNC_SUBMIT"], "0"); + assert_eq!(plan.sources["LEONIDA_ASYNC_SUBMIT"], "config"); + assert_eq!(plan.settings["LEONIDA_QUEUE2"], "0"); + assert_eq!(plan.sources["LEONIDA_QUEUE2"], "environment"); + assert_eq!(plan.settings["LEONIDA_COPY_PLAIN"], ""); + assert_eq!(plan.settings["LEONIDA_JOIN_PARTS"], "alt"); + assert_eq!(plan.settings["LEONIDA_CAPTURE"], "C:/測定/capture"); + assert!(!plan.settings.contains_key("LEONIDA_CONFIG")); + assert!(!plan.settings.contains_key("LEONIDA_D3D12_WARP")); + } + + #[test] + fn local_order_null_and_user_overrides_preserve_all_layers() { + let local = local(json!([ + { "name": "first", "env": { "LEONIDA_QUEUE2": "2", "LEONIDA_INDIRECT_SINGLE": "1" } }, + { "name": "last", "env": { "LEONIDA_QUEUE2": null, "LEONIDA_INDIRECT_SINGLE": "0", "LEONIDA_COPY_PLAIN": null } } + ])); + let settings = GraphicsSettings { + queue2: Some(3), + ..Default::default() + }; + let plan = resolve( + &settings, + gpu(), + &env(&[("LEONIDA_INDIRECT_SINGLE", "1")]), + Some(&local), + ) + .unwrap(); + assert_eq!(plan.profiles, ["base", "first", "last"]); + assert_eq!(plan.settings["LEONIDA_QUEUE2"], "3"); + assert_eq!(plan.sources["LEONIDA_QUEUE2"], "config"); + assert_eq!(plan.settings["LEONIDA_INDIRECT_SINGLE"], "1"); + assert_eq!(plan.sources["LEONIDA_INDIRECT_SINGLE"], "environment"); + assert!(!plan.settings.contains_key("LEONIDA_COPY_PLAIN")); + assert!(!plan.sources.contains_key("LEONIDA_COPY_PLAIN")); + } + + #[test] + fn none_retains_toml_but_measurement_off_suppresses_it() { + for names in [ + vec![], + vec!["NoNe".into()], + vec!["none".into(), "missing".into()], + ] { + let settings = GraphicsSettings { + profiles: Some(names), + queue2: Some(3), + ..Default::default() + }; + let plan = resolve(&settings, gpu(), &env(&[]), Some("broken json")).unwrap(); + assert!(plan.profiles.is_empty()); + assert_eq!(plan.settings, env(&[("LEONIDA_QUEUE2", "3")])); + } + let settings = GraphicsSettings { + async_submit: Some(true), + ..Default::default() + }; + let plan = resolve( + &settings, + gpu(), + &env(&[ + ("LEONIDA_GRAPHICS_OFF", "1"), + ("LEONIDA_PROFILE", "missing"), + ("LEONIDA_QUEUE2", "2"), + ]), + Some("broken json"), + ) + .unwrap(); + assert!(plan.profiles.is_empty()); + assert_eq!(plan.settings, env(&[("LEONIDA_QUEUE2", "2")])); + } + + #[test] + fn empty_profile_environment_keeps_toml_selection() { + let settings = GraphicsSettings { + profiles: Some(vec![]), + ..Default::default() + }; + let plan = resolve(&settings, gpu(), &env(&[("LEONIDA_PROFILE", "")]), None).unwrap(); + assert!(plan.settings.is_empty()); + // PowerShell ignores empty entries in a comma-separated override. + let plan = resolve( + &settings, + gpu(), + &env(&[("LEONIDA_PROFILE", " , , ")]), + None, + ) + .unwrap(); + assert_eq!(plan.profiles, ["base"]); + } + + #[test] + fn sampling_profiler_switch_does_not_select_a_graphics_profile() { + let environment = env(&[("LEONIDA_PROFILE", "1")]); + let plan = resolve(&GraphicsSettings::default(), gpu(), &environment, None).unwrap(); + assert_eq!(plan.profiles, ["base"]); + assert!(!plan.settings.contains_key("LEONIDA_PROFILE")); + for (names, expected) in [ + (vec![], vec![]), + (vec!["card-windows".into()], vec!["base", "card-windows"]), + ] { + let settings = GraphicsSettings { + profiles: Some(names), + async_submit: Some(false), + ..Default::default() + }; + let plan = resolve(&settings, gpu(), &environment, None).unwrap(); + assert_eq!(plan.profiles, expected); + assert_eq!(plan.settings["LEONIDA_ASYNC_SUBMIT"], "0"); + } + assert_eq!(environment["LEONIDA_PROFILE"], "1"); + } + + #[test] + fn local_catalog_follows_config_and_can_be_bypassed_for_recovery() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("custom.toml"); + let path = dir.path().join("gpu-profiles.local.json"); + std::fs::write( + &path, + local(json!([ + { "name": "beside-config", "env": { "LEONIDA_INDIRECT_SINGLE": "1" } } + ])), + ) + .unwrap(); + let plan = load( + &GraphicsSettings::default(), + Some(&source), + gpu(), + &env(&[]), + ) + .unwrap(); + assert_eq!(plan.settings["LEONIDA_INDIRECT_SINGLE"], "1"); + std::fs::write(&path, "broken json").unwrap(); + assert!( + load( + &GraphicsSettings::default(), + Some(&source), + gpu(), + &env(&[]) + ) + .is_err() + ); + for value in [ + env(&[("LEONIDA_GRAPHICS_OFF", "1")]), + env(&[("LEONIDA_PROFILE", "none")]), + ] { + let plan = load(&GraphicsSettings::default(), Some(&source), gpu(), &value).unwrap(); + assert!(plan.settings.is_empty()); + } + } + + #[test] + fn matching_uses_vendor_inclusive_vram_bounds_and_name() { + let local = local(json!([ + { "name": "fits", "match": { "vendor": "NVIDIA", "min_vram_mb": 32768, + "max_vram_mb": 32768, "name": "*RTX [45]0?0" }, "env": {} }, + { "name": "small", "match": { "max_vram_mb": 32767 }, "env": {} }, + { "name": "large", "match": { "min_vram_mb": 32769 }, "env": {} }, + { "name": "other", "match": { "vendor": "amd" }, "env": {} }, + { "name": "opt-in", "opt_in": true, "env": { "LEONIDA_INDIRECT_SINGLE": "1" } } + ])); + let plan = resolve(&GraphicsSettings::default(), gpu(), &env(&[]), Some(&local)).unwrap(); + assert_eq!(plan.profiles, ["base", "fits"]); + let plan = resolve( + &GraphicsSettings::default(), + None, + &env(&[("LEONIDA_PROFILE", "OpT-In")]), + Some(&local), + ) + .unwrap(); + assert_eq!(plan.profiles, ["base", "opt-in"]); + assert_eq!(plan.settings["LEONIDA_INDIRECT_SINGLE"], "1"); + } + + #[test] + fn unknown_adapter_only_matches_unqualified_profiles() { + let local = local(json!([ + { "name": "unqualified", "env": {} }, + { "name": "vendor", "match": { "vendor": "other" }, "env": {} }, + { "name": "name", "match": { "name": "*" }, "env": {} }, + { "name": "min", "match": { "min_vram_mb": 0 }, "env": {} }, + { "name": "max", "match": { "max_vram_mb": 99999 }, "env": {} } + ])); + let plan = resolve(&GraphicsSettings::default(), None, &env(&[]), Some(&local)).unwrap(); + assert_eq!(plan.profiles, ["base", "unqualified"]); + } + + #[test] + fn wildcard_syntax_is_case_insensitive_and_checks_whole_names() { + for (pattern, name, expected) in [ + ("", "", true), + ("*", "", true), + ("?", "", false), + ("*RTX [3-5]0?0*", "Nvidia RTX 5090", true), + ("*RTX [3-5]0?0*", "Nvidia RTX 6090", false), + ("RTX", "RTX 5090", false), + ("R?X", "rtx", true), + ("*[[]test]", "card[test]", true), + ("[a-c-]", "-", true), + ("**a*b*c", "aaabbbc", true), + ("*a*b", "ba", false), + ("*É*", "café", true), + ] { + assert_eq!( + wildcard(pattern, name).unwrap(), + expected, + "{pattern:?}, {name:?}" + ); + } + for pattern in ["[", "[]", "[z-a]", "[!a]", "[^a]", "`*"] { + assert!(wildcard(pattern, "anything").is_err(), "{pattern}"); + } + } + + #[test] + fn unknown_profiles_and_invalid_catalog_entries_are_errors() { + assert!( + resolve( + &GraphicsSettings::default(), + gpu(), + &env(&[("LEONIDA_PROFILE", "missing")]), + None + ) + .is_err() + ); + for key in [ + "PATH", + "LEONIDA_CONFIG", + "LEONIDA_GAME_DIR", + "LEONIDA_CACHE_DIR", + "LEONIDA_DATA_DIR", + "LEONIDA_LOG", + "LEONIDA_PROFILE", + "LEONIDA_TEST_TITLES", + "LEONIDA_KEEP_WINDOW", + "LEONIDA_GRAPHICS_OFF", + "LEONIDA_D3D12_WARP", + "LEONIDA_RENDERDOC", + "LEONIDA_RENDERDOC_OUT", + "LEONIDA_RELAUNCHED_FROM", + "LEONIDA_AUDIO_CAPTURE_OF", + "LEONIDA_bad", + "LEONIDA_X=Y", + "LEONIDA_", + ] { + let local = local(json!([{ "name": "bad", "opt_in": true, "env": { (key): "1" } }])); + assert!( + resolve(&GraphicsSettings::default(), gpu(), &env(&[]), Some(&local)).is_err(), + "{key}" + ); + } + for profile in [ + json!({ "name": "", "env": {} }), + json!({ "name": "bad", "env": { "LEONIDA_QUEUE2": "\u{0}" } }), + json!({ "name": "bad", "match": { "min_vram_mb": 2, "max_vram_mb": 1 }, "env": {} }), + json!({ "name": "bad", "match": { "name": "[" }, "env": {} }), + json!({ "name": "bad", "match": { "vendor": "nvida" }, "env": {} }), + json!({ "name": "bad", "opt-in": true, "env": {} }), + ] { + assert!( + resolve( + &GraphicsSettings::default(), + gpu(), + &env(&[]), + Some(&local(json!([profile]))) + ) + .is_err() + ); + } + } + + #[test] + fn toml_ranges_types_and_unknown_fields_are_checked() { + for text in [ + "queue2 = 4", + "card_windows_mb = 17592186044416", + "texture_room_percent = 49", + "texture_room_percent = 98", + "profiles = ['']", + ] { + let settings: GraphicsSettings = toml::from_str(text).unwrap(); + assert!(settings.validate().is_err(), "{text}"); + } + for text in [ + "queue2 = -1", + "async_submit = 1", + "copy_plian = true", + "profiles = 'base'", + ] { + assert!(toml::from_str::(text).is_err(), "{text}"); + } + for text in [ + "queue2 = 0", + "queue2 = 3", + "card_windows_mb = 17592186044415", + "texture_room_percent = 50", + "texture_room_percent = 97", + ] { + toml::from_str::(text) + .unwrap() + .validate() + .unwrap(); + } + } + + #[test] + fn all_toml_switches_have_the_expected_environment_mapping() { + let settings: GraphicsSettings = toml::from_str( + "profiles = []\nasync_submit = false\nqueue2 = 3\nindirect_window = true\n\ + copy_plain = false\njoin_parts = true\nback_own_view = false\n\ + indirect_gather = true\ncard_rehash_runs = false\nwindow_upload = true\n\ + card_windows_mb = 4096\ntexture_room_percent = 97\n", + ) + .unwrap(); + let plan = resolve(&settings, None, &env(&[]), None).unwrap(); + assert_eq!( + plan.settings, + env(&[ + ("LEONIDA_ASYNC_SUBMIT", "0"), + ("LEONIDA_QUEUE2", "3"), + ("LEONIDA_INDIRECT_WINDOW", "1"), + ("LEONIDA_COPY_PLAIN", "0"), + ("LEONIDA_JOIN_PARTS", "1"), + ("LEONIDA_BACK_OWN_VIEW", "0"), + ("LEONIDA_INDIRECT_GATHER", "1"), + ("LEONIDA_CARD_REHASH_RUNS", "0"), + ("LEONIDA_WINDOW_UPLOAD", "1"), + ("LEONIDA_CARD_WINDOWS_MB", "4096"), + ("LEONIDA_TEXTURE_ROOM_PERCENT", "97"), + ]) + ); + assert!(plan.sources.values().all(|source| source == "config")); + let json: serde_json::Value = serde_json::from_str(&plan.to_json().unwrap()).unwrap(); + assert!(json["gpu"].is_null()); + assert_eq!(json["settings"]["LEONIDA_QUEUE2"], "3"); + } + + #[test] + fn environment_snapshot_preserves_empty_and_unicode_values() { + let snapshot = snapshot_from([ + ("leonida_queue2".into(), "".into()), + ("LEONIDA_CAPTURE".into(), "C:/測定".into()), + ("LEONIDA_PROFILE".into(), "base".into()), + ("PATH".into(), "unrelated".into()), + ]) + .unwrap(); + assert_eq!( + snapshot, + env(&[ + ("LEONIDA_QUEUE2", ""), + ("LEONIDA_CAPTURE", "C:/測定"), + ("LEONIDA_PROFILE", "base"), + ]) + ); + } + + #[test] + fn environment_snapshot_rejects_non_unicode_switches() { + #[cfg(unix)] + let bad = { + use std::os::unix::ffi::OsStringExt; + std::ffi::OsString::from_vec(vec![0xff]) + }; + #[cfg(windows)] + let bad = { + use std::os::windows::ffi::OsStringExt; + std::ffi::OsString::from_wide(&[0xd800]) + }; + assert!(snapshot_from([("LEONIDA_QUEUE2".into(), bad.clone())]).is_err()); + assert!(snapshot_from([("LEONIDA_PROFILE".into(), bad.clone())]).is_err()); + // Unrelated variables and paths retain their OS-specific handling. + assert!( + snapshot_from([ + ("PATH".into(), bad.clone()), + ("LEONIDA_GAME_DIR".into(), bad) + ]) + .is_ok() + ); + } +} diff --git a/crates/leonida-core/src/lib.rs b/crates/leonida-core/src/lib.rs index 5cecf8319..b7132e8da 100644 --- a/crates/leonida-core/src/lib.rs +++ b/crates/leonida-core/src/lib.rs @@ -6,6 +6,7 @@ //! * [`logging`]: one tracing setup for all binaries. pub mod config; +pub mod graphics; pub mod logging; pub mod policy; diff --git a/crates/leonida-gpu/src/adapter.rs b/crates/leonida-gpu/src/adapter.rs index 98b14f9b2..b683a2fac 100644 --- a/crates/leonida-gpu/src/adapter.rs +++ b/crates/leonida-gpu/src/adapter.rs @@ -7,6 +7,11 @@ pub struct Description { pub vram_mb: u64, } +#[cfg(windows)] +pub(crate) fn warp_requested() -> bool { + cfg!(feature = "diagnostics") && std::env::var_os("LEONIDA_D3D12_WARP").is_some() +} + /// Describes the adapter that `host::create` will use, without making the host /// device or starting its workers. A failed probe leaves automatic settings /// limited to profiles that do not require a particular card. @@ -24,9 +29,7 @@ pub fn describe() -> Result { // SAFETY: DXGI queries own their returned interfaces; no title pointers // or D3D12 device state are accessed. unsafe { - let adapter: IDXGIAdapter1 = if cfg!(feature = "diagnostics") - && std::env::var_os("LEONIDA_D3D12_WARP").is_some_and(|v| v == "1") - { + let adapter: IDXGIAdapter1 = if warp_requested() { crate::host::warp_adapter()?.cast()? } else { let factory: IDXGIFactory1 = CreateDXGIFactory1()?; @@ -50,3 +53,41 @@ pub fn describe() -> Result { pub fn describe() -> Result { Err("Direct3D adapter discovery requires Windows or Wine".into()) } + +#[cfg(all(test, windows))] +mod tests { + #[test] + #[ignore = "requires a physical Direct3D 12 adapter"] + fn profile_metadata_matches_the_default_hardware_device() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D12::{D3D12CreateDevice, ID3D12Device}; + use windows::Win32::Graphics::Dxgi::*; + + assert!(std::env::var_os("LEONIDA_D3D12_WARP").is_none()); + let selected = super::describe().expect("a physical adapter is required"); + // SAFETY: creates an ordinary default D3D12 device and queries its + // adapter identity. No title code, pointers, commands or assets are used. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).unwrap(); + let device = device.unwrap(); + let factory: IDXGIFactory4 = CreateDXGIFactory1().unwrap(); + let adapter: IDXGIAdapter1 = + factory.EnumAdapterByLuid(device.GetAdapterLuid()).unwrap(); + let actual = adapter.GetDesc1().unwrap(); + assert_eq!(actual.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32, 0); + let end = actual + .Description + .iter() + .position(|&c| c == 0) + .unwrap_or(128); + assert_eq!( + selected.name, + String::from_utf16_lossy(&actual.Description[..end]) + ); + assert_eq!(selected.vendor_id, actual.VendorId); + assert_eq!(selected.vram_mb, (actual.DedicatedVideoMemory as u64) >> 20); + } + eprintln!("graphics adapter: metadata matches the physical default D3D12 device"); + } +} diff --git a/crates/leonida-gpu/src/descriptor/host.rs b/crates/leonida-gpu/src/descriptor/host.rs index 47909fa9a..4b294752c 100644 --- a/crates/leonida-gpu/src/descriptor/host.rs +++ b/crates/leonida-gpu/src/descriptor/host.rs @@ -3509,15 +3509,15 @@ mod tests { let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; assert_eq!(queued, 1); heap.texture_slot_done(1, write, None); - assert_eq!(slots(u64::MAX), []); + assert!(slots(u64::MAX).is_empty()); // Uploaded and out of the queue. Memory elsewhere: nothing. assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); // Under it, counted only: it stays out of the queue. assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); - assert_eq!(slots(u64::MAX), []); + assert!(slots(u64::MAX).is_empty()); // Under it, asked for: due two frames on, not before. assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]); - assert_eq!(slots(61), []); + assert!(slots(61).is_empty()); assert_eq!(slots(62), [1]); } @@ -3589,12 +3589,12 @@ mod tests { let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; assert_eq!(queued, 1); heap.texture_slot_done(1, write, None); - assert_eq!(slots(u64::MAX), []); + assert!(slots(u64::MAX).is_empty()); // Memory elsewhere: nothing. Under the texture: due from the next frame. remapped((at + 2 * len) as usize, 0x1000); remapped(at as usize, 0x1000); assert_eq!(heap.texture_slots_remapped(50), 1); - assert_eq!(slots(50), []); + assert!(slots(50).is_empty()); assert_eq!(slots(51), [1]); // A wider texture written at the same address: slot 1 is stale. assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); @@ -3633,7 +3633,7 @@ mod tests { heap.tabled_in(2, false, frame + 1); assert_eq!(slots(frame + 1), [2]); heap.queue_texture(2, true, false, frame + 2); - assert_eq!(slots(frame + 2), []); + assert!(slots(frame + 2).is_empty()); // Long after the last table, a write is due at once. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); diff --git a/crates/leonida-gpu/src/host.rs b/crates/leonida-gpu/src/host.rs index d9bc03747..07f32b0aa 100644 --- a/crates/leonida-gpu/src/host.rs +++ b/crates/leonida-gpu/src/host.rs @@ -642,7 +642,7 @@ fn create() -> windows::core::Result { // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. - if cfg!(feature = "diagnostics") && std::env::var_os("LEONIDA_D3D12_WARP").is_some() { + if crate::adapter::warp_requested() { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); diff --git a/docs/fork-notes.md b/docs/fork-notes.md index 669a206ff..611636770 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -5,6 +5,39 @@ The status summary is in [README.md](../README.md). ## Newest (2026-11-26) +**U-3: graphics profiles are selected by the executable.** +Direct `leonida run` and translation warm-up now resolve the same measured +base profile that the launch scripts used, before the runtime caches its +switches. The catalog is embedded at build time; an optional +`gpu-profiles.local.json` beside the selected config is applied afterwards. +The base profile still contains the same eight values, and `card-windows` +and the optional one-record clamp remain opt-in. This moves existing +optimizations into direct Windows/Wine launches; it adds no measured FPS gain. + +`[graphics]` in `leonida.toml` provides typed settings for the eleven +options in the catalog. Explicit environment values override TOML, and +TOML overrides profiles. `profiles = []` or `["none"]` disables profile +selection while retaining explicit settings. Named selections include +base and apply in catalog order, with null cancelling earlier profile +values. `LEONIDA_PROFILE` still overrides selection; its existing value +`1` remains the diagnostics CPU sampler and does not select a graphics +profile. Malformed settings and unknown profile names report errors. + +Adapter discovery uses the first DXGI adapter, matching the runtime's +`D3D12CreateDevice(None)`, rather than the scripts' largest-VRAM heuristic. +It respects diagnostics WARP selection and loads an explicitly requested +RenderDoc hook before querying DXGI. If discovery fails, only unqualified +profiles match. Profiles cannot set paths used for config/game/cache/data, +logging, adapter selection, or RenderDoc's startup controls. + +`leonida config --graphics` reports the effective plan and each value's +source as JSON without game files. Launchers use this result for reporting +and let the child apply it. They preserve caller overrides and restore +their temporary environment changes afterwards. `-SpeedSwitches off` +disables both profile and TOML settings through `LEONIDA_GRAPHICS_OFF=1` +and clears runtime overrides, preserving adapter and capture-hook selection. +Shareable switch reports redact paths and other arbitrary string values. + **P-5: less clock work in emulated wait hints.** Each `monitorx` / `mwaitx` pair previously read and converted the performance counter three times: once for each rate-line check and once for wait diff --git a/gpu-profiles.json b/gpu-profiles.json index c590ebab8..b66515fe7 100644 --- a/gpu-profiles.json +++ b/gpu-profiles.json @@ -1,13 +1,13 @@ { "about": [ - "LEONIDA_* switches the run scripts set, by graphics card (scripts/leonida-settings.ps1).", + "LEONIDA_* switches the executable selects by its Direct3D adapter; this catalog is embedded at build time.", "Every profile whose match fits the PC's card is applied, in this order; a later one overrides an earlier one.", - "match: vendor (nvidia, amd, intel), min_vram_mb, max_vram_mb, name (a wildcard on the card's name); empty matches every card.", - "opt_in: true: never applied by its match, only when LEONIDA_PROFILE names it.", - "A value of null unsets the switch. LEONIDA_* switches left in the PowerShell window by earlier runs are cleared first (LEONIDA_KEEP_WINDOW=1 keeps them; paths, LEONIDA_PROFILE and LEONIDA_LOG always stay).", + "match: vendor (nvidia, amd, intel, other), min_vram_mb, max_vram_mb, name (a wildcard on the card's name); empty matches every card.", + "opt_in: true: never applied by its match, only when [graphics].profiles or LEONIDA_PROFILE names it.", + "A value of null cancels an earlier profile value. Explicit environment values override TOML graphics settings, which override profiles.", "Add a profile only with a measurement: the card, the CPU, the scene and the frame times before and after.", - "Your own changes go in gpu-profiles.local.json (same form, applied after this file; git ignores it).", - "LEONIDA_PROFILE=[,...] applies base and those profiles whatever the card; LEONIDA_PROFILE=none applies none." + "Your own changes go in gpu-profiles.local.json beside the selected config (current folder without one); same form, applied after this catalog; git ignores it.", + "LEONIDA_PROFILE=[,...] overrides [graphics].profiles: base and those profiles whatever the card; none disables profiles while keeping explicit settings. The existing value 1 is reserved for the diagnostics CPU sampler." ], "profiles": [ { diff --git a/leonida.example.toml b/leonida.example.toml index 8e51f5f30..f37a556c4 100644 --- a/leonida.example.toml +++ b/leonida.example.toml @@ -18,3 +18,26 @@ # Other Xbox Series titles used to test platform-level code. # env: LEONIDA_TEST_TITLES (separated by ';') test_titles = [] + +# The executable selects the measured profiles automatically, including in Wine. +# Precedence: explicit environment > these settings > selected profiles. +# See the effective values with `leonida config --graphics` (no game needed). +[graphics] +# Omit profiles for automatic selection. [] or ["none"] disables profiles; +# individual settings below still apply. Named profiles also include base. +# profiles = ["base"] + +# Leave a setting commented to use its profile value. false explicitly turns it off. +# async_submit = true # LEONIDA_ASYNC_SUBMIT +# queue2 = 1 # LEONIDA_QUEUE2: 0..3, copy-queue bit mask +# indirect_window = true # LEONIDA_INDIRECT_WINDOW +# copy_plain = true # LEONIDA_COPY_PLAIN +# join_parts = true # LEONIDA_JOIN_PARTS +# back_own_view = true # LEONIDA_BACK_OWN_VIEW +# indirect_gather = true # LEONIDA_INDIRECT_GATHER +# card_rehash_runs = true # LEONIDA_CARD_REHASH_RUNS + +# These experimental settings are NOT enabled automatically. +# card_windows_mb = 0 # LEONIDA_CARD_WINDOWS_MB: limit in MiB, 0 disables +# window_upload = false # LEONIDA_WINDOW_UPLOAD +# texture_room_percent = 90 # LEONIDA_TEXTURE_ROOM_PERCENT: 50..97 diff --git a/measure-gta6.ps1 b/measure-gta6.ps1 index b39c62c08..bfe1161ca 100644 --- a/measure-gta6.ps1 +++ b/measure-gta6.ps1 @@ -19,7 +19,7 @@ param( # yes: warm up the shader cache before starting, no: skip it, ask: ask (default). [ValidateSet('ask', 'yes', 'no')] [string]$WarmUp = 'ask', - # on: the switches gpu-profiles.json picks for this card (default), off: none, ask: ask. + # on: native profiles and graphics settings (default), off: baseline, ask: ask. [ValidateSet('on', 'off', 'ask')] [string]$SpeedSwitches = 'on', # ask: offer a test report when the game closes (default), no: don't. @@ -29,6 +29,9 @@ param( $ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') +$environmentBefore = Save-LeonidaEnvironment + function Test-GameDir([string]$dir) { $dir -ne '' -and (Test-Path -LiteralPath (Join-Path $dir 'MicrosoftGame.config') -PathType Leaf) } @@ -66,27 +69,24 @@ try { } $env:LEONIDA_GAME_DIR = $dir - # The frame-rate switches for this PC's graphics card (gpu-profiles.json). - . (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') - Set-LeonidaProfiles $PSScriptRoot - - # Whatever LEONIDA_* is set now, besides paths and logging, is a speed switch. - $notSwitches = 'LEONIDA_CONFIG', 'LEONIDA_GAME_DIR', 'LEONIDA_CACHE_DIR', 'LEONIDA_DATA_DIR', 'LEONIDA_PROFILE', 'LEONIDA_LOG', 'LEONIDA_KEEP_WINDOW' - $switches = @(Get-ChildItem Env:LEONIDA_* | Where-Object { $_.Name -notin $notSwitches }) if ($SpeedSwitches -eq 'ask') { + $graphics = Get-LeonidaGraphics $exe + Show-LeonidaGraphics $graphics Write-Host '' - Write-Host 'Turn the speed switches on? They are the frame-rate switches measured faster for your card:' - Write-Host (($switches | ForEach-Object { $_.Name -replace '^LEONIDA_', '' }) -join ', ') + Write-Host 'Use the graphics settings selected for this run?' + Write-Host ((Get-LeonidaGraphicsSwitches $graphics -Short) -join ', ') Write-Host 'To help compare, play once with them and once without, in the same place in the game.' $answer = Read-Host 'Speed switches on? [Y/n]' $SpeedSwitches = if ($answer.Trim() -match '^(y|yes)?$') { 'on' } else { 'off' } } if ($SpeedSwitches -eq 'off') { - $switches | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } - $switches = @() + Disable-LeonidaGraphics Write-Host 'speed switches: off' } - $switchList = @($switches | ForEach-Object { '{0}={1}' -f $_.Name, $_.Value }) + # Capture the effective plan before adding diagnostic flags, including native-only settings. + $graphics = Get-LeonidaGraphics $exe + Show-LeonidaGraphics $graphics + $switchList = @(Get-LeonidaGraphicsSwitches $graphics) $env:LEONIDA_FRAME_LOG = '1' $env:LEONIDA_CARD_METER = '1' @@ -123,11 +123,13 @@ try { if ($Report -eq 'ask') { try { & (Join-Path $PSScriptRoot 'scripts\test-report.ps1') -Log $log -SpeedSwitches $switchList ` - -SwitchMode $SpeedSwitches -WarmUp $WarmUp -Started $started -ExitCode "$exitCode" -Exe $exe + -SwitchMode $SpeedSwitches -WarmUp $WarmUp -Started $started ` + -ExitCode "$exitCode" -Exe $exe -Graphics $graphics } catch { Write-Warning "the test report failed: $_" } } } finally { + Restore-LeonidaEnvironment $environmentBefore Pop-Location } diff --git a/run-gta6.ps1 b/run-gta6.ps1 index bfaa38aab..06eaeed07 100644 --- a/run-gta6.ps1 +++ b/run-gta6.ps1 @@ -1,5 +1,5 @@ # Builds Leonida Legacy and starts the game with the frame-rate switches measured to help -# for this PC's graphics card (gpu-profiles.json; all off by default in the code). +# for this PC's graphics card, resolved natively from profiles and leonida.toml. # # The first time, it offers to look for your copy of the game (the folder with # MicrosoftGame.config in it) or asks for that folder (scripts\game-dir.ps1), and offers to @@ -20,6 +20,9 @@ param( $ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') +$environmentBefore = Save-LeonidaEnvironment + function Test-GameDir([string]$dir) { $dir -ne '' -and (Test-Path -LiteralPath (Join-Path $dir 'MicrosoftGame.config') -PathType Leaf) } @@ -57,9 +60,8 @@ try { } $env:LEONIDA_GAME_DIR = $dir - # The frame-rate switches for this PC's graphics card (gpu-profiles.json). - . (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') - Set-LeonidaProfiles $PSScriptRoot + # Show the settings the program will resolve again when it starts. + Show-LeonidaGraphics (Get-LeonidaGraphics $exe) # Shaders not in the cache are translated the first time the game uses them, mid-play. if ($WarmUp -eq 'ask') { @@ -83,5 +85,6 @@ try { & $exe run --execute } finally { + Restore-LeonidaEnvironment $environmentBefore Pop-Location } diff --git a/scripts/leonida-settings.ps1 b/scripts/leonida-settings.ps1 index 00eb0971e..80f281590 100644 --- a/scripts/leonida-settings.ps1 +++ b/scripts/leonida-settings.ps1 @@ -1,81 +1,134 @@ -# The LEONIDA_* switches for this PC's graphics card, from gpu-profiles.json (and -# gpu-profiles.local.json, if there is one). Dot-sourced by the run scripts: -# -# . (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') -# Set-LeonidaProfiles $PSScriptRoot - -# The card with the most memory of its own: name, vendor and memory in MB, from the -# display adapters' registry keys (Win32_VideoController stops counting at 4 GB). -function Get-LeonidaGpu { - $class = 'HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}' - $best = $null - foreach ($key in @(Get-ChildItem -LiteralPath $class -ErrorAction SilentlyContinue)) { - if ($key.PSChildName -notmatch '^\d{4}$') { continue } - $p = Get-ItemProperty -LiteralPath $key.PSPath -ErrorAction SilentlyContinue - if (-not $p -or -not $p.DriverDesc) { continue } - $bytes = [double]0 - $q = $p.'HardwareInformation.qwMemorySize' - $d = $p.'HardwareInformation.MemorySize' - if ($q) { $bytes = [double]$q } - elseif ($d -is [byte[]] -and $d.Length -ge 4) { $bytes = [double][BitConverter]::ToUInt32($d, 0) } - elseif ($d) { $bytes = [double]$d } - $vendor = switch -Regex ([string]$p.MatchingDeviceId) { - 'ven_10de' { 'nvidia'; break } - 'ven_1002' { 'amd'; break } - 'ven_8086' { 'intel'; break } - default { 'other' } +# The program resolves graphics settings, including profiles, leonida.toml and explicit +# environment overrides. Query the same plan for launch messages and measurement reports; +# never copy profile values into this PowerShell window. +function Get-LeonidaGraphics { + [CmdletBinding()] + param([string]$Exe) + if (-not $Exe) { throw 'no leonida executable was supplied for graphics settings' } + $errors = [System.IO.Path]::GetTempFileName() + try { + # Windows PowerShell 5.1 represents native stderr as errors. Keep it separate from + # the JSON and check the native exit code ourselves, including when stderr is used. + $before = $ErrorActionPreference + $encodingBefore = [Console]::OutputEncoding + $ErrorActionPreference = 'Continue' + $PSNativeCommandUseErrorActionPreference = $false + try { + # Rust writes UTF-8; Windows PowerShell otherwise decodes the console code page. + [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) + $out = & $Exe config --graphics 2> $errors + $code = $LASTEXITCODE + } catch { + throw "could not query graphics settings from '$Exe': $_" + } finally { + [Console]::OutputEncoding = $encodingBefore + $ErrorActionPreference = $before + } + $detail = (Get-Content -LiteralPath $errors -Raw -ErrorAction SilentlyContinue) + if ($code -ne 0) { + throw ("leonida config --graphics failed (exit $code); " + + "check leonida.toml and graphics profiles. $detail") + } + try { + $plan = ($out -join "`n") | ConvertFrom-Json -ErrorAction Stop + foreach ($field in 'gpu', 'profiles', 'settings', 'sources') { + if ($field -notin $plan.PSObject.Properties.Name) { throw "missing '$field'" } + } + if ($plan.settings -isnot [pscustomobject] -or $plan.sources -isnot [pscustomobject]) { + throw 'settings and sources must be JSON objects' + } + } catch { + throw ("leonida config --graphics returned invalid JSON settings; " + + "rebuild leonida.exe. $_") } - $gpu = [pscustomobject]@{ Name = [string]$p.DriverDesc; Vendor = $vendor; VramMB = [int]($bytes / 1MB) } - if (-not $best -or $gpu.VramMB -gt $best.VramMB) { $best = $gpu } + if ($detail) { Write-Warning $detail.Trim() } + $plan + } finally { + Remove-Item -LiteralPath $errors -ErrorAction SilentlyContinue } - if (-not $best) { $best = [pscustomobject]@{ Name = 'unknown'; Vendor = 'other'; VramMB = 0 } } - $best } -function Test-LeonidaMatch($match, $gpu) { - if (-not $match) { return $true } - if ($match.vendor -and $match.vendor -ne $gpu.Vendor) { return $false } - if ($match.min_vram_mb -and $gpu.VramMB -lt [int]$match.min_vram_mb) { return $false } - if ($match.max_vram_mb -and $gpu.VramMB -gt [int]$match.max_vram_mb) { return $false } - if ($match.name -and $gpu.Name -notlike $match.name) { return $false } - $true +function Show-LeonidaGraphics($Plan) { + $gpu = $Plan.gpu + $card = if ($gpu) { '{0} ({1}, {2} MB)' -f $gpu.name, $gpu.vendor, $gpu.vram_mb } + else { 'unknown' } + $profiles = if (@($Plan.profiles).Count) { $Plan.profiles -join ', ' } else { 'none' } + Write-Host ("graphics card: {0}; profiles: {1}" -f $card, $profiles) + $kept = @($Plan.sources.PSObject.Properties | Where-Object { $_.Value -eq 'environment' } | + Sort-Object Name | ForEach-Object { $_.Name }) + if ($kept.Count) { Write-Host ("explicit environment overrides: {0}" -f ($kept -join ', ')) } +} + +# Shareable reports show simple switch values only, never paths, hashes or arbitrary text. +# Keep the complete values local in `leonida config --graphics`. +function Format-LeonidaGraphicsSwitch([string]$Name, [string]$Value, [switch]$Short) { + if ($Name -notmatch '\ALEONIDA_[A-Z0-9_]+\z') { return '=' } + $simple = '\A(?:[0-9]{1,10}|0x[0-9a-f]{1,8}|alt|on|off||)\z' + $safe = if ($Value -match $simple) { $Value } + elseif ($Value -eq '') { '' } + else { '' } + if ($Short) { $Name = $Name -replace '^LEONIDA_', '' } + '{0}={1}' -f $Name, $safe } -# Sets the switches of the profiles that fit (or those LEONIDA_PROFILE names) and says -# which they were. -Gpu stands in for the card, for trying a profile out. -function Set-LeonidaProfiles([string]$Root, $Gpu = $null) { - if (-not $Gpu) { $Gpu = Get-LeonidaGpu } - $forced = @() - if ($env:LEONIDA_PROFILE) { $forced = @($env:LEONIDA_PROFILE -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } - $set = [ordered]@{} - $applied = @() - # Switches an earlier run left in this window (this script, play.ps1, by hand) go, so the - # profiles decide; LEONIDA_KEEP_WINDOW=1 keeps them. Paths, LEONIDA_PROFILE and LEONIDA_LOG stay. - $stay = 'LEONIDA_CONFIG', 'LEONIDA_GAME_DIR', 'LEONIDA_CACHE_DIR', 'LEONIDA_DATA_DIR', 'LEONIDA_PROFILE', 'LEONIDA_LOG', 'LEONIDA_KEEP_WINDOW' - if ($env:LEONIDA_KEEP_WINDOW -ne '1') { - Get-ChildItem Env:LEONIDA_* | Where-Object { $_.Name -notin $stay } | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } +# Includes native-only settings and sanitizes values for messages and shareable reports. +function Get-LeonidaGraphicsSwitches($Plan, [switch]$Short) { + $Plan.settings.PSObject.Properties | Sort-Object Name | ForEach-Object { + Format-LeonidaGraphicsSwitch $_.Name $_.Value -Short:$Short } - $files = @(Join-Path $Root 'gpu-profiles.json') - $local = Join-Path $Root 'gpu-profiles.local.json' - if (Test-Path -LiteralPath $local) { $files += $local } - foreach ($file in $files) { - $data = Get-Content -LiteralPath $file -Raw | ConvertFrom-Json - foreach ($p in @($data.profiles)) { - $wanted = if ($forced -contains 'none') { $false } - elseif ($forced.Count -gt 0) { $p.name -eq 'base' -or $forced -contains $p.name } - elseif ($p.opt_in) { $false } - else { Test-LeonidaMatch $p.match $Gpu } - if (-not $wanted) { continue } - foreach ($s in @($p.env.PSObject.Properties)) { $set[$s.Name] = $s.Value } - $applied += $p.name - } +} + +# Launchers change process environment variables, which otherwise survive into another +# script in the same PowerShell window. Restore the caller's values even after a failure. +function Save-LeonidaEnvironment { + $saved = @{} + Get-ChildItem Env:LEONIDA_* | ForEach-Object { $saved[$_.Name] = $_.Value } + $saved +} + +# .NET Framework and older PowerShell versions delete empty values through Env:. +# The Windows API distinguishes an explicit empty override from an absent variable. +function Set-LeonidaEmptyEnvironment([string]$Name) { + if (-not ('LeonidaLauncherEnvironment' -as [type])) { + Add-Type -TypeDefinition @' +using System.Runtime.InteropServices; +public static class LeonidaLauncherEnvironment { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetEnvironmentVariable(string name, string value); +} +'@ } - $kept = @() - foreach ($name in $set.Keys) { - if (Test-Path -LiteralPath "Env:$name") { $kept += $name; continue } - if ($null -ne $set[$name]) { Set-Item -LiteralPath "Env:$name" ([string]$set[$name]) } + if (-not [LeonidaLauncherEnvironment]::SetEnvironmentVariable($Name, '')) { + throw "could not restore empty environment value $Name" + } +} + +function Restore-LeonidaEnvironment([System.Collections.IDictionary]$Before) { + Get-ChildItem Env:LEONIDA_* | Where-Object { -not $Before.Contains($_.Name) } | + ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + foreach ($name in $Before.Keys) { + if ([Environment]::GetEnvironmentVariable($name) -cne $Before[$name]) { + if ($Before[$name] -eq '' -and + [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + Set-LeonidaEmptyEnvironment $name + } else { + Set-Item -LiteralPath "Env:$name" $Before[$name] + } + } } - if ($applied.Count -eq 0) { $applied = @('none') } - Write-Host ("graphics card: {0} ({1}, {2} MB); profiles: {3}" -f $Gpu.Name, $Gpu.Vendor, $Gpu.VramMB, ($applied -join ', ')) - if ($kept.Count -gt 0) { Write-Host ("already set in this window, left as they are: {0}" -f ($kept -join ', ')) } +} + +# A measurement baseline disables both profiles and TOML graphics settings. Explicit +# runtime overrides must also go; paths, logging and early startup controls remain available. +function Disable-LeonidaGraphics { + $stay = 'LEONIDA_CONFIG', 'LEONIDA_GAME_DIR', 'LEONIDA_CACHE_DIR', 'LEONIDA_DATA_DIR', + 'LEONIDA_TEST_TITLES', 'LEONIDA_PROFILE', 'LEONIDA_LOG', 'LEONIDA_KEEP_WINDOW', + 'LEONIDA_GRAPHICS_OFF', 'LEONIDA_D3D12_WARP', 'LEONIDA_RELAUNCHED_FROM', + 'LEONIDA_AUDIO_CAPTURE_OF' + Get-ChildItem Env:LEONIDA_* | Where-Object { + $_.Name -notin $stay -and $_.Name -notlike 'LEONIDA_RENDERDOC*' + } | + ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + $env:LEONIDA_GRAPHICS_OFF = '1' } diff --git a/scripts/measure-run.ps1 b/scripts/measure-run.ps1 index e1159e148..54e5bac3e 100644 --- a/scripts/measure-run.ps1 +++ b/scripts/measure-run.ps1 @@ -33,6 +33,9 @@ param( $ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'leonida-settings.ps1') +$environmentBefore = Save-LeonidaEnvironment + function Get-Median([double[]]$xs) { if ($xs.Count -eq 0) { return [double]::NaN } $s = $xs | Sort-Object @@ -52,10 +55,13 @@ $crashBefore = (@(Get-ChildItem (Join-Path $env:LOCALAPPDATA 'leonida\data\*\cra # leonida.toml is read from the current folder. Push-Location $repo try { - if ($Profile) { $env:LEONIDA_PROFILE = $Profile } else { Remove-Item Env:LEONIDA_PROFILE -ErrorAction SilentlyContinue } - . (Join-Path $PSScriptRoot 'leonida-settings.ps1') - Set-LeonidaProfiles $repo - $switches = @(Get-ChildItem Env:LEONIDA_* | Where-Object { $_.Name -ne 'LEONIDA_PROFILE' } | ForEach-Object { '{0}={1}' -f ($_.Name -replace '^LEONIDA_', ''), $_.Value }) + if ($PSBoundParameters.ContainsKey('Profile')) { + if ($Profile) { $env:LEONIDA_PROFILE = $Profile } + else { Remove-Item Env:LEONIDA_PROFILE -ErrorAction SilentlyContinue } + } + $graphics = Get-LeonidaGraphics $exe + Show-LeonidaGraphics $graphics + $switches = @(Get-LeonidaGraphicsSwitches $graphics -Short) $env:LEONIDA_KEYS = ((0..20) | ForEach-Object { '{0}:Enter' -f (20 + 8 * $_) }) -join ',' $env:LEONIDA_CAPTURE = Join-Path $run 'cap' # Shots a fixed number of frames after the world's first frame; the every-8th-frame world @@ -72,6 +78,7 @@ try { if ($p.WaitForExit($Seconds * 1000)) { $end = "exit $($p.ExitCode)" } else { taskkill /pid $p.Id /t /f | Out-Null; $end = 'timeout (closed)' } $null = $p.WaitForExit(15000) } finally { + Restore-LeonidaEnvironment $environmentBefore Pop-Location } @@ -123,7 +130,7 @@ if ($null -ne $first) { $summary = [ordered]@{ label = $Label - profile = if ($Profile) { $Profile } else { '(by the card only)' } + profile = if (@($graphics.profiles).Count) { $graphics.profiles -join ', ' } else { 'none' } console = $Console end = $end world_at_s = if ($world) { [Math]::Round($world) } else { 'never' } diff --git a/scripts/test-graphics-settings.ps1 b/scripts/test-graphics-settings.ps1 new file mode 100644 index 000000000..e1e2816d7 --- /dev/null +++ b/scripts/test-graphics-settings.ps1 @@ -0,0 +1,189 @@ +# No game files needed. Tests native delegation and measurement baseline handling. +# Supply a built executable to also exercise its real config --graphics JSON interface: +# powershell -File scripts\test-graphics-settings.ps1 -Exe target\release\leonida.exe +param([string]$Exe = '') + +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'leonida-settings.ps1') + +function Assert-Graphics($Condition, [string]$Message) { + if (-not $Condition) { throw $Message } +} + +function Assert-GraphicsThrows([scriptblock]$Action, [string]$Pattern) { + try { & $Action | Out-Null } + catch { + Assert-Graphics ("$_" -match $Pattern) "unexpected error: $_" + return + } + throw "expected an error matching: $Pattern" +} + +# This command stands in for the native executable. It deliberately provides profile and +# TOML values absent from Env:, so reading only the PowerShell environment cannot pass. +function Invoke-SyntheticLeonida { + Assert-Graphics (($args -join ' ') -eq 'config --graphics') 'wrong native command' + Set-Variable -Name LASTEXITCODE -Value 0 -Scope 1 + if ($script:queryMode -eq 'invalid') { 'not JSON'; return } + if ($script:queryMode -eq 'failure') { + Write-Error 'synthetic configuration error' -ErrorAction Continue + Set-Variable -Name LASTEXITCODE -Value 19 -Scope 1 + return + } + if ($script:queryMode -eq 'stderr') { + Write-Error 'synthetic native warning' -ErrorAction Continue + } + $settings = [ordered]@{} + $sources = [ordered]@{} + $profiles = @() + if ($env:LEONIDA_GRAPHICS_OFF -ne '1') { + $profiles = @('base', 'synthetic') + $settings['LEONIDA_COPY_PLAIN'] = '1' + $sources['LEONIDA_COPY_PLAIN'] = 'profile:base' + $settings['LEONIDA_JOIN_PARTS'] = '0' + $sources['LEONIDA_JOIN_PARTS'] = 'config' + } + if (Test-Path Env:LEONIDA_ASYNC_SUBMIT) { + $settings['LEONIDA_ASYNC_SUBMIT'] = $env:LEONIDA_ASYNC_SUBMIT + $sources['LEONIDA_ASYNC_SUBMIT'] = 'environment' + } + [ordered]@{ gpu = $null; profiles = $profiles; settings = $settings; sources = $sources } | + ConvertTo-Json -Depth 4 +} + +$saved = @{} +Get-ChildItem Env:LEONIDA_* | ForEach-Object { $saved[$_.Name] = $_.Value } +$temporary = Join-Path ([IO.Path]::GetTempPath()) ('leonida-graphics-test-' + [guid]::NewGuid()) +try { + Get-ChildItem Env:LEONIDA_* | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + $script:queryMode = 'valid' + $env:LEONIDA_ASYNC_SUBMIT = '0' + $encodingBefore = [Console]::OutputEncoding.CodePage + $plan = Get-LeonidaGraphics 'Invoke-SyntheticLeonida' + Assert-Graphics ([Console]::OutputEncoding.CodePage -eq $encodingBefore) ` + 'native query changed the caller console encoding' + Assert-Graphics ($plan.profiles -join ',' -eq 'base,synthetic') 'native profiles were lost' + Assert-Graphics ($env:LEONIDA_ASYNC_SUBMIT -eq '0') 'explicit override was changed' + Assert-Graphics (-not (Test-Path Env:LEONIDA_COPY_PLAIN)) 'profile leaked into the shell' + $switches = @(Get-LeonidaGraphicsSwitches $plan) + Assert-Graphics ($switches -contains 'LEONIDA_COPY_PLAIN=1') 'profile missing from report' + Assert-Graphics ($switches -contains 'LEONIDA_JOIN_PARTS=0') 'TOML setting missing from report' + Assert-Graphics ($switches -contains 'LEONIDA_ASYNC_SUBMIT=0') 'override missing from report' + Assert-Graphics (@(Get-LeonidaGraphicsSwitches $plan -Short) -contains 'JOIN_PARTS=0') ` + 'short measurement report is wrong' + $shown = (Show-LeonidaGraphics $plan 6>&1 | ForEach-Object { "$_" }) -join ' ' + Assert-Graphics ($shown -match 'graphics card: unknown') 'missing adapter is not handled' + Assert-Graphics ($shown -match 'base, synthetic') 'selected profiles are not displayed' + Assert-Graphics ($shown -match 'LEONIDA_ASYNC_SUBMIT') 'explicit overrides are not displayed' + + $private = 'C:\Users\Private\captures\frame.png' + $plan.settings | Add-Member -NotePropertyName LEONIDA_CAPTURE -NotePropertyValue $private + $reported = (Get-LeonidaGraphicsSwitches $plan) -join ' ' + Assert-Graphics ($reported -match 'LEONIDA_CAPTURE=') 'capture path was not redacted' + Assert-Graphics ($reported -notmatch 'Private|captures|frame.png') 'report contains a path' + foreach ($value in @($private, 'private-name', '0123456789abcdef0123456789abcdef', '1,2,3')) { + Assert-Graphics ((Format-LeonidaGraphicsSwitch 'LEONIDA_SHOT' $value) -eq + 'LEONIDA_SHOT=') 'direct report value was not redacted' + } + Assert-Graphics ((Format-LeonidaGraphicsSwitch $private '1') -notmatch 'Private') ` + 'an invalid switch name leaked into the report' + foreach ($value in '0', '1', '3072', '0x10', 'alt', 'on', 'off') { + Assert-Graphics ((Format-LeonidaGraphicsSwitch 'LEONIDA_QUEUE2' $value) -eq + "LEONIDA_QUEUE2=$value") 'safe switch value was lost' + } + + $prior = Save-LeonidaEnvironment + $env:LEONIDA_ASYNC_SUBMIT = '1' + $env:LEONIDA_FRAME_LOG = '1' + Restore-LeonidaEnvironment $prior + Assert-Graphics ($env:LEONIDA_ASYNC_SUBMIT -eq '0') 'caller override was not restored' + Assert-Graphics (-not (Test-Path Env:LEONIDA_FRAME_LOG)) ` + 'diagnostic switch leaked after restore' + + if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + Set-LeonidaEmptyEnvironment 'LEONIDA_EMPTY_TEST' + $prior = Save-LeonidaEnvironment + Disable-LeonidaGraphics + Restore-LeonidaEnvironment $prior + Assert-Graphics (Test-Path Env:LEONIDA_EMPTY_TEST) 'empty caller override was deleted' + Assert-Graphics ([Environment]::GetEnvironmentVariable('LEONIDA_EMPTY_TEST') -ceq '') ` + 'empty caller override changed value' + Remove-Item Env:LEONIDA_EMPTY_TEST + } + + $script:queryMode = 'stderr' + $plan = Get-LeonidaGraphics 'Invoke-SyntheticLeonida' -WarningAction SilentlyContinue + Assert-Graphics ($plan.settings.LEONIDA_COPY_PLAIN -eq '1') 'stderr corrupted native JSON' + $script:queryMode = 'invalid' + Assert-GraphicsThrows { Get-LeonidaGraphics 'Invoke-SyntheticLeonida' } 'invalid JSON' + $script:queryMode = 'failure' + Assert-GraphicsThrows { Get-LeonidaGraphics 'Invoke-SyntheticLeonida' } 'exit 19' + $script:queryMode = 'valid' + + $controls = 'CONFIG', 'GAME_DIR', 'CACHE_DIR', 'DATA_DIR', 'TEST_TITLES', 'PROFILE', + 'LOG', 'KEEP_WINDOW', 'D3D12_WARP', 'RELAUNCHED_FROM', 'AUDIO_CAPTURE_OF', + 'RENDERDOC', 'RENDERDOC_OUT', 'RENDERDOC_AT', 'RENDERDOC_FUTURE_OPTION' + foreach ($name in $controls) { Set-Item -LiteralPath "Env:LEONIDA_$name" "preserved-$name" } + $env:LEONIDA_UNLISTED_RUNTIME_SWITCH = '1' + $prior = Save-LeonidaEnvironment + Disable-LeonidaGraphics + Assert-Graphics ($env:LEONIDA_GRAPHICS_OFF -eq '1') 'baseline did not disable native profiles' + Assert-Graphics (-not (Test-Path Env:LEONIDA_ASYNC_SUBMIT)) 'baseline kept an override' + Assert-Graphics (-not (Test-Path Env:LEONIDA_UNLISTED_RUNTIME_SWITCH)) ` + 'baseline kept a runtime switch' + foreach ($name in $controls) { + Assert-Graphics ((Get-Item -LiteralPath "Env:LEONIDA_$name").Value -eq "preserved-$name") ` + "baseline removed control $name" + } + $plan = Get-LeonidaGraphics 'Invoke-SyntheticLeonida' + Assert-Graphics (@($plan.profiles).Count -eq 0) 'baseline still selected profiles' + Assert-Graphics (@(Get-LeonidaGraphicsSwitches $plan).Count -eq 0) ` + 'baseline report is not empty' + + Restore-LeonidaEnvironment $prior + Assert-Graphics ($env:LEONIDA_ASYNC_SUBMIT -eq '0') 'baseline lost the caller override' + Assert-Graphics (-not (Test-Path Env:LEONIDA_GRAPHICS_OFF)) 'baseline leaked into the next run' + + if ($Exe) { + $Exe = (Resolve-Path -LiteralPath $Exe).Path + Get-ChildItem Env:LEONIDA_* | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + [IO.Directory]::CreateDirectory($temporary) | Out-Null + $env:LEONIDA_CONFIG = Join-Path $temporary 'leonida.toml' + [IO.File]::WriteAllText($env:LEONIDA_CONFIG, '') + $env:LEONIDA_CACHE_DIR = Join-Path $temporary 'cache' + $env:LEONIDA_DATA_DIR = Join-Path $temporary 'data' + $env:LEONIDA_PROFILE = 'none' + $env:LEONIDA_ASYNC_SUBMIT = '0' + Push-Location $temporary + try { + $plan = Get-LeonidaGraphics $Exe + Assert-Graphics (@($plan.profiles).Count -eq 0) 'native profile=none was ignored' + Assert-Graphics ($plan.settings.LEONIDA_ASYNC_SUBMIT -eq '0') 'native override was lost' + Assert-Graphics ($plan.sources.LEONIDA_ASYNC_SUBMIT -eq 'environment') ` + 'wrong native source' + # Construct non-ASCII text without requiring a BOM in this PowerShell 5.1 script. + $unicodeName = 'test-' + [char]0x6e2c + [char]0x5b9a + $catalog = @{ profiles = @(@{ + name = $unicodeName; opt_in = $true; env = @{ LEONIDA_QUEUE2 = '2' } + }) } | ConvertTo-Json -Depth 4 + [IO.File]::WriteAllText((Join-Path $temporary 'gpu-profiles.local.json'), $catalog) + $env:LEONIDA_PROFILE = $unicodeName + $plan = Get-LeonidaGraphics $Exe + Assert-Graphics ($plan.profiles -contains $unicodeName) ` + 'native Unicode profile was corrupted' + Assert-Graphics ($plan.sources.LEONIDA_QUEUE2 -ceq "profile:$unicodeName") ` + 'native Unicode source was corrupted' + Remove-Item Env:LEONIDA_PROFILE + Disable-LeonidaGraphics + $plan = Get-LeonidaGraphics $Exe + Assert-Graphics (@($plan.profiles).Count -eq 0) 'native baseline enabled a profile' + Assert-Graphics (@(Get-LeonidaGraphicsSwitches $plan).Count -eq 0) ` + 'native baseline is not empty' + } finally { Pop-Location } + Write-Host 'real native graphics query: passed' + } + Write-Host 'graphics launcher checks: passed' +} finally { + Restore-LeonidaEnvironment $saved + if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Recurse -Force } +} diff --git a/scripts/test-report.ps1 b/scripts/test-report.ps1 index 4cd84462c..e5fdc4931 100644 --- a/scripts/test-report.ps1 +++ b/scripts/test-report.ps1 @@ -20,12 +20,20 @@ param( [datetime]$Started = [datetime]::MinValue, [string]$ExitCode = '', # leonida.exe, to find the data folder (crashes.log) with `leonida config`. - [string]$Exe = '' + [string]$Exe = '', + # The pre-launch native plan, when called by measure-gta6.ps1. + $Graphics = $null ) $ErrorActionPreference = 'Stop' $root = Split-Path -Parent $PSScriptRoot . (Join-Path $PSScriptRoot 'leonida-settings.ps1') +if (-not $Exe) { + foreach ($build in 'diag', 'release') { + $candidate = Join-Path $root "target\$build\leonida.exe" + if (Test-Path -LiteralPath $candidate) { $Exe = $candidate; break } + } +} $server = '1574773017114841229' $channel = '1575267731857739916' @@ -150,15 +158,23 @@ $where = Limit-Text (Read-Host 'Where in the game were you at the end (for examp $issue = Limit-Text (Read-Host 'Anything wrong (crash, missing textures, flashing, sound)?').Trim() 600 if ($Started -eq [datetime]::MinValue) { $Started = (Get-Item -LiteralPath $Log).CreationTime } -$gpu = Get-LeonidaGpu +if (-not $Graphics -and $Exe) { + Push-Location $root + try { $Graphics = Get-LeonidaGraphics $Exe } + catch { Write-Warning "graphics card could not be queried: $_" } + finally { Pop-Location } +} +$gpu = if ($Graphics -and $Graphics.gpu) { $Graphics.gpu } + else { [pscustomobject]@{ name = 'unknown'; vendor = 'other'; vram_mb = 0 } } $cpu = ([string]@(Get-CimInstance Win32_Processor)[0].Name).Trim() $ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB) $os = (Get-CimInstance Win32_OperatingSystem).Caption -replace '^Microsoft\s+', '' $nt = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' $names = @($SpeedSwitches | Where-Object { $_ } | ForEach-Object { $name, $value = $_ -split '=', 2 - $short = $name -replace '^LEONIDA_', '' - if ($value -eq '1') { $short } else { "$short=$value" } + # Direct callers can supply raw values too: never copy paths into the shared report. + $safe = Format-LeonidaGraphicsSwitch $name $value -Short + if ($safe -match '^([^=]+)=1$') { $Matches[1] } else { $safe } }) $switchText = $SwitchMode if ($names.Count -gt 0) { $switchText += ': ' + ($names -join ', ') } @@ -170,7 +186,7 @@ $crashed = Test-CrashWritten $Exe $Started $lines = @( '**Leonida Legacy test report**' - "GPU: $($gpu.Name), $($gpu.VramMB) MB" + "GPU: $($gpu.name), $($gpu.vram_mb) MB" "Driver: $(Get-DriverVersion $gpu.Name)" "CPU: $cpu" "RAM: $ram GB" diff --git a/shot-run.ps1 b/shot-run.ps1 index ca78e84da..86b6b2019 100644 --- a/shot-run.ps1 +++ b/shot-run.ps1 @@ -18,6 +18,9 @@ param( $ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') +$environmentBefore = Save-LeonidaEnvironment + Push-Location $PSScriptRoot try { cargo build --profile diag -p leonida --features diagnostics @@ -33,9 +36,8 @@ try { New-Item -ItemType Directory -Force $run | Out-Null $wanted = @($ShotAt -split ',' | Where-Object { $_.Trim() -ne '' }).Count - # The frame-rate switches for this PC's graphics card (gpu-profiles.json). - . (Join-Path $PSScriptRoot 'scripts\leonida-settings.ps1') - Set-LeonidaProfiles $PSScriptRoot + # Show the settings the program will resolve again when it starts. + Show-LeonidaGraphics (Get-LeonidaGraphics $exe) $env:LEONIDA_SHOT = $run $env:LEONIDA_SHOT_AT = $ShotAt if ($Keys -ne '') { $env:LEONIDA_KEYS = $Keys } @@ -55,5 +57,6 @@ try { $done = @(Get-ChildItem -Path $run -Recurse -Filter 'done' -ErrorAction SilentlyContinue).Count Write-Host "$done of $wanted shot(s) written to $run" } finally { + Restore-LeonidaEnvironment $environmentBefore Pop-Location } From 7d3a884fdb4397132dee3ac7377226642ef3fb32 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:45:25 -0800 Subject: [PATCH 3/4] fix(launcher): preserve empty Windows environment overrides --- scripts/leonida-settings.ps1 | 27 +++++++++++++------- scripts/test-graphics-settings.ps1 | 41 +++++++++++++++++++++++++----- 2 files changed, 52 insertions(+), 16 deletions(-) diff --git a/scripts/leonida-settings.ps1 b/scripts/leonida-settings.ps1 index 80f281590..f64b9f5c6 100644 --- a/scripts/leonida-settings.ps1 +++ b/scripts/leonida-settings.ps1 @@ -82,7 +82,12 @@ function Get-LeonidaGraphicsSwitches($Plan, [switch]$Short) { # script in the same PowerShell window. Restore the caller's values even after a failure. function Save-LeonidaEnvironment { $saved = @{} - Get-ChildItem Env:LEONIDA_* | ForEach-Object { $saved[$_.Name] = $_.Value } + # .NET Framework's single-variable getter (also used by Env:) can mistake an + # existing empty value for a missing one after a stale Win32 error. The full + # environment block preserves both presence and value without that lookup. + foreach ($entry in [Environment]::GetEnvironmentVariables().GetEnumerator()) { + if ($entry.Key -like 'LEONIDA_*') { $saved[$entry.Key] = $entry.Value } + } $saved } @@ -105,15 +110,17 @@ public static class LeonidaLauncherEnvironment { } function Restore-LeonidaEnvironment([System.Collections.IDictionary]$Before) { - Get-ChildItem Env:LEONIDA_* | Where-Object { -not $Before.Contains($_.Name) } | - ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + $current = Save-LeonidaEnvironment + foreach ($name in $current.Keys) { + if (-not $Before.Contains($name)) { [Environment]::SetEnvironmentVariable($name, $null) } + } foreach ($name in $Before.Keys) { - if ([Environment]::GetEnvironmentVariable($name) -cne $Before[$name]) { + if (-not $current.Contains($name) -or $current[$name] -cne $Before[$name]) { if ($Before[$name] -eq '' -and [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { Set-LeonidaEmptyEnvironment $name } else { - Set-Item -LiteralPath "Env:$name" $Before[$name] + [Environment]::SetEnvironmentVariable($name, $Before[$name]) } } } @@ -126,9 +133,11 @@ function Disable-LeonidaGraphics { 'LEONIDA_TEST_TITLES', 'LEONIDA_PROFILE', 'LEONIDA_LOG', 'LEONIDA_KEEP_WINDOW', 'LEONIDA_GRAPHICS_OFF', 'LEONIDA_D3D12_WARP', 'LEONIDA_RELAUNCHED_FROM', 'LEONIDA_AUDIO_CAPTURE_OF' - Get-ChildItem Env:LEONIDA_* | Where-Object { - $_.Name -notin $stay -and $_.Name -notlike 'LEONIDA_RENDERDOC*' - } | - ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + $current = Save-LeonidaEnvironment + foreach ($name in $current.Keys) { + if ($name -notin $stay -and $name -notlike 'LEONIDA_RENDERDOC*') { + [Environment]::SetEnvironmentVariable($name, $null) + } + } $env:LEONIDA_GRAPHICS_OFF = '1' } diff --git a/scripts/test-graphics-settings.ps1 b/scripts/test-graphics-settings.ps1 index e1e2816d7..f00e9b7f0 100644 --- a/scripts/test-graphics-settings.ps1 +++ b/scripts/test-graphics-settings.ps1 @@ -51,11 +51,10 @@ function Invoke-SyntheticLeonida { ConvertTo-Json -Depth 4 } -$saved = @{} -Get-ChildItem Env:LEONIDA_* | ForEach-Object { $saved[$_.Name] = $_.Value } +$saved = Save-LeonidaEnvironment $temporary = Join-Path ([IO.Path]::GetTempPath()) ('leonida-graphics-test-' + [guid]::NewGuid()) try { - Get-ChildItem Env:LEONIDA_* | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + Restore-LeonidaEnvironment @{} $script:queryMode = 'valid' $env:LEONIDA_ASYNC_SUBMIT = '0' $encodingBefore = [Console]::OutputEncoding.CodePage @@ -102,13 +101,27 @@ try { if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { Set-LeonidaEmptyEnvironment 'LEONIDA_EMPTY_TEST' + # Leave ERROR_ENVVAR_NOT_FOUND behind, which makes Framework's single-variable + # getter unreliable for empty values. Check the complete environment block instead. + $null = [Environment]::GetEnvironmentVariable('LEONIDA_NO_SUCH_EMPTY_TEST') $prior = Save-LeonidaEnvironment + Assert-Graphics ($prior.Contains('LEONIDA_EMPTY_TEST')) 'snapshot lost an empty override' + Assert-Graphics ($prior['LEONIDA_EMPTY_TEST'] -ceq '') 'snapshot changed an empty override' Disable-LeonidaGraphics + $actual = [Environment]::GetEnvironmentVariables() + Assert-Graphics (-not $actual.Contains('LEONIDA_EMPTY_TEST')) ` + 'baseline kept an empty runtime override' Restore-LeonidaEnvironment $prior - Assert-Graphics (Test-Path Env:LEONIDA_EMPTY_TEST) 'empty caller override was deleted' - Assert-Graphics ([Environment]::GetEnvironmentVariable('LEONIDA_EMPTY_TEST') -ceq '') ` + $actual = [Environment]::GetEnvironmentVariables() + Assert-Graphics ($actual.Contains('LEONIDA_EMPTY_TEST')) 'empty caller override was deleted' + Assert-Graphics ($actual['LEONIDA_EMPTY_TEST'] -ceq '') ` 'empty caller override changed value' - Remove-Item Env:LEONIDA_EMPTY_TEST + Set-LeonidaEmptyEnvironment 'LEONIDA_NEW_EMPTY_TEST' + Restore-LeonidaEnvironment $prior + $actual = [Environment]::GetEnvironmentVariables() + Assert-Graphics (-not $actual.Contains('LEONIDA_NEW_EMPTY_TEST')) ` + 'new empty override survived restoration' + [Environment]::SetEnvironmentVariable('LEONIDA_EMPTY_TEST', $null) } $script:queryMode = 'stderr' @@ -146,7 +159,7 @@ try { if ($Exe) { $Exe = (Resolve-Path -LiteralPath $Exe).Path - Get-ChildItem Env:LEONIDA_* | ForEach-Object { Remove-Item -LiteralPath "Env:$($_.Name)" } + Restore-LeonidaEnvironment @{} [IO.Directory]::CreateDirectory($temporary) | Out-Null $env:LEONIDA_CONFIG = Join-Path $temporary 'leonida.toml' [IO.File]::WriteAllText($env:LEONIDA_CONFIG, '') @@ -173,6 +186,20 @@ try { 'native Unicode profile was corrupted' Assert-Graphics ($plan.sources.LEONIDA_QUEUE2 -ceq "profile:$unicodeName") ` 'native Unicode source was corrupted' + if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { + Set-LeonidaEmptyEnvironment 'LEONIDA_ASYNC_SUBMIT' + $prior = Save-LeonidaEnvironment + Disable-LeonidaGraphics + Restore-LeonidaEnvironment $prior + $plan = Get-LeonidaGraphics $Exe + $names = $plan.settings.PSObject.Properties.Name + Assert-Graphics ('LEONIDA_ASYNC_SUBMIT' -in $names) ` + 'native child did not inherit the restored empty override' + Assert-Graphics ($plan.settings.LEONIDA_ASYNC_SUBMIT -ceq '') ` + 'native child inherited the wrong empty override value' + Assert-Graphics ($plan.sources.LEONIDA_ASYNC_SUBMIT -eq 'environment') ` + 'native child did not treat the empty override as explicit' + } Remove-Item Env:LEONIDA_PROFILE Disable-LeonidaGraphics $plan = Get-LeonidaGraphics $Exe From 52d6ad6eeef160244fb1d402ef3a064fb3f3e308 Mon Sep 17 00:00:00 2001 From: John Reed <87283488+JohnReedV@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:51:01 -0800 Subject: [PATCH 4/4] fix(launcher): delete overrides consistently across PowerShell versions --- docs/fork-notes.md | 19 ++++++++++++++++++- scripts/leonida-settings.ps1 | 7 +++++-- scripts/test-graphics-settings.ps1 | 3 ++- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/docs/fork-notes.md b/docs/fork-notes.md index c86f58f40..a5557154b 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -12,7 +12,8 @@ switches. The catalog is embedded at build time; an optional `gpu-profiles.local.json` beside the selected config is applied afterwards. The base profile still contains the same eight values, and `card-windows` and the optional one-record clamp remain opt-in. This moves existing -optimizations into direct Windows/Wine launches; it adds no measured FPS gain. +optimizations into direct Windows/Wine launches. No new gameplay frame-rate +measurement is claimed. `[graphics]` in `leonida.toml` provides typed settings for the eleven options in the catalog. Explicit environment values override TOML, and @@ -38,6 +39,22 @@ disables both profile and TOML settings through `LEONIDA_GRAPHICS_OFF=1` and clears runtime overrides, preserving adapter and capture-hook selection. Shareable switch reports redact paths and other arbitrary string values. +Validation uses original synthetic inputs: 32 core tests and 13 default / +14 diagnostics CLI integration tests, run on native Windows and through +Wine. Each integration suite runs three generated PE programs through the +real loader, checking that profile, TOML and environment values reach the +title. The PowerShell checks also cover Unicode profile names, empty +overrides, state restoration, report redaction and baseline selection. +They inspect the complete environment block: Windows PowerShell 5.1's +single-variable lookup can mistake an empty value for an absent one. + +On an Intel Core i9-14900KS / RTX 5090, NVIDIA 580.173.02, Pop!_OS 22.04 +and Proton 11's Wine 11.0 in Steam's offline Flatpak runtime, the physical +adapter parity test passed and a direct CLI query selected exactly the +eight base settings. DXVK reports an AMD vendor ID for this NVIDIA card; +profiles intentionally use the adapter identity exposed to Direct3D. +No game files were used in these checks. + **P-5: less clock work in emulated wait hints.** Each `monitorx` / `mwaitx` pair previously read and converted the performance counter three times: once for each rate-line check and once for wait diff --git a/scripts/leonida-settings.ps1 b/scripts/leonida-settings.ps1 index f64b9f5c6..2b0dda7e0 100644 --- a/scripts/leonida-settings.ps1 +++ b/scripts/leonida-settings.ps1 @@ -112,7 +112,10 @@ public static class LeonidaLauncherEnvironment { function Restore-LeonidaEnvironment([System.Collections.IDictionary]$Before) { $current = Save-LeonidaEnvironment foreach ($name in $current.Keys) { - if (-not $Before.Contains($name)) { [Environment]::SetEnvironmentVariable($name, $null) } + if (-not $Before.Contains($name)) { + # Plain $null binds as an empty string, which .NET 9+ preserves. + [Environment]::SetEnvironmentVariable($name, [NullString]::Value) + } } foreach ($name in $Before.Keys) { if (-not $current.Contains($name) -or $current[$name] -cne $Before[$name]) { @@ -136,7 +139,7 @@ function Disable-LeonidaGraphics { $current = Save-LeonidaEnvironment foreach ($name in $current.Keys) { if ($name -notin $stay -and $name -notlike 'LEONIDA_RENDERDOC*') { - [Environment]::SetEnvironmentVariable($name, $null) + [Environment]::SetEnvironmentVariable($name, [NullString]::Value) } } $env:LEONIDA_GRAPHICS_OFF = '1' diff --git a/scripts/test-graphics-settings.ps1 b/scripts/test-graphics-settings.ps1 index f00e9b7f0..c84f4c59d 100644 --- a/scripts/test-graphics-settings.ps1 +++ b/scripts/test-graphics-settings.ps1 @@ -55,6 +55,7 @@ $saved = Save-LeonidaEnvironment $temporary = Join-Path ([IO.Path]::GetTempPath()) ('leonida-graphics-test-' + [guid]::NewGuid()) try { Restore-LeonidaEnvironment @{} + Assert-Graphics ((Save-LeonidaEnvironment).Count -eq 0) 'cleanup left empty environment values' $script:queryMode = 'valid' $env:LEONIDA_ASYNC_SUBMIT = '0' $encodingBefore = [Console]::OutputEncoding.CodePage @@ -121,7 +122,7 @@ try { $actual = [Environment]::GetEnvironmentVariables() Assert-Graphics (-not $actual.Contains('LEONIDA_NEW_EMPTY_TEST')) ` 'new empty override survived restoration' - [Environment]::SetEnvironmentVariable('LEONIDA_EMPTY_TEST', $null) + [Environment]::SetEnvironmentVariable('LEONIDA_EMPTY_TEST', [NullString]::Value) } $script:queryMode = 'stderr'