Merge agent/dlss: DLSS Super Resolution through the title's FidelityFX dispatch (VICTORY_DLSS), DLSS Frame Generation (VICTORY_FRAMEGEN), both off by default; Streamline loaded at run time from outside the repo
Co-Authored-By: Claude Opus 5.5 <[email protected]> # Conflicts: # crates/victory-gpu/src/host.rs
This commit is contained in:
commit
89dca0a59c
16 files changed
+3589
-12
No files matched your search
@@ -153,6 +153,24 @@ enum Command {
|
||||
Replay(replay::Replay),
|
||||
/// Show the resolved configuration and check it.
|
||||
Config,
|
||||
/// Check NVIDIA Streamline, DLSS and DLSS Frame Generation on this PC
|
||||
/// without the title (`VICTORY_STREAMLINE_DIR`, `VICTORY_DLSS_MODE`,
|
||||
/// `VICTORY_DLSS_PRESET`): what loads and what this GPU supports; with
|
||||
/// --device, the host device handed over and DLSS run three times on
|
||||
/// stand-in textures; with --present too, three seconds of presents with
|
||||
/// frame generation in a window of ours.
|
||||
#[cfg(windows)]
|
||||
UpscalerCheck {
|
||||
/// The output size, `<width>x<height>`.
|
||||
#[arg(long, default_value = "2560x1440")]
|
||||
output: String,
|
||||
/// Make the host device and run DLSS on it.
|
||||
#[arg(long)]
|
||||
device: bool,
|
||||
/// Present for three seconds with frame generation (with --device).
|
||||
#[arg(long)]
|
||||
present: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
@@ -230,6 +248,17 @@ fn main() -> Result<()> {
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
Command::Replay(options) => replay::run(options),
|
||||
Command::Config => show_config(),
|
||||
#[cfg(windows)]
|
||||
Command::UpscalerCheck { output, device, present } => {
|
||||
let size = output
|
||||
.split_once(['x', 'X'])
|
||||
.and_then(|(w, h)| Some([w.trim().parse().ok()?, h.trim().parse().ok()?]))
|
||||
.ok_or_else(|| anyhow::anyhow!("--output {output}: not <width>x<height>"))?;
|
||||
for line in victory_hle::streamline::check(size, device || present, present) {
|
||||
println!("{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc};
|
||||
use victory_hle::streamline::Mode;
|
||||
use victory_loader::PreparedImage;
|
||||
|
||||
const RETAIL_BUILD: &str = "b99f876b74d4a77f03af5f878223b27bd647b5c35a79d5decd9f716504239e93";
|
||||
@@ -74,6 +75,69 @@ pub(super) fn prepare(image: &mut PreparedImage, render_1080p: bool) -> Result<(
|
||||
Ok((render_width, render_height))
|
||||
}
|
||||
|
||||
/// The title's renderer selection: `mov eax, 6; cmovne eax, ecx` (the
|
||||
/// title's own temporal pass, or on Series S with the upscaler there the
|
||||
/// FidelityFX path, 7).
|
||||
const RENDERER_SELECTION: u32 = 0x007e_9421;
|
||||
const STOCK_RENDERER_SELECTION: [u8; 8] = [0xb8, 6, 0, 0, 0, 0x0f, 0x45, 0xc1];
|
||||
/// The FidelityFX path's render size: the console check's result (Series S)
|
||||
/// is noted as the FidelityFX quality mode and picks the scaled branch
|
||||
/// (`movzx eax, al; mov [r14+0x90], eax; test al, al; jne`), whose scale
|
||||
/// multiplies the output size.
|
||||
const UPSCALER_SIZING: u32 = 0x028e_f69a;
|
||||
const STOCK_UPSCALER_SIZING: [u8; 14] = [0x0f, 0xb6, 0xc0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0x84, 0xc0, 0x75, 0x0a];
|
||||
/// The native branch's load of 1.0, and the scaled branch's of the scale.
|
||||
const NATIVE_LOAD: u32 = 0x028e_f6a8;
|
||||
const STOCK_NATIVE_LOAD: [u8; 10] = [0xc5, 0xfa, 0x10, 0x05, 0x28, 0x78, 0x6d, 0x03, 0xeb, 0x08];
|
||||
const SCALED_LOAD: u32 = 0x028e_f6b2;
|
||||
const STOCK_SCALED_LOAD: [u8; 8] = [0xc5, 0xfa, 0x10, 0x05, 0xa2, 0xe2, 0x86, 0x03];
|
||||
/// The scale the scaled branch loads (shared with other code: not written).
|
||||
const UPSCALER_SCALE: u32 = 0x0615_d95c;
|
||||
|
||||
/// Makes the title render through its FidelityFX upscaler path (renderer 7,
|
||||
/// as Series S does) with the scene at `mode`'s scale of the output, so that
|
||||
/// DLSS can take its upscale dispatches over (`victory_hle::modules::fidelityfx`).
|
||||
/// On Series X the stock title uses its own temporal pass instead and never
|
||||
/// loads its upscaler. The FidelityFX quality mode the title notes is
|
||||
/// `mode`'s; the temporal scene scale (the title's own pass, and
|
||||
/// `prepare`'s 1440p patch) is set to the same scale, as the stock Series X
|
||||
/// image pairs them (2/3 each). Every patched instruction is checked against
|
||||
/// the stock bytes first; nothing is written if one differs.
|
||||
///
|
||||
/// From DexNom's fork (DexNom/VIctory, `apps/victory/src/native_1440p.rs`,
|
||||
/// `prepare_fsr_4k`, GPL-3.0-or-later), there for a 4K output; kept here
|
||||
/// with the 1440p one.
|
||||
pub(super) fn prepare_upscaler(image: &mut PreparedImage, mode: Mode) -> Result<()> {
|
||||
ensure!(
|
||||
image.original_hash.to_hex().as_str() == RETAIL_BUILD,
|
||||
"the upscaler path is only known for the retail build {RETAIL_BUILD}"
|
||||
);
|
||||
ensure!(*field::<8>(image, RENDERER_SELECTION)? == STOCK_RENDERER_SELECTION, "unexpected renderer selection");
|
||||
ensure!(*field::<14>(image, UPSCALER_SIZING)? == STOCK_UPSCALER_SIZING, "unexpected upscaler render size selection");
|
||||
ensure!(*field::<10>(image, NATIVE_LOAD)? == STOCK_NATIVE_LOAD, "unexpected upscaler native scale load");
|
||||
ensure!(*field::<8>(image, SCALED_LOAD)? == STOCK_SCALED_LOAD, "unexpected upscaler scaled load");
|
||||
ensure!(*field::<4>(image, UPSCALER_SCALE)? == (2.0f32 / 3.0).to_le_bytes(), "unexpected upscaler scale");
|
||||
let temporal = f32::from_le_bytes(*field::<4>(image, TEMPORAL_SCALE)?);
|
||||
ensure!(
|
||||
temporal == 2.0 / 3.0 || temporal == 1.0,
|
||||
"unexpected temporal scene scale {temporal} (stock 2/3, or 1 with the 1440p output)"
|
||||
);
|
||||
// Renderer 7 every time it is asked (the console check has run).
|
||||
*field::<8>(image, RENDERER_SELECTION)? = [0xb8, 7, 0, 0, 0, 0x90, 0x90, 0x90];
|
||||
// `mov eax, mode; mov [r14+0x90], eax; jmp scaled`.
|
||||
*field::<14>(image, UPSCALER_SIZING)? = [0xb8, mode.ffx_mode(), 0, 0, 0, 0x41, 0x89, 0x86, 0x90, 0, 0, 0, 0xeb, 0x0a];
|
||||
if mode != Mode::Quality {
|
||||
// The jump leaves the native branch unreached: its load's operand
|
||||
// becomes a literal of ours, which the scaled branch loads.
|
||||
let literal = NATIVE_LOAD + 4;
|
||||
*field::<4>(image, literal)? = mode.scale().to_le_bytes();
|
||||
let displacement = literal as i32 - (SCALED_LOAD as i32 + 8);
|
||||
*field::<4>(image, SCALED_LOAD + 4)? = displacement.to_le_bytes();
|
||||
}
|
||||
*field::<4>(image, TEMPORAL_SCALE)? = mode.scale().to_le_bytes();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn field<const N: usize>(image: &mut PreparedImage, rva: u32) -> Result<&mut [u8; N]> {
|
||||
let offset = image.info.rva_to_file_offset(rva).context("display profile field missing")? as usize;
|
||||
image
|
||||
@@ -112,4 +176,39 @@ mod tests {
|
||||
assert!(prepare(&mut image, render_1080p).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// With the retail executable (as above): the upscaler path at each
|
||||
/// scale, alone (4K output) and after the 1440p patch; the scaled
|
||||
/// branch then loads the mode's scale and the noted mode is its
|
||||
/// FidelityFX mode.
|
||||
#[test]
|
||||
fn patches_the_upscaler_path() {
|
||||
let Some(path) = std::env::var_os("VICTORY_DISPLAY_PROFILE_TEST_IMAGE") else {
|
||||
return;
|
||||
};
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
for native in [false, true] {
|
||||
for mode in [Mode::Dlaa, Mode::Quality, Mode::Balanced, Mode::Performance, Mode::UltraPerformance] {
|
||||
let mut image = victory_loader::prepare(&bytes).unwrap();
|
||||
if native {
|
||||
prepare(&mut image, false).unwrap();
|
||||
}
|
||||
prepare_upscaler(&mut image, mode).unwrap();
|
||||
assert_eq!(*field::<8>(&mut image, RENDERER_SELECTION).unwrap(), [0xb8, 7, 0, 0, 0, 0x90, 0x90, 0x90]);
|
||||
let sizing = *field::<14>(&mut image, UPSCALER_SIZING).unwrap();
|
||||
assert_eq!(sizing[1], mode.ffx_mode());
|
||||
assert_eq!(sizing[12..], [0xeb, 0x0a]);
|
||||
// The jump lands on the scaled load.
|
||||
assert_eq!(UPSCALER_SIZING + 14 + 0x0a, SCALED_LOAD);
|
||||
let disp = i32::from_le_bytes(*field::<4>(&mut image, SCALED_LOAD + 4).unwrap());
|
||||
let loaded = (SCALED_LOAD + 8).wrapping_add_signed(disp);
|
||||
assert_eq!(f32::from_le_bytes(*field::<4>(&mut image, loaded).unwrap()), mode.scale());
|
||||
assert_eq!(f32::from_le_bytes(*field::<4>(&mut image, TEMPORAL_SCALE).unwrap()), mode.scale());
|
||||
// The shared constant stays as it was.
|
||||
assert_eq!(*field::<4>(&mut image, UPSCALER_SCALE).unwrap(), (2.0f32 / 3.0).to_le_bytes());
|
||||
// Patched once, refused.
|
||||
assert!(prepare_upscaler(&mut image, mode).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-4
@@ -56,6 +56,28 @@ pub fn run(
|
||||
// A title that relaunched itself: the old process must be gone first.
|
||||
victory_hle::modules::lifecycle::wait_for_previous();
|
||||
let cfg = victory_core::Config::load()?;
|
||||
// DLSS and frame generation (`VICTORY_DLSS`, `VICTORY_FRAMEGEN`): Streamline
|
||||
// is loaded before anything of the title or the host GPU, and fails soft;
|
||||
// only if it offers one of them does the title render through its
|
||||
// FidelityFX path, which DLSS takes over (`native_1440p::prepare_upscaler`).
|
||||
let asked = victory_hle::streamline::Asked::from_env().map_err(anyhow::Error::msg)?;
|
||||
let available = victory_hle::streamline::init(&asked);
|
||||
// `VICTORY_FSR_PATH=1`: the title's FidelityFX path at VICTORY_DLSS_MODE's
|
||||
// scale with its own FidelityFX upscaling (no Streamline): DLSS's
|
||||
// comparison, and on Series X what that path alone looks like.
|
||||
let fsr_path = std::env::var_os("VICTORY_FSR_PATH").is_some_and(|v| v == "1");
|
||||
let upscaler = (available.dlss || available.framegen || fsr_path).then_some(asked.mode);
|
||||
if fsr_path && !asked.any() {
|
||||
println!("upscaling the title's own FidelityFX at the {} scale (VICTORY_FSR_PATH=1)", asked.mode.name());
|
||||
}
|
||||
if asked.any() {
|
||||
println!(
|
||||
"upscaling DLSS {}, frame generation {}{}",
|
||||
if available.dlss { "on" } else if asked.dlss { "asked, not available" } else { "off" },
|
||||
if available.framegen { "on" } else if asked.framegen { "asked, not available" } else { "off" },
|
||||
upscaler.map(|m| format!(", scene at the {} scale ({})", m.name(), m.scale())).unwrap_or_default()
|
||||
);
|
||||
}
|
||||
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
|
||||
let mut prepared = victory_loader::prepare(&original)?;
|
||||
let hash = prepared.original_hash.to_hex();
|
||||
@@ -70,15 +92,46 @@ pub fn run(
|
||||
let native_1440p = render_1080p || std::env::var("VICTORY_NATIVE_1440P").as_deref() == Ok("1");
|
||||
let images = if native_1440p {
|
||||
anyhow::ensure!(matches!(console, Console::SeriesX), "1440p output needs the Series X profile");
|
||||
let (w, h) = native_1440p::prepare(&mut prepared, render_1080p)?;
|
||||
if upscaler.is_some() && render_1080p {
|
||||
println!("display VICTORY_RENDER_1080P is left out: VICTORY_DLSS_MODE sets the scene's size");
|
||||
}
|
||||
let (w, h) = native_1440p::prepare(&mut prepared, render_1080p && upscaler.is_none())?;
|
||||
// SAFETY: nothing else runs yet; the title and the display mode list
|
||||
// read these later.
|
||||
unsafe {
|
||||
std::env::set_var("VICTORY_DISPLAY_MODE", format!("{}x{}", native_1440p::WIDTH, native_1440p::HEIGHT));
|
||||
std::env::set_var("VICTORY_NATIVE_1440P", "1");
|
||||
}
|
||||
println!("display {}x{} SDR, scene {w}x{h}", native_1440p::WIDTH, native_1440p::HEIGHT);
|
||||
cfg.cache_subdir(if render_1080p { "images/1080p-to-1440p-sdr" } else { "images/native-1440p-sdr" })?
|
||||
match upscaler.map(|mode| (mode, native_1440p::prepare_upscaler(&mut prepared, mode))) {
|
||||
Some((mode, Ok(()))) => {
|
||||
let [rw, rh] = mode.render_size([native_1440p::WIDTH, native_1440p::HEIGHT]);
|
||||
println!(
|
||||
"display {}x{} SDR, scene {rw}x{rh} through the title's FidelityFX path ({})",
|
||||
native_1440p::WIDTH,
|
||||
native_1440p::HEIGHT,
|
||||
mode.name()
|
||||
);
|
||||
cfg.cache_subdir(&format!("images/native-1440p-upscaler-{}-sdr", mode.name()))?
|
||||
}
|
||||
other => {
|
||||
if let Some((_, Err(e))) = other {
|
||||
println!("upscaling the title's FidelityFX path was not patched in: {e:#}");
|
||||
}
|
||||
println!("display {}x{} SDR, scene {w}x{h}", native_1440p::WIDTH, native_1440p::HEIGHT);
|
||||
cfg.cache_subdir(if render_1080p { "images/1080p-to-1440p-sdr" } else { "images/native-1440p-sdr" })?
|
||||
}
|
||||
}
|
||||
} else if let Some(mode) = upscaler {
|
||||
match native_1440p::prepare_upscaler(&mut prepared, mode) {
|
||||
Ok(()) => {
|
||||
println!("display the title's output, scene at {} of it through its FidelityFX path ({})", mode.scale(), mode.name());
|
||||
cfg.cache_subdir(&format!("images/upscaler-{}", mode.name()))?
|
||||
}
|
||||
Err(e) => {
|
||||
println!("upscaling the title's FidelityFX path was not patched in: {e:#}");
|
||||
cfg.cache_subdir("images")?
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cfg.cache_subdir("images")?
|
||||
};
|
||||
@@ -182,7 +235,10 @@ pub fn run(
|
||||
show(name, dll.bind_imports(&with_dlls, policy)?);
|
||||
}
|
||||
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
|
||||
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
|
||||
// The title's FidelityFX calls go through ours when DLSS or frame
|
||||
// generation is on (bound as before otherwise).
|
||||
let interposed = victory_hle::modules::fidelityfx::Interpose { inner: &with_dlls };
|
||||
show(&exe_name, image.bind_imports(&interposed, policy)?);
|
||||
if execute {
|
||||
let size = image.info().size_of_image as usize;
|
||||
// SAFETY: the image stays mapped, and nothing of it has run yet.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -954,10 +954,16 @@ fn create() -> windows::core::Result<Host> {
|
||||
let messages = debug
|
||||
.then(|| device.cast::<ID3D12InfoQueue>().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 =
|
||||
@@ -1217,6 +1223,9 @@ pub(crate) struct HostList {
|
||||
indirect_run: Mutex<Option<(crate::indirect::merge::Run, Option<crate::indirect::merge::Held>)>>,
|
||||
/// Whether an execution is held back.
|
||||
holding: std::sync::atomic::AtomicBool,
|
||||
/// 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
|
||||
@@ -4161,6 +4170,7 @@ impl Host {
|
||||
title_calls: std::sync::atomic::AtomicU64::new(0),
|
||||
indirect_run: Mutex::default(),
|
||||
holding: std::sync::atomic::AtomicBool::new(false),
|
||||
upscale: std::sync::atomic::AtomicU64::new(0),
|
||||
_alive: Counted::new(),
|
||||
#[cfg(feature = "diagnostics")]
|
||||
notes,
|
||||
@@ -5534,6 +5544,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")]
|
||||
@@ -6388,6 +6406,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();
|
||||
@@ -7367,6 +7386,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) {
|
||||
@@ -8859,6 +8888,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);
|
||||
two_queues::line(frames);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -9201,6 +9231,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
|
||||
@@ -9420,7 +9451,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());
|
||||
@@ -9460,9 +9501,24 @@ impl Host {
|
||||
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
|
||||
..Default::default()
|
||||
};
|
||||
let swap_chain = factory
|
||||
.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
|
||||
.cast::<IDXGISwapChain3>()?;
|
||||
// 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::<IDXGISwapChain3>())
|
||||
});
|
||||
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::<IDXGISwapChain3>()?
|
||||
}
|
||||
None => factory.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?.cast::<IDXGISwapChain3>()?,
|
||||
};
|
||||
let copy = self.new_list()?;
|
||||
copy.close();
|
||||
tracing::info!(width, height, format = format.0, "presenting to a window");
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -180,6 +180,42 @@ fn with_state_on(
|
||||
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<dyn FnOnce(&crate::host::HostList) -> 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.
|
||||
|
||||
@@ -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::<u32>(&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<AtomicUsize>);
|
||||
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]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<LogCallback>,
|
||||
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<ApiErrorCallback>,
|
||||
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::<BaseStructure>(), 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::<Constants>(), 456);
|
||||
assert_eq!(size_of::<ViewportHandle>(), 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::<DlssOptions>(), 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::<DlssgOptions>(), 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::<ReflexOptions>(), 48);
|
||||
assert_eq!(size_of::<Resource>(), 112);
|
||||
assert_eq!(size_of::<ResourceTag>(), 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");
|
||||
}
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<u32> {
|
||||
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<abi::Float4x4> {
|
||||
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::<f32>());
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,9 @@ pub mod runtime;
|
||||
pub use host::HostPolicy;
|
||||
pub use registry::{HleExport, HleModule, registry};
|
||||
pub use victory_gpu::console;
|
||||
/// DLSS and frame generation (`VICTORY_DLSS`, `VICTORY_FRAMEGEN`).
|
||||
#[cfg(windows)]
|
||||
pub use victory_gpu::streamline;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub use victory_gpu::replay;
|
||||
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
//! `amd_fidelityfx_loader_xbox.dll`: the title's FidelityFX API, five
|
||||
//! functions over chains of descriptions, each starting with a type id and
|
||||
//! the next one's address. With DLSS or frame generation on
|
||||
//! (`victory_gpu::streamline`, `VICTORY_DLSS=1`, `VICTORY_FRAMEGEN=1`), the
|
||||
//! title's imports of it are bound to the functions here ([`Interpose`]),
|
||||
//! which call the title's own DLL for everything except an upscale dispatch
|
||||
//! DLSS takes: DLSS then records the upscaling at that place of the title's
|
||||
//! command list instead, from the same textures into the same output. With
|
||||
//! frame generation alone the title's own upscaling runs and its depth and
|
||||
//! motion vectors are noted for the present. Without either switch, or
|
||||
//! without Streamline, the imports are bound as before.
|
||||
//!
|
||||
//! The title's upscaler context stays the title's own (its FidelityFX makes
|
||||
//! it), so the title's upscaling runs again on any frame DLSS does not take.
|
||||
//!
|
||||
//! The description layouts are the FidelityFX SDK's API (MIT) as DexNom's fork
|
||||
//! reads them (DexNom/VIctory, `crates/victory-hle/src/modules/fidelityfx.rs`,
|
||||
//! GPL-3.0-or-later), from which they are ported.
|
||||
#![allow(non_snake_case)]
|
||||
// Title code calls these through its import table.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
use victory_gpu::object::Object;
|
||||
use victory_gpu::streamline::{self, Taken, Upscale, plan::Camera};
|
||||
use victory_loader::{ImportResolver, Provenance, Resolution};
|
||||
use victory_pe::ImportSymbol;
|
||||
|
||||
/// The DLL the title imports the API from (it loads the upscaler itself).
|
||||
pub const LOADER_DLL: &str = "amd_fidelityfx_loader_xbox.dll";
|
||||
|
||||
// Return codes.
|
||||
const OK: u32 = 0;
|
||||
const PARAMETER: u32 = 6;
|
||||
|
||||
// Description types.
|
||||
const CREATE_UPSCALE: u64 = 0x1_0000;
|
||||
const DISPATCH_UPSCALE: u64 = 0x1_0001;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Header {
|
||||
kind: u64,
|
||||
next: *mut Header,
|
||||
}
|
||||
|
||||
/// An upscaler context: flags, largest render and output sizes, a message
|
||||
/// callback.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct CreateUpscale {
|
||||
header: Header,
|
||||
flags: u32,
|
||||
max_render: [u32; 2],
|
||||
max_output: [u32; 2],
|
||||
message: usize,
|
||||
}
|
||||
|
||||
/// A resource, its description (type, format, sizes, mips, flags, usage)
|
||||
/// and the state it is in.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Resource {
|
||||
resource: *mut c_void,
|
||||
description: [u32; 8],
|
||||
state: u32,
|
||||
}
|
||||
|
||||
/// One upscaling: the command list, then colour, depth, motion vectors,
|
||||
/// exposure, reactive mask, transparency mask and output; jitter,
|
||||
/// motion-vector scale, sizes, sharpening, frame time (ms), pre-exposure,
|
||||
/// reset, camera and flags. (The C `bool`s are read as bytes.)
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct DispatchUpscale {
|
||||
header: Header,
|
||||
list: *mut c_void,
|
||||
resources: [Resource; 7],
|
||||
jitter: [f32; 2],
|
||||
motion_scale: [f32; 2],
|
||||
render_size: [u32; 2],
|
||||
upscale_size: [u32; 2],
|
||||
enable_sharpening: u8,
|
||||
sharpness: f32,
|
||||
frame_time_delta: f32,
|
||||
pre_exposure: f32,
|
||||
reset: u8,
|
||||
camera_near: f32,
|
||||
camera_far: f32,
|
||||
camera_fov_angle_vertical: f32,
|
||||
view_space_to_meters_factor: f32,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<CreateUpscale>() == 0x30);
|
||||
const _: () = assert!(size_of::<Resource>() == 0x30);
|
||||
const _: () = assert!(size_of::<DispatchUpscale>() == 0x1b0);
|
||||
|
||||
type Create = unsafe extern "C" fn(*mut *mut c_void, *mut Header, *const c_void) -> u32;
|
||||
type Destroy = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> u32;
|
||||
/// Configure, query and dispatch.
|
||||
type Call = unsafe extern "C" fn(*mut *mut c_void, *mut Header) -> u32;
|
||||
|
||||
/// The title's own functions, by [`NAMES`].
|
||||
static ORIGINALS: [AtomicUsize; 5] = [const { AtomicUsize::new(0) }; 5];
|
||||
const NAMES: [&str; 5] = ["ffxCreateContext", "ffxDestroyContext", "ffxConfigure", "ffxQuery", "ffxDispatch"];
|
||||
|
||||
/// An upscaler context the title made: its creation flags and largest
|
||||
/// sizes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Created {
|
||||
flags: u32,
|
||||
max_render: [u32; 2],
|
||||
max_output: [u32; 2],
|
||||
}
|
||||
|
||||
static CONTEXTS: Mutex<Option<HashMap<usize, Created>>> = Mutex::new(None);
|
||||
|
||||
macro_rules! once {
|
||||
($level:ident, $($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::$level!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
/// Binds the title's imports of [`LOADER_DLL`] to the functions here when
|
||||
/// DLSS or frame generation is on, keeping what `inner` binds them to (the
|
||||
/// title's own DLL) for them to call; otherwise binds as `inner` does.
|
||||
pub struct Interpose<'a> {
|
||||
pub inner: &'a dyn ImportResolver,
|
||||
}
|
||||
|
||||
impl ImportResolver for Interpose<'_> {
|
||||
fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution {
|
||||
let found = self.inner.resolve(dll, symbol);
|
||||
if !dll.eq_ignore_ascii_case(LOADER_DLL) || !streamline::serving() {
|
||||
return found;
|
||||
}
|
||||
match (&found, symbol) {
|
||||
(&Resolution::Found { address, .. }, ImportSymbol::Name { name, .. }) => match interpose(name, address) {
|
||||
Some(ours) => Resolution::Found { address: ours, provenance: Provenance::Hle },
|
||||
None => found,
|
||||
},
|
||||
_ => found,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps `original` as the title's `name` and gives ours, if we have one.
|
||||
fn interpose(name: &str, original: usize) -> Option<usize> {
|
||||
let i = NAMES.iter().position(|n| *n == name)?;
|
||||
ORIGINALS[i].store(original, Relaxed);
|
||||
let ours = [
|
||||
ffxCreateContext as *const () as usize,
|
||||
ffxDestroyContext as *const () as usize,
|
||||
ffxConfigure as *const () as usize,
|
||||
ffxQuery as *const () as usize,
|
||||
ffxDispatch as *const () as usize,
|
||||
][i];
|
||||
tracing::info!(name, original = format_args!("{original:#x}"), "FidelityFX: the title's import goes through ours (DLSS / frame generation)");
|
||||
Some(ours)
|
||||
}
|
||||
|
||||
fn original(i: usize) -> Option<*const ()> {
|
||||
let address = ORIGINALS[i].load(Relaxed);
|
||||
(address != 0).then_some(address as *const ())
|
||||
}
|
||||
|
||||
fn contexts<T>(f: impl FnOnce(&mut HashMap<usize, Created>) -> T) -> T {
|
||||
let mut contexts = CONTEXTS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
f(contexts.get_or_insert_with(HashMap::new))
|
||||
}
|
||||
|
||||
extern "C" fn ffxCreateContext(context: *mut *mut c_void, desc: *mut Header, memory: *const c_void) -> u32 {
|
||||
let Some(create) = original(0) else { return PARAMETER };
|
||||
// SAFETY: the title's own function, with its arguments.
|
||||
let code = unsafe { std::mem::transmute::<*const (), Create>(create)(context, desc, memory) };
|
||||
if code != OK || context.is_null() || desc.is_null() {
|
||||
return code;
|
||||
}
|
||||
// SAFETY: the title passes a chain of descriptions.
|
||||
if unsafe { (*desc).kind } != CREATE_UPSCALE {
|
||||
return code;
|
||||
}
|
||||
// SAFETY: an upscaler description, by its type; the context was made.
|
||||
let (created, handle) = unsafe {
|
||||
let d = desc.cast::<CreateUpscale>().read();
|
||||
(Created { flags: d.flags, max_render: d.max_render, max_output: d.max_output }, *context as usize)
|
||||
};
|
||||
tracing::info!(
|
||||
context = format_args!("{handle:#x}"),
|
||||
flags = format_args!("{:#x}", created.flags),
|
||||
max_render = ?created.max_render,
|
||||
max_output = ?created.max_output,
|
||||
"FidelityFX: the title made its upscaler"
|
||||
);
|
||||
contexts(|c| c.insert(handle, created));
|
||||
code
|
||||
}
|
||||
|
||||
extern "C" fn ffxDestroyContext(context: *mut *mut c_void, memory: *const c_void) -> u32 {
|
||||
let Some(destroy) = original(1) else { return PARAMETER };
|
||||
if !context.is_null() {
|
||||
// SAFETY: the title passes its context.
|
||||
let handle = unsafe { *context } as usize;
|
||||
if contexts(|c| c.remove(&handle)).is_some() {
|
||||
streamline::upscaler_destroyed(handle);
|
||||
}
|
||||
}
|
||||
// SAFETY: the title's own function, with its arguments.
|
||||
unsafe { std::mem::transmute::<*const (), Destroy>(destroy)(context, memory) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxConfigure(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
let Some(configure) = original(2) else { return PARAMETER };
|
||||
// SAFETY: the title's own function, with its arguments.
|
||||
unsafe { std::mem::transmute::<*const (), Call>(configure)(context, desc) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxQuery(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
let Some(query) = original(3) else { return PARAMETER };
|
||||
if !desc.is_null() {
|
||||
// SAFETY: the title passes a description.
|
||||
let kind = unsafe { (*desc).kind };
|
||||
static SEEN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&kind) && seen.len() < 32 {
|
||||
seen.push(kind);
|
||||
tracing::info!(kind = format_args!("{kind:#x}"), "FidelityFX: the title asks a query of this kind (answered by its own DLL)");
|
||||
}
|
||||
}
|
||||
// SAFETY: the title's own function, with its arguments.
|
||||
unsafe { std::mem::transmute::<*const (), Call>(query)(context, desc) }
|
||||
}
|
||||
|
||||
extern "C" fn ffxDispatch(context: *mut *mut c_void, desc: *mut Header) -> u32 {
|
||||
let Some(dispatch) = original(4) else { return PARAMETER };
|
||||
// SAFETY: the title's own function, with its arguments.
|
||||
let own = || unsafe { std::mem::transmute::<*const (), Call>(dispatch)(context, desc) };
|
||||
if context.is_null() || desc.is_null() {
|
||||
return own();
|
||||
}
|
||||
// SAFETY: the title passes a description and its context.
|
||||
let (kind, handle) = unsafe { ((*desc).kind, *context as usize) };
|
||||
if kind != DISPATCH_UPSCALE {
|
||||
return own();
|
||||
}
|
||||
let Some(created) = contexts(|c| c.get(&handle).copied()) else {
|
||||
once!(warn, "FidelityFX: an upscale dispatch on a context we did not see made; the title's own runs");
|
||||
return own();
|
||||
};
|
||||
// SAFETY: an upscaling, by its type.
|
||||
let d = unsafe { desc.cast::<DispatchUpscale>().read() };
|
||||
first_dispatch(&d, &created);
|
||||
let up = upscale(&d, &created, handle);
|
||||
match streamline::upscale(&up) {
|
||||
Taken::Dlss => OK,
|
||||
Taken::Noted => own(),
|
||||
Taken::No(why) => {
|
||||
streamline::forwarded();
|
||||
refused(why);
|
||||
own()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each reason the title's own upscaling ran instead, once.
|
||||
fn refused(why: &'static str) {
|
||||
static SEEN: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&why) {
|
||||
seen.push(why);
|
||||
tracing::warn!("FidelityFX: the title's own upscaling runs: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The first upscale dispatch, all of it.
|
||||
fn first_dispatch(d: &DispatchUpscale, created: &Created) {
|
||||
once!(
|
||||
info,
|
||||
render = ?d.render_size,
|
||||
output = ?d.upscale_size,
|
||||
max_render = ?created.max_render,
|
||||
max_output = ?created.max_output,
|
||||
create_flags = format_args!("{:#x}", created.flags),
|
||||
flags = format_args!("{:#x}", d.flags),
|
||||
jitter = ?d.jitter,
|
||||
motion_vector_scale = ?d.motion_scale,
|
||||
near = d.camera_near,
|
||||
far = d.camera_far,
|
||||
fov = d.camera_fov_angle_vertical,
|
||||
frame_ms = d.frame_time_delta,
|
||||
pre_exposure = d.pre_exposure,
|
||||
reset = d.reset != 0,
|
||||
sharpening = d.enable_sharpening != 0,
|
||||
resources = ?d.resources.iter().map(|r| (r.resource as usize != 0, r.description[1], r.description[2], r.description[3], r.state)).collect::<Vec<_>>(),
|
||||
"FidelityFX: the title's first upscale dispatch (resources: present, format, width, height, state)"
|
||||
);
|
||||
}
|
||||
|
||||
/// An upscaling in `victory_gpu::streamline`'s terms. The output size is the
|
||||
/// context's largest when the dispatch names none (as FidelityFX reads it).
|
||||
fn upscale(d: &DispatchUpscale, created: &Created, context: usize) -> Upscale {
|
||||
let output = if d.upscale_size == [0, 0] { created.max_output } else { d.upscale_size };
|
||||
Upscale {
|
||||
context,
|
||||
list: d.list.cast::<Object>().cast_const(),
|
||||
resources: d.resources.map(|r| (r.resource.cast::<Object>().cast_const(), r.state)),
|
||||
camera: Camera {
|
||||
jitter: d.jitter,
|
||||
motion_scale: d.motion_scale,
|
||||
render: d.render_size,
|
||||
output,
|
||||
near: d.camera_near,
|
||||
far: d.camera_far,
|
||||
fov_y: d.camera_fov_angle_vertical,
|
||||
reset: d.reset != 0,
|
||||
flags: created.flags,
|
||||
},
|
||||
pre_exposure: d.pre_exposure,
|
||||
frame_ms: d.frame_time_delta,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::mem::offset_of;
|
||||
use std::ptr::null_mut;
|
||||
|
||||
#[test]
|
||||
fn descriptions_lay_out_as_the_sdk() {
|
||||
assert_eq!(offset_of!(CreateUpscale, flags), 0x10);
|
||||
assert_eq!(offset_of!(CreateUpscale, max_output), 0x1c);
|
||||
assert_eq!(offset_of!(Resource, state), 0x28);
|
||||
assert_eq!(offset_of!(DispatchUpscale, list), 0x10);
|
||||
assert_eq!(offset_of!(DispatchUpscale, resources), 0x18);
|
||||
assert_eq!(offset_of!(DispatchUpscale, jitter), 0x168);
|
||||
assert_eq!(offset_of!(DispatchUpscale, render_size), 0x178);
|
||||
assert_eq!(offset_of!(DispatchUpscale, upscale_size), 0x180);
|
||||
assert_eq!(offset_of!(DispatchUpscale, enable_sharpening), 0x188);
|
||||
assert_eq!(offset_of!(DispatchUpscale, frame_time_delta), 0x190);
|
||||
assert_eq!(offset_of!(DispatchUpscale, reset), 0x198);
|
||||
assert_eq!(offset_of!(DispatchUpscale, camera_near), 0x19c);
|
||||
assert_eq!(offset_of!(DispatchUpscale, flags), 0x1ac);
|
||||
}
|
||||
|
||||
fn resource(at: usize, state: u32) -> Resource {
|
||||
Resource { resource: at as *mut c_void, description: [1, 10, 2560, 1440, 1, 1, 0, 0], state }
|
||||
}
|
||||
|
||||
fn dispatch(output: [u32; 2]) -> DispatchUpscale {
|
||||
DispatchUpscale {
|
||||
header: Header { kind: DISPATCH_UPSCALE, next: null_mut() },
|
||||
list: 0x1000 as *mut c_void,
|
||||
resources: [
|
||||
resource(0x10, 0xc),
|
||||
resource(0x20, 0xc),
|
||||
resource(0x30, 0xc),
|
||||
resource(0, 0),
|
||||
resource(0x50, 0xc),
|
||||
resource(0, 0),
|
||||
resource(0x70, 0x2),
|
||||
],
|
||||
jitter: [0.25, -0.125],
|
||||
motion_scale: [1706.0, 960.0],
|
||||
render_size: [1706, 960],
|
||||
upscale_size: output,
|
||||
enable_sharpening: 0,
|
||||
sharpness: 0.0,
|
||||
frame_time_delta: 33.3,
|
||||
pre_exposure: 1.5,
|
||||
reset: 1,
|
||||
camera_near: 0.1,
|
||||
camera_far: 5000.0,
|
||||
camera_fov_angle_vertical: 0.9,
|
||||
view_space_to_meters_factor: 1.0,
|
||||
flags: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A dispatch reads as the upscaling it names; without an output size
|
||||
/// the context's largest is the output.
|
||||
#[test]
|
||||
fn a_dispatch_reads_as_its_upscaling() {
|
||||
let created = Created { flags: 0x29, max_render: [2560, 1440], max_output: [2560, 1440] };
|
||||
let up = upscale(&dispatch([2560, 1440]), &created, 0xabc);
|
||||
assert_eq!(up.context, 0xabc);
|
||||
assert_eq!(up.list as usize, 0x1000);
|
||||
assert_eq!(up.resources[streamline::COLOUR], (0x10 as *const Object, 0xc));
|
||||
assert_eq!(up.resources[streamline::EXPOSURE].0 as usize, 0);
|
||||
assert_eq!(up.resources[streamline::OUTPUT], (0x70 as *const Object, 0x2));
|
||||
assert_eq!(up.camera.render, [1706, 960]);
|
||||
assert_eq!(up.camera.output, [2560, 1440]);
|
||||
assert_eq!(up.camera.flags, 0x29);
|
||||
assert!(up.camera.reset && up.camera.depth_inverted());
|
||||
assert_eq!((up.pre_exposure, up.frame_ms), (1.5, 33.3));
|
||||
let up = upscale(&dispatch([0, 0]), &Created { max_output: [1920, 1080], ..created }, 0);
|
||||
assert_eq!(up.camera.output, [1920, 1080]);
|
||||
}
|
||||
|
||||
struct Fixed;
|
||||
impl ImportResolver for Fixed {
|
||||
fn resolve(&self, dll: &str, _: &ImportSymbol) -> Resolution {
|
||||
if dll.eq_ignore_ascii_case(LOADER_DLL) {
|
||||
Resolution::Found { address: 0x1234, provenance: Provenance::Title }
|
||||
} else {
|
||||
Resolution::Missing
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Without Streamline the title's imports bind as before; the names we
|
||||
/// serve are the API's five.
|
||||
#[test]
|
||||
fn without_streamline_the_titles_own_binds() {
|
||||
let name = |n: &str| ImportSymbol::Name { hint: 0, name: n.into() };
|
||||
let interposed = Interpose { inner: &Fixed };
|
||||
assert_eq!(
|
||||
interposed.resolve("AMD_FIDELITYFX_LOADER_XBOX.DLL", &name("ffxDispatch")),
|
||||
Resolution::Found { address: 0x1234, provenance: Provenance::Title }
|
||||
);
|
||||
assert_eq!(interposed.resolve("other.dll", &name("ffxDispatch")), Resolution::Missing);
|
||||
assert_eq!(interpose("ffxGetVersion", 1), None);
|
||||
assert!(interpose("ffxQuery", 0x5678).is_some());
|
||||
assert_eq!(original(3), Some(0x5678 as *const ()));
|
||||
ORIGINALS[3].store(0, Relaxed);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ pub mod dsp;
|
||||
#[cfg(windows)]
|
||||
pub mod dstorage;
|
||||
#[cfg(windows)]
|
||||
pub mod fidelityfx;
|
||||
#[cfg(windows)]
|
||||
pub mod files;
|
||||
pub mod gameinput;
|
||||
pub mod kernel;
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# DLSS and DLSS Frame Generation (NVIDIA Streamline)
|
||||
|
||||
Two switches, both off by default:
|
||||
|
||||
- `VICTORY_DLSS=1`: DLSS Super Resolution does the title's FidelityFX upscaling
|
||||
(its `ffxDispatch`), 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_FRAMEGEN=1`: DLSS Frame Generation (2x) on our present, from the depth
|
||||
and motion vectors of the last upscaling submitted before the present.
|
||||
|
||||
Nothing NVIDIA ships is in this repository. The library is loaded at run time
|
||||
from a folder you name; if anything is missing (the folder, a signature, a
|
||||
feature on this GPU, the device hand-over), the log says what, and the title's
|
||||
own upscaling and our plain present run as before.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Download NVIDIA's Streamline SDK release (NVIDIA RTX SDK license) from
|
||||
<https://github.com/NVIDIA-RTX/Streamline/releases> and unpack it outside the
|
||||
repository. Tested: `streamline-sdk-v2.14.16.zip`, unpacked to
|
||||
`C:\dev\sdk\streamline-sdk-v2.14.16`. Its `bin\x64` folder holds what is
|
||||
loaded:
|
||||
- `sl.interposer.dll` (loaded by us; its Authenticode signature is checked),
|
||||
- `sl.common.dll`, `sl.dlss.dll`, `sl.dlss_g.dll`, `sl.reflex.dll`,
|
||||
`sl.pcl.dll` (Streamline's plugins; it checks their NVIDIA signatures),
|
||||
- `nvngx_dlss.dll` (DLSS Super Resolution, 310.x), `nvngx_dlssg.dll` (DLSS
|
||||
Frame Generation).
|
||||
A newer `nvngx_dlss.dll` (the DLSS SDK, <https://github.com/NVIDIA/DLSS>,
|
||||
`lib\Windows_x86_64\rel`) can replace the one in that folder.
|
||||
2. `VICTORY_STREAMLINE_DIR=<that bin\x64 folder>`; the default is
|
||||
`C:\dev\sdk\streamline-sdk-v2.14.16\bin\x64`.
|
||||
3. Check the PC without the title (a few seconds):
|
||||
- `victory upscaler-check`: Streamline loads, and what this GPU supports.
|
||||
- `victory upscaler-check --device`: the host device is made and handed over
|
||||
to Streamline, DLSS's render sizes for the output are listed, and DLSS runs
|
||||
three times on stand-in textures.
|
||||
- `victory upscaler-check --present`: as `--device`, then three seconds of
|
||||
presents in a window of ours with frame generation on stand-in depth and
|
||||
motion vectors; it reports how many frames frame generation showed.
|
||||
|
||||
Windows 10 2004 or later, a GeForce RTX GPU (frame generation: RTX 40 or
|
||||
later), hardware-accelerated GPU scheduling on (frame generation needs it).
|
||||
|
||||
## Switches
|
||||
|
||||
| Variable | Values | Default | What |
|
||||
|---|---|---|---|
|
||||
| `VICTORY_DLSS` | `1` | off | DLSS in place of the title's FidelityFX upscaling |
|
||||
| `VICTORY_FRAMEGEN` | `1` | off | DLSS Frame Generation on our present; needs `VICTORY_THIN=1` or `VICTORY_ASYNC_SUBMIT=1` (the line of submissions) |
|
||||
| `VICTORY_DLSS_MODE` | `dlaa`, `quality`, `balanced`, `performance`, `ultraperformance` | `quality` (`dlaa` with frame generation alone) | the scene's size: 1, 2/3, 0.58, 1/2, 1/3 of the output; the DLSS mode follows the sizes the title then passes |
|
||||
| `VICTORY_DLSS_PRESET` | `default`, `j`, `k`, `l`, `m` (`e`, `f` deprecated) | `default` | the DLSS model, for every mode |
|
||||
| `VICTORY_STREAMLINE_DIR` | a folder | see above | where `sl.interposer.dll` and the rest are |
|
||||
| `VICTORY_STREAMLINE_LOG` | a folder | none | Streamline's own log files there, verbose |
|
||||
| `VICTORY_DLSS_JITTER` | `x,y` | `1,1` | multipliers for the jitter DLSS is given (`-1,1` flips x) |
|
||||
| `VICTORY_DLSS_MV` | `x,y` | `1,1` | multipliers for the motion-vector scale |
|
||||
| `VICTORY_DLSS_REACTIVE` | `0` | on | `0`: the title's reactive mask is not given to DLSS |
|
||||
| `VICTORY_FSR_PATH` | `1` | off | the title's FidelityFX path at `VICTORY_DLSS_MODE`'s scale with its own FidelityFX (no Streamline): the comparison for DLSS |
|
||||
|
||||
## How it works
|
||||
|
||||
**Where the title upscales.** The title imports `ffxCreateContext`,
|
||||
`ffxDestroyContext`, `ffxQuery` and `ffxDispatch` from
|
||||
`amd_fidelityfx_loader_xbox.dll`, which loads `amd_fidelityfx_upscaler_xbox.dll`
|
||||
itself. With a switch on, the executable's imports of the loader are bound to
|
||||
ours (`victory_hle::modules::fidelityfx::Interpose`), which call the title's own
|
||||
DLL for everything; only an upscale `ffxDispatch` (type `0x10001`) is taken. The
|
||||
title's upscaler context stays the title's own, so its upscaling runs again on
|
||||
any frame DLSS does not take.
|
||||
|
||||
**Series X does not use FidelityFX by itself.** Run logs: the upscaler DLL is
|
||||
loaded on every Series S run and on no Series X run (stock or 1440p). The
|
||||
renderer selection at title+0x7e9421 picks renderer 7 (the FidelityFX path)
|
||||
only when the console is a Series S (title+0x75140 tests the device type for
|
||||
6, Lockhart) and a capability bit is set; Series X takes renderer 6, the
|
||||
title's own temporal pass. So with DLSS or frame generation available, the app
|
||||
patches the image (`native_1440p::prepare_upscaler`, from DexNom's
|
||||
`prepare_fsr_4k`): renderer 7 always, and the FidelityFX path's render size
|
||||
code at title+0x28ef69a notes the FidelityFX quality mode of `VICTORY_DLSS_MODE`
|
||||
and takes its scaled branch, whose scale is the mode's. The title computes the
|
||||
render size itself there (scale times the output size, truncated); it does not
|
||||
ask `ffxQuery` for it, so a query answer cannot change it. The temporal scene
|
||||
scale (title+0x28f1e7e) is set to the same scale, as the stock Series X image
|
||||
pairs them (2/3 each). Every patched instruction is checked against the stock
|
||||
bytes first (the test `patches_the_upscaler_path` does so with the retail
|
||||
executable). Image caches: `images\native-1440p-upscaler-<mode>-sdr` (with
|
||||
`VICTORY_NATIVE_1440P=1`), `images\upscaler-<mode>` (otherwise).
|
||||
|
||||
**At the dispatch.** On the title's thread the dispatch's textures are checked
|
||||
(host copies, states a shader can read or write); then a step is put into the
|
||||
title's list (`crate::list::external`): run at once, or with `VICTORY_THIN=1`
|
||||
written into the list's stream and run where it is translated, in order. The
|
||||
step prepares the inputs as a compute shader's would be prepared (aliased
|
||||
views, uploads of title-written textures, depth twins), moves each into the
|
||||
state the title gave FidelityFX, records `slEvaluateFeature` into the host list
|
||||
with the textures as local tags in those states (Streamline moves them to what
|
||||
it needs and back), marks the output as written on the host, and has the
|
||||
title's draw state set again before its next draw. Viewport 1, frame index =
|
||||
the upscaling's number.
|
||||
|
||||
Constants from the dispatch: jitter, motion-vector scale (FidelityFX's scale
|
||||
over the render size), near, far, vertical field of view, reset; from the
|
||||
context's flags: HDR, inverted depth, auto exposure (no exposure texture),
|
||||
display-resolution motion vectors, jittered motion vectors. The title passes
|
||||
no camera matrices: the projection is made of the field of view, the render
|
||||
aspect and the depth range; camera motion is in the motion vectors, so the
|
||||
clip-to-previous-clip matrices are the identity and the camera stands at the
|
||||
origin. DLSS Super Resolution reads none of the matrices; frame generation may.
|
||||
|
||||
**Frame generation.** Streamline is used with manual hooking: nothing of D3D12
|
||||
or DXGI is hooked globally. The host device is handed over (`slSetD3DDevice`);
|
||||
the direct queue is made through Streamline's device proxy (the native queue
|
||||
behind it runs everything); our swap chain is made through its factory proxy
|
||||
on the queue proxy. A list that recorded an upscaling is noted; when it is
|
||||
submitted, its depth and motion vectors become the latest. Each present (on
|
||||
the line's thread, `VICTORY_THIN=1`) then gets a frame token of the title's
|
||||
frame number, the latency markers (simulation, render submit, present), the
|
||||
constants and the depth and motion-vector tags in the states the submissions
|
||||
left them in (viewport 0), and frame generation is switched on; a present
|
||||
without a new upscaling (menus, loads) switches it off and clears the tags.
|
||||
Reflex low latency is on (frame generation needs it); `slReflexSleep` is not
|
||||
called. On Series S, whose interface is a second plane, the scene plane is the
|
||||
colour without the interface and the interface plane its colour and alpha
|
||||
(premultiplied, as our composer blends them). On Series X the interface is
|
||||
drawn into the scene's output: no interface-free colour is tagged yet.
|
||||
|
||||
## Log lines
|
||||
|
||||
At start: `Streamline: DLSS Super Resolution is supported on this GPU`
|
||||
(requirements), `Streamline loaded (manual hooking, no downloads)`, the `display`
|
||||
line with `through the title's FidelityFX path`. At the device: `Streamline: DLSS
|
||||
Super Resolution loaded streamline=… ngx=…` (and frame generation, Reflex),
|
||||
`the direct queue was made through the device proxy`, `our swap chain is
|
||||
Streamline's proxy`. At the title: `FidelityFX: the title's import goes through
|
||||
ours`, `FidelityFX: the title made its upscaler` (flags, sizes), `FidelityFX:
|
||||
the title's first upscale dispatch` (every field), `DLSS: upscaling recorded in
|
||||
place of the title's FidelityFX` (render and output sizes, DLSS mode, optimal
|
||||
size, formats; again when they change). Every second: `DLSS per frame: …
|
||||
upscalings by DLSS, … failed, … left to the title's FidelityFX` and `DLSS Frame
|
||||
Generation: … presents with it on, … off, … frames shown by it (status …)`.
|
||||
`FidelityFX: the title's own upscaling runs: <why>` names each reason once.
|
||||
|
||||
## Limits
|
||||
|
||||
- Motion vectors: blocks of wrong motion inside character silhouettes (likely
|
||||
the heat-haze pass `731a39171b568298`) show as smearing with DLSS and as
|
||||
warped shapes in generated frames.
|
||||
- No interface-free colour on Series X: generated frames warp the interface
|
||||
with the scene.
|
||||
- Camera matrices are made, not the title's (see above).
|
||||
- Video memory: the title's FidelityFX context stays allocated beside DLSS's;
|
||||
frame generation needs about 0.5 GB more at 1440p.
|
||||
- Latency: frame generation holds a frame back; it is meant for a base frame
|
||||
rate of 60 and up.
|
||||
- `slShutdown` is not called; the process ends with the title.
|
||||
|
||||
Credits: the FidelityFX description layouts and the image patch of the
|
||||
FidelityFX path are DexNom's (DexNom/VIctory, GPL-3.0-or-later).
|
||||
Reference in new issue
Block a user