diff --git a/d3d12/apps/leonida/src/main.rs b/d3d12/apps/leonida/src/main.rs index 08df7abe85..b3ed3fd51d 100644 --- a/d3d12/apps/leonida/src/main.rs +++ b/d3d12/apps/leonida/src/main.rs @@ -235,6 +235,9 @@ fn main() -> Result<()> { console, title_args, } => { + // Before the host GPU and Streamline: a proxy DLL hooks what loads after it. + #[cfg(windows)] + leonida_loader::preload_dlls(); leonida_hle::runtime::set_title_args(title_args); run::run(&exe, unimplemented, strict, execute, console) } diff --git a/d3d12/crates/leonida-gpu/src/inplace.rs b/d3d12/crates/leonida-gpu/src/inplace.rs index f7889af0bc..1426ab13d8 100644 --- a/d3d12/crates/leonida-gpu/src/inplace.rs +++ b/d3d12/crates/leonida-gpu/src/inplace.rs @@ -308,6 +308,12 @@ fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> { VIEWS.write().unwrap_or_else(|e| e.into_inner()) } +/// The bytes of the section with handle `section`, if the runtime told of it +/// ([`title_memory_section`]). +pub(crate) fn section_bytes(section: usize) -> Option { + views().sections.iter().find(|s| s.0 == section).map(|s| s.1) +} + /// The runtime made a section of `bytes` for physical pages; `committed` /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { @@ -535,6 +541,34 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover { cover_in(&views().views, at, len) } +/// The section and offset of every 64 KiB page of title memory `[at, at + +/// len)`, in order, if every page is in a view of a section: the page-pool +/// windows are not one run of a section, but each page can be mapped into +/// one run of ours ([`crate::port`] level 2). +pub(crate) fn page_sections(at: usize, len: usize) -> Option> { + if len == 0 { + return None; + } + let start = at & !(K64 - 1); + let end = at.checked_add(len)?.checked_add(K64 - 1)? & !(K64 - 1); + if end <= start { + return None; + } + let v = views(); + let mut pages = Vec::with_capacity((end - start) / K64); + let mut page = start; + while page < end { + let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?; + let within = page.checked_sub(base)?; + if within >= bytes || !within.is_multiple_of(K64) { + return None; + } + pages.push((section, offset + within as u64)); + page += K64; + } + Some(pages) +} + /// The whole stretch of views around `[at, at + len)` that follow one /// another in memory and in one section alike, if the range is one run of a /// section ([`Cover::Run`]): its first address, its bytes, the section and @@ -1258,10 +1292,24 @@ fn real_part(spans: &[(u64, u64, bool)]) -> Vec { lines } +/// When the census is taken, in seconds after the probe +/// (`LEONIDA_INPLACE_CENSUS_S`, `30,150`): later ones see the world, which +/// the first minutes of a run (menus, the load) do not. +fn census_times() -> &'static [u64] { + static TIMES: std::sync::OnceLock> = std::sync::OnceLock::new(); + TIMES.get_or_init(|| { + let times: Vec = std::env::var("LEONIDA_INPLACE_CENSUS_S") + .ok() + .map(|v| v.split(',').filter_map(|s| s.trim().parse().ok()).collect()) + .unwrap_or_default(); + if times.is_empty() { vec![30, 150] } else { times } + }) +} + /// Called once a second by the thread that submits, before a submission /// (`host::sweep`): with [`probe_level`], the probe at the first call, the -/// census (on a thread of its own: it asks Windows about every copy) 30 -/// and 150 seconds later. +/// census (on a thread of its own: it asks Windows about every copy) at +/// [`census_times`]. pub(crate) fn tick() { if level() > 0 { say(); @@ -1288,11 +1336,8 @@ pub(crate) fn tick() { } Err(started) => started, }; - let due = match DONE.load(Ordering::Relaxed) { - 0 => now >= started + 30_000, - 1 => now >= started + 150_000, - _ => false, - }; + let done = DONE.load(Ordering::Relaxed) as usize; + let due = census_times().get(done).is_some_and(|&s| now >= started + s * 1000); if due { let which = DONE.fetch_add(1, Ordering::Relaxed); std::thread::spawn(move || { diff --git a/d3d12/crates/leonida-gpu/src/port.rs b/d3d12/crates/leonida-gpu/src/port.rs index 3e18d7d3b9..d2cbee5a8c 100644 --- a/d3d12/crates/leonida-gpu/src/port.rs +++ b/d3d12/crates/leonida-gpu/src/port.rs @@ -53,12 +53,27 @@ //! the air writes there: in place nothing tells the flights' writes, so //! nothing waits for them. The title's constants are its CPU's; how many //! such steps there are is on the frame-rate line ([`log`]). +//! +//! Leonida, level 2 (`LEONIDA_PORT_CONSTANTS=2`): the same for windows of +//! title memory anywhere in the title's page pool, for 8 GB cards on 16 GB +//! PCs. Windows outside buffers were 3.2-4.6 GB of copies in the PC's +//! memory there (2026-11-29, RTX 3060 Ti), which the card reads over the bus +//! all the same, beside the title's own pages: the PC ran out of memory in +//! heavy scenes. A window is put in place only where such a copy would be +//! made ([`place_window_anywhere`], after the card memory the CPU maps), so +//! nothing the card reads from its own memory moves; only the window's own +//! pages are opened (the heap locks them), at most `LEONIDA_PORT_MB` at once, +//! and only in sections of a gigabyte and more (the page pool, allocated at +//! the title's start and kept), so that a view of ours, which stays mapped, +//! never holds a section the title let go. Title buffers are left as they +//! are. use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use windows::Win32::Graphics::Direct3D12::*; use windows_sys::Win32::System::Memory as mem; +use windows_sys::Win32::System::Threading::GetCurrentProcess; use crate::inplace::{Placed, cover, stretch}; @@ -74,12 +89,37 @@ const MOST: u64 = 512 << 20; /// `LEONIDA_PORT_CONSTANTS`: `1` turns renderer port #1 on (title buffers /// and windows of title memory in the title's 32-bit graphics memory, view -/// memory that is one stretch of a section, used in place); unset or -/// anything else: off, everything as before. -pub(crate) fn on() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); +/// memory that is one stretch of a section, used in place); `2` also puts +/// windows anywhere in the title's page pool in place where a copy in the +/// PC's memory would be made ([`place_window_anywhere`]); unset or anything +/// else: off, everything as before. +pub(crate) fn level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); // Read once, here: the switch of renderer port #1. - *ON.get_or_init(|| std::env::var("LEONIDA_PORT_CONSTANTS").is_ok_and(|v| v.trim() == "1")) + *LEVEL.get_or_init(|| match std::env::var("LEONIDA_PORT_CONSTANTS").as_deref().map(str::trim) { + Ok("1") => 1, + Ok("2") => 2, + _ => 0, + }) +} + +/// Whether renderer port #1 is on ([`level`] 1 or 2). +pub(crate) fn on() -> bool { + level() >= 1 +} + +/// Level 2 puts windows in place only in sections of at least this many +/// bytes: the title's page pool (6.1 GiB in one section, made at its start +/// and kept), so that a view of ours, which stays mapped, never holds a +/// section the title let go. +const POOL_LEAST: u64 = 1 << 30; + +/// The most bytes of level-2 regions at once (`LEONIDA_PORT_MB`, 3072): their +/// pages are locked into the PC's memory while their heaps stand, as the +/// copies they stand in for were. +fn general_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("LEONIDA_PORT_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(3072) << 20) } /// A stretch of title memory opened as a heap through a view of ours. @@ -87,6 +127,9 @@ struct Region { start: u64, end: u64, heap: ID3D12Heap, + /// Opened by level 2 ([`place_window_anywhere`]): only a window's own + /// pages, counted against [`general_most`]. + general: bool, } // SAFETY: D3D12 heaps are free-threaded. @@ -101,10 +144,11 @@ static BOUNDS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// Since the start: regions opened, their bytes; title buffers and windows /// placed; refused because the memory is not one stretch of a section, /// not committed, refused by the host; regions forgotten because the title -/// mapped other pages there. Then, since the last line: fills read out of -/// ported memory on the CPU, their bytes, buffer copies on the CPU that -/// touch it, their bytes. -static STATS: [AtomicU64; 13] = [const { AtomicU64::new(0) }; 13]; +/// mapped other pages there; level-2 regions opened. Then, since the last +/// line: fills read out of ported memory on the CPU, their bytes, buffer +/// copies on the CPU that touch it, their bytes. Last, since the start: +/// level-2 windows refused over `LEONIDA_PORT_MB`. +static STATS: [AtomicU64; 14] = [const { AtomicU64::new(0) }; 14]; /// Whether `[at, at + len)` may be ported: in the title's 32-bit graphics /// memory. @@ -144,22 +188,71 @@ pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { } } +/// Level 2: a window of title memory `[start, start + len)` outside the +/// title's 32-bit graphics memory in place, if it is one stretch of the page +/// pool: called where a copy in the PC's memory would be made otherwise. +/// `None` leaves the caller to make that copy, as before. +pub(crate) fn place_window_anywhere(start: u64, len: u64) -> Option { + // The 32-bit graphics memory is level 1's, which was asked first. + if level() < 2 || len == 0 || wanted(start, len) { + return None; + } + let host = crate::host::host()?; + match place_in_as(&host.device, start, len, true) { + Ok(placed) => { + crate::inplace::counted(true, len); + let n = STATS[2].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + tracing::info!( + start = format_args!("{start:#x}"), + len, + "renderer port 1 (level 2): a window of the page pool in place, no copy of it in the PC's memory" + ); + } + Some(placed) + } + Err((at, why)) => { + let n = STATS[at].fetch_add(1, Ordering::Relaxed) + 1; + // "Not one stretch" is the common answer (private memory, scattered pages): said rarely. + if at != 3 && (n <= 8 || n.is_power_of_two()) { + tracing::info!(start = format_args!("{start:#x}"), len, why, "renderer port 1 (level 2): a window not in place, a copy as before"); + } + None + } + } +} + /// [`place_for`]'s work: the region holding the pages of `[start, start + /// len)`, opened if none does, and a buffer placed in it. `Err` with the /// statistic to count and why. pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result { + place_in_as(device, start, len, false) +} + +/// [`place_in`], with `general` for level 2 ([`place_window_anywhere`]): a +/// region of only the pages asked for, within [`general_most`]. +fn place_in_as(device: &ID3D12Device, start: u64, len: u64, general: bool) -> Result { let at = start & !(K64 - 1); let end = (start + len.max(1)).next_multiple_of(K64); let mut regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); let i = match regions.iter().position(|r| r.start <= at && end <= r.end) { Some(i) => i, None => { - let region = open_region(device, at, end)?; + if general { + let alive: u64 = regions.iter().filter(|r| r.general).map(|r| r.end - r.start).sum(); + if alive + (end - at) > general_most() { + return Err((13, format!("{} MB in place already: LEONIDA_PORT_MB", alive >> 20))); + } + } + let region = open_region(device, at, end, general)?; regions.push(region); let n = regions.len() - 1; let r = ®ions[n]; STATS[0].fetch_add(1, Ordering::Relaxed); STATS[1].fetch_add(r.end - r.start, Ordering::Relaxed); + if general { + STATS[8].fetch_add(1, Ordering::Relaxed); + } bounds(®ions); n } @@ -171,20 +264,98 @@ pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result Result { + let bytes = (end - at) as usize; + let Some(pages) = crate::inplace::page_sections(at as usize, bytes) else { + return Err((3, "not one stretch of a section and not page-by-page views".to_owned())); + }; + if pages + .iter() + .any(|(section, _)| !crate::inplace::section_bytes(*section).is_some_and(|b| b >= POOL_LEAST)) + { + return Err((3, "not in the page pool (a section under a gigabyte)".to_owned())); + } + let process = unsafe { GetCurrentProcess() }; + // SAFETY: a placeholder of our own; the pages mapped into it are the + // title's committed section pages, and the heap below is the only owner. + let hole = unsafe { + mem::VirtualAlloc2( + process, + std::ptr::null(), + bytes, + mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, + mem::PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) + } + .cast::(); + if hole.is_null() { + return Err((5, format!("no placeholder for the window: {}", std::io::Error::last_os_error()))); + } + for (i, (section, offset)) in pages.iter().enumerate() { + // SAFETY: a 64 KiB page of a section this run has a view of; the + // placeholder is ours and replaced page by page. + let view = unsafe { + mem::MapViewOfFile3( + *section as _, + process, + hole.add(i * K64 as usize).cast(), + *offset, + K64 as usize, + mem::MEM_REPLACE_PLACEHOLDER, + mem::PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + if view.Value.is_null() { + return Err((5, format!("no view of page {}: {}", i, std::io::Error::last_os_error()))); + } + } + match crate::inplace::open(device, crate::inplace::From::Part(hole as usize, bytes)) { + Ok(heap) => { + if STATS[8].load(Ordering::Relaxed) < 8 { + tracing::info!( + start = format_args!("{at:#x}"), + bytes, + pages = pages.len(), + "renderer port 1 (level 2): a scattered page-pool window gathered into one view of ours" + ); + } + Ok(Region { start: at, end, heap, general: true }) + } + Err(e) => Err((5, format!("refused by the host on the gathered view: {e}"))), + } +} + /// Opens the stretch around `[at, end)` (64 KiB aligned) as a heap through -/// a view of ours of the same pages. -fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result { +/// a view of ours of the same pages; with `general` (level 2) only `[at, +/// end)` itself, and only in the page pool ([`POOL_LEAST`]). +fn open_region(device: &ID3D12Device, at: u64, end: u64, general: bool) -> Result { let Some((first, bytes, section, offset)) = stretch(at as usize, (end - at) as usize) else { + if general { + return gather_region(device, at, end); + } return Err((3, format!("not one stretch of a section: {:?}", cover(at as usize, (end - at) as usize)))); }; + if general && !crate::inplace::section_bytes(section).is_some_and(|b| b >= POOL_LEAST) { + return Err((3, "not in the page pool (a section under a gigabyte)".to_owned())); + } // The whole stretch, kept to what may be ported: the next buffer in it // finds the region made. let (mut first, mut bytes, mut offset) = (first as u64, bytes as u64, offset); - if first < LOW && first + bytes > LOW { + if !general && first < LOW && first + bytes > LOW { bytes = LOW.saturating_sub(first); } - if bytes > MOST { - // Only what was asked for. + if general || bytes > MOST { + // Only what was asked for (level 2: the heap locks every page it + // holds, so no more than the copy it stands in for). offset += at - first; (first, bytes) = (at, end - at); } @@ -210,17 +381,22 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result { - tracing::info!( - start = format_args!("{first:#x}"), - bytes, - section = format_args!("{section:#x}"), - offset = format_args!("{offset:#x}"), - view = format_args!("{view:#x}"), - "renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours" - ); + // Level 2 opens hundreds of small regions: said for the first few. + let say = !general || STATS[8].load(Ordering::Relaxed) < 8; + if say { + tracing::info!( + start = format_args!("{first:#x}"), + bytes, + section = format_args!("{section:#x}"), + offset = format_args!("{offset:#x}"), + view = format_args!("{view:#x}"), + general, + "renderer port 1: a stretch of the title's graphics memory opened as a host heap through a view of ours" + ); + } // shortcut: the view stays mapped for good (the heap holds its // pages while anything names it). - Ok(Region { start: first, end: first + bytes, heap }) + Ok(Region { start: first, end: first + bytes, heap, general }) } Err(e) => { unmap(); @@ -294,14 +470,30 @@ pub(crate) fn log(frames: f64) { return; } let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); - let per: Vec = STATS[9..].iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let per: Vec = STATS[9..13].iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + // What stands now (the counts above are since the start): all regions, then level 2's. + let (alive, general) = { + let regions = REGIONS.lock().unwrap_or_else(|e| e.into_inner()); + let sum = |only_general: bool| { + regions.iter().filter(|r| !only_general || r.general).fold((0u64, 0u64), |a, r| (a.0 + 1, a.1 + (r.end - r.start))) + }; + (sum(false), sum(true)) + }; tracing::info!( - "renderer port 1 (LEONIDA_PORT_CONSTANTS=1): {} regions of the title's graphics memory in place ({} MB), {} title buffers and windows placed in them \ - (no host copy, nothing sent up or fetched back for them); per frame on the CPU: {:.0} fills read out of them ({:.1} KB), {:.1} buffer copies \ - touching them ({:.1} KB); since the start refused: {} not one stretch of a section, {} not committed, {} by the host, {} no buffer; {} regions \ - forgotten (other pages mapped there)", + "renderer port 1 (LEONIDA_PORT_CONSTANTS={}): {} regions of title memory in place now ({} MB; level 2: {} of them, {} MB of at most {} MB); \ + since the start {} regions opened ({} MB, {} by level 2) and {} title buffers and windows placed in them (no host copy, nothing sent up or \ + fetched back for them); per frame on the CPU: {:.0} fills read out of them ({:.1} KB), {:.1} buffer copies touching them ({:.1} KB); since the \ + start refused: {} not one stretch of a section, {} not committed, {} by the host, {} no buffer, {} over LEONIDA_PORT_MB; {} regions forgotten \ + (other pages mapped there)", + level(), + alive.0, + alive.1 >> 20, + general.0, + general.1 >> 20, + general_most() >> 20, s[0], s[1] >> 20, + s[8], s[2], per[0], per[1] / 1024.0, @@ -311,6 +503,7 @@ pub(crate) fn log(frames: f64) { s[4], s[5], s[6], + s[13], s[7], ); } @@ -402,4 +595,66 @@ mod tests { windows_sys::Win32::Foundation::CloseHandle(section); } } + + /// Level 2: a window in the page pool (a section of a gigabyte and more) + /// is placed in a region of only its own pages, and the card reads the + /// title's bytes there; a window in a small section is turned down. + #[test] + fn warp_level_two_opens_only_a_window_s_own_pages_of_the_page_pool() { + let _turn = crate::indirect::tests::warp_turn(); + let Some(device) = crate::inplace::tests::warp() else { return }; + if windows::core::Interface::cast::(&device).is_err() { + return; + } + const K: usize = 64 << 10; + // SAFETY (the whole test): the sections and views made here. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let mut made = Vec::new(); + for bytes in [POOL_LEAST as usize, 8 * K] { + let section = mem::CreateFileMappingW( + windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE, + std::ptr::null(), + mem::PAGE_READWRITE | mem::SEC_RESERVE, + (bytes as u64 >> 32) as u32, + bytes as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + crate::inplace::title_memory_section(section as usize, bytes as u64, false); + // A view of its first 8 pages, committed, as `xmem` maps them. + let view = mem::MapViewOfFile3(section, process, std::ptr::null(), 0, 8 * K, 0, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + assert!(!view.Value.is_null(), "{}", std::io::Error::last_os_error()); + assert!(!mem::VirtualAlloc(view.Value, 8 * K, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null()); + crate::inplace::title_memory_view(view.Value as usize, 8 * K, section as usize, 0); + made.push((section, view.Value as usize)); + } + let (pool, small) = (made[0].1 as u64, made[1].1 as u64); + // A window over pages 2 to 4 of the pool's view. + let (start, len) = (pool + 2 * K as u64 + 0x10, 2 * K as u64); + let placed = place_in_as(&device, start, len, true).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x10); + { + let regions = REGIONS.lock().unwrap(); + let r = regions.iter().find(|r| r.general && r.start <= start && start < r.end).expect("a level-2 region"); + assert_eq!((r.start, r.end), (pool + 2 * K as u64, pool + 5 * K as u64), "only the window's own pages are opened"); + } + let mut rig = crate::inplace::Rig::new(&device).unwrap(); + for (i, b) in std::slice::from_raw_parts_mut(start as *mut u8, len as usize).iter_mut().enumerate() { + *b = (i * 13 + 1) as u8; + } + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(got == std::slice::from_raw_parts(start as *const u8, len as usize), "the card reads the title's bytes"); + // Not the page pool: a copy as before. + assert!(matches!(place_in_as(&device, small + K as u64, K as u64, true), Err((3, _))), "a small section is turned down"); + drop(placed); + for &(section, view) in &made { + forget(view, 8 * K); + crate::inplace::views_gone(view, 8 * K); + assert!(mem::UnmapViewOfFile(mem::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) != 0, "the title's own view can be unmapped"); + crate::inplace::title_memory_section_gone(section as usize); + windows_sys::Win32::Foundation::CloseHandle(section); + } + } + } } diff --git a/d3d12/crates/leonida-gpu/src/resource.rs b/d3d12/crates/leonida-gpu/src/resource.rs index 2fc331a1ef..f9b4c9295b 100644 --- a/d3d12/crates/leonida-gpu/src/resource.rs +++ b/d3d12/crates/leonida-gpu/src/resource.rs @@ -1812,6 +1812,23 @@ pub(crate) fn room(memory: Option<[u64; 4]>) -> bool { // (With the tiles of the copies made level by level, whose own bytes // count as none: `crate::tiles`.) let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total(); + // Never add host copies while the card is already over the budget the + // system gave it, explicit budget or not. The free room in our own + // texture pool is not room for the title's heaps: on the 8 GB card this + // is how the process reached 7,991 MB, the title's tile heap filled to + // 3,516/3,977 MB and the NVIDIA driver faulted. With the explicit budget + // checked first, this line was never reached on 8 GB profiles: the + // 2026-11-29 runs went on adding copies at 7,823 of a 7,256 MB budget + // until the driver faulted (nvwgf2umx.dll+0x34a44a) or a host list did + // not close (0x8007000E). + if let Some([budget, used, ..]) = memory + && used >= budget + { + return false; + } + // An explicit budget is the 8 GB workaround from the VIctory fork run + // reports: it has to override the 90 % rule, or characters stay + // untextured as soon as the card crosses that line. if let Some(limit) = texture_budget_bytes() { return filled < limit; } diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 8415889fac..0205298877 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -6423,6 +6423,19 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: `wide` is a NUL-terminated path of a DLL the user asked to be loaded into this process. + let module = unsafe { LoadLibraryW(wide.as_ptr()) }; + if module.is_null() { + tracing::warn!( + path = %path.display(), + error = %std::io::Error::last_os_error(), + "preloaded DLL did not load ({})", + PRELOAD_DLLS_ENV + ); + } else { + tracing::info!(path = %path.display(), "preloaded DLL ({})", PRELOAD_DLLS_ENV); + } + } +} diff --git a/d3d12/docs/8gb-memory-2026-11-30.md b/d3d12/docs/8gb-memory-2026-11-30.md new file mode 100644 index 0000000000..38ea6186db --- /dev/null +++ b/d3d12/docs/8gb-memory-2026-11-30.md @@ -0,0 +1,65 @@ +# 8 GB cards: over-budget guard, page-pool in-place prototype and the 8 GB profile + +Measured on an RTX 3060 Ti 8 GB, Ryzen 5 5600, 16 GB RAM, Windows 11 26H2, +driver 621.40, Series S, 540p, after the shader warm-up. No game data is +included in this note. + +## What changed + +- **`resource.rs` `room()`**: the "card is already over its DXGI budget" check + now runs before the explicit `LEONIDA_TEXTURE_BUDGET_MB` branch. The 8 GB + profiles set that budget, so without this order the runtime kept adding host + copies at 7.8 GB of a 7.25 GB budget until the driver faulted. +- **`inplace.rs` / `port.rs` / `shadow.rs`, level 2** (`LEONIDA_PORT_CONSTANTS=2`, + off by default): a page-pool window whose pages are not one run of a section + is gathered page-by-page into one view of ours and opened as a host heap, so + the card reads the title's bytes without a PC copy. `inplace::page_sections` + supplies the section/offset of each 64 KiB page. +- **`preload.rs` + `LEONIDA_PRELOAD_DLLS`**: load user-supplied DLLs before the + GPU is made. Off unless set; no DLLs are shipped. +- **`scripts/play-8gb.ps1`**: the 8 GB profile. 540p, the title's own upscaler, + no DLSS and no frame generation; texture budget 4000 MB, staging 1024 MB, + card buffers 1024 MB, 512 MB of title-memory windows, page writes 262 and a + 120-frame heap recheck. + +## Measured + +| Configuration | Result | +|---|---| +| 540p, textures 4000, card 1024, windows 512 | **18–19 fps** in the prison interiors; 7.76–7.82 GB of card memory; guard's face and Lucia's hair textured | +| same, heaviest cutscene | after **6m54s**: `nvwgf2umx.dll+0x34a44a` (read `0xc`), tile heap 3,290/3,977 MB, `Unused 0/203 MB` | +| 540p, textures 3000, card 1024 | **17 fps** at 3,609 draws; 7.23 GB; after **8m51s** `DEVICE_REMOVED` (`0x887A0005`), card 7,781 of 7,252 MB, shared 7,057 of 7,491 MB, 307 MB free RAM | +| 540p + frame generation 2x on the title upscaler | 14 fps rendered / **27 shown**; frame generation disabled with `eWarnOutOfVRAM` at 7.98 GB | +| 720p DLSS quality + frame generation 2x | 12–13 fps rendered / 22–25 shown; off at about 7.95 GB | +| Series S DLSS **performance** (960x540) | title aborts at the first upscale: `FSR4 configuration mismatch: maxRenderSize must be 1280x720` | +| full D3D12 debug layer + full DRED | no failed `Create*` and no `severity=3` message; the device is removed by a TDR at the same memory wall | +| `LEONIDA_PORT_CONSTANTS=2` page-pool gather | 1 region / 4 MB placed; 1,081 windows not one stretch; 65 refused with `MapViewOfFile3` os error 487; 10 fps | + +The pagefile was 64 GB on H: and 1 GB on C: in the later runs. It removed +commit failures, not the GPU wall: the card and WDDM shared memory were both +full. + +## Known limits + +- **8 GB VRAM is the wall.** The profile removes copies and lowers the + pressure; it does not fit the heaviest cutscenes. 12 GB cards in the public + reports use 10+ GB. +- **`LEONIDA_PORT_CONSTANTS=2` is experimental and currently fails on many + page-pool windows** with `MapViewOfFile3` error 487. It is off by default and + should not be enabled for play until the gathered-view path is fixed. +- **DLSS performance is not usable on Series S** because the title's FSR4 + path requires 1280x720. +- **Official DLSS frame generation is not supported on RTX 30.** The runtime + can use FSR 3 through other forks; this repository does not include a + frame-generation DLL. + +## Run the profile + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\play-8gb.ps1 -Game -Log +``` + +The profile leaves DLSS and frame generation off on purpose: on this PC the +540p title upscaler was the fastest configuration that kept the faces correct. +For a heavy cutscene, lower the texture budget first; the profile's comment +lists the 8 GB switches. diff --git a/scripts/play-8gb.ps1 b/scripts/play-8gb.ps1 new file mode 100644 index 0000000000..375ff0677b --- /dev/null +++ b/scripts/play-8gb.ps1 @@ -0,0 +1,60 @@ +# Leonida, 8 GB card / 16 GB RAM profile. +# +# This is the best 540p combination measured on the RTX 3060 Ti 8 GB on +# 2026-11-29, after the VIctory 8 GB reports (Marvisak/VIctory #1820): +# +# - LEONIDA_TEXTURE_BUDGET_MB=4000 bounds the host copies of textures. +# resource::room() still refuses new copies while the card is over the +# DXGI budget; both are needed on 8 GB. +# - LEONIDA_TEXTURE_STAGE_MB=1024 drains that queue without the 2 GB +# staging backlog the 32 GB-RAM reports use. +# - LEONIDA_CARD_BUFFERS_MB=1024 is the 8 GB end of the reported range; +# 1536 is too much, 512 costs too much CPU (19 -> 7 fps here). +# - 512 MB of title-memory windows. 0 caused a shared-buffer OOM. +# +# The VIctory fork's 256 KiB / tails window trick is deliberately not used: +# in this runtime it created 37,579 windows / 36 GB of PC memory and paged +# the game to 1 fps. Its plain-window host-copy patch is not here. +# +# Expect about 18-19 fps in the prison interiors, 15-19 in the cutscenes, +# 7.7-7.8 GB of VRAM and about 1 GB of free RAM on a 16 GB machine. The +# remaining failures at the heaviest cutscenes are the 8 GB / 16 GB wall, +# not the texture queue. +# +# powershell -ExecutionPolicy Bypass -File scripts\play-8gb.ps1 -Game +param( + [Parameter(Mandatory = $true)][string]$Game, + [string]$Data = (Join-Path $env:LOCALAPPDATA "Leonida\d3d12"), + [switch]$Quality, + [switch]$NoPrecompile, + [switch]$Log, + [switch]$DryRun +) + +$more = @{ + LEONIDA_WINDOWS_BAR_MB = '512' + LEONIDA_TEXTURE_BUDGET_MB = '4000' + LEONIDA_TEXTURE_STAGE_MB = '1024' + LEONIDA_TEXTURE_NO_WAIT = '1' + LEONIDA_CARD_BUFFERS_MB = '1024' + LEONIDA_CARD_BUFFERS_MIN_KB = '64' + LEONIDA_CARD_ROOM_FOR_TARGETS_MB = '3584' + LEONIDA_PAGE_WRITES = '262' + LEONIDA_HEAP_RECHECK_EVERY = '120' + LEONIDA_JOIN_PARTS = '1' + LEONIDA_BAKE_TEXTURES_MS = '0' +} + +$launch = @{ + Game = $Game + Data = $Data + SeriesS = $true + Resolution = '540' + More = $more +} +if ($Quality) { $launch.Quality = $true } +if ($NoPrecompile) { $launch.NoPrecompile = $true } +if ($Log) { $launch.Log = $true } +if ($DryRun) { $launch.DryRun = $true } + +& (Join-Path $PSScriptRoot 'play-d3d12.ps1') @launch