diff --git a/README.md b/README.md index d304d86..c3f81af 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder ``` Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests -(D3D12, SM 6.6; skipped without a GPU / DXC). Tests on real game data are opt-in through +(D3D12, SM 6.6; skipped without a GPU / DXC; `XCL_ADAPTER=1` or `XCL_ADAPTER=radeon` picks +another adapter than the first high-performance one, for titles too). Tests on real game data are opt-in through environment variables pointing at your own files – `XCL_SAMPLE_RPF` (shader pack), `XCL_SAMPLE_DLLS` (the game's console DLLs), `XCL_SAMPLE_TTPF` (texture archive), `XCL_SAMPLE_BK2` (a movie), `XCL_SAMPLE_BVH4`, `XCL_SAMPLE_AWC` (a sound) – described in `HANDOFF.md`; without them those diff --git a/crates/xcl/src/config.rs b/crates/xcl/src/config.rs index 23257c0..09bbbdb 100644 --- a/crates/xcl/src/config.rs +++ b/crates/xcl/src/config.rs @@ -43,7 +43,8 @@ pub struct Config { pub stub_returns: BTreeMap, /// "d3d12" (real GPU, default) or "null" (no rendering). pub graphics: String, - /// "auto" (high-performance GPU, then WARP) or "warp". + /// "auto" (high-performance GPU, then WARP), "warp", a number (that hardware adapter in + /// high-performance order) or a part of the adapter's name ("radeon"). `XCL_ADAPTER` overrides. pub d3d12_adapter: String, /// Enable the D3D12 debug layer (needs Graphics Tools). pub d3d12_debug: bool, diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs new file mode 100644 index 0000000..85a6ded --- /dev/null +++ b/crates/xcl/src/gpu/adapter.rs @@ -0,0 +1,110 @@ +//! Which D3D12 adapter XCL uses: `d3d12_adapter` in `xcl.toml`, overridden by `XCL_ADAPTER`. +//! +//! - `auto` (or empty): the hardware adapters in high-performance order, the first one that +//! creates a device; +//! - `warp`: the software renderer; +//! - a number `N`: the N-th hardware adapter in high-performance order (0 = the first); +//! - anything else: the hardware adapters whose name contains it (case-insensitive), e.g. +//! `radeon` or `rtx 3080`. +//! +//! The same choice drives the title's device (`hle::d3d12x::real`) and the GPU test bench +//! (`gpu::recomp::runner`), so the GPU tests can be run on each adapter of a machine in turn. + +use std::fmt; + +use windows::Win32::Graphics::Dxgi::*; + +/// The environment variable that overrides `d3d12_adapter`. +pub const ENV: &str = "XCL_ADAPTER"; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Selector { + Auto, + Warp, + /// Position among the hardware adapters in high-performance order. + Index(usize), + /// Lower-case part of the adapter's name. + Name(String), +} + +impl Selector { + pub fn parse(s: &str) -> Selector { + let s = s.trim(); + if s.is_empty() || s.eq_ignore_ascii_case("auto") { + Selector::Auto + } else if s.eq_ignore_ascii_case("warp") { + Selector::Warp + } else if let Ok(n) = s.parse::() { + Selector::Index(n) + } else { + Selector::Name(s.to_lowercase()) + } + } + + /// `XCL_ADAPTER` if set (and not empty), otherwise `configured`. + pub fn from_env_or(configured: &str) -> Selector { + match std::env::var(ENV) { + Ok(v) if !v.trim().is_empty() => Selector::parse(&v), + _ => Selector::parse(configured), + } + } + + /// Whether the hardware adapter at `index` (high-performance order) named `name` is chosen. + pub fn allows(&self, index: usize, name: &str) -> bool { + match self { + Selector::Auto => true, + Selector::Warp => false, + Selector::Index(n) => *n == index, + Selector::Name(part) => name.to_lowercase().contains(part.as_str()), + } + } +} + +impl fmt::Display for Selector { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Selector::Auto => f.write_str("auto"), + Selector::Warp => f.write_str("warp"), + Selector::Index(n) => write!(f, "{n}"), + Selector::Name(s) => write!(f, "\"{s}\""), + } + } +} + +/// The adapter's name from its description. +pub fn name(desc: &DXGI_ADAPTER_DESC1) -> String { + let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + String::from_utf16_lossy(&desc.Description[..n]) +} + +/// The hardware adapters (software ones skipped) in high-performance order. +pub fn hardware(factory: &IDXGIFactory6) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> { + let mut out = Vec::new(); + let mut i = 0; + unsafe { + while let Ok(adapter) = factory.EnumAdapterByGpuPreference::(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { + i += 1; + let Ok(desc) = adapter.GetDesc1() else { continue }; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + continue; + } + out.push((adapter, desc)); + } + } + out +} + +/// The hardware adapters `sel` allows, in high-performance order (empty for `warp`). +pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1, DXGI_ADAPTER_DESC1)> { + hardware(factory).into_iter().enumerate().filter(|(i, (_, d))| sel.allows(*i, &name(d))).map(|(_, a)| a).collect() +} + +/// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips. +pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String { + let have: Vec = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect(); + format!("{ENV} / d3d12_adapter {sel} matches no hardware adapter (have: {})", have.join(", ")) +} + +#[cfg(test)] +#[path = "adapter_tests.rs"] +mod tests; diff --git a/crates/xcl/src/gpu/adapter_tests.rs b/crates/xcl/src/gpu/adapter_tests.rs new file mode 100644 index 0000000..f2fd0e8 --- /dev/null +++ b/crates/xcl/src/gpu/adapter_tests.rs @@ -0,0 +1,23 @@ +use super::Selector; + +#[test] +fn selector_parsing() { + assert_eq!(Selector::parse(""), Selector::Auto); + assert_eq!(Selector::parse(" Auto "), Selector::Auto); + assert_eq!(Selector::parse("WARP"), Selector::Warp); + assert_eq!(Selector::parse("1"), Selector::Index(1)); + assert_eq!(Selector::parse("Radeon"), Selector::Name("radeon".into())); + assert_eq!(Selector::parse(" RTX 3080 "), Selector::Name("rtx 3080".into())); +} + +#[test] +fn selector_matching() { + let nv = "NVIDIA GeForce RTX 3080"; + let amd = "AMD Radeon(TM) Graphics"; + assert!(Selector::Auto.allows(0, nv) && Selector::Auto.allows(1, amd)); + assert!(!Selector::Warp.allows(0, nv)); + assert!(Selector::Index(1).allows(1, amd) && !Selector::Index(1).allows(0, nv)); + let radeon = Selector::parse("radeon"); + assert!(radeon.allows(1, amd) && !radeon.allows(0, nv)); + assert!(Selector::parse("geforce rtx").allows(0, nv)); +} diff --git a/crates/xcl/src/gpu/mod.rs b/crates/xcl/src/gpu/mod.rs index a83d41f..3b6874a 100644 --- a/crates/xcl/src/gpu/mod.rs +++ b/crates/xcl/src/gpu/mod.rs @@ -1,6 +1,7 @@ //! GPU side of XCL: console shader capture and the RDNA2 microcode toolchain //! (decoder / disassembler – the front-end of the shader recompiler). +pub mod adapter; pub mod bvh; pub mod desc; pub mod dxbc; diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index cceffd6..e8898b3 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -61,6 +61,8 @@ struct Gpu { value: u64, adapter: String, wave64: bool, + /// mesh shader tier 1 or higher (`mesh_draw`) + mesh: bool, } // D3D12 objects are free-threaded; access is serialised by the mutex. @@ -75,9 +77,17 @@ fn e(x: windows::core::Error) -> String { fn init() -> Result { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(e)?; - let adapter: IDXGIAdapter1 = factory.EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE).map_err(e)?; - let desc = adapter.GetDesc1().map_err(e)?; - let name = String::from_utf16_lossy(&desc.Description).trim_end_matches('\0').to_string(); + // `XCL_ADAPTER` picks the adapter (default: the first in high-performance order) + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { + (factory.EnumWarpAdapter().map_err(e)?, "WARP (software renderer)".into()) + } else { + let (a, desc) = crate::gpu::adapter::candidates(&factory, &sel) + .into_iter() + .next() + .ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + (a, crate::gpu::adapter::name(&desc)) + }; let mut dev: Option = None; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut dev).map_err(e)?; let dev = dev.ok_or("no device")?; @@ -93,11 +103,14 @@ fn init() -> Result { return Err(format!("{name}: no wave operations/int64")); } let wave64 = o1.WaveLaneCountMin <= 64 && o1.WaveLaneCountMax >= 64; + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mesh = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32).is_ok() + && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0; let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).map_err(e)?; let rs = root_signature(&dev, false)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; - Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64 }) + Ok(Gpu { dev, queue, rs, fence, value: 0, adapter: name, wave64, mesh }) } } @@ -337,6 +350,14 @@ pub fn wave64_supported() -> Result { gpu.as_ref().map(|x| x.wave64).map_err(|x| x.clone()) } +/// Whether the adapter runs mesh shaders (`mesh_draw`); an integrated RDNA2 GPU, for one, +/// reports wave64 but no mesh shader tier. +pub fn mesh_shaders_supported() -> Result { + let mut g = GPU.lock().unwrap(); + let gpu = g.get_or_insert_with(init); + gpu.as_ref().map(|x| x.mesh).map_err(|x| x.clone()) +} + /// Run a compiled kernel (DXIL) with `state` and flat memory `mem`. pub fn run(dxil: &[u8], state: &KernelState, mem: &[u32]) -> Result { run_with(dxil, state, mem, &[], &[]) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index f020e31..98840bf 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -26,6 +26,17 @@ fn gpu_ready_wave32() -> bool { } } +/// `runner::mesh_draw` needs mesh shaders (not every adapter with wave64 has them). +fn mesh_ready() -> bool { + match runner::mesh_shaders_supported() { + Ok(true) => true, + r => { + println!("GPU without mesh shaders – skipping ({r:?})"); + false + } + } +} + /// Assemble a program from (name, encoding, fields, literal). fn prog(list: &[(&str, &str, &[(&str, u64)], Option)]) -> Vec { let mut v = Vec::new(); @@ -1673,7 +1684,7 @@ void main(uint gi : SV_GroupIndex, out vertices V verts[128], out indices uint3 /// shader, the pass-through mesh shader rasterises its records. #[test] fn gpu_mesh_mode_two_passes() { - if !gpu_ready() { + if !gpu_ready() || !mesh_ready() { return; } use super::{dxc, mesh_passthrough, MsInterface, MESH_HEADER}; @@ -2290,7 +2301,7 @@ fn dump_retail_interfaces() { /// vertex by vertex (strip winding included), then drawn by the mesh pass-through. #[test] fn gpu_geometry_mode_es_gs_strip() { - if !gpu_ready_wave32() { + if !gpu_ready_wave32() || !mesh_ready() { return; } use super::{dxc, mesh_passthrough, GsInterface, IO_GS_PRIMS, IO_GS_VERTICES, MESH_HEADER}; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9c4a539..3e8f8bf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -322,12 +322,8 @@ fn geometry_wave32_required(device: *mut c_void) -> bool { } } -fn adapter_name(desc: &DXGI_ADAPTER_DESC1) -> String { - let n = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); - String::from_utf16_lossy(&desc.Description[..n]) -} - -/// Create the process-wide D3D12 device (high-performance GPU → WARP); once – later calls +/// Create the process-wide D3D12 device (the adapter `d3d12_adapter` / `XCL_ADAPTER` chooses, +/// by default the high-performance GPU → WARP); once – later calls /// return the existing device's adapter. pub fn init() -> Result { if !device_raw().is_null() { @@ -358,16 +354,16 @@ pub fn init() -> Result { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option = None; let mut name = String::new(); - if !cfg.d3d12_adapter.eq_ignore_ascii_case("warp") { - let mut i = 0; - while let Ok(adapter) = factory.EnumAdapterByGpuPreference::(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE) { - i += 1; - let Ok(desc) = adapter.GetDesc1() else { continue }; - if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { - continue; - } + let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); + if sel != crate::gpu::adapter::Selector::Warp { + let mut list = crate::gpu::adapter::candidates(&factory, &sel); + if list.is_empty() { + crate::xlog_warn!("D3D12: {} – using auto", crate::gpu::adapter::no_match(&factory, &sel)); + list = crate::gpu::adapter::candidates(&factory, &crate::gpu::adapter::Selector::Auto); + } + for (adapter, desc) in list { if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok() { - name = format!("{} ({} MiB VRAM)", adapter_name(&desc), desc.DedicatedVideoMemory >> 20); + name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } } diff --git a/crates/xcl/tests/gpu_pso_e2e.rs b/crates/xcl/tests/gpu_pso_e2e.rs index 1e06b48..03f8f33 100644 --- a/crates/xcl/tests/gpu_pso_e2e.rs +++ b/crates/xcl/tests/gpu_pso_e2e.rs @@ -30,6 +30,18 @@ fn f(x: f32) -> u32 { x.to_bits() } +/// Console GS and NGG programs are drawn through a mesh pass: they need mesh shaders, which +/// not every adapter has (an integrated RDNA2 GPU reports none). +fn mesh_shaders(dev: &ID3D12Device) -> bool { + let mut o7 = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let ok = unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS7, &mut o7 as *mut _ as _, std::mem::size_of_val(&o7) as u32) }.is_ok() + && o7.MeshShaderTier.0 >= D3D12_MESH_SHADER_TIER_1.0; + if !ok { + println!("GPU without mesh shaders – skipping"); + } + ok +} + /// Console shader containers by record name (as a title passes them in /// D3D12_SHADER_BYTECODE) and the backend device. None: no sample pack / DXC / GPU. /// `setup` holds `SERIAL` for the test: they share the backend device and its global PSO @@ -237,6 +249,9 @@ fn retail_pipelines_built_in_the_background_behind_a_stand_in() { assert!(!pso_async::is_pending(again.as_raw() as usize) && pso_async::resolve(again.as_raw() as usize) == again.as_raw() as usize); // a mesh pipeline (MS + PS of one pass) the same way + if !mesh_shaders(&dev) { + return; + } let data = std::fs::read(std::env::var("XCL_SAMPLE_RPF").unwrap()).unwrap(); let recs = pack::scan(&data, 0x40); let (ms, ps) = recs @@ -431,6 +446,9 @@ fn retail_textured_ps_decoded_descriptors_and_a_descriptor_change_between_draws( #[test] fn retail_es_gs_voxelize_geometry_mode() { let Some((blobs, _dev, _serial)) = setup(&["VS_VoxelizeGeneric_6be01b34_Wrapped", "GS_VoxelizeGeneric_6be01b34_Wrapped"]) else { return }; + if !mesh_shaders(&_dev) { + return; + } use xcl::gpu::recomp::{self, dxc, IO_GS_PRIMS, IO_GS_VERTICES, MESH_HEADER}; let (code, g) = recomp::geometry_program(&blobs[0], &blobs[1]).expect("ES + GS pair"); assert_eq!((g.max_vertex_count, g.vertex_bytes()), (3, 64)); @@ -539,6 +557,9 @@ fn pass_hash(name: &str) -> Option<&str> { #[test] fn retail_mesh_pipelines_through_the_hook() { let Some((_, dev, _serial)) = setup(&[]) else { return }; + if !mesh_shaders(&dev) { + return; + } let data = std::fs::read(std::env::var("XCL_SAMPLE_RPF").unwrap()).unwrap(); let recs = pack::scan(&data, 0x40); let every: usize = std::env::var("XCL_MS_EVERY").ok().and_then(|v| v.parse().ok()).unwrap_or(1500); @@ -608,6 +629,9 @@ fn retail_mesh_pipelines_through_the_hook() { #[test] fn retail_gs_pipeline_through_the_hook() { let Some((blobs, dev, _serial)) = setup(&["VS_VoxelizeGeneric_6be01b34_Wrapped", "GS_VoxelizeGeneric_6be01b34_Wrapped"]) else { return }; + if !mesh_shaders(&dev) { + return; + } let code = |b: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: b.as_ptr() as _, BytecodeLength: b.len() }; let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC { VS: code(&blobs[0]), diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index 4ad91cc..d84d465 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -13,11 +13,8 @@ use windows::Win32::Graphics::Dxgi::Common::*; type HRESULT = i32; -#[link(name = "d3d12_xs", kind = "raw-dylib")] -extern "system" { - fn D3D12CreateDevice(adapter: *mut c_void, fl: u32, riid: *const c_void, dev: *mut *mut c_void) -> HRESULT; - fn D3D12SerializeRootSignature(desc: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT; -} +type D3D12CreateDeviceFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT; +type D3D12SerializeRootSignatureFn = unsafe extern "system" fn(*const c_void, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; // the console's texture layout library #[link(name = "xg_xs", kind = "raw-dylib")] @@ -68,6 +65,19 @@ macro_rules! ensure { ($c:expr, $($m:tt)*) => { if !$c { return Err(format!($($m)*)); } }; } +/// An export of `d3d12_xs.dll` (XCL), looked up by name. Not a static import: the `windows` +/// crate imports the same two functions from `d3d12.dll`, and of two imports of one symbol +/// the linker keeps one – the system's. The title then got the system's device for the +/// default adapter, which is XCL's device only while that adapter is the one XCL chose +/// (D3D12 hands out one device per adapter); on a machine with two GPUs it is another one. +unsafe fn xs(name: &str) -> Result { + let h = crate::LoadLibraryW(crate::wide("d3d12_xs.dll").as_ptr()); + ensure!(h != 0, "LoadLibrary(d3d12_xs.dll) failed"); + let f = crate::GetProcAddress(h, format!("{name}\0").as_ptr()); + ensure!(f != 0, "d3d12_xs.dll!{name} not found"); + Ok(transmute_copy(&f)) +} + /// A command list method at its console slot: from SetDescriptorHeaps (PC 28) on, the /// console list has the PC methods 4 slots further (the query methods come first). unsafe fn xslot(list: &ID3D12GraphicsCommandList, slot: usize) -> F { @@ -90,7 +100,8 @@ fn e(x: windows::core::Error) -> String { fn device() -> Result { unsafe { let mut p = std::ptr::null_mut(); - let hr = D3D12CreateDevice(std::ptr::null_mut(), 0xC000, &ID3D12Device::IID as *const _ as *const c_void, &mut p); + let create: D3D12CreateDeviceFn = xs("D3D12CreateDevice")?; + let hr = create(std::ptr::null_mut(), 0xC000, &ID3D12Device::IID as *const _ as *const c_void, &mut p); ensure!(hr >= 0 && !p.is_null(), "D3D12CreateDevice hr={hr:#x}"); Ok(ID3D12Device::from_raw(p)) } @@ -115,7 +126,8 @@ fn root_signature(dev: &ID3D12Device) -> Result { unsafe { let desc = D3D12_ROOT_SIGNATURE_DESC { Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, ..Default::default() }; let (mut blob, mut err) = (std::ptr::null_mut(), std::ptr::null_mut()); - let hr = D3D12SerializeRootSignature(&desc as *const _ as *const c_void, 1, &mut blob, &mut err); + let serialize: D3D12SerializeRootSignatureFn = xs("D3D12SerializeRootSignature")?; + let hr = serialize(&desc as *const _ as *const c_void, 1, &mut blob, &mut err); ensure!(hr == 0 && !blob.is_null(), "D3D12SerializeRootSignature hr={hr:#x}"); let blob = ID3DBlob::from_raw(blob); let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize());