From 3bde492368c19f826a03a6efe218dc5e585832a6 Mon Sep 17 00:00:00 2001 From: ArnoX5 Date: Tue, 1 Dec 2026 05:39:16 +0530 Subject: [PATCH] UI: anti-aliased Segoe UI/Consolas F1 menu and slim F3 stats panel --- crates/victory-gpu/src/host/font.rs | 423 ++++- crates/victory-gpu/src/host/menu.rs | 2446 +++++--------------------- crates/victory-gpu/src/host/panel.rs | 800 +++------ 3 files changed, 1168 insertions(+), 2501 deletions(-) diff --git a/crates/victory-gpu/src/host/font.rs b/crates/victory-gpu/src/host/font.rs index 6cd704fa3..3578e4f10 100644 --- a/crates/victory-gpu/src/host/font.rs +++ b/crates/victory-gpu/src/host/font.rs @@ -1,11 +1,421 @@ -//! The dot letters the stats panel (`panel.rs`, diagnostics builds) and the settings menu -//! (`menu.rs`, every build) are written with, and the pixels they are painted in. +//! Smooth anti-aliased GDI canvas renderer (Vice City theme) for the F1 settings +//! menu (`menu.rs`), F2 advisor, and F3 stats panel (`panel.rs`), plus the legacy +//! 5x7 glyph table kept for compatibility with upstream helpers and tests. +use std::ffi::c_void; use windows::Win32::Graphics::Dxgi::Common::*; -/// Seven rows of five dots, the leftmost the highest bit. +/// RGB tuple (0..=255). +pub(super) type Rgb = (u8, u8, u8); + +/// Refined Vice City color palette. +pub(super) mod theme { + use super::Rgb; + pub const BG: Rgb = (17, 13, 28); // #110D1C deep twilight plum + pub const BORDER: Rgb = (58, 43, 82); // #3A2B52 subtle card border + pub const DIVIDER: Rgb = (42, 32, 61); // #2A203D section divider + pub const ROW_HI: Rgb = (35, 26, 56); // #231A38 active row highlight + pub const GRAPH_BG: Rgb = (24, 18, 40); // #181228 sparkline track + pub const PINK: Rgb = (255, 79, 163); // #FF4FA3 Vice neon pink + pub const CYAN: Rgb = (92, 235, 255); // #5CEBFF Vice electric cyan + pub const MINT: Rgb = (92, 255, 184); // #5CFFB8 active / ON / FG + pub const AMBER: Rgb = (255, 184, 92); // #FFB85C changed (*) / notice + pub const CORAL: Rgb = (255, 110, 140); // #FF6E8C warning / dropped > 0 + pub const TEXT: Rgb = (232, 226, 244); // #E8E2F4 crisp off-white + pub const LABEL: Rgb = (198, 190, 218); // #C6BEDA secondary label + pub const MUTED: Rgb = (146, 136, 172); // #9288AC hints / OFF / footer + pub const SHADOW: Rgb = (5, 3, 10); // #05030A 1px drop shadow +} + +#[repr(C)] +struct BitmapInfoHeader { + bi_size: u32, + bi_width: i32, + bi_height: i32, + bi_planes: u16, + bi_bit_count: u16, + bi_compression: u32, + bi_size_image: u32, + bi_x_pels_per_meter: i32, + bi_y_pels_per_meter: i32, + bi_clr_used: u32, + bi_clr_important: u32, +} + +#[repr(C)] +struct BitmapInfo { + header: BitmapInfoHeader, + colors: [u32; 1], +} + +#[repr(C)] +struct GdiSize { + cx: i32, + cy: i32, +} + +#[link(name = "gdi32")] +unsafe extern "system" { + fn CreateCompatibleDC(hdc: *mut c_void) -> *mut c_void; + fn DeleteDC(hdc: *mut c_void) -> i32; + fn CreateDIBSection( + hdc: *mut c_void, + pbmi: *const BitmapInfo, + usage: u32, + ppv_bits: *mut *mut c_void, + hsection: *mut c_void, + offset: u32, + ) -> *mut c_void; + fn SelectObject(hdc: *mut c_void, h: *mut c_void) -> *mut c_void; + fn DeleteObject(ho: *mut c_void) -> i32; + fn CreateFontW( + height: i32, + width: i32, + escapement: i32, + orientation: i32, + weight: i32, + italic: u32, + underline: u32, + strikeout: u32, + charset: u32, + out_prec: u32, + clip_prec: u32, + quality: u32, + pitch_family: u32, + face: *const u16, + ) -> *mut c_void; + fn SetBkMode(hdc: *mut c_void, mode: i32) -> i32; + fn SetTextColor(hdc: *mut c_void, color: u32) -> u32; + fn TextOutW(hdc: *mut c_void, x: i32, y: i32, lpstring: *const u16, c: i32) -> i32; + fn GetTextExtentPoint32W(hdc: *mut c_void, lpstring: *const u16, c: i32, psizl: *mut GdiSize) -> i32; + fn GdiFlush() -> i32; +} + +const TRANSPARENT: i32 = 1; +const ANTIALIASED_QUALITY: u32 = 4; +const FW_NORMAL: i32 = 400; +const FW_BOLD: i32 = 700; + +fn colorref((r, g, b): Rgb) -> u32 { + u32::from(r) | (u32::from(g) << 8) | (u32::from(b) << 16) +} + +fn wide_z(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() +} + +pub(super) struct Canvas { + hdc: *mut c_void, + bmp: *mut c_void, + old_bmp: *mut c_void, + bits: *mut u8, + pub(super) width: u32, + pub(super) height: u32, +} + +impl Canvas { + pub(super) fn new(width: u32, height: u32) -> Option { + if width == 0 || height == 0 { + return None; + } + unsafe { + let hdc = CreateCompatibleDC(std::ptr::null_mut()); + if hdc.is_null() { + return None; + } + let bmi = BitmapInfo { + header: BitmapInfoHeader { + bi_size: std::mem::size_of::() as u32, + bi_width: width as i32, + bi_height: -(height as i32), + bi_planes: 1, + bi_bit_count: 32, + bi_compression: 0, + bi_size_image: 0, + bi_x_pels_per_meter: 0, + bi_y_pels_per_meter: 0, + bi_clr_used: 0, + bi_clr_important: 0, + }, + colors: [0], + }; + let mut bits: *mut c_void = std::ptr::null_mut(); + let bmp = CreateDIBSection(hdc, &bmi, 0, &mut bits, std::ptr::null_mut(), 0); + if bmp.is_null() || bits.is_null() { + DeleteDC(hdc); + return None; + } + let old_bmp = SelectObject(hdc, bmp); + SetBkMode(hdc, TRANSPARENT); + Some(Canvas { hdc, bmp, old_bmp, bits: bits.cast::(), width, height }) + } + } + + fn pixels_mut(&mut self) -> &mut [u8] { + let len = (self.width as usize) * (self.height as usize) * 4; + unsafe { std::slice::from_raw_parts_mut(self.bits, len) } + } + + pub(super) fn clear(&mut self, (r, g, b): Rgb) { + let px = [b, g, r, 0xFF]; + for chunk in self.pixels_mut().chunks_exact_mut(4) { + chunk.copy_from_slice(&px); + } + } + + pub(super) fn fill_rect(&mut self, x0: u32, y0: u32, x1: u32, y1: u32, (r, g, b): Rgb) { + let x0 = x0.min(self.width); + let x1 = x1.min(self.width); + let y0 = y0.min(self.height); + let y1 = y1.min(self.height); + if x0 >= x1 || y0 >= y1 { + return; + } + let w = self.width as usize; + let px = [b, g, r, 0xFF]; + let buf = self.pixels_mut(); + for y in y0..y1 { + let row = (y as usize) * w * 4; + for x in x0..x1 { + let at = row + (x as usize) * 4; + buf[at..at + 4].copy_from_slice(&px); + } + } + } + + pub(super) fn stroke_border(&mut self, thickness: u32, col: Rgb) { + let t = thickness.max(1); + let (w, h) = (self.width, self.height); + self.fill_rect(0, 0, w, t, col); + self.fill_rect(0, h.saturating_sub(t), w, h, col); + self.fill_rect(0, 0, t, h, col); + self.fill_rect(w.saturating_sub(t), 0, w, h, col); + } + + pub(super) fn top_gradient_bar(&mut self, bar_h: u32, left: Rgb, right: Rgb) { + let h = bar_h.min(self.height); + let w = self.width.max(1); + let span = (w - 1).max(1) as f32; + let buf = self.pixels_mut(); + for x in 0..w { + let t = x as f32 / span; + let r = (f32::from(left.0) + (f32::from(right.0) - f32::from(left.0)) * t).round() as u8; + let g = (f32::from(left.1) + (f32::from(right.1) - f32::from(left.1)) * t).round() as u8; + let b = (f32::from(left.2) + (f32::from(right.2) - f32::from(left.2)) * t).round() as u8; + let px = [b, g, r, 0xFF]; + for y in 0..h { + let at = ((y as usize) * (w as usize) + (x as usize)) * 4; + buf[at..at + 4].copy_from_slice(&px); + } + } + } + + pub(super) fn text( + &mut self, + x: i32, + y: i32, + text: &str, + face: &str, + px_height: i32, + bold: bool, + color: Rgb, + shadow_px: i32, + ) { + if text.is_empty() { + return; + } + let utf16: Vec = text.encode_utf16().collect(); + let face_w = wide_z(face); + unsafe { + let font = CreateFontW( + -px_height.max(8), + 0, + 0, + 0, + if bold { FW_BOLD } else { FW_NORMAL }, + 0, + 0, + 0, + 0, + 0, + 0, + ANTIALIASED_QUALITY, + 0, + face_w.as_ptr(), + ); + let old_font = if !font.is_null() { SelectObject(self.hdc, font) } else { std::ptr::null_mut() }; + if shadow_px > 0 { + SetTextColor(self.hdc, colorref(theme::SHADOW)); + TextOutW(self.hdc, x + shadow_px, y + shadow_px, utf16.as_ptr(), utf16.len() as i32); + } + SetTextColor(self.hdc, colorref(color)); + TextOutW(self.hdc, x, y, utf16.as_ptr(), utf16.len() as i32); + if !font.is_null() { + SelectObject(self.hdc, old_font); + DeleteObject(font); + } + } + } + + pub(super) fn text_right( + &mut self, + right_x: i32, + y: i32, + text: &str, + face: &str, + px_height: i32, + bold: bool, + color: Rgb, + shadow_px: i32, + ) { + if text.is_empty() { + return; + } + let utf16: Vec = text.encode_utf16().collect(); + let face_w = wide_z(face); + unsafe { + let font = CreateFontW( + -px_height.max(8), + 0, + 0, + 0, + if bold { FW_BOLD } else { FW_NORMAL }, + 0, + 0, + 0, + 0, + 0, + 0, + ANTIALIASED_QUALITY, + 0, + face_w.as_ptr(), + ); + let old_font = if !font.is_null() { SelectObject(self.hdc, font) } else { std::ptr::null_mut() }; + let mut sz = GdiSize { cx: 0, cy: 0 }; + GetTextExtentPoint32W(self.hdc, utf16.as_ptr(), utf16.len() as i32, &mut sz); + let x = right_x - sz.cx; + if shadow_px > 0 { + SetTextColor(self.hdc, colorref(theme::SHADOW)); + TextOutW(self.hdc, x + shadow_px, y + shadow_px, utf16.as_ptr(), utf16.len() as i32); + } + SetTextColor(self.hdc, colorref(color)); + TextOutW(self.hdc, x, y, utf16.as_ptr(), utf16.len() as i32); + if !font.is_null() { + SelectObject(self.hdc, old_font); + DeleteObject(font); + } + } + } + + pub(super) fn pack(&self, format: DXGI_FORMAT, pitch: usize) -> Option> { + unsafe { GdiFlush() }; + let w = self.width as usize; + let h = self.height as usize; + let src = unsafe { std::slice::from_raw_parts(self.bits, w * h * 4) }; + let mut out = vec![0u8; pitch * h]; + match format { + DXGI_FORMAT_B8G8R8A8_UNORM => { + for y in 0..h { + let srow = y * w * 4; + let drow = y * pitch; + for x in 0..w { + let s = srow + x * 4; + let d = drow + x * 4; + out[d] = src[s]; + out[d + 1] = src[s + 1]; + out[d + 2] = src[s + 2]; + out[d + 3] = 0xFF; + } + } + } + DXGI_FORMAT_R8G8B8A8_UNORM => { + for y in 0..h { + let srow = y * w * 4; + let drow = y * pitch; + for x in 0..w { + let s = srow + x * 4; + let d = drow + x * 4; + out[d] = src[s + 2]; + out[d + 1] = src[s + 1]; + out[d + 2] = src[s]; + out[d + 3] = 0xFF; + } + } + } + DXGI_FORMAT_R10G10B10A2_UNORM => { + for y in 0..h { + let srow = y * w * 4; + let drow = y * pitch; + for x in 0..w { + let s = srow + x * 4; + let r10 = (u32::from(src[s + 2]) * 1023 + 127) / 255; + let g10 = (u32::from(src[s + 1]) * 1023 + 127) / 255; + let b10 = (u32::from(src[s]) * 1023 + 127) / 255; + let packed = r10 | (g10 << 10) | (b10 << 20) | (3u32 << 30); + let d = drow + x * 4; + out[d..d + 4].copy_from_slice(&packed.to_le_bytes()); + } + } + } + DXGI_FORMAT_R16G16B16A16_FLOAT => { + for y in 0..h { + let srow = y * w * 4; + let drow = y * pitch; + for x in 0..w { + let s = srow + x * 4; + let r = f32_to_f16(srgb_to_lin(src[s + 2])); + let g = f32_to_f16(srgb_to_lin(src[s + 1])); + let b = f32_to_f16(srgb_to_lin(src[s])); + let d = drow + x * 8; + out[d..d + 2].copy_from_slice(&r.to_le_bytes()); + out[d + 2..d + 4].copy_from_slice(&g.to_le_bytes()); + out[d + 4..d + 6].copy_from_slice(&b.to_le_bytes()); + out[d + 6..d + 8].copy_from_slice(&0x3C00u16.to_le_bytes()); + } + } + } + _ => return None, + } + Some(out) + } +} + +impl Drop for Canvas { + fn drop(&mut self) { + unsafe { + SelectObject(self.hdc, self.old_bmp); + DeleteObject(self.bmp); + DeleteDC(self.hdc); + } + } +} + +#[inline] +fn srgb_to_lin(c: u8) -> f32 { + let x = f32::from(c) / 255.0; + x * x +} + +#[inline] +fn f32_to_f16(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exp = ((bits >> 23) & 0xFF) as i32 - 127 + 15; + let mant = bits & 0x007F_FFFF; + if exp <= 0 { + sign + } else if exp >= 31 { + sign | 0x7C00 + } else { + sign | ((exp as u16) << 10) | ((mant >> 13) as u16) + } +} + +pub(super) fn bpp(format: DXGI_FORMAT) -> Option { + Some(colours(format)?[0].len() as u32) +} + #[rustfmt::skip] -#[allow(unreachable_patterns, clippy::match_overlapping_arm)] pub(super) const fn glyph(c: u8) -> [u8; 7] { match c { b'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], @@ -48,7 +458,6 @@ pub(super) const fn glyph(c: u8) -> [u8; 7] { b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000], b'%' => [0b11000, 0b11001, 0b00010, 0b00100, 0b01000, 0b10011, 0b00011], b'-' => [0, 0, 0, 0b11111, 0, 0, 0], - // For the settings menu (menu.rs). b'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000], b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010], b'*' => [0, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0], @@ -66,16 +475,14 @@ pub(super) const fn glyph(c: u8) -> [u8; 7] { } } -/// The bytes of a black and a white pixel of a swap chain's format. pub(super) fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> { Some(match format { DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM => [&[0, 0, 0, 0xFF], &[0xFF; 4]], DXGI_FORMAT_R10G10B10A2_UNORM => [&[0, 0, 0, 0xC0], &[0xFF; 4]], - // Halves of 0 and 1. DXGI_FORMAT_R16G16B16A16_FLOAT => [ &[0, 0, 0, 0, 0, 0, 0, 0x3C], &[0, 0x3C, 0, 0x3C, 0, 0x3C, 0, 0x3C], ], _ => return None, }) -} +} \ No newline at end of file diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs index 1642912f5..aa6cd4a4b 100644 --- a/crates/victory-gpu/src/host/menu.rs +++ b/crates/victory-gpu/src/host/menu.rs @@ -1,86 +1,49 @@ -//! The F1 settings menu. F1 shows and hides it while our window has the -//! focus; Up/Down pick a setting, Left/Right change it, Enter runs the line -//! picked (save, save and restart, preload shaders, clear the shader cache, -//! reset, close), Esc closes. Preloading saves, ends this run and has the -//! launcher make every shader before the title starts again -//! (`VICTORY_PRELOAD=1`, `victory preload`); clearing does the same but has it -//! delete the shaders and pipelines made so far instead -//! (`VICTORY_CLEAR_SHADERS=1`, `victory clear-shaders`). Both ask for a second -//! Enter first. While it is -//! shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`, read by the -//! input module). By default a pad still works. With `VICTORY_MENU_PAD=1`, -//! press both stick buttons on the physical pad in slot 0 to toggle F1. Use the D-pad to -//! navigate, A to select, and B to go back. -//! -//! The settings are read once at start, so a change is saved at once (as well as by the save -//! lines) to the file -//! `VICTORY_MENU_FILE` names (`scripts\play-nvidia.ps1` sets it to -//! `victory-settings.txt` in the repository's folder and applies it at every -//! start) and takes effect at the next start; "SAVE AND RESTART" starts the -//! launcher again (`VICTORY_MENU_PLAY`, with `VICTORY_MENU_ARGS`) and ends -//! this run. The `VICTORY_MENU_...` settings are the launcher's own choices -//! (DLSS mode, frame generation, frame rate, console, picture size), which it -//! turns into the layer's switches; the others are the switches themselves. -//! -//! In every build, as the stats panel is. Drawn as -//! that panel is: white text on a black box, copied onto the swap chain's -//! buffer, in the middle of the picture. +//! The F1 settings menu, rendered with smooth anti-aliased Segoe UI / Consolas +//! text, 1px drop shadow, active-row highlight bar, and a refined Vice City palette. +//! Includes 100% of v2026.11.29.01 features: F2 advisor toggle, per-item descriptions, +//! CLEAR SHADER CACHE, GPU adapter picker, M&K key bindings, gamepad menu navigation, +//! GRAY SHADOW LIFT, FORCE 3X ON RTX 40, and Series S picture modes. -use std::io::{self, Write}; -use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Duration; -use windows::Win32::Foundation::{POINT, RECT}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -use windows::Win32::Graphics::Gdi::ScreenToClient; -use windows::Win32::UI::WindowsAndMessaging::{GetClientRect, GetCursorPos, GetForegroundWindow, GetWindowThreadProcessId}; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ - GetAsyncKeyState, VK_DOWN, VK_ESCAPE, VK_F1, VK_LBUTTON, VK_LEFT, VK_RBUTTON, VK_RETURN, VK_RIGHT, VK_UP, + GetAsyncKeyState, VK_DOWN, VK_ESCAPE, VK_F1, VK_LEFT, VK_RETURN, VK_RIGHT, VK_UP, }; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; -use super::font::{colours, glyph}; +use super::font::{Canvas, bpp, glyph, theme}; use super::{Host, HostList, transition}; -const GLYPH: (u32, u32) = (5, 7); -const CELL: (u32, u32) = (6, 9); -const SELECTION_MARKER: [u8; GLYPH.1 as usize] = [ - 0b10000, 0b11000, 0b11110, 0b11111, 0b11110, 0b11000, 0b10000, -]; -const COLUMNS: u32 = 60; -/// Lines of the box: a title, a help line, a blank, the settings shown, a -/// blank, what the line picked does (`ABOUT`, else blank), a note and the -/// repository's link. const ROWS: usize = 20; -const LINES: u32 = ROWS as u32 + 9; -/// The action that preloads shaders, and what is said of it while it is picked. +const COLUMNS: u32 = 60; const PRELOAD: usize = 0; +const CLEAR: usize = 1; +const RESET: usize = 2; +const EXPORT: usize = 3; +const IMPORT: usize = 4; +const CLOSE: usize = 5; +const SAVE_QUIT: usize = 6; +const SAVE_RESTART: usize = 7; +const SAVE_NEXT: usize = 8; +const IMPORT_NAME: usize = 56; +const SCENE_DRAWS: u64 = 100; +const UPLOADS: usize = 4; + const ABOUT_PRELOAD: [&str; 3] = [ "MAKES EVERY SHADER AHEAD, THEN STARTS THE GAME AGAIN.", "TAKES A WHILE: MAYBE A LONG TIME, DEPENDING ON HARDWARE.", "A LATER UPDATE OF THIS BUILD MAY NEED A NEW PRELOAD.", ]; -/// The action that deletes the shaders and pipelines made so far (`VICTORY_CLEAR_SHADERS=1` at -/// the start it asks for, `victory clear-shaders`), and what is said of it while it is picked. -const CLEAR: usize = 1; -// The first start after a clear may draw without parts of the picture (a head, in a -// test of the same clear on an RTX 4070: pipelines not made yet, as on a fresh -// install); the next start, or a preload, has them (#629). const ABOUT_CLEAR: [&str; 3] = [ "DELETES THE SHADERS AND PIPELINES MADE SO FAR AND RESTARTS.", "THE FIRST START AFTER IT MAY MISS PARTS OF THE PICTURE:", "START ONCE MORE, OR PRELOAD SHADERS. SAVES ARE KEPT.", ]; -/// The note after the first Enter on it: the second one does it. const CONFIRM_CLEAR: &str = "ENTER AGAIN: SAVE, CLOSE THE GAME AND CLEAR SHADERS"; -/// The line that sets every setting back to the play defaults. -const RESET: usize = 2; -/// The actions that export and import the game's save (`crate::save_share`), and what is said -/// of them while they are picked. -const EXPORT: usize = 3; -const IMPORT: usize = 4; const ABOUT_EXPORT: [&str; 3] = [ "MAKES A ZIP OF YOUR SAVE IN SAVES, IN THE FOLDER OF", "GAME_SCARLETT_MASTER.EXE. SEND THAT ZIP TO SHARE IT.", @@ -91,34 +54,19 @@ const ABOUT_IMPORT: [&str; 3] = [ "GAME_SCARLETT_MASTER.EXE, THEN PRESS ENTER HERE AND", "PICK IT FROM THE LIST. YOUR GAME SETTINGS ARE KEPT.", ]; -/// The list IMPORT SAVE opens: the saves in `Saves`, then a line back to the settings. -const PICK_TITLE: &str = "IMPORT SAVE ESC GOES BACK"; -const PICK_HELP: &str = "UP/DOWN PICK ENTER TWICE IMPORTS IT"; -const PICK_NONE: &str = " NONE YET: PUT A SAVE ZIP INTO SAVES IN THE GAME FOLDER"; +const PICK_TITLE: &str = "IMPORT SAVE"; +const PICK_HELP: &str = "UP/DOWN PICK ENTER TWICE IMPORTS IT"; +const PICK_NONE: &str = "NONE YET: PUT A SAVE ZIP INTO SAVES IN THE GAME FOLDER"; const PICK_BACK: &str = "BACK TO THE SETTINGS"; const ABOUT_PICK: [&str; 3] = [ "THE SAVE ZIPS IN SAVES, IN THE GAME FOLDER, NEWEST FIRST.", "ENTER TWICE: THE GAME RESTARTS WITH THE SAVE PICKED.", "YOUR OLD SAVE IS ZIPPED INTO SAVES FIRST, SO IT IS KEPT.", ]; -/// The note after the first Enter on a save in the list: the second one imports it. const CONFIRM_IMPORT: &str = "ENTER AGAIN: IMPORT IT AND RESTART THE GAME"; -/// The longest save name shown in the list. -const IMPORT_NAME: usize = 56; +const CONFIRM_PRELOAD: &str = "ENTER AGAIN: SAVE, CLOSE THE GAME AND PRELOAD"; -/// A save's file name as the menu's letters can show it. -fn shown_name(name: &str) -> String { - name.chars() - .map(|c| c.to_ascii_uppercase()) - .map(|c| if c.is_ascii() && glyph(c as u8) != glyph(b'#') { c } else { '-' }) - .take(IMPORT_NAME) - .collect() -} - -/// The setting that turns MFG Unlocker on, and what is said of it while it is picked. const MFG: &str = "VICTORY_MFG_UNLOCKER"; -/// The setting that forces 3x DLSS frame generation on an RTX 40 card through MFG Unlocker, and -/// what is said of it while it is picked. const FORCE_MFG: &str = "VICTORY_FORCE_MFG_RTX40"; const ABOUT_FORCE_MFG: [&str; 3] = [ "RTX 40: 3X DLSS FRAME GEN THROUGH MFG UNLOCKER (A MOD).", @@ -130,46 +78,48 @@ const ABOUT_MFG: [&str; 3] = [ "ON: DOWNLOADED FROM ITS GITHUB, RUN WITH DLSS FRAME GEN.", "NVIDIA DOES NOT SUPPORT IT. IF THE GAME FAILS, TURN IT OFF.", ]; -/// The DLSS setting, and what is said while it is picked on in a start without NVIDIA's files. const DLSS: &str = "VICTORY_MENU_DLSS"; const ABOUT_NO_DLSS: [&str; 3] = [ "NVIDIA DLSS FILES MISSING (ABOUT 70 MB FROM NVIDIA).", "IN VICTORY PLAY, SAVE AND RESTART NOW TO DOWNLOAD.", "FOR THE SCRIPT LAUNCHER, RUN GET-NVIDIA-DLSS.CMD.", ]; -/// Frame generation that this run did not start with: it is made ready only at a start with it -/// on (a start with it ready but off held some PCs at 14 fps, #515, #574), so turning it on takes -/// a restart; a run started with it on changes it, or turns it off, live. +const FRAMEGEN: &str = "VICTORY_MENU_FRAMEGEN"; const ABOUT_FRAMEGEN_RESTART: [&str; 3] = [ "RESTART REQUIRED TO ENABLE FRAME GENERATION: THIS RUN", "STARTED WITHOUT IT. SAVE AND RESTART NOW TURNS IT ON.", "AFTER THAT IT CHANGES, OR TURNS OFF, LIVE.", ]; -const FRAMEGEN: &str = "VICTORY_MENU_FRAMEGEN"; -/// The console, and the picture row of each: only the one of the console picked is shown. const CONSOLE: &str = "VICTORY_MENU_CONSOLE"; const X_RES: &str = "VICTORY_MENU_RES"; const S_RES: &str = "VICTORY_MENU_S_RES"; -/// The Series S scene sizes and the DLSS mode of each (the picture is 1920x1080). Only DLSS -/// changes it: the title's own FidelityFX path from 540 stopped it at the start (0xc0000094, -/// a division by zero in the title, 2026-11-28), so with DLSS off the scene stays at 720. -/// No 1080 and no DLAA: with its scene at 1920x1080 the Series S title stops during the boot -/// screens (`streamline::Mode::on_console`, #707, #710). const S_MODES: [(&str, &str); 4] = [("720", "quality"), ("626", "balanced"), ("540", "performance"), ("360", "ultraperformance")]; const ABOUT_S_RES: [&str; 3] = [ "THE SIZE THE GAME RENDERS AT. THE PICTURE IS 1920X1080.", "OTHER THAN 720 NEEDS DLSS: 720 QUALITY, 626 BALANCED, 540", "PERFORMANCE, 360 ULTRA PERF. NO DLAA: IT STOPS THE GAME.", ]; -/// The note after the first Enter on it: the second one does it. -const CONFIRM_PRELOAD: &str = "ENTER AGAIN: SAVE, CLOSE THE GAME AND PRELOAD"; -/// The last line of the box: where this build comes from. const REPO: &str = "GITHUB.COM/TRUSTNO1-CODER/VICTORY-NVIDIA"; -const RIM: u32 = 4; -const UPLOADS: usize = 4; +const ADAPTER: &str = "VICTORY_ADAPTER"; +const BINDS: &str = "VICTORY_MENU_KEY_BINDINGS"; +const BINDS_TITLE: &str = "KEY BINDINGS"; +const BINDS_HELP: &str = "UP/DOWN PICK ENTER, THEN A KEY OR MOUSE BUTTON"; +const BINDS_BACK: &str = "BACK TO THE SETTINGS"; +const BINDS_OFF: &str = "TURN ON MOUSE AND KEYBOARD AND RESTART FIRST"; +const ABOUT_BINDS: [&str; 3] = [ + "THE KEY OR MOUSE BUTTON PRESSED REPLACES THE LINE KEYS.", + "ESC CANCELS. LEFT/RIGHT CHANGES THE SENSITIVITY.", + "SAVED TO BINDINGS.INI AND USED AT ONCE.", +]; + +fn shown_name(name: &str) -> String { + name.chars() + .map(|c| c.to_ascii_uppercase()) + .map(|c| if c.is_ascii() && glyph(c as u8) != glyph(b'#') { c } else { '-' }) + .take(IMPORT_NAME) + .collect() +} -/// A setting: the variable, its name in the menu, the values it takes -/// (`""`: not set, the build's own default), and whether a change applies at once. struct Item { var: &'static str, label: &'static str, @@ -178,24 +128,16 @@ struct Item { } impl Item { - /// Its values: [`ADAPTER`]'s are the PC's cards, found at the first look. fn values(&self) -> &'static [(&'static str, &'static str)] { if self.var == ADAPTER { adapters() } else { self.values } } } -/// The card the game runs on (`VICTORY_ADAPTER`, a part of its name; empty: the one the monitor -/// is plugged into, else the one with the most memory). Read at the start: a change restarts. -const ADAPTER: &str = "VICTORY_ADAPTER"; - -/// AUTO, then each card of the PC's with 2 GB of its own memory or more (no virtual displays, -/// no integrated GPUs), by its full name. fn adapters() -> &'static [(&'static str, &'static str)] { - static ALL: std::sync::OnceLock<&'static [(&'static str, &'static str)]> = std::sync::OnceLock::new(); + static ALL: OnceLock<&'static [(&'static str, &'static str)]> = OnceLock::new(); ALL.get_or_init(|| { let mut all: Vec<(&'static str, &'static str)> = vec![("", "AUTO")]; #[cfg(windows)] - // SAFETY: a factory of our own, adapters only described. unsafe { use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE, IDXGIFactory1}; if let Ok(factory) = CreateDXGIFactory1::() { @@ -229,20 +171,13 @@ const ABOUT_SHADOW_LIFT: [&str; 3] = [ "APPLIES LIVE AND SAVES WITHOUT RESTARTING.", ]; -/// The first value of each is what the launcher starts with. #[rustfmt::skip] const ITEMS: &[Item] = &[ - // At the top: what holds the frame rate back, and what helps (panel.rs, `Advisor`; F2). Item { var: "VICTORY_ADVISOR", label: "WHAT LIMITS FPS (F2)", values: &[("0", "OFF"), ("1", "ON")], live: true }, - // The launcher's own choices. Item { var: "VICTORY_MENU_DLSS", label: "DLSS", values: &[("quality", "QUALITY"), ("balanced", "BALANCED"), ("performance", "PERFORMANCE"), ("ultraperformance", "ULTRA PERFORMANCE"), ("dlaa", "DLAA (NATIVE)"), ("off", "OFF")], live: false }, Item { var: "VICTORY_MENU_FRAMEGEN", label: "FRAME GENERATION", values: &[("0", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false }, - // DLSS Frame Generation where it runs (RTX 40 and later), else AMD's FSR 3 (2X only). Item { var: "VICTORY_MENU_FG_TYPE", label: "FRAME GEN TYPE", values: &[("auto", "AUTO"), ("dlss", "DLSS"), ("fsr", "FSR 3 (OLDER CARDS)"), ("fsr4", "FSR 4 (EXPERIMENTAL)")], live: false }, - // Frame generation paused while the title works a Bink movie. In the world it does that - // about every frame, so ON leaves frame generation off for the whole game (streamline.rs). Item { var: "VICTORY_MOVIE_GATE", label: "FRAME GEN PAUSED IN MOVIES", values: UNSET_ON, live: false }, - // Someone else's mod (apps\victory\src\play.rs): downloaded at the next start, then loaded. Item { var: MFG, label: "MFG UNLOCKER (MOD, RTX 20/30)", values: UNSET_ON, live: false }, Item { var: FORCE_MFG, label: "FORCE 3X ON RTX 40 (MOD)", values: UNSET_ON, live: false }, Item { var: "VICTORY_MENU_FPS", label: "FRAME RATE CAP", values: &[("1000", "NONE"), ("120", "120"), ("60", "60"), ("30", "30 (THE GAME)")], live: false }, @@ -251,21 +186,14 @@ const ITEMS: &[Item] = &[ Item { var: "VICTORY_FULLSCREEN", label: "FULLSCREEN (NO BORDER)", values: UNSET_ON, live: false }, Item { var: "VICTORY_CONTROLS", label: "CONTROLS", values: &[("", "AUTO"), ("keyboard", "KEYBOARD"), ("gamepad", "GAMEPAD"), ("dualsense", "DUALSENSE (NATIVE)")], live: false }, Item { var: "VICTORY_MOUSE_CAPTURE", label: "MOUSE CAPTURE", values: UNSET_ON, live: false }, - // Keys and sensitivity in bindings.ini in %LOCALAPPDATA%\victory (apps\victory\src\play.rs). Item { var: "VICTORY_MNK", label: "MOUSE AND KEYBOARD", values: UNSET_ON, live: false }, Item { var: BINDS, label: "KEY BINDINGS", values: &[("", "ENTER OPENS")], live: false }, Item { var: "VICTORY_VEHICLE_AUTO_CENTER", label: "VEHICLE AUTO-CENTER", values: UNSET_ON, live: true }, Item { var: "VICTORY_IME_ENGLISH", label: "ENGLISH KEYBOARD", values: UNSET_ON, live: false }, - // The PC's cards (`adapters`): the list here is only a stand-in. Item { var: ADAPTER, label: "GPU", values: &[("", "AUTO")], live: false }, Item { var: "VICTORY_MENU_CONSOLE", label: "CONSOLE", values: &[("series-x", "SERIES X"), ("series-s", "SERIES S (FASTER)")], live: false }, Item { var: X_RES, label: "SERIES X PICTURE", values: &[("1440", "2560X1440"), ("1080to1440", "1080P TO 1440P"), ("4k", "3840X2160")], live: false }, - // In place of SERIES X PICTURE when CONSOLE is Series S. Item { var: S_RES, label: "SERIES S PICTURE", values: &[("720", "1280X720 (THE GAME)"), ("626", "1113X626"), ("540", "960X540"), ("360", "640X360 (FASTEST)")], live: false }, - // The layer's switches. - // AUTO = what NVIDIA's own override recommends per the mode the picture - // is actually upscaled at (M for performance, L for ultra performance, - // K for the rest); DEFAULT is the model the game ships with. Item { var: "VICTORY_DLSS_PRESET", label: "DLSS MODEL", values: &[("", "DEFAULT"), ("auto", "AUTO (BY MODE)"), ("k", "K"), ("j", "J"), ("m", "M"), ("l", "L")], live: false }, Item { var: "VICTORY_AMBIENT", label: "LIGHT ESTIMATE", values: &[("0.8", "0.8"), ("1", "1"), ("0.5", "0.5"), ("", "OFF")], live: false }, Item { var: "VICTORY_SHADOW_LIFT", label: "GRAY SHADOW LIFT", values: &[("0", "0% (OFF)"), ("0.03", "10%"), ("0.06", "20%"), ("0.09", "30%"), ("0.12", "40%"), ("0.15", "50%"), ("0.18", "60%"), ("0.21", "70%"), ("0.24", "80%"), ("0.27", "90%"), ("0.3", "100% (MAX)")], live: true }, @@ -273,10 +201,7 @@ const ITEMS: &[Item] = &[ Item { var: "VICTORY_AMBIENT_SPECULAR", label: "REFLECTION ESTIMATE", values: ON_UNSET, live: false }, Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1", "1"), ("1.5", "1.5"), ("2", "2"), ("", "NONE")], live: false }, Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING", values: UNSET_ON, live: false }, - // Being measured: off by default (crate::hwrt). Item { var: "VICTORY_HW_RT", label: "HARDWARE RAY TRACING", values: UNSET_ON, live: false }, - // Left out by default on 32-lane hosts to avoid dark blocks underwater (#739); - // "1" (ON) runs them for testing. Item { var: "VICTORY_WATER_LIGHT", label: "WATER LIGHT", values: UNSET_ON, live: false }, Item { var: "VICTORY_LEAVE_OUT", label: "FACE RELOCATION AND HEAT HAZE", values: &[("02384a60fda6f2d0,731a39171b568298", "LEFT OUT"), ("", "RUN (SLOWER, SMEARS)")], live: false }, Item { var: "VICTORY_EARLY_DEPTH", label: "EARLY DEPTH TEST", values: ON_UNSET, live: false }, @@ -291,18 +216,11 @@ const ITEMS: &[Item] = &[ Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: STAGES, live: false }, Item { var: "VICTORY_CARD_BUFFERS_MIN_KB", label: "CARD COMPARES FROM (KB)", values: &[("64", "64"), ("1024", "1024")], live: false }, Item { var: "VICTORY_PORT_CONSTANTS", label: "CONSTANTS HEAP IN PLACE", values: UNSET_ON, live: false }, - // THIN records the title's list calls on our threads: switches for it and for what goes with it. - // Faces without skin come from the first start, before the pipelines are made, with THIN on or off - // (PR 66: RTX 5070, 5070 Ti and 5080); on a Ryzen 5 9600X with an RTX 5080 THIN was the faster - // (23.6 frames a second against 21.1, warm cache). Frame generation needs the line of submissions: - // without THIN, ASYNC SUBMIT gives it. Item { var: "VICTORY_THIN", label: "THIN LISTS", values: ON_UNSET, live: false }, Item { var: "VICTORY_JOIN_PARTS", label: "JOIN PARTS", values: &[("8", "8"), ("", "1 (OFF)")], live: false }, Item { var: "VICTORY_ASYNC_SUBMIT", label: "ASYNC SUBMIT (FRAME GEN WITHOUT THIN)", values: UNSET_ON, live: false }, ]; -/// What the highlighted line does, in the three lines under the list (the more particular -/// notes, such as [`ABOUT_NO_DLSS`], go first). Every setting has one -/// (`every_line_says_what_it_does`). + fn about_item(var: &str) -> [&'static str; 3] { match var { "VICTORY_ADVISOR" => [ @@ -523,7 +441,6 @@ fn about_item(var: &str) -> [&'static str; 3] { } } -/// What the action lines without a note of their own do. const ABOUT_SAVE_RESTART: [&str; 3] = [ "SAVES THESE SETTINGS AND STARTS THE GAME AGAIN WITH THEM.", "PROGRESS SINCE YOUR LAST GAME SAVE IS LOST.", @@ -544,12 +461,13 @@ const ABOUT_CLOSE: [&str; 3] = [ "", "", ]; + const ABOUT_SAVE_QUIT: [&str; 3] = [ "SAVES THESE SETTINGS AND CLOSES THE GAME.", "PROGRESS SINCE YOUR LAST GAME SAVE IS LOST.", "", ]; -/// The lines after the settings; the three that save are the last. + const ACTIONS: [&str; 9] = [ "PRELOAD SHADERS (RESTARTS THE GAME)", "CLEAR SHADER CACHE (RESTARTS THE GAME)", @@ -561,41 +479,15 @@ const ACTIONS: [&str; 9] = [ "SAVE AND RESTART NOW", "SAVE FOR NEXT START", ]; -/// The line that closes the menu, and the lines that save: and close the game, and start it -/// again, and no more. -const CLOSE: usize = 5; -const SAVE_QUIT: usize = 6; -const SAVE_RESTART: usize = 7; -const SAVE_NEXT: usize = 8; -/// The line under MOUSE AND KEYBOARD that opens the list of key bindings ([`binds`]): -/// a setting of one value, never saved. -const BINDS: &str = "VICTORY_MENU_KEY_BINDINGS"; -const BINDS_TITLE: &str = "KEY BINDINGS ESC GOES BACK"; -const BINDS_HELP: &str = "UP/DOWN PICK ENTER, THEN A KEY OR MOUSE BUTTON"; -const BINDS_BACK: &str = "BACK TO THE SETTINGS"; -const BINDS_OFF: &str = "TURN ON MOUSE AND KEYBOARD AND RESTART FIRST"; -/// A wait for a key ended because another program came in front ([`binds::Heard::Lost`]). -const BINDS_LOST: &str = "NOT CHANGED: THE GAME WINDOW WAS NOT IN FRONT"; -const ABOUT_BINDS: [&str; 3] = [ - "THE KEY OR MOUSE BUTTON PRESSED REPLACES THE LINE KEYS.", - "ESC CANCELS. LEFT/RIGHT CHANGES THE SENSITIVITY.", - "SAVED TO BINDINGS.INI AND USED AT ONCE.", -]; -/// What the start a restart asks for does before the game. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Then { - /// Nothing: the game at once. Play, - /// Makes every shader first (`VICTORY_PRELOAD=1`, for that start alone). Preload, - /// Deletes the shaders and pipelines made so far first (`VICTORY_CLEAR_SHADERS=1`, for that - /// start alone). ClearShaders, } impl Then { - /// The PowerShell that sets the start's variable, before the launcher's command. fn switch(self) -> &'static str { match self { Then::Play => "", @@ -609,9 +501,6 @@ fn get(var: &str) -> String { std::env::var(var).unwrap_or_default() } -/// Where the menu saves: the file `VICTORY_MENU_FILE` names (`victory play` sets it); else, -/// however the game was started (a script, another launcher), the one `victory play` reads at -/// every start, `victory-settings.txt` in `VICTORY_HOME` or `%LOCALAPPDATA%\victory`. fn settings_file() -> Option { let set = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(std::path::PathBuf::from); set("VICTORY_MENU_FILE") @@ -619,26 +508,10 @@ fn settings_file() -> Option { .or_else(|| set("LOCALAPPDATA").map(|base| base.join("victory").join("victory-settings.txt"))) } -/// The first start of a new victory.exe: the seconds it plays before it starts -/// again by itself (`VICTORY_WARMUP_RESTART`, set by the launcher while the exe -/// has no mark under `%LOCALAPPDATA%\victory\warmed`). On the RTX 5070, every -/// new build's first run stayed at a flat 14 fps (Present ~40 ms) for as long as -/// it ran, and every later run was normal (27-29 fps), even after a first run of -/// 45 seconds; a copy of an exe already run was fast at once (2026-11-27). Likely -/// the driver's cache of the program; not ours to fix, so it is run through once. -/// Draws in a frame from which the warm-up's time counts: the game's scenes -/// (loading into the world: about 300, in the world: thousands), not its -/// title screen and menus (about 10). -const SCENE_DRAWS: u64 = 100; - pub(crate) fn warmup_seconds() -> Option { get("VICTORY_WARMUP_RESTART").parse().ok().filter(|s| *s > 0) } -/// Marks this victory.exe as warmed up, whether it went down. Only a -/// written mark can end the warm-up: the launcher arms a new one whenever -/// none exists (`apps/victory/src/play.rs`, `warmup_mark`), so the write's -/// result is what decides whether the restart is safe to do. fn mark_written(mark: &std::path::Path) -> bool { if let Some(dir) = mark.parent() { let _ = std::fs::create_dir_all(dir); @@ -646,7 +519,6 @@ fn mark_written(mark: &std::path::Path) -> bool { std::fs::write(mark, "this victory.exe was warmed up (its first start, then a restart)\r\n").is_ok() } -/// The start's notice lines for the warm-up start ([`warmup_seconds`]). pub(crate) fn warmup_notice(seconds: u64) -> Vec { vec![ "FIRST START OF THIS VERSION: A ONE-TIME WARM-UP".to_owned(), @@ -658,22 +530,15 @@ pub(crate) fn warmup_notice(seconds: u64) -> Vec { ] } -/// Starts `command_line` in a console window of its own, with that console's input and output. -/// (`std::process::Command` always hands its child this process's standard handles: the restarted -/// launcher then wrote into the old launcher's pipe and log, not its own window, and kept the old -/// launcher waiting on that pipe.) fn new_console(command_line: &str, cwd: Option<&std::ffi::OsStr>) -> std::io::Result<()> { use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{CREATE_NEW_CONSOLE, CreateProcessW, PROCESS_INFORMATION, STARTUPINFOW}; let mut line: Vec = command_line.encode_utf16().chain(Some(0)).collect(); let cwd = cwd.map(|p| p.encode_wide().chain(Some(0)).collect::>()); - // SAFETY: plain structs, zero is their empty value. let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() }; startup.cb = std::mem::size_of::() as u32; let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; - // SAFETY: `line` is a writable, terminated UTF-16 string; no handles inherited; this - // process's environment. The optional directory stays alive through the call. let made = unsafe { CreateProcessW( std::ptr::null(), @@ -691,7 +556,6 @@ fn new_console(command_line: &str, cwd: Option<&std::ffi::OsStr>) -> std::io::Re if made == 0 { return Err(std::io::Error::last_os_error()); } - // SAFETY: the two handles CreateProcessW gave, closed once. unsafe { CloseHandle(process.hThread); CloseHandle(process.hProcess); @@ -699,25 +563,19 @@ fn new_console(command_line: &str, cwd: Option<&std::ffi::OsStr>) -> std::io::Re Ok(()) } -/// Whether a change of `item` shows at once. Frame generation does when this run started with -/// it ready (the launcher asks for that whenever Streamline is there). fn live(item: &Item) -> bool { item.live || (item.var == "VICTORY_MENU_FRAMEGEN" && crate::streamline::framegen_live()) } -/// Whether the frame-rate line is shown at the top while the menu is closed -/// (`VICTORY_FPS_LINE=0`: not; the menu changes it). fn fps_line_on() -> &'static AtomicBool { static ON: OnceLock = OnceLock::new(); ON.get_or_init(|| AtomicBool::new(std::env::var_os("VICTORY_FPS_LINE").is_none_or(|v| v != "0"))) } -/// That line: the frames rendered a second and, while frame generation shows more, those shown. fn fps_line() -> Option { if !fps_line_on().load(Ordering::Relaxed) { return None; } - // The stats panel has that corner (F3), and says the same. if super::panel::shown().load(Ordering::Relaxed) { return None; } @@ -727,12 +585,10 @@ fn fps_line() -> Option { } Some(match crate::streamline::shown_per_frame() { 1 => format!("FPS: {fps:.1}"), - per => format!("FPS: {fps:.1} FG: {:.1}", fps * f64::from(per)), + per => format!("FPS: {fps:.1} FG: {:.1}", fps * f64::from(per)), }) } -/// The index of `value` among the item's values (an unknown value: shown as -/// itself, at the end). fn index_of(item: &Item, value: &str) -> Option { if item.var == "VICTORY_SHADOW_LIFT" && value.is_empty() { return Some(0); @@ -740,9 +596,6 @@ fn index_of(item: &Item, value: &str) -> Option { item.values().iter().position(|(v, _)| *v == value) } -/// What the menu shows for `value`: its label, an unknown value as itself, -/// and a value the launcher did not set (a start without play.ps1) as -/// "NOT SET" rather than a blank. fn shown_value(item: &Item, value: &str) -> String { match index_of(item, value) { Some(i) => item.values()[i].1.to_owned(), @@ -758,22 +611,14 @@ enum MenuKey { } static MENU_KEYS: Mutex> = Mutex::new(Vec::new()); - -// A toggle stays pending until the frame has applied it or focus loss cancels it. -// The input sampler can run many times before a single presented frame. static PAD_TOGGLES: AtomicUsize = AtomicUsize::new(0); -// Invalidate pad events even if a frame has already taken them out of the queue. static PAD_GENERATION: AtomicUsize = AtomicUsize::new(0); -/// Whether F1 is open, and whether a controller toggle is queued or being processed. pub fn settings_pad_capture() -> (bool, bool) { let pending = PAD_TOGGLES.load(Ordering::Acquire) != 0; (crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed), pending) } -/// Queue a controller action from GameInput's pad sampler. When the pad loses -/// focus or disconnects, cancel its unconsumed actions. Keyboard events retain -/// their original order in both cases. pub fn settings_pad_key(key: Option) { let mut keys = MENU_KEYS.lock().unwrap_or_else(|e| e.into_inner()); match key { @@ -797,167 +642,78 @@ pub fn settings_pad_key(key: Option) { fn focused() -> bool { let mut process = 0; - // SAFETY: plain queries; room for the answer. - unsafe { - let hwnd = GetForegroundWindow(); - if hwnd.0.is_null() { - return false; - } - GetWindowThreadProcessId(hwnd, Some(&mut process)); - } + unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; process == std::process::id() } -/// Keys and mouse buttons pressed, gathered on a thread of their own every 10 ms: a frame -/// lasts 50 ms and more, and a short press or click would fall between two frames. fn watch_keys() { static WATCH: std::sync::Once = std::sync::Once::new(); WATCH.call_once(|| { let _ = std::thread::Builder::new().name("settings menu keys".into()).spawn(|| { - const WATCHED: [u16; 9] = [VK_F1, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_RETURN, VK_ESCAPE, VK_LBUTTON, VK_RBUTTON]; - let ours = focused(); - let mut was = [false; WATCHED.len()]; - for (i, &vk) in WATCHED.iter().enumerate() { - // SAFETY: a plain query. - was[i] = ours && unsafe { GetAsyncKeyState(i32::from(vk)) } < 0; - } + const WATCHED: [u16; 7] = [VK_F1, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_RETURN, VK_ESCAPE]; + const REPEAT_DELAY: u32 = 30; + const REPEAT_EVERY: u32 = 6; + let mut held = [0u32; WATCHED.len()]; loop { std::thread::sleep(Duration::from_millis(10)); let ours = focused(); - let open = Menu::open(); for (i, &vk) in WATCHED.iter().enumerate() { - // SAFETY: a plain query. let down = ours && unsafe { GetAsyncKeyState(i32::from(vk)) } < 0; - let is_mouse = vk == VK_LBUTTON || vk == VK_RBUTTON; - if down && !was[i] && (!is_mouse || open) { - MENU_KEYS.lock().unwrap_or_else(|e| e.into_inner()).push(MenuKey::Keyboard(vk)); + if down { + let repeatable = matches!(vk, VK_UP | VK_DOWN | VK_LEFT | VK_RIGHT); + let fire = held[i] == 0 + || (repeatable + && held[i] >= REPEAT_DELAY + && (held[i] - REPEAT_DELAY) % REPEAT_EVERY == 0); + if fire { + MENU_KEYS.lock().unwrap_or_else(|e| e.into_inner()).push(MenuKey::Keyboard(vk)); + } + held[i] = held[i].saturating_add(1); + } else { + held[i] = 0; } - was[i] = down; } } }); }); } -/// The box's size in pixels. -const fn size(scale: u32) -> (u32, u32) { - ((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale) +fn scale_pct(height: u32) -> u32 { + std::env::var("VICTORY_UI_PCT").ok().and_then(|v| v.parse::().ok()).filter(|&s| s >= 50).unwrap_or_else(|| ((height * 117) / 1080).clamp(95, 275)) } -/// Maps client-area coordinates `(cx, cy)` inside `(client_w, client_h)` to swap-chain -/// coordinates `(bx, by)` inside `(width, height)`. -fn client_to_backbuffer(cx: i32, cy: i32, client_w: i32, client_h: i32, width: u32, height: u32) -> Option<(u32, u32)> { - if client_w <= 0 || client_h <= 0 || width == 0 || height == 0 { - return None; - } - if cx < 0 || cy < 0 || cx >= client_w || cy >= client_h { - return None; - } - let bx = ((cx as u64 * u64::from(width)) / client_w as u64) as u32; - let by = ((cy as u64 * u64::from(height)) / client_h as u64) as u32; - Some((bx.min(width - 1), by.min(height - 1))) +#[inline] +fn s(base: u32, pct: u32) -> u32 { + ((base * pct) + 50) / 100 } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct BoxHit { - row: usize, - col: u32, +fn menu_size(pct: u32) -> (u32, u32) { + (s(676, pct).max(490), s(592, pct).max(416)) } -/// Maps swap-chain coordinates `(bx, by)` to the visible row (from `visible_rows`, starting at -/// text line `start_line`) and character column `0..COLUMNS` inside the centered menu box. -fn hit_test_menu_box( - (bx, by): (u32, u32), - (width, height): (u32, u32), - start_line: usize, - visible_rows: &[usize], -) -> Option { - if width == 0 || height == 0 { - return None; - } - let scale = (height / 540).max(1); - let (full_w, full_h) = size(scale); - let (w, h) = (full_w.min(width), full_h.min(height)); - let (box_x, box_y) = ((width - w) / 2, (height - h) / 2); - if bx < box_x || bx >= box_x + w || by < box_y || by >= box_y + h { - return None; - } - let ux = (bx - box_x) / scale; - let uy = (by - box_y) / scale; - let (Some(ix), Some(iy)) = (ux.checked_sub(RIM), uy.checked_sub(RIM)) else { - return None; - }; - let col = ix / CELL.0; - let line = (iy / CELL.1) as usize; - if col >= COLUMNS || line >= LINES as usize { - return None; - } - let rel = line.checked_sub(start_line)?; - let &row = visible_rows.get(rel)?; - Some(BoxHit { row, col }) -} - -/// Direction (`-1` or `+1`) for a click at character column `col` on setting row `row`. -fn setting_step(row: usize, col: u32) -> isize { - let lt_col = 2 + ITEMS[row].label.chars().count().max(27) as u32 + 1; - if col <= lt_col + 1 { -1 } else { 1 } -} - -fn lit(lines: &[String], x: u32, y: u32) -> bool { - let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else { - return false; - }; - if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS { - return false; - } - let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else { - return false; - }; - // Only the leading `>` is a selection marker. The value brackets keep their normal glyphs. - let bitmap = if x < CELL.0 && c == b'>' { SELECTION_MARKER } else { glyph(c.to_ascii_uppercase()) }; - (bitmap[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0 -} - -fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec { - let (width, height) = size(scale); - let bytes = colours[0].len(); - let mut out = vec![0; pitch * height as usize]; - for y in 0..height / scale { - let top = pitch * (y * scale) as usize; - for x in 0..width / scale { - let colour = colours[usize::from(lit(lines, x, y))]; - for i in 0..scale { - let at = top + (x * scale + i) as usize * bytes; - out[at..at + bytes].copy_from_slice(colour); - } - } - for i in 1..scale as usize { - out.copy_within(top..top + pitch, top + i * pitch); - } - } - out +fn pill_size(pct: u32) -> (u32, u32) { + (s(220, pct).max(160), s(30, pct).max(24)) } struct Buffers { format: DXGI_FORMAT, - scale: u32, + pct: u32, + width: u32, + height: u32, pitch: u32, uploads: Vec<(ID3D12Resource, *mut u8)>, card: ID3D12Resource, turn: usize, fresh: bool, - /// The card's buffer was copied into before (it is in the copy-source state; - /// at first it is in the common state, promoted by the first copy). used: bool, } -// SAFETY: free-threaded resources, and memory only written under the presenter's lock. unsafe impl Send for Buffers {} impl Buffers { - fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option { - let (width, height) = size(scale); - let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256); + fn new(host: &Host, format: DXGI_FORMAT, pct: u32) -> Option { + let (width, height) = menu_size(pct); + let pitch = (width * bpp(format)?).next_multiple_of(256); let bytes = u64::from(pitch) * u64::from(height); let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::>>()?; let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; @@ -972,62 +728,39 @@ impl Buffers { ..Default::default() }; let mut card: Option = None; - // SAFETY: plain creation of a buffer. unsafe { host.device .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card) .ok()?; } - Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false, used: false }) + Some(Buffers { format, pct, width, height, pitch, uploads, card: card?, turn: 0, fresh: false, used: false }) } - fn write(&mut self, lines: &[String]) { - let Some(colours) = colours(self.format) else { return }; - let picture = painted(lines, self.scale, colours, self.pitch as usize); + fn upload(&mut self, picture: Vec) { self.turn = (self.turn + 1) % UPLOADS; - // SAFETY: a mapped upload buffer of the picture's size, which the card read frames ago. unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) }; self.fresh = true; } } -/// The menu of a presenter. pub(super) struct Menu { - /// The values chosen, by item (as at start until changed). values: Vec, - /// The values at start, then at the last save: [`Menu::save`] writes what differs. started: Vec, - /// The values at start, never changed: one the list lacks stays in [`Menu::change`]'s cycle. - launched: Vec, - /// The line picked: an item, or an action after them. at: usize, note: String, changed: bool, - /// What the buffer holds: the frame-rate line, or (none) the menu's lines. painted: Option, buffers: Option, failed: bool, - /// The picture the failed buffers were for: a change of it tries again. - failed_at: Option<(DXGI_FORMAT, u32)>, - /// The saves in `Saves` that can be imported (read when the menu opens), and the line - /// picked in their list (`imports.len()`: the line back), shown while `picking`. imports: Vec, import_at: usize, picking: bool, - /// The key bindings list, while it is shown. binds: Option, - /// Swap-chain dimensions and integer UI scale captured by `draw`. - backbuffer: (u32, u32), - scale: u32, - /// Last mapped swap-chain cursor position, so stationary cursor doesn't fight Up/Down. - last_cursor: Option<(u32, u32)>, } impl Menu { pub(super) fn new() -> Menu { - // Start the key thread now: F1 must be seen while the menu is closed. watch_keys(); - // `VICTORY_MENU_OPEN=1`: shown from the start (to look at it in a run nobody presses keys in). if std::env::var_os("VICTORY_MENU_OPEN").is_some_and(|v| v == "1") { crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed); } @@ -1042,66 +775,39 @@ impl Menu { } }) .collect(); - Menu { started: values.clone(), launched: values.clone(), values, at: 0, note: String::new(), changed: true, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None } + Menu { + started: values.clone(), + values, + at: 0, + note: String::new(), + changed: true, + painted: None, + buffers: None, + failed: false, + imports: Vec::new(), + import_at: 0, + picking: false, + binds: None, + } } fn open() -> bool { crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed) } - /// The value of the setting `var` as the menu holds it now. fn value(&self, var: &str) -> &str { ITEMS.iter().position(|i| i.var == var).map_or("", |i| self.values[i].as_str()) } - /// Row `row` is left out: the picture row of the console not picked. fn hidden(&self, row: usize) -> bool { let series_s = self.value(CONSOLE) == "series-s"; ITEMS.get(row).is_some_and(|i| if series_s { i.var == X_RES } else { i.var == S_RES }) } - /// The rows shown, settings then actions. fn rows(&self) -> Vec { (0..ITEMS.len() + ACTIONS.len()).filter(|r| !self.hidden(*r)).collect() } - /// Visible main-menu rows in the current scroll window. - fn main_visible_rows(&self) -> Vec { - let rows = self.rows(); - let total = rows.len(); - let at = rows.iter().position(|r| *r == self.at).unwrap_or(0); - let first = at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); - rows[first..(first + ROWS).min(total)].to_vec() - } - - /// Starting text line and visible save-list rows (`picking` mode). - fn pick_visible_layout(&self) -> (usize, Vec) { - let start_line = if self.imports.is_empty() { 4 } else { 3 }; - let rows = ROWS - (start_line - 3); - let total = self.imports.len() + 1; - let first = self.import_at.saturating_sub(rows / 2).min(total.saturating_sub(rows)); - (start_line, (first..(first + rows).min(total)).collect()) - } - - /// Visible key-binding rows in the current scroll window. - fn bind_visible_rows(b: &binds::Binds) -> Vec { - let total = binds::ROWS.len() + 1; - let first = b.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); - (first..(first + ROWS).min(total)).collect() - } - - /// Starting text line and visible row indices for whichever mode is active. - fn visible_layout(&self) -> (usize, Vec) { - if self.picking { - self.pick_visible_layout() - } else if let Some(b) = &self.binds { - (3, Self::bind_visible_rows(b)) - } else { - (3, self.main_visible_rows()) - } - } - - /// The row shown `step` (+1 / -1) from the one picked, round the ends. fn step(&self, step: isize) -> usize { let rows = self.rows(); let n = rows.len() as isize; @@ -1111,174 +817,310 @@ impl Menu { } } - fn lines(&self) -> Vec { - self.lines_with_streamline(std::env::var_os("VICTORY_STREAMLINE_DIR").is_some()) - } + fn render_menu(&self, width: u32, height: u32, pct: u32, format: DXGI_FORMAT, pitch: usize) -> Option> { + let mut c = Canvas::new(width, height)?; + let border = (pct / 100).max(1); + let bar_h = s(3, pct).max(2); + let pad_x = s(16, pct) as i32; + let shadow = (pct / 110).max(1) as i32; - fn lines_with_streamline(&self, streamline_configured: bool) -> Vec { + c.clear(theme::BG); + c.stroke_border(border, theme::BORDER); + c.top_gradient_bar(bar_h, theme::PINK, theme::CYAN); + + let hdr_y = (bar_h + s(10, pct)) as i32; + let div1_y = bar_h + s(51, pct); + let row_h = s(21, pct) as i32; + let f_row = s(13, pct) as i32; + let f_tag = s(11, pct) as i32; + let footer_y = height.saturating_sub(s(94, pct)); + let f_foot = s(11, pct) as i32; + + // 1. IMPORT SAVE picker view if self.picking { - return self.pick_lines(); + let (right_hint, help) = if crate::settings_pad_mode() != crate::SettingsPadMode::Off { + ("ESC / B: BACK", "UP/DOWN PICK ENTER OR A TWICE TO IMPORT") + } else { + ("ESC: BACK", PICK_HELP) + }; + c.text(pad_x, hdr_y, PICK_TITLE, "Segoe UI", s(17, pct) as i32, true, theme::TEXT, shadow); + c.text_right(width as i32 - pad_x, hdr_y + s(3, pct) as i32, right_hint, "Consolas", s(12, pct) as i32, false, theme::MUTED, shadow); + c.text(pad_x, hdr_y + s(23, pct) as i32, help, "Consolas", s(11, pct) as i32, false, theme::MUTED, shadow); + c.fill_rect(pad_x as u32, div1_y, width.saturating_sub(pad_x as u32), div1_y + border, theme::DIVIDER); + + let mut y = (div1_y + s(8, pct)) as i32; + let mut avail = ROWS; + if self.imports.is_empty() { + c.text(s(22, pct) as i32, y, PICK_NONE, "Consolas", f_row, false, theme::AMBER, shadow); + y += row_h; + avail = ROWS.saturating_sub(1); + } + let total = self.imports.len() + 1; + let first = self.import_at.saturating_sub(avail / 2).min(total.saturating_sub(avail)); + for row in first..(first + avail).min(total) { + let selected = row == self.import_at; + if selected { + let ry0 = (y - s(2, pct) as i32).max(0) as u32; + let ry1 = (y + row_h - s(3, pct) as i32).max(0) as u32; + c.fill_rect(s(10, pct), ry0, width.saturating_sub(s(10, pct)), ry1, theme::ROW_HI); + c.fill_rect(s(10, pct), ry0, s(13, pct), ry1, theme::PINK); + } + let (name, col) = match self.imports.get(row) { + Some(n) => (shown_name(n), if selected { theme::CYAN } else { theme::TEXT }), + None => (PICK_BACK.to_owned(), theme::PINK), + }; + c.text(s(22, pct) as i32, y, &name, "Consolas", f_row, selected, col, shadow); + y += row_h; + } + + c.fill_rect(pad_x as u32, footer_y, width.saturating_sub(pad_x as u32), footer_y + border, theme::DIVIDER); + let mut fy = (footer_y + s(7, pct)) as i32; + for line in ABOUT_PICK { + c.text(pad_x, fy, line, "Consolas", f_foot, false, theme::CYAN, shadow); + fy += s(14, pct) as i32; + } + let note_txt = if self.note.is_empty() { + format!("{} IN SAVES", self.imports.len()) + } else { + self.note.clone() + }; + c.text(pad_x, fy, ¬e_txt, "Consolas", f_foot, false, theme::AMBER, shadow); + c.text(pad_x, fy + s(16, pct) as i32, REPO, "Consolas", f_foot, false, theme::MUTED, shadow); + return c.pack(format, pitch); } + + // 2. KEY BINDINGS sub-menu view if let Some(b) = &self.binds { - return self.bind_lines(b); + c.text(pad_x, hdr_y, BINDS_TITLE, "Segoe UI", s(17, pct) as i32, true, theme::TEXT, shadow); + c.text_right(width as i32 - pad_x, hdr_y + s(3, pct) as i32, "ESC: BACK", "Consolas", s(12, pct) as i32, false, theme::MUTED, shadow); + c.text(pad_x, hdr_y + s(23, pct) as i32, BINDS_HELP, "Consolas", s(11, pct) as i32, false, theme::MUTED, shadow); + c.fill_rect(pad_x as u32, div1_y, width.saturating_sub(pad_x as u32), div1_y + border, theme::DIVIDER); + + let val_x = s(366, pct) as i32; + let mut y = (div1_y + s(8, pct)) as i32; + let total = binds::ROWS.len() + 1; + let first = b.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); + for row in first..(first + ROWS).min(total) { + let selected = row == b.at; + if selected { + let ry0 = (y - s(2, pct) as i32).max(0) as u32; + let ry1 = (y + row_h - s(3, pct) as i32).max(0) as u32; + c.fill_rect(s(10, pct), ry0, width.saturating_sub(s(10, pct)), ry1, theme::ROW_HI); + c.fill_rect(s(10, pct), ry0, s(13, pct), ry1, theme::PINK); + } + match binds::ROWS.get(row) { + Some((name, label)) => { + let value = b.value(name); + let shown = if value.is_empty() { "NONE" } else { &value }; + let lbl_col = if selected { theme::TEXT } else { theme::LABEL }; + let val_col = if shown == "NONE" { theme::MUTED } else { theme::CYAN }; + c.text(s(22, pct) as i32, y, label, "Consolas", f_row, selected, lbl_col, shadow); + c.text(val_x, y, shown, "Consolas", f_row, selected, val_col, shadow); + } + None => { + c.text(s(22, pct) as i32, y, BINDS_BACK, "Consolas", f_row, true, theme::PINK, shadow); + } + } + y += row_h; + } + + c.fill_rect(pad_x as u32, footer_y, width.saturating_sub(pad_x as u32), footer_y + border, theme::DIVIDER); + let mut fy = (footer_y + s(7, pct)) as i32; + for line in ABOUT_BINDS { + c.text(pad_x, fy, line, "Consolas", f_foot, false, theme::CYAN, shadow); + fy += s(14, pct) as i32; + } + let note_txt = if self.note.is_empty() { + "SAVED TO BINDINGS.INI IMMEDIATELY" + } else { + &self.note + }; + c.text(pad_x, fy, note_txt, "Consolas", f_foot, false, theme::AMBER, shadow); + c.text(pad_x, fy + s(16, pct) as i32, REPO, "Consolas", f_foot, false, theme::MUTED, shadow); + return c.pack(format, pitch); } - let visible = self.main_visible_rows(); - let pad_help = "D-PAD/ARROWS PICK OR CHANGE A/CROSS OR ENTER SELECTS"; - let (title, help) = match crate::settings_pad_mode() { - crate::SettingsPadMode::StickShortcut => ("SETTINGS F1/ESC OR L3+R3 OR B/CIRCLE CLOSES", pad_help), - crate::SettingsPadMode::MenuOnly => ("SETTINGS F1/ESC OR B/CIRCLE CLOSES", pad_help), - crate::SettingsPadMode::Off => ("SETTINGS F1 OR ESC CLOSES", "UP/DOWN PICK LEFT/RIGHT CHANGE ENTER DOES IT"), + + // 3. Normal settings menu + let (close_hint, help) = match crate::settings_pad_mode() { + crate::SettingsPadMode::StickShortcut => ("F1 / ESC / L3+R3 / B", "D-PAD/ARROWS PICK OR CHANGE A/ENTER APPLY"), + crate::SettingsPadMode::MenuOnly => ("F1 / ESC / B: CLOSE", "D-PAD/ARROWS PICK OR CHANGE A/ENTER APPLY"), + crate::SettingsPadMode::Off => ("F1 / ESC: CLOSE", "UP/DOWN PICK LEFT/RIGHT CHANGE (AUTO-SAVES) ENTER APPLY"), }; - let mut out = vec![title.to_owned(), help.to_owned(), String::new()]; - for row in visible { - let cursor = if row == self.at { '>' } else { ' ' }; - let line = if let Some(item) = ITEMS.get(row) { + c.text(pad_x, hdr_y, "VICTORY-NVIDIA SETTINGS", "Segoe UI", s(17, pct) as i32, true, theme::TEXT, shadow); + c.text_right(width as i32 - pad_x, hdr_y + s(3, pct) as i32, close_hint, "Consolas", s(12, pct) as i32, false, theme::MUTED, shadow); + c.text(pad_x, hdr_y + s(23, pct) as i32, help, "Consolas", s(11, pct) as i32, false, theme::MUTED, shadow); + c.fill_rect(pad_x as u32, div1_y, width.saturating_sub(pad_x as u32), div1_y + border, theme::DIVIDER); + + let rows = self.rows(); + let total = rows.len(); + let at = rows.iter().position(|r| *r == self.at).unwrap_or(0); + let first = at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); + let val_x = s(366, pct) as i32; + let mut y = (div1_y + s(8, pct)) as i32; + + for &row in &rows[first..(first + ROWS).min(total)] { + let selected = row == self.at; + if selected { + let ry0 = (y - s(2, pct) as i32).max(0) as u32; + let ry1 = (y + row_h - s(3, pct) as i32).max(0) as u32; + c.fill_rect(s(10, pct), ry0, width.saturating_sub(s(10, pct)), ry1, theme::ROW_HI); + c.fill_rect(s(10, pct), ry0, s(13, pct), ry1, theme::PINK); + } + if let Some(item) = ITEMS.get(row) { let value = &self.values[row]; let shown = shown_value(item, value); - let mark = if *value != self.started[row] { if live(item) { " *LIVE" } else { " *" } } else if live(item) { " LIVE" } else { "" }; - format!("{cursor} {:<27} < {shown} >{mark}", item.label) + let is_changed = *value != self.started[row]; + let is_live = live(item); + let lbl_col = if selected { theme::TEXT } else { theme::LABEL }; + c.text(s(22, pct) as i32, y, item.label, "Consolas", f_row, selected, lbl_col, shadow); + + let val_col = match shown.as_str() { + "ON" | "2X" | "3X" | "4X" | "5X" | "6X (MOST)" => theme::MINT, + "OFF" | "0% (OFF)" | "NOT SET" => theme::MUTED, + "DLSS" | "QUALITY" | "BALANCED" | "PERFORMANCE" | "ULTRA PERFORMANCE" + | "DLAA (NATIVE)" | "3840X2160" | "2560X1440" | "1280X720 (THE GAME)" + | "1113X626" | "960X540" | "640X360 (FASTEST)" | "ENTER OPENS" => theme::CYAN, + _ => theme::TEXT, + }; + let val_txt = format!("< {shown} >"); + c.text(val_x, y, &val_txt, "Consolas", f_row, selected, val_col, shadow); + + let tag = if is_changed { + if is_live { "*LIVE" } else { "*" } + } else if is_live { + "LIVE" + } else { + "" + }; + if !tag.is_empty() { + let tag_col = if is_changed { theme::AMBER } else { theme::MINT }; + c.text_right(width as i32 - pad_x, y + s(2, pct) as i32, tag, "Consolas", f_tag, true, tag_col, shadow); + } } else { - format!("{cursor} {}", ACTIONS[row - ITEMS.len()]) - }; - out.push(line.chars().take(COLUMNS as usize).collect()); + let act_idx = row - ITEMS.len(); + let act_col = if act_idx == SAVE_RESTART || act_idx == SAVE_QUIT { + theme::PINK + } else if act_idx == SAVE_NEXT || act_idx == EXPORT || act_idx == IMPORT { + theme::CYAN + } else if act_idx == CLEAR || act_idx == RESET { + theme::AMBER + } else if selected { + theme::TEXT + } else { + theme::LABEL + }; + c.text(s(22, pct) as i32, y, ACTIONS[act_idx], "Consolas", f_row, true, act_col, shadow); + } + y += row_h; } - while out.len() < 3 + ROWS { - out.push(String::new()); - } - out.push(String::new()); - let about = if self.at == ITEMS.len() + PRELOAD { - ABOUT_PRELOAD + + // Per-item description + Footer + c.fill_rect(pad_x as u32, footer_y, width.saturating_sub(pad_x as u32), footer_y + border, theme::DIVIDER); + let mut fy = (footer_y + s(7, pct)) as i32; + let streamline_configured = std::env::var_os("VICTORY_STREAMLINE_DIR").is_some(); + let (about, about_col): ([&str; 3], _) = if self.at == ITEMS.len() + PRELOAD { + (ABOUT_PRELOAD, theme::CYAN) } else if self.at == ITEMS.len() + CLEAR { - ABOUT_CLEAR + (ABOUT_CLEAR, theme::AMBER) } else if self.at == ITEMS.len() + EXPORT { - ABOUT_EXPORT + (ABOUT_EXPORT, theme::CYAN) } else if self.at == ITEMS.len() + IMPORT { - ABOUT_IMPORT + (ABOUT_IMPORT, theme::CYAN) } else if ITEMS.get(self.at).is_some_and(|i| i.var == MFG) { - ABOUT_MFG + (ABOUT_MFG, theme::AMBER) } else if ITEMS.get(self.at).is_some_and(|i| i.var == S_RES) { - ABOUT_S_RES + (ABOUT_S_RES, theme::CYAN) } else if ITEMS.get(self.at).is_some_and(|i| i.var == FORCE_MFG) { - ABOUT_FORCE_MFG + (ABOUT_FORCE_MFG, theme::AMBER) } else if ITEMS.get(self.at).is_some_and(|i| i.var == "VICTORY_SHADOW_LIFT") { - ABOUT_SHADOW_LIFT + (ABOUT_SHADOW_LIFT, theme::CYAN) } else if ITEMS.get(self.at).is_some_and(|i| i.var == DLSS) && !matches!(self.values[self.at].as_str(), "" | "off") && !streamline_configured { - ABOUT_NO_DLSS + (ABOUT_NO_DLSS, theme::AMBER) } else if ITEMS.get(self.at).is_some_and(|i| i.var == FRAMEGEN && !live(i)) && !matches!(self.values[self.at].as_str(), "" | "0") { - ABOUT_FRAMEGEN_RESTART + (ABOUT_FRAMEGEN_RESTART, theme::AMBER) } else if self.at == ITEMS.len() + SAVE_RESTART { - ABOUT_SAVE_RESTART + (ABOUT_SAVE_RESTART, theme::PINK) } else if self.at == ITEMS.len() + SAVE_NEXT { - ABOUT_SAVE_NEXT + (ABOUT_SAVE_NEXT, theme::CYAN) } else if self.at == ITEMS.len() + SAVE_QUIT { - ABOUT_SAVE_QUIT + (ABOUT_SAVE_QUIT, theme::PINK) } else if self.at == ITEMS.len() + RESET { - ABOUT_RESET + (ABOUT_RESET, theme::AMBER) } else if self.at == ITEMS.len() + CLOSE { - ABOUT_CLOSE + (ABOUT_CLOSE, theme::MUTED) } else { - ITEMS.get(self.at).map_or([""; 3], |i| about_item(i.var)) + (ITEMS.get(self.at).map_or([""; 3], |i| about_item(i.var)), theme::CYAN) }; - out.extend(about.iter().map(|l| (*l).to_owned())); - out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() }); - out.push(REPO.to_owned()); - out + for line in about { + if !line.is_empty() { + c.text(pad_x, fy, line, "Consolas", f_foot, false, about_col, shadow); + } + fy += s(14, pct) as i32; + } + let note_txt = if self.note.is_empty() { + "* = CHANGED (AUTO-SAVED, APPLIES NEXT START UNLESS LIVE)" + } else { + &self.note + }; + c.text(pad_x, fy, note_txt, "Consolas", f_foot, false, theme::AMBER, shadow); + c.text(pad_x, fy + s(16, pct) as i32, REPO, "Consolas", f_foot, false, theme::MUTED, shadow); + + c.pack(format, pitch) } - /// The list KEY BINDINGS opens, in the box's lines. - fn bind_lines(&self, b: &binds::Binds) -> Vec { - let mut out = vec![BINDS_TITLE.to_owned(), BINDS_HELP.to_owned(), String::new()]; - let total = binds::ROWS.len() + 1; - let first = b.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); - for row in first..(first + ROWS).min(total) { - let cursor = if row == b.at { '>' } else { ' ' }; - let line = match binds::ROWS.get(row) { - Some((name, label)) => { - let value = b.value(name); - format!("{cursor} {label:<27} {}", if value.is_empty() { "NONE" } else { &value }) - } - None => format!("{cursor} {BINDS_BACK}"), - }; - out.push(line.chars().take(COLUMNS as usize).collect()); + fn render_pill(line: &str, buf_w: u32, buf_h: u32, pct: u32, format: DXGI_FORMAT, pitch: usize) -> Option> { + let (pw, ph) = pill_size(pct); + let mut c = Canvas::new(buf_w, buf_h)?; + let border = (pct / 100).max(1); + let bar_h = s(2, pct).max(2); + let shadow = (pct / 110).max(1) as i32; + + c.clear(theme::BG); + c.fill_rect(0, 0, pw, ph, theme::BG); + c.fill_rect(0, 0, pw, border, theme::BORDER); + c.fill_rect(0, ph.saturating_sub(border), pw, ph, theme::BORDER); + c.fill_rect(0, 0, border, ph, theme::BORDER); + c.fill_rect(pw.saturating_sub(border), 0, pw, ph, theme::BORDER); + let span = pw.saturating_sub(1).max(1) as f32; + for x in 0..pw { + let t = x as f32 / span; + let r = (f32::from(theme::PINK.0) + (f32::from(theme::CYAN.0) - f32::from(theme::PINK.0)) * t).round() as u8; + let g = (f32::from(theme::PINK.1) + (f32::from(theme::CYAN.1) - f32::from(theme::PINK.1)) * t).round() as u8; + let b = (f32::from(theme::PINK.2) + (f32::from(theme::CYAN.2) - f32::from(theme::PINK.2)) * t).round() as u8; + c.fill_rect(x, 0, x + 1, bar_h, (r, g, b)); } - while out.len() < 3 + ROWS { - out.push(String::new()); - } - out.push(String::new()); - out.extend(ABOUT_BINDS.iter().map(|l| (*l).to_owned())); - out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() }); - out.push(REPO.to_owned()); - out + c.text(s(10, pct) as i32, (bar_h + s(5, pct)) as i32, line, "Consolas", s(14, pct) as i32, true, theme::CYAN, shadow); + c.pack(format, pitch) } - /// While a binding waits for its key: the key or button pressed is written. fn hear_binding(&mut self) { let Some(b) = self.binds.as_mut() else { return }; - let vk = match b.heard() { - binds::Heard::Key(vk) => vk, - binds::Heard::Lost => { - self.note = BINDS_LOST.to_owned(); - self.changed = true; - return; - } - binds::Heard::Nothing => return, - }; + let Some(vk) = b.heard() else { return }; let (name, label) = binds::ROWS[b.at]; let key = binds::name(vk); - self.note = if b.set(name, &key) { format!("{label}: {}", key.to_ascii_uppercase()) } else { "COULD NOT SAVE BINDINGS.INI".to_owned() }; + self.note = if b.set(name, &key) { + format!("{label}: {}", key.to_ascii_uppercase()) + } else { + "COULD NOT SAVE BINDINGS.INI".to_owned() + }; self.note = self.note.chars().take(COLUMNS as usize).collect(); self.changed = true; } - /// The list IMPORT SAVE opens, in the box's lines. - fn pick_lines(&self) -> Vec { - let (title, help) = if crate::settings_pad_mode() != crate::SettingsPadMode::Off { - ("IMPORT SAVE ESC OR B/CIRCLE GOES BACK", "UP/DOWN PICK ENTER OR A/CROSS TWICE TO IMPORT") - } else { - (PICK_TITLE, PICK_HELP) - }; - let mut out = vec![title.to_owned(), help.to_owned(), String::new()]; - if self.imports.is_empty() { - out.push(PICK_NONE.to_owned()); - } - let (_, visible) = self.pick_visible_layout(); - for row in visible { - let cursor = if row == self.import_at { '>' } else { ' ' }; - let name = self.imports.get(row).map_or_else(|| PICK_BACK.to_owned(), |n| shown_name(n)); - out.push(format!("{cursor} {name}").chars().take(COLUMNS as usize).collect()); - } - while out.len() < 3 + ROWS { - out.push(String::new()); - } - out.push(String::new()); - out.extend(ABOUT_PICK.iter().map(|l| (*l).to_owned())); - out.push(if self.note.is_empty() { format!("{} IN SAVES", self.imports.len()) } else { self.note.clone() }); - out.push(REPO.to_owned()); - out - } - - /// Changes item `i` by `step` (+1 / -1) through its values, and the one it started with if - /// the list lacks it (set by hand, as `VICTORY_AMBIENT=1.5`): after the last one. fn change(&mut self, i: usize, step: isize) { let item = &ITEMS[i]; - let listed = item.values(); - let own = self.launched.get(i).filter(|v| index_of(item, v).is_none()); - let n = (listed.len() + usize::from(own.is_some())) as isize; - let now = index_of(item, &self.values[i]) - .or_else(|| (own == Some(&self.values[i])).then_some(listed.len())) - .map_or(-1, |x| x as isize); + let n = item.values().len() as isize; + let now = index_of(item, &self.values[i]).map_or(-1, |x| x as isize); let mut next = if now < 0 { if step > 0 { 0 } else { n - 1 } } else { (now + step).rem_euclid(n) }; - // No DLAA on Series S (`S_MODES`): the DLSS line goes past it. - if item.var == DLSS && listed.get(next as usize).is_some_and(|(v, _)| *v == "dlaa") && self.value(CONSOLE) == "series-s" { + if item.var == DLSS && item.values()[next as usize].0 == "dlaa" && self.value(CONSOLE) == "series-s" { next = (next + step.signum()).rem_euclid(n); } - // Past the list: `own`, the only value there. - self.values[i] = listed.get(next as usize).map_or_else(|| own.cloned().unwrap_or_default(), |(v, _)| (*v).to_owned()); + self.values[i] = item.values()[next as usize].0.to_owned(); if live(item) { self.apply_live(i); } @@ -1289,8 +1131,6 @@ impl Menu { self.match_series_s(item.var); } - /// On Series S the scene's size and DLSS's mode are one choice: a change of either - /// (`changed`) sets the other. DLSS off is the game's 720, and 720 picked leaves it off. fn match_series_s(&mut self, changed: &str) { let (Some(dlss), Some(res)) = (ITEMS.iter().position(|i| i.var == DLSS), ITEMS.iter().position(|i| i.var == S_RES)) else { return; @@ -1298,7 +1138,6 @@ impl Menu { if self.value(CONSOLE) != "series-s" { return; } - // DLAA, picked on Series X before the console changed: the game's 720 at quality. if self.values[dlss] == "dlaa" { "quality".clone_into(&mut self.values[dlss]); "720".clone_into(&mut self.values[res]); @@ -1316,12 +1155,8 @@ impl Menu { } } - /// A setting the build reads at each use: changed in this run's environment at once. fn apply_live(&self, i: usize) { let (var, value) = (ITEMS[i].var, &self.values[i]); - // SAFETY: the variables changed here are read by this build with - // std::env::var at each use; Windows' environment block is locked by - // the process heap's routines, and std holds its own lock. unsafe { if value.is_empty() { std::env::remove_var(var); @@ -1330,7 +1165,6 @@ impl Menu { } } match var { - // Off (0) or the frames shown for each one rendered, from the next present on. "VICTORY_MENU_FRAMEGEN" => crate::streamline::set_framegen(value.parse().unwrap_or(0)), "VICTORY_FPS_LINE" => fps_line_on().store(value != "0", Ordering::Relaxed), "VICTORY_PANEL" => super::panel::shown().store(value == "1", Ordering::Relaxed), @@ -1339,30 +1173,16 @@ impl Menu { } } - /// Writes the changed values over those in the settings file. fn save(&mut self) -> bool { let Some(path) = settings_file() else { self.note = "NO FOLDER FOR THE SETTINGS FILE".to_owned(); return false; }; - self.save_to(&path) - } - - fn write_settings(&self, path: &Path) -> io::Result<()> { - // Preserve an existing symlink to the settings file when replacing its contents. - let target; - let path = if std::fs::symlink_metadata(path).is_ok_and(|entry| entry.is_symlink()) { - target = std::fs::canonicalize(path)?; - target.as_path() - } else { - path - }; - let previous = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(), - Err(error) => return Err(error), - }; - let mut kept: Vec<(String, String)> = previous + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let mut kept: Vec<(String, String)> = std::fs::read_to_string(&path) + .unwrap_or_default() .lines() .filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))) .filter(|(k, _)| k.starts_with("VICTORY_")) @@ -1372,67 +1192,39 @@ impl Menu { continue; } kept.retain(|(k, _)| k != item.var); - // A launcher's choice back to NOT SET: no line. An empty one would override the - // launcher's own option (`VICTORY_MENU_CONSOLE=` reads as Series X). - let value = &self.values[i]; - if value.is_empty() && item.var.starts_with("VICTORY_MENU_") && index_of(item, value).is_none() { - continue; - } - kept.push((item.var.to_owned(), value.clone())); + kept.push((item.var.to_owned(), self.values[i].clone())); } let mut text = String::from("# Saved by the F1 menu; applied over the play settings at every start (an empty value: unset).\r\n"); for (k, v) in &kept { text.push_str(&format!("{k}={v}\r\n")); } - let dir = path - .parent() - .filter(|dir| !dir.as_os_str().is_empty()) - .unwrap_or(Path::new(".")); - std::fs::create_dir_all(dir)?; - // Publish only after the complete settings file has been written. - let mut pending = tempfile::NamedTempFile::new_in(dir)?; - pending.write_all(text.as_bytes())?; - pending.as_file().sync_all()?; - pending.persist(path).map(|_| ()).map_err(|error| error.error) - } - - fn save_to(&mut self, path: &Path) -> bool { - match self.write_settings(path) { + match std::fs::write(&path, text) { Ok(()) => { tracing::info!(path = %path.display(), "settings menu: saved"); self.started = self.values.clone(); self.note = if std::env::var_os("VICTORY_MENU_FILE").is_some() { "SAVED. APPLIES AT THE NEXT START" } else { - // Started some other way (a script, another launcher): the file `victory play` - // reads at every start, which this start did not. "SAVED. APPLIES WHEN VICTORY.EXE STARTS THE GAME" } .to_owned(); true } Err(e) => { - tracing::warn!(path = %path.display(), error = %e, "settings menu: not saved"); + tracing::warn!(error = %e, "settings menu: not saved"); self.note = "COULD NOT SAVE THE SETTINGS FILE".to_owned(); false } } } - /// Starts the launcher again in a new console, a few seconds on, and ends this run. - /// `then` says what that start does before the game ([`Then::switch`]). fn restart(&mut self, then: Then) { self.restart_as(then, false); } - /// [`Menu::restart`]; `own_command`: without the launcher's line (a start of victory.exe by - /// hand), with the command this process was started with (a save import, which must not - /// leave the game running; the settings' restarts keep asking for the launcher). fn restart_as(&mut self, then: Then, own_command: bool) { let quoted = |s: &std::ffi::OsStr| format!("'{}'", s.to_string_lossy().replace('\'', "''")); let (play, args) = match std::env::var_os("VICTORY_MENU_PLAY") { - // By its variable, not its text: PowerShell also reads typographic quotes as quotes, - // and a launcher's path with one broke the quoted command (#563). Some(_) => ("$env:VICTORY_MENU_PLAY".to_owned(), get("VICTORY_MENU_ARGS")), None => { let Some(exe) = std::env::current_exe().ok().filter(|_| own_command) else { @@ -1444,10 +1236,6 @@ impl Menu { } }; let cwd = std::env::var_os("VICTORY_MENU_CWD").filter(|p| !p.is_empty()); - // What that start does first is asked by a variable both launchers read (victory.exe's - // preload is `--preload`, the script's `-Preload`: the script's flag given to victory.exe - // was refused, and the window closed before it could be read, 2026-11-27). A launcher that - // fails keeps its window until Enter. let command = format!( "Start-Sleep 3; {}& {play} {args}; if ($LASTEXITCODE) {{ Read-Host 'The start failed (see above). Press Enter to close this window' }}", then.switch() @@ -1459,9 +1247,6 @@ impl Menu { match new_console(&shell, cwd.as_deref()) { Ok(()) => { tracing::info!(command, ?then, "settings menu: restarting"); - // Ended at once: std::process::exit runs the DLLs' unloading, which with - // Streamline loaded did not come back (a windowless leftover process). - // SAFETY: this process, with nothing of its own left to save. unsafe { use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; TerminateProcess(GetCurrentProcess(), 0); @@ -1475,13 +1260,6 @@ impl Menu { } } - /// The warm-up start ([`warmup_seconds`]): once the game has drawn whole - /// scenes for that long, this exe is marked as warmed up - /// (`VICTORY_WARMUP_MARK`) and the game starts again. The time counts - /// from the first frame of [`SCENE_DRAWS`] draws or more, not from the - /// start: a player who waited on the title screen ("press A", about ten - /// draws a frame) was restarted after 20 seconds and still had the 14 fps - /// first run after it (2026-11-27). fn warmup(&mut self) { static BEGAN: OnceLock = OnceLock::new(); static DONE: AtomicBool = AtomicBool::new(false); @@ -1505,22 +1283,17 @@ impl Menu { tracing::info!(seconds, mark = %mark.display(), "first start of this victory.exe: warmed up; the game starts again"); self.restart(Then::Play); } else { - // The launcher arms a warm-up whenever no mark exists: one the - // host could not write would have the game come back here for - // ever, so this start goes on at its slow pace instead. tracing::warn!(mark = %mark.display(), "first start: the warmed mark could not be written; the game goes on, no restart"); self.note = "WARMED UP, BUT THE MARK WOULD NOT WRITE: THIS RUN GOES ON".to_owned(); } } - /// Reads which saves `Saves` holds, keeping the one picked if it is still there. fn read_imports(&mut self) { let picked = self.imports.get(self.import_at).cloned(); self.imports = crate::save_share::share().map(|s| crate::save_share::exports(&s)).unwrap_or_default(); self.import_at = picked.and_then(|p| self.imports.iter().position(|n| *n == p)).unwrap_or(0); } - /// Writes the game's save into a new zip in `Saves`. fn export_save(&mut self) { let (Some(data), Some(share)) = (crate::save_share::data(), crate::save_share::share()) else { self.note = "SAVE FOLDERS NOT KNOWN IN THIS START".to_owned(); @@ -1545,7 +1318,6 @@ impl Menu { } } - /// Stages the save picked to be put in place at the next start, and starts the game again. fn import_save(&mut self) { let (Some(data), Some(share)) = (crate::save_share::data(), crate::save_share::share()) else { self.note = "SAVE FOLDERS NOT KNOWN IN THIS START".to_owned(); @@ -1566,8 +1338,6 @@ impl Menu { return; } tracing::info!(name, "settings menu: save import staged; put in place at the next start"); - // At once, before an autosave of this run (the staged save replaces the live one at - // the start, so the import itself is safe either way). Back here only if it failed. self.note.clear(); self.restart_as(Then::Play, true); if !self.note.is_empty() { @@ -1575,28 +1345,13 @@ impl Menu { } } - /// Removes the settings file: the launcher's own settings at the next start. fn reset(&mut self) { if let Some(path) = settings_file() { - self.reset_at(&path); - } else { - self.note = "NO FOLDER FOR THE SETTINGS FILE".to_owned(); - } - } - - fn reset_at(&mut self, path: &Path) { - if let Err(error) = std::fs::remove_file(path) - && error.kind() != io::ErrorKind::NotFound - { - tracing::warn!(path = %path.display(), %error, "settings menu: reset failed"); - self.note = "COULD NOT RESET THE SETTINGS FILE".to_owned(); - return; + let _ = std::fs::remove_file(path); } self.note = "RESET. PLAY DEFAULTS AT THE NEXT START".to_owned(); } - /// Changes a setting and saves it at once: many players changed settings and closed the - /// menu without the save lines, and lost them. The save lines stay (and restart, preload). fn change_and_save(&mut self, i: usize, step: isize) { self.change(i, step); if self.save() && live(&ITEMS[i]) { @@ -1604,256 +1359,35 @@ impl Menu { } } - /// Closes the F1 menu and clears transient menu state. - fn close_menu(&mut self) { - crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed); - crate::SETTINGS_MENU_WHEEL.store(0, Ordering::Relaxed); - self.note.clear(); - self.picking = false; - self.binds = None; - self.last_cursor = None; - self.changed = true; - } - - /// Queries the foreground window cursor and maps it to swap-chain coordinates `(bx, by)`. - fn cursor(&self) -> Option<(u32, u32)> { - let (width, height) = self.backbuffer; - if width == 0 || height == 0 { - return None; - } - // SAFETY: plain window and cursor queries against the foreground window. - unsafe { - let hwnd = GetForegroundWindow(); - if hwnd.0.is_null() { - return None; - } - let mut process = 0; - GetWindowThreadProcessId(hwnd, Some(&mut process)); - if process != std::process::id() { - return None; - } - let mut pt = POINT::default(); - if GetCursorPos(&mut pt).is_err() || !ScreenToClient(hwnd, &mut pt).as_bool() { - return None; - } - let mut rect = RECT::default(); - if GetClientRect(hwnd, &mut rect).is_err() { - return None; - } - client_to_backbuffer(pt.x, pt.y, rect.right - rect.left, rect.bottom - rect.top, width, height) - } - } - - /// Maps swap-chain coordinates `(bx, by)` to the hit row and character column. - fn hit_test(&self, pos: (u32, u32)) -> Option { - let (start_line, visible) = self.visible_layout(); - hit_test_menu_box(pos, self.backbuffer, start_line, &visible) - } - - /// Updates hover selection only when the cursor actually moved (`!= last_cursor`). - fn handle_hover(&mut self, cursor: Option<(u32, u32)>) -> Option { - if self.binds.as_ref().is_some_and(|b| b.waiting.is_some()) { - return None; - } - let Some(pos) = cursor else { - self.last_cursor = None; - return None; - }; - let hit = self.hit_test(pos); - if self.last_cursor != Some(pos) { - self.last_cursor = Some(pos); - if let Some(hit) = hit { - let row_changed = if self.picking { - let changed = self.import_at != hit.row; - self.import_at = hit.row; - changed - } else if let Some(b) = self.binds.as_mut() { - let changed = b.at != hit.row; - b.at = hit.row; - changed - } else { - let changed = self.at != hit.row; - self.at = hit.row; - changed - }; - if row_changed { - if [CONFIRM_PRELOAD, CONFIRM_CLEAR, CONFIRM_IMPORT].contains(&self.note.as_str()) { - self.note.clear(); - } - self.changed = true; - } - } - } - hit - } - - /// Runs Enter / Left-Click logic in `picking` mode for the selected `import_at`. - fn activate_pick(&mut self, confirmed: bool) { - if self.import_at >= self.imports.len() { - self.picking = false; - self.note.clear(); - } else if !confirmed { - self.note = CONFIRM_IMPORT.to_owned(); - } else { - self.import_save(); - } - } - - /// Runs Enter / Left-Click logic for main-menu action index `action` (`0..ACTIONS.len()`). - fn activate_action(&mut self, action: usize, confirmed: bool) { - match action { - SAVE_RESTART => { - if self.save() { - self.restart(Then::Play); - } - } - SAVE_NEXT => { - self.save(); - } - SAVE_QUIT => { - if self.save() { - tracing::info!("settings menu: saved, closing the game"); - // Ended at once, as a restart ends it (`restart_as` says why). - // SAFETY: this process, with nothing of its own left to save. - #[cfg(windows)] - unsafe { - use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; - TerminateProcess(GetCurrentProcess(), 0); - } - std::process::exit(0); - } - } - PRELOAD if !confirmed => self.note = CONFIRM_PRELOAD.to_owned(), - PRELOAD => { - if self.save() { - self.restart(Then::Preload); - } - } - CLEAR if !confirmed => self.note = CONFIRM_CLEAR.to_owned(), - CLEAR => { - if self.save() { - self.restart(Then::ClearShaders); - } - } - RESET => self.reset(), - EXPORT => self.export_save(), - IMPORT => { - self.read_imports(); - self.import_at = 0; - self.picking = true; - } - _ => self.close_menu(), - } - } - - /// Handles a Left-Click at optional box hit `hit`. - fn handle_left_click(&mut self, hit: Option) { - if self.binds.as_ref().is_some_and(|b| b.waiting.is_some()) { - return; - } - let confirmed = [CONFIRM_PRELOAD, CONFIRM_CLEAR, CONFIRM_IMPORT].contains(&self.note.as_str()); - if confirmed { - self.note.clear(); - } - let Some(hit) = hit else { - if confirmed { - self.changed = true; - } - return; - }; - if self.picking { - self.import_at = hit.row; - self.activate_pick(confirmed); - } else if let Some(b) = self.binds.as_mut() { - b.at = hit.row; - if hit.row == binds::ROWS.len() { - self.binds = None; - self.note.clear(); - } else if binds::ROWS.get(hit.row).is_some_and(|(name, _)| *name == binds::SENSITIVITY) { - let step = if hit.col <= 30 { -1 } else { 1 }; - self.note = match b.sensitivity(step) { - Some(v) => format!("MOUSE SENSITIVITY: {v}"), - None => "COULD NOT SAVE BINDINGS.INI".to_owned(), - }; - } else if let Some((_, label)) = binds::ROWS.get(hit.row) { - b.listen(); - self.note = format!("PRESS A KEY OR MOUSE BUTTON: {label}").chars().take(COLUMNS as usize).collect(); - } - } else if hit.row < ITEMS.len() { - self.at = hit.row; - if ITEMS[hit.row].var == BINDS { - match binds::Binds::open() { - Some(b) => { - self.binds = Some(b); - self.note.clear(); - } - None => BINDS_OFF.clone_into(&mut self.note), - } - } else { - self.change_and_save(hit.row, setting_step(hit.row, hit.col)); - } - } else { - self.at = hit.row; - self.activate_action(hit.row - ITEMS.len(), confirmed); - } - self.changed = true; - } - - /// Handles a Right-Click while the menu is open (back from binds/picking, or close main menu). - fn handle_right_click(&mut self) { - if self.binds.as_ref().is_some_and(|b| b.waiting.is_some()) { - return; - } - if self.binds.take().is_some() { - self.note.clear(); - self.changed = true; - } else if self.picking { - self.picking = false; - self.note.clear(); - self.changed = true; - } else { - self.close_menu(); - } - } - - /// Steps selection by `notches` wheel clicks (positive = up, negative = down). - fn scroll(&mut self, notches: i32) { - if notches == 0 || self.binds.as_ref().is_some_and(|b| b.waiting.is_some()) { - return; - } - let dir = if notches > 0 { -1 } else { 1 }; - let count = notches.unsigned_abs().min(64); - for _ in 0..count { - if self.picking { - let n = self.imports.len() + 1; - self.import_at = (self.import_at as isize + dir).rem_euclid(n as isize) as usize; - } else if let Some(b) = self.binds.as_mut() { - let n = binds::ROWS.len() + 1; - b.at = (b.at as isize + dir).rem_euclid(n as isize) as usize; - } else { - self.at = self.step(dir); - } - } - if [CONFIRM_PRELOAD, CONFIRM_CLEAR, CONFIRM_IMPORT].contains(&self.note.as_str()) { - self.note.clear(); - } - self.changed = true; - } - - /// A frame was presented: the keys, mouse clicks, cursor hover, and wheel notches since the last one. pub(super) fn frame(&mut self) { self.warmup(); let (pressed, generation) = { let mut keys = MENU_KEYS.lock().unwrap_or_else(|e| e.into_inner()); (std::mem::take(&mut *keys), PAD_GENERATION.load(Ordering::Relaxed)) }; - let was_open = Self::open(); - if !was_open && pressed.is_empty() { + if pressed.is_empty() { + if Self::open() { + let notches = crate::take_settings_menu_wheel_notches(); + if notches != 0 && !self.binds.as_ref().is_some_and(|b| b.waiting.is_some()) { + let dir = if notches > 0 { -1 } else { 1 }; + for _ in 0..notches.unsigned_abs().min(64) { + if self.picking { + let n = self.imports.len() + 1; + self.import_at = (self.import_at as isize + dir).rem_euclid(n as isize) as usize; + } else if let Some(b) = self.binds.as_mut() { + let n = binds::ROWS.len() + 1; + b.at = (b.at as isize + dir).rem_euclid(n as isize) as usize; + } else { + self.at = self.step(dir); + } + } + self.changed = true; + } + } + self.hear_binding(); return; } let toggles = pressed.iter().filter(|key| matches!(key, MenuKey::Pad(VK_F1))).count(); - let cursor = if was_open { self.cursor() } else { None }; - let mut pending_hit = if was_open { self.handle_hover(cursor) } else { None }; for event in pressed { let vk = match event { MenuKey::Keyboard(vk) => vk, @@ -1861,72 +1395,52 @@ impl Menu { MenuKey::Pad(_) => continue, }; let open = Self::open(); - // Esc in the key bindings: a wait for a key ends, else back to the settings. if open && vk == VK_ESCAPE && let Some(b) = self.binds.as_mut() { if b.waiting.take().is_none() { self.binds = None; } self.note.clear(); self.changed = true; - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); continue; } - // Esc in the list of saves goes back to the settings. if open && self.picking && vk == VK_ESCAPE { self.picking = false; self.note.clear(); self.changed = true; - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); continue; } if vk == VK_F1 || (open && vk == VK_ESCAPE) { - if !open && vk == VK_F1 { - crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed); - crate::SETTINGS_MENU_WHEEL.store(0, Ordering::Relaxed); - self.note.clear(); - self.picking = false; - self.binds = None; + crate::SETTINGS_MENU_OPEN.store(!open && vk == VK_F1, Ordering::Relaxed); + self.note.clear(); + self.picking = false; + self.binds = None; + if !open { self.read_imports(); if let Some(i) = ITEMS.iter().position(|item| item.var == "VICTORY_VEHICLE_AUTO_CENTER") { self.values[i] = if get(ITEMS[i].var) == "1" { "1" } else { "" }.to_owned(); } - self.last_cursor = self.cursor(); - self.changed = true; - } else { - self.close_menu(); } - pending_hit = None; + self.changed = true; continue; } if !open { continue; } - if vk == VK_LBUTTON { - self.handle_left_click(pending_hit); - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); - continue; - } - if vk == VK_RBUTTON { - self.handle_right_click(); - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); - continue; - } - // Only an Enter right after the first one starts a preload, a clearing or an import - // (any other key clears the note, so the line picked is the one the note is about). let confirmed = [CONFIRM_PRELOAD, CONFIRM_CLEAR, CONFIRM_IMPORT].contains(&self.note.as_str()); if confirmed { self.note.clear(); } if self.picking { - let n = self.imports.len() + 1; + let (n, back) = (self.imports.len() + 1, self.import_at >= self.imports.len()); match vk { VK_UP => self.import_at = (self.import_at + n - 1) % n, VK_DOWN => self.import_at = (self.import_at + 1) % n, - VK_RETURN => self.activate_pick(confirmed), + VK_RETURN if back => self.picking = false, + VK_RETURN if !confirmed => self.note = CONFIRM_IMPORT.to_owned(), + VK_RETURN => self.import_save(), _ => {} } self.changed = true; - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); continue; } if let Some(b) = self.binds.as_mut() { @@ -1952,7 +1466,6 @@ impl Menu { } } self.changed = true; - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); continue; } match vk { @@ -1968,17 +1481,50 @@ impl Menu { None => BINDS_OFF.clone_into(&mut self.note), }, VK_RETURN if self.at < ITEMS.len() => self.change_and_save(self.at, 1), - VK_RETURN => self.activate_action(self.at - ITEMS.len(), confirmed), + VK_RETURN => match self.at - ITEMS.len() { + SAVE_RESTART => { + if self.save() { + self.restart(Then::Play); + } + } + SAVE_NEXT => { + self.save(); + } + SAVE_QUIT => { + if self.save() { + tracing::info!("settings menu: saved, closing the game"); + #[cfg(windows)] + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + TerminateProcess(GetCurrentProcess(), 0); + } + std::process::exit(0); + } + } + PRELOAD if !confirmed => self.note = CONFIRM_PRELOAD.to_owned(), + PRELOAD => { + if self.save() { + self.restart(Then::Preload); + } + } + CLEAR if !confirmed => self.note = CONFIRM_CLEAR.to_owned(), + CLEAR => { + if self.save() { + self.restart(Then::ClearShaders); + } + } + RESET => self.reset(), + EXPORT => self.export_save(), + IMPORT => { + self.read_imports(); + self.import_at = 0; + self.picking = true; + } + _ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed), + }, _ => {} } self.changed = true; - pending_hit = cursor.and_then(|pos| self.hit_test(pos)); - } - if Self::open() { - let notches = crate::take_settings_menu_wheel_notches(); - if notches != 0 { - self.scroll(notches); - } } if toggles != 0 { PAD_TOGGLES.fetch_sub(toggles, Ordering::Release); @@ -1986,53 +1532,54 @@ impl Menu { self.hear_binding(); } - /// Records the copy of the box onto `back` (in the copy-destination state). pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) { - // A failed making of the buffers gives up on this picture only: a - // resize (or a format change) tries again, so one transient - // failure does not take the menu and the frame-rate line away for - // the run. - let scale = (height / 540).max(1); - if self.failed && self.failed_at == Some((format, scale)) { - self.backbuffer = (width, height); - self.scale = scale; + if self.failed { return; } - // Closed: the frame-rate line in the top left corner, if it is wanted and there is a rate. let open = Self::open(); let line = if open { None } else { fps_line() }; if !open && line.is_none() { return; } - // Our own copies are not part of a recorded frame (the recorder is in diagnostics builds). #[cfg(feature = "diagnostics")] let _ours = crate::replay::record::unrecorded(); - if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + let pct = scale_pct(height); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) { std::mem::forget(self.buffers.take()); - self.buffers = Buffers::new(host, format, scale); + self.buffers = Buffers::new(host, format, pct); self.failed = self.buffers.is_none(); - self.failed_at = self.failed.then_some((format, scale)); self.changed = true; } if self.painted != line { self.painted = line.clone(); self.changed = true; } - let lines = if self.changed { Some(line.as_ref().map_or_else(|| self.lines(), |l| vec![l.clone()])) } else { None }; - let Some(buffers) = &mut self.buffers else { return }; - if let Some(lines) = lines { + let Some((bw, bh, bpitch)) = self.buffers.as_ref().map(|b| (b.width, b.height, b.pitch as usize)) else { return }; + let pic = if self.changed { self.changed = false; - buffers.write(&lines); + match &line { + Some(l) => Self::render_pill(l, bw, bh, pct, format, bpitch), + None => self.render_menu(bw, bh, pct, format, bpitch), + } + } else { + None + }; + let Some(buffers) = &mut self.buffers else { return }; + if let Some(p) = pic { + buffers.upload(p); } - // The whole box in the middle, or of it the first line's part in the corner. let (w, h) = match &line { - Some(l) => ((l.len() as u32 * CELL.0 + 2 * RIM) * scale, (CELL.1 + 2 * RIM) * scale), - None => size(scale), + Some(_) => pill_size(pct), + None => (buffers.width, buffers.height), }; let (w, h) = (w.min(width), h.min(height)); - let (x, y) = if line.is_some() { (0, 0) } else { ((width - w) / 2, (height - h) / 2) }; + let margin = s(10, pct); + let (x, y) = if line.is_some() { + (margin.min(width.saturating_sub(w)), margin.min(height.saturating_sub(h))) + } else { + ((width - w) / 2, (height - h) / 2) + }; let list = &list.list; - // SAFETY: an open list and live resources; the box lies within both. unsafe { if std::mem::take(&mut buffers.fresh) { if std::mem::replace(&mut buffers.used, true) { @@ -2047,7 +1594,13 @@ impl Menu { Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: 0, - Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: size(scale).0, Height: size(scale).1, Depth: 1, RowPitch: buffers.pitch }, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: format, + Width: buffers.width, + Height: buffers.height, + Depth: 1, + RowPitch: buffers.pitch, + }, }, }, }; @@ -2062,15 +1615,12 @@ impl Menu { } } -/// The mouse and keyboard bindings (`bindings.ini`, F1's MOUSE AND KEYBOARD) as KEY BINDINGS -/// edits them: a line's keys replaced by the one pressed, written at once. mod binds { use std::path::PathBuf; use std::sync::atomic::Ordering::Relaxed; use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; pub(super) const SENSITIVITY: &str = "Sensitivity"; - /// The name in the file, and on the line. pub(super) const ROWS: [(&str, &str); 21] = [ ("MoveUp", "MOVE FORWARD"), ("MoveDown", "MOVE BACK"), @@ -2099,37 +1649,20 @@ mod binds { file: PathBuf, text: String, pub(super) at: usize, - /// Waiting for a key: what was held when the wait began (it must be let go first). pub(super) waiting: Option<[bool; 256]>, } impl Binds { - /// The file the game was started with (VICTORY_MNK_BINDINGS), if any. pub(super) fn open() -> Option { - Self::read(PathBuf::from(std::env::var_os("VICTORY_MNK_BINDINGS")?)) - } - - /// The bindings in `file`, if it reads. - pub(super) fn read(file: PathBuf) -> Option { + let file = PathBuf::from(std::env::var_os("VICTORY_MNK_BINDINGS")?); let text = std::fs::read_to_string(&file).ok()?; Some(Binds { file, text, at: 0, waiting: None }) } - #[cfg(test)] - pub(super) fn of(text: &str) -> Binds { - Binds { file: PathBuf::new(), text: text.to_owned(), at: 0, waiting: None } - } - - /// What the file sets `name` to, upper case ("" if nothing). pub(super) fn value(&self, name: &str) -> String { self.text.lines().find_map(|l| setting(l, name)).map(|v| v.trim().to_ascii_uppercase()).unwrap_or_default() } - /// `name` set to `value` (its first line replaced, others of it dropped), written. - /// What the list shows changes only once the file took it: the text was changed first, - /// so after a write that failed (a read-only file, a folder gone, a full disk) the list - /// showed a key the game did not use, under COULD NOT SAVE, and the next line that did - /// save wrote that key with it. pub(super) fn set(&mut self, name: &str, value: &str) -> bool { let text = with(&self.text, name, value); let written = std::fs::write(&self.file, &text).is_ok(); @@ -2140,7 +1673,6 @@ mod binds { written } - /// The sensitivity a step up or down (0.015 each), written; the new value. pub(super) fn sensitivity(&mut self, step: isize) -> Option { let now = self.value(SENSITIVITY).parse::().ok().filter(|v| v.is_finite() && *v > 0.0).unwrap_or(0.135); let next = format!("{:.3}", (now + 0.015 * step as f32).clamp(0.015, 1.5)); @@ -2151,57 +1683,26 @@ mod binds { self.waiting = Some(held()); } - /// While waiting: a key or mouse button pressed since (not Esc, which cancels, nor F1). - pub(super) fn heard(&mut self) -> Heard { - self.heard_from(super::focused(), held) - } - - /// [`Binds::heard`]'s rule, with `ours` (a window of ours is in front) and the keys held - /// now given. `GetAsyncKeyState` answers for the whole desktop, not for our window: the - /// menu's own keys are only counted while we are in front (`watch_keys`), but a wait for - /// a key went on after Alt+Tab or a click on another window, and the next key typed or - /// button clicked there was written to `bindings.ini`. So a wait ends, with the line as - /// it was, as soon as we are not in front, before any key is asked for. - pub(super) fn heard_from(&mut self, ours: bool, held: impl FnOnce() -> [bool; 256]) -> Heard { - let Some(was) = self.waiting.as_mut() else { return Heard::Nothing }; - if !ours { - self.waiting = None; - return Heard::Lost; - } + pub(super) fn heard(&mut self) -> Option { + let was = self.waiting.as_mut()?; let now = held(); let key = (1..255).find(|&vk| now[vk] && !was[vk] && !matches!(vk, 0x1B | 0x70)).map(|vk| vk as u8); *was = now; - match key { - Some(vk) => { - self.waiting = None; - Heard::Key(vk) - } - None => Heard::Nothing, + if key.is_some() { + self.waiting = None; } + key } } - /// What a frame of [`Binds::heard`] came to. - #[derive(Debug, PartialEq, Eq)] - pub(super) enum Heard { - /// Not waiting, or nothing pressed yet. - Nothing, - /// This key or mouse button: the wait is over. - Key(u8), - /// Another program is in front: the wait is over and nothing is bound. - Lost, - } - fn held() -> [bool; 256] { let mut down = [false; 256]; for (vk, d) in down.iter_mut().enumerate().skip(1).take(254) { - // SAFETY: a plain query. *d = unsafe { GetAsyncKeyState(vk as i32) } < 0; } down } - /// The value of a `name = value` line (case aside), comments cut. fn setting<'a>(line: &'a str, name: &str) -> Option<&'a str> { let (k, v) = line.split('#').next()?.split_once('=')?; k.trim().eq_ignore_ascii_case(name).then_some(v) @@ -2227,7 +1728,6 @@ mod binds { out.join(end) + end } - /// A key as the bindings file names it (what the input module reads). pub(super) fn name(vk: u8) -> String { match vk { b'A'..=b'Z' | b'0'..=b'9' => (vk as char).to_string(), @@ -2250,1008 +1750,4 @@ mod binds { _ => format!("0x{vk:02X}"), } } - - #[cfg(test)] - pub(super) fn edited(text: &str, name: &str, value: &str) -> String { - with(text, name, value) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Held by the tests that set where [`settings_file`] points: they run in one process. - static SETTINGS_FILE_ENV: Mutex<()> = Mutex::new(()); - - fn test_env_lock() -> std::sync::MutexGuard<'static, ()> { - SETTINGS_FILE_ENV.lock().unwrap_or_else(|e| e.into_inner()) - } - - /// Every setting says what it does under the list, in lines that fit the box and that the - /// menu's letters can draw. - #[test] - fn every_line_says_what_it_does() { - use super::{ - ABOUT_CLOSE, ABOUT_RESET, ABOUT_SAVE_NEXT, ABOUT_SAVE_RESTART, COLUMNS, ITEMS, about_item, glyph, - }; - let fits = |line: &str| { - assert!(line.chars().count() <= COLUMNS as usize, "too long: {line}"); - for c in line.chars() { - assert!(c == ' ' || (c.is_ascii() && glyph(c as u8) != glyph(b'#')), "{c:?} in {line}"); - } - }; - for item in ITEMS { - let about = about_item(item.var); - assert!(!about[0].is_empty(), "{} ({}) says nothing", item.label, item.var); - about.iter().for_each(|l| fits(l)); - } - for about in [ABOUT_SAVE_RESTART, ABOUT_SAVE_NEXT, ABOUT_RESET, ABOUT_CLOSE] { - about.iter().for_each(|l| fits(l)); - } - } - - fn settings_test_menu() -> Menu { - let started = vec![String::new(); ITEMS.len()]; - let mut values = started.clone(); - values[0] = "1".to_owned(); - Menu { - launched: started.clone(), started, values, at: 0, note: String::new(), changed: true, painted: None, - buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, - binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None, - } - } - - #[test] - fn failed_settings_replace_keeps_the_previous_file() { - use std::os::windows::fs::OpenOptionsExt; - use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, FILE_SHARE_WRITE}; - - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("victory-settings.txt"); - let original = b"VICTORY_EXTRA_SWITCH=keep\r\n"; - std::fs::write(&file, original).unwrap(); - // Allow ordinary writes. Deny deletion or replacement while this handle is open. - let shared = std::fs::OpenOptions::new() - .read(true) - .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) - .open(&file) - .unwrap(); - - let mut menu = settings_test_menu(); - assert!(!menu.save_to(&file)); - assert_eq!(menu.note, "COULD NOT SAVE THE SETTINGS FILE"); - assert_ne!(menu.started[0], menu.values[0]); - assert_eq!(std::fs::read(&file).unwrap(), original); - assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); - - drop(shared); - assert!(menu.save_to(&file)); - assert_eq!(menu.started, menu.values); - let saved = std::fs::read_to_string(&file).unwrap(); - assert!(saved.contains("VICTORY_EXTRA_SWITCH=keep\r\n")); - assert!(saved.contains(&format!("{}=1\r\n", ITEMS[0].var))); - } - - #[test] - fn failed_settings_read_keeps_the_previous_file() { - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("victory-settings.txt"); - let original = [0xff]; - std::fs::write(&file, original).unwrap(); - - let mut menu = settings_test_menu(); - assert!(!menu.save_to(&file)); - assert_eq!(std::fs::read(&file).unwrap(), original); - } - - #[test] - fn reset_settings_reports_errors_and_accepts_missing_file() { - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("victory-settings.txt"); - let mut menu = settings_test_menu(); - - menu.reset_at(&file); - assert_eq!(menu.note, "RESET. PLAY DEFAULTS AT THE NEXT START"); - - std::fs::write(&file, b"VICTORY_TEST=1\r\n").unwrap(); - menu.reset_at(&file); - assert_eq!(menu.note, "RESET. PLAY DEFAULTS AT THE NEXT START"); - assert!(!file.exists()); - - std::fs::create_dir(&file).unwrap(); - menu.reset_at(&file); - assert_eq!(menu.note, "COULD NOT RESET THE SETTINGS FILE"); - assert!(file.is_dir()); - } - - #[test] - fn gray_shadow_lift_is_live_and_saved_as_a_percentage() { - struct Restore(Vec<(&'static str, Option)>); - impl Drop for Restore { - fn drop(&mut self) { - for (key, value) in &self.0 { - // SAFETY: restore the two variables changed by this Windows-only test. - unsafe { - match value { - Some(value) => std::env::set_var(key, value), - None => std::env::remove_var(key), - } - } - } - } - } - // Declared before `_restore`: the variables are put back while it is still held. - let _env = SETTINGS_FILE_ENV.lock().unwrap_or_else(|e| e.into_inner()); - let _restore = Restore(["VICTORY_MENU_FILE", "VICTORY_SHADOW_LIFT"].map(|key| (key, std::env::var_os(key))).into()); - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("victory-settings.txt"); - // SAFETY: the focused test runs serially; Windows serializes environment access. - unsafe { - std::env::set_var("VICTORY_MENU_FILE", &file); - std::env::remove_var("VICTORY_SHADOW_LIFT"); - } - let row = ITEMS.iter().position(|i| i.var == "VICTORY_SHADOW_LIFT").unwrap(); - let values: Vec = ITEMS.iter().map(|i| get(i.var)).collect(); - let mut menu = Menu { started: values.clone(), launched: values.clone(), values, at: row, note: String::new(), changed: true, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - assert_eq!(shown_value(&ITEMS[row], ""), "0% (OFF)"); - assert!(live(&ITEMS[row])); - for percent in 1..=10 { - menu.change_and_save(row, 1); - // The same value reader feeds every newly recorded composition. - assert!((crate::compose::shadow_lift() - percent as f32 * 0.03).abs() < 0.000001); - assert_eq!(menu.note, "SAVED. ON NOW"); - let saved = std::fs::read_to_string(&file).unwrap(); - assert!(saved.lines().any(|line| line == format!("VICTORY_SHADOW_LIFT={}", menu.values[row]))); - } - assert!(menu.lines().iter().any(|line| line.contains("100% (MAX)") && line.contains("LIVE"))); - menu.change_and_save(row, 1); - assert_eq!(crate::compose::shadow_lift(), 0.0); - assert!(std::fs::read_to_string(&file).unwrap().contains("VICTORY_SHADOW_LIFT=0\r\n")); - menu.change_and_save(row, -1); - assert_eq!(crate::compose::shadow_lift(), 0.3); - } - - /// A mark that lands ends the warm-up; one that cannot (here, beside a - /// file of the same name) does not: the launcher arms a new warm-up - /// whenever no mark exists, and a restart without one would come back - /// here for ever. - #[test] - fn a_mark_that_cannot_be_written_does_not_end_the_warm_up() { - let dir = tempfile::tempdir().unwrap(); - let blocked = dir.path().join("a file"); - std::fs::write(&blocked, b"not a folder").unwrap(); - assert!(mark_written(&dir.path().join("warmed").join("mark"))); - assert!(!mark_written(&blocked.join("mark"))); - } - - #[test] - fn preload_restart_preserves_paths_and_working_directory() { - // A successful menu restart exits its process. Only the child takes that path. - const RESULT: &str = "VICTORY_TEST_PRELOAD_RESTART_RESULT"; - if std::env::var_os(RESULT).is_some() { - let mut menu = Menu::new(); - menu.restart(Then::Preload); - panic!("restart returned: {}", menu.note); - } - - let tmp = tempfile::tempdir().unwrap(); - let original = tmp.path().join("Launcher 雪"); - let game_dir = tmp.path().join("Game directory"); - std::fs::create_dir(&original).unwrap(); - std::fs::create_dir(&game_dir).unwrap(); - let play = original.join("Player’s launcher.ps1"); - let title = game_dir.join("Player’s game.exe"); - let result = tmp.path().join("result.txt"); - std::fs::write(original.join("launcher.txt"), "").unwrap(); - std::fs::write( - &play, - r#"param([string]$Exe) -[IO.File]::WriteAllLines($env:VICTORY_TEST_PRELOAD_RESTART_RESULT, [string[]]@( - $Exe, $env:VICTORY_PRELOAD, (Test-Path -LiteralPath '.\launcher.txt') -)) -"#, - ) - .unwrap(); - let status = std::process::Command::new(std::env::current_exe().unwrap()) - .arg("--exact") - .arg(std::thread::current().name().unwrap()) - .current_dir(game_dir) - .env(RESULT, &result) - .env("VICTORY_MENU_PLAY", play) - .env("VICTORY_MENU_EXE", &title) - .env("VICTORY_MENU_ARGS", "-Exe $env:VICTORY_MENU_EXE") - .env("VICTORY_MENU_CWD", original) - .env_remove("VICTORY_PRELOAD") - .status() - .unwrap(); - assert!(status.success(), "menu process exited with {status}"); - let began = std::time::Instant::now(); - loop { - if let Ok(text) = std::fs::read_to_string(&result) - && text.ends_with('\n') - { - assert_eq!( - text.lines().collect::>(), - [title.to_str().unwrap(), "1", "True"] - ); - break; - } - assert!( - began.elapsed() < std::time::Duration::from_secs(30), - "the restarted launcher did not report" - ); - std::thread::sleep(std::time::Duration::from_millis(50)); - } - } - - #[test] - fn selection_marker_is_filled_without_changing_value_brackets() { - let lines = ["> >".to_owned(), " >".to_owned()]; - let center_y = RIM + GLYPH.1 / 2; - for x in 0..GLYPH.0 { - assert!(lit(&lines, RIM + x, center_y)); - assert_eq!(lit(&lines, RIM + 2 * CELL.0 + x, center_y), x == GLYPH.0 - 1); - assert!(!lit(&lines, RIM + x, center_y + CELL.1)); - } - } - - #[test] - fn a_change_is_saved_at_once_however_the_game_was_started() { - let _guard = test_env_lock(); - let home = std::env::temp_dir().join(format!("victory-menu-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&home); - // SAFETY: the other tests that set these take the same lock (`test_env_lock`). - unsafe { - std::env::remove_var("VICTORY_MENU_FILE"); - std::env::set_var("VICTORY_HOME", &home); - } - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - let dlss = ITEMS.iter().position(|i| i.var == "VICTORY_MENU_DLSS").expect("in the menu"); - menu.change_and_save(dlss, 1); - let text = std::fs::read_to_string(home.join("victory-settings.txt")).expect("saved without a save line"); - assert!(text.contains("VICTORY_MENU_DLSS=quality"), "{text}"); - assert_eq!(menu.note, "SAVED. APPLIES WHEN VICTORY.EXE STARTS THE GAME"); - // A later start may have no NVIDIA files. An unrelated F1 edit must merge with - // the settings on disk, even if that launcher showed DLSS as off. - menu.values[dlss] = "off".to_owned(); - let fps = ITEMS.iter().position(|i| i.var == "VICTORY_MENU_FPS").expect("in the menu"); - menu.values[fps] = "120".to_owned(); - menu.started = menu.values.clone(); - menu.change_and_save(fps, 1); - let text = std::fs::read_to_string(home.join("victory-settings.txt")).unwrap(); - assert!(text.lines().any(|line| line == "VICTORY_MENU_DLSS=quality")); - assert!(text.lines().any(|line| line == "VICTORY_MENU_FPS=60")); - - // A value set by hand, picked again after a save, is written again as it was. - let ambient = ITEMS.iter().position(|i| i.var == "VICTORY_AMBIENT").expect("in the menu"); - menu.values[ambient] = "constant:0.25".to_owned(); - menu.launched = menu.values.clone(); - menu.started = menu.values.clone(); - menu.change_and_save(ambient, 1); - menu.change_and_save(ambient, -1); - let text = std::fs::read_to_string(home.join("victory-settings.txt")).unwrap(); - assert!(text.lines().any(|line| line == "VICTORY_AMBIENT=constant:0.25"), "{text}"); - // A launcher's choice back to NOT SET leaves no line of its own. - let console = ITEMS.iter().position(|i| i.var == CONSOLE).expect("in the menu"); - menu.values[console].clear(); - menu.launched = menu.values.clone(); - menu.started = menu.values.clone(); - menu.change_and_save(console, 1); - menu.change_and_save(console, -1); - let text = std::fs::read_to_string(home.join("victory-settings.txt")).unwrap(); - assert!(!text.contains(CONSOLE), "{text}"); - - // Every note fits the box and has its letters. - for note in [menu.note.as_str(), "SAVED. ON NOW", "SAVED. APPLIES AT THE NEXT START", "NO FOLDER FOR THE SETTINGS FILE"] { - assert!(note.len() <= COLUMNS as usize, "{note}"); - assert!(note.bytes().all(|c| glyph(c) != glyph(b'#')), "{note}"); - } - let _ = std::fs::remove_dir_all(&home); - } - - #[test] - fn every_line_fits_and_every_character_has_a_picture() { - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - for at in 0..ITEMS.len() + ACTIONS.len() { - menu.at = at; - for line in menu.lines() { - assert!(line.len() <= COLUMNS as usize, "{line}"); - for c in line.bytes() { - assert_ne!(glyph(c.to_ascii_uppercase()), glyph(b'#'), "{line}: {}", c as char); - } - } - } - } - - #[test] - fn the_link_is_always_right_under_the_note() { - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - for note in ["", "SAVED"] { - menu.note = note.to_owned(); - for at in 0..ITEMS.len() + ACTIONS.len() { - menu.at = at; - let lines = menu.lines(); - assert_eq!(lines.len(), LINES as usize); - let n = lines.len(); - assert!(lines[n - 2].starts_with("* = CHANGED") || lines[n - 2] == note, "{}", lines[n - 2]); - assert_eq!(lines[n - 1], REPO); - // What a preload costs, and what MFG Unlocker is, is said while it is picked, and only then. - let about = &lines[n - 5..n - 2]; - if at == ITEMS.len() + PRELOAD { - assert_eq!(about, ABOUT_PRELOAD); - } else if at == ITEMS.len() + CLEAR { - assert_eq!(about, ABOUT_CLEAR); - } else if at == ITEMS.len() + EXPORT { - assert_eq!(about, ABOUT_EXPORT); - } else if at == ITEMS.len() + IMPORT { - assert_eq!(about, ABOUT_IMPORT); - } else if at < ITEMS.len() && ITEMS[at].var == MFG { - assert_eq!(about, ABOUT_MFG); - } else if at < ITEMS.len() && ITEMS[at].var == S_RES { - assert_eq!(about, ABOUT_S_RES); - } else if at < ITEMS.len() && ITEMS[at].var == FORCE_MFG { - assert_eq!(about, ABOUT_FORCE_MFG); - } else if at < ITEMS.len() && ITEMS[at].var == "VICTORY_SHADOW_LIFT" { - assert_eq!(about, ABOUT_SHADOW_LIFT); - } else if at < ITEMS.len() { - // DLSS and FRAME GENERATION may show their own notes instead. - if !matches!(ITEMS[at].var, DLSS | FRAMEGEN) { - assert_eq!(about, about_item(ITEMS[at].var)); - } - } else if at == ITEMS.len() + SAVE_RESTART { - assert_eq!(about, ABOUT_SAVE_RESTART); - } else if at == ITEMS.len() + SAVE_NEXT { - assert_eq!(about, ABOUT_SAVE_NEXT); - } else if at == ITEMS.len() + SAVE_QUIT { - assert_eq!(about, ABOUT_SAVE_QUIT); - } else if at == ITEMS.len() + RESET { - assert_eq!(about, ABOUT_RESET); - } else { - assert_eq!(about, ABOUT_CLOSE); - } - } - } - assert_eq!(ACTIONS[PRELOAD], "PRELOAD SHADERS (RESTARTS THE GAME)"); - assert!(CONFIRM_PRELOAD.len() <= COLUMNS as usize); - assert_eq!(ACTIONS[CLEAR], "CLEAR SHADER CACHE (RESTARTS THE GAME)"); - assert_eq!(ACTIONS[RESET], "RESET ALL TO PLAY DEFAULTS"); - assert_eq!(ACTIONS[EXPORT], "EXPORT SAVE (TO SAVES IN THE GAME FOLDER)"); - assert_eq!(ACTIONS[IMPORT], "IMPORT SAVE (PICK FROM SAVES)"); - let pick = [PICK_TITLE, PICK_HELP, PICK_NONE, PICK_BACK, CONFIRM_IMPORT, "IMPORT FAILED: THAT ZIP IS DAMAGED OR NOT A SAVE"]; - for line in ABOUT_EXPORT.iter().chain(&ABOUT_IMPORT).chain(&ABOUT_PICK).chain(&ABOUT_CLEAR).chain(&pick).chain(&[CONFIRM_CLEAR]) { - assert!(line.len() <= COLUMNS as usize, "{line}"); - assert!(line.bytes().all(|c| glyph(c) != glyph(b'#')), "{line}"); - } - assert!(ABOUT_MFG.iter().all(|l| l.len() <= COLUMNS as usize)); - assert!(ABOUT_FORCE_MFG.iter().all(|l| l.len() <= COLUMNS as usize && l.bytes().all(|c| glyph(c) != glyph(b'#')))); - for line in ABOUT_NO_DLSS { - assert!(line.len() <= COLUMNS as usize && line.bytes().all(|c| glyph(c) != glyph(b'#')), "{line}"); - } - // DLSS download instructions must not depend on the test process environment. - let dlss = ITEMS.iter().position(|i| i.var == DLSS).expect("in the menu"); - menu.at = dlss; - menu.values[dlss] = "quality".to_owned(); - - let lines = menu.lines_with_streamline(false); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_NO_DLSS); - - // With the files there, or with DLSS off: what DLSS is. - let lines = menu.lines_with_streamline(true); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], about_item(DLSS)); - - menu.values[dlss] = "off".to_owned(); - for configured in [false, true] { - let lines = menu.lines_with_streamline(configured); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], about_item(DLSS)); - } - assert_eq!(ITEMS.iter().filter(|i| i.var == MFG).count(), 1); - // Frame generation turned on in a run started without it (no Streamline in tests): a - // restart is required, and the menu says so; OFF needs no word. - for line in ABOUT_FRAMEGEN_RESTART { - assert!(line.len() <= COLUMNS as usize && line.bytes().all(|c| glyph(c) != glyph(b'#')), "{line}"); - } - let fg = ITEMS.iter().position(|i| i.var == FRAMEGEN).expect("in the menu"); - menu.at = fg; - menu.values[fg] = "0".to_owned(); - menu.change(fg, 1); - assert_eq!(menu.values[fg], "2"); - assert_eq!(menu.note, "RESTART REQUIRED TO ENABLE FRAME GENERATION"); - let lines = menu.lines(); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_FRAMEGEN_RESTART); - menu.change(fg, -1); - assert!(menu.note.is_empty()); - let lines = menu.lines(); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], about_item(FRAMEGEN)); - } - - #[test] - fn the_picture_line_is_the_consoles() { - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - let at = |var: &str| ITEMS.iter().position(|i| i.var == var).expect("in the menu"); - let (console, x, s, dlss) = (at(CONSOLE), at(X_RES), at(S_RES), at(DLSS)); - let shown = |menu: &Menu, label: &str| menu.lines().iter().any(|l| l.contains(label)); - "series-x".clone_into(&mut menu.values[console]); - assert!(shown(&menu, "SERIES X PICTURE") && !shown(&menu, "SERIES S PICTURE")); - // down from the console: the Series X line, never the hidden one - menu.at = console; - assert_eq!(menu.step(1), x); - assert!(!menu.rows().contains(&s)); - "series-s".clone_into(&mut menu.values[console]); - assert!(shown(&menu, "SERIES S PICTURE") && !shown(&menu, "SERIES X PICTURE")); - assert_eq!(menu.step(1), s); - assert_eq!(menu.step(-1), console - 1); - // the size and DLSS's mode follow each other on Series S - "quality".clone_into(&mut menu.values[dlss]); - "720".clone_into(&mut menu.values[s]); - menu.change(s, 1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("626", "balanced")); - menu.change(s, 1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("540", "performance")); - menu.change(dlss, -2); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("720", "quality")); - // DLSS off is 720, and 720 leaves it off; another size turns DLSS on at its mode - menu.change(dlss, -1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("720", "off")); - menu.change(s, -1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("360", "ultraperformance")); - // no DLAA on Series S: no 1080, and the DLSS line goes past DLAA both ways - assert!(ITEMS[s].values.iter().all(|(v, _)| *v != "1080")); - menu.change(dlss, 1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("720", "off")); - menu.change(dlss, -1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("360", "ultraperformance")); - // Series X keeps DLAA; picked there, it is 720 at quality once the console is Series S - "series-x".clone_into(&mut menu.values[console]); - menu.change(dlss, 1); - assert_eq!(menu.values[dlss], "dlaa"); - menu.change(console, 1); - assert_eq!(menu.values[console], "series-s"); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("720", "quality")); - "off".clone_into(&mut menu.values[dlss]); - "626".clone_into(&mut menu.values[s]); - menu.change(s, -1); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("720", "off")); - menu.change(s, 2); - assert_eq!((menu.values[s].as_str(), menu.values[dlss].as_str()), ("540", "performance")); - menu.at = s; - assert_eq!(&menu.lines()[menu.lines().len() - 5..menu.lines().len() - 2], ABOUT_S_RES); - for line in ABOUT_S_RES { - assert!(line.len() <= COLUMNS as usize && line.bytes().all(|b| glyph(b) != glyph(b'#') || b == b'#'), "{line}"); - } - } - - #[test] - fn key_bindings_are_shown_and_written() { - let text = "# keys\r\nSensitivity = 0.135\r\nRT = Mouse1\r\nY = F # car\r\nY = G\r\n"; - let edited = binds::edited(text, "Y", "E"); - assert_eq!(edited, "# keys\r\nSensitivity = 0.135\r\nRT = Mouse1\r\nY = E\r\n"); - assert!(binds::edited("A = Shift\n", "LB", "Tab").ends_with("LB = Tab\n")); - let b = binds::Binds::of(&edited); - assert_eq!((b.value("rt").as_str(), b.value("Y").as_str(), b.value("LB").as_str()), ("MOUSE1", "E", "")); - assert_eq!((binds::name(b'W'), binds::name(1), binds::name(0xA2)), ("W".to_owned(), "Mouse1".to_owned(), "0xA2".to_owned())); - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: Some(b), backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - let mut fixed = [BINDS_TITLE, BINDS_HELP, BINDS_BACK, BINDS_OFF, BINDS_LOST, "COULD NOT SAVE BINDINGS.INI", "MOUSE SENSITIVITY: 0.150"].map(str::to_owned).to_vec(); - fixed.extend(binds::ROWS.iter().map(|(_, l)| format!("PRESS A KEY OR MOUSE BUTTON: {l}"))); - for at in 0..=binds::ROWS.len() { - menu.binds.as_mut().expect("shown").at = at; - let lines = menu.lines(); - assert_eq!(lines.len(), 3 + ROWS + 1 + 3 + 2); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_BINDS); - assert!(lines.iter().any(|l| l.starts_with('>'))); - fixed.extend(lines); - } - for line in fixed.iter().map(String::as_str).chain(ABOUT_BINDS) { - assert!(line.len() <= COLUMNS as usize, "{line}"); - for c in line.bytes() { - assert_ne!(glyph(c.to_ascii_uppercase()), glyph(b'#'), "{line}: {}", c as char); - } - } - } - - /// A wait for a key ends when another program comes in front, before any key is asked - /// for: what is typed there is not bound, and the wait does not go on once we are back. - #[test] - fn a_wait_for_a_key_ends_when_the_window_is_not_in_front() { - let pressed = |vk: usize| { - let mut down = [false; 256]; - down[vk] = true; - down - }; - let mut b = binds::Binds::of("Y = F\n"); - // not waiting: nothing, in front or not, and no key is asked for - assert_eq!(b.heard_from(false, || panic!("keys asked for with no wait")), binds::Heard::Nothing); - // waiting and in front: Esc and F1 are not bound, the first other key is - b.waiting = Some([false; 256]); - assert_eq!(b.heard_from(true, || [false; 256]), binds::Heard::Nothing); - assert_eq!(b.heard_from(true, || pressed(0x1B)), binds::Heard::Nothing); - assert!(b.waiting.is_some()); - assert_eq!(b.heard_from(true, || pressed(usize::from(b'E'))), binds::Heard::Key(b'E')); - assert!(b.waiting.is_none()); - // waiting, and another program in front: over, with no key asked for - b.waiting = Some([false; 256]); - assert_eq!(b.heard_from(false, || panic!("keys asked for while not in front")), binds::Heard::Lost); - assert!(b.waiting.is_none(), "the wait went on"); - // back in front: a key pressed now is not bound - assert_eq!(b.heard_from(true, || panic!("keys asked for after the wait ended")), binds::Heard::Nothing); - assert_eq!(b.value("Y"), "F"); - } - - #[test] - fn values_cycle_both_ways() { - let mut menu = Menu { values: ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - let n = ITEMS[0].values.len(); - for _ in 0..n { - menu.change(0, 1); - } - assert_eq!(menu.values[0], ITEMS[0].values[0].0); - menu.change(0, -1); - assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0); - } - - #[test] - fn a_value_set_by_hand_stays_in_the_cycle_both_ways() { - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: 0, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: Vec::new(), import_at: 0, picking: false, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - let ambient = ITEMS.iter().position(|i| i.var == "VICTORY_AMBIENT").expect("in the menu"); - let listed = ITEMS[ambient].values; - for own in ["1.5", "constant:0.25"] { - own.clone_into(&mut menu.values[ambient]); - menu.launched = menu.values.clone(); - for step in [1, -1] { - let mut seen = Vec::new(); - for _ in 0..=listed.len() { - menu.change(ambient, step); - seen.push(menu.values[ambient].clone()); - } - let mut round: Vec<&str> = listed.iter().map(|(v, _)| *v).collect(); - if step < 0 { - round.reverse(); - } - round.push(own); - assert_eq!(seen, round, "step {step}"); - } - } - } - - #[test] - fn vehicle_auto_center_zero_is_normalized_to_off() { - let item = ITEMS.iter().find(|i| i.var == "VICTORY_VEHICLE_AUTO_CENTER").expect("in the menu"); - assert_eq!(shown_value(item, ""), "OFF"); - assert_eq!(shown_value(item, "1"), "ON"); - // SAFETY: isolated env var check inside menu unit tests. - let prev = std::env::var_os("VICTORY_VEHICLE_AUTO_CENTER"); - unsafe { std::env::set_var("VICTORY_VEHICLE_AUTO_CENTER", "0") }; - let menu = Menu::new(); - let idx = ITEMS.iter().position(|i| i.var == "VICTORY_VEHICLE_AUTO_CENTER").unwrap(); - assert_eq!(menu.values[idx], ""); - assert_eq!(menu.started[idx], ""); - assert_eq!(shown_value(item, &menu.values[idx]), "OFF"); - unsafe { - match prev { - Some(v) => std::env::set_var("VICTORY_VEHICLE_AUTO_CENTER", v), - None => std::env::remove_var("VICTORY_VEHICLE_AUTO_CENTER"), - } - } - } - - #[test] - fn a_shared_save_name_is_shown_in_letters_the_menu_has() { - let names = vec!["save 2026-11-27 23-45-10.zip".to_owned(), "Jason's boat ~ 100% [\u{e9}] and a very long name that goes on and on.zip".to_owned()]; - let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), launched: Vec::new(), at: ITEMS.len() + IMPORT, note: String::new(), changed: false, painted: None, buffers: None, failed: false, failed_at: None, imports: names, import_at: 0, picking: true, binds: None, backbuffer: (0, 0), scale: 1, last_cursor: None }; - menu.started = menu.values.clone(); - let check = |menu: &Menu| { - let lines = menu.lines(); - assert_eq!(lines.len(), LINES as usize); - assert_eq!(lines[lines.len() - 1], REPO); - assert_eq!(&lines[lines.len() - 5..lines.len() - 2], ABOUT_PICK); - for line in &lines { - assert!(line.len() <= COLUMNS as usize, "{line}"); - assert!(line.bytes().all(|c| glyph(c.to_ascii_uppercase()) != glyph(b'#')), "{line}"); - } - lines - }; - let lines = check(&menu); - assert!(lines.iter().any(|l| l == "> SAVE 2026-11-27 23-45-10.ZIP"), "{lines:?}"); - assert!(lines.iter().any(|l| l == &format!(" {PICK_BACK}")), "{lines:?}"); - menu.import_at = 1; - check(&menu); - menu.import_at = 2; - assert!(check(&menu).iter().any(|l| l == &format!("> {PICK_BACK}"))); - // Many saves: the list scrolls and the box keeps its size. - menu.imports = (0..50).map(|i| format!("save {i}.zip")).collect(); - for at in [0, 25, 49, 50] { - menu.import_at = at; - let lines = check(&menu); - let picked = if at == 50 { format!("> {PICK_BACK}") } else { format!("> SAVE {at}.ZIP") }; - assert!(lines.contains(&picked), "{at}: {lines:?}"); - } - menu.imports.clear(); - menu.import_at = 0; - let lines = check(&menu); - assert!(lines.iter().any(|l| l == PICK_NONE)); - assert!(lines.iter().any(|l| l == &format!("> {PICK_BACK}"))); - } - - #[test] - fn a_restart_asks_its_start_for_what_it_was_picked_for() { - assert_eq!(Then::Play.switch(), ""); - assert_eq!(Then::Preload.switch(), "$env:VICTORY_PRELOAD='1'; "); - assert_eq!(Then::ClearShaders.switch(), "$env:VICTORY_CLEAR_SHADERS='1'; "); - } - - fn blank_menu() -> Menu { - let values: Vec = ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(); - Menu { - started: values.clone(), - launched: values.clone(), - values, - at: 0, - note: String::new(), - changed: false, - painted: None, - buffers: None, - failed: false, - failed_at: None, - imports: Vec::new(), - import_at: 0, - picking: false, - binds: None, - backbuffer: (1920, 1080), - scale: 2, - last_cursor: None, - } - } - - fn cell_center(width: u32, height: u32, line: usize, col: u32) -> (u32, u32) { - let scale = (height / 540).max(1); - let (w, h) = size(scale); - let (w, h) = (w.min(width), h.min(height)); - let (box_x, box_y) = ((width - w) / 2, (height - h) / 2); - let bx = box_x + (RIM + col * CELL.0 + CELL.0 / 2) * scale; - let by = box_y + (RIM + line as u32 * CELL.1 + CELL.1 / 2) * scale; - (bx, by) - } - - fn with_temp_settings_file(f: F) { - let _guard = test_env_lock(); - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("victory-settings.txt"); - let prev_file = std::env::var_os("VICTORY_MENU_FILE"); - let prev_home = std::env::var_os("VICTORY_HOME"); - // SAFETY: serialized via `test_env_lock()`. - unsafe { - std::env::set_var("VICTORY_MENU_FILE", &file); - std::env::remove_var("VICTORY_HOME"); - } - f(&file); - // SAFETY: serialized via `test_env_lock()`. - unsafe { - match prev_file { - Some(v) => std::env::set_var("VICTORY_MENU_FILE", v), - None => std::env::remove_var("VICTORY_MENU_FILE"), - } - match prev_home { - Some(v) => std::env::set_var("VICTORY_HOME", v), - None => std::env::remove_var("VICTORY_HOME"), - } - } - } - - #[test] - fn client_to_backbuffer_maps_and_rejects_out_of_bounds() { - assert_eq!(client_to_backbuffer(0, 0, 1280, 720, 1920, 1080), Some((0, 0))); - assert_eq!(client_to_backbuffer(640, 360, 1280, 720, 1920, 1080), Some((960, 540))); - assert_eq!(client_to_backbuffer(1279, 719, 1280, 720, 1920, 1080), Some((1918, 1078))); - assert_eq!(client_to_backbuffer(-1, 10, 1280, 720, 1920, 1080), None); - assert_eq!(client_to_backbuffer(1280, 10, 1280, 720, 1920, 1080), None); - assert_eq!(client_to_backbuffer(10, 720, 1280, 720, 1920, 1080), None); - assert_eq!(client_to_backbuffer(0, 0, 0, 720, 1920, 1080), None); - assert_eq!(client_to_backbuffer(0, 0, 1280, 720, 0, 1080), None); - } - - #[test] - fn hit_test_menu_box_handles_headers_rim_scrolled_rows_and_hidden_console_row() { - let mut menu = blank_menu(); - let (w, h) = (1920, 1080); - // Outside box, inside rim, header lines (0..3), and footer lines return None. - let (box_w, box_h) = size(2); - let (box_x, box_y) = ((w - box_w) / 2, (h - box_h) / 2); - assert_eq!(menu.hit_test((box_x - 1, box_y + 10)), None); - assert_eq!(menu.hit_test((box_x + 2, box_y + 2)), None); - assert_eq!(menu.hit_test(cell_center(w, h, 0, 5)), None); - assert_eq!(menu.hit_test(cell_center(w, h, 2, 5)), None); - assert_eq!(menu.hit_test(cell_center(w, h, 3 + ROWS, 5)), None); - - // Hidden Series S/X picture row: Series X shows X_RES and omits S_RES; Series S does the reverse. - let console_idx = ITEMS.iter().position(|i| i.var == CONSOLE).unwrap(); - let x_idx = ITEMS.iter().position(|i| i.var == X_RES).unwrap(); - let s_idx = ITEMS.iter().position(|i| i.var == S_RES).unwrap(); - "series-x".clone_into(&mut menu.values[console_idx]); - menu.at = x_idx; - let (_, visible_x) = menu.visible_layout(); - let x_slot = visible_x.iter().position(|&r| r == x_idx).unwrap(); - assert!(!visible_x.contains(&s_idx)); - assert_eq!( - menu.hit_test(cell_center(w, h, 3 + x_slot, 30)), - Some(BoxHit { row: x_idx, col: 30 }) - ); - // Next visual line after x_slot skips s_idx cleanly. - assert_eq!( - menu.hit_test(cell_center(w, h, 3 + x_slot + 1, 10)), - Some(BoxHit { row: s_idx + 1, col: 10 }) - ); - - "series-s".clone_into(&mut menu.values[console_idx]); - menu.at = s_idx; - let (_, visible_s) = menu.visible_layout(); - let s_slot = visible_s.iter().position(|&r| r == s_idx).unwrap(); - assert!(!visible_s.contains(&x_idx)); - assert_eq!( - menu.hit_test(cell_center(w, h, 3 + s_slot, 32)), - Some(BoxHit { row: s_idx, col: 32 }) - ); - - // Scrolled view (`first > 0`): line 3 maps to the scrolled first row, not row 0. - menu.at = ITEMS.len() + 2; - let (start_line, visible_scrolled) = menu.visible_layout(); - assert_eq!(start_line, 3); - assert!(visible_scrolled[0] > 0); - assert_eq!( - hit_test_menu_box(cell_center(w, h, 3, 12), (w, h), start_line, &visible_scrolled), - Some(BoxHit { row: visible_scrolled[0], col: 12 }) - ); - assert_eq!( - hit_test_menu_box(cell_center(w, h, 3 + ROWS - 1, 4), (w, h), start_line, &visible_scrolled), - Some(BoxHit { row: visible_scrolled[ROWS - 1], col: 4 }) - ); - } - - #[test] - fn hover_updates_selection_only_when_cursor_moves() { - let mut menu = blank_menu(); - let pos_row3 = cell_center(1920, 1080, 3 + 3, 10); - // First movement onto row 3 selects it. - menu.handle_hover(Some(pos_row3)); - assert_eq!(menu.at, 3); - assert!(menu.changed); - - // Stationary cursor must NOT override keyboard Up/Down. - menu.changed = false; - menu.at = menu.step(1); - assert_eq!(menu.at, 4); - menu.handle_hover(Some(pos_row3)); - assert_eq!(menu.at, 4); - assert!(!menu.changed); - - // Moving within the same row preserves CONFIRM_PRELOAD; moving to another row clears it. - menu.at = ITEMS.len() + PRELOAD; - let (_, visible) = menu.visible_layout(); - let preload_slot = visible.iter().position(|&r| r == ITEMS.len() + PRELOAD).unwrap(); - let pos_a = cell_center(1920, 1080, 3 + preload_slot, 5); - let pos_b = cell_center(1920, 1080, 3 + preload_slot, 15); - menu.last_cursor = Some(pos_a); - menu.note = CONFIRM_PRELOAD.to_owned(); - menu.handle_hover(Some(pos_b)); - assert_eq!(menu.at, ITEMS.len() + PRELOAD); - assert_eq!(menu.note, CONFIRM_PRELOAD); - - let other_pos = cell_center(1920, 1080, 3 + preload_slot + 1, 5); - menu.handle_hover(Some(other_pos)); - assert_ne!(menu.at, ITEMS.len() + PRELOAD); - assert!(menu.note.is_empty()); - } - - #[test] - fn left_click_cycles_setting_left_and_right_around_arrows() { - with_temp_settings_file(|file| { - let mut menu = blank_menu(); - // `DLSS` values are ["quality", "balanced", "performance", "dlaa", "off"]. - let dlss_idx = ITEMS.iter().position(|i| i.var == DLSS).unwrap(); - let pos_lt = cell_center(1920, 1080, 3 + dlss_idx, 30); - let hit_lt = menu.hit_test(pos_lt); - menu.handle_left_click(hit_lt); - assert_eq!(menu.at, dlss_idx); - assert_eq!(menu.values[dlss_idx], "off"); - - let pos_gt = cell_center(1920, 1080, 3 + dlss_idx, 35); - let hit_gt = menu.hit_test(pos_gt); - menu.handle_left_click(hit_gt); - assert_eq!(menu.values[dlss_idx], "quality"); - - // Wide-label setting (`VICTORY_ASYNC_SUBMIT`, `<` at col 40). - let async_idx = ITEMS.iter().position(|i| i.var == "VICTORY_ASYNC_SUBMIT").unwrap(); - menu.at = async_idx; - let (_, visible) = menu.visible_layout(); - let slot = visible.iter().position(|&r| r == async_idx).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + slot, 40))); - assert_eq!(menu.values[async_idx], "1"); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + slot, 45))); - assert_eq!(menu.values[async_idx], ""); - assert!(file.exists()); - }); - } - - #[test] - fn left_click_executes_actions_and_two_click_confirmation() { - with_temp_settings_file(|file| { - let mut menu = blank_menu(); - let dlss_idx = ITEMS.iter().position(|i| i.var == DLSS).unwrap(); - menu.values[dlss_idx] = "off".to_owned(); - menu.at = ITEMS.len() + SAVE_NEXT; - let (_, visible) = menu.visible_layout(); - let save_slot = visible.iter().position(|&r| r == ITEMS.len() + SAVE_NEXT).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + save_slot, 8))); - let saved = std::fs::read_to_string(file).unwrap(); - assert!(saved.contains("VICTORY_MENU_DLSS=off"), "{saved}"); - - // RESET removes the settings file. - let reset_row = ITEMS.len() + RESET; - let reset_slot = visible.iter().position(|&r| r == reset_row).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + reset_slot, 8))); - assert!(!file.exists()); - assert_eq!(menu.note, "RESET. PLAY DEFAULTS AT THE NEXT START"); - - // EXPORT runs export_save. - let export_row = ITEMS.len() + EXPORT; - let export_slot = visible.iter().position(|&r| r == export_row).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + export_slot, 8))); - assert_eq!(menu.note, "SAVE FOLDERS NOT KNOWN IN THIS START"); - - // PRELOAD requires two clicks without leaving the row. - let preload_row = ITEMS.len() + PRELOAD; - let preload_slot = visible.iter().position(|&r| r == preload_row).unwrap(); - let preload_hit = menu.hit_test(cell_center(1920, 1080, 3 + preload_slot, 8)); - menu.handle_left_click(preload_hit); - assert_eq!(menu.note, CONFIRM_PRELOAD); - assert!(!file.exists()); - // Second click confirms and saves (VICTORY_MENU_PLAY is unset in test). - menu.handle_left_click(preload_hit); - assert_eq!(menu.note, "SAVED. START THE LAUNCHER AGAIN YOURSELF"); - - // IMPORT enters picking mode. - let import_row = ITEMS.len() + IMPORT; - let import_slot = visible.iter().position(|&r| r == import_row).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + import_slot, 8))); - assert!(menu.picking); - - // CLOSE sets SETTINGS_MENU_OPEN to false. - menu.picking = false; - crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed); - let close_row = ITEMS.len() + CLOSE; - menu.at = close_row; - let (_, visible_end) = menu.visible_layout(); - let close_slot = visible_end.iter().position(|&r| r == close_row).unwrap(); - menu.handle_left_click(menu.hit_test(cell_center(1920, 1080, 3 + close_slot, 4))); - assert!(!Menu::open()); - }); - } - - #[test] - fn picking_mode_click_confirm_back_and_empty_layout() { - let mut menu = blank_menu(); - menu.picking = true; - menu.imports = vec!["save-a.zip".to_owned(), "save-b.zip".to_owned()]; - - // First click on save-b sets CONFIRM_IMPORT. - let hit_b = menu.hit_test(cell_center(1920, 1080, 4, 8)); - assert_eq!(hit_b, Some(BoxHit { row: 1, col: 8 })); - menu.handle_left_click(hit_b); - assert_eq!(menu.import_at, 1); - assert_eq!(menu.note, CONFIRM_IMPORT); - - // Second click on save-b executes import_save(). - menu.handle_left_click(hit_b); - assert_ne!(menu.note, CONFIRM_IMPORT); - - // Click on BACK TO THE SETTINGS exits picking mode. - let hit_back = menu.hit_test(cell_center(1920, 1080, 5, 8)); - assert_eq!(hit_back, Some(BoxHit { row: 2, col: 8 })); - menu.handle_left_click(hit_back); - assert!(!menu.picking); - assert!(menu.note.is_empty()); - - // Empty imports list puts PICK_NONE at line 3 and PICK_BACK at line 4. - menu.picking = true; - menu.imports.clear(); - menu.import_at = 0; - assert_eq!(menu.hit_test(cell_center(1920, 1080, 3, 8)), None); - let hit_empty_back = menu.hit_test(cell_center(1920, 1080, 4, 8)); - assert_eq!(hit_empty_back, Some(BoxHit { row: 0, col: 8 })); - menu.handle_left_click(hit_empty_back); - assert!(!menu.picking); - } - - #[test] - fn right_click_exits_picking_or_closes_menu() { - let _guard = test_env_lock(); - let mut menu = blank_menu(); - crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed); - menu.picking = true; - menu.note = CONFIRM_IMPORT.to_owned(); - menu.changed = false; - - menu.handle_right_click(); - assert!(!menu.picking); - assert!(menu.note.is_empty()); - assert!(menu.changed); - assert!(Menu::open()); - - menu.note = "SAVED".to_owned(); - menu.changed = false; - menu.handle_right_click(); - assert!(!Menu::open()); - assert!(menu.note.is_empty()); - assert!(menu.changed); - } - - #[test] - fn wheel_scroll_steps_selection_and_drains_notches() { - let _guard = test_env_lock(); - crate::SETTINGS_MENU_WHEEL.store(0, Ordering::Relaxed); - crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed); - crate::push_settings_menu_wheel(120); - assert_eq!(crate::take_settings_menu_wheel_notches(), 0); - - crate::SETTINGS_MENU_OPEN.store(true, Ordering::Relaxed); - crate::push_settings_menu_wheel(60); - assert_eq!(crate::take_settings_menu_wheel_notches(), 0); - crate::push_settings_menu_wheel(120); - assert_eq!(crate::take_settings_menu_wheel_notches(), 1); - crate::push_settings_menu_wheel(60); - assert_eq!(crate::take_settings_menu_wheel_notches(), 1); - crate::push_settings_menu_wheel(-240); - assert_eq!(crate::take_settings_menu_wheel_notches(), -2); - crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed); - - let mut menu = blank_menu(); - menu.note = CONFIRM_PRELOAD.to_owned(); - menu.scroll(-2); - assert_eq!(menu.at, 2); - assert!(menu.note.is_empty()); - assert!(menu.changed); - menu.scroll(1); - assert_eq!(menu.at, 1); - - menu.picking = true; - menu.imports = vec!["a.zip".to_owned(), "b.zip".to_owned()]; - menu.import_at = 0; - menu.scroll(1); - assert_eq!(menu.import_at, 2); - menu.scroll(-1); - assert_eq!(menu.import_at, 0); - } - - /// A key that could not be written to `bindings.ini` is not shown as the line's key, and - /// is not written later with another line's; one that was written is shown. - #[test] - fn a_binding_is_shown_only_once_its_file_took_it() { - use std::sync::atomic::Ordering::Relaxed; - let dir = std::env::temp_dir().join(format!("victory-menu-binds-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("bindings.ini"); - std::fs::write(&file, "Y = F\nSensitivity = 0.135\n").unwrap(); - let mut b = binds::Binds::read(file.clone()).expect("reads"); - let count = crate::MNK_BINDINGS_CHANGED.load(Relaxed); - // the folder is gone: nothing can be written - std::fs::remove_dir_all(&dir).unwrap(); - assert!(!b.set("Y", "E")); - assert_eq!(b.value("Y"), "F", "a key that was not saved is shown"); - assert_eq!(b.sensitivity(1), None); - assert_eq!(b.value(binds::SENSITIVITY), "0.135"); - assert_eq!(crate::MNK_BINDINGS_CHANGED.load(Relaxed), count, "the game was told to read the file again"); - // the folder is back: this line is written, without the ones that failed - std::fs::create_dir_all(&dir).unwrap(); - assert!(b.set("LB", "Tab")); - assert_eq!((b.value("LB").as_str(), b.value("Y").as_str()), ("TAB", "F")); - assert_eq!(std::fs::read_to_string(&file).unwrap(), "Y = F\nSensitivity = 0.135\nLB = Tab\n"); - assert_eq!(crate::MNK_BINDINGS_CHANGED.load(Relaxed), count + 1); - let _ = std::fs::remove_dir_all(&dir); - } -} +} \ No newline at end of file diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index 7ffc2d9d0..42b7d2dbd 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -1,14 +1,6 @@ -//! The run's numbers on the picture, in every build (`VICTORY_PANEL=1`; off -//! by default; F3 or the settings menu shows and hides it while our window -//! has the focus; the time spent recording is counted in diagnostics builds -//! only): white -//! text on a black box in the upper left corner of what is shown, so that a -//! screenshot carries them, with what it costs itself on the submitting -//! thread. Made again twice a second from the counters of -//! the frame-rate line, memory and textures; a frame itself only copies the -//! box out of a buffer in the card's memory. Copied onto the swap chain's -//! buffer, behind the title's picture: saved frames and the frame recorder -//! see the title's own. +//! Slim vertical Top-Left F3 stats panel (with 2-minute sparkline graphs), +//! startup notice banner, and F2 performance advisor, rendered with smooth +//! anti-aliased Consolas text, 1px drop shadow, and a Vice City color theme. use std::sync::{Once, OnceLock}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -16,64 +8,38 @@ use std::time::{Duration, Instant}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; -use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F3, VK_F7, VK_F8}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F2, VK_F3, VK_F7, VK_F8}; use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; -use super::font::{colours, glyph}; +use super::font::{Canvas, Rgb, bpp, theme}; use super::{Host, HostList, transition}; -/// How often the numbers change. const EVERY: Duration = Duration::from_millis(500); - -/// A character's dots, and with the space beside and below it. -const GLYPH: (u32, u32) = (5, 7); -const CELL: (u32, u32) = (6, 9); -/// Characters in a line, lines, and the box's rim in dots. -const COLUMNS: u32 = 40; -const LINES: u32 = 13; -const RIM: u32 = 3; - -/// Graphs under the text (FPS, the game's CPU, its memory, the card's -/// memory): each [`GRAPH`] dots high with [`GRAPH_GAP`] below, one sample a -/// dot across the box, the newest on the right (two minutes at [`EVERY`]). -const GRAPHS: u32 = 4; -const GRAPH: u32 = 16; -const GRAPH_GAP: u32 = 3; -const HISTORY: usize = (COLUMNS * CELL.0) as usize; - -/// The texts are put into one of these in turn: the card reads the others, -/// at most half a second old. const UPLOADS: usize = 4; +const GRAPHS: usize = 4; +const HISTORY: usize = 190; fn asked() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| crate::switch::on("VICTORY_PANEL")) } -/// Whether it is shown now. pub(super) fn shown() -> &'static AtomicBool { static SHOWN: OnceLock = OnceLock::new(); SHOWN.get_or_init(|| AtomicBool::new(asked())) } -/// F3 was pressed since the last call, with one of our windows in front. fn pressed() -> bool { static DOWN: AtomicBool = AtomicBool::new(false); - // SAFETY: a plain query. let down = unsafe { GetAsyncKeyState(i32::from(VK_F3)) } < 0; if DOWN.swap(down, Ordering::Relaxed) || !down { return false; } let mut process = 0; - // SAFETY: plain queries; room for the answer. unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; process == std::process::id() } -/// The F3 key, gathered on a thread of its own every 10 ms: a frame lasts -/// 50 ms and more, and a short press would fall between two presents and -/// never toggle the panel (the settings menu's keys run on one for the -/// same reason). fn watch_f3() { static WATCH: Once = Once::new(); WATCH.call_once(|| { @@ -86,8 +52,6 @@ fn watch_f3() { }); } -/// F8 or F7 was pressed since the last call, with one of our windows in -/// front: the flush it asks for (`crate::resource::ask_flush`). fn flush_pressed() -> Option { static DOWN: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2]; let mut asked = None; @@ -96,7 +60,6 @@ fn flush_pressed() -> Option { (VK_F7, crate::resource::FLUSH_HARD), ]; for (was, (key, kind)) in DOWN.iter().zip(keys) { - // SAFETY: a plain query. let down = unsafe { GetAsyncKeyState(i32::from(key)) } < 0; if !was.swap(down, Ordering::Relaxed) && down { asked = Some(kind); @@ -104,101 +67,44 @@ fn flush_pressed() -> Option { } let kind = asked?; let mut process = 0; - // SAFETY: plain queries; room for the answer. unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; (process == std::process::id()).then_some(kind) } -/// A box's characters in a line, and lines. +fn scale_pct(height: u32) -> u32 { + std::env::var("VICTORY_UI_PCT").ok().and_then(|v| v.parse::().ok()).filter(|&s| s >= 50).unwrap_or_else(|| ((height * 117) / 1080).clamp(95, 275)) +} + +#[inline] +fn s(base: u32, pct: u32) -> u32 { + ((base * pct) + 50) / 100 +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub(super) struct Shape { - columns: u32, - lines: u32, - /// Graphs under the lines ([`GRAPHS`]). - graphs: u32, +enum Kind { + Stats, + Notice(u32, u32), + Advisor, } -/// The numbers panel's box. -const PANEL: Shape = Shape { columns: COLUMNS, lines: LINES, graphs: GRAPHS }; - -/// The box's size in pixels, a dot being `scale` of them each way. -const fn size(shape: Shape, scale: u32) -> (u32, u32) { - ( - (shape.columns * CELL.0 + 2 * RIM) * scale, - (shape.lines * CELL.1 + shape.graphs * (GRAPH + GRAPH_GAP) + 2 * RIM) * scale, - ) -} - -/// Pixels to a dot for a picture that high: a 720-line screenshot of it -/// shows one and a third. -fn scale(height: u32) -> u32 { - (height / 540).max(1) -} - -/// Whether a dot of the picture of `lines` and `graphs` is white. -fn lit(lines: &[String], graphs: &[Vec], shape: Shape, x: u32, y: u32) -> bool { - let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else { - return false; - }; - if let Some(below) = y.checked_sub(shape.lines * CELL.1) { - return graph_lit(graphs, shape, x, below); - } - if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= shape.columns { - return false; - } - let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else { - return false; - }; - (glyph(c.to_ascii_uppercase())[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0 -} - -/// Whether a dot `below` the lines, `x` across, is white: a bar as high as -/// the sample in its column (0 to 1 of the graph's scale), and a dotted line -/// at the bottom of each graph. -fn graph_lit(graphs: &[Vec], shape: Shape, x: u32, below: u32) -> bool { - let (i, within) = ((below / (GRAPH + GRAPH_GAP)) as usize, below % (GRAPH + GRAPH_GAP)); - let width = shape.columns * CELL.0; - if i >= shape.graphs as usize || within >= GRAPH || x >= width { - return false; - } - if within == GRAPH - 1 { - return x.is_multiple_of(2); - } - let Some(samples) = graphs.get(i) else { - return false; - }; - // The newest on the right. - let back = (width - 1 - x) as usize; - let Some(&value) = samples.len().checked_sub(1 + back).and_then(|k| samples.get(k)) else { - return false; - }; - let high = (value.clamp(0.0, 1.0) * (GRAPH - 1) as f32).round() as u32; - within + high >= GRAPH - 1 -} - -/// The box as rows of `pitch` bytes. -fn painted(lines: &[String], graphs: &[Vec], shape: Shape, scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec { - let (width, height) = size(shape, scale); - let bytes = colours[0].len(); - let mut out = vec![0; pitch * height as usize]; - for y in 0..height / scale { - let top = pitch * (y * scale) as usize; - for x in 0..width / scale { - let colour = colours[usize::from(lit(lines, graphs, shape, x, y))]; - for i in 0..scale { - let at = top + (x * scale + i) as usize * bytes; - out[at..at + bytes].copy_from_slice(colour); - } - } - for i in 1..scale as usize { - out.copy_within(top..top + pitch, top + i * pitch); +fn box_size(kind: Kind, pct: u32) -> (u32, u32) { + match kind { + Kind::Stats => (s(226, pct).max(170), s(394, pct).max(290)), + Kind::Notice(cols, lines) => { + let w = s((cols.max(20) * 9 + 28).min(560), pct).max(220); + let h = s(lines.max(1) * 20 + 20, pct).max(40); + (w, h) } + Kind::Advisor => (s(610, pct).max(420), s(172, pct).max(124)), } - out } -/// The counters read for it. They grow, and go back to 0 with the frame-rate -/// line (right behind a look of ours). +#[derive(Clone)] +enum StatRow { + Metric { label: &'static str, value: String, color: Rgb, bold: bool, small: bool }, + Divider, +} + #[derive(Clone, Copy, Default)] struct Counters([u64; COUNTERS]); @@ -227,7 +133,6 @@ impl Counters { ]) } - /// What came since `before`, per frame. fn since(self, before: Counters, frames: f64) -> [f64; COUNTERS] { let mut out = [0.0; COUNTERS]; for (i, out) in out.iter_mut().enumerate() { @@ -238,8 +143,6 @@ impl Counters { } } -/// The process's memory in bytes: in physical memory, and committed -/// (private bytes). pub(super) fn process_memory() -> (u64, u64) { use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -247,41 +150,30 @@ pub(super) fn process_memory() -> (u64, u64) { cb: size_of::() as u32, ..Default::default() }; - // SAFETY: our own process and a sized structure. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; (c.WorkingSetSize as u64, c.PagefileUsage as u64) } -/// The PC's memory in bytes: physical free and in all, and what is left to -/// commit before the system's limit. fn pc_memory() -> (u64, u64, u64) { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - // SAFETY: plain data the call fills in. let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = size_of::() as u32; - // SAFETY: a sized structure. unsafe { GlobalMemoryStatusEx(&mut m) }; (m.ullAvailPhys, m.ullTotalPhys, m.ullAvailPageFile) } -/// CPU time in 100 ns units: this process's (kernel and user), and the -/// whole PC's idle and busy-or-idle (kernel, which holds idle, and user). fn cpu_times() -> (u64, u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes, GetSystemTimes}; let t = |f: FILETIME| (u64::from(f.dwHighDateTime) << 32) | u64::from(f.dwLowDateTime); let z = || FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; let (mut created, mut exited, mut kernel, mut user) = (z(), z(), z(), z()); - // SAFETY: our own process; room for the answers. unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; let (mut idle, mut sys_kernel, mut sys_user) = (z(), z(), z()); - // SAFETY: room for the answers. unsafe { GetSystemTimes(&mut idle, &mut sys_kernel, &mut sys_user) }; (t(kernel) + t(user), t(idle), t(sys_kernel) + t(sys_user)) } -/// The game's and the PC's CPU use in percent between two [`cpu_times`] -/// `seconds` apart on `cores` logical processors. fn cpu_percent(before: (u64, u64, u64), now: (u64, u64, u64), seconds: f64, cores: f64) -> (f64, f64) { let ours = now.0.saturating_sub(before.0) as f64 / 1e7; let game = 100.0 * ours / (seconds * cores).max(1e-9); @@ -290,7 +182,6 @@ fn cpu_percent(before: (u64, u64, u64), now: (u64, u64, u64), seconds: f64, core (game.clamp(0.0, 100.0), pc.clamp(0.0, 100.0)) } -/// What the panel says of the PC beside the run's counters. #[derive(Clone, Copy, Default)] struct Pc { cpu_game: f64, @@ -300,115 +191,229 @@ struct Pc { commit_left: u64, } -/// The lines of [`Pc`]. -fn pc_lines(pc: Pc) -> [String; 2] { - let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64; - [ - format!("CPU GAME {:.0}% PC {:.0}%", pc.cpu_game, pc.cpu_pc), - format!("FREE RAM {:.1}/{:.0} GB COMMIT LEFT {:.1}", gb(pc.free), gb(pc.total), gb(pc.commit_left)), - ] -} - -/// The line that names the graphs, top to bottom. -const LEGEND: &str = "GRAPHS 2 MIN: FPS/60 CPU RAM/PC VRAM"; - -/// Show the applied mode and, when the backend reports it, the last present count. -fn generated(fps: f64, reading: crate::streamline::FramegenReading) -> String { - use crate::streamline::FramegenReading; - match reading { - FramegenReading::Off => "FRAME GEN OFF".to_owned(), - FramegenReading::Dlss(None) => "FRAME GEN ON WAITING FOR PRESENT".to_owned(), - FramegenReading::Dlss(Some(per)) => { - format!("FRAME GEN ON {per}X SHOWN {:.1} FPS", fps * f64::from(per)) - } - FramegenReading::Fsr => "FSR 3 FRAME GEN ON TARGET 2X".to_owned(), - } -} - -/// The upscaling line: DLSS's mode and preset, or that the title's own -/// upscaling runs. -fn upscaler(dlss: Option<(&str, Option)>) -> String { - match dlss { - Some((mode, Some(preset))) => format!("DLSS {mode} PRESET {preset}").to_uppercase(), - Some((mode, None)) => format!("DLSS {mode}").to_uppercase(), - None => "DLSS OFF THE TITLE UPSCALES".to_owned(), - } -} - -/// The text. `c`: [`Counters`] per frame, `ms` a frame's time, `worst` the -/// longest frame's, `cost` what this takes of a frame, in microseconds, -/// `output` the picture's size. -fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, pc: Pc, output: (u32, u32), host: &Host) -> Vec { +fn build_rows(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, pc: Pc, output: (u32, u32), host: &Host) -> Vec { let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64; let (_, private) = process_memory(); let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); let idle = (c[1] / 1e3).min(ms); let fps = 1e3 / ms.max(0.001); - let console = match crate::console::current() { - crate::console::Console::SeriesS => "SERIES S", - crate::console::Console::SeriesX => "SERIES X", + let (fg_lbl, fg_val, fg_col) = match crate::streamline::framegen_reading() { + crate::streamline::FramegenReading::Off => ("FG", "OFF".to_owned(), theme::MUTED), + crate::streamline::FramegenReading::Dlss(None) => ("FG", "WAIT".to_owned(), theme::AMBER), + crate::streamline::FramegenReading::Dlss(Some(per)) => { + let lbl = match per { + 2 => "FG 2X", + 3 => "FG 3X", + 4 => "FG 4X", + 5 => "FG 5X", + 6 => "FG 6X", + _ => "FG", + }; + (lbl, format!("{:.1} FPS", fps * f64::from(per)), theme::MINT) + } + crate::streamline::FramegenReading::Fsr => ("FSR3", "2X ON".to_owned(), theme::MINT), }; - let dlss = crate::streamline::upscaled_lately(); - let size = |[w, h]: [u32; 2]| format!("{w}X{h}"); - let picture = match dlss { - Some((_, scene, out, _)) => format!("SCENE {} OUTPUT {}", size(scene), size(out)), - None => format!("OUTPUT {}", size([output.0, output.1])), + let dlss_val = match crate::streamline::upscaled_lately() { + Some((mode, _, _, Some(preset))) => format!("{} ({preset})", mode.to_ascii_uppercase()), + Some((mode, _, _, None)) => mode.to_ascii_uppercase(), + None => format!("OFF {}P", output.1), }; - // Which ray tracing runs: the card's own (DXR, `VICTORY_HW_RT=1`), ours - // in shaders (`VICTORY_BVH_BUILDER=1`), or none. - let rays = if crate::hwrt::active() { - "RAY TRACING HARDWARE (DXR)" + let (rt_val, rt_col, rt_bold) = if crate::hwrt::active() { + ("DXR".to_owned(), theme::PINK, true) } else if std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1") { - "RAY TRACING SOFTWARE" + ("ON".to_owned(), theme::PINK, true) } else { - "RAY TRACING OFF" + ("OFF".to_owned(), theme::MUTED, false) }; - let [cpu, free] = pc_lines(pc); + let vram_col = if budget > 0 && (used as f64 / budget as f64) > 0.85 { theme::CORAL } else { theme::TEXT }; + let drop_col = if c[8] >= 1.0 { theme::CORAL } else { theme::MINT }; + let free_col = if pc.free < (3u64 << 30) { theme::AMBER } else { theme::TEXT }; + vec![ - format!("FPS {fps:.1} FRAME {ms:.1} MS LONGEST {worst:.0}"), - format!("{console} BUILD {}", env!("VICTORY_BUILD")).to_uppercase(), - picture, - upscaler(dlss.map(|(mode, _, _, preset)| (mode, preset))), - generated(fps, crate::streamline::framegen_reading()), - rays.to_owned(), - format!("GPU BUSY {:.1} MS WAITS FOR GPU {:.1}", ms - idle, c[3] / 1e3), - format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]), - format!("RAM {:.1} GB", gb(private)), - format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)), - cpu, - free, - format!("THIS PANEL {:.0} US A FRAME", cost), - LEGEND.to_owned(), + StatRow::Metric { label: "FPS", value: format!("{fps:.1}"), color: theme::CYAN, bold: true, small: false }, + StatRow::Metric { label: "FRAME", value: format!("{ms:.1} ms"), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "LONGEST", value: format!("{worst:.0} ms"), color: theme::MUTED, bold: false, small: false }, + StatRow::Metric { label: fg_lbl, value: fg_val, color: fg_col, bold: true, small: false }, + StatRow::Metric { label: "DLSS", value: dlss_val, color: theme::CYAN, bold: false, small: false }, + StatRow::Metric { label: "RT", value: rt_val, color: rt_col, bold: rt_bold, small: false }, + StatRow::Divider, + StatRow::Metric { label: "DRAWS", value: format!("{:.0}", c[10]), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "DROPPED", value: format!("{:.0}", c[8]), color: drop_col, bold: false, small: false }, + StatRow::Metric { label: "SUBMIT BUSY", value: format!("{:.1} ms", c[0] / 1e3), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "WAITS FOR GPU", value: format!("{:.1} ms", c[3] / 1e3), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "GPU BUSY", value: format!("{:.1} ms", ms - idle), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "COPY BACK", value: format!("{:.1} ms", c[6] / 1e3), color: theme::MUTED, bold: false, small: false }, + StatRow::Divider, + StatRow::Metric { label: "RAM", value: format!("{:.1} GB", gb(private)), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "FREE RAM", value: format!("{:.1}/{:.0}G", gb(pc.free), gb(pc.total)), color: free_col, bold: false, small: false }, + StatRow::Metric { label: "VRAM", value: format!("{:.1}/{:.1}G", gb(used), gb(budget)), color: vram_col, bold: false, small: false }, + StatRow::Metric { label: "SHARED", value: format!("{:.1} GB", gb(shared)), color: theme::MUTED, bold: false, small: false }, + StatRow::Metric { label: "CPU", value: format!("{:.0}% / {:.0}%", pc.cpu_game, pc.cpu_pc), color: theme::TEXT, bold: false, small: false }, + StatRow::Metric { label: "COMMIT LEFT", value: format!("{:.1} GB", gb(pc.commit_left)), color: theme::MUTED, bold: false, small: true }, + StatRow::Metric { label: "THIS PANEL", value: format!("{cost:.0} us"), color: theme::MUTED, bold: false, small: true }, ] } -/// The buffers of a box that size and format. +fn render_stats(rows: &[StatRow], history: &[Vec], pct: u32, format: DXGI_FORMAT, pitch: usize) -> Option> { + let (w, h) = box_size(Kind::Stats, pct); + let mut c = Canvas::new(w, h)?; + let border = (pct / 100).max(1); + let bar_h = s(3, pct).max(2); + let pad_x = s(10, pct) as i32; + let right_x = w as i32 - pad_x; + let shadow = (pct / 110).max(1) as i32; + let f_main = s(12, pct) as i32; + let f_small = s(10, pct) as i32; + let row_step = s(15, pct) as i32; + let small_step = s(13, pct) as i32; + + c.clear(theme::BG); + c.stroke_border(border, theme::BORDER); + c.top_gradient_bar(bar_h, theme::PINK, theme::CYAN); + + let mut y = (bar_h + s(7, pct)) as i32; + for r in rows { + match r { + StatRow::Metric { label, value, color, bold, small } => { + let fh = if *small { f_small } else { f_main }; + let lcol = if *small { theme::MUTED } else { theme::LABEL }; + c.text(pad_x, y, label, "Consolas", fh, false, lcol, shadow); + c.text_right(right_x, y, value, "Consolas", fh, *bold, *color, shadow); + y += if *small { small_step } else { row_step }; + } + StatRow::Divider => { + let dy = (y + s(2, pct) as i32).max(0) as u32; + c.fill_rect(pad_x as u32, dy, w.saturating_sub(pad_x as u32), dy + border, theme::DIVIDER); + y += s(7, pct) as i32; + } + } + } + + // 4 compact 2-minute sparkline graphs (FPS/60, CPU, RAM, VRAM) + let dy = (y + s(2, pct) as i32).max(0) as u32; + c.fill_rect(pad_x as u32, dy, w.saturating_sub(pad_x as u32), dy + border, theme::DIVIDER); + let gx0 = pad_x as u32; + let gx1 = w.saturating_sub(pad_x as u32); + let gw = gx1.saturating_sub(gx0); + let mut gy = dy + s(6, pct); + let gh = s(14, pct).max(10); + let ggap = s(4, pct).max(2); + let g_cols = [theme::CYAN, theme::PINK, theme::AMBER, theme::MINT]; + let g_lbls = ["FPS", "CPU", "RAM", "VRAM"]; + let f_glbl = s(9, pct) as i32; + + for i in 0..GRAPHS { + if gy + gh >= h.saturating_sub(border) { + break; + } + c.fill_rect(gx0, gy, gx1, gy + gh, theme::GRAPH_BG); + if let Some(samples) = history.get(i) { + let n = samples.len(); + if n > 0 && gw > 0 { + let cols = gw.min(HISTORY as u32); + for dx in 0..cols { + let back = (cols - 1 - dx) as usize; + if let Some(&val) = n.checked_sub(1 + back).and_then(|k| samples.get(k)) { + let bh = (val.clamp(0.0, 1.0) * (gh - 1) as f32).round() as u32; + if bh > 0 { + let x = gx1 - cols + dx; + c.fill_rect(x, gy + gh - bh, x + 1, gy + gh, g_cols[i]); + } + } + } + } + } + c.text(gx0 as i32 + 2, gy as i32 + 1, g_lbls[i], "Consolas", f_glbl, true, theme::TEXT, 1); + gy += gh + ggap; + } + + c.pack(format, pitch) +} + +fn render_notice(lines: &[String], kind: Kind, pct: u32, format: DXGI_FORMAT, pitch: usize) -> Option> { + let (w, h) = box_size(kind, pct); + let mut c = Canvas::new(w, h)?; + let border = (pct / 100).max(1); + let bar_h = s(3, pct).max(2); + let pad_x = s(14, pct) as i32; + let shadow = (pct / 110).max(1) as i32; + let fh = s(13, pct) as i32; + let step = s(18, pct) as i32; + + c.clear(theme::BG); + c.stroke_border(border, theme::BORDER); + c.top_gradient_bar(bar_h, theme::PINK, theme::CYAN); + + let mut y = (bar_h + s(9, pct)) as i32; + for (idx, line) in lines.iter().enumerate() { + let col = if idx == 0 { theme::CYAN } else { theme::TEXT }; + c.text(pad_x, y, line, "Consolas", fh, idx == 0, col, shadow); + y += step; + } + c.pack(format, pitch) +} + +fn render_advisor(lines: &[String], pct: u32, format: DXGI_FORMAT, pitch: usize) -> Option<(Vec, u32)> { + let (w, max_h) = box_size(Kind::Advisor, pct); + let mut c = Canvas::new(w, max_h)?; + let border = (pct / 100).max(1); + let bar_h = s(3, pct).max(2); + let pad_x = s(14, pct) as i32; + let shadow = (pct / 110).max(1) as i32; + let fh = s(12, pct) as i32; + let step = s(17, pct) as i32; + let visible = lines.len().max(1) as u32; + let draw_h = (bar_h + s(8, pct) + visible * s(17, pct) + s(6, pct)).min(max_h); + + c.clear(theme::BG); + c.fill_rect(0, 0, w, border, theme::BORDER); + c.fill_rect(0, draw_h.saturating_sub(border), w, draw_h, theme::BORDER); + c.fill_rect(0, 0, border, draw_h, theme::BORDER); + c.fill_rect(w.saturating_sub(border), 0, w, draw_h, theme::BORDER); + c.top_gradient_bar(bar_h, theme::PINK, theme::CYAN); + + let mut y = (bar_h + s(8, pct)) as i32; + for (idx, line) in lines.iter().enumerate() { + let (col, bold) = if idx == 0 { + (theme::CYAN, true) + } else if line.starts_with("LIMIT:") || line.starts_with("ALSO:") { + (theme::CORAL, true) + } else if line.starts_with(" TRY:") { + (theme::MINT, false) + } else if line.starts_with("NOTE:") { + (theme::AMBER, false) + } else { + (theme::MUTED, false) + }; + c.text(pad_x, y, line, "Consolas", fh, bold, col, shadow); + y += step; + } + c.pack(format, pitch).map(|pic| (pic, draw_h)) +} + struct Buffers { - shape: Shape, format: DXGI_FORMAT, - scale: u32, + pct: u32, + width: u32, + height: u32, + draw_h: u32, pitch: u32, uploads: Vec<(ID3D12Resource, *mut u8)>, card: ID3D12Resource, - /// The upload written last. turn: usize, - /// It is not in the card's buffer yet. fresh: bool, + used: bool, } -// SAFETY: free-threaded resources, and memory only written under the presenter's lock. unsafe impl Send for Buffers {} impl Buffers { - fn new(host: &Host, shape: Shape, format: DXGI_FORMAT, scale: u32) -> Option { - let (width, height) = size(shape, scale); - let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256); + fn new(host: &Host, kind: Kind, format: DXGI_FORMAT, pct: u32) -> Option { + let (width, height) = box_size(kind, pct); + let pitch = (width * bpp(format)?).next_multiple_of(256); let bytes = u64::from(pitch) * u64::from(height); let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::>>()?; - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, @@ -420,34 +425,29 @@ impl Buffers { ..Default::default() }; let mut card: Option = None; - // SAFETY: plain creation of a buffer. unsafe { host.device .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card) .ok()?; } - Some(Buffers { shape, format, scale, pitch, uploads, card: card?, turn: 0, fresh: false }) + Some(Buffers { format, pct, width, height, draw_h: height, pitch, uploads, card: card?, turn: 0, fresh: false, used: false }) } - fn write(&mut self, lines: &[String], graphs: &[Vec]) { - let Some(colours) = colours(self.format) else { return }; - let picture = painted(lines, graphs, self.shape, self.scale, colours, self.pitch as usize); + fn upload(&mut self, picture: Vec) { self.turn = (self.turn + 1) % UPLOADS; - // SAFETY: a mapped upload buffer of the picture's size, which the card read a second or more ago. unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) }; self.fresh = true; } - /// Records the copy of the box onto `back` (of `width` x `height`, in the - /// state to be copied into), its upper left corner at `at`. fn copy(&mut self, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, at: (u32, u32), (width, height): (u32, u32)) { - let (w, h) = size(self.shape, self.scale); if at.0 >= width || at.1 >= height { return; } - // SAFETY: an open list and live resources; the box lies within both. unsafe { if std::mem::take(&mut self.fresh) { + if std::mem::replace(&mut self.used, true) { + crate::barstat::rb(list, &[transition(&self.card, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } list.CopyResource(&self.card, &self.uploads[self.turn].0); crate::barstat::rb(list, &[transition(&self.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); } @@ -459,8 +459,8 @@ impl Buffers { Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: self.format, - Width: w, - Height: h, + Width: self.width, + Height: self.height, Depth: 1, RowPitch: self.pitch, }, @@ -472,32 +472,32 @@ impl Buffers { Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, }; - let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w.min(width - at.0), bottom: h.min(height - at.1), back: 1 }; + let part = D3D12_BOX { + left: 0, + top: 0, + front: 0, + right: self.width.min(width - at.0), + bottom: self.draw_h.min(self.height).min(height - at.1), + back: 1, + }; list.CopyTextureRegion(&to, at.0, at.1, 0, &from, Some(&part)); } } } -/// The panel of a presenter. pub(super) struct Panel { since: Instant, frames: u32, last: Instant, worst: f64, - /// What this took since the last text. cost: Duration, before: Counters, - lines: Vec, + rows: Vec, changed: bool, buffers: Option, failed: bool, - /// The picture the failed buffers were for: a change of it tries again. - failed_at: Option<(DXGI_FORMAT, u32)>, - /// The picture's size, as the last draw had it. output: (u32, u32), - /// The graphs' samples, 0 to 1 of their scales ([`GRAPHS`]). history: Vec>, - /// [`cpu_times`] at the last text, and when. cpu: Option<((u64, u64, u64), Instant)>, } @@ -512,18 +512,16 @@ impl Panel { worst: 0.0, cost: Duration::ZERO, before: Counters::default(), - lines: Vec::new(), + rows: Vec::new(), changed: false, buffers: None, failed: false, - failed_at: None, output: (0, 0), - history: vec![Vec::new(); GRAPHS as usize], + history: vec![Vec::new(); GRAPHS], cpu: None, } } - /// The PC's numbers now, and a sample for each graph. fn sample(&mut self, fps: f64, host: &Host) -> Pc { let now = (cpu_times(), Instant::now()); let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64; @@ -545,8 +543,6 @@ impl Panel { Pc { cpu_game, cpu_pc, free, total, commit_left } } - /// A frame was presented; `line`: the counters go back to 0 right behind - /// this call. (Not shown it asks for the key's state and no more.) pub(super) fn frame(&mut self, line: bool) { if let Some(kind) = flush_pressed() { crate::resource::ask_flush(kind); @@ -557,10 +553,6 @@ impl Panel { } let now = Instant::now(); if self.frames == 0 { - // Shown from here on, whatever the hidden gap was: a window - // that keeps it in `since` and `last` prints the gap as a - // frame time (the panel re-shown within a second printed - // about a second a frame) and spreads the counters over it. (self.since, self.last, self.worst, self.before) = (now, now, 0.0, Counters::now()); } self.frames += 1; @@ -578,14 +570,12 @@ impl Panel { let cost = self.cost.as_secs_f64() * 1e6 / frames; let ms = elapsed.as_secs_f64() * 1e3 / frames; let pc = self.sample(1e3 / ms.max(0.001), host); - self.lines = text(&c, ms, self.worst, cost, pc, self.output, host); + self.rows = build_rows(&c, ms, self.worst, cost, pc, self.output, host); self.changed = true; (self.since, self.frames, self.worst) = (now, 0, 0.0); self.cost = now.elapsed(); } - /// Records the copy of the box onto `back`, a buffer of the swap chain of - /// that size and format in the state to be copied into. pub(super) fn draw( &mut self, host: &Host, @@ -594,48 +584,40 @@ impl Panel { (width, height): (u32, u32), format: DXGI_FORMAT, ) { - // A failed making of the buffers gives up on this picture only: a - // resize (or a format change) tries again. - let scale = scale(height); - if self.failed && self.failed_at == Some((format, scale)) { - return; - } - if !shown().load(Ordering::Relaxed) || self.lines.is_empty() { + if !shown().load(Ordering::Relaxed) || self.rows.is_empty() || self.failed { return; } let began = Instant::now(); self.output = (width, height); - // Not the title's: the frame recorder leaves it out. #[cfg(feature = "diagnostics")] let _ours = crate::replay::record::unrecorded(); - if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { - // (What the card may still read stays: a picture's size changes once or twice in a run.) + let pct = scale_pct(height); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) { std::mem::forget(self.buffers.take()); - self.buffers = Buffers::new(host, PANEL, format, scale); + self.buffers = Buffers::new(host, Kind::Stats, format, pct); self.failed = self.buffers.is_none(); - self.failed_at = self.failed.then_some((format, scale)); self.changed = true; } let Some(buffers) = &mut self.buffers else { return }; if std::mem::take(&mut self.changed) { - buffers.write(&self.lines, &self.history); + if let Some(pic) = render_stats(&self.rows, &self.history, pct, format, buffers.pitch as usize) { + buffers.upload(pic); + } } - buffers.copy(&list.list, back, (0, 0), (width, height)); + let margin = s(10, pct); + let x = margin.min(width.saturating_sub(buffers.width)); + let y = margin.min(height.saturating_sub(buffers.height)); + buffers.copy(&list.list, back, (x, y), (width, height)); self.cost += began.elapsed(); } } -/// How long the start's notice stays. const NOTICE_FOR: Duration = Duration::from_secs(30); -/// The longest notice line, in characters. const NOTICE_COLUMNS: u32 = 52; -/// What this card does for frame generation, said at the top of the picture -/// for the first [`NOTICE_FOR`] of a run (`crate::streamline::notice`); in -/// every build, nothing without a notice. pub(super) struct Notice { lines: Vec, - shape: Shape, + kind: Kind, since: Option, buffers: Option, written: bool, @@ -644,9 +626,7 @@ pub(super) struct Notice { impl Notice { pub(super) fn new() -> Notice { - // The first start of a new victory.exe says first that it restarts by itself (menu.rs). let warmup = super::menu::warmup_seconds().map(super::menu::warmup_notice).unwrap_or_default(); - // What the start itself has to say comes before both, with an empty line after it. let mut start = crate::start_notice::lines(); if !start.is_empty() { start.push(String::new()); @@ -654,29 +634,30 @@ impl Notice { let lines: Vec = start.into_iter().chain(warmup).chain(crate::streamline::notice()).map(|l| l.to_ascii_uppercase()).collect(); let columns = lines.iter().map(|l| l.len() as u32).max().unwrap_or(0).min(NOTICE_COLUMNS); - let shape = Shape { columns, lines: lines.len() as u32, graphs: 0 }; - Notice { done: lines.is_empty(), lines, shape, since: None, buffers: None, written: false } + let kind = Kind::Notice(columns, lines.len() as u32); + Notice { done: lines.is_empty(), lines, kind, since: None, buffers: None, written: false } + } + + pub(super) fn showing(&self) -> bool { + !self.done } - /// Records the copy of the notice onto `back` (as [`Panel::draw`]), at - /// the top in the middle, while it is due. pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) { if self.done { return; } let since = *self.since.get_or_insert_with(Instant::now); if since.elapsed() > NOTICE_FOR { - // (Its buffers stay: the card may still read them.) std::mem::forget(self.buffers.take()); self.done = true; return; } #[cfg(feature = "diagnostics")] let _ours = crate::replay::record::unrecorded(); - let scale = scale(height); - if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + let pct = scale_pct(height); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) { std::mem::forget(self.buffers.take()); - self.buffers = Buffers::new(host, self.shape, format, scale); + self.buffers = Buffers::new(host, self.kind, format, pct); self.written = false; if self.buffers.is_none() { self.done = true; @@ -685,53 +666,39 @@ impl Notice { } let Some(buffers) = &mut self.buffers else { return }; if !std::mem::replace(&mut self.written, true) { - buffers.write(&self.lines, &[]); + if let Some(pic) = render_notice(&self.lines, self.kind, pct, format, buffers.pitch as usize) { + buffers.upload(pic); + } } - let (w, _) = size(self.shape, scale); - let at = (width.saturating_sub(w) / 2, 24 * scale); + let at = (width.saturating_sub(buffers.width) / 2, s(18, pct)); buffers.copy(&list.list, back, at, (width, height)); } } -/// Whether the performance explainer is shown (`VICTORY_ADVISOR=1`; the settings menu's -/// "WHAT LIMITS FPS" changes it). pub(super) fn advisor_shown() -> &'static AtomicBool { static SHOWN: OnceLock = OnceLock::new(); SHOWN.get_or_init(|| AtomicBool::new(crate::switch::on("VICTORY_ADVISOR"))) } -/// The explainer's box: what holds the frame rate back now, and what helps. -const ADVISOR: Shape = Shape { columns: 68, lines: 9, graphs: 0 }; -/// The lines [`advice`] may fill; the last two are the first start's ([`FIRST_START`]). const ADVICE_LINES: usize = 7; -/// F2 was pressed since the last call, with one of our windows in front: the explainer is -/// shown or hidden. fn f2_pressed() -> bool { - use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_F2; static DOWN: AtomicBool = AtomicBool::new(false); - // SAFETY: a plain query. let down = unsafe { GetAsyncKeyState(i32::from(VK_F2)) } < 0; if DOWN.swap(down, Ordering::Relaxed) || !down { return false; } let mut process = 0; - // SAFETY: plain queries; room for the answer. unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; process == std::process::id() } -/// How long the explainer is shown on the first start of a build, whether it is asked for. const FIRST_START_FOR: Duration = Duration::from_secs(60); -/// What it says then, below the advice. const FIRST_START: [&str; 2] = [ "SHOWN FOR 1 MINUTE ON THE FIRST START OF A NEW BUILD, TO SAY WHAT", "THE GAME IS DOING. KEEP IT ON: F2, OR F1 > WHAT LIMITS FPS (F2)", ]; -/// Whether this is the first start of this build here: its mark -/// (`%LOCALAPPDATA%\victory\advisor-shown\`) is written now, so the next start is not. -/// `VICTORY_ADVISOR_FIRST=0`: never shown by itself. fn first_start_of_build() -> bool { if std::env::var_os("VICTORY_ADVISOR_FIRST").is_some_and(|v| v == "0") { return false; @@ -743,33 +710,26 @@ fn first_start_of_build() -> bool { return false; } let _ = std::fs::create_dir_all(mark.parent().unwrap_or(&mark)); - // (Unwritten, it is shown again at the next start: no harm.) let _ = std::fs::write(&mark, "the performance explainer was shown on this build's first start\r\n"); true } -/// What a half second of play said, for [`advice`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct Sample { fps: f64, - /// A frame's time, the card's busy part of it and the submitting thread's wait for the card. ms: f64, gpu_ms: f64, wait_ms: f64, - /// Pipelines being made, and draws a frame skipped for want of one. making: u64, dropped: f64, - /// Video memory in use and the budget, in GB. vram: f64, budget: f64, - /// The frame rate cap (0: none), ray tracing, the upscaler's mode, frame generation's factor. cap: f64, rays: bool, dlss: Option<&'static str>, framegen: u32, } -/// The explainer's lines for `s`: a headline, then each cause with what helps. fn advice(s: &Sample) -> Vec { let mut out = vec![format!("{:.0} FPS ({:.1} MS PER FRAME)", s.fps, s.ms)]; let mut add = |what: String, help: &str| { @@ -791,7 +751,6 @@ fn advice(s: &Sample) -> Vec { }; let gpu_line = |lead: &str| format!("{lead}: YOUR GPU IS FULLY BUSY ({:.0} OF EVERY {:.0} MS)", s.gpu_ms, s.ms); if s.making > 0 { - // The processor is making them: what it says of the CPU then is the compiling. add( format!("LIMIT: {} SHADERS STILL COMPILING (STUTTER, MISSING OBJECTS)", s.making), "WAIT, IT CLEARS BY ITSELF. RUN THE PRELOAD BEFORE PLAYING", @@ -827,9 +786,6 @@ fn advice(s: &Sample) -> Vec { out } -/// The explainer at the top in the middle (`VICTORY_ADVISOR=1`, or F1): what limits the frame -/// rate now (shaders being made, video memory, the card, the processor or the cap) and what -/// helps, made again twice a second from the stats panel's counters. pub(super) struct Advisor { since: Instant, frames: u32, @@ -838,14 +794,11 @@ pub(super) struct Advisor { changed: bool, buffers: Option, failed: bool, - /// The first start of this build ([`first_start_of_build`]): shown for [`FIRST_START_FOR`] - /// from when it is first drawn, whether it is asked for. first: bool, first_since: Option, } impl Advisor { - /// Whether it is shown now: asked for, or the first start's minute. fn on(&self) -> bool { advisor_shown().load(Ordering::Relaxed) || self.first } @@ -864,10 +817,8 @@ impl Advisor { } } - /// A frame was presented. pub(super) fn frame(&mut self) { if f2_pressed() { - // On during the first start's minute: kept on. Off: off, that minute too. let on = !self.on(); advisor_shown().store(on, Ordering::Relaxed); self.first = false; @@ -922,8 +873,6 @@ impl Advisor { (self.since, self.frames) = (now, 1); } - /// Records the copy of the box onto `back` (as [`Panel::draw`]), at the top in the middle; - /// not while the start's notice has that place. pub(super) fn draw( &mut self, host: &Host, @@ -941,210 +890,25 @@ impl Advisor { } #[cfg(feature = "diagnostics")] let _ours = crate::replay::record::unrecorded(); - let scale = scale(height); - if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + let pct = scale_pct(height); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.pct) != (format, pct)) { std::mem::forget(self.buffers.take()); - self.buffers = Buffers::new(host, ADVISOR, format, scale); + self.buffers = Buffers::new(host, Kind::Advisor, format, pct); self.failed = self.buffers.is_none(); self.changed = true; } let Some(buffers) = &mut self.buffers else { return }; if std::mem::take(&mut self.changed) { let mut lines = self.lines.clone(); - lines.resize(ADVICE_LINES, String::new()); if self.first && !advisor_shown().load(Ordering::Relaxed) { lines.extend(FIRST_START.map(str::to_owned)); } - lines.resize(ADVISOR.lines as usize, String::new()); - buffers.write(&lines, &[]); - } - let (w, _) = size(ADVISOR, scale); - buffers.copy(&list.list, back, (width.saturating_sub(w) / 2, 0), (width, height)); - } -} - -impl Notice { - /// Whether the start's notice is still due. - pub(super) fn showing(&self) -> bool { - !self.done - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A panel re-shown within a second starts its window over: the hidden - /// gap is not a frame time (`LONGEST` printed about a second), and the - /// counters are not spread over it. - #[test] - fn a_re_shown_panel_starts_its_window_over() { - let was = shown().load(Ordering::Relaxed); - shown().store(true, Ordering::Relaxed); - let mut p = Panel::new(); - p.frame(false); - // Hidden again, its window frozen where the hide caught it. - shown().store(false, Ordering::Relaxed); - p.frame(false); - p.last -= Duration::from_millis(800); - p.since -= Duration::from_millis(800); - // Re-shown within the second: the window starts over. - shown().store(true, Ordering::Relaxed); - p.frame(false); - assert_eq!(p.worst, 0.0, "the hidden gap became a frame time"); - assert_eq!(p.frames, 1); - shown().store(was, Ordering::Relaxed); - } - - /// Every character the lines use has its own picture, and no two look - /// alike. - #[test] - fn characters_differ() { - let used: Vec = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./- %:").collect(); - for (i, a) in used.iter().enumerate() { - assert_ne!(glyph(*a), glyph(b'#'), "{} has a picture", *a as char); - assert!(glyph(*a).iter().all(|row| row >> GLYPH.0 == 0)); - for b in &used[i + 1..] { - assert_ne!(glyph(*a), glyph(*b), "{} {}", *a as char, *b as char); + if let Some((pic, draw_h)) = render_advisor(&lines, pct, format, buffers.pitch as usize) { + buffers.draw_h = draw_h; + buffers.upload(pic); } } + let at = (width.saturating_sub(buffers.width) / 2, s(10, pct)); + buffers.copy(&list.list, back, at, (width, height)); } - - /// The frame generation line fits the box and says what is shown. - #[test] - fn generated_frames_are_told() { - use crate::streamline::FramegenReading::*; - assert_eq!(generated(27.5, Off), "FRAME GEN OFF"); - assert_eq!(generated(27.5, Dlss(None)), "FRAME GEN ON WAITING FOR PRESENT"); - assert_eq!(generated(27.5, Dlss(Some(0))), "FRAME GEN ON 0X SHOWN 0.0 FPS"); - assert_eq!(generated(27.5, Dlss(Some(1))), "FRAME GEN ON 1X SHOWN 27.5 FPS"); - assert_eq!(generated(27.5, Dlss(Some(2))), "FRAME GEN ON 2X SHOWN 55.0 FPS"); - assert_eq!(generated(27.5, Fsr), "FSR 3 FRAME GEN ON TARGET 2X"); - assert!(generated(999.9, Dlss(Some(6))).len() <= COLUMNS as usize); - } - - /// The upscaling line names DLSS's mode and preset, and fits the box. - #[test] - fn the_upscaler_is_told() { - assert_eq!(upscaler(Some(("quality", Some('K')))), "DLSS QUALITY PRESET K"); - assert_eq!(upscaler(Some(("ultra performance", None))), "DLSS ULTRA PERFORMANCE"); - assert_eq!(upscaler(None), "DLSS OFF THE TITLE UPSCALES"); - assert!(upscaler(Some(("ultra performance", Some('M')))).len() <= COLUMNS as usize); - } - - #[test] - fn a_box_is_painted() { - let lines = vec!["I".to_owned(), " i".to_owned()]; - for scale in [1, 2, 4] { - let (width, height) = size(PANEL, scale); - let pitch = (width * 4).next_multiple_of(256) as usize; - let colours = colours(DXGI_FORMAT_R10G10B10A2_UNORM).unwrap(); - let picture = painted(&lines, &[], PANEL, scale, colours, pitch); - assert_eq!(picture.len(), pitch * height as usize); - let at = |x: u32, y: u32| &picture[y as usize * pitch + x as usize * 4..][..4]; - // The rim is black, the first letter's top row lit in its middle. - assert_eq!(at(0, 0), colours[0]); - assert_eq!(at((RIM + 2) * scale, RIM * scale), colours[1]); - assert_eq!(at((RIM + 2) * scale + scale - 1, RIM * scale + scale - 1), colours[1]); - assert_eq!(at(RIM * scale, RIM * scale), colours[0]); - // Small letters are shown as capitals, a line and a cell on. - assert_eq!(at((RIM + CELL.0 + 2) * scale, (RIM + CELL.1) * scale), colours[1]); - // Nothing past a line's end. - assert_eq!(at((RIM + CELL.0 * 2 + 2) * scale, (RIM + CELL.1) * scale), colours[0]); - } - } - - /// A graph's newest sample is its rightmost column, as high as its value; - /// a column with no sample yet is dark but for the dotted bottom line. - #[test] - fn graphs_are_bars_of_their_samples() { - let lines: Vec = Vec::new(); - let graphs = vec![vec![0.0, 1.0], vec![0.5]]; - let top = RIM + LINES * CELL.1; - let right = RIM + COLUMNS * CELL.0 - 1; - let at = |x: u32, y: u32| lit(&lines, &graphs, PANEL, x, y); - // First graph, newest sample 1.0: lit from its top down. - assert!(at(right, top)); - assert!(at(right, top + GRAPH - 2)); - // The one before it, 0.0: dark above the bottom line. - assert!(!at(right - 1, top)); - assert!(!at(right - 1, top + GRAPH - 2)); - // No sample further left: dark. - assert!(!at(right - 5, top + GRAPH - 2)); - // The bottom line is dotted. - assert_ne!(at(RIM, top + GRAPH - 1), at(RIM + 1, top + GRAPH - 1)); - // Second graph, 0.5: dark at its top, lit near its bottom. - let second = top + GRAPH + GRAPH_GAP; - assert!(!at(right, second)); - assert!(at(right, second + GRAPH - 3)); - // The gap between graphs is dark. - assert!(!at(right, top + GRAPH)); - // The box holds the graphs. - let (_, height) = size(PANEL, 1); - assert_eq!(height, top + GRAPHS * (GRAPH + GRAPH_GAP) + RIM); - } - - /// CPU use in percent: the game's of all processors, the PC's of its - /// busy time. - #[test] - fn cpu_use_is_told_in_percent() { - // One second on 4 processors; the game used 2 s of CPU; the PC was - // idle 1 s of 4. - let (game, pc) = cpu_percent((0, 0, 0), (20_000_000, 10_000_000, 40_000_000), 1.0, 4.0); - assert!((game - 50.0).abs() < 1e-6); - assert!((pc - 75.0).abs() < 1e-6); - assert_eq!(cpu_percent((5, 5, 5), (5, 5, 5), 1.0, 4.0), (0.0, 0.0)); - } - - /// The PC's lines and the legend fit the box. - #[test] - fn the_pc_lines_fit() { - let pc = Pc { cpu_game: 100.0, cpu_pc: 100.0, free: 127 << 30, total: 128 << 30, commit_left: 199 << 30 }; - for line in pc_lines(pc).iter().map(String::as_str).chain([LEGEND]) { - assert!(line.len() <= COLUMNS as usize, "{line}"); - } - } - - #[test] - fn counters_that_went_back_to_nothing_count_from_there() { - let (mut a, mut b) = (Counters::default(), Counters::default()); - (a.0[0], b.0[0]) = (10, 30); - (a.0[1], b.0[1]) = (50, 20); - let c = b.since(a, 10.0); - assert_eq!((c[0], c[1]), (2.0, 2.0)); - } - - #[test] - fn the_advisor_names_what_limits_the_frame_rate() { - let base = Sample { - fps: 20.0, - ms: 50.0, - gpu_ms: 46.0, - wait_ms: 1.0, - budget: 10.0, - vram: 6.0, - rays: true, - dlss: Some("quality"), - ..Sample::default() - }; - let lines = advice(&base); - assert!(lines[1].starts_with("LIMIT: YOUR GPU"), "{lines:?}"); - assert!(lines[2].contains("TURN OFF RAY TRACING"), "{lines:?}"); - let cpu = advice(&Sample { gpu_ms: 20.0, ..base }); - assert!(cpu[1].starts_with("LIMIT: YOUR CPU") && cpu[1].contains("WAITS 30"), "{cpu:?}"); - let busy = advice(&Sample { making: 40, dropped: 12.0, vram: 10.0, ..base }); - assert!(busy[1].starts_with("LIMIT: 40 SHADERS") && busy[3].starts_with("ALSO: YOUR GPU") && busy[5].starts_with("ALSO: VIDEO MEMORY"), "{busy:?}"); - assert_eq!(busy.len(), ADVICE_LINES); - let skipped = advice(&Sample { dropped: 47.0, ..base }); - assert!(skipped[3].starts_with("NOTE: 47 DRAWS SKIPPED"), "{skipped:?}"); - let capped = advice(&Sample { fps: 60.0, ms: 16.7, cap: 60.0, ..base }); - assert!(capped[1].contains("CAP"), "{capped:?}"); - let compiling = advice(&Sample { making: 247, gpu_ms: 39.0, ..base }); - assert!(compiling[1].starts_with("LIMIT: 247 SHADERS") && !compiling.iter().any(|l| l.contains("CPU")), "{compiling:?}"); - let first = FIRST_START.map(str::to_owned); - for line in lines.iter().chain(&cpu).chain(&busy).chain(&skipped).chain(&capped).chain(&compiling).chain(&first) { - assert!(line.len() <= ADVISOR.columns as usize, "{line}"); - assert!(line.bytes().all(|b| b == b' ' || glyph(b) != glyph(b'~')), "{line}"); - } - } -} +} \ No newline at end of file