From 63957271cdd1783da4164f398d6ed75270035b74 Mon Sep 17 00:00:00 2001 From: trustno1-coder <361337194+trustno1-coder@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:56:14 -0800 Subject: [PATCH] CGBJ's renderer, DLSS, an F1 settings menu, frame generation, ray tracing switch The default of scripts\play-nvidia.ps1 changes: the game renders its own 720p and DLSS takes it to 1080p (Series S), in place of the half render scale and the title's upscaler. -Resolution still reaches the older path. - Renderer: codec-d/cool_fox f4b48ad (GPL-3.0) with this fork's NVIDIA fixes on top (residency.rs, stretch.rs, the ffx upscale dispatch). - DLSS for the title's upscale, from avatarmanz/VIctory-7900XTX pull request 203 (feature `dlss`, VICTORY_UPSCALE=dlss), with VICTORY_DLSS_PRESET and a live sharpness setting. - F1 settings menu in the game (host/menu.rs): saved to victory-settings.txt, applied by the launcher at the next start, "save and restart" from the menu. F3: the panel, now with the generated frame rate beside the real one. - DLSS frame generation through NVIDIA Streamline (streamline.rs, fg.rs), 2x to 6x, the amount changed while playing. Constants and the depth and motion vector tags are handed over at each present. - VICTORY_FPS_CAP: the title's own 30 frames a second can be lifted (60, 120, none), live from the menu. - Real ray tracing as an option (-RayTracing, VICTORY_BVH_BUILDER=1): on this renderer the structure builder runs on NVIDIA. Frame generation is left off with it: the two together run at about 0.1 fps, cause not found. - VICTORY_HEAP_RECHECK_EVERY: textures picked by index looked at again for the whole run (a test against the posterized look). - Get-NVIDIA-DLSS.cmd / scripts\get-nvidia-sdks.ps1: fetch the few NVIDIA files DLSS and frame generation need (about 70 MB) from NVIDIA's GitHub into nvidia-sdk\ (git-ignored). They are NVIDIA's, under NVIDIA's licences, and are not part of this repository. Without them the picture is stretched and there is no frame generation. - scripts\build-nvidia.ps1; the launcher builds the layer when it is not built, and again with DLSS once those files are there. Measured on an RTX 5070 (Series S, DLSS, opening rooms): about 15-17 fps without ray tracing, 13-15 with it, before generated frames. What is known to be wrong is in the README's new section. Co-Authored-By: Claude Fable 5.2 --- .gitignore | 5 + Cargo.lock | 1 + Get-NVIDIA-DLSS.cmd | 11 + README.md | 70 +- apps/victory/Cargo.toml | 3 + apps/victory/src/run.rs | 31 +- crates/victory-gpu/Cargo.toml | 3 + crates/victory-gpu/build.rs | 9 + crates/victory-gpu/src/ambient.rs | 17 +- crates/victory-gpu/src/compose.rs | 491 ++-- crates/victory-gpu/src/descriptor/host.rs | 519 ++++- crates/victory-gpu/src/dlss.rs | 318 +++ crates/victory-gpu/src/draw.rs | 851 +++++-- crates/victory-gpu/src/fence.rs | 33 +- crates/victory-gpu/src/fg.rs | 405 ++++ crates/victory-gpu/src/frame.rs | 47 +- crates/victory-gpu/src/host.rs | 429 +++- crates/victory-gpu/src/host/card_steps.rs | 6 + crates/victory-gpu/src/host/menu.rs | 528 +++++ crates/victory-gpu/src/host/panel.rs | 27 +- crates/victory-gpu/src/host/place.rs | 1 + crates/victory-gpu/src/host/upcheck.rs | 42 + crates/victory-gpu/src/indirect.rs | 10 +- crates/victory-gpu/src/lib.rs | 16 +- crates/victory-gpu/src/list.rs | 165 ++ crates/victory-gpu/src/list/thin.rs | 20 + crates/victory-gpu/src/pipeline.rs | 3 + crates/victory-gpu/src/pipeline/host.rs | 1 + crates/victory-gpu/src/pipeline/make.rs | 94 +- crates/victory-gpu/src/pool.rs | 93 +- crates/victory-gpu/src/queue.rs | 188 +- crates/victory-gpu/src/queue/behind.rs | 25 +- crates/victory-gpu/src/residency.rs | 201 ++ crates/victory-gpu/src/resource.rs | 9 + crates/victory-gpu/src/shadow.rs | 6 + crates/victory-gpu/src/streamline.rs | 2184 ++++++++++++++++++ crates/victory-gpu/src/stretch.rs | 292 +++ crates/victory-gpu/src/texture.rs | 254 +- crates/victory-gpu/src/texture/ahead.rs | 72 +- crates/victory-hle/src/modules/audio.rs | 24 +- crates/victory-hle/src/modules/dstorage.rs | 15 +- crates/victory-hle/src/modules/ffx.rs | 250 ++ crates/victory-hle/src/modules/gameinput.rs | 9 +- crates/victory-hle/src/modules/mod.rs | 1 + crates/victory-shader/src/emit/diff_tests.rs | 39 +- crates/victory-shader/src/emit/host.rs | 46 + crates/victory-shader/src/emit/intersect.rs | 23 +- crates/victory-shader/src/emit/lower.rs | 90 +- crates/victory-shader/src/emit/mod.rs | 131 +- crates/victory-shader/src/emit/shader.rs | 5 + crates/victory-shader/src/emit/valu_tests.rs | 693 +++--- crates/victory-shader/src/resource.rs | 129 +- scripts/build-nvidia.ps1 | 25 + scripts/get-nvidia-sdks.ps1 | 154 ++ scripts/play-nvidia.ps1 | 229 +- 55 files changed, 8030 insertions(+), 1313 deletions(-) create mode 100644 Get-NVIDIA-DLSS.cmd create mode 100644 crates/victory-gpu/src/dlss.rs create mode 100644 crates/victory-gpu/src/fg.rs create mode 100644 crates/victory-gpu/src/host/menu.rs create mode 100644 crates/victory-gpu/src/residency.rs create mode 100644 crates/victory-gpu/src/streamline.rs create mode 100644 crates/victory-gpu/src/stretch.rs create mode 100644 crates/victory-hle/src/modules/ffx.rs create mode 100644 scripts/build-nvidia.ps1 create mode 100644 scripts/get-nvidia-sdks.ps1 diff --git a/.gitignore b/.gitignore index ac9edc3..a089e99 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,8 @@ *.swp Thumbs.db .DS_Store + +# NVIDIA's own files (scripts/get-nvidia-sdks.ps1 fetches them from NVIDIA; never part of this repository) +/nvidia-sdk/ +# What the F1 menu saved +/victory-settings.txt diff --git a/Cargo.lock b/Cargo.lock index 29bab8c..b0b1c77 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "memchr", "victory-core", "victory-game", + "victory-gpu", "victory-hle", "victory-loader", "victory-pe", diff --git a/Get-NVIDIA-DLSS.cmd b/Get-NVIDIA-DLSS.cmd new file mode 100644 index 0000000..9c03370 --- /dev/null +++ b/Get-NVIDIA-DLSS.cmd @@ -0,0 +1,11 @@ +@echo off +rem Downloads the NVIDIA files that DLSS and DLSS frame generation need (about 70 MB) from NVIDIA's own +rem GitHub and puts them where the launcher looks for them (nvidia-sdk\ in this folder). Run it once. +rem They are NVIDIA's files under NVIDIA's licences, which are saved beside them; this repository does +rem not contain them. Without them the game still runs: its picture is stretched instead of going +rem through DLSS, and there is no DLSS frame generation. +rem Get-NVIDIA-DLSS.cmd DLSS and frame generation +rem Get-NVIDIA-DLSS.cmd -NoStreamline DLSS only (about 60 MB) +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\get-nvidia-sdks.ps1" %* +echo. +pause diff --git a/README.md b/README.md index 53a6c1c..1b2b054 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,51 @@ everything on NVIDIA cards and run fastest there**, using the Series S profile. copy of the game. It is not affiliated with or endorsed by the game's developer or publisher. +## New on 2026-11-26: another renderer, DLSS, a settings menu + +The default of `scripts\play-nvidia.ps1` changed. What is below this section +was written on 2026-11-25 for the settings before it, which `-Resolution` +still reaches. + +- **The renderer is CGBJ's** ([codec-d/cool_fox](https://github.com/codec-d/cool_fox) + `f4b48ad`, GPL-3.0 like this fork), with this fork's NVIDIA fixes on top. +- **DLSS does the title's upscale** (from pull request 203 of + [avatarmanz/VIctory-7900XTX](https://github.com/avatarmanz/VIctory-7900XTX)): + the game renders its own 720p and DLSS takes it to 1080p, in place of the + render scale and the title's upscaler. Series S only. +- **F1 in the game opens a settings menu** (arrows pick and change, Enter + does it): upscaler, DLSS model and sharpness, frame generation, frame rate + cap, ray tracing, Smooth Motion, console profile, graphics card, and the + speed switches. Lines marked LIVE change at once; the others are saved to + `victory-settings.txt` and apply at the next start, which "SAVE AND RESTART + NOW" does for you. F3 shows the numbers panel. +- **DLSS frame generation** (NVIDIA Streamline), 2x to 6x, from the menu. The + amount changes while playing. Frames are only generated while the game's + window has the focus. +- **Frame rate cap**: the title asks for 30 frames a second; the menu's FRAME + RATE CAP lifts that (60, 120 or none). +- **Real ray tracing**, off by default: `-RayTracing` or the menu. On this + renderer the title's structure builder runs on NVIDIA (53 programs), and + the draws dropped for it go from hundreds or thousands a frame to one. + +Measured on the RTX 5070 below (Series S, DLSS, opening rooms): about 15-17 +fps without ray tracing and 13-15 with it, before generated frames. + +Known to be wrong with it: + +- **Ray tracing and DLSS frame generation together do not work**: about 0.1 + fps and a white picture. Each alone is fine. The launcher and the layer + leave frame generation off when ray tracing is on (Smooth Motion can do the + extra frames then). The cause is not found. +- **Without ray tracing, lit places further into the game blow out to white + with black holes** (the bank, outdoors): the lighting runs with every ray + missing. With ray tracing on, that has not been checked that far yet. +- **With ray tracing, shaders build for minutes** the first time a place is + seen (about 1,700 pipelines for the opening alone). +- **A posterized "oil paint" look** comes in some runs and not in others. +- "SAVE AND RESTART NOW" can leave the old game's process behind without a + window; it goes when the PC restarts. + ## Where it stands (2026-11-25) Tested on one machine only: Windows 11, AMD Ryzen 7 9800X3D, 64 GB RAM, @@ -231,16 +276,33 @@ tools, and your own dump of the title. git clone https://github.com/trustno1-coder/VIctory-NVIDIA cd VIctory-NVIDIA copy victory.example.toml victory.toml # then set your paths, outside this folder -cargo build --locked --profile diag -p victory --features diagnostics scripts\play-nvidia.ps1 -Exe ``` +The first start builds the layer by itself (`scripts\build-nvidia.ps1`: the +`diag` profile with `diagnostics`). + +**For DLSS and DLSS frame generation, run `Get-NVIDIA-DLSS.cmd` once** (double +click it, or `Get-NVIDIA-DLSS.cmd -NoStreamline` for DLSS alone). It downloads +the few NVIDIA files they need, about 70 MB, from NVIDIA's own GitHub +([NVIDIA/DLSS](https://github.com/NVIDIA/DLSS), +[NVIDIA-RTX/Streamline](https://github.com/NVIDIA-RTX/Streamline)) into +`nvidia-sdk\` (git-ignored), and the next start builds the layer again with +DLSS in it (about a minute). Those files are NVIDIA's, under NVIDIA's licences, +which are saved beside them; this repository does not carry them and may not. +A build with DLSS links NVIDIA's loader library: it is for your own use, not +for passing on. + +Without that step the game runs all the same: its 720p picture is stretched to +the screen instead of going through DLSS (softer), and there is no DLSS frame +generation. Nothing is downloaded unless you run that file. + `scripts\play-nvidia.ps1` starts a copy of the build named `victory_sm.exe`, so NVIDIA Smooth Motion applies every time once it is turned on for that exe in the NVIDIA App. `-NoSmoothMotion` runs `victory.exe` itself; `-SeriesX` uses the -Series X profile (sharper, much slower); `-Quality` gives fewer stretched bodies -and less rainbow skin for about 7 fps. The fork's own `scripts\play.ps1` is -still there for AMD cards. +Series X profile (sharper, much slower, no DLSS); `-Quality` gives fewer +stretched bodies, slower; `-RayTracing` turns the title's real ray tracing on. +The fork's own `scripts\play.ps1` is still there for AMD cards. ### Picking a resolution diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index 5fddd5b..86fcf7d 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -12,6 +12,7 @@ victory-core.workspace = true victory-pe.workspace = true victory-loader.workspace = true victory-hle.workspace = true +victory-gpu.workspace = true victory-shader = { workspace = true, features = ["host"] } victory-game.workspace = true anyhow.workspace = true @@ -21,6 +22,8 @@ clap.workspace = true walkdir.workspace = true [features] +# NVIDIA DLSS for the title's upscale (VICTORY_UPSCALE=dlss); needs VICTORY_DLSS_SDK. +dlss = ["victory-gpu/dlss"] # Debug-level logs and the debugging switches (frame capture, stack dumps, # the host debug layer, scripted keys). Off in a plain release build. diagnostics = [ diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 6706904..5e3f35a 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -108,6 +108,11 @@ pub fn run( println!("console {}", victory_hle::console::current().name()); let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; for (name, dll) in &dlls { + if name.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && let Some(real) = dll.export("ffxDispatch") + { + victory_hle::modules::ffx::set_real_dispatch(real); + } println!("title dll {name} at {:#x}", dll.base()); victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); } @@ -162,7 +167,31 @@ pub fn run( show(name, dll.bind_imports(&with_dlls, policy)?); } let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); - show(&exe_name, image.bind_imports(&with_dlls, policy)?); + // `VICTORY_UPSCALE=stretch` (Series S): the upscale dispatch is ours + // (`victory_hle::modules::ffx`, a plain stretch) instead of the title's + // own FidelityFX passes, which are slow translated on 32-lane hosts; the + // rest of that DLL stays the title's. Unset: the title's own, as before. + struct TakeDispatch<'a>(&'a dyn victory_loader::ImportResolver, bool); + impl victory_loader::ImportResolver for TakeDispatch<'_> { + fn resolve(&self, dll: &str, symbol: &victory_pe::ImportSymbol) -> victory_loader::Resolution { + let ours = self.1 + && dll.eq_ignore_ascii_case(victory_hle::modules::ffx::LOADER) + && matches!(symbol, victory_pe::ImportSymbol::Name { name, .. } if name == "ffxDispatch"); + if ours { + return victory_loader::Resolution::Found { + address: victory_hle::modules::ffx::dispatch_address(), + provenance: victory_loader::Provenance::Hle, + }; + } + self.0.resolve(dll, symbol) + } + } + let take = victory_hle::console::current() == victory_hle::console::Console::SeriesS + && std::env::var_os("VICTORY_UPSCALE").is_some_and(|v| v == "stretch" || v == "dlss"); + if take { + println!("upscale the title's ffxDispatch is ours (VICTORY_UPSCALE=stretch|dlss)"); + } + show(&exe_name, image.bind_imports(&TakeDispatch(&with_dlls, take), policy)?); if execute { let size = image.info().size_of_image as usize; // SAFETY: the image stays mapped, and nothing of it has run yet. diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 16c7495..d98532e 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -25,6 +25,9 @@ tempfile.workspace = true [features] # Debugging switches (frame capture, the host debug layer, per-draw data). diagnostics = [] +# NVIDIA DLSS for the title's upscale (`VICTORY_UPSCALE=dlss`); needs the DLSS +# SDK (NVIDIA/DLSS: include, lib/Windows_x86_64) at `VICTORY_DLSS_SDK`. +dlss = [] [lints] workspace = true diff --git a/crates/victory-gpu/build.rs b/crates/victory-gpu/build.rs index 9dcfa61..591d003 100644 --- a/crates/victory-gpu/build.rs +++ b/crates/victory-gpu/build.rs @@ -42,4 +42,13 @@ fn main() { } println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rustc-env=VICTORY_TRANSLATOR={}", hash.finalize().to_hex()); + // The `dlss` feature links the DLSS SDK's loader (`nvsdk_ngx_d.lib`, the + // dynamic-CRT one) from `VICTORY_DLSS_SDK`. + println!("cargo:rerun-if-env-changed=VICTORY_DLSS_SDK"); + if std::env::var_os("CARGO_FEATURE_DLSS").is_some() { + let sdk = std::env::var_os("VICTORY_DLSS_SDK") + .map(PathBuf::from) + .expect("the dlss feature needs VICTORY_DLSS_SDK (the NVIDIA/DLSS checkout)"); + println!("cargo:rustc-link-search=native={}", sdk.join("lib/Windows_x86_64/x64").display()); + } } diff --git a/crates/victory-gpu/src/ambient.rs b/crates/victory-gpu/src/ambient.rs index a714aa2..e868476 100644 --- a/crates/victory-gpu/src/ambient.rs +++ b/crates/victory-gpu/src/ambient.rs @@ -112,18 +112,6 @@ fn air() -> f32 { }) } -/// LOCAL: how many times the estimate the title's own result may keep -/// (`VICTORY_AMBIENT_MOST=`, 4 when unset). Without rays the -/// probes hold the sky's light indoors too; at 4 times the estimate a room -/// looked towards a window or the sky goes very bright. -fn most() -> f32 { - static SET: OnceLock = OnceLock::new(); - *SET.get_or_init(|| { - let set = std::env::var("VICTORY_AMBIENT_MOST").unwrap_or_default(); - set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(4.0) - }) -} - /// Strength and radius of the creases' shade. fn shade() -> [f32; 2] { static SET: OnceLock<[f32; 2]> = OnceLock::new(); @@ -255,9 +243,6 @@ void clear_air(uint3 at : SV_DispatchThreadID) { float far = float(at.z) / float(d); float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far); float3 c = scattered[at]; - // LOCAL: a NaN or infinity in the air is summed along every view ray - // through it: black or white patches floating in the room. - if (any(isnan(c)) || any(isinf(c))) { scattered[at] = 0; return; } float has = dot(c, LUMA); if (has > cap) scattered[at] = c * (cap / has); } @@ -474,7 +459,7 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool { words[6] = views.size[0]; words[7] = views.size[1]; words[8] = 0.04f32.to_bits(); - words[9] = most().to_bits(); + words[9] = 4.0f32.to_bits(); words[10] = air().to_bits(); let l = &list.list; // SAFETY: an open list with the heap of the views set; the title's diff --git a/crates/victory-gpu/src/compose.rs b/crates/victory-gpu/src/compose.rs index 9aa45cb..dfcf50b 100644 --- a/crates/victory-gpu/src/compose.rs +++ b/crates/victory-gpu/src/compose.rs @@ -1,244 +1,325 @@ -//! Ported from fxceless/victory-gta6 PR #1189 (Series S interface plane), `VICTORY_COMPOSE=1`. -//! A present's second plane laid over its first. -//! -//! A Series S title presents two planes (run 2026-11-25: plane 0 the -//! game, 1920x1080 or what the display mode makes it, plane 1 the -//! interface, 3840x2160); the console's display lays the second over the -//! first and scales both to the screen. The host shows one texture, so -//! the interface is laid over the game here, at the game plane's size, -//! into a texture of ours that is shown instead (filtered: the interface -//! is scaled down). shortcut: the planes' placement and source rectangles -//! are not read; both cover the screen. The interface's alpha is taken as -//! straight (`VICTORY_PLANE_PREMULTIPLIED=1`: premultiplied). - -use std::sync::Mutex; +//! 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. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; use windows::Win32::Graphics::Direct3D::ID3DBlob; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::{PCSTR, s}; -/// Frames of descriptors in the ring (three each): presents in flight -/// must not find theirs rewritten. -const SLOTS: u32 = 16; +use crate::host::Host; const SOURCE: &str = r#" -#define RS "RootConstants(num32BitConstants=3, b0), DescriptorTable(SRV(t0, numDescriptors=2), UAV(u0)), StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)" -cbuffer Size : register(b0) { uint w; uint h; uint premultiplied; }; -Texture2D game : register(t0); -Texture2D ui : register(t1); -RWTexture2D outp : register(u0); -SamplerState linear_clamp : register(s0); +#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)] -[numthreads(8, 8, 1)] -void main(uint3 id : SV_DispatchThreadID) { - if (id.x >= w || id.y >= h) return; - float2 uv = (float2(id.xy) + 0.5) / float2(w, h); - float4 g = game.Load(int3(id.xy, 0)); - float4 u = ui.SampleLevel(linear_clamp, uv, 0); - float3 c = premultiplied != 0 ? g.rgb * (1.0 - u.a) + u.rgb : lerp(g.rgb, u.rgb, u.a); - outp[id.xy] = float4(c, 1.0); +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; +} +[RootSignature(RS)] +float4 ps(V v) : SV_Target { + float4 s = scene.SampleLevel(smooth_, v.uv, 0); + float4 o = over.SampleLevel(smooth_, v.uv, 0); + return float4(saturate(o.rgb + s.rgb * (1 - saturate(o.a))), 1); } "#; -struct Pass { +pub(crate) struct Composer { root: ID3D12RootSignature, pso: ID3D12PipelineState, - views: ID3D12DescriptorHeap, - cpu: usize, - gpu: u64, + views: Vec, step: u32, - next: u32, - /// The texture shown instead, by size. - out: Option<(u64, u32, ID3D12Resource)>, } -// SAFETY: D3D12 objects are free-threaded; the pass is used under a lock. -unsafe impl Send for Pass {} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Composer {} +// SAFETY: as above. +unsafe impl Sync for Composer {} -/// The pass: not tried yet, could not be made, or made. -static PASS: Mutex>> = Mutex::new(None); - -fn make(device: &ID3D12Device) -> windows::core::Result { +fn compile(entry: PCSTR, target: PCSTR) -> windows::core::Result { let mut code: Option = None; - // SAFETY: the source and names live through the call; the out pointer - // is ours. + // SAFETY: the source and names live through the call; the out pointer is + // ours. unsafe { D3DCompile( SOURCE.as_ptr().cast(), SOURCE.len(), - windows::core::s!("present planes"), + s!("compose"), None, None, - windows::core::s!("main"), - windows::core::s!("cs_5_1"), + entry, + target, 0, 0, &mut code, None, )?; } - let code = code.ok_or_else(windows::core::Error::empty)?; - // SAFETY: the blob's own bytes (the root signature is inside the - // shader); plain object creation and queries. - unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); - let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; - let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - })?; - let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - let views: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: SLOTS * 3, - Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, - NodeMask: 0, - })?; - Ok(Pass { - cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, - gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, - step: device.GetDescriptorHandleIncrementSize(kind), - root, - pso, - views, - next: 0, - out: None, - }) + code.ok_or_else(windows::core::Error::empty) +} + +impl Composer { + pub(crate) fn new(host: &Host, format: DXGI_FORMAT) -> windows::core::Result { + let (vs, ps) = ( + compile(s!("vs"), s!("vs_5_1"))?, + compile(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(), + BytecodeLength: b.GetBufferSize(), + }; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs), + PS: code(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.RTVFormats[0] = format; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let pso = device.CreateGraphicsPipelineState(&desc)?; + Ok(Composer { + root, + pso, + views: Vec::new(), + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + }) + } + } + + /// 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. + pub(crate) fn record( + &mut self, + host: &Host, + slot: usize, + list: &ID3D12GraphicsCommandList, + planes: [(&ID3D12Resource, DXGI_FORMAT); 2], + back: &ID3D12Resource, + (width, height): (u32, u32), + ) -> windows::core::Result<()> { + 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, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })? + }; + self.views.push(heap); + } + let views = &self.views[slot]; + // SAFETY: an open list; the views are made in slots no frame in flight + // reads; live textures. + unsafe { + let (cpu, gpu) = ( + views.GetCPUDescriptorHandleForHeapStart(), + views.GetGPUDescriptorHandleForHeapStart(), + ); + for (i, plane) in planes.iter().enumerate() { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: cpu.ptr + (i * self.step as usize), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: plane.1, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + host.device + .CreateShaderResourceView(Some(plane.0), Some(&desc), at); + } + let rtv = host.rtv(Some(back), None); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetGraphicsRootSignature(&self.root); + list.SetPipelineState(&self.pso); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: width as f32, + Height: height as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.DrawInstanced(3, 1, 0, 0); + } + Ok(()) } } -/// Whether a host texture's format is one this pass reads and writes -/// (8-bit RGBA, typeless or not). -fn rgba8(format: DXGI_FORMAT) -> bool { - matches!(format.0, 27 | 28) -} - -fn premultiplied() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_PLANE_PREMULTIPLIED").is_some_and(|v| v == "1")) -} - -/// Records, into the present's `list`, `ui` laid over `game` into a -/// texture of ours, and gives that texture, left in the copy-source -/// state. `game` is in the copy-source state (the present put it there); -/// `ui` is in `ui_state` and is left in it. `None` (nothing recorded) if -/// a format is not 8-bit RGBA or the pass could not be made. -pub(crate) fn record( - device: &ID3D12Device, - list: &ID3D12GraphicsCommandList, - game: &ID3D12Resource, - ui: &ID3D12Resource, - ui_state: u32, -) -> Option { - // SAFETY: live resources; plain queries. - let (gd, ud) = unsafe { (game.GetDesc(), ui.GetDesc()) }; - if !rgba8(gd.Format) || !rgba8(ud.Format) { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - tracing::warn!(game = gd.Format.0, ui = ud.Format.0, "present planes not laid over each other: a format this pass does not read"); - }); +/// Select a legal float-sampled view of a display plane, preserving a typed +/// resource's format. Typeless resources use the corresponding display type. +pub(crate) fn view(d: &D3D12_RESOURCE_DESC) -> Option { + if d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || d.DepthOrArraySize != 1 + || d.SampleDesc.Count != 1 + || d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + { return None; } - let mut kept = PASS.lock().unwrap_or_else(|e| e.into_inner()); - if kept.is_none() { - *kept = Some(match make(device) { - Ok(p) => { - tracing::info!(premultiplied = premultiplied(), "present planes: the interface is laid over the game"); - Some(p) + match d.Format.0 { + 9 => Some(DXGI_FORMAT_R16G16B16A16_FLOAT), + 23 => Some(DXGI_FORMAT_R10G10B10A2_UNORM), + 27 => Some(DXGI_FORMAT_R8G8B8A8_UNORM), + 90 => Some(DXGI_FORMAT_B8G8R8A8_UNORM), + 10 | 11 | 13 | 24 | 26 | 28 | 29 | 31 | 67 | 87 | 91 => Some(d.Format), + _ => None, + } +} + +#[cfg(all(test, feature = "diagnostics"))] +mod tests { + use super::*; + + #[test] + fn composes_scaled_premultiplied_plane_on_gpu() { + let Some(host) = crate::host::host() else { + eprintln!("skipping display-plane readback: no D3D12 device"); + return; + }; + 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 target = D3D12_RESOURCE_STATE_RENDER_TARGET; + let read = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + let cmds = &list.list; + unsafe { + cmds.ClearRenderTargetView(host.rtv(Some(&base), None), &[0.5, 0.0, 0.0, 1.0], None); + let overlay_rtv = host.rtv(Some(&overlay), None); + let colors = [ + [0.0, 0.0, 0.0, 0.0], + [0.0, 0.5, 0.0, 0.5], + [0.0, 0.0, 1.0, 1.0], + ]; + for (i, color) in colors.iter().enumerate() { + let rect = windows::Win32::Foundation::RECT { + left: i as i32, + right: i as i32 + 1, + top: 0, + bottom: 1, + }; + cmds.ClearRenderTargetView(overlay_rtv, color, Some(&[rect])); } - Err(e) => { - tracing::warn!(error = %e, "present planes: the pass that lays them over each other could not be made"); - None + cmds.ResourceBarrier(&[ + crate::host::transition(&base, target, read), + crate::host::transition(&overlay, target, read), + ]); + compositor + .record( + host, + 0, + cmds, + [(&base, format), (&overlay, format)], + &output, + (3, 1), + ) + .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 start = mapped.cast::().add(footprint.Offset as usize); + let pixels: [u8; 12] = std::slice::from_raw_parts(start, 12).try_into().unwrap(); + buffer.Unmap(0, None); + for (actual, expected) in pixels + .iter() + .zip([128, 0, 0, 255, 64, 128, 0, 255, 0, 0, 255, 255]) + { + assert!( + actual.abs_diff(expected) <= 1, + "unexpected composite {pixels:?}" + ); } - }); + eprintln!("D3D12 display-plane readback RGBA: {pixels:?}"); + } } - let pass = kept.as_mut()?.as_mut()?; - let (w, h) = (gd.Width, gd.Height); - if pass.out.as_ref().is_none_or(|o| (o.0, o.1) != (w, h)) { - let heap = D3D12_HEAP_PROPERTIES { - Type: D3D12_HEAP_TYPE_DEFAULT, - ..Default::default() - }; - let desc = D3D12_RESOURCE_DESC { - Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, - Width: w, - Height: h, - DepthOrArraySize: 1, - MipLevels: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - }; - let mut out: Option = None; - // SAFETY: plain creation of a device-local texture. - unsafe { - device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_SOURCE, None, &mut out) - .ok()?; - } - pass.out = Some((w, h, out?)); - } - let out = pass.out.as_ref()?.2.clone(); - let first = (pass.next % SLOTS) * 3; - pass.next = pass.next.wrapping_add(1); - let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: pass.cpu + ((first + i) * pass.step) as usize }; - let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: pass.gpu + u64::from(first * pass.step) }; - let srv = D3D12_SHADER_RESOURCE_VIEW_DESC { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, - Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_SRV { - MostDetailedMip: 0, - MipLevels: 1, - ..Default::default() - }, - }, - }; - let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT_R8G8B8A8_UNORM, - ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, - Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, - }, - }; - let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - let ui_state = D3D12_RESOURCE_STATES(ui_state as i32); - let t = crate::host::transition; - let mut before = vec![ - t(game, D3D12_RESOURCE_STATE_COPY_SOURCE, read), - t(&out, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - ]; - let mut after = vec![ - t(game, read, D3D12_RESOURCE_STATE_COPY_SOURCE), - t(&out, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - ]; - if ui_state != read { - before.push(t(ui, ui_state, read)); - after.push(t(ui, read, ui_state)); - } - let constants: [u32; 3] = [w as u32, h, u32::from(premultiplied())]; - // SAFETY: an open list (the present's); slots of our heap; live - // resources and objects (the pass's own live as long as the process, - // the texture is kept by the present's list). - unsafe { - device.CreateShaderResourceView(game, Some(&srv), cpu(0)); - device.CreateShaderResourceView(ui, Some(&srv), cpu(1)); - device.CreateUnorderedAccessView(&out, None::<&ID3D12Resource>, Some(&uav), cpu(2)); - list.ResourceBarrier(&before); - list.SetDescriptorHeaps(&[Some(pass.views.clone())]); - list.SetComputeRootSignature(&pass.root); - list.SetPipelineState(&pass.pso); - list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); - list.SetComputeRootDescriptorTable(1, gpu); - list.Dispatch((w as u32).div_ceil(8), h.div_ceil(8), 1); - list.ResourceBarrier(&after); - } - Some(out) } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index b6e8f9c..305145a 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -112,6 +112,8 @@ impl Made { } pub(crate) struct HostHeap { + pub(crate) buffer_sweep: Mutex, + pub(crate) buffer_frame: std::sync::atomic::AtomicU64, pub(crate) heap: ID3D12DescriptorHeap, cpu: usize, step: u32, @@ -424,6 +426,48 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option> = Mutex::new(Vec::new()); +/// Deferred slot flips recorded into an open or not-yet-submitted command +/// list (`HostHeap::flip`), tracked so a one-shot decoration bake draw can +/// promote them out of the `neutral()` gray stand-in before sampling them. +pub(crate) struct PendingListFlip { + id: u64, + pub(crate) origin: (usize, u64), + flip: Flip, +} + +impl PendingListFlip { + pub(crate) fn index(&self) -> u32 { + self.flip.index + } + + pub(crate) fn handle(&self) -> u64 { + self.flip.handle + } + + pub(crate) fn key(&self) -> u64 { + self.flip.key + } +} + +static NEXT_PENDING_FLIP: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); +static PENDING_LIST_FLIPS: Mutex> = Mutex::new(Vec::new()); +static PENDING_LIST_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +fn take_pending_list_flip(id: u64) -> Option { + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return None; + } + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + let pos = pending.iter().position(|p| p.id == id)?; + let entry = pending.swap_remove(pos); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + Some(entry.flip) +} + +fn remove_pending_list_flip(id: u64) { + let _ = take_pending_list_flip(id); +} + /// Makes the slots whose new texture's upload has run /// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at /// something else: the next texture pass does. @@ -712,6 +756,12 @@ impl Spans { /// pass last took the ranges ([`page_written`]). Kept apart from /// [`REMAPPED`] so that what such writes do is counted by itself. static PAGE_WRITTEN: Mutex> = Mutex::new(Vec::new()); +/// Physical-page writes retained specifically for one-shot decoration/ped +/// texture bakes when `VICTORY_PAGE_WRITES` bit 2 is off (the default): normal +/// frames stay free of queue flooding while every bake still sees freshly +/// DirectStorage-streamed texture bytes immediately instead of waiting on +/// `RECHECK_FRAMES`. +static BAKE_PAGE_WRITTEN: Mutex> = Mutex::new(Vec::new()); /// Since the start: such ranges kept for a pass; ranges dropped because no /// pass took them; slots of placed textures that held bytes of them when a @@ -1134,29 +1184,46 @@ pub(crate) fn device_removed() -> Option { pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -/// Bytes per element of a buffer view, as the console's descriptor holds -/// them for indexed reads (structured: the stride; raw: 1, the index is the -/// byte; typed: the format's); `None` if `view` is not a buffer view. -fn view_stride(view: &View) -> Option { - let (stride, raw, format) = view_elements(view)?; - Some(if stride > 0 { +/// Bytes per element and typed integer format bits of a buffer view, decoded +/// in a single pass over the view descriptor; `(None, 0)` if not a buffer view. +fn view_stride_and_kind(view: &View) -> (Option, u32) { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let Some((stride, raw, format)) = view_elements(view) else { + return (None, 0); + }; + let bytes = if stride > 0 { stride } else if raw { 1 } else { crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32) - }) + }; + let kind = if stride == 0 && !raw { + match format { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => VIEW_INTEGER, + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => VIEW_INTEGER | VIEW_SIGNED, + _ => 0, + } + } else { + 0 + }; + (Some(bytes), kind) } -/// What else the table of strides says of a typed buffer view of an integer -/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view. +/// Packed [`victory_shader::emit::SLOT_STRIDES`] word for `view`. +fn view_stride_word(view: &View) -> u32 { + let (stride, kind) = view_stride_and_kind(view); + stride.unwrap_or(0) | kind +} + +#[cfg(test)] +fn view_stride(view: &View) -> Option { + view_stride_and_kind(view).0 +} + +#[cfg(test)] fn view_kind(view: &View) -> u32 { - use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; - match view_elements(view) { - Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER, - Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED, - _ => 0, - } + view_stride_and_kind(view).1 } /// A buffer view's structure stride, whether it is raw, and its format; @@ -1568,6 +1635,8 @@ impl HostHeap { }) .flatten(); let h = HostHeap { + buffer_sweep: Mutex::default(), + buffer_frame: std::sync::atomic::AtomicU64::new(u64::MAX), heap, cpu, step, @@ -1675,10 +1744,16 @@ impl HostHeap { } /// A plain point sampler at `at`. +/// LOCAL (11/26, `VICTORY_NULL_SAMPLER_LINEAR=1`): a linear one instead. The +/// oil-painting look of some runs is posterization (colour bands), as from a +/// colour-grading LUT read with a point sampler: a sampler slot whose +/// description was missed at start would read as this one all run. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { let Some(host) = host() else { return }; + static LINEAR: std::sync::OnceLock = std::sync::OnceLock::new(); + let linear = *LINEAR.get_or_init(|| std::env::var_os("VICTORY_NULL_SAMPLER_LINEAR").is_some_and(|v| v == "1")); let desc = D3D12_SAMPLER_DESC { - Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + Filter: if linear { D3D12_FILTER_MIN_MAG_MIP_LINEAR } else { D3D12_FILTER_MIN_MAG_MIP_POINT }, AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, @@ -1780,7 +1855,7 @@ impl HostHeap { pub(crate) fn texture_news(&self) -> (u64, bool) { let writes = self.textures.lock().unwrap_or_else(|e| e.into_inner()).writes; let noted = |ranges: &Mutex>| !ranges.lock().unwrap_or_else(|e| e.into_inner()).is_empty(); - (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN)) + (writes, noted(&REMAPPED) || noted(&PAGE_WRITTEN) || noted(&BAKE_PAGE_WRITTEN)) } /// Every title slot of the queue that is due at `frame`, and whether @@ -1928,7 +2003,48 @@ impl HostHeap { if ranges.is_empty() { return 0; } - self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + let due = crate::watch::page_writes() & 2 != 0; + let made_due = self.slots_written_under(&ranges, frame, due)[2]; + if !due { + let mut kept = BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + kept.extend(ranges); + if kept.len() > 256 { + join(&mut kept); + const MOST: usize = 1 << 14; + if kept.len() > MOST { + let drop_n = kept.len() - MOST; + kept.drain(..drop_n); + } + } + } + made_due + } + + /// Wakes uploaded placed-texture slots touched by recent physical-page + /// writes (DirectStorage completions) immediately (`due = frame`) right + /// before a one-shot ped/decoration bake draw. + pub(crate) fn texture_slots_bake_written(&self, frame: u64) -> usize { + let mut ranges = std::mem::take(&mut *BAKE_PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + join(&mut ranges); + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + if slots.is_empty() { + return 0; + } + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + for &slot in &slots { + textures.changed(slot, frame, frame); + } + slots.len() } /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): @@ -2223,6 +2339,7 @@ impl HostHeap { /// reads the table's dynamic slots). pub(crate) fn mirror_after(&self, list: &crate::host::HostList, index: u32, handle: u64) { if show_after() + && !crate::texture::BAKING.get() && index < self.count && !self.texture_slot_made_from(index, handle) && let Some(view) = super::view(handle) @@ -2237,14 +2354,143 @@ impl HostHeap { } fn flip(&self, list: &crate::host::HostList, index: u32, handle: u64, late: Option) { + use std::sync::atomic::Ordering::{Relaxed, Release}; let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle)); + let id = NEXT_PENDING_FLIP.fetch_add(1, Relaxed); + let origin = (std::ptr::from_ref(list) as usize, list.epoch()); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(PendingListFlip { + id, + origin, + flip: Flip { after: 0, heap, index, handle, key, late }, + }); + PENDING_LIST_COUNT.store(pending.len(), Release); + } + struct PendingGuard(u64); + impl PendingGuard { + fn id(&self) -> u64 { + self.0 + } + } + impl Drop for PendingGuard { + fn drop(&mut self) { + remove_pending_list_flip(self.0); + } + } + let guard = PendingGuard(id); list.defer_host(move || { - let after = crate::host::submissions().0; - let flip = Flip { after, heap, index, handle, key, late }; + // Call a `&self` method so Rust 2021+ moves the whole `guard` + // into this closure rather than copying `guard.0` and dropping + // `guard` immediately at the end of `flip()`. + let Some(mut flip) = take_pending_list_flip(guard.id()) else { + return; + }; + flip.after = crate::host::submissions().0; FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip); }); } + /// Whether any deferred slot flip or view remake for this heap requires + /// settling in-flight GPU submissions before exposing real textures to a + /// one-shot decoration bake draw. + pub(crate) fn needs_gpu_settle_for_bake(&self) -> bool { + let own = std::ptr::from_ref(self) as usize; + let finished = crate::host::submissions().1; + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) > 0 { + let pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if pending.iter().any(|p| p.flip.heap == own) { + return true; + } + } + { + let flips = FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + if flips.iter().any(|f| f.heap == own && f.after > finished) { + return true; + } + } + let after = RESHOWN_AFTER.lock().unwrap_or_else(|e| e.into_inner()); + after.iter().any(|&(at, _)| at > finished) + } + + /// Drains deferred flips still sitting in unsubmitted command lists for + /// this heap so a decoration bake can mirror them out of `neutral()`. + /// Entries that cannot be promoted yet (unmapped memory or deferred + /// staging) must be returned via [`HostHeap::restore_pending_list_flip`]. + pub(crate) fn take_pending_list_flips(&self) -> Vec { + if PENDING_LIST_COUNT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return Vec::new(); + } + let own = std::ptr::from_ref(self) as usize; + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + let (mine, rest): (Vec, Vec) = + pending.drain(..).partition(|p| p.flip.heap == own); + *pending = rest; + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + mine + } + + /// Re-queues an unpromoted deferred flip drained by + /// [`HostHeap::take_pending_list_flips`] so its originating command list + /// still flips it out of `neutral()` once submitted. + pub(crate) fn restore_pending_list_flip(&self, item: PendingListFlip) { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(item); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + + /// Whether title descriptor slot `handle` still holds record `key`. + pub(crate) fn slot_still_at(&self, handle: u64, key: u64) -> bool { + key != 0 && record_key(handle) == key + } + + /// Looks up `(view, key)` for slot `index` prior to a synchronous bake + /// upload without replacing its current host descriptor with `neutral()`; + /// [`HostHeap::publish_uploaded_slot`] exposes the real descriptor and + /// updates `Spans`/stride tracking once the GPU copy finishes. + pub(crate) fn prepare_bake_slot(&self, index: u32, handle: u64) -> Option<(View, u64)> { + if index >= self.count { + return None; + } + let key = record_key(handle); + let view = (key != 0).then(|| view_at(key as u32, (key >> 32) as u32)).flatten()?; + Some((view, key)) + } + + /// Exposes the real host descriptor for slot `index` after its synchronous + /// bake upload has completed on the GPU, updating `Spans`/stride tracking + /// without re-queuing the slot in `TextureQueue`. + pub(crate) fn publish_uploaded_slot(&self, index: u32, handle: u64, key: u64) -> bool { + if index >= self.count || key == 0 { + return false; + } + let (published, stale) = { + let _made = self.made.lock(index); + if self.made.get(index) == Some(key) { + return false; + } + if record_key(handle) != key { + return false; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + return false; + }; + let stale = self.note_buffer(index, Some(&view), true); + if let Some(kept) = make(&view, self.at(index)) { + self.put(index); + self.quick_is(index, 0); + self.clear_twin(index); + self.made.set(index, key); + self.keep(index, kept); + (true, stale) + } else { + (false, stale) + } + }; + self.unmake_stale(index, stale); + published + } + /// Makes the slots whose new view's upload has run /// ([`HostHeap::texture_slot_flip`]); returns how many. pub(crate) fn texture_slots_flip(&self) -> usize { @@ -2262,6 +2508,7 @@ impl HostHeap { ready }; let mut flipped = 0; + let mut late_flipped = 0; for f in ready { let _made = self.made.lock(f.index); let Some(shown) = self.made.get(f.index) else { @@ -2304,6 +2551,7 @@ impl HostHeap { same_bytes(was, f.key); } if let Some(since) = f.late { + late_flipped += 1; let frames = crate::frame::current().saturating_sub(since); let n = LATE[0].fetch_add(1, Relaxed) + 1; let all = LATE[1].fetch_add(frames, Relaxed) + frames; @@ -2322,7 +2570,7 @@ impl HostHeap { } } FLIPPED[0].fetch_add(flipped as u64, Relaxed); - flipped + flipped + late_flipped } /// The memory of the texture title slot `index` views is there (again): @@ -2351,6 +2599,7 @@ impl HostHeap { } self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2546,24 +2795,17 @@ impl HostHeap { textures.remove(slot); } } - let stride = view.and_then(view_stride); - let kind = view.map_or(0, view_kind); - if let Some((_, _, data)) = &self.strides - && index < victory_shader::emit::SLOT_STRIDES_COUNT - { - // LOCAL (port of fxceless #1216): constant buffer views marked; - // programs read no other non-buffer slot as one. - let entry = match (stride, view) { - (Some(s), _) => s | kind, - (None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => { - victory_shader::emit::SLOT_STRIDE_CONSTANT - } - _ => kind, - }; - // SAFETY: inside the mapping; shaders read it while we write (a - // dword, either value is one the slot had). - unsafe { (*data as *mut u32).add(index as usize).write_volatile(entry) }; - } + let (stride, kind) = view.map_or((None, 0), view_stride_and_kind); + // LOCAL (port of fxceless #1216): constant buffer views marked; + // programs read no other non-buffer slot as one. + let entry = match (stride, view) { + (Some(s), _) => s | kind, + (None, Some(View::Constant(..))) if victory_shader::emit::constant_marks() => { + victory_shader::emit::SLOT_STRIDE_CONSTANT + } + _ => kind, + }; + self.write_stride(index, entry); let was = if stride.is_some() { self.buffers.put(index); true @@ -2576,6 +2818,20 @@ impl HostHeap { stale } + /// Writes `word` (stride | format kind) for view-heap slot `index` into + /// the host's [`victory_shader::emit::SLOT_STRIDES`] table. + #[inline] + fn write_stride(&self, index: u32, word: u32) { + if let Some((_, _, data)) = &self.strides + && index < victory_shader::emit::SLOT_STRIDES_COUNT + { + // SAFETY: inside the mapping; shaders read it while we write (a + // single aligned dword: either value is one the slot had, and + // dynamic slots are exclusively owned until submission finishes). + unsafe { (*data as *mut u32).add(index as usize).write_volatile(word) }; + } + } + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] /// returned). /// @@ -2603,6 +2859,7 @@ impl HostHeap { } self.put(index); self.twin_made(index, kept.is_some() && twinned(view)); + self.write_stride(index, if kept.is_some() { view_stride_word(view) } else { 0 }); self.keep(index, kept.flatten()); } @@ -2635,13 +2892,14 @@ impl HostHeap { } let twin = twinned(&view); let kept = make_twinned(&view, views.slot(at), Some(views.slot(at + 1)))?; + let stride_word = view_stride_word(&view); let listed = Listed { kind: crate::draw::view_kind(&view), texture: is_texture_view(&view), ready: (0, 0, false), tabled: None, }; - views.made.insert(words, ListView { view, at, twin, kept, listed }); + views.made.insert(words, ListView { view, at, twin, stride_word, kept, listed }); } let made = &views.made[&words]; self.copy_from(index, views.slot(made.at)); @@ -2651,6 +2909,7 @@ impl HostHeap { } else { self.clear_twin(index); } + self.write_stride(index, made.stride_word); self.keep(index, made.kept.clone()); Some(made.listed) }) @@ -2675,6 +2934,7 @@ impl HostHeap { } else { null_view(self.at(index)); self.put(index); + self.write_stride(index, 0); } self.clear_twin(index); self.keep(index, None); @@ -2761,6 +3021,7 @@ impl HostHeap { self.put(index); // (Bound by its handle, not read by index.) self.clear_twin(index); + self.write_stride(index, 1); self.keep(index, Some(buffer.clone())); } @@ -2770,6 +3031,7 @@ impl HostHeap { null_buffer_view(self.at(index)); self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2804,6 +3066,7 @@ impl HostHeap { }; self.put(index); self.clear_twin(index); + self.write_stride(index, 1); self.keep(index, Some(buffer.clone())); } @@ -2833,6 +3096,7 @@ impl HostHeap { }; self.put(index); self.clear_twin(index); + self.write_stride(index, 0); self.keep(index, None); } @@ -2890,6 +3154,7 @@ impl HostHeap { unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) }; } self.twin_made(index, twin.is_some()); + self.write_stride(index, 0); // After the descriptor: what it showed is let go when nothing shows // it any more. self.keep(index, holds.then(|| buffer.clone())); @@ -4203,24 +4468,27 @@ fn make_twinned( } const BUFFER: u32 = 1; if resource[0] != BUFFER { - // shortcut: unordered access to a texture the title placed - // itself is not mirrored; give it a resource as shader - // views of such textures get when a dispatch writes one. - // Each texture is said once (the first 64), with how many times - // such a view was asked for so far: what shaders write through - // them is lost. - static SAID: Mutex> = Mutex::new(std::collections::BTreeSet::new()); - static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; let at = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); - if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { - tracing::warn!( - address = format_args!("{at:#x}"), - times, - "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}", - &desc[..10] - ); + if *unordered || at != 0 { + // shortcut: unordered access to a texture the title placed + // itself is not mirrored; give it a resource as shader + // views of such textures get when a dispatch writes one. + // Each texture is said once (the first 64), with how many times + // such a view was asked for so far: what shaders write through + // them is lost. + static SAID: Mutex> = Mutex::new(std::collections::BTreeSet::new()); + static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() { + tracing::warn!( + address = format_args!("{at:#x}"), + unordered = *unordered, + times, + "placed texture view not mirrored (null): resource {resource:?}, view {:?}", + &desc[..10] + ); + } } return None; } @@ -5827,6 +6095,71 @@ void BY_FLOATS_OR_NOT(uint3 id : SV_DispatchThreadID) { heap.release(last, 1); assert_eq!(heap.dynamic(2), None); } + + #[test] + fn dynamic_slots_populate_and_clear_stride_table() { + use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED}; + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let Some((_, _, data)) = heap.strides else { + panic!("view heap should allocate strides table"); + }; + let read_stride = |slot: u32| -> u32 { + // SAFETY: inside `SLOT_STRIDES_COUNT` mapping of `heap.strides`. + unsafe { *(data as *const u32).add(slot as usize) } + }; + let memory = vec![0u64; 1 << 11]; + let addr = (memory.as_ptr() as u64).next_multiple_of(4096); + let placed_typed = |uav: bool, dxgi_fmt: u32, elems: u32| { + let resource: [u32; 14] = [1, 0, 0, 0, 4096, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0]; + let mut desc = [0u32; 16]; + // [format, dim=1 (buffer), mapping/pad, ..., num_elements @6, stride @7, flags @8] + let words = if uav { + [dxgi_fmt, 1, 0, 0, elems, 0, 0, 0, 0, 0] + } else { + [dxgi_fmt, 1, 5768, 0, 0, 0, elems, 0, 0, 0] + }; + desc[..10].copy_from_slice(&words); + (desc[10], desc[11]) = (addr as u32, (addr >> 32) as u32); + View::Placed(uav, resource, desc) + }; + + let s0 = heap.dynamic(4).unwrap(); + // R16G16B16A16_UINT (12): 8 bytes + VIEW_INTEGER + let u16x4 = placed_typed(true, 12, 64); + heap.make_at(s0, &u16x4); + assert_eq!(read_stride(s0), 8 | VIEW_INTEGER); + + // R16_SINT (59): 2 bytes + VIEW_INTEGER | VIEW_SIGNED + let s16 = placed_typed(false, 59, 64); + heap.make_at(s0 + 1, &s16); + assert_eq!(read_stride(s0 + 1), 2 | VIEW_INTEGER | VIEW_SIGNED); + + // R16G16B16A16_FLOAT (10): 8 bytes, no integer bits + let f16x4 = placed_typed(true, 10, 64); + heap.make_at(s0 + 2, &f16x4); + assert_eq!(read_stride(s0 + 2), 8); + + // Clearing / nulling / raw views overwrite stale bits cleanly. + heap.make_null(s0); + assert_eq!(read_stride(s0), 0); + heap.null_raw_at(s0 + 1); + assert_eq!(read_stride(s0 + 1), 0); + heap.null_raw_uav_at(s0 + 2); + assert_eq!(read_stride(s0 + 2), 0); + + // `make_listed` (both cold creation and cached copy hit) must populate strides. + let mut slot_mem = [0u32; 8]; + crate::descriptor::record(slot_mem.as_mut_ptr() as u64, u16x4); + let rec = [slot_mem[0], slot_mem[1], slot_mem[2]]; + assert!(heap.make_listed(0x1234, rec, s0).is_some()); + assert_eq!(read_stride(s0), 8 | VIEW_INTEGER); + heap.make_null(s0 + 3); + assert_eq!(read_stride(s0 + 3), 0); + assert!(heap.make_listed(0x1234, rec, s0 + 3).is_some()); + assert_eq!(read_stride(s0 + 3), 8 | VIEW_INTEGER); + } } /// What is known of a record a list's tables hold, in that recording of the @@ -5847,6 +6180,7 @@ struct ListView { /// Its descriptor's slot in [`ListViews`]; its raw twin's is the next. at: u32, twin: bool, + stride_word: u32, kept: Kept, listed: Listed, } @@ -5925,3 +6259,74 @@ pub(crate) fn note_listed(recording: u64, words: [u32; 3], listed: Listed) { pub(crate) fn list_views() -> bool { crate::toggled!("VICTORY_LIST_VIEWS") } + +#[cfg(test)] +mod bake_flip_tests { + use super::*; + + #[test] + fn pending_list_flips_promote_once_and_clean_up() { + let heap = 0xdead_beefusize; + let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + pending.push(PendingListFlip { + id: id1, + origin: (1, 1), + flip: Flip { after: 0, heap, index: 7, handle: 0, key: 11, late: Some(1) }, + }); + pending.push(PendingListFlip { + id: id2, + origin: (2, 1), + flip: Flip { after: 0, heap, index: 8, handle: 0, key: 12, late: Some(1) }, + }); + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + let taken = take_pending_list_flip(id1).expect("id1 should be present"); + assert_eq!(taken.index, 7); + assert!(take_pending_list_flip(id1).is_none(), "second take must be a no-op"); + remove_pending_list_flip(id2); + assert!(take_pending_list_flip(id2).is_none(), "removed entry must be gone"); + } + + #[test] + fn deferred_flip_closure_keeps_pending_entry_alive_until_called_or_dropped() { + let heap = 0xcafe_babeusize; + let id1 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let id2 = NEXT_PENDING_FLIP.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + { + let mut pending = PENDING_LIST_FLIPS.lock().unwrap_or_else(|e| e.into_inner()); + for (id, idx) in [(id1, 10), (id2, 11)] { + pending.push(PendingListFlip { + id, + origin: (3, 1), + flip: Flip { after: 0, heap, index: idx, handle: 0, key: 20, late: Some(1) }, + }); + } + PENDING_LIST_COUNT.store(pending.len(), std::sync::atomic::Ordering::Release); + } + struct TestGuard(u64); + impl TestGuard { + fn id(&self) -> u64 { + self.0 + } + } + impl Drop for TestGuard { + fn drop(&mut self) { + remove_pending_list_flip(self.0); + } + } + let make_cb = |id: u64| -> Box Option + Send + 'static> { + let guard = TestGuard(id); + Box::new(move || take_pending_list_flip(guard.id()).map(|f| f.index)) + }; + let cb1 = make_cb(id1); + let cb2 = make_cb(id2); + // Must still be present after make_cb returns (guard moved, not dropped). + assert_eq!(cb1(), Some(10)); + assert_eq!(cb1(), None); + drop(cb2); + assert!(take_pending_list_flip(id2).is_none(), "dropping uncalled closure cleans up entry"); + } +} diff --git a/crates/victory-gpu/src/dlss.rs b/crates/victory-gpu/src/dlss.rs new file mode 100644 index 0000000..3133846 --- /dev/null +++ b/crates/victory-gpu/src/dlss.rs @@ -0,0 +1,318 @@ +//! NVIDIA DLSS in place of the title's FidelityFX upscale (Series S, +//! `VICTORY_UPSCALE=dlss`, builds with the `dlss` feature). +//! +//! The title renders below its output size and asks its upscaler to make the +//! output from the colour, depth and motion vectors it rendered, with the +//! camera's jitter: what DLSS takes as well. The title's own FidelityFX passes +//! are slow translated for 32-lane cards (about 150 ms of card time a frame on +//! an RTX 3070 Ti); DLSS runs on the card's tensor cores in a millisecond or +//! two. +//! +//! The SDK (NVIDIA/DLSS on GitHub: `include`, `lib/Windows_x86_64`) is not part +//! of this repository: the build links `nvsdk_ngx_d.lib` from +//! `VICTORY_DLSS_SDK`, and `nvngx_dlss.dll` is looked for in `VICTORY_DLSS_DIR` +//! (else beside the executable). Any failure leaves the caller to stretch. +//! +//! Switches: `VICTORY_DLSS_QUALITY` (0 performance .. 2 quality, 5 DLAA; 2 by +//! default), `VICTORY_DLSS_MV_SIGN=-1` (motion vectors the other way), +//! `VICTORY_DLSS_JITTER_SIGN=-1`, `VICTORY_DLSS_HDR=0|1` (default: by the colour +//! format), `VICTORY_DLSS_DEPTH_INVERTED=0|1` (default: by near > far), +//! `VICTORY_DLSS_SHARPNESS=<0..1>`. + +use std::ffi::{CString, c_char, c_int, c_uint, c_void}; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::Interface; + +type Result = c_int; +const SUCCESS: Result = 1; +const FEATURE_SUPER_SAMPLING: c_int = 1; +const ENGINE_CUSTOM: c_int = 0; +const VERSION_API: c_int = 0x15; + +const FLAG_HDR: c_int = 1 << 0; +const FLAG_MV_LOW_RES: c_int = 1 << 1; +const FLAG_MV_JITTERED: c_int = 1 << 2; +const FLAG_DEPTH_INVERTED: c_int = 1 << 3; +const FLAG_AUTO_EXPOSURE: c_int = 1 << 6; + +#[repr(C)] +struct PathList { + path: *const *const u16, + length: c_uint, +} + +#[repr(C)] +struct Logging { + callback: *const c_void, + minimum: c_int, + disable_other_sinks: bool, +} + +#[repr(C)] +struct CommonInfo { + paths: PathList, + internal: *const c_void, + logging: Logging, +} + +#[link(name = "nvsdk_ngx_d", kind = "static")] +unsafe extern "C" { + fn NVSDK_NGX_D3D12_Init_with_ProjectID( + project: *const c_char, + engine: c_int, + engine_version: *const c_char, + data_path: *const u16, + device: *mut c_void, + info: *const CommonInfo, + version: c_int, + ) -> Result; + fn NVSDK_NGX_D3D12_GetCapabilityParameters(out: *mut *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_CreateFeature(list: *mut c_void, feature: c_int, params: *mut c_void, out: *mut *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_ReleaseFeature(handle: *mut c_void) -> Result; + fn NVSDK_NGX_D3D12_EvaluateFeature_C(list: *mut c_void, handle: *const c_void, params: *const c_void, callback: *const c_void) -> Result; + fn NVSDK_NGX_Parameter_SetUI(p: *mut c_void, name: *const c_char, value: c_uint); + fn NVSDK_NGX_Parameter_SetI(p: *mut c_void, name: *const c_char, value: c_int); + fn NVSDK_NGX_Parameter_SetF(p: *mut c_void, name: *const c_char, value: f32); + fn NVSDK_NGX_Parameter_SetD3d12Resource(p: *mut c_void, name: *const c_char, value: *mut c_void); + fn NVSDK_NGX_Parameter_GetI(p: *mut c_void, name: *const c_char, out: *mut c_int) -> Result; +} + +/// A parameter name as the SDK spells it. +macro_rules! name { + ($s:literal) => { + concat!($s, "\0").as_ptr().cast::() + }; +} + +/// What the title gives an upscale, as the host's resources. +pub(crate) struct Inputs<'a> { + pub colour: &'a ID3D12Resource, + pub depth: Option<&'a ID3D12Resource>, + pub motion: Option<&'a ID3D12Resource>, + pub exposure: Option<&'a ID3D12Resource>, + pub output: &'a ID3D12Resource, + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub render: [u32; 2], + pub reset: bool, + pub pre_exposure: f32, + pub near: f32, + pub far: f32, + pub frame_ms: f32, +} + +struct Feature { + handle: *mut c_void, + /// render width and height the feature was made for, output size, flags + key: [u32; 5], +} + +struct Dlss { + params: *mut c_void, + feature: Option, +} + +// SAFETY: the SDK's objects are used under the mutex only. +unsafe impl Send for Dlss {} + +/// `None` until tried; `Some(None)`: unavailable, never tried again. +static DLSS: Mutex>> = Mutex::new(None); + +fn env_f(name: &str, default: f32) -> f32 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn env_flag(name: &str) -> Option { + std::env::var(name).ok().map(|v| v.trim() == "1") +} + +fn wide(s: &std::ffi::OsStr) -> Vec { + use std::os::windows::ffi::OsStrExt; + s.encode_wide().chain([0]).collect() +} + +fn init(device: &ID3D12Device) -> Option { + let dir = std::env::var_os("VICTORY_DLSS_DIR") + .map(std::path::PathBuf::from) + .or_else(|| std::env::current_exe().ok()?.parent().map(|p| p.to_path_buf()))?; + let data = std::env::temp_dir().join("victory-ngx"); + let _ = std::fs::create_dir_all(&data); + let dir_w = wide(dir.as_os_str()); + let data_w = wide(data.as_os_str()); + let paths = [dir_w.as_ptr()]; + let info = CommonInfo { + paths: PathList { path: paths.as_ptr(), length: 1 }, + internal: std::ptr::null(), + logging: Logging { callback: std::ptr::null(), minimum: 0, disable_other_sinks: false }, + }; + let project = CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").ok()?; + let version = CString::new("1.0").ok()?; + // SAFETY: live strings and device; the SDK copies what it keeps. + let r = unsafe { + NVSDK_NGX_D3D12_Init_with_ProjectID( + project.as_ptr(), + ENGINE_CUSTOM, + version.as_ptr(), + data_w.as_ptr(), + device.as_raw(), + &info, + VERSION_API, + ) + }; + if r != SUCCESS { + tracing::warn!(result = format_args!("{r:#x}"), dir = %dir.display(), "DLSS: the SDK did not start; the upscale stays a stretch"); + return None; + } + let mut params = std::ptr::null_mut(); + // SAFETY: an out pointer. + let r = unsafe { NVSDK_NGX_D3D12_GetCapabilityParameters(&mut params) }; + if r != SUCCESS || params.is_null() { + tracing::warn!(result = format_args!("{r:#x}"), "DLSS: no capability parameters"); + return None; + } + let mut available = 0; + // SAFETY: live parameters. + unsafe { NVSDK_NGX_Parameter_GetI(params, name!("SuperSampling.Available"), &mut available) }; + if available == 0 { + tracing::warn!("DLSS: super sampling is not available on this card or driver"); + return None; + } + tracing::info!(dir = %dir.display(), "DLSS: started; the title's upscale is DLSS (VICTORY_UPSCALE=dlss)"); + Some(Dlss { params, feature: None }) +} + +/// Records DLSS over `inputs` into `list`; false if it could not (the caller +/// stretches instead). The list's descriptor heaps and root state are the +/// SDK's afterwards: the caller replays the title's. +pub(crate) fn record(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, inputs: &Inputs<'_>) -> bool { + let mut guard = DLSS.lock().unwrap_or_else(|e| e.into_inner()); + let dlss = match guard.get_or_insert_with(|| init(device)) { + Some(d) => d, + None => return false, + }; + // SAFETY: live resources. + let (out, colour) = unsafe { (inputs.output.GetDesc(), inputs.colour.GetDesc()) }; + let render = [ + if inputs.render[0] == 0 { colour.Width as u32 } else { inputs.render[0] }, + if inputs.render[1] == 0 { colour.Height } else { inputs.render[1] }, + ]; + // The feature's input size is the largest the colour texture holds, so + // that a dynamic render size inside it needs no new feature. + let (in_w, in_h) = (colour.Width as u32, colour.Height); + let hdr = env_flag("VICTORY_DLSS_HDR").unwrap_or(matches!(colour.Format.0, 2 | 10 | 26 | 24 | 9)); + let inverted = env_flag("VICTORY_DLSS_DEPTH_INVERTED").unwrap_or(inputs.near > inputs.far); + let mut flags = FLAG_MV_LOW_RES | FLAG_MV_JITTERED; + if hdr { + flags |= FLAG_HDR; + } + if inverted { + flags |= FLAG_DEPTH_INVERTED; + } + if inputs.exposure.is_none() { + flags |= FLAG_AUTO_EXPOSURE; + } + let key = [in_w, in_h, out.Width as u32, out.Height, flags as u32]; + let p = dlss.params; + if dlss.feature.as_ref().is_none_or(|f| f.key != key) { + if let Some(old) = dlss.feature.take() { + // SAFETY: a handle the SDK made. + unsafe { NVSDK_NGX_D3D12_ReleaseFeature(old.handle) }; + } + let quality = env_f("VICTORY_DLSS_QUALITY", 2.0) as c_int; + let mut handle = std::ptr::null_mut(); + // SAFETY: live parameters and an open list. + let r = unsafe { + NVSDK_NGX_Parameter_SetUI(p, name!("CreationNodeMask"), 1); + NVSDK_NGX_Parameter_SetUI(p, name!("VisibilityNodeMask"), 1); + NVSDK_NGX_Parameter_SetUI(p, name!("Width"), in_w); + NVSDK_NGX_Parameter_SetUI(p, name!("Height"), in_h); + NVSDK_NGX_Parameter_SetUI(p, name!("OutWidth"), out.Width as u32); + NVSDK_NGX_Parameter_SetUI(p, name!("OutHeight"), out.Height); + NVSDK_NGX_Parameter_SetI(p, name!("PerfQualityValue"), quality); + NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Feature.Create.Flags"), flags); + NVSDK_NGX_Parameter_SetI(p, name!("DLSS.Enable.Output.Subrects"), 0); + // LOCAL (11/26): `VICTORY_DLSS_PRESET=J|K|L|M`: the model, for every mode (unset: + // the DLL's default; 310.9.16 uses K, the DLSS 4 transformer model, for Quality). + let preset: c_uint = match std::env::var("VICTORY_DLSS_PRESET").as_deref().map(str::trim) { + Ok("J") => 10, + Ok("K") => 11, + Ok("L") => 12, + Ok("M") => 13, + _ => 0, + }; + if preset != 0 { + for mode in [ + name!("DLSS.Hint.Render.Preset.DLAA"), + name!("DLSS.Hint.Render.Preset.Quality"), + name!("DLSS.Hint.Render.Preset.Balanced"), + name!("DLSS.Hint.Render.Preset.Performance"), + name!("DLSS.Hint.Render.Preset.UltraPerformance"), + name!("DLSS.Hint.Render.Preset.UltraQuality"), + ] { + NVSDK_NGX_Parameter_SetUI(p, mode, preset); + } + } + NVSDK_NGX_D3D12_CreateFeature(list.as_raw(), FEATURE_SUPER_SAMPLING, p, &mut handle) + }; + if r != SUCCESS || handle.is_null() { + tracing::warn!(result = format_args!("{r:#x}"), ?key, "DLSS: no feature for these sizes; the upscale stays a stretch"); + *guard = Some(None); + return false; + } + tracing::info!( + input = ?(in_w, in_h), + output = ?(out.Width, out.Height), + hdr, + depth_inverted = inverted, + auto_exposure = inputs.exposure.is_none(), + quality, + colour_format = colour.Format.0, + "DLSS: feature made" + ); + dlss.feature = Some(Feature { handle, key }); + } + let Some(feature) = dlss.feature.as_ref() else { return false }; + let mv = env_f("VICTORY_DLSS_MV_SIGN", 1.0); + let jit = env_f("VICTORY_DLSS_JITTER_SIGN", 1.0); + let raw = |r: Option<&ID3D12Resource>| r.map_or(std::ptr::null_mut(), |r| r.as_raw()); + let scale = |s: f32| if s == 0.0 { 1.0 } else { s }; + // SAFETY: live parameters, resources and feature; an open list. + let r = unsafe { + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Color"), inputs.colour.as_raw()); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Output"), inputs.output.as_raw()); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("Depth"), raw(inputs.depth)); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("MotionVectors"), raw(inputs.motion)); + NVSDK_NGX_Parameter_SetD3d12Resource(p, name!("ExposureTexture"), raw(inputs.exposure)); + NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.X"), jit * inputs.jitter[0]); + NVSDK_NGX_Parameter_SetF(p, name!("Jitter.Offset.Y"), jit * inputs.jitter[1]); + NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.X"), mv * scale(inputs.motion_scale[0])); + NVSDK_NGX_Parameter_SetF(p, name!("MV.Scale.Y"), mv * scale(inputs.motion_scale[1])); + NVSDK_NGX_Parameter_SetI(p, name!("Reset"), inputs.reset as c_int); + NVSDK_NGX_Parameter_SetF(p, name!("Sharpness"), env_f("VICTORY_DLSS_SHARPNESS", 0.0)); + NVSDK_NGX_Parameter_SetF(p, name!("DLSS.Pre.Exposure"), if inputs.pre_exposure > 0.0 { inputs.pre_exposure } else { 1.0 }); + NVSDK_NGX_Parameter_SetF(p, name!("FrameTimeDeltaInMsec"), inputs.frame_ms); + NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Width"), render[0].min(in_w)); + NVSDK_NGX_Parameter_SetUI(p, name!("DLSS.Render.Subrect.Dimensions.Height"), render[1].min(in_h)); + NVSDK_NGX_D3D12_EvaluateFeature_C(list.as_raw(), feature.handle, p, std::ptr::null()) + }; + if r != SUCCESS { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| tracing::warn!(result = format_args!("{r:#x}"), "DLSS: an evaluation failed; that upscale is a stretch")); + return false; + } + // LOCAL (11/26): DLSS Frame Generation's inputs (`VICTORY_FRAME_GEN`), in the state the + // upscale read them in. + if crate::fg::active() { + crate::fg::tag( + [render[0].min(in_w), render[1].min(in_h)], + [jit * inputs.jitter[0], jit * inputs.jitter[1]], + [mv * scale(inputs.motion_scale[0]), mv * scale(inputs.motion_scale[1])], + inputs.near, + inputs.far, + inputs.reset, + ); + } + true +} diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 567e472..c97e032 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -24,6 +24,94 @@ use crate::host::HostList; use crate::object::This; use crate::pipeline::host::HostPipeline; +/// Shader interface metadata shared by every pipeline variant and draw. +pub(crate) struct TablePlan { + groups: Vec, + // Direct entries can interleave slots. Preserve their declaration order + // when recording resource reads, writes, and transitions. + direct: Vec<(usize, usize)>, +} + +struct TableGroup { + slot: u8, + has_cbv: bool, + has_uav: bool, + max_dword: u32, + entries: Vec, + indexed: Vec, + // Descriptor number -> first declaration, matching the bind-time search. + by_descriptor: Vec<(u32, usize)>, +} + +impl TablePlan { + pub(crate) fn new(used: &[UsedResource], indexed: &[RootIndexedView]) -> Self { + let mut slots: Vec<_> = used + .iter() + .filter(|u| u.root == RootType::Table) + .map(|u| u.slot) + .collect(); + slots.sort_unstable(); + slots.dedup(); + let mut groups: Vec<_> = slots + .iter() + .map(|&slot| TableGroup { + slot, + has_cbv: false, + has_uav: false, + max_dword: 0, + entries: Vec::new(), + by_descriptor: Vec::new(), + indexed: indexed.iter().filter(|v| v.table_slot == slot).copied().collect(), + }) + .collect(); + let mut direct = Vec::new(); + for &u in used.iter().filter(|u| u.root == RootType::Table) { + let i = slots + .binary_search(&u.slot) + .expect("table slot collected from these declarations"); + let group = &mut groups[i]; + group.has_cbv |= u.kind == ResourceType::Cbv; + group.has_uav |= u.kind == ResourceType::Uav; + group.max_dword = group.max_dword.max(u.table_offset_dwords); + direct.push((i, group.entries.len())); + group + .by_descriptor + .push((u.table_offset_dwords / 8, group.entries.len())); + group.entries.push(u); + } + for group in &mut groups { + group.by_descriptor.sort_unstable(); + group.by_descriptor.dedup_by_key(|item| item.0); + } + Self { groups, direct } + } +} + +impl TableGroup { + fn entry(&self, descriptor: u32) -> Option<&UsedResource> { + let i = self + .by_descriptor + .binary_search_by_key(&descriptor, |item| item.0) + .ok()?; + Some(&self.entries[self.by_descriptor[i].1]) + } + + fn needs_snapshot(&self, heap: &crate::descriptor::Heap, host_count: u32, table: u64) -> bool { + let index_at = |dword: u32| { + table + .checked_add(u64::from(dword) * 4) + .and_then(|end| heap.index(end)) + }; + match index_at(self.max_dword) { + Some(i) => i >= host_count, + None => self + .entries + .iter() + .any(|u| index_at(u.table_offset_dwords).is_some_and(|i| i >= host_count)), + } + } +} + /// A root argument as the title set it. #[derive(Debug, Clone, Default)] enum Root { @@ -69,7 +157,7 @@ thread_local! { /// While `State::early_textures` runs the texture pass: the /// milliseconds and the bytes that run may take, in place of the /// pass's own per frame. - static PASS_BUDGET: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static PASS_BUDGET: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// The milliseconds of every frame the pass that uploads textures picked @@ -129,12 +217,45 @@ const BAKE_AHEAD: [u64; 2] = [12, 2]; /// until something is new, the next bakes of the frame need no pass. static BAKE_SERVED: AtomicU64 = AtomicU64::new(0); +/// Free-threaded wrapper around a reusable upload-only [`HostList`] protected +/// by [`BAKE_UPLOAD`]. D3D12 command allocators, lists, and retained COM +/// resources are free-threaded when externally synchronized. +struct BakeList(HostList); +// SAFETY: accessed exclusively under `BAKE_UPLOAD`'s mutex. +unsafe impl Send for BakeList {} + +/// Serializes synchronous one-shot ped/decoration bake uploads across +/// concurrent `VICTORY_THIN=1` recording threads and owns the reusable +/// upload-only host command list. +static BAKE_UPLOAD: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Pending descriptor publications for a synchronous bake upload pass: slots +/// stay on `neutral()` (or their previous compatible view) until the dedicated +/// upload list has finished executing on the host GPU. +struct BakeSync { + publish: Vec<(u32, u64, u64)>, + keep: Vec>, +} + /// The pixel shaders of the title's decoration bake (the title: /// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the /// frame listings print it. They draw into a 256x256 corner of 2048x2048 /// targets and name no texture in a table. -const BAKE_PIXEL_SHADERS: [&str; 4] = - ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; +pub(crate) const BAKE_PIXEL_SHADERS: [&str; 7] = [ + "c0a7fe77b1862e10", + "0d1575a396dfe513", + "b7cfd8dda91ebb6b", + "280967ad158cee0b", + "fa455c8a3c32577b", + "d126bcae5d5d8d26", + "fcee612943c008e0", +]; + +/// Geometry stages shared by every ped texture compositor / decoration bake +/// permutation (`vertex 089d6271be6650ef` fullscreen-triangle ped baker and +/// `mesh d4111a6e6ea49d91` decoration projection mesh), catching pixel-shader +/// permutations beyond `BAKE_PIXEL_SHADERS`. +const BAKE_GEOMETRY_SHADERS: [&str; 2] = ["089d6271be6650ef", "d4111a6e6ea49d91"]; /// Since the start: early runs of the texture pass, and those of them /// made for a bake draw. @@ -338,6 +459,7 @@ pub(crate) struct State { /// Graphics, compute. host_roots: [usize; 2], host_heaps: [usize; 2], + host_heaps_set: bool, /// Tables made afresh in this list: (table, slot count, contents) → first /// dynamic slot. fresh_tables: std::collections::HashMap<(u64, u32, u64), FreshTable, std::hash::BuildHasherDefault>, @@ -515,6 +637,20 @@ fn heap_spread() -> bool { #[derive(Default)] struct HeapRanges(Vec>); +/// Descriptor-derived references belong to the heap that produced them. +pub(crate) struct BufferSweep { + passes: u64, + ranges: HeapRanges>, + // Last refresh frame and covered interval for throttled, unwatched copies. + unwatched: std::collections::HashMap, +} + +impl Default for BufferSweep { + fn default() -> Self { + Self { passes: 0, ranges: HeapRanges(Vec::new()), unwatched: Default::default() } + } +} + impl HeapRanges { fn set(&mut self, slot: u32, range: Option<(T, u64, u64)>) { let slot = slot as usize; @@ -655,6 +791,16 @@ fn reupload_when_full() -> bool { /// Whether textures picked by index are looked at again after their upload /// (`VICTORY_HEAP_RECHECK=0`: no). +/// LOCAL (11/26): `VICTORY_HEAP_RECHECK_EVERY=`: textures picked by index are looked at +/// again that often after the usual looks (`RECHECK_FRAMES`), all run; 0 or unset: not. +fn heap_recheck_every() -> u64 { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| std::env::var("VICTORY_HEAP_RECHECK_EVERY").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// LOCAL (11/26): changes found by those later looks, since the start. +pub(crate) static HEAP_TEXTURES_LATE: AtomicU64 = AtomicU64::new(0); + fn heap_recheck() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0")) @@ -754,14 +900,8 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = HeapRanges>; - static RANGES: std::sync::Mutex>> = - std::sync::Mutex::new(None); - let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); - let (passes, ranges) = kept - .get_or_insert_with(Default::default) - .entry(std::ptr::from_ref(host) as usize) - .or_insert_with(|| (0, HeapRanges(Vec::new()))); + let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner()); + let BufferSweep { passes, ranges, unwatched } = &mut *kept; let changed = host.buffer_changes(); let all = *passes == 0 || (*passes % HEAP_ROUND == 0 && !heap_spread()); let slots = if all { @@ -857,7 +997,6 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho span.1 = span.1.min(*from); span.2 = span.2.max(*to); } - drop(kept); let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); // Memory that is not write-watched is copied whole by every refresh. // It was once refreshed only every 120 frames (unmapped pages read @@ -866,32 +1005,27 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho // the garbage ended runs (the card stopped answering 14-90 frames // into the opening cutscene; with every frame it ran on). The pass // costs some 30 ms a frame this way. - static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); - let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let whole = whole.get_or_insert_with(Default::default); + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("VICTORY_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1) + }); let mut found = Vec::with_capacity(spans.len()); + let mut next_unwatched = std::collections::HashMap::new(); for (shadow, from, to) in spans.values() { - if shadow.unwatched() { - // By the copy's number: a copy made where one let go was - // (`shadow::let_go_idle`) has never been refreshed. - let key = shadow.id() as usize; - // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame). - static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); - let every = *EVERY.get_or_init(|| { - std::env::var("VICTORY_UNWATCHED_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(1) - }); - match whole.get(&key) { - Some(&last) if frame < last + every => continue, - _ => { - whole.insert(key, frame); - } + if every > 1 && shadow.unwatched() { + let id = shadow.id(); + if let Some(&(last, low, high)) = unwatched.get(&id) + && frame >= last && frame - last < every && low <= *from && *to <= high + { + next_unwatched.insert(id, (last, low, high)); + continue; } + next_unwatched.insert(id, (frame, *from, *to)); } found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from)))); } + *unwatched = next_unwatched; + drop(kept); #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); crate::watch::look_at_holes(); @@ -1157,6 +1291,7 @@ impl State { self.host_pipeline = 0; self.host_roots = [0; 2]; self.host_heaps = [0; 2]; + self.host_heaps_set = false; if self.topology_set { self.set_topology(list, self.topology); } @@ -1457,19 +1592,44 @@ impl State { self.heaps[0] = heap; } // Heaps first: a root signature with directly indexed heaps must be - // set after them. - if self.host_heaps != self.heaps { - let heaps: Vec> = self - .heaps - .iter() - .filter(|&&h| h != 0) - .filter_map(|&h| crate::descriptor::heap(h as This).host()) - .map(|h| Some(h.heap.clone())) - .collect(); - heaps.iter().flatten().for_each(|h| list.keep(h)); - // SAFETY: an open list and shader-visible heaps. - unsafe { l.SetDescriptorHeaps(&heaps) }; + // set after them, with both a view heap and a sampler heap bound. + if !self.host_heaps_set || self.host_heaps != self.heaps { + let mut view_heap: Option = None; + let mut sampler_heap: Option = None; + for &h in &self.heaps { + if h == 0 { + continue; + } + let title_heap = crate::descriptor::heap(h as This); + if let Some(host_heap) = title_heap.host() { + if title_heap.samplers() { + sampler_heap = Some(host_heap.heap.clone()); + } else { + view_heap = Some(host_heap.heap.clone()); + } + } + } + if view_heap.is_none() { + view_heap = crate::host::host().and_then(|h| h.fallback_view_heap().cloned()); + } + if sampler_heap.is_none() { + sampler_heap = crate::host::host().and_then(|h| h.fallback_sampler_heap().cloned()); + } + let mut heaps: Vec> = Vec::with_capacity(2); + if let Some(h) = view_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if let Some(h) = sampler_heap { + list.keep(&h); + heaps.push(Some(h)); + } + if !heaps.is_empty() { + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + } self.host_heaps = self.heaps; + self.host_heaps_set = true; self.host_roots = [0; 2]; } // The depth target a draw only tests, for the views of it that the @@ -1507,13 +1667,7 @@ impl State { if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) { crate::picked::runs_in(list); } - let made = self.tables( - list, - &t.used, - &t.host.root_indexed_views, - &t.host.half_views, - compute, - ); + let made = self.tables(list, &t.tables, &t.host.half_views, compute); STORES.set(true); if made.iter().any(|m| m.1 == u32::MAX) { once!("a draw whose descriptor table found no free slots is dropped"); @@ -1617,6 +1771,24 @@ impl State { } continue; } + if srv && slot == victory_shader::emit::SLOT_TABLE_STRIDES { + // Ours: the shader inspects typed view kinds for its + // descriptor tables only (already mirrored by `tables`), + // so bind the strides buffer without sweeping the heap. + match self.heap_strides(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader inspects table view kinds without a view heap set"), + } + continue; + } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { @@ -1775,7 +1947,10 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| find(a).map(|s| (a, s))); - let Some(index) = host.dynamic(1) else { + let Some(index) = host.dynamic(1).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { return false; }; self.dynamic.push((key.0, index, 1)); @@ -1846,7 +2021,10 @@ impl State { Some((index, shadow)) => (*index, address.zip(shadow.clone())), None => { let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); - let Some(index) = host.dynamic(1) else { + let Some(index) = host.dynamic(1).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(1) + }) else { return false; }; self.dynamic.push((key.0, index, 1)); @@ -1917,9 +2095,9 @@ impl State { .find(|h| !h.samplers())?; let host = heap.host()?; let gpu = host.strides_gpu()?; - // One key per list, as textures have: no title resource is there. - const ONCE: usize = usize::MAX - 0x5e; - if !list.first_use(ONCE) { + // Stride buffers have aligned GPU addresses. Tag the list key so it + // is distinct from aligned guest resource pointers. + if !list.first_use(gpu as usize | 1) { return Some(gpu); } // The list may outlive the title's heap object, which owns the table. @@ -1931,9 +2109,8 @@ impl State { // frame (2026-11-24, run 11). // shortcut: what the title writes into such buffers between lists // of one frame is seen a frame late. - static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); let frame = crate::frame::current(); - if FRAME.swap(frame, Ordering::Relaxed) == frame { + if host.buffer_frame.swap(frame, Ordering::Relaxed) == frame { return Some(gpu); } let started = std::time::Instant::now(); @@ -1941,7 +2118,11 @@ impl State { if crate::host::aside::on() { let at = std::ptr::from_ref(heap) as usize; list.refreshes_coming(move || { - crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame))) + crate::descriptor::with_heap(at, |heap| { + // The list retains the original stride buffer. A newly + // allocated heap at the same CPU address has another one. + heap.host().filter(|h| h.strides_gpu() == Some(gpu)).map(|h| heap_buffer_pass(heap, h, frame)) + }) .flatten() .unwrap_or_default() }); @@ -1953,7 +2134,7 @@ impl State { #[cfg(feature = "diagnostics")] let refreshed = std::time::Instant::now(); stage.next("the heap pass: textures"); - self.heap_textures(list, heap, host); + let _ = self.heap_textures(list, heap, host, None); stage.end(); #[cfg(feature = "diagnostics")] HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed); @@ -1962,20 +2143,179 @@ impl State { Some(gpu) } + /// The GPU address of the bound view heap's stride/kind table without + /// running the bindless heap buffer/texture sweep (for shaders that only + /// inspect descriptors already mirrored via their descriptor tables). + fn heap_strides(&self, list: &HostList) -> Option { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // Tag bit 1 (distinct from `heap_buffers`'s `| 1` and aligned guest pointers). + if list.first_use(gpu as usize | 2) + && let Some(buffer) = host.strides_buffer() + { + list.keep(buffer); + } + Some(gpu) + } + + /// Ensures textures claimed by background copy-queue uploads + /// (`VICTORY_UPLOAD_AHEAD=1`) or deferred behind the `neutral()` gray + /// stand-in (`VICTORY_SHOW_AFTER=1` / `shows_other`) have finished + /// uploading and flipped to their real descriptors before a one-shot + /// decoration bake draw samples them. + fn flush_for_bake( + &self, + list: &HostList, + host: &crate::descriptor::host::HostHeap, + mut sync: Option<&mut BakeSync>, + ) { + static RESCUED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + let drained = crate::texture::ahead::drain(); + let mut settled = false; + let mut flipped = 0usize; + for _ in 0..4 { + let need_settle = host.needs_gpu_settle_for_bake(); + if need_settle { + settled = true; + crate::host::settle_for_fence(); + } + flipped += host.texture_views_remade(); + flipped += host.texture_slots_flip(); + if !need_settle || !host.needs_gpu_settle_for_bake() { + break; + } + } + let pending = host.take_pending_list_flips(); + let mut promoted = 0usize; + if !pending.is_empty() { + let this_list = (std::ptr::from_ref(list) as usize, list.epoch()); + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + for item in pending { + let (origin, index, handle, key) = (item.origin, item.index(), item.handle(), item.key()); + if !host.slot_still_at(handle, key) { + continue; + } + let Some(view) = crate::descriptor::view(handle) else { + continue; + }; + if let View::Placed(_, resource, desc) = &view { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(resource).unwrap_or(1); + if crate::texture::mapped_bytes(address as *const u8, len as usize) == 0 { + host.restore_pending_list_flip(item); + continue; + } + } + if sync.is_some() || origin != this_list { + let placed = crate::descriptor::host::placed_texture(&view); + if let Some(&View::Shader(resource, _)) = placed.as_ref().or(Some(&view)) { + let resource = resource as This; + let texture = crate::resource::host_resource(resource); + let title_fills = texture.is_some_and(crate::texture::title_written); + let first = match (&placed, &view) { + (Some(_), View::Placed(_, _, desc)) => crate::resource::first_mip(desc), + _ => 0, + }; + if let (Some(sync), Some(copy)) = (sync.as_deref_mut(), crate::resource::host_copy(resource)) { + sync.keep.push(copy); + } + if title_fills + && !crate::texture::ahead::there(resource) + && (sync.is_some() || !crate::texture::unchanged(resource, first)) + { + let was_staged = crate::texture::is_staged(resource); + let _ = crate::residency::take_staging_deferred(); + readable(list, sampled.kind, &view); + let failed = crate::residency::take_staging_deferred() || crate::residency::upload_refused(); + if !was_staged { + crate::texture::unstage(resource); + } + if failed { + host.restore_pending_list_flip(item); + continue; + } + } + } + } + if let Some(sync) = sync.as_deref_mut() { + sync.publish.push((index, handle, key)); + } else { + let _ = host.mirror(index, handle, true); + } + promoted += 1; + } + } + if drained > 0 || settled || flipped > 0 || promoted > 0 { + let n = RESCUED[0].fetch_add(1, Ordering::Relaxed) + 1; + let all_drained = RESCUED[1].fetch_add(drained as u64, Ordering::Relaxed) + drained as u64; + let all_flipped = RESCUED[2].fetch_add(flipped as u64, Ordering::Relaxed) + flipped as u64; + let all_promoted = RESCUED[3].fetch_add(promoted as u64, Ordering::Relaxed) + promoted as u64; + if n.is_power_of_two() { + tracing::info!( + frame = crate::frame::current(), + flushes = n, + drained_ahead = all_drained, + flipped = all_flipped, + promoted_from_lists = all_promoted, + settled, + "flushed deferred texture stand-ins before decoration bake" + ); + } + } + } + + /// Whether a graphics draw is a one-shot texture compositor / decoration + /// bake whose bindless texture inputs must be flushed and up to date + /// before recording the draw. Matches known bake pixel/geometry shaders + /// and structurally detects depth-less 4+ MRT square atlas bakes + /// (`>= 512x512`) so unseen NPC/head/clothing shader permutations never + /// bake `neutral()` or `null` stand-ins into permanent ped textures. + fn is_bake_draw(&self, p: &HostPipeline) -> bool { + if p.stages.iter().any(|s| { + let h = s.shader.hash.as_str(); + BAKE_PIXEL_SHADERS.contains(&h) || BAKE_GEOMETRY_SHADERS.contains(&h) + }) { + return true; + } + self.depth == 0 + && self.targets.len() >= 4 + && self + .targets + .first() + .and_then(|&t| crate::resource::texture_kind(t as This)) + .is_some_and(|(w, h, _)| w >= 512 && w == u64::from(h)) + } + /// Runs the pass that uploads textures picked by index /// ([`State::heap_textures`]) where nothing has asked for it yet /// ([`early_budgets`]): once a frame for a few milliseconds, at the /// frame's first draw with a view heap set, and with a larger budget /// of its own before every draw whose pixel shader is one of the - /// title's bake programs. The uploads are recorded into `list` ahead - /// of the draw being bound, as the world's pass records them. + /// title's bake programs. For decoration bakes, uploads run synchronously + /// on a dedicated internal command list and descriptors are published only + /// after the GPU copy finishes so concurrent `VICTORY_THIN=1` lists can + /// never submit a bake draw ahead of its texture uploads. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { let (early_ms, bake_ms) = early_budgets(); if compute || (early_ms == 0 && bake_ms == 0) { return; } - let bake = bake_ms > 0 - && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + let is_bake = bake_ms > 0 && self.is_bake_draw(p); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); // The milliseconds this frame's bake draws have taken so far: a // frame has several, and together they get `bake_ms`. @@ -1985,15 +2325,9 @@ impl State { if first { BAKED_MS.store(0, Ordering::Relaxed); } - let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); - let budget = if bake && left > 0 { - // What a bake may read must be there now: up to 2 GiB. - (left, 2 << 30) - } else if first && early_ms > 0 { - (early_ms, 64 << 20) - } else { + if !is_bake && !(first && early_ms > 0) { return; - }; + } let Some(heap) = self .heaps .iter() @@ -2006,34 +2340,102 @@ impl State { let Some(host) = heap.host() else { return; }; - let bake = bake && left > 0; - if bake && !first && bake_exact() { - let (writes, noted) = host.texture_news(); - if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + if is_bake { + let began = std::time::Instant::now(); + let mut bake_slot = BAKE_UPLOAD.lock().unwrap_or_else(|e| e.into_inner()); + let gpu = crate::host::host(); + if bake_slot.is_none() + && let Some(gpu) = gpu + { + match gpu.new_list() { + Ok(upload_list) => *bake_slot = Some(BakeList(upload_list)), + Err(e) => tracing::warn!(error = %e, "no host list for synchronous bake uploads"), + } + } + let exact = bake_exact(); + if let (Some(gpu), Some(BakeList(bake_list))) = (gpu, bake_slot.as_ref()) { + let mut sync = BakeSync { publish: Vec::new(), keep: Vec::new() }; + crate::texture::BAKING.set(exact); + self.flush_for_bake(bake_list, host, Some(&mut sync)); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let run_pass = left > 0 + && (first + || !exact + || { + let (writes, noted) = host.texture_news(); + noted || BAKE_SERVED.load(Ordering::Relaxed) != writes + 1 + }); + let mut served = false; + if run_pass { + let n = EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded synchronously first (VICTORY_BAKE_TEXTURES_MS=0: not)" + ); + } + BAKE_SERVED.store(0, Ordering::Relaxed); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + served = self.heap_textures(bake_list, heap, host, Some(&mut sync)); + PASS_BUDGET.set(None); + } + crate::texture::BAKING.set(false); + if bake_list.has_recorded_work() { + bake_list.close(); + gpu.execute_sync_internal(bake_list); + bake_list.reset(); + } else if !sync.publish.is_empty() { + crate::host::settle_for_fence(); + } + for (index, handle, key) in sync.publish { + let _ = host.publish_uploaded_slot(index, handle, key); + } + host.texture_views_remade(); + host.texture_slots_flip(); + drop(sync.keep); + if run_pass && served && exact { + BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); + } + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); return; } - } - let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; - if bake && n.is_power_of_two() { - let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); - tracing::info!( - frame, - bakes = n, - queued_at_the_last_pass = slots, - due_at_the_last_pass = due, - uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), - "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)" - ); - } - let began = std::time::Instant::now(); - PASS_BUDGET.set(Some(budget)); - crate::texture::BAKING.set(bake && bake_exact()); - self.heap_textures(list, heap, host); - crate::texture::BAKING.set(false); - PASS_BUDGET.set(None); - if bake { + // Fallback when no host GPU list can be created (e.g. headless tests). + crate::texture::BAKING.set(exact); + self.flush_for_bake(list, host, None); + crate::texture::BAKING.set(false); + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + if left == 0 { + return; + } + if !first && exact { + let (writes, noted) = host.texture_news(); + if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 { + return; + } + } + EARLY_TEXTURE_PASSES[1].fetch_add(1, Ordering::Relaxed); + PASS_BUDGET.set(Some((left, 2 << 30, true))); + crate::texture::BAKING.set(exact); + let _ = self.heap_textures(list, heap, host, None); + crate::texture::BAKING.set(false); + PASS_BUDGET.set(None); BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + return; } + let budget = if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + EARLY_TEXTURE_PASSES[0].fetch_add(1, Ordering::Relaxed); + PASS_BUDGET.set(Some((budget.0, budget.1, false))); + let _ = self.heap_textures(list, heap, host, None); + PASS_BUDGET.set(None); } /// The queue's side of the card accounting line @@ -2130,10 +2532,11 @@ impl State { list: &HostList, heap: &crate::descriptor::Heap, host: &crate::descriptor::host::HostHeap, - ) { + mut sync: Option<&mut BakeSync>, + ) -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) { - return; + return true; } let memory = crate::host::host().and_then(|h| h.video_memory()); // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of @@ -2144,7 +2547,14 @@ impl State { }); let per_frame = match asked { Some(mb) => mb << 20, - None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)), + None => { + let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget)); + if crate::residency::limited_host_ram() { + base.min(128 << 20) + } else { + base + } + } }; static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); @@ -2178,6 +2588,10 @@ impl State { // Slots whose texture's memory the runtime mapped, unmapped or // wrote since the last pass are due again. host.texture_slots_remapped(frame); + let baking = crate::texture::BAKING.get(); + if baking { + host.texture_slots_bake_written(frame); + } host.texture_slots_short(frame); // The slots of textures whose first level with memory (levels on // demand), or whose host copy for one with more levels, changed since @@ -2190,7 +2604,7 @@ impl State { if room { host.texture_slots_waiting(frame); } - let baking = crate::texture::BAKING.get(); + let required = PASS_BUDGET.get().is_some_and(|(_, _, bake)| bake); let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 }); // (Those that are due later after all that are due.) let on_time = due.len(); @@ -2259,13 +2673,29 @@ impl State { // own: its bytes on top of what the frame has spent so far. // (Not `most`: that is the longest wait between looks, used below.) let (span, bytes_at_most) = match PASS_BUDGET.get() { - Some((ms, bytes)) => { + Some((ms, bytes, _)) => { (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes)) } None => (span, per_frame), }; + // Apply the shared frame ceiling after early-pass and catch-up budgets. + // A bake samples its inputs immediately and cannot retry that draw. + let bytes_at_most = if required || asked.is_some() { + bytes_at_most + } else { + crate::residency::prefetch_limit( + bytes_at_most, + crate::residency::pressured(), + crate::residency::critical_commit(), + crate::residency::limited_host_ram(), + crate::texture::live_staging_bytes(), + ) + }; + let began = std::time::Instant::now(); - BAKE_SERVED.store(0, Ordering::Relaxed); + if sync.is_none() { + BAKE_SERVED.store(0, Ordering::Relaxed); + } let mut served = true; for (index, write) in due { if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { @@ -2304,10 +2734,36 @@ impl State { Some(wait) => { host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) } + // LOCAL (11/26, oil hunt): `VICTORY_HEAP_RECHECK_EVERY=`: after the + // last look, looked at again that often for the rest of the run. + None if heap_recheck_every() > 0 => host.texture_slot_recheck( + index, + write, + frame + heap_recheck_every(), + (at, len), + print, + looks, + uploaded, + ), None => host.texture_slot_done(index, write, None), } continue; } + if usize::from(looks) + 1 >= RECHECK_FRAMES.len() { + // A change after the last of the usual looks: one the build kept from + // the screen for the rest of the run before. + let n = HEAP_TEXTURES_LATE.fetch_add(1, Ordering::Relaxed); + if n < 300 { + tracing::warn!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + late = n + 1, + "a texture picked by index changed after the last usual look (VICTORY_HEAP_RECHECK_EVERY): uploaded again" + ); + } + } if recheck_soon() { again_in = 1; } @@ -2412,27 +2868,49 @@ impl State { ); } } + // Gate new host texture creation / staging on commit reserve after + // `mapped == 0` reclamation (`texture_slot_gone`) has run, and + // before mirroring a slot to an unuploaded texture. + if !crate::residency::admit_texture_pass(required) { + served = false; + break; + } // A slot that shows the texture by an earlier view of it (one // from another level) goes on doing so until the upload of what // the new one shows has run. + let sync_bake = sync.is_some(); let shows_other = !baking + && !sync_bake && crate::resource::held_only() && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle)); // A slot that shows nothing of it yet, or something else, shows it // when the upload has run too. let late = !shows_other && !baking + && !sync_bake && crate::descriptor::host::show_after() && heap.handle(index).is_some_and(|handle| !host.texture_slot_made_from(index, handle)); - let view = heap.handle(index).and_then(|handle| { - if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } - }); + let (view, bake_key) = if sync_bake { + match heap.handle(index).and_then(|handle| host.prepare_bake_slot(index, handle)) { + Some((view, key)) => (Some(view), Some(key)), + None => (None, None), + } + } else { + let view = heap.handle(index).and_then(|handle| { + if shows_other || late { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) } + }); + (view, None) + }; let at_once = || { - if late && let Some(handle) = heap.handle(index) { + if (late || bake_key.is_some()) && let Some(handle) = heap.handle(index) { let _ = host.mirror(index, handle, true); } }; let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + if crate::residency::upload_refused() { + served = false; + break; + } let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, _ => { @@ -2442,6 +2920,10 @@ impl State { } }; let texture = crate::resource::host_resource(resource); + if crate::residency::upload_refused() { + served = false; + break; + } let title_fills = texture.is_some_and(crate::texture::title_written); if !title_fills { at_once(); @@ -2461,16 +2943,23 @@ impl State { let same = !tabled && crate::texture::unchanged(resource, first); if same { HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed); - if shows_other && let Some(handle) = heap.handle(index) { - let _ = host.mirror(index, handle, true); - } - // Its bytes are in, or on the way there in a list before. - if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { - if let Some(handle) = heap.handle(index) { - host.texture_slot_show_after(list, index, handle); + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let Some(copy) = crate::resource::host_copy(resource) { + sync.keep.push(copy); } + sync.publish.push((index, handle, key)); } else { - at_once(); + if shows_other && let Some(handle) = heap.handle(index) { + let _ = host.mirror(index, handle, true); + } + // Its bytes are in, or on the way there in a list before. + if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) { + if let Some(handle) = heap.handle(index) { + host.texture_slot_show_after(list, index, handle); + } + } else { + at_once(); + } } let again = partly.map(|mapped| (frame + 1, mapped)); let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None }; @@ -2500,7 +2989,12 @@ impl State { crate::texture::ahead::send(job); } } + if ahead.is_none() && crate::residency::upload_refused() { + served = false; + break; + } let late = late && ahead.is_none(); + let _ = crate::residency::take_staging_deferred(); if let Some(view) = &view && ahead.is_none() { @@ -2510,6 +3004,21 @@ impl State { readable(list, sampled.kind, view); crate::texture::PICKING.set(None); } + // A failed or deferred staging allocation leaves this slot due. + // Publishing it or marking it served would lose the only retry for + // some materials. + if ahead.is_none() + && (crate::residency::take_staging_deferred() || crate::residency::upload_refused()) + { + served = false; + break; + } + if let (Some(sync), Some(key), Some(handle)) = (sync.as_deref_mut(), bake_key, heap.handle(index)) { + if let Some(copy) = crate::resource::host_copy(resource) { + sync.keep.push(copy); + } + sync.publish.push((index, handle, key)); + } if shows_other && let Some(handle) = heap.handle(index) { host.texture_slot_flip(list, index, handle); } @@ -2542,7 +3051,7 @@ impl State { let text: String = format!("{view:?}").chars().take(300).collect(); tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); crate::host::log_removal_context(); - return; + return false; } let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true)); // Not all of it there: looked at again next frame, and from @@ -2593,9 +3102,10 @@ impl State { None => host.texture_slot_done(index, write, again), } } - if baking && served { + if sync.is_none() && baking && served { BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed); } + served } /// For the frame listing, after a dropped dispatch's line: its group @@ -3196,21 +3706,29 @@ impl State { pub(crate) fn tables( &mut self, list: &HostList, - used: &[UsedResource], - indexed: &[RootIndexedView], + plan: &TablePlan, half: &[(u8, u32)], compute: bool, ) -> Few<(u8, u32), 16> { - let tables = |u: &&UsedResource| u.root == RootType::Table; - let mut fresh: Few = Few::default(); - for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) { - if !fresh.contains(&u.slot) { - fresh.push(u.slot); + let mut fresh = [0u64; 4]; + let selected_slot = |mask: &[u64; 4], slot: u8| mask[usize::from(slot / 64)] & (1u64 << (slot % 64)) != 0; + for group in &plan.groups { + let slot = group.slot; + let needs_snapshot = group.has_cbv + || match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => self.heap_of(table).is_some_and(|heap| { + heap.host() + .is_some_and(|host| group.needs_snapshot(heap, host.count(), table)) + }), + _ => false, + }; + if needs_snapshot { + fresh[usize::from(slot / 64)] |= 1u64 << (slot % 64); } } - // The view shown in place of the title's at dword `at` of the table - // in root parameter `slot`, if the shader moves halves there and - // the title's view is a 16-bit float or signed buffer view. + // LOCAL (faces): the view shown in place of the title's at dword `at` + // of the table in root parameter `slot`, if the shader moves halves + // there and the title's view is a 16-bit float or signed buffer view. let halved = |state: &Self, slot: u8, at: u32| -> Option { if !half.contains(&(slot, at)) { return None; @@ -3228,9 +3746,7 @@ impl State { continue; }; if crate::descriptor::host::half_view(&view).is_some() { - if !fresh.contains(&slot) { - fresh.push(slot); - } + fresh[usize::from(slot / 64)] |= 1u64 << (slot % 64); } else if let Some(format) = crate::descriptor::host::half_inexact(&view) { once!( format, @@ -3238,44 +3754,22 @@ impl State { ); } } - // Tables reaching past a host heap smaller than the title's (the - // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the - // title's slots there have no host slot of their own. - for u in used.iter().filter(tables) { - if fresh.contains(&u.slot) { - continue; - } - let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { - continue; - }; - let end = table + u64::from(u.table_offset_dwords) * 4; - let Some(heap) = self.heap_of(table) else { - continue; - }; - let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { - continue; - }; - if index >= host.count() { - fresh.push(u.slot); - } - } - fresh.sort_unstable(); - for u in used.iter().filter(tables) { - if !fresh.contains(&u.slot) { - self.table_entry(list, u, compute); + for &(g, e) in &plan.direct { + let group = &plan.groups[g]; + if !selected_slot(&fresh, group.slot) { + self.table_entry(list, &group.entries[e], compute); } } let mut made = Few::default(); - for &slot in fresh.iter() { + for group in &plan.groups { + let slot = group.slot; + if !selected_slot(&fresh, slot) { + continue; + } let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { continue; }; - // (Their places among `used`.) - let mut places: Few = Few::default(); - for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) { - places.push(i as u16); - } - let entries = || places.iter().map(|&i| &used[usize::from(i)]); + let entries = &group.entries; let Some(heap) = self.heap_of(table) else { continue; }; @@ -3285,9 +3779,9 @@ impl State { let Some(host) = heap.host() else { continue; }; - let mut selected: Vec = indexed + let mut selected: Vec = group + .indexed .iter() - .filter(|index| index.table_slot == slot) .map(|index| { let constant = self.user_value( compute, @@ -3310,12 +3804,7 @@ impl State { ); selected.sort_unstable(); selected.dedup(); - let n = entries() - .map(|u| u.table_offset_dwords / 8) - .chain(selected.last().copied()) - .max() - .unwrap_or(0) - + 1; + let n = (group.max_dword / 8).max(selected.last().copied().unwrap_or(0)) + 1; let last = table.checked_add(u64::from(n - 1) * 32); if n > crate::descriptor::host::DYNAMIC || last.and_then(|handle| heap.index(handle)).is_none() @@ -3339,12 +3828,12 @@ impl State { (table, n, h.0) }; // Who reads of it, and as what, as far as [`readable`] goes by it. - let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0); + let reader = (std::ptr::from_ref(plan) as usize, plan.direct.len(), STORES.get(), TESTED_DEPTH.get().0); if let Some(known) = self.fresh_tables.get_mut(&key) { let first = known.first; // This reader had it brought up to date, and nothing in the // list changed since: nothing to do again. - let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav); + let once = ready_once() && selected.is_empty() && !group.has_uav; if once && known.epoch == list.epoch() && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader) @@ -3357,14 +3846,14 @@ impl State { } let depth_before = TESTED_DEPTH.get(); TESTED_DEPTH.set((depth_before.0, false)); - for u in entries().filter(|u| u.kind != ResourceType::Cbv) { + for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { let handle = table + u64::from(u.table_offset_dwords) * 4; if let Some(view) = crate::descriptor::view(handle) { readable(list, u.kind, &view); } } for k in selected { - if entries().any(|u| u.table_offset_dwords / 8 == k) { + if group.entry(k).is_some() { continue; } let handle = table + u64::from(k) * 32; @@ -3391,7 +3880,10 @@ impl State { made.push((slot, first * 32)); continue; } - let Some(first) = host.dynamic(n) else { + let Some(first) = host.dynamic(n).or_else(|| { + crate::host::settle_for_fence(); + host.dynamic(n) + }) else { // No room: the draw must not run with the title's own // offsets (slots never made for it); `bind` drops it. made.push((slot, u32::MAX)); @@ -3407,7 +3899,7 @@ impl State { // which may lie over slots shaders pick by index, only the ones // the shader names.) if let Some(title) = title_first { - for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) { + for k in (0..n).filter(|&k| n <= 64 || group.entry(k).is_some()) { host.slot_tabled(title + k); } } @@ -3427,8 +3919,8 @@ impl State { && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32) && let Some(mut listed) = host.make_listed(recording, words, index) { - let kind = entries() - .find(|u| u.table_offset_dwords / 8 == k) + let kind = group + .entry(k) .map(|u| u.kind) .or_else(|| selected.binary_search(&k).ok().and(listed.kind)); let was = (listed.ready, listed.tabled); @@ -3439,11 +3931,12 @@ impl State { TESTED_DEPTH.set((tested.0, true)); } } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) { + let _ = crate::residency::take_staging_deferred(); TESTED_DEPTH.set((tested.0, false)); readable(list, kind, &view); let depth = TESTED_DEPTH.get().1; TESTED_DEPTH.set((tested.0, tested.1 || depth)); - if kind == ResourceType::Srv { + if kind == ResourceType::Srv && !crate::residency::take_staging_deferred() { listed.ready = (list.epoch(), tested.0, depth); } } @@ -3463,7 +3956,7 @@ impl State { } continue; } - let used = entries().find(|u| u.table_offset_dwords / 8 == k); + let used = group.entry(k); match crate::descriptor::view(table + u64::from(k) * 32) { Some(View::Constant(address, size)) => { let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else { diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 10a9e93..3ca3d41 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -115,7 +115,32 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if fence.value.load(Ordering::Acquire) >= value { return S_OK; } - tracing::warn!(value, "blocking fence wait not implemented"); + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250); + loop { + let current = fence.value.load(Ordering::Acquire); + if current >= value { + return S_OK; + } + let now = std::time::Instant::now(); + if now >= deadline { + break; + } + let ms = (deadline - now).as_millis().min(10) as u32; + // SAFETY: wait on the atomic u64 until woken by WakeByAddressAll or timeout. + unsafe { + windows_sys::Win32::System::Threading::WaitOnAddress( + (&raw const fence.value).cast(), + (&raw const current).cast(), + size_of::(), + ms.max(1), + ); + } + crate::queue::release_held(false); + } + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait timed out"); return E_NOTIMPL; } // shortcut: a null event means "block until reached"; nothing can @@ -140,6 +165,12 @@ pub(crate) fn set(this: This, value: u64) { } !reached }); + drop(waiters); + #[cfg(windows)] + // SAFETY: wake any guest thread polling/blocking via WaitOnAddress on the fence's GPU VA. + unsafe { + windows_sys::Win32::System::Threading::WakeByAddressAll((&raw const fence.value).cast()); + } } pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { let _called = crate::timeline::span("a fence set"); diff --git a/crates/victory-gpu/src/fg.rs b/crates/victory-gpu/src/fg.rs new file mode 100644 index 0000000..ac511c2 --- /dev/null +++ b/crates/victory-gpu/src/fg.rs @@ -0,0 +1,405 @@ +//! LOCAL (11/26): DLSS Frame Generation through NVIDIA Streamline (manual hooking). +//! +//! `VICTORY_FRAME_GEN=2|3|4` (frames shown per rendered one; unset or 1: off) with the SDK's +//! signed DLLs in `VICTORY_STREAMLINE_DIR` (sl.interposer, sl.common, sl.dlss_g, sl.reflex, +//! sl.pcl, nvngx_dlssg). NVIDIA's licence: for own use only, never pushed. +//! +//! - [`start`] (from the presenter, before its swap chain): `slInit`, `slSetD3DDevice`, Reflex +//! low latency, and the factory upgraded to Streamline's proxy, so that the swap chain made +//! from it is the proxy that generates frames at `Present`. +//! - [`tag`] (from the DLSS upscale, `crate::dlss::record`): the frame's constants and its depth +//! and motion vectors (copied by Streamline on that list: `eOnlyValidNow`). +//! - [`present_start`] / [`present_end`] around the proxy's `Present`. +//! +//! The title gives no camera matrices: they are made from a 60 degree field of view, the +//! upscale's near/far and the render size, the camera standing still (its motion is in the +//! motion vectors). Frame indices are the presents so far: the upscale of a frame is recorded +//! before its present. + +use std::ffi::CString; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::IDXGIFactory2; +use windows::core::Interface; + +use crate::streamline as sl; + +/// Frames to generate per rendered frame (1 = 2x .. 5 = 6x), 0: off, as `VICTORY_FRAME_GEN` +/// says now (the F1 menu changes it while running). +fn wanted_now() -> u32 { + std::env::var("VICTORY_FRAME_GEN").ok().and_then(|v| v.trim().parse::().ok()).map_or(0, |n| n.clamp(1, 6) - 1) +} + +/// [`wanted_now`] at the start: whether Streamline is started at all (its proxy swap chain is +/// made once; with it, the amount and off/on change while running). +pub(crate) fn wanted() -> u32 { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + let n = wanted_now(); + // Not together with the ray-tracing structure builder: each runs at about 15 frames a + // second alone and the two at 0.1 (11/26 r_rtE/F/G: from the moment Streamline has its + // first constants in the world, recording takes seconds a frame; Reflex off and no + // generated frames change nothing). `VICTORY_FG_WITH_RT=1` starts it anyway. + let rt = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + let forced = std::env::var_os("VICTORY_FG_WITH_RT").is_some_and(|v| v == "1"); + if n > 0 && rt && !forced { + tracing::warn!("frame generation: not started with ray tracing on (together they run at 0.1 frames a second); VICTORY_FG_WITH_RT=1 starts it anyway"); + return 0; + } + n + }) +} + +/// `VICTORY_FG_REFLEX=0`: Reflex left off and its sleep not taken (to tell its cost from the rest). +fn reflex_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_FG_REFLEX").is_none_or(|v| v != "0")) +} + +struct State { + sl: sl::Sl, + /// Frames to generate as last given to DLSS-G (0: turned off); none before the first present. + set: Option, + /// The most frames this card generates per rendered one, as DLSS-G says; 0: not asked yet. + most: u32, + told: u32, +} + +static STATE: OnceLock>> = OnceLock::new(); +/// Presents so far: the index of the frame being made. +static FRAME: AtomicU32 = AtomicU32::new(1); +/// A frame was tagged since the last present. +static TAGGED: AtomicBool = AtomicBool::new(false); + +const VIEWPORT: sl::ViewportHandle = sl::ViewportHandle::new(0); + +fn state() -> Option<&'static Mutex> { + STATE.get().and_then(|s| s.as_ref()) +} + +fn init(device: &ID3D12Device) -> anyhow::Result { + let dir = std::env::var_os("VICTORY_STREAMLINE_DIR") + .ok_or_else(|| anyhow::anyhow!("VICTORY_STREAMLINE_DIR is not set"))?; + // SAFETY: NVIDIA's signed interposer from the SDK folder the launcher names. + let mut s = unsafe { sl::Sl::load(std::path::Path::new(&dir)) }?; + let features = sl::FG_FEATURES; + static ENGINE: OnceLock<(CString, CString)> = OnceLock::new(); + let (version, project) = ENGINE.get_or_init(|| { + (CString::new("1.0").unwrap_or_default(), CString::new("5e2f9a3c-1b7d-4c8e-9a6f-0d3b2c1e4f57").unwrap_or_default()) + }); + let logs: Vec = std::env::temp_dir().join("victory-sl").as_os_str().encode_wide_z(); + let _ = std::fs::create_dir_all(std::env::temp_dir().join("victory-sl")); + let pref = sl::Preferences { + logLevel: sl::LogLevel::eDefault, + pathToLogsAndData: logs.as_ptr(), + logMessageCallback: Some(sl::log_to_tracing), + flags: sl::PreferenceFlags::MANUAL_HOOKING_FRAME_TAGS, + featuresToLoad: features.as_ptr(), + numFeaturesToLoad: features.len() as u32, + engine: sl::EngineType::eCustom, + engineVersion: version.as_ptr(), + projectId: project.as_ptr(), + renderAPI: sl::RenderAPI::eD3D12, + ..Default::default() + }; + // SAFETY: every pointer in `pref` lives through the call (SL copies them); the log + // callback is a static function. + unsafe { s.init(&pref) }.ok().map_err(|e| anyhow::anyhow!("slInit: {e}"))?; + // SAFETY: the host's live native device. + unsafe { s.set_d3d_device(device.as_raw()) }.ok().map_err(|e| anyhow::anyhow!("slSetD3DDevice: {e}"))?; + // SAFETY: a plain query of a live device. + let luid = unsafe { device.GetAdapterLuid() }; + let mut bytes = [0u8; 8]; + bytes[..4].copy_from_slice(&luid.LowPart.to_le_bytes()); + bytes[4..].copy_from_slice(&luid.HighPart.to_le_bytes()); + let supported = s.is_feature_supported(sl::kFeatureDLSS_G, Some(&bytes)); + if !supported.is_ok() { + anyhow::bail!("DLSS-G is not supported here: {supported}"); + } + s.resolve_feature_functions()?; + let reflex = sl::ReflexOptions { + mode: if reflex_on() { sl::ReflexMode::eLowLatency } else { sl::ReflexMode::eOff }, + ..Default::default() + }; + let r = s.reflex_set_options(&reflex); + if !r.is_ok() { + tracing::warn!(result = %r, "frame generation: Reflex not set"); + } + Ok(State { sl: s, set: None, most: 0, told: 0 }) +} + +trait WideZ { + fn encode_wide_z(&self) -> Vec; +} +impl WideZ for std::ffi::OsStr { + fn encode_wide_z(&self) -> Vec { + use std::os::windows::ffi::OsStrExt; + self.encode_wide().chain([0]).collect() + } +} + +/// Before the presenter's swap chain is made: starts Streamline (once) and gives back the +/// factory to make it from, the proxy if frame generation is wanted and could start. +pub(crate) fn start(device: &ID3D12Device, factory: IDXGIFactory2) -> IDXGIFactory2 { + if wanted() == 0 { + return factory; + } + let state = STATE.get_or_init(|| match init(device) { + Ok(s) => { + tracing::info!(frames = wanted() + 1, "frame generation: Streamline started"); + Some(Mutex::new(s)) + } + Err(e) => { + tracing::warn!(error = %e, "frame generation: Streamline did not start; presenting without it"); + None + } + }); + let Some(state) = state else { return factory }; + let s = state.lock().unwrap_or_else(|e| e.into_inner()); + let mut raw = factory.as_raw(); + // SAFETY: a live factory; the call puts a new proxy (with its own reference) in `raw` and + // leaves ours to the native one. + let r = unsafe { s.sl.upgrade_interface(&mut raw) }; + if !r.is_ok() || raw.is_null() { + tracing::warn!(result = %r, "frame generation: the factory was not upgraded"); + return factory; + } + // SAFETY: SL's proxy, an IDXGIFactory2 with one reference, now ours. + unsafe { IDXGIFactory2::from_raw(raw) } +} + +/// What the last DLSS upscale read: the frame's numbers and its depth and motion vectors (title +/// resources, whose host copies and states are looked up at the present). +struct Latest { + depth: usize, + motion: usize, + render: [u32; 2], + jitter: [f32; 2], + mv_pixels: [f32; 2], + near: f32, + far: f32, + reset: bool, +} + +static LATEST: Mutex> = Mutex::new(None); + +/// With frame generation on: the numbers of the DLSS upscale just recorded ([`crate::dlss::record`]). +/// The upscale of a frame is recorded after its present has been asked for (the lists are recorded +/// at submission), so everything is handed to Streamline at the next present, whose index is the +/// one the constants and tags carry. +#[allow(clippy::too_many_arguments)] +pub(crate) fn tag(render: [u32; 2], jitter: [f32; 2], mv_pixels: [f32; 2], near: f32, far: f32, reset: bool) { + if state().is_none() { + return; + } + let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + let (depth, motion) = latest.as_ref().map_or((0, 0), |l| (l.depth, l.motion)); + *latest = Some(Latest { depth, motion, render, jitter, mv_pixels, near, far, reset }); + TAGGED.store(true, Ordering::Relaxed); +} + +/// The title's depth and motion vectors the DLSS upscale read (`crate::list::upscale_now`). +pub(crate) fn note_titles(depth: u64, motion: u64) { + if state().is_none() { + return; + } + let mut latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(l) = latest.as_mut() { + (l.depth, l.motion) = (depth as usize, motion as usize); + } +} + +fn constants(l: &Latest) -> sl::Constants { + let (w, h) = (l.render[0].max(1) as f32, l.render[1].max(1) as f32); + let inverted = l.near > l.far; + let (n, f) = (l.near.min(l.far).max(1e-3), l.near.max(l.far).min(1e6).max(l.near.min(l.far) + 1.0)); + let fov = 60f32.to_radians(); + let ys = 1.0 / (fov / 2.0).tan(); + let xs = ys / (w / h); + let (c, d) = if inverted { (n / (n - f), -n * f / (n - f)) } else { (f / (f - n), -n * f / (f - n)) }; + sl::Constants { + cameraViewToClip: sl::float4x4::from_rows([[xs, 0.0, 0.0, 0.0], [0.0, ys, 0.0, 0.0], [0.0, 0.0, c, 1.0], [0.0, 0.0, d, 0.0]]), + clipToCameraView: sl::float4x4::from_rows([ + [1.0 / xs, 0.0, 0.0, 0.0], + [0.0, 1.0 / ys, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0 / d], + [0.0, 0.0, 1.0, -c / d], + ]), + clipToPrevClip: sl::float4x4::identity(), + prevClipToClip: sl::float4x4::identity(), + jitterOffset: sl::float2::new(l.jitter[0], l.jitter[1]), + mvecScale: sl::float2::new(l.mv_pixels[0] / w, l.mv_pixels[1] / h), + cameraPinholeOffset: sl::float2::new(0.0, 0.0), + cameraPos: sl::float3::new(0.0, 0.0, 0.0), + cameraUp: sl::float3::new(0.0, 1.0, 0.0), + cameraRight: sl::float3::new(1.0, 0.0, 0.0), + cameraFwd: sl::float3::new(0.0, 0.0, 1.0), + cameraNear: n, + cameraFar: f, + cameraFOV: fov, + cameraAspectRatio: w / h, + depthInverted: inverted.into(), + cameraMotionIncluded: sl::Boolean::eTrue, + motionVectors3D: sl::Boolean::eFalse, + reset: l.reset.into(), + motionVectorsJittered: sl::Boolean::eTrue, + ..Default::default() + } +} + +/// Right before the proxy's `Present`: generation on (once), and for a frame the upscale ran in, +/// its constants and its depth and motion vectors (valid until this present: the next frame's +/// lists come after it on the queue). +pub(crate) fn present_start() { + let Some(state) = state() else { return }; + let mut s = state.lock().unwrap_or_else(|e| e.into_inner()); + let index = FRAME.load(Ordering::Relaxed); + // The amount, at the first present and whenever the menu changed it (looked at twice a second + // or so): no restart, the proxy swap chain stays. + if s.set.is_none() || index % 8 == 0 { + let asked = wanted_now(); + // No more than the card and driver generate (DLSS 4.5 gives up to 5 here: 6x). + // Asked once here (each question restarts Streamline's count of presented frames). + if s.most == 0 { + s.most = match s.sl.dlssg_get_state(&VIEWPORT, None) { + Ok(st) if st.numFramesToGenerateMax > 0 => st.numFramesToGenerateMax, + _ => 1, + }; + } + let want = asked.min(s.most); + if s.set != Some(want) { + if want != asked { + tracing::warn!(asked = asked + 1, given = want + 1, "frame generation: more than this card generates; its most is used"); + } + let options = sl::DLSSGOptions { + mode: if want == 0 { sl::DLSSGMode::eOff } else { sl::DLSSGMode::eOn }, + numFramesToGenerate: want.max(1), + flags: sl::DLSSGFlags::eRetainResourcesWhenOff, + ..Default::default() + }; + let r = s.sl.dlssg_set_options(&VIEWPORT, &options); + tracing::info!(result = %r, frames = want + 1, "frame generation: amount set (1 = off)"); + s.set = Some(want); + if want == 0 { + SHOWN.store(1, Ordering::Relaxed); + } + } + } + let Ok(token) = s.sl.new_frame_token(Some(index)) else { return }; + for marker in [ + sl::PCLMarker::eSimulationStart, + sl::PCLMarker::eSimulationEnd, + sl::PCLMarker::eRenderSubmitStart, + sl::PCLMarker::eRenderSubmitEnd, + ] { + let _ = s.sl.pcl_set_marker(marker, token); + } + // Every present carries the last upscale's numbers and buffers, a present with no new + // upscale since the last one too (DLSS-G drops a frame that has none). + let fresh = TAGGED.swap(false, Ordering::Relaxed); + { + let latest = LATEST.lock().unwrap_or_else(|e| e.into_inner()); + let found = latest.as_ref().and_then(|l| { + // Only a title resource that is still one, and only its copy as it is: the handles + // are a frame old at a present with no new upscale, and the title may have let the + // resource go since (with ray tracing on it makes and frees buffers all the time); + // `host_copy` would make a copy of whatever lies there now. + let look = |title: usize| { + let this = title as crate::object::This; + if this.is_null() || !crate::resource::is_resource(this) { + return None; + } + let copy = crate::resource::made_copy(this)?; + let state = crate::host::legal_state(©.texture, copy.state.load(Ordering::Relaxed)); + Some((copy, state)) + }; + Some((l, look(l.depth)?, look(l.motion)?)) + }); + if let Some((l, (depth, depth_state), (motion, motion_state))) = found { + let r = s.sl.set_constants(&constants(l), token, &VIEWPORT); + let mut depth_res = sl::Resource::d3d12_tex2d(depth.texture.as_raw(), depth_state); + let mut motion_res = sl::Resource::d3d12_tex2d(motion.texture.as_raw(), motion_state); + let extent = Some(sl::Extent { top: 0, left: 0, width: l.render[0], height: l.render[1] }); + let tags = [ + sl::ResourceTag::new(&mut depth_res, sl::kBufferTypeDepth, sl::ResourceLifecycle::eValidUntilPresent, extent), + sl::ResourceTag::new(&mut motion_res, sl::kBufferTypeMotionVectors, sl::ResourceLifecycle::eValidUntilPresent, extent), + ]; + // SAFETY: live resources (their host copies are held through the call), in the + // states they will be in at the present; no list needed for eValidUntilPresent. + let t = unsafe { s.sl.set_tag_for_frame(token, &VIEWPORT, &tags, std::ptr::null_mut()) }; + if (!r.is_ok() || !t.is_ok()) && s.told < 5 { + s.told += 1; + tracing::warn!(constants = %r, tags = %t, index, "frame generation: constants or tags refused"); + } + PRESENT_TAGGED.store(fresh, Ordering::Relaxed); + } + } + let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentStart, token); +} + +/// The present now ending had constants and tags. +static PRESENT_TAGGED: AtomicBool = AtomicBool::new(false); + +/// Right after the proxy's `Present`: the next frame's index, Reflex's sleep, and now and then +/// what the generator says of itself. +pub(crate) fn present_end() { + let Some(state) = state() else { return }; + let s = state.lock().unwrap_or_else(|e| e.into_inner()); + let index = FRAME.load(Ordering::Relaxed); + if let Ok(token) = s.sl.new_frame_token(Some(index)) { + let _ = s.sl.pcl_set_marker(sl::PCLMarker::ePresentEnd, token); + } + let tagged = PRESENT_TAGGED.swap(false, Ordering::Relaxed); + // For the frame-rate texts: frames shown per rendered one, as Streamline says of the last + // present (r_cgbj41: 1 over 30 presents with the window not focused, so not a running count; + // DLSS-G generates nothing while the window is not focused). + const POLL: u32 = 10; + if index % POLL == 0 { + match s.sl.dlssg_get_state(&VIEWPORT, None) { + Ok(st) => { + let per = if st.status.0 == 0 { st.numFramesActuallyPresented.clamp(1, 6) } else { 1 }; + SHOWN.store(per, Ordering::Relaxed); + if index % 600 == 0 || (index / POLL).is_power_of_two() { + tracing::info!( + index, + tagged, + status = st.status.0, + presented = st.numFramesActuallyPresented, + per, + max = st.numFramesToGenerateMax, + "frame generation: state (status 0 = working; 2 Reflex, 8 constants)" + ); + } + } + Err(e) => { + SHOWN.store(1, Ordering::Relaxed); + if index % 600 == 0 { + tracing::warn!(error = %e, "frame generation: no state"); + } + } + } + } + let next = index + 1; + FRAME.store(next, Ordering::Relaxed); + // Reflex paces the next frame here. + if reflex_on() + && let Ok(token) = s.sl.new_frame_token(Some(next)) + { + let _ = s.sl.reflex_sleep(token); + } +} +/// Frames shown per frame rendered (1 without generation working), as Streamline last said. +static SHOWN: AtomicU32 = AtomicU32::new(1); + +/// For the frame-rate texts: frames shown per frame rendered; 1 when generation is off or failing. +pub(crate) fn shown_per_frame() -> u32 { + if state().is_some() { SHOWN.load(Ordering::Relaxed).max(1) } else { 1 } +} + +/// Whether Streamline is presenting (the presenter's swap chain is its proxy). +pub(crate) fn active() -> bool { + state().is_some() +} + diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 8bf432f..91cf709 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -25,8 +25,47 @@ const ORIGIN: u32 = 0; const TOKEN_ON_TIMEOUT: u32 = 2; const SIXTIETH: Duration = Duration::from_micros(16_667); +/// LOCAL (11/26): `VICTORY_FPS_CAP`. Unset: the title's own interval (30 frames a second on a +/// Series S); `0`: none (ticks half a millisecond apart); `n`: n frames a second. The F1 menu +/// changes it while running ([`set_cap`]). -1: not read yet; 0: the title's; else microseconds. +static CAP_US: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1); + +fn parse_cap(value: Option<&str>) -> i64 { + match value.map(str::trim).and_then(|v| v.parse::().ok()) { + None => 0, + Some(0) => 500, + Some(n) => (1_000_000 / i64::from(n)).max(500), + } +} + +/// The interval ticks are apart: the title's, or the cap's when one is set. +fn capped(asked: Duration) -> Duration { + let mut us = CAP_US.load(Ordering::Relaxed); + if us < 0 { + us = parse_cap(std::env::var("VICTORY_FPS_CAP").ok().as_deref()); + CAP_US.store(us, Ordering::Relaxed); + } + if us == 0 { asked } else { Duration::from_micros(us as u64) } +} + +/// The cap changed (the F1 menu): the clock goes on from now with the new interval. +#[allow(dead_code)] +pub(crate) fn set_cap(value: &str) { + CAP_US.store(parse_cap(Some(value).filter(|v| !v.is_empty())), Ordering::Relaxed); + let first = LAST.iter().map(|t| t.load(Ordering::Relaxed)).max().unwrap_or(0); + if let Some(c) = clock().as_mut() { + c.start = Instant::now(); + c.first = first; + c.interval = capped(c.asked); + tracing::info!(asked = ?c.asked, interval = ?c.interval, "frame interval: the cap changed"); + } +} + struct Clock { start: Instant, + /// What the title asked for. + asked: Duration, + /// What ticks are apart ([`capped`]). interval: Duration, /// The tick number at `start` (ticks go on across interval changes). first: u64, @@ -53,7 +92,9 @@ pub(crate) extern "system" fn set_interval( 0 => SIXTIETH, us => Duration::from_micros(u64::from(us)), }; - tracing::info!(?interval, "frame interval"); + let asked = interval; + let interval = capped(asked); + tracing::info!(?asked, ?interval, "frame interval (VICTORY_FPS_CAP: unset the title's, 0 none, n frames a second)"); // A new interval starts from now, after the last tick handed out. let first = LAST .iter() @@ -62,6 +103,7 @@ pub(crate) extern "system" fn set_interval( .unwrap_or(0); *clock() = Some(Clock { start: Instant::now(), + asked, interval, first, }); @@ -105,7 +147,8 @@ fn next_tick(kind: u32) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { start: Instant::now(), - interval: SIXTIETH, + asked: SIXTIETH, + interval: capped(SIXTIETH), first: 0, }); let elapsed = c.start.elapsed().as_nanos(); diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 1aceb9c..98ddda3 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -57,6 +57,10 @@ pub(crate) struct Host { /// The adapter the device is on, for its memory budget /// ([`Host::video_memory`]); `None` if the system does not name it. adapter: Option, + /// 1-descriptor shader-visible fallback heaps bound when a command list + /// omits a view or sampler heap while using directly-indexed root signatures. + fallback_view: OnceLock>, + fallback_sampler: OnceLock>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are @@ -368,7 +372,11 @@ pub(crate) fn keep_freed() -> bool { /// when free physical RAM is low. Never returns less than 2,000 ms. /// With plenty of it five minutes ([`keep_freed`]). pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { - ram_idle_for(avail_phys, keep_freed()) + let effective = match (avail_phys, crate::residency::headroom()) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + ram_idle_for(effective, keep_freed() && !crate::residency::limited_host_ram()) } fn ram_idle_for(avail_phys: Option, keep: bool) -> u64 { @@ -432,6 +440,10 @@ fn sweep() { } #[cfg(feature = "diagnostics")] crate::book::check(); + crate::residency::refresh(); + if crate::residency::pressured() { + trim_spare_chunks(); + } crate::pool::room(host().and_then(|h| h.video_memory())); crate::pipeline::trim_library(); crate::shadow::let_go_idle(); @@ -484,7 +496,10 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { /// recorded and not yet sent may name them. `VICTORY_BURY_LAG=0`: not. fn bury_lag() -> u64 { static LAG: OnceLock = OnceLock::new(); - *LAG.get_or_init(|| std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(64)) + *LAG.get_or_init(|| { + let default = if crate::residency::limited_host_ram() { 16 } else { 64 }; + std::env::var("VICTORY_BURY_LAG").ok().and_then(|v| v.parse().ok()).unwrap_or(default) + }) } /// Drops what waited for submissions up to `finished` ([`bury_lag`]). The @@ -970,6 +985,8 @@ fn create() -> windows::core::Result { next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), adapter, + fallback_view: OnceLock::new(), + fallback_sampler: OnceLock::new(), }) } } @@ -1963,7 +1980,12 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); for (chunk, size) in chunks { let back = if scratch_pool() { - spare.give(chunk, size, if keep_freed() { SPARE_KEPT } else { SPARE_MOST }) + let limit = if keep_freed() && !crate::residency::limited_host_ram() { + SPARE_KEPT + } else { + SPARE_MOST + }; + spare.give(chunk, size, limit) } else { Some(chunk) }; @@ -1984,6 +2006,25 @@ fn give_chunks(chunks: Vec<(Chunk, u64)>) { drop(freed); } +/// Drops spare scratch chunks kept idle when host memory is pressured. +fn trim_spare_chunks() { + let freed: Vec<(Chunk, u64)> = { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if spare.kept.is_empty() { + return; + } + spare.bytes = 0; + std::mem::take(&mut spare.kept) + }; + let count = freed.len() as u64; + let bytes: u64 = freed.iter().map(|(_, s)| *s).sum(); + ALIVE[1].fetch_sub(count, Ordering::Relaxed); + ALIVE[2].fetch_sub(bytes, Ordering::Relaxed); + ALIVE[3].fetch_sub(count, Ordering::Relaxed); + ALIVE[4].fetch_sub(bytes, Ordering::Relaxed); + drop(freed); +} + /// What the host keeps for copies in the card's own memory /// ([`crate::shadow::cards`]): three lists of ours and the compare. struct CardWork { @@ -2243,6 +2284,8 @@ enum Step { /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc), + /// Reads a CPU-written linear movie plane into a per-list upload buffer. + Plane((usize, usize), Box), /// A title buffer copy that the list does on the card ([`place`]): what /// is done on the CPU for it. Placed(place::Placed), @@ -2256,6 +2299,8 @@ struct Deferred { /// Destination, source, bytes. copies: Vec, uploads: Vec, + /// Standalone upload footprints kept through this list's fence (movie planes). + plane_uploads: Vec<(Chunk, u64)>, /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). upload_bytes: u64, /// Host objects the list's commands name (pipelines, root signatures, @@ -2320,6 +2365,7 @@ impl Deferred { impl Drop for Deferred { fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.plane_uploads)); ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); } @@ -2733,6 +2779,10 @@ const WHY_FENCE: usize = 10; /// copy, a fill of upload memory, a texture). static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; +/// LOCAL (11/26): settles for refreshes of memory a flight writes through +/// another copy (`upcheck::crossed`), since the last frame-rate line. +static CROSS_SETTLES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + /// Since the last frame-rate line: the microseconds settles waited for the /// card, by why they settled (the `WHY_` places). static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; @@ -2998,6 +3048,16 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op return Some(WHY_READ); } } + &Step::Plane((at, len), _) => { + if touches(written, at, at.saturating_add(len)) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + blame("a movie plane", written, at, len); + } + return Some(WHY_READ); + } + } Step::Run(_) => return Some(WHY_RUN), Step::Placed(p) => match p.waits(written) { place::Waits::No => {} @@ -3566,6 +3626,10 @@ fn late_line(frames: f64) { if !late() { return; } + if upcheck::cross_on() { + let n = CROSS_SETTLES.swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!("relay cross settles per frame (VICTORY_RELAY_CROSS=1): {n:.1}"); + } let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); tracing::info!( "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ @@ -3676,6 +3740,8 @@ mod card_steps; pub(crate) mod indirects; #[cfg(feature = "diagnostics")] mod panel; +#[cfg(feature = "diagnostics")] +mod menu; mod place; mod send; pub(crate) use send::{goes_as_words, words_under}; @@ -4313,6 +4379,7 @@ impl Host { // pass: a wait between each copy and its pass had the // card do them one after the other. let mut sent = Vec::new(); + let mut transitioned = Vec::new(); if let Some(own) = &own { own.record(self, list, &dirty, |shadow| looks.as_ref().is_some_and(|l| l.hold(shadow))); } @@ -4331,11 +4398,15 @@ impl Host { #[cfg(feature = "diagnostics")] traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied()); if own.is_none() && before.is_some() && !ranges.is_empty() { - sent.push(transition( - &shadow.buffer, - D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, - )); + let raw = shadow.buffer.as_raw(); + if !transitioned.contains(&raw) { + transitioned.push(raw); + sent.push(transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )); + } } } if !sent.is_empty() { @@ -4906,7 +4977,7 @@ impl Host { let mut telling = std::time::Instant::now(); for item in items { telling = match item { - Late::Run(flight) => { + Late::Run(mut flight) => { last = flight.number; for &i in &flight.order { read_backs(flight.lists[i].host()); @@ -4918,6 +4989,9 @@ impl Host { if let Some(own) = flight.own { own.landed(); } + for detached in &mut flight.lists { + detached.release_tables(); + } crate::land::spent(crate::land::stat::RB_DONE, done_from); landed.push((flight.lists, flight.order)); crate::land::spent(crate::land::stat::READ_BACKS, telling) @@ -5121,6 +5195,14 @@ impl Host { let _ = self.submit(runs, &[], false); } + /// Runs a closed internal upload-only host list synchronously without + /// draining title queues (`queue::before_sync`), so it is deadlock-safe + /// when invoked from `VICTORY_THIN=1` worker threads. Settles in-flight + /// GPU work and waits for the upload list's fence before returning. + pub(crate) fn execute_sync_internal(&self, list: &HostList) { + let _ = self.submit(&[list], &[], false); + } + /// A queue's submission with [`late`]: the host lists `lists`, taken /// from the title's, go to the card in `order` and are not waited for. /// They join the line of flights and are settled, with the others in @@ -5378,7 +5460,7 @@ impl Host { let mut landed = Vec::new(); for item in items { match item { - Late::Run(flight) => { + Late::Run(mut flight) => { last = flight.number; for &i in &flight.order { read_backs(flight.lists[i].host()); @@ -5386,6 +5468,9 @@ impl Host { if let Some(card) = flight.card { self.card_done(card); } + for detached in &mut flight.lists { + detached.release_tables(); + } landed.push((flight.lists, flight.order)); } Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), @@ -5592,10 +5677,24 @@ impl Host { self.settle_stale(&mut submitted, runs, stale, &ranges); settled += settling.elapsed(); } + // LOCAL (11/26): refreshes of memory a flight writes through + // another copy wait for that flight (`upcheck::cross_on`). + if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) { + let settling = std::time::Instant::now(); + CROSS_SETTLES.fetch_add(1, Ordering::Relaxed); + self.settle(&mut submitted, WHY_STALE); + crate::watch::ask_once(&ranges); + settled += settling.elapsed(); + } } else if behind && !stale_under_flights(runs).is_empty() { let settling = std::time::Instant::now(); self.settle(&mut submitted, WHY_STALE); settled += settling.elapsed(); + } else if behind && upcheck::cross_on() && flying() && upcheck::crossed(runs) { + let settling = std::time::Instant::now(); + CROSS_SETTLES.fetch_add(1, Ordering::Relaxed); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); } #[cfg(feature = "diagnostics")] split.part(1); @@ -6120,6 +6219,71 @@ impl Host { handle } } + + /// 1-descriptor shader-visible CBV/SRV/UAV fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_view_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_view + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible heap + null SRV initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::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::default(), + }, + }; + self.device.CreateShaderResourceView( + None, + Some(&desc), + heap.GetCPUDescriptorHandleForHeapStart(), + ); + Some(heap) + } + }) + .as_ref() + } + + /// 1-descriptor shader-visible Sampler fallback heap for directly-indexed root signatures. + pub(crate) fn fallback_sampler_heap(&self) -> Option<&ID3D12DescriptorHeap> { + self.fallback_sampler + .get_or_init(|| { + // SAFETY: plain 1-descriptor shader-visible sampler heap initialization. + unsafe { + let heap: ID3D12DescriptorHeap = self + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxLOD: f32::MAX, + ..Default::default() + }; + self.device + .CreateSampler(&desc, heap.GetCPUDescriptorHandleForHeapStart()); + Some(heap) + } + }) + .as_ref() + } } impl HostList { @@ -6300,6 +6464,13 @@ impl HostList { self.epoch.load(Ordering::Relaxed) } + /// Whether any deferred steps or texture state transitions have been + /// recorded into this list since creation or its last [`HostList::reset`]. + pub(crate) fn has_recorded_work(&self) -> bool { + !self.deferred().copies.is_empty() + || !self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + /// Moves a title texture's host copy to `wanted` (a host state) in this /// list: the host texture and the state it leaves, if that is a change. /// The list's first use of a texture records nothing: its prelude brings @@ -7209,6 +7380,23 @@ impl HostList { self.deferred().copies.push(Step::Texture(staging)); } + /// A copy source owned exclusively by this list until reset after its + /// last execution. A different list can prepare its movie plane concurrently. + pub(crate) fn plane_upload( + &self, + size: u64, + read: (usize, usize), + fill: impl Fn(usize) + Send + 'static, + ) -> Option { + let chunk = take_chunk(host()?, size)?; + let source = chunk.buffer.clone(); + let destination = chunk.data; + let mut deferred = self.deferred(); + deferred.plane_uploads.push((chunk, size)); + deferred.copies.push(Step::Plane(read, Box::new(move || fill(destination)))); + Some(source) + } + /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). Copies and fills that @@ -7327,6 +7515,13 @@ impl HostList { } continue; } + Step::Plane((_, len), fill) => { + let started = std::time::Instant::now(); + fill(); + PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[3].fetch_add(*len as u64, Ordering::Relaxed); + continue; + } }; us += started.elapsed(); bytes += copied as u64; @@ -8525,6 +8720,7 @@ impl Host { match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, size, "no upload buffer"); None } @@ -8558,8 +8754,11 @@ struct Presenter { ahead: Vec<(HostList, u64)>, hwnd: HWND, meter: Meter, + composer: Option, #[cfg(feature = "diagnostics")] panel: panel::Panel, + #[cfg(feature = "diagnostics")] + menu: menu::Menu, } /// The frame rate, shown in the window's caption every second and logged @@ -8849,7 +9048,13 @@ impl Meter { self.caption = Some(buffer); } let Some(caption) = &self.caption else { return }; - let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); + // LOCAL (11/26): with frame generation, the frames shown too. + let shown = crate::fg::shown_per_frame(); + let text = if shown > 1 { + format!(" | VIctory {fps:.0} fps (frame gen {:.0} fps) {ms:.1} ms/frame {draws:.0} draws/frame", fps * f64::from(shown)) + } else { + format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame") + }; let mut text: Vec = caption.iter().copied().chain(text.encode_utf16()).collect(); text.push(0); // Setting the text waits for the window's thread (a title thread, @@ -8881,25 +9086,40 @@ impl Host { /// Shows `texture`, which is in `state` (a host state) and stays in it, /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. + #[allow(dead_code)] pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { - self.present_over(texture, state, None, frame) + self.present_planes(texture, state, None, frame) } - /// LOCAL (port of fxceless #1189): [`Self::present`], with a second - /// plane laid over `texture` if there is one (`crate::compose`): its - /// texture and its state, which it is left in. - pub(crate) fn present_over( + /// Shows `texture`, optionally alpha-compositing a second `overlay` plane + /// over it (Series S two-plane presentation), and returns them to their states. + pub(crate) fn present_planes( &self, texture: &ID3D12Resource, state: u32, - over: Option<(&ID3D12Resource, u32)>, + overlay: Option<(&ID3D12Resource, u32)>, frame: u64, ) -> Option { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; - let Some(format) = swap_format(desc.Format) else { - tracing::warn!(format = desc.Format.0, "cannot present this format"); - return None; + let planes = overlay.and_then(|(over, over_state)| { + // SAFETY: a live overlay resource. + let over_desc = unsafe { over.GetDesc() }; + Some(( + over, + D3D12_RESOURCE_STATES(over_state as i32), + crate::compose::view(&desc)?, + crate::compose::view(&over_desc)?, + )) + }); + let format = if planes.is_some() { + DXGI_FORMAT_R8G8B8A8_UNORM + } else { + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + format }; let (width, height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); @@ -8912,7 +9132,18 @@ impl Host { } }; } + let state_u32 = state; let p = presenter.as_mut()?; + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } if (p.width, p.height, p.format) != (width, height, format) { // Presents sent ahead hold back buffers until they have run. settle_now(WHY_SYNC); @@ -8923,6 +9154,9 @@ impl Host { }; match resized { Ok(()) => { + if p.format != format { + p.composer = None; + } (p.width, p.height, p.format) = (width, height, format); tracing::info!( width, @@ -8939,8 +9173,18 @@ impl Host { } } } - let state = D3D12_RESOURCE_STATES(state as i32); - // SAFETY: our swap chain, list and a live source texture. + if planes.is_some() && p.composer.is_none() { + match crate::compose::Composer::new(self, format) { + Ok(c) => p.composer = Some(c), + Err(e) => { + tracing::warn!(error = %e, "two-plane composer not made after resize; showing base plane only"); + drop(presenter); + return self.present_planes(texture, state_u32, None, frame); + } + } + } + let state = D3D12_RESOURCE_STATES(state_u32 as i32); + // SAFETY: our swap chain, list and live source texture(s). unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::(index) else { @@ -8969,42 +9213,136 @@ impl Host { None => &p.copy, }; copy.reset(); + copy.keep(texture); let list = ©.list; - list.ResourceBarrier(&[ - transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition( + let composed = if let Some((over, over_state, base_fmt, over_fmt)) = planes { + copy.keep(over); + if let Some(composer) = p.composer.as_mut() { + let mut pre = Vec::with_capacity(3); + 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)); + } + pre.push(transition(&back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + list.ResourceBarrier(&pre); + let compose_slot = slot.map_or(0, |i| i + 1); + if let Err(err) = composer.record( + self, + compose_slot, + list, + [(texture, base_fmt), (over, over_fmt)], + &back, + (width, height), + ) { + copy.close(); + drop(back); + drop(presenter); + tracing::warn!(%err, "could not record display composite; presenting the base plane"); + return self.present_planes(texture, state_u32, None, frame); + } + static ONCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::info!( + frame, + width, + height, + base_format = base_fmt.0, + overlay_format = over_fmt.0, + "display output: compositing two planes (overlay active)" + ); + } + let mut post = Vec::with_capacity(3); + 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)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_DEST, + )); + list.ResourceBarrier(&post); + true + } else { + false + } + } else { + false + }; + if !composed { + let mut pre = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + pre.push(transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE)); + } + pre.push(transition( &back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST, - ), - ]); - // LOCAL (port of fxceless #1189): the second plane laid over the - // first, into a texture of ours shown instead (`crate::compose`). - let laid = over.and_then(|(ui, ui_state)| crate::compose::record(&self.device, list, texture, ui, ui_state)); - if let Some(laid) = &laid { - copy.keep(laid); + )); + list.ResourceBarrier(&pre); + list.CopyResource(&back, texture); } - list.CopyResource(&back, laid.as_ref().unwrap_or(texture)); #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) - .then(|| crate::capture::read_back(&self.device, list, texture)) + .then(|| { + if composed { + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let res = crate::capture::read_back(&self.device, list, &back); + list.ResourceBarrier(&[transition( + &back, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + res + } else { + crate::capture::read_back(&self.device, list, texture) + } + }) .flatten(); #[cfg(feature = "diagnostics")] - let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + let probe = if slot.is_some() || composed { + None + } else { + crate::capture::probe(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] - let watched = crate::popwatch::take(&self.device, list, texture); + let watched = if composed { + None + } else { + crate::popwatch::take(&self.device, list, texture) + }; #[cfg(feature = "diagnostics")] p.panel.draw(self, copy, &back, (width, height), format); + #[cfg(feature = "diagnostics")] + p.menu.draw(self, copy, &back, (width, height), format); #[cfg(not(feature = "diagnostics"))] let _ = frame; - list.ResourceBarrier(&[ - transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), - transition( + if composed { + list.ResourceBarrier(&[transition( &back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT, - ), - ]); + )]); + } else { + let mut post = Vec::with_capacity(2); + if state != D3D12_RESOURCE_STATE_COPY_SOURCE { + post.push(transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state)); + } + post.push(transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + )); + list.ResourceBarrier(&post); + } copy.close(); let flown = match slot { Some(i) => { @@ -9030,10 +9368,14 @@ impl Host { #[cfg(feature = "diagnostics")] crate::replay::record::present(texture, state); let mut showing = crate::timeline::span("the host's Present"); + crate::fg::present_start(); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + crate::fg::present_end(); showing.next("the frame meter"); #[cfg(feature = "diagnostics")] p.panel.frame(p.meter.line_due()); + #[cfg(feature = "diagnostics")] + p.menu.frame(); p.meter.frame(p.hwnd); showing.end(); #[cfg(feature = "diagnostics")] @@ -9057,6 +9399,8 @@ impl Host { // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + // LOCAL (11/26): with `VICTORY_FRAME_GEN`, Streamline's proxy factory (crate::fg). + let factory = crate::fg::start(&self.device, factory); let desc = DXGI_SWAP_CHAIN_DESC1 { Width: width, Height: height, @@ -9086,8 +9430,11 @@ impl Host { ahead: Vec::new(), hwnd, meter: Meter::new(), + composer: None, #[cfg(feature = "diagnostics")] panel: panel::Panel::new(), + #[cfg(feature = "diagnostics")] + menu: menu::Menu::new(), }) } } diff --git a/crates/victory-gpu/src/host/card_steps.rs b/crates/victory-gpu/src/host/card_steps.rs index 9ee1494..166addd 100644 --- a/crates/victory-gpu/src/host/card_steps.rs +++ b/crates/victory-gpu/src/host/card_steps.rs @@ -201,6 +201,7 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool { .iter() .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))), Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to), + Step::Plane((at, len), _) => copies.iter().any(|w| w.from < at.saturating_add(*len) && *at < w.to), _ => false, }) }) @@ -440,6 +441,11 @@ fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec, Vec<(u asked: touches(written, at, at + len), } } + &Step::Plane((at, len), _) => Does::Read { + from: at, + to: at.saturating_add(len), + asked: touches(written, at, at.saturating_add(len)), + }, &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false }, Step::Refresh(shadow, at, len) => Does::Refresh { shadow: Arc::as_ptr(shadow) as usize, diff --git a/crates/victory-gpu/src/host/menu.rs b/crates/victory-gpu/src/host/menu.rs new file mode 100644 index 0000000..837995a --- /dev/null +++ b/crates/victory-gpu/src/host/menu.rs @@ -0,0 +1,528 @@ +//! LOCAL (11/26): the F1 settings menu. F1 shows and hides it while our +//! window has the focus; Up/Down pick a setting, Left/Right change it, Enter +//! runs the line picked (save, save and restart, reset, close), Esc closes. +//! While it is shown the title sees no keyboard (`crate::SETTINGS_MENU_OPEN`, +//! read by the input module); a pad still works. +//! +//! Most settings are read once at start, so a change is saved to the file +//! `VICTORY_MENU_FILE` names (play.ps1 sets it to the play folder's +//! settings.txt and applies it at every start) and takes effect at the next +//! start; "SAVE AND RESTART" starts play.ps1 again (`VICTORY_MENU_PLAY`, +//! with `VICTORY_MENU_ARGS`) and ends this run. Lines marked LIVE change at +//! once. +//! +//! Drawn as the stats panel is (`super::panel`): white text on a black box, +//! copied onto the swap chain's buffer, in the middle of the picture. + +use std::sync::atomic::Ordering; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, VK_DOWN, VK_ESCAPE, VK_F1, VK_LEFT, VK_RETURN, VK_RIGHT, VK_UP, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId}; + +use super::panel::{colours, glyph}; +use super::{Host, HostList, transition}; + +const GLYPH: (u32, u32) = (5, 7); +const CELL: (u32, u32) = (6, 9); +const COLUMNS: u32 = 60; +/// Lines of the box: a title, a help line, a blank, the settings shown, a +/// blank and a note. +const ROWS: usize = 20; +const LINES: u32 = ROWS as u32 + 5; +const RIM: u32 = 4; +const UPLOADS: usize = 4; + +/// A setting: the variable, its name in the menu, the values it takes +/// (`""`: not set, the build's own default), and whether a change applies at once. +struct Item { + var: &'static str, + label: &'static str, + values: &'static [(&'static str, &'static str)], + live: bool, +} + +const OFF_ON: &[(&str, &str)] = &[("0", "OFF"), ("1", "ON")]; +const UNSET_ON: &[(&str, &str)] = &[("", "OFF"), ("1", "ON")]; + +#[rustfmt::skip] +const ITEMS: &[Item] = &[ + Item { var: "VICTORY_UPSCALE", label: "UPSCALER", values: &[("dlss", "DLSS"), ("stretch", "STRETCH"), ("", "GAME FSR4 (SLOW)")], live: false }, + Item { var: "VICTORY_FRAME_GEN", label: "FRAME GEN (NOT WITH RAY TR.)", values: &[("", "OFF"), ("2", "2X"), ("3", "3X"), ("4", "4X"), ("5", "5X"), ("6", "6X (MOST)")], live: false }, + Item { var: "VICTORY_FPS_CAP", label: "FRAME RATE CAP", values: &[("", "GAME (30)"), ("60", "60"), ("120", "120"), ("0", "NONE")], live: true }, + Item { var: "VICTORY_BVH_BUILDER", label: "RAY TRACING (REAL LIGHTING)", values: &[("", "OFF"), ("1", "ON")], live: false }, + Item { var: "VICTORY_DLSS_PRESET", label: "DLSS MODEL", values: &[("", "DEFAULT (K)"), ("K", "K TRANSFORMER"), ("J", "J TRANSFORMER"), ("M", "M TRANSFORMER"), ("L", "L TRANSFORMER")], live: false }, + Item { var: "VICTORY_DLSS_SHARPNESS", label: "DLSS SHARPNESS", values: &[("0", "0"), ("0.25", "0.25"), ("0.5", "0.5"), ("0.75", "0.75"), ("1", "1")], live: true }, + Item { var: "VICTORY_MENU_SMOOTH_MOTION", label: "SMOOTH MOTION", values: &[("1", "ON"), ("0", "OFF")], live: false }, + Item { var: "VICTORY_MENU_CONSOLE", label: "CONSOLE", values: &[("series-s", "SERIES S"), ("series-x", "SERIES X")], live: false }, + Item { var: "VICTORY_ADAPTER", label: "GRAPHICS CARD", values: &[("", "WINDOWS DEFAULT"), ("#0", "CARD 0"), ("#1", "CARD 1"), ("#2", "CARD 2")], live: false }, + Item { var: "VICTORY_PANEL", label: "STATS PANEL (F3)", values: UNSET_ON, live: true }, + Item { var: "VICTORY_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_RELAY_COPY", label: "RELAY COPY QUEUE", values: OFF_ON, live: false }, + Item { var: "VICTORY_FETCH_CHECK", label: "FETCH CHECK", values: OFF_ON, live: false }, + Item { var: "VICTORY_WIDE_BACK", label: "WIDE COPY BACK", values: OFF_ON, live: false }, + Item { var: "VICTORY_CARD_STEPS", label: "CARD STEPS", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_TEXTURE_NO_WAIT", label: "TEXTURE NO WAIT", values: OFF_ON, live: false }, + Item { var: "VICTORY_HEAP_RECHECK_EVERY", label: "TEXTURE RECHECK (OIL TEST)", values: &[("", "OFF"), ("60", "EVERY 60 FRAMES"), ("15", "EVERY 15 FRAMES")], live: false }, + Item { var: "VICTORY_NULL_SAMPLER_LINEAR", label: "LINEAR STAND-IN SAMPLER", values: UNSET_ON, live: false }, + Item { var: "VICTORY_AMBIENT", label: "AMBIENT STAND-IN", values: OFF_ON, live: false }, + Item { var: "VICTORY_AMBIENT_AIR", label: "FOG CAP", values: &[("1.5", "1.5"), ("1", "1"), ("2", "2"), ("", "NONE")], live: false }, + Item { var: "VICTORY_NAN_SCRUB", label: "NAN SCRUB (SHADERS REBUILD)", values: OFF_ON, live: false }, + Item { var: "VICTORY_THIN", label: "THIN", values: OFF_ON, live: false }, + Item { var: "VICTORY_JOIN_PARTS", label: "JOIN PARTS", values: &[("8", "8"), ("4", "4"), ("16", "16"), ("1", "1")], live: false }, + Item { var: "VICTORY_JOIN_COPIES", label: "JOIN COPIES", values: OFF_ON, live: false }, + Item { var: "VICTORY_UPLOAD_AHEAD", label: "UPLOAD AHEAD", values: OFF_ON, live: false }, + Item { var: "VICTORY_INDIRECT_WINDOW", label: "INDIRECT WINDOW", values: OFF_ON, live: false }, + Item { var: "VICTORY_INDIRECT_BATCH", label: "INDIRECT BATCH", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_CARD_REHASH_RUNS", label: "CARD REHASH RUNS", values: OFF_ON, live: false }, + Item { var: "VICTORY_MAP_THREADS", label: "MAP THREADS", values: OFF_ON, live: false }, + Item { var: "VICTORY_TITLE_PRIORITIES", label: "TITLE THREAD PRIORITIES", values: OFF_ON, live: false }, + Item { var: "VICTORY_CARD_AWAKE", label: "KEEP CARD AWAKE", values: OFF_ON, live: false }, + Item { var: "VICTORY_SHOW_AFTER", label: "SHOW AFTER", values: OFF_ON, live: false }, + Item { var: "VICTORY_PIPELINE_WAIT_MS", label: "SHADER WAIT MS", values: &[("10000", "10000"), ("30000", "30000"), ("1000", "1000"), ("0", "0 SKIP")], live: false }, + Item { var: "VICTORY_DYNAMIC_SLOTS", label: "DESCRIPTOR SLOTS", values: &[("524288", "524288"), ("262144", "262144"), ("1000000", "1000000")], live: false }, + Item { var: "VICTORY_CARD_BUFFERS_MB", label: "CARD BUFFERS MB", values: &[("1536", "1536"), ("1024", "1024"), ("2048", "2048"), ("512", "512"), ("0", "0 OFF")], live: false }, + Item { var: "VICTORY_RENDER_SCALE", label: "RENDER SCALE", values: &[("", "GAME (720P)"), ("0.5", "0.5 (540P)"), ("0.75", "0.75")], live: false }, + Item { var: "VICTORY_OWN_UPSCALER", label: "OWN UPSCALER", values: UNSET_ON, live: false }, + Item { var: "VICTORY_D3D12_DRED", label: "CRASH BREADCRUMBS", values: &[("light", "LIGHT"), ("", "OFF")], live: false }, +]; + +/// The lines after the settings. +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() +} + +/// Whether a change of `item` shows at once. +fn live(item: &Item) -> bool { + item.live || (item.var == "VICTORY_FRAME_GEN" && crate::fg::active()) +} + +/// The index of `value` among the item's values (an unknown value: shown as +/// itself, at the end). +fn index_of(item: &Item, value: &str) -> Option { + item.values.iter().position(|(v, _)| *v == value) +} + +/// Keys pressed, gathered on a thread of their own every 10 ms: a frame +/// lasts 50 ms and more, and a short press would fall between two frames. +fn keys() -> &'static Mutex> { + static KEYS: OnceLock>> = OnceLock::new(); + KEYS.get_or_init(|| { + let _ = std::thread::Builder::new().name("settings menu keys".into()).spawn(|| { + const WATCHED: [u16; 7] = [VK_F1, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_RETURN, VK_ESCAPE]; + let mut was = [false; WATCHED.len()]; + loop { + std::thread::sleep(Duration::from_millis(10)); + let mut process = 0; + // SAFETY: plain queries; room for the answer. + unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) }; + let ours = process == std::process::id(); + for (i, &vk) in WATCHED.iter().enumerate() { + // SAFETY: a plain query. + let down = ours && unsafe { GetAsyncKeyState(i32::from(vk)) } < 0; + if down && !was[i] { + keys().lock().unwrap_or_else(|e| e.into_inner()).push(vk); + } + was[i] = down; + } + } + }); + Mutex::new(Vec::new()) + }) +} + +/// The box's size in pixels. +const fn size(scale: u32) -> (u32, u32) { + ((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale) +} + +fn lit(lines: &[String], x: u32, y: u32) -> bool { + let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else { + return false; + }; + if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS { + return false; + } + let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else { + return false; + }; + (glyph(c.to_ascii_uppercase())[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0 +} + +fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec { + let (width, height) = size(scale); + let bytes = colours[0].len(); + let mut out = vec![0; pitch * height as usize]; + for y in 0..height / scale { + let top = pitch * (y * scale) as usize; + for x in 0..width / scale { + let colour = colours[usize::from(lit(lines, x, y))]; + for i in 0..scale { + let at = top + (x * scale + i) as usize * bytes; + out[at..at + bytes].copy_from_slice(colour); + } + } + for i in 1..scale as usize { + out.copy_within(top..top + pitch, top + i * pitch); + } + } + out +} + +struct Buffers { + format: DXGI_FORMAT, + scale: u32, + pitch: u32, + uploads: Vec<(ID3D12Resource, *mut u8)>, + card: ID3D12Resource, + turn: usize, + fresh: bool, + /// The card's buffer was copied into before (it is in the copy-source state; + /// at first it is in the common state, promoted by the first copy). + used: bool, +} + +// SAFETY: free-threaded resources, and memory only written under the presenter's lock. +unsafe impl Send for Buffers {} + +impl Buffers { + fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option { + let (width, height) = size(scale); + let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256); + let bytes = u64::from(pitch) * u64::from(height); + let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::>>()?; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut card: Option = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card) + .ok()?; + } + Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false, used: false }) + } + + fn write(&mut self, lines: &[String]) { + let Some(colours) = colours(self.format) else { return }; + let picture = painted(lines, self.scale, colours, self.pitch as usize); + self.turn = (self.turn + 1) % UPLOADS; + // SAFETY: a mapped upload buffer of the picture's size, which the card read frames ago. + unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) }; + self.fresh = true; + } +} + +/// The menu of a presenter. +pub(super) struct Menu { + /// The values chosen, by item (as at start until changed). + values: Vec, + /// The values at start. + started: Vec, + /// The line picked: an item, or an action after them. + at: usize, + note: String, + changed: bool, + buffers: Option, + failed: bool, +} + +impl Menu { + pub(super) fn new() -> Menu { + // Start the key thread now: F1 must be seen while the menu is closed. + let _ = keys(); + let values: Vec = ITEMS.iter().map(|i| get(i.var)).collect(); + Menu { started: values.clone(), values, at: 0, note: String::new(), changed: true, buffers: None, failed: false } + } + + fn open() -> bool { + crate::SETTINGS_MENU_OPEN.load(Ordering::Relaxed) + } + + fn lines(&self) -> Vec { + let total = ITEMS.len() + ACTIONS.len(); + let first = self.at.saturating_sub(ROWS / 2).min(total.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) { + 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 { "" }; + format!("{cursor} {:<27} < {shown} >{mark}", item.label) + } else { + format!("{cursor} {}", ACTIONS[row - ITEMS.len()]) + }; + out.push(line.chars().take(COLUMNS as usize).collect()); + } + while out.len() < 3 + ROWS { + out.push(String::new()); + } + out.push(String::new()); + out.push(if self.note.is_empty() { "* = CHANGED: APPLIES AT THE NEXT START UNLESS LIVE".to_owned() } else { self.note.clone() }); + out + } + + /// Changes item `i` by `step` (+1 / -1) through its values. + fn change(&mut self, i: usize, step: isize) { + let item = &ITEMS[i]; + let n = item.values.len() as isize; + 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) { + self.apply_live(i); + } + self.note.clear(); + } + + /// With a start that had frame generation on, its amount (and off) changes while running; + /// from a start without it, turning it on needs the restart (Streamline's swap chain). + fn apply_live(&self, i: usize) { + let (var, value) = (ITEMS[i].var, &self.values[i]); + // SAFETY: the variables changed here are read by this build with + // std::env::var at each use; Windows' environment block is locked by + // the process heap's routines, and std holds its own lock. + unsafe { + if value.is_empty() { + std::env::remove_var(var); + } else { + std::env::set_var(var, value); + } + } + if var == "VICTORY_FPS_CAP" { + crate::frame::set_cap(value); + } + if var == "VICTORY_PANEL" { + super::panel::shown().store(!value.is_empty(), Ordering::Relaxed); + } + } + + /// Writes the changed values over those in the settings file. + fn save(&mut self) -> bool { + let Some(path) = std::env::var_os("VICTORY_MENU_FILE") else { + self.note = "NO SETTINGS FILE: START THE GAME WITH PLAY.PS1".to_owned(); + return false; + }; + let mut kept: Vec<(String, String)> = std::fs::read_to_string(&path) + .unwrap_or_default() + .lines() + .filter_map(|l| l.split_once('=').map(|(k, v)| (k.trim().to_owned(), v.trim().to_owned()))) + .filter(|(k, _)| k.starts_with("VICTORY_")) + .collect(); + for (i, item) in ITEMS.iter().enumerate() { + if self.values[i] == self.started[i] { + continue; + } + kept.retain(|(k, _)| k != item.var); + 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"); + for (k, v) in &kept { + text.push_str(&format!("{k}={v}\r\n")); + } + match std::fs::write(&path, text) { + Ok(()) => { + tracing::info!(path = %std::path::Path::new(&path).display(), "settings menu: saved"); + self.started = self.values.clone(); + self.note = "SAVED. APPLIES AT THE NEXT START".to_owned(); + true + } + Err(e) => { + tracing::warn!(error = %e, "settings menu: not saved"); + self.note = "COULD NOT SAVE THE SETTINGS FILE".to_owned(); + false + } + } + } + + /// Starts play.ps1 again in a new console, a few seconds on, and ends this run. + fn restart(&mut self) { + use std::os::windows::process::CommandExt; + let Some(play) = std::env::var_os("VICTORY_MENU_PLAY") else { + self.note = "SAVED. RESTART PLAY.PS1 YOURSELF".to_owned(); + return; + }; + let play = play.to_string_lossy().replace('\'', "''"); + let args = get("VICTORY_MENU_ARGS"); + let command = format!("Start-Sleep 3; & '{play}' {args}"); + const CREATE_NEW_CONSOLE: u32 = 0x10; + match std::process::Command::new("powershell.exe") + .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &command]) + .creation_flags(CREATE_NEW_CONSOLE) + .spawn() + { + Ok(_) => { + tracing::info!(command, "settings menu: restarting"); + // Ended at once: std::process::exit runs the DLLs' unloading, and with Streamline + // loaded that never came back (11/26: a windowless leftover with one thread + // and 27 GB, which also kept the new build from being put in place). + // SAFETY: this process, with nothing of its own left to save. + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + TerminateProcess(GetCurrentProcess(), 0); + } + std::process::exit(0); + } + Err(e) => { + tracing::warn!(error = %e, "settings menu: restart failed"); + self.note = "SAVED, BUT THE RESTART FAILED".to_owned(); + } + } + } + + /// Empties the settings file: play.ps1's own settings at the next start. + fn reset(&mut self) { + if let Some(path) = std::env::var_os("VICTORY_MENU_FILE") { + let _ = std::fs::remove_file(path); + } + self.note = "RESET. PLAY DEFAULTS AT THE NEXT START".to_owned(); + } + + /// A frame was presented: the keys pressed since the last one. + pub(super) fn frame(&mut self) { + let pressed = std::mem::take(&mut *keys().lock().unwrap_or_else(|e| e.into_inner())); + 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) { + crate::SETTINGS_MENU_OPEN.store(!open && vk == VK_F1, Ordering::Relaxed); + self.note.clear(); + self.changed = true; + continue; + } + if !open { + continue; + } + match vk { + VK_UP => self.at = (self.at + total - 1) % total, + VK_DOWN => self.at = (self.at + 1) % total, + 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), + VK_RETURN => match self.at - ITEMS.len() { + 0 => { + if self.save() { + self.restart(); + } + } + 1 => { + self.save(); + } + 2 => self.reset(), + _ => crate::SETTINGS_MENU_OPEN.store(false, Ordering::Relaxed), + }, + _ => {} + } + self.changed = true; + } + } + + /// Records the copy of the box onto `back` (in the copy-destination state). + pub(super) fn draw(&mut self, host: &Host, list: &HostList, back: &ID3D12Resource, (width, height): (u32, u32), format: DXGI_FORMAT) { + if !Self::open() || self.failed { + return; + } + let _ours = crate::replay::record::unrecorded(); + let scale = (height / 540).max(1); + if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) { + std::mem::forget(self.buffers.take()); + self.buffers = Buffers::new(host, format, scale); + self.failed = self.buffers.is_none(); + self.changed = true; + } + let lines = if self.changed { Some(self.lines()) } else { None }; + let Some(buffers) = &mut self.buffers else { return }; + if let Some(lines) = lines { + self.changed = false; + buffers.write(&lines); + } + let (w, h) = size(scale); + let (w, h) = (w.min(width), h.min(height)); + let (x, y) = ((width - w) / 2, (height - h) / 2); + let list = &list.list; + // SAFETY: an open list and live resources; the box lies within both. + unsafe { + if std::mem::take(&mut buffers.fresh) { + if std::mem::replace(&mut buffers.used, true) { + list.ResourceBarrier(&[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0); + list.ResourceBarrier(&[transition(&buffers.card, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + } + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffers.card), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: size(scale).0, Height: size(scale).1, Depth: 1, RowPitch: buffers.pitch }, + }, + }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(back), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let part = D3D12_BOX { left: 0, top: 0, front: 0, right: w, bottom: h, back: 1 }; + list.CopyTextureRegion(&to, x, y, 0, &from, Some(&part)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_line_fits_and_every_character_has_a_picture() { + let mut menu = Menu { values: ITEMS.iter().map(|_| String::new()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false }; + menu.started = menu.values.clone(); + for at in 0..ITEMS.len() + ACTIONS.len() { + menu.at = at; + for line in menu.lines() { + assert!(line.len() <= COLUMNS as usize, "{line}"); + for c in line.bytes() { + assert_ne!(glyph(c.to_ascii_uppercase()), glyph(b'#'), "{line}: {}", c as char); + } + } + } + } + + #[test] + fn values_cycle_both_ways() { + let mut menu = Menu { values: ITEMS.iter().map(|i| i.values[0].0.to_owned()).collect(), started: Vec::new(), at: 0, note: String::new(), changed: false, buffers: None, failed: false }; + menu.started = menu.values.clone(); + let n = ITEMS[0].values.len(); + for _ in 0..n { + menu.change(0, 1); + } + assert_eq!(menu.values[0], ITEMS[0].values[0].0); + menu.change(0, -1); + assert_eq!(menu.values[0], ITEMS[0].values[n - 1].0); + } +} diff --git a/crates/victory-gpu/src/host/panel.rs b/crates/victory-gpu/src/host/panel.rs index a3d2f9b..808bc52 100644 --- a/crates/victory-gpu/src/host/panel.rs +++ b/crates/victory-gpu/src/host/panel.rs @@ -40,7 +40,7 @@ fn asked() -> bool { } /// Whether it is shown now. -fn shown() -> &'static AtomicBool { +pub(super) fn shown() -> &'static AtomicBool { static SHOWN: OnceLock = OnceLock::new(); SHOWN.get_or_init(|| AtomicBool::new(asked())) } @@ -61,7 +61,7 @@ fn pressed() -> bool { /// Seven rows of five dots, the leftmost the highest bit. #[rustfmt::skip] -const fn glyph(c: u8) -> [u8; 7] { +pub(super) const fn glyph(c: u8) -> [u8; 7] { match c { b'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], b'1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], @@ -103,6 +103,19 @@ const fn glyph(c: u8) -> [u8; 7] { b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000], b'-' => [0, 0, 0, 0b11111, 0, 0, 0], b' ' => [0; 7], + // LOCAL (11/26): for the F1 settings menu (menu.rs). + b'>' => [0b01000, 0b00100, 0b00010, 0b00001, 0b00010, 0b00100, 0b01000], + b'<' => [0b00010, 0b00100, 0b01000, 0b10000, 0b01000, 0b00100, 0b00010], + b'*' => [0, 0b00100, 0b10101, 0b01110, 0b10101, 0b00100, 0], + b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0], + b'_' => [0, 0, 0, 0, 0, 0, 0b11111], + b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0], + b'(' => [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010], + b')' => [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000], + b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0], + b',' => [0, 0, 0, 0, 0b01100, 0b00100, 0b01000], + b'!' => [0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0, 0b00100], + b'?' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0, 0b00100], _ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111], } } @@ -133,7 +146,7 @@ fn lit(lines: &[String], x: u32, y: u32) -> bool { } /// The bytes of a black and a white pixel of a swap chain's format. -fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> { +pub(super) fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> { Some(match format { DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM => [&[0, 0, 0, 0xFF], &[0xFF; 4]], DXGI_FORMAT_R10G10B10A2_UNORM => [&[0, 0, 0, 0xC0], &[0xFF; 4]], @@ -213,8 +226,12 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); let idle = (c[1] / 1e3).min(ms); vec![ - format!("FPS {:.1} FRAME {ms:.1} MS LONGEST {worst:.0}", 1e3 / ms.max(0.001)), - format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]), + // LOCAL (11/26): with frame generation, the frames shown beside those rendered. + match crate::fg::shown_per_frame() { + 1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)), + n => format!("FPS {:.1} FG {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001), f64::from(n) * 1e3 / ms.max(0.001)), + }, + format!("DRAWS {:.0} DROPPED {:.0} LONGEST {worst:.0}", c[10], c[8]), format!("SUBMIT BUSY {:.1} WAITS FOR GPU {:.1}", c[0] / 1e3, c[3] / 1e3), format!("GPU BUSY {:.1} IDLE BEHIND US {:.1}", ms - idle, c[2] / 1e3), format!("RECORDING {:.0} MS COPY BACK {:.1}", c[9] / 1e6, c[5] / 1e3), diff --git a/crates/victory-gpu/src/host/place.rs b/crates/victory-gpu/src/host/place.rs index 9e815d4..b5a7bb7 100644 --- a/crates/victory-gpu/src/host/place.rs +++ b/crates/victory-gpu/src/host/place.rs @@ -119,6 +119,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo let (at, len) = staging.memory(); touches(&ranges, at, at + len) } + &Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)), Step::Host(_, (from, to)) => touches(&ranges, *from, *to), Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len), _ => false, diff --git a/crates/victory-gpu/src/host/upcheck.rs b/crates/victory-gpu/src/host/upcheck.rs index d82a0c9..56ff942 100644 --- a/crates/victory-gpu/src/host/upcheck.rs +++ b/crates/victory-gpu/src/host/upcheck.rs @@ -317,6 +317,48 @@ fn known(copy: u64, at: usize) -> String { type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>; static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new())); +/// LOCAL (11/26, `VICTORY_RELAY_CROSS=1`): whether a refresh of `runs` reads +/// title memory that a flight in the air may be writing through another copy +/// of it ([`reads`] counts those). Such a refresh sends the bytes from before +/// the flight, and draws of that submission read them: one frame of stale +/// vertices and indices (triangles flung across the screen with the relay on, +/// none with `VICTORY_RELAY=0`). The caller settles the flights first. +pub(crate) fn cross_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_CROSS").is_some_and(|v| v == "1")) +} + +pub(super) fn crossed(runs: &[&HostList]) -> bool { + let mut writes: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + let mut all = Vec::new(); + for item in &super::line().line { + if let Late::Run(flight) = item { + for (shadow, ranges) in &flight.back { + writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b))); + join_ranges(&mut all, ranges.iter().copied()); + } + } + } + if writes.is_empty() { + return false; + } + for list in runs { + for step in &list.deferred().copies { + let Step::Refresh(shadow, at, len) = step else { + continue; + }; + let (from, to) = (*at, *at + *len); + if !touches(&all, from, to) { + continue; + } + if writes.iter().any(|(writer, a, b)| *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow)) { + return true; + } + } + } + false +} + /// Flights are in the air and `runs` are about to be prepared: which /// refreshes of theirs read title memory that a flight may be writing through /// another copy of it. Such a refresh takes what was there before the flight diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index 5c13842..e50f572 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -295,12 +295,10 @@ pub(crate) fn amd(device: &ID3D12Device) -> bool { /// Whether a record that does not fit in what is left of its list's budget /// takes the rest, so that every record after it runs empty too -/// (`VICTORY_INDIRECT_REST=0`: it takes nothing, and the next one that fits -/// runs). A list whose budget one garbage record empties loses all its later -/// draws, and which record that is may differ from frame to frame. The frame -/// line says how many records a frame are refused. +/// (`VICTORY_INDIRECT_REST=1`; off by default so one oversized record takes +/// nothing and later valid draws still run). fn rest() -> u32 { - u32::from(std::env::var("VICTORY_INDIRECT_REST").map_or(true, |v| v != "0")) + u32::from(std::env::var("VICTORY_INDIRECT_REST").is_ok_and(|v| v == "1")) } /// The clamp compiled from `source` (ours, or in the benchmark the one it @@ -2607,7 +2605,7 @@ void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) { /// left then, and the records as clamped. fn four_records_of_a_group(rest: bool) -> Option<(u32, Vec)> { let mut warp = WarpHarness::new()?; - let source = if rest { SOURCE.to_owned() } else { SOURCE.replace("REST ?", "false ?") }; + let source = SOURCE.replace("REST ?", if rest { "true ?" } else { "false ?" }); let clamp = make_from(&warp.device, &source).expect("the clamp must compile on WARP"); const KIND_DRAW: u32 = 0; const STRIDE: u32 = 16; diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 9441fe2..4ae200b 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -19,10 +19,9 @@ mod ambient; #[cfg(all(windows, feature = "diagnostics"))] mod capture; -pub mod console; -// LOCAL (port of fxceless #1189): Series S interface plane laid over the game (VICTORY_COMPOSE=1). #[cfg(windows)] mod compose; +pub mod console; #[cfg(all(windows, feature = "diagnostics"))] mod copystat; #[cfg(all(windows, feature = "diagnostics"))] @@ -40,6 +39,13 @@ pub mod frame; mod book; #[cfg(windows)] mod host; + +/// LOCAL (11/26): the F1 settings menu is shown (host/menu.rs): the title gets no keyboard. +pub static SETTINGS_MENU_OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(windows)] +pub mod streamline; +#[cfg(windows)] +mod fg; #[cfg(windows)] mod indirect; #[cfg(windows)] @@ -61,9 +67,15 @@ pub mod query; pub mod queue; #[cfg(all(windows, feature = "diagnostics"))] pub mod replay; +#[cfg(windows)] +mod residency; pub mod resource; pub mod root; #[cfg(windows)] +mod stretch; +#[cfg(all(windows, feature = "dlss"))] +mod dlss; +#[cfg(windows)] mod safecopy; #[cfg(windows)] mod sampler; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 8a17ddb..1622bb6 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -203,6 +203,12 @@ impl Detached { pub(crate) fn host(&self) -> &crate::host::HostList { &self.host } + + /// Releases this list's dynamic descriptor slots once its GPU submission + /// has completed, without waiting for the full `bury_lag` allocator delay. + pub(crate) fn release_tables(&mut self) { + self._state.tables_done(); + } } /// A host list that has run and waits to be used again, and the bytes of @@ -811,6 +817,165 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> 0 } +/// What the title gives its upscale (`ffxDispatch`, Series S), as plain words +/// so that a list whose calls are only written down (`VICTORY_THIN=1`) can +/// carry it to the thread that records. +#[derive(Clone, Copy, Debug, Default)] +pub struct Upscale { + pub colour: u64, + pub depth: u64, + pub motion: u64, + pub exposure: u64, + pub output: u64, + pub render: [u32; 2], + pub jitter: [f32; 2], + pub motion_scale: [f32; 2], + pub reset: bool, + pub pre_exposure: f32, + pub near: f32, + pub far: f32, + pub frame_ms: f32, + /// DLSS where it can (`crate::dlss`, the `dlss` feature), else a stretch. + pub dlss: bool, +} + +impl Upscale { + pub(crate) const WORDS: usize = 11; + + pub(crate) fn to_words(self) -> [u64; Self::WORDS] { + let pair = |a: f32, b: f32| u64::from(a.to_bits()) | u64::from(b.to_bits()) << 32; + [ + self.colour, + self.depth, + self.motion, + self.exposure, + self.output, + u64::from(self.render[0]) | u64::from(self.render[1]) << 32, + pair(self.jitter[0], self.jitter[1]), + pair(self.motion_scale[0], self.motion_scale[1]), + pair(self.pre_exposure, self.frame_ms), + pair(self.near, self.far), + u64::from(self.reset) | u64::from(self.dlss) << 1, + ] + } + + pub(crate) fn from_words(w: &[u64]) -> Option { + if w.len() < Self::WORDS { + return None; + } + let pair = |v: u64| [f32::from_bits(v as u32), f32::from_bits((v >> 32) as u32)]; + let [pre_exposure, frame_ms] = pair(w[8]); + let [near, far] = pair(w[9]); + Some(Self { + colour: w[0], + depth: w[1], + motion: w[2], + exposure: w[3], + output: w[4], + render: [w[5] as u32, (w[5] >> 32) as u32], + jitter: pair(w[6]), + motion_scale: pair(w[7]), + pre_exposure, + frame_ms, + near, + far, + reset: w[10] & 1 != 0, + dlss: w[10] & 2 != 0, + }) + } +} + +/// The title's upscale in place of its own FidelityFX passes (slow translated +/// for 32-lane cards): DLSS if asked for and it can, else a plain stretch of +/// the colour input over the output (`crate::stretch`, from +/// CuteBooty/victory-8gb). With `VICTORY_THIN=1` it is written down with the +/// list's other calls and recorded by the thread that records them. False if +/// it could not be recorded or written down. +#[cfg(windows)] +pub fn upscale(this: *const std::ffi::c_void, up: &Upscale) -> bool { + let this: This = this.cast(); + if this.is_null() || up.colour == 0 || up.output == 0 { + return false; + } + if thin::on() { + return thin::upscale(this, up); + } + upscale_now(this, up) +} + +/// [`upscale`], recorded now on the host list behind `this`. +#[cfg(windows)] +pub(super) fn upscale_now(this: This, up: &Upscale) -> bool { + const SHADER_READ: u32 = 0x40; + const UNORDERED: u32 = 0x8; + let t = |a: u64| -> This { a as This }; + let (colour, output) = (t(up.colour), t(up.output)); + let mut done = false; + with_state(this, |list, state| { + let (Some(to), Some(from), Some(host)) = ( + crate::resource::host_resource(output), + crate::resource::host_resource(colour), + crate::host::host(), + ) else { + return; + }; + ensure_state(list, colour, SHADER_READ); + ensure_state(list, output, UNORDERED); + #[cfg(feature = "dlss")] + if up.dlss { + let input = |a: u64| { + let r = t(a); + crate::resource::host_resource(r).inspect(|_| ensure_state(list, r, SHADER_READ)) + }; + let inputs = crate::dlss::Inputs { + colour: from, + depth: input(up.depth), + motion: input(up.motion), + exposure: input(up.exposure), + output: to, + jitter: up.jitter, + motion_scale: up.motion_scale, + render: up.render, + reset: up.reset, + pre_exposure: up.pre_exposure, + near: up.near, + far: up.far, + frame_ms: up.frame_ms, + }; + done = crate::dlss::record(&host.device, &list.list, &inputs); + if done { + // LOCAL (11/26): frame generation's depth and motion vectors (crate::fg). + crate::fg::note_titles(up.depth, up.motion); + } + } + if !done { + done = crate::stretch::record_stretch(&host.device, &list.list, to, from, up.render); + } + if done { + crate::texture::host_written(output); + } + state.replay(list); + }); + done +} + +/// For the upscale probe (`VICTORY_UPSCALE_PROBE=1`): each title texture's +/// host copy as `WxH fmt N` (DXGI format number), or `none`. +#[cfg(windows)] +pub fn upscale_inputs(textures: &[*const std::ffi::c_void]) -> Vec { + textures + .iter() + .map(|&t| match crate::resource::host_resource(t.cast()) { + Some(r) => { + // SAFETY: a live host resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} fmt {}", d.Width, d.Height, d.Format.0) + } + None => "none".to_owned(), + }) + .collect() +} + /// Moves a title texture's host copy to `state` in the list, if needed. #[cfg(windows)] pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index fe9277d..cfc7aab 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -469,6 +469,18 @@ const TARGETS: u64 = after(13); const CLEAR_RTV: u64 = after(14); const CLEAR_DSV: u64 = after(15); const COPY_TEXTURE: u64 = after(16); +const UPSCALE: u64 = after(17); + +/// Writes the title's upscale down with the list's calls (`super::upscale`); +/// false if the list has no recording being written. +pub(super) fn upscale(this: This, up: &super::Upscale) -> bool { + let front = front(this); + if front.closed || front.recording.is_none() { + return false; + } + front.put(UPSCALE, &(*up).to_words()); + true +} /// The bytes of `count` things at `items` (none if null). fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] { @@ -779,6 +791,14 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) at(w, 2 + 2 * step, boxed), ); } + UPSCALE => { + if let Some(up) = super::Upscale::from_words(w) + && !super::upscale_now(list, &up) + { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| tracing::warn!("a written-down upscale could not be recorded: its output stays as it is")); + } + } _ => {} } } diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index bd5c8bc..a900e6a 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -130,6 +130,7 @@ pub(crate) struct Translated { /// A compute program's threads in a group. pub(crate) threads: Option<[u32; 3]>, pub(crate) used: Vec, + pub(crate) tables: crate::draw::TablePlan, /// Whether the shader's code can store to buffer memory ([`stores`]); /// true when its code is not known. pub(crate) stores: bool, @@ -222,10 +223,12 @@ fn translate(container: &[u8]) -> Result { }) .map(|p| p.used) .unwrap_or_default(); + let tables = crate::draw::TablePlan::new(&used, &host.root_indexed_views); Ok(Translated { host, threads, used, + tables, stores, stores_by_address, picks: Default::default(), diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 0c8c21c..3ed2259 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -602,6 +602,7 @@ impl HostPipeline { slot == victory_shader::emit::SLOT_FAULTS } else { slot == victory_shader::emit::SLOT_STRIDES + || slot == victory_shader::emit::SLOT_TABLE_STRIDES || slot == victory_shader::emit::SLOT_MEMORY }; if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index a22e80c..979a223 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -41,8 +41,13 @@ pub(crate) struct Pending { /// whether a draw or dispatch has requested it yet. key: String, used: AtomicBool, - /// A pass over the screen ([`GraphicsState::screen_pass`]). + /// A pass over the screen ([`GraphicsState::screen_pass`]) or a confirmed + /// opening-scene / bake producer that must never sit behind cold RT shaders. screen: bool, + /// Confirmed first-scene / bake producer prepared early even on a cold cache. + scene_input: bool, + /// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH). + left_out: Option<&'static str>, /// LOCAL: how long draws have waited for it so far, in microseconds /// ([`wait_once`]). waited_us: AtomicU64, @@ -53,6 +58,56 @@ pub(crate) struct Pending { variant: OnceLock>, } +fn named(shaders: &[Arc], name: &[u8]) -> bool { + shaders + .iter() + .any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name)) +} + +fn left_out(shaders: &[Arc]) -> Option<&'static str> { + static SKIP_RT_RESOLVE: OnceLock = OnceLock::new(); + let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return false; + } + // Without BVH, ~1,000 CS_RaytracingResolve shaders shade no hits while + // clogging the cold compiler queue; skip unless VICTORY_RT_RESOLVE=1. + std::env::var_os("VICTORY_RT_RESOLVE").is_none_or(|v| v == "0") + }); + if skip_rt && named(shaders, b"CS_RaytracingResolve") { + return Some("shades ray-tracing hits without BVH, left out"); + } + static SKIP_ACTIVATE_RAYS: OnceLock = OnceLock::new(); + let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| { + let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1"); + if builder { + return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0"); + } + std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0") + }); + if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") { + return Some("ray activation shader without BVH, left out"); + } + None +} + +/// Confirmed first-scene producers. Prepare these at creation even on a cold +/// launch so cutscene lighting, tiling, and bakes never miss their first frame. +fn scene_input(shaders: &[Arc]) -> bool { + shaders.iter().any(|s| { + matches!( + s.hash.as_str(), + "970c4fbb3b017c0e" + | "068c90badc86f1fd" + | "e4a7e088c7780ce8" + | "ebe4e53f031f5249" + | "2cc4c197ee29e291" + | "369cbe906ea72764" + ) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str()) + }) +} + // SAFETY: D3D12 objects are free-threaded; the graphics state (whose input // elements point into its own names) is only read after creation. unsafe impl Send for Pending {} @@ -67,10 +122,17 @@ impl Pending { key.update(s.hash.as_bytes()); } key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + let scene_input = scene_input(&shaders); + let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass()) + && shaders.iter().all(|s| s.stage != "mesh")) + || scene_input; + let left_out = left_out(&shaders); Pending { + screen, + scene_input, + left_out, formats: graphics.as_ref().map_or([0; 9], |g| g.formats()), variant: OnceLock::new(), - screen: graphics.as_ref().is_some_and(|g| g.screen_pass()), shaders, graphics, queue_state: AtomicU8::new(NOT_QUEUED), @@ -216,6 +278,9 @@ fn variant<'a>(p: &'a Arc, g: &GraphicsState, bound: &TargetFormats) -> /// The host pipeline if it is made (or is made within the frame's budget); /// queues it on first use. pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + if p.left_out.is_some() { + return None; + } // A still-pending pipeline was requested by the title too. Prewarm it // on the next launch, even if this run never got to use it. if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { @@ -231,16 +296,23 @@ pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { /// Makes `p` on this thread if it is not made yet (waiting for a worker /// that is making it); whether it has a host pipeline. pub(crate) fn now(p: &Arc) -> bool { + if p.left_out.is_some() { + return false; + } p.make(); p.made.get().is_some_and(|made| made.is_some()) } /// At the title's creation of a pipeline: starts it at once if an earlier -/// run drew with it (during loading, so the world's first frames find it). +/// run drew with it (during loading, so the world's first frames find it), +/// or if it is a confirmed opening-scene / bake producer. pub(crate) fn early(p: &Arc) { - if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + if p.left_out.is_some() { + return; + } + if !p.shaders.is_empty() && (p.scene_input || super::library::wanted_early(&p.key)) { super::library::EARLY.fetch_add(1, Ordering::Relaxed); - start(p, EARLY); + start(p, if p.scene_input { REQUESTED } else { EARLY }); } } @@ -492,8 +564,13 @@ fn next(screens_only: bool) -> Arc { /// 64), else two thirds of the logical processors, 2 to 16. They run below the /// title's own threads, and a cold cache queues hundreds at once. fn worker_count(asked: Option, processors: usize) -> usize { + worker_count_for(asked, processors, false) +} + +fn worker_count_for(asked: Option, processors: usize, limited_ram: bool) -> usize { match asked { Some(n) => n.clamp(1, 64), + None if limited_ram => (processors * 3 / 4).clamp(2, 8), None => (processors * 2 / 3).clamp(2, 16), } } @@ -503,11 +580,12 @@ fn workers() -> bool { static RUNNING: OnceLock = OnceLock::new(); *RUNNING.get_or_init(|| { let mut running = false; - let workers = worker_count( + let workers = worker_count_for( std::env::var("VICTORY_PIPELINE_WORKERS") .ok() .and_then(|v| v.trim().parse().ok()), std::thread::available_parallelism().map_or(2, |n| n.get()), + crate::residency::limited_host_ram(), ); tracing::info!(workers, "pipeline workers"); let screens = if screens_first() { SCREEN_WORKERS } else { 0 }; @@ -580,6 +658,10 @@ mod tests { assert_eq!(worker_count(None, 64), 16); assert_eq!(worker_count(Some(0), 24), 1); assert_eq!(worker_count(Some(20), 24), 20); + assert_eq!(worker_count_for(None, 8, true), 6); + assert_eq!(worker_count_for(None, 16, true), 8); + assert_eq!(worker_count_for(None, 24, true), 8); + assert_eq!(worker_count_for(Some(12), 8, true), 12); } /// A first use queues the pipeline and, within the budget, gets the diff --git a/crates/victory-gpu/src/pool.rs b/crates/victory-gpu/src/pool.rs index 4d6a92d..cde4cdb 100644 --- a/crates/victory-gpu/src/pool.rs +++ b/crates/victory-gpu/src/pool.rs @@ -42,7 +42,25 @@ static SPARES: AtomicUsize = AtomicUsize::new(SPARE); /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`]. /// Asked once a second. pub(crate) fn room(memory: Option<[u64; 4]>) { - SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed); + let pressure = crate::residency::pressured(); + let limit = spares(memory, crate::host::keep_freed() && !pressure); + SPARES.store(limit, Ordering::Relaxed); + let tick = now(); + // A full pool can become idle while another subsystem needs the VRAM. + // A busy allocator observes the new limit on its next allocation or tick. + if let Ok(mut pool) = TEXTURES.try_lock() { + pool.reclaim(tick, limit, true); + } + if let Ok(mut pool) = STAGING.try_lock() { + let staging_limit = if crate::residency::critical_commit() { + 0 + } else if pressure { + 1 + } else { + limit + }; + pool.reclaim(tick, staging_limit, true); + } } fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize { @@ -180,11 +198,12 @@ struct Pool { /// The empty blocks it was last told to keep, and the most it keeps. spare: usize, most: usize, + retry_growth_at: u64, } impl Pool { const fn new(most: usize) -> Pool { - Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most } + Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 } } /// A piece of `len` bytes and the memory it lies in, and whether that @@ -226,10 +245,13 @@ impl Pool { unripe.sort_unstable(); found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?))); } + // A failed 64 MiB block must not trigger another driver call for each + // small texture. Existing free ranges remain usable during backoff. let (i, start) = match found { Some(found) => found, None => { - let i = self.add(make()?, ripe.started); + let memory = self.grow(now, &mut make)?; + let i = self.add(memory, ripe.started); (i, self.blocks[i].as_mut()?.free.take(len, align)?) } }; @@ -242,7 +264,7 @@ impl Pool { } let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count(); if empty < ripe.ahead - && let Some(memory) = make() + && let Some(memory) = self.grow(now, &mut make) { self.add(memory, ripe.started); } @@ -253,6 +275,17 @@ impl Pool { Some((Piece { block: i, start, len }, block.memory.clone(), again)) } + fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option) -> Option { + if now < self.retry_growth_at { + return None; + } + let block = make(); + if block.is_none() { + self.retry_growth_at = now.saturating_add(500); + } + block + } + fn add(&mut self, memory: B, made: u64) -> usize { let i = match self.blocks.iter().position(Option::is_none) { Some(i) => i, @@ -272,6 +305,10 @@ impl Pool { /// Makes the pieces that rested long enough free, and lets go of empty /// blocks past [`SPARE`]. fn rested(&mut self, now: u64) { + self.reclaim(now, SPARES.load(Ordering::Relaxed), false); + } + + fn reclaim(&mut self, now: u64, limit: usize, sweep: bool) { let mut any = false; while let Some(&(ready, piece)) = self.resting.front() && ready <= now @@ -283,9 +320,9 @@ impl Pool { } } // (Without a piece given back too, once there is less room.) - let most = SPARES.load(Ordering::Relaxed).min(self.most); - if any || most < self.spare { - self.spare = most; + let most = limit.min(self.most); + let previous = std::mem::replace(&mut self.spare, most); + if sweep || any || most < previous { let mut spare = 0; for block in &mut self.blocks { if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) { @@ -349,6 +386,13 @@ pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPi // Copies from a buffer begin at multiples of 512. let bytes = bytes.next_multiple_of(512); let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || { + // Only gate speculative bindless prefetch on staging-pool growth + // headroom; table-bound textures and decoration bakes are sampled + // immediately and would otherwise read uninitialized/reused VRAM. + let speculative = crate::texture::PICKING.get().is_some() && !crate::texture::BAKING.get(); + if speculative && !crate::residency::allow_staging_growth(false) { + return None; + } let (buffer, data) = host.upload_buffer(BLOCK)?; crate::host::name(&buffer, || "staging of textures (a block)".into()); Some(Upload(buffer, data)) @@ -488,6 +532,7 @@ pub(crate) unsafe fn texture( let mut heap: Option = None; // SAFETY: plain creation. if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, "no block of texture memory"); } if let Some(h) = &heap @@ -560,6 +605,40 @@ mod tests { assert_eq!(spares(None, true), SPARE); } + #[test] + fn a_failed_block_is_not_retried_for_each_small_upload() { + let mut pool: Pool = Pool::new(2); + let calls = std::cell::Cell::new(0); + let refuse = || { calls.set(calls.get() + 1); None }; + for size in [704008, 179720, 179720, 24080, 48648, 524288, 89616, 351760] { + assert!(pool.take(size, 512, 12, refuse).is_none()); + } + assert_eq!(calls.get(), 1); + assert!(pool.take(24080, 512, 1012, || Some(1)).is_some()); + } + + #[test] + fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() { + let mut pool = Pool::new(STAGING_KEPT); + let (held, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(1)).unwrap(); + let (resting, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(2)).unwrap(); + pool.give(resting, 0); + for i in 0..12 { + pool.add(i, 0); + } + pool.reclaim(0, SPARE_KEPT, true); + assert_eq!(pool.blocks(), STAGING_KEPT + 1); + pool.reclaim(REST - 1, SPARE, true); + assert_eq!(pool.blocks(), SPARE + 1); + assert_eq!(pool.resting.len(), 1); + pool.reclaim(REST, 0, true); + assert_eq!(pool.blocks(), 1); + assert!(pool.resting.is_empty()); + pool.give(held, REST); + pool.reclaim(2 * REST, 0, true); + assert_eq!(pool.blocks(), 0); + } + #[test] fn pieces_never_overlap_and_rest_before_they_are_used_again() { let mut pool: Pool = Pool::new(SPARE); diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index 0dc2f38..2a908ec 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -651,6 +651,42 @@ pub(crate) struct Plane { count: u32, resources: *const This, } +/// Retail PresentX adds source-rectangle and destination pointers, a color +/// space and seven option words after the common prefix. Older callers pass +/// only the prefix for single-plane presents. +#[cfg(windows)] +#[repr(C)] +struct RetailPlane { + prefix: Plane, + source_rects: *const (), + destination: *const (), + color_space: u32, + options: [u32; 7], +} +#[cfg(windows)] +const _: () = assert!(size_of::() == 72); + +#[cfg(windows)] +fn overlay_resource(parameters: *const Plane) -> Option { + // Read only the second prefix at the 72-byte retail PresentX stride. A + // caller using a different layout can still present its base plane safely. + let second = parameters.cast::().wrapping_add(1).cast::(); + let mut prefix = [0; size_of::()]; + if !crate::host::read_into(second, &mut prefix) { + return None; + } + // SAFETY: the prefix has the C layout above and its bytes were copied. + let plane = unsafe { prefix.as_ptr().cast::().read_unaligned() }; + let mut pointer = [0; size_of::()]; + if plane.count == 0 + || plane.resources.is_null() + || !crate::host::read_into(plane.resources.cast(), &mut pointer) + { + return None; + } + let resource = usize::from_ne_bytes(pointer) as This; + crate::resource::is_resource(resource).then_some(resource) +} /// Submission tagged with the frame it belongs to `(count, lists, frame /// token, flags)`; frames are paced elsewhere, so it runs as a plain one. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { @@ -801,6 +837,8 @@ impl Written { } else { at.cast::().write_unaligned(value); } + #[cfg(windows)] + windows_sys::Win32::System::Threading::WakeByAddressAll(at.cast()); } } } @@ -924,21 +962,21 @@ extern "system" fn present( crate::capture::dump_targets(frame); } } - #[cfg(all(windows, feature = "diagnostics"))] - note_planes(planes, plane_parameters); #[cfg(windows)] if behind::on() && !this.is_null() { const COPY_SOURCE: u32 = 0x800; - let texture = if planes > 0 + let base_res = if planes > 0 // SAFETY: the title passes `planes` plane descriptions. && let Some(plane) = unsafe { plane_parameters.as_ref() } && plane.count > 0 && !plane.resources.is_null() { // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources }; - // The state the lists recorded so far leave it in (the next - // frame's, recorded before this is shown, go on from there). + Some(unsafe { *plane.resources }) + } else { + None + }; + let take_copy = |resource: This| { crate::resource::host_copy(resource).map(|copy| { let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); crate::resource::host_transition(resource, state); @@ -947,14 +985,20 @@ extern "system" fn present( let state = if crate::list::thin::wanted() { u32::MAX } else { state }; (resource as usize, copy, state) }) - } else { - None }; + let texture = base_res.and_then(take_copy); + let overlay = (planes > 1 && !plane_parameters.is_null()) + .then(|| overlay_resource(plane_parameters)) + .flatten() + .filter(|&over_res| base_res != Some(over_res)) + .and_then(take_copy); let resource = texture.as_ref().map_or(0, |t| t.0); - // LOCAL (port of fxceless #1189): the interface plane, as the first. - let over = second_plane(planes, plane_parameters, resource as This) - .map(|(copy, state)| (copy, if crate::list::thin::wanted() { u32::MAX } else { state })); - behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource, over }); + behind::present( + this, + texture.map(|(_, copy, state)| (copy, state)), + overlay.map(|(_, copy, state)| (copy, state)), + Shown { frame, resource }, + ); called.end(); #[cfg(feature = "diagnostics")] frame_ends(); @@ -974,9 +1018,27 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - let over = second_plane(planes, plane_parameters, resource); - show(texture, state, Shown { frame, resource: resource as usize, over }); + let overlay = (planes > 1) + .then(|| overlay_resource(plane_parameters)) + .flatten() + .filter(|&over_res| over_res != resource) + .and_then(|over_res| { + crate::resource::host_resource(over_res).map(|over_tex| { + let over_state = crate::resource::host_transition(over_res, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + (over_res, over_tex, over_state) + }) + }); + show_planes( + texture, + state, + overlay.as_ref().map(|(_, tex, st)| (*tex, *st)), + Shown { frame, resource: resource as usize }, + ); crate::resource::host_transition(resource, state); + if let Some((over_res, _, over_state)) = overlay { + crate::resource::host_transition(over_res, over_state); + } let _ = host; } #[cfg(not(windows))] @@ -1001,104 +1063,24 @@ fn frame_ends() { /// The frame a present shows, and the title's resource it shows. #[cfg(windows)] -#[derive(Clone)] +#[derive(Clone, Copy)] struct Shown { frame: u64, resource: usize, - /// LOCAL (port of fxceless #1189): the second plane to lay over the - /// shown one, and its host state (`u32::MAX`: the state its lists left - /// it in when they ran). - over: Option<(std::sync::Arc, u32)>, } -/// LOCAL (port of fxceless #1189): a present's second plane, to be laid over -/// the first (`crate::compose`), with `VICTORY_COMPOSE=1`. Its host copy and -/// the host state the lists recorded so far leave it in (noted as before). -/// A Series S title presents two planes: the game and the interface -/// (menus, loading screens, the intro), 72-byte descriptions each. +/// Shows `texture` (with optional `overlay` plane blended over it) in our window. #[cfg(windows)] -fn second_plane(planes: u32, plane_parameters: *const Plane, first: This) -> Option<(std::sync::Arc, u32)> { - const STRIDE: usize = 72; - const COPY_SOURCE: u32 = 0x800; - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - let on = *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_COMPOSE").is_some_and(|v| v == "1"); - if on { - tracing::warn!("LOCAL present planes: a second plane is laid over the first (VICTORY_COMPOSE=1)"); - } - on - }); - if !on || planes < 2 || plane_parameters.is_null() { - return None; - } - // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. - let plane = unsafe { plane_parameters.cast::().add(STRIDE).cast::().as_ref() }?; - if plane.count == 0 || plane.resources.is_null() { - return None; - } - // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources }; - if resource == first { - return None; - } - let copy = crate::resource::host_copy(resource)?; - let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); - crate::resource::host_transition(resource, state); - Some((copy, state)) -} - -/// Diagnostics (LOCAL, from fxceless #1189): the planes a present asks for, -/// at presents 1, 2, 4, ... up to 4096 and whenever their number changes. -#[cfg(all(windows, feature = "diagnostics"))] -fn note_planes(planes: u32, plane_parameters: *const Plane) { - const STRIDE: usize = 72; - static LAST: AtomicU64 = AtomicU64::new(u64::MAX); - let frame = FRAMES.load(Ordering::Relaxed); - let changed = LAST.swap(u64::from(planes), Ordering::Relaxed) != u64::from(planes); - if !changed && !(frame.is_power_of_two() && frame <= 4096) { - return; - } - if plane_parameters.is_null() { - return; - } - for i in 0..planes.min(4) as usize { - // SAFETY: the title passes `planes` descriptions of `STRIDE` bytes. - let Some(plane) = (unsafe { plane_parameters.cast::().add(i * STRIDE).cast::().as_ref() }) else { - continue; - }; - if plane.resources.is_null() { - tracing::warn!(frame, planes, plane = i, count = plane.count, "present plane without resources"); - continue; - } - for k in 0..plane.count.min(2) as usize { - // SAFETY: the plane lists `count` resources. - let resource = unsafe { *plane.resources.add(k) }; - let desc = crate::resource::texture_memory(resource).map(|m| m.1); - tracing::warn!( - frame, - planes, - plane = i, - count = plane.count, - resource = ?resource, - hosted = crate::resource::host_copy(resource).is_some(), - desc = ?desc, - "present plane" - ); - } - } -} - -/// Shows `texture`, in host state `state`, in our window. -#[cfg(windows)] -fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) { +fn show_planes( + texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + overlay: Option<(&windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32)>, + what: Shown, +) { let Some(host) = crate::host::host() else { return; }; - let over = what.over.as_ref().map(|(t, s)| { - let s = if *s == u32::MAX { t.state.load(Ordering::Relaxed) } else { *s }; - (&t.texture, s) - }); - let shown = host.present_over(texture, state, over, what.frame); + let shown = host.present_planes(texture, state, overlay, what.frame); #[cfg(feature = "diagnostics")] blinks(what.frame, what.resource as This, state, shown); #[cfg(not(feature = "diagnostics"))] diff --git a/crates/victory-gpu/src/queue/behind.rs b/crates/victory-gpu/src/queue/behind.rs index b5624eb..813155c 100644 --- a/crates/victory-gpu/src/queue/behind.rs +++ b/crates/victory-gpu/src/queue/behind.rs @@ -391,8 +391,12 @@ enum Job { Joined(usize, Vec, Vec, Vec, Vec<(usize, u64)>), /// A signal of the queue's. Signal(usize, u64), - /// A frame is shown: the texture and the state its lists leave it in. - Present(Option<(std::sync::Arc, u32)>, super::Shown), + /// A frame is shown: the base texture (and optional overlay plane) and the states their lists leave them in. + Present( + Option<(std::sync::Arc, u32)>, + Option<(std::sync::Arc, u32)>, + super::Shown, + ), } // SAFETY: D3D12 objects are free-threaded; a job is touched by whoever put it @@ -569,12 +573,16 @@ impl Work for Job { crate::fence::set(fence as This, value); } } - Job::Present(texture, shown) => { + Job::Present(texture, overlay, shown) => { if let Some((texture, state)) = texture { // (Where its lists were not translated when the title // presented: the state they left it in.) let state = if state == u32::MAX { texture.state.load(Relaxed) } else { state }; - super::show(&texture.texture, state, shown); + let over = overlay.as_ref().map(|(ov, ov_state)| { + let st = if *ov_state == u32::MAX { ov.state.load(Relaxed) } else { *ov_state }; + (&ov.texture, st) + }); + super::show_planes(&texture.texture, state, over, shown); } QUEUED.fetch_sub(1, Relaxed); } @@ -811,10 +819,15 @@ pub(super) fn wait(this: This, fence: This, value: u64) { /// A present on queue `this` of `texture`, in the state the lists recorded so /// far leave it in. -pub(super) fn present(this: This, texture: Option<(std::sync::Arc, u32)>, shown: super::Shown) { +pub(super) fn present( + this: This, + texture: Option<(std::sync::Arc, u32)>, + overlay: Option<(std::sync::Arc, u32)>, + shown: super::Shown, +) { QUEUED.fetch_add(1, Relaxed); STATS[PRESENTS].fetch_add(1, Relaxed); - LANE.push(this as usize, [Job::Present(texture, shown)]); + LANE.push(this as usize, [Job::Present(texture, overlay, shown)]); let began = Instant::now(); let _waiting = crate::timeline::span("a present waits for the one before it to be sent"); LANE.wait_presents(frames_most()); diff --git a/crates/victory-gpu/src/residency.rs b/crates/victory-gpu/src/residency.rs new file mode 100644 index 0000000..0e701e5 --- /dev/null +++ b/crates/victory-gpu/src/residency.rs @@ -0,0 +1,201 @@ +//! Host-memory admission for speculative texture work and reusable upload storage. +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + +const MIB: u64 = 1 << 20; +const GIB: u64 = 1 << 30; +static PRESSURED: AtomicBool = AtomicBool::new(false); +static HEADROOM: AtomicU64 = AtomicU64::new(u64::MAX); + +fn memory_status() -> Option { + // SAFETY: the API initializes the fields of a correctly sized structure. + let mut status: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + status.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut status) } != 0).then_some(status) +} + +// The texture sweep may run for seconds inside a single submitted frame. +static NEXT_COMMIT_SAMPLE: AtomicU64 = AtomicU64::new(0); +static AVAILABLE_COMMIT: AtomicU64 = AtomicU64::new(u64::MAX); +static RETRY_UPLOAD_AT: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn allocation_error(error: &windows::core::Error) { + if error.code() == windows::Win32::Foundation::E_OUTOFMEMORY { + RETRY_UPLOAD_AT.fetch_max(crate::host::coarse_ms().saturating_add(500), Ordering::Relaxed); + } +} + +thread_local! { + static STAGING_DEFERRED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +pub(crate) fn note_staging_deferred() { + STAGING_DEFERRED.set(true); +} + +pub(crate) fn take_staging_deferred() -> bool { + STAGING_DEFERRED.replace(false) +} + +pub(crate) fn upload_refused() -> bool { + crate::host::coarse_ms() < RETRY_UPLOAD_AT.load(Ordering::Relaxed) +} + +fn sample_commit(now: u64) -> u64 { + let next = NEXT_COMMIT_SAMPLE.load(Ordering::Relaxed); + if now >= next + && NEXT_COMMIT_SAMPLE + .compare_exchange(next, now.saturating_add(32), Ordering::Relaxed, Ordering::Relaxed) + .is_ok() + && let Some(status) = memory_status() + { + AVAILABLE_COMMIT.store(status.ullAvailPageFile, Ordering::Relaxed); + } + AVAILABLE_COMMIT.load(Ordering::Relaxed) +} + +fn has_upload_reserve(commit: u64, bake: bool) -> bool { + // Keep a protective floor against Rust/game OOM aborts without starving + // bindless world textures or one-shot ped decoration bakes when steady-state + // commit headroom sits in the 1-4 GiB range on 32 GiB hosts. + commit >= if bake { 256 * MIB } else { 512 * MIB } +} + +fn has_growth_reserve(commit: u64, bake: bool) -> bool { + // Growing a fresh 64 MiB upload block for speculative bindless prefetch + // requires more headroom than reusing slices already committed inside the + // staging pool. + commit >= if bake { 256 * MIB } else { 1024 * MIB } +} + +/// Leave commit for game allocations and submissions already in flight while +/// still letting bindless textures and one-shot material bakes upload. +pub(crate) fn admit_texture_pass(bake: bool) -> bool { + let now = crate::host::coarse_ms(); + if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { + return false; + } + has_upload_reserve(sample_commit(now), bake) +} + +/// Whether the staging allocator may commit a brand-new OS upload buffer +/// (reusing existing free ranges in already-committed pool blocks stays open +/// whenever `admit_texture_pass` is true). +pub(crate) fn allow_staging_growth(bake: bool) -> bool { + let now = crate::host::coarse_ms(); + if now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) { + return false; + } + has_growth_reserve(sample_commit(now), bake) +} + +pub(crate) fn limited_host_ram() -> bool { + static LIMITED: OnceLock = OnceLock::new(); + *LIMITED.get_or_init(|| memory_status().is_some_and(|s| s.ullTotalPhys <= 32 * GIB)) +} + +fn next_pressure(was: bool, physical: u64, commit: u64) -> bool { + if was { + physical < 5 * GIB || commit < 6 * GIB + } else { + physical <= 3 * GIB || commit <= 4 * GIB + } +} + +/// Called by the once-per-second submission sweep. A failed sample keeps the last good state. +pub(crate) fn refresh() { + let Some(status) = memory_status() else { return }; + let (physical, commit) = (status.ullAvailPhys, status.ullAvailPageFile); + HEADROOM.store(physical.min(commit), Ordering::Relaxed); + let was = pressured(); + let pressure = next_pressure(was, physical, commit); + if pressure != was { + PRESSURED.store(pressure, Ordering::Relaxed); + if pressure { + tracing::warn!( + pid = std::process::id(), + frame = crate::frame::current(), + physical_free_mib = physical >> 20, + available_commit_mib = commit >> 20, + buffer_mirror_span_mib = crate::shadow::live_span_bytes() >> 20, + texture_staging_mib = crate::texture::live_staging_bytes() >> 20, + spare_scratch_mib = crate::host::ALIVE[4].load(Ordering::Relaxed) >> 20, + game_filled_gpu_texture_mib = crate::resource::KINDS[1].load(Ordering::Relaxed) >> 20, + "host memory pressure: limiting texture prefetch and idle upload storage" + ); + } else { + tracing::info!(physical_free_mib = physical >> 20, available_commit_mib = commit >> 20, "host memory pressure cleared"); + } + } +} + +pub(crate) fn headroom() -> Option { + let bytes = HEADROOM.load(Ordering::Relaxed); + (bytes != u64::MAX).then_some(bytes) +} + +pub(crate) fn pressured() -> bool { + PRESSURED.load(Ordering::Relaxed) +} + +/// True when OS commit headroom is critically low (< 1.5 GiB) or an allocation +/// just failed with `E_OUTOFMEMORY`, requiring emergency throttling. +pub(crate) fn critical_commit() -> bool { + let now = crate::host::coarse_ms(); + now < RETRY_UPLOAD_AT.load(Ordering::Relaxed) || sample_commit(now) < 1536 * MIB +} + +/// A soft per-frame admission limit. A single texture can cross it. The +/// queue retains unserved slots so they can be retried on later frames. +pub(crate) fn prefetch_limit(bytes: u64, pressure: bool, critical: bool, limited: bool, staging: u64) -> u64 { + if critical { + bytes.min(16 << 20) + } else if pressure || (limited && staging >= GIB) { + bytes.min(64 << 20) + } else { + bytes + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bake_and_lookahead_leave_room_for_live_game_allocations() { + for (commit, bake, lookahead, growth) in [ + (128 * MIB, false, false, false), + (256 * MIB, true, false, false), + (512 * MIB, true, true, false), + (768 * MIB, true, true, false), + (1024 * MIB, true, true, true), + ] { + assert_eq!(has_upload_reserve(commit, true), bake); + assert_eq!(has_upload_reserve(commit, false), lookahead); + assert_eq!(has_growth_reserve(commit, false), growth); + } + } + + #[test] + fn either_constraint_enters_pressure_and_both_must_recover() { + assert!(next_pressure(false, 12 * GIB, 4 * GIB)); + assert!(next_pressure(false, 3 * GIB, 16 * GIB)); + assert!(next_pressure(true, 4 * GIB, 7 * GIB)); + assert!(next_pressure(true, 6 * GIB, 5 * GIB)); + assert!(!next_pressure(true, 5 * GIB, 6 * GIB)); + assert!(!next_pressure(false, 4 * GIB, 5 * GIB)); + } + + #[test] + fn prefetch_respects_existing_budgets_and_resumes_after_recovery() { + assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB), 64 << 20); + assert_eq!(prefetch_limit(512 << 20, false, false, true, GIB - 1), 512 << 20); + assert_eq!(prefetch_limit(512 << 20, false, false, false, 2 * GIB), 512 << 20); + assert_eq!(prefetch_limit(0, true, true, false, 0), 0); + assert_eq!(prefetch_limit(8 << 20, true, true, false, 0), 8 << 20); + assert_eq!(prefetch_limit(512 << 20, true, false, false, 0), 64 << 20); + assert_eq!(prefetch_limit(512 << 20, true, true, false, 0), 16 << 20); + assert_eq!(prefetch_limit(192 << 20, false, false, false, 0), 192 << 20); + } +} diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 32ef56a..e6c8b65 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2379,6 +2379,14 @@ pub(crate) fn host_resource<'a>( Some(unsafe { &*std::ptr::from_ref(&host.texture) }) } +/// Whether `this` is a valid title resource created by this runtime. +#[cfg(windows)] +pub(crate) fn is_resource(this: This) -> bool { + let mut table = [0; size_of::()]; + crate::host::read_into(this.cast(), &mut table) + && usize::from_ne_bytes(table) == RESOURCE_FUNCTIONS.0.as_ptr() as usize +} + /// A title texture's host copy, shared, for a list to hold. #[cfg(windows)] pub(crate) fn host_copy(this: This) -> Option> { @@ -2525,6 +2533,7 @@ fn host_texture_as( } }; if let Err(e) = &made { + crate::residency::allocation_error(&e); tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); } if !reserved diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 43d1b76..14dc160 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -314,6 +314,12 @@ static CARDED: Mutex>> = Mutex::new(Vec::new()); /// bytes; the waits for the card the fetches added and their microseconds. pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +pub(crate) fn live_span_bytes() -> u64 { + CARD_BYTES[0].load(Ordering::Relaxed) + + WINDOW_CARD_BYTES.load(Ordering::Relaxed) + + WINDOW_MAPPED_BYTES.load(Ordering::Relaxed) +} + /// [`CARD_STATS`], taken; then the copies in the card's memory, their /// bytes and their "before" twins' bytes. pub(crate) fn card_stats() -> [u64; 10] { diff --git a/crates/victory-gpu/src/streamline.rs b/crates/victory-gpu/src/streamline.rs new file mode 100644 index 0000000..daf182b --- /dev/null +++ b/crates/victory-gpu/src/streamline.rs @@ -0,0 +1,2184 @@ +//! NVIDIA Streamline (SL) 2.14.16 FFI: DLSS Frame Generation (DLSS-G), Reflex and PC Latency (PCL). +//! +//! Hand-written mirrors of the SDK headers (`sl.h`, `sl_struct.h`, `sl_core_types.h`, +//! `sl_core_api.h`, `sl_consts.h`, `sl_dlss_g.h`, `sl_reflex.h`, `sl_pcl.h`, `sl_version.h`, +//! `sl_result.h`, `sl_appidentity.h`, `sl_device_wrappers.h`) plus a runtime loader for +//! `sl.interposer.dll`. Nothing links against `sl.interposer.lib`; every core entry point is +//! resolved with `GetProcAddress`, every feature entry point with `slGetFeatureFunction`. +//! Layouts are x64 MSVC and are checked by the `const` asserts at the bottom of the file. +//! +//! The headers mirrored here are NVIDIA's, published under the MIT licence +//! (github.com/NVIDIA-RTX/Streamline, `license.txt`), whose notice follows: +//! +//! ```text +//! Copyright (c) 2023 NVIDIA CORPORATION. All rights reserved +//! +//! Permission is hereby granted, free of charge, to any person obtaining a copy +//! of this software and associated documentation files (the "Software"), to deal +//! in the Software without restriction, including without limitation the rights +//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +//! copies of the Software, and to permit persons to whom the Software is +//! furnished to do so, subject to the following conditions: +//! +//! The above copyright notice and this permission notice shall be included in all +//! copies or substantial portions of the Software. +//! +//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +//! SOFTWARE. +//! ``` +//! +//! # Call sequence for a D3D12 app using MANUAL HOOKING with DLSS-G +//! +//! (from ProgrammingGuide.md, ProgrammingGuideManualHooking.md, ProgrammingGuideDLSS_G.md, +//! ProgrammingGuideReflex.md, ProgrammingGuidePCL.md, cross-checked against the interposer source) +//! +//! ## Start-up +//! +//! 1. `Sl::load(dir)` (LoadLibraryW of `\sl.interposer.dll` by full path). +//! 2. `slInit` before any hooked DXGI call can happen (before swap-chain creation). Not from +//! `DllMain`. With manual hooking the D3D12 device may be created before or after `slInit`. +//! * `flags = eDisableCLStateTracking | eUseManualHooking | eUseFrameBasedResourceTagging` +//! (`PreferenceFlags::MANUAL_HOOKING_FRAME_TAGS`). `eUseFrameBasedResourceTagging` is +//! required to use `slSetTagForFrame`. The C++ default also has `eAllowOTA | +//! eLoadDownloadedPlugins` (internet updates of SL/NGX); add them back if wanted. +//! * `featuresToLoad = [kFeatureDLSS_G, kFeatureReflex]` (`FG_FEATURES`). sl.dlss_g's manifest +//! lists `required_plugins: ["sl.common", "sl.reflex"]`. `sl.common` and `sl.pcl` are always +//! added by the plugin manager (`kFeatureCommon`, `kFeaturePCL`), they need not be listed. +//! Add `kFeatureDLSS` only if DLSS-SR is also driven through SL. +//! * `renderAPI = eD3D12`, `engine = eCustom`. +//! * App identity: without an NVIDIA application id, `applicationId = 0` makes SL use +//! `kTemporaryAppId` (100721531, `source/core/sl.api/internal.h`). In the signed +//! (SL_PRODUCTION) build sl.common then REFUSES to start NGX ("Please provide correct +//! application id ... NGX based features will be disabled") unless BOTH `engineVersion` and +//! `projectId` are non-empty, in which case it uses `NVSDK_NGX_D3D12_Init_with_ProjectID`. +//! DLSS-G is NGX-based, so set `engine = eCustom`, `engineVersion = c"..."` and +//! `projectId = c""` (see `commonEntry.cpp`, `hasProjectId`). +//! * `pathsToPlugins`: by default plugins are searched next to `sl.interposer.dll` itself +//! (`file::getModulePath()`), not next to the exe. Give an absolute path to override. +//! * Pass `sdkVersion = kSDKVersion`. +//! 3. Create the native `ID3D12Device`, then `slSetD3DDevice(nativeDevice)` "IMMEDIATELY after the +//! main device is created" (with manual hooking this is what initialises the plugins). +//! 4. `slIsFeatureSupported(kFeatureDLSS_G / kFeatureReflex / kFeaturePCL, AdapterInfo{LUID})`, +//! optionally `slGetFeatureRequirements` (OS/driver, `eHardwareSchedulingRequired`, ...). +//! 5. `Sl::resolve_feature_functions()` - `slGetFeatureFunction` only works AFTER the device is set. +//! 6. Proxies (sl_hooks.h list; everything NOT in that list must use native interfaces): +//! * `slUpgradeInterface(&device)` -> proxy `ID3D12Device`. Create the PRESENT queue through +//! the proxy (`eID3D12Device_CreateCommandQueue` is "Mandatory" and sl.dlss_g's embedded +//! manifest hooks `ID3D12Device::CreateCommandQueue`); the result is a proxy queue. The +//! interposer's factory proxy also accepts a native queue but logs "Detected base interface +//! 'ID3D12CommandQueue' while expecting SL proxy" when a plugin wants the proxy. +//! `ExecuteCommandLists` etc. may go to the native queue (`slGetNativeInterface`). +//! * `CreateDXGIFactory2` (native) then `slUpgradeInterface(&factory)` BEFORE +//! `CreateSwapChainForHwnd`; call `CreateSwapChainForHwnd(proxyQueue, ...)` on the PROXY +//! factory. The returned `IDXGISwapChain1` is the SL proxy (needs IDXGISwapChain3 support). +//! * Route `Present`, `Present1`, `GetBuffer`, `GetDesc`, `ResizeBuffers`, `ResizeBuffers1`, +//! `GetCurrentBackBufferIndex`, `SetFullscreenState` through the proxy swap chain; other +//! swap-chain calls may use `slGetNativeInterface(proxySwapChain)`. Calling +//! `GetCurrentBackBufferIndex` on the proxy is mandatory (`eFailGetCurrentBackBufferIndexNotCalled`). +//! With DLSS-G loaded the proxy's back buffers are off-screen copies owned by SL. +//! * Ref counts: `slUpgradeInterface` replaces the pointer in place with a NEW proxy object +//! (ref count 1) that AddRefs the base; the caller still owns its original native ref. +//! `slGetNativeInterface` returns an AddRef'd native pointer. +//! * Use native interfaces for NVAPI / 3rd party SDKs. +//! * Presenting through the proxy is also what makes sl.common's `presentCommon()` run once per +//! frame (garbage collection; memory grows across resizes if it does not run). +//! 7. `slReflexSetOptions(ReflexOptions{ mode: eLowLatency, .. })` at least once (even if Reflex is +//! "off"). DLSS-G reports `eFailReflexNotDetectedAtRuntime` when Reflex is not ACTIVE while +//! DLSS-G is on, so keep mode `eLowLatency`/`eLowLatencyWithBoost` while FG is on. +//! 8. `slDLSSGSetOptions(viewport, DLSSGOptions{ mode: eOn, numFramesToGenerate: 1, .. })`; +//! takes effect at the next `Present`; call it on the presenting thread. Loading the plugin +//! and tagging does NOT enable interpolation by itself. `numFramesToGenerate` (1 = 2x) must +//! be <= `DLSSGState::numFramesToGenerateMax` (from `slDLSSGGetState`). Recommended flag: +//! `eRetainResourcesWhenOff` (no realloc stutter when toggling off/on). +//! +//! ## Per frame (one `FrameToken`, one viewport; no `slEvaluateFeature` for DLSS-G - Present is the marker) +//! +//! 1. `slGetNewFrameToken(&token, Some(frameIndex))` where the simulation of the frame starts. +//! 2. `slReflexSleep(token)` (always, regardless of Reflex mode), then PCL markers with the same +//! token: `eSimulationStart` .. `eSimulationEnd`, `eRenderSubmitStart` .. `eRenderSubmitEnd`, +//! `ePresentStart` / proxy `Present` / `ePresentEnd`. The index on the present markers must be +//! the index of the frame being presented and match the one used for `slSetConstants` +//! (otherwise "common constants cannot be found for frame N"). Optional: `ePCLatencyPing` when +//! the `PCLState::statsWindowMessage` window message arrives, `eTriggerFlash` on left click. +//! 3. `slSetConstants(consts, token, viewport)` ONCE per frame, as early as possible. All +//! non-optional fields must be valid (defaults are `INVALID_FLOAT` / `Boolean::eInvalid`): +//! `cameraViewToClip`, `clipToCameraView`, `clipToPrevClip`, `prevClipToClip` (row-major, NO +//! jitter), `jitterOffset` (pixels), `mvecScale` (scales MV to [-1,1]; `1/renderWidth, +//! 1/renderHeight` for pixel-space MVs), `cameraPos/Up/Right/Fwd` (Up/Right/Fwd must be +//! orthonormal or auto scene-change detection disables itself), `cameraNear/Far/FOV(radians)/ +//! AspectRatio`, `depthInverted`, `cameraMotionIncluded`, `motionVectors3D`, `reset`. +//! Optional: `clipToLensClip`, `cameraPinholeOffset`, `motionVectorsInvalidValue` (only if +//! camera motion is not included). Invalid constants -> `eFailCommonConstantsInvalid`. +//! 4. `slSetTagForFrame(token, viewport, tags, cmdList)`: +//! * Required: `kBufferTypeDepth` (or `kBufferTypeLinearDepth`) and `kBufferTypeMotionVectors` +//! (dense: camera + object motion). The final colour comes from the proxy swap chain. +//! * Strongly recommended for UI quality: `kBufferTypeHUDLessColor` (same size / colour space / +//! post-processing as the back buffer, no UI) plus `kBufferTypeUIAlpha` (preferred) or +//! `kBufferTypeUIColorAndAlpha` (premultiplied; alpha precision > 2 bits). Sizes must +//! exactly match the back buffer (or its extent). +//! * `kBufferTypeBackbuffer` only to pass a sub-rect (resource pointer may be null). +//! * Lifecycle: tagged buffers are consumed during `Present`. If the resource is untouched +//! until Present use `eValidUntilPresent` (cmdList may be null; `Resource::state` must be +//! the state at Present time; SL keeps a reference until a null tag is set). If it will be +//! overwritten/reused before Present (typical when tagging on a command list right after +//! rendering a transient target) use `eOnlyValidNow` with that command list: SL records a +//! copy on it, `state` must be the state the resource is in ON THAT LIST at that point, and +//! the producing GPU work must already be on that list or on one executed before it. +//! NVIDIA advises trying `eValidUntilPresent` first (copies cost VRAM). +//! * Manual hooking: `Resource::state` (D3D12_RESOURCE_STATES) is mandatory - SL cannot track +//! it. No transitions are needed; SL restores states. +//! * Loading/menus/cut-scenes: set the tags to null (`resource = null`) and/or turn DLSS-G off. +//! 5. Viewport: an app-chosen integer (`ViewportHandle::new(0)`; the checklist says "Tag buffers +//! with unique id 0"); the SAME handle for constants, tags, `slDLSSGSetOptions/GetState`. +//! 6. Optionally `slDLSSGGetState(viewport, null options)` after Present: `status` must be `eOk` +//! (else turn FG off; an invalid FG draws a pink overlay), `numFramesActuallyPresented`, +//! `minWidthOrHeight` (FG must be off below it). Never pass `eRequestVRAMEstimate` per frame. +//! +//! ## Swap chain, resize, auto-disable +//! +//! * Docs do not prescribe a swap effect / buffer count / flags beyond D3D12's flip model and the +//! IDXGISwapChain3 requirement of the interposer proxy. `DLSSGOptions::numBackBuffers` is optional. +//! * Frame latency: SL's internal swap chain always uses +//! `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT`. If the app does NOT request that flag +//! (recommended) it must not call `GetFrameLatencyWaitableObject` / `SetMaximumFrameLatency` +//! (applies whenever sl.dlss_g is loaded, even with FG off); pace with `slReflexSleep` / +//! `ReflexOptions::frameLimitUs`. If it requests the flag it owns the waitable. +//! * HDR: only UINT10/RGB10 + HDR10/BT.2100. FP16 (R16G16B16A16_FLOAT) back buffers / scRGB are +//! NOT supported (`eFailHDRFormatNotSupported`). +//! * VSync: `SyncInterval` 0 or 1 only (D3D12), check `DLSSGState::bIsVsyncSupportAvailable`. +//! * Turn FG off (`mode = eOff`) before resizing, minimise/maximise, full-screen transitions or any +//! operation that could deadlock `Present` (FG presents on its own thread), and in pause/full +//! screen menus. Recreate the swap chain whenever FG is switched on/off (and use +//! `slSetFeatureLoaded(kFeatureDLSS_G, false)` + recreate to remove the off-screen copy and +//! queue sync overhead while off). `slSetFeatureLoaded` = unload/unhook, not on/off. +//! * Auto-off: `eAuto` mode disables FG when it would lower FPS; `eEnableFullscreenMenuDetection` +//! (needs `kBufferTypeUIColorAndAlpha`) turns it off in full-screen menus; FG is unusable when +//! a `DLSSGStatus` failure bit is set (resolution too low, Reflex not active, HDR format, +//! invalid constants, GetCurrentBackBufferIndex not called). +//! * OS: Windows 10 20H1 (build 19041+) and Hardware-accelerated GPU Scheduling ON. +//! * Multiple swap chains are not supported by DLSS-G; with manual hooking only the upgraded one +//! is attached. +//! * `slShutdown()` before releasing the DXGI/D3D12 objects. +//! +//! ## DLLs (all from `sdk\bin\x64`, same directory) +//! +//! `sl.interposer.dll`, `sl.common.dll` (mandatory), `sl.dlss_g.dll` + `nvngx_dlssg.dll`, +//! `sl.reflex.dll`, `sl.pcl.dll`. (`sl.dlss.dll` + `nvngx_dlss.dll` only for DLSS-SR, +//! `NvLowLatencyVk.dll` only for Vulkan.) `sdk\bin\x64\development` holds unsigned dev builds. +//! +//! ## Signatures +//! +//! The production `sl.interposer.dll` loads every plugin through `sl::security::loadLibrary`, +//! which under `SL_PRODUCTION` calls `verifyEmbeddedSignature` (WinVerifyTrust + NVIDIA's second +//! signature) on the plugin's full path and silently refuses unsigned modules. There is no +//! location check: NVIDIA-signed plugins load from any folder (next to the interposer or +//! `pathsToPlugins`). Mixing in the unsigned `development` plugins with the production +//! interposer will make them fail to load. The docs ask the HOST to verify the signature of +//! `sl.interposer.dll` before loading it; this module does not (that needs WinTrust bindings). +//! OTA-downloaded plugins are only loaded by production builds with `eLoadDownloadedPlugins`. + +#![allow( + dead_code, + non_snake_case, + non_camel_case_types, + non_upper_case_globals, + clippy::missing_safety_doc, + clippy::too_many_arguments +)] + +use core::ffi::{CStr, c_char, c_void}; +use core::ptr::{self, NonNull}; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, anyhow, bail}; +use windows::Win32::Foundation::HMODULE; +use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; +use windows::core::{PCSTR, PCWSTR}; + +// --------------------------------------------------------------------------------------------- +// Versions (sl_version.h, sl_struct.h) +// --------------------------------------------------------------------------------------------- + +pub const SL_VERSION_MAJOR: u64 = 2; +pub const SL_VERSION_MINOR: u64 = 14; +pub const SL_VERSION_PATCH: u64 = 16; +pub const kSDKVersionMagic: u64 = 0xfedc; +/// `sl::kSDKVersion`, the second argument of `slInit`. +pub const kSDKVersion: u64 = + (SL_VERSION_MAJOR << 48) | (SL_VERSION_MINOR << 32) | (SL_VERSION_PATCH << 16) | kSDKVersionMagic; + +pub const kStructVersion1: u32 = 1; +pub const kStructVersion2: u32 = 2; +pub const kStructVersion3: u32 = 3; +pub const kStructVersion4: u32 = 4; +pub const kStructVersion5: u32 = 5; +pub const kStructVersion6: u32 = 6; +pub const kStructVersion7: u32 = 7; + +/// What SL substitutes when `Preferences::applicationId == 0` +/// (`source/core/sl.api/internal.h`, `pluginManager.cpp`). Not in the public headers. Leaving +/// `applicationId` at 0 is equivalent to passing this; see the module docs for why +/// `engineVersion` + `projectId` must then be set for NGX features (DLSS-G) in production builds. +pub const kTemporaryAppId: u32 = 100721531; + +/// `sl::INVALID_FLOAT` (== FLT_MAX), the "not provided" value of the float defaults. +pub const INVALID_FLOAT: f32 = f32::MAX; +pub const INVALID_UINT: u32 = 0xffff_ffff; +pub const MAX_FRAMES_IN_FLIGHT: u32 = 6; + +pub const INTERPOSER_DLL: &str = "sl.interposer.dll"; + +/// DLLs that must sit next to `sl.interposer.dll` (or in `pathsToPlugins`) for DLSS-G + Reflex. +pub const FG_DLLS: [&str; 6] = [ + "sl.interposer.dll", + "sl.common.dll", + "sl.dlss_g.dll", + "nvngx_dlssg.dll", + "sl.reflex.dll", + "sl.pcl.dll", +]; + +// --------------------------------------------------------------------------------------------- +// StructType / BaseStructure (sl_struct.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::StructType` - a GUID. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct StructType { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +impl StructType { + pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Self { + Self { data1, data2, data3, data4 } + } +} + +/// `sl::BaseStructure`: `BaseStructure* next{}; StructType structType{}; size_t structVersion;` +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct BaseStructure { + pub next: *mut BaseStructure, + pub structType: StructType, + pub structVersion: usize, +} + +impl BaseStructure { + pub const fn new(structType: StructType, structVersion: u32) -> Self { + Self { next: ptr::null_mut(), structType, structVersion: structVersion as usize } + } +} + +/// `SL_STRUCT_BEGIN(name, guid, version)`: the GUID / version constants plus helpers. Every +/// struct using it has `base: BaseStructure` as its first field. +macro_rules! sl_struct { + ($name:ident, $guid:expr, $version:expr) => { + impl $name { + pub const STRUCT_TYPE: StructType = $guid; + pub const STRUCT_VERSION: u32 = $version; + /// Header exactly as the C++ constructor fills it (next = null). + #[inline] + pub const fn header() -> BaseStructure { + BaseStructure::new(Self::STRUCT_TYPE, Self::STRUCT_VERSION) + } + /// For `next` chains and `slEvaluateFeature` inputs. + #[inline] + pub fn as_base(&self) -> *const BaseStructure { + (self as *const Self).cast() + } + #[inline] + pub fn as_base_mut(&mut self) -> *mut BaseStructure { + (self as *mut Self).cast() + } + } + }; +} + +/// A C/C++ enum as a transparent integer (an FFI-returned value outside the known set must not +/// be UB, so these are newtypes rather than Rust enums). +macro_rules! c_enum { + ($(#[$m:meta])* $name:ident : $repr:ty { $($(#[$vm:meta])* $variant:ident = $value:expr),* $(,)? }) => { + $(#[$m])* + #[repr(transparent)] + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] + pub struct $name(pub $repr); + impl $name { + $($(#[$vm])* pub const $variant: Self = Self($value);)* + } + }; +} + +/// A `c_enum!` that is used as a bit set (`SL_ENUM_OPERATORS_32/64`). +macro_rules! c_flags { + ($name:ident : $repr:ty) => { + impl $name { + #[inline] + pub const fn bits(self) -> $repr { + self.0 + } + #[inline] + pub const fn contains(self, other: Self) -> bool { + (self.0 & other.0) == other.0 + } + #[inline] + pub const fn intersects(self, other: Self) -> bool { + (self.0 & other.0) != 0 + } + #[inline] + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } + } + impl core::ops::BitOr for $name { + type Output = Self; + fn bitor(self, rhs: Self) -> Self { + Self(self.0 | rhs.0) + } + } + impl core::ops::BitOrAssign for $name { + fn bitor_assign(&mut self, rhs: Self) { + self.0 |= rhs.0; + } + } + impl core::ops::BitAnd for $name { + type Output = Self; + fn bitand(self, rhs: Self) -> Self { + Self(self.0 & rhs.0) + } + } + impl core::ops::Not for $name { + type Output = Self; + fn not(self) -> Self { + Self(!self.0) + } + } + }; +} + +// --------------------------------------------------------------------------------------------- +// Result (sl_result.h) - `enum class Result` (no underlying type => int) +// --------------------------------------------------------------------------------------------- + +/// `sl::Result`. +#[repr(transparent)] +#[must_use] +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct SlResult(pub i32); + +const RESULT_NAMES: [&str; 40] = [ + "eOk", + "eErrorIO", + "eErrorDriverOutOfDate", + "eErrorOSOutOfDate", + "eErrorOSDisabledHWS", + "eErrorDeviceNotCreated", + "eErrorNoSupportedAdapterFound", + "eErrorAdapterNotSupported", + "eErrorNoPlugins", + "eErrorVulkanAPI", + "eErrorDXGIAPI", + "eErrorD3DAPI", + "eErrorNRDAPI", + "eErrorNVAPI", + "eErrorReflexAPI", + "eErrorNGXFailed", + "eErrorJSONParsing", + "eErrorMissingProxy", + "eErrorMissingResourceState", + "eErrorInvalidIntegration", + "eErrorMissingInputParameter", + "eErrorNotInitialized", + "eErrorComputeFailed", + "eErrorInitNotCalled", + "eErrorExceptionHandler", + "eErrorInvalidParameter", + "eErrorMissingConstants", + "eErrorDuplicatedConstants", + "eErrorMissingOrInvalidAPI", + "eErrorCommonConstantsMissing", + "eErrorUnsupportedInterface", + "eErrorFeatureMissing", + "eErrorFeatureNotSupported", + "eErrorFeatureMissingHooks", + "eErrorFeatureFailedToLoad", + "eErrorFeatureWrongPriority", + "eErrorFeatureMissingDependency", + "eErrorFeatureManagerInvalidState", + "eErrorInvalidState", + "eWarnOutOfVRAM", +]; + +impl SlResult { + pub const eOk: Self = Self(0); + pub const eErrorIO: Self = Self(1); + pub const eErrorDriverOutOfDate: Self = Self(2); + pub const eErrorOSOutOfDate: Self = Self(3); + pub const eErrorOSDisabledHWS: Self = Self(4); + pub const eErrorDeviceNotCreated: Self = Self(5); + pub const eErrorNoSupportedAdapterFound: Self = Self(6); + pub const eErrorAdapterNotSupported: Self = Self(7); + pub const eErrorNoPlugins: Self = Self(8); + pub const eErrorVulkanAPI: Self = Self(9); + pub const eErrorDXGIAPI: Self = Self(10); + pub const eErrorD3DAPI: Self = Self(11); + pub const eErrorNRDAPI: Self = Self(12); + pub const eErrorNVAPI: Self = Self(13); + pub const eErrorReflexAPI: Self = Self(14); + pub const eErrorNGXFailed: Self = Self(15); + pub const eErrorJSONParsing: Self = Self(16); + pub const eErrorMissingProxy: Self = Self(17); + pub const eErrorMissingResourceState: Self = Self(18); + pub const eErrorInvalidIntegration: Self = Self(19); + pub const eErrorMissingInputParameter: Self = Self(20); + pub const eErrorNotInitialized: Self = Self(21); + pub const eErrorComputeFailed: Self = Self(22); + pub const eErrorInitNotCalled: Self = Self(23); + pub const eErrorExceptionHandler: Self = Self(24); + pub const eErrorInvalidParameter: Self = Self(25); + pub const eErrorMissingConstants: Self = Self(26); + pub const eErrorDuplicatedConstants: Self = Self(27); + pub const eErrorMissingOrInvalidAPI: Self = Self(28); + pub const eErrorCommonConstantsMissing: Self = Self(29); + pub const eErrorUnsupportedInterface: Self = Self(30); + pub const eErrorFeatureMissing: Self = Self(31); + pub const eErrorFeatureNotSupported: Self = Self(32); + pub const eErrorFeatureMissingHooks: Self = Self(33); + pub const eErrorFeatureFailedToLoad: Self = Self(34); + pub const eErrorFeatureWrongPriority: Self = Self(35); + pub const eErrorFeatureMissingDependency: Self = Self(36); + pub const eErrorFeatureManagerInvalidState: Self = Self(37); + pub const eErrorInvalidState: Self = Self(38); + pub const eWarnOutOfVRAM: Self = Self(39); + + #[inline] + pub const fn is_ok(self) -> bool { + self.0 == 0 + } + #[inline] + pub fn ok(self) -> Result<(), SlResult> { + if self.is_ok() { Ok(()) } else { Err(self) } + } + pub fn name(self) -> &'static str { + usize::try_from(self.0) + .ok() + .and_then(|i| RESULT_NAMES.get(i).copied()) + .unwrap_or("") + } +} + +impl core::fmt::Debug for SlResult { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}({})", self.name(), self.0) + } +} + +impl core::fmt::Display for SlResult { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "sl::Result::{} ({})", self.name(), self.0) + } +} + +impl std::error::Error for SlResult {} + +/// Returned by the wrappers when an optional / feature function pointer was not resolved. +pub const MISSING_FUNCTION: SlResult = SlResult::eErrorMissingOrInvalidAPI; + +// --------------------------------------------------------------------------------------------- +// Ids and enums (sl_core_types.h, sl_consts.h, sl_appidentity.h, sl_device_wrappers.h) +// --------------------------------------------------------------------------------------------- + +/// `using Feature = uint32_t;` +pub type Feature = u32; +pub const kFeatureDLSS: Feature = 0; +pub const kFeatureNRD_INVALID: Feature = 1; +pub const kFeatureNIS: Feature = 2; +pub const kFeatureReflex: Feature = 3; +pub const kFeaturePCL: Feature = 4; +pub const kFeatureDeepDVC: Feature = 5; +pub const kFeatureLatewarp: Feature = 6; +pub const kFeatureDLSS_G: Feature = 1000; +pub const kFeatureDLSS_RR: Feature = 1001; +pub const kFeatureNvPerf: Feature = 1002; +pub const kFeatureDirectSR: Feature = 1003; +pub const kFeatureDLSS_NR: Feature = 1004; +pub const kFeatureImGUI: Feature = 9999; +/// sl.common (UINT_MAX), "NOT intended to be used directly"; always loaded. +pub const kFeatureCommon: Feature = u32::MAX; + +/// `featuresToLoad` for frame generation. sl.dlss_g requires sl.common + sl.reflex; sl.common and +/// sl.pcl are added by SL itself. +pub const FG_FEATURES: [Feature; 2] = [kFeatureDLSS_G, kFeatureReflex]; + +/// `using BufferType = uint32_t;` (subset; the header has 0..=72) +pub type BufferType = u32; +pub const kBufferTypeDepth: BufferType = 0; +pub const kBufferTypeMotionVectors: BufferType = 1; +pub const kBufferTypeHUDLessColor: BufferType = 2; +pub const kBufferTypeScalingInputColor: BufferType = 3; +pub const kBufferTypeScalingOutputColor: BufferType = 4; +pub const kBufferTypeExposure: BufferType = 13; +pub const kBufferTypeUIColorAndAlpha: BufferType = 23; +pub const kBufferTypeHiResDepth: BufferType = 48; +pub const kBufferTypeLinearDepth: BufferType = 49; +pub const kBufferTypeBidirectionalDistortionField: BufferType = 50; +pub const kBufferTypeBackbuffer: BufferType = 53; +pub const kBufferTypeNoWarpMask: BufferType = 54; +pub const kBufferTypeUIAlpha: BufferType = 69; + +c_enum! { + /// `enum class LogLevel : uint32_t` + LogLevel: u32 { eOff = 0, eDefault = 1, eVerbose = 2, eCount = 3 } +} + +c_enum! { + /// `enum class LogType : uint32_t` + LogType: u32 { eInfo = 0, eWarn = 1, eError = 2, eCount = 3 } +} + +c_enum! { + /// `enum class ResourceType : char` + ResourceType: u8 { + eTex2d = 0, + eBuffer = 1, + eCommandQueue = 2, + eCommandBuffer = 3, + eCommandPool = 4, + eFence = 5, + eSwapchain = 6, + eHostFence = 7, + eUnknown = 8, + eCount = 9, + } +} + +c_enum! { + /// `enum ResourceLifecycle` (unscoped, no fixed type => int) + ResourceLifecycle: i32 { eOnlyValidNow = 0, eValidUntilPresent = 1, eValidUntilEvaluate = 2 } +} + +c_enum! { + /// `enum Boolean : char` + Boolean: u8 { eFalse = 0, eTrue = 1, eInvalid = 2 } +} + +impl From for Boolean { + fn from(b: bool) -> Self { + if b { Self::eTrue } else { Self::eFalse } + } +} + +c_enum! { + /// `enum class PreferenceFlags : uint64_t` + PreferenceFlags: u64 { + eDisableCLStateTracking = 1 << 0, + eDisableDebugText = 1 << 1, + eUseManualHooking = 1 << 2, + eAllowOTA = 1 << 3, + eBypassOSVersionCheck = 1 << 4, + eUseDXGIFactoryProxy = 1 << 5, + eLoadDownloadedPlugins = 1 << 6, + eUseFrameBasedResourceTagging = 1 << 7, + eAll = 0xff, + } +} +c_flags!(PreferenceFlags: u64); + +impl PreferenceFlags { + /// The C++ default member initializer of `Preferences::flags`. + pub const DEFAULT: Self = Self( + Self::eDisableCLStateTracking.0 | Self::eAllowOTA.0 | Self::eLoadDownloadedPlugins.0, + ); + /// Manual hooking + `slSetTagForFrame` (no OTA). + pub const MANUAL_HOOKING_FRAME_TAGS: Self = Self( + Self::eDisableCLStateTracking.0 + | Self::eUseManualHooking.0 + | Self::eUseFrameBasedResourceTagging.0, + ); +} + +c_enum! { + /// `enum class EngineType : uint32_t` + EngineType: u32 { eCustom = 0, eUnreal = 1, eUnity = 2, eCount = 3 } +} + +c_enum! { + /// `enum class RenderAPI : uint32_t` + RenderAPI: u32 { eD3D11 = 0, eD3D12 = 1, eVulkan = 2, eCount = 3 } +} + +c_enum! { + /// `enum class FeatureRequirementFlags : uint32_t` + FeatureRequirementFlags: u32 { + eD3D11Supported = 1 << 0, + eD3D12Supported = 1 << 1, + eVulkanSupported = 1 << 2, + eVSyncOffRequired = 1 << 3, + eHardwareSchedulingRequired = 1 << 4, + eAll = 0x1f, + } +} +c_flags!(FeatureRequirementFlags: u32); + +// DLSS-G (sl_dlss_g.h) + +c_enum! { + /// `enum class DLSSGMode : uint32_t` + DLSSGMode: u32 { eOff = 0, eOn = 1, eAuto = 2, eDynamic = 3, eCount = 4 } +} + +c_enum! { + /// `enum class DLSSGFlags : uint32_t` + DLSSGFlags: u32 { + eShowOnlyInterpolatedFrame = 1 << 0, + eDynamicResolutionEnabled = 1 << 1, + eRequestVRAMEstimate = 1 << 2, + eRetainResourcesWhenOff = 1 << 3, + eEnableFullscreenMenuDetection = 1 << 4, + eAll = 0x1f, + } +} +c_flags!(DLSSGFlags: u32); + +c_enum! { + /// `enum class DLSSGQueueParallelismMode : uint32_t` (eBlockNoClientQueues is Vulkan-only) + DLSSGQueueParallelismMode: u32 { eBlockPresentingClientQueue = 0, eBlockNoClientQueues = 1, eCount = 2 } +} + +c_enum! { + /// `enum class DLSSGStatus : uint32_t` + DLSSGStatus: u32 { + eOk = 0, + eFailResolutionTooLow = 1 << 0, + eFailReflexNotDetectedAtRuntime = 1 << 1, + eFailHDRFormatNotSupported = 1 << 2, + eFailCommonConstantsInvalid = 1 << 3, + eFailGetCurrentBackBufferIndexNotCalled = 1 << 4, + eReserved5 = 1 << 5, + eAll = 0x3f, + } +} +c_flags!(DLSSGStatus: u32); + +// Reflex (sl_reflex.h) + +c_enum! { + /// `enum ReflexMode` (unscoped, no fixed type => int) + ReflexMode: i32 { eOff = 0, eLowLatency = 1, eLowLatencyWithBoost = 2, ReflexMode_eCount = 3 } +} + +pub const kReflexFrameReportCount: usize = 64; + +// PCL (sl_pcl.h) + +c_enum! { + /// `enum class PCLHotKey : int16_t` + PCLHotKey: i16 { eUsePingMessage = 0, eVK_F13 = 0x7C, eVK_F14 = 0x7D, eVK_F15 = 0x7E } +} + +c_enum! { + /// `enum class PCLMarker : uint32_t` + PCLMarker: u32 { + eSimulationStart = 0, + eSimulationEnd = 1, + eRenderSubmitStart = 2, + eRenderSubmitEnd = 3, + ePresentStart = 4, + ePresentEnd = 5, + // 6 = eInputSample, deprecated/removed + eTriggerFlash = 7, + ePCLatencyPing = 8, + eOutOfBandRenderSubmitStart = 9, + eOutOfBandRenderSubmitEnd = 10, + eOutOfBandPresentStart = 11, + eOutOfBandPresentEnd = 12, + eControllerInputSample = 13, + eDeltaTCalculation = 14, + eLateWarpPresentStart = 15, + eLateWarpPresentEnd = 16, + eCameraConstructed = 17, + eLateWarpRenderSubmitStart = 18, + eLateWarpRenderSubmitEnd = 19, + eVendorInternalAsyncPresentStart = 20, + eVendorInternalAsyncPresentEnd = 21, + eNumPresentsInBatch = 22, + eMaximum = 23, + } +} + +// --------------------------------------------------------------------------------------------- +// Math types (sl_consts.h) - default-constructed to INVALID_FLOAT like the C++ constructors +// --------------------------------------------------------------------------------------------- + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float2 { + pub x: f32, + pub y: f32, +} +impl float2 { + pub const fn new(x: f32, y: f32) -> Self { + Self { x, y } + } +} +impl Default for float2 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float3 { + pub x: f32, + pub y: f32, + pub z: f32, +} +impl float3 { + pub const fn new(x: f32, y: f32, z: f32) -> Self { + Self { x, y, z } + } +} +impl Default for float3 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct float4 { + pub x: f32, + pub y: f32, + pub z: f32, + pub w: f32, +} +impl float4 { + pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self { + Self { x, y, z, w } + } +} +impl Default for float4 { + fn default() -> Self { + Self::new(INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT, INVALID_FLOAT) + } +} + +/// Row-major 4x4 (`float4 row[4]`). +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct float4x4 { + pub row: [float4; 4], +} +impl float4x4 { + pub const fn from_rows(r: [[f32; 4]; 4]) -> Self { + Self { + row: [ + float4::new(r[0][0], r[0][1], r[0][2], r[0][3]), + float4::new(r[1][0], r[1][1], r[1][2], r[1][3]), + float4::new(r[2][0], r[2][1], r[2][2], r[2][3]), + float4::new(r[3][0], r[3][1], r[3][2], r[3][3]), + ], + } + } + pub const fn identity() -> Self { + Self::from_rows([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct uint2 { + pub x: u32, + pub y: u32, +} + +/// `sl::Extent { top, left, width, height }` (all zero = whole resource). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Extent { + pub top: u32, + pub left: u32, + pub width: u32, + pub height: u32, +} + +/// `sl::Version { major, minor, build }`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Version { + pub major: u32, + pub minor: u32, + pub build: u32, +} + +/// `struct APIError { union { HRESULT hres; SL_VKResult vkRes; }; }` (both 32-bit). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct APIError { + pub hres: i32, +} + +// --------------------------------------------------------------------------------------------- +// Callbacks +// --------------------------------------------------------------------------------------------- + +/// `Resource(const ResourceAllocationDesc* desc, void* device)` +pub type PFun_ResourceAllocateCallback = + unsafe extern "C" fn(desc: *const ResourceAllocationDesc, device: *mut c_void) -> Resource; +/// `void(Resource* resource, void* device)` +pub type PFun_ResourceReleaseCallback = unsafe extern "C" fn(resource: *mut Resource, device: *mut c_void); +/// `void(LogType type, const char* msg)` +pub type PFun_LogMessageCallback = unsafe extern "C" fn(ty: LogType, msg: *const c_char); +/// `void(const APIError& lastError)` - called on the present thread, must return quickly. +pub type PFunOnAPIErrorCallback = unsafe extern "C" fn(lastError: *const APIError); + +/// A ready-made `logMessageCallback` that forwards SL's log to `tracing`. +pub unsafe extern "C" fn log_to_tracing(ty: LogType, msg: *const c_char) { + if msg.is_null() { + return; + } + // SAFETY: SL passes a NUL-terminated string valid for the duration of the call. + let text = unsafe { CStr::from_ptr(msg) }.to_string_lossy(); + let text = text.trim_end(); + match ty { + LogType::eError => tracing::error!(target: "streamline", "{text}"), + LogType::eWarn => tracing::warn!(target: "streamline", "{text}"), + _ => tracing::info!(target: "streamline", "{text}"), + } +} + +// --------------------------------------------------------------------------------------------- +// Core structs (sl_core_types.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::Preferences` {1CA10965-BF8E-432B-8DA1-6716D879FB14}, kStructVersion1. All fields of the +/// 2.14.16 header, in order. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Preferences { + pub base: BaseStructure, + pub showConsole: bool, + pub logLevel: LogLevel, + /// `const wchar_t** pathsToPlugins` - absolute paths, first has highest priority. + pub pathsToPlugins: *const *const u16, + pub numPathsToPlugins: u32, + /// `const wchar_t*` - null disables file logging. + pub pathToLogsAndData: *const u16, + pub allocateCallback: Option, + pub releaseCallback: Option, + pub logMessageCallback: Option, + pub flags: PreferenceFlags, + pub featuresToLoad: *const Feature, + pub numFeaturesToLoad: u32, + pub applicationId: u32, + pub engine: EngineType, + pub engineVersion: *const c_char, + pub projectId: *const c_char, + pub renderAPI: RenderAPI, +} +sl_struct!( + Preferences, + StructType::new(0x1ca10965, 0xbf8e, 0x432b, [0x8d, 0xa1, 0x67, 0x16, 0xd8, 0x79, 0xfb, 0x14]), + kStructVersion1 +); +impl Default for Preferences { + fn default() -> Self { + Self { + base: Self::header(), + showConsole: false, + logLevel: LogLevel::eDefault, + pathsToPlugins: ptr::null(), + numPathsToPlugins: 0, + pathToLogsAndData: ptr::null(), + allocateCallback: None, + releaseCallback: None, + logMessageCallback: None, + flags: PreferenceFlags::DEFAULT, + featuresToLoad: ptr::null(), + numFeaturesToLoad: 0, + applicationId: 0, + engine: EngineType::eCustom, + engineVersion: ptr::null(), + projectId: ptr::null(), + renderAPI: RenderAPI::eD3D12, + } + } +} + +/// `sl::ResourceAllocationDesc` {00BB57E5-49A2-4C23-A519-AB9286E74014}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ResourceAllocationDesc { + pub base: BaseStructure, + pub r#type: ResourceType, + /// D3D12_RESOURCE_DESC* + pub desc: *mut c_void, + /// D3D12_RESOURCE_STATES + pub state: u32, + /// D3D12_HEAP_PROPERTIES* or null + pub heap: *mut c_void, +} +sl_struct!( + ResourceAllocationDesc, + StructType::new(0x00bb57e5, 0x49a2, 0x4c23, [0xa5, 0x19, 0xab, 0x92, 0x86, 0xe7, 0x40, 0x14]), + kStructVersion1 +); +impl Default for ResourceAllocationDesc { + fn default() -> Self { + Self { base: Self::header(), r#type: ResourceType::eTex2d, desc: ptr::null_mut(), state: 0, heap: ptr::null_mut() } + } +} + +/// `sl::Resource` {3A9D70CF-2418-4B72-8391-13F8721C7261}, kStructVersion1. +/// +/// For D3D12 only `type`, `native` and `state` are needed (state is MANDATORY with manual hooking). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Resource { + pub base: BaseStructure, + pub r#type: ResourceType, + /// ID3D12Resource* + pub native: *mut c_void, + /// Vulkan only + pub memory: *mut c_void, + /// Vulkan only + pub view: *mut c_void, + /// D3D12_RESOURCE_STATES (UINT_MAX = not provided) + pub state: u32, + pub width: u32, + pub height: u32, + pub nativeFormat: u32, + pub mipLevels: u32, + pub arrayLayers: u32, + pub gpuVirtualAddress: u64, + /// VkImageCreateFlags (no initializer in C++; zeroed here) + pub flags: u32, + pub usage: u32, + /// `enum InternalFlags : uint16_t` - do not modify + pub internalFlags: u16, + pub reserved: u16, +} +sl_struct!( + Resource, + StructType::new(0x3a9d70cf, 0x2418, 0x4b72, [0x83, 0x91, 0x13, 0xf8, 0x72, 0x1c, 0x72, 0x61]), + kStructVersion1 +); +impl Default for Resource { + fn default() -> Self { + Self { + base: Self::header(), + r#type: ResourceType::eTex2d, + native: ptr::null_mut(), + memory: ptr::null_mut(), + view: ptr::null_mut(), + state: u32::MAX, + width: 0, + height: 0, + nativeFormat: 0, + mipLevels: 0, + arrayLayers: 0, + gpuVirtualAddress: 0, + flags: 0, + usage: 0, + internalFlags: 0, + reserved: 0, + } + } +} +impl Resource { + /// `Resource(ResourceType::eTex2d, native, state)` for an `ID3D12Resource*`. + pub fn d3d12_tex2d(native: *mut c_void, state: u32) -> Self { + Self { native, state, ..Self::default() } + } +} + +/// `sl::ResourceTag` {4C6A5AAD-B445-496C-87FF-1AF3845BE653}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ResourceTag { + pub base: BaseStructure, + /// Null removes the tag (releases SL's reference for eValidUntilPresent). + pub resource: *mut Resource, + pub r#type: BufferType, + pub lifecycle: ResourceLifecycle, + /// All zero = whole resource. + pub extent: Extent, +} +sl_struct!( + ResourceTag, + StructType::new(0x4c6a5aad, 0xb445, 0x496c, [0x87, 0xff, 0x1a, 0xf3, 0x84, 0x5b, 0xe6, 0x53]), + kStructVersion1 +); +impl Default for ResourceTag { + fn default() -> Self { + Self { + base: Self::header(), + resource: ptr::null_mut(), + r#type: 0, + lifecycle: ResourceLifecycle::eOnlyValidNow, + extent: Extent::default(), + } + } +} +impl ResourceTag { + /// `ResourceTag(Resource* r, BufferType t, ResourceLifecycle l, const Extent* e = nullptr)` + pub fn new(resource: *mut Resource, ty: BufferType, lifecycle: ResourceLifecycle, extent: Option) -> Self { + Self { resource, r#type: ty, lifecycle, extent: extent.unwrap_or_default(), ..Self::default() } + } + /// A null tag for `ty` (removes it). + pub fn null(ty: BufferType) -> Self { + Self::new(ptr::null_mut(), ty, ResourceLifecycle::eValidUntilPresent, None) + } +} + +/// `sl::FrameToken` {830A0F35-DB84-4171-A804-59B206499B18}, kStructVersion1 - OPAQUE. +/// +/// It is an abstract C++ class (`virtual operator uint32_t() const = 0`), so the object starts +/// with a vtable pointer and is only ever handled by pointer, as obtained from +/// `slGetNewFrameToken`. SL owns it (a small ring of tokens). +#[repr(C)] +pub struct FrameToken { + _opaque: [u8; 0], + _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, +} +impl FrameToken { + pub const STRUCT_TYPE: StructType = + StructType::new(0x830a0f35, 0xdb84, 0x4171, [0xa8, 0x04, 0x59, 0xb2, 0x06, 0x49, 0x9b, 0x18]); + pub const STRUCT_VERSION: u32 = kStructVersion1; +} + +/// A frame token handle returned by [`Sl::new_frame_token`]. Copyable; the docs allow handing a +/// copy to other threads ("Store a copy of the handle and use that in any async tasks"). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Frame(NonNull); +// SAFETY: the token is SL-owned, immutable from our side and documented as usable from any thread. +unsafe impl Send for Frame {} +// SAFETY: as above. +unsafe impl Sync for Frame {} + +impl Frame { + #[inline] + pub fn as_ptr(self) -> *const FrameToken { + self.0.as_ptr() + } + + /// The frame index SL associates with the token (the C++ `operator uint32_t()`), read through + /// vtable slot 0 (MSVC x64: vfptr at offset 0, `this` in RCX, result in EAX). + /// + /// Prefer remembering the index you passed to `slGetNewFrameToken`. + pub unsafe fn sl_index(self) -> u32 { + type IndexFn = unsafe extern "C" fn(this: *const FrameToken) -> u32; + let this = self.as_ptr(); + // SAFETY: caller guarantees the token is alive (before slShutdown); slot 0 of the + // vtable of every FrameToken implementation is `operator uint32_t() const`. + unsafe { + let vtable = *(this as *const *const IndexFn); + (*vtable)(this) + } + } +} + +/// `sl::ViewportHandle` {171B6435-9B3C-4FC8-9994-FBE52569AAA4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ViewportHandle { + pub base: BaseStructure, + /// Private in C++; default UINT_MAX. + pub value: u32, +} +sl_struct!( + ViewportHandle, + StructType::new(0x171b6435, 0x9b3c, 0x4fc8, [0x99, 0x94, 0xfb, 0xe5, 0x25, 0x69, 0xaa, 0xa4]), + kStructVersion1 +); +impl ViewportHandle { + pub const fn new(value: u32) -> Self { + Self { base: Self::header(), value } + } +} +impl Default for ViewportHandle { + fn default() -> Self { + Self::new(u32::MAX) + } +} + +/// `sl::FeatureRequirements` {66714097-AC6D-4BC6-8915-1E0F55A6B61F}, kStructVersion2. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct FeatureRequirements { + pub base: BaseStructure, + pub flags: FeatureRequirementFlags, + pub maxNumCPUThreads: u32, + pub maxNumViewports: u32, + pub numRequiredTags: u32, + pub requiredTags: *const BufferType, + pub osVersionDetected: Version, + pub osVersionRequired: Version, + pub driverVersionDetected: Version, + pub driverVersionRequired: Version, + pub vkNumComputeQueuesRequired: u32, + pub vkNumGraphicsQueuesRequired: u32, + pub vkNumDeviceExtensions: u32, + pub vkDeviceExtensions: *const *const c_char, + pub vkNumInstanceExtensions: u32, + pub vkInstanceExtensions: *const *const c_char, + pub vkNumFeatures12: u32, + pub vkFeatures12: *const *const c_char, + pub vkNumFeatures13: u32, + pub vkFeatures13: *const *const c_char, + pub vkNumOpticalFlowQueuesRequired: u32, +} +sl_struct!( + FeatureRequirements, + StructType::new(0x66714097, 0xac6d, 0x4bc6, [0x89, 0x15, 0x1e, 0x0f, 0x55, 0xa6, 0xb6, 0x1f]), + kStructVersion2 +); +impl Default for FeatureRequirements { + fn default() -> Self { + Self { + base: Self::header(), + flags: FeatureRequirementFlags(0), + maxNumCPUThreads: 0, + maxNumViewports: 0, + numRequiredTags: 0, + requiredTags: ptr::null(), + osVersionDetected: Version::default(), + osVersionRequired: Version::default(), + driverVersionDetected: Version::default(), + driverVersionRequired: Version::default(), + vkNumComputeQueuesRequired: 0, + vkNumGraphicsQueuesRequired: 0, + vkNumDeviceExtensions: 0, + vkDeviceExtensions: ptr::null(), + vkNumInstanceExtensions: 0, + vkInstanceExtensions: ptr::null(), + vkNumFeatures12: 0, + vkFeatures12: ptr::null(), + vkNumFeatures13: 0, + vkFeatures13: ptr::null(), + vkNumOpticalFlowQueuesRequired: 0, + } + } +} +impl FeatureRequirements { + /// The required buffer tags (pointer owned by SL). + pub unsafe fn required_tags(&self) -> &[BufferType] { + if self.requiredTags.is_null() || self.numRequiredTags == 0 { + &[] + } else { + // SAFETY: SL guarantees `numRequiredTags` entries. + unsafe { core::slice::from_raw_parts(self.requiredTags, self.numRequiredTags as usize) } + } + } +} + +/// `sl::FeatureVersion` {6D5B51F0-076B-486D-9995-5A561043F5C1}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct FeatureVersion { + pub base: BaseStructure, + pub versionSL: Version, + pub versionNGX: Version, +} +sl_struct!( + FeatureVersion, + StructType::new(0x6d5b51f0, 0x076b, 0x486d, [0x99, 0x95, 0x5a, 0x56, 0x10, 0x43, 0xf5, 0xc1]), + kStructVersion1 +); +impl Default for FeatureVersion { + fn default() -> Self { + Self { base: Self::header(), versionSL: Version::default(), versionNGX: Version::default() } + } +} + +/// `sl::AdapterInfo` {0677315F-A746-4492-9F42-CB6142C9C3D4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct AdapterInfo { + pub base: BaseStructure, + /// Points at a `LUID` (DXGI_ADAPTER_DESC::AdapterLuid). + pub deviceLUID: *mut u8, + /// `sizeof(LUID)` = 8 + pub deviceLUIDSizeInBytes: u32, + pub vkPhysicalDevice: *mut c_void, +} +sl_struct!( + AdapterInfo, + StructType::new(0x0677315f, 0xa746, 0x4492, [0x9f, 0x42, 0xcb, 0x61, 0x42, 0xc9, 0xc3, 0xd4]), + kStructVersion1 +); +impl Default for AdapterInfo { + fn default() -> Self { + Self { base: Self::header(), deviceLUID: ptr::null_mut(), deviceLUIDSizeInBytes: 0, vkPhysicalDevice: ptr::null_mut() } + } +} + +// --------------------------------------------------------------------------------------------- +// Constants (sl_consts.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::Constants` {DCD35AD7-4E4A-4BAD-A90C-E0C49EB23AFE}, kStructVersion2. +/// Defaults match C++: every matrix/vector element INVALID_FLOAT. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct Constants { + pub base: BaseStructure, + pub cameraViewToClip: float4x4, + pub clipToCameraView: float4x4, + /// Optional + pub clipToLensClip: float4x4, + pub clipToPrevClip: float4x4, + pub prevClipToClip: float4x4, + /// Pixel space + pub jitterOffset: float2, + pub mvecScale: float2, + /// Optional + pub cameraPinholeOffset: float2, + pub cameraPos: float3, + pub cameraUp: float3, + pub cameraRight: float3, + pub cameraFwd: float3, + pub cameraNear: f32, + pub cameraFar: f32, + /// Radians + pub cameraFOV: f32, + pub cameraAspectRatio: f32, + /// Only needed if `cameraMotionIncluded` is false + pub motionVectorsInvalidValue: f32, + pub depthInverted: Boolean, + pub cameraMotionIncluded: Boolean, + pub motionVectors3D: Boolean, + pub reset: Boolean, + pub orthographicProjection: Boolean, + pub motionVectorsDilated: Boolean, + pub motionVectorsJittered: Boolean, + // Version 2 + pub minRelativeLinearDepthObjectSeparation: f32, +} +sl_struct!( + Constants, + StructType::new(0xdcd35ad7, 0x4e4a, 0x4bad, [0xa9, 0x0c, 0xe0, 0xc4, 0x9e, 0xb2, 0x3a, 0xfe]), + kStructVersion2 +); +impl Default for Constants { + fn default() -> Self { + Self { + base: Self::header(), + cameraViewToClip: float4x4::default(), + clipToCameraView: float4x4::default(), + clipToLensClip: float4x4::default(), + clipToPrevClip: float4x4::default(), + prevClipToClip: float4x4::default(), + jitterOffset: float2::default(), + mvecScale: float2::default(), + cameraPinholeOffset: float2::default(), + cameraPos: float3::default(), + cameraUp: float3::default(), + cameraRight: float3::default(), + cameraFwd: float3::default(), + cameraNear: INVALID_FLOAT, + cameraFar: INVALID_FLOAT, + cameraFOV: INVALID_FLOAT, + cameraAspectRatio: INVALID_FLOAT, + motionVectorsInvalidValue: INVALID_FLOAT, + depthInverted: Boolean::eInvalid, + cameraMotionIncluded: Boolean::eInvalid, + motionVectors3D: Boolean::eInvalid, + reset: Boolean::eInvalid, + orthographicProjection: Boolean::eFalse, + motionVectorsDilated: Boolean::eFalse, + motionVectorsJittered: Boolean::eFalse, + minRelativeLinearDepthObjectSeparation: 40.0, + } + } +} + +// --------------------------------------------------------------------------------------------- +// DLSS-G (sl_dlss_g.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::DLSSGOptions` {FAC5F1CB-2DFD-4F36-A1E6-3A9E865256C5}, kStructVersion5. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct DLSSGOptions { + pub base: BaseStructure, + pub mode: DLSSGMode, + /// 1 = 2x, 2 = 3x, 3 = 4x; <= DLSSGState::numFramesToGenerateMax + pub numFramesToGenerate: u32, + pub flags: DLSSGFlags, + pub dynamicResWidth: u32, + pub dynamicResHeight: u32, + pub numBackBuffers: u32, + pub mvecDepthWidth: u32, + pub mvecDepthHeight: u32, + pub colorWidth: u32, + pub colorHeight: u32, + /// DXGI_FORMAT values + pub colorBufferFormat: u32, + pub mvecBufferFormat: u32, + pub depthBufferFormat: u32, + pub hudLessBufferFormat: u32, + pub uiBufferFormat: u32, + pub onErrorCallback: Option, + // kStructVersion2 + pub bReserved15: Boolean, + // kStructVersion3 + pub queueParallelismMode: DLSSGQueueParallelismMode, + // kStructVersion4 + pub enableUserInterfaceRecomposition: Boolean, + // kStructVersion5 + /// 0 = display refresh rate (eDynamic only) + pub dynamicTargetFrameRate: f32, +} +sl_struct!( + DLSSGOptions, + StructType::new(0xfac5f1cb, 0x2dfd, 0x4f36, [0xa1, 0xe6, 0x3a, 0x9e, 0x86, 0x52, 0x56, 0xc5]), + kStructVersion5 +); +impl Default for DLSSGOptions { + fn default() -> Self { + Self { + base: Self::header(), + mode: DLSSGMode::eOff, + numFramesToGenerate: 1, + flags: DLSSGFlags(0), + dynamicResWidth: 0, + dynamicResHeight: 0, + numBackBuffers: 0, + mvecDepthWidth: 0, + mvecDepthHeight: 0, + colorWidth: 0, + colorHeight: 0, + colorBufferFormat: 0, + mvecBufferFormat: 0, + depthBufferFormat: 0, + hudLessBufferFormat: 0, + uiBufferFormat: 0, + onErrorCallback: None, + bReserved15: Boolean::eInvalid, + queueParallelismMode: DLSSGQueueParallelismMode::eBlockPresentingClientQueue, + enableUserInterfaceRecomposition: Boolean::eFalse, + dynamicTargetFrameRate: 0.0, + } + } +} + +/// `sl::DLSSGState` {CC8AC8E1-A179-44F5-97FA-E74112F9BC61}, kStructVersion4. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct DLSSGState { + pub base: BaseStructure, + pub estimatedVRAMUsageInBytes: u64, + pub status: DLSSGStatus, + pub minWidthOrHeight: u32, + pub numFramesActuallyPresented: u32, + // kStructVersion2 + pub numFramesToGenerateMax: u32, + pub bReserved4: Boolean, + pub bIsVsyncSupportAvailable: Boolean, + /// Internal fence (ID3D12Fence*) for eBlockNoClientQueues / cross-queue input reuse + pub inputsProcessingCompletionFence: *mut c_void, + pub lastPresentInputsProcessingCompletionFenceValue: u64, + // kStructVersion4 + pub bIsDynamicMFGSupported: Boolean, +} +sl_struct!( + DLSSGState, + StructType::new(0xcc8ac8e1, 0xa179, 0x44f5, [0x97, 0xfa, 0xe7, 0x41, 0x12, 0xf9, 0xbc, 0x61]), + kStructVersion4 +); +impl Default for DLSSGState { + fn default() -> Self { + Self { + base: Self::header(), + estimatedVRAMUsageInBytes: 0, + status: DLSSGStatus::eOk, + minWidthOrHeight: 0, + numFramesActuallyPresented: 0, + numFramesToGenerateMax: 0, + bReserved4: Boolean::eFalse, + bIsVsyncSupportAvailable: Boolean::eFalse, + inputsProcessingCompletionFence: ptr::null_mut(), + lastPresentInputsProcessingCompletionFenceValue: 0, + bIsDynamicMFGSupported: Boolean::eFalse, + } + } +} + +// --------------------------------------------------------------------------------------------- +// Reflex (sl_reflex.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::ReflexOptions` {F03AF81A-6D0B-4902-A651-C4965E215434}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexOptions { + pub base: BaseStructure, + pub mode: ReflexMode, + /// 0 = no cap, else microseconds per frame + pub frameLimitUs: u32, + /// Leave false unless told otherwise by NVIDIA + pub useMarkersToOptimize: bool, + /// VK_F13/14/15 or 0 + pub virtualKey: u16, + pub idThread: u32, +} +sl_struct!( + ReflexOptions, + StructType::new(0xf03af81a, 0x6d0b, 0x4902, [0xa6, 0x51, 0xc4, 0x96, 0x5e, 0x21, 0x54, 0x34]), + kStructVersion1 +); +impl Default for ReflexOptions { + fn default() -> Self { + Self { base: Self::header(), mode: ReflexMode::eOff, frameLimitUs: 0, useMarkersToOptimize: false, virtualKey: 0, idThread: 0 } + } +} + +/// `sl::ReflexReport` {0D569B37-A1C8-4453-BE4D-40F4DE57952B}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexReport { + pub base: BaseStructure, + pub frameID: u64, + pub inputSampleTime: u64, + pub simStartTime: u64, + pub simEndTime: u64, + pub renderSubmitStartTime: u64, + pub renderSubmitEndTime: u64, + pub presentStartTime: u64, + pub presentEndTime: u64, + pub driverStartTime: u64, + pub driverEndTime: u64, + pub osRenderQueueStartTime: u64, + pub osRenderQueueEndTime: u64, + pub gpuRenderStartTime: u64, + pub gpuRenderEndTime: u64, + pub gpuActiveRenderTimeUs: u32, + pub gpuFrameTimeUs: u32, +} +sl_struct!( + ReflexReport, + StructType::new(0x0d569b37, 0xa1c8, 0x4453, [0xbe, 0x4d, 0x40, 0xf4, 0xde, 0x57, 0x95, 0x2b]), + kStructVersion1 +); +impl Default for ReflexReport { + fn default() -> Self { + Self { + base: Self::header(), + frameID: 0, + inputSampleTime: 0, + simStartTime: 0, + simEndTime: 0, + renderSubmitStartTime: 0, + renderSubmitEndTime: 0, + presentStartTime: 0, + presentEndTime: 0, + driverStartTime: 0, + driverEndTime: 0, + osRenderQueueStartTime: 0, + osRenderQueueEndTime: 0, + gpuRenderStartTime: 0, + gpuRenderEndTime: 0, + gpuActiveRenderTimeUs: 0, + gpuFrameTimeUs: 0, + } + } +} + +/// `sl::ReflexReport2` {68BB0632-5E1C-402B-899D-B49F633C56C2}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexReport2 { + pub base: BaseStructure, + pub cameraConstructedTime: u64, + pub crossAdapterCopyTimeUs: u32, +} +sl_struct!( + ReflexReport2, + StructType::new(0x68bb0632, 0x5e1c, 0x402b, [0x89, 0x9d, 0xb4, 0x9f, 0x63, 0x3c, 0x56, 0xc2]), + kStructVersion1 +); +impl Default for ReflexReport2 { + fn default() -> Self { + Self { base: Self::header(), cameraConstructedTime: 0, crossAdapterCopyTimeUs: 0 } + } +} + +/// `sl::ReflexState` {F0BB5985-DAF9-4728-B2FD-AE80A2BD7989}, kStructVersion2 (12848 bytes). +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct ReflexState { + pub base: BaseStructure, + /// Show the Reflex UI only if true; everything else is done regardless. + pub lowLatencyAvailable: bool, + pub latencyReportAvailable: bool, + /// No initializer in C++; zeroed here + pub statsWindowMessage: u32, + pub frameReport: [ReflexReport; kReflexFrameReportCount], + pub flashIndicatorDriverControlled: bool, + // kStructVersion2 + pub frameReport2: [ReflexReport2; kReflexFrameReportCount], +} +sl_struct!( + ReflexState, + StructType::new(0xf0bb5985, 0xdaf9, 0x4728, [0xb2, 0xfd, 0xae, 0x80, 0xa2, 0xbd, 0x79, 0x89]), + kStructVersion2 +); +impl Default for ReflexState { + fn default() -> Self { + Self { + base: Self::header(), + lowLatencyAvailable: false, + latencyReportAvailable: false, + statsWindowMessage: 0, + frameReport: [ReflexReport::default(); kReflexFrameReportCount], + flashIndicatorDriverControlled: false, + frameReport2: [ReflexReport2::default(); kReflexFrameReportCount], + } + } +} + +// --------------------------------------------------------------------------------------------- +// PCL (sl_pcl.h) +// --------------------------------------------------------------------------------------------- + +/// `sl::PCLOptions` {CFA32F9B-023C-420E-9056-6832B74F89B4}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct PCLOptions { + pub base: BaseStructure, + pub virtualKey: PCLHotKey, + pub idThread: u32, +} +sl_struct!( + PCLOptions, + StructType::new(0xcfa32f9b, 0x023c, 0x420e, [0x90, 0x56, 0x68, 0x32, 0xb7, 0x4f, 0x89, 0xb4]), + kStructVersion1 +); +impl Default for PCLOptions { + fn default() -> Self { + Self { base: Self::header(), virtualKey: PCLHotKey::eUsePingMessage, idThread: 0 } + } +} + +/// `sl::PCLState` {CFA32F9B-023C-420E-9056-6832B74F89B5}, kStructVersion1. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct PCLState { + pub base: BaseStructure, + /// Window message id of the PCL ping (send `ePCLatencyPing` when it arrives) + pub statsWindowMessage: u32, +} +sl_struct!( + PCLState, + StructType::new(0xcfa32f9b, 0x023c, 0x420e, [0x90, 0x56, 0x68, 0x32, 0xb7, 0x4f, 0x89, 0xb5]), + kStructVersion1 +); +impl Default for PCLState { + fn default() -> Self { + Self { base: Self::header(), statsWindowMessage: 0 } + } +} + +// --------------------------------------------------------------------------------------------- +// Function pointer types (sl_core_api.h, sl_dlss_g.h, sl_reflex.h, sl_pcl.h) +// C++ references are passed as pointers; `bool` is the 1-byte C++ bool. +// --------------------------------------------------------------------------------------------- + +pub type PFun_slInit = unsafe extern "C" fn(pref: *const Preferences, sdkVersion: u64) -> SlResult; +pub type PFun_slShutdown = unsafe extern "C" fn() -> SlResult; +pub type PFun_slIsFeatureSupported = unsafe extern "C" fn(feature: Feature, adapterInfo: *const AdapterInfo) -> SlResult; +pub type PFun_slIsFeatureLoaded = unsafe extern "C" fn(feature: Feature, loaded: *mut bool) -> SlResult; +pub type PFun_slSetFeatureLoaded = unsafe extern "C" fn(feature: Feature, loaded: bool) -> SlResult; +pub type PFun_slEvaluateFeature = unsafe extern "C" fn( + feature: Feature, + frame: *const FrameToken, + inputs: *const *const BaseStructure, + numInputs: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slAllocateResources = + unsafe extern "C" fn(cmdBuffer: *mut c_void, feature: Feature, viewport: *const ViewportHandle) -> SlResult; +pub type PFun_slFreeResources = unsafe extern "C" fn(feature: Feature, viewport: *const ViewportHandle) -> SlResult; +/// Deprecated; cannot be mixed with slSetTagForFrame. +pub type PFun_slSetTag = unsafe extern "C" fn( + viewport: *const ViewportHandle, + tags: *const ResourceTag, + numTags: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slSetTagForFrame = unsafe extern "C" fn( + frame: *const FrameToken, + viewport: *const ViewportHandle, + tags: *const ResourceTag, + numTags: u32, + cmdBuffer: *mut c_void, +) -> SlResult; +pub type PFun_slGetFeatureRequirements = + unsafe extern "C" fn(feature: Feature, requirements: *mut FeatureRequirements) -> SlResult; +pub type PFun_slGetFeatureVersion = unsafe extern "C" fn(feature: Feature, version: *mut FeatureVersion) -> SlResult; +pub type PFun_slUpgradeInterface = unsafe extern "C" fn(baseInterface: *mut *mut c_void) -> SlResult; +pub type PFun_slSetConstants = unsafe extern "C" fn( + values: *const Constants, + frame: *const FrameToken, + viewport: *const ViewportHandle, +) -> SlResult; +pub type PFun_slGetNativeInterface = + unsafe extern "C" fn(proxyInterface: *mut c_void, baseInterface: *mut *mut c_void) -> SlResult; +pub type PFun_slGetFeatureFunction = + unsafe extern "C" fn(feature: Feature, functionName: *const c_char, function: *mut *mut c_void) -> SlResult; +pub type PFun_slGetNewFrameToken = unsafe extern "C" fn(token: *mut *mut FrameToken, frameIndex: *const u32) -> SlResult; +pub type PFun_slSetD3DDevice = unsafe extern "C" fn(d3dDevice: *mut c_void) -> SlResult; + +pub type PFun_slDLSSGGetState = unsafe extern "C" fn( + viewport: *const ViewportHandle, + state: *mut DLSSGState, + options: *const DLSSGOptions, +) -> SlResult; +pub type PFun_slDLSSGSetOptions = + unsafe extern "C" fn(viewport: *const ViewportHandle, options: *const DLSSGOptions) -> SlResult; + +pub type PFun_slReflexGetState = unsafe extern "C" fn(state: *mut ReflexState) -> SlResult; +pub type PFun_slReflexSleep = unsafe extern "C" fn(frame: *const FrameToken) -> SlResult; +pub type PFun_slReflexSetOptions = unsafe extern "C" fn(options: *const ReflexOptions) -> SlResult; + +pub type PFun_slPCLGetState = unsafe extern "C" fn(state: *mut PCLState) -> SlResult; +pub type PFun_slPCLSetMarker = unsafe extern "C" fn(marker: PCLMarker, frame: *const FrameToken) -> SlResult; +pub type PFun_slPCLSetOptions = unsafe extern "C" fn(options: *const PCLOptions) -> SlResult; + +// --------------------------------------------------------------------------------------------- +// Runtime loader +// --------------------------------------------------------------------------------------------- + +/// `GetProcAddress(module, name)` typed as `$ty`, or `None`. +macro_rules! proc_address { + ($module:expr, $name:literal, $ty:ty) => {{ + // SAFETY: `module` is a loaded module and the name is a NUL-terminated literal. + let raw = unsafe { GetProcAddress($module, PCSTR(concat!($name, "\0").as_ptr())) }; + // SAFETY: the export has the C signature declared by `$ty` (sl_core_api.h). + raw.map(|f| unsafe { core::mem::transmute:: isize, $ty>(f) }) + }}; +} + +/// `slGetFeatureFunction(feature, name, ptr)` typed as `$ty`; failures are pushed to `$missing`. +macro_rules! feature_function { + ($get:expr, $feature:expr, $name:literal, $ty:ty, $missing:ident) => {{ + let mut p: *mut c_void = ptr::null_mut(); + // SAFETY: NUL-terminated literal name and a valid out pointer. + let r = unsafe { ($get)($feature, concat!($name, "\0").as_ptr().cast::(), &mut p) }; + if r.is_ok() && !p.is_null() { + // SAFETY: SL hands out the function declared as `$ty` in the feature header. + Some(unsafe { core::mem::transmute::<*mut c_void, $ty>(p) }) + } else { + $missing.push(format!("{} ({})", $name, r)); + None + } + }}; +} + +/// Function table for `sl.interposer.dll`. Core functions are resolved by [`Sl::load`]; feature +/// functions by [`Sl::resolve_feature_functions`] (only after `slSetD3DDevice`). +/// +/// The module is never unloaded (SL keeps hooks and threads alive until process exit). +pub struct Sl { + pub module: HMODULE, + /// Absolute directory `sl.interposer.dll` was loaded from. + pub dir: PathBuf, + + pub slInit: PFun_slInit, + pub slShutdown: PFun_slShutdown, + pub slSetD3DDevice: PFun_slSetD3DDevice, + pub slIsFeatureSupported: PFun_slIsFeatureSupported, + pub slIsFeatureLoaded: PFun_slIsFeatureLoaded, + pub slSetFeatureLoaded: PFun_slSetFeatureLoaded, + pub slGetNewFrameToken: PFun_slGetNewFrameToken, + pub slSetConstants: PFun_slSetConstants, + pub slSetTagForFrame: PFun_slSetTagForFrame, + pub slEvaluateFeature: PFun_slEvaluateFeature, + pub slUpgradeInterface: PFun_slUpgradeInterface, + pub slGetNativeInterface: PFun_slGetNativeInterface, + pub slGetFeatureRequirements: PFun_slGetFeatureRequirements, + pub slGetFeatureFunction: PFun_slGetFeatureFunction, + pub slAllocateResources: PFun_slAllocateResources, + pub slFreeResources: PFun_slFreeResources, + /// Optional exports. + pub slGetFeatureVersion: Option, + pub slSetTag: Option, + + // Feature functions (slGetFeatureFunction) + pub slDLSSGSetOptions: Option, + pub slDLSSGGetState: Option, + pub slReflexSetOptions: Option, + pub slReflexGetState: Option, + pub slReflexSleep: Option, + pub slPCLSetMarker: Option, + pub slPCLGetState: Option, + pub slPCLSetOptions: Option, +} + +// SAFETY: the table only holds immutable function pointers and a module handle; thread safety of +// each call is SL's (documented per function in sl_core_api.h / feature headers). +unsafe impl Send for Sl {} +// SAFETY: as above. +unsafe impl Sync for Sl {} + +impl core::fmt::Debug for Sl { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Sl") + .field("dir", &self.dir) + .field("dlssg", &self.slDLSSGSetOptions.is_some()) + .field("reflex", &self.slReflexSetOptions.is_some()) + .field("pcl", &self.slPCLSetMarker.is_some()) + .finish_non_exhaustive() + } +} + +impl Sl { + /// Loads `\sl.interposer.dll` (full path) and resolves the core exports. + /// + /// # Safety + /// Loading the DLL runs its initialisation code. The caller should have verified the + /// signature of the file if that matters (see module docs). + pub unsafe fn load(dir: &Path) -> anyhow::Result { + let dir = std::path::absolute(dir).with_context(|| format!("resolving {}", dir.display()))?; + let dll = dir.join(INTERPOSER_DLL); + if !dll.is_file() { + bail!("{} not found", dll.display()); + } + let wide: Vec = dll.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: NUL-terminated full path; the caller accepts running the DLL's init code. + let module = unsafe { LoadLibraryW(PCWSTR(wide.as_ptr())) } + .with_context(|| format!("LoadLibraryW({})", dll.display()))?; + + macro_rules! need { + ($name:literal, $ty:ty) => { + proc_address!(module, $name, $ty) + .ok_or_else(|| anyhow!("{} does not export {}", dll.display(), $name))? + }; + } + + Ok(Self { + module, + slInit: need!("slInit", PFun_slInit), + slShutdown: need!("slShutdown", PFun_slShutdown), + slSetD3DDevice: need!("slSetD3DDevice", PFun_slSetD3DDevice), + slIsFeatureSupported: need!("slIsFeatureSupported", PFun_slIsFeatureSupported), + slIsFeatureLoaded: need!("slIsFeatureLoaded", PFun_slIsFeatureLoaded), + slSetFeatureLoaded: need!("slSetFeatureLoaded", PFun_slSetFeatureLoaded), + slGetNewFrameToken: need!("slGetNewFrameToken", PFun_slGetNewFrameToken), + slSetConstants: need!("slSetConstants", PFun_slSetConstants), + slSetTagForFrame: need!("slSetTagForFrame", PFun_slSetTagForFrame), + slEvaluateFeature: need!("slEvaluateFeature", PFun_slEvaluateFeature), + slUpgradeInterface: need!("slUpgradeInterface", PFun_slUpgradeInterface), + slGetNativeInterface: need!("slGetNativeInterface", PFun_slGetNativeInterface), + slGetFeatureRequirements: need!("slGetFeatureRequirements", PFun_slGetFeatureRequirements), + slGetFeatureFunction: need!("slGetFeatureFunction", PFun_slGetFeatureFunction), + slAllocateResources: need!("slAllocateResources", PFun_slAllocateResources), + slFreeResources: need!("slFreeResources", PFun_slFreeResources), + slGetFeatureVersion: proc_address!(module, "slGetFeatureVersion", PFun_slGetFeatureVersion), + slSetTag: proc_address!(module, "slSetTag", PFun_slSetTag), + slDLSSGSetOptions: None, + slDLSSGGetState: None, + slReflexSetOptions: None, + slReflexGetState: None, + slReflexSleep: None, + slPCLSetMarker: None, + slPCLGetState: None, + slPCLSetOptions: None, + dir, + }) + } + + /// Resolves the DLSS-G / Reflex / PCL functions with `slGetFeatureFunction`. + /// Must be called AFTER `slSetD3DDevice`. Keeps whatever resolved; errors list the rest. + pub fn resolve_feature_functions(&mut self) -> anyhow::Result<()> { + let get = self.slGetFeatureFunction; + let mut missing: Vec = Vec::new(); + self.slDLSSGSetOptions = + feature_function!(get, kFeatureDLSS_G, "slDLSSGSetOptions", PFun_slDLSSGSetOptions, missing); + self.slDLSSGGetState = feature_function!(get, kFeatureDLSS_G, "slDLSSGGetState", PFun_slDLSSGGetState, missing); + self.slReflexSetOptions = + feature_function!(get, kFeatureReflex, "slReflexSetOptions", PFun_slReflexSetOptions, missing); + self.slReflexGetState = feature_function!(get, kFeatureReflex, "slReflexGetState", PFun_slReflexGetState, missing); + self.slReflexSleep = feature_function!(get, kFeatureReflex, "slReflexSleep", PFun_slReflexSleep, missing); + self.slPCLSetMarker = feature_function!(get, kFeaturePCL, "slPCLSetMarker", PFun_slPCLSetMarker, missing); + self.slPCLGetState = feature_function!(get, kFeaturePCL, "slPCLGetState", PFun_slPCLGetState, missing); + self.slPCLSetOptions = feature_function!(get, kFeaturePCL, "slPCLSetOptions", PFun_slPCLSetOptions, missing); + if missing.is_empty() { + Ok(()) + } else { + Err(anyhow!("Streamline feature functions not available: {}", missing.join(", "))) + } + } + + // ---- core wrappers ---------------------------------------------------------------------- + + /// `slInit(pref, kSDKVersion)`. + /// + /// # Safety + /// Every pointer in `pref` must be valid for the call (SL copies paths, features and strings). + /// The log callback must stay valid until `slShutdown`. + pub unsafe fn init(&self, pref: &Preferences) -> SlResult { + // SAFETY: caller upholds the pointer requirements of `pref`. + unsafe { (self.slInit)(pref, kSDKVersion) } + } + + /// `slShutdown()` - before releasing DXGI/D3D objects. + pub fn shutdown(&self) -> SlResult { + // SAFETY: no arguments. + unsafe { (self.slShutdown)() } + } + + /// `slSetD3DDevice(nativeDevice)`. + /// + /// # Safety + /// `native_device` must be a live NATIVE `ID3D12Device*` (not the SL proxy). + pub unsafe fn set_d3d_device(&self, native_device: *mut c_void) -> SlResult { + // SAFETY: caller guarantees a live device. + unsafe { (self.slSetD3DDevice)(native_device) } + } + + /// `slIsFeatureSupported(feature, AdapterInfo{LUID})`; `None` checks OS/driver only. + pub fn is_feature_supported(&self, feature: Feature, adapter_luid: Option<&[u8; 8]>) -> SlResult { + let mut luid = adapter_luid.copied().unwrap_or_default(); + let mut info = AdapterInfo::default(); + if adapter_luid.is_some() { + info.deviceLUID = luid.as_mut_ptr(); + info.deviceLUIDSizeInBytes = 8; + } + // SAFETY: `info` and `luid` outlive the call. + unsafe { (self.slIsFeatureSupported)(feature, &info) } + } + + /// `slIsFeatureLoaded(feature, loaded)`. + pub fn is_feature_loaded(&self, feature: Feature) -> Result { + let mut loaded = false; + // SAFETY: valid out pointer. + unsafe { (self.slIsFeatureLoaded)(feature, &mut loaded) }.ok()?; + Ok(loaded) + } + + /// `slSetFeatureLoaded(feature, loaded)` - load/unload (unhook) a feature. Flush the GPU and + /// make no DXGI/D3D calls in parallel. + pub fn set_feature_loaded(&self, feature: Feature, loaded: bool) -> SlResult { + // SAFETY: plain values. + unsafe { (self.slSetFeatureLoaded)(feature, loaded) } + } + + /// `slGetNewFrameToken(token, frameIndex)`. Passing your own index bypasses SL's counter. + pub fn new_frame_token(&self, frame_index: Option) -> Result { + let mut token: *mut FrameToken = ptr::null_mut(); + let index = frame_index.unwrap_or(0); + let index_ptr = if frame_index.is_some() { &index as *const u32 } else { ptr::null() }; + // SAFETY: valid out pointer; `index` outlives the call. + unsafe { (self.slGetNewFrameToken)(&mut token, index_ptr) }.ok()?; + NonNull::new(token).map(Frame).ok_or(SlResult::eErrorInvalidState) + } + + /// `slSetConstants(values, frame, viewport)` - once per frame. + pub fn set_constants(&self, values: &Constants, frame: Frame, viewport: &ViewportHandle) -> SlResult { + // SAFETY: references are valid; the token came from SL. + unsafe { (self.slSetConstants)(values, frame.as_ptr(), viewport) } + } + + /// `slSetTagForFrame(frame, viewport, tags, numTags, cmdList)`. + /// + /// # Safety + /// Every non-null `tags[i].resource` must point at a valid `Resource` whose `native` is a live + /// `ID3D12Resource*`; `cmd_list` is a NATIVE open `ID3D12GraphicsCommandList*` or null (null + /// only if all tags are null or `eValidUntilPresent`). + pub unsafe fn set_tag_for_frame( + &self, + frame: Frame, + viewport: &ViewportHandle, + tags: &[ResourceTag], + cmd_list: *mut c_void, + ) -> SlResult { + // SAFETY: caller guarantees the resource and command list pointers. + unsafe { (self.slSetTagForFrame)(frame.as_ptr(), viewport, tags.as_ptr(), tags.len() as u32, cmd_list) } + } + + /// Deprecated `slSetTag` (only without `eUseFrameBasedResourceTagging`). + /// + /// # Safety + /// As [`Sl::set_tag_for_frame`]. + pub unsafe fn set_tag(&self, viewport: &ViewportHandle, tags: &[ResourceTag], cmd_list: *mut c_void) -> SlResult { + match self.slSetTag { + // SAFETY: caller guarantees the resource and command list pointers. + Some(f) => unsafe { f(viewport, tags.as_ptr(), tags.len() as u32, cmd_list) }, + None => MISSING_FUNCTION, + } + } + + /// `slEvaluateFeature` (not needed for DLSS-G). + /// + /// # Safety + /// `inputs` must point at live SL structs; `cmd_list` a native command list. + pub unsafe fn evaluate_feature( + &self, + feature: Feature, + frame: Frame, + inputs: &[*const BaseStructure], + cmd_list: *mut c_void, + ) -> SlResult { + // SAFETY: caller guarantees the inputs. + unsafe { (self.slEvaluateFeature)(feature, frame.as_ptr(), inputs.as_ptr(), inputs.len() as u32, cmd_list) } + } + + /// `slUpgradeInterface(&iface)` - replaces `*iface` in place with a new SL proxy + /// (`ID3D12Device`, `IDXGIFactory*`, `IDXGISwapChain*`). The proxy has its own reference + /// (count 1) and AddRefs the base; the caller's reference to the native object is NOT consumed. + /// + /// # Safety + /// `*iface` must be a live COM pointer of a supported interface. + pub unsafe fn upgrade_interface(&self, iface: &mut *mut c_void) -> SlResult { + // SAFETY: caller guarantees a live COM pointer. + unsafe { (self.slUpgradeInterface)(iface) } + } + + /// `slGetNativeInterface(proxy, &base)` - returns an AddRef'd native pointer. + /// + /// # Safety + /// `proxy` must be a live COM pointer. + pub unsafe fn get_native_interface(&self, proxy: *mut c_void) -> Result<*mut c_void, SlResult> { + let mut base: *mut c_void = ptr::null_mut(); + // SAFETY: caller guarantees a live COM pointer; valid out pointer. + unsafe { (self.slGetNativeInterface)(proxy, &mut base) }.ok()?; + Ok(base) + } + + /// `slGetFeatureRequirements(feature, requirements)`. + pub fn get_feature_requirements(&self, feature: Feature) -> Result { + let mut req = FeatureRequirements::default(); + // SAFETY: valid out struct with a correct header. + unsafe { (self.slGetFeatureRequirements)(feature, &mut req) }.ok()?; + Ok(req) + } + + /// `slGetFeatureVersion(feature, version)`. + pub fn get_feature_version(&self, feature: Feature) -> Result { + let f = self.slGetFeatureVersion.ok_or(MISSING_FUNCTION)?; + let mut v = FeatureVersion::default(); + // SAFETY: valid out struct. + unsafe { f(feature, &mut v) }.ok()?; + Ok(v) + } + + /// `slGetFeatureFunction(feature, name, &fn)` (raw). + /// + /// # Safety + /// The caller must transmute the pointer to the exact signature of `name`. + pub unsafe fn get_feature_function(&self, feature: Feature, name: &CStr) -> Result<*mut c_void, SlResult> { + let mut p: *mut c_void = ptr::null_mut(); + // SAFETY: NUL-terminated name, valid out pointer. + unsafe { (self.slGetFeatureFunction)(feature, name.as_ptr(), &mut p) }.ok()?; + Ok(p) + } + + /// `slAllocateResources(cmdList, feature, viewport)`. + /// + /// # Safety + /// `cmd_list` is a native command list on the SL device, or null. + pub unsafe fn allocate_resources(&self, cmd_list: *mut c_void, feature: Feature, viewport: &ViewportHandle) -> SlResult { + // SAFETY: caller guarantees the command list. + unsafe { (self.slAllocateResources)(cmd_list, feature, viewport) } + } + + /// `slFreeResources(feature, viewport)` - flush pending work first. + pub fn free_resources(&self, feature: Feature, viewport: &ViewportHandle) -> SlResult { + // SAFETY: valid reference. + unsafe { (self.slFreeResources)(feature, viewport) } + } + + // ---- DLSS-G ----------------------------------------------------------------------------- + + /// `slDLSSGSetOptions(viewport, options)` - applies at the next Present; call on the present thread. + pub fn dlssg_set_options(&self, viewport: &ViewportHandle, options: &DLSSGOptions) -> SlResult { + match self.slDLSSGSetOptions { + // SAFETY: valid references; `onErrorCallback` (if any) is a valid fn pointer. + Some(f) => unsafe { f(viewport, options) }, + None => MISSING_FUNCTION, + } + } + + /// `slDLSSGGetState(viewport, state, options)`. Pass `None` for the cheap per-frame query. + pub fn dlssg_get_state(&self, viewport: &ViewportHandle, options: Option<&DLSSGOptions>) -> Result { + let f = self.slDLSSGGetState.ok_or(MISSING_FUNCTION)?; + let mut state = DLSSGState::default(); + let opts = options.map_or(ptr::null(), |o| o as *const DLSSGOptions); + // SAFETY: valid references / out struct. + unsafe { f(viewport, &mut state, opts) }.ok()?; + Ok(state) + } + + // ---- Reflex ----------------------------------------------------------------------------- + + /// `slReflexSetOptions(options)` - at least once, even with Reflex off. + pub fn reflex_set_options(&self, options: &ReflexOptions) -> SlResult { + match self.slReflexSetOptions { + // SAFETY: valid reference. + Some(f) => unsafe { f(options) }, + None => MISSING_FUNCTION, + } + } + + /// `slReflexGetState(state)` (boxed: 12.8 KB). + pub fn reflex_get_state(&self) -> Result, SlResult> { + let f = self.slReflexGetState.ok_or(MISSING_FUNCTION)?; + let mut state = Box::::default(); + // SAFETY: valid out struct. + unsafe { f(&mut *state) }.ok()?; + Ok(state) + } + + /// `slReflexSleep(frame)` - every frame, regardless of Reflex mode. + pub fn reflex_sleep(&self, frame: Frame) -> SlResult { + match self.slReflexSleep { + // SAFETY: token from SL. + Some(f) => unsafe { f(frame.as_ptr()) }, + None => MISSING_FUNCTION, + } + } + + // ---- PCL -------------------------------------------------------------------------------- + + /// `slPCLSetMarker(marker, frame)` (thread safe). + pub fn pcl_set_marker(&self, marker: PCLMarker, frame: Frame) -> SlResult { + match self.slPCLSetMarker { + // SAFETY: token from SL. + Some(f) => unsafe { f(marker, frame.as_ptr()) }, + None => MISSING_FUNCTION, + } + } + + /// `slPCLGetState(state)` - `statsWindowMessage` for the ping. + pub fn pcl_get_state(&self) -> Result { + let f = self.slPCLGetState.ok_or(MISSING_FUNCTION)?; + let mut state = PCLState::default(); + // SAFETY: valid out struct. + unsafe { f(&mut state) }.ok()?; + Ok(state) + } + + /// `slPCLSetOptions(options)`. + pub fn pcl_set_options(&self, options: &PCLOptions) -> SlResult { + match self.slPCLSetOptions { + // SAFETY: valid reference. + Some(f) => unsafe { f(options) }, + None => MISSING_FUNCTION, + } + } +} + +// --------------------------------------------------------------------------------------------- +// Layout checks (x64 MSVC sizes/offsets computed from the 2.14.16 headers) +// --------------------------------------------------------------------------------------------- + +#[cfg(target_pointer_width = "64")] +const _: () = { + use core::mem::{align_of, offset_of, size_of}; + + assert!(size_of::() == 16); + assert!(size_of::() == 32); + assert!(offset_of!(BaseStructure, structType) == 8); + assert!(offset_of!(BaseStructure, structVersion) == 24); + + assert!(size_of::() == 144); + assert!(offset_of!(Preferences, showConsole) == 32); + assert!(offset_of!(Preferences, logLevel) == 36); + assert!(offset_of!(Preferences, pathsToPlugins) == 40); + assert!(offset_of!(Preferences, numPathsToPlugins) == 48); + assert!(offset_of!(Preferences, pathToLogsAndData) == 56); + assert!(offset_of!(Preferences, logMessageCallback) == 80); + assert!(offset_of!(Preferences, flags) == 88); + assert!(offset_of!(Preferences, featuresToLoad) == 96); + assert!(offset_of!(Preferences, numFeaturesToLoad) == 104); + assert!(offset_of!(Preferences, applicationId) == 108); + assert!(offset_of!(Preferences, engine) == 112); + assert!(offset_of!(Preferences, engineVersion) == 120); + assert!(offset_of!(Preferences, projectId) == 128); + assert!(offset_of!(Preferences, renderAPI) == 136); + + assert!(size_of::() == 64); + + assert!(size_of::() == 112); + assert!(offset_of!(Resource, r#type) == 32); + assert!(offset_of!(Resource, native) == 40); + assert!(offset_of!(Resource, state) == 64); + assert!(offset_of!(Resource, gpuVirtualAddress) == 88); + assert!(offset_of!(Resource, flags) == 96); + assert!(offset_of!(Resource, internalFlags) == 104); + + assert!(size_of::() == 16); + assert!(size_of::() == 64); + assert!(offset_of!(ResourceTag, resource) == 32); + assert!(offset_of!(ResourceTag, r#type) == 40); + assert!(offset_of!(ResourceTag, lifecycle) == 44); + assert!(offset_of!(ResourceTag, extent) == 48); + + assert!(size_of::() == 40); + assert!(size_of::() == 56); + assert!(size_of::() == 12); + assert!(size_of::() == 184); + assert!(offset_of!(FeatureRequirements, osVersionDetected) == 56); + assert!(offset_of!(FeatureRequirements, vkNumComputeQueuesRequired) == 104); + assert!(offset_of!(FeatureRequirements, vkNumOpticalFlowQueuesRequired) == 176); + assert!(size_of::() == 56); + + assert!(size_of::() == 64); + assert!(size_of::() == 456); + assert!(offset_of!(Constants, jitterOffset) == 352); + assert!(offset_of!(Constants, mvecScale) == 360); + assert!(offset_of!(Constants, cameraPos) == 376); + assert!(offset_of!(Constants, cameraFwd) == 412); + assert!(offset_of!(Constants, cameraNear) == 424); + assert!(offset_of!(Constants, motionVectorsInvalidValue) == 440); + assert!(offset_of!(Constants, depthInverted) == 444); + assert!(offset_of!(Constants, motionVectorsJittered) == 450); + assert!(offset_of!(Constants, minRelativeLinearDepthObjectSeparation) == 452); + + assert!(size_of::() == 120); + assert!(offset_of!(DLSSGOptions, mode) == 32); + assert!(offset_of!(DLSSGOptions, uiBufferFormat) == 88); + assert!(offset_of!(DLSSGOptions, onErrorCallback) == 96); + assert!(offset_of!(DLSSGOptions, bReserved15) == 104); + assert!(offset_of!(DLSSGOptions, queueParallelismMode) == 108); + assert!(offset_of!(DLSSGOptions, enableUserInterfaceRecomposition) == 112); + assert!(offset_of!(DLSSGOptions, dynamicTargetFrameRate) == 116); + + assert!(size_of::() == 88); + assert!(offset_of!(DLSSGState, status) == 40); + assert!(offset_of!(DLSSGState, numFramesToGenerateMax) == 52); + assert!(offset_of!(DLSSGState, bIsVsyncSupportAvailable) == 57); + assert!(offset_of!(DLSSGState, inputsProcessingCompletionFence) == 64); + assert!(offset_of!(DLSSGState, bIsDynamicMFGSupported) == 80); + + assert!(size_of::() == 48); + assert!(offset_of!(ReflexOptions, useMarkersToOptimize) == 40); + assert!(offset_of!(ReflexOptions, virtualKey) == 42); + assert!(offset_of!(ReflexOptions, idThread) == 44); + assert!(size_of::() == 152); + assert!(size_of::() == 48); + assert!(size_of::() == 12848); + assert!(offset_of!(ReflexState, frameReport) == 40); + assert!(offset_of!(ReflexState, flashIndicatorDriverControlled) == 9768); + assert!(offset_of!(ReflexState, frameReport2) == 9776); + + assert!(size_of::() == 40); + assert!(offset_of!(PCLOptions, idThread) == 36); + assert!(size_of::() == 40); + + assert!(size_of::() == 1 && size_of::() == 1); + assert!(size_of::() == 4 && align_of::() == 4); + assert!(size_of::>() == 8); +}; diff --git a/crates/victory-gpu/src/stretch.rs b/crates/victory-gpu/src/stretch.rs new file mode 100644 index 0000000..0c5da95 --- /dev/null +++ b/crates/victory-gpu/src/stretch.rs @@ -0,0 +1,292 @@ +//! The upscaler's output by a plain stretch of its colour input (from CuteBooty/victory-8gb over.rs), +//! for builds that otherwise run the title's own FidelityFX upscaler, whose translated passes are slow +//! on 32-lane hosts. Taken by `victory_hle::modules::ffx` in Series S. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + +/// A bilinear, clamping sampler at `s0` for the stages `visibility` names. +fn bilinear(visibility: D3D12_SHADER_VISIBILITY) -> D3D12_STATIC_SAMPLER_DESC { + D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + MaxLOD: f32::MAX, + ShaderRegister: 0, + RegisterSpace: 0, + ShaderVisibility: visibility, + ..Default::default() + } +} + +/// A root signature of `parameters` and one bilinear sampler, serialized by +/// the runtime and not taken from a shader: the system compiler under Wine +/// compiles a `[RootSignature]` attribute without writing the signature +/// into the shader, and `CreateRootSignature` then fails on it (#188). +fn root_signature( + device: &ID3D12Device, + parameters: &[D3D12_ROOT_PARAMETER], + sampler: D3D12_SHADER_VISIBILITY, + flags: D3D12_ROOT_SIGNATURE_FLAGS, +) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let samplers = [bilinear(sampler)]; + let desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: parameters.len() as u32, + pParameters: parameters.as_ptr(), + NumStaticSamplers: 1, + pStaticSamplers: samplers.as_ptr(), + Flags: flags, + }; + let mut blob: Option = None; + // SAFETY: the description points at live slices; the blob is the + // runtime's own, read while it lives. + unsafe { + D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None)?; + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} + +/// One descriptor range of one view at register 0, at `offset` in its table. +fn range(kind: D3D12_DESCRIPTOR_RANGE_TYPE, offset: u32) -> D3D12_DESCRIPTOR_RANGE { + D3D12_DESCRIPTOR_RANGE { + RangeType: kind, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: offset, + } +} + +/// A root parameter that is a table of `ranges`, for the stages `visibility` +/// names. +fn table(ranges: &[D3D12_DESCRIPTOR_RANGE], visibility: D3D12_SHADER_VISIBILITY) -> D3D12_ROOT_PARAMETER { + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ranges.len() as u32, + pDescriptorRanges: ranges.as_ptr(), + }, + }, + ShaderVisibility: visibility, + } +} + +// --------------------------------------------------------------------------- +// The upscaler's output, by a plain stretch +// --------------------------------------------------------------------------- + +/// The title in its Series S mode renders below its output size and has the +/// console's upscaler (its `ffxDispatch`) write the output. That upscaler's +/// passes are compute pipelines in a container we do not translate, so the +/// output stayed black. This pass stands in for it: each output texel is the +/// bilinear sample of the rendered part of the colour input. +/// +/// shortcut: no temporal accumulation, sharpening or use of the depth and +/// motion inputs: an image, not the upscaler's quality. +const STRETCH: &str = r#" +cbuffer Sizes : register(b0) { float2 scale; float2 texel; }; +Texture2D source : register(t0); +RWTexture2D target : register(u0); +SamplerState bilinear : register(s0); +[numthreads(8, 8, 1)] +void stretch(uint3 id : SV_DispatchThreadID) { + // Groups are 8 by 8: the last ones reach past a size that is not a + // multiple of 8. + uint width, height; + target.GetDimensions(width, height); + if (id.x >= width || id.y >= height) return; + float2 at = (float2(id.xy) + 0.5) * texel * scale; + // The rendered size can be the top left of a larger texture: stay half a + // texel inside it, or the filter takes in what is beside it. + uint sw, sh; + source.GetDimensions(sw, sh); + at = min(at, scale - 0.5 / float2(sw, sh)); + target[id.xy] = source.SampleLevel(bilinear, at, 0); +} +"#; + +struct Stretch { + root: ID3D12RootSignature, + pipeline: ID3D12PipelineState, + views: ID3D12DescriptorHeap, + step: u32, + next: u32, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Stretch {} + +static STRETCHER: Mutex> = Mutex::new(None); + +/// Views of a stretch are kept this many stretches (two views each). +/// +/// shortcut: a fixed count. The title dispatches the upscaler once a frame +/// and a list runs within the frames the title keeps in flight; 64 frames +/// is far more than it keeps. +const STRETCH_RING: u32 = 64; + +fn make_stretch(device: &ID3D12Device) -> windows::core::Result { + use windows::core::s; + let cs = crate::host::compile(STRETCH, s!("stretch"), s!("cs_5_1"))?; + let views = [ + range(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0), + range(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1), + ]; + let sizes = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 4, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let root = root_signature( + device, + &[sizes, table(&views, D3D12_SHADER_VISIBILITY_ALL)], + D3D12_SHADER_VISIBILITY_ALL, + D3D12_ROOT_SIGNATURE_FLAG_NONE, + )?; + // SAFETY: the description points at live data and never releases its + // pointer. + unsafe { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateComputePipelineState(&desc)?; + let views: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: STRETCH_RING * 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + })?; + Ok(Stretch { + root, + pipeline, + step: device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + views, + next: 0, + }) + } +} + +/// A typeless colour format as the typed one shaders read and write. +fn typed(format: DXGI_FORMAT) -> DXGI_FORMAT { + DXGI_FORMAT(match format.0 { + 1 => 2, + 9 => 10, + 23 => 24, + 27 => 28, + f => f, + }) +} + +/// Records into `list` the stretch of the top-left `render` texels of +/// `source` (readable by compute shaders) over the whole of `target` (in +/// the unordered-access state). False if nothing was recorded. +/// +/// The pass sets the list's descriptor heap, compute root signature and +/// pipeline and puts none of them back: the caller replays the title's. +pub(crate) fn record_stretch( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + target: &ID3D12Resource, + source: &ID3D12Resource, + render: [u32; 2], +) -> bool { + // SAFETY: live resources. + let (to, from) = unsafe { (target.GetDesc(), source.GetDesc()) }; + if to.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || to.Width == 0 + || from.Width == 0 + { + return false; + } + let mut made = STRETCHER.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + // Tried again at the next dispatch if it fails, as the pass over a + // present is: a failure need not last. + *made = match make_stretch(device) { + Ok(p) => { + tracing::info!("the upscaler's output is made by a plain stretch of its colour input"); + Some(p) + } + Err(e) => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::warn!(error = %e, "no pass to stretch the upscaler's input: its output stays as it is"); + }); + None + } + }; + } + let Some(p) = made.as_mut() else { return false }; + let slot = (p.next % STRETCH_RING) * 2; + p.next = p.next.wrapping_add(1); + let (width, height) = (to.Width as u32, to.Height); + let rendered = [ + if render[0] == 0 { from.Width as u32 } else { render[0].min(from.Width as u32) }, + if render[1] == 0 { from.Height } else { render[1].min(from.Height) }, + ]; + let sizes = [ + rendered[0] as f32 / from.Width as f32, + rendered[1] as f32 / from.Height as f32, + 1.0 / width as f32, + 1.0 / height as f32, + ]; + let read = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: typed(from.Format), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + ..Default::default() + }, + }, + }; + let written = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: typed(to.Format), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + // SAFETY: an open list; slots of our heap; live resources and objects + // (the pass's own live as long as the process). + unsafe { + let cpu = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetCPUDescriptorHandleForHeapStart().ptr + ((slot + i) * p.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: p.views.GetGPUDescriptorHandleForHeapStart().ptr + u64::from(slot * p.step), + }; + device.CreateShaderResourceView(source, Some(&read), cpu(0)); + device.CreateUnorderedAccessView(target, None, Some(&written), cpu(1)); + list.SetDescriptorHeaps(&[Some(p.views.clone())]); + list.SetComputeRootSignature(&p.root); + list.SetPipelineState(&p.pipeline); + list.SetComputeRoot32BitConstants(0, 4, sizes.as_ptr().cast(), 0); + list.SetComputeRootDescriptorTable(1, gpu); + list.Dispatch(width.div_ceil(8), height.div_ceil(8), 1); + } + true +} + diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs index 337e7c3..9df7533 100644 --- a/crates/victory-gpu/src/texture.rs +++ b/crates/victory-gpu/src/texture.rs @@ -95,6 +95,11 @@ pub(crate) struct Staging { /// recorded again about a second later if the card has room by then /// ([`upload`]). waiting: std::sync::atomic::AtomicU64, + /// Recorded for a one-shot decoration bake (`BAKING`): submission-time + /// refresh must wait for title memory to stop remapping + /// (`title_memory_reading`) instead of taking `no_wait()` / + /// `refresh_unlocked()` or the 30-frame partial-read throttle. + exact: std::sync::atomic::AtomicBool, } /// What a texture's staging buffer holds: the hash of the memory detiled @@ -485,6 +490,10 @@ fn with_title(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> /// bytes. static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +pub(crate) fn live_staging_bytes() -> u64 { + STAGED[1].load(std::sync::atomic::Ordering::Relaxed) +} + impl Drop for Staging { fn drop(&mut self) { use std::sync::atomic::Ordering::Relaxed; @@ -533,7 +542,7 @@ pub(crate) fn let_go_idle() { if map.is_empty() { return; } - let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom()); // A list that recorded an upload or a check holds the staging until it // is reset: one only the table holds is named by no list, recorded or // running. @@ -770,6 +779,10 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { return; }; use std::sync::atomic::Ordering::Relaxed; + let baking = BAKING.get(); + if baking { + staging.exact.store(true, Relaxed); + } let picking = PICKING.get(); if picking.is_none() { // A draw samples it through a table: kept and checked from here on. @@ -802,10 +815,31 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { } } } + // The video decoder cycles CPU-written linear plane buffers. Keep a + // 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() { + let (at, len) = staging.memory(); + let footprint = staging.footprints[0].Footprint; + let pitch = footprint.RowPitch as usize; + let bytes = pitch * staging.rows[0] as usize; + let plane = staging.clone(); + let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| { + fill_plane(&plane.layout, at, len, dst, bytes, pitch); + }) else { + once!("no upload buffer for a CPU-written movie plane"); + return; + }; + record_upload(list, resource, texture, &staging, &source, 0); + staging.uploaded.store(true, Relaxed); + return; + } // The host texture has the staging buffer's contents: only the check // at submission is left, and what it finds changed the next list that // samples the texture uploads (a frame late where every list of the - // frame was recorded before that check). + // frame was recorded before that check). During a one-shot bake we + // always record the copy so any change found at submission lands in + // VRAM before the bake draw executes. // LOCAL: not for a video's picture planes (`guard_view` false). Their // check at submission finds the frame the decoder wrote since, but the // copy came only with the next list that samples the plane: three @@ -814,7 +848,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { // ghosts and pictures from earlier (r_avm23, the user's recording). // With the copy recorded here, it takes what that check puts in the // staging buffer at this list's submission. - if staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + if !baking && staging.guard_view && staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::TexSkipped, 1); list.defer_texture(staging); @@ -829,77 +863,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }; staging.expected.store(there, Relaxed); } - const COPY_DEST: u32 = 0x400; - // A texture cut from a block may lie where another did: what the card - // holds of that one is done with before the first upload into this one. - if crate::pool::on() && !staging.uploaded.load(Relaxed) { - let aliasing = D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { - pResourceBefore: std::mem::ManuallyDrop::new(None), - // SAFETY: a borrowed pointer the barrier never releases. - pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, - }), - }, - }; - // SAFETY: an open list and a live texture. - unsafe { list.list.ResourceBarrier(&[aliasing]) }; - } - crate::list::ensure_state(list, resource, COPY_DEST); - // The staging buffer lives as long as `staging`, which the deferred - // refresh below holds until the list is reset. - for (i, footprint) in staging.footprints.iter().enumerate() { - #[cfg(feature = "diagnostics")] - { - let f = footprint.Footprint; - // SAFETY: live resources. - let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; - let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); - list.note_read( - || { - format!( - "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", - d.Width, - d.Height, - d.DepthOrArraySize, - d.Format.0, - d.MipLevels, - staging.footprints.len(), - staging.size, - staging.base + footprint.Offset, - f.Width, - f.Height, - f.Depth, - f.RowPitch - ) - }, - (gpu + staging.base + footprint.Offset, len), - ); - } - let to = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: a borrowed pointer the location never releases. - pResource: unsafe { std::mem::transmute_copy(texture) }, - Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - SubresourceIndex: staging.first - staging.level0 + i as u32, - }, - }; - let from = D3D12_TEXTURE_COPY_LOCATION { - // SAFETY: as above. - pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, - Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { - PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { - Offset: staging.base + footprint.Offset, - ..*footprint - }, - }, - }; - // SAFETY: an open list; both locations name live resources. - unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; - } + record_upload(list, resource, texture, &staging, &staging.buffer, staging.base); // When the list is submitted, its copy takes what the staging buffer // holds by then: noted before the check below, which sets `dirty` // again if it detiles (the next list then uploads once more). @@ -943,6 +907,115 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) { }); } +fn record_upload( + list: &HostList, + resource: This, + texture: &ID3D12Resource, + staging: &Staging, + source: &ID3D12Resource, + base: u64, +) { + use std::sync::atomic::Ordering::Relaxed; + const COPY_DEST: u32 = 0x400; + // A texture cut from a block may lie where another did: what the card + // holds of that one is done with before the first upload into this one. + if crate::pool::on() && !staging.uploaded.load(Relaxed) { + let aliasing = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::ManuallyDrop::new(None), + // SAFETY: a borrowed pointer the barrier never releases. + pResourceAfter: unsafe { std::mem::transmute_copy(texture) }, + }), + }, + }; + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[aliasing]) }; + } + crate::list::ensure_state(list, resource, COPY_DEST); + // The staging/plane upload buffer lives until the list is reset. + for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (source.GetGPUVirtualAddress(), texture.GetDesc()) }; + let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + list.note_read( + || { + format!( + "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + base + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + base + footprint.Offset, len), + ); + } + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: staging.first - staging.level0 + i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(source) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: base + footprint.Offset, + ..*footprint + }, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } +} + +fn fill_plane( + layout: &victory_formats::texture::Layout, + at: usize, + len: usize, + dst: usize, + bytes: usize, + pitch: usize, +) { + let _pin = crate::watch::title_memory_reading(); + // SAFETY: the list owns this full upload allocation until its GPU work completes. + let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) }; + let mip = &layout.mips[0]; + if mip.offset == 0 + && mip.pitch as usize * layout.desc.element_bytes as usize == pitch + && bytes <= len + && crate::host::read_into(at as *const _, out) + { + return; + } + with_read(len, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false); + if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) { + out.fill(0); + once!("could not copy the linear plane into the list's upload buffer: {error:?}"); + } + }); +} + /// Levels on demand: the levels a list claimed for its zeros /// (`crate::tiles::Tiled::claim`), held by the list's submission-time /// step. A list that is reset without having been submitted gives the @@ -1191,6 +1264,20 @@ impl Staging { preparing[3].fetch_add(read as u64, Relaxed); } + fn movie_plane(&self) -> bool { + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM; + let desc = &self.layout.desc; + !self.on_demand + && desc.dimension == victory_formats::texture::Dimension::Tex2d + && desc.swizzle.0 == 0 + && desc.depth == 1 + && desc.mips == 1 + && desc.samples == 1 + && self.footprints.len() == 1 + && self.footprints[0].Offset == 0 + && self.footprints[0].Footprint.Format == DXGI_FORMAT_R8_UNORM + } + /// Returns the bytes of title memory read. fn refresh_now(&self) -> usize { let whole = std::time::Instant::now(); @@ -1204,12 +1291,13 @@ impl Staging { let start = self.memory as usize; let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); let last = &mut *last; + let exact = self.exact.swap(false, std::sync::atomic::Ordering::Relaxed); let alone = self.once.load(std::sync::atomic::Ordering::Relaxed); - if alone && last.hash.is_some() { + if alone && !exact && last.hash.is_some() { return 0; } if !alone && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { - if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { + if !exact && last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { return 0; } last.asked = now; @@ -1254,7 +1342,7 @@ impl Staging { last.hot_until = frame + HOT_FRAMES; } let hot = hot_textures() && frame < last.hot_until; - if unwritten && !turn && !hot { + if !exact && unwritten && !turn && !hot { return 0; } blind = unwritten; @@ -1273,7 +1361,7 @@ impl Staging { // stays mapped (see `crate::watch::title_memory_reading`; without // it a page went between the asking and the read in runs 71 and // 74). - let _mapped = if no_wait() { + let _mapped = if no_wait() && !exact { // Not waited for: while the runtime remaps title memory the // texture is read through the kernel instead, whole or not at // all (`no_wait`). @@ -1293,7 +1381,7 @@ impl Staging { // unmapped pages is slow, and nothing tells us when pages // arrive): a mip that streams in shows up to 30 frames late. let frame = crate::frame::current(); - if last.partial.is_some_and(|at| frame < at + 30) { + if !exact && last.partial.is_some_and(|at| frame < at + 30) { return 0; } last.partial = Some(frame); @@ -1857,6 +1945,13 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O let (piece, buffer, base, data) = match crate::pool::staging(host, total) { Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data), None => { + let speculative = PICKING.get().is_some() && !BAKING.get(); + if crate::residency::upload_refused() + || (speculative && !crate::residency::allow_staging_growth(false)) + { + crate::residency::note_staging_deferred(); + return None; + } let (buffer, data) = host.upload_buffer(total)?; crate::host::name(&buffer, || { format!( @@ -1899,6 +1994,7 @@ fn staging(resource: This, copy: &crate::resource::HostTexture, first: u32) -> O detiled: std::sync::atomic::AtomicU32::new(0), judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], waiting: std::sync::atomic::AtomicU64::new(0), + exact: std::sync::atomic::AtomicBool::new(BAKING.get()), }); map.insert(resource as usize, s.clone()); Some(s) diff --git a/crates/victory-gpu/src/texture/ahead.rs b/crates/victory-gpu/src/texture/ahead.rs index 4474435..2cfdde6 100644 --- a/crates/victory-gpu/src/texture/ahead.rs +++ b/crates/victory-gpu/src/texture/ahead.rs @@ -13,7 +13,7 @@ //! it as any texture. use std::collections::VecDeque; -use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed}; +use std::sync::atomic::{AtomicU8, AtomicU64, AtomicUsize, Ordering::Relaxed}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use windows::Win32::Graphics::Direct3D12::*; @@ -80,6 +80,7 @@ pub(crate) enum Taken { static QUEUE: (Mutex>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new()); /// Those on their way, by host copy ([`HostTexture::serial`]). static ON_THEIR_WAY: Mutex)>> = Mutex::new(Vec::new()); +static IN_FLIGHT: AtomicUsize = AtomicUsize::new(0); static LANDED: Condvar = Condvar::new(); static BYTES: AtomicU64 = AtomicU64::new(0); /// Since the start: uploads, bytes, microseconds from the asking until the @@ -103,7 +104,9 @@ fn claim(resource: This, first: u32, there: u64) -> Option { let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone())); } - if BYTES.load(Relaxed) >= MOST + let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST }; + if !crate::residency::allow_staging_growth(false) + || BYTES.load(Relaxed) >= most || copy.flags() & 0x7 != 0 || copy.state.load(Relaxed) != 0 || copy.grown.load(Relaxed) @@ -132,7 +135,11 @@ fn claim(resource: This, first: u32, there: u64) -> Option { } let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) }); BYTES.fetch_add(job.staging.read as u64, Relaxed); - ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone())); + { + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + way.push((job.copy.serial, job.clone())); + IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release); + } Some(Taken::New(job)) } @@ -142,6 +149,25 @@ pub(crate) fn send(job: &Arc) { QUEUE.1.notify_one(); } +/// Waits until every upload currently on its way here has finished copying +/// and run its completion callbacks (queuing slot flips into `FLIPS`). +/// Returns how many jobs were waited for. +pub(crate) fn drain() -> usize { + if IN_FLIGHT.load(std::sync::atomic::Ordering::Acquire) == 0 { + return 0; + } + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + let waiting = way.len(); + let started = std::time::Instant::now(); + while !way.is_empty() && started.elapsed().as_millis() < 2000 { + way = LANDED + .wait_timeout(way, std::time::Duration::from_millis(50)) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + waiting +} + /// A list is about to record an upload into `copy`: one on its way here runs /// first, and no other is taken after it. pub(crate) fn listed(copy: &HostTexture) { @@ -291,11 +317,6 @@ fn finish(jobs: Vec>) { job.copy.ahead.store(DONE, Relaxed); BYTES.fetch_sub(job.staging.read as u64, Relaxed); } - { - let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); - way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial)); - LANDED.notify_all(); - } for job in &jobs { let us = job.asked.elapsed().as_micros() as u64; let n = STATS[0].fetch_add(1, Relaxed) + 1; @@ -317,6 +338,14 @@ fn finish(jobs: Vec>) { f(); } } + // Remove from `ON_THEIR_WAY` only after `job.then` callbacks have queued + // their `FLIPS` entries so `drain()` observes every flip ready to apply. + { + let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()); + way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial)); + IN_FLIGHT.store(way.len(), std::sync::atomic::Ordering::Release); + LANDED.notify_all(); + } crate::descriptor::host::flip_now(); } @@ -414,4 +443,31 @@ mod tests { back.Unmap(0, None); } } + + #[test] + fn drain_waits_until_then_callbacks_have_run() { + use std::sync::atomic::AtomicBool; + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + let Some(_host) = crate::host::host() else { return }; + let desc = [3u32, 0, 0, 0, 128, 0, 128, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let whole = crate::resource::placed_bytes(&desc).unwrap() as usize; + // SAFETY: memory of our own that stays for the test. + let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::(); + // SAFETY: as above. + unsafe { std::ptr::write_bytes(at, 0x5a, whole) }; + let texture = crate::resource::texture_at(at as u64, &desc).unwrap(); + crate::resource::want_level(texture, 0); + let copy = crate::resource::host_copy(texture).unwrap(); + if !crate::pool::fresh(©.texture) { + return; + } + let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") }; + let ran = Arc::new(AtomicBool::new(false)); + let flag = ran.clone(); + job.then(move || flag.store(true, std::sync::atomic::Ordering::Release)); + send(&job); + assert!(drain() >= 1); + assert!(ran.load(std::sync::atomic::Ordering::Acquire), "job.then callback must run before drain() returns"); + assert_eq!(drain(), 0); + } } diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 8da3346..0951144 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -517,7 +517,16 @@ fn pump(context: Context, voice: &mut Voice) { return; } while context.field(1, 31, 1) == 1 { - if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + // A skipped frame or an input boundary can advance the decoder without + // producing samples. Publish only complete blocks, except the final + // padded tail. Limit empty steps so a broken looping voice cannot hold + // its lock or stall other voices for the whole decoding pass. + for _ in 0..8 { + if voice.pcm.len() >= SAMPLES_PER_BLOCK || !decode(context, voice) { + break; + } + } + if voice.pcm.is_empty() || (voice.pcm.len() < SAMPLES_PER_BLOCK && !voice.ended) { return; } // The write block is the title's too: taken modulo the ring before @@ -549,12 +558,21 @@ fn pump(context: Context, voice: &mut Voice) { /// Decodes the next frame of the current input into `voice.pcm`; false /// when there is nothing left to decode. fn decode(context: Context, voice: &mut Voice) -> bool { + let valid = context.field(0, 20, 2); if voice.ended { - return false; + // The title can refill either input while the context stays enabled. + // Flush the previous tail once and leave the ring idle until a valid + // buffer is published. The decoder resets its overlap when flushed. + if valid == 0 { + return false; + } + voice.ended = false; + if context.field(2, 26, 5) == INPUT_INVALID { + context.set_field(2, 26, 6, 0); + } } let channels = context.channels(); let mut current = context.field(4, 31, 1); - let valid = context.field(0, 20, 2); if valid & (1 << current) == 0 { if valid & (1 << (1 - current)) == 0 { // Out of input: the overlap tail, then nothing. diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index a44d599..14911cd 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -227,11 +227,20 @@ extern "system" fn create_queue( ) } -/// The title asks for 32 MiB and stops if this fails. +/// The title asks for 32 MiB and stops if this fails. Give PC worker threads +/// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't +/// starve the remaining cores. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { - tracing::info!(size, "dstorage: staging buffer size"); + static FLOOR_MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let floor = *FLOOR_MB.get_or_init(|| { + std::env::var("VICTORY_DSTORAGE_STAGING_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(256) + }) << 20; + tracing::info!(size, floor, "dstorage: staging buffer size"); if let Some(scheduler) = scheduler() { - scheduler.lock().staging = u64::from(size); + scheduler.lock().staging = u64::from(size).max(floor); } S_OK } diff --git a/crates/victory-hle/src/modules/ffx.rs b/crates/victory-hle/src/modules/ffx.rs new file mode 100644 index 0000000..0611f4a --- /dev/null +++ b/crates/victory-hle/src/modules/ffx.rs @@ -0,0 +1,250 @@ +//! `amd_fidelityfx_loader_xbox.dll`: the upscale dispatch. +//! +//! The title's Series S mode renders below its output size and calls the +//! console's FidelityFX upscaler to make the output. The loader and the +//! upscaler are the title's own DLLs and run as they are, but the +//! upscaler's passes are compute pipelines in a container we do not +//! translate: its output stayed black. `ffxDispatch` alone is taken here: +//! an upscale dispatch becomes a plain stretch of the colour input +//! (`victory_gpu::list::upscale_stretch`); anything else, and an upscale we +//! could not stretch, goes to the title's DLL. +//! +//! The structures are the public FidelityFX API's (`ffx_api.h`, +//! `ffx_upscale.h`): a header of a type and a next pointer, and resources of +//! a pointer, a 32-byte description and a state. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; + + +/// The DLL whose `ffxDispatch` is taken. +pub const LOADER: &str = "amd_fidelityfx_loader_xbox.dll"; + +static REAL: AtomicUsize = AtomicUsize::new(0); + +/// The title's own `ffxDispatch`, for what is not stretched here. +pub fn set_real_dispatch(address: usize) { + REAL.store(address, Ordering::Relaxed); +} + +#[repr(C)] +struct Header { + kind: u64, + next: *const Header, +} + +#[repr(C)] +struct Resource { + resource: *const c_void, + description: [u32; 8], + state: u32, +} + +#[repr(C)] +struct Upscale { + header: Header, + list: *const c_void, + colour: Resource, + depth: Resource, + motion: Resource, + exposure: Resource, + reactive: Resource, + composition: Resource, + output: Resource, + jitter: [f32; 2], + motion_scale: [f32; 2], + render: [u32; 2], + upscale: [u32; 2], + // The rest of `ffxDispatchDescUpscale` (`ffx_upscale.h`), read by the + // probe only. + enable_sharpening: u8, + sharpness: f32, + frame_time_delta: f32, + pre_exposure: f32, + reset: u8, + camera_near: f32, + camera_far: f32, + camera_fov: f32, + view_to_meters: f32, + flags: u32, +} + +/// `VICTORY_UPSCALE_PROBE=1`: logs what the title gives each upscale (the +/// inputs a temporal upscaler such as DLSS or FSR 2 needs), now and then. +fn probe() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_UPSCALE_PROBE").is_some_and(|v| v == "1")) +} + +const _: () = assert!(size_of::() == 48); +const _: () = assert!(std::mem::offset_of!(Upscale, output) == 0x138); + +/// `FFX_API_RETURN_ERROR`: what a dispatch nothing could answer returns. +const ERROR: u32 = 1; + +/// `FFX_API_DISPATCH_DESC_TYPE_UPSCALE`. +const UPSCALE: u64 = 0x0001_0001; + +type Dispatch = extern "system" fn(*mut *mut c_void, *const Header) -> u32; + +extern "system" fn dispatch(context: *mut *mut c_void, desc: *const Header) -> u32 { + // SAFETY: the title passes a dispatch description, whose header says + // what follows it. + if let Some(header) = unsafe { desc.as_ref() } { + static SEEN: AtomicU32 = AtomicU32::new(0); + let first = SEEN.fetch_add(1, Ordering::Relaxed) < 4; + if header.kind == UPSCALE { + // SAFETY: an upscale description, by its type. + let d = unsafe { &*desc.cast::() }; + if first { + tracing::info!( + list = ?d.list, + colour = ?d.colour.resource, + colour_size = ?(d.colour.description[2], d.colour.description[3]), + output = ?d.output.resource, + output_size = ?(d.output.description[2], d.output.description[3]), + render = ?d.render, + upscale = ?d.upscale, + "upscale dispatch" + ); + } + #[cfg(windows)] + if probe() { + static N: AtomicU32 = AtomicU32::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + // the first 12 upscales, then one in 300 + if n < 12 || n.is_multiple_of(300) { + let inputs = victory_gpu::list::upscale_inputs(&[ + d.colour.resource, + d.depth.resource, + d.motion.resource, + d.exposure.resource, + d.reactive.resource, + d.composition.resource, + d.output.resource, + ]); + tracing::info!( + n, + colour = %inputs[0], + depth = %inputs[1], + motion = %inputs[2], + exposure = %inputs[3], + reactive = %inputs[4], + composition = %inputs[5], + output = %inputs[6], + jitter = ?d.jitter, + motion_scale = ?d.motion_scale, + render = ?d.render, + upscale = ?d.upscale, + sharpening = d.enable_sharpening, + sharpness = d.sharpness, + frame_time_delta = d.frame_time_delta, + pre_exposure = d.pre_exposure, + reset = d.reset, + near = d.camera_near, + far = d.camera_far, + fov = d.camera_fov, + meters = d.view_to_meters, + flags = format_args!("{:#x}", d.flags), + "upscale probe" + ); + } + } + #[cfg(windows)] + { + let up = victory_gpu::list::Upscale { + colour: d.colour.resource as u64, + depth: d.depth.resource as u64, + motion: d.motion.resource as u64, + exposure: d.exposure.resource as u64, + output: d.output.resource as u64, + render: d.render, + jitter: d.jitter, + motion_scale: d.motion_scale, + reset: d.reset != 0, + pre_exposure: d.pre_exposure, + near: d.camera_near, + far: d.camera_far, + frame_ms: d.frame_time_delta, + dlss: std::env::var_os("VICTORY_UPSCALE").is_some_and(|v| v == "dlss"), + }; + if victory_gpu::list::upscale(d.list, &up) { + return 0; + } + } + if first { + tracing::warn!("upscale dispatch not stretched: left to the title's upscaler"); + } + } else if first { + tracing::info!( + kind = format_args!("{:#x}", header.kind), + "another FidelityFX dispatch" + ); + } + } + match REAL.load(Ordering::Relaxed) { + // Neither stretched nor passed on: the output was not written, and + // the title is told so instead of presenting it as it is. + 0 => { + static TOLD: std::sync::Once = std::sync::Once::new(); + TOLD.call_once(|| { + tracing::error!( + "a FidelityFX dispatch was not answered: no stretch was recorded and the title's own ffxDispatch was not found" + ); + }); + ERROR + } + // SAFETY: the title's own `ffxDispatch`, with its own arguments. + real => unsafe { std::mem::transmute::(real)(context, desc) }, + } +} + +/// What the title's import of `ffxDispatch` is bound to. The DLL is not an +/// HLE module: the title's own must load, for its other entry points and +/// for the dispatches passed on. +pub fn dispatch_address() -> usize { + dispatch as *const () as usize +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::offset_of; + + /// The upscale description as the public API lays it out: what the + /// stretch reads sits where the title wrote it. + #[test] + fn the_upscale_description_is_laid_out_as_the_public_api() { + assert_eq!(size_of::
(), 16); + assert_eq!(offset_of!(Upscale, list), 0x10); + assert_eq!(offset_of!(Upscale, colour), 0x18); + assert_eq!(offset_of!(Upscale, depth), 0x48); + assert_eq!(offset_of!(Upscale, motion), 0x78); + assert_eq!(offset_of!(Upscale, output), 0x138); + assert_eq!(offset_of!(Upscale, jitter), 0x168); + assert_eq!(offset_of!(Upscale, motion_scale), 0x170); + assert_eq!(offset_of!(Upscale, render), 0x178); + assert_eq!(offset_of!(Upscale, upscale), 0x180); + assert_eq!(offset_of!(Upscale, enable_sharpening), 0x188); + assert_eq!(offset_of!(Upscale, sharpness), 0x18c); + assert_eq!(offset_of!(Upscale, reset), 0x198); + assert_eq!(offset_of!(Upscale, camera_near), 0x19c); + assert_eq!(offset_of!(Upscale, flags), 0x1ac); + assert_eq!(offset_of!(Resource, description), 8); + assert_eq!(offset_of!(Resource, state), 40); + } + + /// A dispatch that is not an upscale, with no DLL of the title's to + /// pass it to, is an error and not a silent success. + #[test] + fn a_dispatch_nothing_answers_is_an_error() { + let before = REAL.swap(0, Ordering::Relaxed); + let other = Header { + kind: 0x0002_0001, + next: std::ptr::null(), + }; + assert_eq!(dispatch(std::ptr::null_mut(), &other), ERROR); + assert_eq!(dispatch(std::ptr::null_mut(), std::ptr::null()), ERROR); + REAL.store(before, Ordering::Relaxed); + } +} diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 424c0ed..5d78b80 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1259,7 +1259,6 @@ mod host { // pad's buttons, by the stand-in pad's table: with a real pad // connected the stand-in is not there, and a title that listens // to the pad (the title's start screen) saw nothing. - #[cfg(feature = "diagnostics")] if slot == 0 { for vk in scripted() { if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { @@ -1271,10 +1270,11 @@ mod host { } fn keys(&mut self) -> Vec { - #[cfg(feature = "diagnostics")] let mut down = scripted(); - #[cfg(not(feature = "diagnostics"))] - let mut down = Vec::new(); + // LOCAL (11/26): the F1 settings menu takes the keyboard while shown. + if victory_gpu::SETTINGS_MENU_OPEN.load(std::sync::atomic::Ordering::Relaxed) { + return Vec::new(); + } if focused_window().is_some() { // Left/right modifier keys only, as devices report them; no // mouse buttons (below 0x08). @@ -1348,7 +1348,6 @@ mod host { /// time), with or without focus. A key is a /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, /// `Left`, `Right` (the stand-in pad's table maps them to buttons). - #[cfg(feature = "diagnostics")] fn scripted() -> Vec { static SCRIPT: LazyLock<(Instant, Vec<(Duration, Duration, u8)>)> = LazyLock::new(|| { let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 7f8a931..7efb196 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -17,6 +17,7 @@ pub mod dsp; #[cfg(windows)] pub mod dstorage; #[cfg(windows)] +pub mod ffx; pub mod files; pub mod gameinput; pub mod kernel; diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs index 8d09700..f3582c9 100644 --- a/crates/victory-shader/src/emit/diff_tests.rs +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -1228,12 +1228,43 @@ fn translated_compute_matches_pc() { let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); root_views.sort_unstable(); + let view_strides: Vec = views + .iter() + .map(|v| match *v { + View::RawUav(_) => 1, + View::HalfUav(_) => 8, + View::Buffer { stride, .. } => match stride { + Stride::Raw => 1, + Stride::Typed => 16, + Stride::Structured(s) => s, + Stride::Format(f, bytes) => { + let kind = match f.0 as u32 { + 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62 => { + super::VIEW_INTEGER + } + 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64 => { + super::VIEW_INTEGER | super::VIEW_SIGNED + } + _ => 0, + }; + bytes | kind + } + }, + _ => 0, + }) + .collect(); for (n, (slot, srv)) in root_views.into_iter().enumerate() { - assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); - let data = if srv { - root_srv.clone() + let data = if srv + && (slot == super::SLOT_STRIDES || slot == super::SLOT_TABLE_STRIDES) + { + view_strides.clone() } else { - root_cbv.clone() + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + if srv { + root_srv.clone() + } else { + root_cbv.clone() + } }; roots.push((1 + n as u32, Root::View { srv, data })); } diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs index 3fbc2b9..9fbf373 100644 --- a/crates/victory-shader/src/emit/host.rs +++ b/crates/victory-shader/src/emit/host.rs @@ -1006,6 +1006,12 @@ pub enum View<'a> { UintTextureUav(u32, u32), /// A typed RGBA16F buffer UAV of this many elements, zeroed. HalfUav(u32), + /// A typed buffer UAV pre-filled with `data` (`format`, bytes per element). + TypedUav { + data: &'a [u32], + format: DXGI_FORMAT, + elem_bytes: u32, + }, /// The same buffer viewed as R16G16B16A16_UINT: what a translated /// program that moves halves is shown ([`super::HostShader::half_views`]). HalfUintUav(u32), @@ -1290,6 +1296,46 @@ impl Host { )?; uavs.push((b, None, n, rb)); } + View::TypedUav { + data, + format, + elem_bytes, + } => { + let n = data.len() as u32; + let bytes = u64::from(n) * 4; + let elements = (bytes / u64::from(elem_bytes)) as u32; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let up = upload(data)?; + list.CopyBufferRegion(&b, 0, &up, 0, bytes); + list.ResourceBarrier(&[transition( + &b, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + keep.push(up); + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: elements, + Flags: D3D12_BUFFER_UAV_FLAG_NONE, + ..Default::default() + }, + }, + }; + dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, n, rb)); + } View::TextureUav(w, h) => { let t = make( D3D12_HEAP_TYPE_DEFAULT, diff --git a/crates/victory-shader/src/emit/intersect.rs b/crates/victory-shader/src/emit/intersect.rs index 66665ef..b32afa8 100644 --- a/crates/victory-shader/src/emit/intersect.rs +++ b/crates/victory-shader/src/emit/intersect.rs @@ -59,14 +59,6 @@ struct Ray { inverse: [V; 3], } -/// LOCAL (from our wt5): `VICTORY_BVH_MISS=1` (off by default): the node test -/// misses every node. While the structure builder is off the structures are -/// never built, and a walk of what lies in their memory is not the console's. -fn bvh_miss() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_MISS").is_some_and(|v| v == "1")) -} - impl<'a> Lower<'a> { /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`. pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { @@ -199,22 +191,11 @@ impl<'a> Lower<'a> { .m .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join)); self.cur = box_block; - // LOCAL (from our wt5): with `VICTORY_BVH_MISS=1` every node is missed - // without being read: a box returns no child and a triangle the - // triangle miss, so a walk ends at its first node. - let boxes = if bvh_miss() { - [self.s.m.i32(bvh::NONE); 4] - } else { - self.bvh_boxes(at, kind, &ray, sort) - }; + let boxes = self.bvh_boxes(at, kind, &ray, sort); let box_end = self.cur; self.s.m.terminate(box_end, Term::Br(join)); self.cur = triangle_block; - let triangle = if bvh_miss() { - bvh::MISS.map(|f| self.s.m.i32(f.to_bits())) - } else { - self.bvh_triangle(at, kind, &ray) - }; + let triangle = self.bvh_triangle(at, kind, &ray); let triangle_end = self.cur; self.s.m.terminate(triangle_end, Term::Br(join)); self.cur = join; diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 326f88f..e242e19 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -441,6 +441,7 @@ enum MaskData { /// What a value holding a lane mask read as a number stops with. pub(super) const LANE_MASK: Why = "a lane mask read as data"; +pub(super) const DIVERGENT_MASK_EXCHANGE: Why = "a lane mask exchanged where not every lane runs"; /// A mask with lanes outside EXEC where it is written, read as a number where the lanes that /// run that block are not all of the wave. pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; @@ -564,7 +565,7 @@ fn need(block: usize) { /// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. /// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes /// run (no lane branch can have split the arriving lanes); loop-carried values never do. -fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { +fn lane_uniform(p: &Program, st: &Structured, all: &[bool], ordered_lds: bool) -> HashSet { let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let mut same: HashSet = HashSet::new(); for b in crate::ir::reverse_postorder(&p.blocks) { @@ -577,6 +578,9 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { } for (i, inst) in block.insts.iter().enumerate() { let name = inst.name(); + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } let ops: Vec = match &inst.fields { Fields::Valu(v) if v.dpp.is_none() @@ -587,11 +591,18 @@ fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { { v.src.clone() } + Fields::Ds { + addr: Some(Operand::Vector { reg, dwords: 1 }), + gds: false, + .. + } if ordered_lds && name == "ds_read_b32" => { + if inst.read(Reg::V(*reg)).is_some_and(|a| same.contains(&a)) { + same.extend(inst.writes.iter().map(|w| w.1)); + } + continue; + } _ => continue, }; - if st.guards[b][i].is_some() { - continue; // lanes outside EXEC keep another value - } let alike = ops.iter().all(|op| match *op { Operand::Vector { reg, .. } => { // every dword of the operand the instruction reads from that register on @@ -1193,6 +1204,13 @@ thread_local! { } pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + // A scalar select uses the condition of the whole guest wave, even + // when the preceding mask operation has no scalar-dword consumers. + if matches!(i.fields, Fields::Sop { .. } | Fields::Valu(_)) + && i.read(Reg::Scc).is_some_and(|s| st.scc_some.contains_key(&s)) + { + return true; + } let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); let ops: Vec<&Operand> = match &i.fields { // A mask operation (its result a mask) is no data use. @@ -1698,7 +1716,9 @@ impl<'a> Lower<'a> { local_ok: false, local_any: LOCAL_ANY.get(), uniform: match &exchange { - Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + Some((_, false, all)) if !LOCAL_WAVES.get() => { + lane_uniform(p, x.st, all, split_lds && super::group_sync() != 0) + } _ => HashSet::new(), }, own_bits: match &exchange { @@ -3549,7 +3569,7 @@ impl<'a> Lower<'a> { } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { // (a group of 32 or fewer has no other half to exchange with) need(b.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } xy = self.exchange_halves(at, xy.0); } @@ -4250,7 +4270,7 @@ impl<'a> Lower<'a> { } if !made.is_none_or(|b| self.all_lanes(b)) { need(made.unwrap_or(0)); - return Err("a lane mask exchanged where not every lane runs"); + return Err(DIVERGENT_MASK_EXCHANGE); } let some = self.s.m.cast(at, Cast::ZExt, some, i32t); let (lo, hi) = self.exchange_halves(at, some); @@ -6049,6 +6069,13 @@ impl<'a> Lower<'a> { fn scc_in(&mut self, inst: &Inst) -> Result { let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + if self.x.st.scc_some.contains_key(&v) + && matches!(self.vals.get(&v), None | Some(Val::Missing(_))) + { + let x = self.scc_some(v)?; + self.vals.insert(v, Val::Bit(x)); + return Ok(x); + } match self.get(v) { Ok(Val::Bit(x)) => Ok(x), Ok(_) => Err("SCC without a value"), @@ -7526,7 +7553,7 @@ impl<'a> Lower<'a> { /// `ResourceHeap`): read from the host's table by heap slot in the /// current block. fn slot_stride(&mut self, src: &Source) -> Result, Why> { - let word = self.slot_word(src)?; + let word = self.slot_word(src, false)?; Ok(word.map(|word| { let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS); let stride = self.s.m.bin(self.cur, Bin::And, word, bits); @@ -7549,18 +7576,17 @@ impl<'a> Lower<'a> { if !super::shader::constant_marks() { return Ok(None); } - let Some(word) = self.slot_word(src)? else { + let Some(word) = self.slot_word(src, false)? else { return Ok(None); }; - let mark = self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); + let mark =self.s.m.i32(super::shader::SLOT_STRIDE_CONSTANT); Ok(Some(self.s.m.cmp(self.cur, pred::EQ, word, mark))) } /// Whether the typed buffer view `src` names is one of an integer format, - /// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the - /// program does not pick from the heap). + /// and whether a signed one (`ResourceHeap` or `Table`). fn integer_view(&mut self, src: &Source) -> Result, Why> { - let Some(word) = self.slot_word(src)? else { + let Some(word) = self.slot_word(src, true)? else { return Ok(None); }; let c = self.cur; @@ -7574,19 +7600,22 @@ impl<'a> Lower<'a> { } /// The host's word for the buffer view `src` names: its stride and - /// format kind ([`super::shader::SLOT_STRIDES`]). - fn slot_word(&mut self, src: &Source) -> Result, Why> { + /// format kind ([`super::shader::SLOT_STRIDES`] for `ResourceHeap`, + /// [`super::shader::SLOT_TABLE_STRIDES`] for `Table` when `allow_table`). + fn slot_word(&mut self, src: &Source, allow_table: bool) -> Result, Why> { let Source::Loaded { load, first } = src else { return Ok(None); }; - let heap = self + let srv_slot = match self .scalar .get(load) .and_then(|a| self.x.native.layout.get(a.param)) - .is_some_and(|p| p.root == RootType::ResourceHeap); - if !heap { - return Ok(None); - } + .map(|p| p.root) + { + Some(RootType::ResourceHeap) => super::shader::SLOT_STRIDES, + Some(RootType::Table) if allow_table => super::shader::SLOT_TABLE_STRIDES, + _ => return Ok(None), + }; let key = (self.cur, *load, *first); if let Some(&v) = self.strides.get(&key) { return Ok(Some(v)); @@ -7601,7 +7630,7 @@ impl<'a> Lower<'a> { self.s.m.tag(slot, Tag::Clamp); let two = self.s.m.i32(2); let byte = self.s.m.bin(c, Bin::Shl, slot, two); - let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); + let h = self.s.root_srv_handle(srv_slot); let iu = self.s.m.undef(self.s.t.i32); let mask = self.s.m.i8(1); let align = self.s.m.i32(4); @@ -7769,6 +7798,15 @@ impl<'a> Lower<'a> { unreachable!() }; let name = inst.name(); + if let Some(&source) = self.x.res.restored_lanes.get(&(b, i)) { + // This lane was overwritten by a uniform scalar. The previous + // contents of other lanes can be unknown (a reduction scratch). + let word = match source { + crate::resource::Moved::Value(v) => self.i32_of(v)?, + crate::resource::Moved::Const(k) => self.s.m.i32(k), + }; + return self.write_i(inst, word, None); + } if self.x.res.waterfall.compares.contains(&(b, i)) { // The first lane's dwords of a waterfall loop are each lane's // own (see `resource::Waterfall`). @@ -11963,9 +12001,13 @@ impl<'a> Lower<'a> { // through a view of an integer format it is a 16-bit // integer, zero- or sign-extended (VIctory 4243a96a: the face // network keeps its halves in UINT views; its output was - // noise). shortcut: that is known of the views a program - // picks from the heap; and the handle stays a float one, - // whose bits the drivers pass. + // noise). Both `ResourceHeap` (`SLOT_STRIDES`) and `Table` + // (`SLOT_TABLE_STRIDES`, dynamic table snapshots included) + // populate the view-kind bits, while the handle stays a float + // one (`0x409`), whose raw bits RTX and WARP pass bit-exact + // without extra CFG blocks or touching non-d16 shaders. + // LOCAL (faces): not where the program moves halves as + // integers (`halves`): those views are shown as UINT already. let integer = if typed && !halves { self.integer_view(src)? } else { None }; let mut wide = Vec::new(); for k in 0..count { diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index 85a9e0f..8404cc9 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -122,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna}; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDE_CONSTANT, SLOT_STRIDES_COUNT, SLOT_TABLE_STRIDES, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS, constant_marks, raw_views, set_raw_views, set_view_heap_limit, view_heap_limit, }; @@ -500,17 +500,45 @@ pub fn emit( }; // The program in two other forms: without its early-outs, and // without any branch that only skips code no lane is left for. - let form = |p: Option| { - p.and_then(|p| { - let st = structure::structure(&p).ok()?; - let io = io::raise(&p, native).ok()?; - let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; - Some((p, st, io, res)) - }) + let form = |label: &str, p: Option| { + let Some(p) = p else { + if why { + eprintln!("WAVE64-FORM {label}: ir returned None"); + } + return None; + }; + let st = match structure::structure(&p) { + Ok(st) => st, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: structure failed: {e}"); + } + return None; + } + }; + let io = match io::raise(&p, native) { + Ok(io) => io, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: io::raise failed: {e}"); + } + return None; + } + }; + let res = match resource::track(&p, &native.layout, native.stage, Some(&st)) { + Ok(res) => res, + Err(e) => { + if why { + eprintln!("WAVE64-FORM {label}: resource::track failed: {e}"); + } + return None; + } + }; + Some((p, st, io, res)) }; let forms = [ - ("without early-outs", form(ir::without_early_outs(p))), - ("without skips", form(ir::without_skips(p, false))), + ("without early-outs", form("without early-outs", ir::without_early_outs(p))), + ("without skips", form("without skips", ir::without_skips(p, false))), ]; for (name, f) in &forms { if let Some((p, st, io, res)) = f { @@ -526,7 +554,24 @@ pub fn emit( // lost the card in a submission of two programs that had just moved to it // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which // has no barrier, stays on. - let wide_on = std::env::var_os("VICTORY_WAVE_WIDE").is_some_and(|v| v == "1"); + let wide_option = std::env::var_os("VICTORY_WAVE_WIDE"); + // Both archived kernels use one logical wave per group and have + // validated wave32 PSOs on RTX. Explicit policy wins. + let scene_kernel = matches!(native.io, crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64) + && matches!( + c.digest, + [0x58, 0x1d, 0xab, 0x2c, 0xd8, 0xbc, 0xf2, 0x2e, 0x5c, 0x96, 0x4b, 0x98, 0xe9, 0x03, 0x48, 0xd1] + | [0x24, 0x31, 0xbb, 0xe7, 0xdc, 0x15, 0x4a, 0xd7, 0x59, 0xd2, 0x0b, 0xc9, 0x54, 0x82, 0x9c, 0x1c] + ); + let wide_on = wide_option.as_ref().map_or(scene_kernel, |v| v == "1"); + // A single guest wave can iterate an active-lane loop until both host + // halves have finished. The precise latch and convergence conditions + // for the driver compute route are checked by widen(). + let driver_loop = wide_option.is_none() + && c.part(FourCC::DXIL).is_none() + && c.part(FourCC::ACCC).is_some() + && matches!(&original, Err(ShaderError::Unsupported { what, .. }) + if *what == lower::DIVERGENT_MASK_EXCHANGE); // exact first: each host wave on its own where that is exact (the idiom, every // form; no barriers), then the other exact forms; then approximate for exact in [true, false] { @@ -537,7 +582,7 @@ pub fn emit( // lane runs, where the two host waves can exchange. // (`VICTORY_WAVE_DEEP_SKIPS=0` and `VICTORY_WAVE_WIDE=0` turn the two off.) let deep_on = std::env::var_os("VICTORY_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); - let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; + let deep = if deep_on { form("without skips, scalars followed", ir::without_skips(p, true)) } else { None }; if let Some((p, st, io, res)) = &deep { let again = emit_program(c, native, p, st, io, res); report("without skips, scalars followed", &again); @@ -548,7 +593,7 @@ pub fn emit( // Still stopped where not every lane runs: the per-lane branches around // those places taken as the console takes them, by the whole wave at once // ([`widen`]), at two group barriers per such branch. - if wide_on { + if wide_on || driver_loop { let bases = [ deep.as_ref().map(|f| &f.0), forms[1].1.as_ref().map(|f| &f.0), @@ -556,7 +601,7 @@ pub fn emit( Some(p), ]; if let Some(base) = bases.into_iter().flatten().next() { - let again = widen(c, native, base, why); + let again = widen(c, native, base, why, driver_loop); report("wave-wide branches", &again); if done(&again) { return again.map(|(shader, _)| shader); @@ -618,7 +663,7 @@ pub fn emit( && what == lower::LANE_MASK && std::env::var_os("VICTORY_WAVE_WIDE").is_none_or(|v| v != "0") => { - let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some()); + let again = widen(c, native, p, std::env::var_os("VICTORY_WAVE_WHY").is_some(), false); match again { Ok(_) => again, Err(_) => emit_program(c, native, p, st, io, res), @@ -626,7 +671,17 @@ pub fn emit( } other => other, }; - let original = original.map(|(shader, _)| shader); + let supported = |(shader, wave): (HostShader, Option)| { + if wave == Some(64) && lower::host_max_wave() == 32 { + Err(ShaderError::Unsupported { + offset: 0, + what: "no wave32 lowering for this wave64 program", + }) + } else { + Ok(shader) + } + }; + let original = original.and_then(supported); // Retry unsupported programs only. Threading can separate an unknown // register value from its apparent use on a mutually exclusive path. if !matches!(original, Err(ShaderError::Unsupported { .. })) { @@ -640,7 +695,7 @@ pub fn emit( let st = structure::structure(&p)?; let io = io::raise(&p, native)?; let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; - emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) + emit_program(c, native, &p, &st, &io, &res).and_then(supported) } /// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane @@ -655,6 +710,7 @@ fn widen( native: &NativeProgram, p: &ir::Program, why: bool, + active_loop_only: bool, ) -> Result<(HostShader, Option), ShaderError> { const NOT: ShaderError = ShaderError::Unsupported { offset: 0, @@ -687,7 +743,22 @@ fn widen( || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); if !stuck { if why { - eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + let order = ir::reverse_postorder(&p.blocks); + let mut rpo = vec![0usize; p.blocks.len()]; + for (i, &b) in order.iter().enumerate() { + rpo[b] = i; + } + let mut sorted: Vec = wide.iter().copied().collect(); + sorted.sort_unstable(); + let desc: Vec = sorted + .iter() + .map(|&b| { + let back = matches!(p.blocks[b].exit, ir::Exit::Branch { taken, not_taken } if rpo[taken] <= rpo[b] || rpo[not_taken] <= rpo[b]); + let nm = p.blocks[b].insts.last().map_or("?", |i| i.name()); + format!("B{b}({nm}{})", if back { ",BACK" } else { "" }) + }) + .collect(); + eprintln!("WAVE64-WIDE {} branches taken wave-wide: [{}]", wide.len(), desc.join(", ")); } return r; } @@ -702,6 +773,30 @@ fn widen( } return r; } + if active_loop_only { + // Only a single backward branch on the SCC just set by + // s_andn2_wrexec_b64. This instruction restricts EXEC to the + // unfinished lanes. The guest repeats the loop if *either* + // half still has work, while individual vector writes retain + // their EXEC predicates. + let [latch] = more.as_slice() else { + return r; + }; + let block = &p.blocks[*latch]; + let [.., update, branch] = block.insts.as_slice() else { + return r; + }; + if !wide.is_empty() + || update.name() != "s_andn2_wrexec_b64" + || branch.name() != "s_cbranch_scc1" + || !matches!( + block.exit, + ir::Exit::Branch { taken, not_taken } if taken <= *latch && not_taken > *latch + ) + { + return r; + } + } wide.extend(more); } } diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs index 4a44a92..34f0e2c 100644 --- a/crates/victory-shader/src/emit/shader.rs +++ b/crates/victory-shader/src/emit/shader.rs @@ -24,6 +24,11 @@ pub const ROOT_CBV_SPACE: u32 = 1; /// root SRV also tells the host that the buffer views of the whole heap /// must be ready when it runs, not only those its tables name. pub const SLOT_STRIDES: u8 = 255; +/// The same table of strides and format kinds as [`SLOT_STRIDES`], bound for +/// shaders that only inspect views from descriptor tables (`RootType::Table`). +/// Kept distinct from [`SLOT_STRIDES`] so the host binds the table without +/// running the full bindless heap buffer sweep. +pub const SLOT_TABLE_STRIDES: u8 = 252; /// The bits of a [`SLOT_STRIDES`] dword that hold the stride. pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1; /// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index f3067d2..6622452 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -181,7 +181,6 @@ fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { @@ -1919,7 +1918,6 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: Vec::new(), - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -2060,76 +2058,48 @@ fn rdna_forms_give_what_the_spelled_out_ones_give() { } } -/// A program that moves a typed buffer's 16-bit channels -/// (`buffer_load_format_d16_xyzw` from the table's first view, -/// `buffer_store_format_d16_xyzw` to its second) names both places for the -/// host (`HostShader::half_views`) and moves every pattern as it is through -/// unsigned views: half floats, the not-a-number ones among them, and -/// plain 16-bit integers (the title keeps both in such buffers; the -/// network that moves its faces reads indices this way). A program that -/// moves no halves names nothing. -#[test] -fn halves_go_through_a_table_as_they_are_and_name_their_views() { - use super::host::Stride; - use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_UINT; - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_D16_XYZW: u32 = 0x83; - const STORE_D16_XYZW: u32 = 0x87; - const THREADS: u32 = 32; - // The table's second descriptor, 0x20 bytes on. - let mut second = s_load_dwordx4(12, 4); - second[1] |= 0x20; - let mut words = vec![s_mov_b32(5, 0x80)]; - words.extend_from_slice(&s_load_dwordx4(8, 4)); - words.extend_from_slice(&second); - // v[1:2] = first[thread] (four halves), second[thread] = v[1:2]. - words.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - words.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); +/// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. +const fn mubuf_idxen(op: u8, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { + [ + 0x38 << 26 | (op as u32) << 18 | 1 << 13, + 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, + ] +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], byte_offset` (soffset = null). +const fn s_load_dwordx4_off(dst: u8, base: u8, byte_offset: u32) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + (125 << 25) | (byte_offset & 0x1F_FFFF), + ] +} + +/// Builds a compute shader whose descriptors live in a `RootType::Table` at +/// `s4` (like `compute_graph_ops` and `ped_standard_head_cs`). +fn build_table_typed_cs(body: &[u32], used: Vec) -> HostShader { + let mut words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); // s5 = 0 + words.extend_from_slice(body); words.push(S_ENDPGM); - let view = |kind: ResourceType, table_offset_dwords: u32| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, - stride: 4, - dwords: 4, - user_data: 4, - slot: 1, - }; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let native = NativeProgram { stage: HwStage::Cs, wave64: false, vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![view(ResourceType::Srv, 0), view(ResourceType::Uav, 8)], + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 0, + }], + used, io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [THREADS, 1, 1], + rsrc2: 5 << 1, // 5 user SGPRs: s0..s4 + threads: [4, 1, 1], }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + code, }; let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let st = structure::structure(&p).expect("structure"); @@ -2148,7 +2118,6 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() { mesh_stride: 0, }) .expect("lower"); - assert_eq!(lowered.half_views, [(1, 0), (1, 8)]); let shader = HostShader { stage: HwStage::Cs, dxil: lowered.dxil, @@ -2159,362 +2128,252 @@ fn halves_go_through_a_table_as_they_are_and_name_their_views() { root_srvs: lowered.root_srvs, root_uavs: lowered.root_uavs, root_indexed_views: res.root_indexed_views, - half_views: lowered.half_views, }; if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - let mut dxil = shader.dxil.clone(); - v.validate(&mut dxil).expect("DXIL validation failed"); + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); } - // A raw store through the same table: no halves, nothing named. - assert!(build_valu_cs(&[]).half_views.is_empty()); - - // Four halves a thread: numbers, both zeros, subnormals, infinities, - // not-a-numbers of both signs, and integers past the largest number's - // pattern, as indices are. - const SPECIAL: [u16; 16] = [ - 0x0000, 0x0001, 0x03ff, 0x0400, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e00, 0x7fff, 0x8000, - 0x8001, 0xbc00, 0xfc00, 0xfc01, 0xffff, - ]; - let halves: Vec = (0..4 * THREADS as usize) - .map(|i| match i { - 0..16 => SPECIAL[i], - _ => (i as u16).wrapping_mul(0x0203).wrapping_add(0x7b00), - }) - .collect(); - let data: Vec = halves - .chunks(2) - .map(|pair| u32::from(pair[0]) | u32::from(pair[1]) << 16) - .collect(); - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - let (root, pso) = host - .compute_pipeline(&shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); - let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; - for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; - } - let out = host - .dispatch( - &root, - &pso, - &Dispatch { - roots: vec![(0, Root::Constants(ud))], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Format(DXGI_FORMAT_R16G16B16A16_UINT, 8), - }, - View::HalfUintUav(THREADS), - ], - samplers: &[], - groups: [1, 1, 1], - }, - ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!( - out[0], data, - "{label}: the halves stored are the halves loaded" - ); - ran += 1; - } - assert!(ran > 0, "no SM 6.6 device available"); + shader } -/// The places a program that moves halves names are the descriptors it -/// loads, not the start of the range their used-resource entry describes: -/// with one entry for a range from dword 0, a load at byte 0x20 names -/// dword 8 (a host view there in a 16-bit float format is the one shown -/// as its unsigned twin). A descriptor picked at run time (the load's -/// offset in an SGPR) names nothing and keeps the float path: which slot -/// it reads, and in which format, is known only then. +/// `compute_graph_ops` (facial lip-sync & wrapped submesh solver) binds +/// `R16G16B16A16_UINT` / `R16_UINT` UAVs via `RootType::Table` (which on NVIDIA +/// are snapshotted into dynamic descriptor slots) and reads/writes FP16 bit +/// patterns with `buffer_load_format_d16_xyzw` and `buffer_store_format_d16_xyzw`. +/// Verify bit-exact round-trips for UINT, SINT, and FLOAT views (including +/// non-zero table offsets matching dynamic descriptor snapshots) on hardware +/// GPU and WARP. #[test] -fn half_places_are_the_descriptors_the_program_loads() { - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_D16_XYZW: u32 = 0x83; - const STORE_D16_XYZW: u32 = 0x87; - let lowered = |words: &[u32]| { - let range = |kind: ResourceType, table_offset_dwords: u32| UsedResource { - kind, +fn typed_d16_table_uav_roundtrip_uint_sint_and_float() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_SINT, + DXGI_FORMAT_R16G16B16A16_UINT, + }; + let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut body = Vec::new(); + // s[8:11] = table[0] (src typed UAV), s[12:15] = table[1] (dst typed UAV), + // s[16:19] = table[2] (raw UAV dump of loaded v[2:3]). + body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0)); + body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32)); + body.extend_from_slice(&s_load_dwordx4_off(16, 4, 64)); + // buffer_load_format_d16_xyzw v[2:3], v0, s[8:11], 0 idxen (op 0x83) + body.extend_from_slice(&mubuf_idxen(0x83, 2, 0, 8)); + // buffer_store_format_d16_xyzw v[2:3], v0, s[12:15], 0 idxen (op 0x87) + body.extend_from_slice(&mubuf_idxen(0x87, 2, 0, 12)); + // Also dump thread 0's loaded v[2:3] into raw UAV (table[2]) to verify the load itself. + // v4 = v0 << 3 (byte offset = thread * 8) + body.push(0x3408_0083); // v_lshlrev_b32 v4, 3, v0 + // buffer_store_dwordx2 v[2:3], v4, s[16:19], 0 offen (op 0x1D, offen bit 12) + body.extend_from_slice(&[ + 0x38 << 26 | 0x1D << 18 | 1 << 12, + 0x80 << 24 | (16u32 >> 2) << 16 | (2u32 << 8) | 4u32, + ]); + let used = (0..3u32) + .map(|k| UsedResource { + kind: ResourceType::Uav, root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, + table_offset_dwords: k * 8, + lower_bound: k, stride: 4, dwords: 4, user_data: 4, - slot: 1, - }; - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - // One entry for a range of views from dword 0, one at 16. - used: vec![range(ResourceType::Srv, 0), range(ResourceType::Uav, 16)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [32, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = structure::structure(&p).expect("structure"); - let res = - resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, + slot: 0, }) - .expect("lower") - }; - // `s_load_dwordx4 s[dst:dst+3], s[4:5], offset` (soffset null), or with - // the offset in `soffset` instead. - let at = |dst: u8, offset: u32| { - let mut w = s_load_dwordx4(dst, 4); - w[1] |= offset; - w - }; - let picked = |dst: u8, soffset: u8| { - let mut w = s_load_dwordx4(dst, 4); - w[1] = u32::from(soffset) << 25; - w - }; - let mut fixed = vec![s_mov_b32(5, 0x80)]; - fixed.extend_from_slice(&at(8, 0x20)); - fixed.extend_from_slice(&at(12, 0x40)); - fixed.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - fixed.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); - fixed.push(S_ENDPGM); - assert_eq!(lowered(&fixed).half_views, [(1, 8), (1, 16)]); - // The load's offset in s20, from the first lane's thread index - // (`v_readfirstlane_b32 s20, v0`): picked at run time. The pick may land - // on the store's place too, so no place of that table is named: the d16 - // accesses there take the float path, as before half views. - let mut runtime = vec![s_mov_b32(5, 0x80), vop1(0x02, 20, vgpr(0))]; - runtime.extend_from_slice(&picked(8, 20)); - runtime.extend_from_slice(&at(12, 0x40)); - runtime.extend_from_slice(&mubuf_idxen(LOAD_D16_XYZW, 1, 0, 8)); - runtime.extend_from_slice(&mubuf_idxen(STORE_D16_XYZW, 1, 0, 12)); - runtime.push(S_ENDPGM); - assert!(lowered(&runtime).half_views.is_empty()); -} - -/// A format load of whole dwords (`buffer_load_format_x`, not d16) whose -/// result the program only reads one half of as a half float -/// (`v_cvt_f32_f16`) is moving 16-bit integers: the head program reads the -/// face network's output so, from an `R16_UINT` view. It names its view for -/// the host and loads the integer: 0x3c00 comes through as 1.0. Used as a -/// whole float instead (`v_add_f32`), the load stays a float load and names -/// nothing; so does a load of halves beside a load of the same view read as -/// a whole float (a view of numbers the program also picks one half float -/// out of, as hundreds of the title's pixel programs do). -#[test] -fn a_format_load_read_as_halves_loads_the_integer() { - use super::host::Stride; - use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16_UINT; - /// MUBUF `op vdata, vaddr, s[srsrc:srsrc+3], 0 idxen`. - const fn mubuf_idxen(op: u32, vdata: u8, vaddr: u8, srsrc: u8) -> [u32; 2] { - [ - 0x38 << 26 | op << 18 | 1 << 13, - 0x80 << 24 | ((srsrc as u32 >> 2) & 0x1F) << 16 | (vdata as u32) << 8 | vaddr as u32, - ] - } - const LOAD_FORMAT_X: u32 = 0x00; - const V_CVT_F32_F16: u16 = 0x0B; - const V_ADD_F32: u8 = 0x03; - let lowered = |body: &[u32]| { - let view = |kind: ResourceType, table_offset_dwords: u32, stride: u32| UsedResource { - kind, - root: RootType::Table, - table_offset_dwords, - lower_bound: table_offset_dwords / 8, - stride, - dwords: 4, - user_data: 4, - slot: 1, - }; - let mut second = s_load_dwordx4(12, 4); - second[1] |= 0x20; - let mut words = vec![s_mov_b32(5, 0x80)]; - words.extend_from_slice(&s_load_dwordx4(8, 4)); - words.extend_from_slice(&second); - // `body` leaves v2, stored raw. - words.extend_from_slice(body); - words.extend_from_slice(&buffer_store_dword(2, 12, 0)); - words.push(S_ENDPGM); - let native = NativeProgram { - stage: HwStage::Cs, - wave64: false, - vgprs: 8, - layout: vec![ - RootParam { - root: RootType::Constants, - table_offset_dwords: 0, - sgprs: 4, - base_register: 0, - user_data: 0, - slot: 0, - }, - RootParam { - root: RootType::Table, - table_offset_dwords: 0, - sgprs: 1, - base_register: 0, - user_data: 4, - slot: 1, - }, - ], - used: vec![view(ResourceType::Srv, 0, 4), view(ResourceType::Uav, 8, 0)], - io: StageIo::Cs(ComputeIo { - rsrc2: 5 << 1, - threads: [1, 1, 1], - }), - code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), - }; - let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - let st = structure::structure(&p).expect("structure"); - let res = - resource::track(&p, &native.layout, native.stage, Some(&st)).expect("resource::track"); - let io = io::raise(&p, &native).expect("io::raise"); - let l = lower::lower(&lower::Parts { - native: &native, - p: &p, - st: &st, - io: &io, - res: &res, - inputs: Vec::new(), - outputs: Vec::new(), - prims: Vec::new(), - mesh_stride: 0, - }) - .expect("lower"); - HostShader { - stage: HwStage::Cs, - dxil: l.dxil, - user_data: l.user_data, - samplers: l.samplers, - static_samplers: Vec::new(), - root_cbvs: l.root_cbvs, - root_srvs: l.root_srvs, - root_uavs: l.root_uavs, - root_indexed_views: res.root_indexed_views, - half_views: l.half_views, - } - }; - // v1 = first[v0] (one channel). - let load = mubuf_idxen(LOAD_FORMAT_X, 1, 0, 8); - let half = vop1(V_CVT_F32_F16, 2, vgpr(1)); - let as_halves = lowered(&[&load[..], &[half]].concat()); - assert_eq!(as_halves.half_views, [(1, 0)]); - let as_float = lowered(&[&load[..], &[vop2(V_ADD_F32, 2, vgpr(1), 1)]].concat()); - assert!(as_float.half_views.is_empty()); - // v3 = first[v0] too, read as a whole float: v2 = half(v1) + v3. - let mut beside = load.to_vec(); - beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); - beside.push(half); - beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); - assert!(lowered(&beside).half_views.is_empty()); - // Behind a branch, as the head program has it: where the lanes meet - // again the loaded value goes on through a phi, and a later write of - // v1 under EXEC reads it only to keep it in the lanes it leaves alone. - const SAVE_EXEC: u32 = 0xBE90_037E; // s_mov_b32 s16, exec_lo - const ONLY_LANE_0: u32 = 0x7DA4_0080; // v_cmpx_eq_u32 exec_lo, 0, v0 - const SKIP_3: u32 = 0xBF88_0003; // s_cbranch_execz over the next 3 words - const RESTORE_EXEC: u32 = 0xBEFE_0310; // s_mov_b32 exec_lo, s16 - let zero = vop1(0x01, 2, 128); // v_mov_b32 v2, 0 - let rewrite = vop1(0x01, 1, 128); // v_mov_b32 v1, 0 - let branched = lowered( - &[ - &[zero, SAVE_EXEC, ONLY_LANE_0, SKIP_3][..], - &load, - &[ - half, - RESTORE_EXEC, - SAVE_EXEC, - ONLY_LANE_0, - rewrite, - RESTORE_EXEC, - ], - ] - .concat(), + .collect(); + let shader = build_table_typed_cs(&body, used); + assert!( + shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "table typed d16 shader should request SLOT_TABLE_STRIDES" ); - assert_eq!(branched.half_views, [(1, 0)]); - // A d16 load names its place where it is the only access there... - const LOAD_FORMAT_D16_X: u32 = 0x80; - let d16 = mubuf_idxen(LOAD_FORMAT_D16_X, 1, 0, 8); - let d16_alone = lowered(&[&d16[..], &[half]].concat()); - assert_eq!(d16_alone.half_views, [(1, 0)]); - // ...and not beside a whole float read through the same place, which - // would see the unsigned twin: v2 = half(d16 v1) + v3. - let mut d16_beside = d16.to_vec(); - d16_beside.extend_from_slice(&mubuf_idxen(LOAD_FORMAT_X, 3, 0, 8)); - d16_beside.push(half); - d16_beside.push(vop2(V_ADD_F32, 2, vgpr(3), 2)); - assert!(lowered(&d16_beside).half_views.is_empty()); - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { - for shader in [&as_halves, &branched, &d16_alone] { - let mut dxil = shader.dxil.clone(); - v.validate(&mut dxil).expect("DXIL validation failed"); - } - } - // Element 0 of an R16_UINT buffer holds the half 1.0 (0x3c00). - let data = [0x0000_3c00u32, 0]; - let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let mut ran = 0; - for (label, warp) in [("hardware", false), ("warp", true)] { - let Ok(host) = Host::new(warp) else { - eprintln!("no SM 6.6 {label} device; skipped"); - continue; - }; - for (name, shader) in [("straight", &as_halves), ("branched", &branched)] { - let (root, pso) = host - .compute_pipeline(shader) - .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}")); + assert!( + !shader.root_srvs.contains(&super::SLOT_STRIDES), + "table-only shader must not trigger the bindless SLOT_STRIDES sweep" + ); + + // 4 elements x 4 u16 channels = 8 u32 dwords. + // Includes FP16 subnormal (0x0001), -0.0 (0x8000), 1.0 (0x3C00), -1.0 (0xBC00), + // NaN (0x7E00), max u16 (0xFFFF), and arbitrary patterns. + let uint_bits: [u32; 8] = [ + 0x3C00_0001, 0x7E00_BC00, + 0xFFFF_8000, 0xABCD_1234, + 0x0002_0000, 0x7BFF_FBFF, + 0xDEAD_BEEF, 0xCAFE_BABE, + ]; + let sint_bits: [u32; 8] = [ + 0xFFFF_8000, 0x7FFF_0001, + 0xC000_0000, 0x8001_7FFE, + 0xFFFF_FFFF, 0x0000_0000, + 0xFEDC_BA98, 0x7654_3210, + ]; + // Normal finite FP16 values that round-trip cleanly through f32. + let float_bits: [u32; 8] = [ + 0x4000_3C00, 0x3800_BC00, // 1.0, 2.0, -1.0, 0.5 + 0xC200_3400, 0x4500_0000, // 0.25, -3.0, 0.0, 5.0 + 0x3E00_BE00, 0x4400_C400, // -1.5, 1.5, -4.0, 4.0 + 0x3C00_0000, 0x4200_C000, // 0.0, 1.0, -2.0, 3.0 + ]; + let zeros = [0u32; 8]; + + let cases = [ + ("R16G16B16A16_UINT @0", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 0u32), + ("R16G16B16A16_UINT @3 (dynamic offset)", DXGI_FORMAT_R16G16B16A16_UINT, 8 | super::VIEW_INTEGER, &uint_bits, 3u32), + ("R16G16B16A16_SINT @0", DXGI_FORMAT_R16G16B16A16_SINT, 8 | super::VIEW_INTEGER | super::VIEW_SIGNED, &sint_bits, 0u32), + ("R16G16B16A16_FLOAT @0", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &float_bits, 0u32), + ]; + + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}")); + for &(label, format, stride_word, input, base_slot) in &cases { + let mut views = Vec::new(); + let mut strides = Vec::new(); + for _ in 0..base_slot { + views.push(View::RawUav(1)); + strides.push(0u32); + } + let uav_base = base_slot as usize; + views.push(View::TypedUav { data: input, format, elem_bytes: 8 }); + strides.push(stride_word); + views.push(View::TypedUav { data: &zeros, format, elem_bytes: 8 }); + strides.push(stride_word); + views.push(View::RawUav(8)); + strides.push(1); + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { - ud[u.index as usize] = match (u.root, u.slot) { - (RootType::Table, 1) => 0, - other => panic!("unexpected user data {other:?}"), - }; + if u.root == RootType::Table && u.slot == 0 { + ud[u.index as usize] = base_slot * 32; + } + } + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![ + (0, Root::Constants(ud)), + (1, Root::View { srv: true, data: strides }), + ], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}")); + assert_eq!( + out[uav_base + 2], + input, + "{backend} {label}: buffer_load_format_d16_xyzw mismatch" + ); + assert_eq!( + out[uav_base + 1], + input, + "{backend} {label}: buffer_store_format_d16_xyzw mismatch" + ); + } + } +} + +/// Non-`d16` typed loads (`buffer_load_format_x`) are used by +/// `CS_BlendshapeTranslationsHSSGraphOutputExtract` (reading `HSSGraphOut` +/// `R16_UINT`) and `CS_PedStandardSkinning_*` (reading bone indices). Verify +/// exact integer bits for `R16_UINT`, `R16_SINT`, and `R32_UINT`. +#[test] +fn typed_non_d16_table_load_preserves_integer_bits() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R32_UINT, + }; + let _serial = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut body = Vec::new(); + // s[8:11] = table[0] (src typed SRV), s[12:15] = table[1] (raw UAV out) + body.extend_from_slice(&s_load_dwordx4_off(8, 4, 0)); + body.extend_from_slice(&s_load_dwordx4_off(12, 4, 32)); + // buffer_load_format_x v2, v0, s[8:11], 0 idxen (op 0x00) + body.extend_from_slice(&mubuf_idxen(0x00, 2, 0, 8)); + // v4 = v0 << 2 (byte offset = thread * 4) + body.push(0x3408_0082); // v_lshlrev_b32 v4, 2, v0 + // buffer_store_dword v2, v4, s[12:15], 0 offen (op 0x1C, offen bit 12) + body.extend_from_slice(&[ + 0x38 << 26 | 0x1C << 18 | 1 << 12, + 0x80 << 24 | (12u32 >> 2) << 16 | (2u32 << 8) | 4u32, + ]); + let used = vec![ + UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 0, + }, + UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 8, + lower_bound: 1, + stride: 4, + dwords: 4, + user_data: 4, + slot: 0, + }, + ]; + let shader = build_table_typed_cs(&body, used); + // Non-d16 typed loads stay untouched (no SLOT_TABLE_STRIDES root SRV, no + // CFG branches) so non-d16 pixel/mesh/particle/skinning shaders keep + // identical DXIL and pipeline cache keys while still preserving raw bits. + assert!( + !shader.root_srvs.contains(&super::SLOT_TABLE_STRIDES), + "non-d16 typed load should not add SLOT_TABLE_STRIDES" + ); + + let r16_data = [0x3C00_0001u32, 0xFFFF_BC00u32]; + let r32_data = [0xDEAD_BEEFu32, 0x0000_0001, 0x8000_0000, 0x7FFF_FFFF]; + let cases: [(&str, _, u32, &[u32], [u32; 4]); 3] = [ + ( + "R16_UINT", + DXGI_FORMAT_R16_UINT, + 2, + &r16_data, + [0x0001, 0x3C00, 0xBC00, 0xFFFF], + ), + ( + "R16_SINT", + DXGI_FORMAT_R16_SINT, + 2, + &r16_data, + [0x0001, 0x3C00, 0xFFFF_BC00, 0xFFFF_FFFF], + ), + ( + "R32_UINT", + DXGI_FORMAT_R32_UINT, + 4, + &r32_data, + r32_data, + ), + ]; + + for (backend, warp) in [("hardware", false), ("warp", true)] { + let Ok(host) = Host::new(warp) else { continue }; + let (root, pso) = host + .compute_pipeline(&shader) + .unwrap_or_else(|e| panic!("{backend}: compute_pipeline failed: {e}")); + for &(label, format, elem_bytes, input, want) in &cases { + let views = [ + View::Buffer { + data: input, + stride: super::host::Stride::Format(format, elem_bytes), + }, + View::RawUav(4), + ]; + let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; + for u in &shader.user_data { + if u.root == RootType::Table && u.slot == 0 { + ud[u.index as usize] = 0; + } } let out = host .dispatch( @@ -2522,25 +2381,13 @@ fn a_format_load_read_as_halves_loads_the_integer() { &pso, &Dispatch { roots: vec![(0, Root::Constants(ud))], - views: &[ - View::Buffer { - data: &data, - stride: Stride::Format(DXGI_FORMAT_R16_UINT, 2), - }, - View::RawUav(1), - ], + views: &views, samplers: &[], groups: [1, 1, 1], }, ) - .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); - assert_eq!( - out[0][0], - 1.0f32.to_bits(), - "{label}, {name}: the half read as an integer's bits" - ); + .unwrap_or_else(|e| panic!("{backend} {label}: dispatch failed: {e}")); + assert_eq!(out[0], want, "{backend} {label}: buffer_load_format_x mismatch"); } - ran += 1; } - assert!(ran > 0, "no SM 6.6 device available"); } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index 835c067..ddc03dd 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -138,6 +138,9 @@ pub struct RootIndexedView { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Resources { + /// Scalar values saved to a constant VGPR lane and restored within one + /// block, even if that VGPR is also used in ordinary vector operations. + pub(crate) restored_lanes: std::collections::HashMap, /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and /// every global memory access (`global_*`, the dynamic term per lane). pub scalar: Vec<(Site, Address)>, @@ -224,9 +227,12 @@ pub fn track( let mut offset_at = std::collections::BTreeMap::, Vec, Vec)>::new(); for (b, block) in p.blocks.iter().enumerate() { - t.at.set(Some(b)); for (i, inst) in block.insts.iter().enumerate() { let site = (b, i); + t.at.set(Some(site)); + if let Some(value) = t.restored(inst, Some(b)) { + out.restored_lanes.insert(site, value); + } let fail = |what| ShaderError::Unsupported { offset: inst.machine.offset, what, @@ -234,7 +240,7 @@ pub fn track( let mut first_lane = Vec::new(); let mut offset = Vec::new(); let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { - let source = t.descriptor(inst, op, b).map_err(fail)?; + let source = t.descriptor(inst, op, site).map_err(fail)?; // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) // is the same in every lane: its loop is lowered as it stands // and needs no proof. @@ -411,8 +417,8 @@ struct Tracer<'a> { meets: std::cell::RefCell, /// Reverse-postorder index per block. rpo: Vec, - /// The block of the access being traced ([`Self::live`]). - at: std::cell::Cell>, + /// The instruction site of the access being traced ([`Self::live`]). + at: std::cell::Cell>, } /// What lanes are known to satisfy: each [`Bool`] where its flag is set, @@ -514,7 +520,7 @@ impl<'a> Tracer<'a> { } for inst in &block.insts { for (k, &(_, v)) in inst.writes.iter().enumerate() { - let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + let new = match copy_source(inst, k).or_else(|| self.restored(inst, None)) { Some(Moved::Const(c)) => Some(Term::Const(c)), Some(Moved::Value(s)) => o[s.0 as usize], None => Some(Term::Value(v)), @@ -1113,8 +1119,8 @@ impl<'a> Tracer<'a> { self.address(lo, hi, extra) } - /// The source of the descriptor operand `op` of `inst`, in block `at`. - fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result { + /// The source of the descriptor operand `op` of `inst`, at `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: Site) -> Result { let Operand::Scalar { code, dwords } = *op else { return Err("a descriptor not in SGPRs"); }; @@ -1129,8 +1135,14 @@ impl<'a> Tracer<'a> { { words = raw.to_vec(); } - // Only the lanes that reach the access read the descriptor. - let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + // Only the lanes that reach and run the access read the descriptor. + let mut known = Vec::new(); + if let Some(l) = self.lanes { + known.push((l.reach[at.0], true)); + if let Some(guard) = l.guards[at.0][at.1] { + known.push((guard, true)); + } + } self.classify(&words, &mut Vec::new(), &mut known) } @@ -1282,7 +1294,10 @@ impl<'a> Tracer<'a> { let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { return t; }; - let mut known = vec![(lanes.reach[at], true)]; + let mut known = vec![(lanes.reach[at.0], true)]; + if let Some(guard) = lanes.guards[at.0][at.1] { + known.push((guard, true)); + } for _ in 0..MAX_JOINS { let Term::Value(v) = t else { break }; let Some((block, i)) = self.phis[v.0 as usize] else { @@ -2292,41 +2307,64 @@ impl<'a> Tracer<'a> { } } -#[derive(Clone, Copy, PartialEq, Eq)] -enum Moved { +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Moved { Const(u32), Value(Value), } +fn plain_lane(v: &crate::gfx10::Valu) -> bool { + v.abs == 0 + && v.neg == 0 + && v.opsel == 0 + && !v.clamp + && v.omod == 0 + && v.sdwa.is_none() + && v.dpp.is_none() +} + impl Tracer<'_> { /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that /// lane, found by following the VGPR's `v_writelane_b32` writes. - fn restored(&self, inst: &Inst) -> Option { + fn restored(&self, inst: &Inst, block: Option) -> Option { let Fields::Valu(v) = &inst.fields else { return None; }; - if inst.name() != "v_readlane_b32" { + if inst.name() != "v_readlane_b32" || !plain_lane(v) { return None; } let [Operand::Vector { reg, .. }, lane] = v.src[..] else { return None; }; - self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + let lane = lane_of(lane)?; + if lane >= if self.p.wave64 { 64 } else { 32 } { + return None; + } + self.spilled(inst.read(Reg::V(reg))?, lane, block, &mut Vec::new()) .ok() .flatten() } /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in /// `seen` (already being resolved), `Err` if not a spilled SGPR. - fn spilled(&self, v: Value, lane: u32, seen: &mut Vec) -> Result, ()> { + fn spilled( + &self, + v: Value, + lane: u32, + block: Option, + seen: &mut Vec, + ) -> Result, ()> { if let Some((b, i)) = self.phis[v.0 as usize] { + if block.is_some() { + return Err(()); + } if seen.contains(&v) { return Ok(None); } seen.push(v); let mut found = None; for &a in &self.p.blocks[b].phis[i].args { - if let Some(m) = self.spilled(a, lane, seen)? { + if let Some(m) = self.spilled(a, lane, block, seen)? { if found.is_some_and(|f| f != m) { return Err(()); } @@ -2335,18 +2373,26 @@ impl Tracer<'_> { } return Ok(found); } - let inst = self.def(v).ok_or(())?; + let site = self.defs[v.0 as usize].ok_or(())?; + if block.is_some_and(|b| site.0 != b) { + return Err(()); + } + let inst = self.inst(site); let Fields::Valu(w) = &inst.fields else { return Err(()); }; let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { return Err(()); }; - if inst.name() != "v_writelane_b32" { + if inst.name() != "v_writelane_b32" || !plain_lane(w) { return Err(()); } - if lane_of(*at).ok_or(())? != lane { - return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + let written = lane_of(*at).ok_or(())?; + if written >= if self.p.wave64 { 64 } else { 32 } { + return Err(()); + } + if written != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, block, seen); } match *value { Operand::Scalar { code, .. } if code != NULL => { @@ -4061,4 +4107,45 @@ pub(crate) mod tests { assert_eq!(r.waterfall.compares.len(), 2); assert_eq!(r.waterfall.reads.len(), 4); } + + #[test] + fn a_guarded_access_excludes_dead_lane_edges_at_a_join() { + // Lanes failing `v_cmp_gt_u32` clear EXEC and take `s_cbranch_execz` + // directly to the join block without initializing the immediate + // sampler `s[8:11]`. The join's `image_sample_lz` is guarded by EXEC, + // so only the arm where `s[8:11]` was built can execute it. + let code: Vec = [ + 0xBE84_0300u32, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF40C_0302, + 0xFA00_0000, // s_load_dwordx8 s[12:19], s[4:5], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x877E_6A7E, // s_and_b32 exec_lo, exec_lo, vcc_lo + 0xBF88_0004, // s_cbranch_execz -> join (skips 4 dwords) + 0xBE88_0380, // s_mov_b32 s8, 0 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE8A_0380, // s_mov_b32 s10, 0 + 0xBE8B_0380, // s_mov_b32 s11, 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let structured = lanes(&p).expect("structured form"); + assert!(structured.guards[2][0].is_some(), "join access must carry an EXEC guard"); + let r = track(&p, &[param(Table, 0, 1)], HwStage::Cs, Some(&structured)).unwrap(); + assert!( + r.descriptors + .iter() + .any(|d| d.role == Role::Sampler && d.source == Source::Constant(vec![0; 4])), + "guarded join should resolve the immediate sampler from the live arm: {:?}", + r.descriptors + ); + } } diff --git a/scripts/build-nvidia.ps1 b/scripts/build-nvidia.ps1 new file mode 100644 index 0000000..41e864a --- /dev/null +++ b/scripts/build-nvidia.ps1 @@ -0,0 +1,25 @@ +# Builds the layer the way scripts\play-nvidia.ps1 expects it (the diag profile with diagnostics: the F1 menu, +# the F3 panel and several NVIDIA settings are diagnostics switches). +# scripts\build-nvidia.ps1 with DLSS when nvidia-sdk\DLSS is there (Get-NVIDIA-DLSS.cmd fetches it), +# without it otherwise +# scripts\build-nvidia.ps1 -NoDlss without DLSS even then +# scripts\build-nvidia.ps1 -DlssSdk +# A build with DLSS links NVIDIA's loader library: it is for your own use, not for passing on. +param( + [string]$DlssSdk, + [switch]$NoDlss +) +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +if (-not $DlssSdk) { $DlssSdk = Join-Path $root 'nvidia-sdk\DLSS' } +$features = 'diagnostics' +if (-not $NoDlss -and (Test-Path (Join-Path $DlssSdk 'lib\Windows_x86_64\x64\nvsdk_ngx_d.lib'))) { + $env:VICTORY_DLSS_SDK = (Resolve-Path $DlssSdk).Path + $features = 'diagnostics,dlss' + Write-Host "Building with DLSS (SDK: $env:VICTORY_DLSS_SDK)" +} else { + Write-Host 'Building without DLSS (Get-NVIDIA-DLSS.cmd fetches its files; without them the picture is stretched to the screen)' +} +Push-Location $root +try { cargo build --locked --profile diag -p victory --features $features } finally { Pop-Location } +if ($LASTEXITCODE -eq 0) { Set-Content -Path (Join-Path $root 'target\diag\built-with.txt') -Value $features -Encoding ascii } +if ($LASTEXITCODE -eq 0) { Write-Host "Built: $(Join-Path $root 'target\diag\victory.exe'). Next: scripts\play-nvidia.ps1 -Exe " } diff --git a/scripts/get-nvidia-sdks.ps1 b/scripts/get-nvidia-sdks.ps1 new file mode 100644 index 0000000..4c333f8 --- /dev/null +++ b/scripts/get-nvidia-sdks.ps1 @@ -0,0 +1,154 @@ +# Fetches the few NVIDIA files DLSS and DLSS frame generation need (about 70 MB) from NVIDIA's own GitHub +# into nvidia-sdk\ here (git-ignored). They are NVIDIA's, under NVIDIA's licences (saved beside them: read +# them); this repository does not and may not carry them, so each person gets them from NVIDIA directly. +# Get-NVIDIA-DLSS.cmd in the repository's folder runs this. +# scripts\get-nvidia-sdks.ps1 DLSS and frame generation +# scripts\get-nvidia-sdks.ps1 -NoStreamline DLSS only (about 60 MB) +# Then: scripts\build-nvidia.ps1 (scripts\play-nvidia.ps1 does it by itself at its next start). +param( + [string]$DlssTag = 'v310.9.16', + [string]$StreamlineTag = 'v2.14.16', + [switch]$NoStreamline +) +$ProgressPreference = 'SilentlyContinue' # Invoke-WebRequest's progress bar makes it many times slower +[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$sdk = Join-Path $root 'nvidia-sdk' + +# One file from a URL, with curl's progress line where Windows has curl (it has since Windows 10 1803). +function Get-File([string]$Url, [string]$To) { + New-Item -ItemType Directory -Force (Split-Path $To) | Out-Null + $part = "$To.part" + if (Get-Command curl.exe -ErrorAction SilentlyContinue) { + & curl.exe --location --fail --silent --show-error --progress-bar --output $part $Url + if ($LASTEXITCODE -ne 0) { Remove-Item $part -ErrorAction SilentlyContinue; throw "could not get $Url" } + } else { + Invoke-WebRequest -Uri $Url -OutFile $part -UseBasicParsing -ErrorAction Stop + } + Move-Item $part $To -Force +} + +# Bytes first..last of a URL. +function Get-Range([string]$Url, [long]$First, [long]$Last) { + $q = [Net.HttpWebRequest]::Create($Url) + $q.UserAgent = 'get-nvidia-sdks' + $q.AddRange($First, $Last) + $r = $q.GetResponse() + try { + if ([int]$r.StatusCode -ne 206) { throw 'the server does not give parts of the file' } + $m = New-Object IO.MemoryStream + $r.GetResponseStream().CopyTo($m) + , $m.ToArray() + } finally { $r.Close() } +} + +# Takes the named files out of a zip on a server without downloading the whole zip: its directory is at +# its end, and each file in it can be asked for by its place. $Want: a regex on the paths in the zip. +# Each goes into $Into under the part of its path after the SDK's top folder. +function Get-FromZip([string]$Url, [string]$Want, [string]$Into) { + # Where the file really is (the download address redirects), and how long it is. + $h = [Net.HttpWebRequest]::Create($Url); $h.Method = 'HEAD'; $h.UserAgent = 'get-nvidia-sdks' + $r = $h.GetResponse(); $real = $r.ResponseUri.AbsoluteUri; $length = $r.ContentLength; $r.Close() + $tailLen = [Math]::Min($length, 2MB) + $tail = Get-Range $real ($length - $tailLen) ($length - 1) + $end = -1 + for ($i = $tail.Length - 22; $i -ge 0; $i--) { + if ($tail[$i] -eq 0x50 -and $tail[$i + 1] -eq 0x4b -and $tail[$i + 2] -eq 5 -and $tail[$i + 3] -eq 6) { $end = $i; break } + } + if ($end -lt 0) { throw 'no zip directory found' } + $dirSize = [BitConverter]::ToUInt32($tail, $end + 12) + $dirAt = [BitConverter]::ToUInt32($tail, $end + 16) + if ($dirAt -eq [uint32]::MaxValue) { throw 'a zip64 archive' } + $dir = if ($dirAt -ge $length - $tailLen) { + $from = [int]($dirAt - ($length - $tailLen)); , $tail[$from..($from + $dirSize - 1)] + } else { Get-Range $real $dirAt ($dirAt + $dirSize - 1) } + $got = 0 + $at = 0 + while ($at + 46 -le $dir.Length -and [BitConverter]::ToUInt32($dir, $at) -eq 0x02014b50) { + $method = [BitConverter]::ToUInt16($dir, $at + 10) + $packed = [BitConverter]::ToUInt32($dir, $at + 20) + $size = [BitConverter]::ToUInt32($dir, $at + 24) + $nameLen = [BitConverter]::ToUInt16($dir, $at + 28) + $extraLen = [BitConverter]::ToUInt16($dir, $at + 30) + $noteLen = [BitConverter]::ToUInt16($dir, $at + 32) + $headerAt = [BitConverter]::ToUInt32($dir, $at + 42) + $name = [Text.Encoding]::UTF8.GetString($dir, $at + 46, $nameLen) + $at += 46 + $nameLen + $extraLen + $noteLen + if ($name -notmatch $Want) { continue } + # The file's own header (its extra field may be longer than the directory's), then its bytes. + $piece = Get-Range $real $headerAt ($headerAt + 30 + $nameLen + 2048 + $packed - 1) + if ([BitConverter]::ToUInt32($piece, 0) -ne 0x04034b50) { throw "no file header for $name" } + $dataAt = 30 + [BitConverter]::ToUInt16($piece, 26) + [BitConverter]::ToUInt16($piece, 28) + if ($dataAt + $packed -gt $piece.Length) { throw "the header of $name is longer than expected" } + $bytes = if ($method -eq 0) { , $piece[$dataAt..($dataAt + $packed - 1)] } + elseif ($method -eq 8) { + $in = [IO.MemoryStream]::new($piece, $dataAt, [int]$packed) + $z = [IO.Compression.DeflateStream]::new($in, [IO.Compression.CompressionMode]::Decompress) + $out = [IO.MemoryStream]::new(); $z.CopyTo($out); $z.Close(); , $out.ToArray() + } else { throw "$name is packed in a way this script does not know ($method)" } + if ($bytes.Length -ne $size) { throw "$name came out $($bytes.Length) bytes long, not $size" } + $rel = ($name -replace '^.*?(?=(bin/x64/|license\.txt$))', '') -replace '/', '\' + $to = Join-Path $Into $rel + New-Item -ItemType Directory -Force (Split-Path $to) | Out-Null + [IO.File]::WriteAllBytes($to, $bytes) + Write-Host (" {0} {1:N1} MB" -f $rel, ($size / 1MB)) + $got++ + } + $got +} + +# DLSS: the library the build links (4 MB) and the DLL the game loads (56 MB), each at NVIDIA's release tag. +$dlss = Join-Path $sdk 'DLSS' +$raw = "https://raw.githubusercontent.com/NVIDIA/DLSS/$DlssTag" +$files = @('LICENSE.txt', 'lib/Windows_x86_64/x64/nvsdk_ngx_d.lib', 'lib/Windows_x86_64/rel/nvngx_dlss.dll') +Write-Host "NVIDIA DLSS $DlssTag from github.com/NVIDIA/DLSS (about 60 MB):" +foreach ($f in $files) { + $to = Join-Path $dlss ($f -replace '/', '\') + if (Test-Path $to) { Write-Host " $f is there already"; continue } + Write-Host " $f" + Get-File "$raw/$f" $to +} +Write-Host " NVIDIA's licence for these: $(Join-Path $dlss 'LICENSE.txt')" + +# Frame generation: Streamline's five DLLs (3 MB, taken out of NVIDIA's 263 MB release archive without +# downloading the rest) and the frame generation model (7 MB, from the DLSS repository). +if (-not $NoStreamline) { + $sl = Join-Path $sdk 'Streamline' + $bin = Join-Path $sl 'bin\x64' + Write-Host "NVIDIA Streamline $StreamlineTag from github.com/NVIDIA-RTX/Streamline (about 10 MB):" + if (Test-Path (Join-Path $bin 'sl.interposer.dll')) { + Write-Host ' the Streamline DLLs are there already' + } else { + $url = "https://github.com/NVIDIA-RTX/Streamline/releases/download/$StreamlineTag/streamline-sdk-$StreamlineTag.zip" + $want = '(^|/)bin/x64/(sl\.(interposer|common|dlss_g|reflex|pcl)\.dll|[^/]*license[^/]*\.txt)$|^([^/]+/)?license\.txt$' + $got = 0 + try { $got = Get-FromZip $url $want $sl } + catch { Write-Host " Taking the files out of the archive in place did not work ($($_.Exception.Message))." } + if (-not (Test-Path (Join-Path $bin 'sl.interposer.dll'))) { + # The whole archive then (263 MB). + Write-Host ' Getting the whole archive instead (263 MB) ...' + $zip = Join-Path $sdk "streamline-sdk-$StreamlineTag.zip" + Get-File $url $zip + $into = Join-Path $sdk 'streamline-unpacked' + Expand-Archive -Path $zip -DestinationPath $into -Force -ErrorAction Stop + $found = Get-ChildItem $into -Recurse -Filter 'sl.interposer.dll' | + Where-Object { $_.FullName -match '\\bin\\x64\\sl\.interposer\.dll$' -and $_.FullName -notmatch '\\development\\' } | + Select-Object -First 1 + if (-not $found) { throw 'The Streamline archive has no bin\x64\sl.interposer.dll.' } + $top = Split-Path (Split-Path (Split-Path $found.FullName)) + New-Item -ItemType Directory -Force $bin | Out-Null + Get-ChildItem (Join-Path $top 'bin\x64') -File | + Where-Object { $_.Name -match '^(sl\.(interposer|common|dlss_g|reflex|pcl)\.dll|.*license.*\.txt)$' } | + Copy-Item -Destination $bin -Force + Copy-Item (Join-Path $top 'license.txt') $sl -Force -ErrorAction SilentlyContinue + Remove-Item $into -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item $zip -Force + } + } + $model = Join-Path $bin 'nvngx_dlssg.dll' + if (Test-Path $model) { Write-Host ' nvngx_dlssg.dll is there already' } + else { Write-Host ' nvngx_dlssg.dll'; Get-File "$raw/lib/Windows_x86_64/rel/nvngx_dlssg.dll" $model } + Write-Host " licences: $(Join-Path $sl 'license.txt') (Streamline) and NVIDIA's DLSS licence above (nvngx_dlssg.dll)" +} +Write-Host '' +Write-Host 'Done. The next start of scripts\play-nvidia.ps1 builds the layer with DLSS (about a minute) and uses it.' diff --git a/scripts/play-nvidia.ps1 b/scripts/play-nvidia.ps1 index 3918918..52eff56 100644 --- a/scripts/play-nvidia.ps1 +++ b/scripts/play-nvidia.ps1 @@ -1,17 +1,28 @@ -# Starts the title on an NVIDIA card with the Series S settings measured on an RTX 5070 (about 18-22 fps, no device loss). +# Starts the title on an NVIDIA card: Series S, the game's own 720p picture taken to 1080p by DLSS, the F1 +# settings menu in the game (measured on an RTX 5070: about 15-17 fps before generated frames). # scripts\play-nvidia.ps1 -Exe +# DLSS and DLSS frame generation need a few NVIDIA files (about 70 MB) that this repository does not carry: +# run Get-NVIDIA-DLSS.cmd in the repository's folder once, and they are fetched from NVIDIA's GitHub into +# nvidia-sdk\. Without them the game runs with its picture stretched to the screen instead. +# The layer is built here if it is not built yet, and built again with DLSS once those files are there. +# In the game: F1 = settings (arrows pick and change, Enter saves; kept in victory-settings.txt next to this +# folder), F3 = the numbers panel. # -NoSmoothMotion run target\\victory.exe itself. By default a copy named victory_sm.exe is started instead, # so a Smooth Motion profile set for that exe in the NVIDIA App applies every time. -# -SeriesX the Series X profile instead (slower: about 7 fps at half scale) -# -Quality fewer stretched/jumping bodies and less rainbow skin, at about 13 fps instead of about 20 -# -RayTracing keep the title's ray-tracing passes (off by default: see below) -# -Resolution the height the game renders at before the title's own upscaler: 2160, 1440, 1080, 720, 540 or 480. -# Series S outputs 1080p (so up to 1080 there), Series X 2160p. Default: half the output (540 on S, -# 1080 on X). The play-S-*.ps1 and play-X-*.ps1 scripts next to this one call it with each. +# -NoDlss no DLSS: the picture is stretched (fast, softer) +# -SeriesX the Series X profile instead (much slower; no DLSS there) +# -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 +# first time, and DLSS frame generation is left off with it (the two together do not work yet). +# -Resolution the older path: the game renders at this height (2160, 1440, 1080, 720, 540 or 480) and the +# title's own upscaler does the rest, without DLSS. The play-S-*.ps1 and play-X-*.ps1 scripts use it. # -Adapter on a PC with more than one card, the one to use: part of its name (-Adapter 5060) or its index -# (-Adapter '#1'). Default: Windows' default card (the one the main display is on). +# (-Adapter '#1'). Default: Windows' default card. # -Build target\diag (the default, the build all measurements are of) or target\release -# (the release build ignores the ray-tracing skip list: VICTORY_SKIP_PIPELINES is a diagnostics switch) +# -DlssDir the folder with nvngx_dlss.dll, if not nvidia-sdk\DLSS\lib\Windows_x86_64\rel +# -StreamlineDir the folder with sl.interposer.dll (frame generation), if not nvidia-sdk\Streamline\bin\x64 +# -Log the layer's log goes to a file in %LOCALAPPDATA%\VIctory\logs instead of this window +# -Capture F9 in the game saves that frame and the pictures it drew, in %LOCALAPPDATA%\VIctory\captures # -WindowsBarMB maximum MiB of title memory windows in CPU-mapped VRAM (by default 3072 on PCs with under # 24 GB of RAM, else 0; -WindowsBarMB 0 turns it off). # -More other settings: -More @{VICTORY_PANEL='1'} @@ -19,70 +30,90 @@ param( [Parameter(Mandatory)][string]$Exe, [switch]$NoSmoothMotion, + [switch]$NoDlss, [switch]$SeriesX, [switch]$Quality, [switch]$RayTracing, [ValidateSet('2160', '1440', '1080', '720', '540', '480')][string]$Resolution, [string]$Adapter, [ValidateSet('diag', 'release')][string]$Build = 'diag', + [string]$DlssDir, + [string]$StreamlineDir, + [switch]$Log, + [switch]$Capture, [hashtable]$More = @{}, [uint32]$WindowsBarMB ) +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } +$Exe = (Resolve-Path $Exe).Path + +# NVIDIA's own files: where they are (Get-NVIDIA-DLSS.cmd puts them in nvidia-sdk\). Nothing is downloaded here. +if (-not $DlssDir) { $DlssDir = $env:VICTORY_DLSS_DIR } +if (-not $StreamlineDir) { $StreamlineDir = $env:VICTORY_STREAMLINE_DIR } +$sdkDlss = Join-Path $root 'nvidia-sdk\DLSS' +$sdkDlssLib = Join-Path $sdkDlss 'lib\Windows_x86_64\x64\nvsdk_ngx_d.lib' +$sdkStreamline = Join-Path $root 'nvidia-sdk\Streamline\bin\x64' +$wantDlss = -not $NoDlss -and -not $SeriesX -and -not $Resolution +if (-not $DlssDir -and (Test-Path (Join-Path $sdkDlss 'lib\Windows_x86_64\rel\nvngx_dlss.dll'))) { $DlssDir = Join-Path $sdkDlss 'lib\Windows_x86_64\rel' } +if (-not $StreamlineDir -and (Test-Path (Join-Path $sdkStreamline 'sl.interposer.dll'))) { $StreamlineDir = $sdkStreamline } +if ($wantDlss -and -not $DlssDir) { + Write-Host 'No DLSS files here: the picture is stretched to the screen instead. Get-NVIDIA-DLSS.cmd (in the' + Write-Host "repository's folder) fetches them from NVIDIA once, about 70 MB, with frame generation's." +} + +# The build: made here if there is none, and made again with DLSS once its SDK is there (the diag build only). +$victory = Join-Path $root "target\$Build\victory.exe" +$built = Join-Path $root "target\$Build\built-with.txt" +$hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') +$canDlss = $wantDlss -and (Test-Path $sdkDlssLib) +if ($Build -eq 'diag' -and (-not (Test-Path $victory) -or ($canDlss -and -not $hasDlss -and (Test-Path $built)))) { + if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { Write-Host 'No build and no cargo: install Rust (README.md), then start this again.'; return } + Write-Host 'Building the layer (a few minutes the first time) ...' + & (Join-Path $PSScriptRoot 'build-nvidia.ps1') + $hasDlss = (Test-Path $built) -and ((Get-Content $built -Raw) -match 'dlss') +} +if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (scripts\build-nvidia.ps1)."; return } +# A build nobody noted the making of (cargo by hand) is taken at its word: with DLSS if the files are there. +$dlss = $wantDlss -and $DlssDir -and ($hasDlss -or -not (Test-Path $built)) + $settings = @{ - # This fork's play set (scripts\play.ps1, not -Safe): the speed set. - VICTORY_TEXTURE_NO_WAIT = '1'; VICTORY_RELAY = '2'; VICTORY_CARD_STEPS = '2' + # The play set. Textures are waited for: one loaded once at the start could stay empty for the run otherwise. + VICTORY_TEXTURE_NO_WAIT = '0'; VICTORY_RELAY = '2'; VICTORY_CARD_STEPS = '2' VICTORY_WIDE_BACK = '1'; VICTORY_CARD_REHASH_RUNS = '1' VICTORY_JOIN_COPIES = '1'; VICTORY_INDIRECT_WINDOW = '1'; VICTORY_RELAY_COPY = '1' + # Copy-backs caught half-written are fetched again (torn.rs). + VICTORY_FETCH_CHECK = '1' VICTORY_INDIRECT_BATCH = '2'; VICTORY_MAP_THREADS = '1'; VICTORY_TITLE_PRIORITIES = '0'; VICTORY_CARD_AWAKE = '1' - VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0.8'; VICTORY_D3D12_DRED = 'light'; VICTORY_SKIP_PIPELINES = 'none' + # The renderer's light stand-in is off (its coarse estimate made indoor light blotchy). + VICTORY_SHOW_AFTER = '1'; VICTORY_AMBIENT = '0'; VICTORY_D3D12_DRED = 'light' VICTORY_THIN = '1'; VICTORY_JOIN_PARTS = '8'; VICTORY_UPLOAD_AHEAD = '1' - # Cheap picture fixes, on in both sets: - # - Overbright views: without rays the light probes keep the sky's light indoors. The fog is bounded by 1.5 times - # the light around, and what the title left by 2 times the estimate (was 4; ambient.rs). - VICTORY_AMBIENT_AIR = '1.5'; VICTORY_AMBIENT_MOST = '2' - # - Black blobs: a NaN a shader writes is made 0 before blur and the temporal upscaler spread it (emit/lower.rs). - VICTORY_NAN_SCRUB = '1' - # Wait for new shaders rather than skip their draws (a hitch the first time a place is seen). Each pipeline is - # waited for at most once (VICTORY_PIPELINE_WAIT_ONCE, on by default): one that takes longer no longer stops the - # picture in every frame it is in view (pipeline/make.rs). + # Fog bounded by 1.5 times the light around; a NaN a shader writes is made 0 before blur and the upscaler spread it. + VICTORY_AMBIENT_AIR = '1.5'; VICTORY_NAN_SCRUB = '1' + # Wait for new shaders rather than skip their draws (each pipeline is waited for at most once). The F1 menu's + # SHADER WAIT MS changes it: 0 never waits, things then show up as their shaders are done. VICTORY_PIPELINE_WAIT_MS = '10000' # NVIDIA caps the shader-visible view heap at 1,000,000: without more dynamic slots thousands of draws a frame # are dropped (descriptor/host.rs dynamic_slots). VICTORY_DYNAMIC_SLOTS = '524288' - # Half render scale with the title's own upscaler (Series S needs it with a scale below 1; victory-loader hooks.rs). - VICTORY_RENDER_SCALE = '0.5'; VICTORY_OWN_UPSCALER = '1' - # Ray walks end at the root while the structure builder is off (emit/intersect.rs). - VICTORY_BVH_MISS = '1' - # Memory compares on the card instead of the CPU: 11 -> about 22 fps on Series S. + # Memory compares on the card instead of the CPU. VICTORY_CARD_BUFFERS_MIN_MB = '1'; VICTORY_CARD_BUFFERS_MB = '1536' - # Series S presents the interface as a second plane: laid over the game (compose.rs), else black before gameplay. - VICTORY_COMPOSE = '1' } -# Ray tracing mostly off. The structure builder cannot run on NVIDIA (its 64-lane programs are refused; upstream -# Marvisak/VIctory pull request 2311), so every ray misses, and the passes that turn misses into light made rooms go -# white depending on the view angle. rt_off_hashes.txt lists the 1,000 CS_RaytracingResolve and 34 traced-shadow -# shaders, which are skipped. The screen-probe and visibility traces keep running: skipping those too left their -# outputs as garbage (rainbow glitter everywhere). -$rtList = Join-Path $PSScriptRoot 'rt_off_hashes.txt' -if (-not $RayTracing -and (Test-Path $rtList)) { - $settings.VICTORY_SKIP_PIPELINES = (Get-Content $rtList -Raw).Trim() -} -if ($Quality) { - # Stretched/jumping bodies: relay stage 1 and no card steps (avatarmanz/VIctory-7900XTX issue 13, - # fxceless/victory-fork issue 89). Rainbow skin: texture refreshes wait for the runtime's remapping. - # Costs about 7 fps (the submitting thread waits about 30 ms a frame for the card). - $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0'; $settings.VICTORY_TEXTURE_NO_WAIT = '0' -} -# The render scale is the rendered height over the output height (Series S 1080, Series X 2160). -$outHeight = if ($SeriesX) { 2160 } else { 1080 } -$console = if ($SeriesX) { 'X' } else { 'S' } +$console = if ($SeriesX) { 'series-x' } else { 'series-s' } if ($Resolution) { - if ([int]$Resolution -gt $outHeight) { - Write-Host "Series $console outputs ${outHeight}p: ${Resolution}p is above it." - return - } + # The older path: a render scale and the title's own upscaler (rendered height over output height). + $outHeight = if ($SeriesX) { 2160 } else { 1080 } + if ([int]$Resolution -gt $outHeight) { Write-Host "That console outputs ${outHeight}p: ${Resolution}p is above it."; return } $settings.VICTORY_RENDER_SCALE = ([int]$Resolution / $outHeight).ToString('0.####', [Globalization.CultureInfo]::InvariantCulture) + $settings.VICTORY_OWN_UPSCALER = '1' +} elseif ($dlss) { + $settings.VICTORY_UPSCALE = 'dlss'; $settings.VICTORY_DLSS_DIR = $DlssDir +} elseif (-not $SeriesX) { + $settings.VICTORY_UPSCALE = 'stretch' } +if ($StreamlineDir) { $settings.VICTORY_STREAMLINE_DIR = $StreamlineDir } +if ($Quality) { $settings.VICTORY_RELAY = '1'; $settings.VICTORY_CARD_STEPS = '0' } +if ($RayTracing) { $settings.VICTORY_BVH_BUILDER = '1' } if ($Adapter) { $settings.VICTORY_ADAPTER = $Adapter } if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $settings.VICTORY_WINDOWS_BAR_MB = $WindowsBarMB.ToString([Globalization.CultureInfo]::InvariantCulture) @@ -96,27 +127,99 @@ if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { Write-Host "$([math]::Round($ram / 1GB)) GB of RAM: title memory windows in the card's memory the CPU maps, up to 3 GB (-WindowsBarMB 0 turns this off)" } } -foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } -$scale = [double]::Parse($settings.VICTORY_RENDER_SCALE, [Globalization.CultureInfo]::InvariantCulture) -Write-Host "Series $console, rendering at $([int]($outHeight * $scale))p (render scale $($settings.VICTORY_RENDER_SCALE))" -$victory = Join-Path $PSScriptRoot "..\target\$Build\victory.exe" -if (-not (Test-Path $victory)) { Write-Host "No $victory. Build it first (README.md)."; return } -if (-not (Test-Path $Exe)) { Write-Host "No $Exe."; return } -if (-not $NoSmoothMotion) { +# What the F1 menu saved (victory-settings.txt, git-ignored), over the settings above. An empty value unsets one. +$menuFile = Join-Path $root 'victory-settings.txt' +$smooth = -not $NoSmoothMotion +if (Test-Path $menuFile) { + foreach ($line in Get-Content $menuFile) { + if ($line -notmatch '^\s*(VICTORY_[A-Z0-9_]+)\s*=(.*)$') { continue } + $k = $Matches[1]; $v = $Matches[2].Trim() + if ($k -eq 'VICTORY_MENU_SMOOTH_MOTION') { $smooth = $v -ne '0'; continue } + if ($k -eq 'VICTORY_MENU_CONSOLE') { if ($v) { $console = $v }; continue } + if ($v) { $settings[$k] = $v } else { $settings.Remove($k) } + } +} +foreach ($k in $More.Keys) { $settings[$k] = $More[$k] } +# DLSS only where it can be: a menu choice of it without the files or the build falls back to the stretch. +if ($settings.VICTORY_UPSCALE -eq 'dlss' -and -not $dlss) { $settings.VICTORY_UPSCALE = 'stretch' } +# DLSS frame generation and real ray tracing do not work together yet (0.1 frames a second): with ray tracing +# on, frame generation is left off and Smooth Motion can do the extra frames. +if ($settings.VICTORY_BVH_BUILDER -eq '1' -and $settings.VICTORY_FRAME_GEN -and $settings.VICTORY_FG_WITH_RT -ne '1') { + Write-Host 'Ray tracing is on: DLSS frame generation is left off (the two together do not work yet).' + $settings.Remove('VICTORY_FRAME_GEN') +} +if ($settings.VICTORY_FRAME_GEN -and -not $StreamlineDir) { + Write-Host 'Frame generation needs the Streamline files (Get-NVIDIA-DLSS.cmd): left off.' + $settings.Remove('VICTORY_FRAME_GEN') +} +# Smooth Motion is a second frame generator: off while DLSS frame generation is on. +if ($settings.VICTORY_FRAME_GEN -and $settings.VICTORY_FRAME_GEN -ne '1') { $smooth = $false } +# For the menu: what it shows as the current values, where it saves, and how it starts the game again. +$settings.VICTORY_MENU_SMOOTH_MOTION = if ($smooth) { '1' } else { '0' } +$settings.VICTORY_MENU_CONSOLE = $console +$settings.VICTORY_MENU_FILE = $menuFile +$settings.VICTORY_MENU_PLAY = $MyInvocation.MyCommand.Path +$again = @("-Exe '$($Exe -replace "'", "''")'", "-Build $Build") +foreach ($s in 'NoSmoothMotion', 'NoDlss', 'SeriesX', 'Quality', 'RayTracing', 'Log', 'Capture') { + if ($PSBoundParameters[$s]) { $again += "-$s" } +} +foreach ($s in 'Resolution', 'Adapter', 'DlssDir', 'StreamlineDir') { + if ($PSBoundParameters[$s]) { $again += "-$s '$($PSBoundParameters[$s] -replace "'", "''")'" } +} +if ($PSBoundParameters.ContainsKey('WindowsBarMB')) { $again += "-WindowsBarMB $WindowsBarMB" } +$settings.VICTORY_MENU_ARGS = $again -join ' ' + +$picture = if ($settings.VICTORY_RENDER_SCALE) { "render scale $($settings.VICTORY_RENDER_SCALE), the title's upscaler" } + elseif ($settings.VICTORY_UPSCALE -eq 'dlss') { 'DLSS' } + elseif ($settings.VICTORY_UPSCALE -eq 'stretch') { 'stretched (no DLSS)' } + else { "the title's upscaler" } +$extras = '' +if ($settings.VICTORY_FRAME_GEN) { $extras += ", frame generation $($settings.VICTORY_FRAME_GEN)x" } +if ($settings.VICTORY_BVH_BUILDER -eq '1') { $extras += ', ray tracing' } +Write-Host "Series $(if ($console -eq 'series-x') { 'X' } else { 'S' }), $picture$extras. F1 in the game: settings." + +if ($smooth) { # A copy under the name the NVIDIA App's Smooth Motion profile is set for, refreshed when the build changes. $sm = Join-Path (Split-Path $victory) 'victory_sm.exe' if (-not (Test-Path $sm) -or (Get-Item $sm).LastWriteTime -lt (Get-Item $victory).LastWriteTime) { - Copy-Item $victory $sm -Force + try { Copy-Item $victory $sm -Force -ErrorAction Stop } + catch { + # Still held by a game that has not quite gone: Windows lets it be renamed out of the way. + Rename-Item $sm "victory_sm.exe.old-$(Get-Date -Format HHmmss)" -ErrorAction SilentlyContinue + Copy-Item $victory $sm -Force + } } $victory = $sm } +Get-ChildItem (Join-Path (Split-Path $victory) '*.old-*') -ErrorAction SilentlyContinue | Remove-Item -ErrorAction SilentlyContinue + # (Other settings left over in this window go; where your files are stays.) $paths = 'VICTORY_CONFIG', 'VICTORY_GAME_DIR', 'VICTORY_CACHE_DIR', 'VICTORY_DATA_DIR' Get-ChildItem Env:VICTORY_* | Where-Object { $_.Name -notin $paths } | ForEach-Object { Remove-Item "Env:$($_.Name)" } foreach ($k in $settings.Keys) { Set-Item "Env:$k" $settings[$k] } -$Exe = (Resolve-Path $Exe).Path -$runArgs = @('run', $Exe, '--execute') -if (-not $SeriesX) { $runArgs += @('--console', 'series-s') } -Push-Location (Join-Path $PSScriptRoot '..') # victory.toml is looked for here -try { & $victory @runArgs } finally { Pop-Location } +# A shader cache of its own: one an earlier version of this fork filled does not fit this renderer's pipelines. +$toml = Join-Path $root 'victory.toml' +if (-not $env:VICTORY_CACHE_DIR -and -not ((Test-Path $toml) -and (Select-String -Path $toml -Pattern '^\s*cache_dir\s*=' -Quiet))) { + $env:VICTORY_CACHE_DIR = Join-Path $env:LOCALAPPDATA 'VIctory\cache-nvidia-2' +} +$stamp = Get-Date -Format 'MMdd-HHmmss' +if ($Capture) { + $env:VICTORY_CAPTURE = Join-Path $env:LOCALAPPDATA "VIctory\captures\$stamp" + $env:VICTORY_DUMP_TARGETS = '1' + New-Item -ItemType Directory -Force $env:VICTORY_CAPTURE | Out-Null + Write-Host "F9 saves a frame to $env:VICTORY_CAPTURE" +} +$runArgs = @('run', "`"$Exe`"", '--execute', '--console', $console) +Push-Location $root # victory.toml is looked for here +try { + if ($Log) { + $logs = Join-Path $env:LOCALAPPDATA 'VIctory\logs' + New-Item -ItemType Directory -Force $logs | Out-Null + Get-ChildItem $logs -Filter 'play-*.log' | Sort-Object LastWriteTime -Descending | Select-Object -Skip 4 | Remove-Item -ErrorAction SilentlyContinue + Write-Host "log: $logs\play-$stamp.log" + Start-Process -FilePath $victory -ArgumentList $runArgs -NoNewWindow -Wait -RedirectStandardError "$logs\play-$stamp.log" + } else { + Start-Process -FilePath $victory -ArgumentList $runArgs -NoNewWindow -Wait + } +} finally { Pop-Location }