diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 16c7495..b08d111 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -30,7 +30,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/external.rs b/crates/victory-gpu/src/external.rs new file mode 100644 index 0000000..a52cafb --- /dev/null +++ b/crates/victory-gpu/src/external.rs @@ -0,0 +1,51 @@ +//! Host work that a host library records into a title's command list in +//! place of a console one (DLSS in place of the title's FidelityFX +//! upscaling, `crate::streamline`): the title textures' host copies in the +//! states the library is told, prepared as a compute shader's inputs would +//! be, and what was written. +//! +//! Ported from DexNom's fork (DexNom/VIctory, `crates/victory-gpu/src/external.rs`, +//! GPL-3.0-or-later); the work runs where the title's list is translated +//! (`crate::list::external`, also with `VICTORY_THIN=1`). + +use windows::Win32::Graphics::Direct3D12::ID3D12Resource; + +use crate::host::HostList; +use crate::object::This; + +/// A title texture's host copy, moved to the host resource `state` in +/// `list`, and the state it is in: `state` without the bits the host copy +/// cannot take (see `host::legal_state`). What the list records next finds +/// it there and must leave it there. The list holds the texture until it is +/// reset. `None` for a buffer. +pub(crate) fn host_texture(list: &HostList, resource: This, state: u32) -> Option<(ID3D12Resource, u32)> { + let texture = crate::resource::host_resource(resource)?.clone(); + crate::list::ensure_state(list, resource, state); + let state = crate::host::legal_state(&texture, state); + Some((texture, state)) +} + +/// Prepares a title-authored input with the alias, upload and depth twin +/// rules a compute shader's resource view has in the renderer. +pub(crate) fn prepare_input(list: &HostList, resource: This) -> Option<()> { + let texture = crate::resource::host_resource(resource)?; + let aliased = crate::resource::alias_of(resource).is_some_and(|source| crate::texture::alias(list, resource, source)); + if !aliased && crate::texture::title_written(texture) { + crate::texture::upload_from(list, resource, 0); + } + list.twin_use(resource, false, false); + Some(()) +} + +/// The library wrote `resource` on the host: its contents are there, not in +/// title memory. +pub(crate) fn output_written(resource: This) { + crate::texture::host_written(resource); +} + +/// Sends what the title submitted (the line of submissions first) and +/// settles it, before a library lets go of resources the GPU may still use. +pub(crate) fn finish_submitted() { + crate::queue::before_sync(); + crate::host::settle_for_fence(); +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 64df9ba..a3c4135 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -954,10 +954,16 @@ fn create() -> windows::core::Result { let messages = debug .then(|| device.cast::().ok()) .flatten(); - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_DIRECT, - ..Default::default() - })?; + // Streamline is given the device (DLSS, `VICTORY_DLSS`); for frame + // generation (`VICTORY_FRAMEGEN`) the direct queue is made through + // its device proxy. + let queue: ID3D12CommandQueue = match crate::streamline::device_made(&device) { + Some(queue) => queue, + None => device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?, + }; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = CreateEventW(None, false, false, None)?; let rtvs: ID3D12DescriptorHeap = @@ -1210,6 +1216,9 @@ pub(crate) struct HostList { /// depends on ([`HostList::changed_something`]); no two lists have the /// same. epoch: std::sync::atomic::AtomicU64, + /// The upscaling (`crate::streamline`) recorded in the list, noted for + /// the present after its submission; 0 for none. + upscale: std::sync::atomic::AtomicU64, /// Counts the list in [`ALIVE`] while it lives. _alive: Counted, /// The texts of the markers `note_op` set, in order (for device-removed @@ -4118,6 +4127,7 @@ impl Host { batch_args: Mutex::default(), coming: Mutex::default(), epoch: std::sync::atomic::AtomicU64::new(next_epoch()), + upscale: std::sync::atomic::AtomicU64::new(0), _alive: Counted::new(), #[cfg(feature = "diagnostics")] notes, @@ -5491,6 +5501,14 @@ impl Host { // and the ranges shaders write are per host copy, not per submission. let mut stage = crate::timeline::span("submit: the submission lock"); let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Upscalings these lists recorded, in submission order: the next + // present tags the latest (frame generation). + for run in runs { + let id = run.take_upscale(); + if id != 0 { + crate::streamline::submitted(id); + } + } let was_working = working(true); submitting(1, runs.len()); #[cfg(feature = "diagnostics")] @@ -6335,6 +6353,7 @@ impl HostList { let started = std::time::Instant::now(); let _resetting = crate::timeline::span("resetting a host list"); self._alive.used(); + self.upscale.store(0, Ordering::Relaxed); *self.coming.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); @@ -7267,6 +7286,16 @@ impl HostList { self.deferred().textures.contains(&key) } + /// The list recorded upscaling `id` (`crate::streamline`). + pub(crate) fn mark_upscale(&self, id: u64) { + self.upscale.store(id, Ordering::Relaxed); + } + + /// The upscaling the list recorded, taken (0 for none). + pub(crate) fn take_upscale(&self) -> u64 { + self.upscale.swap(0, Ordering::Relaxed) + } + /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { @@ -8752,6 +8781,7 @@ impl Meter { crate::descriptor::sync_line(frames); late_line(frames); crate::queue::behind_line(frames); + crate::streamline::line(frames); card_clock_line(frames, ms); #[cfg(feature = "diagnostics")] spans::line(frames); @@ -9093,6 +9123,7 @@ impl Host { if (p.width, p.height, p.format) != (width, height, format) { // Presents sent ahead hold back buffers until they have run. settle_now(WHY_SYNC); + crate::streamline::resizing(); // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { p.swap_chain @@ -9312,7 +9343,17 @@ impl Host { #[cfg(feature = "diagnostics")] crate::replay::record::present(texture, state); let mut showing = crate::timeline::span("the host's Present"); + // Frame generation: the frame's markers, constants and tags. + let presenting = crate::streamline::present_begins( + frame, + crate::streamline::Planes { + base: (texture, state_u32), + overlay: overlay.filter(|_| composed), + size: [width, height], + }, + ); let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + crate::streamline::present_ends(presenting); showing.next("the frame meter"); #[cfg(feature = "diagnostics")] p.panel.frame(p.meter.line_due()); @@ -9352,9 +9393,24 @@ impl Host { SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; - let swap_chain = factory - .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? - .cast::()?; + // With frame generation, through Streamline's factory proxy and + // on its queue proxy: the swap chain is its proxy. + let proxied = crate::streamline::swap_chain_factory(&factory).map(|(proxy, queue)| { + proxy + .CreateSwapChainForHwnd(&queue, hwnd, &desc, None, None) + .and_then(|s| s.cast::()) + }); + let swap_chain = match proxied { + Some(Ok(swap_chain)) => { + crate::streamline::swap_chain_made(true, None); + swap_chain + } + Some(Err(e)) => { + crate::streamline::swap_chain_made(false, Some(&e)); + factory.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?.cast::()? + } + None => factory.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?.cast::()?, + }; let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 4c7d78a..0fb34ea 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -33,6 +33,8 @@ pub mod device; #[cfg(windows)] mod draw; pub mod dxgi; +#[cfg(windows)] +mod external; pub mod fence; pub mod frame; #[cfg(all(windows, feature = "diagnostics"))] @@ -77,6 +79,8 @@ mod shadow; #[cfg(windows)] mod tiles; pub mod signature; +#[cfg(windows)] +pub mod streamline; mod switch; #[cfg(all(windows, feature = "diagnostics"))] mod ab; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index a18363d..93917d8 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -160,6 +160,42 @@ fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::dra crate::copystat::recorded(started); } +/// Work of ours at a place in a title list (DLSS in place of the title's +/// FidelityFX upscaling, `crate::streamline`): it is given the host list +/// there and says whether it recorded into it; if it did, what the title set +/// is set again before the title's next draw or dispatch. +#[cfg(windows)] +pub(crate) type External = Box bool + Send>; + +/// Runs `work` at this place of title list `this`: now, or, with +/// `VICTORY_THIN=1`, when the list's calls are translated (in their order). +/// False if the list records nowhere. +#[cfg(windows)] +pub(crate) fn external(this: This, work: External) -> bool { + if this.is_null() { + return false; + } + let work = match thin::put_external(this, work) { + Ok(()) => return true, + Err(work) => work, + }; + if host_list(this).is_none() { + return false; + } + run_external(this, work); + true +} + +/// [`external`]'s work on the list that records `this`'s calls. +#[cfg(windows)] +fn run_external(this: This, work: External) { + with_state(this, |host, state| { + if work(host) { + state.replay(host); + } + }); +} + /// The submission of `lists` has run: each gives its descriptor tables' /// slots back ([`crate::draw::State::tables_done`]). A list cut at waits /// keeps them: its state goes with its last part. diff --git a/crates/victory-gpu/src/list/thin.rs b/crates/victory-gpu/src/list/thin.rs index fe9277d..e2371c3 100644 --- a/crates/victory-gpu/src/list/thin.rs +++ b/crates/victory-gpu/src/list/thin.rs @@ -469,6 +469,22 @@ const TARGETS: u64 = after(13); const CLEAR_RTV: u64 = after(14); const CLEAR_DSV: u64 = after(15); const COPY_TEXTURE: u64 = after(16); +/// Work of ours (`super::external`), boxed. +const EXTERNAL: u64 = after(17); + +/// Writes down work of ours at this place of a title list's stream +/// ([`super::external`]); gives it back if the list is not written down. +pub(super) fn put_external(this: This, work: super::External) -> Result<(), super::External> { + if !wanted() || !on() { + return Err(work); + } + let front = front(this); + if front.closed || front.recording.is_none() { + return Err(work); + } + front.put(EXTERNAL, &[Box::into_raw(Box::new(work)) as u64]); + Ok(()) +} /// The bytes of `count` things at `items` (none if null). fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] { @@ -699,6 +715,15 @@ fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) held(uploads).push(block); continue; } + if op == EXTERNAL { + // SAFETY: made by `put_external`, named once. + let work = *unsafe { Box::from_raw(w[0] as *mut super::External) }; + // (A recording let go of drops it unrun.) + if !skip { + super::run_external(list, work); + } + continue; + } if skip && op != CLOSE && op != RESET { continue; } @@ -899,6 +924,46 @@ mod tests { assert!(at::(&w[1..], 2, 0).is_null()); } + /// Work of ours written down in a stream is taken out of it once: run + /// on the list the stream is translated on, or dropped unrun when the + /// recording was let go of (or there is no host list). + #[test] + fn external_work_is_taken_out_once() { + use std::sync::atomic::AtomicUsize; + struct Counted(Arc); + impl Drop for Counted { + fn drop(&mut self) { + self.0.fetch_add(1, Relaxed); + } + } + let dropped = Arc::new(AtomicUsize::new(0)); + let ran = Arc::new(AtomicUsize::new(0)); + let make = || -> super::super::External { + let guard = Counted(dropped.clone()); + let ran = ran.clone(); + Box::new(move |_| { + let _kept = &guard; + ran.fetch_add(1, Relaxed); + true + }) + }; + let mut f = Front::default(); + f.recording = Some(Arc::new(Recording::new(0))); + f.put(EXTERNAL, &[Box::into_raw(Box::new(make())) as u64]); + f.put(Plain::TOPOLOGY as u64, &[4]); + f.put(EXTERNAL, &[Box::into_raw(Box::new(make())) as u64]); + let s = std::mem::take(&mut f.words); + let (calls, closed) = translate(std::ptr::null(), &s, || true); + assert_eq!((calls, closed), (3, false)); + assert_eq!((ran.load(Relaxed), dropped.load(Relaxed)), (0, 2)); + // Not let go of, but without a host list behind it: dropped unrun. + f.put(EXTERNAL, &[Box::into_raw(Box::new(make())) as u64]); + let s = std::mem::take(&mut f.words); + assert_eq!(translate(std::ptr::null(), &s, || false), (1, false)); + assert_eq!((ran.load(Relaxed), dropped.load(Relaxed)), (0, 3)); + f.recording = None; + } + /// A view's record is the one at the call, also if its slot is written /// again right after. #[test] diff --git a/crates/victory-gpu/src/streamline.rs b/crates/victory-gpu/src/streamline.rs new file mode 100644 index 0000000..e0f1aee --- /dev/null +++ b/crates/victory-gpu/src/streamline.rs @@ -0,0 +1,1433 @@ +//! NVIDIA DLSS Super Resolution and DLSS Frame Generation through NVIDIA +//! Streamline, loaded at run time from a folder of the user's; both off by +//! default. +//! +//! - `VICTORY_DLSS=1`: the title's FidelityFX upscaling (its `ffxDispatch`, +//! served by `victory_hle::modules::fidelityfx`) is done by DLSS instead, +//! from the same colour, depth, motion vectors, exposure and reactive mask +//! into the same output, at the same place of the title's command list. +//! `VICTORY_DLSS_MODE` (dlaa, quality, balanced, performance, +//! ultraperformance) is the render scale the app patches the title's +//! renderer to; the DLSS mode follows the sizes the title then passes. +//! `VICTORY_DLSS_PRESET` (default, j, k, l, m) picks the model. +//! - `VICTORY_FRAMEGEN=1`: DLSS Frame Generation (2x) on our present. The +//! device's direct queue and the swap chain are made through Streamline's +//! proxies; every present tags the depth and motion vectors of the last +//! upscaling submitted before it, with constants made from it, and sends +//! the latency markers Frame Generation needs (Reflex on). Needs the line +//! of submissions (`VICTORY_THIN=1` or `VICTORY_ASYNC_SUBMIT=1`). +//! - `VICTORY_STREAMLINE_DIR`: the folder of `sl.interposer.dll`, its plugins +//! and NGX's DLLs (default [`DEFAULT_DIR`]). +//! +//! Anything missing (the folder, a signature, a feature on this GPU, the +//! device hand-over) leaves the title's own upscaling and our plain present +//! as they were, with a warning in the log. +//! +//! Streamline is used with manual hooking: nothing of D3D12 or DXGI is +//! hooked globally; only the objects handed to `slUpgradeInterface` are +//! proxies (the device that makes the direct queue, the factory that makes +//! the swap chain, and what they make). + +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +pub(crate) mod abi; +pub mod plan; + +pub use plan::Mode; + +use std::ffi::{CStr, c_char, c_void}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::*}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::Interface; + +use crate::object::Object; + +/// Where `sl.interposer.dll` is looked for without `VICTORY_STREAMLINE_DIR`. +pub const DEFAULT_DIR: &str = r"C:\dev\sdk\streamline-sdk-v2.14.16\bin\x64"; +const INTERPOSER: &str = "sl.interposer.dll"; +/// The project id NGX is given (engine "custom", no NVIDIA application id). +const PROJECT_ID: &CStr = c"6f0d7b2e-3a41-4c1e-9b57-2d8e4f1a9c30"; +const ENGINE_VERSION: &CStr = c"VIctory 0.1"; +/// The viewport of the upscaling; frame generation wants 0. +const VIEWPORT_DLSS: u32 = 1; +const VIEWPORT_FG: u32 = 0; + +/// What the user asked for, read from the environment once. +#[derive(Clone, Debug)] +pub struct Asked { + pub dlss: bool, + pub framegen: bool, + pub mode: Mode, + pub preset: u32, + pub dir: PathBuf, + /// `VICTORY_DLSS_JITTER` and `VICTORY_DLSS_MV`: sign or scale fixes. + pub jitter: [f32; 2], + pub mvec: [f32; 2], + /// `VICTORY_DLSS_REACTIVE=0`: the reactive mask is not given to DLSS. + pub reactive: bool, + /// `VICTORY_STREAMLINE_LOG=`: Streamline's own log there, verbose. + pub log_dir: Option, +} + +impl Asked { + /// The switches; an unknown mode or preset name is an error. + pub fn from_env() -> Result { + let var = |name: &str| std::env::var(name).ok(); + let on = |name: &str| var(name).is_some_and(|v| v.trim() == "1"); + let framegen = on("VICTORY_FRAMEGEN"); + let mode = match var("VICTORY_DLSS_MODE") { + Some(name) => Mode::from_name(&name).ok_or_else(|| { + format!("VICTORY_DLSS_MODE={name}: not one of dlaa, quality, balanced, performance, ultraperformance") + })?, + // Frame generation alone keeps the scene at the output's size. + None if framegen && !on("VICTORY_DLSS") => Mode::Dlaa, + None => Mode::Quality, + }; + let preset = match var("VICTORY_DLSS_PRESET") { + Some(name) => plan::preset(&name) + .ok_or_else(|| format!("VICTORY_DLSS_PRESET={name}: not one of default, e, f, j, k, l, m"))?, + None => 0, + }; + Ok(Asked { + dlss: on("VICTORY_DLSS"), + framegen, + mode, + preset, + dir: var("VICTORY_STREAMLINE_DIR").map_or_else(|| PathBuf::from(DEFAULT_DIR), PathBuf::from), + jitter: plan::pair(var("VICTORY_DLSS_JITTER").as_deref()), + mvec: plan::pair(var("VICTORY_DLSS_MV").as_deref()), + reactive: var("VICTORY_DLSS_REACTIVE").is_none_or(|v| v.trim() != "0"), + log_dir: var("VICTORY_STREAMLINE_LOG").filter(|v| !v.trim().is_empty() && v.trim() != "0").map(PathBuf::from), + }) + } + + pub fn any(&self) -> bool { + self.dlss || self.framegen + } +} + +/// What [`init`] made available: the upscaling (the title's renderer may be +/// patched to the FidelityFX path for it) and frame generation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Available { + pub dlss: bool, + pub framegen: bool, +} + +/// One upscaling the title asked for: a FidelityFX `ffxDispatch` of an +/// upscale, in its own terms (`victory_hle::modules::fidelityfx` reads it). +#[derive(Clone, Copy, Debug)] +pub struct Upscale { + /// The FidelityFX context. + pub context: usize, + /// The title's command list. + pub list: *const Object, + /// Colour, depth, motion vectors, exposure, reactive mask, transparency + /// and composition mask, output: the title's resource (null if none) and + /// the FidelityFX state it is in. + pub resources: [(*const Object, u32); 7], + pub camera: plan::Camera, + pub pre_exposure: f32, + pub frame_ms: f32, +} + +// SAFETY: pointers to title objects that live until the list has run (the +// title's part, as on the console); nothing else is shared. +unsafe impl Send for Upscale {} + +pub const COLOUR: usize = 0; +pub const DEPTH: usize = 1; +pub const MOTION: usize = 2; +pub const EXPOSURE: usize = 3; +pub const REACTIVE: usize = 4; +pub const OUTPUT: usize = 6; + +/// What became of an upscaling. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Taken { + /// DLSS does it: the title's own must not run. + Dlss, + /// Only noted for frame generation: the title's own runs. + Noted, + /// Neither: the title's own runs. Why, for the log. + No(&'static str), +} + +macro_rules! once { + ($level:ident, $($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::$level!($($arg)*)); + }}; +} + +struct Library(windows_sys::Win32::Foundation::HMODULE); + +impl Drop for Library { + fn drop(&mut self) { + // SAFETY: this owns the reference LoadLibraryExW took. + unsafe { windows_sys::Win32::Foundation::FreeLibrary(self.0) }; + } +} + +// SAFETY: a module handle. +unsafe impl Send for Library {} +// SAFETY: as above. +unsafe impl Sync for Library {} + +/// The library's exported functions. +struct Sl { + _library: Library, + init: abi::SlInit, + is_feature_supported: abi::SlIsFeatureSupported, + evaluate_feature: abi::SlEvaluateFeature, + free_resources: abi::SlFreeResources, + set_tag_for_frame: abi::SlSetTagForFrame, + get_feature_requirements: abi::SlGetFeatureRequirements, + get_feature_version: abi::SlGetFeatureVersion, + upgrade_interface: abi::SlUpgradeInterface, + set_constants: abi::SlSetConstants, + get_native_interface: abi::SlGetNativeInterface, + get_feature_function: abi::SlGetFeatureFunction, + get_new_frame_token: abi::SlGetNewFrameToken, + set_d3d_device: abi::SlSetD3DDevice, +} + +static SL: OnceLock = OnceLock::new(); + +/// What is on once the library is in: the switches and the features found. +struct Plan { + asked: Asked, + dlss: bool, + framegen: bool, +} + +static PLAN: OnceLock = OnceLock::new(); + +/// The per-feature functions, once the device is set. +#[derive(Default)] +struct Functions { + dlss_optimal: Option, + dlss_set_options: Option, + dlssg_set_options: Option, + dlssg_get_state: Option, + reflex_set_options: Option, + pcl_set_marker: Option, +} + +static FUNCTIONS: OnceLock = OnceLock::new(); +static DLSS_READY: AtomicBool = AtomicBool::new(false); +static FG_READY: AtomicBool = AtomicBool::new(false); + +/// Streamline's proxies kept for frame generation: the device that made the +/// direct queue and the queue the swap chain is made on. +struct Proxies { + _device: ID3D12Device, + queue: ID3D12CommandQueue, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Proxies {} +// SAFETY: as above. +unsafe impl Sync for Proxies {} + +static PROXIES: OnceLock = OnceLock::new(); +/// Our present goes through Streamline's swap chain. +static SWAP_CHAIN_PROXIED: AtomicBool = AtomicBool::new(false); + +/// Library calls that are not thread safe, and what the upscaling keeps +/// between frames, one caller at a time. +#[derive(Default)] +struct Calls { + /// Optimal render sizes by output size and mode. + optimal: Vec<([u32; 2], u32, Option<[u32; 2]>)>, + /// The mode, sizes and preset the last options named. + last: Option<(u32, [u32; 2], [u32; 2])>, + /// Frame generation: on, and the frame whose simulation began. + framegen_on: bool, + simulating: Option, +} + +static CALLS: Mutex = Mutex::new(Calls { + optimal: Vec::new(), + last: None, + framegen_on: false, + simulating: None, +}); + +fn calls() -> std::sync::MutexGuard<'static, Calls> { + CALLS.lock().unwrap_or_else(|e| e.into_inner()) +} + +// Counters since the last frame-rate line: upscalings done by DLSS, failed, +// left to the title; presents with frame generation on and off, frames it +// reported shown; and in all. +static EVALUATED: AtomicU64 = AtomicU64::new(0); +static FAILED: AtomicU64 = AtomicU64::new(0); +static FORWARDED: AtomicU64 = AtomicU64::new(0); +static FG_ON: AtomicU64 = AtomicU64::new(0); +static FG_OFF: AtomicU64 = AtomicU64::new(0); +static FG_SHOWN: AtomicU64 = AtomicU64::new(0); +static EVALUATED_ALL: AtomicU64 = AtomicU64::new(0); +static FG_STATUS: AtomicU32 = AtomicU32::new(0); +/// Presents with frame generation on, and frames it showed, in all. +static FG_ON_ALL: AtomicU64 = AtomicU64::new(0); +static FG_SHOWN_ALL: AtomicU64 = AtomicU64::new(0); +/// Upscalings noted so far (their ids). +static NEXT_ID: AtomicU64 = AtomicU64::new(0); +/// [`check`] presents from its one thread, with nothing else submitting. +static CHECKING: AtomicBool = AtomicBool::new(false); + +/// Loads Streamline from `asked.dir` and asks for what `asked` names; call +/// once, before the host device is made (`crate::host::host`) and before the +/// title's imports are bound. Fails soft: what is not there is logged and +/// left off. +pub fn init(asked: &Asked) -> Available { + if !asked.any() { + return Available::default(); + } + match load_and_init(asked, true) { + Ok(available) => available, + Err(why) => { + tracing::warn!( + folder = %asked.dir.display(), + "Streamline: {why}; DLSS and frame generation stay off, the title's own upscaling and our present run" + ); + Available::default() + } + } +} + +fn load_and_init(asked: &Asked, require_line: bool) -> Result { + let path = std::path::absolute(asked.dir.join(INTERPOSER)).map_err(|e| e.to_string())?; + if !path.is_file() { + return Err(format!("no {INTERPOSER} in that folder (VICTORY_STREAMLINE_DIR)")); + } + verify_signature(&path)?; + let sl = load(&path)?; + let sl = SL.get_or_init(|| sl); + let dir_wide: Vec = wide(&asked.dir); + let paths = [dir_wide.as_ptr()]; + let log_wide = asked.log_dir.as_deref().map(wide); + // Frame generation presents from the line's thread, in order with the + // submissions: without the line it is not loaded at all. + let framegen_asked = asked.framegen && (!require_line || line_asked()); + if asked.framegen && !framegen_asked { + tracing::warn!( + "DLSS Frame Generation needs the line of submissions (VICTORY_THIN=1 or VICTORY_ASYNC_SUBMIT=1): frame generation stays off" + ); + } + let mut features = Vec::new(); + if asked.dlss { + features.push(abi::FEATURE_DLSS); + } + if framegen_asked { + features.extend([abi::FEATURE_DLSS_G, abi::FEATURE_REFLEX, abi::FEATURE_PCL]); + } + let preferences = abi::Preferences { + base: abi::BaseStructure::new(abi::PREFERENCES, 1), + show_console: false, + log_level: if asked.log_dir.is_some() { abi::LOG_VERBOSE } else { abi::LOG_DEFAULT }, + paths_to_plugins: paths.as_ptr(), + num_paths_to_plugins: 1, + path_to_logs_and_data: log_wide.as_ref().map_or(std::ptr::null(), |w| w.as_ptr()), + allocate_callback: std::ptr::null(), + release_callback: std::ptr::null(), + log_message_callback: Some(log_message), + // No downloads (OTA): only what is in the folder runs. + flags: abi::DISABLE_CL_STATE_TRACKING + | abi::DISABLE_DEBUG_TEXT + | abi::USE_MANUAL_HOOKING + | abi::USE_DXGI_FACTORY_PROXY + | abi::USE_FRAME_BASED_RESOURCE_TAGGING, + features_to_load: features.as_ptr(), + num_features_to_load: features.len() as u32, + application_id: 0, + engine: abi::ENGINE_CUSTOM, + engine_version: ENGINE_VERSION.as_ptr(), + project_id: PROJECT_ID.as_ptr(), + render_api: abi::RENDER_API_D3D12, + }; + // SAFETY: a filled preferences structure; the library copies what it keeps. + let code = unsafe { (sl.init)(&preferences, abi::SDK_VERSION) }; + if code != 0 { + return Err(format!("slInit failed: {} ({code})", abi::result_name(code))); + } + let adapter = default_adapter(); + let luid = adapter.as_ref().map(|a| a.1); + let supported = |feature: u32| -> Result<(), String> { + let Some(luid) = luid else { return Err("no adapter".into()) }; + let info = abi::AdapterInfo { + base: abi::BaseStructure::new(abi::ADAPTER_INFO, 1), + device_luid: std::ptr::from_ref(&luid).cast(), + device_luid_size: size_of_val(&luid) as u32, + vk_physical_device: std::ptr::null_mut(), + }; + // SAFETY: an adapter description that lives through the call. + let code = unsafe { (sl.is_feature_supported)(feature, &info) }; + if code == 0 { Ok(()) } else { Err(format!("{} ({code})", abi::result_name(code))) } + }; + let dlss = asked.dlss && report("DLSS Super Resolution", abi::FEATURE_DLSS, supported(abi::FEATURE_DLSS), sl); + let framegen = framegen_asked + && report("DLSS Frame Generation", abi::FEATURE_DLSS_G, supported(abi::FEATURE_DLSS_G), sl) + && report("Reflex", abi::FEATURE_REFLEX, supported(abi::FEATURE_REFLEX), sl); + tracing::info!( + library = %path.display(), + sdk = "2.14.16", + adapter = adapter.as_ref().map_or("?", |a| a.0.as_str()), + dlss, + framegen, + mode = asked.mode.name(), + preset = asked.preset, + "Streamline loaded (manual hooking, no downloads)" + ); + let _ = PLAN.set(Plan { asked: asked.clone(), dlss, framegen }); + Ok(Available { dlss, framegen }) +} + +/// Logs whether a feature is supported, with its requirements; whether it is. +fn report(name: &str, feature: u32, supported: Result<(), String>, sl: &Sl) -> bool { + let mut requirements: abi::FeatureRequirements = unsafe_zeroed_requirements(); + // SAFETY: a structure to fill. + let asked = unsafe { (sl.get_feature_requirements)(feature, &mut requirements) }; + let needs = (asked == 0).then(|| { + format!( + "OS {} (needs {}), driver {} (needs {}){}{}", + requirements.os_version_detected, + requirements.os_version_required, + requirements.driver_version_detected, + requirements.driver_version_required, + if requirements.flags & abi::REQUIRES_HARDWARE_SCHEDULING != 0 { ", hardware GPU scheduling" } else { "" }, + if requirements.flags & abi::REQUIRES_VSYNC_OFF != 0 { ", v-sync off" } else { "" }, + ) + }); + match supported { + Ok(()) => { + tracing::info!(requirements = needs.as_deref().unwrap_or("?"), "Streamline: {name} is supported on this GPU"); + true + } + Err(why) => { + tracing::warn!(requirements = needs.as_deref().unwrap_or("?"), "Streamline: {name} is not supported here: {why}"); + false + } + } +} + +fn unsafe_zeroed_requirements() -> abi::FeatureRequirements { + // SAFETY: plain data; pointers null, counts zero. + let mut r: abi::FeatureRequirements = unsafe { std::mem::zeroed() }; + r.base = abi::BaseStructure::new(abi::FEATURE_REQUIREMENTS, 2); + r +} + +/// Whether the switches turn the line of submissions on (frame generation +/// presents from its thread, in order with the submissions). +fn line_asked() -> bool { + let on = |name: &str| std::env::var_os(name).is_some_and(|v| v == "1"); + on("VICTORY_THIN") || on("VICTORY_ASYNC_SUBMIT") +} + +unsafe extern "C" fn log_message(kind: u32, message: *const c_char) { + if message.is_null() { + return; + } + // SAFETY: a NUL-terminated message for the call. + let text = unsafe { CStr::from_ptr(message) }.to_string_lossy(); + let text = text.trim_end(); + // (Every plugin in the folder that was not asked for says so.) + let noise = text.contains("since it is was not requested by the host"); + match kind { + abi::LOG_ERROR => tracing::error!(target: "streamline", "{text}"), + abi::LOG_WARN if !noise => tracing::warn!(target: "streamline", "{text}"), + _ => tracing::debug!(target: "streamline", "{text}"), + } +} + +fn wide(path: &Path) -> Vec { + use std::os::windows::ffi::OsStrExt; + path.as_os_str().encode_wide().chain([0]).collect() +} + +/// The adapter a device made with no adapter named is on (the first), its +/// name and LUID. +fn default_adapter() -> Option<(String, windows::Win32::Foundation::LUID)> { + // SAFETY: plain DXGI queries. + unsafe { + let factory: IDXGIFactory1 = CreateDXGIFactory1().ok()?; + let adapter = factory.EnumAdapters1(0).ok()?; + let desc = adapter.GetDesc1().ok()?; + let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + Some((String::from_utf16_lossy(&desc.Description[..len]), desc.AdapterLuid)) + } +} + +/// The Authenticode signature of `path` (NVIDIA signs its DLLs), checked +/// without going online. +fn verify_signature(path: &Path) -> Result<(), String> { + use windows_sys::Win32::Security::WinTrust::*; + let file = wide(path); + let mut info = WINTRUST_FILE_INFO { + cbStruct: size_of::() as u32, + pcwszFilePath: file.as_ptr(), + hFile: std::ptr::null_mut(), + pgKnownSubject: std::ptr::null_mut(), + }; + let mut data = WINTRUST_DATA { + cbStruct: size_of::() as u32, + dwUIChoice: WTD_UI_NONE, + fdwRevocationChecks: WTD_REVOKE_NONE, + dwUnionChoice: WTD_CHOICE_FILE, + Anonymous: WINTRUST_DATA_0 { pFile: &mut info }, + dwStateAction: WTD_STATEACTION_VERIFY, + dwProvFlags: WTD_CACHE_ONLY_URL_RETRIEVAL | WTD_REVOCATION_CHECK_NONE, + ..Default::default() + }; + let mut action = WINTRUST_ACTION_GENERIC_VERIFY_V2; + // SAFETY: filled structures that live through both calls. + let code = unsafe { WinVerifyTrust(std::ptr::null_mut(), &mut action, (&raw mut data).cast()) }; + data.dwStateAction = WTD_STATEACTION_CLOSE; + // SAFETY: as above; closes the state the first call opened. + unsafe { WinVerifyTrust(std::ptr::null_mut(), &mut action, (&raw mut data).cast()) }; + if code == 0 { + Ok(()) + } else { + Err(format!("{} is not validly signed ({:#x})", path.display(), code as u32)) + } +} + +fn load(path: &Path) -> Result { + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + let file = wide(path); + // Its own folder and System32 only, never the current folder. + // SAFETY: a NUL-terminated full path. + let module = + unsafe { LoadLibraryExW(file.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32) }; + if module.is_null() { + return Err(format!("{INTERPOSER} did not load ({})", std::io::Error::last_os_error())); + } + let library = Library(module); + let find = |name: &CStr| { + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, name.as_ptr().cast()) } + .map(|f| f as *const c_void) + .ok_or_else(|| format!("{INTERPOSER} has no {}", name.to_string_lossy())) + }; + macro_rules! get { + ($name:literal, $t:ty) => { + // SAFETY: the export of that name has the header's signature. + unsafe { std::mem::transmute::<*const c_void, $t>(find($name)?) } + }; + } + Ok(Sl { + init: get!(c"slInit", abi::SlInit), + is_feature_supported: get!(c"slIsFeatureSupported", abi::SlIsFeatureSupported), + evaluate_feature: get!(c"slEvaluateFeature", abi::SlEvaluateFeature), + free_resources: get!(c"slFreeResources", abi::SlFreeResources), + set_tag_for_frame: get!(c"slSetTagForFrame", abi::SlSetTagForFrame), + get_feature_requirements: get!(c"slGetFeatureRequirements", abi::SlGetFeatureRequirements), + get_feature_version: get!(c"slGetFeatureVersion", abi::SlGetFeatureVersion), + upgrade_interface: get!(c"slUpgradeInterface", abi::SlUpgradeInterface), + set_constants: get!(c"slSetConstants", abi::SlSetConstants), + get_native_interface: get!(c"slGetNativeInterface", abi::SlGetNativeInterface), + get_feature_function: get!(c"slGetFeatureFunction", abi::SlGetFeatureFunction), + get_new_frame_token: get!(c"slGetNewFrameToken", abi::SlGetNewFrameToken), + set_d3d_device: get!(c"slSetD3DDevice", abi::SlSetD3DDevice), + _library: library, + }) +} + +/// Whether the title's FidelityFX calls are to be served (DLSS or frame +/// generation is on): `victory_hle` then puts its own in front of them. +pub fn serving() -> bool { + PLAN.get().is_some_and(|p| p.dlss || p.framegen) +} + +/// The host device is made: Streamline is given it (`slSetD3DDevice`), the +/// feature functions are fetched, and, for frame generation, the direct +/// queue is made through Streamline's device proxy. The native queue to use +/// for everything, if it was made here. +pub(crate) fn device_made(device: &ID3D12Device) -> Option { + let plan = PLAN.get()?; + let sl = SL.get()?; + // SAFETY: the native device. + let code = unsafe { (sl.set_d3d_device)(device.as_raw()) }; + if code != 0 { + tracing::warn!( + "Streamline: slSetD3DDevice failed: {} ({code}); DLSS and frame generation stay off", + abi::result_name(code) + ); + return None; + } + let function = |feature: u32, name: &CStr| -> Option<*mut c_void> { + let mut f = std::ptr::null_mut(); + // SAFETY: a NUL-terminated name and an out pointer. + let code = unsafe { (sl.get_feature_function)(feature, name.as_ptr(), &mut f) }; + if code != 0 || f.is_null() { + tracing::warn!( + "Streamline: no {} ({}, {code})", + name.to_string_lossy(), + abi::result_name(code) + ); + return None; + } + Some(f) + }; + macro_rules! f { + ($feature:expr, $name:literal, $t:ty) => { + // SAFETY: the function of that name has the header's signature. + function($feature, $name).map(|f| unsafe { std::mem::transmute::<*mut c_void, $t>(f) }) + }; + } + let mut functions = Functions::default(); + if plan.dlss { + functions.dlss_optimal = f!(abi::FEATURE_DLSS, c"slDLSSGetOptimalSettings", abi::SlDlssGetOptimalSettings); + functions.dlss_set_options = f!(abi::FEATURE_DLSS, c"slDLSSSetOptions", abi::SlDlssSetOptions); + let ready = functions.dlss_optimal.is_some() && functions.dlss_set_options.is_some(); + log_version(sl, abi::FEATURE_DLSS, "DLSS Super Resolution"); + DLSS_READY.store(ready, Release); + } + let mut queue = None; + if plan.framegen { + functions.dlssg_set_options = f!(abi::FEATURE_DLSS_G, c"slDLSSGSetOptions", abi::SlDlssgSetOptions); + functions.dlssg_get_state = f!(abi::FEATURE_DLSS_G, c"slDLSSGGetState", abi::SlDlssgGetState); + functions.reflex_set_options = f!(abi::FEATURE_REFLEX, c"slReflexSetOptions", abi::SlReflexSetOptions); + functions.pcl_set_marker = f!(abi::FEATURE_PCL, c"slPCLSetMarker", abi::SlPclSetMarker); + log_version(sl, abi::FEATURE_DLSS_G, "DLSS Frame Generation"); + log_version(sl, abi::FEATURE_REFLEX, "Reflex"); + let have = functions.dlssg_set_options.is_some() + && functions.dlssg_get_state.is_some() + && functions.reflex_set_options.is_some() + && functions.pcl_set_marker.is_some(); + if have { + if let Some(reflex) = functions.reflex_set_options { + let options = abi::ReflexOptions { + base: abi::BaseStructure::new(abi::REFLEX_OPTIONS, 1), + mode: abi::REFLEX_LOW_LATENCY, + frame_limit_us: 0, + use_markers_to_optimize: false, + virtual_key: 0, + id_thread: 0, + }; + // SAFETY: filled options. + let code = unsafe { reflex(&options) }; + tracing::info!(code, result = abi::result_name(code), "Streamline: Reflex low latency on (needed by frame generation)"); + } + queue = proxied_queue(sl, device); + } + FG_READY.store(have && queue.is_some(), Release); + if !(have && queue.is_some()) { + tracing::warn!("DLSS Frame Generation stays off: the device hand-over to Streamline did not complete"); + } + } + let _ = FUNCTIONS.set(functions); + queue +} + +fn log_version(sl: &Sl, feature: u32, name: &str) { + let mut version = abi::FeatureVersion { + base: abi::BaseStructure::new(abi::FEATURE_VERSION, 1), + version_sl: abi::Version::default(), + version_ngx: abi::Version::default(), + }; + // SAFETY: a structure to fill. + let code = unsafe { (sl.get_feature_version)(feature, &mut version) }; + if code == 0 { + tracing::info!(streamline = %version.version_sl, ngx = %version.version_ngx, "Streamline: {name} loaded"); + } else { + tracing::warn!("Streamline: {name} has no version: {} ({code})", abi::result_name(code)); + } +} + +/// The direct queue, made through Streamline's proxy of `device` (frame +/// generation hooks queue creation); the native queue is returned for our +/// use and the proxy kept for the swap chain. +fn proxied_queue(sl: &Sl, device: &ID3D12Device) -> Option { + let mut raw = device.as_raw(); + // SAFETY: an owned reference of ours; on success `raw` is a new proxy + // that holds its own reference to the device. + let code = unsafe { (sl.upgrade_interface)(&mut raw) }; + if code != 0 || raw.is_null() || raw == device.as_raw() { + tracing::warn!("Streamline: the device was not upgraded: {} ({code})", abi::result_name(code)); + return None; + } + // SAFETY: the proxy's one reference, now ours. + let proxy_device = unsafe { ID3D12Device::from_raw(raw) }; + let desc = D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }; + // SAFETY: plain queue creation through the proxy. + let proxy_queue: ID3D12CommandQueue = match unsafe { proxy_device.CreateCommandQueue(&desc) } { + Ok(q) => q, + Err(e) => { + tracing::warn!(error = %e, "Streamline: no queue from the device proxy"); + return None; + } + }; + let mut native = std::ptr::null_mut(); + // SAFETY: a proxy queue; the native one comes back with a reference. + let code = unsafe { (sl.get_native_interface)(proxy_queue.as_raw(), &mut native) }; + if code != 0 || native.is_null() { + tracing::warn!("Streamline: no native queue behind the proxy: {} ({code})", abi::result_name(code)); + return None; + } + // SAFETY: the reference slGetNativeInterface added. + let native = unsafe { ID3D12CommandQueue::from_raw(native) }; + tracing::info!("Streamline: the direct queue was made through the device proxy (frame generation)"); + let _ = PROXIES.set(Proxies { _device: proxy_device, queue: proxy_queue }); + Some(native) +} + +/// For frame generation: Streamline's proxy of `factory` and the queue +/// proxy to make the swap chain with; `None` to make it as before. +pub(crate) fn swap_chain_factory(factory: &IDXGIFactory2) -> Option<(IDXGIFactory2, ID3D12CommandQueue)> { + if !FG_READY.load(Acquire) { + return None; + } + let sl = SL.get()?; + let queue = PROXIES.get()?.queue.clone(); + let mut raw = factory.as_raw(); + // SAFETY: as for the device: a new proxy with its own reference. + let code = unsafe { (sl.upgrade_interface)(&mut raw) }; + if code != 0 || raw.is_null() || raw == factory.as_raw() { + tracing::warn!("Streamline: the DXGI factory was not upgraded: {} ({code})", abi::result_name(code)); + FG_READY.store(false, Release); + return None; + } + // SAFETY: the proxy's reference, now ours. + let proxy = unsafe { IDXGIFactory2::from_raw(raw) }; + Some((proxy, queue)) +} + +/// The swap chain was made through the proxy (or not, after all: then +/// frame generation stays off). +pub(crate) fn swap_chain_made(proxied: bool, error: Option<&windows::core::Error>) { + SWAP_CHAIN_PROXIED.store(proxied, Release); + if proxied { + tracing::info!("Streamline: our swap chain is Streamline's proxy; DLSS Frame Generation can run on its presents"); + } else { + FG_READY.store(false, Release); + tracing::warn!( + error = error.map(|e| e.to_string()).unwrap_or_default(), + "Streamline: the swap chain could not be made through the proxy; made as before, frame generation off" + ); + } +} + +fn frame_token(sl: &Sl, index: u32) -> Option<*mut abi::FrameToken> { + let mut token = std::ptr::null_mut(); + // SAFETY: an out pointer and an index. + let code = unsafe { (sl.get_new_frame_token)(&mut token, &index) }; + (code == 0 && !token.is_null()).then_some(token) +} + +/// The upscaling `up` asked for on the title's thread: DLSS records it at +/// this place of the title's list instead (or, with frame generation alone, +/// its inputs are noted there for the present); the title's own runs +/// otherwise. +pub fn upscale(up: &Upscale) -> Taken { + let Some(plan) = PLAN.get() else { + return Taken::No("Streamline is not loaded"); + }; + let dlss = plan.dlss && DLSS_READY.load(Acquire); + let framegen = plan.framegen && FG_READY.load(Acquire); + if !dlss && !framegen { + return Taken::No("Streamline has no device yet, or its features did not start"); + } + if [COLOUR, DEPTH, MOTION, OUTPUT].iter().any(|&i| up.resources[i].0.is_null()) { + return Taken::No("a required texture (colour, depth, motion vectors, output) is missing"); + } + if up.camera.render.contains(&0) || up.camera.output.contains(&0) { + return Taken::No("an empty render or output size"); + } + if dlss && let Err(why) = validate(up) { + return Taken::No(why); + } + let id = NEXT_ID.fetch_add(1, Relaxed) + 1; + let up = *up; + let asked = crate::list::external( + up.list, + Box::new(move |host| { + if framegen { + note(host, &up, id); + } + dlss && evaluate(host, &up, id) + }), + ); + if !asked { + return Taken::No("the title's list records nowhere (no host list)"); + } + if dlss { Taken::Dlss } else { Taken::Noted } +} + +/// The title's own upscaling ran for this reason. +pub fn forwarded() { + FORWARDED.fetch_add(1, Relaxed); +} + +/// What an upscaling's textures must be for DLSS, checked on the title's +/// thread (the title's own runs if not): host textures, in states they can +/// be in. +fn validate(up: &Upscale) -> Result<(), &'static str> { + for (i, &(resource, state)) in up.resources.iter().enumerate() { + if resource.is_null() || i == 5 { + continue; + } + if !crate::resource::is_resource(resource) { + return Err("a texture of the upscaling is no resource of ours"); + } + let Some(copy) = crate::resource::host_copy(resource) else { + return Err("a texture of the upscaling has no host copy (a buffer?)"); + }; + let wanted = if i == OUTPUT { plan::output_state(state) } else { plan::input_state(state) }; + if crate::host::legal_state(©.texture, wanted) != wanted { + return Err(if i == OUTPUT { + "the output cannot be written by a shader (no unordered access)" + } else { + "an input cannot be read by a shader" + }); + } + } + Ok(()) +} + +/// Frame generation: what the present after this list's submission tags, +/// noted on the host list ([`submitted`] then makes it the latest). +fn note(host: &crate::host::HostList, up: &Upscale, id: u64) { + let (Some(depth), Some(motion)) = + (crate::resource::host_copy(up.resources[DEPTH].0), crate::resource::host_copy(up.resources[MOTION].0)) + else { + return; + }; + let mut pending = pending(); + pending.retain(|n| id.saturating_sub(n.id) < 16); + pending.push(Noted { id, depth: Source::Host(depth), motion: Source::Host(motion), camera: up.camera }); + drop(pending); + host.mark_upscale(id); +} + +/// The inputs of an upscaling for frame generation. +struct Noted { + id: u64, + depth: Source, + motion: Source, + camera: plan::Camera, +} + +/// A texture frame generation reads at the present, and the state it is in +/// then: a title texture's host copy (in the state the lists submitted so +/// far left it in), or one of the check's ([`check`]) in a fixed state. +#[derive(Clone)] +enum Source { + Host(Arc), + Fixed(ID3D12Resource, u32), +} + +impl Source { + fn tagged(&self) -> abi::Resource { + match self { + Source::Host(t) => abi::Resource::texture(t.texture.as_raw(), t.state.load(Relaxed)), + Source::Fixed(t, state) => abi::Resource::texture(t.as_raw(), *state), + } + } +} + +// SAFETY: D3D12 resources are free-threaded. +unsafe impl Send for Source {} + +static PENDING: Mutex> = Mutex::new(Vec::new()); +/// The latest upscaling submitted, and the one the last present tagged. +static SUBMITTED: Mutex> = Mutex::new(None); +static PRESENTED_ID: AtomicU64 = AtomicU64::new(0); + +fn pending() -> std::sync::MutexGuard<'static, Vec> { + PENDING.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A host list that recorded upscaling `id` is submitted (in submission +/// order, before the present that follows it). +pub(crate) fn submitted(id: u64) { + let noted = { + let mut pending = pending(); + let at = pending.iter().position(|n| n.id == id); + at.map(|i| pending.swap_remove(i)) + }; + if let Some(noted) = noted { + let mut latest = SUBMITTED.lock().unwrap_or_else(|e| e.into_inner()); + if latest.as_ref().is_none_or(|l| l.id < noted.id) { + *latest = Some(noted); + } + } +} + +/// DLSS in place of the title's upscaling, recorded into `host` (where the +/// title's list is now). Whether it recorded anything. +fn evaluate(host: &crate::host::HostList, up: &Upscale, id: u64) -> bool { + let Some(plan) = PLAN.get() else { return false }; + let camera = up.camera; + let fail = |why: &str| { + FAILED.fetch_add(1, Relaxed); + tracing::warn!(id, "DLSS: the upscaling was not recorded: {why} (the output keeps what it had)"); + false + }; + // The inputs as a compute shader's would be (aliased views, uploads of + // title-written textures, depth twins), then in the states DLSS is told. + let used = |i: usize| { + !up.resources[i].0.is_null() + && (i != REACTIVE || plan.asked.reactive) + && (i != EXPOSURE || camera.flags & plan::FFX_AUTO_EXPOSURE == 0) + }; + let mut textures: Textures = Default::default(); + for i in [COLOUR, DEPTH, MOTION, EXPOSURE, REACTIVE, OUTPUT] { + if !used(i) { + continue; + } + let (resource, state) = up.resources[i]; + if i != OUTPUT && crate::external::prepare_input(host, resource).is_none() { + return fail("an input could not be prepared"); + } + let wanted = if i == OUTPUT { plan::output_state(state) } else { plan::input_state(state) }; + let Some((texture, legal)) = crate::external::host_texture(host, resource, wanted) else { + return fail("a texture has no host copy"); + }; + if legal != wanted { + return fail("a texture cannot be in the state DLSS needs"); + } + textures[i] = Some((texture, legal)); + } + let recorded = match record(host.list.as_raw(), &textures, &camera, up.pre_exposure, id) { + Ok(recorded) => recorded, + Err(why) => return fail(&why), + }; + crate::external::output_written(up.resources[OUTPUT].0); + EVALUATED.fetch_add(1, Relaxed); + let all = EVALUATED_ALL.fetch_add(1, Relaxed) + 1; + if all == 1 || recorded.changed { + tracing::info!( + render = ?camera.render, + output = ?camera.output, + mode = plan::sl_mode_name(recorded.mode), + asked = plan.asked.mode.name(), + preset = plan.asked.preset, + optimal = ?recorded.optimal, + hdr = camera.flags & plan::FFX_HIGH_DYNAMIC_RANGE != 0, + depth_inverted = camera.depth_inverted(), + auto_exposure = textures[EXPOSURE].is_none(), + reactive = textures[REACTIVE].is_some(), + display_motion_vectors = camera.display_motion_vectors(), + jitter = ?recorded.jitter, + mvec_scale = ?recorded.mvec_scale, + near = camera.near, + far = camera.far, + fov = camera.fov_y, + formats = ?formats(&textures), + evaluations = all, + "DLSS: upscaling recorded in place of the title's FidelityFX" + ); + } + true +} + +/// Colour, depth, motion vectors, exposure, reactive mask, (transparency), +/// output: the host textures DLSS is given and the states they are in. +type Textures = [Option<(ID3D12Resource, u32)>; 7]; + +fn formats(textures: &Textures) -> Vec { + textures + .iter() + .flatten() + .map(|(t, _)| { + // SAFETY: a live texture. + unsafe { t.GetDesc() }.Format.0 + }) + .collect() +} + +/// What [`record`] recorded. +struct Recorded { + mode: u32, + optimal: Option<[u32; 2]>, + /// Another mode or size than the last time. + changed: bool, + jitter: [f32; 2], + mvec_scale: [f32; 2], +} + +/// The DLSS evaluation of `textures` recorded into the open command list +/// `list`: the mode whose render size holds the title's, the options, the +/// frame's constants (frame `id` of the upscaling's viewport), the textures +/// as local tags. The textures are left in the states given. +fn record(list: *mut c_void, textures: &Textures, camera: &plan::Camera, pre_exposure: f32, id: u64) -> Result { + let (Some(plan), Some(sl), Some(functions)) = (PLAN.get(), SL.get(), FUNCTIONS.get()) else { + return Err("Streamline is not ready".into()); + }; + let (Some(optimal_of), Some(set_options)) = (functions.dlss_optimal, functions.dlss_set_options) else { + return Err("no DLSS functions".into()); + }; + let mut calls = calls(); + let output = camera.output; + let optimal = |calls: &mut Calls, mode: u32| -> Option<[u32; 2]> { + if let Some(&(_, _, size)) = calls.optimal.iter().find(|(o, m, _)| *o == output && *m == mode) { + return size; + } + let options = abi::DlssOptions::new(mode, output, plan.asked.preset); + let mut settings = abi::DlssOptimalSettings::default(); + // SAFETY: filled options and a structure to fill. + let code = unsafe { optimal_of(&options, &mut settings) }; + let size = (code == 0 && settings.optimal_render_width > 0) + .then_some([settings.optimal_render_width, settings.optimal_render_height]); + calls.optimal.push((output, mode, size)); + size + }; + let sizes: Vec<(u32, Option<[u32; 2]>)> = plan::MODES.iter().map(|&m| (m, optimal(&mut calls, m))).collect(); + let optimal_of_mode = |m: u32| sizes.iter().find(|s| s.0 == m).and_then(|s| s.1); + let mode = plan::pick_mode(camera.render, output, optimal_of_mode) + .ok_or_else(|| format!("no DLSS mode takes a {:?} render for a {output:?} output", camera.render))?; + let mut options = abi::DlssOptions::new(mode, output, plan.asked.preset); + options.pre_exposure = if pre_exposure > 0.0 { pre_exposure } else { 1.0 }; + options.color_buffers_hdr = abi::boolean(camera.flags & plan::FFX_HIGH_DYNAMIC_RANGE != 0); + options.use_auto_exposure = abi::boolean(textures[EXPOSURE].is_none()); + let viewport = abi::ViewportHandle::new(VIEWPORT_DLSS); + // SAFETY: filled options for our viewport. + let code = unsafe { set_options(&viewport, &options) }; + if code != 0 { + return Err(format!("slDLSSSetOptions: {} ({code})", abi::result_name(code))); + } + let changed = calls.last != Some((mode, camera.render, output)); + calls.last = Some((mode, camera.render, output)); + let token = frame_token(sl, id as u32).ok_or("no frame token")?; + let constants = camera.constants(plan.asked.jitter, plan.asked.mvec); + // SAFETY: constants for this frame and viewport. + let code = unsafe { (sl.set_constants)(&constants, token, &viewport) }; + if code != 0 { + return Err(format!("slSetConstants: {} ({code})", abi::result_name(code))); + } + let kinds = [ + (COLOUR, abi::BUFFER_SCALING_INPUT_COLOR, camera.render), + (DEPTH, abi::BUFFER_DEPTH, camera.render), + (MOTION, abi::BUFFER_MOTION_VECTORS, camera.motion_size()), + (EXPOSURE, abi::BUFFER_EXPOSURE, [1, 1]), + (REACTIVE, abi::BUFFER_BIAS_CURRENT_COLOR_HINT, camera.render), + (OUTPUT, abi::BUFFER_SCALING_OUTPUT_COLOR, output), + ]; + let mut resources: Vec<(abi::Resource, u32, [u32; 2])> = kinds + .iter() + .filter_map(|&(i, kind, size)| { + textures[i].as_ref().map(|(t, state)| (abi::Resource::texture(t.as_raw(), *state), kind, size)) + }) + .collect(); + let mut tags: Vec = resources + .iter_mut() + .map(|(r, kind, size)| abi::ResourceTag::new(r, *kind, abi::VALID_UNTIL_EVALUATE, abi::Extent::sized(*size))) + .collect(); + let mut inputs: Vec<*const abi::BaseStructure> = vec![std::ptr::from_ref(&viewport.base)]; + inputs.extend(tags.iter_mut().map(|t| std::ptr::from_ref(&t.base))); + // SAFETY: an open command list; inputs that live through the call. + let code = unsafe { (sl.evaluate_feature)(abi::FEATURE_DLSS, token, inputs.as_ptr(), inputs.len() as u32, list) }; + if code != 0 { + return Err(format!("slEvaluateFeature: {} ({code})", abi::result_name(code))); + } + Ok(Recorded { mode, optimal: optimal_of_mode(mode), changed, jitter: constants.jitter_offset, mvec_scale: constants.mvec_scale }) +} + +/// The title's FidelityFX upscaler `context` is destroyed: what DLSS made +/// for it goes once submitted work has run. +pub fn upscaler_destroyed(context: usize) { + let (Some(sl), true) = (SL.get(), DLSS_READY.load(Acquire)) else { return }; + let _ = context; + crate::external::finish_submitted(); + let viewport = abi::ViewportHandle::new(VIEWPORT_DLSS); + let mut calls = calls(); + // SAFETY: our viewport; nothing that names it is in flight. + let code = unsafe { (sl.free_resources)(abi::FEATURE_DLSS, &viewport) }; + calls.last = None; + tracing::info!(code, result = abi::result_name(code), "DLSS: the title's upscaler was destroyed; DLSS let go of its resources"); +} + +/// The planes a present shows (Series S: the scene and the interface over +/// it), the host states they are in, and the back buffer's size. +pub(crate) struct Planes<'a> { + pub base: (&'a ID3D12Resource, u32), + pub overlay: Option<(&'a ID3D12Resource, u32)>, + pub size: [u32; 2], +} + +/// What [`present_begins`] began, for [`present_ends`]. +pub(crate) struct Presenting { + token: *mut abi::FrameToken, + frame: u32, +} + +/// Before our swap chain's Present of title frame `frame`: with frame +/// generation, the frame's latency markers, constants and tags, and whether +/// frame generation runs on it (it does when an upscaling was submitted +/// since the last present). +pub(crate) fn present_begins(frame: u64, planes: Planes<'_>) -> Option { + if !FG_READY.load(Acquire) || !SWAP_CHAIN_PROXIED.load(Acquire) { + return None; + } + // The tagged textures' states are those the submissions before this + // present left: only the line of submissions orders the two. + if !crate::queue::line_on() && !CHECKING.load(Relaxed) { + once!(warn, "DLSS Frame Generation: the line of submissions did not start; frame generation stays off"); + return None; + } + let (sl, functions) = (SL.get()?, FUNCTIONS.get()?); + let (set_options, marker) = (functions.dlssg_set_options?, functions.pcl_set_marker?); + let frame = frame as u32; + let token = frame_token(sl, frame)?; + let mark = |m: u32| { + // SAFETY: a marker for a token of ours. + unsafe { marker(m, token) }; + }; + let mut calls = calls(); + if calls.simulating != Some(frame) { + mark(abi::SIMULATION_START); + } + calls.simulating = None; + mark(abi::SIMULATION_END); + mark(abi::RENDER_SUBMIT_START); + mark(abi::RENDER_SUBMIT_END); + let fresh = { + let latest = SUBMITTED.lock().unwrap_or_else(|e| e.into_inner()); + latest + .as_ref() + .filter(|n| n.id > PRESENTED_ID.load(Relaxed)) + .map(|n| (n.id, n.depth.clone(), n.motion.clone(), n.camera)) + }; + let viewport = abi::ViewportHandle::new(VIEWPORT_FG); + let on = if let Some((id, depth, motion, camera)) = fresh { + PRESENTED_ID.store(id, Relaxed); + let plan = PLAN.get()?; + let constants = camera.constants(plan.asked.jitter, plan.asked.mvec); + // SAFETY: constants for this frame and viewport. + let code = unsafe { (sl.set_constants)(&constants, token, &viewport) }; + if code != 0 { + once!(warn, "frame generation: slSetConstants: {} ({code})", abi::result_name(code)); + } + let mut resources = vec![ + (depth.tagged(), abi::BUFFER_DEPTH, camera.render), + (motion.tagged(), abi::BUFFER_MOTION_VECTORS, camera.motion_size()), + ]; + // Two planes: the scene is the colour without the interface, the + // interface plane its colour and alpha (premultiplied, as `compose` + // blends it). + if let Some((over, over_state)) = planes.overlay { + resources.push((abi::Resource::texture(planes.base.0.as_raw(), planes.base.1), abi::BUFFER_HUDLESS_COLOR, planes.size)); + resources.push((abi::Resource::texture(over.as_raw(), over_state), abi::BUFFER_UI_COLOR_AND_ALPHA, planes.size)); + } + let tags: Vec = resources + .iter_mut() + .map(|(r, kind, size)| abi::ResourceTag::new(r, *kind, abi::VALID_UNTIL_PRESENT, abi::Extent::sized(*size))) + .collect(); + // SAFETY: tags of live textures in the states they are in at the + // present (the line of submissions sends the present after them). + let code = unsafe { (sl.set_tag_for_frame)(token, &viewport, tags.as_ptr(), tags.len() as u32, std::ptr::null_mut()) }; + if code != 0 { + once!(warn, "frame generation: slSetTagForFrame: {} ({code})", abi::result_name(code)); + } + once!( + info, + render = ?camera.render, + output = ?camera.output, + back_buffer = ?planes.size, + interface_plane = planes.overlay.is_some(), + "DLSS Frame Generation: first frame with depth and motion vectors tagged" + ); + code == 0 + } else { + if calls.framegen_on { + // No upscaling this frame (a menu, a load): what was tagged may + // no longer hold what it did. + let tags = [abi::BUFFER_DEPTH, abi::BUFFER_MOTION_VECTORS, abi::BUFFER_HUDLESS_COLOR, abi::BUFFER_UI_COLOR_AND_ALPHA] + .map(|kind| abi::ResourceTag::new(std::ptr::null_mut(), kind, abi::VALID_UNTIL_PRESENT, abi::Extent::default())); + // SAFETY: null tags. + unsafe { (sl.set_tag_for_frame)(token, &viewport, tags.as_ptr(), tags.len() as u32, std::ptr::null_mut()) }; + } + false + }; + if on != calls.framegen_on { + let mut options = abi::DlssgOptions::new(if on { abi::DLSSG_ON } else { abi::DLSSG_OFF }); + options.flags = abi::DLSSG_RETAIN_RESOURCES_WHEN_OFF; + options.num_back_buffers = 2; + options.color_width = planes.size[0]; + options.color_height = planes.size[1]; + options.on_error_callback = Some(present_error); + // SAFETY: filled options for viewport 0, on the presenting thread. + let code = unsafe { set_options(&viewport, &options) }; + tracing::info!(frame, on, code, result = abi::result_name(code), "DLSS Frame Generation switched"); + if code == 0 { + calls.framegen_on = on; + } + } + if calls.framegen_on { + FG_ON.fetch_add(1, Relaxed); + FG_ON_ALL.fetch_add(1, Relaxed); + } else { + FG_OFF.fetch_add(1, Relaxed); + } + drop(calls); + mark(abi::PRESENT_START); + Some(Presenting { token, frame }) +} + +unsafe extern "C" fn present_error(error: *const i32) { + // SAFETY: the error for the call. + let code = unsafe { error.as_ref() }.copied().unwrap_or(0); + once!(warn, hresult = format_args!("{:#x}", code as u32), "DLSS Frame Generation: a present failed"); +} + +/// After our swap chain's Present: the frame's last marker, the next +/// frame's first, and what frame generation reports. +pub(crate) fn present_ends(presenting: Option) { + let Some(Presenting { token, frame }) = presenting else { return }; + let (Some(sl), Some(functions)) = (SL.get(), FUNCTIONS.get()) else { return }; + let (Some(marker), Some(get_state)) = (functions.pcl_set_marker, functions.dlssg_get_state) else { return }; + // SAFETY: a marker for this frame's token. + unsafe { marker(abi::PRESENT_END, token) }; + let mut calls = calls(); + if let Some(next) = frame_token(sl, frame.wrapping_add(1)) { + // SAFETY: as above, for the next frame. + unsafe { marker(abi::SIMULATION_START, next) }; + calls.simulating = Some(frame.wrapping_add(1)); + } + if calls.framegen_on { + let mut state = abi::DlssgState::default(); + let viewport = abi::ViewportHandle::new(VIEWPORT_FG); + // SAFETY: a structure to fill, no options (no estimate asked). + let code = unsafe { get_state(&viewport, &mut state, std::ptr::null()) }; + if code == 0 { + FG_SHOWN.fetch_add(u64::from(state.num_frames_actually_presented), Relaxed); + FG_SHOWN_ALL.fetch_add(u64::from(state.num_frames_actually_presented), Relaxed); + let before = FG_STATUS.swap(state.status, Relaxed); + if state.status != before { + tracing::warn!( + status = format_args!("{:#x}", state.status), + "DLSS Frame Generation status changed (0 ok, 1 output too small, 2 Reflex not seen, 4 HDR format, 8 constants invalid, 16 back buffer index not asked)" + ); + } + } + } +} + +/// Our swap chain's buffers are about to be made again: frame generation is +/// off until the next present with an upscaling (Streamline asks so). +pub(crate) fn resizing() { + if !FG_READY.load(Acquire) || !SWAP_CHAIN_PROXIED.load(Acquire) { + return; + } + let Some(set_options) = FUNCTIONS.get().and_then(|f| f.dlssg_set_options) else { return }; + let mut calls = calls(); + if calls.framegen_on { + let options = abi::DlssgOptions::new(abi::DLSSG_OFF); + let viewport = abi::ViewportHandle::new(VIEWPORT_FG); + // SAFETY: filled options. + unsafe { set_options(&viewport, &options) }; + calls.framegen_on = false; + } +} + +/// `victory upscaler-check`: Streamline, DLSS and DLSS Frame Generation on +/// this PC, without the title. Always: the library loads (signature, +/// `slInit`) and says what this GPU supports. With `device`: the host device +/// is made and handed over (versions, the queue through the device proxy +/// for frame generation), DLSS's render sizes for `output` are listed, and +/// DLSS runs three times on stand-in textures of the sizes `mode` gives. +/// With `present` too: three seconds of presents in a window of ours, with +/// stand-in depth and motion vectors tagged, frame generation on. The lines +/// say what happened. +pub fn check(output: [u32; 2], device: bool, present: bool) -> Vec { + let mut lines = Vec::new(); + let mut asked = match Asked::from_env() { + Ok(asked) => asked, + Err(why) => return vec![why], + }; + asked.dlss = true; + asked.framegen = true; + let available = match load_and_init(&asked, false) { + Ok(available) => available, + Err(why) => return vec![format!("Streamline did not load from {}: {why}", asked.dir.display())], + }; + lines.push(format!( + "Streamline loaded from {}: DLSS {}, frame generation {} on this GPU", + asked.dir.display(), + if available.dlss { "supported" } else { "NOT supported" }, + if available.framegen { "supported" } else { "NOT supported" } + )); + if !device { + return lines; + } + let Some(host) = crate::host::host() else { + lines.push("no host D3D12 device".into()); + return lines; + }; + let (dlss, framegen) = (DLSS_READY.load(Acquire), FG_READY.load(Acquire)); + lines.push(format!("device handed over: DLSS ready {dlss}, frame generation ready {framegen} (queue through Streamline's device proxy)")); + let render = asked.mode.render_size(output); + let camera = plan::Camera { + jitter: [0.0, 0.0], + motion_scale: [render[0] as f32, render[1] as f32], + render, + output, + near: 0.1, + far: 10_000.0, + fov_y: 1.0, + reset: true, + flags: plan::FFX_HIGH_DYNAMIC_RANGE | plan::FFX_DEPTH_INVERTED | plan::FFX_AUTO_EXPOSURE, + }; + let device = &host.device; + let made = (|| -> windows::core::Result<_> { + use windows::Win32::Graphics::Dxgi::Common::*; + let depth = texture(device, render, DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, SHADER_READ)?; + let motion = texture(device, render, DXGI_FORMAT_R16G16_FLOAT, D3D12_RESOURCE_FLAG_NONE, SHADER_READ)?; + let colour = texture(device, render, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_NONE, SHADER_READ)?; + let out = texture(device, output, DXGI_FORMAT_R16G16B16A16_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, UNORDERED)?; + let base = texture(device, output, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE, 0)?; + Ok((depth, motion, colour, out, base)) + })(); + let (depth, motion, colour, out, base) = match made { + Ok(made) => made, + Err(e) => { + lines.push(format!("stand-in textures not made: {e}")); + return lines; + } + }; + if dlss { + // (Known once the first evaluation asked for them.) + let sizes = || -> String { + let calls = calls(); + let sizes: Vec = calls + .optimal + .iter() + .filter(|(o, _, _)| *o == output) + .map(|&(_, m, s)| format!("{} {:?}", plan::sl_mode_name(m), s)) + .collect(); + if sizes.is_empty() { "?".into() } else { sizes.join(", ") } + }; + let mut textures: Textures = Default::default(); + textures[COLOUR] = Some((colour, SHADER_READ)); + textures[DEPTH] = Some((depth.clone(), SHADER_READ)); + textures[MOTION] = Some((motion.clone(), SHADER_READ)); + textures[OUTPUT] = Some((out, UNORDERED)); + for round in 0..3 { + let id = NEXT_ID.fetch_add(1, Relaxed) + 1; + let list = match host.new_list() { + Ok(list) => list, + Err(e) => { + lines.push(format!("no command list: {e}")); + return lines; + } + }; + let recorded = record(list.list.as_raw(), &textures, &camera, 1.0, id); + list.close(); + host.execute_sync_internal(&list); + // SAFETY: a plain query. + let removed = unsafe { device.GetDeviceRemovedReason() }; + match (recorded, removed) { + (Ok(r), Ok(())) if round == 0 => lines.push(format!( + "DLSS ran on the GPU: {render:?} -> {output:?} as {} (optimal {:?}); render sizes for {output:?}: {}", + plan::sl_mode_name(r.mode), + r.optimal, + sizes() + )), + (Ok(_), Ok(())) => {} + (Err(why), _) => { + lines.push(format!("DLSS did not run: {why}")); + return lines; + } + (_, Err(e)) => { + lines.push(format!("the device was removed after DLSS ran: {e}")); + return lines; + } + } + } + lines.push("DLSS ran three times on stand-in textures; the device is fine".into()); + } + if present && framegen { + CHECKING.store(true, Relaxed); + let (on, shown) = (FG_ON_ALL.load(Relaxed), FG_SHOWN_ALL.load(Relaxed)); + for frame in 1..=180u64 { + let id = NEXT_ID.fetch_add(1, Relaxed) + 1; + *SUBMITTED.lock().unwrap_or_else(|e| e.into_inner()) = Some(Noted { + id, + depth: Source::Fixed(depth.clone(), SHADER_READ), + motion: Source::Fixed(motion.clone(), SHADER_READ), + camera, + }); + host.present_planes(&base, 0, None, frame); + std::thread::sleep(std::time::Duration::from_millis(16)); + } + crate::host::settle_for_fence(); + lines.push(format!( + "frame generation: 180 presents, {} with it on, {} frames shown by it, status {:#x} (0 is fine){}", + FG_ON_ALL.load(Relaxed) - on, + FG_SHOWN_ALL.load(Relaxed) - shown, + FG_STATUS.load(Relaxed), + if SWAP_CHAIN_PROXIED.load(Relaxed) { "" } else { "; the swap chain is NOT Streamline's proxy" } + )); + // SAFETY: a plain query. + if let Err(e) = unsafe { device.GetDeviceRemovedReason() } { + lines.push(format!("the device was removed while presenting: {e}")); + } + } else if present { + lines.push("frame generation is not ready: no presents tried".into()); + } + lines +} + +const SHADER_READ: u32 = 0xc0; +const UNORDERED: u32 = 0x8; + +/// A stand-in texture for [`check`] (its contents are whatever the memory held). +fn texture( + device: &ID3D12Device, + size: [u32; 2], + format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: u32, +) -> windows::core::Result { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: u64::from(size[0]), + Height: size[1], + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + }; + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut made: Option = None; + // SAFETY: plain texture creation. + unsafe { + device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATES(state as i32), None, &mut made)? + }; + made.ok_or_else(windows::core::Error::empty) +} + +/// For the frame-rate line. +pub(crate) fn line(frames: f64) { + let Some(plan) = PLAN.get() else { return }; + let [done, failed, forwarded, on, off, shown] = + [&EVALUATED, &FAILED, &FORWARDED, &FG_ON, &FG_OFF, &FG_SHOWN].map(|c| c.swap(0, Relaxed)); + if plan.dlss || forwarded > 0 { + tracing::info!( + "DLSS per frame: {:.2} upscalings by DLSS, {:.2} failed, {:.2} left to the title's FidelityFX ({} by DLSS so far)", + done as f64 / frames, + failed as f64 / frames, + forwarded as f64 / frames, + EVALUATED_ALL.load(Relaxed) + ); + } + if plan.framegen { + tracing::info!( + "DLSS Frame Generation: {on} presents with it on, {off} off, {shown} frames shown by it (status {:#x}){}", + FG_STATUS.load(Relaxed), + if FG_READY.load(Relaxed) && SWAP_CHAIN_PROXIED.load(Relaxed) { "" } else { "; not running (see above)" } + ); + } +} diff --git a/crates/victory-gpu/src/streamline/abi.rs b/crates/victory-gpu/src/streamline/abi.rs new file mode 100644 index 0000000..c3f20e2 --- /dev/null +++ b/crates/victory-gpu/src/streamline/abi.rs @@ -0,0 +1,679 @@ +//! The part of NVIDIA Streamline's C ABI this crate calls (SDK 2.14, the +//! `sl_*.h` headers of the SDK's `include` folder), written down by hand from +//! those headers: structures that begin with a chained header (next, type id, +//! version), the features, buffer types and options used here, and the +//! signatures of the exported and per-feature functions. No NVIDIA header or +//! binary is part of this repository; the library is loaded at run time +//! (`super::load`). The offsets the SDK asserts in `sl.api/sl.cpp` are asserted +//! again in the tests below. +#![allow(dead_code)] + +use std::ffi::{c_char, c_void}; + +/// A structure type id (a GUID). +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StructType { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +const fn guid(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> StructType { + StructType { data1, data2, data3, data4 } +} + +/// The header every chained structure starts with. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct BaseStructure { + pub next: *mut BaseStructure, + pub kind: StructType, + pub version: usize, +} + +impl BaseStructure { + pub const fn new(kind: StructType, version: usize) -> Self { + BaseStructure { next: std::ptr::null_mut(), kind, version } + } +} + +pub const PREFERENCES: StructType = guid(0x1ca1_0965, 0xbf8e, 0x432b, [0x8d, 0xa1, 0x67, 0x16, 0xd8, 0x79, 0xfb, 0x14]); +pub const RESOURCE: StructType = guid(0x3a9d_70cf, 0x2418, 0x4b72, [0x83, 0x91, 0x13, 0xf8, 0x72, 0x1c, 0x72, 0x61]); +pub const RESOURCE_TAG: StructType = guid(0x4c6a_5aad, 0xb445, 0x496c, [0x87, 0xff, 0x1a, 0xf3, 0x84, 0x5b, 0xe6, 0x53]); +pub const CONSTANTS: StructType = guid(0xdcd3_5ad7, 0x4e4a, 0x4bad, [0xa9, 0x0c, 0xe0, 0xc4, 0x9e, 0xb2, 0x3a, 0xfe]); +pub const VIEWPORT_HANDLE: StructType = guid(0x171b_6435, 0x9b3c, 0x4fc8, [0x99, 0x94, 0xfb, 0xe5, 0x25, 0x69, 0xaa, 0xa4]); +pub const FEATURE_VERSION: StructType = guid(0x6d5b_51f0, 0x076b, 0x486d, [0x99, 0x95, 0x5a, 0x56, 0x10, 0x43, 0xf5, 0xc1]); +pub const ADAPTER_INFO: StructType = guid(0x0677_315f, 0xa746, 0x4492, [0x9f, 0x42, 0xcb, 0x61, 0x42, 0xc9, 0xc3, 0xd4]); +pub const FEATURE_REQUIREMENTS: StructType = + guid(0x6671_4097, 0xac6d, 0x4bc6, [0x89, 0x15, 0x1e, 0x0f, 0x55, 0xa6, 0xb6, 0x1f]); +pub const DLSS_OPTIONS: StructType = guid(0x6ac8_26e4, 0x4c61, 0x4101, [0xa9, 0x2d, 0x63, 0x8d, 0x42, 0x10, 0x57, 0xb8]); +pub const DLSS_OPTIMAL_SETTINGS: StructType = + guid(0xef1d_0957, 0xfd58, 0x4df7, [0xb5, 0x04, 0x8b, 0x69, 0xd8, 0xaa, 0x6b, 0x76]); +pub const DLSSG_OPTIONS: StructType = guid(0xfac5_f1cb, 0x2dfd, 0x4f36, [0xa1, 0xe6, 0x3a, 0x9e, 0x86, 0x52, 0x56, 0xc5]); +pub const DLSSG_STATE: StructType = guid(0xcc8a_c8e1, 0xa179, 0x44f5, [0x97, 0xfa, 0xe7, 0x41, 0x12, 0xf9, 0xbc, 0x61]); +pub const REFLEX_OPTIONS: StructType = guid(0xf03a_f81a, 0x6d0b, 0x4902, [0xa6, 0x51, 0xc4, 0x96, 0x5e, 0x21, 0x54, 0x34]); + +/// `sl::kSDKVersion` of the headers mirrored here (2.14.16). +pub const SDK_VERSION: u64 = (2 << 48) | (14 << 32) | (16 << 16) | 0xfedc; + +// Features (`sl::Feature`). +pub const FEATURE_DLSS: u32 = 0; +pub const FEATURE_REFLEX: u32 = 3; +pub const FEATURE_PCL: u32 = 4; +pub const FEATURE_DLSS_G: u32 = 1000; + +// Buffer types (`sl::BufferType`). +pub const BUFFER_DEPTH: u32 = 0; +pub const BUFFER_MOTION_VECTORS: u32 = 1; +pub const BUFFER_HUDLESS_COLOR: u32 = 2; +pub const BUFFER_SCALING_INPUT_COLOR: u32 = 3; +pub const BUFFER_SCALING_OUTPUT_COLOR: u32 = 4; +pub const BUFFER_EXPOSURE: u32 = 13; +pub const BUFFER_UI_COLOR_AND_ALPHA: u32 = 23; +pub const BUFFER_BIAS_CURRENT_COLOR_HINT: u32 = 29; + +// `sl::ResourceType` (a char). +pub const RESOURCE_TEX2D: u8 = 0; + +// `sl::ResourceLifecycle`. +pub const ONLY_VALID_NOW: u32 = 0; +pub const VALID_UNTIL_PRESENT: u32 = 1; +pub const VALID_UNTIL_EVALUATE: u32 = 2; + +// `sl::Boolean` (a char). +pub const FALSE: u8 = 0; +pub const TRUE: u8 = 1; +pub const INVALID: u8 = 2; + +pub const fn boolean(value: bool) -> u8 { + if value { TRUE } else { FALSE } +} + +/// `sl::INVALID_FLOAT`: a value left unset. +pub const INVALID_FLOAT: f32 = f32::MAX; + +// `sl::PreferenceFlags`. +pub const DISABLE_CL_STATE_TRACKING: u64 = 1 << 0; +pub const DISABLE_DEBUG_TEXT: u64 = 1 << 1; +pub const USE_MANUAL_HOOKING: u64 = 1 << 2; +pub const USE_DXGI_FACTORY_PROXY: u64 = 1 << 5; +pub const USE_FRAME_BASED_RESOURCE_TAGGING: u64 = 1 << 7; + +// `sl::LogLevel`, `sl::LogType`. +pub const LOG_DEFAULT: u32 = 1; +pub const LOG_VERBOSE: u32 = 2; +pub const LOG_INFO: u32 = 0; +pub const LOG_WARN: u32 = 1; +pub const LOG_ERROR: u32 = 2; + +// `sl::RenderAPI`, `sl::EngineType`. +pub const RENDER_API_D3D12: u32 = 1; +pub const ENGINE_CUSTOM: u32 = 0; + +// `sl::DLSSMode`. +pub const DLSS_OFF: u32 = 0; +pub const DLSS_MAX_PERFORMANCE: u32 = 1; +pub const DLSS_BALANCED: u32 = 2; +pub const DLSS_MAX_QUALITY: u32 = 3; +pub const DLSS_ULTRA_PERFORMANCE: u32 = 4; +pub const DLSS_ULTRA_QUALITY: u32 = 5; +pub const DLSS_DLAA: u32 = 6; + +// `sl::DLSSGMode`, `sl::DLSSGFlags`. +pub const DLSSG_OFF: u32 = 0; +pub const DLSSG_ON: u32 = 1; +pub const DLSSG_RETAIN_RESOURCES_WHEN_OFF: u32 = 1 << 3; + +// `sl::ReflexMode`. +pub const REFLEX_OFF: u32 = 0; +pub const REFLEX_LOW_LATENCY: u32 = 1; +pub const REFLEX_LOW_LATENCY_WITH_BOOST: u32 = 2; + +// `sl::PCLMarker`. +pub const SIMULATION_START: u32 = 0; +pub const SIMULATION_END: u32 = 1; +pub const RENDER_SUBMIT_START: u32 = 2; +pub const RENDER_SUBMIT_END: u32 = 3; +pub const PRESENT_START: u32 = 4; +pub const PRESENT_END: u32 = 5; + +/// `sl::Preferences` (version 1). +#[repr(C)] +pub struct Preferences { + pub base: BaseStructure, + pub show_console: bool, + pub log_level: u32, + pub paths_to_plugins: *const *const u16, + pub num_paths_to_plugins: u32, + pub path_to_logs_and_data: *const u16, + pub allocate_callback: *const c_void, + pub release_callback: *const c_void, + pub log_message_callback: Option, + pub flags: u64, + pub features_to_load: *const u32, + pub num_features_to_load: u32, + pub application_id: u32, + pub engine: u32, + pub engine_version: *const c_char, + pub project_id: *const c_char, + pub render_api: u32, +} + +pub type LogCallback = unsafe extern "C" fn(kind: u32, message: *const c_char); + +/// `sl::Resource` (version 1): for D3D12 the resource and its state are what +/// counts. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Resource { + pub base: BaseStructure, + pub kind: u8, + pub native: *mut c_void, + pub memory: *mut c_void, + pub view: *mut c_void, + pub state: u32, + pub width: u32, + pub height: u32, + pub native_format: u32, + pub mip_levels: u32, + pub array_layers: u32, + pub gpu_virtual_address: u64, + pub flags: u32, + pub usage: u32, + pub internal_flags: u16, + pub reserved: u16, +} + +impl Resource { + /// A 2D texture in host state `state`. + pub fn texture(native: *mut c_void, state: u32) -> Self { + Resource { + base: BaseStructure::new(RESOURCE, 1), + kind: RESOURCE_TEX2D, + native, + memory: std::ptr::null_mut(), + view: std::ptr::null_mut(), + state, + width: 0, + height: 0, + native_format: 0, + mip_levels: 0, + array_layers: 0, + gpu_virtual_address: 0, + flags: 0, + usage: 0, + internal_flags: 0, + reserved: 0, + } + } +} + +/// `sl::Extent`: the area of a resource that counts (all of it if empty). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Extent { + pub top: u32, + pub left: u32, + pub width: u32, + pub height: u32, +} + +impl Extent { + /// The top left `size` of a resource. + pub const fn sized(size: [u32; 2]) -> Self { + Extent { top: 0, left: 0, width: size[0], height: size[1] } + } +} + +/// `sl::ResourceTag` (version 1). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct ResourceTag { + pub base: BaseStructure, + pub resource: *mut Resource, + pub kind: u32, + pub lifecycle: u32, + pub extent: Extent, +} + +impl ResourceTag { + pub fn new(resource: *mut Resource, kind: u32, lifecycle: u32, extent: Extent) -> Self { + ResourceTag { base: BaseStructure::new(RESOURCE_TAG, 1), resource, kind, lifecycle, extent } + } +} + +/// `sl::float4x4`: four rows. +pub type Float4x4 = [[f32; 4]; 4]; + +/// `sl::Constants` (version 2): per frame and viewport. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Constants { + pub base: BaseStructure, + pub camera_view_to_clip: Float4x4, + pub clip_to_camera_view: Float4x4, + pub clip_to_lens_clip: Float4x4, + pub clip_to_prev_clip: Float4x4, + pub prev_clip_to_clip: Float4x4, + pub jitter_offset: [f32; 2], + pub mvec_scale: [f32; 2], + pub camera_pinhole_offset: [f32; 2], + pub camera_pos: [f32; 3], + pub camera_up: [f32; 3], + pub camera_right: [f32; 3], + pub camera_fwd: [f32; 3], + pub camera_near: f32, + pub camera_far: f32, + pub camera_fov: f32, + pub camera_aspect_ratio: f32, + pub motion_vectors_invalid_value: f32, + pub depth_inverted: u8, + pub camera_motion_included: u8, + pub motion_vectors_3d: u8, + pub reset: u8, + pub orthographic_projection: u8, + pub motion_vectors_dilated: u8, + pub motion_vectors_jittered: u8, + pub min_relative_linear_depth_object_separation: f32, +} + +/// `sl::ViewportHandle`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct ViewportHandle { + pub base: BaseStructure, + pub value: u32, +} + +impl ViewportHandle { + pub const fn new(value: u32) -> Self { + ViewportHandle { base: BaseStructure::new(VIEWPORT_HANDLE, 1), value } + } +} + +/// `sl::Version`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Version { + pub major: u32, + pub minor: u32, + pub build: u32, +} + +impl std::fmt::Display for Version { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}.{}.{}", self.major, self.minor, self.build) + } +} + +/// `sl::FeatureVersion`. +#[repr(C)] +pub struct FeatureVersion { + pub base: BaseStructure, + pub version_sl: Version, + pub version_ngx: Version, +} + +/// `sl::AdapterInfo`. +#[repr(C)] +pub struct AdapterInfo { + pub base: BaseStructure, + pub device_luid: *const u8, + pub device_luid_size: u32, + pub vk_physical_device: *mut c_void, +} + +/// `sl::FeatureRequirements` (version 2). +#[repr(C)] +pub struct FeatureRequirements { + pub base: BaseStructure, + pub flags: u32, + pub max_num_cpu_threads: u32, + pub max_num_viewports: u32, + pub num_required_tags: u32, + pub required_tags: *const u32, + pub os_version_detected: Version, + pub os_version_required: Version, + pub driver_version_detected: Version, + pub driver_version_required: Version, + pub vk_num_compute_queues_required: u32, + pub vk_num_graphics_queues_required: u32, + pub vk_num_device_extensions: u32, + pub vk_device_extensions: *const *const c_char, + pub vk_num_instance_extensions: u32, + pub vk_instance_extensions: *const *const c_char, + pub vk_num_features12: u32, + pub vk_features12: *const *const c_char, + pub vk_num_features13: u32, + pub vk_features13: *const *const c_char, + pub vk_num_optical_flow_queues_required: u32, +} + +/// `sl::FeatureRequirementFlags`. +pub const REQUIRES_D3D12: u32 = 1 << 1; +pub const REQUIRES_VSYNC_OFF: u32 = 1 << 3; +pub const REQUIRES_HARDWARE_SCHEDULING: u32 = 1 << 4; + +/// `sl::DLSSOptions` (version 3). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct DlssOptions { + pub base: BaseStructure, + pub mode: u32, + pub output_width: u32, + pub output_height: u32, + pub sharpness: f32, + pub pre_exposure: f32, + pub exposure_scale: f32, + pub color_buffers_hdr: u8, + pub indicator_invert_axis_x: u8, + pub indicator_invert_axis_y: u8, + pub dlaa_preset: u32, + pub quality_preset: u32, + pub balanced_preset: u32, + pub performance_preset: u32, + pub ultra_performance_preset: u32, + pub ultra_quality_preset: u32, + pub use_auto_exposure: u8, + pub alpha_upscaling_enabled: u8, +} + +impl DlssOptions { + /// The header's defaults, with `mode` for an output of `output`. + pub fn new(mode: u32, output: [u32; 2], preset: u32) -> Self { + DlssOptions { + base: BaseStructure::new(DLSS_OPTIONS, 3), + mode, + output_width: output[0], + output_height: output[1], + sharpness: 0.0, + pre_exposure: 1.0, + exposure_scale: 1.0, + color_buffers_hdr: TRUE, + indicator_invert_axis_x: FALSE, + indicator_invert_axis_y: FALSE, + dlaa_preset: preset, + quality_preset: preset, + balanced_preset: preset, + performance_preset: preset, + ultra_performance_preset: preset, + ultra_quality_preset: preset, + use_auto_exposure: FALSE, + alpha_upscaling_enabled: FALSE, + } + } +} + +/// `sl::DLSSOptimalSettings`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct DlssOptimalSettings { + pub base: BaseStructure, + pub optimal_render_width: u32, + pub optimal_render_height: u32, + pub optimal_sharpness: f32, + pub render_width_min: u32, + pub render_height_min: u32, + pub render_width_max: u32, + pub render_height_max: u32, +} + +impl Default for DlssOptimalSettings { + fn default() -> Self { + DlssOptimalSettings { + base: BaseStructure::new(DLSS_OPTIMAL_SETTINGS, 1), + optimal_render_width: 0, + optimal_render_height: 0, + optimal_sharpness: 0.0, + render_width_min: 0, + render_height_min: 0, + render_width_max: 0, + render_height_max: 0, + } + } +} + +/// `sl::DLSSGOptions` (version 5). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct DlssgOptions { + pub base: BaseStructure, + pub mode: u32, + pub num_frames_to_generate: u32, + pub flags: u32, + pub dynamic_res_width: u32, + pub dynamic_res_height: u32, + pub num_back_buffers: u32, + pub mvec_depth_width: u32, + pub mvec_depth_height: u32, + pub color_width: u32, + pub color_height: u32, + pub color_buffer_format: u32, + pub mvec_buffer_format: u32, + pub depth_buffer_format: u32, + pub hud_less_buffer_format: u32, + pub ui_buffer_format: u32, + pub on_error_callback: Option, + pub reserved15: u8, + pub queue_parallelism_mode: u32, + pub enable_user_interface_recomposition: u8, + pub dynamic_target_frame_rate: f32, +} + +/// `PFunOnAPIErrorCallback`: the HRESULT a present returned (a union of +/// HRESULT and VkResult, passed by reference). +pub type ApiErrorCallback = unsafe extern "C" fn(error: *const i32); + +impl DlssgOptions { + pub fn new(mode: u32) -> Self { + DlssgOptions { + base: BaseStructure::new(DLSSG_OPTIONS, 5), + mode, + num_frames_to_generate: 1, + flags: 0, + dynamic_res_width: 0, + dynamic_res_height: 0, + num_back_buffers: 0, + mvec_depth_width: 0, + mvec_depth_height: 0, + color_width: 0, + color_height: 0, + color_buffer_format: 0, + mvec_buffer_format: 0, + depth_buffer_format: 0, + hud_less_buffer_format: 0, + ui_buffer_format: 0, + on_error_callback: None, + reserved15: INVALID, + queue_parallelism_mode: 0, + enable_user_interface_recomposition: FALSE, + dynamic_target_frame_rate: 0.0, + } + } +} + +/// `sl::DLSSGState` (version 4). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct DlssgState { + pub base: BaseStructure, + pub estimated_vram_usage_in_bytes: u64, + pub status: u32, + pub min_width_or_height: u32, + pub num_frames_actually_presented: u32, + pub num_frames_to_generate_max: u32, + pub reserved4: u8, + pub is_vsync_support_available: u8, + pub inputs_processing_completion_fence: *mut c_void, + pub last_present_inputs_processing_completion_fence_value: u64, + pub is_dynamic_mfg_supported: u8, +} + +impl Default for DlssgState { + fn default() -> Self { + DlssgState { + base: BaseStructure::new(DLSSG_STATE, 4), + estimated_vram_usage_in_bytes: 0, + status: 0, + min_width_or_height: 0, + num_frames_actually_presented: 0, + num_frames_to_generate_max: 0, + reserved4: 0, + is_vsync_support_available: 0, + inputs_processing_completion_fence: std::ptr::null_mut(), + last_present_inputs_processing_completion_fence_value: 0, + is_dynamic_mfg_supported: 0, + } + } +} + +/// `sl::ReflexOptions`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct ReflexOptions { + pub base: BaseStructure, + pub mode: u32, + pub frame_limit_us: u32, + pub use_markers_to_optimize: bool, + pub virtual_key: u16, + pub id_thread: u32, +} + +/// An opaque `sl::FrameToken` (a structure with a virtual table). +pub type FrameToken = c_void; + +// The exported functions (`sl_core_api.h`): C++ references are pointers; +// `sl::Result` is an `int`. +pub type SlInit = unsafe extern "C" fn(*const Preferences, u64) -> i32; +pub type SlShutdown = unsafe extern "C" fn() -> i32; +pub type SlIsFeatureSupported = unsafe extern "C" fn(u32, *const AdapterInfo) -> i32; +pub type SlSetFeatureLoaded = unsafe extern "C" fn(u32, bool) -> i32; +pub type SlEvaluateFeature = + unsafe extern "C" fn(u32, *const FrameToken, *const *const BaseStructure, u32, *mut c_void) -> i32; +pub type SlFreeResources = unsafe extern "C" fn(u32, *const ViewportHandle) -> i32; +pub type SlSetTagForFrame = + unsafe extern "C" fn(*const FrameToken, *const ViewportHandle, *const ResourceTag, u32, *mut c_void) -> i32; +pub type SlGetFeatureRequirements = unsafe extern "C" fn(u32, *mut FeatureRequirements) -> i32; +pub type SlGetFeatureVersion = unsafe extern "C" fn(u32, *mut FeatureVersion) -> i32; +pub type SlUpgradeInterface = unsafe extern "C" fn(*mut *mut c_void) -> i32; +pub type SlSetConstants = unsafe extern "C" fn(*const Constants, *const FrameToken, *const ViewportHandle) -> i32; +pub type SlGetNativeInterface = unsafe extern "C" fn(*mut c_void, *mut *mut c_void) -> i32; +pub type SlGetFeatureFunction = unsafe extern "C" fn(u32, *const c_char, *mut *mut c_void) -> i32; +pub type SlGetNewFrameToken = unsafe extern "C" fn(*mut *mut FrameToken, *const u32) -> i32; +pub type SlSetD3DDevice = unsafe extern "C" fn(*mut c_void) -> i32; + +// Per-feature functions (`slGetFeatureFunction`). +pub type SlDlssGetOptimalSettings = unsafe extern "C" fn(*const DlssOptions, *mut DlssOptimalSettings) -> i32; +pub type SlDlssSetOptions = unsafe extern "C" fn(*const ViewportHandle, *const DlssOptions) -> i32; +pub type SlDlssgSetOptions = unsafe extern "C" fn(*const ViewportHandle, *const DlssgOptions) -> i32; +pub type SlDlssgGetState = unsafe extern "C" fn(*const ViewportHandle, *mut DlssgState, *const DlssgOptions) -> i32; +pub type SlReflexSetOptions = unsafe extern "C" fn(*const ReflexOptions) -> i32; +pub type SlPclSetMarker = unsafe extern "C" fn(u32, *const FrameToken) -> i32; + +/// The name of an `sl::Result`, for the log. +pub fn result_name(code: i32) -> &'static str { + const NAMES: [&str; 40] = [ + "ok", + "IO error", + "driver out of date", + "OS out of date", + "OS hardware scheduling disabled", + "device not created", + "no supported adapter found", + "adapter not supported", + "no plugins", + "Vulkan API", + "DXGI API", + "D3D API", + "NRD API", + "NVAPI", + "Reflex API", + "NGX failed", + "JSON parsing", + "missing proxy", + "missing resource state", + "invalid integration", + "missing input parameter", + "not initialized", + "compute failed", + "init not called", + "exception handler", + "invalid parameter", + "missing constants", + "duplicated constants", + "missing or invalid API", + "common constants missing", + "unsupported interface", + "feature missing", + "feature not supported", + "feature missing hooks", + "feature failed to load", + "feature wrong priority", + "feature missing dependency", + "feature manager invalid state", + "invalid state", + "warning: out of VRAM", + ]; + usize::try_from(code).ok().and_then(|i| NAMES.get(i)).copied().unwrap_or("unknown result") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::{offset_of, size_of}; + + /// The offsets `sl.api/sl.cpp` asserts (they may only grow at the end). + #[test] + fn offsets_match_the_sdk_asserts() { + assert_eq!(size_of::(), 32); + assert_eq!(offset_of!(Preferences, render_api), 136); + assert_eq!(offset_of!(ResourceTag, extent), 48); + assert_eq!(offset_of!(Resource, internal_flags), 104); + assert_eq!(offset_of!(Resource, reserved), 106); + assert_eq!(offset_of!(Constants, motion_vectors_jittered), 450); + assert_eq!(offset_of!(FeatureVersion, version_ngx), 44); + assert_eq!(offset_of!(FeatureRequirements, vk_num_optical_flow_queues_required), 176); + assert_eq!(offset_of!(AdapterInfo, vk_physical_device), 48); + } + + /// Fields the SDK does not assert, laid out as the headers' C++ would. + #[test] + fn feature_structures_lay_out_as_the_headers() { + assert_eq!(offset_of!(Constants, jitter_offset), 352); + assert_eq!(offset_of!(Constants, camera_near), 424); + assert_eq!(offset_of!(Constants, depth_inverted), 444); + assert_eq!(offset_of!(Constants, min_relative_linear_depth_object_separation), 452); + assert_eq!(size_of::(), 456); + assert_eq!(size_of::(), 40); + assert_eq!(offset_of!(DlssOptions, color_buffers_hdr), 56); + assert_eq!(offset_of!(DlssOptions, dlaa_preset), 60); + assert_eq!(offset_of!(DlssOptions, use_auto_exposure), 84); + assert_eq!(size_of::(), 88); + assert_eq!(offset_of!(DlssOptimalSettings, render_height_max), 56); + assert_eq!(offset_of!(DlssgOptions, on_error_callback), 96); + assert_eq!(offset_of!(DlssgOptions, queue_parallelism_mode), 108); + assert_eq!(offset_of!(DlssgOptions, dynamic_target_frame_rate), 116); + assert_eq!(size_of::(), 120); + assert_eq!(offset_of!(DlssgState, num_frames_actually_presented), 48); + assert_eq!(offset_of!(DlssgState, inputs_processing_completion_fence), 64); + assert_eq!(offset_of!(DlssgState, is_dynamic_mfg_supported), 80); + assert_eq!(offset_of!(ReflexOptions, virtual_key), 42); + assert_eq!(size_of::(), 48); + assert_eq!(size_of::(), 112); + assert_eq!(size_of::(), 64); + } + + #[test] + fn the_sdk_version_is_2_14_16() { + assert_eq!(SDK_VERSION >> 48, 2); + assert_eq!((SDK_VERSION >> 32) & 0xffff, 14); + assert_eq!((SDK_VERSION >> 16) & 0xffff, 16); + assert_eq!(SDK_VERSION & 0xffff, 0xfedc); + assert_eq!(result_name(0), "ok"); + assert_eq!(result_name(26), "missing constants"); + assert_eq!(result_name(39), "warning: out of VRAM"); + assert_eq!(result_name(-1), "unknown result"); + } +} diff --git a/crates/victory-gpu/src/streamline/plan.rs b/crates/victory-gpu/src/streamline/plan.rs new file mode 100644 index 0000000..a4c8d3b --- /dev/null +++ b/crates/victory-gpu/src/streamline/plan.rs @@ -0,0 +1,473 @@ +//! What does not need the library: the switches, which DLSS mode a title's +//! render and output sizes call for, the FidelityFX states and flags as the +//! host and Streamline read them, and the camera constants built from what an +//! upscaling names. + +use super::abi; + +/// `VICTORY_DLSS_MODE`: the render scale asked for (the title's renderer is +/// patched to it, see the app's `native_1440p::prepare_upscaler`), named as +/// DLSS names its modes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Dlaa, + Quality, + Balanced, + Performance, + UltraPerformance, +} + +impl Mode { + pub fn from_name(name: &str) -> Option { + Some(match name.trim().to_ascii_lowercase().as_str() { + "dlaa" | "native" => Mode::Dlaa, + "quality" => Mode::Quality, + "balanced" => Mode::Balanced, + "performance" => Mode::Performance, + "ultraperformance" | "ultra-performance" | "ultra_performance" => Mode::UltraPerformance, + _ => return None, + }) + } + + pub fn name(self) -> &'static str { + match self { + Mode::Dlaa => "dlaa", + Mode::Quality => "quality", + Mode::Balanced => "balanced", + Mode::Performance => "performance", + Mode::UltraPerformance => "ultraperformance", + } + } + + /// The render size over the output size (DLSS's ratios). + pub fn scale(self) -> f32 { + match self { + Mode::Dlaa => 1.0, + Mode::Quality => 2.0 / 3.0, + Mode::Balanced => 0.58, + Mode::Performance => 0.5, + Mode::UltraPerformance => 1.0 / 3.0, + } + } + + /// The FidelityFX quality mode of the same ratio (native AA, quality, + /// balanced, performance, ultra performance), which the title notes. + pub fn ffx_mode(self) -> u8 { + match self { + Mode::Dlaa => 0, + Mode::Quality => 1, + Mode::Balanced => 2, + Mode::Performance => 3, + Mode::UltraPerformance => 4, + } + } + + /// The `sl::DLSSMode` of the same ratio. + pub fn sl_mode(self) -> u32 { + match self { + Mode::Dlaa => abi::DLSS_DLAA, + Mode::Quality => abi::DLSS_MAX_QUALITY, + Mode::Balanced => abi::DLSS_BALANCED, + Mode::Performance => abi::DLSS_MAX_PERFORMANCE, + Mode::UltraPerformance => abi::DLSS_ULTRA_PERFORMANCE, + } + } + + /// The render size the title makes of `output` at this scale (it + /// truncates, as the title's own sizing code does). + pub fn render_size(self, output: [u32; 2]) -> [u32; 2] { + output.map(|v| (v as f32 * self.scale()) as u32) + } +} + +/// `VICTORY_DLSS_PRESET`: the DLSS model for every mode (`sl::DLSSPreset`). +pub fn preset(name: &str) -> Option { + Some(match name.trim().to_ascii_lowercase().as_str() { + "" | "default" => 0, + "e" => 5, + "f" => 6, + "j" => 10, + "k" => 11, + "l" => 12, + "m" => 13, + _ => return None, + }) +} + +/// The name of a `sl::DLSSMode`. +pub fn sl_mode_name(mode: u32) -> &'static str { + match mode { + abi::DLSS_OFF => "off", + abi::DLSS_MAX_PERFORMANCE => "performance", + abi::DLSS_BALANCED => "balanced", + abi::DLSS_MAX_QUALITY => "quality", + abi::DLSS_ULTRA_PERFORMANCE => "ultra performance", + abi::DLSS_ULTRA_QUALITY => "ultra quality", + abi::DLSS_DLAA => "DLAA", + _ => "?", + } +} + +/// The DLSS modes tried for a render size, largest render size first. +pub const MODES: [u32; 6] = [ + abi::DLSS_DLAA, + abi::DLSS_ULTRA_QUALITY, + abi::DLSS_MAX_QUALITY, + abi::DLSS_BALANCED, + abi::DLSS_MAX_PERFORMANCE, + abi::DLSS_ULTRA_PERFORMANCE, +]; + +/// The DLSS mode for a title that renders `render` for an output of +/// `output`: of the modes whose optimal render size (`optimal`, from the +/// library) holds `render` (DLSS makes its feature for that size and takes +/// smaller ones as a sub-rectangle), the one with the smallest. +pub fn pick_mode(render: [u32; 2], output: [u32; 2], optimal: impl Fn(u32) -> Option<[u32; 2]>) -> Option { + if render[0] == 0 || render[1] == 0 || render[0] > output[0] || render[1] > output[1] { + return None; + } + MODES + .iter() + .filter_map(|&mode| optimal(mode).map(|size| (mode, size))) + .filter(|&(_, size)| size[0] >= render[0] && size[1] >= render[1] && size[0] <= output[0] && size[1] <= output[1]) + .min_by_key(|&(_, size)| u64::from(size[0]) * u64::from(size[1])) + .map(|(mode, _)| mode) +} + +// FidelityFX API upscale flags (`FFX_UPSCALE_ENABLE_*`). +pub const FFX_HIGH_DYNAMIC_RANGE: u32 = 1 << 0; +pub const FFX_DISPLAY_RESOLUTION_MOTION_VECTORS: u32 = 1 << 1; +pub const FFX_MOTION_VECTORS_JITTER_CANCELLATION: u32 = 1 << 2; +pub const FFX_DEPTH_INVERTED: u32 = 1 << 3; +pub const FFX_DEPTH_INFINITE: u32 = 1 << 4; +pub const FFX_AUTO_EXPOSURE: u32 = 1 << 5; + +/// A FidelityFX resource state as the host resource state it means (as the +/// PC backend reads it); `None` for generic read and indirect arguments, +/// which a texture DLSS reads cannot be in. (From DexNom's `fidelityfx.rs`.) +pub fn host_state(state: u32) -> Option { + Some(match state { + 0x1 | 0x80 => 0, // common, present + 0x2 => 0x8, // unordered access + 0x4 => 0x40, // compute read + 0x8 => 0x80, // pixel read + 0xc => 0xc0, // both + 0x10 => 0x800, // copy source + 0x20 => 0x400, // copy destination + 0x100 => 0x4, // render target + 0x200 => 0x10, // depth write + _ => return None, // generic read, indirect arguments + }) +} + +/// The host state DLSS is told an input is in: the one the title gave, or, +/// where that cannot be a texture's, shader resource. +pub fn input_state(ffx_state: u32) -> u32 { + host_state(ffx_state).filter(|&s| s != 0x800 && s != 0x400 && s != 0).unwrap_or(0xc0) +} + +/// The host state DLSS is told the output is in: the one the title gave if +/// that is unordered access, else unordered access. +pub fn output_state(ffx_state: u32) -> u32 { + host_state(ffx_state).filter(|&s| s == 0x8).unwrap_or(0x8) +} + +/// What an upscaling says of the camera, and of how to read its inputs. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub jitter: [f32; 2], + /// Multiplies the motion vectors into render pixels (FidelityFX). + pub motion_scale: [f32; 2], + pub render: [u32; 2], + pub output: [u32; 2], + pub near: f32, + pub far: f32, + pub fov_y: f32, + pub reset: bool, + /// The context's creation flags (`FFX_*` above). + pub flags: u32, +} + +impl Camera { + pub fn depth_inverted(&self) -> bool { + self.flags & FFX_DEPTH_INVERTED != 0 + } + + pub fn display_motion_vectors(&self) -> bool { + self.flags & FFX_DISPLAY_RESOLUTION_MOTION_VECTORS != 0 + } + + /// The size the motion vectors cover. + pub fn motion_size(&self) -> [u32; 2] { + if self.display_motion_vectors() { self.output } else { self.render } + } + + /// Streamline's motion vector scale: it multiplies by the render size + /// itself before handing the scale to DLSS, which then gets FidelityFX's + /// scale back. + pub fn mvec_scale(&self, multiplier: [f32; 2]) -> [f32; 2] { + let size = self.motion_size(); + [0, 1].map(|i| self.motion_scale[i] * multiplier[i] / size[i].max(1) as f32) + } + + /// The common constants of a frame. The title names no camera matrices: + /// the projection is made of the field of view, the aspect and the depth + /// range it gives; camera motion is in the motion vectors, so the + /// clip-to-previous-clip matrices stay the identity and the camera stands + /// at the origin looking down +z. + pub fn constants(&self, jitter_multiplier: [f32; 2], mvec_multiplier: [f32; 2]) -> abi::Constants { + let aspect = self.render[0].max(1) as f32 / self.render[1].max(1) as f32; + let view_to_clip = projection(self.near, self.far, self.fov_y, aspect, self.depth_inverted()); + let clip_to_view = invert(&view_to_clip).unwrap_or(IDENTITY); + abi::Constants { + base: abi::BaseStructure::new(abi::CONSTANTS, 2), + camera_view_to_clip: view_to_clip, + clip_to_camera_view: clip_to_view, + clip_to_lens_clip: IDENTITY, + clip_to_prev_clip: IDENTITY, + prev_clip_to_clip: IDENTITY, + jitter_offset: [self.jitter[0] * jitter_multiplier[0], self.jitter[1] * jitter_multiplier[1]], + mvec_scale: self.mvec_scale(mvec_multiplier), + camera_pinhole_offset: [0.0, 0.0], + camera_pos: [0.0, 0.0, 0.0], + camera_up: [0.0, 1.0, 0.0], + camera_right: [1.0, 0.0, 0.0], + camera_fwd: [0.0, 0.0, 1.0], + camera_near: self.near, + camera_far: self.far, + camera_fov: self.fov_y, + camera_aspect_ratio: aspect, + motion_vectors_invalid_value: 0.0, + depth_inverted: abi::boolean(self.depth_inverted()), + camera_motion_included: abi::TRUE, + motion_vectors_3d: abi::FALSE, + reset: abi::boolean(self.reset), + orthographic_projection: abi::FALSE, + motion_vectors_dilated: abi::FALSE, + motion_vectors_jittered: abi::boolean(self.flags & FFX_MOTION_VECTORS_JITTER_CANCELLATION != 0), + min_relative_linear_depth_object_separation: 40.0, + } + } +} + +pub const IDENTITY: abi::Float4x4 = [[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]]; + +/// A left-handed perspective projection in Streamline's layout (row vectors, +/// rows as stored): depth 0 at `near` and 1 at `far`, or reversed; a far +/// plane past 1e30 (or not finite) is at infinity. Degenerate inputs give +/// the identity. +pub fn projection(near: f32, far: f32, fov_y: f32, aspect: f32, inverted: bool) -> abi::Float4x4 { + if !(near > 0.0 && fov_y > 0.0 && fov_y < std::f32::consts::PI && aspect > 0.0) || near.is_nan() { + return IDENTITY; + } + let y = 1.0 / (fov_y * 0.5).tan(); + let x = y / aspect; + let infinite = !far.is_finite() || far > 1e30 || far <= near; + let (a, b) = match (infinite, inverted) { + (false, false) => (far / (far - near), -near * far / (far - near)), + (false, true) => (near / (near - far), far * near / (far - near)), + (true, false) => (1.0, -near), + (true, true) => (0.0, near), + }; + [[x, 0.0, 0.0, 0.0], [0.0, y, 0.0, 0.0], [0.0, 0.0, a, 1.0], [0.0, 0.0, b, 0.0]] +} + +/// A 4x4 inverse by cofactors; `None` if singular. +pub fn invert(m: &abi::Float4x4) -> Option { + let a: [f64; 16] = std::array::from_fn(|i| f64::from(m[i / 4][i % 4])); + let mut inv = [0f64; 16]; + inv[0] = a[5] * a[10] * a[15] - a[5] * a[11] * a[14] - a[9] * a[6] * a[15] + a[9] * a[7] * a[14] + a[13] * a[6] * a[11] + - a[13] * a[7] * a[10]; + inv[4] = -a[4] * a[10] * a[15] + a[4] * a[11] * a[14] + a[8] * a[6] * a[15] - a[8] * a[7] * a[14] - a[12] * a[6] * a[11] + + a[12] * a[7] * a[10]; + inv[8] = a[4] * a[9] * a[15] - a[4] * a[11] * a[13] - a[8] * a[5] * a[15] + a[8] * a[7] * a[13] + a[12] * a[5] * a[11] + - a[12] * a[7] * a[9]; + inv[12] = -a[4] * a[9] * a[14] + a[4] * a[10] * a[13] + a[8] * a[5] * a[14] - a[8] * a[6] * a[13] - a[12] * a[5] * a[10] + + a[12] * a[6] * a[9]; + inv[1] = -a[1] * a[10] * a[15] + a[1] * a[11] * a[14] + a[9] * a[2] * a[15] - a[9] * a[3] * a[14] - a[13] * a[2] * a[11] + + a[13] * a[3] * a[10]; + inv[5] = a[0] * a[10] * a[15] - a[0] * a[11] * a[14] - a[8] * a[2] * a[15] + a[8] * a[3] * a[14] + a[12] * a[2] * a[11] + - a[12] * a[3] * a[10]; + inv[9] = -a[0] * a[9] * a[15] + a[0] * a[11] * a[13] + a[8] * a[1] * a[15] - a[8] * a[3] * a[13] - a[12] * a[1] * a[11] + + a[12] * a[3] * a[9]; + inv[13] = a[0] * a[9] * a[14] - a[0] * a[10] * a[13] - a[8] * a[1] * a[14] + a[8] * a[2] * a[13] + a[12] * a[1] * a[10] + - a[12] * a[2] * a[9]; + inv[2] = a[1] * a[6] * a[15] - a[1] * a[7] * a[14] - a[5] * a[2] * a[15] + a[5] * a[3] * a[14] + a[13] * a[2] * a[7] + - a[13] * a[3] * a[6]; + inv[6] = -a[0] * a[6] * a[15] + a[0] * a[7] * a[14] + a[4] * a[2] * a[15] - a[4] * a[3] * a[14] - a[12] * a[2] * a[7] + + a[12] * a[3] * a[6]; + inv[10] = a[0] * a[5] * a[15] - a[0] * a[7] * a[13] - a[4] * a[1] * a[15] + a[4] * a[3] * a[13] + a[12] * a[1] * a[7] + - a[12] * a[3] * a[5]; + inv[14] = -a[0] * a[5] * a[14] + a[0] * a[6] * a[13] + a[4] * a[1] * a[14] - a[4] * a[2] * a[13] - a[12] * a[1] * a[6] + + a[12] * a[2] * a[5]; + inv[3] = -a[1] * a[6] * a[11] + a[1] * a[7] * a[10] + a[5] * a[2] * a[11] - a[5] * a[3] * a[10] - a[9] * a[2] * a[7] + + a[9] * a[3] * a[6]; + inv[7] = a[0] * a[6] * a[11] - a[0] * a[7] * a[10] - a[4] * a[2] * a[11] + a[4] * a[3] * a[10] + a[8] * a[2] * a[7] + - a[8] * a[3] * a[6]; + inv[11] = -a[0] * a[5] * a[11] + a[0] * a[7] * a[9] + a[4] * a[1] * a[11] - a[4] * a[3] * a[9] - a[8] * a[1] * a[7] + + a[8] * a[3] * a[5]; + inv[15] = a[0] * a[5] * a[10] - a[0] * a[6] * a[9] - a[4] * a[1] * a[10] + a[4] * a[2] * a[9] + a[8] * a[1] * a[6] + - a[8] * a[2] * a[5]; + let det = a[0] * inv[0] + a[1] * inv[4] + a[2] * inv[8] + a[3] * inv[12]; + if det.abs() < 1e-30 || !det.is_finite() { + return None; + } + Some(std::array::from_fn(|r| std::array::from_fn(|c| (inv[r * 4 + c] / det) as f32))) +} + +/// `"x,y"` as two multipliers (`VICTORY_DLSS_JITTER`, `VICTORY_DLSS_MV`): +/// what a run may have to flip; unset or malformed is `[1, 1]`. +pub fn pair(value: Option<&str>) -> [f32; 2] { + let Some(value) = value else { return [1.0, 1.0] }; + let mut parts = value.split(',').map(|p| p.trim().parse::()); + match (parts.next(), parts.next(), parts.next()) { + (Some(Ok(x)), Some(Ok(y)), None) if x.is_finite() && y.is_finite() => [x, y], + _ => [1.0, 1.0], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// DLSS's optimal render sizes for a 2560x1440 output, as the 310 SDK + /// reports them (ultra quality has none). + fn optimal_1440p(mode: u32) -> Option<[u32; 2]> { + Some(match mode { + abi::DLSS_DLAA => [2560, 1440], + abi::DLSS_MAX_QUALITY => [1707, 960], + abi::DLSS_BALANCED => [1485, 835], + abi::DLSS_MAX_PERFORMANCE => [1280, 720], + abi::DLSS_ULTRA_PERFORMANCE => [853, 480], + _ => return None, + }) + } + + #[test] + fn the_title_render_sizes_pick_their_mode() { + let out = [2560, 1440]; + for (mode, sl) in [ + (Mode::Dlaa, abi::DLSS_DLAA), + (Mode::Quality, abi::DLSS_MAX_QUALITY), + (Mode::Balanced, abi::DLSS_BALANCED), + (Mode::Performance, abi::DLSS_MAX_PERFORMANCE), + (Mode::UltraPerformance, abi::DLSS_ULTRA_PERFORMANCE), + ] { + let render = mode.render_size(out); + assert_eq!(pick_mode(render, out, optimal_1440p), Some(sl), "{mode:?} {render:?}"); + assert_eq!(mode.sl_mode(), sl); + assert_eq!(Mode::from_name(mode.name()), Some(mode)); + } + assert_eq!(Mode::Quality.render_size(out), [1706, 960]); + assert_eq!(Mode::Balanced.render_size(out), [1484, 835]); + // Series S: a 1280x720 scene for a 1920x1080 output is quality. + let s = |mode: u32| optimal_1440p(mode).map(|[w, h]| [w * 3 / 4, h * 3 / 4]); + assert_eq!(pick_mode([1280, 720], [1920, 1080], s), Some(abi::DLSS_MAX_QUALITY)); + // A size between modes takes the next larger one. + assert_eq!(pick_mode([1600, 900], out, optimal_1440p), Some(abi::DLSS_MAX_QUALITY)); + // Nothing for a render larger than the output, or empty. + assert_eq!(pick_mode([2561, 1440], out, optimal_1440p), None); + assert_eq!(pick_mode([0, 1440], out, optimal_1440p), None); + assert_eq!(pick_mode([1280, 720], out, |_| None), None); + } + + #[test] + fn names_and_presets() { + assert_eq!(Mode::from_name(" Quality "), Some(Mode::Quality)); + assert_eq!(Mode::from_name("ultra-performance"), Some(Mode::UltraPerformance)); + assert_eq!(Mode::from_name("fast"), None); + assert_eq!(Mode::Balanced.ffx_mode(), 2); + assert_eq!(preset("K"), Some(11)); + assert_eq!(preset("default"), Some(0)); + assert_eq!(preset("a"), None); + assert_eq!(sl_mode_name(abi::DLSS_DLAA), "DLAA"); + } + + #[test] + fn states_read_as_the_pc_backend_reads_them() { + assert_eq!(host_state(0xc), Some(0xc0)); + assert_eq!(host_state(0x2), Some(0x8)); + assert_eq!(host_state(0x200), Some(0x10)); + assert_eq!(host_state(0x14), None); + // Inputs a texture cannot be read in are read as shader resources. + assert_eq!(input_state(0x14), 0xc0); + assert_eq!(input_state(0x10), 0xc0); + assert_eq!(input_state(0x4), 0x40); + assert_eq!(input_state(0x200), 0x10); + assert_eq!(output_state(0x2), 0x8); + assert_eq!(output_state(0x100), 0x8); + } + + fn camera(flags: u32) -> Camera { + Camera { + jitter: [0.25, -0.5], + motion_scale: [1706.0, 960.0], + render: [1706, 960], + output: [2560, 1440], + near: 0.1, + far: 10_000.0, + fov_y: 1.0, + reset: true, + flags, + } + } + + #[test] + fn constants_follow_the_upscaling() { + let c = camera(FFX_HIGH_DYNAMIC_RANGE | FFX_DEPTH_INVERTED | FFX_AUTO_EXPOSURE).constants([1.0, 1.0], [1.0, 1.0]); + // Motion vectors in UV space scaled to pixels: Streamline gets them + // back to [-1, 1]. + assert_eq!(c.mvec_scale, [1.0, 1.0]); + assert_eq!(c.jitter_offset, [0.25, -0.5]); + assert_eq!((c.depth_inverted, c.reset, c.camera_motion_included), (abi::TRUE, abi::TRUE, abi::TRUE)); + assert_eq!(c.motion_vectors_jittered, abi::FALSE); + assert!((c.camera_aspect_ratio - 1706.0 / 960.0).abs() < 1e-6); + let flipped = camera(0).constants([-1.0, 1.0], [1.0, -2.0]); + assert_eq!(flipped.jitter_offset, [-0.25, -0.5]); + assert_eq!(flipped.mvec_scale, [1.0, -2.0]); + assert_eq!(flipped.depth_inverted, abi::FALSE); + // Display-resolution motion vectors are scaled by the output size. + let display = camera(FFX_DISPLAY_RESOLUTION_MOTION_VECTORS); + assert_eq!(display.motion_size(), [2560, 1440]); + assert_eq!(display.mvec_scale([1.0, 1.0]), [1706.0 / 2560.0, 960.0 / 1440.0]); + } + + /// Points at the near and far planes land at the depth the convention + /// says; the inverse maps clip space back. + #[test] + fn projections_place_near_and_far() { + let depth = |m: &abi::Float4x4, z: f32| { + let (zc, wc) = (z * m[2][2] + m[3][2], z * m[2][3] + m[3][3]); + zc / wc + }; + let standard = projection(0.5, 100.0, 1.2, 16.0 / 9.0, false); + assert!((depth(&standard, 0.5) - 0.0).abs() < 1e-5); + assert!((depth(&standard, 100.0) - 1.0).abs() < 1e-5); + let reversed = projection(0.5, 100.0, 1.2, 16.0 / 9.0, true); + assert!((depth(&reversed, 0.5) - 1.0).abs() < 1e-5); + assert!((depth(&reversed, 100.0) - 0.0).abs() < 1e-5); + let infinite = projection(0.5, f32::MAX, 1.2, 1.0, true); + assert!((depth(&infinite, 0.5) - 1.0).abs() < 1e-5); + assert!(depth(&infinite, 1e7) < 1e-6); + assert_eq!(projection(0.0, 100.0, 1.2, 1.0, false), IDENTITY); + let inverse = invert(&standard).unwrap(); + let product: abi::Float4x4 = + std::array::from_fn(|r| std::array::from_fn(|c| (0..4).map(|k| standard[r][k] * inverse[k][c]).sum())); + for r in 0..4 { + for c in 0..4 { + let want = if r == c { 1.0 } else { 0.0 }; + assert!((product[r][c] - want).abs() < 1e-4, "{r} {c} {}", product[r][c]); + } + } + assert_eq!(invert(&[[0.0; 4]; 4]), None); + } + + #[test] + fn multiplier_pairs() { + assert_eq!(pair(None), [1.0, 1.0]); + assert_eq!(pair(Some("-1, 1")), [-1.0, 1.0]); + assert_eq!(pair(Some("1")), [1.0, 1.0]); + assert_eq!(pair(Some("1,2,3")), [1.0, 1.0]); + assert_eq!(pair(Some("x,1")), [1.0, 1.0]); + } +}