From dcc6672aa65efb2c02fd5b04c03c993b8b0d797e Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:23 +0100 Subject: [PATCH 1/6] Port native Series X ultrawide output to Mandy Expose 3440x1440, 3840x1080 and 5120x1440 through the launchers and F1 menu. Keep render height independent of output and apply the retail HUD, memory and directional-shadow changes through the loader and presenter. Port the Victory changes through 6944be606 on 4ffd627ce. Use Foxhound PR readmet3xt-lab/foxhound#281 and its opt-in HUD follow-up cf95b5e3f as references for the PresentX adaptation. --- README.md | 1 + d3d12/Cargo.lock | 1 + d3d12/apps/leonida/Cargo.toml | 3 + d3d12/apps/leonida/src/heap_budget.rs | 465 ++++++++ d3d12/apps/leonida/src/main.rs | 10 + d3d12/apps/leonida/src/run.rs | 23 +- d3d12/apps/leonida/src/ultrawide.rs | 103 ++ d3d12/crates/leonida-gpu/src/aspect.rs | 21 +- d3d12/crates/leonida-gpu/src/compose.rs | 1011 +++++++++++++++-- d3d12/crates/leonida-gpu/src/draw.rs | 440 +++++++ d3d12/crates/leonida-gpu/src/host.rs | 94 +- d3d12/crates/leonida-gpu/src/host/menu.rs | 10 +- d3d12/crates/leonida-gpu/src/lib.rs | 6 + d3d12/crates/leonida-gpu/src/list.rs | 1 + d3d12/crates/leonida-gpu/src/queue.rs | 107 +- d3d12/crates/leonida-gpu/src/shader_cache.rs | 14 + d3d12/crates/leonida-gpu/src/texture.rs | 1 + d3d12/crates/leonida-gpu/src/world_marker.rs | 521 +++++++++ d3d12/crates/leonida-hle/src/lib.rs | 2 + d3d12/crates/leonida-hle/src/ultrawide.rs | 302 +++++ d3d12/crates/leonida-loader/src/callhook.rs | 194 ++++ d3d12/crates/leonida-loader/src/hooks.rs | 42 +- d3d12/crates/leonida-loader/src/lib.rs | 8 + .../leonida-loader/src/native_output.rs | 163 +++ d3d12/crates/leonida-loader/src/prepare.rs | 4 + d3d12/crates/leonida-loader/src/tls.rs | 2 +- d3d12/crates/leonida-loader/src/windows.rs | 4 +- d3d12/crates/leonida-shader/src/emit/mod.rs | 17 +- .../src/emit/wide_shadow_tiles.rs | 197 ++++ d3d12/scripts/play-nvidia.ps1 | 37 +- docs/design.md | 4 + docs/launcher.md | 3 +- docs/ultrawide.md | 26 + launcher/index.html | 15 +- scripts/play-d3d12.ps1 | 12 +- scripts/play-linux.sh | 29 +- tests/test_leonida_launcher.py | 10 + tests/test_win_launchers.py | 50 + tools/leonida_launcher.py | 32 +- 39 files changed, 3818 insertions(+), 167 deletions(-) create mode 100644 d3d12/apps/leonida/src/heap_budget.rs create mode 100644 d3d12/apps/leonida/src/ultrawide.rs create mode 100644 d3d12/crates/leonida-gpu/src/world_marker.rs create mode 100644 d3d12/crates/leonida-hle/src/ultrawide.rs create mode 100644 d3d12/crates/leonida-loader/src/callhook.rs create mode 100644 d3d12/crates/leonida-loader/src/native_output.rs create mode 100644 d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs diff --git a/README.md b/README.md index 0ab58ddfe1..ed62278dff 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ Useful switches of `scripts\play-d3d12.ps1` (the launcher's Settings page has th | `-MotionBlur` | the game's own motion blur (off by default: at this frame rate it smears in blocks on camera turns) | | `-FrameGen 2`…`6` with `-Dlss quality\|balanced\|performance\|ultra` | DLSS makes the output and frame generation shows 2 to 6 times the frames | | `-SeriesS` | the lighter Series S profile (720p rendered, DLSS to 1080p) | +| `-Ultrawide 3440x1440\|3840x1080\|5120x1440` | native Series X ultrawide, with `-HudPosition center\|edges` for the gameplay HUD ([details](docs/ultrawide.md)) | | `-RayTracing` | the game's real ray tracing: slower, shaders build for minutes the first time, not with frame generation | | `-NoPrecompile` | start at once, without translating the shaders first | | `-Capture` | F9 in the game saves that frame | diff --git a/d3d12/Cargo.lock b/d3d12/Cargo.lock index 31a2236608..b8aae9247d 100644 --- a/d3d12/Cargo.lock +++ b/d3d12/Cargo.lock @@ -282,6 +282,7 @@ dependencies = [ "leonida-shader", "memchr", "walkdir", + "windows-sys", ] [[package]] diff --git a/d3d12/apps/leonida/Cargo.toml b/d3d12/apps/leonida/Cargo.toml index 461e0c2494..a186c27b7a 100644 --- a/d3d12/apps/leonida/Cargo.toml +++ b/d3d12/apps/leonida/Cargo.toml @@ -23,6 +23,9 @@ memchr.workspace = true clap.workspace = true walkdir.workspace = true +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_System_SystemInformation"] } + [features] # NVIDIA DLSS for the title's upscale (LEONIDA_UPSCALE=dlss); needs LEONIDA_DLSS_SDK. dlss = ["leonida-gpu/dlss"] diff --git a/d3d12/apps/leonida/src/heap_budget.rs b/d3d12/apps/leonida/src/heap_budget.rs new file mode 100644 index 0000000000..127796b6bd --- /dev/null +++ b/d3d12/apps/leonida/src/heap_budget.rs @@ -0,0 +1,465 @@ +//! Wider Series X scenes exhaust the stock render-target heap and scene pool. +//! The pool array must grow with its unit count. + +use anyhow::{Context, Result, ensure}; +use leonida_loader::{NATIVE_OUTPUT_RETAIL_HASH as RETAIL_BUILD, PreparedImage}; + +fn same(bytes: &[u8], hash: &str) -> bool { + blake3::hash(bytes).to_hex().as_str() == hash +} + +const MIB: u64 = 1 << 20; +const RT_HEAP_ENV: &str = "LEONIDA_RT_HEAP_MB"; +const SCENE_POOL_ENV: &str = "LEONIDA_SCENE_POOL_MB"; + +/// The Series X's table: its total, then nine heap sizes. +const SERIES_X_TABLE: u32 = 0x0618_6250 + 0x50; +/// Heap 2's size in it. +const RT_HEAP: u32 = SERIES_X_TABLE + 8 + 2 * 8; +const STOCK_TOTAL: u64 = 13_312 << 20; +const STOCK_RT_HEAP: u64 = 2_199 << 20; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Preset { + rt_heap_mib: u64, + scene_pool_mib: u32, +} + +pub(super) fn ultrawide_preset(output: (u32, u32), scene: (u32, u32)) -> Option { + let pixels = u64::from(scene.0) * u64::from(scene.1); + if pixels <= 2560 * 1440 { + return None; + } + match output { + (3440, 1440) | (3840, 1080) => Some(Preset { + rt_heap_mib: 7200, + scene_pool_mib: 1600, + }), + (5120, 1440) => Some(Preset { + rt_heap_mib: 8000, + scene_pool_mib: 1600, + }), + _ => None, + } +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub(super) struct Budgets { + pub(super) rt_bytes: Option, + pub(super) scene_units: Option, + pub(super) automatic: bool, +} + +impl Budgets { + pub(super) fn requested(preset: Option) -> Result { + let rt = std::env::var_os(RT_HEAP_ENV); + let scene = std::env::var_os(SCENE_POOL_ENV); + Self::resolve(preset, rt.as_deref(), scene.as_deref()) + } + + fn resolve( + preset: Option, + rt: Option<&std::ffi::OsStr>, + scene: Option<&std::ffi::OsStr>, + ) -> Result { + Ok(Self { + rt_bytes: rt_heap_asked(rt, preset.map(|value| value.rt_heap_mib))?, + scene_units: scene_pool_asked(scene, preset.map(|value| value.scene_pool_mib))?, + automatic: preset.is_some() && (rt.is_none() || scene.is_none()), + }) + } + + pub(super) fn check_available_commit(&self, available: u64) -> Result<()> { + let extra_heap = self.rt_bytes.unwrap_or(STOCK_RT_HEAP) - STOCK_RT_HEAP; + let extra_pool = u64::from(self.scene_units.unwrap_or(STOCK_UNITS) - STOCK_UNITS) << 16; + let minimum = STOCK_TOTAL + extra_heap + extra_pool; + ensure!( + !self.automatic || available >= minimum, + "automatic ultrawide budgets need at least {} MiB of available Windows commit, with {} MiB available. Pick an upscaling mode such as DLSS Quality or increase the Windows page file", + minimum.div_ceil(MIB), + available / MIB, + ); + Ok(()) + } +} + +#[cfg(windows)] +pub(super) fn available_commit() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + + let mut status = MEMORYSTATUSEX { + dwLength: size_of::() as u32, + ..Default::default() + }; + // SAFETY: Windows fills the initialized, correctly sized status structure. + let found = unsafe { GlobalMemoryStatusEx(&mut status) } != 0; + found.then_some(status.ullAvailPageFile) +} + +fn asked_mib( + value: Option<&std::ffi::OsStr>, + default: Option, + env: &str, +) -> Result> { + match value { + Some(raw) => { + let text = raw + .to_str() + .with_context(|| format!("{env} must be a whole number in MiB"))?; + let mib = text + .trim() + .parse::() + .with_context(|| format!("{env} must be a whole number in MiB"))?; + Ok((mib != 0).then_some(mib)) + } + None => Ok(default), + } +} + +fn rt_heap_asked(value: Option<&std::ffi::OsStr>, default: Option) -> Result> { + let Some(mib) = asked_mib(value, default, RT_HEAP_ENV)? else { + return Ok(None); + }; + ensure!( + ((STOCK_RT_HEAP / MIB + 1)..=24 * 1024).contains(&mib), + "{RT_HEAP_ENV} must be 0 or 2200 to 24576 MiB" + ); + Ok(Some(mib * MIB)) +} + +/// Patches `image`: heap 2 is `bytes` long and the total grows by as much. +pub(super) fn prepare_rt_heap(image: &mut PreparedImage, bytes: u64) -> Result<()> { + ensure!( + image.original_hash.to_hex().as_str() == RETAIL_BUILD, + "the render-target heap is only known for the retail build {RETAIL_BUILD}" + ); + let total = u64::from_le_bytes(*field::<8>(image, SERIES_X_TABLE)?); + let heap = u64::from_le_bytes(*field::<8>(image, RT_HEAP)?); + ensure!( + total == STOCK_TOTAL && heap == STOCK_RT_HEAP, + "the Series X heap table is not the stock one (total {total:#x}, heap 2 {heap:#x})" + ); + ensure!( + bytes > heap, + "the render-target heap asked for is not bigger than the stock one" + ); + *field::<8>(image, RT_HEAP)? = bytes.to_le_bytes(); + *field::<8>(image, SERIES_X_TABLE)? = (total + (bytes - heap)).to_le_bytes(); + Ok(()) +} + +/// The two loads of the pool's unit count (`mov eax, ; mov esi, +/// `, 10 bytes): the Series X count is its last four bytes. +const SCENE_POOL_UNITS: u32 = 0x01d4_88ac; +const STOCK_SCENE_POOL: &str = "24ee573f2d52472e3a964bcf583618cb9f02f00ec4d9d98735fdab6bd3034a88"; +const STOCK_UNITS: u32 = 0x2c60; + +fn scene_pool_asked(value: Option<&std::ffi::OsStr>, default: Option) -> Result> { + let Some(mib) = asked_mib(value, default.map(u64::from), SCENE_POOL_ENV)? else { + return Ok(None); + }; + ensure!( + (u64::from(STOCK_UNITS / 16 + 1)..=0xffff / 16).contains(&mib), + "{SCENE_POOL_ENV} must be 0 or 711 to 4095 MiB" + ); + Ok(Some(mib as u32 * 16)) +} + +/// Patches `image`: the Series X's scene pool is `units` of 64 KiB, and its +/// per-unit array lies in a section of its own, whose RVA is returned. +pub(super) fn prepare_scene_pool(image: &mut PreparedImage, units: u32) -> Result { + ensure!( + image.original_hash.to_hex().as_str() == RETAIL_BUILD, + "the scene pool is only known for the retail build {RETAIL_BUILD}" + ); + ensure!( + units > STOCK_UNITS && units <= 0xffff, + "the scene pool asked for is not bigger than the stock one" + ); + ensure!( + same(&field::<10>(image, SCENE_POOL_UNITS)?[..], STOCK_SCENE_POOL), + "unexpected scene pool unit counts" + ); + let array = relocate_unit_array(image, units)?; + field::<10>(image, SCENE_POOL_UNITS)?[6..10].copy_from_slice(&units.to_le_bytes()); + Ok(array) +} + +/// The only four places that take the per-unit array's address, each a +/// 7-byte `lea reg, [rip+disp]` (its RVA and the stock bytes' hash): the +/// pool's allocation and check (three) and its reservation, which fills the +/// array. Nothing else in the code addresses the array or inside it (every +/// RIP-relative displacement of `.text` into its range was looked at). +const UNIT_ARRAY_LEAS: [(u32, &str); 4] = [ + ( + 0x0247_3fa1, + "b7518a48bc0007deaa9966263959502315c9561f0fbc5ef8bb2623f6f104ab2a", + ), + ( + 0x0247_4079, + "16882fd85dc4b9c44488bb550045230deb00eadcb0221819e2a1b67b845321bb", + ), + ( + 0x0247_40ec, + "4a927d3bf20744b6f3eb7094de6a6ac4fb05b379da6857c8e201b614de915c4a", + ), + ( + 0x05eb_278d, + "91f9b4974217482cdbfa4505b428080afa2e8b1fb49d5e8b22983da0ef30bdf8", + ), +]; + +/// Points the four `lea`s at a new uninitialised section of `units` entries +/// and returns its RVA. Everything is checked before anything is written. +fn relocate_unit_array(image: &mut PreparedImage, units: u32) -> Result { + for &(rva, stock) in &UNIT_ARRAY_LEAS { + ensure!( + same(&field::<7>(image, rva)?[..], stock), + "the scene pool's array is not taken where the stock image takes it (+{rva:#x})" + ); + } + let section = add_section(image, b".vicpool", units as usize * 8 + 0x1000)?; + for &(rva, _) in &UNIT_ARRAY_LEAS { + let disp = i32::try_from(i64::from(section) - (i64::from(rva) + 7)) + .context("the new array is out of reach")?; + field::<7>(image, rva)?[3..7].copy_from_slice(&disp.to_le_bytes()); + } + Ok(section) +} + +/// Appends an uninitialised read-write section of at least `size` bytes +/// after the image's last one and returns its RVA. The Windows loader maps +/// it zeroed. Refused unless the headers have an empty slot for it and the +/// last section ends at the image's size. +fn add_section(image: &mut PreparedImage, name: &[u8; 8], size: usize) -> Result { + const UNINITIALISED_READ_WRITE: u32 = 0xc000_0080; + let b = &mut image.bytes; + let u16_at = |b: &[u8], o: usize| b.get(o..o + 2).map(|v| u16::from_le_bytes([v[0], v[1]])); + let u32_at = |b: &[u8], o: usize| { + b.get(o..o + 4) + .map(|v| u32::from_le_bytes([v[0], v[1], v[2], v[3]])) + }; + let short = "incomplete image headers"; + let pe = u32_at(b, 0x3c).context(short)? as usize; + ensure!( + b.get(pe..pe + 4) == Some(b"PE\0\0".as_slice()), + "no PE header" + ); + let file = pe + 4; + let count = usize::from(u16_at(b, file + 2).context(short)?); + let optional = file + 20; + ensure!(u16_at(b, optional) == Some(0x20b), "not a PE32+ image"); + let align = u32_at(b, optional + 32).context(short)?; + ensure!(align.is_power_of_two(), "unexpected section alignment"); + let size_of_image_at = optional + 56; + let headers = u32_at(b, optional + 60).context(short)? as usize; + let table = optional + usize::from(u16_at(b, file + 16).context(short)?); + let slot = table + count * 40; + ensure!( + slot + 40 <= headers && headers <= b.len(), + "no room in the headers for another section" + ); + ensure!( + b[slot..slot + 40].iter().all(|&x| x == 0), + "the next section header slot is not empty" + ); + // Each section's virtual address plus its virtual size. + let end = (0..count) + .filter_map(|i| u32_at(b, table + i * 40 + 12)?.checked_add(u32_at(b, table + i * 40 + 8)?)) + .max() + .context("no sections")?; + let rva = end + .checked_next_multiple_of(align) + .context("image too big")?; + ensure!( + Some(rva) == u32_at(b, size_of_image_at), + "the last section does not end at the image's size" + ); + let virtual_size = u32::try_from(size) + .ok() + .and_then(|s| s.checked_next_multiple_of(align)) + .context("section too big")?; + let new_size = rva.checked_add(virtual_size).context("image too big")?; + b[slot..slot + 8].copy_from_slice(name); + b[slot + 8..slot + 12].copy_from_slice(&virtual_size.to_le_bytes()); + b[slot + 12..slot + 16].copy_from_slice(&rva.to_le_bytes()); + // (No raw data: its size and pointer stay zero.) + b[slot + 36..slot + 40].copy_from_slice(&UNINITIALISED_READ_WRITE.to_le_bytes()); + b[file + 2..file + 4].copy_from_slice( + &u16::try_from(count + 1) + .context("too many sections")? + .to_le_bytes(), + ); + b[size_of_image_at..size_of_image_at + 4].copy_from_slice(&new_size.to_le_bytes()); + image.info.size_of_image = new_size; + Ok(rva) +} + +fn field(image: &mut PreparedImage, rva: u32) -> Result<&mut [u8; N]> { + let offset = image + .info + .rva_to_file_offset(rva) + .context("memory budget field missing")? as usize; + image + .bytes + .get_mut(offset..offset + N) + .context("incomplete memory budget field")? + .try_into() + .context("invalid memory budget field length") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ultrawide_budgets_follow_the_rendered_scene() { + let middle = Some(Preset { + rt_heap_mib: 7200, + scene_pool_mib: 1600, + }); + assert_eq!(ultrawide_preset((3440, 1440), (3440, 1440)), middle); + assert_eq!(ultrawide_preset((3840, 1080), (3840, 1080)), middle); + assert_eq!( + ultrawide_preset((5120, 1440), (5120, 1440)), + Some(Preset { + rt_heap_mib: 8000, + scene_pool_mib: 1600 + }), + ); + assert_eq!(ultrawide_preset((5120, 1440), (3413, 960)), None); + assert_eq!(ultrawide_preset((5120, 1440), (2560, 720)), None); + assert_eq!(ultrawide_preset((2560, 1440), (2560, 1440)), None); + assert_eq!(ultrawide_preset((3840, 2160), (3840, 2160)), None); + } + + #[test] + fn each_manual_budget_overrides_its_automatic_default() { + use std::ffi::OsStr; + let preset = ultrawide_preset((5120, 1440), (5120, 1440)); + assert_eq!( + Budgets::resolve(preset, Some(OsStr::new("8300")), None).unwrap(), + Budgets { + rt_bytes: Some(8300 * MIB), + scene_units: Some(1600 * 16), + automatic: true + }, + ); + assert_eq!( + Budgets::resolve(preset, None, Some(OsStr::new("0"))).unwrap(), + Budgets { + rt_bytes: Some(8000 * MIB), + scene_units: None, + automatic: true + }, + ); + assert_eq!( + Budgets::resolve(preset, Some(OsStr::new("0")), Some(OsStr::new("1700"))).unwrap(), + Budgets { + rt_bytes: None, + scene_units: Some(1700 * 16), + automatic: false + }, + ); + } + + #[test] + fn rejects_invalid_manual_budgets_before_disabling_an_automatic_preset() { + use std::ffi::OsStr; + let preset = ultrawide_preset((5120, 1440), (5120, 1440)); + for value in ["8GB", "2199", "24577", "18446744073709551615"] { + assert!(Budgets::resolve(preset, Some(OsStr::new(value)), None).is_err()); + } + for value in ["", "710", "4096"] { + assert!(Budgets::resolve(preset, None, Some(OsStr::new(value))).is_err()); + } + } + + #[test] + fn automatic_budgets_check_available_commit() { + use std::ffi::OsStr; + let preset = ultrawide_preset((5120, 1440), (5120, 1440)); + let automatic = Budgets::resolve(preset, None, None).unwrap(); + assert!(automatic.check_available_commit(20_002 * MIB).is_err()); + assert!(automatic.check_available_commit(20_003 * MIB).is_ok()); + let manual = + Budgets::resolve(preset, Some(OsStr::new("8000")), Some(OsStr::new("1600"))).unwrap(); + assert!(manual.check_available_commit(20_002 * MIB).is_ok()); + } + + fn retail() -> Option> { + Some(std::fs::read(std::env::var_os("LEONIDA_DISPLAY_PROFILE_TEST_IMAGE")?).unwrap()) + } + + /// With the retail executable named by `LEONIDA_DISPLAY_PROFILE_TEST_IMAGE` + /// (not part of the repository): heap 2 and the total grow by the same + /// amount, and a patched image is refused; without it, nothing is checked. + #[test] + fn grows_the_render_target_heap() { + let Some(bytes) = retail() else { return }; + let mut image = leonida_loader::prepare(&bytes).unwrap(); + prepare_rt_heap(&mut image, 8_000 << 20).unwrap(); + assert_eq!( + u64::from_le_bytes(*field::<8>(&mut image, RT_HEAP).unwrap()), + 8_000 << 20 + ); + assert_eq!( + u64::from_le_bytes(*field::<8>(&mut image, SERIES_X_TABLE).unwrap()), + STOCK_TOTAL + (8_000 << 20) - STOCK_RT_HEAP + ); + // The other eight heaps are as they were. + let fresh = leonida_loader::prepare(&bytes).unwrap(); + let (mut fresh, mut patched) = (fresh, image); + for heap in (0..9).filter(|&h| h != 2) { + let at = SERIES_X_TABLE + 8 + heap * 8; + assert_eq!( + field::<8>(&mut fresh, at).unwrap(), + field::<8>(&mut patched, at).unwrap() + ); + } + assert!(prepare_rt_heap(&mut patched, 9_000 << 20).is_err()); + } + + /// With the retail executable (as above): the scene pool's count is the + /// one asked, the four `lea`s name the new section, which is the image's + /// last, zero-filled by the loader and big enough; the Series S count is + /// untouched. + #[test] + fn grows_the_scene_pool() { + let Some(bytes) = retail() else { return }; + let mut image = leonida_loader::prepare(&bytes).unwrap(); + let before = image.info.size_of_image; + let stock = *field::<10>(&mut image, SCENE_POOL_UNITS).unwrap(); + let units = 1_600 * 16; + assert_eq!(prepare_scene_pool(&mut image, units).unwrap(), before); + let now = *field::<10>(&mut image, SCENE_POOL_UNITS).unwrap(); + assert_eq!(now[..6], stock[..6]); + assert_eq!(now[6..], units.to_le_bytes()); + assert!(image.info.size_of_image >= before + units * 8); + for (rva, _) in UNIT_ARRAY_LEAS { + let lea = *field::<7>(&mut image, rva).unwrap(); + let disp = i32::from_le_bytes(lea[3..].try_into().unwrap()); + assert_eq!(rva.wrapping_add(7).wrapping_add_signed(disp), before); + } + // Patched once, the image is no longer the stock one: refused. + assert!(prepare_scene_pool(&mut image, units).is_err()); + } + + /// With the retail executable (as above): a section is added after the + /// image's last one, at the image's size rounded up to the section + /// alignment, and the next one after it. + #[test] + fn adds_sections_after_the_last() { + let Some(bytes) = retail() else { return }; + let mut image = leonida_loader::prepare(&bytes).unwrap(); + let before = image.info.size_of_image; + let rva = add_section(&mut image, b".victest", 0x2345).unwrap(); + assert_eq!(rva, before); + assert_eq!(image.info.size_of_image, before + 0x3000); + // The next one goes after it. + assert_eq!( + add_section(&mut image, b".victwo\0", 1).unwrap(), + before + 0x3000 + ); + } +} diff --git a/d3d12/apps/leonida/src/main.rs b/d3d12/apps/leonida/src/main.rs index 1cd6e79763..8be7779b5c 100644 --- a/d3d12/apps/leonida/src/main.rs +++ b/d3d12/apps/leonida/src/main.rs @@ -6,6 +6,10 @@ mod agility; mod census; mod inspect; +#[cfg(windows)] +mod heap_budget; +#[cfg(windows)] +mod ultrawide; mod leonida; #[cfg(all(windows, feature = "diagnostics"))] mod native_scan; @@ -196,6 +200,12 @@ fn main() -> Result<()> { return Ok(()); } let cli = Cli::parse(); + #[cfg(windows)] + if matches!(&cli.command, Command::Shaders { .. } | Command::Warm { .. } | Command::Translate { .. }) { + if let Some(profile) = ultrawide::Profile::requested()? { + profile.configure_shaders(); + } + } match cli.command { Command::Inspect { file, diff --git a/d3d12/apps/leonida/src/run.rs b/d3d12/apps/leonida/src/run.rs index 45f7e36389..c833e08127 100644 --- a/d3d12/apps/leonida/src/run.rs +++ b/d3d12/apps/leonida/src/run.rs @@ -54,14 +54,28 @@ pub fn run( leonida_hle::modules::lifecycle::wait_for_previous(); let cfg = leonida_core::Config::load()?; let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; - let prepared = leonida_loader::prepare(&original)?; + let mut prepared = leonida_loader::prepare(&original)?; let hash = prepared.original_hash.to_hex(); match leonida_game::identify(&hash) { Some(build) => println!("build {} ({hash})", build.label), None => println!("build unknown ({hash})"), } - let images = cfg.cache_subdir("images")?; + let native = super::ultrawide::Profile::requested()?; + let (images, wide_ui) = if let Some(profile) = native { + anyhow::ensure!(matches!(console, Console::SeriesX), "native ultrawide requires Series X"); + let layout = profile.prepare(&mut prepared, execute)?; + profile.configure_shaders(); + leonida_gpu::aspect::set_native_output(profile.output()); + let (width, height) = profile.output(); + println!("display Series X native ultrawide {width}x{height}"); + // Both the display and the heap patches contribute to the cached image bytes. + let variant = blake3::hash(&prepared.bytes).to_hex(); + let folder = cfg.cache_subdir(&format!("images/ultrawide-{}", &variant[..16]))?; + (folder, layout.map(|layout| (profile.output(), layout))) + } else { + (cfg.cache_subdir("images")?, None) + }; leonida_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = leonida_loader::load(&prepared, &images)?; // The program is mapped from the copy `load` wrote: the file's bytes @@ -72,6 +86,11 @@ pub fn run( drop(prepared); drop(original); leonida_hle::runtime::set_main_image(image.base()); + if execute && let Some((output, layout)) = wide_ui { + // SAFETY: the display profile has verified this build, and the title has not run. + unsafe { leonida_hle::ultrawide::install(image.base(), output, layout) } + .map_err(anyhow::Error::msg)?; + } // Where the Lua mods' memory scan looks (`LEONIDA_LUA=0`: nothing reads it). leonida_lua::set_image(image.base(), image.info().size_of_image as usize); leonida_hle::runtime::set_image_path(image.base(), exe); diff --git a/d3d12/apps/leonida/src/ultrawide.rs b/d3d12/apps/leonida/src/ultrawide.rs new file mode 100644 index 0000000000..e97f743edc --- /dev/null +++ b/d3d12/apps/leonida/src/ultrawide.rs @@ -0,0 +1,103 @@ +use anyhow::{Context, Result, bail}; +use leonida_loader::PreparedImage; + +use crate::heap_budget; + +pub(super) struct Profile { + output: (u32, u32), + scene: (u32, u32), + wide_hud: bool, +} + +impl Profile { + pub(super) fn requested() -> Result> { + let Some(value) = std::env::var_os("LEONIDA_NATIVE_ULTRAWIDE") else { + return Ok(None); + }; + let value = value + .to_str() + .context("LEONIDA_NATIVE_ULTRAWIDE must name an output preset")?; + let Some(output) = parse_output(value)? else { + return Ok(None); + }; + Ok(Some(Self { + output, + scene: maximum_scene(output, leonida_loader::render_scale_cap()), + wide_hud: std::env::var_os("LEONIDA_ULTRAWIDE_HUD").is_none_or(|value| value != "0"), + })) + } + + pub(super) fn configure_shaders(&self) { + if self.scene.0 > 4096 { + leonida_shader::emit::enable_wide_shadow_tiles(); + } + } + + pub(super) fn prepare( + &self, + image: &mut PreparedImage, + execute: bool, + ) -> Result> { + let layout = leonida_loader::prepare_native_output(image, self.output, self.wide_hud)?; + let budgets = heap_budget::Budgets::requested(heap_budget::ultrawide_preset( + self.output, + self.scene, + ))?; + if execute && let Some(available) = heap_budget::available_commit() { + budgets.check_available_commit(available)?; + } + if let Some(bytes) = budgets.rt_bytes { + heap_budget::prepare_rt_heap(image, bytes)?; + } + if let Some(units) = budgets.scene_units { + heap_budget::prepare_scene_pool(image, units)?; + } + Ok(layout) + } + + pub(super) fn output(&self) -> (u32, u32) { + self.output + } +} + +fn parse_output(value: &str) -> Result> { + match value.trim().to_ascii_lowercase().as_str() { + "" | "off" | "0" => Ok(None), + "3440x1440" => Ok(Some((3440, 1440))), + "3840x1080" => Ok(Some((3840, 1080))), + "5120x1440" => Ok(Some((5120, 1440))), + _ => bail!("LEONIDA_NATIVE_ULTRAWIDE wants off, 3440x1440, 3840x1080, or 5120x1440"), + } +} + +fn maximum_scene((width, height): (u32, u32), scale: f32) -> (u32, u32) { + let scaled = |size| (size as f32 * scale).ceil() as u32; + (scaled(width), scaled(height)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_ultrawide_only_accepts_supported_series_x_presets() { + assert_eq!(parse_output("off").unwrap(), None); + assert_eq!(parse_output("3440x1440").unwrap(), Some((3440, 1440))); + assert_eq!(parse_output("3840X1080").unwrap(), Some((3840, 1080))); + assert_eq!(parse_output("5120x1440").unwrap(), Some((5120, 1440))); + assert!(parse_output("7680x2160").is_err()); + } + + #[test] + fn native_ultrawide_memory_and_shadows_follow_the_maximum_scene() { + let output = (5120, 1440); + let native = maximum_scene(output, 1.0); + let quality = maximum_scene(output, 2.0 / 3.0); + assert_eq!(native, output); + assert_eq!(quality, (3414, 960)); + assert!(native.0 > 4096); + assert!(quality.0 <= 4096); + assert!(heap_budget::ultrawide_preset(output, native).is_some()); + assert!(heap_budget::ultrawide_preset(output, quality).is_none()); + } +} diff --git a/d3d12/crates/leonida-gpu/src/aspect.rs b/d3d12/crates/leonida-gpu/src/aspect.rs index 6b3d4a064d..60dbbaeb09 100644 --- a/d3d12/crates/leonida-gpu/src/aspect.rs +++ b/d3d12/crates/leonida-gpu/src/aspect.rs @@ -17,6 +17,13 @@ use std::sync::atomic::{AtomicU8, Ordering}; +static NATIVE_OUTPUT: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + +/// Keeps the top-level window in the native output's shape by default. +pub fn set_native_output(output: (u32, u32)) { + let _ = NATIVE_OUTPUT.set(output); +} + /// What `LEONIDA_ASPECT` can say. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Asked { @@ -59,12 +66,14 @@ pub fn resolve(asked: Option, screen: Option<(u32, u32)>) -> Option pub fn asked() -> Option { static ASKED: std::sync::OnceLock> = std::sync::OnceLock::new(); *ASKED.get_or_init(|| { - let text = std::env::var("LEONIDA_ASPECT").ok()?; - let asked = parse(&text); - if asked.is_none() && !matches!(text.trim().to_ascii_lowercase().as_str(), "" | "off" | "none") { - tracing::warn!(text, "LEONIDA_ASPECT wants 21:9, 32:9, W:H, a number from 1 to 4, or auto; ignored"); - } - resolve(asked, screen()) + let shape = std::env::var("LEONIDA_ASPECT").ok().and_then(|text| { + let asked = parse(&text); + if asked.is_none() && !matches!(text.trim().to_ascii_lowercase().as_str(), "" | "off" | "none") { + tracing::warn!(text, "LEONIDA_ASPECT wants 21:9, 32:9, W:H, a number from 1 to 4, or auto; ignored"); + } + resolve(asked, screen()) + }); + shape.or_else(|| NATIVE_OUTPUT.get().map(|&(w, h)| f64::from(w) / f64::from(h))) }) } diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 0884e6751c..00ab86f53a 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs @@ -1,6 +1,8 @@ -//! Two presented planes as one image: the console's display puts the second +//! Two presented planes as one image: the console's display puts the second //! (the interface) over the first (the scene), each scaled to the screen. -//! Grand Theft Auto VI presents so on Series S. +//! The game presents so on Series S. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; @@ -10,32 +12,212 @@ use windows::core::{PCSTR, s}; use crate::host::Host; -const SOURCE: &str = r#" -#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" -Texture2D scene : register(t0); -Texture2D over : register(t1); -SamplerState smooth_ : register(s0); -struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; -[RootSignature(RS)] -V vs(uint id : SV_VertexID) { - V v; - v.uv = float2((id << 1) & 2, id & 2); - v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1); - return v; +pub(crate) fn center_series_x_ui() -> bool { + crate::world_marker::canvas_size().0 > 3840 +} + +/// Where a plane is shown: its source rectangle (pixels of its texture, +/// left, top, right, bottom; `None`: all of it) and its place on the screen +/// (fractions of it, the same order; `None`: all of it), as +/// `pSrcViewRects` and `pDestPlacementBase` give them. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Placement { + pub source: Option<[i32; 4]>, + pub dest: Option<[f32; 4]>, +} + +impl Placement { + pub const WHOLE: Placement = Placement { + source: None, + dest: None, + }; + + /// The texture shown whole over the whole screen. + pub(crate) fn is_whole(&self, width: u64, height: u32) -> bool { + self.uv(width, height) == [0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0] + } + + pub(crate) fn center_startup_ui(self, output: (u64, u32)) -> Self { + Self { + dest: Self::WHOLE.center_legacy_ui((3840, 2160), output).dest, + ..self + } + } + + /// Keep the legacy interface canvas proportional when spanning a wider output. + pub(crate) fn center_legacy_ui(self, canvas: (u64, u32), output: (u64, u32)) -> Self { + let (width, height) = output; + let (canvas_width, canvas_height) = canvas; + if canvas_height == 0 + || canvas_width * 9 != u64::from(canvas_height) * 16 + || height == 0 + || width * 9 <= u64::from(height) * 16 + || !self.is_whole(canvas_width, canvas_height) + { + return self; + } + let band = (u64::from(height) * 16 + 4) / 9; + let left = (width - band) / 2; + let dest = [ + left as f32 / width as f32, + 0.0, + (left + band) as f32 / width as f32, + 1.0, + ]; + Self { + dest: Some(dest), + ..self + } + } + + /// The shader's constants: the source as texture coordinates, then the + /// place on the screen. + pub(crate) fn uv(&self, width: u64, height: u32) -> [f32; 8] { + let [w, h] = [width as f32, height as f32]; + let source = self.source.map_or([0.0, 0.0, 1.0, 1.0], |[l, t, r, b]| { + [l as f32 / w, t as f32 / h, r as f32 / w, b as f32 / h] + }); + let dest = self.dest.unwrap_or([0.0, 0.0, 1.0, 1.0]); + [ + source[0], source[1], source[2], source[3], dest[0], dest[1], dest[2], dest[3], + ] + } +} + +/// Root constants: scene and HUD placements, optional layer bits and shadow lift. +const CONSTANTS: u32 = 17; +const VIEWS: u32 = 5; +static HUD: std::sync::OnceLock HudState> = std::sync::OnceLock::new(); +static LOADING: std::sync::OnceLock bool> = std::sync::OnceLock::new(); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HudState { + Gameplay, + Pause, + OtherMenu, + Startup, +} + +pub fn set_gameplay_hud_probe(probe: fn() -> HudState) { + let _ = HUD.set(probe); +} + +pub fn set_loading_ui_probe(probe: fn() -> bool) { + let _ = LOADING.set(probe); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FrameUi { + Game, + Pause, + Menu, + Startup, + Loading, + Video, +} + +static MOVIE_UNTIL: AtomicU64 = AtomicU64::new(0); +static STARTUP: AtomicBool = AtomicBool::new(true); + +pub(crate) fn note_movie_upload() { + if crate::world_marker::enabled() { + let until = crate::queue::presented().saturating_add(4); + MOVIE_UNTIL.fetch_max(until, Ordering::Relaxed); + } +} + +pub(crate) fn movie_active(frame: u64) -> bool { + frame <= MOVIE_UNTIL.load(Ordering::Relaxed) +} + +impl FrameUi { + pub(crate) fn capture(video: bool) -> Self { + if !center_series_x_ui() { + return Self::Menu; + } + let hud = HUD.get().map_or(HudState::OtherMenu, |probe| probe()); + let startup = hud == HudState::Startup; + let ui = Self::classify(video && startup, Self::loading(), startup, || hud); + STARTUP.store(ui == Self::Startup, Ordering::Relaxed); + ui + } + + pub(crate) fn startup() -> bool { + STARTUP.load(Ordering::Relaxed) + } + + fn loading() -> bool { + LOADING.get().is_some_and(|probe| probe()) + } + + fn classify(video: bool, loading: bool, startup: bool, hud: impl FnOnce() -> HudState) -> Self { + if video { + Self::Video + } else if loading { + Self::Loading + } else if startup { + Self::Startup + } else { + match hud() { + HudState::Gameplay => Self::Game, + HudState::Pause => Self::Pause, + HudState::OtherMenu => Self::Menu, + HudState::Startup => Self::Startup, + } + } + } + + pub(crate) fn centers_wide_overlay(self) -> bool { + matches!(self, Self::Startup | Self::Video) + } +} + +#[derive(Clone, Copy)] +pub(crate) enum HudLayout { + Whole, + ToEdges, + FromEdges([f32; 2]), } -// Leonida: the scene sharpened before the interface goes over it (SHARPEN, 0 to 1, set when the pass is made from -// LEONIDA_SHARPEN). Contrast-adaptive, after the idea of AMD FidelityFX CAS (MIT): each pixel is pushed away from -// its four neighbours by an amount that shrinks where the neighbourhood already spans much of the range, so soft -// areas gain detail and hard edges get no halo; the result stays inside the neighbourhood's range. + +impl HudLayout { + pub(crate) fn for_present( + centered: bool, + wide: bool, + ui: FrameUi, + edges: bool, + output: (u64, u32), + ) -> Self { + if !(centered || wide) || !(ui == FrameUi::Game || (wide && ui == FrameUi::Pause)) { + return Self::Whole; + } + match (wide, edges) { + (true, false) => Placement::WHOLE + .center_legacy_ui((3840, 2160), output) + .dest + .map_or(Self::Whole, |[left, _, right, _]| { + Self::FromEdges([left, right]) + }), + (false, true) => Self::ToEdges, + _ => Self::Whole, + } + } + + pub(crate) fn uses_split(self) -> bool { + !matches!(self, Self::Whole) + } +} + +const COLOR: &str = r#" float3 at(float2 uv) { return scene.SampleLevel(smooth_, uv, 0).rgb; } -float3 sharpened(float2 uv) { - float3 g = at(uv); +float3 sharpened(float2 uv, float3 g, float4 bounds) { if (SHARPEN <= 0.0) return g; float w, h; scene.GetDimensions(w, h); float2 t = 1.0 / float2(w, h); - float3 l = at(uv - float2(t.x, 0)), r = at(uv + float2(t.x, 0)); - float3 u = at(uv - float2(0, t.y)), d = at(uv + float2(0, t.y)); + float3 l = at(clamp(uv - float2(t.x, 0), bounds.xy, bounds.zw)); + float3 r = at(clamp(uv + float2(t.x, 0), bounds.xy, bounds.zw)); + float3 u = at(clamp(uv - float2(0, t.y), bounds.xy, bounds.zw)); + float3 d = at(clamp(uv + float2(0, t.y), bounds.xy, bounds.zw)); float3 lo = min(g, min(min(l, r), min(u, d))); float3 hi = max(g, max(max(l, r), max(u, d))); float3 amp = sqrt(saturate(min(lo, 1.0 - hi) / max(hi, 1e-4))); @@ -43,11 +225,7 @@ float3 sharpened(float2 uv) { float3 c = (g + (l + r + u + d) * k) / (1.0 + 4.0 * k); return clamp(c, lo, hi); } -// A clamp to [0,1] that is safe for NaN and infinity (CLEAN, set when the pass is made from LEONIDA_COMPOSE_NAN): -// saturate() makes a NaN 0, which showed as black specks and a black sun where the upscaler or frame generation -// handed one over (sun glints on water). Here a NaN becomes 1, +infinity 1, a negative value and -infinity 0. The -// test is on the bits: the compiler may fold x != x or isnan() away. -// From aki-gta6/aki-runtime 33c21b9 (Aki-Developer), GPL-3.0. +// The bit test preserves NaN handling under compiler optimizations. float clean1(float x) { #if CLEAN return (asuint(x) & 0x7FFFFFFFu) > 0x7F800000u ? 1.0 : saturate(x); @@ -58,24 +236,218 @@ float clean1(float x) { float3 clean(float3 x) { return float3(clean1(x.r), clean1(x.g), clean1(x.b)); } +"#; + +const STOCK_SOURCE: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors=2), visibility=SHADER_VISIBILITY_PIXEL), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" +Texture2D scene : register(t0); +Texture2D over : register(t1); +SamplerState smooth_ : register(s0); +struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] +V vs(uint id : SV_VertexID) { + V v; + v.uv = float2((id << 1) & 2, id & 2); + v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1); + return v; +} +/* COLOR */ [RootSignature(RS)] float4 ps(V v) : SV_Target { - float3 s = sharpened(v.uv); + float3 s = sharpened(v.uv, at(v.uv), float4(0, 0, 1, 1)); float4 o = over.SampleLevel(smooth_, v.uv, 0); return float4(clean(o.rgb + s * (1 - clean1(o.a))), 1); } "#; -/// Whether the composer's clamp keeps a NaN from coming out black (`clean1` in [`SOURCE`]). On by default; -/// `LEONIDA_COMPOSE_NAN=0`: plain `saturate`, as before. +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=17, b0), DescriptorTable(SRV(t0, numDescriptors=4), UAV(u0)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" +Texture2D scene : register(t0); +Texture2D over : register(t1); +Texture2D markers : register(t2); +Buffer splits : register(t3); +RWBuffer found_splits : register(u0); +SamplerState smooth_ : register(s0); +cbuffer Planes : register(b0) { + float4 scene_source; float4 scene_place; + float4 over_source; float4 over_place; + uint layers; +}; +struct V { float4 at : SV_Position; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] +V vs(uint id : SV_VertexID) { + V v; + v.uv = float2((id << 1) & 2, id & 2); + v.at = float4(v.uv * float2(2, -2) + float2(-1, 1), 0, 1); + return v; +} +// A plane at screen position `uv`: its source rectangle stretched over its +// place, nothing (zero) outside that place. +/* COLOR */ +float4 plane(Texture2D t, float4 source, float4 place, float2 uv, bool sharpen_scene) { + float2 f = (uv - place.xy) / (place.zw - place.xy); + if (any(f < 0) || any(f > 1)) return 0; + float2 sample_uv = lerp(source.xy, source.zw, f); + float4 bounds = source; + if (any(source.xy != 0) || any(source.zw != 1)) { + // The sampler clamps at the texture edge. When a crop is enlarged, + // clamp at its outer texel centres so the filter stays inside it. + uint width, height; + t.GetDimensions(width, height); + float2 half_texel = 0.5 / float2(width, height); + bounds = float4(source.xy + half_texel, source.zw - half_texel); + sample_uv = clamp(sample_uv, bounds.xy, bounds.zw); + } + float4 color = t.SampleLevel(smooth_, sample_uv, 0); + if (sharpen_scene) color.rgb = sharpened(sample_uv, color.rgb, bounds); + return color; +} +groupshared uint covered[16]; +groupshared bool preserve_panel; +groupshared float4 background; + +void inspect_edges(uint width, uint height) { + background = 0; + preserve_panel = false; + if ((layers & 8) == 0 || height < 5) + return; + + float4 corner = over.Load(int3(0, 0, 0)); + bool uniform_fade = corner.a > 0 && corner.a < 1; + bool left_panel = true; + bool right_panel = true; + [unroll] + for (uint band = 0; band < 5; ++band) { + uint y = (height - 1) * (2 * band + 1) / 10; + float4 left = over.Load(int3(0, y, 0)); + float4 right = over.Load(int3(width - 1, y, 0)); + uniform_fade = uniform_fade && all(left == corner) && all(right == corner); + left_panel = left_panel && left.a != 0; + right_panel = right_panel && right.a != 0; + } + if (uniform_fade) + background = corner; + else + preserve_panel = left_panel || right_panel; +} + +bool clear_column_pixel(uint x, uint y) { + float4 pixel = over.Load(int3(x, y, 0)); + return background.a == 0 ? pixel.a == 0 : all(pixel == background); +} + +uint seam(uint i, uint width) { + const float candidates[8] = { 0.25, 0.28, 0.22, 0.31, 0.19, 0.35, 0.15, 0.10 }; + float span = (layers & 8) != 0 ? over_place.z - over_place.x : 1.0; + uint x = clamp((uint)round(candidates[i % 8] * span * width), 1u, width - 1); + return i < 8 ? x : width - x; +} + +// Adjacent background columns protect bilinear samples on both sides of a cut. +[RootSignature(RS)] +[numthreads(16, 8, 1)] +void find_splits(uint3 id : SV_GroupThreadID, uint index : SV_GroupIndex) { + uint width, height; + over.GetDimensions(width, height); + if (width < 4) { + if (index == 0) { found_splits[0] = 0; found_splits[1] = width; found_splits[2] = 0; } + return; + } + uint x = seam(id.x, width); + if (id.y == 0) covered[id.x] = 0; + if (index == 0) inspect_edges(width, height); + GroupMemoryBarrierWithGroupSync(); + if (index == 0) found_splits[2] = background.a != 0 ? 1 : 0; + if (preserve_panel) { + if (index == 0) { found_splits[0] = 0; found_splits[1] = width; } + return; + } + for (uint y = id.y; y < height; y += 8) { + if (!clear_column_pixel(x - 1, y) || !clear_column_pixel(x, y)) { + InterlockedOr(covered[id.x], 1); + break; + } + } + GroupMemoryBarrierWithGroupSync(); + if (index < 2) { + uint cut = index == 0 ? 0 : width; + for (uint i = index * 8; i < (index + 1) * 8; ++i) { + if (covered[i] == 0) { cut = seam(i, width); break; } + } + found_splits[index] = cut; + } +} + +float4 edge_hud(float2 uv) { + uint width, height; + over.GetDimensions(width, height); + float2 cut = float2(splits[0], splits[1]) / width; + float span = over_place.z - over_place.x; + float x = (uv.x - over_place.x) / span; + if (uv.x < cut.x * span) { + x = uv.x / span; + } else if (uv.x > 1 - (1 - cut.y) * span) { + x = 1 + (uv.x - 1) / span; + } else if (x < cut.x || x > cut.y) { + return 0; + } + return over.SampleLevel(smooth_, float2(x, uv.y), 0); +} + +float4 center_hud(float2 uv) { + uint width, height; + over.GetDimensions(width, height); + uint2 split = uint2(splits[0], splits[1]); + if (split.x == 0 && split.y == width) + return over.SampleLevel(smooth_, uv, 0); + + float2 cut = float2(split) / width; + float4 fade = splits[2] != 0 ? over.Load(int3(0, 0, 0)) : 0; + float fade_transmission = 1 - fade.a; + float4 hud = fade; + if (uv.x >= cut.x && uv.x <= cut.y) + hud = over.SampleLevel(smooth_, uv, 0); + float left = uv.x - over_place.x; + if (left >= 0 && left < cut.x) { + float4 group = over.SampleLevel(smooth_, float2(left, uv.y), 0); + // Both samples already contain the fade. Blend only the underlying HUD contribution. + hud = group + (hud - fade) * ((1 - saturate(group.a)) / fade_transmission); + } + float right = uv.x + 1 - over_place.z; + if (right > cut.y && right <= 1) { + float4 group = over.SampleLevel(smooth_, float2(right, uv.y), 0); + hud = group + (hud - fade) * ((1 - saturate(group.a)) / fade_transmission); + } + return hud; +} + +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + float4 s = plane(scene, scene_source, scene_place, v.uv, true); + if ((layers & 2) != 0) { + float4 m = markers.SampleLevel(smooth_, v.uv, 0); + s.rgb = m.rgb + s.rgb * (1 - saturate(m.a)); + } + float4 o = 0; + if ((layers & 8) != 0) o = center_hud(v.uv); + else if ((layers & 4) != 0) o = edge_hud(v.uv); + else if ((layers & 1) != 0) o = plane(over, over_source, over_place, v.uv, false); + return float4(clean(o.rgb + s.rgb * (1 - clean1(o.a))), 1); +} +"#; + fn clean() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LEONIDA_COMPOSE_NAN").is_none_or(|v| v != "0")) } /// [`SOURCE`] with its two settings in front. -fn source(sharpen: f32, clean: bool) -> String { - format!("#define SHARPEN {sharpen:.3}\n#define CLEAN {}\n{SOURCE}", u8::from(clean)) +fn source(shader: &str, sharpen: f32, clean: bool) -> String { + let body = shader.replace("/* COLOR */", COLOR); + format!( + "#define SHARPEN {sharpen:.3}\n#define CLEAN {}\n{body}", + u8::from(clean) + ) } /// Leonida: how much the scene is sharpened before the interface goes over it (`LEONIDA_SHARPEN`, 0 to 1; @@ -93,22 +465,127 @@ fn sharpen() -> f32 { } pub(crate) struct Composer { + wide: bool, root: ID3D12RootSignature, pso: ID3D12PipelineState, - views: Vec, + views: Vec, + edges: std::sync::OnceLock>, + step: u32, +} + +struct Slot { + views: ID3D12DescriptorHeap, + splits: std::sync::OnceLock>, +} + +fn edge_pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, +) -> windows::core::Result { + let blob = compile(SOURCE, s!("find_splits"), s!("cs_5_1"))?; + // SAFETY: the root and compiled shader are alive through pipeline creation. + unsafe { + device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: blob.GetBufferPointer(), + BytecodeLength: blob.GetBufferSize(), + }, + ..Default::default() + }) + } +} + +const EDGE_DATA_LEN: u32 = 3; + +fn edge_buffer(device: &ID3D12Device) -> windows::core::Result { + let mut buffer = None; + // SAFETY: the default-heap buffer holds two split coordinates and the fade flag. + unsafe { + device.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(EDGE_DATA_LEN) * size_of::() as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut buffer, + )?; + } + buffer.ok_or_else(|| windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)) +} + +fn edge_views( + device: &ID3D12Device, + heap: &ID3D12DescriptorHeap, step: u32, + splits: Option<&ID3D12Resource>, +) { + // SAFETY: the caller owns the idle descriptor heap slot. + unsafe { + let cpu = heap.GetCPUDescriptorHandleForHeapStart(); + let at = |i| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + i * step as usize, + }; + device.CreateShaderResourceView( + splits, + Some(&D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + NumElements: EDGE_DATA_LEN, + ..Default::default() + }, + }, + }), + at(3), + ); + device.CreateUnorderedAccessView( + splits, + None, + Some(&D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: EDGE_DATA_LEN, + ..Default::default() + }, + }, + }), + at(4), + ); + } } // SAFETY: D3D12 objects are free-threaded. unsafe impl Send for Composer {} // SAFETY: as above. unsafe impl Sync for Composer {} -fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result { - compile_source(&source(sharpen(), clean()), entry, target) +fn compile(shader: &str, entry: PCSTR, target: PCSTR) -> windows::core::Result { + compile_source(&source(shader, sharpen(), clean()), entry, target) } fn compile_source(source: &str, entry: PCSTR, target: PCSTR) -> windows::core::Result { let mut code: Option = None; + let mut errors: Option = None; // SAFETY: the source and names live through the call; the out pointer is // ours. unsafe { @@ -123,24 +600,37 @@ fn compile_source(source: &str, entry: PCSTR, target: PCSTR) -> windows::core::R 0, 0, &mut code, - None, - )?; + Some(&mut errors), + ).inspect_err(|_| { + if let Some(errors) = &errors { + let bytes = std::slice::from_raw_parts(errors.GetBufferPointer().cast::(), errors.GetBufferSize()); + tracing::warn!(message = %String::from_utf8_lossy(bytes), "display composer compilation failed"); + } + })?; } code.ok_or_else(windows::core::Error::empty) } impl Composer { pub(crate) fn new(host: &Host, format: DXGI_FORMAT) -> windows::core::Result { + Self::for_device(&host.device, format, center_series_x_ui()) + } + + fn for_device( + device: &ID3D12Device, + format: DXGI_FORMAT, + wide: bool, + ) -> windows::core::Result { + let source = if wide { SOURCE } else { STOCK_SOURCE }; let (vs, ps) = ( - compile(s!("vs"), s!("vs_5_1"))?, - compile(s!("ps"), s!("ps_5_1"))?, + compile(source, s!("vs"), s!("vs_5_1"))?, + compile(source, s!("ps"), s!("ps_5_1"))?, ); // SAFETY: the blobs' own bytes, alive through the calls. unsafe { let bytes = |b: &ID3DBlob| { std::slice::from_raw_parts(b.GetBufferPointer().cast::(), b.GetBufferSize()) }; - let device = &host.device; let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes(&vs))?; let code = |b: &ID3DBlob| D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), @@ -169,41 +659,91 @@ impl Composer { D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; let pso = device.CreateGraphicsPipelineState(&desc)?; Ok(Composer { + wide, root, pso, views: Vec::new(), + edges: std::sync::OnceLock::new(), step: device .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), }) } } - /// Draws the two planes over `width` x `height` of `back` from (`left`, `top`). - /// Each presenter command-list slot owns its own pair of SRVs. The swap - /// chain may have several outstanding presents; the slot is selected by - /// the completion fence, and its descriptors are only overwritten on reuse. + /// The completion fence protects each slot's descriptors from in-flight presents. + #[allow(clippy::too_many_arguments)] pub(crate) fn record( &mut self, host: &Host, slot: usize, list: &ID3D12GraphicsCommandList, - planes: [(&ID3D12Resource, DXGI_FORMAT); 2], + base: (&ID3D12Resource, DXGI_FORMAT, Placement), + overlay: Option<(&ID3D12Resource, DXGI_FORMAT, Placement)>, + markers: Option<&ID3D12Resource>, + hud_layout: HudLayout, back: &ID3D12Resource, ((left, top), (width, height)): ((u32, u32), (u32, u32)), ) -> windows::core::Result<()> { + let mut constants = [0u32; CONSTANTS as usize]; + let planes = [ + Some(base), + overlay, + markers.map(|r| (r, DXGI_FORMAT_R8G8B8A8_UNORM, Placement::WHOLE)), + ]; + if self.wide { + for (i, plane) in planes[..2].iter().enumerate() { + let Some((resource, _, placement)) = plane else { + continue; + }; + // SAFETY: a live resource. + let desc = unsafe { resource.GetDesc() }; + for (k, v) in placement + .uv(desc.Width, desc.Height) + .into_iter() + .enumerate() + { + constants[i * 8 + k] = v.to_bits(); + } + } + constants[16] = u32::from(overlay.is_some()) | (u32::from(markers.is_some()) << 1); + } + let plane_count = if self.wide { 3 } else { 2 }; while self.views.len() <= slot { let heap = unsafe { host.device .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: 2, + NumDescriptors: if self.wide { VIEWS } else { 2 }, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, })? }; - self.views.push(heap); + if self.wide { + edge_views(&host.device, &heap, self.step, None); + } + self.views.push(Slot { + views: heap, + splits: std::sync::OnceLock::new(), + }); } - let views = &self.views[slot]; + let slot = &self.views[slot]; + let views = &slot.views; + let edges = if self.wide && hud_layout.uses_split() && overlay.is_some() { + let pipeline = self.edges.get_or_init(|| edge_pipeline(&host.device, &self.root) + .inspect_err(|error| tracing::warn!(%error, "could not prepare screen-edge HUD placement")).ok()); + let splits = slot.splits.get_or_init(|| { + let buffer = edge_buffer(&host.device) + .inspect_err( + |error| tracing::warn!(%error, "could not allocate the HUD split buffer"), + ) + .ok()?; + edge_views(&host.device, views, self.step, Some(&buffer)); + Some(buffer) + }); + pipeline.as_ref().zip(splits.as_ref()) + } else { + None + }; // SAFETY: an open list; the views are made in slots no frame in flight // reads; live textures. unsafe { @@ -211,12 +751,15 @@ impl Composer { views.GetCPUDescriptorHandleForHeapStart(), views.GetGPUDescriptorHandleForHeapStart(), ); - for (i, plane) in planes.iter().enumerate() { + for (i, plane) in planes[..plane_count].iter().enumerate() { let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: cpu.ptr + (i * self.step as usize), }; + // Inactive layers bind null so all slots in the table are valid. + let (resource, format) = + plane.map_or((None, DXGI_FORMAT_R8G8B8A8_UNORM), |(r, f, _)| (Some(r), f)); let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: plane.1, + Format: format, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { @@ -227,18 +770,39 @@ impl Composer { }, }; host.device - .CreateShaderResourceView(Some(plane.0), Some(&desc), at); + .CreateShaderResourceView(resource, Some(&desc), at); } let rtv = host.rtv(Some(back), None); - list.OMSetRenderTargets(1, Some(&rtv), false, None); list.SetDescriptorHeaps(&[Some(views.clone())]); + if let Some((pipeline, splits)) = edges { + if let HudLayout::FromEdges([left, right]) = hud_layout { + constants[12] = left.to_bits(); + constants[14] = right.to_bits(); + constants[16] |= 8; + } else { + constants[16] |= 4; + } + list.SetComputeRootSignature(&self.root); + list.SetComputeRoot32BitConstants(0, CONSTANTS, constants.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.SetPipelineState(pipeline); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[crate::host::transition( + splits, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )]); + } + list.OMSetRenderTargets(1, Some(&rtv), false, None); list.SetGraphicsRootSignature(&self.root); list.SetPipelineState(&self.pso); - list.SetGraphicsRootDescriptorTable(0, gpu); + if self.wide { + list.SetGraphicsRoot32BitConstants(0, CONSTANTS, constants.as_ptr().cast(), 0); + } + list.SetGraphicsRootDescriptorTable(u32::from(self.wide), gpu); list.IASetPrimitiveTopology( windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ); - // Leonida: the picture's place in `back`, which is larger when bars go around it (`crate::aspect`). list.RSSetViewports(&[D3D12_VIEWPORT { TopLeftX: left as f32, TopLeftY: top as f32, @@ -254,6 +818,13 @@ impl Composer { bottom: (top + height) as i32, }]); list.DrawInstanced(3, 1, 0, 0); + if let Some((_, splits)) = edges { + list.ResourceBarrier(&[crate::host::transition( + splits, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } } Ok(()) } @@ -279,33 +850,125 @@ pub(crate) fn view(d: &D3D12_RESOURCE_DESC) -> Option { } } -/// No card needed: the compiler alone. -#[cfg(test)] -mod source_tests { +#[cfg(all(test, feature = "diagnostics"))] +mod tests { use super::*; - /// The pixel program compiles with the NaN-safe clamp and without it, sharpened or not, and the two clamps - /// are different code (the bit test is not folded away). + fn texture(host: &Host, width: u64, height: u32) -> ID3D12Resource { + let mut resource = None; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: width, + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut resource, + ) + .unwrap() + }; + resource.unwrap() + } + #[test] - fn the_composer_compiles_with_and_without_the_nan_clamp() { - let bytes = |source: &str| { - let blob = compile_source(source, s!("ps"), s!("ps_5_1")).expect("the composer's pixel program compiles"); - // SAFETY: the blob's own bytes, copied while it lives. - unsafe { std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()).to_vec() } + fn centers_edge_hud_without_moving_the_middle_on_gpu() { + let Some(host) = crate::host::host() else { + eprintln!("skipping display-plane readback: no D3D12 device"); + return; }; - for sharpen in [0.0, 0.6] { - let (with, without) = (bytes(&source(sharpen, true)), bytes(&source(sharpen, false))); - assert_ne!(with, without, "the clamp changed nothing at sharpen {sharpen}"); + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut compositor = Composer::for_device(&host.device, format, true).unwrap(); + let base = texture(host, 16, 8); + let overlay = texture(host, 16, 8); + let output = texture(host, 16, 8); + let list = host.new_list().unwrap(); + let cmds = &list.list; + let target = D3D12_RESOURCE_STATE_RENDER_TARGET; + let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + // SAFETY: all resources and their views remain live through readback. + unsafe { + cmds.ClearRenderTargetView(host.rtv(Some(&base), None), &[0., 0., 0., 1.], None); + let overlay_rtv = host.rtv(Some(&overlay), None); + cmds.ClearRenderTargetView(overlay_rtv, &[0.; 4], None); + for (x, color) in [ + (0, [1., 0., 0., 1.]), + (7, [0., 0., 1., 1.]), + (15, [0., 1., 0., 1.]), + ] { + let rect = windows::Win32::Foundation::RECT { + left: x, + right: x + 1, + top: 0, + bottom: 1, + }; + cmds.ClearRenderTargetView(overlay_rtv, &color, Some(&[rect])); + } + cmds.ResourceBarrier(&[ + crate::host::transition(&base, target, read), + crate::host::transition( + &overlay, + target, + read | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + ), + ]); + compositor + .record( + host, + 0, + cmds, + (&base, format, Placement::WHOLE), + Some((&overlay, format, Placement::WHOLE)), + None, + HudLayout::FromEdges([0.25, 0.75]), + &output, + ((0, 0), (16, 8)), + ) + .unwrap(); + cmds.ResourceBarrier(&[crate::host::transition( + &output, + target, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let (buffer, footprint) = + crate::capture::read_back(&host.device, cmds, &output).unwrap(); + list.close(); + host.execute(&[&list]); + host.device.GetDeviceRemovedReason().unwrap(); + let mut mapped = std::ptr::null_mut(); + buffer.Map(0, None, Some(&mut mapped)).unwrap(); + let row = + std::slice::from_raw_parts(mapped.cast::().add(footprint.Offset as usize), 64) + .to_vec(); + buffer.Unmap(0, None); + for (x, expected) in [ + (0, [0, 0, 0, 255]), + (4, [255, 0, 0, 255]), + (7, [0, 0, 255, 255]), + (11, [0, 255, 0, 255]), + (15, [0, 0, 0, 255]), + ] { + assert_eq!(&row[x * 4..x * 4 + 4], &expected, "pixel {x} in {row:?}"); + } } - compile_source(&source(0.6, true), s!("vs"), s!("vs_5_1")).expect("the vertex program compiles"); - assert!(source(0.25, true).starts_with("#define SHARPEN 0.250\n#define CLEAN 1\n")); - assert!(source(0.0, false).contains("#define CLEAN 0\n")); } -} - -#[cfg(all(test, feature = "diagnostics"))] -mod tests { - use super::*; #[test] fn composes_scaled_premultiplied_plane_on_gpu() { @@ -316,44 +979,11 @@ mod tests { let format = DXGI_FORMAT_R8G8B8A8_UNORM; let mut compositor = Composer::new(host, format).unwrap(); let list = host.new_list().unwrap(); - let texture = |width: u64| -> ID3D12Resource { - let mut resource = None; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: width, - Height: 1, - DepthOrArraySize: 1, - MipLevels: 1, - Format: format, - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, - ..Default::default() - }; - unsafe { - host.device - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }, - D3D12_HEAP_FLAG_NONE, - &desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, - None, - &mut resource, - ) - .unwrap() - }; - resource.unwrap() - }; // A half-red base at one resolution. The overlay at output resolution // contains transparent, half-opaque green and fully opaque blue pixels. - let base = texture(1); - let overlay = texture(3); - let output = texture(3); + let base = texture(host, 1, 1); + let overlay = texture(host, 3, 1); + let output = texture(host, 3, 1); let target = D3D12_RESOURCE_STATE_RENDER_TARGET; let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; let cmds = &list.list; @@ -383,7 +1013,10 @@ mod tests { host, 0, cmds, - [(&base, format), (&overlay, format)], + (&base, format, Placement::WHOLE), + Some((&overlay, format, Placement::WHOLE)), + None, + HudLayout::Whole, &output, ((0, 0), (3, 1)), ) @@ -416,3 +1049,157 @@ mod tests { } } } + +#[cfg(test)] +mod placement_tests { + use super::{FrameUi, HudLayout, HudState, Placement}; + + #[test] + fn placements_are_texture_coordinates_and_screen_fractions() { + assert!(Placement::WHOLE.is_whole(1920, 1080)); + // A source rectangle that is the whole texture is whole too. + let all = Placement { + source: Some([0, 0, 1920, 1080]), + dest: Some([0.0, 0.0, 1.0, 1.0]), + }; + assert!(all.is_whole(1920, 1080)); + // A dynamic resolution's 1280x720 of a 1920x1080 texture. + let part = Placement { + source: Some([0, 0, 1280, 720]), + dest: None, + }; + assert!(!part.is_whole(1920, 1080)); + let uv = part.uv(1920, 1080); + assert!( + (uv[2] - 2.0 / 3.0).abs() < 1e-6 && (uv[3] - 2.0 / 3.0).abs() < 1e-6, + "{uv:?}" + ); + assert_eq!(&uv[4..], &[0.0, 0.0, 1.0, 1.0]); + let placed = Placement { + source: None, + dest: Some([0.25, 0.0, 0.75, 1.0]), + }; + assert_eq!(placed.uv(8, 8), [0.0, 0.0, 1.0, 1.0, 0.25, 0.0, 0.75, 1.0]); + } + + #[test] + fn startup_overlays_use_the_entire_16_by_9_picture_on_ultrawide() { + for (width, output_width) in [(5160, 3440), (7680, 5120)] { + let source = [0, 0, width, 2160]; + let layer = Placement { + source: Some(source), + dest: None, + } + .center_startup_ui((output_width, 1440)); + let [left, top, right, bottom] = layer.dest.unwrap(); + assert_eq!(layer.source, Some(source)); + assert!(((right - left) * output_width as f32 - 2560.0).abs() < 0.001); + assert_eq!((top, bottom), (0.0, 1.0)); + } + } + + #[test] + fn startup_and_reload_keep_the_loading_movies_own_viewport() { + for startup in [false, true] { + let loading = FrameUi::classify(false, true, startup, || unreachable!()); + assert_eq!(loading, FrameUi::Loading); + assert!(!loading.centers_wide_overlay()); + } + assert!(FrameUi::classify(false, false, true, || unreachable!()).centers_wide_overlay()); + assert!(FrameUi::classify(true, true, false, || unreachable!()).centers_wide_overlay()); + } + + #[test] + fn a_queued_present_uses_the_captured_gameplay_state() { + let output = (5120, 1440); + let hud = std::cell::Cell::new(HudState::OtherMenu); + let menu = FrameUi::classify(false, false, false, || hud.get()); + hud.set(HudState::Gameplay); + let gameplay = FrameUi::classify(false, false, false, || hud.get()); + hud.set(HudState::Pause); + let pause = FrameUi::classify(false, false, false, || hud.get()); + assert!(!HudLayout::for_present(false, true, menu, false, output).uses_split()); + assert!(matches!( + HudLayout::for_present(false, true, gameplay, false, output), + HudLayout::FromEdges(_) + )); + assert!(matches!( + HudLayout::for_present(false, true, pause, false, output), + HudLayout::FromEdges(_) + )); + assert!(!HudLayout::for_present(false, true, pause, true, output).uses_split()); + assert!(!HudLayout::for_present(true, false, pause, true, output).uses_split()); + } + + #[test] + fn legacy_ui_preserves_its_aspect_on_wide_outputs() { + let ui = Placement { + source: Some([0, 0, 3840, 2160]), + dest: Some([0.0, 0.0, 1.0, 1.0]), + }; + let canvas = (3840, 2160); + for (output, band) in [ + ((5120, 1440), [0.25, 0.0, 0.75, 1.0]), + ((3840, 1080), [0.25, 0.0, 0.75, 1.0]), + ((3440, 1440), [440.0 / 3440.0, 0.0, 3000.0 / 3440.0, 1.0]), + ] { + let placed = ui.center_legacy_ui(canvas, output); + assert_eq!(placed.dest, Some(band)); + assert_eq!(placed.source, ui.source); + } + assert_eq!(ui.center_legacy_ui(canvas, (2560, 1440)), ui); + assert_eq!( + Placement::WHOLE.center_legacy_ui((5120, 1440), (5120, 1440)), + Placement::WHOLE + ); + let positioned = Placement { + dest: Some([0.25, 0.0, 0.75, 1.0]), + ..ui + }; + assert_eq!( + positioned.center_legacy_ui(canvas, (5120, 1440)), + positioned + ); + } +} + +/// No card needed: the compiler alone. +#[cfg(test)] +mod source_tests { + use super::*; + + /// The pixel program compiles with the NaN-safe clamp and without it, sharpened or not, and the two clamps + /// are different code (the bit test is not folded away). + #[test] + fn the_composer_compiles_with_and_without_the_nan_clamp() { + let bytes = |source: &str| { + let blob = compile_source(source, s!("ps"), s!("ps_5_1")) + .expect("the composer's pixel program compiles"); + // SAFETY: the blob's own bytes, copied while it lives. + unsafe { + std::slice::from_raw_parts( + blob.GetBufferPointer().cast::(), + blob.GetBufferSize(), + ) + .to_vec() + } + }; + for sharpen in [0.0, 0.6] { + let (with, without) = ( + bytes(&source(STOCK_SOURCE, sharpen, true)), + bytes(&source(STOCK_SOURCE, sharpen, false)), + ); + assert_ne!( + with, without, + "the clamp changed nothing at sharpen {sharpen}" + ); + } + compile_source(&source(STOCK_SOURCE, 0.6, true), s!("vs"), s!("vs_5_1")) + .expect("the vertex program compiles"); + assert!( + source(STOCK_SOURCE, 0.25, true) + .starts_with("#define SHARPEN 0.250\n#define CLEAN 1\n") + ); + assert!(source(STOCK_SOURCE, 0.0, false).contains("#define CLEAN 0\n")); + } +} diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index ff6ad22280..6728d48774 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -1114,6 +1114,7 @@ pub(crate) struct State { index: IndexView, /// Bound render target and depth resources, for their host states. targets: Vec, + target_bounds: Option<(i32, i32)>, depth: usize, /// The host state the bound depth view needs ([`depth_state`]). depth_state: u32, @@ -1136,6 +1137,9 @@ pub(crate) struct State { /// a null view) and what its descriptor says. host_targets: Option<(Vec, Option)>, viewports: Vec, + marker_label: Option, + projected_prompt: Option<(usize, crate::world_marker::ProjectedPrompt)>, + dialog_band: Option<(usize, f32)>, scissors: Vec, blend: Option<[f32; 4]>, stencil: Option, @@ -2629,6 +2633,7 @@ impl State { self.depth_handle = depth; self.targets_set = true; self.targets.clear(); + self.target_bounds = None; let mut views = Vec::with_capacity(handles.len()); let mut keys = Vec::with_capacity(handles.len()); // The title resource of each view in `views` (0: none), for frame generation below. @@ -2665,6 +2670,13 @@ impl State { views.push((Some(texture), record.desc())); keys.push((texture.as_raw() as usize, record.key())); } + if crate::compose::center_series_x_ui() + && let [(Some(texture), _)] = views.as_slice() + { + // SAFETY: the render target belongs to an active title descriptor. + let desc = unsafe { texture.GetDesc() }; + self.target_bounds = Some((desc.Width as i32, desc.Height as i32)); + } self.depth = 0; self.depth_state = DEPTH_WRITE; let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { @@ -6065,6 +6077,7 @@ impl State { first_instance: u32, ) { self.window = None; + self.projected_prompt = None; #[cfg(feature = "diagnostics")] self.trace("draw", vertices, first); if crate::fg::hudless_wanted() { @@ -6192,6 +6205,264 @@ impl State { true } + fn bind_world_markers( + &self, + list: &HostList, + ) -> Option<( + D3D12_CPU_DESCRIPTOR_HANDLE, + Option, + )> { + let host = crate::host::host()?; + let &[handle] = self.target_handles.as_slice() else { + return None; + }; + let record = crate::descriptor::rtv_record(handle)?; + let overlay = crate::resource::host_resource(record.resource)?; + let markers = crate::world_marker::target(host, list, overlay)?; + let original = host.rtv(Some(overlay), record.desc().as_ref()); + let marker_rtv = host.rtv(Some(&markers), record.desc().as_ref()); + let depth = crate::descriptor::dsv_record(self.depth_handle).and_then(|d| { + let resource = crate::resource::host_resource(d.resource)?; + Some(host.dsv(resource, d.depth_desc().as_ref())) + }); + // SAFETY: the layer has the overlay's dimensions and compatible RTV format. + unsafe { + list.list.OMSetRenderTargets( + 1, + Some(&marker_rtv), + false, + depth.as_ref().map(std::ptr::from_ref), + ) + }; + Some((original, depth)) + } + + fn world_marker_viewport( + &self, + pipeline: &HostPipeline, + previous: Option, + ) -> Option<(D3D12_VIEWPORT, Option)> { + let [viewport] = self.viewports.as_slice() else { + return None; + }; + let shaders = pipeline + .stages + .iter() + .map(|stage| stage.shader.hash.as_str()); + let (table_offset, bytes, label_binding) = crate::world_marker::anchor_constant(shaders)?; + let Root::Table(table) = self.roots_ref(false).first()? else { + return None; + }; + let View::Constant(address, size) = + crate::descriptor::view(table.checked_add(table_offset)?)? + else { + return None; + }; + if size != bytes { + return None; + } + // Word 11 is the clip-space x of the affine transform's origin. + let mut anchor = [0u8; 4]; + if !crate::host::read_into(address.checked_add(11 * 4)? as *const u8, &mut anchor) { + return None; + } + let x = f32::from_le_bytes(anchor); + let label = label_binding.and_then(|(offset, starts_label)| { + if !starts_label && previous.is_none() { + return None; + } + let View::Constant(address, 32) = crate::descriptor::view(table.checked_add(offset)?)? + else { + return None; + }; + let mut depth = [0; 32]; + if !crate::host::read_into(address as *const u8, &mut depth) { + return None; + } + if starts_label { + Some(crate::world_marker::LabelAnchor::for_batch( + previous, depth, x, + )) + } else { + crate::world_marker::LabelAnchor::matching(previous, &depth) + } + }); + let x = label.map_or(x, |label| label.x); + Some((crate::world_marker::fit_sprite(*viewport, x)?, label)) + } + + fn projected_prompt_viewport( + &mut self, + pipeline: &HostPipeline, + previous: Option<(usize, crate::world_marker::ProjectedPrompt)>, + ) -> Option { + let [viewport] = self.viewports.as_slice() else { + return None; + }; + let &[target] = self.targets.as_slice() else { + return None; + }; + let (batch, offset, bytes) = crate::world_marker::PromptBatch::binding(pipeline)?; + let origin = self.prompt_origin(offset, bytes)?; + let previous = previous + .filter(|&(surface, _)| surface == target) + .map(|(_, state)| state); + let (prompt, anchor) = crate::world_marker::ProjectedPrompt::advance( + previous, + batch, + origin, + crate::world_marker::canvas_size(), + )?; + self.projected_prompt = Some((target, prompt)); + crate::world_marker::fit_sprite(*viewport, anchor?) + } + + fn prompt_origin(&self, offset: u64, bytes: u32) -> Option<[f32; 2]> { + let translation = self.ui_constant::<20>(offset, bytes, 11 * 4)?; + Some([ + f32::from_le_bytes(translation[..4].try_into().unwrap()), + f32::from_le_bytes(translation[16..].try_into().unwrap()), + ]) + } + + fn ui_constant(&self, offset: u64, bytes: u32, start: u64) -> Option<[u8; N]> { + let Root::Table(table) = self.roots_ref(false).first()? else { + return None; + }; + let View::Constant(address, size) = crate::descriptor::view(table.checked_add(offset)?)? + else { + return None; + }; + let mut data = [0; N]; + if size != bytes + || start.checked_add(N as u64)? > u64::from(size) + || !crate::host::read_into(address.checked_add(start)? as *const u8, &mut data) + { + return None; + } + Some(data) + } + + fn dialog_viewport(&mut self, pipeline: &HostPipeline, indices: u32) -> Option { + let canvas = crate::world_marker::canvas_size(); + let [viewport] = self.viewports.as_slice() else { + return None; + }; + let &[target] = self.targets.as_slice() else { + return None; + }; + if self.target_bounds != Some(canvas) + || canvas.0 <= 3840 + || !crate::compose::center_series_x_ui() + || ( + viewport.TopLeftX, + viewport.TopLeftY, + viewport.Width, + viewport.Height, + ) != (0.0, 0.0, canvas.0 as f32, canvas.1 as f32) + { + return None; + } + let viewport = *viewport; + let pixel = pipeline + .stages + .iter() + .find_map(|stage| match stage.shader.hash.as_str() { + hash @ ("e370f602fa0db9b2" | "a1f23b1756077215" | "fb0b42420f99e5e7") => Some(hash), + _ => None, + })?; + let (slot, bytes) = match pixel { + "e370f602fa0db9b2" => (0, 1536), + "a1f23b1756077215" => (64, 96), + _ => (32, 64), + }; + if pixel == "e370f602fa0db9b2" + && indices == 90 + && let Some(matrix) = self.ui_constant::<160>(slot, bytes, 8 * 4) + { + let at = |word: usize| { + f32::from_le_bytes(matrix[word * 4..word * 4 + 4].try_into().unwrap()) + }; + let transforms = [0, 16, 32].map(|i| [at(i), at(i + 3), at(i + 7)]); + if let Some(top) = dialog_band_top(transforms) { + self.dialog_band = Some((target, top)); + return None; + } + } + let (_, top) = self.dialog_band.filter(|&(surface, _)| surface == target)?; + let origin = self.prompt_origin(slot, bytes)?; + fit_dialog_content(viewport, origin, top) + } + + fn startup_prompt_viewport(&self, pipeline: &HostPipeline) -> Option { + let canvas = crate::world_marker::canvas_size(); + if self.target_bounds != Some(canvas) + || canvas.0 <= 3840 + || !crate::compose::FrameUi::startup() + || !crate::compose::center_series_x_ui() + { + return None; + } + let [viewport] = self.viewports.as_slice() else { + return None; + }; + if ( + viewport.TopLeftX, + viewport.TopLeftY, + viewport.Width, + viewport.Height, + ) != (0.0, 0.0, canvas.0 as f32, canvas.1 as f32) + { + return None; + } + let (crate::world_marker::PromptBatch::Glyphs, offset, bytes) = + crate::world_marker::PromptBatch::binding(pipeline)? + else { + return None; + }; + crate::world_marker::fit_startup_prompt(*viewport, self.prompt_origin(offset, bytes)?) + } + + fn pause_header_viewport( + &self, + pipeline: &HostPipeline, + indices: u32, + instances: u32, + ) -> Option { + if instances != 1 || !matches!(indices, 30 | 144) { + return None; + } + let binding = pipeline.stages.iter().find_map(|stage| { + match (indices, stage.shader.hash.as_str()) { + (30, "a1f23b1756077215") => Some((64, 96)), + (144, "02c6cf86ca283ce1") => Some((0, 64)), + _ => None, + } + })?; + let canvas = crate::world_marker::canvas_size(); + let [viewport] = self.viewports.as_slice() else { + return None; + }; + if self.target_bounds != Some(canvas) + || self.targets.len() != 1 + || canvas.0 <= 3840 + || !crate::compose::center_series_x_ui() + || ( + viewport.TopLeftX, + viewport.TopLeftY, + viewport.Width, + viewport.Height, + ) != (0.0, 0.0, canvas.0 as f32, canvas.1 as f32) + { + return None; + } + let transform = self.ui_constant::<32>(binding.0, binding.1, 32)?; + let words = std::array::from_fn(|i| { + f32::from_le_bytes(transform[i * 4..i * 4 + 4].try_into().unwrap()) + }); + fit_pause_header(*viewport, words) + } + pub(crate) fn draw_indexed( &mut self, list: &HostList, @@ -6202,6 +6473,8 @@ impl State { first_instance: u32, ) { self.window = None; + let previous_label = self.marker_label.take(); + let previous_prompt = self.projected_prompt.take(); #[cfg(feature = "diagnostics")] self.trace("indexed", indices, first); // Indexed rectangles are drawn by the rectangle geometry stage @@ -6219,11 +6492,74 @@ impl State { if ran { #[cfg(feature = "diagnostics")] list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + let pipeline = self.graphics_pipeline(); + let (marker_targets, viewport) = if crate::world_marker::enabled() { + let world_layer = self.target_bounds == Some(crate::world_marker::canvas_size()); + let depth_marker = + world_layer && pipeline.is_some_and(crate::world_marker::draws_marker); + let projected_viewport = if world_layer && (depth_marker || previous_prompt.is_some()) { + pipeline.and_then(|p| self.projected_prompt_viewport(p, previous_prompt)) + } else { + None + }; + let dialog_viewport = if !depth_marker && projected_viewport.is_none() { + pipeline.and_then(|p| self.dialog_viewport(p, indices)) + } else { + None + }; + let marker_targets = (depth_marker || projected_viewport.is_some()) + .then(|| self.bind_world_markers(list)) + .flatten(); + let marker_viewport = marker_targets.and_then(|_| { + projected_viewport + .map(|viewport| (viewport, None)) + .or_else(|| self.world_marker_viewport(pipeline?, previous_label)) + }); + let viewport = if let Some((viewport, label)) = marker_viewport { + self.marker_label = label; + #[cfg(feature = "diagnostics")] + list.note_op(|| { + format!( + "world marker viewport x={} width={}", + viewport.TopLeftX, viewport.Width + ) + }); + Some(viewport) + } else { + pipeline + .and_then(|p| { + self.startup_prompt_viewport(p) + .or_else(|| self.pause_header_viewport(p, indices, instances)) + }) + .or(dialog_viewport) + }; + (marker_targets, viewport) + } else { + (None, None) + }; + if let Some(viewport) = viewport { + // SAFETY: an open list with a viewport inside the D3D12 bounds. + unsafe { list.list.RSSetViewports(&[viewport]) }; + } // SAFETY: an open list with everything set. unsafe { list.list .DrawIndexedInstanced(indices, instances, first, base, first_instance) }; + if let Some((original, depth)) = marker_targets { + // SAFETY: restore the title's live descriptors before another draw. + unsafe { + list.list.OMSetRenderTargets( + 1, + Some(&original), + false, + depth.as_ref().map(std::ptr::from_ref), + ) + }; + } + if viewport.is_some() { + viewports(list, &self.viewports); + } self.drew(crate::pipeline::host_pipeline(self.pipeline as This)); DRAWN.fetch_add(1, Ordering::Relaxed); } @@ -6236,6 +6572,107 @@ impl State { } } +fn fit_pause_header( + viewport: D3D12_VIEWPORT, + [xx, xy, _, x, yx, yy, _, y]: [f32; 8], +) -> Option { + let authored_width = viewport.Height * 16.0 / 9.0; + let scale = viewport.Width / authored_width; + // Both backplate passes use a 16:9-wide stage centered at the top edge. + let authored_xx = 2.0 / 65520.0; + if scale <= 1.0 + || !(0.997..=1.003).contains(&y) + || !(-0.002..=0.002).contains(&x) + || !(-1e-8..=1e-8).contains(&xy) + || !(-1e-8..=1e-8).contains(&yx) + || !(-5.4e-6..=-5.0e-6).contains(&yy) + || !((authored_xx * 0.99)..=(authored_xx * 1.01)).contains(&(xx * scale)) + { + return None; + } + let width = viewport.Width * scale; + Some(D3D12_VIEWPORT { + TopLeftX: (viewport.Width - width) / 2.0, + Width: width, + ..viewport + }) +} + +#[test] +fn wide_pause_header_expands_both_backplate_passes_from_the_center() { + for width in [5160.0, 7680.0] { + let viewport = D3D12_VIEWPORT { + Width: width, + Height: 2160.0, + MaxDepth: 1.0, + ..Default::default() + }; + for (xx, yy, y) in [(1.529e-5, -5.19e-6, 1.0), (1.53e-5, -5.23e-6, 0.9997685)] { + let mut transform = [xx * 7680.0 / width, 0.0, 0.0, 0.0, 0.0, yy, 0.0, y]; + let placed = fit_pause_header(viewport, transform).unwrap(); + assert!((placed.TopLeftX + placed.Width / 2.0 - width / 2.0).abs() < 0.001); + assert!((placed.Width * 3840.0 / width - width).abs() < 0.001); + assert_eq!((placed.TopLeftY, placed.Height), (0.0, 2160.0)); + transform[3] = 0.12; + assert!(fit_pause_header(viewport, transform).is_none()); + } + } +} + +fn dialog_band_top(transforms: [[f32; 3]; 3]) -> Option { + let [[_, _, upper], [_, _, footer], [_, _, top]] = transforms; + // The confirmation backplate is three rectangles across the full stage. + let full_width = transforms + .iter() + .all(|[scale, center, _]| (*scale - 2.0 / 65520.0).abs() < 1e-8 && center.abs() < 1e-5); + (full_width && (upper - footer - 1.0).abs() < 1e-5 && (-0.75..=-0.25).contains(&top)) + .then_some(top) +} + +fn fit_dialog_content( + viewport: D3D12_VIEWPORT, + [x, y]: [f32; 2], + top: f32, +) -> Option { + // The backplate and right-aligned controls already use the full viewport. + if !(-1.0..=-0.3).contains(&x) || !(-1.0..=top).contains(&y) { + return None; + } + Some(D3D12_VIEWPORT { + Width: viewport.Height * 16.0 / 9.0, + ..viewport + }) +} + +#[test] +fn wide_confirmation_keeps_proportions_without_moving_the_controls() { + let width = 2.0 / 65520.0; + let rectangles = [ + [width, 0.0, 0.2712073], + [width, 0.0, -0.7287927], + [width, 0.0, -0.4590658], + ]; + let top = dialog_band_top(rectangles).unwrap(); + let mut ordinary = rectangles; + ordinary[2][1] = 0.5; + assert_eq!(dialog_band_top(ordinary), None); + for canvas_width in [5160.0, 7680.0] { + let viewport = D3D12_VIEWPORT { + Width: canvas_width, + Height: 2160.0, + MaxDepth: 1.0, + ..Default::default() + }; + let text = fit_dialog_content(viewport, [-0.9195309, -0.6552398], top).unwrap(); + assert_eq!( + (text.TopLeftX, text.Width, text.Height), + (0.0, 3840.0, 2160.0) + ); + assert!(fit_dialog_content(viewport, [0.9551576, -0.9207352], top).is_none()); + assert!(fit_dialog_content(viewport, [-0.9195309, 0.914294], top).is_none()); + } +} + impl State { /// Shaders that can write buffers were recorded: arguments may be others /// from here on. @@ -6606,6 +7043,9 @@ impl State { const INDEXED: u32 = 1; const DISPATCH: u32 = 2; const MESH: u32 = 10; + if matches!(kind, DRAW | INDEXED | MESH) { + self.projected_prompt = None; + } #[cfg(feature = "diagnostics")] let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); #[cfg(not(feature = "diagnostics"))] diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 513b2f0283..17b9c0b349 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -13770,6 +13770,24 @@ impl Host { overlay: Option<(&ID3D12Resource, u32)>, frame: u64, ) -> Option { + self.present_placed( + texture, + state, + overlay, + [crate::compose::Placement::WHOLE; 2], + frame, + crate::compose::FrameUi::capture(false), + ) + } + + pub(crate) fn present_placed( + &self, + texture: &ID3D12Resource, + state: u32, + overlay: Option<(&ID3D12Resource, u32)>, + placement: [crate::compose::Placement; 2], + frame: u64, + ui: crate::compose::FrameUi, ) -> Option { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; // Leonida: whether the title presents the interface on a plane of its own (what frame generation could be @@ -13794,16 +13812,55 @@ impl Host { } } } + let source_placement = placement; + let mut placement = placement; + let mut overlay_centered = false; + let mut wide_overlay = false; let planes = overlay.and_then(|(over, over_state)| { // SAFETY: a live overlay resource. let over_desc = unsafe { over.GetDesc() }; + let base_fmt = crate::compose::view(&desc)?; + let over_fmt = crate::compose::view(&over_desc)?; + if crate::compose::center_series_x_ui() { + let (width, height) = crate::world_marker::canvas_size(); + wide_overlay = width > 3840 + && (over_desc.Width, over_desc.Height) == (width as u64, height as u32) + && placement[1].is_whole(over_desc.Width, over_desc.Height); + let original = placement[1]; + let output = (desc.Width, desc.Height); + placement[1] = if wide_overlay && ui.centers_wide_overlay() { + original.center_startup_ui(output) + } else { + original.center_legacy_ui((over_desc.Width, over_desc.Height), output) + }; + overlay_centered = original != placement[1]; + } Some(( over, D3D12_RESOURCE_STATES(over_state as i32), - crate::compose::view(&desc)?, - crate::compose::view(&over_desc)?, + base_fmt, + over_fmt, )) }); + let markers = if crate::world_marker::enabled() { + planes.and_then(|(over, ..)| crate::world_marker::layer(over)) + } else { + None + }; + let edges = wide_overlay && std::env::var_os("LEONIDA_HUD_POSITION").is_some_and(|v| v == "edges"); + let hud_layout = crate::compose::HudLayout::for_present( + overlay_centered, + wide_overlay, + ui, + edges, + (desc.Width, desc.Height), + ); + let over_read = if hud_layout.uses_split() { + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE + } else { + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + }; let format = if planes.is_some() { planes_format(crate::fg::active(), present_tenbit(), TEN_REFUSED.load(Ordering::Relaxed)) } else { @@ -13881,7 +13938,7 @@ impl Host { // Once: the planes are composed into 8 bits from now on. tracing::warn!(error = %e, "the swap chain does not take 10 bits a channel: the two planes are composed into 8, as before"); drop(presenter); - return self.present_planes(texture, state_u32, overlay, frame); + return self.present_placed(texture, state_u32, overlay, source_placement, frame, ui); } Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); @@ -13948,8 +14005,16 @@ impl Host { if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { pre.push(transition(texture, state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); } - if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - pre.push(transition(over, over_state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE)); + if over_state != over_read { + pre.push(transition(over, over_state, over_read)); + } + if let Some(markers) = &markers { + copy.keep(markers); + pre.push(transition( + markers, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )); } pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); list.ResourceBarrier(&pre); @@ -13962,7 +14027,10 @@ impl Host { self, compose_slot, list, - [(texture, base_fmt), (over, over_fmt)], + (texture, base_fmt, placement[0]), + Some((over, over_fmt, placement[1])), + markers.as_ref(), + hud_layout, &back, ((placed.left, placed.top), (width, height)), ) { @@ -13987,8 +14055,15 @@ impl Host { if state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { post.push(transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, state)); } - if over_state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE { - post.push(transition(over, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, over_state)); + if over_state != over_read { + post.push(transition(over, over_read, over_state)); + } + if let Some(markers) = &markers { + post.push(transition( + markers, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + )); } post.push(transition( &back, @@ -14114,7 +14189,8 @@ impl Host { } // Leonida: FSR 3 frame generation's prepare dispatch and configuration for this present (crate::fsr), // last on the list before `Present`. Series S's base plane is the colour without the interface. - let hudless = (composed && whole).then_some((texture, state_u32)); + let hudless = (composed && whole && placement[0].is_whole(desc.Width, desc.Height)) + .then_some((texture, state_u32)); crate::fsr::before_present( &self.device, &p.swap_chain, diff --git a/d3d12/crates/leonida-gpu/src/host/menu.rs b/d3d12/crates/leonida-gpu/src/host/menu.rs index b60bae46db..7cdf560f45 100644 --- a/d3d12/crates/leonida-gpu/src/host/menu.rs +++ b/d3d12/crates/leonida-gpu/src/host/menu.rs @@ -69,7 +69,9 @@ const ITEMS: &[Item] = &[ // Turned on, it applies at the next start (the swap chain is FidelityFX's); off and on again while it runs. Item { var: "LEONIDA_FSR_FRAMEGEN", label: "FSR 3 FRAME GEN 2X (RTX 20/30)", values: UNSET_ON, live: false }, // The window's shape, and the game's 16:9 picture in a window of another shape (`crate::aspect`). - Item { var: "LEONIDA_ASPECT", label: "WINDOW SHAPE", values: &[("", "16:9 (GAME)"), ("21:9", "21:9"), ("32:9", "32:9"), ("auto", "AS THE SCREEN")], live: false }, + Item { var: "LEONIDA_NATIVE_ULTRAWIDE", label: "SERIES X ULTRAWIDE", values: &[("", "OFF"), ("3440x1440", "3440x1440"), ("3840x1080", "3840x1080"), ("5120x1440", "5120x1440")], live: false }, + Item { var: "LEONIDA_HUD_POSITION", label: "ULTRAWIDE HUD", values: &[("", "CENTER"), ("edges", "SCREEN EDGES")], live: true }, + Item { var: "LEONIDA_ASPECT", label: "WINDOW SHAPE", values: &[("", "GAME OUTPUT"), ("21:9", "21:9"), ("32:9", "32:9"), ("auto", "AS THE SCREEN")], live: false }, Item { var: "LEONIDA_PRESENT_SCALE", label: "PICTURE IN ANOTHER SHAPE", values: &[("", "BY WINDOW SHAPE"), ("fit", "BARS"), ("stretch", "STRETCH")], live: true }, // Leonida: the title's window borderless over its monitor from the start (leonida-hle's lifecycle.rs); Alt+Enter // switches while it runs either way. @@ -119,7 +121,11 @@ const ITEMS: &[Item] = &[ const ACTIONS: [&str; 4] = ["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "RESET ALL TO PLAY DEFAULTS", "CLOSE"]; fn get(var: &str) -> String { - std::env::var(var).unwrap_or_default() + let value = std::env::var(var).unwrap_or_default(); + match (var, value.as_str()) { + ("LEONIDA_NATIVE_ULTRAWIDE", "off" | "0") | ("LEONIDA_HUD_POSITION", "center") => String::new(), + _ => value, + } } /// Whether the frame-rate line is shown at the top while the menu is closed diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index cbc06fcdfe..9bc16a7ce1 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -31,6 +31,12 @@ mod census; mod shown; #[cfg(windows)] mod compose; +#[cfg(windows)] +mod world_marker; +#[cfg(windows)] +pub use compose::{HudState, set_gameplay_hud_probe, set_loading_ui_probe}; +#[cfg(windows)] +pub use world_marker::set_world_marker_output; pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index aa6582fe71..3f4560e001 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -1938,6 +1938,7 @@ extern "system" fn clear_rtv( } list.list.ClearRenderTargetView(rtv, color, rects); } + crate::world_marker::clear(host, list, texture, rects); } #[cfg(not(windows))] let _ = (this, handle, color, count, rects); diff --git a/d3d12/crates/leonida-gpu/src/queue.rs b/d3d12/crates/leonida-gpu/src/queue.rs index b6d71f94a9..58fc4e75c4 100644 --- a/d3d12/crates/leonida-gpu/src/queue.rs +++ b/d3d12/crates/leonida-gpu/src/queue.rs @@ -999,6 +999,65 @@ struct RetailPlane { #[cfg(windows)] const _: () = assert!(size_of::() == 72); +#[cfg(windows)] +fn placement(parameters: *const Plane, index: usize, texture: This) -> crate::compose::Placement { + let mut whole = crate::compose::Placement::WHOLE; + let at = parameters + .cast::() + .wrapping_add(index) + .cast::(); + let mut bytes = [0; size_of::()]; + if parameters.is_null() || !crate::host::read_into(at, &mut bytes) { + return whole; + } + // SAFETY: the bytes of a `RetailPlane`, copied. + let plane = unsafe { bytes.as_ptr().cast::().read_unaligned() }; + let size = crate::resource::host_resource(texture).map(|t| { + // SAFETY: a live host resource. + let d = unsafe { t.GetDesc() }; + (d.Width, d.Height) + }); + if !plane.source_rects.is_null() + && let Some((width, height)) = size + { + let mut rect = [0; 16]; + if crate::host::read_into(plane.source_rects.cast(), &mut rect) { + let r: [i32; 4] = std::array::from_fn(|i| { + i32::from_ne_bytes(rect[i * 4..i * 4 + 4].try_into().unwrap()) + }); + whole.source = source_rect(r, width, height); + } + } + if !plane.destination.is_null() { + let mut rect = [0; 16]; + if crate::host::read_into(plane.destination.cast(), &mut rect) { + let r: [f32; 4] = std::array::from_fn(|i| { + f32::from_ne_bytes(rect[i * 4..i * 4 + 4].try_into().unwrap()) + }); + whole.dest = dest_rect(r); + } + } + whole +} + +/// A source rectangle (left, top, right, bottom) inside a `width` by +/// `height` texture, with an area. +#[cfg(windows)] +fn source_rect([l, t, r, b]: [i32; 4], width: u64, height: u32) -> Option<[i32; 4]> { + let inside = + 0 <= l && l < r && i64::from(r) <= width as i64 && 0 <= t && t < b && b as u32 <= height; + inside.then_some([l, t, r, b]) +} + +/// A place on the screen (fractions: left, top, right, bottom) inside it, +/// with an area. +#[cfg(windows)] +fn dest_rect([l, t, r, b]: [f32; 4]) -> Option<[f32; 4]> { + let unit = |v: f32| (0.0..=1.0).contains(&v); + let inside = [l, t, r, b].into_iter().all(unit) && l < r && t < b; + inside.then_some([l, t, r, b]) +} + #[cfg(windows)] fn overlay_resource(parameters: *const Plane) -> Option { // Read only the second prefix at the 72-byte retail PresentX stride. A @@ -1227,7 +1286,7 @@ fn system_timestamp() -> u64 { /// Frames presented so far. static FRAMES: AtomicU64 = AtomicU64::new(0); -#[cfg(feature = "diagnostics")] +#[cfg(any(windows, feature = "diagnostics"))] pub(crate) fn presented() -> u64 { FRAMES.load(Ordering::Relaxed) } @@ -1364,11 +1423,22 @@ extern "system" fn present( .filter(|&over_res| base_res != Some(over_res)) .and_then(take_copy); let resource = texture.as_ref().map_or(0, |t| t.0); + let placement = placements( + plane_parameters, + base_res, + overlay.as_ref().map(|(r, ..)| *r as This), + ); + let ui = crate::compose::FrameUi::capture(crate::compose::movie_active(frame)); behind::present( this, texture.map(|(_, copy, state)| (copy, state)), overlay.map(|(_, copy, state)| (copy, state)), - Shown { frame, resource }, + Shown { + frame, + resource, + ui, + placement, + }, ); called.end(); #[cfg(feature = "diagnostics")] @@ -1400,11 +1470,22 @@ extern "system" fn present( (over_res, over_tex, over_state) }) }); + let placement = placements( + plane_parameters, + Some(resource), + overlay.as_ref().map(|(r, ..)| *r), + ); + let ui = crate::compose::FrameUi::capture(crate::compose::movie_active(frame)); show_planes( texture, state, overlay.as_ref().map(|(_, tex, st)| (*tex, *st)), - Shown { frame, resource: resource as usize }, + Shown { + frame, + resource: resource as usize, + ui, + placement, + }, ); crate::resource::host_transition(resource, state); if let Some((over_res, _, over_state)) = overlay { @@ -1438,6 +1519,24 @@ fn frame_ends() { struct Shown { frame: u64, resource: usize, + ui: crate::compose::FrameUi, + placement: [crate::compose::Placement; 2], +} + +#[cfg(windows)] +fn placements( + parameters: *const Plane, + base: Option, + over: Option, +) -> [crate::compose::Placement; 2] { + use crate::compose::Placement; + if !crate::world_marker::enabled() || over.is_none() { + return [Placement::WHOLE; 2]; + } + [ + base.map_or(Placement::WHOLE, |r| placement(parameters, 0, r)), + over.map_or(Placement::WHOLE, |r| placement(parameters, 1, r)), + ] } /// Shows `texture` (with optional `overlay` plane blended over it) in our window. @@ -1451,7 +1550,7 @@ fn show_planes( let Some(host) = crate::host::host() else { return; }; - let shown = host.present_planes(texture, state, overlay, what.frame); + let shown = host.present_placed(texture, state, overlay, what.placement, what.frame, what.ui); #[cfg(feature = "diagnostics")] blinks(what.frame, what.resource as This, state, shown); #[cfg(not(feature = "diagnostics"))] diff --git a/d3d12/crates/leonida-gpu/src/shader_cache.rs b/d3d12/crates/leonida-gpu/src/shader_cache.rs index dc098e7580..90ccca5d60 100644 --- a/d3d12/crates/leonida-gpu/src/shader_cache.rs +++ b/d3d12/crates/leonida-gpu/src/shader_cache.rs @@ -42,6 +42,10 @@ pub(crate) fn counts() -> (u64, u64) { /// what it was told of the host. Not our executable: a rebuild of anything /// else used to translate every shader again. fn build() -> [u8; 32] { + build_for_shadow_layout(leonida_shader::emit::wide_shadow_tiles_enabled()) +} + +fn build_for_shadow_layout(wide: bool) -> [u8; 32] { // The view heap's null slot differs by host GPU: a translation cached // without the clamp must not be served (`host_settings` below). crate::descriptor::host::probe_view_limit(); @@ -106,6 +110,9 @@ fn build() -> [u8; 32] { }); let mut hash = blake3::Hasher::new(); hash.update(fixed); + if wide { + hash.update(b"LEONIDA_WIDE_SHADOW_TILES=1\0"); + } for value in leonida_shader::emit::host_settings() { hash.update(&value.to_le_bytes()); } @@ -640,6 +647,13 @@ mod tests { } } + #[test] + fn wide_shadow_tiles_have_a_separate_cache_key() { + let compact = build_for_shadow_layout(false); + assert_ne!(compact, build_for_shadow_layout(true)); + assert_eq!(build_for_shadow_layout(false), compact); + } + #[test] fn translations_come_back_from_the_cache() { let dir = tempfile::tempdir().unwrap(); diff --git a/d3d12/crates/leonida-gpu/src/texture.rs b/d3d12/crates/leonida-gpu/src/texture.rs index cb9f50a066..12d61e168d 100644 --- a/d3d12/crates/leonida-gpu/src/texture.rs +++ b/d3d12/crates/leonida-gpu/src/texture.rs @@ -1525,6 +1525,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { // dedicated per-list upload buffer through the list's GPU fence so // concurrent frames never overwrite each other or stall on staging hashes. if staging.movie_plane() { + crate::compose::note_movie_upload(); let (at, len) = staging.memory(); let footprint = staging.footprints[0].Footprint; let pitch = footprint.RowPitch as usize; diff --git a/d3d12/crates/leonida-gpu/src/world_marker.rs b/d3d12/crates/leonida-gpu/src/world_marker.rs new file mode 100644 index 0000000000..e599b89d42 --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/world_marker.rs @@ -0,0 +1,521 @@ +//! Sends depth-occluded world indicators to a layer with display coordinates. + +use std::sync::{ + Mutex, + atomic::{AtomicU32, Ordering}, +}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM; +use windows::core::{GUID, IUnknown, Interface}; + +use crate::host::{Host, HostList}; +use crate::pipeline::host::HostPipeline; + +const LAYER: GUID = GUID::from_u128(0x9dc9c22f_565d_462f_ae00_604bb7bc8078); +const LEGACY_CANVAS: (i32, i32) = (3840, 2160); +static SCALE: AtomicU32 = AtomicU32::new(1.0_f32.to_bits()); +static CANVAS_WIDTH: AtomicU32 = AtomicU32::new(LEGACY_CANVAS.0 as u32); + +// Scaleform DepthStencilOccluded pixel shaders in the Series X retail archive. +const OCCLUDED: &[&str] = &[ + "02a551986643d643", + "0325cbdca3616333", + "0a1799fb7d5da783", + "0c1ed8d60b672368", + "1579833b3d76cfb1", + "22a3172d91443114", + "28d4900c27d2de27", + "2d9141a07a8f723a", + "31d22c188183d6ca", + "330b995018b05057", + "39c15d2acf2d7bf1", + "3ae2b1fe4945806d", + "3e6dbba2c681838e", + "4dd579164f78d9cb", + "50b8012397f92085", + "50f8b89c712e6aaa", + "5280f1691027080a", + "574c51af38ebc30f", + "5df75167fc24daee", + "5e5baa656e633353", + "60f856f099347bf4", + "637a823c9b9d7491", + "675560db98e61347", + "6e74c21c8f9156b8", + "70de2bb0a5f7c443", + "76d50eb2f6799aca", + "7e5e4dd7cf82c937", + "823fbfe25f32d01b", + "8c708b3de86ea044", + "91cbe89832eb575b", + "97cb076e6ab60f6b", + "9ac8c3ec84112320", + "9b41ddf32d55a240", + "9b889b7e5c40f0d3", + "9d1d08c117ad0330", + "a38a40eda87f3473", + "ab3256599c8c7b7a", + "ae0edc50abb259a9", + "aee9e38b668df166", + "b6d73bedf7bf7f0c", + "bcb46c80dba24918", + "bf7d126b2e0ae095", + "c1f20fa939968895", + "c4332f96c61df29d", + "c45bafda4202205a", + "c82fca24156f21bb", + "c944dea8b658e62f", + "c9f676d7c03fdba0", + "ce80143ca1b0fea3", + "d0e20608fa65e943", + "d490f7b83d98034f", + "d536eebf10f8404a", + "d8b5a069aeb6f34a", + "d93768376f4eefaf", + "defe36ec41cc5f3b", + "dfcb7f2adc8c76b6", + "e2dd1c1d58b90f97", + "e41a34f8d487806a", + "eefbfdb9a7a38da0", + "f5a8464359fd0297", + "fbe513516e50cbe5", + "fde6e72388b080ba", + "fe0c1af484195ea0", + "ff8feae806a74299", +]; + +/// Sets the display size that the retail title renders for. +pub fn set_world_marker_output((width, height): (u32, u32), layout: (u32, u32)) { + let scale = if width > 0 && height > 0 { + (16.0 * height as f32 / (9.0 * width as f32)).min(1.0) + } else { + 1.0 + }; + SCALE.store(scale.to_bits(), Ordering::Relaxed); + if layout.1 == LEGACY_CANVAS.1 as u32 && (3840..=7680).contains(&layout.0) { + CANVAS_WIDTH.store(layout.0, Ordering::Relaxed); + } +} + +pub(crate) fn canvas_size() -> (i32, i32) { + (CANVAS_WIDTH.load(Ordering::Relaxed) as i32, LEGACY_CANVAS.1) +} + +pub(crate) fn enabled() -> bool { + scale() < 1.0 && crate::compose::center_series_x_ui() +} + +fn scale() -> f32 { + f32::from_bits(SCALE.load(Ordering::Relaxed)) +} + +pub(crate) fn draws_marker(pipeline: &HostPipeline) -> bool { + pipeline + .stages + .iter() + .any(|stage| OCCLUDED.binary_search(&stage.shader.hash.as_str()).is_ok()) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum PromptBatch { + Marker, + Glyphs, + Shape, +} + +impl PromptBatch { + pub(crate) fn binding(pipeline: &HostPipeline) -> Option<(Self, u64, u32)> { + let mut vertex = ""; + let mut pixel = ""; + for stage in &pipeline.stages { + let hash = stage.shader.hash.as_str(); + match hash { + "223f27deecba7ecc" | "d166c341988178de" | "571fe570756bc393" => vertex = hash, + "91cbe89832eb575b" | "e370f602fa0db9b2" | "02c6cf86ca283ce1" => pixel = hash, + _ => {} + } + } + match (vertex, pixel) { + ("223f27deecba7ecc", "91cbe89832eb575b") => Some((Self::Marker, 96, 96)), + ("d166c341988178de", "e370f602fa0db9b2") => Some((Self::Glyphs, 0, 1536)), + ("571fe570756bc393", "02c6cf86ca283ce1") => Some((Self::Shape, 0, 64)), + _ => None, + } + } +} + +#[derive(Clone, Copy)] +pub(crate) enum ProjectedPrompt { + Marker([f32; 2]), + Caption { marker_x: f32, button: [f32; 2] }, +} + +impl ProjectedPrompt { + pub(crate) fn advance( + previous: Option, + batch: PromptBatch, + origin: [f32; 2], + canvas: (i32, i32), + ) -> Option<(Self, Option)> { + if !origin.iter().all(|value| value.is_finite()) { + return None; + } + if batch == PromptBatch::Marker { + return Some((Self::Marker(origin), None)); + } + let half_width = canvas.0 as f32 / 2.0; + let half_height = canvas.1 as f32 / 2.0; + let (marker_x, button) = match previous? { + Self::Marker(marker) if batch == PromptBatch::Glyphs => { + // The 2D button starts at a fixed canvas offset from the coloured world sprite. + let dx = (marker[0] - origin[0]) * half_width; + let dy = (origin[1] - marker[1]) * half_height; + if (dx - 76.17).abs() > 0.25 || (dy - 1.12).abs() > 0.25 { + return None; + } + (marker[0], origin) + } + // The glyphs and inline shapes share a baseline with the button. + Self::Caption { marker_x, button } + if origin[0] >= button[0] + && ((origin[1] - button[1]) * half_height).abs() <= 1.0 => + { + (marker_x, button) + } + _ => return None, + }; + Some((Self::Caption { marker_x, button }, Some(marker_x))) + } +} + +pub(crate) fn anchor_constant<'a>( + mut shaders: impl Iterator + Clone, +) -> Option<(u64, u32, Option<(u64, bool)>)> { + let pixel = shaders.clone().find(|hash| { + matches!( + *hash, + "1579833b3d76cfb1" | "ab3256599c8c7b7a" | "91cbe89832eb575b" + ) + }); + // VBatchVertexCxformEAlpha stores the same x transform in its first 64-byte entry. + shaders.find_map(|hash| match hash { + "223f27deecba7ecc" => Some(( + 24 * 4, + 96, + (pixel == Some("91cbe89832eb575b")).then_some((32 * 4, false)), + )), + "67e814f3c3be6dac" => Some((8 * 4, 96, None)), + "ea212fca1f658aef" if pixel == Some("1579833b3d76cfb1") => { + Some((16 * 4, 1536, Some((24 * 4, true)))) + } + "e2974aa5215d4a7f" if pixel == Some("ab3256599c8c7b7a") => { + Some((16 * 4, 64, Some((24 * 4, true)))) + } + _ => None, + }) +} + +#[derive(Clone, Copy)] +pub(crate) struct LabelAnchor { + depth: [u8; 32], + pub(crate) x: f32, +} + +impl LabelAnchor { + pub(crate) fn for_batch(previous: Option, depth: [u8; 32], x: f32) -> Self { + Self::matching(previous, &depth).unwrap_or(Self { depth, x }) + } + + pub(crate) fn matching(previous: Option, depth: &[u8; 32]) -> Option { + // Depth, fade and scene stamp identify consecutive batches of the same label. + previous.filter(|label| label.depth[..12] == depth[..12]) + } +} + +pub(crate) fn fit_sprite(viewport: D3D12_VIEWPORT, anchor: f32) -> Option { + let canvas_scale = canvas_size().0 as f32 / LEGACY_CANVAS.0 as f32; + fit_at(viewport, anchor, (scale() * canvas_scale).min(1.0)) +} + +pub(crate) fn fit_startup_prompt( + viewport: D3D12_VIEWPORT, + origin: [f32; 2], +) -> Option { + // The title's button groups are anchored near the bottom-right in clip space. + if viewport.Width <= LEGACY_CANVAS.0 as f32 + || !(0.5..=1.0).contains(&origin[0]) + || !(-1.0..=-0.75).contains(&origin[1]) + { + return None; + } + fit_at(viewport, 1.0, viewport.Width / LEGACY_CANVAS.0 as f32) +} + +fn fit_at(viewport: D3D12_VIEWPORT, anchor: f32, scale: f32) -> Option { + let width = viewport.Width * scale; + let x = (anchor + 1.0) * 0.5; + let left = viewport.TopLeftX + x * (viewport.Width - width); + // D3D12 viewport bounds still apply to sprites anchored outside the picture. + (left >= D3D12_VIEWPORT_BOUNDS_MIN as f32 && left + width <= D3D12_VIEWPORT_BOUNDS_MAX as f32) + .then_some(D3D12_VIEWPORT { + TopLeftX: left, + Width: width, + ..viewport + }) +} + +fn canvas(desc: &D3D12_RESOURCE_DESC) -> bool { + let (width, height) = canvas_size(); + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && (desc.Width, desc.Height) == (width as u64, height as u32) + && desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM + && desc.MipLevels == 1 + && desc.DepthOrArraySize == 1 + && desc.SampleDesc.Count == 1 +} + +pub(crate) fn layer(overlay: &ID3D12Resource) -> Option { + let mut pointer = std::ptr::null_mut::(); + let mut size = size_of_val(&pointer) as u32; + // SAFETY: this key holds an AddRef'd IUnknown and the buffer has pointer size. + unsafe { + overlay + .GetPrivateData( + &LAYER, + &mut size, + Some(std::ptr::from_mut(&mut pointer).cast()), + ) + .ok()?; + (!pointer.is_null()) + .then(|| IUnknown::from_raw(pointer))? + .cast() + .ok() + } +} + +pub(crate) fn target( + host: &Host, + list: &HostList, + overlay: &ID3D12Resource, +) -> Option { + // SAFETY: an open command list and a live render target. + unsafe { + let mut desc = overlay.GetDesc(); + if !canvas(&desc) { + return None; + } + if let Some(layer) = layer(overlay) { + return Some(layer); + } + static CREATE: Mutex<()> = Mutex::new(()); + let _create = CREATE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(layer) = layer(overlay) { + return Some(layer); + } + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + let mut markers: Option = None; + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut markers, + ) + .inspect_err( + |error| tracing::warn!(%error, "could not allocate the world marker layer"), + ) + .ok()?; + let markers = markers?; + overlay.SetPrivateDataInterface(&LAYER, &markers).ok()?; + list.keep(&markers); + list.list + .ClearRenderTargetView(host.rtv(Some(&markers), None), &[0.0; 4], None); + tracing::info!("drawing depth-occluded world indicators at display coordinates"); + Some(markers) + } +} + +pub(crate) fn clear( + host: &Host, + list: &HostList, + overlay: &ID3D12Resource, + rects: Option<&[windows::Win32::Foundation::RECT]>, +) { + // SAFETY: an open command list and a live render target. + unsafe { + if enabled() + && canvas(&overlay.GetDesc()) + && let Some(markers) = layer(overlay) + { + list.keep(&markers); + list.list + .ClearRenderTargetView(host.rtv(Some(&markers), None), &[0.0; 4], rects); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn startup_prompt_keeps_its_width_and_right_inset_after_composition() { + let right_inset = 80.0; + let glyph_width = 36.0; + for width in [5160.0, 7680.0] { + let viewport = D3D12_VIEWPORT { + Width: width, + Height: 2160.0, + ..Default::default() + }; + let right = 1.0 - 2.0 * right_inset / width; + let left = right - 2.0 * glyph_width / width; + let fitted = fit_startup_prompt(viewport, [left, -0.9]).unwrap(); + let composed_x = + |clip| (fitted.TopLeftX + (clip + 1.0) * 0.5 * fitted.Width) * 3840.0 / width; + assert!((3840.0_f32 - composed_x(right) - right_inset).abs() < 0.002); + assert!((composed_x(right) - composed_x(left) - glyph_width).abs() < 0.002); + assert_eq!(fitted.Height, viewport.Height); + assert!(fit_startup_prompt(viewport, [0.0, 0.0]).is_none()); + } + let native = D3D12_VIEWPORT { + Width: 3840.0, + Height: 2160.0, + ..Default::default() + }; + assert!(fit_startup_prompt(native, [0.8, -0.9]).is_none()); + } + + #[test] + fn narrow_a_sprite_around_its_own_anchor() { + let original = D3D12_VIEWPORT { + Width: 3840.0, + Height: 2160.0, + MaxDepth: 1.0, + ..Default::default() + }; + let pixel = + |viewport: D3D12_VIEWPORT, x| viewport.TopLeftX + (x + 1.0) * 0.5 * viewport.Width; + for x in [-0.875, 0.0, 0.625, 0.875] { + let fit = fit_at(original, x, 0.5).unwrap(); + assert_eq!(fit.Width, 1920.0); + assert_eq!(fit.Height, original.Height); + assert_eq!(pixel(fit, x), pixel(original, x)); + assert_eq!(pixel(fit, x + 0.125) - pixel(fit, x), 120.0); + } + } + + #[test] + fn a_flat_world_caption_keeps_its_button_and_glyphs_with_the_marker() { + let viewport = D3D12_VIEWPORT { + Width: 3840.0, + Height: 2160.0, + ..Default::default() + }; + let canvas_x = + |viewport: D3D12_VIEWPORT, x| viewport.TopLeftX + (x + 1.0) * 0.5 * viewport.Width; + for x in [-0.65, 0.0, 0.65] { + let marker = [x, 0.2]; + let (pending, unmodified) = + ProjectedPrompt::advance(None, PromptBatch::Marker, marker, LEGACY_CANVAS).unwrap(); + assert_eq!(unmodified, None); + let button = [x - 76.17 / 1920.0, marker[1] + 1.12 / 1080.0]; + let (caption, anchor) = + ProjectedPrompt::advance(Some(pending), PromptBatch::Glyphs, button, LEGACY_CANVAS) + .unwrap(); + let text = [button[0] + 0.08, button[1] - 0.0004]; + let (_, text_anchor) = + ProjectedPrompt::advance(Some(caption), PromptBatch::Shape, text, LEGACY_CANVAS) + .unwrap(); + let fitted = fit_at(viewport, anchor.unwrap(), 0.5).unwrap(); + let fitted_text = fit_at(viewport, text_anchor.unwrap(), 0.5).unwrap(); + let centred = D3D12_VIEWPORT { + TopLeftX: 960.0, + Width: 1920.0, + ..viewport + }; + assert!( + (canvas_x(fitted, button[0]) - canvas_x(viewport, x) + 76.17 * 0.5).abs() < 0.001 + ); + assert!( + (canvas_x(fitted_text, text[0]) - canvas_x(fitted, button[0]) - 76.8).abs() < 0.001 + ); + assert!( + (canvas_x(fitted, button[0]) - canvas_x(centred, button[0]) - 960.0 * x).abs() + < 0.001 + ); + assert!( + ProjectedPrompt::advance( + Some(caption), + PromptBatch::Glyphs, + [0.88, 0.92], + LEGACY_CANVAS + ) + .is_none() + ); + assert!( + ProjectedPrompt::advance( + Some(pending), + PromptBatch::Glyphs, + [x, marker[1]], + LEGACY_CANVAS + ) + .is_none() + ); + assert!( + ProjectedPrompt::advance(None, PromptBatch::Glyphs, button, LEGACY_CANVAS) + .is_none() + ); + } + } + + #[test] + fn a_batched_world_prompt_uses_the_vertex_transform_table() { + assert_eq!( + anchor_constant(["ea212fca1f658aef", "1579833b3d76cfb1"].into_iter()), + Some((64, 1536, Some((96, true)))), + ); + assert_eq!( + anchor_constant(["ea212fca1f658aef", "e370f602fa0db9b2"].into_iter()), + None + ); + } + + #[test] + fn overlapping_outline_and_text_use_the_same_label_anchor() { + assert_eq!( + anchor_constant(["e2974aa5215d4a7f", "ab3256599c8c7b7a"].into_iter()), + Some((64, 64, Some((96, true)))), + ); + let depth = [0x36; 32]; + let cap = LabelAnchor::for_batch(None, depth, -0.37); + let outline = LabelAnchor::for_batch(Some(cap), depth, -0.29); + let mut text_depth = depth; + text_depth[12..].fill(0x52); + let text = LabelAnchor::for_batch(Some(outline), text_depth, -0.32); + assert_eq!([cap.x, outline.x, text.x], [-0.37; 3]); + let next = LabelAnchor::for_batch(Some(text), [0x73; 32], 0.45); + assert_eq!(next.x, 0.45); + } + + #[test] + fn label_icons_share_the_caption_anchor_and_standalone_icons_do_not() { + assert_eq!( + anchor_constant(["223f27deecba7ecc", "91cbe89832eb575b"].into_iter()), + Some((96, 96, Some((128, false)))), + ); + let depth = [0x36; 32]; + let cap = LabelAnchor::for_batch(None, depth, -0.37); + assert_eq!( + LabelAnchor::matching(Some(cap), &depth).map(|a| a.x), + Some(-0.37) + ); + assert!(LabelAnchor::matching(Some(cap), &[0x11; 32]).is_none()); + assert!(LabelAnchor::matching(None, &depth).is_none()); + } +} diff --git a/d3d12/crates/leonida-hle/src/lib.rs b/d3d12/crates/leonida-hle/src/lib.rs index 57f66b38e6..25af34d907 100644 --- a/d3d12/crates/leonida-hle/src/lib.rs +++ b/d3d12/crates/leonida-hle/src/lib.rs @@ -19,6 +19,8 @@ pub use leonida_gpu::frame_phase; pub mod modules; mod registry; pub mod runtime; +#[cfg(windows)] +pub mod ultrawide; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; diff --git a/d3d12/crates/leonida-hle/src/ultrawide.rs b/d3d12/crates/leonida-hle/src/ultrawide.rs new file mode 100644 index 0000000000..25e49ff4ee --- /dev/null +++ b/d3d12/crates/leonida-hle/src/ultrawide.rs @@ -0,0 +1,302 @@ +//! UI state and checked viewport adjustments for the retail widescreen layout. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant}; + +use leonida_gpu::HudState; +use leonida_loader::callhook::{self, Regs}; +use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const UI_FRONTEND_ACTIVE: usize = 0x0984_8c01; +const USER_PAUSE: usize = 0x0abb_e2e0; +const MENU_PAUSE: usize = 0x0abb_e2e1; +const EXTRA_PAUSE: usize = 0x0745_3ed0; +const LOADING_MOVIE_READY: usize = 0x074e_0073; +const LOADING_VIEWPORT_CALL: usize = 0x0404_21ab; +const SET_MOVIE_VIEWPORT: usize = 0x013c_ba40; +const LOADING_CANVAS_WIDTH: u32 = 3840; +static LOADING_LAYOUT_WIDTH: AtomicU32 = AtomicU32::new(LOADING_CANVAS_WIDTH); +const UI_MODAL_MGR: usize = 0x09e2_4df8; +const LOCAL_PLAYER: usize = 0x0ab5_6e38; +const UI_HUD_MGR: usize = 0x0999_abd8; +const HUD_STD_STATE_VFN: usize = 0x04df_8430; +const HUD_QUICK_SELECT: u32 = 0x2c79_0e9c; +const HUD_PAUSE_MENU: u32 = 0x01c4_6ad2; +const HUD_SHOP_MENU: u32 = 0x4ce0_2008; +static LAST_MAP_CURSOR: Mutex> = Mutex::new(None); + +fn read(base: usize, offset: usize) -> Option<[u8; N]> { + let at = base.checked_add(offset)?; + let mut bytes = [0; N]; + // SAFETY: Windows checks the source mapping and copies at most N bytes. + let ok = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + at as *const _, + bytes.as_mut_ptr().cast(), + N, + std::ptr::null_mut(), + ) + }; + (ok != 0).then_some(bytes) +} + +fn pointer(base: usize, offset: usize) -> Option { + let address = usize::from_le_bytes(read(base, offset)?); + (address >= 0x1_0000 && (address >> 47) == 0 && address.is_multiple_of(4)).then_some(address) +} + +fn active_component(base: usize, hash: u32, transitions: bool) -> Option { + let manager = pointer(base, UI_HUD_MGR)?; + let entries = pointer(manager, 0x20)?; + let count = usize::from(u16::from_le_bytes(read(manager, 0x28)?)); + if !(1..=4096).contains(&count) { + return None; + } + let mut lo = 0; + let mut hi = count; + while lo < hi { + let mid = lo + (hi - lo) / 2; + let entry = entries.checked_add(mid * 16)?; + match u32::from_le_bytes(read(entry, 0)?).cmp(&hash) { + std::cmp::Ordering::Less => lo = mid + 1, + std::cmp::Ordering::Greater => hi = mid, + std::cmp::Ordering::Equal => { + let component = pointer(entry, 8)?; + let vtable = pointer(component, 0)?; + if pointer(vtable, 0x28)? != base + HUD_STD_STATE_VFN { + return Some(false); + } + let [state] = read(component, 0x3a)?; + if transitions { + return Some(matches!(state, 2 | 3)); + } + let flags = u32::from_le_bytes(read(component, 0x34)?); + return Some( + state == 2 + && read(component, 0x38)? == [0, 0] + && (flags & 2 != 0 || flags & 1 == 0), + ); + } + } + } + Some(false) +} + +fn title_hud_state() -> HudState { + let Some(base) = crate::runtime::main_image() else { + return HudState::OtherMenu; + }; + if read(base, LOCAL_PLAYER) == Some([0; 8]) { + return HudState::Startup; + } + if read(base, UI_FRONTEND_ACTIVE) != Some([0]) { + return HudState::OtherMenu; + } + if active_component(base, HUD_PAUSE_MENU, true) == Some(true) + || LAST_MAP_CURSOR + .lock() + .is_ok_and(|last| last.is_some_and(|at| at.elapsed() < Duration::from_millis(250))) + { + return HudState::Pause; + } + if active_component(base, HUD_SHOP_MENU, false) == Some(true) { + return HudState::OtherMenu; + } + if active_component(base, HUD_QUICK_SELECT, false) == Some(true) { + return HudState::Gameplay; + } + if read(base, EXTRA_PAUSE) != Some([0; 4]) + || pointer(base, UI_MODAL_MGR).is_some_and(|modal| read(modal, 0x14) != Some([0; 4])) + { + return HudState::OtherMenu; + } + if read(base, USER_PAUSE) == Some([0]) && read(base, MENU_PAUSE) == Some([0]) { + HudState::Gameplay + } else { + HudState::Pause + } +} + +fn loading_ui_active() -> bool { + let Some(base) = crate::runtime::main_image() else { + return false; + }; + let phase = read(base, EXTRA_PAUSE).map(u32::from_le_bytes); + phase == Some(3) + || (phase == Some(2) && read(base, LOADING_MOVIE_READY).is_some_and(|[ready]| ready != 0)) +} + +const MAP_CENTERED_WIDTH: u32 = 3840; +const MAP_CURSOR_PIXELS_CALL: usize = 0x0232_46fc; +const MAP_CURSOR_PIXELS: usize = 0x0232_4770; +const MAP_SNAP_CALL: usize = 0x0232_3009; +const MAP_SNAP_TARGET: usize = 0x0232_4d50; +const MAP_CURSOR_RAY: [(usize, usize); 4] = [ + (0x0232_4f38, 0x02a7_eb60), // Destination. + (0x0232_3a05, 0x0232_41d0), // Pin selection. + (0x0232_4198, 0x022d_a890), // Interior selection. + (0x0232_4757, 0x02a7_ebe0), // Region selection cursor cache. +]; +const MAP_ZOOM_CURSOR_READ: usize = 0x0232_4356; +static MAP_LAYOUT_WIDTH: AtomicU32 = AtomicU32::new(MAP_CENTERED_WIDTH); + +fn map_cursor_gutter(layout_width: u32) -> f32 { + layout_width.saturating_sub(MAP_CENTERED_WIDTH) as f32 * 0.5 +} + +unsafe extern "C" fn map_cursor_before(regs: *mut Regs) { + let width = MAP_LAYOUT_WIDTH.load(Ordering::Relaxed); + if let Ok(mut last) = LAST_MAP_CURSOR.lock() { + *last = Some(Instant::now()); + } + // SAFETY: r8 points to the stack copy of the normalized cursor used for the widget. + unsafe { + let x = (*regs).r8 as *mut f32; + *x -= map_cursor_gutter(width) / width as f32; + } +} + +unsafe extern "C" fn map_cursor_ray_before(regs: *mut Regs) { + // SAFETY: these sites put a writable copy of the widget position in rdx. + unsafe { + let x = (*regs).rdx as *mut f32; + *x += map_cursor_gutter(MAP_LAYOUT_WIDTH.load(Ordering::Relaxed)); + } +} + +unsafe extern "C" fn map_snap_before(regs: *mut Regs) { + // SAFETY: the snap query puts its writable copy of the widget position in r8. + unsafe { + let x = (*regs).r8 as *mut f32; + *x += map_cursor_gutter(MAP_LAYOUT_WIDTH.load(Ordering::Relaxed)); + } +} + +/// # Safety +/// The retail Series X 1.0.2.1 image must be mapped with no title thread running. +unsafe fn install_wide_map_cursor(base: usize, layout_width: u32) -> Result<(), String> { + MAP_LAYOUT_WIDTH.store(layout_width, Ordering::Relaxed); + // SAFETY: the retail sites use checked calls and their coordinate pairs are stack locals. + unsafe { + (|| { + callhook::redirect_call( + base + MAP_CURSOR_PIXELS_CALL, + base + MAP_CURSOR_PIXELS, + map_cursor_before, + )?; + callhook::redirect_call( + base + MAP_SNAP_CALL, + base + MAP_SNAP_TARGET, + map_snap_before, + )?; + for (site, target) in MAP_CURSOR_RAY { + callhook::redirect_call(base + site, base + target, map_cursor_ray_before)?; + } + // Zoom uses the saved normalized cursor at +A8, before the widget gutter is applied. + callhook::patch_checked( + base + MAP_ZOOM_CURSOR_READ, + 0x3318_07a5_c4bb_0ef6, + [ + 0xc5, 0xfb, 0x10, 0x87, 0xa8, 0, 0, 0, 0x0f, 0x1f, 0x84, 0, 0, 0, 0, 0, + ], + ) + })() + } + .map_err(|error| error.to_string())?; + tracing::info!( + layout_width, + "positioning the map cursor relative to its display area" + ); + Ok(()) +} + +fn loading_viewport_x(layout_width: u32, surface: [f32; 2], absolute: bool) -> Option<(f32, f32)> { + if surface != [layout_width as f32, 2160.0] { + return None; + } + let units = if absolute { 1.0 } else { layout_width as f32 }; + let left = (layout_width - LOADING_CANVAS_WIDTH) as f32 * 0.5; + Some((left / units, LOADING_CANVAS_WIDTH as f32 / units)) +} + +unsafe extern "C" fn loading_viewport_before(regs: *mut Regs) { + // The same initializer also opens movies drawn into offscreen targets. + unsafe { + let movie = (*regs).rcx as *mut u8; + let absolute = *movie.add(0xcc) & 4 != 0; + let surface = movie.add(0xa0).cast::<[f32; 2]>().read(); + if let Some((left, width)) = loading_viewport_x( + LOADING_LAYOUT_WIDTH.load(Ordering::Relaxed), + surface, + absolute, + ) { + *movie.add(0x90).cast::() = left; + *movie.add(0xa8).cast::() = width; + } + } +} + +/// # Safety +/// The retail Series X 1.0.2.1 image must be mapped with no title thread running. +unsafe fn install_loading_viewport(base: usize, layout_width: u32) -> Result<(), String> { + if layout_width <= LOADING_CANVAS_WIDTH + || std::env::var_os("LEONIDA_UI_LETTERBOX").is_some_and(|value| value == "0") + { + return Ok(()); + } + LOADING_LAYOUT_WIDTH.store(layout_width, Ordering::Relaxed); + unsafe { + callhook::redirect_call( + base + LOADING_VIEWPORT_CALL, + base + SET_MOVIE_VIEWPORT, + loading_viewport_before, + ) + } + .map_err(|error| error.to_string())?; + leonida_gpu::set_loading_ui_probe(loading_ui_active); + Ok(()) +} + +/// # Safety +/// The verified retail Series X image must remain mapped while rendering. +pub unsafe fn install(base: usize, output: (u32, u32), layout: (u32, u32)) -> Result<(), String> { + if !(3841..=7680).contains(&layout.0) || layout.1 != 2160 { + return Err("unsupported ultrawide UI layout".into()); + } + // SAFETY: the caller checked the executable identity and no title thread runs yet. + unsafe { + install_wide_map_cursor(base, layout.0)?; + install_loading_viewport(base, layout.0)?; + } + leonida_gpu::set_world_marker_output(output, layout); + leonida_gpu::set_gameplay_hud_probe(title_hud_state); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cursor_widget_and_map_queries_share_the_wide_gutter() { + assert_eq!(map_cursor_gutter(3840), 0.0); + assert_eq!(map_cursor_gutter(5160), 660.0); + assert_eq!(map_cursor_gutter(7680), 1920.0); + } + + #[test] + fn viewport_letterboxes_only_the_wide_loading_surface() { + assert_eq!( + loading_viewport_x(7680, [7680.0, 2160.0], false), + Some((0.25, 0.5)) + ); + assert_eq!( + loading_viewport_x(5160, [5160.0, 2160.0], true), + Some((660.0, 3840.0)) + ); + assert_eq!(loading_viewport_x(7680, [3840.0, 2160.0], true), None); + } +} diff --git a/d3d12/crates/leonida-loader/src/callhook.rs b/d3d12/crates/leonida-loader/src/callhook.rs new file mode 100644 index 0000000000..0faa02e377 --- /dev/null +++ b/d3d12/crates/leonida-loader/src/callhook.rs @@ -0,0 +1,194 @@ +//! Redirects a checked call site to a Win64 callback before the original target. + +use anyhow::{Context, Result, bail, ensure}; +use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; +use windows_sys::Win32::System::Memory::{ + PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// The saved Win64 volatile registers and return address. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct Regs { + pub r11: u64, + pub r10: u64, + pub r9: u64, + pub r8: u64, + pub rdx: u64, + pub rcx: u64, + pub rax: u64, + pub flags: u64, + pub ret: u64, +} + +/// Called before the hooked code, with the saved registers. +pub type Before = unsafe extern "C" fn(*mut Regs); +/// Whether `code` (5 bytes at address `site`) is `call target`. +fn is_call_to(code: &[u8], site: usize, target: usize) -> bool { + code.len() >= 5 + && code[0] == 0xE8 + && (site as i64 + 5 + i64::from(i32::from_le_bytes([code[1], code[2], code[3], code[4]]))) + as usize + == target +} + +/// Preserves Win64 volatile registers and flags across the callback. +fn before_thunk(before: usize, resume: usize) -> Vec { + let mut c = vec![ + 0x9C, 0x50, 0x51, 0x52, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41, 0x53, + ]; + c.extend([0x48, 0x81, 0xEC, 0x88, 0, 0, 0]); // sub rsp, 0x88 + for x in 0..6u8 { + c.extend([0xF3, 0x0F, 0x7F, 0x44 | x << 3, 0x24, 0x20 + 0x10 * x]); // movdqu [rsp+..], xmmN + } + c.extend([0x48, 0x8D, 0x8C, 0x24, 0x88, 0, 0, 0]); // lea rcx, [rsp+0x88]: the saved registers + c.extend([0x48, 0xB8]); + c.extend((before as u64).to_le_bytes()); // mov rax, before + c.extend([0xFF, 0xD0]); // call rax + for x in 0..6u8 { + c.extend([0xF3, 0x0F, 0x6F, 0x44 | x << 3, 0x24, 0x20 + 0x10 * x]); // movdqu xmmN, [rsp+..] + } + c.extend([0x48, 0x81, 0xC4, 0x88, 0, 0, 0]); // add rsp, 0x88 + c.extend([ + 0x41, 0x5B, 0x41, 0x5A, 0x41, 0x59, 0x41, 0x58, 0x5A, 0x59, 0x58, 0x9D, + ]); + c.extend([0xFF, 0x25, 0, 0, 0, 0]); // jmp [rip] + c.extend((resume as u64).to_le_bytes()); + c +} + +/// Our code on a fresh page near `near_to`, made executable. +fn place(near_to: usize, code: &[u8]) -> Result { + if code.len() > 4096 { + bail!("hook thunk too large"); + } + let page = crate::tls::near(near_to, 0)?; + // SAFETY: a fresh writable page of ours, 4096 bytes. + unsafe { std::ptr::copy_nonoverlapping(code.as_ptr(), page, code.len()) }; + let mut old = 0; + // SAFETY: our page. + if unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 { + bail!( + "VirtualProtect(hook thunk) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: this region is our new executable thunk page. + ensure!( + unsafe { FlushInstructionCache(GetCurrentProcess(), page as _, code.len()) } != 0, + "could not flush the callback instruction cache" + ); + Ok(page as usize) +} + +/// Writes `bytes` over the code at `at`. +/// +/// # Safety +/// `at..at + bytes.len()` is mapped code no thread is running. +unsafe fn write_code(at: usize, bytes: &[u8]) -> Result<()> { + let mut old = 0; + // SAFETY: the caller's range. + if unsafe { VirtualProtect(at as _, bytes.len(), PAGE_EXECUTE_READWRITE, &mut old) } == 0 { + bail!( + "VirtualProtect(code) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: writable now; see the caller's promise. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), at as *mut u8, bytes.len()); + ensure!( + VirtualProtect(at as _, bytes.len(), old, &mut old) != 0, + "could not restore the title code protection" + ); + ensure!( + FlushInstructionCache(GetCurrentProcess(), at as _, bytes.len()) != 0, + "could not flush the title instruction cache" + ); + } + Ok(()) +} + +fn rel32(from_end: usize, to: usize) -> Result<[u8; 4]> { + let rel = to as i64 - from_end as i64; + match i32::try_from(rel) { + Ok(r) => Ok(r.to_le_bytes()), + Err(_) => bail!("hook thunk out of rel32 reach"), + } +} + +/// Redirects the `call target` at `site` to a thunk that runs `before`, +/// then `target`. Refuses (and changes nothing) unless the 5 bytes there +/// are that call. +/// +/// # Safety +/// `site` is mapped title code that no thread runs yet. +pub unsafe fn redirect_call(site: usize, target: usize, before: Before) -> Result<()> { + // SAFETY: the caller's mapped code. + let found = unsafe { std::slice::from_raw_parts(site as *const u8, 5) }; + if !is_call_to(found, site, target) { + bail!("call site {site:#x} does not target {target:#x}"); + } + let thunk = place(site, &before_thunk(before as usize, target))?; + let mut call = vec![0xE8]; + call.extend(rel32(site + 5, thunk)?); + // SAFETY: the caller's promise. + unsafe { write_code(site, &call) } +} + +/// # Safety +/// The mapped site must be readable executable code that has yet to run. +pub unsafe fn patch_checked( + at: usize, + fingerprint: u64, + replacement: [u8; N], +) -> Result<()> { + // SAFETY: the title image remains mapped and has yet to run. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, N) }; + let hash = bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |hash, &byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3) + }); + ensure!(hash == fingerprint, "unexpected title code at {at:#x}"); + unsafe { write_code(at, &replacement) }.context("patching a validated title code site") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_redirect_changes_one_argument_and_runs_the_original_target() { + unsafe extern "C" fn before(regs: *mut Regs) { + // SAFETY: the live thunk supplies its saved register block. + unsafe { (*regs).r8 += 2 }; + } + extern "system" fn target(a: u64, b: u64, c: u64, d: u64) -> u64 { + 1000 * a + 100 * b + 10 * c + d + } + + let target = target as *const () as usize; + let page = crate::tls::near(target, 0).unwrap(); + let base = page as usize; + let save_stack = [0x48, 0x83, 0xec, 0x28]; + let mut code = save_stack.to_vec(); + let call = base + code.len(); + code.push(0xe8); + code.extend(rel32(call + 5, target).unwrap()); + code.extend([0x48, 0x83, 0xc4, 0x28, 0xc3]); + // SAFETY: this test owns the fresh page and calls a Win64 stub. + unsafe { + std::ptr::copy_nonoverlapping(code.as_ptr(), page, code.len()); + let mut old = 0; + assert_ne!( + VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), + 0 + ); + let invoke: extern "system" fn(u64, u64, u64, u64) -> u64 = std::mem::transmute(page); + assert!(redirect_call(call, target + 1, before).is_err()); + assert_eq!(invoke(1, 2, 3, 4), 1234); + redirect_call(call, target, before).unwrap(); + assert_eq!(invoke(1, 2, 3, 4), 1254); + } + } +} diff --git a/d3d12/crates/leonida-loader/src/hooks.rs b/d3d12/crates/leonida-loader/src/hooks.rs index 4970ff9cfc..d18627f6d7 100644 --- a/d3d12/crates/leonida-loader/src/hooks.rs +++ b/d3d12/crates/leonida-loader/src/hooks.rs @@ -125,15 +125,17 @@ fn parse_output(text: &str) -> Option<(u32, u32)> { /// The bytes the title reserves for its two scanout buffers of `width` x `height`: RGBA8 in the console's 64 KiB /// tiling (128x128 texels a tile), together rounded up to 2 MiB. 0x4000000 for 3840x2160, the title's own figure. fn scanout_pool_bytes(width: u32, height: u32) -> u32 { - const TWO_MIB: u64 = 2 << 20; - let tiles = u64::from(width.div_ceil(128)) * u64::from(height.div_ceil(128)); - ((tiles * 65536 * 2).div_ceil(TWO_MIB) * TWO_MIB) as u32 + display_pair_bytes((width, height)).next_multiple_of(2 << 20) +} + +fn display_pair_bytes((width, height): (u32, u32)) -> u32 { + width.div_ceil(128) * height.div_ceil(128) * 65536 * 2 } /// The patches for an output of `width` x `height` in place of 3840x2160: the mode row, the scanout /// reservation that fits it, and the Settings viewport pointed at the mode row (it reads a pair of its own /// otherwise). All three or none ([`apply_all`]). -fn output_patches(width: u32, height: u32) -> Vec { +pub(super) fn output_patches(width: u32, height: u32) -> Vec { let pair = |w: u32, h: u32| [w.to_le_bytes(), h.to_le_bytes()].concat(); let reservation = |bytes: u32| [&[0xB9][..], &bytes.to_le_bytes()].concat(); let viewport = (OUTPUT_ROW as i64 - (SETTINGS_VIEWPORT as i64 + 8)) as i32; @@ -159,12 +161,21 @@ fn output_patches(width: u32, height: u32) -> Vec { ] } +/// The legacy UI allocates two canvas surfaces in the scanout pool. +pub(super) fn use_legacy_ui(patches: &mut Vec, output: (u32, u32), layout: (u32, u32)) { + let reservation = (display_pair_bytes(output) + display_pair_bytes(layout)).next_multiple_of(2 << 20); + for patch in patches.iter_mut().filter(|patch| patch.rva == SCANOUT_RESERVATION) { + patch.new[1..].copy_from_slice(&reservation.to_le_bytes()); + } + patches.retain(|patch| patch.rva != SETTINGS_VIEWPORT); +} + /// A patch whose bytes are computed at load time. -struct OwnedPatch { - what: &'static str, - rva: usize, - expect: Vec, - new: Vec, +pub(super) struct OwnedPatch { + pub(super) what: &'static str, + pub(super) rva: usize, + pub(super) expect: Vec, + pub(super) new: Vec, } impl OwnedPatch { @@ -374,12 +385,21 @@ fn parse_scale(text: &str) -> Option { (0.2..=1.0).contains(&v).then_some(v) } +/// Upper bound for the scene when the title chooses the dynamic scale. +pub fn render_scale_cap() -> f32 { + let scale = std::env::var(RENDER_SCALE_ENV).ok().and_then(|v| parse_scale(&v)); + let fsr = std::env::var_os(FSR_UPSCALER_ENV).is_some_and(|v| v == "1") + && !std::env::var_os(OWN_UPSCALER_ENV).is_some_and(|v| v != "0"); + scale.filter(|scale| !fsr || FSR_SCALES.iter().any(|(v, _)| (v - scale).abs() < 1e-3)) + .unwrap_or(1.0) +} + /// Applies the resolution levers asked for in the environment /// ([`RENDER_SCALE_ENV`], [`OWN_UPSCALER_ENV`], [`FSR_UPSCALER_ENV`], [`OUTPUT_ENV`]). Returns how many applied. /// /// # Safety /// As `disarm_watchdog`. -pub(crate) unsafe fn resolution_levers(base: usize, hash: &blake3::Hash) -> usize { +pub(crate) unsafe fn resolution_levers(base: usize, hash: &blake3::Hash, native_output_patched: bool) -> usize { let scale = std::env::var(RENDER_SCALE_ENV).ok().filter(|v| !v.trim().is_empty()); let min = std::env::var(RENDER_SCALE_MIN_ENV).ok().filter(|v| !v.trim().is_empty()); let pinned = scale.as_deref().and_then(parse_scale).is_some(); @@ -398,7 +418,7 @@ pub(crate) unsafe fn resolution_levers(base: usize, hash: &blake3::Hash) -> usiz return 0; } let mut applied = 0; - if let Some(text) = output { + if let Some(text) = output.filter(|_| !native_output_patched) { match parse_output(&text) { // The title's own output. Some((3840, 2160)) => {} diff --git a/d3d12/crates/leonida-loader/src/lib.rs b/d3d12/crates/leonida-loader/src/lib.rs index b41ca1945b..a005780081 100644 --- a/d3d12/crates/leonida-loader/src/lib.rs +++ b/d3d12/crates/leonida-loader/src/lib.rs @@ -21,6 +21,8 @@ //! point on a thread with the stack size the image asks for; from then //! on, pass every thread start and end on to the attached images. +#[cfg(windows)] +pub mod callhook; #[cfg(windows)] mod console_insn; mod crash; @@ -60,6 +62,12 @@ pub use crash::{ }; #[cfg(all(windows, feature = "diagnostics"))] pub use crash::save_on_crash; +#[cfg(windows)] +pub use hooks::render_scale_cap; +#[cfg(windows)] +mod native_output; +#[cfg(windows)] +pub use native_output::{NATIVE_OUTPUT_RETAIL_HASH, prepare_native_output}; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/d3d12/crates/leonida-loader/src/native_output.rs b/d3d12/crates/leonida-loader/src/native_output.rs new file mode 100644 index 0000000000..e587523e47 --- /dev/null +++ b/d3d12/crates/leonida-loader/src/native_output.rs @@ -0,0 +1,163 @@ +use anyhow::{Context, Result, ensure}; + +use crate::PreparedImage; + +pub const NATIVE_OUTPUT_RETAIL_HASH: &str = + "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93"; + +/// The shared video-settings copy used at startup and for later settings changes. +const SETTINGS_COPY: usize = 0x01d7_0b98; +const STOCK_SETTINGS_COPY: &str = + "9d8829e6720f7624fd7004b8905ccfd6e1d9c6610ec186100f8350e091344038"; +const SETTINGS_COPY_LEN: usize = 11; +/// Free padding within the image executable section. +const SETTINGS_CAVE: usize = 0x055f_f285; +const SETTINGS_CAVE_LEN: usize = 59; + +/// Writes separate layout and output sizes into each video settings copy. +fn settings_cave_bytes( + output: (u32, u32), + layout: (u32, u32), + stock_copy: &[u8; SETTINGS_COPY_LEN], +) -> Result> { + let pair = |w: u32, h: u32| (u64::from(h) << 32 | u64::from(w)).to_le_bytes(); + let mut cave = Vec::with_capacity(SETTINGS_CAVE_LEN); + cave.extend_from_slice(&stock_copy[..8]); + cave.extend_from_slice(&[0xc6, 0x86, 0x38, 0x06, 0, 0, 0x01]); + cave.extend_from_slice(&[0x48, 0xb8]); + cave.extend_from_slice(&pair(layout.0, layout.1)); + cave.extend_from_slice(&[0x48, 0x89, 0x86, 0x3c, 0x06, 0, 0]); + cave.extend_from_slice(&[0x48, 0xb8]); + cave.extend_from_slice(&pair(output.0, output.1)); + cave.extend_from_slice(&[0x48, 0x89, 0x86, 0x54, 0x06, 0, 0]); + cave.extend_from_slice(&stock_copy[8..]); + let back = SETTINGS_COPY as i64 + SETTINGS_COPY_LEN as i64 + - (SETTINGS_CAVE as i64 + cave.len() as i64 + 5); + cave.push(0xe9); + cave.extend_from_slice(&i32::try_from(back)?.to_le_bytes()); + ensure!( + cave.len() <= SETTINGS_CAVE_LEN, + "settings cave code too long" + ); + Ok(cave) +} + +/// `jmp cave` and NOPs over the copy's last store. +fn settings_copy_bytes() -> Result<[u8; SETTINGS_COPY_LEN]> { + let mut site = [0x90; SETTINGS_COPY_LEN]; + site[0] = 0xe9; + let to = SETTINGS_CAVE as i64 - (SETTINGS_COPY as i64 + 5); + site[1..5].copy_from_slice(&i32::try_from(to)?.to_le_bytes()); + Ok(site) +} + +/// Prepares the display before mapping so its whole patch is validated first. +pub fn prepare_native_output( + image: &mut PreparedImage, + output: (u32, u32), + wide_hud: bool, +) -> Result> { + ensure!( + image.original_hash.to_hex().as_str() == NATIVE_OUTPUT_RETAIL_HASH, + "native ultrawide requires the Series X 1.0.2.1 retail executable" + ); + let (width, height) = output; + ensure!( + matches!(output, (3440, 1440) | (3840, 1080) | (5120, 1440)), + "unknown native ultrawide output {width}x{height}" + ); + let layout = wide_hud.then(|| ((width * 2160 + height / 2) / height, 2160)); + let mut patches = super::hooks::output_patches(width, height); + if let Some(layout) = layout { + super::hooks::use_legacy_ui(&mut patches, output, layout); + let copy: [u8; SETTINGS_COPY_LEN] = + field(image, SETTINGS_COPY, SETTINGS_COPY_LEN)?.try_into()?; + ensure!( + blake3::hash(©).to_hex().as_str() == STOCK_SETTINGS_COPY, + "unexpected video-settings copy" + ); + let mut cave = vec![0xcc; SETTINGS_CAVE_LEN]; + let code = settings_cave_bytes(output, layout, ©)?; + cave[..code.len()].copy_from_slice(&code); + patches.extend([ + super::hooks::OwnedPatch { + what: "wide UI layout", + rva: SETTINGS_CAVE, + expect: vec![0xcc; SETTINGS_CAVE_LEN], + new: cave, + }, + super::hooks::OwnedPatch { + what: "video-settings copy", + rva: SETTINGS_COPY, + expect: copy.to_vec(), + new: settings_copy_bytes()?.to_vec(), + }, + ]); + } + let mut writes = Vec::with_capacity(patches.len()); + for patch in patches { + let at = offset(image, patch.rva)?; + ensure!( + image.bytes.get(at..at + patch.expect.len()) == Some(patch.expect.as_slice()), + "unexpected bytes for {}", + patch.what + ); + writes.push((at, patch.new)); + } + for (at, bytes) in writes { + image.bytes[at..at + bytes.len()].copy_from_slice(&bytes); + } + image.native_output_patched = true; + Ok(layout) +} + +fn offset(image: &PreparedImage, rva: usize) -> Result { + image + .info + .rva_to_file_offset(rva as u32) + .map(|at| at as usize) + .context("native display field missing") +} + +fn field(image: &PreparedImage, rva: usize, len: usize) -> Result<&[u8]> { + let at = offset(image, rva)?; + image + .bytes + .get(at..at + len) + .context("incomplete native display field") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_output_patches_each_retail_profile() { + let Some(dir) = std::env::var_os("LEONIDA_GAME_DIR") else { + return; + }; + let bytes = + std::fs::read(std::path::Path::new(&dir).join("game_scarlett_master.exe")).unwrap(); + for (output, layout) in [ + ((3440, 1440), (5160, 2160)), + ((3840, 1080), (7680, 2160)), + ((5120, 1440), (7680, 2160)), + ] { + for wide_hud in [false, true] { + let mut image = crate::prepare(&bytes).unwrap(); + let expected_layout = wide_hud.then_some(layout); + assert_eq!( + prepare_native_output(&mut image, output, wide_hud).unwrap(), + expected_layout + ); + let mode = crate::hooks::output_patches(output.0, output.1).remove(0); + assert_eq!(field(&image, mode.rva, mode.new.len()).unwrap(), mode.new); + assert_eq!( + field(&image, SETTINGS_COPY, 1).unwrap()[0] == 0xe9, + wide_hud + ); + assert!(prepare_native_output(&mut image, output, wide_hud).is_err()); + } + } + } +} diff --git a/d3d12/crates/leonida-loader/src/prepare.rs b/d3d12/crates/leonida-loader/src/prepare.rs index f8b2ecf248..9f2cbb43fd 100644 --- a/d3d12/crates/leonida-loader/src/prepare.rs +++ b/d3d12/crates/leonida-loader/src/prepare.rs @@ -22,6 +22,8 @@ pub struct PreparedImage { pub bytes: Vec, /// BLAKE3 of the original bytes: identifies the exact build. pub original_hash: blake3::Hash, + #[cfg(windows)] + pub(crate) native_output_patched: bool, } impl PreparedImage { @@ -107,6 +109,8 @@ pub fn prepare(original: &[u8]) -> Result { } Ok(PreparedImage { + #[cfg(windows)] + native_output_patched: false, info, bytes, original_hash: blake3::hash(original), diff --git a/d3d12/crates/leonida-loader/src/tls.rs b/d3d12/crates/leonida-loader/src/tls.rs index 83f7ad1427..ab6e1c497c 100644 --- a/d3d12/crates/leonida-loader/src/tls.rs +++ b/d3d12/crates/leonida-loader/src/tls.rs @@ -140,7 +140,7 @@ fn thunks(block: *mut u8, index: u32) -> Result { /// One writable page within `rel32` reach of `[base, base + size)`. Leaked: /// title code calls into it for the life of the process. -fn near(base: usize, size: usize) -> Result<*mut u8> { +pub(crate) fn near(base: usize, size: usize) -> Result<*mut u8> { const GRANULE: usize = 0x1_0000; // The search spans 1 GiB each side, so every call site stays in reach. if size >= 1 << 30 { diff --git a/d3d12/crates/leonida-loader/src/windows.rs b/d3d12/crates/leonida-loader/src/windows.rs index d1ee577a8b..7819d22488 100644 --- a/d3d12/crates/leonida-loader/src/windows.rs +++ b/d3d12/crates/leonida-loader/src/windows.rs @@ -95,7 +95,9 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { tracing::info!(applied, "title watchdog hooks ({})", crate::hooks::NO_WATCHDOG_ENV); } // SAFETY: just mapped, and no title code has run. - let levers = unsafe { crate::hooks::resolution_levers(loaded.base(), &prepared.original_hash) }; + let levers = unsafe { + crate::hooks::resolution_levers(loaded.base(), &prepared.original_hash, prepared.native_output_patched) + }; if levers > 0 { tracing::warn!( applied = levers, diff --git a/d3d12/crates/leonida-shader/src/emit/mod.rs b/d3d12/crates/leonida-shader/src/emit/mod.rs index 94af6b9a6b..8332ae5cb1 100644 --- a/d3d12/crates/leonida-shader/src/emit/mod.rs +++ b/d3d12/crates/leonida-shader/src/emit/mod.rs @@ -695,13 +695,25 @@ pub fn translate(container: &[u8]) -> Result { } } +mod wide_shadow_tiles; + +/// Whether the directional-shadow list uses wider tile coordinates. +pub fn wide_shadow_tiles_enabled() -> bool { + wide_shadow_tiles::on() +} + +/// Selects the wide directional-shadow layout before shader translation starts. +pub fn enable_wide_shadow_tiles() { + wide_shadow_tiles::enable(); +} + fn translate_plain(container: &[u8]) -> Result { let c = Container::parse(container)?; let dxil = c .part(FourCC::DXIL) .or(c.part(FourCC::ACCC)) .ok_or(ShaderError::Malformed("no DXIL part"))?; - let native = crate::native_programs(dxil.data)? + let mut native = crate::native_programs(dxil.data)? .into_iter() .find(|p| { matches!( @@ -713,6 +725,9 @@ fn translate_plain(container: &[u8]) -> Result { offset: 0, what: "a container without a vertex, pixel, compute or mesh program", })?; + if wide_shadow_tiles_enabled() { + wide_shadow_tiles::rewrite(c.digest, &mut native); + } let p = crate::spill::build(&native)?; // Structurisation first: tracing per-lane descriptors needs it (its // failure is reported after the earlier stages'). diff --git a/d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs b/d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs new file mode 100644 index 0000000000..bd47c09ecb --- /dev/null +++ b/d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs @@ -0,0 +1,197 @@ +//! Widens the screen-space shadow tile lists of Series X retail 1.0.2.1. + +use crate::native::{HwStage, NativeProgram}; + +#[derive(Clone, Copy)] +enum LayoutEdit { + Write, + ReadScalar, + ReadVector, +} + +use LayoutEdit::{ReadScalar, ReadVector, Write}; + +// The 16-bit tile coordinate comes before the 16 bits of shadow flags. +// A 9/7 X/Y split covers an 8192x2048 scene at 16 pixels per tile. +const SHADERS: &[(u128, LayoutEdit, usize)] = &[ + (0x4cd054fb6dd4c0171b9b10f1e5126d0e, Write, 0x1068), + (0xbf669653117574b9a814f1d5bf88c9fc, Write, 0x1058), + (0xc143868fdbb12d366ee2e01f76e4593d, ReadScalar, 0x00c8), + (0x66c26c6cbf8787eef15c5926f0bd6f91, ReadScalar, 0x00c8), + (0x5e9fcef8720eceee9ccd9aa1ee0b1a8a, ReadScalar, 0x00d0), + (0x1ed7e377d2f4696247fc0ae25b9d0cbc, ReadScalar, 0x00d0), + (0xc50e8d3d5edda2655e8d0b8a6ea28049, ReadScalar, 0x00c8), + (0x80fc24c85c813dec7ee633d1ce451293, ReadScalar, 0x00d0), + (0x83a4b028c7b76fed8d4f68b9717ba901, ReadScalar, 0x00c8), + (0xf7781f7ec21aba9cc2d6a76f79ed98a7, ReadScalar, 0x00c8), + (0x7396cccca7eecbbba3e84e1a6ca79e65, ReadScalar, 0x00c8), + (0x39d2983b3f1a41e093907e218a8d1177, ReadScalar, 0x00cc), + (0x4940669946a742e3391d724f421fcbc7, ReadScalar, 0x00cc), + (0x96145550a0c67e48d3e75f0b06011f7e, ReadScalar, 0x00d4), + (0xf61b48e9df3a10ae2d4fc15fab3c3067, ReadScalar, 0x00d0), + (0x77510107217bb5ff15b06a510ed1ea3c, ReadScalar, 0x00cc), + (0xe387b84fdc0cf22389a6f89195b72176, ReadScalar, 0x00d4), + (0x68bf77351adc9d64acb745b22d0be9d3, ReadScalar, 0x00cc), + (0xd25017ba71c7e190bd130a18ea278f93, ReadScalar, 0x00cc), + (0x9055bac81c0a41bb9c01369c52a78e2d, ReadScalar, 0x00cc), + (0x7b523821b80616110b9c4fb87f30359e, ReadScalar, 0x00cc), + (0xb869670766fae914b3f6dc75388a9da9, ReadVector, 0x00f0), + (0x0bd2422c36a7f49aeb5431e75809be59, ReadScalar, 0x00cc), + (0x61817dce4fa7f8fa8e16633c4f3b605c, ReadVector, 0x00f0), + (0x7e9f4d75149c5673624656daa620e24b, ReadScalar, 0x00ec), + (0xb0e8dc468c126be7fb590f9351e1eeea, ReadScalar, 0x00ec), + (0xa62d11a6bef57571a1ab8e73e10c470b, ReadScalar, 0x00f8), + (0x2b0e7e48c95b73f6783a261cb172ba92, ReadScalar, 0x00f0), + (0x9dd5b69273710bd8f0f65c96d3b9e886, ReadScalar, 0x00e0), + (0x307c85a98da880f25de6f5210506df05, ReadScalar, 0x00ec), + (0x89db99696fc99a870da2b1c2491463d5, ReadScalar, 0x00ec), + (0x9ee0d6f8fd87f7de5b7823ff4eac8989, ReadScalar, 0x00f8), + (0xbb600289cbf42b0a5e98cd9cbeb14044, ReadScalar, 0x00f0), + (0xe31db7cdb04110ddc674fd0ced8e18ae, ReadScalar, 0x00e0), +]; + +static ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(super) fn enable() { + ENABLED.store(true, std::sync::atomic::Ordering::Relaxed); +} + +pub(super) fn on() -> bool { + ENABLED.load(std::sync::atomic::Ordering::Relaxed) +} + +pub(super) fn rewrite(digest: [u8; 16], native: &mut NativeProgram) -> bool { + if native.stage != HwStage::Cs { + return false; + } + let digest = u128::from_be_bytes(digest); + let Some(&(_, edit, offset)) = SHADERS.iter().find(|&&(known, _, _)| known == digest) else { + return false; + }; + let words: &[(usize, u32, u32)] = match edit { + // Shift Y by nine when writing the tile list. + Write => &[(0, 0x3404_0488, 0x3404_0489)], + // The scalar BFE literals encode width in bits 16..23 and start in bits 0..5. + ReadScalar => &[ + (4, 0x0008_0000, 0x0009_0000), + (12, 0x0008_0008, 0x0007_0009), + ], + // The vector BFE has separate inline start and width operands. + ReadVector => &[ + (4, 0x0221_0100, 0x0225_0100), + (12, 0x0221_1100, 0x021d_1300), + ], + }; + if !words.iter().all(|&(at, before, _)| { + native.code.get(offset + at..offset + at + 4) == Some(&before.to_le_bytes()) + }) { + return false; + } + for &(at, _, after) in words { + native.code[offset + at..offset + at + 4].copy_from_slice(&after.to_le_bytes()); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + fn program(digest: u128, words: &[u32]) -> (NativeProgram, usize) { + let &(_, _, offset) = SHADERS.iter().find(|entry| entry.0 == digest).unwrap(); + let mut code = vec![0; offset]; + code.extend(words.iter().flat_map(|word| word.to_le_bytes())); + ( + NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 32, + layout: Vec::new(), + used: Vec::new(), + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 0, + threads: [16, 16, 1], + }), + code, + }, + offset, + ) + } + + fn word(native: &NativeProgram, offset: usize) -> u32 { + u32::from_le_bytes(native.code[offset..offset + 4].try_into().unwrap()) + } + + fn inline_constant(operand: u32) -> u32 { + (operand & 0x1ff) - 0x80 + } + + #[test] + fn shadow_lists_address_the_full_ultrawide_scene() { + let writers: &[u128] = &[ + 0x4cd054fb6dd4c0171b9b10f1e5126d0e, + 0xbf669653117574b9a814f1d5bf88c9fc, + ]; + let scalar = 0xc143868fdbb12d366ee2e01f76e4593d_u128; + let vector = 0xb869670766fae914b3f6dc75388a9da9_u128; + let (mut raster, r) = program( + scalar, + &[0x9388_ff07, 0x0008_0000, 0x938a_ff07, 0x0008_0008], + ); + let (mut rt, t) = program( + vector, + &[0xd548_0003, 0x0221_0100, 0xd548_0007, 0x0221_1100], + ); + assert!(rewrite(scalar.to_be_bytes(), &mut raster)); + assert!(rewrite(vector.to_be_bytes(), &mut rt)); + let scalar_field = |at| { + let literal = word(&raster, r + at); + (literal & 31, literal >> 16 & 0x7f) + }; + let vector_field = |at| { + let operands = word(&rt, t + at); + ( + inline_constant(operands >> 9), + inline_constant(operands >> 18), + ) + }; + let extract = |packed, (start, width)| (packed >> start) & ((1_u32 << width) - 1); + for &writer in writers { + let (mut native, w) = program(writer, &[0x3404_0488, 0x3406_0690]); + assert!(rewrite(writer.to_be_bytes(), &mut native)); + let shift = inline_constant(word(&native, w)); + let flag_shift = inline_constant(word(&native, w + 4)); + for (x, y) in [(0, 0), (255, 89), (256, 89), (319, 89), (511, 127)] { + let flags = 0xa55a_u32; + let packed = flags << flag_shift | y << shift | x; + assert_eq!( + ( + extract(packed, scalar_field(4)), + extract(packed, scalar_field(12)) + ), + (x, y) + ); + assert_eq!( + ( + extract(packed, vector_field(4)), + extract(packed, vector_field(12)) + ), + (x, y) + ); + assert_eq!(packed >> 16, flags); + } + } + } + + #[test] + fn a_changed_reader_cannot_be_partly_rewritten() { + let digest = 0xc143868fdbb12d366ee2e01f76e4593d_u128; + let (mut native, r) = program( + digest, + &[0x9388_ff07, 0x0008_0000, 0x938a_ff07, 0x0008_0009], + ); + assert!(!rewrite(digest.to_be_bytes(), &mut native)); + assert_eq!(word(&native, r + 4), 0x0008_0000); + assert_eq!(word(&native, r + 12), 0x0008_0009); + } +} diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 26862777f5..8be6005162 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -31,7 +31,9 @@ # -FidelityFxDir the folder with AMD's two DLLs, if not amd-sdk\FidelityFX\bin # -Fullscreen the game's window borderless over its whole monitor from the start (Alt+Enter switches back and # forth while it runs, with or without this; also FULLSCREEN in the F1 menu) -# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9. +# -Ultrawide native Series X output: off, 3440x1440, 3840x1080, or 5120x1440. +# -HudPosition center or edges for the native ultrawide HUD. +# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). # -PresentScale fit (the 16:9 picture centred, black bars beside it: the default with -Aspect) or stretch # -Quality fewer stretched/jumping bodies, slower (relay stage 1, no card steps) # -RayTracing the title's real ray tracing (the structure builder runs). Shaders build for minutes the @@ -78,6 +80,8 @@ param( [switch]$FsrFrameGen, [string]$FidelityFxDir, [switch]$Fullscreen, + [ValidateSet('off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide, + [ValidateSet('center', 'edges')][string]$HudPosition, [ValidatePattern('^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$')][string]$Aspect, [ValidateSet('fit', 'stretch')][string]$PresentScale, [string]$Adapter, @@ -424,6 +428,8 @@ if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -no } } if ($Fullscreen) { $settings.LEONIDA_FULLSCREEN = '1' } +if ($Ultrawide) { $settings.LEONIDA_NATIVE_ULTRAWIDE = $Ultrawide } +if ($HudPosition) { $settings.LEONIDA_HUD_POSITION = $HudPosition } if ($Aspect) { $settings.LEONIDA_ASPECT = $Aspect } if ($PresentScale) { $settings.LEONIDA_PRESENT_SCALE = $PresentScale } if ($StreamlineDir) { $settings.LEONIDA_STREAMLINE_DIR = $StreamlineDir } @@ -542,6 +548,8 @@ $switchSettings = @{ NoFrameGen = 'LEONIDA_FRAME_GEN' FsrFrameGen = 'LEONIDA_FSR_FRAMEGEN', 'LEONIDA_FRAME_GEN' Fullscreen = 'LEONIDA_FULLSCREEN' + Ultrawide = 'LEONIDA_NATIVE_ULTRAWIDE' + HudPosition = 'LEONIDA_HUD_POSITION' Aspect = 'LEONIDA_ASPECT' PresentScale = 'LEONIDA_PRESENT_SCALE' Adapter = 'LEONIDA_ADAPTER' @@ -610,6 +618,29 @@ if (-not $DryRun -and $menu.Count -ne $menuRead) { # Leonida: the runs write down the pipelines the title creates (pipeline/known.rs), for the precompile below. if (-not $NoPrecompile) { $settings.LEONIDA_PIPELINE_BOOK = '1' } foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } +$nativeOutput = "$($settings.LEONIDA_NATIVE_ULTRAWIDE)".Trim().ToLowerInvariant() +if ($nativeOutput -in '', 'off', '0') { + $nativeOutput = '' +} elseif ($nativeOutput -notin '3440x1440', '3840x1080', '5120x1440') { + throw 'Ultrawide must be off, 3440x1440, 3840x1080, or 5120x1440.' +} elseif ($console -ne 'series-x') { + if ($chosenNow.ContainsKey('LEONIDA_NATIVE_ULTRAWIDE')) { throw 'Native ultrawide requires Series X.' } + $settings.Remove('LEONIDA_NATIVE_ULTRAWIDE') + $nativeOutput = '' +} +if ($nativeOutput) { + $settings.Remove('LEONIDA_OUTPUT') + if ($Resolution -or $Lowest) { + $scaleKey = if ($Resolution) { 'LEONIDA_RENDER_SCALE' } else { 'LEONIDA_RENDER_SCALE_MIN' } + if (-not $menu.Contains($scaleKey) -and -not $More.ContainsKey($scaleKey)) { + $nativeHeight = [int]($nativeOutput.Split('x')[1]) + if ([int]$height -gt $nativeHeight -and -not $MenuRestart) { + throw "The selected output is ${nativeHeight}p: ${height}p is above it." + } + $settings[$scaleKey] = [Math]::Min(1.0, [int]$height / $nativeHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) + } + } +} # DLSS only where it can be: a menu choice of it without the files or the build falls back to the stretch # (Series X: to the title's own upscaler, which is sharper than a stretch to 3840x2160). if ($settings.LEONIDA_UPSCALE -eq 'dlss' -and -not $dlssCan) { @@ -693,7 +724,7 @@ $again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build") foreach ($s in 'NoSmoothMotion', 'MotionBlur', 'NoDlss', 'NoFrameGen', 'SeriesX', 'Quality', 'RayTracing', 'FsrFrameGen', 'NoPrecompile', 'Log', 'Capture', 'Fullscreen') { if ($PSBoundParameters[$s]) { $again += "-$s" } } -foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir', 'FidelityFxDir') { +foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'Ultrawide', 'HudPosition', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir', 'FidelityFxDir') { if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" } } if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" } @@ -713,7 +744,7 @@ $picture = if ($own -and $settings.LEONIDA_RENDER_SCALE) { "render scale $($sett elseif ($settings.LEONIDA_UPSCALE -eq 'stretch') { "stretched$scaled (no DLSS)" } elseif ($settings.LEONIDA_RENDER_SCALE) { "render scale $($settings.LEONIDA_RENDER_SCALE), the title's upscaler" } else { "the title's upscaler" } -$extras = '' +$extras = if ($nativeOutput) { ", native output $nativeOutput" } else { '' } if ($settings.LEONIDA_ASPECT) { $extras += ", window $($settings.LEONIDA_ASPECT)" } if ($settings.LEONIDA_FRAME_GEN) { $extras += ", frame generation $($settings.LEONIDA_FRAME_GEN)x" } if ($settings.LEONIDA_FSR_FRAMEGEN -eq '1') { $extras += ', FSR 3 frame generation 2x' } diff --git a/docs/design.md b/docs/design.md index cd7cdba356..e70a1b12c7 100644 --- a/docs/design.md +++ b/docs/design.md @@ -292,6 +292,10 @@ Test shaders are in `\gputest`. ### Translator status and runtime contract +| Direct3D 12 shader rule | Contract and evidence | +|---|---| +| Wide directional shadow lists | The Series X retail shader writers and readers use 9 horizontal and 7 vertical tile-coordinate bits above a 4096-pixel scene width. The rewrite checks both the shader digest and the words it replaces. The wide layout has a separate shader-cache key. Synthetic writer and reader fixtures in `d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs` check the packing and that mismatched words are left intact. | + Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **All 26,503 shaders translate and pass `spirv-val`** (Vulkan 1.2 target, `--allow-offset-texture-operand`): 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry. `spirv/index.json` lists each one's requirements. Output: `\shaders\spirv\` (`.spvasm` + `.spv`), and the log is `\shaders\spirv_run.log`. diff --git a/docs/launcher.md b/docs/launcher.md index d58929f72c..84b0aeaac8 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -24,7 +24,8 @@ Standard library only (`tools/leonida_launcher.py`). - **Settings**: the game folder (a picker, and a check that `game_scarlett_master.exe` is in it), the data folder (empty = the script's default), the mods folder, and the options of `play-d3d12.ps1`: DLSS (off is `-NoDlss`), `-RayTracing`, `-SmoothMotion`, shader preparation (off is `-NoPrecompile`), `-SeriesX`, `-Quality`, `-Resolution` - (default = none), `-Capture`, `-Log`. On Linux only the game folder and Series X are used. + (default = none), `-Capture`, `-Log`. Series X offers native 21:9 and 32:9 outputs and a center or edge HUD + under [Ultrawide](ultrawide.md). Linux supports the game folder, Series X and the native ultrawide options. - **Mods**: the `mods\*\mod.json` of the mods folder (this repository's `mods` unless changed), with the enabled flag written back as the mod manager does it (`tools/leonida_mods.py`); a button opens that manager. - **Saves**: the D3D12 runtime's saves under the data folder, `\data\7952987A\saves\\\~Built on the work of others // The keys are those of the launcher's settings file (tools/leonida_launcher.py). Two controls stand for two keys // each: `console` (series_s, series_x) and `upscale` (dlss, off = -NoDlss, and dlss_mode, -Dlss ). const DEFAULTS = { game_dir: "", data_dir: "", mods_dir: "", background: "", series_s: false, series_x: false, dlss: true, dlss_mode: "", resolution: "", - frame_gen: 0, smooth_motion: false, aspect: "", present_scale: "", ray_tracing: false, quality: false, adapter: "", precompile: true, + frame_gen: 0, smooth_motion: false, aspect: "", present_scale: "", ultrawide: "", hud_position: "", ray_tracing: false, quality: false, adapter: "", precompile: true, capture: false, log: false }; const GROUPS = [ { title: "Folders", fields: [ @@ -432,6 +432,10 @@

Built on the work of others

{ title: "Picture", fields: [ { key: "console", kind: "seg", label: "Console profile", options: [["x", "Series X"], ["s", "Series S"]], help: "Series X renders 2560x1440 for a 3840x2160 output. Series S is lighter: the game's own 720p picture, taken to 1080p." }, + { key: "ultrawide", kind: "seg", label: "Native ultrawide output", when: s => consoleOf(s) === "x", + options: [["", "Default"], ["off", "Off"], ["3440x1440", "3440×1440"], ["3840x1080", "3840×1080"], ["5120x1440", "5120×1440"]] }, + { key: "hud_position", kind: "seg", label: "Ultrawide HUD", when: s => consoleOf(s) === "x" && s.ultrawide !== "off", + options: [["", "Default"], ["center", "Center"], ["edges", "Screen edges"]] }, { key: "upscale", kind: "seg", label: "Upscaling", windows: true, options: [["default", "Default"], ["quality", "DLSS Quality"], ["balanced", "Balanced"], ["performance", "Performance"], ["ultra", "Ultra"], ["off", "Off"]], help: "Default is the game's own upscaler on Series X. A DLSS mode renders at 1440, 1296, 1080 or 720 lines of the 2160. Off stretches the picture." }, @@ -446,8 +450,8 @@

Built on the work of others

{ key: "smooth_motion", kind: "switch", label: "NVIDIA Smooth Motion", windows: true, help: "The driver shows twice the frames (RTX 40 and 50). One start with it ended after 2.4 s on 27 Nov 2026." } ] }, { title: "Window", fields: [ - { key: "aspect", kind: "seg", label: "Shape", windows: true, options: [["", "16:9"], ["21:9", "21:9"], ["32:9", "32:9"], ["auto", "The screen's"]], help: "The game still draws 16:9." }, - { key: "present_scale", kind: "seg", label: "The 16:9 picture in it", windows: true, options: [["", "Centred, black bars"], ["stretch", "Stretched"]], when: s => !!s.aspect }, + { key: "aspect", kind: "seg", label: "Shape", windows: true, options: [["", "Game output"], ["21:9", "21:9"], ["32:9", "32:9"], ["auto", "The screen's"]] }, + { key: "present_scale", kind: "seg", label: "Picture fitting", windows: true, options: [["", "Centred, black bars"], ["stretch", "Stretched"]], when: s => !!s.aspect }, { key: "adapter", kind: "text", label: "Graphics card", windows: true, placeholder: "Windows' default card", help: "On a PC with more than one: part of its name (5060) or its index (#1)." } ] }, { title: "Start", fields: [ @@ -484,6 +488,8 @@

Built on the work of others

if (s.series_x && !s.series_s) a.push("-SeriesX"); if (s.quality) a.push("-Quality"); if (s.resolution && !(s.dlss && s.dlss_mode)) a.push("-Resolution", s.resolution); + if (!s.series_s && s.ultrawide) a.push("-Ultrawide", s.ultrawide); + if (!s.series_s && s.hud_position) a.push("-HudPosition", s.hud_position); if (s.aspect) { a.push("-Aspect", s.aspect); if (s.present_scale) a.push("-PresentScale", s.present_scale); } if (s.adapter.trim()) a.push("-Adapter", s.adapter.trim()); if (s.capture) a.push("-Capture"); @@ -504,7 +510,8 @@

Built on the work of others

: s.resolution ? s.resolution + " lines, game's upscaler" : lighter ? "720p to 1080p" : "1440 lines, game's upscaler"; const frames = (s.frame_gen ? "Frame generation " + s.frame_gen + "x" : "No generated frames") + (s.smooth_motion ? ", Smooth Motion" : ""); - const shape = s.aspect ? (s.aspect === "auto" ? "The screen's shape" : s.aspect) + (s.present_scale === "stretch" ? ", stretched" : ", black bars") : "16:9"; + const nativeOutput = !lighter && s.ultrawide && s.ultrawide !== "off" ? s.ultrawide : ""; + const shape = s.aspect ? (s.aspect === "auto" ? "The screen's shape" : s.aspect) + (s.present_scale === "stretch" ? ", stretched" : ", fitted") : nativeOutput || "Game output"; const start = s.precompile ? "Shaders prepared first" : "Starts at once"; return [["Profile", lighter ? "Series S" : "Series X"], ["Picture", picture + (s.ray_tracing ? ", ray tracing" : "")], ["Frames", frames], ["Window", shape], ["Start", start + (s.capture ? ", F9 captures" : "") + (s.log ? ", log file" : "")]]; diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1 index caaa53736a..a128cce2f6 100644 --- a/scripts/play-d3d12.ps1 +++ b/scripts/play-d3d12.ps1 @@ -27,8 +27,9 @@ # -FsrFrameGen AMD's FSR 3 frame generation instead (2x), for cards without DLSS frame generation (RTX 20 and 30): # needs AMD's two signed FidelityFX DLLs in d3d12\amd-sdk\FidelityFX\bin # -Fullscreen the game's window borderless over its whole monitor (Alt+Enter switches while it runs) -# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). The game still draws 16:9, shown -# centred with black bars (-PresentScale fit, the default with -Aspect) or stretched (stretch). +# -Ultrawide native Series X output: 3440x1440, 3840x1080, 5120x1440, or off. +# -HudPosition center (default) or edges for the ultrawide gameplay HUD. +# -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto. -PresentScale fits or stretches the picture. # -Resolution the older path: the game renders at this height and the title's own upscaler does the rest # -Lowest the lowest height of the title's own dynamic resolution (1080 by default on Series X): it renders # between this and 1440 lines. Same save, RTX 4060 Ti (2026-11-29): 57.0 and 59.6 ms a frame (median, @@ -59,6 +60,8 @@ param( [switch]$MotionBlur, [switch]$FsrFrameGen, [switch]$Fullscreen, + [ValidateSet('', 'off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide = '', + [ValidateSet('', 'center', 'edges')][string]$HudPosition = '', [string]$Aspect = '', [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', [string]$Adapter = '', @@ -76,6 +79,8 @@ param( ) $ErrorActionPreference = "Stop" +$nativeOutputAsked = $Ultrawide -and $Ultrawide -ne 'off' +if ($SeriesS -and $nativeOutputAsked) { throw 'Native ultrawide requires Series X.' } $repo = Split-Path -Parent $PSScriptRoot $runtime = Join-Path $repo "d3d12" $exe = Join-Path $runtime "target\diag\leonida.exe" @@ -103,6 +108,8 @@ if (-not $SeriesS) { } if ($Dlss) { $launch.Dlss = $Dlss } if ($FrameGen) { $launch.FrameGen = $FrameGen } +if ($Ultrawide) { $launch.Ultrawide = $Ultrawide } +if ($HudPosition) { $launch.HudPosition = $HudPosition } if ($Aspect) { $launch.Aspect = $Aspect } if ($PresentScale) { $launch.PresentScale = $PresentScale } foreach ($switch in 'Quality', 'NoDlss', 'NoFrameGen', 'MotionBlur', 'RayTracing', 'Capture', 'NoPrecompile', 'Log', 'DryRun', 'FsrFrameGen', 'Fullscreen') { @@ -117,4 +124,5 @@ if ($PcGlyphs) { $launch.PcGlyphs = (Resolve-Path $PcGlyphs).Path } $launch.Typed = @($PSBoundParameters.Keys | ForEach-Object { switch ($_) { 'SeriesS' { 'SeriesX' } 'SmoothMotion' { 'NoSmoothMotion' } default { $_ } } }) +if ($nativeOutputAsked -and 'SeriesX' -notin $launch.Typed) { $launch.Typed += 'SeriesX' } & (Join-Path $runtime "scripts\play-nvidia.ps1") @launch diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh index 35a44256f3..89ab462c57 100755 --- a/scripts/play-linux.sh +++ b/scripts/play-linux.sh @@ -3,7 +3,7 @@ # the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be # downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's. # -# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] +# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] [--ultrawide 3440x1440] [--hud-position edges] # # Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled # d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix @@ -11,13 +11,36 @@ set -eu if [ $# -lt 1 ]; then - echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x]" >&2 + echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x] [--ultrawide WIDTHxHEIGHT|off] [--hud-position center|edges]" >&2 exit 2 fi game_exe=$1 shift console=series-s -if [ "${1:-}" = "--series-x" ]; then console=series-x; fi +while [ "$#" -gt 0 ]; do + case "$1" in + --series-x) + console=series-x ;; + --ultrawide) + case "${2:-}" in + off|3440x1440|3840x1080|5120x1440) export LEONIDA_NATIVE_ULTRAWIDE="$2" ;; + *) echo "--ultrawide wants off, 3440x1440, 3840x1080, or 5120x1440" >&2; exit 2 ;; + esac + shift ;; + --hud-position) + case "${2:-}" in + center|edges) export LEONIDA_HUD_POSITION="$2" ;; + *) echo "--hud-position wants center or edges" >&2; exit 2 ;; + esac + shift ;; + *) echo "Unknown option: $1" >&2; exit 2 ;; + esac + shift +done +case "${LEONIDA_NATIVE_ULTRAWIDE:-}" in + ''|off|0) ;; + *) [ "$console" = series-x ] || { echo "Native ultrawide requires --series-x" >&2; exit 2; } ;; +esac [ -f "$game_exe" ] || { echo "No $game_exe" >&2; exit 1; } here=$(cd "$(dirname "$0")" && pwd) diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index 4317cd5998..1d654a2fe2 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -112,6 +112,16 @@ def test_linux_command(self): self.assertEqual(command, ["sh", os.path.join("/r", "scripts", "play-linux.sh"), os.path.join("/g", launcher.EXPECTED_EXE), "--series-x"]) + def test_ultrawide_is_forwarded_on_both_platforms_and_skipped_for_series_s(self): + selected = launcher.normalise(settings(ultrawide="5120x1440", hud_position="edges")) + windows = launcher.play_command(selected, windows=True) + linux = launcher.play_command(selected, windows=False) + self.assertEqual(windows[-4:], ["-Ultrawide", "5120x1440", "-HudPosition", "edges"]) + self.assertEqual(linux[-5:], ["--series-x", "--ultrawide", "5120x1440", "--hud-position", "edges"]) + selected["series_s"] = True + self.assertEqual(launcher.switch_args(selected), ["-SeriesS"]) + self.assertEqual(launcher.normalise(settings(ultrawide="8192x2048"))["ultrawide"], "") + def test_no_game_folder_is_refused(self): with self.assertRaises(ValueError): launcher.play_command(settings(game_dir=" "), windows=True) diff --git a/tests/test_win_launchers.py b/tests/test_win_launchers.py index 6dd78303dd..a0cf3f3d66 100644 --- a/tests/test_win_launchers.py +++ b/tests/test_win_launchers.py @@ -85,6 +85,56 @@ def test_nvidia_menu_restart_preserves_motion_blur_switch(self) -> None: for args in restart_args[1:]: self.assertNotRegex(args, r"(?:^| )-MotionBlur(?: |$)") + @unittest.skipUnless(POWERSHELL, "requires PowerShell") + def test_native_ultrawide_preserves_render_height_and_f1_restart_choices(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + scripts = root / "scripts" + scripts.mkdir() + launcher = scripts / NVIDIA_LAUNCHER.name + shutil.copyfile(NVIDIA_LAUNCHER, launcher) + executable = root / "synthetic title.exe" + executable.touch() + (root / "leonida-settings.txt").write_text( + "LEONIDA_NATIVE_ULTRAWIDE=5120x1440\nLEONIDA_HUD_POSITION=center\n", encoding="utf-8", newline="\n" + ) + command = r""" +$ErrorActionPreference = 'Stop' +function Get-CimInstance { + param([string]$ClassName) + if ($ClassName -ne 'Win32_OperatingSystem') { throw "Unexpected CIM query: $ClassName" } + [pscustomobject]@{ BuildNumber = '26100' } +} +$options = @{ + Exe = $env:TEST_NVIDIA_EXE + DryRun = $true + NoDlss = $true + NoFrameGen = $true + NoPrecompile = $true + WindowsBarMB = 0 + SeriesX = $true + Resolution = '1080' + Ultrawide = '3840x1080' + HudPosition = 'edges' +} +& $env:TEST_NVIDIA_LAUNCHER @options +& $env:TEST_NVIDIA_LAUNCHER @options -MenuRestart +""" + env = {name: value for name, value in os.environ.items() if not name.upper().startswith("LEONIDA_")} + env.update(TEST_NVIDIA_LAUNCHER=str(launcher), TEST_NVIDIA_EXE=str(executable)) + result = subprocess.run( + [POWERSHELL, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], + env=env, check=True, capture_output=True, encoding="utf-8", errors="replace", timeout=30, + ) + lines = result.stdout.splitlines() + for key, values in { + "LEONIDA_NATIVE_ULTRAWIDE": ["3840x1080", "5120x1440"], + "LEONIDA_HUD_POSITION": ["edges", "center"], + "LEONIDA_RENDER_SCALE": ["1", "0.75"], + }.items(): + self.assertEqual([line.split("=", 1)[1] for line in lines if line.startswith(key + "=")], values) + self.assertFalse(any(line.startswith("LEONIDA_OUTPUT=") for line in lines)) + def test_static_quoting_and_no_pause_guards(self) -> None: build_txt = BUILD_BAT.read_text(encoding="utf-8") mods_txt = MODS_BAT.read_text(encoding="utf-8") diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 67944f9b81..2b2a4df4a1 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -36,6 +36,8 @@ RESOLUTIONS = ("", "2160", "1440", "1080", "720", "540", "480") DLSS_MODES = ("", "quality", "balanced", "performance", "ultra") FRAME_GEN = (0, 2, 3, 4, 5, 6) +ULTRAWIDE_OUTPUTS = ("", "off", "3440x1440", "3840x1080", "5120x1440") +HUD_POSITIONS = ("", "center", "edges") PRESENT_SCALES = ("", "fit", "stretch") ASPECT = re.compile(r"^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$") # the script's own pattern for -Aspect ADAPTER = re.compile(r"^[\w #.()+-]{0,64}$") # part of a card's name, or # @@ -55,6 +57,8 @@ "series_s": False, # -SeriesS (the script's default is Series X) "dlss_mode": "", # -Dlss , empty = the profile's own path "frame_gen": 0, # -FrameGen , 0 = off + "ultrawide": "", # -Ultrawide , empty = follow the F1 settings + "hud_position": "", # -HudPosition , empty = follow the F1 settings "aspect": "", # -Aspect , empty = 16:9 "present_scale": "", # -PresentScale, with -Aspect; empty = the script's default (fit) "adapter": "", # -Adapter @@ -62,7 +66,7 @@ } # The options with a fixed set of values, and the others whose text has to match a pattern. CHOICES: dict = {"resolution": RESOLUTIONS, "dlss_mode": DLSS_MODES, "frame_gen": FRAME_GEN, - "present_scale": PRESENT_SCALES} + "present_scale": PRESENT_SCALES, "ultrawide": ULTRAWIDE_OUTPUTS, "hud_position": HUD_POSITIONS} PATTERNS: dict = {"aspect": ASPECT, "adapter": ADAPTER} @@ -149,6 +153,11 @@ def switch_args(settings: dict) -> list[str]: args.append("-Quality") if settings["resolution"] and not (settings["dlss"] and settings["dlss_mode"]): args += ["-Resolution", settings["resolution"]] # the script wants it left out with a DLSS mode + if not settings["series_s"]: + if settings["ultrawide"]: + args += ["-Ultrawide", settings["ultrawide"]] + if settings["hud_position"]: + args += ["-HudPosition", settings["hud_position"]] if settings["aspect"]: args += ["-Aspect", settings["aspect"]] if settings["present_scale"]: @@ -173,10 +182,14 @@ def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS) -> l if settings["data_dir"].strip(): command += ["-Data", settings["data_dir"].strip()] return command + switch_args(settings) - # scripts/play-linux.sh takes the executable and --series-x; the other options are Windows launcher switches. command = ["sh", os.path.join(repo, "scripts", "play-linux.sh"), os.path.join(game, EXPECTED_EXE)] - if settings["series_x"]: + if settings["series_x"] or (not settings["series_s"] and settings["ultrawide"] not in ("", "off")): command.append("--series-x") + if not settings["series_s"]: + if settings["ultrawide"]: + command += ["--ultrawide", settings["ultrawide"]] + if settings["hud_position"]: + command += ["--hud-position", settings["hud_position"]] return command @@ -695,9 +708,18 @@ def build_settings(self): ttk.Combobox(options, textvariable=res, state="readonly", width=12, values=["default"] + [r for r in RESOLUTIONS if r]).grid(row=4, column=1, sticky="w", pady=(10, 0)) + for row, key, label, values in ( + (5, "ultrawide", "Series X ultrawide output", ULTRAWIDE_OUTPUTS), + (6, "hud_position", "Ultrawide HUD position", HUD_POSITIONS), + ): + ttk.Label(options, text=label).grid(row=row, column=0, sticky="w", pady=(6, 0)) + var = tk.StringVar(value=self.settings[key] or "default") + self.vars[key] = var + ttk.Combobox(options, textvariable=var, state="readonly", width=12, + values=["default", *values[1:]]).grid(row=row, column=1, sticky="w", pady=(6, 0)) if not WINDOWS: ttk.Label(inner, text="On Linux the launcher starts scripts/play-linux.sh, which takes the " - "game folder and the Series X profile; the other options are for Windows.", + "game folder, Series X profile and ultrawide settings.", style="Muted.TLabel", wraplength=720).grid(row=9, column=0, columnspan=3, sticky="w", pady=(10, 0)) buttons = ttk.Frame(inner) @@ -724,7 +746,7 @@ def check_game(self): def collect_settings(self): for key, var in self.vars.items(): value = var.get() - if key == "resolution": + if key in ("resolution", "ultrawide", "hud_position"): value = "" if value == "default" else value self.settings[key] = value.strip() if isinstance(value, str) else value self.settings = normalise(self.settings) From 0e39338f99c9c01f669125f6ab247bfa5ab5dfae Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:24 +0100 Subject: [PATCH 2/6] Expose Series X aspect ratio and HUD controls --- README.md | 2 +- d3d12/apps/leonida/src/main.rs | 10 ++ d3d12/apps/leonida/src/ultrawide.rs | 25 ++- d3d12/crates/leonida-gpu/src/aspect.rs | 140 ++++++++++++++-- d3d12/crates/leonida-gpu/src/host.rs | 2 +- d3d12/crates/leonida-gpu/src/host/menu.rs | 99 ++++++++++-- d3d12/scripts/play-nvidia.ps1 | 58 +++++-- docs/launcher.md | 5 +- docs/ultrawide.md | 24 +-- launcher/index.html | 38 +++-- launcher/serve.py | 5 +- scripts/play-d3d12.ps1 | 12 +- scripts/play-linux.sh | 28 +++- tests/test_launcher_serve.py | 8 + tests/test_leonida_launcher.py | 51 +++++- tests/test_win_launchers.py | 15 +- tools/leonida_launcher.py | 189 ++++++++++++++++++---- 17 files changed, 577 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index ed62278dff..7ee92cb298 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ Useful switches of `scripts\play-d3d12.ps1` (the launcher's Settings page has th | `-MotionBlur` | the game's own motion blur (off by default: at this frame rate it smears in blocks on camera turns) | | `-FrameGen 2`…`6` with `-Dlss quality\|balanced\|performance\|ultra` | DLSS makes the output and frame generation shows 2 to 6 times the frames | | `-SeriesS` | the lighter Series S profile (720p rendered, DLSS to 1080p) | -| `-Ultrawide 3440x1440\|3840x1080\|5120x1440` | native Series X ultrawide, with `-HudPosition center\|edges` for the gameplay HUD ([details](docs/ultrawide.md)) | +| `-AspectRatio auto\|16:9\|21:9\|32:9` | Series X aspect ratio, with `-HudPosition edges\|center\|off` for ultrawide HUD correction ([details](docs/ultrawide.md)) | | `-RayTracing` | the game's real ray tracing: slower, shaders build for minutes the first time, not with frame generation | | `-NoPrecompile` | start at once, without translating the shaders first | | `-Capture` | F9 in the game saves that frame | diff --git a/d3d12/apps/leonida/src/main.rs b/d3d12/apps/leonida/src/main.rs index 8be7779b5c..3541595661 100644 --- a/d3d12/apps/leonida/src/main.rs +++ b/d3d12/apps/leonida/src/main.rs @@ -47,6 +47,9 @@ struct Cli { #[derive(Subcommand)] enum Command { + /// Resolve a Series X aspect ratio to the native ultrawide output size. + #[cfg(windows)] + AspectOutput { aspect: String }, /// Summarise one PE image: headers, sections, imports, TLS, build id. Inspect { file: PathBuf, @@ -207,6 +210,13 @@ fn main() -> Result<()> { } } match cli.command { + #[cfg(windows)] + Command::AspectOutput { aspect } => { + if let Some((width, height)) = ultrawide::output_for(&aspect)? { + println!("{width}x{height}"); + } + Ok(()) + } Command::Inspect { file, imports, diff --git a/d3d12/apps/leonida/src/ultrawide.rs b/d3d12/apps/leonida/src/ultrawide.rs index e97f743edc..32bf4e2e84 100644 --- a/d3d12/apps/leonida/src/ultrawide.rs +++ b/d3d12/apps/leonida/src/ultrawide.rs @@ -1,4 +1,5 @@ use anyhow::{Context, Result, bail}; +use leonida_gpu::aspect::{self, NATIVE_ASPECT_ENV, NativeAspect}; use leonida_loader::PreparedImage; use crate::heap_budget; @@ -11,19 +12,23 @@ pub(super) struct Profile { impl Profile { pub(super) fn requested() -> Result> { - let Some(value) = std::env::var_os("LEONIDA_NATIVE_ULTRAWIDE") else { - return Ok(None); + let output = if let Some(value) = std::env::var_os("LEONIDA_NATIVE_ULTRAWIDE") { + let value = value + .to_str() + .context("LEONIDA_NATIVE_ULTRAWIDE must name an output preset")?; + parse_output(value)? + } else if let Some(value) = std::env::var_os(NATIVE_ASPECT_ENV) { + output_for(value.to_str().context("invalid Series X aspect ratio")?)? + } else { + None }; - let value = value - .to_str() - .context("LEONIDA_NATIVE_ULTRAWIDE must name an output preset")?; - let Some(output) = parse_output(value)? else { + let Some(output) = output else { return Ok(None); }; Ok(Some(Self { output, scene: maximum_scene(output, leonida_loader::render_scale_cap()), - wide_hud: std::env::var_os("LEONIDA_ULTRAWIDE_HUD").is_none_or(|value| value != "0"), + wide_hud: aspect::hud_position() != "off", })) } @@ -60,6 +65,12 @@ impl Profile { } } +pub(super) fn output_for(value: &str) -> Result> { + let aspect = NativeAspect::parse(value) + .with_context(|| format!("{NATIVE_ASPECT_ENV} wants auto, 16:9, 21:9, or 32:9"))?; + Ok(aspect.output()) +} + fn parse_output(value: &str) -> Result> { match value.trim().to_ascii_lowercase().as_str() { "" | "off" | "0" => Ok(None), diff --git a/d3d12/crates/leonida-gpu/src/aspect.rs b/d3d12/crates/leonida-gpu/src/aspect.rs index 60dbbaeb09..723b80a977 100644 --- a/d3d12/crates/leonida-gpu/src/aspect.rs +++ b/d3d12/crates/leonida-gpu/src/aspect.rs @@ -1,18 +1,6 @@ -//! Leonida: a window of another shape than the title's picture (ultrawide monitors). -//! -//! The title outputs 16:9 (3840x2160 on Series X) whatever its window is, and the swap chain was stretched over -//! the window. Two settings, the ones `docs/ultrawide.md` gives the Vulkan runtime: -//! -//! - `LEONIDA_ASPECT=21:9|32:9|16:9|W:H||auto`: the shape the title's window is made in (`auto`: the -//! primary monitor's). Read by leonida-hle's `lifecycle.rs`, which widens the window the title asks for. -//! - `LEONIDA_PRESENT_SCALE=fit|stretch`: `fit` keeps the picture's shape in a window of another one, centred, -//! with black bars beside it (or above and below); `stretch` fills the window as before. Unset: `fit` with -//! `LEONIDA_ASPECT`, else `stretch`. The F1 menu changes it while running. -//! -//! With `fit` the swap chain takes the window's shape at the picture's height (or width), the picture is copied -//! into its middle unscaled and the rest is cleared ([`frame`], used by the presenter in `host.rs`); the window -//! then scales it evenly. Neither makes the title draw a wider view: that is the title's output size -//! (`LEONIDA_OUTPUT`, leonida-loader's `hooks.rs`, and `docs/ultrawide.md` for what is known of it). +//! Native Series X aspect selection and window fitting. +//! `LEONIDA_ASPECT_RATIO` selects native output. `LEONIDA_ASPECT` and +//! `LEONIDA_PRESENT_SCALE` control window shape and fitting. #![cfg_attr(not(windows), allow(dead_code))] use std::sync::atomic::{AtomicU8, Ordering}; @@ -24,6 +12,108 @@ pub fn set_native_output(output: (u32, u32)) { let _ = NATIVE_OUTPUT.set(output); } +pub const NATIVE_ASPECT_ENV: &str = "LEONIDA_ASPECT_RATIO"; +pub const HUD_POSITION_ENV: &str = "LEONIDA_HUD_POSITION"; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum NativeAspect { + Auto, + Standard, + Wide, + Superwide, +} + +impl NativeAspect { + pub fn parse(value: &str) -> Option { + match value.trim() { + "auto" => Some(Self::Auto), + "16:9" => Some(Self::Standard), + "21:9" => Some(Self::Wide), + "32:9" => Some(Self::Superwide), + _ => None, + } + } + + pub fn output(self) -> Option<(u32, u32)> { + #[cfg(windows)] + { + let current = display_mode(u32::MAX).or_else(screen); + self.output_for(current, (0..).map_while(display_mode)) + } + #[cfg(not(windows))] + self.output_for(None, []) + } + + fn output_for( + self, + current: Option<(u32, u32)>, + modes: impl IntoIterator, + ) -> Option<(u32, u32)> { + match if self == Self::Auto { + current.and_then(Self::classify)? + } else { + self + } { + Self::Wide => Some((3440, 1440)), + Self::Superwide => { + let height = current.into_iter().chain(modes) + .filter(|&size| Self::classify(size) == Some(Self::Superwide)) + .map(|(_, height)| height) + .max(); + Some(if height.is_some_and(|height| height < 1440) { + (3840, 1080) + } else { + (5120, 1440) + }) + } + Self::Auto | Self::Standard => None, + } + } + + fn classify((width, height): (u32, u32)) -> Option { + let (w, h) = (u64::from(width), u64::from(height)); + if height >= 1080 && w * 9 == h * 32 { + Some(Self::Superwide) + } else if width >= 3440 && height >= 1440 && (w * 27).abs_diff(h * 64) * 100 <= h * 64 { + Some(Self::Wide) + } else { + None + } + } +} + +#[cfg(windows)] +fn display_mode(index: u32) -> Option<(u32, u32)> { + use windows::Win32::Graphics::Gdi::{DEVMODEW, ENUM_DISPLAY_SETTINGS_MODE, EnumDisplaySettingsW}; + use windows::core::PCWSTR; + + let mut mode = DEVMODEW { dmSize: size_of::() as u16, ..Default::default() }; + // SAFETY: a null name selects the desktop display, and mode is initialized. + let found = unsafe { EnumDisplaySettingsW(PCWSTR::null(), ENUM_DISPLAY_SETTINGS_MODE(index), &mut mode) }.as_bool(); + found.then_some((mode.dmPelsWidth, mode.dmPelsHeight)) +} + +pub fn hud_position() -> &'static str { + let value = std::env::var(HUD_POSITION_ENV).ok(); + let legacy_off = std::env::var_os("LEONIDA_ULTRAWIDE_HUD").is_some_and(|v| v == "0"); + hud_position_for(value.as_deref(), legacy_off) +} + +pub(crate) fn hud_at_edges() -> bool { + let value = std::env::var(HUD_POSITION_ENV).ok(); + hud_position_for(value.as_deref(), false) == "edges" +} + +fn hud_position_for(value: Option<&str>, legacy_off: bool) -> &'static str { + if legacy_off || value == Some("off") { + "off" + } else if matches!(value, Some("center" | "centered")) { + "center" + } else { + "edges" + } +} + /// What `LEONIDA_ASPECT` can say. #[derive(Debug, Clone, Copy, PartialEq)] pub enum Asked { @@ -189,6 +279,26 @@ pub fn frame(picture: (u32, u32), window: (u32, u32)) -> Frame { mod tests { use super::*; + #[test] + fn native_aspect_uses_the_desktop_and_reported_modes() { + let standard = Some((2560, 1440)); + let low_wide = Some((3840, 1080)); + assert_eq!(NativeAspect::Auto.output_for(standard, [(5120, 1440)]), None); + assert_eq!(NativeAspect::Auto.output_for(Some((5120, 2160)), []), Some((3440, 1440))); + assert_eq!(NativeAspect::Auto.output_for(low_wide, []), Some((3840, 1080))); + assert_eq!(NativeAspect::Superwide.output_for(low_wide, [(5120, 1440)]), Some((5120, 1440))); + assert_eq!(NativeAspect::Superwide.output_for(standard, [(3840, 1080)]), Some((3840, 1080))); + assert_eq!(NativeAspect::Standard.output_for(low_wide, [(5120, 1440)]), None); + } + + #[test] + fn ultrawide_hud_defaults_to_edges_and_can_disable_correction() { + assert_eq!(hud_position_for(None, false), "edges"); + assert_eq!(hud_position_for(Some("center"), false), "center"); + assert_eq!(hud_position_for(Some("off"), false), "off"); + assert_eq!(hud_position_for(Some("edges"), true), "off"); + } + #[test] fn shapes_read_as_ratios_decimals_and_auto() { assert_eq!(parse("21:9"), Some(Asked::Ratio(21.0 / 9.0))); diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 17b9c0b349..eb0bc8ad18 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -13847,7 +13847,7 @@ impl Host { } else { None }; - let edges = wide_overlay && std::env::var_os("LEONIDA_HUD_POSITION").is_some_and(|v| v == "edges"); + let edges = wide_overlay && crate::aspect::hud_at_edges(); let hud_layout = crate::compose::HudLayout::for_present( overlay_centered, wide_overlay, diff --git a/d3d12/crates/leonida-gpu/src/host/menu.rs b/d3d12/crates/leonida-gpu/src/host/menu.rs index 7cdf560f45..71632377dc 100644 --- a/d3d12/crates/leonida-gpu/src/host/menu.rs +++ b/d3d12/crates/leonida-gpu/src/host/menu.rs @@ -18,6 +18,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Duration; +use crate::aspect::{HUD_POSITION_ENV, NATIVE_ASPECT_ENV, NativeAspect}; + use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ @@ -69,8 +71,8 @@ const ITEMS: &[Item] = &[ // Turned on, it applies at the next start (the swap chain is FidelityFX's); off and on again while it runs. Item { var: "LEONIDA_FSR_FRAMEGEN", label: "FSR 3 FRAME GEN 2X (RTX 20/30)", values: UNSET_ON, live: false }, // The window's shape, and the game's 16:9 picture in a window of another shape (`crate::aspect`). - Item { var: "LEONIDA_NATIVE_ULTRAWIDE", label: "SERIES X ULTRAWIDE", values: &[("", "OFF"), ("3440x1440", "3440x1440"), ("3840x1080", "3840x1080"), ("5120x1440", "5120x1440")], live: false }, - Item { var: "LEONIDA_HUD_POSITION", label: "ULTRAWIDE HUD", values: &[("", "CENTER"), ("edges", "SCREEN EDGES")], live: true }, + Item { var: NATIVE_ASPECT_ENV, label: "ASPECT RATIO", values: &[("auto", "MATCH MONITOR"), ("16:9", "16:9"), ("21:9", "21:9"), ("32:9", "32:9")], live: false }, + Item { var: HUD_POSITION_ENV, label: "ULTRAWIDE HUD", values: &[("edges", "SCREEN EDGES"), ("center", "CENTERED"), ("off", "OFF")], live: true }, Item { var: "LEONIDA_ASPECT", label: "WINDOW SHAPE", values: &[("", "GAME OUTPUT"), ("21:9", "21:9"), ("32:9", "32:9"), ("auto", "AS THE SCREEN")], live: false }, Item { var: "LEONIDA_PRESENT_SCALE", label: "PICTURE IN ANOTHER SHAPE", values: &[("", "BY WINDOW SHAPE"), ("fit", "BARS"), ("stretch", "STRETCH")], live: true }, // Leonida: the title's window borderless over its monitor from the start (leonida-hle's lifecycle.rs); Alt+Enter @@ -121,9 +123,20 @@ const ITEMS: &[Item] = &[ const ACTIONS: [&str; 4] = ["SAVE AND RESTART NOW", "SAVE FOR NEXT START", "RESET ALL TO PLAY DEFAULTS", "CLOSE"]; fn get(var: &str) -> String { + if var == HUD_POSITION_ENV { + return crate::aspect::hud_position().to_owned(); + } let value = std::env::var(var).unwrap_or_default(); match (var, value.as_str()) { - ("LEONIDA_NATIVE_ULTRAWIDE", "off" | "0") | ("LEONIDA_HUD_POSITION", "center") => String::new(), + ("LEONIDA_MENU_CONSOLE", "") => match crate::console::current() { + crate::console::Console::SeriesS => "series-s", + crate::console::Console::SeriesX => "series-x", + }.to_owned(), + (NATIVE_ASPECT_ENV, "") => match std::env::var("LEONIDA_NATIVE_ULTRAWIDE").as_deref() { + Ok("3440x1440") => "21:9", + Ok("3840x1080" | "5120x1440") => "32:9", + _ => "16:9", + }.to_owned(), _ => value, } } @@ -324,20 +337,55 @@ impl Menu { crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed) } + fn value(&self, var: &str) -> &str { + ITEMS.iter().position(|item| item.var == var).map_or("", |row| &self.values[row]) + } + + fn visible_rows(&self) -> Vec { + let series_x = self.value("LEONIDA_MENU_CONSOLE") != "series-s"; + let wide = series_x && match NativeAspect::parse(self.value(NATIVE_ASPECT_ENV)) { + Some(NativeAspect::Wide | NativeAspect::Superwide) => true, + Some(NativeAspect::Auto) => { + static AUTO_WIDE: OnceLock = OnceLock::new(); + *AUTO_WIDE.get_or_init(|| NativeAspect::Auto.output().is_some()) + } + _ => false, + }; + (0..ITEMS.len() + ACTIONS.len()).filter(|&row| match ITEMS.get(row).map(|item| item.var) { + Some(NATIVE_ASPECT_ENV) => series_x, + Some(HUD_POSITION_ENV) => wide, + _ => true, + }).collect() + } + + fn move_selection(&mut self, step: isize) { + let rows = self.visible_rows(); + let position = rows.iter().position(|&row| row == self.at).unwrap_or(0); + self.at = rows[(position as isize + step).rem_euclid(rows.len() as isize) as usize]; + } + + fn is_live(&self, row: usize) -> bool { + if ITEMS[row].var == HUD_POSITION_ENV { + return self.values[row] != "off" && crate::world_marker::enabled(); + } + live(&ITEMS[row]) + } + fn lines(&self) -> Vec { - let total = ITEMS.len() + ACTIONS.len(); - let first = self.at.saturating_sub(ROWS / 2).min(total.saturating_sub(ROWS)); + let rows = self.visible_rows(); + let position = rows.iter().position(|&row| row == self.at).unwrap_or(0); + let first = position.saturating_sub(ROWS / 2).min(rows.len().saturating_sub(ROWS)); let mut out = vec![ "SETTINGS F1 OR ESC CLOSES".to_owned(), "UP/DOWN PICK LEFT/RIGHT CHANGE ENTER DOES IT".to_owned(), String::new(), ]; - for row in first..(first + ROWS).min(total) { + for &row in rows.iter().skip(first).take(ROWS) { let cursor = if row == self.at { '>' } else { ' ' }; let line = if let Some(item) = ITEMS.get(row) { let value = &self.values[row]; let shown = index_of(item, value).map_or(value.to_ascii_uppercase(), |i| item.values[i].1.to_owned()); - let mark = if *value != self.started[row] { if live(item) { " *LIVE" } else { " *" } } else if live(item) { " LIVE" } else { "" }; + let mark = if *value != self.started[row] { if self.is_live(row) { " *LIVE" } else { " *" } } else if self.is_live(row) { " LIVE" } else { "" }; format!("{cursor} {:<27} < {shown} >{mark}", item.label) } else { format!("{cursor} {}", ACTIONS[row - ITEMS.len()]) @@ -359,7 +407,7 @@ impl Menu { let now = index_of(item, &self.values[i]).map_or(-1, |x| x as isize); let next = if now < 0 { if step > 0 { 0 } else { n - 1 } } else { (now + step).rem_euclid(n) }; self.values[i] = item.values[next as usize].0.to_owned(); - if live(item) { + if self.is_live(i) { self.apply_live(i); } self.note.clear(); @@ -399,7 +447,7 @@ impl Menu { /// change the panel, the frame-rate cap and DLSS's sharpness too. fn refresh_live(&mut self) { for (i, item) in ITEMS.iter().enumerate() { - if !item.live { + if !item.live || (item.var == HUD_POSITION_ENV && !self.is_live(i)) { continue; } self.values[i] = match item.var { @@ -427,7 +475,9 @@ impl Menu { if self.values[i] == self.started[i] { continue; } - kept.retain(|(k, _)| k != item.var); + kept.retain(|(k, _)| k != item.var + && !(item.var == NATIVE_ASPECT_ENV && k == "LEONIDA_NATIVE_ULTRAWIDE") + && !(item.var == HUD_POSITION_ENV && k == "LEONIDA_ULTRAWIDE_HUD")); kept.push((item.var.to_owned(), self.values[i].clone())); } let mut text = String::from("# Saved by the F1 menu; play.ps1 applies these after its own settings (an empty value: unset).\r\n"); @@ -498,7 +548,6 @@ impl Menu { if pressed.is_empty() { return; } - let total = ITEMS.len() + ACTIONS.len(); for vk in pressed { let open = Self::open(); if vk == VK_F1 || (open && vk == VK_ESCAPE) { @@ -514,8 +563,8 @@ impl Menu { continue; } match vk { - VK_UP => self.at = (self.at + total - 1) % total, - VK_DOWN => self.at = (self.at + 1) % total, + VK_UP => self.move_selection(-1), + VK_DOWN => self.move_selection(1), VK_LEFT if self.at < ITEMS.len() => self.change(self.at, -1), VK_RIGHT if self.at < ITEMS.len() => self.change(self.at, 1), VK_RETURN if self.at < ITEMS.len() => self.change(self.at, 1), @@ -637,4 +686,28 @@ mod tests { menu.change(0, -1); assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0); } + + #[test] + fn selecting_ultrawide_reveals_hud_and_standard_skips_it() { + let values = ITEMS.iter().map(|item| item.values[0].0.to_owned()).collect::>(); + let row = |var| ITEMS.iter().position(|item| item.var == var).unwrap(); + let (aspect, hud, console) = (row(NATIVE_ASPECT_ENV), row(HUD_POSITION_ENV), row("LEONIDA_MENU_CONSOLE")); + let mut menu = Menu { started: values.clone(), values, at: aspect, note: String::new(), changed: false, painted: None, buffers: None, failed: false }; + menu.values[console] = "series-x".to_owned(); + menu.values[aspect] = "16:9".to_owned(); + assert!(!menu.visible_rows().contains(&hud)); + menu.move_selection(1); + assert_eq!(menu.at, hud + 1); + menu.move_selection(-1); + menu.change(aspect, 1); + assert_eq!(menu.value(NATIVE_ASPECT_ENV), "21:9"); + menu.move_selection(1); + assert_eq!(menu.at, hud); + assert_eq!(menu.value(HUD_POSITION_ENV), "edges"); + menu.change(hud, -1); + assert_eq!(menu.value(HUD_POSITION_ENV), "off"); + assert!(!menu.is_live(hud)); + menu.values[console] = "series-s".to_owned(); + assert!(!menu.visible_rows().contains(&hud)); + } } diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 8be6005162..26fe45fc43 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -31,8 +31,8 @@ # -FidelityFxDir the folder with AMD's two DLLs, if not amd-sdk\FidelityFX\bin # -Fullscreen the game's window borderless over its whole monitor from the start (Alt+Enter switches back and # forth while it runs, with or without this; also FULLSCREEN in the F1 menu) -# -Ultrawide native Series X output: off, 3440x1440, 3840x1080, or 5120x1440. -# -HudPosition center or edges for the native ultrawide HUD. +# -AspectRatio native Series X output: auto, 16:9, 21:9, or 32:9. +# -HudPosition edges (default), center, or off for ultrawide HUD correction. # -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto (the screen's). # -PresentScale fit (the 16:9 picture centred, black bars beside it: the default with -Aspect) or stretch # -Quality fewer stretched/jumping bodies, slower (relay stage 1, no card steps) @@ -80,8 +80,9 @@ param( [switch]$FsrFrameGen, [string]$FidelityFxDir, [switch]$Fullscreen, - [ValidateSet('off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide, - [ValidateSet('center', 'edges')][string]$HudPosition, + [ValidateSet('auto', '16:9', '21:9', '32:9')][string]$AspectRatio, + [Parameter(DontShow)][ValidateSet('off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide, + [ValidateSet('off', 'center', 'edges')][string]$HudPosition, [ValidatePattern('^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$')][string]$Aspect, [ValidateSet('fit', 'stretch')][string]$PresentScale, [string]$Adapter, @@ -428,6 +429,7 @@ if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -no } } if ($Fullscreen) { $settings.LEONIDA_FULLSCREEN = '1' } +if ($AspectRatio) { $settings.LEONIDA_ASPECT_RATIO = $AspectRatio } if ($Ultrawide) { $settings.LEONIDA_NATIVE_ULTRAWIDE = $Ultrawide } if ($HudPosition) { $settings.LEONIDA_HUD_POSITION = $HudPosition } if ($Aspect) { $settings.LEONIDA_ASPECT = $Aspect } @@ -548,8 +550,9 @@ $switchSettings = @{ NoFrameGen = 'LEONIDA_FRAME_GEN' FsrFrameGen = 'LEONIDA_FSR_FRAMEGEN', 'LEONIDA_FRAME_GEN' Fullscreen = 'LEONIDA_FULLSCREEN' - Ultrawide = 'LEONIDA_NATIVE_ULTRAWIDE' - HudPosition = 'LEONIDA_HUD_POSITION' + AspectRatio = 'LEONIDA_ASPECT_RATIO', 'LEONIDA_NATIVE_ULTRAWIDE' + Ultrawide = 'LEONIDA_ASPECT_RATIO', 'LEONIDA_NATIVE_ULTRAWIDE' + HudPosition = 'LEONIDA_HUD_POSITION', 'LEONIDA_ULTRAWIDE_HUD' Aspect = 'LEONIDA_ASPECT' PresentScale = 'LEONIDA_PRESENT_SCALE' Adapter = 'LEONIDA_ADAPTER' @@ -593,7 +596,13 @@ foreach ($k in @($menu.Keys)) { $fromMenu += "$k=$(if ($v) { $v } else { '(unset)' })" if ($k -eq 'LEONIDA_MENU_SMOOTH_MOTION') { $smooth = $v -ne '0'; continue } if ($k -eq 'LEONIDA_MENU_CONSOLE') { if ($v) { $console = $v }; continue } - if ($v) { $settings[$k] = $v } else { $settings.Remove($k) } + if ($k -eq 'LEONIDA_NATIVE_ULTRAWIDE' -and -not $menu.Contains('LEONIDA_ASPECT_RATIO')) { + $settings.Remove('LEONIDA_ASPECT_RATIO') + } + if ($v) { $settings[$k] = $v } + elseif ($k -eq 'LEONIDA_HUD_POSITION') { $settings[$k] = 'center' } + elseif ($k -eq 'LEONIDA_NATIVE_ULTRAWIDE') { $settings[$k] = 'off' } + else { $settings.Remove($k) } } if ($fromMenu) { Write-Host "F1 menu settings (leonida-settings.txt, for what the command line did not set): $($fromMenu -join ', ')" } if ($replaced) { Write-Host "Command line over the F1 menu's saved values: $($replaced -join ', ')" } @@ -619,16 +628,37 @@ if (-not $DryRun -and $menu.Count -ne $menuRead) { if (-not $NoPrecompile) { $settings.LEONIDA_PIPELINE_BOOK = '1' } foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } $nativeOutput = "$($settings.LEONIDA_NATIVE_ULTRAWIDE)".Trim().ToLowerInvariant() -if ($nativeOutput -in '', 'off', '0') { +$nativeAspect = "$($settings.LEONIDA_ASPECT_RATIO)".Trim().ToLowerInvariant() +if ($nativeAspect -and $nativeAspect -notin 'auto', '16:9', '21:9', '32:9') { + throw 'AspectRatio must be auto, 16:9, 21:9, or 32:9.' +} +if ($console -ne 'series-x') { + if (($nativeAspect -in '21:9', '32:9' -or $nativeOutput -in '3440x1440', '3840x1080', '5120x1440') -and + $chosenNow.ContainsKey('LEONIDA_NATIVE_ULTRAWIDE')) { throw 'Native ultrawide requires Series X.' } + $settings.Remove('LEONIDA_ASPECT_RATIO') + $settings.Remove('LEONIDA_NATIVE_ULTRAWIDE') + $nativeAspect = '' $nativeOutput = '' -} elseif ($nativeOutput -notin '3440x1440', '3840x1080', '5120x1440') { - throw 'Ultrawide must be off, 3440x1440, 3840x1080, or 5120x1440.' -} elseif ($console -ne 'series-x') { - if ($chosenNow.ContainsKey('LEONIDA_NATIVE_ULTRAWIDE')) { throw 'Native ultrawide requires Series X.' } +} elseif (($nativeAspect -and -not $More.ContainsKey('LEONIDA_NATIVE_ULTRAWIDE')) -or -not $nativeOutput) { + if (-not $nativeAspect) { $nativeAspect = 'auto' } + $settings.LEONIDA_ASPECT_RATIO = $nativeAspect $settings.Remove('LEONIDA_NATIVE_ULTRAWIDE') $nativeOutput = '' + if ($nativeAspect -eq '16:9' -or ($nativeAspect -eq 'auto' -and ($Resolution -eq '2160' -or $More.ContainsKey('LEONIDA_OUTPUT')))) { + $settings.LEONIDA_NATIVE_ULTRAWIDE = 'off' + } elseif (Test-Path $leonida) { + $nativeOutput = "$(& $leonida aspect-output $nativeAspect)" + if ($LASTEXITCODE -ne 0) { throw 'Could not resolve the aspect ratio. Rebuild leonida.exe and try again.' } + if (-not $nativeOutput) { $settings.LEONIDA_NATIVE_ULTRAWIDE = 'off' } + } elseif ($nativeAspect -eq '21:9') { + $nativeOutput = '3440x1440' + } + if ($nativeOutput) { $settings.LEONIDA_NATIVE_ULTRAWIDE = $nativeOutput } +} elseif ($nativeOutput -in 'off', '0') { + $nativeOutput = '' } if ($nativeOutput) { + if ($nativeOutput -notin '3440x1440', '3840x1080', '5120x1440') { throw "Unsupported native output: $nativeOutput." } $settings.Remove('LEONIDA_OUTPUT') if ($Resolution -or $Lowest) { $scaleKey = if ($Resolution) { 'LEONIDA_RENDER_SCALE' } else { 'LEONIDA_RENDER_SCALE_MIN' } @@ -724,7 +754,7 @@ $again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build") foreach ($s in 'NoSmoothMotion', 'MotionBlur', 'NoDlss', 'NoFrameGen', 'SeriesX', 'Quality', 'RayTracing', 'FsrFrameGen', 'NoPrecompile', 'Log', 'Capture', 'Fullscreen') { if ($PSBoundParameters[$s]) { $again += "-$s" } } -foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'Ultrawide', 'HudPosition', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir', 'FidelityFxDir') { +foreach ($s in 'Resolution', 'Lowest', 'Dlss', 'FrameGen', 'AspectRatio', 'Ultrawide', 'HudPosition', 'Aspect', 'PresentScale', 'Adapter', 'DlssDir', 'StreamlineDir', 'FidelityFxDir') { if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" } } if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" } @@ -744,7 +774,7 @@ $picture = if ($own -and $settings.LEONIDA_RENDER_SCALE) { "render scale $($sett elseif ($settings.LEONIDA_UPSCALE -eq 'stretch') { "stretched$scaled (no DLSS)" } elseif ($settings.LEONIDA_RENDER_SCALE) { "render scale $($settings.LEONIDA_RENDER_SCALE), the title's upscaler" } else { "the title's upscaler" } -$extras = if ($nativeOutput) { ", native output $nativeOutput" } else { '' } +$extras = if ($nativeOutput) { ", native output $nativeOutput" } elseif ($nativeAspect) { ", aspect $nativeAspect" } else { '' } if ($settings.LEONIDA_ASPECT) { $extras += ", window $($settings.LEONIDA_ASPECT)" } if ($settings.LEONIDA_FRAME_GEN) { $extras += ", frame generation $($settings.LEONIDA_FRAME_GEN)x" } if ($settings.LEONIDA_FSR_FRAMEGEN -eq '1') { $extras += ', FSR 3 frame generation 2x' } diff --git a/docs/launcher.md b/docs/launcher.md index 84b0aeaac8..8f6a6dd547 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -24,8 +24,9 @@ Standard library only (`tools/leonida_launcher.py`). - **Settings**: the game folder (a picker, and a check that `game_scarlett_master.exe` is in it), the data folder (empty = the script's default), the mods folder, and the options of `play-d3d12.ps1`: DLSS (off is `-NoDlss`), `-RayTracing`, `-SmoothMotion`, shader preparation (off is `-NoPrecompile`), `-SeriesX`, `-Quality`, `-Resolution` - (default = none), `-Capture`, `-Log`. Series X offers native 21:9 and 32:9 outputs and a center or edge HUD - under [Ultrawide](ultrawide.md). Linux supports the game folder, Series X and the native ultrawide options. + (default = none), `-Capture`, `-Log`. Check **Series X profile** to show **Aspect ratio (-AspectRatio)**. + **Ultrawide HUD correction (-HudPosition)** appears when the resulting aspect is ultrawide. The same + settings are available on Linux. See [Ultrawide](ultrawide.md). - **Mods**: the `mods\*\mod.json` of the mods folder (this repository's `mods` unless changed), with the enabled flag written back as the mod manager does it (`tools/leonida_mods.py`); a button opens that manager. - **Saves**: the D3D12 runtime's saves under the data folder, `\data\7952987A\saves\\\~Built on the work of others // The keys are those of the launcher's settings file (tools/leonida_launcher.py). Two controls stand for two keys // each: `console` (series_s, series_x) and `upscale` (dlss, off = -NoDlss, and dlss_mode, -Dlss ). const DEFAULTS = { game_dir: "", data_dir: "", mods_dir: "", background: "", series_s: false, series_x: false, dlss: true, dlss_mode: "", resolution: "", - frame_gen: 0, smooth_motion: false, aspect: "", present_scale: "", ultrawide: "", hud_position: "", ray_tracing: false, quality: false, adapter: "", precompile: true, + frame_gen: 0, smooth_motion: false, aspect: "", present_scale: "", aspect_ratio: "", hud_position: "", ray_tracing: false, quality: false, adapter: "", precompile: true, capture: false, log: false }; const GROUPS = [ { title: "Folders", fields: [ @@ -432,10 +432,10 @@

Built on the work of others

{ title: "Picture", fields: [ { key: "console", kind: "seg", label: "Console profile", options: [["x", "Series X"], ["s", "Series S"]], help: "Series X renders 2560x1440 for a 3840x2160 output. Series S is lighter: the game's own 720p picture, taken to 1080p." }, - { key: "ultrawide", kind: "seg", label: "Native ultrawide output", when: s => consoleOf(s) === "x", - options: [["", "Default"], ["off", "Off"], ["3440x1440", "3440×1440"], ["3840x1080", "3840×1080"], ["5120x1440", "5120×1440"]] }, - { key: "hud_position", kind: "seg", label: "Ultrawide HUD", when: s => consoleOf(s) === "x" && s.ultrawide !== "off", - options: [["", "Default"], ["center", "Center"], ["edges", "Screen edges"]] }, + { key: "aspect_ratio", kind: "seg", label: "Aspect ratio", when: s => consoleOf(s) === "x", + options: [["", "Default"], ["auto", "Match monitor"], ["16:9", "16:9"], ["21:9", "21:9"], ["32:9", "32:9"]] }, + { key: "hud_position", kind: "seg", label: "Ultrawide HUD correction", when: ultrawideSelected, + options: [["", "Default (edges)"], ["edges", "Screen edges"], ["center", "Centered"], ["off", "Off"]] }, { key: "upscale", kind: "seg", label: "Upscaling", windows: true, options: [["default", "Default"], ["quality", "DLSS Quality"], ["balanced", "Balanced"], ["performance", "Performance"], ["ultra", "Ultra"], ["off", "Off"]], help: "Default is the game's own upscaler on Series X. A DLSS mode renders at 1440, 1296, 1080 or 720 lines of the 2160. Off stretches the picture." }, @@ -471,7 +471,23 @@

Built on the work of others

{ name: "Lighter", text: "Series S: the game's 720p, taken to 1080p", console: "s", set: { dlss: true, dlss_mode: "", frame_gen: 0, resolution: "" } }, ]; const MODE_NAMES = { quality: "Quality", balanced: "Balanced", performance: "Performance", ultra: "Ultra" }; -function consoleOf(s) { return s.series_s ? "s" : s.series_x ? "x" : (S && S.platform !== "windows" ? "s" : "x"); } // each start script's own default +function wideRatio(aspect) { return aspect === "21:9" || aspect === "32:9"; } +function consoleOf(s) { + const defaultX = S?.picture?.default_series_x ?? (S?.platform === "windows"); + return s.series_s ? "s" : s.series_x || wideRatio(s.aspect_ratio) || defaultX ? "x" : "s"; +} +function ultrawideSelected(s) { + if (consoleOf(s) !== "x") return false; + const aspect = s.aspect_ratio || S?.picture?.saved_aspect_ratio || "auto"; + if (aspect !== "auto") return wideRatio(aspect); + if (S?.platform === "windows" && s.resolution === "2160" && !(s.dlss && s.dlss_mode)) return false; + const monitor = S?.picture?.monitor_ultrawide; + if (monitor != null) return monitor; + const scale = window.devicePixelRatio || 1; + const w = Math.round(window.screen.width * scale), h = Math.round(window.screen.height * scale); + return (h >= 1080 && w * 9 === h * 32) + || (w >= 3440 && h >= 1440 && Math.abs(w * 27 - h * 64) * 100 <= h * 64); +} function consolePatch(v) { return v === "s" ? { series_s: true, series_x: false } : { series_s: false, series_x: true }; } function presetOn(p, s) { return consoleOf(s) === p.console && Object.entries(p.set).every(([k, v]) => s[k] === v); } @@ -488,8 +504,8 @@

Built on the work of others

if (s.series_x && !s.series_s) a.push("-SeriesX"); if (s.quality) a.push("-Quality"); if (s.resolution && !(s.dlss && s.dlss_mode)) a.push("-Resolution", s.resolution); - if (!s.series_s && s.ultrawide) a.push("-Ultrawide", s.ultrawide); - if (!s.series_s && s.hud_position) a.push("-HudPosition", s.hud_position); + if (!s.series_s && s.aspect_ratio) a.push("-AspectRatio", s.aspect_ratio); + if (ultrawideSelected(s) && s.hud_position) a.push("-HudPosition", s.hud_position); if (s.aspect) { a.push("-Aspect", s.aspect); if (s.present_scale) a.push("-PresentScale", s.present_scale); } if (s.adapter.trim()) a.push("-Adapter", s.adapter.trim()); if (s.capture) a.push("-Capture"); @@ -510,8 +526,8 @@

Built on the work of others

: s.resolution ? s.resolution + " lines, game's upscaler" : lighter ? "720p to 1080p" : "1440 lines, game's upscaler"; const frames = (s.frame_gen ? "Frame generation " + s.frame_gen + "x" : "No generated frames") + (s.smooth_motion ? ", Smooth Motion" : ""); - const nativeOutput = !lighter && s.ultrawide && s.ultrawide !== "off" ? s.ultrawide : ""; - const shape = s.aspect ? (s.aspect === "auto" ? "The screen's shape" : s.aspect) + (s.present_scale === "stretch" ? ", stretched" : ", fitted") : nativeOutput || "Game output"; + const nativeAspect = !lighter && s.aspect_ratio ? (s.aspect_ratio === "auto" ? "Match monitor" : s.aspect_ratio) : "Game output"; + const shape = s.aspect ? (s.aspect === "auto" ? "The screen's shape" : s.aspect) + (s.present_scale === "stretch" ? ", stretched" : ", fitted") : nativeAspect; const start = s.precompile ? "Shaders prepared first" : "Starts at once"; return [["Profile", lighter ? "Series S" : "Series X"], ["Picture", picture + (s.ray_tracing ? ", ray tracing" : "")], ["Frames", frames], ["Window", shape], ["Start", start + (s.capture ? ", F9 captures" : "") + (s.log ? ", log file" : "")]]; @@ -700,7 +716,7 @@

Built on the work of others

function renderSettings() { const s = S.settings, linux = S.platform !== "windows"; $("settings-where").textContent = linux - ? "On Linux the start script takes the game folder and the console profile; the other options are switches of the Windows script and are greyed here." + ? "On Linux the start script takes the game folder, console profile, aspect ratio and ultrawide HUD correction." : "Each option is a switch of scripts\\play-d3d12.ps1. Changes are saved as you make them."; fill($("groups"), GROUPS.map(g => h("section", null, h("h2", { class: "label" }, g.title), g.fields.filter(f => !f.when || f.when(s)).map(f => { diff --git a/launcher/serve.py b/launcher/serve.py index dc0fe38ad9..478c110e34 100644 --- a/launcher/serve.py +++ b/launcher/serve.py @@ -267,8 +267,9 @@ def saves(self, settings: dict) -> dict: def state(self, with_log: bool = True) -> dict: settings = self.settings() + picture = core.picture_context(self.repo) try: - command = core.play_command(settings, repo=self.repo) + command = core.play_command(settings, repo=self.repo, picture=picture) except ValueError: command = None mods_dir = self.mods_dir(settings) @@ -283,7 +284,7 @@ def state(self, with_log: bool = True) -> dict: return { "sample": False, "can_run": self.can_run, "platform": "windows" if core.WINDOWS else "linux", "version": self.version, "package": self.package, "settings": settings, "checks": self.checks(settings), - "command": command, + "command": command, "picture": picture, "mods": [{"folder": m["folder"], "name": m["name"], "enabled": m["enabled"], "swaps": m["swaps"]} for m in mods], "mod_errors": errors, "mods_dir": mods_dir, "saves": self.saves(settings), "captures": captures, diff --git a/scripts/play-d3d12.ps1 b/scripts/play-d3d12.ps1 index a128cce2f6..efd42dbac6 100644 --- a/scripts/play-d3d12.ps1 +++ b/scripts/play-d3d12.ps1 @@ -27,8 +27,8 @@ # -FsrFrameGen AMD's FSR 3 frame generation instead (2x), for cards without DLSS frame generation (RTX 20 and 30): # needs AMD's two signed FidelityFX DLLs in d3d12\amd-sdk\FidelityFX\bin # -Fullscreen the game's window borderless over its whole monitor (Alt+Enter switches while it runs) -# -Ultrawide native Series X output: 3440x1440, 3840x1080, 5120x1440, or off. -# -HudPosition center (default) or edges for the ultrawide gameplay HUD. +# -AspectRatio native Series X output: auto, 16:9, 21:9, or 32:9. +# -HudPosition edges (default), center, or off for ultrawide HUD correction. # -Aspect the window's shape: 21:9, 32:9, 16:9, W:H or auto. -PresentScale fits or stretches the picture. # -Resolution the older path: the game renders at this height and the title's own upscaler does the rest # -Lowest the lowest height of the title's own dynamic resolution (1080 by default on Series X): it renders @@ -60,8 +60,9 @@ param( [switch]$MotionBlur, [switch]$FsrFrameGen, [switch]$Fullscreen, - [ValidateSet('', 'off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide = '', - [ValidateSet('', 'center', 'edges')][string]$HudPosition = '', + [ValidateSet('', 'auto', '16:9', '21:9', '32:9')][string]$AspectRatio = '', + [Parameter(DontShow)][ValidateSet('', 'off', '3440x1440', '3840x1080', '5120x1440')][string]$Ultrawide = '', + [ValidateSet('', 'off', 'center', 'edges')][string]$HudPosition = '', [string]$Aspect = '', [ValidateSet('', 'fit', 'stretch')][string]$PresentScale = '', [string]$Adapter = '', @@ -79,7 +80,7 @@ param( ) $ErrorActionPreference = "Stop" -$nativeOutputAsked = $Ultrawide -and $Ultrawide -ne 'off' +$nativeOutputAsked = $AspectRatio -in '21:9', '32:9' -or ($Ultrawide -and $Ultrawide -ne 'off') if ($SeriesS -and $nativeOutputAsked) { throw 'Native ultrawide requires Series X.' } $repo = Split-Path -Parent $PSScriptRoot $runtime = Join-Path $repo "d3d12" @@ -108,6 +109,7 @@ if (-not $SeriesS) { } if ($Dlss) { $launch.Dlss = $Dlss } if ($FrameGen) { $launch.FrameGen = $FrameGen } +if ($AspectRatio) { $launch.AspectRatio = $AspectRatio } if ($Ultrawide) { $launch.Ultrawide = $Ultrawide } if ($HudPosition) { $launch.HudPosition = $HudPosition } if ($Aspect) { $launch.Aspect = $Aspect } diff --git a/scripts/play-linux.sh b/scripts/play-linux.sh index 89ab462c57..4f289c8ba3 100755 --- a/scripts/play-linux.sh +++ b/scripts/play-linux.sh @@ -3,7 +3,7 @@ # the package (scripts/fetch_vkd3d_proton.py puts it in vkd3d-proton/ beside this script), so nothing else needs to be # downloaded for Direct3D 12. Wine itself and a Vulkan driver (Mesa or NVIDIA's) are the system's. # -# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] [--ultrawide 3440x1440] [--hud-position edges] +# ./play-linux.sh /path/to/your/game_scarlett_master.exe [--series-x] [--aspect-ratio 21:9] [--hud-position edges] # # Leonida keeps its own Wine prefix (LEONIDA_WINEPREFIX, default ~/.local/share/leonida/prefix): the bundled # d3d12.dll and d3d12core.dll are installed there and preferred over Wine's (WINEDLLOVERRIDES), so no other prefix @@ -11,7 +11,7 @@ set -eu if [ $# -lt 1 ]; then - echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x] [--ultrawide WIDTHxHEIGHT|off] [--hud-position center|edges]" >&2 + echo "usage: $0 /path/to/game_scarlett_master.exe [--series-x] [--aspect-ratio auto|16:9|21:9|32:9] [--hud-position off|center|edges]" >&2 exit 2 fi game_exe=$1 @@ -21,6 +21,12 @@ while [ "$#" -gt 0 ]; do case "$1" in --series-x) console=series-x ;; + --aspect-ratio) + case "${2:-}" in + auto|16:9|21:9|32:9) export LEONIDA_ASPECT_RATIO="$2"; unset LEONIDA_NATIVE_ULTRAWIDE ;; + *) echo "--aspect-ratio wants auto, 16:9, 21:9, or 32:9" >&2; exit 2 ;; + esac + shift ;; --ultrawide) case "${2:-}" in off|3440x1440|3840x1080|5120x1440) export LEONIDA_NATIVE_ULTRAWIDE="$2" ;; @@ -29,18 +35,24 @@ while [ "$#" -gt 0 ]; do shift ;; --hud-position) case "${2:-}" in - center|edges) export LEONIDA_HUD_POSITION="$2" ;; - *) echo "--hud-position wants center or edges" >&2; exit 2 ;; + off|center|edges) export LEONIDA_HUD_POSITION="$2" ;; + *) echo "--hud-position wants off, center, or edges" >&2; exit 2 ;; esac shift ;; *) echo "Unknown option: $1" >&2; exit 2 ;; esac shift done -case "${LEONIDA_NATIVE_ULTRAWIDE:-}" in - ''|off|0) ;; - *) [ "$console" = series-x ] || { echo "Native ultrawide requires --series-x" >&2; exit 2; } ;; -esac +if [ "$console" = series-x ]; then + if [ -z "${LEONIDA_NATIVE_ULTRAWIDE:-}${LEONIDA_ASPECT_RATIO:-}" ]; then + export LEONIDA_ASPECT_RATIO=auto + fi +else + case "${LEONIDA_NATIVE_ULTRAWIDE:-${LEONIDA_ASPECT_RATIO:-}}" in + ''|off|0|auto|16:9) unset LEONIDA_ASPECT_RATIO ;; + *) echo "Native ultrawide requires --series-x" >&2; exit 2 ;; + esac +fi [ -f "$game_exe" ] || { echo "No $game_exe" >&2; exit 1; } here=$(cd "$(dirname "$0")" && pwd) diff --git a/tests/test_launcher_serve.py b/tests/test_launcher_serve.py index 19f9d5fdb6..6bfad18edc 100644 --- a/tests/test_launcher_serve.py +++ b/tests/test_launcher_serve.py @@ -12,6 +12,7 @@ import tempfile import threading import unittest +from unittest import mock ROOT = Path(__file__).resolve().parents[1] _spec = importlib.util.spec_from_file_location("leonida_launcher_serve", ROOT / "launcher" / "serve.py") @@ -142,6 +143,13 @@ def test_other_hosts_and_pages_are_refused(self): self.assertEqual(self.ask("GET", "/api/state", dict(token, Host="example.com"))[0], 403) self.assertEqual(self.ask("POST", "/api/play", dict(token, Origin="http://example.com"), b"{}")[0], 403) + def test_state_exposes_the_display_used_by_match_monitor(self): + context = {"monitor_ultrawide": True, "saved_aspect_ratio": "auto", "default_series_x": True} + with mock.patch.object(serve.core, "picture_context", return_value=context): + status, data = self.ask("GET", "/api/state", {"X-Leonida-Token": self.token}) + self.assertEqual(status, 200) + self.assertEqual(json.loads(data)["picture"], context) + def test_pictures_need_the_cookie(self): self.assertEqual(self.ask("GET", "/media/background")[0], 403) self.assertEqual(self.ask("GET", "/media/background", {"Cookie": f"leonida={self.token}"}), (200, PNG)) diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index 1d654a2fe2..1e0297c1a1 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -112,15 +112,56 @@ def test_linux_command(self): self.assertEqual(command, ["sh", os.path.join("/r", "scripts", "play-linux.sh"), os.path.join("/g", launcher.EXPECTED_EXE), "--series-x"]) - def test_ultrawide_is_forwarded_on_both_platforms_and_skipped_for_series_s(self): - selected = launcher.normalise(settings(ultrawide="5120x1440", hud_position="edges")) + def test_aspect_and_hud_are_forwarded_on_both_platforms(self): + selected = launcher.normalise(settings(aspect_ratio="32:9", hud_position="off")) windows = launcher.play_command(selected, windows=True) linux = launcher.play_command(selected, windows=False) - self.assertEqual(windows[-4:], ["-Ultrawide", "5120x1440", "-HudPosition", "edges"]) - self.assertEqual(linux[-5:], ["--series-x", "--ultrawide", "5120x1440", "--hud-position", "edges"]) + self.assertEqual(windows[-4:], ["-AspectRatio", "32:9", "-HudPosition", "off"]) + self.assertEqual(linux[-5:], ["--series-x", "--aspect-ratio", "32:9", "--hud-position", "off"]) selected["series_s"] = True self.assertEqual(launcher.switch_args(selected), ["-SeriesS"]) - self.assertEqual(launcher.normalise(settings(ultrawide="8192x2048"))["ultrawide"], "") + + def test_match_monitor_and_default_expose_and_forward_hud_on_ultrawide(self): + display = {"monitor_ultrawide": True, "saved_aspect_ratio": "auto", "default_series_x": True} + for aspect_ratio in ("", "auto"): + selected = settings(aspect_ratio=aspect_ratio, hud_position="off") + self.assertTrue(launcher.ultrawide_selected(selected, display, windows=True)) + self.assertEqual(launcher.play_command(selected, windows=True, picture=display)[-2:], + ["-HudPosition", "off"]) + selected["series_x"] = True + linux_display = dict(display, default_series_x=False) + self.assertEqual(launcher.play_command(selected, windows=False, picture=linux_display)[-2:], + ["--hud-position", "off"]) + standard = dict(display, monitor_ultrawide=False) + self.assertNotIn("-HudPosition", launcher.play_command(selected, windows=True, picture=standard)) + self.assertFalse(launcher.ultrawide_selected(settings(aspect_ratio="16:9"), display, windows=True)) + self.assertFalse(launcher.ultrawide_selected(settings(resolution="2160"), display, windows=True)) + saved_standard = dict(display, saved_aspect_ratio="16:9") + self.assertFalse(launcher.ultrawide_selected(settings(), saved_standard, windows=True)) + self.assertTrue(launcher.ultrawide_selected(settings(aspect_ratio="auto"), saved_standard, windows=True)) + self.assertFalse(launcher.ultrawide_selected(settings(), dict(display, default_series_x=False), windows=True)) + + def test_monitor_detection_matches_the_native_output_profiles(self): + for size in ((3440, 1440), (3840, 1080), (5120, 1440), (5120, 2160)): + self.assertTrue(launcher.monitor_is_ultrawide(size), size) + for size in ((1920, 1080), (2560, 1440), (3840, 2160)): + self.assertFalse(launcher.monitor_is_ultrawide(size), size) + + def test_saved_menu_aspect_and_console_are_used_for_default(self): + with tempfile.TemporaryDirectory() as repo: + path = Path(repo, "d3d12", "leonida-settings.txt") + path.parent.mkdir() + path.write_text("LEONIDA_MENU_CONSOLE=series-s\nLEONIDA_NATIVE_ULTRAWIDE=3840x1080\n", + encoding="utf-8", newline="\n") + display = launcher.picture_context(repo, windows=True) + self.assertEqual(display["saved_aspect_ratio"], "32:9") + self.assertFalse(display["default_series_x"]) + + def test_old_aspect_settings_migrate(self): + self.assertEqual(launcher.normalise({"ultrawide": "3440x1440"})["aspect_ratio"], "21:9") + self.assertEqual(launcher.normalise({"ultrawide": "3840x1080"})["aspect_ratio"], "32:9") + self.assertEqual(launcher.normalise({"ultrawide": "off"})["aspect_ratio"], "16:9") + self.assertEqual(launcher.normalise({"ultrawide": "5120x1440", "aspect_ratio": "16:9"})["aspect_ratio"], "16:9") def test_no_game_folder_is_refused(self): with self.assertRaises(ValueError): diff --git a/tests/test_win_launchers.py b/tests/test_win_launchers.py index a0cf3f3d66..12abda8b5b 100644 --- a/tests/test_win_launchers.py +++ b/tests/test_win_launchers.py @@ -86,7 +86,7 @@ def test_nvidia_menu_restart_preserves_motion_blur_switch(self) -> None: self.assertNotRegex(args, r"(?:^| )-MotionBlur(?: |$)") @unittest.skipUnless(POWERSHELL, "requires PowerShell") - def test_native_ultrawide_preserves_render_height_and_f1_restart_choices(self) -> None: + def test_aspect_ratio_infers_output_and_preserves_render_height_and_f1_choices(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) scripts = root / "scripts" @@ -96,7 +96,7 @@ def test_native_ultrawide_preserves_render_height_and_f1_restart_choices(self) - executable = root / "synthetic title.exe" executable.touch() (root / "leonida-settings.txt").write_text( - "LEONIDA_NATIVE_ULTRAWIDE=5120x1440\nLEONIDA_HUD_POSITION=center\n", encoding="utf-8", newline="\n" + "LEONIDA_NATIVE_ULTRAWIDE=3840x1080\nLEONIDA_HUD_POSITION=center\n", encoding="utf-8", newline="\n" ) command = r""" $ErrorActionPreference = 'Stop' @@ -114,8 +114,8 @@ def test_native_ultrawide_preserves_render_height_and_f1_restart_choices(self) - WindowsBarMB = 0 SeriesX = $true Resolution = '1080' - Ultrawide = '3840x1080' - HudPosition = 'edges' + AspectRatio = '21:9' + HudPosition = 'off' } & $env:TEST_NVIDIA_LAUNCHER @options & $env:TEST_NVIDIA_LAUNCHER @options -MenuRestart @@ -128,9 +128,10 @@ def test_native_ultrawide_preserves_render_height_and_f1_restart_choices(self) - ) lines = result.stdout.splitlines() for key, values in { - "LEONIDA_NATIVE_ULTRAWIDE": ["3840x1080", "5120x1440"], - "LEONIDA_HUD_POSITION": ["edges", "center"], - "LEONIDA_RENDER_SCALE": ["1", "0.75"], + "LEONIDA_ASPECT_RATIO": ["21:9"], + "LEONIDA_NATIVE_ULTRAWIDE": ["3440x1440", "3840x1080"], + "LEONIDA_HUD_POSITION": ["off", "center"], + "LEONIDA_RENDER_SCALE": ["0.75", "1"], }.items(): self.assertEqual([line.split("=", 1)[1] for line in lines if line.startswith(key + "=")], values) self.assertFalse(any(line.startswith("LEONIDA_OUTPUT=") for line in lines)) diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 2b2a4df4a1..13e78b006b 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -36,8 +36,10 @@ RESOLUTIONS = ("", "2160", "1440", "1080", "720", "540", "480") DLSS_MODES = ("", "quality", "balanced", "performance", "ultra") FRAME_GEN = (0, 2, 3, 4, 5, 6) -ULTRAWIDE_OUTPUTS = ("", "off", "3440x1440", "3840x1080", "5120x1440") -HUD_POSITIONS = ("", "center", "edges") +ASPECT_RATIOS = {"": "default", "auto": "Match monitor", "16:9": "16:9", "21:9": "21:9", "32:9": "32:9"} +LEGACY_ASPECT_RATIOS = {"off": "16:9", "0": "16:9", "3440x1440": "21:9", "3840x1080": "32:9", "5120x1440": "32:9"} +WIDE_ASPECTS = ("21:9", "32:9") +HUD_POSITIONS = {"": "default", "edges": "Screen edges", "center": "Centered", "off": "Off"} PRESENT_SCALES = ("", "fit", "stretch") ASPECT = re.compile(r"^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$") # the script's own pattern for -Aspect ADAPTER = re.compile(r"^[\w #.()+-]{0,64}$") # part of a card's name, or # @@ -57,7 +59,7 @@ "series_s": False, # -SeriesS (the script's default is Series X) "dlss_mode": "", # -Dlss , empty = the profile's own path "frame_gen": 0, # -FrameGen , 0 = off - "ultrawide": "", # -Ultrawide , empty = follow the F1 settings + "aspect_ratio": "", # -AspectRatio , empty = follow the F1 settings "hud_position": "", # -HudPosition , empty = follow the F1 settings "aspect": "", # -Aspect , empty = 16:9 "present_scale": "", # -PresentScale, with -Aspect; empty = the script's default (fit) @@ -66,7 +68,7 @@ } # The options with a fixed set of values, and the others whose text has to match a pattern. CHOICES: dict = {"resolution": RESOLUTIONS, "dlss_mode": DLSS_MODES, "frame_gen": FRAME_GEN, - "present_scale": PRESENT_SCALES, "ultrawide": ULTRAWIDE_OUTPUTS, "hud_position": HUD_POSITIONS} + "present_scale": PRESENT_SCALES, "aspect_ratio": ASPECT_RATIOS, "hud_position": HUD_POSITIONS} PATTERNS: dict = {"aspect": ASPECT, "adapter": ADAPTER} @@ -99,6 +101,9 @@ def normalise(data: object) -> dict: settings[key] = value.strip() if isinstance(value, str) and PATTERNS[key].match(value.strip()) else default else: settings[key] = value if isinstance(value, str) else default + legacy = data.get("ultrawide") + if "aspect_ratio" not in data and isinstance(legacy, str): + settings["aspect_ratio"] = LEGACY_ASPECT_RATIOS.get(legacy, "") if settings["series_s"]: settings["series_x"] = False return settings @@ -130,7 +135,87 @@ def mods_dir_of(settings: dict) -> str: # ---------------------------------------------------------------- the command line -def switch_args(settings: dict) -> list[str]: +def primary_display_size() -> tuple[int, int] | None: + """Read the current primary display mode in physical pixels on Windows.""" + if not WINDOWS: + return None + import ctypes + from ctypes import wintypes + + class DevMode(ctypes.Structure): + # DEVMODEW, with the unused union members represented by their display fields. + _fields_ = [ + ("device_name", wintypes.WCHAR * 32), + ("spec_version", wintypes.WORD), ("driver_version", wintypes.WORD), + ("size", wintypes.WORD), ("driver_extra", wintypes.WORD), ("fields", wintypes.DWORD), + ("display", wintypes.DWORD * 4), + ("print_fields", ctypes.c_short * 5), ("form_name", wintypes.WCHAR * 32), + ("log_pixels", wintypes.WORD), ("bits_per_pixel", wintypes.DWORD), + ("width", wintypes.DWORD), ("height", wintypes.DWORD), ("remaining", wintypes.DWORD * 10), + ] + + mode = DevMode() + mode.size = ctypes.sizeof(mode) + current_display_settings = 0xFFFFFFFF + read_mode = ctypes.windll.user32.EnumDisplaySettingsW + read_mode.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.LPVOID) + read_mode.restype = wintypes.BOOL + if read_mode(None, current_display_settings, ctypes.byref(mode)): + return mode.width, mode.height + width = ctypes.windll.user32.GetSystemMetrics(0) + height = ctypes.windll.user32.GetSystemMetrics(1) + return (width, height) if width > 0 and height > 0 else None + + +def monitor_is_ultrawide(size: tuple[int, int]) -> bool: + """Match the native aspect classifier in leonida-gpu/src/aspect.rs.""" + width, height = size + return ((height >= 1080 and width * 9 == height * 32) + or (width >= 3440 and height >= 1440 and abs(width * 27 - height * 64) * 100 <= height * 64)) + + +def picture_context(repo: str = REPO, windows: bool = WINDOWS, + screen: tuple[int, int] | None = None) -> dict: + saved = {} + if windows: + keys = {"LEONIDA_MENU_CONSOLE", "LEONIDA_ASPECT_RATIO", "LEONIDA_NATIVE_ULTRAWIDE"} + try: + with open(os.path.join(repo, "d3d12", "leonida-settings.txt"), encoding="utf-8-sig") as file: + for line in file: + key, _, value = line.partition("=") + key = key.strip().upper() + if key in keys: + saved[key] = value.strip().lower() + except (OSError, UnicodeError): + pass + screen = primary_display_size() or screen + aspect = saved.get("LEONIDA_ASPECT_RATIO") + if aspect not in ASPECT_RATIOS or not aspect: + legacy = saved.get("LEONIDA_NATIVE_ULTRAWIDE") + aspect = "16:9" if legacy == "" else LEGACY_ASPECT_RATIOS.get(legacy, "auto") + return {"monitor_ultrawide": None if screen is None else monitor_is_ultrawide(screen), + "saved_aspect_ratio": aspect, + "default_series_x": windows and saved.get("LEONIDA_MENU_CONSOLE") != "series-s"} + + +def ultrawide_selected(settings: dict, picture: dict, windows: bool = WINDOWS) -> bool | None: + """None means the automatic selection depends on a display we could not query.""" + aspect = settings["aspect_ratio"] + if settings["series_s"]: + return False + if aspect in WIDE_ASPECTS: + return True + if not (settings["series_x"] or picture["default_series_x"]): + return False + aspect = aspect or picture["saved_aspect_ratio"] + if aspect != "auto": + return aspect in WIDE_ASPECTS + if windows and settings["resolution"] == "2160" and not (settings["dlss"] and settings["dlss_mode"]): + return False + return picture["monitor_ultrawide"] + + +def switch_args(settings: dict, picture: dict | None = None) -> list[str]: """The PowerShell switches the options stand for (scripts/play-d3d12.ps1).""" args: list[str] = [] if settings["series_s"]: @@ -154,9 +239,9 @@ def switch_args(settings: dict) -> list[str]: if settings["resolution"] and not (settings["dlss"] and settings["dlss_mode"]): args += ["-Resolution", settings["resolution"]] # the script wants it left out with a DLSS mode if not settings["series_s"]: - if settings["ultrawide"]: - args += ["-Ultrawide", settings["ultrawide"]] - if settings["hud_position"]: + if settings["aspect_ratio"]: + args += ["-AspectRatio", settings["aspect_ratio"]] + if settings["hud_position"] and ultrawide_selected(settings, picture or picture_context(windows=True), True) is not False: args += ["-HudPosition", settings["hud_position"]] if settings["aspect"]: args += ["-Aspect", settings["aspect"]] @@ -171,7 +256,8 @@ def switch_args(settings: dict) -> list[str]: return args -def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS) -> list[str]: +def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS, + picture: dict | None = None) -> list[str]: """The command PLAY runs. Raises ValueError when the game folder is not set.""" game = settings["game_dir"].strip() if not game: @@ -181,14 +267,16 @@ def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS) -> l os.path.join(repo, "scripts", "play-d3d12.ps1"), "-Game", game] if settings["data_dir"].strip(): command += ["-Data", settings["data_dir"].strip()] - return command + switch_args(settings) + if picture is None and settings["hud_position"]: + picture = picture_context(repo, windows) + return command + switch_args(settings, picture) command = ["sh", os.path.join(repo, "scripts", "play-linux.sh"), os.path.join(game, EXPECTED_EXE)] - if settings["series_x"] or (not settings["series_s"] and settings["ultrawide"] not in ("", "off")): + if not settings["series_s"] and (settings["series_x"] or settings["aspect_ratio"] in WIDE_ASPECTS): command.append("--series-x") if not settings["series_s"]: - if settings["ultrawide"]: - command += ["--ultrawide", settings["ultrawide"]] - if settings["hud_position"]: + if settings["aspect_ratio"]: + command += ["--aspect-ratio", settings["aspect_ratio"]] + if settings["hud_position"] and ultrawide_selected(settings, picture or picture_context(repo, windows), False) is not False: command += ["--hud-position", settings["hud_position"]] return command @@ -391,6 +479,11 @@ def run_gui() -> int: class Launcher: PAGES = ("Play", "Settings", "Mods", "Saves", "Tools", "About") + PICTURE_CHOICES = { + "resolution": {value: value or "default" for value in RESOLUTIONS}, + "aspect_ratio": ASPECT_RATIOS, + "hud_position": HUD_POSITIONS, + } def __init__(self, root): self.root = root @@ -493,6 +586,8 @@ def show(self, name): self.refresh_saves() if name == "Play": self.refresh_hero() + if name == "Settings": + self.update_picture_choices() # ---- Play def build_play(self): @@ -585,8 +680,11 @@ def play(self): "Choose the folder of your own copy in Settings.") self.show("Settings") return + settings = self.settings + if not settings["series_x"]: + settings = dict(settings, aspect_ratio="", hud_position="") try: - command = play_command(self.settings) + command = play_command(settings) except ValueError as exc: messagebox.showwarning("Play", str(exc)) return @@ -702,21 +800,24 @@ def build_settings(self): self.vars[key] = var ttk.Checkbutton(options, text=text, variable=var).grid(row=index // 2, column=index % 2, sticky="w", pady=3) - ttk.Label(options, text="Resolution (-Resolution)").grid(row=4, column=0, sticky="w", pady=(10, 0)) - res = tk.StringVar(value=self.settings["resolution"] or "default") - self.vars["resolution"] = res - ttk.Combobox(options, textvariable=res, state="readonly", width=12, - values=["default"] + [r for r in RESOLUTIONS if r]).grid(row=4, column=1, sticky="w", - pady=(10, 0)) - for row, key, label, values in ( - (5, "ultrawide", "Series X ultrawide output", ULTRAWIDE_OUTPUTS), - (6, "hud_position", "Ultrawide HUD position", HUD_POSITIONS), - ): - ttk.Label(options, text=label).grid(row=row, column=0, sticky="w", pady=(6, 0)) - var = tk.StringVar(value=self.settings[key] or "default") + + def picture_choice(row, key, label): + values = self.PICTURE_CHOICES[key] + name = ttk.Label(options, text=label) + name.grid(row=row, column=0, sticky="w", pady=(8, 0)) + var = tk.StringVar(value=values[self.settings[key]]) self.vars[key] = var - ttk.Combobox(options, textvariable=var, state="readonly", width=12, - values=["default", *values[1:]]).grid(row=row, column=1, sticky="w", pady=(6, 0)) + box = ttk.Combobox(options, textvariable=var, state="readonly", width=16, + values=list(values.values())) + box.grid(row=row, column=1, sticky="w", pady=(8, 0)) + return name, box + + picture_choice(4, "resolution", "Resolution (-Resolution)") + self.aspect_controls = picture_choice(5, "aspect_ratio", "Aspect ratio (-AspectRatio)") + self.hud_controls = picture_choice(6, "hud_position", "Ultrawide HUD correction (-HudPosition)") + for key in ("aspect_ratio", "resolution", "series_x", "dlss"): + self.vars[key].trace_add("write", self.update_picture_choices) + self.update_picture_choices() if not WINDOWS: ttk.Label(inner, text="On Linux the launcher starts scripts/play-linux.sh, which takes the " "game folder, Series X profile and ultrawide settings.", @@ -743,12 +844,32 @@ def check_game(self): else: self.game_check.set(f"{EXPECTED_EXE} is not in this folder.") + def update_picture_choices(self, *_): + series_x = self.vars["series_x"].get() + wide = False + if series_x: + settings = dict(self.settings, series_x=True, series_s=False, + aspect_ratio=self.setting_value("aspect_ratio"), + resolution=self.setting_value("resolution"), dlss=self.vars["dlss"].get()) + screen = self.root.winfo_screenwidth(), self.root.winfo_screenheight() + wide = ultrawide_selected(settings, picture_context(screen=screen)) + for controls, visible in ((self.aspect_controls, series_x), (self.hud_controls, wide)): + for control in controls: + if visible: + control.grid() + else: + control.grid_remove() + + def setting_value(self, key): + value = self.vars[key].get() + if key in self.PICTURE_CHOICES: + return next((option for option, label in self.PICTURE_CHOICES[key].items() if label == value), "") + return value.strip() if isinstance(value, str) else value + def collect_settings(self): - for key, var in self.vars.items(): - value = var.get() - if key in ("resolution", "ultrawide", "hud_position"): - value = "" if value == "default" else value - self.settings[key] = value.strip() if isinstance(value, str) else value + self.settings.update({key: self.setting_value(key) for key in self.vars}) + if self.settings["series_x"]: + self.settings["series_s"] = False self.settings = normalise(self.settings) def save(self): From 3a3fd64259eb94d012477e5b06516e4dbfe54928 Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:24 +0100 Subject: [PATCH 3/6] Preserve older launcher builds and validate wide shadow packing --- d3d12/scripts/play-nvidia.ps1 | 12 +++++-- docs/design.md | 2 +- .../fixtures/wide_shadow_tile_coords.asm | 14 ++++++++ .../semantic/test_wide_shadow_tile_coords.py | 13 ++++++++ tests/test_win_launchers.py | 32 ++++++++++++++++++- 5 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 tests/semantic/fixtures/wide_shadow_tile_coords.asm create mode 100644 tests/semantic/test_wide_shadow_tile_coords.py diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 26fe45fc43..89feb87a0c 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -431,7 +431,7 @@ if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -no if ($Fullscreen) { $settings.LEONIDA_FULLSCREEN = '1' } if ($AspectRatio) { $settings.LEONIDA_ASPECT_RATIO = $AspectRatio } if ($Ultrawide) { $settings.LEONIDA_NATIVE_ULTRAWIDE = $Ultrawide } -if ($HudPosition) { $settings.LEONIDA_HUD_POSITION = $HudPosition } +if ($HudPosition) { $settings.LEONIDA_HUD_POSITION = $HudPosition.ToLowerInvariant() } if ($Aspect) { $settings.LEONIDA_ASPECT = $Aspect } if ($PresentScale) { $settings.LEONIDA_PRESENT_SCALE = $PresentScale } if ($StreamlineDir) { $settings.LEONIDA_STREAMLINE_DIR = $StreamlineDir } @@ -640,6 +640,7 @@ if ($console -ne 'series-x') { $nativeAspect = '' $nativeOutput = '' } elseif (($nativeAspect -and -not $More.ContainsKey('LEONIDA_NATIVE_ULTRAWIDE')) -or -not $nativeOutput) { + $explicitNativeAspect = [bool]$nativeAspect if (-not $nativeAspect) { $nativeAspect = 'auto' } $settings.LEONIDA_ASPECT_RATIO = $nativeAspect $settings.Remove('LEONIDA_NATIVE_ULTRAWIDE') @@ -647,8 +648,13 @@ if ($console -ne 'series-x') { if ($nativeAspect -eq '16:9' -or ($nativeAspect -eq 'auto' -and ($Resolution -eq '2160' -or $More.ContainsKey('LEONIDA_OUTPUT')))) { $settings.LEONIDA_NATIVE_ULTRAWIDE = 'off' } elseif (Test-Path $leonida) { - $nativeOutput = "$(& $leonida aspect-output $nativeAspect)" - if ($LASTEXITCODE -ne 0) { throw 'Could not resolve the aspect ratio. Rebuild leonida.exe and try again.' } + $nativeOutput = "$(& $leonida aspect-output $nativeAspect 2>$null)".Trim() + if ($LASTEXITCODE -ne 0) { + if ($explicitNativeAspect) { throw 'Could not resolve the aspect ratio. Rebuild leonida.exe and try again.' } + $settings.Remove('LEONIDA_ASPECT_RATIO') + $nativeOutput = '' + Write-Host 'Using the default output. Rebuild leonida.exe to enable automatic aspect ratio selection.' + } if (-not $nativeOutput) { $settings.LEONIDA_NATIVE_ULTRAWIDE = 'off' } } elseif ($nativeAspect -eq '21:9') { $nativeOutput = '3440x1440' diff --git a/docs/design.md b/docs/design.md index e70a1b12c7..dedad7bb88 100644 --- a/docs/design.md +++ b/docs/design.md @@ -294,7 +294,7 @@ Test shaders are in `\gputest`. | Direct3D 12 shader rule | Contract and evidence | |---|---| -| Wide directional shadow lists | The Series X retail shader writers and readers use 9 horizontal and 7 vertical tile-coordinate bits above a 4096-pixel scene width. The rewrite checks both the shader digest and the words it replaces. The wide layout has a separate shader-cache key. Synthetic writer and reader fixtures in `d3d12/crates/leonida-shader/src/emit/wide_shadow_tiles.rs` check the packing and that mismatched words are left intact. | +| Wide directional shadow lists | The Series X retail shader writers and readers use 9 horizontal and 7 vertical tile-coordinate bits above a 4096-pixel scene width. The rewrite checks both the shader digest and the words it replaces. The wide layout has a separate shader-cache key. Rust fixtures check the rewrite and rejection of mismatched words. `tests/semantic/fixtures/wide_shadow_tile_coords.asm` checks coordinate extraction beyond the old horizontal limit. The [Foxhound port](https://github.com/readmet3xt-lab/foxhound/pull/281) verified right-side outdoor shadows at 5120×1440 with DLAA on a Windows RTX 4090. | Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **All 26,503 shaders translate and pass `spirv-val`** (Vulkan 1.2 target, `--allow-offset-texture-operand`): 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry. `spirv/index.json` lists each one's requirements. Output: diff --git a/tests/semantic/fixtures/wide_shadow_tile_coords.asm b/tests/semantic/fixtures/wide_shadow_tile_coords.asm new file mode 100644 index 0000000000..eee74b7aba --- /dev/null +++ b/tests/semantic/fixtures/wide_shadow_tile_coords.asm @@ -0,0 +1,14 @@ +; Round-trip a tile beyond the 8-bit X range through both readers. + s_mov_b32 s12, 89 + s_lshl_b32 s12, s12, 9 + s_or_b32 s12, s12, 319 + s_or_b32 s12, s12, 0xa55a0000 + s_bfe_u32 s13, s12, 0x00090000 + s_bfe_u32 s14, s12, 0x00070009 + v_mov_b32 v0, s13 + v_mov_b32 v1, s14 + v_mov_b32 v2, s12 + v_bfe_u32 v3, v2, 0, 9 + v_bfe_u32 v4, v2, 9, 7 + exp mrt0 v0, v1, v3, v4 done vm + s_endpgm diff --git a/tests/semantic/test_wide_shadow_tile_coords.py b/tests/semantic/test_wide_shadow_tile_coords.py new file mode 100644 index 0000000000..c15cfc9b91 --- /dev/null +++ b/tests/semantic/test_wide_shadow_tile_coords.py @@ -0,0 +1,13 @@ +"""Verify that the 9/7 layout preserves both tile coordinates.""" + +from pathlib import Path +import unittest + +from support import HERE, mrt0_words, translate_listing + + +class WideShadowTileCoordinates(unittest.TestCase): + def test_tile_across_the_old_horizontal_boundary(self): + fixture = Path(HERE) / "fixtures" / "wide_shadow_tile_coords.asm" + translated = translate_listing("ps_wide_shadow_tile_coords", fixture.read_bytes()) + self.assertEqual(mrt0_words(translated), [319, 89, 319, 89]) diff --git a/tests/test_win_launchers.py b/tests/test_win_launchers.py index 12abda8b5b..1cc4b8c649 100644 --- a/tests/test_win_launchers.py +++ b/tests/test_win_launchers.py @@ -115,7 +115,7 @@ def test_aspect_ratio_infers_output_and_preserves_render_height_and_f1_choices(s SeriesX = $true Resolution = '1080' AspectRatio = '21:9' - HudPosition = 'off' + HudPosition = 'OFF' } & $env:TEST_NVIDIA_LAUNCHER @options & $env:TEST_NVIDIA_LAUNCHER @options -MenuRestart @@ -136,6 +136,36 @@ def test_aspect_ratio_infers_output_and_preserves_render_height_and_f1_choices(s self.assertEqual([line.split("=", 1)[1] for line in lines if line.startswith(key + "=")], values) self.assertFalse(any(line.startswith("LEONIDA_OUTPUT=") for line in lines)) + @unittest.skipUnless(os.name == "nt" and POWERSHELL, "requires Windows and PowerShell") + def test_existing_runtime_without_aspect_command_can_launch_at_default_output(self) -> None: + with tempfile.TemporaryDirectory() as td: + root = Path(td) + scripts = root / "scripts" + scripts.mkdir() + launcher = scripts / NVIDIA_LAUNCHER.name + shutil.copyfile(NVIDIA_LAUNCHER, launcher) + runtime = root / "target" / "diag" / "leonida.exe" + runtime.parent.mkdir(parents=True) + shutil.copyfile(Path(os.environ["SystemRoot"], "System32", "where.exe"), runtime) + executable = root / "synthetic title.exe" + executable.touch() + + command = r""" +$ErrorActionPreference = 'Stop' +function Get-CimInstance { [pscustomobject]@{ BuildNumber = '26100' } } +& $env:TEST_NVIDIA_LAUNCHER -Exe $env:TEST_NVIDIA_EXE -SeriesX -DryRun -NoDlss -NoFrameGen -NoPrecompile -WindowsBarMB 0 +""" + env = {name: value for name, value in os.environ.items() if not name.upper().startswith("LEONIDA_")} + env.update(TEST_NVIDIA_LAUNCHER=str(launcher), TEST_NVIDIA_EXE=str(executable)) + result = subprocess.run( + [POWERSHELL, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], + env=env, capture_output=True, encoding="utf-8", errors="replace", timeout=30, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + lines = result.stdout.splitlines() + self.assertIn("LEONIDA_NATIVE_ULTRAWIDE=off", lines) + self.assertFalse(any(line.startswith("LEONIDA_ASPECT_RATIO=") for line in lines)) + def test_static_quoting_and_no_pause_guards(self) -> None: build_txt = BUILD_BAT.read_text(encoding="utf-8") mods_txt = MODS_BAT.read_text(encoding="utf-8") From 858fdd67616fd18acea3aa6d1c9460262d9d127d Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:31:24 +0100 Subject: [PATCH 4/6] Handle aspect probe stderr on Windows PowerShell --- d3d12/scripts/play-nvidia.ps1 | 6 +++++- tests/test_win_launchers.py | 19 ++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 89feb87a0c..2fcb96e964 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -648,7 +648,11 @@ if ($console -ne 'series-x') { if ($nativeAspect -eq '16:9' -or ($nativeAspect -eq 'auto' -and ($Resolution -eq '2160' -or $More.ContainsKey('LEONIDA_OUTPUT')))) { $settings.LEONIDA_NATIVE_ULTRAWIDE = 'off' } elseif (Test-Path $leonida) { - $nativeOutput = "$(& $leonida aspect-output $nativeAspect 2>$null)".Trim() + $nativeOutput = "$(& { + # Windows PowerShell can treat native stderr as a terminating error. + $ErrorActionPreference = 'Continue' + & $leonida aspect-output $nativeAspect 2>$null + })".Trim() if ($LASTEXITCODE -ne 0) { if ($explicitNativeAspect) { throw 'Could not resolve the aspect ratio. Rebuild leonida.exe and try again.' } $settings.Remove('LEONIDA_ASPECT_RATIO') diff --git a/tests/test_win_launchers.py b/tests/test_win_launchers.py index 1cc4b8c649..ff7e43fda1 100644 --- a/tests/test_win_launchers.py +++ b/tests/test_win_launchers.py @@ -15,7 +15,8 @@ BUILD_BAT = ROOT / "Build.bat" MODS_BAT = ROOT / "Mods.bat" NVIDIA_LAUNCHER = ROOT / "d3d12" / "scripts" / "play-nvidia.ps1" -POWERSHELL = shutil.which("pwsh") or shutil.which("powershell.exe") +WINDOWS_POWERSHELL = shutil.which("powershell.exe") +POWERSHELL = shutil.which("pwsh") or WINDOWS_POWERSHELL FAKE_PY_CS = r""" using System; @@ -136,7 +137,7 @@ def test_aspect_ratio_infers_output_and_preserves_render_height_and_f1_choices(s self.assertEqual([line.split("=", 1)[1] for line in lines if line.startswith(key + "=")], values) self.assertFalse(any(line.startswith("LEONIDA_OUTPUT=") for line in lines)) - @unittest.skipUnless(os.name == "nt" and POWERSHELL, "requires Windows and PowerShell") + @unittest.skipUnless(WINDOWS_POWERSHELL, "requires Windows PowerShell") def test_existing_runtime_without_aspect_command_can_launch_at_default_output(self) -> None: with tempfile.TemporaryDirectory() as td: root = Path(td) @@ -146,19 +147,27 @@ def test_existing_runtime_without_aspect_command_can_launch_at_default_output(se shutil.copyfile(NVIDIA_LAUNCHER, launcher) runtime = root / "target" / "diag" / "leonida.exe" runtime.parent.mkdir(parents=True) - shutil.copyfile(Path(os.environ["SystemRoot"], "System32", "where.exe"), runtime) executable = root / "synthetic title.exe" executable.touch() command = r""" $ErrorActionPreference = 'Stop' +Add-Type -OutputAssembly $env:TEST_RUNTIME_EXE -OutputType ConsoleApplication -TypeDefinition @' +using System; +class OldRuntime { + public static int Main() { + Console.Error.WriteLine("Unrecognized subcommand"); + return 2; + } +} +'@ function Get-CimInstance { [pscustomobject]@{ BuildNumber = '26100' } } & $env:TEST_NVIDIA_LAUNCHER -Exe $env:TEST_NVIDIA_EXE -SeriesX -DryRun -NoDlss -NoFrameGen -NoPrecompile -WindowsBarMB 0 """ env = {name: value for name, value in os.environ.items() if not name.upper().startswith("LEONIDA_")} - env.update(TEST_NVIDIA_LAUNCHER=str(launcher), TEST_NVIDIA_EXE=str(executable)) + env.update(TEST_NVIDIA_LAUNCHER=str(launcher), TEST_NVIDIA_EXE=str(executable), TEST_RUNTIME_EXE=str(runtime)) result = subprocess.run( - [POWERSHELL, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], + [WINDOWS_POWERSHELL, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", command], env=env, capture_output=True, encoding="utf-8", errors="replace", timeout=30, ) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) From e7912f698ef17d04043cba2703dfeef15156cdf0 Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:58:58 +0100 Subject: [PATCH 5/6] Fix fractional DPI HUD selection and wide shader compilation Regenerate the switch reference for the drift check added in #2934. Validated four launcher cases, all 20 switch-documentation checks, and both synthetic D3D12 readbacks on Windows with an RTX 4090 (driver 621.01). Independent review used GPT-6.2 Sol. --- d3d12/crates/leonida-gpu/src/compose.rs | 4 ++- d3d12/docs/switches.md | 25 +++++++++------ launcher/index.html | 14 +++++++-- tests/test_launcher_display.cjs | 42 +++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 13 deletions(-) create mode 100644 tests/test_launcher_display.cjs diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 00ab86f53a..567297a41a 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs @@ -622,9 +622,11 @@ impl Composer { wide: bool, ) -> windows::core::Result { let source = if wide { SOURCE } else { STOCK_SOURCE }; + // The bundled D3DCompiler rejects the wide pixel shader's ps_5_1 bytecode. + let pixel_target = if wide { s!("ps_5_0") } else { s!("ps_5_1") }; let (vs, ps) = ( compile(source, s!("vs"), s!("vs_5_1"))?, - compile(source, s!("ps"), s!("ps_5_1"))?, + compile(source, s!("ps"), pixel_target)?, ); // SAFETY: the blobs' own bytes, alive through the calls. unsafe { diff --git a/d3d12/docs/switches.md b/d3d12/docs/switches.md index 33bc9b3cc9..2553cbb974 100644 --- a/d3d12/docs/switches.md +++ b/d3d12/docs/switches.md @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is ** settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first, and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. -674 names; 634 have a sentence of a comment below, the others no comment or only a bare list. +681 names; 633 have a sentence of a comment below, the others no comment or only a bare list. - **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a switch read some other way; its default is not given here. @@ -37,7 +37,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_GAME_ACTIONS` | see the code | | | | `leonida/game_actions.rs` +7 | Where the title's own code for the trainer menu's game actions is, and the hook that runs them once a frame on the title's own thread (`docs/mod-menu.md`, "Game actions"). Off unless `LEONIDA_GAME_ACTIONS=1`. | | `LEONIDA_GAME_ACTIONS_RUN` | see the code | | | | `leonida/game_actions.rs` | ...by default until it has been seen to work in the title). - `LEONIDA_GAME_ACTIONS_RUN="<s>:<command>;..."` asks for commands that many seconds after the start, for a test without the keyboard: `info`, `cheat <n>`, `wanted... | | `LEONIDA_GAME_ACTIONS_WARP` | see the code | | | | `leonida/game_actions.rs` +1 | ...ts results into the log: the arguments are the asker's). - `LEONIDA_GAME_ACTIONS_WARP=1` lets a teleport write the ped's position on the title's thread: an experiment, the title's own function for moving a ped was not fo... | -| `LEONIDA_GAME_DIR` | see the code | | | | `leonida/leonida.rs` +7 | With `LEONIDA_GAME_DIR` set to the folder of the Xbox package: every place is in the code of `game_scarlett_master.exe` exactly once and points inside the image. | +| `LEONIDA_GAME_DIR` | see the code | | | | `leonida/leonida.rs` +8 | With `LEONIDA_GAME_DIR` set to the folder of the Xbox package: every place is in the code of `game_scarlett_master.exe` exactly once and points inside the image. | | `LEONIDA_HOST_MAX_WAVE` | see the code | | | | `leonida/translate.rs` | `LEONIDA_HOST_MAX_WAVE=32`: translate as for a host whose waves have at most 32 lanes (as the runtime does on such a card). | | `LEONIDA_HOST_RDNA` | see the code | | | yes | `leonida/translate.rs` | `LEONIDA_HOST_RDNA=1`: as for an AMD RDNA card (`LEONIDA_RDNA_FLOAT`). | | `LEONIDA_HOST_WAVE` | see the code | | | yes | `leonida/main.rs` | Set `LEONIDA_HOST_WAVE` and `LEONIDA_VIEW_LIMIT` to what the run's log says of the host. | @@ -52,6 +52,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_NATIVE_MIN_RUN` | see the code | | | | `leonida/native_scan.rs` | Tuning, all optional: - `LEONIDA_NATIVE_MIN_RUN` (default 64): fewest array elements in a run. - `LEONIDA_NATIVE_MIN_DISTINCT` (default 200): fewest distinct handlers for a run to be listed and to enter the union. - `LEO... | | `LEONIDA_NATIVE_SCAN` | see the code | | | | `leonida/native_scan.rs` +1 | Diagnostics only (`LEONIDA_NATIVE_SCAN`): looks, at run time, for the tables the title's script engine calls its commands through. | | `LEONIDA_NATIVE_U32` | see the code | | | | `leonida/native_scan.rs` | ...ction start, or a 16-aligned byte after `int3` padding). - `LEONIDA_NATIVE_U32=1`: also looks for arrays of 32-bit offsets that are handler addresses relative to some base `B` (see `OffsetArray`).... | +| `LEONIDA_NATIVE_ULTRAWIDE` | see the code | | yes | | `leonida/ultrawide.rs` +2 | | | `LEONIDA_OWN_UPSCALER` | see the code | | yes | | `leonida/run.rs` +4 | LOCAL (leonida-perf, via our wt5): LEONIDA_RENDER_SCALE / LEONIDA_OWN_UPSCALER / LEONIDA_NO_WATCHDOG title patches. | | `LEONIDA_PAIRS` | see the code | | | | `leonida/translate.rs` | Shaders named in `LEONIDA_PAIRS` (`vs+ps,...`, label substrings), kept to build those pipelines after the walk. | | `LEONIDA_PED_DUMP` | see the code | | | | `leonida/player_context.rs` | `LEONIDA_PED_DUMP=<folder>` (outside the repository) is for measuring: F8 in the game's window, or a file named `dump` in that folder (its text is the dump's label; it is removed as it is seen), writes the first 0x4000 b... | @@ -82,6 +83,8 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_RECORD` | see the code | | | | `leonida/replay.rs` +2 | On with `LEONIDA_RECORD=<folder>` only; without it nothing is hooked. | | `LEONIDA_RELAY` | see the code | | yes | | `leonida/leonida.rs` +8 | The relay's first stage (`LEONIDA_RELAY=1`; off by default; it turns [`late`] on at stage 3 unless `LEONIDA_LATE_WAIT` says another stage, and is off with it, in the timing run and with kept snapshots). | | `LEONIDA_RENDER_SCALE` | see the code | | yes | | `leonida/leonida.rs` +5 | The scale `LEONIDA_RENDER_SCALE` asks for, if valid. | +| `LEONIDA_RT_HEAP_MB` | see the code | | | | `leonida/heap_budget.rs` | | +| `LEONIDA_SCENE_POOL_MB` | see the code | | | | `leonida/heap_budget.rs` | | | `LEONIDA_SHADER_CENSUS` | see the code | | | yes | `leonida/translate.rs` +2 | `LEONIDA_SHADER_CENSUS=<file>`: one line per emitted program, appended: its label, the console program's instructions by encoding class (a static count of the whole program, not of one thread's path), and the host module... | | `LEONIDA_SKIP_BINK` | see the code | | | | `leonida/run.rs` +1 | Skipping the title's Bink movies on request (`LEONIDA_SKIP_BINK`). - unset, empty or `0`: nothing changes, and no import is bound anew; - `1`: the movies that play once (logos, the intro) are skipped; - `all`: the loopin... | | `LEONIDA_SKIP_CPU_CHECK` | see the code | | | | `leonida/run.rs` | | @@ -142,7 +145,8 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_ASK_GAP_KB_AB` | see the code | | | yes | `leonida-gpu/watch.rs` | Named in `LEONIDA_AB`, the gap asked for against `LEONIDA_ASK_GAP_KB_AB` (256 when not set). | | `LEONIDA_ASK_ONCE` | see the code | | | | `leonida-gpu/host.rs` +1 | Whether a submission asks the kernel once, before its first refresh, about every range its lists refresh (`LEONIDA_ASK_ONCE=1`; off by default). | | `LEONIDA_ASK_RANGES` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether an asking for a submission holds the page ranges it asks the kernel about and no others (`LEONIDA_ASK_RANGES=0`: all of memory, as before). [`ask_ahead`] and [`ask_rest`] held everything ([`Asking::hold_all`]) wh... | -| `LEONIDA_ASPECT` | see the code | | yes | | `leonida-gpu/aspect.rs` +4 | Two settings, the ones `docs/ultrawide.md` gives the Vulkan runtime: - `LEONIDA_ASPECT=21:9\|32:9\|16:9\|W:H\|<decimal>\|auto`: the shape the title's window is made in (`auto`: the primary monitor's). | +| `LEONIDA_ASPECT` | see the code | | yes | | `leonida-gpu/aspect.rs` +4 | `LEONIDA_ASPECT` and `LEONIDA_PRESENT_SCALE` control window shape and fitting. | +| `LEONIDA_ASPECT_RATIO` | see the code | | yes | | `leonida-gpu/aspect.rs` +1 | `LEONIDA_ASPECT_RATIO` selects native output. | | `LEONIDA_ASYNC_SUBMIT` | see the code | yes | | yes | `leonida-gpu/queue.rs` +1 | Submissions prepared and sent by a thread of ours, in order, instead of by the thread of the title that submits them (`LEONIDA_ASYNC_SUBMIT=1`). | | `LEONIDA_BACK_RENEW` | on, `0` turns it off | yes | | | `leonida-gpu/host.rs` +1 | `LEONIDA_BACK_RENEW=0`: a stale one is kept, as before. | | `LEONIDA_BAKE_AHEAD` | see the code | yes | | yes | `leonida-gpu/draw.rs` | ...e air, waiting for the uploads and showing the slots then (`LEONIDA_BAKE_AHEAD=1`, or by turns with `LEONIDA_AB`; off by default).... | @@ -195,7 +199,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_COMMITTED_QUERY` | see the code | | | | `leonida-gpu/texture.rs` | Whether the two questions above and below are put to `VirtualQuery`, as they were (`LEONIDA_COMMITTED_QUERY=1`). | | `LEONIDA_COMMIT_FLOOR` | see the code | yes | | yes | `leonida-gpu/resource.rs` | `LEONIDA_COMMIT_FLOOR=1` (off by default; `LEONIDA_AB` can name it), and less left than `LEONIDA_COMMIT_FLOOR_MB` megabytes (4096 where it is unset: where `crate::residency` begins to speak of pressure by commit). | | `LEONIDA_COMMIT_FLOOR_MB` | see the code | | | yes | `leonida-gpu/resource.rs` | `LEONIDA_COMMIT_FLOOR=1` (off by default; `LEONIDA_AB` can name it), and less left than `LEONIDA_COMMIT_FLOOR_MB` megabytes (4096 where it is unset: where `crate::residency` begins to speak of pressure by commit). | -| `LEONIDA_COMPOSE_NAN` | see the code | | | | `leonida-gpu/compose.rs` | A clamp to [0,1] that is safe for NaN and infinity (CLEAN, set when the pass is made from LEONIDA_COMPOSE_NAN): saturate() makes a NaN 0, which showed as black specks and a black sun where the upscaler or frame generatio... | +| `LEONIDA_COMPOSE_NAN` | see the code | | | | `leonida-gpu/compose.rs` | | | `LEONIDA_CONSTANTS_ONCE` | on, `0` turns it off | yes | | | `leonida-gpu/host.rs` +1 | ... whose slots any other table showing the same bytes joins (`LEONIDA_CONSTANTS_ONCE`).... | | `LEONIDA_CONSTANT_MARKS` | see the code | | | | `leonida-gpu/shader_cache.rs` +1 | `LEONIDA_CONSTANT_MARKS=1` turns it on. | | `LEONIDA_CONSTANT_SLOT_INLINE` | off unless set and not `0` | yes | | | `leonida-gpu/host.rs` | | @@ -308,6 +312,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_HELD_RESCHEDULE` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | ...ken by [`TextureQueue::room`] before its own look was due (`LEONIDA_HELD_RESCHEDULE=0`: left in, as before).... | | `LEONIDA_HELPER_OWN` | see the code | | | | `leonida-gpu/shader_cache.rs` +1 | Whether a pixel shader's helper lane reads its own value where the console reads the first lane's (`lower.rs` `first_lane`); on unless `LEONIDA_HELPER_OWN=0`. | | `LEONIDA_HELPER_PRIORITY` | on, `0` turns it off | yes | | | `leonida-gpu/cores.rs` +5 | Whether the threads the submitting thread waits for run at its priority (`LEONIDA_HELPER_PRIORITY`, on unless `0`; `LEONIDA_AB` can flip it while the title runs): above normal, ahead of the title's threads and of the thr... | +| `LEONIDA_HUD_POSITION` | see the code | | yes | | `leonida-gpu/aspect.rs` +1 | | | `LEONIDA_HURRY` | on, `0` turns it off | yes | | yes | `leonida-gpu/list/thin.rs` | Whether what the thread that prepares submissions stands at is translated first, and above normal priority while it is (`LEONIDA_HURRY`, on unless `0`: in turn, as before; `LEONIDA_AB` can flip it while the title runs). | | `LEONIDA_INDEX_HEAP_SPANS` | off unless set and not `0` | yes | yes | yes | `leonida-gpu/draw.rs` +1 | | | `LEONIDA_INDIRECT_BATCH_2` | see the code | yes | | | `leonida-gpu/draw.rs` | (`LEONIDA_AB=<s>,LEONIDA_INDIRECT_BATCH_2`, `..._3` or `..._4`: that setting while the switch is on, so that one run measures it against the setting in one scene.) | @@ -390,7 +395,6 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_NAN_SCRUB` | see the code | | yes | | `leonida-gpu/host/menu.rs` +4 | `LEONIDA_NAN_SCRUB=1` (off by default): see `Lower::scrub_nan`. | | `LEONIDA_NULL_SAMPLER_LINEAR` | see the code | | | | `leonida-gpu/descriptor/host.rs` +1 | LOCAL (11/26, `LEONIDA_NULL_SAMPLER_LINEAR=1`): a linear one instead. | | `LEONIDA_OPEN_ONE_VIEW` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether a write fault opens the view that was written and leaves the page's other views read-only, not clean any more (`LEONIDA_OPEN_ONE_VIEW=0`: opens them all, as before). | -| `LEONIDA_OUTPUT` | see the code | | yes | | `leonida-gpu/aspect.rs` +2 | Neither makes the title draw a wider view: that is the title's output size (`LEONIDA_OUTPUT`, leonida-loader's `hooks.rs`, and `docs/ultrawide.md` for what is known of it). | | `LEONIDA_OWN_STAMPS` | see the code | | | yes | `leonida-gpu/host.rs` +1 | Diagnostics (`LEONIDA_OWN_STAMPS=1`; off by default): what our own lists in the card's queue take of the card, per frame: the sends to copies in the card's memory with their hash passes ([`Host::card_before`]'s list), th... | | `LEONIDA_PAGE_ASK` | on, `0` turns it off | yes | | yes | `leonida-gpu/watch.rs` | Whether a fault asks Windows about its one page before it asks about the region around it (`LEONIDA_PAGE_ASK=0`: the region only, as before). | | `LEONIDA_PAGE_PARTS` | see the code | | | | `leonida-gpu/watch.rs` | Whether the parts of a page that the kernel names are kept, and a refresh copies those (`LEONIDA_PAGE_PARTS=0`: the 64 KiB page, as before). | @@ -438,7 +442,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_PORT_JOURNAL` | see the code | yes | | yes | `leonida-gpu/port_journal.rs` +1 | Renderer port #7: the submitting lane's last waits (`LEONIDA_PORT_JOURNAL=1`, off by default; the switch is [`crate::watch::port_journal`]). | | `LEONIDA_PRELUDE_UPLOAD` | see the code | yes | | | `leonida-gpu/texture.rs` | ...sion once the check of the texture's memory is done there (`LEONIDA_PRELUDE_UPLOAD=0`: by the list itself, where it was recorded, as before).... | | `LEONIDA_PRESENT_10BIT` | see the code | | | | `leonida-gpu/host.rs` | `LEONIDA_PRESENT_10BIT=0`: 8 bits, as before. | -| `LEONIDA_PRESENT_SCALE` | see the code | | yes | | `leonida-gpu/aspect.rs` +4 | Read by leonida-hle's `lifecycle.rs`, which widens the window the title asks for. - `LEONIDA_PRESENT_SCALE=fit\|stretch`: `fit` keeps the picture's shape in a window of another one, centred, with black bars beside it (or... | +| `LEONIDA_PRESENT_SCALE` | see the code | | yes | | `leonida-gpu/aspect.rs` +4 | `LEONIDA_ASPECT` and `LEONIDA_PRESENT_SCALE` control window shape and fitting. | | `LEONIDA_PRESENT_SMOOTH` | see the code | yes | | yes | `leonida-gpu/host.rs` +1 | `LEONIDA_PRESENT_SMOOTH=<fraction>`: each host present is held until at least that fraction of the recent mean interval between presents has passed since the one before, so a quick frame after a slow one waits a little i... | | `LEONIDA_PROFILE` | see the code | | | yes | `leonida-gpu/copystat.rs` +1 | `LEONIDA_PROFILE=<from>,<to>,<ms>,<file>` samples the stacks of the busiest threads every `<ms>` milliseconds between two times (seconds, as `LEONIDA_STACKS`), and writes them counted to `<file>` at the end (several of t... | | `LEONIDA_QUEUE_MARKS` | off unless set and not `0` | yes | | yes | `leonida-gpu/descriptor/host.rs` | Off by default (`LEONIDA_QUEUE_MARKS=1`; `LEONIDA_AB` can name it): here no one waited for that lock, and by turns the submitting thread worked +0.27 and +0.06 ms a frame with the marks (runs d41). | @@ -471,6 +475,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_REMAP_BOOST` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the thread that changes a mapping runs at the highest priority while it holds title memory still (`LEONIDA_REMAP_BOOST=0`: at its own). | | `LEONIDA_REMAP_HISTORY` | on, `0` turns it off | yes | | | `leonida-gpu/descriptor/host.rs` | The cursor of the single shared pass with `LEONIDA_REMAP_HISTORY=0` (as before: the heap whose pass runs first takes the ranges). | | `LEONIDA_REMAP_SPANS` | on, `0` turns it off | yes | | yes | `leonida-gpu/texture.rs` +1 | Whether a read in place that names its range ([`title_memory_reading_range`]) waits only for the changes of mapping that touch that range (`LEONIDA_REMAP_SPANS=0`: for every change, as before; `LEONIDA_AB` can name it).... | +| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-gpu/host/menu.rs` +2 | | | `LEONIDA_REPLAY_GBV` | see the code | | | | `leonida-gpu/replay/play.rs` | | | `LEONIDA_REPLAY_PEEK` | see the code | | | | `leonida-gpu/replay/play/diverge.rs` | | | `LEONIDA_RETIRE_QUEUES` | on, `0` turns it off | yes | | yes | `leonida-gpu/host.rs` | `LEONIDA_RETIRE_QUEUES=0`: every thread takes the first, as before. | @@ -495,7 +500,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_SEND_OWN` | see the code | | | | `leonida-gpu/host/send.rs` | What goes up to copies in the card's memory goes up as it was when its submission was prepared (`LEONIDA_SEND_OWN`, on by default; `0`: as before). | | `LEONIDA_SEND_TAKE_BESIDE` | see the code | yes | | yes | `leonida-gpu/host.rs` +1 | ...re waited for before that list is closed ([`Own::settle`]; `LEONIDA_SEND_TAKE_BESIDE=0`: waited for in `take`, as before; `check`: the bytes are compared with where they came from when they are waited for, which reads up... | | `LEONIDA_SHADER_SAVE` | see the code | | | | `leonida-gpu/pipeline.rs` +1 | `LEONIDA_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as translated (`.dxil`), by the hash crash reports name it with | -| `LEONIDA_SHARPEN` | see the code | | | | `leonida-gpu/compose.rs` | Leonida: the scene sharpened before the interface goes over it (SHARPEN, 0 to 1, set when the pass is made from LEONIDA_SHARPEN). | +| `LEONIDA_SHARPEN` | see the code | | | | `leonida-gpu/compose.rs` | Leonida: how much the scene is sharpened before the interface goes over it (`LEONIDA_SHARPEN`, 0 to 1; default 0.6; 0: off). | | `LEONIDA_SHOW_AFTER` | see the code | | yes | yes | `leonida-gpu/descriptor/host.rs` +4 | Whether a title slot shows a texture that is new to it only once the submission with its upload has finished (`LEONIDA_SHOW_AFTER=1`; off). | | `LEONIDA_SHOW_NEW_LATER` | see the code | yes | | | `leonida-gpu/descriptor/host.rs` | ...e it may still run shows it only once those have finished (`LEONIDA_SHOW_NEW_LATER`, on; 0: at once, as before; A/B-able). [`show_after`] left out slots made "at once" from a draw's table, the texture pass's paths that a... | | `LEONIDA_SKIP_KEPT` | see the code | | | | `leonida-gpu/pipeline.rs` | `LEONIDA_SKIP_KEPT=0`: looked up each time, as before. | @@ -571,6 +576,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_TRAIL` | see the code | | | | `leonida-gpu/host.rs` | `LEONIDA_TRAIL=0`: nothing is kept and nothing is said. | | `LEONIDA_TRANSLATOR` | see the code | | | | `leonida-gpu/shader_cache.rs` | | | `LEONIDA_TWIN_BIAS` | see the code | | | | `leonida-gpu/descriptor/host.rs` | `LEONIDA_TWIN_BIAS=0`: null, as before (programs then add a bias of 0). | +| `LEONIDA_ULTRAWIDE_HUD` | see the code | | | | `leonida-gpu/aspect.rs` +2 | | | `LEONIDA_UNDER_THREADS` | see the code | | | yes | `leonida-gpu/land.rs` | [`Pool::each`] on threads kept for the title's bytes under flights' writes (`LEONIDA_UNDER_THREADS`, 6 with this one). | | `LEONIDA_UNDER_WIDE` | on, `0` turns it off | yes | | | `leonida-gpu/shadow.rs` +1 | Whether the pages of [`Shadow::merge_under_writes`] are compared on several threads (`LEONIDA_UNDER_WIDE=0`: on the submitting one). | | `LEONIDA_UNDER_WORDS` | see the code | | | | `leonida-gpu/host/send.rs` | Whether the title's bytes that go in under flights' writes (`Shadow::merge_under_writes`) go in by whole words (`LEONIDA_UNDER_WORDS=0`: by the bytes that changed, as before). | @@ -665,6 +671,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. | `LEONIDA_SECTION_WINDOW` | see the code | | | | `leonida-hle/modules/xmem.rs` | `LEONIDA_SECTION_WINDOW=0`: a view for each write, as before. | | `LEONIDA_STREAM_NOTICE` | see the code | | | | `leonida-hle/modules/xmem.rs` | `LEONIDA_STREAM_NOTICE=0`: not told; what is then done is `LEONIDA_PAGE_WRITES`' to say (`leonida_gpu::title_memory_written`). | | `LEONIDA_STREAM_PRIORITY` | see the code | | | | `leonida-hle/modules/xmem.rs` | Called where that thread maps and submits: lifts a thread that is below normal to above it (`LEONIDA_STREAM_PRIORITY=0`: left as the title set it). | +| `LEONIDA_UI_LETTERBOX` | see the code | | | | `leonida-hle/ultrawide.rs` | | | `LEONIDA_WINDOW_MAX` | see the code | | | | `leonida-hle/modules/lifecycle.rs` | `LEONIDA_WINDOW_MAX=WIDTHxHEIGHT` applies a smaller limit without changing the title's render targets. | | `LEONIDA_XMA_DUMP` | see the code | | | | `leonida-hle/modules/audio.rs` | `LEONIDA_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`) and input buffer 0 (`.xma`) of the first 32 voices enabled, to test the decoder on a title's streams outside the title. | @@ -674,11 +681,11 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. |---|---|---|---|---|---|---| | `LEONIDA_CLZERO_ASK` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_CLZERO_ASK=1` asks every time, as before. | | `LEONIDA_NO_WATCHDOG` | see the code | | | | `leonida-loader/hooks.rs` +2 | LOCAL (leonida-perf, via our wt5): LEONIDA_RENDER_SCALE / LEONIDA_OWN_UPSCALER / LEONIDA_NO_WATCHDOG title patches. | +| `LEONIDA_OUTPUT` | see the code | | yes | | `leonida-loader/hooks.rs` +1 | | | `LEONIDA_OUTPUT_1440` | see the code | | | | `leonida-loader/hooks.rs` | | | `LEONIDA_PATCH_CLZERO` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_CLZERO=0` emulates each time, as before. | | `LEONIDA_PATCH_WAITS` | see the code | | | | `leonida-loader/console_insn.rs` | `LEONIDA_PATCH_WAITS=0` emulates each time, as before. | | `LEONIDA_PROFILE_ONLY` | see the code | | | yes | `leonida-loader/profile.rs` | `LEONIDA_PROFILE_ONLY=<name>[,<name>..]` samples only the threads whose name or start (`module+rva`) holds one of them, which makes the rounds short. | -| `LEONIDA_RENDER_SCALE_MIN` | see the code | | yes | | `leonida-loader/hooks.rs` +1 | | | `LEONIDA_SIM_MAX_STEP_MS` | see the code | | | | `leonida-loader/hooks.rs` +1 | The ceiling `LEONIDA_SIM_MAX_STEP_MS` asks for: `Some(None)` for the title's own, `None` if not one of them. | | `LEONIDA_STACKS` | see the code | | | | `leonida-loader/profile.rs` +1 | `LEONIDA_STACKS=<seconds>[,<seconds>...]` prints each thread's unwound stack as `module+rva` that many seconds after [`dump_stacks_on_schedule`], to find what a title waits on. | @@ -738,7 +745,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one. ## Only in tests -Read by test code alone, or made up by it: `LEONIDA_A`, `LEONIDA_B`, `LEONIDA_BCPACK_CASES`, `LEONIDA_BCPACK_TABLES`, `LEONIDA_BENCH_CS`, `LEONIDA_BENCH_EXPECT_HEAP_SWEEP`, `LEONIDA_BENCH_FILE`, `LEONIDA_BENCH_HOLES`, `LEONIDA_BENCH_N`, `LEONIDA_BENCH_S`, `LEONIDA_BENCH_THREADS`, `LEONIDA_BENCH_WARP`, `LEONIDA_BLOCK_WAY`, `LEONIDA_CONSOLE_DXC`, `LEONIDA_DIFF_ONLY`, `LEONIDA_EXIT_CHILD`, `LEONIDA_HOST_LOCK_CHILD`, `LEONIDA_LONG`, `LEONIDA_MENU_PREVIEW`, `LEONIDA_NONE_SUCH`, `LEONIDA_PC_DXC`, `LEONIDA_PLACES_DIR`, `LEONIDA_PLACES_RUN`, `LEONIDA_PROBE`, `LEONIDA_PROBE_STREAMLINE`, `LEONIDA_REF_PS`, `LEONIDA_REF_VS`, `LEONIDA_SAVE_CHILD`, `LEONIDA_SAVE_OP`, `LEONIDA_SAVE_STOP`, `LEONIDA_TEST_D3D_DEBUG`, `LEONIDA_TEST_FOLDER`, `LEONIDA_TEST_KEYS`, `LEONIDA_TEST_ROUNDS`, `LEONIDA_TILES_TEST_CARD`, `LEONIDA_TRAP_LOG`, `LEONIDA_XMA_REFERENCE`, `LEONIDA_XMA_STREAMS`. +Read by test code alone, or made up by it: `LEONIDA_A`, `LEONIDA_B`, `LEONIDA_BCPACK_CASES`, `LEONIDA_BCPACK_TABLES`, `LEONIDA_BENCH_CS`, `LEONIDA_BENCH_EXPECT_HEAP_SWEEP`, `LEONIDA_BENCH_FILE`, `LEONIDA_BENCH_HOLES`, `LEONIDA_BENCH_N`, `LEONIDA_BENCH_S`, `LEONIDA_BENCH_THREADS`, `LEONIDA_BENCH_WARP`, `LEONIDA_BLOCK_WAY`, `LEONIDA_CONSOLE_DXC`, `LEONIDA_DIFF_ONLY`, `LEONIDA_DISPLAY_PROFILE_TEST_IMAGE`, `LEONIDA_EXIT_CHILD`, `LEONIDA_HOST_LOCK_CHILD`, `LEONIDA_LONG`, `LEONIDA_MENU_PREVIEW`, `LEONIDA_NONE_SUCH`, `LEONIDA_PC_DXC`, `LEONIDA_PLACES_DIR`, `LEONIDA_PLACES_RUN`, `LEONIDA_PROBE`, `LEONIDA_PROBE_STREAMLINE`, `LEONIDA_REF_PS`, `LEONIDA_REF_VS`, `LEONIDA_SAVE_CHILD`, `LEONIDA_SAVE_OP`, `LEONIDA_SAVE_STOP`, `LEONIDA_TEST_D3D_DEBUG`, `LEONIDA_TEST_FOLDER`, `LEONIDA_TEST_KEYS`, `LEONIDA_TEST_ROUNDS`, `LEONIDA_TILES_TEST_CARD`, `LEONIDA_TRAP_LOG`, `LEONIDA_XMA_REFERENCE`, `LEONIDA_XMA_STREAMS`. ## Only in comments diff --git a/launcher/index.html b/launcher/index.html index 27ba662756..53100dd75f 100644 --- a/launcher/index.html +++ b/launcher/index.html @@ -484,9 +484,17 @@

Built on the work of others

const monitor = S?.picture?.monitor_ultrawide; if (monitor != null) return monitor; const scale = window.devicePixelRatio || 1; - const w = Math.round(window.screen.width * scale), h = Math.round(window.screen.height * scale); - return (h >= 1080 && w * 9 === h * 32) - || (w >= 3440 && h >= 1440 && Math.abs(w * 27 - h * 64) * 100 <= h * 64); + // Each CSS screen dimension can be rounded by half a CSS pixel. + const { width, height } = window.screen; + const minWidth = Math.ceil((width - 0.5) * scale), maxWidth = Math.floor((width + 0.5) * scale); + const minHeight = Math.ceil((height - 0.5) * scale), maxHeight = Math.floor((height + 0.5) * scale); + const min32 = Math.ceil(Math.max(minWidth / 32, Math.max(minHeight, 1080) / 9)); + const max32 = Math.floor(Math.min(maxWidth / 32, maxHeight / 9)); + if (min32 <= max32) return true; + const wideMinWidth = Math.max(minWidth, 3440), wideMinHeight = Math.max(minHeight, 1440); + return wideMinWidth <= maxWidth && wideMinHeight <= maxHeight + && wideMinWidth * 27 * 100 <= maxHeight * 64 * 101 + && maxWidth * 27 * 100 >= wideMinHeight * 64 * 99; } function consolePatch(v) { return v === "s" ? { series_s: true, series_x: false } : { series_s: false, series_x: true }; } function presetOn(p, s) { return consoleOf(s) === p.console && Object.entries(p.set).every(([k, v]) => s[k] === v); } diff --git a/tests/test_launcher_display.cjs b/tests/test_launcher_display.cjs new file mode 100644 index 0000000000..822c0b46bf --- /dev/null +++ b/tests/test_launcher_display.cjs @@ -0,0 +1,42 @@ +const assert = require("node:assert/strict"); +const { readFileSync } = require("node:fs"); +const { join } = require("node:path"); +const test = require("node:test"); +const vm = require("node:vm"); + +const page = readFileSync(join(__dirname, "..", "launcher", "index.html"), "utf8"); +const options = page.slice(page.indexOf("function wideRatio("), page.indexOf("function localCommand(")); + +function launcherPicture(width, height, scale, monitor = null) { + const result = vm.runInNewContext( + options + "\n({ wide: ultrawideSelected(settings), args: switchArgs(settings) })", + { + S: { platform: "windows", picture: { monitor_ultrawide: monitor } }, + settings: { series_x: true, aspect_ratio: "auto", hud_position: "center", + dlss: true, precompile: true, adapter: "" }, + window: { screen: { width, height }, devicePixelRatio: scale }, + }, + ); + return { wide: result.wide, args: Array.from(result.args) }; +} + +test("Match monitor retains the HUD switch on a 32:9 screen rounded at 175% DPI", () => { + assert.deepEqual(launcherPicture(2926, 823, 1.75), { + wide: true, args: ["-SeriesX", "-AspectRatio", "auto", "-HudPosition", "center"], + }); +}); + +test("Match monitor allows rounding at the minimum ultrawide output size", () => { + assert.equal(launcherPicture(1058, 443, 3.25).wide, true); +}); + +test("Match monitor leaves the HUD switch off for standard or inexact screens", () => { + assert.deepEqual(launcherPicture(2194, 1234, 1.75), { + wide: false, args: ["-SeriesX", "-AspectRatio", "auto"], + }); + assert.equal(launcherPicture(5121, 1440, 1).wide, false); +}); + +test("The server monitor hint takes precedence over CSS dimensions", () => { + assert.equal(launcherPicture(2926, 823, 1.75, false).wide, false); +}); From f291ccf40c4241106a7f2a87b4ee7304977bb5fe Mon Sep 17 00:00:00 2001 From: invismann <73877188+invismann@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:32:26 +0100 Subject: [PATCH 6/6] Correct world marker scaling and broaden monitor matching Select the supported fixed preset for more 21:9 panel sizes, remove the unreachable HUD split path, and document the output and memory overrides. Verified 16 focused Rust tests including both synthetic D3D12 readbacks on Windows with an RTX 4090 (driver 621.01), 5 Node tests, and 56 Python launcher and switch checks. Independent review used GPT-6.2 Sol. --- d3d12/crates/leonida-gpu/src/aspect.rs | 23 ++++++- d3d12/crates/leonida-gpu/src/compose.rs | 71 +++++++------------- d3d12/crates/leonida-gpu/src/draw.rs | 14 ++-- d3d12/crates/leonida-gpu/src/host.rs | 3 - d3d12/crates/leonida-gpu/src/world_marker.rs | 25 ++++++- d3d12/scripts/play-nvidia.ps1 | 5 +- docs/ultrawide.md | 15 ++++- launcher/index.html | 6 +- tests/test_launcher_display.cjs | 12 +++- tests/test_leonida_launcher.py | 4 +- tools/leonida_launcher.py | 2 +- 11 files changed, 107 insertions(+), 73 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/aspect.rs b/d3d12/crates/leonida-gpu/src/aspect.rs index 723b80a977..994ccaa8b3 100644 --- a/d3d12/crates/leonida-gpu/src/aspect.rs +++ b/d3d12/crates/leonida-gpu/src/aspect.rs @@ -38,7 +38,18 @@ impl NativeAspect { #[cfg(windows)] { let current = display_mode(u32::MAX).or_else(screen); - self.output_for(current, (0..).map_while(display_mode)) + let selected = self.output_for(current, (0..).map_while(display_mode)); + if self == Self::Auto + && let (Some(monitor), Some(preset)) = (current, selected) + && monitor != preset + { + tracing::warn!( + ?monitor, + ?preset, + "Match monitor selected a supported Series X output preset" + ); + } + selected } #[cfg(not(windows))] self.output_for(None, []) @@ -74,7 +85,7 @@ impl NativeAspect { let (w, h) = (u64::from(width), u64::from(height)); if height >= 1080 && w * 9 == h * 32 { Some(Self::Superwide) - } else if width >= 3440 && height >= 1440 && (w * 27).abs_diff(h * 64) * 100 <= h * 64 { + } else if width >= 2560 && height >= 1080 && (w * 27).abs_diff(h * 64) * 100 <= h * 64 * 2 { Some(Self::Wide) } else { None @@ -284,7 +295,13 @@ mod tests { let standard = Some((2560, 1440)); let low_wide = Some((3840, 1080)); assert_eq!(NativeAspect::Auto.output_for(standard, [(5120, 1440)]), None); - assert_eq!(NativeAspect::Auto.output_for(Some((5120, 2160)), []), Some((3440, 1440))); + for desktop in [(2560, 1080), (3440, 1440), (3840, 1600), (5120, 2160)] { + assert_eq!( + NativeAspect::Auto.output_for(Some(desktop), []), + Some((3440, 1440)), + "{desktop:?}" + ); + } assert_eq!(NativeAspect::Auto.output_for(low_wide, []), Some((3840, 1080))); assert_eq!(NativeAspect::Superwide.output_for(low_wide, [(5120, 1440)]), Some((5120, 1440))); assert_eq!(NativeAspect::Superwide.output_for(standard, [(3840, 1080)]), Some((3840, 1080))); diff --git a/d3d12/crates/leonida-gpu/src/compose.rs b/d3d12/crates/leonida-gpu/src/compose.rs index 567297a41a..0231d41618 100644 --- a/d3d12/crates/leonida-gpu/src/compose.rs +++ b/d3d12/crates/leonida-gpu/src/compose.rs @@ -175,31 +175,25 @@ impl FrameUi { #[derive(Clone, Copy)] pub(crate) enum HudLayout { Whole, - ToEdges, FromEdges([f32; 2]), } impl HudLayout { pub(crate) fn for_present( - centered: bool, wide: bool, ui: FrameUi, edges: bool, output: (u64, u32), ) -> Self { - if !(centered || wide) || !(ui == FrameUi::Game || (wide && ui == FrameUi::Pause)) { + if !wide || edges || !matches!(ui, FrameUi::Game | FrameUi::Pause) { return Self::Whole; } - match (wide, edges) { - (true, false) => Placement::WHOLE - .center_legacy_ui((3840, 2160), output) - .dest - .map_or(Self::Whole, |[left, _, right, _]| { - Self::FromEdges([left, right]) - }), - (false, true) => Self::ToEdges, - _ => Self::Whole, - } + Placement::WHOLE + .center_legacy_ui((3840, 2160), output) + .dest + .map_or(Self::Whole, |[left, _, right, _]| { + Self::FromEdges([left, right]) + }) } pub(crate) fn uses_split(self) -> bool { @@ -378,22 +372,6 @@ void find_splits(uint3 id : SV_GroupThreadID, uint index : SV_GroupIndex) { } } -float4 edge_hud(float2 uv) { - uint width, height; - over.GetDimensions(width, height); - float2 cut = float2(splits[0], splits[1]) / width; - float span = over_place.z - over_place.x; - float x = (uv.x - over_place.x) / span; - if (uv.x < cut.x * span) { - x = uv.x / span; - } else if (uv.x > 1 - (1 - cut.y) * span) { - x = 1 + (uv.x - 1) / span; - } else if (x < cut.x || x > cut.y) { - return 0; - } - return over.SampleLevel(smooth_, float2(x, uv.y), 0); -} - float4 center_hud(float2 uv) { uint width, height; over.GetDimensions(width, height); @@ -430,7 +408,6 @@ float4 ps(V v) : SV_Target { } float4 o = 0; if ((layers & 8) != 0) o = center_hud(v.uv); - else if ((layers & 4) != 0) o = edge_hud(v.uv); else if ((layers & 1) != 0) o = plane(over, over_source, over_place, v.uv, false); return float4(clean(o.rgb + s.rgb * (1 - clean1(o.a))), 1); } @@ -730,7 +707,10 @@ impl Composer { } let slot = &self.views[slot]; let views = &slot.views; - let edges = if self.wide && hud_layout.uses_split() && overlay.is_some() { + let edges = if let HudLayout::FromEdges(bounds) = hud_layout + && self.wide + && overlay.is_some() + { let pipeline = self.edges.get_or_init(|| edge_pipeline(&host.device, &self.root) .inspect_err(|error| tracing::warn!(%error, "could not prepare screen-edge HUD placement")).ok()); let splits = slot.splits.get_or_init(|| { @@ -742,7 +722,10 @@ impl Composer { edge_views(&host.device, views, self.step, Some(&buffer)); Some(buffer) }); - pipeline.as_ref().zip(splits.as_ref()) + pipeline + .as_ref() + .zip(splits.as_ref()) + .map(|(pipeline, splits)| (pipeline, splits, bounds)) } else { None }; @@ -776,14 +759,10 @@ impl Composer { } let rtv = host.rtv(Some(back), None); list.SetDescriptorHeaps(&[Some(views.clone())]); - if let Some((pipeline, splits)) = edges { - if let HudLayout::FromEdges([left, right]) = hud_layout { - constants[12] = left.to_bits(); - constants[14] = right.to_bits(); - constants[16] |= 8; - } else { - constants[16] |= 4; - } + if let Some((pipeline, splits, [left, right])) = edges { + constants[12] = left.to_bits(); + constants[14] = right.to_bits(); + constants[16] |= 8; list.SetComputeRootSignature(&self.root); list.SetComputeRoot32BitConstants(0, CONSTANTS, constants.as_ptr().cast(), 0); list.SetComputeRootDescriptorTable(1, gpu); @@ -820,7 +799,7 @@ impl Composer { bottom: (top + height) as i32, }]); list.DrawInstanced(3, 1, 0, 0); - if let Some((_, splits)) = edges { + if let Some((_, splits, _)) = edges { list.ResourceBarrier(&[crate::host::transition( splits, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, @@ -1120,17 +1099,17 @@ mod placement_tests { let gameplay = FrameUi::classify(false, false, false, || hud.get()); hud.set(HudState::Pause); let pause = FrameUi::classify(false, false, false, || hud.get()); - assert!(!HudLayout::for_present(false, true, menu, false, output).uses_split()); + assert!(!HudLayout::for_present(true, menu, false, output).uses_split()); assert!(matches!( - HudLayout::for_present(false, true, gameplay, false, output), + HudLayout::for_present(true, gameplay, false, output), HudLayout::FromEdges(_) )); assert!(matches!( - HudLayout::for_present(false, true, pause, false, output), + HudLayout::for_present(true, pause, false, output), HudLayout::FromEdges(_) )); - assert!(!HudLayout::for_present(false, true, pause, true, output).uses_split()); - assert!(!HudLayout::for_present(true, false, pause, true, output).uses_split()); + assert!(!HudLayout::for_present(true, pause, true, output).uses_split()); + assert!(!HudLayout::for_present(false, gameplay, true, output).uses_split()); } #[test] diff --git a/d3d12/crates/leonida-gpu/src/draw.rs b/d3d12/crates/leonida-gpu/src/draw.rs index 6728d48774..24b7567018 100644 --- a/d3d12/crates/leonida-gpu/src/draw.rs +++ b/d3d12/crates/leonida-gpu/src/draw.rs @@ -6288,7 +6288,8 @@ impl State { } }); let x = label.map_or(x, |label| label.x); - Some((crate::world_marker::fit_sprite(*viewport, x)?, label)) + let (width, _) = crate::world_marker::canvas_size(); + Some((crate::world_marker::fit_sprite(*viewport, x, width)?, label)) } fn projected_prompt_viewport( @@ -6307,14 +6308,11 @@ impl State { let previous = previous .filter(|&(surface, _)| surface == target) .map(|(_, state)| state); - let (prompt, anchor) = crate::world_marker::ProjectedPrompt::advance( - previous, - batch, - origin, - crate::world_marker::canvas_size(), - )?; + let canvas = crate::world_marker::canvas_size(); + let (prompt, anchor) = + crate::world_marker::ProjectedPrompt::advance(previous, batch, origin, canvas)?; self.projected_prompt = Some((target, prompt)); - crate::world_marker::fit_sprite(*viewport, anchor?) + crate::world_marker::fit_sprite(*viewport, anchor?, canvas.0) } fn prompt_origin(&self, offset: u64, bytes: u32) -> Option<[f32; 2]> { diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index eb0bc8ad18..320a9428b1 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -13814,7 +13814,6 @@ impl Host { } let source_placement = placement; let mut placement = placement; - let mut overlay_centered = false; let mut wide_overlay = false; let planes = overlay.and_then(|(over, over_state)| { // SAFETY: a live overlay resource. @@ -13833,7 +13832,6 @@ impl Host { } else { original.center_legacy_ui((over_desc.Width, over_desc.Height), output) }; - overlay_centered = original != placement[1]; } Some(( over, @@ -13849,7 +13847,6 @@ impl Host { }; let edges = wide_overlay && crate::aspect::hud_at_edges(); let hud_layout = crate::compose::HudLayout::for_present( - overlay_centered, wide_overlay, ui, edges, diff --git a/d3d12/crates/leonida-gpu/src/world_marker.rs b/d3d12/crates/leonida-gpu/src/world_marker.rs index e599b89d42..322ee75a1c 100644 --- a/d3d12/crates/leonida-gpu/src/world_marker.rs +++ b/d3d12/crates/leonida-gpu/src/world_marker.rs @@ -232,9 +232,12 @@ impl LabelAnchor { } } -pub(crate) fn fit_sprite(viewport: D3D12_VIEWPORT, anchor: f32) -> Option { - let canvas_scale = canvas_size().0 as f32 / LEGACY_CANVAS.0 as f32; - fit_at(viewport, anchor, (scale() * canvas_scale).min(1.0)) +pub(crate) fn fit_sprite( + viewport: D3D12_VIEWPORT, + anchor: f32, + canvas_width: i32, +) -> Option { + fit_at(viewport, anchor, LEGACY_CANVAS.0 as f32 / canvas_width as f32) } pub(crate) fn fit_startup_prompt( @@ -391,6 +394,22 @@ mod tests { assert!(fit_startup_prompt(native, [0.8, -0.9]).is_none()); } + #[test] + fn fit_sprite_narrows_the_wide_canvas_around_its_anchor() { + let viewport = D3D12_VIEWPORT { + Width: 7680.0, + Height: 2160.0, + MaxDepth: 1.0, + ..Default::default() + }; + let fitted = fit_sprite(viewport, 0.5, 7680).unwrap(); + assert_eq!( + (fitted.TopLeftX, fitted.Width, fitted.Height), + (2880.0, 3840.0, 2160.0) + ); + assert_eq!(fitted.TopLeftX + 0.75 * fitted.Width, 0.75 * viewport.Width); + } + #[test] fn narrow_a_sprite_around_its_own_anchor() { let original = D3D12_VIEWPORT { diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 2fcb96e964..9f51f085ce 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -663,7 +663,10 @@ if ($console -ne 'series-x') { } elseif ($nativeAspect -eq '21:9') { $nativeOutput = '3440x1440' } - if ($nativeOutput) { $settings.LEONIDA_NATIVE_ULTRAWIDE = $nativeOutput } + if ($nativeOutput) { + $settings.LEONIDA_NATIVE_ULTRAWIDE = $nativeOutput + if ($nativeAspect -eq 'auto') { Write-Host "Match monitor selected the supported $nativeOutput output preset." } + } } elseif ($nativeOutput -in 'off', '0') { $nativeOutput = '' } diff --git a/docs/ultrawide.md b/docs/ultrawide.md index 1eeadf513b..18cff407e5 100644 --- a/docs/ultrawide.md +++ b/docs/ultrawide.md @@ -4,8 +4,10 @@ In the desktop launcher, check **Series X profile** to show **Aspect ratio (-AspectRatio)**. Choose **Match monitor**, **16:9**, **21:9**, or **32:9**, then start or restart the game. -Match monitor is the Series X default. 21:9 uses 3440×1440. 32:9 uses 5120×1440, or 3840×1080 when the primary -display reports 32:9 modes only up to 1080p. These modes use the retail 1.0.2.1 executable. +Match monitor is the Series X default and chooses among fixed output presets. It selects 3440×1440 for +21:9-class displays, including 2560×1080, 3840×1600, and 5120×2160. For 32:9 it selects 5120×1440, or +3840×1080 when the primary display reports 32:9 modes only up to 1080p. The launcher reports its selection. +Choose **16:9** to use the standard Series X output. These native ultrawide presets use the retail 1.0.2.1 executable. The launchers and F1 show **Ultrawide HUD correction** when **21:9** or **32:9** is selected or detected by Match monitor. The default follows the saved F1 aspect choice and otherwise matches the monitor. @@ -30,6 +32,15 @@ render-target and scene-pool budgets when the scene can exceed the stock 2560×1 4096 pixels it translates the retail directional shadow-list shaders with a wider horizontal field and a distinct shader-cache key. When Windows reports insufficient commit, lower the render scale or increase the page file. +The automatic budgets are 7200 MiB for the 3440×1440 and 3840×1080 render-target heaps, 8000 MiB for the +5120×1440 heap, and 1600 MiB for the scene pool. Unit tests cover the budget selection. In-game stability +at those budgets remains unverified on this branch. + +- `LEONIDA_RT_HEAP_MB` overrides the render-target heap reservation in MiB (2200–24576). +- `LEONIDA_SCENE_POOL_MB` overrides the scene-pool reservation in MiB (711–4095). +- Set either override to `0` to retain the corresponding stock budget. +- `LEONIDA_UI_LETTERBOX=0` disables the centered loading-movie viewport hook. + The notes below describe Mandy's earlier window-only controls and the experiments that led to native output. How the output size goes from the window to the title and back to the screen, and what the opt-in ultrawide settings diff --git a/launcher/index.html b/launcher/index.html index 53100dd75f..152f1af77a 100644 --- a/launcher/index.html +++ b/launcher/index.html @@ -491,10 +491,10 @@

Built on the work of others

const min32 = Math.ceil(Math.max(minWidth / 32, Math.max(minHeight, 1080) / 9)); const max32 = Math.floor(Math.min(maxWidth / 32, maxHeight / 9)); if (min32 <= max32) return true; - const wideMinWidth = Math.max(minWidth, 3440), wideMinHeight = Math.max(minHeight, 1440); + const wideMinWidth = Math.max(minWidth, 2560), wideMinHeight = Math.max(minHeight, 1080); return wideMinWidth <= maxWidth && wideMinHeight <= maxHeight - && wideMinWidth * 27 * 100 <= maxHeight * 64 * 101 - && maxWidth * 27 * 100 >= wideMinHeight * 64 * 99; + && wideMinWidth * 27 * 100 <= maxHeight * 64 * 102 + && maxWidth * 27 * 100 >= wideMinHeight * 64 * 98; } function consolePatch(v) { return v === "s" ? { series_s: true, series_x: false } : { series_s: false, series_x: true }; } function presetOn(p, s) { return consoleOf(s) === p.console && Object.entries(p.set).every(([k, v]) => s[k] === v); } diff --git a/tests/test_launcher_display.cjs b/tests/test_launcher_display.cjs index 822c0b46bf..34c8b02eb7 100644 --- a/tests/test_launcher_display.cjs +++ b/tests/test_launcher_display.cjs @@ -26,8 +26,16 @@ test("Match monitor retains the HUD switch on a 32:9 screen rounded at 175% DPI" }); }); -test("Match monitor allows rounding at the minimum ultrawide output size", () => { - assert.equal(launcherPicture(1058, 443, 3.25).wide, true); +test("Match monitor allows rounding at the minimum ultrawide panel size", () => { + assert.equal(launcherPicture(788, 332, 3.25).wide, true); +}); + +test("Match monitor keeps the HUD choice on other 21:9 panel sizes", () => { + for (const [width, height] of [[2560, 1080], [3840, 1600], [5120, 2160]]) { + assert.deepEqual(launcherPicture(width, height, 1), { + wide: true, args: ["-SeriesX", "-AspectRatio", "auto", "-HudPosition", "center"], + }, `${width}×${height}`); + } }); test("Match monitor leaves the HUD switch off for standard or inexact screens", () => { diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index 1e0297c1a1..4b1903fe1d 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -142,7 +142,9 @@ def test_match_monitor_and_default_expose_and_forward_hud_on_ultrawide(self): self.assertFalse(launcher.ultrawide_selected(settings(), dict(display, default_series_x=False), windows=True)) def test_monitor_detection_matches_the_native_output_profiles(self): - for size in ((3440, 1440), (3840, 1080), (5120, 1440), (5120, 2160)): + for size in ( + (2560, 1080), (3440, 1440), (3840, 1600), (3840, 1080), (5120, 1440), (5120, 2160) + ): self.assertTrue(launcher.monitor_is_ultrawide(size), size) for size in ((1920, 1080), (2560, 1440), (3840, 2160)): self.assertFalse(launcher.monitor_is_ultrawide(size), size) diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 13e78b006b..8673a1d320 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -171,7 +171,7 @@ def monitor_is_ultrawide(size: tuple[int, int]) -> bool: """Match the native aspect classifier in leonida-gpu/src/aspect.rs.""" width, height = size return ((height >= 1080 and width * 9 == height * 32) - or (width >= 3440 and height >= 1440 and abs(width * 27 - height * 64) * 100 <= height * 64)) + or (width >= 2560 and height >= 1080 and abs(width * 27 - height * 64) * 100 <= height * 64 * 2)) def picture_context(repo: str = REPO, windows: bool = WINDOWS,