From 2849477415a46f5a079c85cf3e64a3dff32f713c Mon Sep 17 00:00:00 2001 From: Marvis Date: Mon, 23 Nov 2026 23:10:01 +0100 Subject: [PATCH] Run Grand Theft Auto VI from first boot into the world The title now boots through every first-boot and menu screen at its own 30 fps, drawing with translated shaders, with input, sound, saves and loading served; it reaches the world, where the host GPU path still fails (see "Not working yet"). Loader and runtime - Crash reports unwind properly, name C++ throws and host GPU failures, carry the title's last debug lines and are appended to crashes.log. - Thread notices on our own threads, reentrant late DLL loading, exit in the console's order, relaunch on a launch-new-game request. - Offline guard: the title cannot reach the network (sockets, name lookups, WinHTTP, the media source resolver); by-name lookups and loads follow the import rules. - Every runtime area the title calls is served (networking hint, packages, store, saves, display, UI, speech stubs, user, async pool). Saves persist; an update is one rename and survives a kill at any step. - DirectStorage reads for real: shared worker pool, priorities, zlib and BCPack. BCPack is our own decoder; the format's constant tables ship in crates/victory-formats/src/bcpack-tables.bin (the asset policy's one exception, see docs/asset-policy.md). - GameInput from XInput pads and the keyboard, with a keyboard stand-in pad; console timers (1 ms) for the whole process. - Audio: XMA2 decoding on the emulated contexts, Opus on the decoder queues, the DSP interface as a stub; title memory placed below 2^40. - Console texture layouts (sizes, tiling, detiling) and the layout library's imports. GPU - Draws, mesh dispatches and compute dispatches run on the host with shaders translated at first use and cached on disk; descriptor heaps, views, root signatures, barriers and host texture states; rectangle lists; comparison samplers. - Title memory reaches the host through persistent mirrors that copy only pages written since the last copy; shader-written buffers are copied back. - Presentation with frame pacing per event kind; framerate in the window caption. Shaders - DXIL emission for vertex, pixel, compute and mesh programs from the console's native code, with a differential test suite against the PC compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539; utility set complete. Build - Debugging aids (debug logs, frame capture, stack dumps, scripted keys, the host debug layer, the software adapter) exist only with the `diagnostics` feature; `[profile.diag]` keeps that build apart. Not working yet - In the world the host device is removed within seconds (descriptor handling fixes are in, unproven by a surviving run) and frames present black. - 64-bit image atomics, merged geometry stages and the BVH builder's own shaders do not translate; reverb is silent. Co-Authored-By: Claude Fable 5.2 --- .gitignore | 2 + Cargo.lock | 20 + Cargo.toml | 9 + README.md | 15 + apps/victory/Cargo.toml | 12 +- apps/victory/src/main.rs | 47 +- apps/victory/src/run.rs | 236 +- apps/victory/src/shader.rs | 16 +- apps/victory/src/translate.rs | 490 +- crates/victory-core/Cargo.toml | 4 + crates/victory-core/src/logging.rs | 26 +- crates/victory-formats/src/bcpack-tables.bin | Bin 0 -> 77982 bytes crates/victory-formats/src/bcpack.rs | 1398 ++++ crates/victory-formats/src/lib.rs | 12 +- crates/victory-formats/src/texture.rs | 1007 +++ crates/victory-formats/src/xma.rs | 1206 +++ crates/victory-formats/src/xma/tables.rs | 410 ++ crates/victory-gpu/Cargo.toml | 15 +- crates/victory-gpu/src/capture.rs | 525 ++ crates/victory-gpu/src/console.rs | 50 + crates/victory-gpu/src/copystat.rs | 147 + crates/victory-gpu/src/descriptor.rs | 635 +- crates/victory-gpu/src/descriptor/host.rs | 731 ++ crates/victory-gpu/src/device.rs | 199 +- crates/victory-gpu/src/draw.rs | 987 +++ crates/victory-gpu/src/dxgi.rs | 82 +- crates/victory-gpu/src/fence.rs | 25 +- crates/victory-gpu/src/frame.rs | 165 +- crates/victory-gpu/src/host.rs | 1075 ++- crates/victory-gpu/src/lib.rs | 27 +- crates/victory-gpu/src/list.rs | 773 +- crates/victory-gpu/src/object.rs | 41 +- crates/victory-gpu/src/pipeline.rs | 399 +- crates/victory-gpu/src/pipeline/host.rs | 594 ++ crates/victory-gpu/src/primitive.rs | 162 + crates/victory-gpu/src/query.rs | 4 +- crates/victory-gpu/src/queue.rs | 381 +- crates/victory-gpu/src/resource.rs | 729 +- crates/victory-gpu/src/root.rs | 190 +- crates/victory-gpu/src/sampler.rs | 119 + crates/victory-gpu/src/shader_cache.rs | 347 + crates/victory-gpu/src/shadow.rs | 363 + crates/victory-gpu/src/signature.rs | 4 +- crates/victory-gpu/src/texture.rs | 303 + crates/victory-gpu/src/watch.rs | 367 + crates/victory-hle/Cargo.toml | 22 + crates/victory-hle/src/host.rs | 9 +- crates/victory-hle/src/lib.rs | 6 +- crates/victory-hle/src/modules/apu.rs | 524 ++ crates/victory-hle/src/modules/audio.rs | 836 ++- .../victory-hle/src/modules/audio/capture.rs | 229 + crates/victory-hle/src/modules/d3d12x.rs | 59 +- crates/victory-hle/src/modules/display.rs | 195 + crates/victory-hle/src/modules/dsp.rs | 314 + crates/victory-hle/src/modules/dstorage.rs | 1476 ++++ crates/victory-hle/src/modules/files.rs | 318 +- crates/victory-hle/src/modules/gameinput.rs | 1508 +++- crates/victory-hle/src/modules/kernel.rs | 175 +- crates/victory-hle/src/modules/lifecycle.rs | 162 +- crates/victory-hle/src/modules/media.rs | 531 ++ crates/victory-hle/src/modules/mod.rs | 29 + crates/victory-hle/src/modules/net.rs | 1065 +++ crates/victory-hle/src/modules/speech.rs | 151 + crates/victory-hle/src/modules/storage.rs | 42 +- crates/victory-hle/src/modules/xasync.rs | 278 +- crates/victory-hle/src/modules/xg.rs | 780 ++ crates/victory-hle/src/modules/xgame.rs | 87 +- .../victory-hle/src/modules/xgameruntime.rs | 57 +- crates/victory-hle/src/modules/xgamesave.rs | 1291 ++++ crates/victory-hle/src/modules/xgameui.rs | 321 + crates/victory-hle/src/modules/xmem.rs | 669 +- crates/victory-hle/src/modules/xnetworking.rs | 210 + crates/victory-hle/src/modules/xpackage.rs | 371 + crates/victory-hle/src/modules/xstore.rs | 479 ++ crates/victory-hle/src/modules/xsystem.rs | 250 +- crates/victory-hle/src/modules/xuser.rs | 177 +- crates/victory-hle/src/runtime.rs | 128 +- crates/victory-loader/Cargo.toml | 5 + crates/victory-loader/src/crash.rs | 366 +- crates/victory-loader/src/lib.rs | 12 +- crates/victory-loader/src/stacks.rs | 224 + crates/victory-loader/src/threads.rs | 279 +- crates/victory-loader/src/tls.rs | 5 +- crates/victory-loader/src/windows.rs | 41 +- crates/victory-loader/tests/load_probe.rs | 22 +- crates/victory-shader/Cargo.toml | 25 + crates/victory-shader/src/dxbc.rs | 2 + crates/victory-shader/src/emit/bitcode.rs | 986 +++ crates/victory-shader/src/emit/container.rs | 380 + crates/victory-shader/src/emit/diff_tests.rs | 1267 ++++ crates/victory-shader/src/emit/host.rs | 1381 ++++ crates/victory-shader/src/emit/lower.rs | 6500 +++++++++++++++++ crates/victory-shader/src/emit/mod.rs | 452 ++ crates/victory-shader/src/emit/sampler.rs | 125 + crates/victory-shader/src/emit/shader.rs | 645 ++ crates/victory-shader/src/emit/validator.rs | 221 + crates/victory-shader/src/emit/wave.rs | 679 ++ crates/victory-shader/src/io.rs | 693 ++ crates/victory-shader/src/ir.rs | 67 +- crates/victory-shader/src/lib.rs | 7 +- crates/victory-shader/src/native.rs | 687 +- crates/victory-shader/src/resource.rs | 1116 +++ crates/victory-shader/src/structure.rs | 55 +- docs/architecture.md | 22 +- docs/asset-policy.md | 11 + tests/fixtures/hle-probe/src/lib.rs | 16 +- xtask/src/policy.rs | 5 +- 107 files changed, 42526 insertions(+), 868 deletions(-) create mode 100644 crates/victory-formats/src/bcpack-tables.bin create mode 100644 crates/victory-formats/src/bcpack.rs create mode 100644 crates/victory-formats/src/texture.rs create mode 100644 crates/victory-formats/src/xma.rs create mode 100644 crates/victory-formats/src/xma/tables.rs create mode 100644 crates/victory-gpu/src/capture.rs create mode 100644 crates/victory-gpu/src/console.rs create mode 100644 crates/victory-gpu/src/copystat.rs create mode 100644 crates/victory-gpu/src/descriptor/host.rs create mode 100644 crates/victory-gpu/src/draw.rs create mode 100644 crates/victory-gpu/src/pipeline/host.rs create mode 100644 crates/victory-gpu/src/primitive.rs create mode 100644 crates/victory-gpu/src/sampler.rs create mode 100644 crates/victory-gpu/src/shader_cache.rs create mode 100644 crates/victory-gpu/src/shadow.rs create mode 100644 crates/victory-gpu/src/texture.rs create mode 100644 crates/victory-gpu/src/watch.rs create mode 100644 crates/victory-hle/src/modules/apu.rs create mode 100644 crates/victory-hle/src/modules/audio/capture.rs create mode 100644 crates/victory-hle/src/modules/display.rs create mode 100644 crates/victory-hle/src/modules/dsp.rs create mode 100644 crates/victory-hle/src/modules/dstorage.rs create mode 100644 crates/victory-hle/src/modules/media.rs create mode 100644 crates/victory-hle/src/modules/net.rs create mode 100644 crates/victory-hle/src/modules/speech.rs create mode 100644 crates/victory-hle/src/modules/xg.rs create mode 100644 crates/victory-hle/src/modules/xgamesave.rs create mode 100644 crates/victory-hle/src/modules/xgameui.rs create mode 100644 crates/victory-hle/src/modules/xnetworking.rs create mode 100644 crates/victory-hle/src/modules/xpackage.rs create mode 100644 crates/victory-hle/src/modules/xstore.rs create mode 100644 crates/victory-loader/src/stacks.rs create mode 100644 crates/victory-shader/src/emit/bitcode.rs create mode 100644 crates/victory-shader/src/emit/container.rs create mode 100644 crates/victory-shader/src/emit/diff_tests.rs create mode 100644 crates/victory-shader/src/emit/host.rs create mode 100644 crates/victory-shader/src/emit/lower.rs create mode 100644 crates/victory-shader/src/emit/mod.rs create mode 100644 crates/victory-shader/src/emit/sampler.rs create mode 100644 crates/victory-shader/src/emit/shader.rs create mode 100644 crates/victory-shader/src/emit/validator.rs create mode 100644 crates/victory-shader/src/emit/wave.rs create mode 100644 crates/victory-shader/src/io.rs create mode 100644 crates/victory-shader/src/resource.rs diff --git a/.gitignore b/.gitignore index 365392f..ac9edc3 100644 --- a/.gitignore +++ b/.gitignore @@ -45,6 +45,8 @@ # Typical game data (non-exhaustive on purpose; the policy check is an allowlist) *.bin +# The one exception (docs/asset-policy.md): the BCPack format's constant tables. +!/crates/victory-formats/src/bcpack-tables.bin *.dat *.pak *.rpf diff --git a/Cargo.lock b/Cargo.lock index 73a2242..bab4a7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -320,6 +320,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opus-pure" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccd077a3f06e5fc42b04bb59f70d5fe0cdb2c119eef0e240af7e287180ee23ba" + [[package]] name = "pin-project-lite" version = "0.2.18" @@ -682,7 +688,14 @@ dependencies = [ name = "victory-gpu" version = "0.1.0" dependencies = [ + "anyhow", + "blake3", + "miniz_oxide", + "tempfile", "tracing", + "victory-formats", + "victory-pipeline", + "victory-shader", "windows", "windows-sys", ] @@ -691,11 +704,16 @@ dependencies = [ name = "victory-hle" version = "0.1.0" dependencies = [ + "miniz_oxide", + "opus-pure", "tempfile", "tracing", + "victory-formats", "victory-gpu", "victory-loader", "victory-pe", + "windows", + "windows-core", "windows-sys", ] @@ -738,6 +756,8 @@ version = "0.1.0" dependencies = [ "miniz_oxide", "thiserror", + "windows", + "windows-sys", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 900d7e7..2cf0979 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,11 +34,14 @@ toml = "1.2.2" object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } windows-sys = "0.61.2" windows = "0.62.2" +windows-core = "0.62.2" blake3 = "1.8.7" memchr = "2.8.3" miniz_oxide = "0.9.1" walkdir = "2.5.1" tempfile = "3.27.0" +# Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). +opus-pure = "0.2.4" [workspace.lints.rust] unsafe_op_in_unsafe_fn = "deny" @@ -55,3 +58,9 @@ opt-level = 2 [profile.release] debug = "line-tables-only" + +# The development build: release code generation plus the `diagnostics` +# feature (`cargo build --profile diag -p victory --features diagnostics`), +# kept in its own folder so it does not evict the plain release build. +[profile.diag] +inherits = "release" diff --git a/README.md b/README.md index bd7598d..d26f2f5 100644 --- a/README.md +++ b/README.md @@ -33,11 +33,26 @@ victory census [paths...] [--missing] [--strict] victory lib-exports [--list] victory shader-info [paths...] [--verbose] [--disasm] victory run [--execute] [--unimplemented trap|zero] [--strict] + [--console series-x|series-s] [-- ] victory config ``` Logging: `VICTORY_LOG=victory_loader=trace,info`. +Debugging `run --execute` (builds with `--features diagnostics` only): `VICTORY_STACKS=20,60` prints every thread's stack at those seconds; +`VICTORY_WATCH=<rva>,...` logs a title u32 when it changes; `VICTORY_KEYS=30:Enter,35:X` presses keys +(focus or not); `VICTORY_CRASH_SAVE=<rva>:<len>,...` saves title memory to the cache dir on a crash; +`VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title plays (our process only, from a child process); +`VICTORY_XMA_DUMP=<dir>` saves the first 32 XMA voices' context and input (`VICTORY_XMA_STREAMS=<dir>` runs the ignored `xma` test on them); +`VICTORY_D3D12_DEBUG=1` runs the host debug layer, `VICTORY_D3D12_DRED=1` adds device-removed data to a GPU failure +(the allocation a page fault hit, the commands in flight with their pipelines, user data and root views); +`VICTORY_D3D12_WARP=1` puts the host device on the software adapter (a shader's wild access cannot reset the driver); +`VICTORY_DUMP_TARGETS=1` with `VICTORY_CAPTURE` saves every render target and written texture of the frames in `VICTORY_CAPTURE_FRAMES`. +Every build appends crashes and host GPU failures to `crashes.log` in the title's data folder. + +Input: XInput pads. With none connected the keyboard is a pad while the title's window has focus: WASD/IJKL sticks, +arrows D-pad, Enter A, Backspace B, X X, Y Y, Q/E shoulders, Z/C triggers, F/H stick clicks, Esc Menu, Tab View. + ## License GPL-3.0-or-later. See [LICENSE](LICENSE). diff --git a/apps/victory/Cargo.toml b/apps/victory/Cargo.toml index a005875..5fddd5b 100644 --- a/apps/victory/Cargo.toml +++ b/apps/victory/Cargo.toml @@ -12,7 +12,7 @@ victory-core.workspace = true victory-pe.workspace = true victory-loader.workspace = true victory-hle.workspace = true -victory-shader.workspace = true +victory-shader = { workspace = true, features = ["host"] } victory-game.workspace = true anyhow.workspace = true blake3.workspace = true @@ -20,5 +20,15 @@ memchr.workspace = true clap.workspace = true walkdir.workspace = true +[features] +# Debug-level logs and the debugging switches (frame capture, stack dumps, +# the host debug layer, scripted keys). Off in a plain release build. +diagnostics = [ + "victory-core/diagnostics", + "victory-hle/diagnostics", + "victory-loader/diagnostics", + "victory-shader/diagnostics", +] + [lints] workspace = true diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index 86d9287..31392ff 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -69,7 +69,22 @@ enum Command { }, /// Run every shader found (containers, SGD5 files) through the /// translator and report what it cannot handle yet. - Translate { paths: Vec<PathBuf> }, + Translate { + paths: Vec<PathBuf>, + /// Check emitted DXIL with dxil.dll's validator (`VICTORY_DXIL`, + /// else the newest Windows SDK's). + #[arg(long)] + validate: bool, + /// Also create a host D3D12 pipeline for each emitted shader. + #[arg(long)] + pipelines: bool, + /// Print one line per program and outcome. + #[arg(long)] + list: bool, + /// Worker threads (default: every logical core). + #[arg(long)] + jobs: Option<usize>, + }, /// Prepare, map and bind a title executable; with --execute, run it. Run { exe: PathBuf, @@ -82,6 +97,13 @@ enum Command { /// Actually start the title. Without it, stop after binding. #[arg(long)] execute: bool, + /// The console model the title sees (device type, memory). + #[arg(long, value_enum, default_value_t = Console::SeriesX)] + console: Console, + /// Arguments for the title, after `--` (it reads the whole command + /// line; a title that relaunches itself passes some). + #[arg(last = true)] + title_args: Vec<String>, }, /// Show the resolved configuration and check it. Config, @@ -93,8 +115,19 @@ enum Unimplemented { Zero, } +#[derive(Clone, Copy, ValueEnum)] +enum Console { + SeriesX, + SeriesS, +} + fn main() -> Result<()> { victory_core::logging::init("info"); + // The audio recorder `run` starts for `VICTORY_AUDIO_CAPTURE`. + #[cfg(all(windows, feature = "diagnostics"))] + if victory_hle::modules::audio::capture::child() { + return Ok(()); + } let cli = Cli::parse(); match cli.command { Command::Inspect { @@ -113,13 +146,21 @@ fn main() -> Result<()> { verbose, disasm, } => shader::run(paths, verbose || disasm, disasm), - Command::Translate { paths } => translate::run(paths), + Command::Translate { + paths, + validate, + pipelines, + list, + jobs, + } => translate::run(paths, validate, pipelines, list, jobs), Command::Run { exe, unimplemented, strict, execute, - } => run::run(&exe, unimplemented, strict, execute), + console, + title_args: _, + } => run::run(&exe, unimplemented, strict, execute, console), Command::Config => show_config(), } } diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 10bac4b..5213147 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -2,14 +2,22 @@ use std::path::Path; use anyhow::{Context, Result}; -use crate::Unimplemented; +use crate::{Console, Unimplemented}; #[cfg(windows)] -pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool) -> Result<()> { +pub fn run( + exe: &Path, + unimplemented: Unimplemented, + strict: bool, + execute: bool, + console: Console, +) -> Result<()> { use std::sync::Arc; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; + // 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()?; let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; let prepared = victory_loader::prepare(&original)?; @@ -20,6 +28,7 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool } let images = cfg.cache_subdir("images")?; + victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let image = victory_loader::load(&prepared, &images)?; victory_hle::runtime::set_main_image(image.base()); victory_hle::runtime::set_image_path(image.base(), exe); @@ -46,7 +55,16 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool storage.display(), title.storage_bytes >> 20 ); + // The console's fixed drives: the package as `G:`, temporary files `T:`. + victory_hle::modules::files::mount_at('G', title_dir); + let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?; + victory_hle::modules::files::mount_at('T', &temp); victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title }); + victory_hle::console::set(match console { + Console::SeriesX => victory_hle::console::Console::SeriesX, + Console::SeriesS => victory_hle::console::Console::SeriesS, + }); + println!("console {}", victory_hle::console::current().name()); let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; for (name, dll) in &dlls { println!("title dll {name} at {:#x}", dll.base()); @@ -83,12 +101,17 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool return Ok(()); } victory_loader::report_crashes(); + victory_loader::log_crashes_to(temp.with_file_name("crashes.log")); + victory_hle::runtime::use_console_timers(); + #[cfg(feature = "diagnostics")] + diagnostics(&image, &cfg); let late = LateDlls { host: resolver.host.clone(), title_dir: title_dir.to_owned(), cache_dir: images, policy, mapped: std::sync::Mutex::new(dlls.clone()), + lock: LoaderLock::default(), }; victory_hle::runtime::set_title_dll_loader(Box::new(move |file| { late.load(file, show).map_err(|e| format!("{e:#}")) @@ -102,6 +125,60 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool Ok(()) } +/// The debugging aids (README): scheduled stack dumps, watched values and +/// memory saved on a crash. +#[cfg(all(windows, feature = "diagnostics"))] +fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) { + victory_loader::dump_stacks_on_schedule(); + victory_hle::modules::audio::capture::start(); + watch(image.base(), image.info().size_of_image as usize); + // Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those + // title ranges to `crash-<rva>.bin` in the cache dir on a crash. + let size = image.info().size_of_image as usize; + let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default(); + let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok(); + victory_loader::save_on_crash( + ranges + .split(',') + .filter_map(|r| r.split_once(':')) + .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?))) + .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size)) + .map(|(rva, len)| { + let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin")); + (image.base() + rva, len, file) + }) + .collect(), + ); +} + +/// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each +/// title+rva whenever it changes, polled every 5 ms (an engine's state, say). +#[cfg(all(windows, feature = "diagnostics"))] +fn watch(base: usize, size: usize) { + let Ok(list) = std::env::var("VICTORY_WATCH") else { + return; + }; + let rvas: Vec<usize> = list + .split(',') + .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok()) + .filter(|&rva| rva + 4 <= size) + .collect(); + std::thread::spawn(move || { + let mut seen = vec![None; rvas.len()]; + loop { + for (&rva, seen) in rvas.iter().zip(&mut seen) { + // SAFETY: four bytes inside the mapped image, checked above. + let value = unsafe { ((base + rva) as *const u32).read_volatile() }; + if *seen != Some(value) { + eprintln!("VIctory: title+{rva:#x} = {value:#x}"); + *seen = Some(value); + } + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + }); +} + /// DLLs the host or our runtime provide are never taken from the title. #[cfg(windows)] fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { @@ -118,51 +195,144 @@ struct LateDlls { policy: victory_loader::UnimplementedPolicy, /// Every title DLL mapped so far, to bind new ones against. mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>, + lock: LoaderLock, } #[cfg(windows)] impl LateDlls { - /// Maps `file` and the title DLLs it needs, binds them and runs their - /// `DllMain` on the calling thread, as the Windows loader would. + /// Every `LoadLibrary` of the title comes here first. Returns a title + /// image called `file`, mapping it and the title DLLs it needs first, + /// binding them and running their `DllMain` on the calling thread, as + /// the Windows loader would; `None` if `file` is no title image. fn load( &self, file: &str, show: impl Fn(&str, victory_loader::BindReport), ) -> Result<Option<usize>> { - use victory_hle::runtime::{image_named, set_image_path}; - // shortcut: not reentrant, so a DllMain that loads another new title - // DLL deadlocks; use a reentrant lock if a title does that. - let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner()); - let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none(); - let new = victory_loader::load_title_dll(file, &self.title_dir, &self.cache_dir, &wanted)?; - let hle = victory_hle::HleResolver::new(self.host.clone()); - let old = victory_loader::WithTitleDlls { - inner: &hle, - dlls: &mapped, - }; - let resolver = victory_loader::WithTitleDlls { - inner: &old, - dlls: &new, - }; - for (name, dll) in &new { - println!( - "title dll {name} at {:#x} (loaded by the title)", - dll.base() - ); - show(name, dll.bind_imports(&resolver, self.policy)?); - set_image_path(dll.base(), &self.title_dir.join(name)); + use victory_hle::runtime::{forget_image, image_named, set_image_path}; + // Waits while another thread initialises a DLL; a `DllMain` that + // loads another DLL re-enters. + self.lock.hold(|| { + if let Some(base) = image_named(file) { + return Ok(Some(base)); + } + let new = { + let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner()); + let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none(); + let new = victory_loader::load_title_dll( + file, + &self.title_dir, + &self.cache_dir, + &wanted, + )?; + let hle = victory_hle::HleResolver::new(self.host.clone()); + let old = victory_loader::WithTitleDlls { + inner: &hle, + dlls: &mapped, + }; + let resolver = victory_loader::WithTitleDlls { + inner: &old, + dlls: &new, + }; + for (name, dll) in &new { + println!( + "title dll {name} at {:#x} (loaded by the title)", + dll.base() + ); + show(name, dll.bind_imports(&resolver, self.policy)?); + set_image_path(dll.base(), &self.title_dir.join(name)); + } + // Visible before their `DllMain`s run, which may load more. + mapped.extend(new.iter().cloned()); + new + }; + let failed = new.iter().enumerate().find_map(|(i, (name, dll))| { + // SAFETY: bound above, dependencies attached first. + let attached = unsafe { dll.attach() }; + attached + .err() + .map(|e| (i, e.context(format!("attaching {name}")))) + }); + let Some((i, error)) = failed else { + return Ok(new.last().map(|(_, dll)| dll.base())); + }; + // As `LoadLibrary` does when a `DllMain` fails: detach what this + // load attached (the failed one too) and unmap all of it. + let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect(); + self.mapped + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|(_, d)| !bases.contains(&d.base())); + for (_, done) in new[..=i].iter().rev() { + // SAFETY: attached (or failing to) on this thread just now. + unsafe { done.detach() }; + } + for (_, dll) in new { + forget_image(dll.base()); + // SAFETY: detached, and no title code holds it yet. + unsafe { dll.unload() }; + } + Err(error) + }) + } +} + +/// The Windows loader lock's shape: one thread at a time, re-entered by +/// the thread that holds it. +#[cfg(windows)] +#[derive(Default)] +struct LoaderLock { + owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>, + free: std::sync::Condvar, +} + +#[cfg(windows)] +impl LoaderLock { + fn hold<T>(&self, f: impl FnOnce() -> T) -> T { + let me = std::thread::current().id(); + let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut owner = lock(); + while owner.0.is_some_and(|o| o != me) { + owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner()); + } + *owner = (Some(me), owner.1 + 1); } - for (name, dll) in &new { - // SAFETY: bound above, dependencies attached first. - unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; + let result = f(); + let mut owner = lock(); + owner.1 -= 1; + if owner.1 == 0 { + owner.0 = None; + self.free.notify_one(); } - let base = new.last().map(|(_, dll)| dll.base()); - mapped.extend(new); - Ok(base) + result + } +} + +#[cfg(all(test, windows))] +mod tests { + use std::sync::{Arc, Mutex}; + + #[test] + fn loader_lock_is_reentrant_and_exclusive() { + let lock = Arc::new(super::LoaderLock::default()); + assert_eq!(lock.hold(|| lock.hold(|| 7)), 7); + let order = Arc::new(Mutex::new(Vec::new())); + let other = lock.hold(|| { + let (theirs, their_order) = (lock.clone(), order.clone()); + let other = std::thread::spawn(move || { + theirs.hold(|| their_order.lock().unwrap().push(2)); + }); + std::thread::sleep(std::time::Duration::from_millis(50)); + order.lock().unwrap().push(1); + other + }); + other.join().unwrap(); + assert_eq!(*order.lock().unwrap(), [1, 2]); } } #[cfg(not(windows))] -pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> { +pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> { anyhow::bail!("running titles requires Windows") } diff --git a/apps/victory/src/shader.rs b/apps/victory/src/shader.rs index b02b056..49180ea 100644 --- a/apps/victory/src/shader.rs +++ b/apps/victory/src/shader.rs @@ -35,18 +35,21 @@ impl Source<'_> { } } -/// The records of an SGD5 file, or else every container found by its magic. +/// The packed records of SGD5 data, and every container stored as is (the +/// executable keeps some records uncompressed), found by its magic. pub(crate) fn sources(data: &[u8]) -> Vec<Source<'_>> { + let mut out: Vec<Source<'_>> = Vec::new(); if sgd5::is_sgd5(data) { - return sgd5::records(data).map(Source::Packed).collect(); + out.extend(sgd5::records(data).map(Source::Packed)); } - memchr::memmem::find_iter(data, b"DXBC") + let raw = memchr::memmem::find_iter(data, b"DXBC") .filter(|&offset| Container::parse(&data[offset..]).is_ok()) .map(|offset| Source::Raw { offset, data: &data[offset..], - }) - .collect() + }); + out.extend(raw); + out } #[derive(Default)] @@ -119,6 +122,9 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> { *t.unnamed.entry(key).or_default() += 1; } if disasm { + listing + .extend(n.layout.iter().map(|p| format!(" {p:?}"))); + listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); listing.extend( insts.iter().map(|i| format_instruction(i, n.wave64)), ); diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index f56e8fd..dcaf924 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -7,8 +7,13 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use anyhow::Result; +use victory_shader::emit::host::{self, Host}; +use victory_shader::emit::{self, validator::Validator}; use victory_shader::structure::{self, Atom, LaneExit}; -use victory_shader::{Container, FourCC, ShaderError, ir, native_programs}; +use victory_shader::{ + Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs, +}; +use victory_shader::{io, resource}; use crate::shader::{MAX_FILE, Source, sources}; @@ -26,12 +31,59 @@ struct Tally { opaque: usize, lane_branches: usize, uniform_branches: usize, + tracked: usize, + loaded: usize, + built: usize, + constant: usize, + /// Descriptors and scalar accesses with a computed address term. + dynamic: usize, + scalar: usize, + used: usize, + /// Used-resource entries whose root parameter no descriptor traces + /// to, by resource and root type. + untraced_used: BTreeMap<String, usize>, + /// Root parameters descriptors trace to that no used entry names. + unlisted: usize, + /// Vertex and pixel programs, and those whose I/O was raised. + io_programs: usize, + io_raised: usize, + interpolated: usize, + vertex_values: usize, + /// Exports by target kind. + exports: BTreeMap<&'static str, usize>, + /// Exports still packed as f16 pairs after the export patch. + compressed: usize, + /// Vertex and pixel programs every earlier stage handled, and how far + /// emission got with them. + emit_programs: usize, + emitted: usize, + validated: usize, + pipelines: usize, + /// The same for compute programs. + cs_programs: usize, + cs_emitted: usize, + cs_validated: usize, + cs_pipelines: usize, + /// The same for mesh programs. + ms_programs: usize, + ms_emitted: usize, + ms_validated: usize, + ms_pipelines: usize, /// Reason → programs stopped by it, and the first one. failed: BTreeMap<String, (usize, String)>, + /// With `--list`: one line per program and outcome. + list: bool, + lines: Vec<String>, } impl Tally { fn fail(&mut self, reason: String, example: impl FnOnce() -> String) { + if self.list { + let e = example(); + self.lines.push(format!("{e} {reason}")); + self.failed.entry(reason).or_insert((0, e)).0 += 1; + return; + } self.failed .entry(reason) .or_insert_with(|| (0, example())) @@ -50,15 +102,85 @@ impl Tally { self.opaque += other.opaque; self.lane_branches += other.lane_branches; self.uniform_branches += other.uniform_branches; + self.tracked += other.tracked; + self.loaded += other.loaded; + self.built += other.built; + self.constant += other.constant; + self.dynamic += other.dynamic; + self.scalar += other.scalar; + self.used += other.used; + for (k, n) in other.untraced_used { + *self.untraced_used.entry(k).or_default() += n; + } + self.unlisted += other.unlisted; + self.io_programs += other.io_programs; + self.io_raised += other.io_raised; + self.interpolated += other.interpolated; + self.vertex_values += other.vertex_values; + self.compressed += other.compressed; + self.emit_programs += other.emit_programs; + self.emitted += other.emitted; + self.validated += other.validated; + self.pipelines += other.pipelines; + self.cs_programs += other.cs_programs; + self.cs_emitted += other.cs_emitted; + self.cs_validated += other.cs_validated; + self.cs_pipelines += other.cs_pipelines; + self.ms_programs += other.ms_programs; + self.ms_emitted += other.ms_emitted; + self.ms_validated += other.ms_validated; + self.ms_pipelines += other.ms_pipelines; + for (k, n) in other.exports { + *self.exports.entry(k).or_default() += n; + } + self.lines.extend(other.lines); for (reason, (n, example)) in other.failed { self.failed.entry(reason).or_insert((0, example)).0 += n; } } } -pub fn run(paths: Vec<PathBuf>) -> Result<()> { +/// Emitted shaders by label, shared between threads. +type Kept = std::sync::Arc<Mutex<Vec<(String, emit::HostShader)>>>; + +/// The optional checks after emission, one set per thread. +struct Checks { + /// Shaders named in `VICTORY_PAIRS` (`vs+ps,...`, label substrings), + /// kept to build those pipelines after the walk. + keep: Option<Kept>, + validator: Option<Validator>, + host: Option<(Host, emit::HostShader)>, +} + +pub fn run( + paths: Vec<PathBuf>, + validate: bool, + pipelines: bool, + list: bool, + jobs: Option<usize>, +) -> Result<()> { let paths = crate::default_paths(paths)?; - let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + let dll = validate.then(Validator::default_path).flatten(); + if validate { + Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; + println!( + "validator {}", + dll.as_ref() + .map_or("dxil.dll".into(), |p| p.display().to_string()) + ); + } + if pipelines { + Host::new(false).map_err(anyhow::Error::msg)?; + } + let pairs: Vec<(String, String)> = std::env::var("VICTORY_PAIRS") + .unwrap_or_default() + .split(',') + .filter_map(|p| p.split_once('+')) + .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned())) + .collect(); + let kept = std::sync::Arc::new(Mutex::new(Vec::new())); + let threads = + jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); let seen = Mutex::new(HashSet::new()); let total = Mutex::new(Tally::default()); for root in &paths { @@ -77,9 +199,21 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> { std::thread::scope(|s| { for _ in 0..threads.min(jobs.len()) { s.spawn(|| { - let mut t = Tally::default(); + let mut t = Tally { + list, + ..Tally::default() + }; + let mut checks = Checks { + keep: (!pairs.is_empty()).then(|| kept.clone()), + validator: validate + .then(|| Validator::load(dll.as_deref()).ok()) + .flatten(), + host: pipelines + .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps()))) + .flatten(), + }; while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { - translate(job, entry.path(), &seen, &mut t); + translate(job, entry.path(), &seen, &mut t, &mut checks); } lock(&total).merge(t); }); @@ -107,6 +241,58 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> { t.lane_branches, t.uniform_branches ); + println!( + "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \ + {} scalar accesses; {} with a computed term)", + t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic + ); + println!( + " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed", + t.used, + t.untraced_used.values().sum::<usize>(), + t.untraced_used, + t.unlisted + ); + println!( + "I/O {} of {} vertex and pixel programs raised ({} interpolations, \ + {} vertex values; exports {:?}, {} still f16 pairs)", + t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed + ); + println!( + "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines", + t.emitted, t.emit_programs, t.validated, t.pipelines + ); + println!( + " {} emitted of {} compute programs; {} validated, {} pipelines", + t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines + ); + println!( + " {} emitted of {} mesh programs; {} validated, {} pipelines", + t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines + ); + if !pairs.is_empty() { + let host = Host::new(false).map_err(anyhow::Error::msg)?; + let kept = lock(&kept); + let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + for (v, p) in &pairs { + let made = match (find(v), find(p)) { + (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + host.mesh_pipeline(vs, ps) + } else { + host.pipeline(vs, ps) + } + .map(|_| "pipeline created".to_owned()) + .unwrap_or_else(|e| e), + _ => "not emitted".to_owned(), + }; + println!("pair {v} + {p}: {made}"); + } + } + let mut lines = t.lines; + lines.sort(); + for l in lines { + println!("{l}"); + } let mut failed: Vec<_> = t.failed.into_iter().collect(); failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n)); for (reason, (n, example)) in failed { @@ -115,16 +301,22 @@ pub fn run(paths: Vec<PathBuf>) -> Result<()> { Ok(()) } -fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, t: &mut Tally) { +fn translate( + source: &Source, + path: &Path, + seen: &Mutex<HashSet<blake3::Hash>>, + t: &mut Tally, + checks: &mut Checks, +) { let example = || format!("{}{}", path.display(), source.label()); let Some(bytes) = source.bytes() else { return t.fail("corrupt record".into(), example); }; t.containers += 1; - let Some(dxil) = Container::parse(&bytes) - .ok() - .and_then(|c| c.part(FourCC::DXIL).map(|p| p.data)) - else { + let Ok(container) = Container::parse(&bytes) else { + return t.fail("no DXIL part (SM5 or older)".into(), example); + }; + let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { return t.fail("no DXIL part (SM5 or older)".into(), example); }; if !lock(seen).insert(blake3::hash(dxil)) { @@ -137,12 +329,50 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, }; for p in programs { t.programs += 1; - match ir::build(&p.code, p.wave64, p.vgprs) { + match ir::build(&p.patched_code(), p.wave64, p.vgprs) { Ok(program) => { t.translated += 1; t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::<usize>(); - match structure::structure(&program) { - Ok(s) => tally_structured(&program, &s, t), + let res = match resource::track(&program, &p.layout, p.stage) { + Ok(r) => { + tally_resources(&p, &r, t); + Some(r) + } + Err(ShaderError::Unsupported { offset, what }) => { + t.fail(format!("resources: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }); + None + } + Err(e) => { + t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)); + None + } + }; + let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); + let compute = p.stage == HwStage::Cs; + let mut raised = None; + if graphics || compute || p.stage == HwStage::Ms { + t.io_programs += usize::from(graphics); + match io::raise(&program, &p) { + Ok(r) => { + if graphics { + tally_io(&r, t); + } + raised = Some(r); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("I/O: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }), + Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), + } + } + let structured = match structure::structure(&program) { + Ok(s) => { + tally_structured(&program, &s, t); + Some(s) + } Err(e) => { let reason = match e { ShaderError::Unsupported { what, .. } => format!("structure: {what}"), @@ -150,6 +380,22 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, e => e.to_string(), }; t.fail(reason, || format!("{} {:?}", example(), p.stage)); + None + } + }; + if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { + let label = || format!("{} {:?}", example(), p.stage); + *counter(t, p.stage, 0) += 1; + match emit::emit(&container, &p, &program, &s, &i, &r) { + Ok(shader) => { + *counter(t, p.stage, 1) += 1; + check(shader, t, checks, label); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("emit: {what}"), || { + format!("{} at {offset:#x}", label()) + }), + Err(e) => t.fail(format!("emit: {e}"), label), } } } @@ -164,6 +410,224 @@ fn translate(source: &Source, path: &Path, seen: &Mutex<HashSet<blake3::Hash>>, } } +/// Validates an emitted shader if asked to. +fn check( + mut shader: emit::HostShader, + t: &mut Tally, + checks: &mut Checks, + label: impl Fn() -> String, +) { + if let Some(keep) = &checks.keep { + lock(keep).push((label(), shader.clone())); + } + // `VICTORY_EMIT_DUMP` with `--list`: every emitted shader as a file. + if t.list + && let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") + { + let name: String = label() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect(); + let _ = std::fs::write( + format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]), + &shader.dxil, + ); + } + if let Some((h, stub_ps)) = &checks.host { + let made = match shader.stage { + HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), + HwStage::Cs => h.compute_pipeline(&shader).map(drop), + HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop), + _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)), + }; + match made { + Ok(()) => { + *counter(t, shader.stage, 3) += 1; + if t.list { + t.lines.push(format!("{} pipeline created", label())); + } + } + Err(e) => t.fail(format!("pipeline: {e}"), &label), + } + } + let Some(v) = checks.validator.as_mut() else { + return; + }; + match v.validate(&mut shader.dxil) { + Ok(()) => { + *counter(t, shader.stage, 2) += 1; + if t.list { + t.lines.push(format!("{} validated", label())); + } + } + Err(text) => { + let first = text + .lines() + .find(|l| l.contains("error")) + .unwrap_or(text.lines().next().unwrap_or("")) + .to_owned(); + if let Ok(dir) = std::env::var("VICTORY_EMIT_DUMP") { + let n = t + .failed + .get(&format!("validator: {first}")) + .map_or(0, |f| f.0); + if n < 3 { + let name = format!( + "{dir}/{}_{n}", + first + .chars() + .filter(char::is_ascii_alphanumeric) + .take(40) + .collect::<String>() + ); + let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil); + let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label())); + } + } + t.fail(format!("validator: {first}"), label); + } + } +} + +/// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated, +/// 3 pipelines. +fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize { + let [a, b, c, d] = match stage { + HwStage::Cs => [ + &mut t.cs_programs, + &mut t.cs_emitted, + &mut t.cs_validated, + &mut t.cs_pipelines, + ], + HwStage::Ms => [ + &mut t.ms_programs, + &mut t.ms_emitted, + &mut t.ms_validated, + &mut t.ms_pipelines, + ], + _ => [ + &mut t.emit_programs, + &mut t.emitted, + &mut t.validated, + &mut t.pipelines, + ], + }; + [a, b, c, d].into_iter().nth(k).expect("0 to 3") +} + +fn tally_io(r: &io::Io, t: &mut Tally) { + t.io_raised += 1; + for (_, i) in &r.interps { + match i { + io::Interp::Interpolated { .. } => t.interpolated += 1, + io::Interp::Vertex { .. } => t.vertex_values += 1, + } + } + for e in &r.exports { + let kind = match e.target { + io::Target::Color(_) => "color", + io::Target::Depth => "depth", + io::Target::Null => "null", + io::Target::Position(_) => "position", + io::Target::Param { .. } => "param", + io::Target::Unread => "unread param", + io::Target::Primitive => "primitive", + io::Target::PrimitiveParam { .. } => "primitive param", + }; + *t.exports.entry(kind).or_default() += 1; + t.compressed += usize::from(e.compressed); + } +} + +fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { + t.tracked += 1; + t.scalar += r.scalar.len(); + t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count(); + let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1); + let mut traced = HashSet::new(); + for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) { + let a = match *leaf { + resource::Source::Loaded { load, .. } => { + t.loaded += 1; + address(load) + } + resource::Source::Built { address, .. } => { + t.built += 1; + t.dynamic += usize::from(address.dynamic.is_some()); + Some(address) + } + resource::Source::Constant(_) => { + t.constant += 1; + None + } + resource::Source::Phi { .. } => unreachable!("leaves are no phis"), + }; + // Heaps hold dynamic resources, which no used entry lists; code + // tables are no root parameter. + if let Some(a) = a + && a.param != resource::CODE + && !matches!( + p.layout[a.param].root, + RootType::ResourceHeap | RootType::SamplerHeap + ) + { + traced.insert(p.layout[a.param].user_data); + } + } + // Root constants are listed as a CBV, read straight from the SGPRs. + traced.extend( + r.params + .iter() + .map(|&(_, param, _)| &p.layout[param]) + .filter(|l| l.root == RootType::Constants) + .map(|l| l.user_data), + ); + let listed: HashSet<u8> = p.used.iter().map(|u| u.user_data).collect(); + t.used += p.used.len(); + // Immediate samplers are literals in the code: the distinct sampler + // values (decoded) are matched against the listed entries, which do not + // say which value is whose. + let mut values: Vec<emit::StaticSampler> = Vec::new(); + for d in r + .descriptors + .iter() + .filter(|d| d.role == resource::Role::Sampler) + { + for leaf in d.source.leaves() { + if let resource::Source::Constant(words) = leaf + && let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)]) + { + let s = emit::StaticSampler::from_words(w); + if !values.contains(&s) { + values.push(s); + } + } + } + } + // Engines often declare equal samplers at several registers, so equal + // values may stand for several entries, but never more values than + // entries. + let immediate = p + .used + .iter() + .filter(|u| u.root == RootType::ImmediateSampler) + .count(); + let samplers_match = !values.is_empty() && values.len() <= immediate; + let matched = |u: &&victory_shader::UsedResource| { + if u.root == RootType::ImmediateSampler { + samplers_match + } else { + traced.contains(&u.user_data) + } + }; + for u in p.used.iter().filter(|u| !matched(u)) { + *t.untraced_used + .entry(format!("{:?} via {:?}", u.kind, u.root)) + .or_default() += 1; + } + t.unlisted += traced.difference(&listed).count(); +} + fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) { t.structured += 1; for (block, guards) in program.blocks.iter().zip(&s.guards) { diff --git a/crates/victory-core/Cargo.toml b/crates/victory-core/Cargo.toml index a235609..19f69d5 100644 --- a/crates/victory-core/Cargo.toml +++ b/crates/victory-core/Cargo.toml @@ -17,5 +17,9 @@ tracing-subscriber.workspace = true [dev-dependencies] tempfile.workspace = true +[features] +# Lets `VICTORY_LOG` enable debug and trace output. +diagnostics = [] + [lints] workspace = true diff --git a/crates/victory-core/src/logging.rs b/crates/victory-core/src/logging.rs index 33388fb..b417542 100644 --- a/crates/victory-core/src/logging.rs +++ b/crates/victory-core/src/logging.rs @@ -1,9 +1,21 @@ //! One tracing setup for every binary. //! //! Filter with `VICTORY_LOG` (falls back to `RUST_LOG`), e.g. -//! `VICTORY_LOG=victory_loader=trace,info`. +//! `VICTORY_LOG=victory_loader=trace,info`. Debug and trace output exist +//! only in builds with the `diagnostics` feature; a plain release build +//! logs info and above whatever the filter asks for. use tracing_subscriber::EnvFilter; +use tracing_subscriber::filter::LevelFilter; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; + +/// The most verbose level this build can log. +const CAP: LevelFilter = if cfg!(feature = "diagnostics") { + LevelFilter::TRACE +} else { + LevelFilter::INFO +}; pub fn init(default_level: &str) { let filter = std::env::var("VICTORY_LOG") @@ -11,9 +23,13 @@ pub fn init(default_level: &str) { .ok() .and_then(|v| EnvFilter::try_new(v).ok()) .unwrap_or_else(|| EnvFilter::new(default_level)); - let _ = tracing_subscriber::fmt() - .with_env_filter(filter) - .with_target(true) - .with_writer(std::io::stderr) + let _ = tracing_subscriber::registry() + .with(CAP) + .with(filter) + .with( + tracing_subscriber::fmt::layer() + .with_target(true) + .with_writer(std::io::stderr), + ) .try_init(); } diff --git a/crates/victory-formats/src/bcpack-tables.bin b/crates/victory-formats/src/bcpack-tables.bin new file mode 100644 index 0000000000000000000000000000000000000000..1e548501764588b06e2ed47aa7fed263cd797f3b GIT binary patch literal 77982 zcmb@P37lM2mH%J8+PZqH>Lq*9-3cLtJp>3LOQ+eRqW_2>=rB%HL`E4!#bss~siqw} zI;fFhBq|Oq;7mZ&h@b&c%SIvWArRI8fv^M;NPqxII^F&Meb0HXy1F|c|Ig=tANMWy z-Fx<P?z#6>nxGgIgJI<#FT3oVVGY4wezD+`;VnPvJ$vEsmVa3P(*uULeEhj9CJt|T z_|^UEhqp}My&*lk<>LcaB!;*Ab#VUhhG1YY9MLj3IAT!n|EneFu%iOss#8`UfASF( z4Z&+?uRF12|H_ujFBmxCH!YPdU-{3Mj#)CMvSs|w7tdQ#SJ`rNZ_A<0*~*qzA31#L zE5n$*bj#h1Yb(11r|<ly>@ZZpxdWFZhRfrH!EwRxmVQa>|3^#E79C}pjydr2`<*#$ zMuqNAoO|6N|G3Zhn#)~+c_)41$bo4e%@4IKJ!9<rH`-QK54GgZ%`cihWo2fl<(n5B z(eb@;-%bv-Z2xhv@JEHORxq;ach4SvcCONZZ+hU0>Ay`@pbDPdvaE5<Fz$EnekD~s ztYy{Ud-YraIM`(p`+sc-3gsgrd+ONMF{_&nX=p0z{!3FHn0VT_8yXguxj%SD-PB)C zys+UHWox)%)}Qygc*?&NPA&V(qJ?)HvaI!z`cupDSbg%nM^0#4Q}fp{k=y<uv7p#; za@8$mk!}BKY0+yFev=w9;AQ_ct9?o1hC~@vaLnqf4nIEk$qMeLZFr>Rt6{35rSMiy z)wE#}x@quedoCjnUX3L7PAx%I#bHz)R<o^odG&_eimGo#x^K*XqW&{=*Va5%H9g|~ z_NGrYezWk=x>D6c5%<d`j32kL>9+cXRo6!T^2@eMCZ9F#FZuUmuZ;*O?Z0!{=83h1 zP3cXMJidSAKO7LWbmV8GJ{Gln?1W2ZZ*1LJ`_V8q;LRWHnK!<5X71%674`Y&uid_A z-Gr-Bv&!-~q-V$c&*m4%>tbFHT>IRNC8_!f30?Zu^s2GLB=mGyKJlp0Ekas(h=QM{ zznA`6dU5)d)caB=8249Xzmz>Jdt+vO`kzvl821g;zst?e9ar^>%+k~r13tFyi?tWm zY|nin+nPGfTAnT3nSW3H^);KaS0~pSXZMVGz3GC6^XsxzuZ3T*mXA)JGhx=4Am5X1 z3J<lG&+hwr>w6|_&tH%^IN=8T+1dX#bIFv8^Z%LpYT%;3<%C;iKij&w_LMM=Iv@Y! zJqvbC`EB;cWqF+O{Ri8>*fi5@%DMmk{mB`PDQqm3;=c}@WD*@}`E!NDBAJCkT6qNP z!h6Ft;Vt3S;n%_$;g#yPK6zJib#g`Wqsgt|obWwrX-@A+ZAkqnH7)hw<e}l4;;bk0 zmCVtZ+tNEz*C*@4pR45uRUfE&K07`8So+oE1BuV5WqQrZ>fO0NR^60IrM{LpS}iN; zd+UB&yP~?7y+2u<7^jvmHSKEHoxi$vXLeEYvH%0VY~uQH?aeFeZ_mCroG;#j;L3d` zwtZ~EYx(mtGZQt|a_dn)Iq;m8J@p%san$+s>HmB5XIgK{6(R`)!LCa#YY&_H%MuBK z6Sf}J_>D+jF0;;I@-Ydy@G8!qNt~1TbmFYU#}cO`79^Sy_Xk@On-k9`HYDy&{37v{ z#N@=)!FR&$@ay5{!uN*_;kAkJiGK}FOTI6;AUQd?DZC(jG*Oi}EjTrGY-+#M>&Z(b z)t!l#f+K?~(-);rP4}mkrp`=;;U9v@!KY=H8#5osoSgo1a&zJvL2d9-?%TONRsGph zGX2T_PMjPhgKO%x)xK2ITK%Eyv&rd+DdJ~&Q)6RY;a9c0vh$MvCG$@NmrXf%;=N;z z$bUWiO2VVgKg~LBzXvDZkbff88A)K<8M%2Uw-$5Tqvu4hZS`q~PtNUAewGkM$R`n; zc5N{DvycAIXRi6t*+0DbQ*V6arT_ZyFMs|IyMOijSDyIlm=iv@J%8%qU%vZ*zd!xk z|G4tX^*?y=zkmDL=RS60_1_KrDc!ei;-fw9z4|8y{`AwWo4+#S|9or3j!#^_<kg#= zAN#po-~I8MAAirX$Bz2NzihbligEut?Vg6u|8df@{qH~i!7p9-g<pSQ%gayx>swF# zZqXrM-1(hDANh~{?pwX*nb%+Y-h>n1*Yf>&*Ui7-s;5u6bL(0EzV8{oIqBXh_n*J9 z=0ivR^`SYd&b+MtlmGlrm)~*DCHsH#n0*q>Yi3_u$YoOh*0DUh^x?I2=QVzP@gJHV ze_`r3{&I5rVYl41DS7a^uXUGdXZ`2G3vR#d=yM+ktBQX<?ufR@7tQRvb-}UYr}rK- zw=4MSX@^fc{_NAgd|vh|pKc2aiH0L)?{nNq=g&$`ZJd7W38#MQ!)JZy$P?2`nhyKY zQK^o7Px)f=e#gxD<cv>zaLgCREzNv<?4Sg=J^#_4edNDB{HY(Fea&Zn^gsXbM$h5Z zcmHbllJp55Jax=VzkKE9pa1@euO9!8KWJDs?Y&nIZ2ME+#GgL*e?E5Oj@G|>^?)nC zed)^gjD2za-+y^yea-35cBB&j{qe$YSAAgDXE#r};=3!p_2wsjJ>l~+mjC3@2T%OU z_dlIGD|6uWufM<LzC}0fdEe)L{QS}z#y$OoEq^@pl<ysL$ZO3z`=5IG!ngk8U-o_G zq<=r-$$$OD@Ba5oN3A~pk$W~gHf6v2zw^axW8K=t-#Bk-xPNi>K9{Wd=c<dpdCosw z*7nf6tLFda-mQ1eDqWYX{m_wT&iU&nFTdm9?ys%;`lc7!|MGCtVKYxY_VGXb+eOol zzUx14=^TH=ap&H)@PV$$b8lbp=L>E<sQ0VEw9^hhK5YB)>1Q|WdrJ1aFCF#8{Uogu z&pNClb>xSpADf(Y()qLZ`QVrtpBVRrrI}-z=X~<GBO0d`5}*DGvi<nj;H!sEJMHY` ztn(VOVcYSE!s%b$=hL%~`bv7qzDJ(Y_@R^bn|j3b)R#VdT+<hiJ^xdOoj9lCgioH8 zId$obPc$DhZp;@xIQHY+i@Fzf&+newJ*Rti_pI)Ny7%wiw|k%NDczI0$8|S#*LT-- zS9NE*!xMw|2PXt)1zn4}7IYombwt<UT?cg?*fpcOz5D3y!@Cdep3&XXJ-$2No$F4X z7MvV(E$lk7>)@{ay7uXs)HSiIsjI%LrYqCCsCQ29fxY|oHuTnX&h0#^b5{3)?jyPn z=x*(9?yl|*&JDWebsf?*y=!vU_^y0cwkzm8vUf&rq4Vg@BRUW4+`qH6b8_d{&U|OC zGh3=JRhJUo^STe|ZtE^|r%nyJ=5)>Mn$p$WRoj*5J+!y6b6)3Rod<Nbbx!JR=&bHc zm1;_1@8P|N^tSen?alY5dNtj2AJx5I_n7YV@j=(2T~oWpbXD~p-8-#we&->b`*u$0 zZ0xKm<x9EVqk8x6o!r~ho9?xss307b?jyUWcGsLAbj|8&=_+)Ey)!!(bRN_>wR2o& zO=nO__Rj8|+S}Y)k%h)1{n~w4_k`|5*HK;5x*B@t_m1g2vU5h~gwEPhZEt(;LA~R9 zYfEoC76{#kb~l_EbnV|Ywkz2?u5)(hw9cl^bSc$4t9L^0P)ar&X~k3bf!(!T^SfHR za=iz1>Bzv(TC7UC=wdx32UqMhpMU?o8KVUE_M^buR4Oud}%`?48>?rMIdA#XH`1 zPyhR%Yu~QA-hDa`?wr_}>0Q{{(p%0*-*KqD?4EW((ACzJ>TK_v-dR^l_wLu5``e?2 zdUQ|jYVVrRdqn4<o#RV&y@&OVSYZzJ-1}Yk#ICtrjlFH1Gdt@`LGQ%gy?1-t*6y)g zv%9K07j?FDCVLO=Eobm=J7C0%?#8YIy3(D8caAAl^-db`@?AY*(1{VHVNz>;T5EDd zN##;uDjZponWS1rqDobz^db=?lS(+OY8nl~R3Z`55VewwBocH~s~0tBQdbW_;2qCY z-BZ&wX?0JknUm6lB-IE=aHoNeO(3%QEM#a{Wlh&)#E6XqL{zf%S>S4v8p;p~t*wQ& zRyCQ|$COnyRH-lh)b3ReqAcPK8e+<_wdqtAJWj7+OeQn68IfGs%8*=RRk}J27Q=*? zgd?3xrn1Pl5*vNtO)ymGC?12Lsy?mm3>>OKkS$~d*E*_?i#d@fOe^H4<V7e*Vvd8V zLKe!9D{pib>&Z-w<<${oMxnPRQ$w;fI6;tW%9VL@s)RJC%4fy2Q6))8BUZE3$xIc5 z`B=SH*JO3GnrU<GyXFH)UGgpK&HD;&I+Zb#f>z$jK7n8yqc>4&+LIjWvw{GIvW#_~ zYsexquwW^ssUT6^oI}18$mgYs6amK+m%P2q)@R%hOb7N>RAlNh7^^Tu5DdQbrWZgo zsv?f-Tk31Z));OVIzy7xW2z<0N?L)PD`Ya&PMMx!-lTasm*eKF;Uc<bY;_`pwhDVl zCWT5KU>w^3M_Fhq2w~jUq^Y+x<7!M7*3lS24)s&&>n7A1y^*~1Dp6?7*H5Z5+)*oi z^R0QXnHcoWXbXbE)B<!NoeBnP#@CqjN%Kw=0D^{n3c1FdQNW|CBFMMYOFG~kYLoRf zW@W6vjXA(3YA4j1HXXauoeUcHZLFJASLRqRA*XSAgTxlW1-fp7Kpm?Z-Bcq&5WToi zkfFiM43Vl7_G!&eu;>ZC7{2^1Q=1mChQ)yBB>7?`5w%WV5Qtvv*K7>zUg{>+)=C`| zHMj>sS#70;^b(APw!9=6nJr+=H*(E67!o!B@D|~TH(U-H0P9!DH(yn#LVA^@Fs-3x zLaoy?#9MW9R$i!)W&fc^{p7l|ELH6S0&x5zk!z}w!$eK^okW*N)Q+z)ZJGx{gcaG2 zdrL%_x7JOrBZ6Zh>KQ|je3Pic4F|p`RduOsja#1&HiqOwRdx8L1mOzizII|Q5yo19 ztocf{X-1=I$VqVef}}iFQpa@F-TLxg9LozGfcNKZbwie@AxE?tNlB4F!PZpZT@8{% zPMCrzz^IMp`YCmeD(=ZO7;`{VzO~-ia!XNbB2eUFf+7q?x&u<}*j!rXEBVt&V+1>y zlpo7}hp?fkFqBOSf(C)aI%=X#HqC63d-`aDV$@YP5j`Coc)aBDDG6S~UA%5`N!gj^ z0FhvEU1I|5qG5UilW#@QF#JN%2ncb3p~5~5DOuDI1hXh<2#!_g9$QeOc7w9!3$(%k z@~9hMUDI6U(zSMIP*BZ;RhoHS5=O4ZH1FR8WqJ=4v{EHs`7zj{qP8F*F3jIz7*6<@ z1DkQrxT8VPjMJ2p)Fr7hOx*?zQ}cDmR|S$(;aDB36#JqUy+bL9nlYMVv4{vlXjesz zA-%<_2x`YwYl>r(jn<7yLa|Q)Uw3B1u{<Uv6B7j$iBMIH<1y7yl=D^tpt+?++JrI& z#IzJz>kJz@b{Sw%$*QD$hz8p9pIs##IYGpl*#f}wQ);ClWa_<aP#|MaBrrM9EDosB zMOL$^@H<R<kr3R-V<RrCxoK)^Z7aE)8zmHoN1=-8HJV)b@>s=(m?wq{Sz^oq&5AJG zMogH5vh`u6)}-aV%yEOJ{hD%$sYV!_n1mB`6Kn87!(@_xmPBiNOY6cZ5pM>Q4r31< z!#w1D&10Zp+^lgH`xtG-n9m>3S~IrA{Q@d{RDNo~Z6|aIg~}qsP+k~oQvhPQHSJSh zm{JQeW6!~d3Wt)fw_1|`g-KaoRo-(s6NH;f{p8xJ0%@DU#Mls%d?=ALFIBr+pdi#w ztf_8P>~lI9L#b(Nsc97#Mg)Xe8F%Pd=8LjD_?X)9wPt-hAs5a;vM{BlZk#eEe~uy4 zjLnh2M%dzjPpDVeabz}}lfp|?LlhCshRq5ar`FYssS+BSthj<!lxdpPjbmrHO5KDS z#dX~Px?CC#Zplw=HG8C!QJ9byHVC9T8WxC=!H|R3PN=aL(MfL-^^<C|b>>55zyeg= zkjdpuL)IEGDGv~6oVb#P#(nZimj%*_v99+`Z7ul&TSbt+h$wE<^e=iV3WGF@Nb?nq z=Kh7Tt+g|~FX$q*Htf?{Uq8hdh^P_({7tE<L$GEzPmDcejI4zBV2QdXs~a;u-1=yY ztXGjHOjM6yjbA2%+iX>scGl=er8HN!)>Vr#HB^L%hN-pnlX5~wrwC&ZjGsMTK{4uE zhCTkUadngN3-7FUXlR^NTTp5(PF<MRU1?@ERbXy03B(`-S1FI-*GMb?2xIqeX&l#r zU(z|Qg;wRM3jB-(qg!C}egz^T!>rxRM{__nTjy3ytG`Lg`pAEy7N|q9(mb;?ovaA9 zfH%)5)J+f<UU&hD!jwAMnQr5*Mu&#ijwhbMfguxtiMk0|3CkDMDjiwXy$H}W;KTh4 z6%%HUms!GAWoa7QQW%GZ5&~PUV-If0<%tCPPh;a6CKO~?8pIX(6~^Z3G`|f|AYp2T zY^utTBdQp)4r=neiTSpAG#^#K2MW~bIs&_4qXkh-o;%U<hscL$R;h2y)YOyWMM404 zkj&>=vbh#(EwdK{EwhtT4uLI;7BT$lrgY61%YuMs6iU`(T3f~{_R&cLpqe*LlUi$< zOb*sBYMyxHgm^BjuoS5Wy-@%xrE(E(scMTF{tV&r`6(^+M@>eX^g;hzYn!TSh+ISV z$bC&qYc@Z{EL5OP&1#i4ZM}(fAXO(pYiwz)KFF+^M{C!+>ajI852*o+ywR(%jV(?4 z!&}+AdC|~Ti~Ta#c++r|nhAAPO`Z)xs9HER&YqI5o?^EZr@Dr8E}k~&<*~JHO1`SO zhQVUjWB~XnM^Bn`!~`?x_?52p`IemNBElmG8YHW0+P7ecVhYq+e|Sr7np>)RBPFBk zh?aWI$1VZLwNf))IZSzf$NI|63gfD)>n+ehm=l*wjytTSd3p;DNntpIPn<JeYSxX- zLr#@)&(@mZ>y`vF{gee$%t|yAsT<?k5g1>as*%eM30N;=XVta&@?M40oz$wiu6k^3 z!sa9+z~ojK*HWJ$OEm7F4EWUwT#8&)T<W4as2<;vIhY@pIDWq-s}5?(Ol&c$gWaf% zYint!MVoYXn~=yA_zJ9Xfa&6-N8RMAbWPM1nfZI=zuM|D1xrNMCL$WfW~*ylGchV% zmA#S$4aXLYOSk0Gt~b4jA=QtwohNJ230lPI*y;J^HYkhi*RNVbYRypYDop54t6R%q z=<Q%3MShX-l@Hv-lBkVVNoo;fDttH3s86OPQIn)Mi3V-p6{c&Rcllbg`edhMs#-{G z%9NoC?Nw+wJ(x(1DCnWGSU;@{MszFhI0=iDLTe#EZ7=;|-pkiTg<w&BaBw6%<T9)* zDkSJ9;E^3gh(=tLa^>3^2S?EdJ`+{c-{@0zHWF{_JzUj42p8oOBJpkM!|;%gmP>49 z?apR0nQS(r95J?!O6dt^nzZ@rUl%#pLD?3D@u~;lwH2O!dL(^%h0&C`7IcBR@WPS( z)Cg(T7uXK3?~RfDTqY(P<P$g_eQ!cF9Hi6PfI6HDJuS)y?R$}nK)4Y?fJ)e&PqgO; z_l(5r7~L}I$9{8bp=M;aVRmKk%novIrnOmHS<3>6ZnVTp<&qbEeI!7mPbYY#s}fml zbL{ThOFt7$+%p7kA-QX0KhZ?CP%b9te06qYKSEh$b$z_{%E*2I5<I7n_-}qx%W_^e zmDQ>!n@PyX%nQn9;CgE-jIpIfHk%Dp?S!qwbE-fyDd^I9(cbVzB0)4kYEfP+2Lo@@ z&uvTcQxX)W!>{i}&cpo_KWZ=3yty}cLPs$%>Pvuj1@~^x>f_p#J&)UeoPO`I^;Jz~ zQPCW%?fVgSDn1HHnd&G$hEtbJR<-9dV!3}LeU8vXVno)o=hby|KWM{cV*Kg$d{TDb zm(FAZ{iol*`Ac(MgXE{0=A3pIM)PZU%lcJ}X_vp{2l|Kjb+#)&*)4w5QpmiP(MJdH z5{bYqeq{y-&}(6zLVj{#!l-x;1L!~IyM9rjTBbiL{#lPW4yiZx+>$T6Hd1~b1&uTZ zYkpK1*-amiTt3(<oTV1#6*}_TXUu3XK{oHz_uGUVh_F&<DdeXYa<7jB2n=|jA3Dh_ zYLH21-;8B~TqGh^Q|2CaRd+tIg^AJnfL~vKy9CpV@~QSha+JM*PX*EpcXm-hT}RuC zUY6%y$n?1J>MQ8Vt87NI!$><VOfKa2Ele0p%dj-l$j{|Bn7+%+)g}UnSMB+oFOHOp zQRgQyuGN_7Bliw|X#pc>Il84vi>AHCaTFF;>~Bh8=O*G0#ZVatF^Q0)5-w^;wAVI2 zKZ-t-Wv1ZqQqHTXrfvre+6#@>6gzB}0j3q46Ycf+nhLCj$>cYLR&uFNwAYQ+8+q(d zRR-9cdz(1q`bT!uWIJ+he0CHcqL&Q`s|ZKIG*B9$5S7)onLbKpwS$;V$5u*UMmTQI zyPq2c&uq%<-m=7GyZFf0S1H%X$Tjc}n;+oUXwwNBG`ZA;Z;giM?_q&bCwrEizD=Ao zQQB!z`=shZb-1S@u7%j^NIp`F8l>WIuk)n<8Ew$#ez`k6nm)&gOrSJuZ%Qnxuic)( z@Kvx8OhVP@r#Edm=B<2U6dyzM8FIe5Na3UXT)50HWiqzk;PG_dF|JBnO*xx{u4jtj zhQ_eHHqqWV<^}0jx(&2qbN#wrrP~-T^I%h9$J_90Yf0c0_ATTm76yYbo6b~LM>uqr zb0pduGNb(nfkcJg&5QCia*<JTVO<ebk*$u{Rbkw-#1#oTA!#RwGb4*W@M`~gwEWc1 z0h$;UpC=Xa`xORla+d56T}C?8o`WP31vjig8;7Z?<VD{cB^R7tCC2ab>Kmi{!zB{w zL!cWL<u!F>`WR}1F&d$cl?FWC5r-D#`x$6eC)7%};ibJPY_DtCBw0u%0X39Zd`6A< zFdC3w{hOOd@d3XT)%>z1eB5w(MsN6_%Q`wkn)hY*4Z$wsLq;W%iTa~{_2uig$<K_$ zJ3=nWhJ6||Pd~9~WIw0Pb6KQq`C9F`z2(J`jat02bx%t^z2WWP89xZOUGcttpIw<W z>m&2u@}xx{@n>o>xip2lN5YeEaEo#Y+Z*w>s*(L7vDwA=kY6s!r+1PMp*M7<DqNL4 zb&nqvcH~FG1EH+Jti$dV?-%Cxe@x_t%x*F%%qk0gSPgK&OB~;)Fk{R}crYPzaZAv> zt&bXJycNeaH33?1h8L4x!|S8<3r3AG0Sa&P{>{?wlY7yx^AST0vwU-YaR4RIrX{QR zNZYz1?!$G=qC$gG=uzwBSRd$3C1`HX*R~fXKO;cQYwTDlKI<gHuzbXWd}M!xX^qRi zHBv4nH=Q)j<d;}fmuRmU*d_W5zI$(4^QGH?VO3{eM;(4hC{3uQshVCDU%>9wRIPRB z!hE`SG+ql2MkxG>2~E}cZ6o^$uMuK+)h}F#9c;W$?kK#P#})6H*99o%!LB*2D>P3( zkA9dZC1#EAcxn*=xgeiKb>YJ1siX7@zf>>u6CX`Yk0}gU{E2Lu{N79p9w_0WrbK&n z-D^g*o-tC7yY@PQr@Vb;AwRBg;2xAuC*CRnhK+K326BE%U9O;Y%E*bj+z%R6`R&i7 zy1r5KzFtX{LzTQ~Vd0<&W-F2ia^&80RS{3Cq>uK(w7tX^^d>qZL-6>wMY$F0WS^tq z+4w=b5Go3*+MAT;>^<K#-NCnNs=Y>2dN3+4##yMbuoH_K6AQ<r_A;LXXDDW6+Z&SY z4U>&FqYqxKmQ}%kpfID5pHOIcS;EpnWT;m3vfHZm#<c$HH=T)5u?%b|i|`t_Ai1y* zF32C-Cvyo^^*zR}VuAQQRMSe<+UxS$G&L(iyWBAOk$8QbchIPOGFF-67w4J>7uL^c z8tF&ah}2L9TeYxWU0X-xC8k^SYaFTjf<ibye@qE|!zn&QMP>pSrxM9V<$vw@^dNH# zh4B>dTHtln1zH3o7FKV20DdcJ#GJ(UP+8O%E~uXQ1PxFFOyom9g9|5mmu;_2x7TMi zznS<9vBz<H?<{LT*j}T&eb2*{IJqywGx=!DBI#}Hv^SWy#HRT=*JzCr$2R5nEy1Fy zoqH^<Sk9)nAP<H%6^Tc7013jopenT+<`An`$ilmIau#4C3>S_`ENo8hHu*|=FrsR_ z8a(wy=E;R)6(`5-#OrBNfpXT<!Ut3@;|>|8Z?`*EqBj+5M20b8&`0;ew7m8$21S>4 z8&&8lY8YU^IWf3ezu3~g-i3;}#Cwk$7Poj0Zm;=CHOW*sIzKh>#uTfs;%PW9Tl0pj z%HmHs4uMPnBbZ@QdBnon3HpJY$8ih`*+5rW0=g}XFXRs>9I{6uBR{B!_s~Z?AUzHO z{pui_&pdNC3~TDJc?+IgirA|2p<lD<S3AXjA89WTr(yzyglv1A{CDS*qxwZcrw{5) zF4Q`uFii=$>w@@!Mf2Wp>%uFO%lNvN^~&Z2H7T}6V<NWcuQ-%yZ+P`7bVhNqI77cW zfKxR?{@j$^Ci$^mv>c2zWH}C*WRm=zPCsY6@Is&8yq~(UHm-<Q`ZX#0T=_ZcNAe3g z&>9^gS5BE)*qqy9&pJUPwr@JKMrVBD;S*%1pF0a&UYV;c$Ayz}owP9DyfB~LIU29v z2p-UkfcE-uepTxzeHdQ-;-(C9K~rL3!#?Xq!jpciKqB(1)_lIGZtM#lg<yjy<m)K- zwF+wXBMMLNMqg5ws(eZJLmZ$Nb=M~5(M|L2R3ObH1V>f-%E~526yGO2W->8_sy+7v zp92KN*2j{xUF+Km)$N7Xo<^my40Vg%EbKxWpu_fYiAA-AQTyIeKM_VxF(iALH=*WL zvrYjLO5Z~@O$er*ZOnoyrN)iVNG{~yqQ&+EB)ce&)QvqXP`oe9e~kP9KeHUs@<ekY zfkG}}I7yq-?S=l=eVu|8+I&!+6W{@Olciso)=S(|RWL14I#l2!xlndr-?zr_D!6!# zXnCT>iALe2)-7mG>A%;EPXnqE4mhICpeZro7u#R^HrkKzshbrrTQ3Qs(ejPP=f$qY zNY9NGU+ClEg<IvZ&4~rg2aJI(Rm)=;WBnX6lCeDEsQiwem{r(?W26Bb6&qsvfBB|A zsFgK9RM{^f_me$P)l*4bVnOwh_*lqVn#x=k!?CNLlI>%|_UeTX$;vd+a~E~fo1qHg zhG`A@{`Q{Vcz*3Zj4WLqn7rF!Zec#PAU|h<jW!-6N6FHNkC5vkew!tlmmdO#*}iVb zwZUt!kRfiTylFu$T;smz^Oh_|e3~IgO4CK~+Urjm>E`;rh03g&oIQ{2n*j|f*ptf{ zNWfHsRprI=#sq&F36L&^8uYqJ%^x2w7+1SH@=3*AVk+E6@PI3T^|I%Mbs6nPV0LI0 z3$u7&=&YL<Mt%$P&;3=Z)tto~>{akIvZ89U>98rOJ(6xY9)Q>3I8N|ZFKo)T*H3#A zn{yj<n=yC-7_l297v#ga4KuDm2WBhIho#~M(-{wCSK-mM``v8(s;}oy@awQ*{F#Nd znlGoVW8RPL9{e#vT_I0-XO;4UftO=Duy2lL2X4m>Pf<tt>Ab>+_7@xR`d9G?&-Sk_ zW^bZ`xI4f3IQhKg?6HrS9|<4wVN5csO^b!qHQNME^RIlEu{Hraq&WWRS6cd{toc&H zg+~2n1wRwdL(lW_;gJnzUP;bJ+@O=fgyaXC^z_1h*uv^(o3UX!MAaA(E0AWTZegK% zLBj#H8U-TJul0;<Mv(Mg)w>4C`8lN$2WtN%idUdPFhj-Q@vki=)-`V#Y0pj{bTX&w zM|ACVx%Rs3Te6q(np@Cp-hvUQPW$%@nv)Bf4yl4Bk!ZRw`9Yn!#pvaf;hgaue=+?= zHihk|13lf>d6?grIJ$A|uhE6U)JgUtzJcd4TzHbnd0E+2VnAXZiq9rz#|dI+3^gCk zt6g_3daJC!sI19(<7Lvd_oFLBN5}=X;~nC|^UjHnBV3VRkzZj1^aCq+We2q%(w`sz z7W-Fty5-~Q5%*FatKWmP<*UA<xn9B*MUg$Ii_N>S{E~Afg-1?q9JN0bzjt-}?+;q@ z8%si_HHYj^N`obnM-)qqK<VS~WcD>-v~S(Wni|g=G2EodZ}Bu(vT=T6@gVNQH90pI zE^M54i`)nc6lQz^dy3@3U}DGINy;N?u`Bz&9_0rn=NP_qJX-68!pENyU&vL(L#1S= zZmti#(!WY#pY<beXj)6KkZ0YkdyLpRaiz4(ub(`>zJH7H%X}&P#<O~fGuMgwY4adF zGBf{{k^W)a<HZI|`*qW*@?*6=lF0B0>|U7N-<-yXo4I4Pe|6mN<2^ImHv>1IWP?_9 z@B8;B==WIImF;&jEvR3Ve?{PG<`>fQ3&-7{cS0>WBVG-Htl0j<kmB>0#Qbz&v&<eF zH9N)MgbE^K+YizUs+04o=1kNGvwIgaKjQTQT+@f*=~2}mdPZ{d-$t1HjE@L4u=RU} zqYL5O!u3~U#wuzg3ewLW>0%|nAfH@Nf9zZI!R(!9JjILqh~~@rx%B*8gVv31OT;&9 z3_jE|R)^w!U3g^bs2zsRbmBPz(9G_zJ<8F_W9#;m5H5rndeI7(bd67``OV?c%}Wjv zs7TK0Bc>dP&Hz>+e?DUJf&pa9yo(R(Hi8$$D<r6Wnj<oAU5A|G#hO@(<DVf0X6oov zcvLd9?+~aYuAqvl37X$uO>Nw~85kx*SDf3G^%aRS+6nW<q>mm`_eP{QbZ6Bq9+=Ki zYVJh&<*~0LUgRQNrZIJhV>8!a{M<tI(S;Km#V7eqxdNw>#-;_eH4ADBqks1h!^1=M zAM^B~^`Fx$ihPk9o*q*LZBAgz+{TGVHO)Zxnpe%|2rq7B(KtytnOc|&=Z|lAMQkvi zSLhe94f)cfqsG_I8Go35Lp+p6L|`Dxcm;d?{Oaud>P>&C5Hp}{KL>cwOTUXcIaij8 zzbW#JFC;3m(?4CoS;I9`vcHrJf4ofG=qK}3a`Qy^o$s>uu9}Rh5bL$pgQ|*a)bIW{ z!ed?!%->xDR0{DZsoCbT@6%2}nj$3m>z|hMFXnXB^}YJynWpOZ7-~tUAG!>hQNNE( zr&s-uJ9J`EK&PKwW3-4?r#lmF|Al^=q~EGr)vt!r>5W$zG0_Q_FRrlFFZiT0T7I~K z*8)zMQ-DY&Z(PL-qPH6Li@0>Q_uoa0Mr2Iq>K?5AA!ErPZLB)|>_$mbYZ~bBy7EdJ zuNGjz{C$GMx>c}5fmELU^OZa)|5FWwAxJ-W7sS{eQK+0lQL^{fprSa(VffswNZwl1 zmkrG;mkV_k0`02LJH0mxXoLsWGU+F}>>`)ZH)d%$4BrxkNWx|nKqmkELwJ(pH2^w9 z;k8MDMJxU+U3_19;6eRdhId>mrr5kr3V#yF_bVfhX2A&3&RYc6Av^TU?n}T3j(C>q z>7nyb$tGV|2cB4tGS+bA_aO}WWFGi^^3rR7K`R=f-haJ~koH8WX?f*k>WpaE05Rt7 zP#^SU>rhEqTDlyj(279l4-2HzE5D`Q$su|&*;Jp+pk@sT@fjvwyGWXl_J-=CHzO5u zb6`me>EGa^=u2lTDt&t|6e>c~Xk{HTB=JXCbV;wiQkc~=R9AmL78UO$yztjIai=0I z8F7<MZhXw1nE)clSPel<v$>Wt>XUfvP9j1mSwM}h>1S>h=jP#%M6P)A@8taa%D7wy zo^{9~kj*lQ^S<>%FwlA;QM}Ol=tM+QOZMkK6g2j`HAo!<{nbra6BceERxSDeh1A&J z$vQS&9Kk_?W~<39^noX#7pIw^RsUKL9O?l)^}ORs`l!Hz)~e}L-&>+fHs-tEz`SEM z^b5K6g`hc;N!=C=Qtl=Rsn7Gz8xGzwm#VD#mV0DbsNrMR8x9H3{8@55_)?=em6E}x z%zmzymMK!GwjhD?+T*fzYm;DcyYSD~h#kurZLO(}*DN;!z)L_OUTWWhLdFY_N;W%D z@z6MT(sj-$hD!=&c1~rlv~0y}j^3|5fHfj5qgiMleL(70;8Ard603^@0Ayq`kebKe zh|3@=YY_!^-)v7tfro|FKaFsiiV^Pa$MG}F*|j9Eyo*`GO<qw@Zwh~m=Mw%A0=k|2 z9r$HN*XE?0HJvHwkBmSsaJ=04Yk~$cj?2`aNl@BbvE+(V*z#BG+3n3o9s80g086k4 zkj-w9r(|Sn@=XzgsPDR+zR&?Ou^zs97s;)u!Z=A}8tx!!MMadQ(|ucnM`6J>Rz+tf z9JfaTKz_nyH8J~I0kgsgH2A$uL|UIS<auhmbGbT*4is(iH9h_!J&7EnP9!DLSKJk1 zTT$gcr9B+;HrYRL65;kOK+{O)L=QLJiD^r+&|`hZJ&BBEEn-rVRoiy$fkK%@J~O}u z{R~;d6gen@mRNK-Q53-PZn~!@-0yG8=hS|!q91GoQaWYk9VUkGL8=Wq;80{te#+*A z$PQ-w&fo%CBN4~EKgcF6HW5mtgT$Qi3??q?KPyuo)c|Raw^(d8owCdkSi)r8YPNFW z34Vn&^E#__i#_xsFdn|2fwPlFDde|Ll~@QfW_(PThjuFzm|6wLoaOL0Z7vXa5h{gc z!xN4{4uAnC(2pI|yrSO90#%{%K<yz5sHj0l$f0(fP~y3!dqjTEl?FpJ0|VMm{kHzv zh>RmzL#TB^v$4bWStRQZ{TL>hl0A|HVYMPQIUO?tHJy3yQQ{af(vZpZz}u0N#RRdz z{Q=L21gy>GP5}t_ALDP(pasbE?1!O@B6Jc*BKyd1WY3HeL8kij_$lHJcKFj1x`yHI z2Zqh2B6sm2#6!*hQCQ3-KfFi!mjkHcQ4+yHIbjc^Fdc#|3q0<-1`uIO+z`;T16QUx zrZ9Zp`^amE1)TV6DF1OQkxdZHS*4Ej39H~h028u7jn1YQeS;P+P%k@Nh&`BKL<V~K zz@G$DU(ggJJZOa<{Rl6_K3Y@`874kfPo$Mtuo&~a_pQ?n5aXIS=Te0MR7@o*W!fJR zLURalVWnxScrwkQ8F89D_2(Ee)31JUC<6?_zkeQiNqP2FN5c~D)8C*G$z`(B>Dp!} z7YGSbLo{69f=~;pioD~2P0&oFSHbf#cfJmFgfjYJE#Lm7%Nv=)NFx0E7WIkz#7sIf zeUIQuyu?F{ArW3xM3$1i!JujJ4F2Mg{<FgEjJ5a!eqnQl1o7D`T?U*rUP;8~UPmmV z-{xg#I`bisPdL<c;Pb)19Aa!5SK>@Em@M0H*A;NfTmI#1dQI>QHOK<$1(zExjK?&V z4bT3hdb5wiCXK|KNq_Y^)1?VW!zG_j+$b_}cs_EPk$<?|;26OP&0Jx4{$r+oi4^%! z|G7mPH@HM2^w|FZGlDlMu&Vsaw*+4jhH;EMo4xivi3)*HWzAvgwD;3f79^`CO-yEf zzlC&xm>$ooXRUFgkS5TG5Px?+G;TW92+G+-TEw}f%FGKNnS<9OYpRANet4uh5+5*B zahu6}c8LaP6WXmsZJDL-aV%PbNEnh!=CLjMyIWu*#kb4#l7;|awtO6u96mEsKs5rr z%P<vl*7Y&{2_pW21`_9ehWX3XAzA2MaHRg85*|UQKtMs}S^c#u(I<2n;S{y$FIQ=P zHGPV8=Dy(kURY9__8u6XO<d9}AfTZj=gjZ_!)|o~8uvf>I0;ddz!|$YRLLleB1_oy z_L+YD@mV^T%L6w9A9B#Egqpbd3TcI`Kr~xJ@cLvq7WO9cY=IbFf0E`p(E*n@RTw^e zfCvLWYzt5}`;V+jBsnC)u5>!H?si_OiNy?KGk1Spqs&8b7D!mGS&umfonbH8!~@D; zqms}}FI|7+JOHbY^rJ(+Ai5$)$Tak(`E2@tQ$?zf7($Vn&0KJdpvVcFULbzy?@T%{ z0=q)|=xW_dx8hb6WTzc0A&~P+AI{xP`+^&P&>Nkyi3@%Y9{X!!C`aX1?RX2ELLVy{ zu&i5c<7I!aP8Rm3Gn5P(KM{A~_|K^;_Ag`}HSfMrNryq?%0EYW?K6?+0E+boZ@dT7 zCq0qrGjC*bM=-z2izIsam5xs@vh7<a;Xk2x_yZbirj6V&^jmY#K`;;zR(9W^o)8OI zQ5`0B-z_9C1fRArxm|ypSB5IC7>INqTCGu-2R<RglN<*}|4XNMEgfG62L}2vS|G%8 zZTv32>R&4GFMhm>S$I}|m3Vjw!+w3;8(xO@NTvD{eWU*6kTh(Cksw%i|GoE&97nrE zhuW<K>Hg%fKE#i>z=S|m1?f@0B4hFt7cuSWH-jCOePSRMjKr?~)t<8V%+BGsgvaSg zr4)uz=7%c>u8If8WN1QA@h7|JPvwm)C|mlpkS?mzdy;SV%Q!6GMyJ$~W0K*{J&Z#T zV4(0!3TzJ|Z}t0s{T_i)4yRv|Sse}Mf6u(?3}MIY%7ICuv89u6f>-zl--Jh*neJ`3 zN&YBL(Ftdfpo8Y1abP5o&=c!Ze5Dc}88}_zEsG=%F_~37Lw8$Zis#)*kR+5cP3#NW z5Xom-V(TdT0T=lJ*&OG82tU$KY%W*gf%}c-BND1~=B_*c`WNI3U=?F_=-HWH{odcq zv#eK(201ykoCQbi>9B54e=^TdM>J?>cSQN!-(7VQeTXI&w}g-(dNg_<U{C+f-CQZq z$a@N8^GthPqJOtSO?l?_89aX0RXVB7?b;>jlEP_S<~zwevt+W|SU3lN|JE-Yx`i9z zA}cQ!O*VS2>f1#;ELUVDDyT9At1H8+21q<rQ&BD3n^GpTyQz~mZb+pQl1Z8!b~8f3 zWF^iYfHS1Ypzmj*Q6Pru2oa{&oP6U+LWQr%7LlLjKE{B_L8qHizZxj(T+qyaxK`8? zlE;{h2^JqRP0rk_Xil^J=P<dxPx4{^L5aGUg<m~uW>!dzo~v@ZUX@1GPDOsy%6skC zex$D-z*3)0Brt2w5gwjTI&%JgvOD=;mTE90W%V0cmAz55O+Fd#zDGOo<!Abev~&CZ zPT(*XW)|C1tb8_^y*2onEZs6%T$_7hhW;b0TCK|UNh!l+W^=o|20Ik#L0I3<Yy&R_ z12`(2%C#xe_X_syMcIJl7C-s4mPzkSZ|xHh*-k2|=maESa)N%6T^`$5Y-c0@Lx^;L zNLaPO{L$^0xWRH<pplh@n)IIhTRFW(F8aMxT7MHxZ`9MOtbiOWIk;ynoWl;+z15=+ zI(+&F^zb~4r0S|yUykq!Bi{$ua<{@{O|B5m+4q3)8fOK$s6TLqJ*UFgcFN2xM(N@) zv*MXCg<O(<k;5&?i;CMY;$sXYH@N#1xZ!&Tm3z+c8P{3i{sSylD|T~jegUEzhqBu} z{hLJK&`!4QL8u;O6H2~s57P~P&VP`Ajp%;p`FF?v<{-<m6ik#d@y*6k9Tvt)<`m+x z>EmY|JPw`cKl5<}qbNS?`NIkvaAL(WQs<0kS*tRqFg!EhOQAHN6SJ%mQ*;&0xp=l{ zd#Ue9nlKwvgxct%XZyHApX4!p%{0DU1?XVa>-12Up{md;OB;%s$<zBz91+`?f33uJ z@ItW3{#7@!2X|a>i@5KxhfJ<ETOOL53{E@-90yIA)+Aq3Hg78AmBuTji~;Hz4D8q* z`vJ=n?nly>9@z6cb(O4?>&67=Dteh%OojuCcOK(<Hq}dv3E;$fSDugvKd|WdBO@D& z?TiqOf#?rK+kBBevE~5%a-H15){@|qaWQ|B2z!|vruPg<STwt@s~7U}n%r;Cpln-l zQ}c0jt<;O%PwJ0sT#_Xa>I`n|M*mq!PZ=oxi>-*6l=^53fNvq1V+rj?6UJ1;FNJ~J zBggo8Y=3gpzr1#P#|O+d(>1%^cn-V*Z@HDmnrv<UQ2^DeV8Msxyq|b0$mI&k%DVE3 zAO9z|t14RTYHCyH#tjT+Y6G!OI+DVPPw3X>4Vzbe9=a>l+fU#cs`5xVmY%KZK67X) z+yhvfCt+3v{#B$h%iGd#r8Y4SB93w)5Hgp<Iz4=!@kSU1Pu>bcytAB1R|SQ{6{oCt zFEoR}t8^7<92=pgm+$&+#5cTK6;hDL1f-`okCPODQ{f73LuJ=^;i=x6+$h{I+;^NW z!L=M|Yt_U0RkbJ*Zz9=rjh&h$DQFTmAI|)5zinVuoYc;C5ml}!JDT~F>=au`364BP zY&bZc4SxECO%JYhdC7l8lC36<98seNMkG(|J6KbT&1KRlV5FGg&*?RTr8w_m3<~jQ z#a0@G|Gs-}{7oEtHQb8GRsQI^3sPOSKG^;$Hlr#$<eTQN@v}6M$sUsm`XmmE@sbOR zSJ7$xeT*KS%l=mXj}%*5C|{GhEi$8fY>;QU;vu`H;up*X?(6K7tB+0u5LrPwUzal* zHx7mrE*SBuK!6U}S<g7uWm2KRANjnaZ|j>HLM){+9?e9)Mwn7EyG8k`*^geT2Q<l^ z5l`8ktE;x}bQ_KOfDHktU`vvr_SSa42v2c^0or*_Px`Mt>5uc^Nkx+p!myC3NA?yp zKt+F)_buz8K1jpjxi^%bccp%&f5GEE0tE7<k<a1QzCVITCSdE{7^ZmEdKp_uryJ|G zZ<7Jau53vmt&>@neG79+?M%P04RNqOw5k)Zj5jeRk`uFYV|T+PQ2>sqdXip->due7 z^nbv`DoKIXeMJu#ycVF6V<OnyutoW<Yz&Kw2*&nBmx{?NteW(u{VN@sFha!=OaO9h z{z7>#-}cz`>Tmk77kY2ZRGfCb{`%H<u8glyPU-o!XqenL@L+|j+pT;+l#<(cqLe;w z*8s5v{}-M1>rBL>DhS9;|Kp(Wp<U*jj^8=62or4rNr+A3WuF>RSp`O#%?47TUH6}o z>qkk^f3^@56+DAozL3%1{Oi-2(Mvqn411P<2Ku*ch%HwrRg4(BLtfb7oa6SN!!<4# zOe{V+vfQg`c*_=jJnNmkr+?*hf9iJT6a`6^4bm=ohCeIb+jF|QW6#0B28`hYxIrF* zm8jmnEk?ps?5eMK<e!DG1DHB}x4vBAsY3<U{K)}+GyNaCr7fl)^Kd*<Vw10$3z_0> z_|RpCMi6A*tij4T7qnyL`s30s_Tj$ra*JC8G3y&Wi@tO&{r%la(T49c2$=enYieNk z_wW_jyrQekC7KURSUlq@LHdik&qwcay~xv@C($mk;`y@GS#Q{{%FF>}4Ps03WxY!X z;yDZ-PpuzdU!gK5f<Ctapy<~=*Zt2=Wp|1yRQqcPigij>fF~fLC;af=A5)q4n%;f1 z8NS(1O~b2iAzG+5_T;S5Gcj8dP3X^6+{j-7D36zhgvkpx7{u6Ds-F?>X8(dNQni9r zdmQhij`ZJ6IL_t^qJ$(T`}3L3pGATASh)DlH$bCV8Dzpxgi8Hv(rrj@*I$&7M)4-y zsEhR>%)6A+>5HHH&Le6hT@o3b6%R%{|LK<Btb#@ZZ~G$t;Sl@~0MC89ZoAd}R{Oee zr&rN4+sO9(#x)yPL^RsPa{34cK(M(L-&_7|1cD(*s8;DBy2>1;Kfm*EHL(|1E&_<J z8Giu(e0ujz><Jy2+LRXBvsjIv`yPJjR!vDmgEUUh{L`Oux!~!G{t!JVD#cQBv=Wsm zCR6jmHmO9hKq8g_${nD5*z>rV*|G9E6r(VKAw!$G@$a+Edow{_+p7(<DvQF(Y(5~( zAQ~b}H3fePFMAXH<3Cn0Vn$#|ku)ZLJa?M<*xZlt!jIkxhHN2veqVab0Ls>X`f7zu zd7R|6Xpjce=?ypEu@ac#M%<b0jQS<&p6VUDV#^UMxdsdw2uXoCC6hjR$)U6HS;Qs1 z%K8i@j;sh_Q%$%vze$s(5ri*582--Ho<(bTOsaL0-e_%u?<(l3(QsBg??1n3U(uY> zuoQSKq7bB!q0K*;?2Y4lBnHpF<13-4vVJxEV!urzp7LsJIjnF`&4drW{$G&;A|?oB zUN%2ra+NH@eFy8ea#cZ3%p0gcGBWx#ES-LR&y)HWpR)O=vTjgFvHVTZR{k4?&xg0~ zl-Xc75}KFjnI?%gn>}=Xq7I2jCKTIG5G3d_St0ya#;j+LQkqb+{$7vS5UNp}L3uK^ zOkv-b`uQie{BJN4(Fw)tA*KIMgq;TKUy$ChaxW49kCq0~0@8CEKPg`0eMrBO^T!qM z`BZ9#_Hrrg@5qV8s|iJdCA(!W?9h9s-|B5T!w!_jC3>EkdUH3{Wg9lKIun2dBgNyH z61=3_{{p`)vSKK~hr(2NMrYM$@B9JJ#2|7Pfw$t%aHY29ZLi>qe9e;07;Is-oL@uC z4|l%w!Xt(g5E_OLj(py4T;FDF*zA~`$o_rW&@&<H2UEX425vAHVPmc~iY&RnCKU&E z?YZ|!qYFfqdJ=)m--zpwo~~)yvsJCKDgjU*$kH=x=-DhT^Tw2Cs$`-X%bBIVfLN4L zFXDorjmvI(3S8P27N5vY=D;&oo+ZySQ$2kGEq7LovTRstsd!eRm%j748`g;!`4Q`U z8*VUV9mH`9Q?C~`X`N#7wA>KF>=}7txOzTk=F$l`T~a6g&$sNPpBLCKW-|QI7@gkw z;D*D6Qk*Jv5!+E6_Pqa=?4KnUfs{x=q9TD~Ic3LhZhlkru&$JEib7q8tHYlAPw(kN z9+(F683o(oIfi@sTdDh`6u!^NLUCVS>DReBxkOXx*52GT5;&36gN=itp9u$;1I@2V zEgolhjVY^Q8fAN)a!PJKQm(9~OcW|#!|(q!+4Zs{DrHFkk^uHV#I(h+9<aZI4!L8E zNHyV^z3MdVS^eJsp1U7XS2I_sTd<WESwD4!Po-NYK0W&mkteT4m%bi!N|-m*A`TbK z$m%cX5if?m{f&I?d*Xp#tE=RUAxM<~AO4)E*|up7CNCSd^{v!}wGVrKqyOjEOUa5T zB&P1(*gUo+dojh_c>n*D7=!}=fO$%&OvdPea?s3cu9UCYnvH4Qs!mZ?x~F$9*m@wO z3KE9p(>5+fL>Hm><#pSC^rTdRxtjYKTI^j0j}uX5?@3)jR3R9kD5!^YjW0jfHEc^k zKjVxj`hy(o(iKzDz8?(-A(a;>mcGcxp4Am0oY;GC`S<%W8MAp~SSNcH@_hPH?blfm z0K;hVQH#wepq_s9gv-q~M4{N^>_1K*1_%b_=^g7|q%TZ}a(v4fu6Vw2_Nq21N+e2Z z@IqK*yjnz&F%jmr+rQuxBxX4klMaBj5}~BicQ3qYCKjncC>Y3zScui?Nh-nnx6XKc zEQpBkARqukr~1gBgj2(s8cMy!Ig!xp8mW{E9+rMOz5GoLbO}XkQ+tl3q&FWpmi;K9 zaUP^2VYI+t>7ob|)wORbpEn9jFc>6ch$1sHo(JbXGtT5rO!aCs>lGG74F;MX8$h&H z&EupJo5f@n#$q=6RNv~y&8m#8h-k4^$=$P0{<O#9m1Hc|RW-uoP=3y?`O{B+P?m;- z!QM_qk>!Ws#t%PqGOSCN@=%GHlQ<Glv7!@)oVo5Nk?t^3ragF3kpSfTI85@hJINE& zP5M%E<fqXy*;gj>zSF9kq&G`0h0lVO1VmOY=Wz`6W1fH0jRJF#9;9b1101MPurmV# zKU%LTK(?alTS%6c682oK>GVOzU3I^PGOuG{1_n@-&;5yquC!+|Luim5gj0Qnp6BMa z-%9?VB3?00*0NC{u1cr}z1;Go#$fNb7NHv<!2r*=OD1vp&yNudv?#6=zg!p68+)Yk zZHfPr^L~6Ms-RI9GqI7+soYi;!V;I#1mQ!jn4!cXCp7Xjve?lX6h|M4J%jIjB#Jw9 zY#u$bde2}opvK3@XW<OGim#6z8OA-|?wTmQHhL5-*>|RO&tP@MxSf^v!pT3)8yxJ{ z9A3=Rxxbr|#y>aW5pqKJ}?O&yzpXM$zHavc?t(n#q@Jx5;qqxNjDF1RnaC%80N z8LSE}4_52ELia0^jDg3uyC#aei@SrqN^E|g9MGtQsEVnKsoo>%lcGLZytik4+g%a0 zG0mbp7fWbJE8Y@6CyVz44;Js#$R6VqZf$%LY>M3`6R<!5@*-IpfRCPCrCl3$jlfw9 zmTP3c=tZi7qL0EzXm{Q-#XlDR6x^{FK9MOJc)M#DY}D~caE^|%f-`iSs;dr@E%3nu zKJbDcI-n<0e609b@L;e+W0nN7f({*vb+;t*w=5wW+!?G1)=Gz~bS#&gR+w&Aichl? z!QcBex%B>x5A@tOOhP7G+0dXkg;%T(YB{@h2PNA~@Ko`M;8Ez)F?WbsS$w}Zq%a1p zFp}Tc4d~6D!EEqEupxLz@?qqeHufAi)yM%G6XOIwGV(JcAJ?(oMlKGP4vkEL&2`At zi?@MSGA=#U@qF=Njp0}<YG;|0!Rfvd`^Ly?CU~N_q4<bNc4bh~u^LYaR!Tzsb}+v3 z@K)^q(bAK$1hmnk@r<(jXe5@3oZt}JkrHrZ#l@G3uLLic^(+y!i^b^@(Y-`Aglw=r zxBOT#vE?U<n@cYipSLlKZTuNFc1eo<NV5NJu9@OP#r47c#$QQe&JaH1)bt5Yl{|7^ z=Ck;6$19~BW!vkKHLcLGEF@;dBe5X2qIjfYLTOh=UvZE6ZZzxNF6_&L?ZHMx6PF01 z-IiiV?ll?N!DGS0(jy06a)xB9_@LQ=5m<m*AC$U>#}GDX<b!4hXPA#-5oZRcn)MM) zh9t{aS~x3?6(1_CE8d~r$Oaq2eswQuT{_qrcw^6wrIaW=6s#%TYQ6DoC?+zT5y_VE zaEX6aT7rJc9z3AqE=i~)37xAkZIaNcV2y0Z>5Qp$+i_~~&#WT+T1Bw4q|3SDvqQ(l zg0sea1&r<)j2CKy##O%3vAJVw$5ZM{q(!RC4!Wz*ihF1%xj640cN4`|i?4OOBK<Fu zgg7r&Ee1<Nw{`l%DH38F5yszS6-m}>RytR-&Q$Coni-#2*CsPa<w#~5$DPr*^~L** zKcbLFBY92e{Tb<T1)SXBD?rQ2ejb*^yM*9$rSMBm(hAaae;JB^v5t}LgF5c9ksXpP z_6L;3Wv#fM#<ql1fvA|!L3Xj-<`pDUlw>(CPsb8<ewpX}&Lsrydo9Xesu7n4*9AAI zuF%}QLi+SRKyYb_bQ_N?iQlC!^t@1dG}0wf#Y3f6jYJ|udMsw>ibW8qlf@@W8%vMK z>af{!q|+sKUTSuW#k$qTkqdiwT9Q4R+lp<)z_TzvZ-i4x$Zgc^m9x*hK09a@44w|2 zDQ<v1i<o36c5l=o6}$_I!Q~Of^;xZc*eMk$T`VrSzc@u-Vjq@A1qSx-l{e4m*dRR~ zA1n~3bAuy-ll9bL8HQ`l{S3WAKM-iI4z3oi<<i5&IygsJO3LRIw*dNr*>gB}=pW39 z&yBKr;>htjgWJxMEu)~#ukgt;+;Xi}T)shg*93o&Y#t2m)|GmlX~n7YdDLMbU*|zt zYH>%fQ=@DKvon!;MP%{xa(%e<GagF-cdw3H6erJ=HJm9+I8&o#e;VnUh_&HdLZ=^z z;`7Dlikrk6GZ~R&g|3Qy(JY9SdjWzU&L=p3D_)T=TE*_AP0cGl^TxIge{NHZMysJl zt<qR|M?A*vE|oqx=;239B~P9|Zj!}6VdGaD%|5#<HcN0h#t|3UAT5tWiC}Zbi^UhE z&Bd0xc^o<?Se}JW@9Fv<(ynumYzvF&jw<u94oSvyla8Q6e7ZK^&ZCigxIdAn%cF|V zS&Us<aW2VMT=$Get1e-u6rK|$)(%_6Czjx6=HBx(a(Icg6JJ?7tPB2I{&9w|A1`W& z@=Jnc8tGa9KAieY=CeJ|S;g9QieW1h+aD3Gk}UW<L0O`a(1_NN6B?ui8{*lhHLc(u zNC?@Q-AXGi5qub)f#Vk7@T$#A)>uwXUcNbaR%cc7G9-wMM_ySQBsbn)`fJBugo#X? zGZ|xtX(hG*aD&-tK+@2VDM~`cd)1e`jht_#LFf>l$ic18qgedxR+I@|30^5~lRiq3 zk9rjB(Jbf({T(M3%i%iB2Dd5#{81Lq%z3eRT&nxk!D`_|G9C}&kuE8haJsa4<CfB^ zK_O_<%*(k$FblzWjl{RHBd;DeJ&t0-_~$M1GG-wnAHE5%s}%cuHW_{;hvLxsK6qj2 zOC7I@N-RP7o}JeQtF+RAPjnu~+c=W>HBs6eY?0m0HI2;FY_!~DyF|IB+nbMsRwTuh zV?bKjSbVbhxMV`~(_C%Zl;uV^;gJ$+2mUyOxAaW$nbK1>a<#CLxp`*n+KWdJ4~BaH z{>j|8OmK&t&2F(9x7f-nTws5X_B>p?PyW%SgB4kipJlhPMBHoKSDa65OL@HIL#$NX zih7LVGty|&{meN7zti9{VqM1S>QZr6l4NJe9?rqz6v2QDUOyPc5zh{(jn8$w7`(1g zfv8=p8K$6fmGVBuak!@-Dfba5!2YtqFJ(VhNlLO+*}<~lYdWtARx9?o1{^PXh&7DG zi<XWDl#Sml$;7h*bG?oX)S?ONWmxb5$LRifm!i;ZCZCclZ><hEUTv~PgW%)}1Z3vB zFv#{19S>PV=#Zx^7qwVYNA1qYu6K!7?TQ7vHBx{7C+O37uD&a<L9)G6zOqDn0;ftV zO9QkL>(jBtl=9@U0zKX$nXJ;Rf3A*m%;Q$1T=Vpg<E7vEj4b>`<;6XB$#NL$Yf!X$ zp5>YzN3b?*euxJ6P81(2JyLqWbh26!;;@XtBot#L_IQML>i~PQnAw;s)e;4C5WO68 zk8&`qZ7A}9k*C-qh}3A}Ze=uUgKyYzIS@1w3yS+;74b;!u!QGJTRMoEc=l>(<s6-L zmv-B8-eS2{;!JMbS=u8Qn-zn$ODhE(J=jGiws$1sbC5@u*ank554Jtrc8~0Jm9$9C z*J0;^sCAon??8v{DMRz|hSFml4@a`~JWO^FEY(PpeH5)-E3ssuI=NB#Md^9rD~Q^q z^0e*Zw4l{8QPamFW9*g!1P&zjUG-1NpU3Opv#phfZPxwdV7#o)vl#lgM%;#+XJ+0P ziexn<aTv>YyrR-_o68(N5a1dK#fLVCiw_6*3bP6;P-gBp!-%EJIOwJLY-IA%T>oV0 zarIuMiY8Zi1e3)>rO!&(Ql%Z>?}^fjW(jSEZLKVUJtEE8;*+u9gIc#CsBmeq>cGa= znP)T8cj#Cw=`KrqFSv_kgq(<Ie$50o6>kh~l=Wi2SiPbbhv9Vj1H*GU?${4QpNWo5 znpd7SOmj8XGh^j8=AW@&x>aE5?yCl2>BFT5OT<1r%+_*>L?v5Yxt$|Nmuk!}?eO_f z@KEu7)5lz5fkw}T0#S=>-QMBNM}wC`*N)A>OT{hX5)YY)4Tw|eMls&`iS>_OI6T6L z&*D?TQ>6_im6C8R)nRsTIW-uOq>sRg-G0HD2{sfT)f%1rYp$?)B-1XOW(VS`+X8%H z|2_u-XU|}|=k=c5ZM!w=29gYvlC5qG&KowbgnH}#;hcK}dvoa<9dDTh^%%9wE!QBA zkG%_A?k6!;#wSV}iW@o}F=`i!R`h8RNznwZkO)_BI=4LYlnm}GKB!%uujy&KG@@C| z&zj4SMm$chRe0urYx1E^&7lQx$Ico1302%j83t6wRJ)8_SHjt|qhot<yQo#xFK)qk zp5V-~okHkjEOvke#`y(!lO2zBJfPhO&%@Cs*|>D0Oe&V6TdPBfZ3u6B$fCRNjbpnj zwT@NxXj*ZZf(tCMZ}Y^+zgR5jQGaX)AA{oM8X4QI_jJEugvY;R>EVs*wHM~LvsC<c z7_~i7jF00cl7&)uMp8)Vm8IL4zNRR!L}Sjek@(uGTD*C;4sc<EzH-#ZMjfd@|EFhB z$+664u?@k7z_Sc??U*s+d;&~B@Hhnh8SMx>s;G%i&J`}?N+gQc4nw>W%NT*wptjnw z@XLjZ!!fhs*`P>`2EpUSvv7FuBdhG<_sT6+NTzEn`&%8HFWEk#JRTeKxEXsjIAiNb zcf8cLCD<k`<nSAXW0mfLV5ZGTjHS3Xk*Rw(qmylK6?ZQk6n7;Z#QC+7u&iGrd5`Ym zu`VGj5sS<Qzf!(<b?~f>dR8>Al5~|fX5IEGWjj1`NCYpIUg&s9c$Uk8X6d|Iw!2Jg zB-hI5Juu`$$rPVggn!(6uaI7f8oxwm-$8SEV6S*9SC=&WXGPtwf-5B(X0juM`)i_B z_AA*ANfeHel1mEi(d(wtGo_8vJ*!>T9A{|U@?eFnSLlgeJi6mEvE{Ol@n*2A)Gun= zj7#SGb9CQkUWOFe0rio{Z0N`aHwQNb*GHCs4U~K}Q1RWtV}g$($8{O!q`y0ZKZ)Db z+LvS|yj#?+40>$-1j7(MWCRuH7|yR%zw0!T9Zg?Fk_Y+@H*#^gx>sTWjQ8trgG*#V z3q<E~?Y|N?ZI9b*DAs-D)nx{R+Z0c3krfe1dgM9RS!R8fWD9inNVMSb&&Sc4(YJ$M z`R5}VwML`)a#0fIb2NVr>C>ePm0)KyQS;7@n>uc>5o<*$JR)CmO^<axD_}hysW~&g z+G5`=M)56@E13rSjNj1g5PN?-*J2USOuKL@OTDwWM%u@Q{JcyYGk?0JB7eu|a)M*D z#oC@#2bytxJ}4<EVn=x&{WxN~1&&jj4W5@w9+urmD&m&>g8QXr@$?%S<G5VT_{z1x zH5&1(Ft1h&LpKKr#@Dp!@cb4ou_MmdJ6vK3iC}AKOX&h>ze8S0<Sd%M6g8KDjnPPz zo?L152$Lv1QQA<>#>JoMRT7S}H)IK)*eh~!K55H}#@_|MFl^+Q<YHi6Y;gz~dL(dr zg@)L&d{62@Ny+!4o>ewZ_PMc~G2&Hj_i)M=X+N~)4c2wsWAY&{E+68P!?7YEr@E3_ zz7XFk>9XraUb0#`(Mn1B^yuNT<sRHFG2mqs(Z5;zcl9mm@bfb6m8Hh3KgJ+kmucLZ z)z_!rXiw@ald9)@=Ws9UbIlD|s&gCjnNuwJZSZqZ>MObx!n;P4Kd5K|ZSgpdd5pzZ zkZ(5ltHq(SOcz+-c;VOjLtmh<gqS~<uX|WzOQmN^&+01x`$DrMot469^RHqb7^z;s zLv{PpS$iLwl^K^bW}`+il3Z$OIm5u>upp=>HUJ5`t=5?96oqcld4;ZbD_>YiT##qe z3k-2@qzzUm#}3!2-@U@aLF}aJyMXx$(7i8`aa(Y$LhWX)>9z)KiU@Nx_8jp$Q+2Uq z3r|qVDDXkGa}V{2jx8OplwPsks|9ttXq~C?J<&Ql)*kc$fvm{KhoX)+g1ug?IJQjr z1@}Gnh1h)**}8mOPH-?F32l{k+^sV+{bogl6*@l~+@MJ9vVc$I3-y)PtmJdQG=U{_ zXfEV@o~UJ?8cN-I8N&f?Bt@&%g2mtK>mHiaib2%kHOl)eY9h^eOg!4hqpg=qFH0^R zk|+2UOTrr^<E2`;B275;G2nMAa{XlGDXW725r5<}8&rvXd|QrnX&NwH#+r0_XGPg( z6^R}crDRd(3BuhvuZ&i7&XooR$P)=s&`YZ0<)FCqB~e(?+wD59QvP2Gw#&0U0?`+$ z;{)ok%8XWJj|2~hLo#DL^ATayj*GszzVm@4{L*Xzd$2ux(X6kjvRk)Vw{q|xRo4<Q zL-oH_bI>ZQ>^b)+*FInRWOjhkSf-2wmP;HPx>`Euk$)_=yP~Kij%~DEb#wxJmkr#- zno)~(KDKsjH%nkg6e#2it0J68l(Dh5LZw@L)-sIiwaYitxRk9+n{B}|?G)}-Ryh!z z=?&(T=|?}fRRp_Ex#m^E!*QKy<#MbrLwtp^m_oGToWeaE|58$6#lR{_k}=EGy=3dQ z=D3*2&@0e5hzT!f=j3J4&?bu=Z(1#hTddFfIc9Kh_&8|KYR3MR@R|07^*oKb0ZXWY zM{EviV~<8hLlXL{Wb_9~g}otS?h@r-Mbqc-6$;ck9e!np`ypAMa;NBEF4Na(@##E) z!#Q>txs=6c@#T)9qIF4lI%IduXY9{oxAdpC7nim3i7h6J>w=q?{$ASb(6L6eE|C>U z(u(mOq1}ey5GXMn?1QZ@-m3K{+FWbrRcJHlsbWNYxTnRwj)eOM(@S^v?AEW>dNgjS zC|wn0^vi4?3`|hz_U17Z+-NtHL>Fr=VbytrqRARNKNzgBsEGz0uXBqH(}s+zwLiE+ z$4u4jcHSY)s72YEkMbB9TR=>)o=YzlU()QrntrvNSDH2WY>#|7hO!O!Zk~zM%J(fs z&(#?GY^khb=*vtjC6_JI#j>=DDgChcoOVQurjKRPOqBUWD>|px{W;Va{KX?!Rx$FP z;CA6+Z<1BVIXblSXITw+eAYyd6!$Z?e!h8KqVL~lY20F+FBRUi^qtpN03IWu&+nXX zm+{14p1zxIke9V-7Cb@`{t?k}x8?ERVT5OI=mJWSFJAUp+3cqzS7ftF+~Q@kw9A8J zDkB)r6k5p}tCd^uUG8q<ajotzm#p>s2wMxf_Q2w@aT$SIqc=Xg@$t6%g>kzu`kA%E zD#MAzfXBIWUB*_G(68RMl^BJ^5{<|=mj^TDW%w9aoxeD8y63?MmT;#=`JNI{o?lU( zS=MKalf6HV*fK&{-H(Lla>byPcD0xpTx{R2T$a!ZW@HQ%K04X9zW8A2F4-NCeYNN$ zcf+&e-7M$PbzgZ-E`77Kv(zUF+ca-37v<aSyf*SOw;iZNui*2jz}jJrZ12}P<1I&s z+vU>c89_<Z#!-lIJYfYM=ZOhfMa-ME>R2isN|MY@jl5WJR@Lqr<lws#<Cwwqf3en~ zpViw@t$46Pp7ITObFqBri<GS$T$7H;WkXzX&a=XFyX?rnE%Q~mB%F%3ktMhdB2DOI zTx|PUts-v|y_ai5N!U4C4pz&I#BAr^$Kvm0>0p=UM&5+N_gmRGyJ%#J%%7}z&zEdn z2bCU)lxXD(GZ|y8>JE9=b~_W#jtF+h;@w){kN!iuAl{x0)@ujjUfc25thtEjd9LKU zvb>^0H{LhaXJlF0Rl2CO*>+y}_E}U!*sk*|%W7hI(ihEejmL*Ud+=UyH(C0BQ0IfB z%V$*|wBNnC#bT{sb*kNZwL7`-sg4b851CZgMmC5g2I6!05%2Ul^+*Uyzd=&jDtw%e z7qy#%xt1|PU#!2_V!;j<@o&{DEy(Ugt>qDBGw>JNj`IpcelfRJ`4BTFKE{sCS(>w5 zo^CT}u<{wslgd&1wWGDntY?`hU8VbtLBVEwVvg%mLnU1-0SQ4tsJ)sS6cxyW?pD26 z5V&7cwp+I(ure0wckKLD;OQc34feQ~>r6hcJx0kEE%+?v_+o9+J}{WxxO*et9h61e z*d@Bto_bK!Z0~aAN~Cv8F-EApUisUV;_hlueZG!w$Zsy!Z}N#l@aXyn3eQ~KGLnix zeQka6%O%VS^019M7lT4An3xOP-uTWy{EM%BgUOB^#qDjcDw>pJ5uQ0N73DpO32}r4 zuj7ehljFWuD|???&eX`|vb-K7CD}qB(sYTsM%>=vHmALz_4?Mqubk$J=G7X_H^RmG zbt&(mnX$1(e7+{0F+1EXO8qxz=gBvhnKiMq<Rju}2^0>G3Y@Rh+G>TeY2q!bPi8XR z%i^6Iu!1+%CeJ>aeUsZ{w`U3$`^@J`TDn&b<|Da6E&4=5e#Npn1d-nwZPvjT0QTi; zgMuW)NaW<a(U%tIoc3N(xmp>*#qtn-|F&I}Ypo=Uck6Zu`^@0lacSigzy4c2nO7dv zsAaMrtvP~AZEX*4ZoO`+jHhCYz6-lt*`G2Q+cQ}vY3uhqnpbv<FCsH@i(j>N)Gr)% ziw7e0FZFf#Qj3)Q3Wzy)r>@Iw&Fj3nEM2xPHRqpSwBBOBgy7!+oT_Z<JRKM3V&8C? zcr>c?Pv5`&V>CCcm0UMUTFM>DzJe@=<m#B6S9T$=)^j8m)`30Z_T1oN%`4D~PkCm| zXzsb9sZjG6zhz(*d5gxME1o&`*zb(N;QExX1jng$U&XVp7uF4$AJ}{2H;MKu-Y6e( zx_}Vta!4z;MDyTvvIFdvEJYkdHsrFTH<+*rctCp9iaG_&dYl(1#&eJjOfT=%c;BS) z2({d~R_>IS-KIH#*!K-#WQXX?;N<emi}m1*tUj1UUDmWfEjv;CI+>m0l^TD3a85Zl z@f;;SV?i8!q8<OdSUi&7mduv;t;>pNf5@eaWZj<P2t#`@C~EIbXUUfHMmw*JaPAWH zKEo2n6TZ>$l`au{w_|hgW%XVx$!e~S&nDZ-Sci0ZhHsx&*2-##ewUgBYHwT5%YsuS z+t`PPqM++CmhC#_7i+}Xxsok=VK)fMH}v(u_2zK^EAV*f-s+b87e$3XN)u;kB)`91 zEO}|wYwPSdp9YIZcw&)z5!Qz;N;<DKdRN%o!k2J*`Ap>eL4|Y99ltm)iNa;Ffewvc zshGmIl1Joa@$5i9w7?mj-FtFco!_UNkzW{`A*^czg&po5jr2%KPmeqC6<)F7>tzYw z)hO1;1zE$&V2?PxJo;B+aV`Vxp5^chPLB8s@gwrDf~13lH)`ZLmfyy{37zrWHsqtd z^6g*B>X{+V(#Rb)LtH9LU=4*<;0xXRc;}Wkx7l}+<7Kx?<Y$X@X5K#6eg))OOo&r> zcFS<fWhA?|YqT0XRi4It#9DHRa%wokzZl{3iqA_POBjg_{l#Xav*c@6i{>RrOVm1j zes=EArdtPBJo}G|3j7kAXhIGqoMs8=!DFERP7^3DS#UC2{y==Nk~?2^&wAyYV3n*7 zOQ5go6-xk$Tb1umm;m1Oi5bOZ_O6GF==lFWnzd5pC<)#)?ttANM<5yTm>Ti?w;zed ztj>Iu#(lhAqt)NOGnDi@zuwDRpkje!J?PD|AAT=`2KoN|w=|Xs6nd^y5YU7Wd|)pq zMm2#Gdj?lLM>$4cGhnr&1`TTv&SG#;@O2$?f>ZQ)@%dq|_woQv{flH(KXXUa*WZFE zx9??GMU!xTJ;GVh`cAhopDBwNoRP816q&y(KEJ6Y;5U^dp0A&f=pWL*6F%O7(<O_? zamO`OtMB+SC%<zMiht7&h%OMfrv@Jm26X(50!|`|=XBU?TB~@U$>I53@p++eqR(~( zqIXf8Prii09h~|s=kxJM@7)_f@!1(%XgKEuv-j3xWE(hLjzrQv@r4B=VYnnRRz{4G zqj@%*aQSsj4Kw%FV`Q7-ghS%0=T<ziOX66O`#Tlkyhz>x&Qs(q@6uO@UM^!~nUb|~ z_4Dw^xHsIw8S8VlHaOo!aa`D@V{smb<V#-i&R~Qy_7wy@AnW}b#bt{|@ej|+@E&G6 zcxHw9&ZR=OX9sQXR<^Otf`xmxBjN)Z?fct&#<B0c!P)N?CmxDq{p|dK&%f%CgS}G` zpG7-}3C9c6-z=_Ax6q-?&Mnw8r*|RSn9ug$Gw+s9mngQfN0KDgx}SQc_Acg?I40=x z_uphv9pIDf1kd+f6qhL3S{xbP8IH-;=dxO*VDHjD|8Hk^*DBdngaNoUA9$hBD-jV1 zAxH=z3?U4I1Q`Yyh9Dt`NRSXDNRSXjL`^iwq!UF%#0xLPYk!2lNc;ifl@hR?{q~yf zqd9BUb~V$dPj}C*uCKS=s=am}GS8Wk`1MIhg~RhzGVh--VgAMkuhJ6-32Vj-$q-E{ zXfo-+n?LcvMGW079BRi937K81X0#3y7RwDihd;knh}&3+TYAxzU3nG$`3!4>-!OjQ z?Qg4YH~k5BqA985hYJNCT6(5tKUS3fZzXlHhMpwpvIgF%+m>oJKg31c-l{E(Z9Qe? z#~aFx3{6jwO1hN!mtvc*7TbKO*k)rz&&=T<P7p{$dCq;qwgZR0R4lBmr~Ze$<VO89 zsZDlz+SLay+m0CeQ`NE^GO;buYFfa~en!t0_Wh!G-?3QVce=c9WFuda7cY_uaT_&z z==q1k(<`fZoi%w3&Y2UDiY53xj~j9O(Z>7UJAAeJmcLiFELLKOrhGVfeC+92`7>V^ z{(PrKAWeVjPGA8I$)RQNH@`PzVtvQ?`_8Y@Gnn^K&2rf`Qw{QQh18bw`~UY*>G}DJ zoX>7O!(aErP^^oKVL-VB7aIQj@YFlpI=p`PN8J`H85zVKz7@IgtxwS4ChwNaV`a;Z z9_iuwTo5PK#5qk>B{Qxd;_QQOc#FpyOx~(@u7a+PpLh+v(~f4DSIQ!1u4WRi)Ur3~ zq+~O0S&uyvGY}z<GkI#*c3{F=hsXBF3?Gq~@+0%7^rS6L9oxQe_-5C(xJaxSeZv;Q z7rZiGn?J+*zEGpSf7FO^u|}*WOTr9PZkoD>y7NO^#L(Ru^EG2g6b-It@~B_pQysUp zlqo;W6TVV-+vFw*?i^j*Km_Oq6Pz8GuhMg1!t0eQZA^edG|d!F{00RR$xE5X%1u#Z z$i4cAb+Gu8-_k9R9;QMPv<-*2Uhc`CWZta$*_3JS<%;C<jlLL)TZ1Qz-rgp?#>#OY z-rkwV+0UWc;MD&v3(QyPIWXaeeH@~tTuE(#fBH1fiRhKFO6CW3!-sZZe7J~COs2ph z`EsZTURAOUZwJ@BclgQNCV4gXbYzi3*YG}dCK1%~XXao#>ZhJhc4kTvZB;X?#i`9w z#cgxZQ?$s=pn=E<8ibv!ta}kd-|5f6&KxX!frUMaeH*oG`18rqw_QISeQ-ZfD}LmN z9BTOUxLNjCTX}A52CKW-N<Ji#a-R-6d6RsZ{r@XG;iq--ys2mXxunt)x@YzU6+Dx= z+Q5Vl5AW{nR}#1E7&h&v&R!L3%@c+{AKx>36EmrzY$|I8@|h$rZF?+#%9ZD9X1s!} zIv828r5eqq5J>GzC0#|(35O!n*IzYdKC)pDE+Qjo<)=@=mkocyTOG@en$5ERDp`Kg zlYK>R`k0lbTm1|Nd$CSlw&ONu8A!`{oOETPifo!+zb<g-xaWKsb_e;`6ay+}Zj#(L zV@U6CZ=0JeJ(?KGTr=}pJAQH#v#Q(mI(nt_e7F3$vqzE_tjeGGkNZ?IdNyqP{{EVs zisIOxD*Nhr^+xHHcyzulV(78jDA10fOh*O}8FP~}Z<tBlWI}}F;ZC2&r=rkSR)z_g zXbw$h5+7hf`p@U<y{#CEH_4=7W<uooEr>XiT6&(jrha9)QokUN_=M~tH5C*J>bK{s zWDc(R<C+ltvpY{nZ$i`bgpo#nC_G=Ap8rQJOXY;G=|tsAvZvL5eoz?-Z+Fi7<bTdU z#+v-;CRdkwj(Plx6}gQSe~Q;cP>|l^R1`=wKg@+ce_h+{+WrjcKm-UB-7sqL)WE)D z<)#dMx#kHg_m=|EQ*3@*b4|%b?zoZIu&wj<{JEoF2^NHN(T$y9VDxV3nfm!sY1>%z z#KGid?Ka-xM*NHl8je3Z(1kyLT70O9x9J?%Imph=bd;~^>U@>V5x37CzBYevULA2O zBh_o(V@-L9-LK)ZWWrkh+%X?wS-K^D!g5)6-DCTIC3E2I&Hj1&;LkV<=zJh7AT!=} z<m*?-9Gv=z!}t6CgzV{egLsf&^t{bn+1cAeo%AQ;9Dv>-voIMmUl)2lUE3KOYs8S~ z!E()_uw1t>p`Rb-LgrU%Ltt~pm>QBOg7xg{IkDWz&v3AvI3yDjN&1Imq)Zu+JkzxF z95ws*)%7+O+a_+pI3X-eGf{x?jhXQ{kMw5$TqN{+q@?(1<##=j=NmDkX77w!bAJ|v zcqB(-2;|n_w*&j`)$Xjuifv(BI;40J^2NsDcYc_QxP7fSbz_kked;RN&6=*M9%m)t zLaUaAQ-8B6=o+9)3a^PGH6%O_B6wc*v|?!B?YD}BHI`$Wx#{IeVo^S%t?Ken;lune zn{A`#i?t)Hsb}QEb=IXb4OLS%##m<S!k;(Gw#}NINX4e1pP#9tWYT*k@k+mP`*643 zyDIXVWuZ-?g^k_l*^_vZ89sEgb}8)A6Q3oS4@XZHe$>!2GM}u?*ln3GA$-<P9?eg^ zM5BI=n*EvD+}^G$s-&aiU2Gcp$;}3jA2@WUzh5)ais{KzSSOmy;9zbhDA(Kflq<63 z`90@!9FY`ORk6>#whWrDi(Gl?@bi8Cq^G%p*cDIke(>Fy)C-v}_3@S_jvqejajeR} z&~PU4O0N8%_SH02FvvZ`6FsAPg^#u7U;}UO)On=FA`PbUTPB&YtbRo-FF^&T9&vl) z@OVRHNy?3O9;q!JrO&pvdL?!9r!%g{jy&&)o@@$x{DVbs!M&(z`E%6I_PJ%XlU?11 zTeE30RUbP4{H5pMeZB~$vFHhBqht6;e$VqXp05j;zpu`$Jx>rXgMZOFXgj)?rObi1 zxBGR)Jl>6Ulapd8)jJlRNi99!->mz~s@Sje_wvNTdL<}?b;5{n&{kdfRmJVDy;-A{ zWGXF7_?M<6w`A(F@7FGjwm%=)vINQvY0zlQ!*=kYN9!W0X3Z8gG6L?fC$56?#m+lw z*^TOvRuEF5!ISA#@;#=c`Zqd#kLIglC^N?Q_RJXb-49TY_t=#u>8F-9FyUCZ2Z_F2 z7~j;>kwuMYO}_$#g1B;Mspr6<SNrFdu>yHW-?5i58SB2~&&2JHIkjlPM-oG%2MIEd zpKH0*?9ubSv1flg4Nd>mE}ETx^6y;g1>U~ZKVK$SNTOXTr)buX@^k|evVZ8kI?MaS zp8Z3~5EVLdL@#fycaC4^`NP8(yLBbAHnl6$HaSB_nD4X9*M-bCtG93BP&AVpB#0$( zj3dFPhHd3am_qw{L70Qd>NRt1S>|Bmwfs5i=MyElsVChs^P`(+^1I13)LpHz?dSfV zy|BS}F$>q}7Bt|`6_}OG!Ef(vGmO=TtYf;RPr<|7R2H*7TH=25gOp4=VbyG37T&yG zaO5S6iYK*Gt%14pUCKP3B1lna_x6cg(MoDML7wz!nle*Y?krtVM~yWz1B<LYLt5CN zk3L(QZF5fNm3{lck}25{>fRieUq#eR;tAtvdA}}zcY*hEMJu`l0n|_b@M^Xm)7<M1 zRC<22or^qP|DLO_kQw9&>ta)x3HQSv8aNa!@7Dxl$9X~DaRLdj>+}yY)IYWD>Zkng z-%8JcLpS^ThY~M%4;`TZw3V$gr7<(s2bvi-7u%94UPy40A0&BR^v+l5InG_}JnxX& z<vw#<3@{9-5x2v(kM`$aI$e04d<^GOXT+??UFtdT_J#gA0MlB>KF4qR1~4W=mom>> z^LDqEsh>2;`5ZnB?#k0v%^ow1@Af%Z&QXQG%Z;4Lp&u<<JU&shqqkQfgF8WjAU>|J zmUspGj>Y?$JOTGowZdCPw9CU=(p95M7#{~Un*+TpjVW_G$jVBL%CnXk%Ed$V?4 z;}3OYiz@_2ubp!_>uLOH-Uo5*L36HSMP^EiFdlKMp0RLtX2FD=z5NbOt+KG7nN;wH zG<g!-UD|f!=R5st_kyX3mLR)`jYoII(CvO-2E|QD!raw0GHIGlc&Vot!V`AvHyJY- zv77y1H0R%-?o#Fl#T3Zg@%;(TtU?<cjL!A9fJ&lAsWD5LKdb9o)z4l0HdaiZ4Fl9v zRYg>{urGQ(Q&XwNa#ULSKDM0WWlz#^hV(7-!xScjX}W&pEA#i})yPaQpU0^&=lPKM zovo7ji>-Uubsb&$1i6Xti5*v0gqyVb>|^;74n0+8b(%N?Q(+!GVIEC03G)gY&sOPq ztX#puUa6}in=<K!frSnEDL)Uz9^hbOJ~ZmeGn<~X54gP+A7(-<JI>!RlJk*?rP*ON zJ&&7p{juaF!ly^VO2SL9zQk;HhtcxknZSCjWM2JVo~2ZJrtegzMUG67FPYOc`B1KD z`&wZ`^ZGLOOLv`E4epYh4t%a?=?RB+_SwN(-z^Vs!&0CG{YBS&UHJ34!?Vk`*TL9U zuP}6i^R(qzj74Qx${e$|pVXI6Hm}c4F9Z+7kK7!28Sb}~Y47CDz3ODdr?hr6nF>x| zDD$=1R{ivcX?9=&kFp|`JE|#e1o;}aJ#N|Q%7gYE7kc8jLtFfWRoNL5%~$C;=6ySO zyuDB&Cl~}3^!egfzBFt*u<zcUeuakNemFw*f|yOEZ(8a(u3z~<?G<QZLShKJg+r{I zX^rUR=cUYZ&%5J0I7UuDKV80QMrvtuPei!MxA*K7peg>tkE5!Ep+xtYrWHe@|NMHL zUumr1P!K2I1C+CbJRIa}<Vw2F`!yYE?{OJ@Nq&Y$j~+tS%s={u36Z+v+8~jtPL7># zscxQ=K@E%_{mL8tb62Kc>?ju@uE>SDmfz=V(=#0GW`A!M`@sSBOsyt2vjlu$DRcNU zZ_J0C{3kIaH^L88O&CkM^Pc23Y<oQ6?F)z7+kdLN*-9Nr^@Q-rm_#iPdo*8Lu7sOB zarj*qhu9JFs9>Tt=ULb^Ikc2HaA^L<2d~mo=a4QJDu^b%8GD<It=2^hJ-uPV${8h* zOcteQyqBJkywtb3)C-x<^ku3ZYBT?dA=5t##<%b`*P-99D-U*Z&F~=jAeMB!^d0iA z*LBk~*|Ostfc`|p<|jN*U!cAH1FLj9#jW0cNBtBh!MmJYW>s+&3pZpA?EB@0L)V++ z^a_u`w{-Nf#<?;zCG$<s%vb3-xXF$FH5Owg<k+z>xv+?hSJ|@pGd25*b)9Q-za|^X zi*ycQojIeP%CgjRd<VyKwP&fxhu~XSEj$Q28hH~&IFou2L$B5z(YDNJW&TCB7&2SH zjofAuxBm0(+P}E7FQcbjAG~O$IyjIx^4n5oxaQ9N37Jr5hYQ9)`k4DQVrazeb6YK& zf5dt<xgtBptU`_?lKtg?^xm_>Y;hZ&aChVJtK`~b%21N@3)%6OP9oV7WVl{x$sCyQ zqZ%$W_xFibGDQm?LVC|6l2#wPWRBk98#NnmpF<DR!bzO<bOt>=3w?*puhVq1Z7|_W z^)>Fza~-S~zok-(U6>bU*0625?47ez89@pLn5x2;ut~Pg*C~cX(aVMLD_7LP22YTa zB=F`yS(-Ncvc&D7x`#Che;`xjX4;0U1c_8JF+E?U=a`$AQ#Y|s#LCaasYrtMcy(q) zOPR;ww=})g|85FgAYB-Qmm~5tsMP9_Mt;72_}={U<yHO^nKFb#Y%h^Sb2-!C3CEM3 zFV}U;?HC#pTgbqsW!ze+YYmyhpFgVW(3}2b%glz-BdI2y`&a3?nkHO1|M}73$u1@& zU&eK9f?fUkbk#RG+lX7|R>V+qk;jYqsaHu?#Kt&oYd$pQ3HJ`SJ7Oa%JdY*$Fn|3< zg=x+;&-L?8S0*``m#8e^B4M|x_l|wW&(?P+w|So)1<pdf{G($qu)$5lt#iv??)NL{ z2IUDaLV2|fI?!{Ka2NISMs*L(TnRVeS=BSLup+<v1oKrg2M+zYpDUu1mMV+P6j5TC z))-4u=5hYM^Q*KW1;RogOXXx+$j_(ecYo5O2X*CsO*PxLO<hUfNxtZbjZ<AdNz(bb zk_ivoc6=`^U9)E?^OGQhIEL{Je~uZ(E9Ke7A}{+eV69m-&xU1UWM|%c-N80J!@=&> zjIqhVf~jFc@J=jcDz0N$F`|pO{Y`&19!*(MW+X${+GASJSIN9Od&7yQYh<BXh8c)l zSVW@EX+0q-nFEJz_Bk~kLJr-sLqRMJPS(iJQM3P8AGnD_so69Qw@qb}H9kv&Cyd@< zSD%dmK?T~<G*-@U4Sx>od+YGp)RCtblPgew4|UqK9y?Cr*ZFZy{?uo`Q<Jc^ZOOn! zG8f`imW6=&ho#KphD68ucFp!)0W(JNgArZcaLus#nbgwLzVXNE-=Y5CX|orU7xsU^ zb$x?-SRkS@(^$wHdVYQTUY=C|)bW#{vNLDrGCdKqZmpTrh}#{r8hB&>13zM2swVsk z7B%|Mf$`s~Z<%W>T0+?DPZ;?~SJg#atyuL%+`d+fs2R8770SBL)W#<fSIN-%M=zNp zKi}-nHQ7`J6-E5Y%5sziR#oM+zc01ywLSH7bl2<%=S8kO@w0(_KRdj=am^hVFF$dh zARwJt*)tHhfeB|G-~JmRj!mKnW!*^kT~GYkh}+@MS1Ui8Ji#11ygfUHSUOz6eWQ06 zJ(52T*I0ZO|FJ0<G;<I4NnahL;&x!d^L6!J^Sh#1)lIg*^h|NX$spl;mCS(&cly`X z;sisI{ER0vr83uD${c#`*gJ_uJ9p!!93>Y<knYiZZMMx0zgzw9UVF6iLjNh2QoYW( z$=~y}*%p)cJ%zizYb4#KS`C$QW|A-A|9oA@e0KYuh-NJdwnGLiFN`GJAa=BrIWXZ) zKUd5V#y%67lAS|iA~%<K!rSynJN61>B9o3&|7*V}eZvHI;Lw}3AFMeWmn-42Y>btJ z>v}E|jhU_w@{^Xw**nK;;!=+Q4`he<_1JG}i=XpVG6&wiwZ-lH?e%J~uSAuGFffcd lvrWB=$epi}IWXb7buDI-_hCcX#jU2OU2qB7Lcx_k{{v_s2ZI0r literal 0 HcmV?d00001 diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs new file mode 100644 index 0000000..cb4ea53 --- /dev/null +++ b/crates/victory-formats/src/bcpack.rs @@ -0,0 +1,1398 @@ +//! BCPack: lossless packing of BC1-BC7 block streams, as the console's +//! DirectStorage hardware unpacks them. Decode only; BC2 is left out (no +//! title data uses it). +//! +//! A packed stream has no header. It is 12 or 16 interleaved rANS *lanes*; +//! each lane is a run of fragments (header byte, length, payload) coded with +//! one of 128 static models, and a fixed schedule decides which lane takes +//! the next input byte. The lanes' symbols form one record per block: two +//! back references (to one of the last 256 blocks, or to a per-format +//! dictionary that stands in for blocks -1 to -255) and the residuals of the +//! endpoints and indices against them. The models, the index rank tables, +//! the BC7 control codes and the dictionaries are constants of the format, +//! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]). + +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "BCPack: {}", self.0) + } +} + +impl std::error::Error for Error {} + +const MODELS: usize = 128; +const BUCKETS: usize = 9; +const HISTORY: usize = 256; +const DICTIONARY: usize = 255; +/// rANS: decode while the state is above this, read while below. +const LOW: u32 = 1 << 24; +/// Input bytes per schedule round. +const ROUND_BYTES: usize = 8; + +/// Bytes of the table file (see [`Tables::parse`]). +pub const TABLES_SIZE: usize = MODELS * BUCKETS * 2 + + 256 + + 64 + + 256 + + 64 + + 64 + + 512 * 2 + + DICTIONARY * (6 + 16 + 8 + 32 + 2 + 16 + 4 + 32 + 25 + 33 + 50 + 66); + +/// Endpoints and indices of BC1, BC3, BC4 and BC5: small unsigned values, +/// summed per element modulo the element's width. +#[derive(Clone, Copy, Default)] +struct Plain { + ep: [u8; 8], + ix: [u8; 32], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ep { + /// Endpoint 0 R G B, then endpoints 1-3, left-aligned and biased. + e: [[u16; 3]; 4], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ix { + mode: u8, + ix: [i16; 16], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ep { + ctrl: u16, + /// Per subset: R0 R1 G0 G1 B0 B1 A0 A1, left-aligned. + rows: [[u16; 8]; 3], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ix { + bits: [u8; 2], + ix: [[i16; 16]; 2], +} + +/// The format's constant tables. +pub struct Tables { + freq: [[u32; BUCKETS]; MODELS], + start: [[u32; BUCKETS]; MODELS], + /// ceil(2^32 / freq): exact division for the offsets inside a bucket. + recip: [[u64; BUCKETS]; MODELS], + rank1: [u8; 256], + rank3a: [u8; 64], + rank3c: [u8; 256], + rank4: [u8; 64], + rank5: [u8; 64], + ctrl7: [u16; 512], + bc1: Vec<Plain>, + bc3: Vec<Plain>, + bc4: Vec<Plain>, + bc5: Vec<Plain>, + bc6: Vec<(Bc6Ep, Bc6Ix)>, + bc7: Vec<(Bc7Ep, Bc7Ix)>, +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn bytes<const N: usize>(&mut self) -> [u8; N] { + let (head, rest) = self.0.split_at(N); + self.0 = rest; + head.try_into().unwrap_or([0; N]) + } + fn u8(&mut self) -> u8 { + self.bytes::<1>()[0] + } + fn u16(&mut self) -> u16 { + u16::from_le_bytes(self.bytes()) + } +} + +impl Tables { + /// The tables VIctory ships with. + pub fn builtin() -> Result<Tables, Error> { + Tables::parse(include_bytes!("bcpack-tables.bin")) + } + + /// Reads the table file: 128 x 9 u16 model frequencies (per bucket, the + /// frequency of each of its symbols), the rank tables (BC1 256 B, BC3 + /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control + /// words, then 255 dictionary entries per format in format order: BC1 + /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode, + /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16). + /// Little-endian, no padding. Every model must tile 65536. + pub fn parse(bytes: &[u8]) -> Result<Tables, Error> { + if bytes.len() != TABLES_SIZE { + return Err(Error("table file has the wrong size")); + } + let mut r = Reader(bytes); + let mut freq = [[0u32; BUCKETS]; MODELS]; + let mut start = [[0u32; BUCKETS]; MODELS]; + let mut recip = [[0u64; BUCKETS]; MODELS]; + for m in 0..MODELS { + for f in &mut freq[m] { + *f = u32::from(r.u16()); + } + // Model 16 g + shape has g + 2 buckets; bucket b > 0 holds 2^(b-1) symbols. + let used = m / 16 + 2; + let mut at = 0u32; + for b in 0..used { + if freq[m][b] == 0 { + return Err(Error("a model has an empty bucket")); + } + start[m][b] = at; + recip[m][b] = (1u64 << 32).div_ceil(u64::from(freq[m][b])); + at += freq[m][b] << b.saturating_sub(1); + } + if at != 1 << 16 { + return Err(Error("a model does not tile 65536")); + } + start[m][used..].fill(1 << 16); + } + let rank1 = r.bytes(); + let rank3a = r.bytes(); + let rank3c = r.bytes(); + let rank4 = r.bytes(); + let rank5 = r.bytes(); + let mut ctrl7 = [0u16; 512]; + for c in &mut ctrl7 { + *c = r.u16(); + } + let mut plain = |ep: usize, ix: usize| { + (0..DICTIONARY) + .map(|_| { + let mut p = Plain::default(); + for v in &mut p.ep[..ep] { + *v = r.u8(); + } + for v in &mut p.ix[..ix] { + *v = r.u8(); + } + p + }) + .collect::<Vec<_>>() + }; + let bc1 = plain(6, 16); + let bc3 = plain(8, 32); + let bc4 = plain(2, 16); + let bc5 = plain(4, 32); + let bc6 = (0..DICTIONARY) + .map(|_| { + // The endpoint entry's mode byte plays no part in decoding. + r.u8(); + let mut ep = Bc6Ep::default(); + for v in ep.e.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc6Ix { + mode: r.u8(), + ..Default::default() + }; + for v in &mut ix.ix { + *v = r.u16() as i16; + } + (ep, ix) + }) + .collect(); + let bc7 = (0..DICTIONARY) + .map(|_| { + let mut ep = Bc7Ep { + ctrl: r.u16(), + ..Default::default() + }; + for v in ep.rows.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc7Ix { + bits: [r.u8(), r.u8()], + ..Default::default() + }; + for v in ix.ix.as_flattened_mut() { + *v = r.u16() as i16; + } + (ep, ix) + }) + .collect(); + Ok(Tables { + freq, + start, + recip, + rank1, + rank3a, + rank3c, + rank4, + rank5, + ctrl7, + bc1, + bc3, + bc4, + bc5, + bc6, + bc7, + }) + } +} + +/// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives +/// the block count. The stream carries no size: bytes after the last one the +/// lanes need are ignored, a stream that runs out is an error. +pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { + let block = match bc { + 1 | 4 => 8, + 3 | 5 | 6 | 7 => 16, + _ => return Err(Error("unsupported BC format")), + }; + if dst.is_empty() || !dst.len().is_multiple_of(block) { + return Err(Error("destination is not a whole number of blocks")); + } + let blocks = dst.len() / block; + let (widths, per): (&[u8], usize) = match bc { + 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1), + 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + }; + let stride = widths.len() * per; + let mut records = vec![0u8; blocks * stride]; + let mut next = src.iter().copied(); + lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + let records = records.chunks_exact(stride); + let out = dst.chunks_exact_mut(block); + let t = tables; + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + 6 => bc6(records, out, &t.bc6), + _ => bc7(records, out, t), + } +} + +// Lanes. + +#[derive(Clone, Copy, Default)] +struct Lane { + /// Symbol bits - 1 at the full alphabet. + width: u8, + /// 0 header, 1 length (low byte), 2 length high byte, 3 payload. + phase: u8, + long: bool, + reset: bool, + model: u8, + need: bool, + latch: Option<u8>, + out: Option<u8>, + stalled: bool, + x: u32, + left: u32, +} + +impl Lane { + /// One step: take the latched byte (header, length or payload) and + /// decode at most one symbol. + fn step(&mut self, t: &Tables) -> Result<(), Error> { + if self.phase != 3 { + let Some(b) = self.latch.take() else { + return Ok(()); + }; + self.need = true; + match self.phase { + 0 => { + // The top two bits shrink the alphabet; width >= 3. + let group = self.width - (b >> 6); + self.model = group * 16 + (b & 15); + self.reset = b & 0x10 != 0; + self.long = b & 0x20 != 0; + self.left = 0; + self.phase = 1; + } + 1 if self.long => { + self.left = b.into(); + self.phase = 2; + } + 1 => { + self.left = u32::from(b) + 1; + self.phase = 3; + } + _ => { + self.left = (u32::from(b) << 8 | self.left) + 257; + self.phase = 3; + } + } + return Ok(()); + } + let mut x = self.x; + if x < LOW + && let Some(b) = self.latch.take() + { + self.left = self.left.wrapping_sub(1); + x = x << 8 | u32::from(b); + } + self.need = self.left != 0 && self.latch.is_none(); + if x > LOW { + let freq = &t.freq[usize::from(self.model)]; + let start = &t.start[usize::from(self.model)]; + let slot = x & 0xffff; + // The bucket: starts are ascending, and 65536 past the model's last. + let b = start[1..].iter().filter(|&&s| s <= slot).count(); + // Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency + // are below 2^16, where the reciprocal divides exactly. + let sym = match b { + 0 => 0, + 1 => 1, + _ => { + let rec = t.recip[usize::from(self.model)][b]; + (1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8 + } + }; + // Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1. + let (f, c) = if sym == 0 { + (freq[0] - 1, 1) + } else { + let k = (8 - sym.leading_zeros()) as usize; + let f = freq[k]; + ( + f, + (u32::from(sym) - (1 << (k - 1))) + .wrapping_mul(f) + .wrapping_add(start[k]) + & 0xffff, + ) + }; + self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot); + self.out = Some(sym); + } else if self.left != 0 { + // At exactly 2^24 the lane neither reads nor decodes again; only a + // lane that has delivered its symbols may end up there. + self.x = x; + } else { + // The fragment ends; a byte read in this step does not reach the carried state. + self.phase = 0; + self.need = self.latch.is_none(); + if self.reset { + self.x = 0; + } + } + Ok(()) + } +} + +/// Decodes `per` symbols per block on every lane into `records` (one record +/// of `widths.len() * per` symbols per block), taking input from `fetch` +/// (given the lane that takes the byte) in the order of the schedule: each +/// round the lanes step in order and take at most 8 bytes between them. +// shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s +// on one core); if texture streaming needs more, run the schedule only to +// split the input per lane and decode the lanes apart. +fn lanes( + t: &Tables, + widths: &[u8], + per: usize, + blocks: usize, + mut fetch: impl FnMut(usize) -> Option<u8>, + records: &mut [u8], +) -> Result<(), Error> { + let mut lanes = [Lane::default(); 16]; + let lanes = &mut lanes[..widths.len()]; + for (lane, &width) in lanes.iter_mut().zip(widths) { + lane.width = width; + lane.need = true; + } + let stride = widths.len() * per; + let full = (1u32 << widths.len()) - 1; + let (mut pos, mut done, mut idle) = (0, 0u32, 0); + while pos < blocks * per { + let (mut taken, mut moved) = (0, false); + for (j, lane) in lanes.iter_mut().enumerate() { + let bit = 1 << j; + let before = taken; + if !lane.stalled { + lane.step(t)?; + } + let waiting = lane.out.is_some() && done & bit != 0; + if lane.need && !waiting && taken < ROUND_BYTES { + // Past the end nothing arrives; in a valid stream only finished lanes ask there. + if let Some(b) = fetch(j) { + lane.latch = Some(b); + taken += 1; + } + } + lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting; + if !lane.stalled + && let Some(sym) = lane.out.take() + { + records[pos / per * stride + j * per + pos % per] = sym; + done |= bit; + moved = true; + } + } + if done == full { + pos += 1; + done = 0; + moved = true; + } + // Nothing read and nothing delivered for a few rounds: no lane can go on. + idle = if taken > 0 || moved { 0 } else { idle + 1 }; + if idle > 3 { + return Err(Error("the stream ends early or is corrupt")); + } + } + Ok(()) +} + +// Blocks. + +/// The record's endpoint and index references. +fn references(s: &[u8], paired: bool) -> (usize, usize) { + let (d, ix) = if paired { + (interleave(s[0], s[1]), interleave(s[2], s[3])) + } else { + (s[0], s[1]) + }; + let delta = (d >> 1) ^ (d & 1).wrapping_neg(); + (usize::from(ix.wrapping_add(delta)), usize::from(ix)) +} + +/// Two 4-bit symbols, the first on the even bits. +fn interleave(a: u8, b: u8) -> u8 { + let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); + spread(a) | spread(b) << 1 +} + +/// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first +/// block into the dictionary. +fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { + match r { + 0 => zero, + r if r <= i => &history[(i - r) % HISTORY], + r => &dictionary[r - i - 1], + } +} + +/// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +fn zz(v: u8, bits: u32) -> u8 { + let mask = ((1u32 << bits) - 1) as u8; + ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask +} + +/// Element widths of the plain formats' endpoints and indices. +struct Widths { + ep: [u8; 8], + ix: [u8; 32], + paired: bool, +} + +const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { + let mut ix = [0; 32]; + let mut k = 0; + while k < ix3 + ix2 { + ix[k] = if k < ix3 { 3 } else { 2 }; + k += 1; + } + Widths { ep, ix, paired } +} + +const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); +const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); +const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); +const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); + +fn plain<'a>( + records: impl Iterator<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + dictionary: &[Plain], + w: &Widths, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8]), +) -> Result<(), Error> { + let mut history = vec![Plain::default(); HISTORY]; + let zero = Plain::default(); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; + let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + } + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); + } + Ok(()) +} + +/// 2-bit index residuals: one symbol per 2x2 quad. +fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { + for (q, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym)]; + let base = (q >> 1) * 8 + (q & 1) * 2; + for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { + ix[base + p] = v >> (2 * k) & 3; + } + } +} + +/// 3-bit index residuals: one symbol per two pixels in raster order. +fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for (k, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym & 63)]; + ix[2 * k] = v & 7; + ix[2 * k + 1] = v >> 4 & 7; + } +} + +fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { + v.ep[k] = zz(s[2 + k], bits); + } + quads(&t.rank1, &s[8..12], &mut v.ix); + v +} + +fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { + // Colour lanes carry each channel's two endpoints together. + let mut v = Plain { + ep: [ + zz(s[14], 5), + zz(s[16], 6), + zz(s[18], 5), + zz(s[15], 5), + zz(s[17], 6), + zz(s[19], 5), + zz(s[4], 8), + zz(s[5], 8), + ], + ..Default::default() + }; + pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); + quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + v +} + +fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); + pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); + v +} + +fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for k in 0..4 { + v.ep[k] = zz(s[4 + k], 8); + } + pairs(&t.rank5, &s[8..24], &mut v.ix); + v +} + +/// Indices along the endpoint line -> BC1 and BC4 codes. +const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; +const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; + +fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { + let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); + let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); + let bits = (0..16).fold(0, |acc, p| { + acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) + }); + out[..2].copy_from_slice(&c0.to_le_bytes()); + out[2..4].copy_from_slice(&c1.to_le_bytes()); + out[4..8].copy_from_slice(&bits.to_le_bytes()); +} + +/// BC4 half: endpoints are kept 128 below their stored value. +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { + let bits = (0..16).fold(0u64, |acc, p| { + acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) + }); + let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; + out[..8].copy_from_slice(&v.to_le_bytes()); +} + +fn bc1_pack(v: &Plain, out: &mut [u8]) { + bc1_color(&v.ep, &v.ix, out); +} + +fn bc3_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); + bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); +} + +fn bc4_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); +} + +fn bc5_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); +} + +/// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); + if odd_first { [odd, even] } else { [even, odd] } +} + +/// Index residual plus reference, both left-aligned to 16 bits at their own +/// widths, back to `bits` bits (signed). +fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { + let up = |v: i16, b: u8| { + if b == 0 || b > 16 { + 0 + } else { + (v as u16) << (16 - b) + } + }; + let sum = up(cur, bits).wrapping_add(up(refv, ref_bits)) as i16; + if bits == 0 { 0 } else { sum >> (16 - bits) } +} + +/// Little-endian bit writer for one 128-bit block. +#[derive(Default)] +struct Bits { + v: u128, + at: u32, +} + +impl Bits { + fn put(&mut self, value: u64, n: u32) { + if n > 0 && self.at < 128 { + self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + } + self.at += n; + } +} + +// BC7. + +/// Public BC7 anchor indices: second subset of two; second and third of three. +const ANCHOR2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, + 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, + 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; +const ANCHOR3A: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, + 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, + 10, 8, 13, 15, 12, 3, 3, +]; +const ANCHOR3B: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, + 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// Endpoint bits of R G B A per mode (public), before p-bits and rotation. +const BC7_BITS: [[u8; 4]; 8] = [ + [4, 4, 4, 0], + [6, 6, 6, 0], + [5, 5, 5, 0], + [7, 7, 7, 0], + [5, 5, 5, 6], + [7, 7, 7, 8], + [7, 7, 7, 7], + [5, 5, 5, 5], +]; +/// Index bits of the primary and secondary sets per mode. +const BC7_INDEX: [[u8; 2]; 8] = [ + [3, 0], + [3, 0], + [2, 0], + [2, 0], + [3, 2], + [2, 2], + [4, 0], + [2, 0], +]; + +fn pbits(mode: u16) -> bool { + matches!(mode, 0 | 1 | 3 | 6 | 7) +} + +/// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha +/// with the rotated channel. +fn bc7_precision(ctrl: u16) -> [u8; 4] { + let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let mut p = BC7_BITS[usize::from(mode)]; + if rot != 0 { + p.swap(3, rot - 1); + } else if pbits(mode) { + p[0] += 1; + } + p +} + +fn bc7<'a>( + records: impl Iterator<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + t: &Tables, +) -> Result<(), Error> { + let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + // Rows the reference lacks build on its first row. + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; + } + let mask = 0xffffu16 << (16 - p); + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = + (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); + } + } + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { + if bits[set] == 0 { + continue; + } + for (k, o) in offsets.into_iter().enumerate() { + for (b, &byte) in s[o..o + 2].iter().enumerate() { + let pair = nibbles(byte, k < 3); + for (h, &v) in pair.iter().enumerate() { + let p = 4 * k + 2 * b + h; + ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); + } + } + } + } + history[i % HISTORY] = (ep, ix); + bc7_pack(&ep, &ix, prec, block); + } + Ok(()) +} + +fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { + let ctrl = ep.ctrl; + let mode = ctrl & 7; + let subsets = usize::from((ctrl & 0xff) >> 6); + let part = usize::from(ctrl >> 8 & 63); + let rot = usize::from(ctrl >> 3 & 3); + let mut w = Bits::default(); + w.put(1 << mode, u32::from(mode) + 1); + match mode { + 0 => w.put(part as u64, 4), + 1 | 2 | 3 | 7 => w.put(part as u64, 6), + 4 => { + w.put(rot as u64, 2); + w.put(u64::from(ctrl >> 5 & 1), 1); + } + 5 => w.put(rot as u64, 2), + _ => {} + } + let ends = 2 * subsets; + let field = |row: usize, col: usize, p: u8| u64::from(ep.rows[row][col] >> (16 - p)); + let mut order = [0, 1, 2, 3]; + if rot != 0 { + order.swap(3, rot - 1); + } + for ch in order { + let p = prec[ch]; + if p == 0 { + continue; + } + let drop = u32::from(ch == 0 && pbits(mode)); + for e in 0..ends { + w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop); + } + } + match mode { + 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)), + m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), + _ => {} + } + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mut indices = |set: usize| { + let bits = ix.bits[set]; + for (p, &v) in ix.ix[set].iter().enumerate() { + let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + w.put(u64::from(v as u16), n); + } + }; + match mode { + 4 => { + indices(1); + indices(0); + } + 5 => { + indices(0); + indices(1); + } + _ => indices(0), + } + out.copy_from_slice(&w.v.to_le_bytes()); +} + +// BC6H. + +/// Bits of endpoint 0, then of the other endpoints' R, G, B, per mode 1-14. +const BC6_BITS: [[u8; 4]; 15] = [ + [0; 4], + [10, 5, 5, 5], + [7, 6, 6, 6], + [11, 5, 4, 4], + [11, 4, 5, 4], + [11, 4, 4, 5], + [9, 5, 5, 5], + [8, 6, 5, 5], + [8, 5, 6, 5], + [8, 5, 5, 6], + [6, 6, 6, 6], + [10, 10, 10, 10], + [11, 9, 9, 9], + [12, 8, 8, 8], + [16, 4, 4, 4], +]; +/// Mode code and its width, modes 1-14. +const BC6_CODE: [(u64, u32); 15] = [ + (0, 0), + (0, 2), + (1, 2), + (2, 5), + (6, 5), + (10, 5), + (14, 5), + (18, 5), + (22, 5), + (26, 5), + (30, 5), + (3, 5), + (7, 5), + (11, 5), + (15, 5), +]; + +/// A run of the public BC6H layout: `len` bits of channel `ch` (0-2; 3 is +/// the partition) of endpoint `ep`, from bit `first` up. +#[derive(Clone, Copy)] +struct Run { + ch: u8, + ep: u8, + first: u8, + len: u8, +} + +const fn r(ch: u8, ep: u8, first: u8, len: u8) -> Run { + Run { ch, ep, first, len } +} + +const R: u8 = 0; +const G: u8 = 1; +const B: u8 = 2; +const D: Run = r(3, 0, 0, 5); + +/// The header after the mode bits, per mode 1-14. Modes 13 and 14 write the +/// high base bits in ascending order (what the console's packer does). +#[rustfmt::skip] +const BC6_LAYOUT: [&[Run]; 15] = [ + &[], + &[ + r(G, 2, 4, 1), r(B, 2, 4, 1), r(B, 3, 4, 1), r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(G, 2, 5, 1), r(G, 3, 4, 1), r(G, 3, 5, 1), r(R, 0, 0, 7), r(B, 3, 0, 1), r(B, 3, 1, 1), + r(B, 2, 4, 1), r(G, 0, 0, 7), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 7), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 5), r(R, 0, 10, 1), r(G, 2, 0, 4), + r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(G, 3, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 5), r(G, 0, 10, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 0, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(G, 2, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(B, 2, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), + r(B, 0, 10, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 1, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(B, 3, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 9), r(B, 2, 4, 1), r(G, 0, 0, 9), r(G, 2, 4, 1), r(B, 0, 0, 9), r(B, 3, 4, 1), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(G, 3, 4, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 3, 2, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 3, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 5), + r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 6), + r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 0, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(G, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(G, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 6), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 6), r(G, 3, 4, 1), r(B, 3, 0, 1), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 6), + r(G, 2, 5, 1), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 6), r(G, 3, 5, 1), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 10), r(G, 1, 0, 10), r(B, 1, 0, 10)], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 9), r(R, 0, 10, 1), r(G, 1, 0, 9), + r(G, 0, 10, 1), r(B, 1, 0, 9), r(B, 0, 10, 1), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 8), r(R, 0, 10, 2), r(G, 1, 0, 8), + r(G, 0, 10, 2), r(B, 1, 0, 8), r(B, 0, 10, 2), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 6), r(G, 1, 0, 4), + r(G, 0, 10, 6), r(B, 1, 0, 4), r(B, 0, 10, 6), + ], +]; + +fn bc6_index_bits(mode: u8) -> u8 { + match mode { + 1..=10 => 3, + 11..=14 => 4, + _ => 0, + } +} + +fn bc6<'a>( + records: impl Iterator<Item = &'a [u8]>, + out: impl Iterator<Item = &'a mut [u8]>, + dictionary: &[(Bc6Ep, Bc6Ix)], +) -> Result<(), Error> { + let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); + let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); + let wide = |a: u8, b: u8| { + (0..8).fold(0u16, |acc, k| { + acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) + }) + }; + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); + } + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) + } else { + (e0, e1) + }; + let r = &pick(i, ep_ref, &history, dictionary, &zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); + } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); + } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; + } + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; + let bits = bc6_index_bits(mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { + let p = 2 * k + h; + ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); + } + } + history[i % HISTORY] = (ep, ix); + // Fields: the working value has its top bit flipped. + let field = |k: usize, c: usize| { + let sh = if k == 0 { shift[0] } else { shift[1 + c] }; + u64::from((ep.e[k][c] ^ 0x8000) >> sh) + }; + let mut w = Bits::default(); + let (code, n) = BC6_CODE[usize::from(mode)]; + w.put(code, n); + let part = s[31] & 31; + for run in BC6_LAYOUT[usize::from(mode)] { + if run.ch == 3 { + w.put(part.into(), 5); + } else { + w.put( + field(run.ep.into(), run.ch.into()) >> run.first, + run.len.into(), + ); + } + } + let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + for (p, &v) in ix.ix.iter().enumerate() { + let short = p == 0 || p == usize::from(anchor); + let v = (v as u16).wrapping_add(1 << (bits - 1)); + w.put(v.into(), u32::from(bits) - u32::from(short)); + } + block.copy_from_slice(&w.v.to_le_bytes()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_shipped_tables_parse() { + assert!(super::Tables::builtin().is_ok()); + } + + use super::*; + + /// Tables we made: uniform models, identity ranks, a BC7 code per mode, + /// empty dictionaries. + fn tables() -> Vec<u8> { + let mut t = Vec::new(); + for m in 0..MODELS { + let g = m / 16; + for b in 0..BUCKETS { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend((0..=255u8).map(|v| v & 0x77)); // rank1 (unused by the tests beyond 2-bit fields) + t.extend(0..64u8); // rank3a + t.extend(0..=255u8); // rank3c + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); // rank4: low 3 bits, next 3 bits + t.extend(0..64u8); // rank5 + for code in 0..512u16 { + // Code c: mode 6 (one subset), the only one the tests use. + let ctrl: u16 = if code == 0 { 0x46 } else { 0 }; + t.extend_from_slice(&ctrl.to_le_bytes()); + } + t.resize(TABLES_SIZE, 0); + t + } + + /// A lane's symbols as one fragment: uniform model, rANS from 2^24, no + /// reset, so the lane keeps 2^24 when it ends. + fn fragment(width: u8, symbols: &[u8]) -> Vec<u8> { + let f = 1u32 << (15 - width); + let mut x = LOW; + let mut bytes = Vec::new(); + for &s in symbols.iter().rev() { + let (freq, start) = if s == 0 { + (f - 1, 1) + } else { + (f, u32::from(s) * f) + }; + while x >= (freq << 16) { + bytes.push(x as u8); + x >>= 8; + } + x = ((x / freq) << 16) + x % freq + start; + } + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.reverse(); + let mut out = vec![0]; + if bytes.len() > 256 { + out[0] |= 0x20; + let n = bytes.len() - 257; + out.extend_from_slice(&[n as u8, (n >> 8) as u8]); + } else { + out.push((bytes.len() - 1) as u8); + } + out.extend(bytes); + out + } + + /// Interleaves per-lane fragments the way the decoder takes bytes. A lane + /// that has finished still asks: a filler fragment (two payload bytes) + /// brings its state to 2^24 with a byte latched, which parks it for good. + fn stream(t: &Tables, widths: &[u8], per: usize, records: &[Vec<u8>]) -> Vec<u8> { + let stride = widths.len() * per; + let mut queues: Vec<std::collections::VecDeque<u8>> = (0..widths.len()) + .map(|j| { + let syms: Vec<u8> = records + .iter() + .flat_map(|r| r[j * per..j * per + per].to_vec()) + .collect(); + let mut bytes = fragment(widths[j], &syms); + bytes.extend([0, 1, 0, 0]); + bytes.into() + }) + .collect(); + let mut out = Vec::new(); + let mut check = vec![0; records.len() * stride]; + let fetch = |j: usize| { + let b = queues[j] + .pop_front() + .expect("a parked lane asked for input"); + out.push(b); + Some(b) + }; + lanes(t, widths, per, records.len(), fetch, &mut check).unwrap(); + assert_eq!(check, records.concat()); + out + } + + const BC4_LANES: [u8; 12] = [7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5]; + + fn zigzag(v: i32) -> u8 { + if v >= 0 { + (2 * v) as u8 + } else { + (-2 * v - 1) as u8 + } + } + + #[test] + fn bc4_blocks_with_and_without_references() { + let t = Tables::parse(&tables()).unwrap(); + // Block 0: endpoints 10, -3 (+128 stored), indices p -> p & 7. + let mut b0 = vec![0, 0, zigzag(10), zigzag(-3)]; + b0.extend((0..8).map(|k| ((2 * k) & 7) | ((2 * k + 1) & 7) << 3)); + // Block 1 refers to block 0 for both: residual endpoints +1, +1; indices +1. + let mut b1 = vec![0, 1, zigzag(1), zigzag(1)]; + b1.extend((0..8).map(|_| 1 | 1 << 3)); + let src = stream(&t, &BC4_LANES, 1, &[b0, b1]); + let mut dst = [0u8; 16]; + decode(4, &src, &mut dst, &t).unwrap(); + let block = |e0: u8, e1: u8, ix: &dyn Fn(usize) -> usize| { + let bits = (0..16).fold(0u64, |a, p| a | BC4_CODE[ix(p)] << (16 + 3 * p)); + (u64::from(e0) | u64::from(e1) << 8 | bits).to_le_bytes() + }; + assert_eq!(dst[..8], block(138, 125, &|p| p & 7)); + assert_eq!(dst[8..], block(139, 126, &|p| (p + 1) & 7)); + } + + #[test] + fn lanes_take_bytes_in_schedule_order_and_long_fragments() { + let t = Tables::parse(&tables()).unwrap(); + // Many blocks: long fragments (over 256 payload bytes) on the wide lanes. + let records: Vec<Vec<u8>> = (0..400u32) + .map(|i| { + let mut r = vec![0, 0, (i * 7) as u8, (i * 13) as u8]; + r.extend((0..8).map(|k| ((i + k) * 5 % 64) as u8)); + r + }) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut got = vec![0u8; records.len() * 12]; + let mut next = src.iter().copied(); + lanes(&t, &BC4_LANES, 1, records.len(), |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat()); + } + + #[test] + fn bc7_mode6_block() { + let t = Tables::parse(&tables()).unwrap(); + // Control code 0 -> mode 6; endpoints R 8 bits (p-bit low), G B A 7 bits. + let mut s = vec![0u8; 32]; + s[4] = zigzag(0x55); // R0 = 0x55: field 0x2a, p-bit 1 + s[5] = zigzag(-1); // R1 = 0xff (8 bits) + s[6] = zigzag(3); + s[10] = zigzag(0x7f >> 1); + let src = stream( + &t, + &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], + 2, + &[s], + ); + let mut dst = [0u8; 16]; + decode(7, &src, &mut dst, &t).unwrap(); + let mut w = Bits::default(); + w.put(1 << 6, 7); + for (v, n) in [ + (0x2a, 7), + (0x7f, 7), + (3, 7), + (0, 7), + (0, 7), + (0, 7), + (0x3f, 7), + (0, 7), + ] { + w.put(v, n); + } + w.put(1, 1); + w.put(1, 1); + assert_eq!(dst, w.v.to_le_bytes()); + } + + #[test] + fn malformed_input_is_an_error() { + let t = Tables::parse(&tables()).unwrap(); + let records: Vec<Vec<u8>> = (0..64u8) + .map(|i| vec![0, 0, i, i, 1, 2, 3, 4, 5, 6, 7, 8]) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut dst = vec![0u8; 64 * 8]; + decode(4, &src, &mut dst, &t).unwrap(); + // Truncated. + assert!(decode(4, &src[..src.len() / 2], &mut dst, &t).is_err()); + // Headers promising more payload than the stream holds. (Other corrupt + // headers decode to garbage: the format has no redundancy.) + let headers = [[0x30; 8], [0xff; 8]].concat(); + assert!(decode(4, &headers, &mut dst[..8], &t).is_err()); + assert!(decode(4, &[], &mut dst, &t).is_err()); + // Destination not a whole number of blocks, empty, more blocks than coded. + assert!(decode(4, &src, &mut dst[..12], &t).is_err()); + assert!(decode(4, &src, &mut [], &t).is_err()); + assert!(decode(4, &src, &mut vec![0u8; 65 * 8], &t).is_err()); + // Unsupported formats, bad tables. + assert!(decode(2, &src, &mut dst, &t).is_err()); + assert!(Tables::parse(&[0; 16]).is_err()); + let mut no_tiling = tables(); + no_tiling[0] = 1; + assert!(Tables::parse(&no_tiling).is_err()); + } + + #[test] + fn noise_never_panics() { + let t = Tables::parse(&tables()).unwrap(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for round in 0..300 { + let len = round * 7 % 900; + let src: Vec<u8> = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }) + .collect(); + for bc in [1, 3, 4, 5, 6, 7] { + let mut dst = vec![0u8; 16 * (1 + round % 40)]; + let _ = decode(bc, &src, &mut dst, &t); + } + } + } + + /// Compares with reference outputs made outside the repository: + /// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a + /// directory of `<name>.bc<n>` packed chunks with `<name>.out` beside them. + #[test] + #[ignore = "needs the format tables and reference chunks"] + fn reference_chunks() { + let tables = std::env::var_os("VICTORY_BCPACK_TABLES").expect("VICTORY_BCPACK_TABLES"); + let cases = std::env::var_os("VICTORY_BCPACK_CASES").expect("VICTORY_BCPACK_CASES"); + let t = Tables::parse(&std::fs::read(tables).unwrap()).unwrap(); + let mut n = 0; + for entry in std::fs::read_dir(cases).unwrap() { + let path = entry.unwrap().path(); + let Some(bc) = path + .extension() + .and_then(|e| e.to_str()?.strip_prefix("bc")?.parse().ok()) + else { + continue; + }; + let want = std::fs::read(path.with_extension("out")).unwrap(); + let mut got = vec![0u8; want.len()]; + decode(bc, &std::fs::read(&path).unwrap(), &mut got, &t).unwrap(); + assert!(got == want, "{}", path.display()); + n += 1; + } + assert!(n > 0); + } +} diff --git a/crates/victory-formats/src/lib.rs b/crates/victory-formats/src/lib.rs index 43c4345..f364177 100644 --- a/crates/victory-formats/src/lib.rs +++ b/crates/victory-formats/src/lib.rs @@ -1,6 +1,10 @@ //! Platform-level data formats, shared by every Xbox Series title. //! -//! Planned modules, each pure (bytes in, bytes out, no I/O): texture -//! layouts (RDNA2 swizzle modes to linear), BCPack textures, audio codecs -//! (XMA2, Opus), and the zlib streams used by hardware decompression. -//! Which come first depends on what Grand Theft Auto VI's assets contain. +//! Each module is pure (bytes in, bytes out, no I/O): [`texture`] (the +//! GPU's tiled texture layouts and copies to and from linear rows). Planned: +//! BCPack textures, audio codecs (XMA2, Opus), and the zlib streams used by +//! hardware decompression. + +pub mod bcpack; +pub mod texture; +pub mod xma; diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs new file mode 100644 index 0000000..8752447 --- /dev/null +++ b/crates/victory-formats/src/texture.rs @@ -0,0 +1,1007 @@ +//! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and +//! alignment, where each mip and array slice starts, the address of each +//! element, and copies between tiled memory and linear rows. +//! +//! Units: an element is a texel, or a 4x4 block of a block-compressed +//! format. Mips of one array slice (or one depth slab of a thick 3D texture) +//! are stored together, smallest first: the mip tail (the small mips sharing +//! one block) at offset 0, mip 0 last. +//! +//! The algorithm follows AMD's address library (addrlib), as shipped in Mesa +//! under `src/amd/addrlib`: block dimensions, mip placement and mip tails +//! from `gfx10addrlib.cpp` and `addrlib2.cpp` +//! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, +//! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, +//! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile +//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! RDNA2). addrlib carries this notice: +//! +//! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +//! SPDX-License-Identifier: MIT +//! +//! Permission is hereby granted, free of charge, to any person obtaining a +//! copy of this software and associated documentation files (the +//! "Software"), to deal in the Software without restriction, including +//! without limitation the rights to use, copy, modify, merge, publish, +//! distribute, sublicense, and/or sell copies of the Software, and to permit +//! persons to whom the Software is furnished to do so, subject to the +//! following conditions: the above copyright notice and this permission +//! notice shall be included in all copies or substantial portions of the +//! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +//! EXPRESS OR IMPLIED. + +/// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Swizzle(pub u32); + +impl Swizzle { + pub const LINEAR: Swizzle = Swizzle(0); + pub const SW_256B_S: Swizzle = Swizzle(1); + pub const SW_256B_D: Swizzle = Swizzle(2); + pub const SW_4KB_S: Swizzle = Swizzle(5); + pub const SW_4KB_D: Swizzle = Swizzle(6); + pub const SW_64KB_S: Swizzle = Swizzle(9); + pub const SW_64KB_D: Swizzle = Swizzle(10); + pub const SW_64KB_S_T: Swizzle = Swizzle(17); + pub const SW_64KB_D_T: Swizzle = Swizzle(18); + pub const SW_4KB_S_X: Swizzle = Swizzle(21); + pub const SW_4KB_D_X: Swizzle = Swizzle(22); + pub const SW_4KB_R_X: Swizzle = Swizzle(23); + pub const SW_64KB_Z_X: Swizzle = Swizzle(24); + pub const SW_64KB_S_X: Swizzle = Swizzle(25); + pub const SW_64KB_D_X: Swizzle = Swizzle(26); + pub const SW_64KB_R_X: Swizzle = Swizzle(27); + + /// log2 of the block size in bytes (0 for linear); `None` for modes + /// GFX10 does not have. + pub fn block_log2(self) -> Option<u32> { + Some(match self.0 { + 0 => 0, + 1 | 2 => 8, + 5 | 6 | 21..=23 => 12, + 9 | 10 | 17 | 18 | 24..=27 => 16, + _ => return None, + }) + } + + fn standard(self) -> bool { + matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25) + } + + fn display(self) -> bool { + matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26) + } + + fn z_order(self) -> bool { + self.0 == 24 + } + + /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the + /// GPU's pipe configuration. + pub fn xor(self) -> bool { + self.0 >= 16 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dimension { + Tex1d, + Tex2d, + Tex3d, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// The description makes no texture (zero size, bad element size, a + /// mode this dimension cannot use, too many mips). + Invalid, + /// A valid layout whose addressing is not implemented here. + Unsupported, + /// A buffer is smaller than the layout or the rows need. + TooSmall, +} + +/// One plane of a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Desc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth: u32, + pub mips: u32, + /// 1, 2, 4, 8 or 16. + pub element_bytes: u32, + /// Texels per element side: 1, or 4 for block compression. + pub block: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +/// Elements along one side of mip `mip`, as data and copies see it: texels +/// halve rounding down (to at least 1), then round up to whole elements. +fn dim(texels: u32, mip: u32, block: u32) -> u32 { + (texels >> mip).max(1).div_ceil(block) +} + +/// Elements along one side of mip `mip` for placement (padding, tail, +/// offsets): addrlib halves mip 0's elements rounding up, which can be one +/// more than [`dim`] for odd sizes. +fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 { + texels.max(1).div_ceil(block).div_ceil(1 << mip) +} + +/// Where one mip lives inside a slice. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mip { + /// Size in elements (depth 1 unless the texture is 3D). + pub width: u32, + pub height: u32, + pub depth: u32, + /// Padded size in elements: whole blocks, or the tail's share of one. + pub pitch: u32, + pub rows: u32, + pub depth_pitch: u32, + /// Byte offset of its first block in the slice (0 in the tail). + pub offset: u64, + /// In the mip tail: byte offset inside the tail block and the element + /// position the mip starts at. + pub tail: Option<Tail>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tail { + pub offset: u32, + pub x: u32, + pub y: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Layout { + pub desc: Desc, + /// Block dimensions in elements (linear: the pitch alignment, 1, 1). + pub block: [u32; 3], + /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes). + pub thick: bool, + /// Array slices, depth slabs of `block[2]` slices (thick), or depth + /// slices (thin and linear 3D). + pub slices: u32, + /// Bytes of one slice: its whole mip chain. + pub slice_size: u64, + pub size: u64, + pub alignment: u64, + /// The first mip in the tail; `mips.len()` without one. + pub first_tail_mip: u32, + pub mips: Vec<Mip>, + /// Byte offsets inside a block of each element coordinate bit, per + /// axis; empty for linear and unsupported modes. + pattern: [Vec<u32>; 3], +} + +/// Micro tile (256 bytes) patterns by log2 of the element size: for each +/// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), +/// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` +/// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`, +/// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger +/// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn. +const MICRO: [[&[u8; 16]; 5]; 3] = [ + [ + b"x0x1x2x3y0y1y2y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1y2x2", + b"------x0y0y1x1x2", + b"--------y0y1x0x1", + ], + [ + b"x0x1x2y1y0y2x3y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1x2y2", + b"------x0y0x1x2y1", + b"--------x0y0x1y1", + ], + [ + b"x0x1z0y0z1y1x2z2", + b"--x0z0y0z1y1x1z2", + b"----x0y0z0y1x1z1", + b"------x0z0y0x1z1", + b"--------z0y0x0z1", + ], +]; + +/// For each axis, the address bit each coordinate bit lands on. +fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec<u32>; 3] { + let mut axes: [Vec<u32>; 3] = Default::default(); + let micro = MICRO[kind][element_log2 as usize]; + for bit in 0..8u32 { + let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]); + let axis = match axis { + b'x' => 0, + b'y' => 1, + b'z' => 2, + _ => continue, + }; + let index = usize::from(index - b'0'); + let to = &mut axes[axis]; + if to.len() <= index { + to.resize(index + 1, 0); + } + to[index] = bit; + } + let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] }; + for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) { + axes[*axis].push(bit); + } + axes +} + +/// Byte offsets inside a block for coordinates 0..2^bits of one axis. +fn spread(bits: &[u32]) -> Vec<u32> { + (0..1u32 << bits.len()) + .map(|c| { + bits.iter() + .enumerate() + .map(|(i, &to)| ((c >> i) & 1) << to) + .sum() + }) + .collect() +} + +const MAX_MIPS: u32 = 16; + +/// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]]; +const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]]; +const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]]; + +impl Layout { + pub fn new(desc: &Desc) -> Result<Layout, Error> { + let d = *desc; + let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?; + let valid = d.width > 0 + && d.height > 0 + && d.depth > 0 + && (1..=MAX_MIPS).contains(&d.mips) + && d.element_bytes.is_power_of_two() + && d.element_bytes <= 16 + && matches!(d.block, 1 | 4) + && d.samples.is_power_of_two() + && d.samples <= 8 + && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1)) + && (d.dimension != Dimension::Tex1d || d.height == 1) + && (d.dimension != Dimension::Tex3d + || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27)); + if !valid { + return Err(Error::Invalid); + } + if block_log2 == 0 { + Ok(Layout::linear(d)) + } else { + Ok(Layout::tiled(d, block_log2)) + } + } + + /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed + /// smallest first, a 3D texture's depth slices each hold the chain. + fn linear(d: Desc) -> Layout { + let bpe = u64::from(d.element_bytes); + let align = 256 / d.element_bytes; + let three_d = d.dimension == Dimension::Tex3d; + let mut mips = vec![]; + let mut offset = 0; + for i in (0..d.mips).rev() { + let h = padded_dim(d.height, i, d.block); + let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align); + mips.push(Mip { + width: dim(d.width, i, d.block), + height: dim(d.height, i, d.block), + depth: if three_d { dim(d.depth, i, 1) } else { 1 }, + pitch, + rows: h, + depth_pitch: if three_d { d.depth } else { 1 }, + offset, + tail: None, + }); + offset += u64::from(pitch) * u64::from(h) * bpe; + } + mips.reverse(); + Layout { + desc: d, + block: [align, 1, 1], + thick: false, + slices: d.depth, + slice_size: offset, + size: offset * u64::from(d.depth), + alignment: 256, + first_tail_mip: d.mips, + mips, + pattern: Default::default(), + } + } + + fn tiled(d: Desc, block_log2: u32) -> Layout { + let element_log2 = d.element_bytes.trailing_zeros(); + let bpe = u64::from(d.element_bytes); + let block_bytes = 1u64 << block_log2; + let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let block = if thick { + // ComputeThickBlockDimension + let amp = (block_log2 - 10) / 3; + let rest = (block_log2 - 10) % 3; + let b = BLOCK_1K_3D[element_log2 as usize]; + [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] + } else { + // ComputeThinBlockDimension + let samples_log2 = d.samples.trailing_zeros(); + let elements_log2 = block_log2 - element_log2 - samples_log2; + let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0; + let w = (elements_log2 + u32::from(wide)) / 2; + [1 << w, 1 << (elements_log2 - w), 1] + }; + let slices = d.depth.next_multiple_of(block[2]); + let three_d = d.dimension == Dimension::Tex3d; + // Mip depths placed by a thick layout (thin ones store depth as + // slices). + let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; + let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; + let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); + let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); + let mut mips = Vec::with_capacity(d.mips as usize); + let mut first_tail_mip = d.mips; + let mut slice_size = 0u64; + if d.mips == 1 { + mips.push(Mip { + width: width(0), + height: height(0), + depth: depth_of(0), + pitch: width(0).next_multiple_of(block[0]), + rows: height(0).next_multiple_of(block[1]), + depth_pitch: if three_d { slices } else { 1 }, + offset: 0, + tail: None, + }); + slice_size = u64::from(mips[0].pitch) + * u64::from(mips[0].rows) + * bpe + * u64::from(d.samples); + } else { + // GetMipTailDim: the largest mip the tail takes. + let mut tail_max = block; + if thick { + match block_log2 % 3 { + 0 => tail_max[1] >>= 1, + 1 => tail_max[0] >>= 1, + _ => tail_max[2] >>= 1, + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail + // (`ComputeSurfaceInfoMicroTiled`). + let effective = if thick { + block_log2 - (block_log2 - 8) / 3 + } else { + block_log2 + }; + let max_in_tail = match effective { + 8 => 0, + 9..=11 => 1 + (1 << (effective - 9)), + _ => effective - 4, + }; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + let mut fixed = tail_max; + if d.swizzle.z_order() && element_log2 <= 1 { + let b = BLOCK_256_2D[element_log2 as usize]; + fixed[0] /= b[0] / BLOCK_256_2D[2][0]; + fixed[1] /= b[1] / BLOCK_256_2D[2][1]; + } + let mut sizes = vec![]; + for i in 0..d.mips { + let (w, h) = padded(i); + if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail { + first_tail_mip = i; + slice_size += block_bytes / u64::from(block[2]); + break; + } + let pitch = w.next_multiple_of(block[0]); + let rows = h.next_multiple_of(block[1]); + let depth = mip_depth(i).next_multiple_of(block[2]); + let one = u64::from(pitch) * u64::from(rows) * bpe; + slice_size += one; + sizes.push(one * u64::from(block[2])); + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if three_d { depth } else { 1 }, + offset: 0, + tail: None, + }); + } + // Standard mips from the smallest up, after the tail block. + let mut offset = if first_tail_mip < d.mips { + block_bytes + } else { + 0 + }; + for i in (0..first_tail_mip as usize).rev() { + mips[i].offset = offset; + offset += sizes[i]; + } + let micro = if thick { + let b = BLOCK_256_3D[element_log2 as usize]; + [b[0], b[1]] + } else { + BLOCK_256_2D[element_log2 as usize] + }; + let (mut pitch, mut rows) = (tail_max[0], tail_max[1]); + for i in first_tail_mip..d.mips { + let m = max_in_tail - 1 - (i - first_tail_mip); + let offset = if m > 6 { 16 << m } else { m << 8 }; + // Address bits 8.. of the offset, odd ones x, even ones y. + let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum(); + let (mut x, mut y): (u32, u32) = (bits(9), bits(8)); + if block_log2 & 1 != 0 { + std::mem::swap(&mut x, &mut y); + if element_log2 & 1 != 0 { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if thick { + mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2]) + } else { + 1 + }, + offset: 0, + tail: Some(Tail { + offset, + x: x * micro[0], + y: y * micro[1], + }), + }); + pitch = (pitch >> 1).max(micro[0]); + rows = (rows >> 1).max(micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + let slab = if thick { u64::from(block[2]) } else { 1 }; + let slice_size = slice_size * slab; + let slices = slices / block[2]; + let addressable = !d.swizzle.xor() && d.samples == 1; + let pattern = if addressable { + let kind = if thick { + 2 + } else { + usize::from(d.swizzle.display()) + }; + pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + } else { + Default::default() + }; + Layout { + desc: d, + block, + thick, + slices, + slice_size, + size: slice_size * u64::from(slices), + alignment: block_bytes, + first_tail_mip, + mips, + pattern, + } + } + + /// Whether [`Layout::offset`] and the copies work for this layout: + /// linear and the modes without pipe or bank XOR, single-sampled. + /// + /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA; + /// they need the GPU's pipe and bank configuration (Series X and S + /// differ). Titles use them for render targets and depth, which the + /// host renders; add them when a title copies into or out of one. + pub fn addressable(&self) -> bool { + self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty() + } + + /// The slice and the depth inside it for `z` (an array slice or a 3D + /// depth slice). + fn split(&self, z: u32) -> (u32, u32) { + if self.thick { + (z / self.block[2], z % self.block[2]) + } else { + (z, 0) + } + } + + /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or + /// depth slice `z`. Coordinates must lie inside the mip. + pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result<u64, Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = if self.desc.dimension == Dimension::Tex3d { + m.depth + } else { + self.slices + }; + let inside = x < m.width && y < m.height && z < depth; + if !inside || !self.addressable() { + return Err(if inside { + Error::Unsupported + } else { + Error::Invalid + }); + } + let (slice, z) = self.split(z); + let base = u64::from(slice) * self.slice_size + m.offset; + if self.desc.swizzle == Swizzle::LINEAR { + let row = u64::from(y) * u64::from(m.pitch) + u64::from(x); + return Ok(base + row * u64::from(self.desc.element_bytes)); + } + Ok(base + self.row(m, y, z) + self.column(m, x)) + } + + /// The part of an address that depends on the row (and depth in a + /// thick block). + fn row(&self, m: &Mip, y: u32, z: u32) -> u64 { + let [bw, bh, _] = self.block; + let log2 = self.alignment.trailing_zeros(); + // In the tail the pattern of the shifted position gives the mip's + // offset inside the tail block. + let y = y + m.tail.map_or(0, |t| t.y); + let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); + (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + } + + /// The part of an address that depends on the column. + fn column(&self, m: &Mip, x: u32) -> u64 { + let bw = self.block[0]; + let x = x + m.tail.map_or(0, |t| t.x); + (u64::from(x / bw) << self.alignment.trailing_zeros()) + + u64::from(self.pattern[0][(x % bw) as usize]) + } + + /// Depth slices a subresource of mip `mip` covers: the mip's depth for + /// 3D textures, else 1 (one array slice). + pub fn subresource_depth(&self, mip: u32) -> u32 { + self.mips.get(mip as usize).map_or(0, |m| m.depth) + } + + /// Copies one subresource out of tiled memory (the whole texture, + /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are + /// `row_pitch` bytes apart, depth slices `depth_pitch`. + pub fn detile( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + row_pitch: usize, + depth_pitch: usize, + ) -> Result<(), Error> { + let n = self.desc.element_bytes as usize; + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| { + for (i, len) in runs(t, count, n) { + linear[l + i * n..][..len].copy_from_slice(&tiled[t[i] as usize..][..len]); + } + }) + } + + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. + pub fn tile( + &self, + tiled: &mut [u8], + mip: u32, + slice: u32, + linear: &[u8], + row_pitch: usize, + depth_pitch: usize, + ) -> Result<(), Error> { + let n = self.desc.element_bytes as usize; + self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| { + for (i, len) in runs(t, count, n) { + tiled[t[i] as usize..][..len].copy_from_slice(&linear[l + i * n..][..len]); + } + }) + } + + /// Calls `row(tiled offsets, linear offset, elements)` for each row of a + /// subresource, after checking both buffers are large enough. + #[allow(clippy::too_many_arguments)] + fn walk( + &self, + tiled_len: usize, + mip: u32, + slice: u32, + linear_len: usize, + row_pitch: usize, + depth_pitch: usize, + mut row: impl FnMut(&[u64], usize, usize), + ) -> Result<(), Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = m.depth; + let first = if self.desc.dimension == Dimension::Tex3d { + if slice != 0 { + return Err(Error::Invalid); + } + 0 + } else { + slice + }; + if first >= self.slices { + return Err(Error::Invalid); + } + if !self.addressable() { + return Err(Error::Unsupported); + } + let n = self.desc.element_bytes as usize; + let bytes = m.width as usize * n; + let need = (depth as usize - 1) * depth_pitch + (m.height as usize - 1) * row_pitch + bytes; + if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + return Err(Error::TooSmall); + } + let linear = self.desc.swizzle == Swizzle::LINEAR; + let columns: Vec<u64> = (0..m.width) + .map(|x| { + if linear { + u64::from(x) * n as u64 + } else { + self.column(m, x) + } + }) + .collect(); + let mut offsets = vec![0u64; m.width as usize]; + for z in 0..depth { + let (s, inner) = self.split(first + z); + let base = u64::from(s) * self.slice_size + m.offset; + for y in 0..m.height { + let start = if linear { + base + u64::from(y) * u64::from(m.pitch) * n as u64 + } else { + base + self.row(m, y, inner) + }; + for (o, c) in offsets.iter_mut().zip(&columns) { + *o = start + c; + } + row(&offsets, z as usize * depth_pitch + y as usize * row_pitch, m.width as usize); + } + } + Ok(()) + } +} + +/// The first `count` element offsets as runs of contiguous memory: (first +/// element, bytes), so a linear row (or a swizzle's contiguous columns) is +/// copied at once rather than element by element. +fn runs(t: &[u64], count: usize, n: usize) -> impl Iterator<Item = (usize, usize)> + '_ { + let mut i = 0; + std::iter::from_fn(move || { + if i >= count { + return None; + } + let start = i; + i += 1; + while i < count && t[i] == t[i - 1] + n as u64 { + i += 1; + } + Some((start, (i - start) * n)) + }) +} + +/// What a DXGI format stores per element: bytes, texels per element side +/// (4 for block compression), and whether its stencil is a second plane +/// (the GPU keeps depth and stencil apart). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Format { + pub bytes: u32, + pub block: u32, + pub stencil: bool, +} + +/// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video +/// formats. +/// +/// shortcut: those formats have no layout here; add them when a title uses +/// one. +pub fn format(dxgi: u32) -> Option<Format> { + let (bytes, block, stencil) = match dxgi { + 1..=4 => (16, 1, false), + 9..=18 => (8, 1, false), + 19..=22 | 44..=47 => (4, 1, true), + 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false), + 48..=59 | 85 | 86 | 115 => (2, 1, false), + 118..=120 => (2, 1, true), + 60..=65 => (1, 1, false), + 70..=72 | 79..=81 => (8, 4, false), + 73..=78 | 82..=84 | 94..=99 => (16, 4, false), + _ => return None, + }; + Some(Format { + bytes, + block, + stencil, + }) +} + +/// A texture as the console allocates it: a D3D12-style description with +/// a swizzle mode. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TextureDesc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth_or_array: u32, + /// 0: the full chain. + pub mips: u32, + /// DXGI format number. + pub format: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Plane { + /// From the start of the texture. + pub offset: u64, + pub stencil: bool, + pub layout: Layout, +} + +/// Every data plane of a texture (depth, then stencil), placed one after +/// the other. +/// +/// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC); +/// the console adds them to render targets and depth buffers unless the +/// description denies them, so those are smaller here than on the console. +/// The host GPU renders them, so nothing reads that memory; add the planes +/// if a title sizes a pool from console sizes and runs out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Texture { + pub planes: Vec<Plane>, + pub size: u64, + pub alignment: u64, +} + +impl Texture { + pub fn new(desc: &TextureDesc) -> Result<Texture, Error> { + let f = format(desc.format).ok_or(Error::Invalid)?; + let depth3d = if desc.dimension == Dimension::Tex3d { + desc.depth_or_array + } else { + 1 + }; + let mips = match desc.mips { + 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), + n => n, + }; + let plane = |bytes| Desc { + dimension: desc.dimension, + width: desc.width, + height: desc.height, + depth: desc.depth_or_array, + mips, + element_bytes: bytes, + block: f.block, + samples: desc.samples.max(1), + swizzle: desc.swizzle, + }; + let mut planes = vec![Plane { + offset: 0, + stencil: false, + layout: Layout::new(&plane(f.bytes))?, + }]; + if f.stencil { + let layout = Layout::new(&plane(1))?; + let offset = planes[0].layout.size.next_multiple_of(layout.alignment); + planes.push(Plane { + offset, + stencil: true, + layout, + }); + } + let last = &planes[planes.len() - 1]; + let size = last.offset + last.layout.size; + let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1); + Ok(Texture { + planes, + size, + alignment, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc { + Desc { + dimension: Dimension::Tex2d, + width: w, + height: h, + depth: 1, + mips, + element_bytes: bpe, + block: 1, + samples: 1, + swizzle, + } + } + + #[test] + fn blocks_hold_their_size_in_elements() { + for log2 in [8u32, 12, 16] { + let swizzle = match log2 { + 8 => Swizzle::SW_256B_S, + 12 => Swizzle::SW_4KB_S, + _ => Swizzle::SW_64KB_D, + }; + for e in 0..5 { + let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap(); + let [w, h, d] = l.block; + assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}"); + // The pattern covers exactly the block's coordinates. + assert_eq!(l.pattern[0].len() as u32, w); + assert_eq!(l.pattern[1].len() as u32, h); + } + } + // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture). + let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.block, [64, 64, 1]); + assert_eq!((l.size, l.alignment), (65536, 65536)); + } + + /// Every element of every mip and slice lands on its own address, inside + /// the texture, and tiling then detiling gives the rows back. + #[test] + fn addresses_are_a_bijection_and_copies_round_trip() { + let cases = [ + desc(64, 64, 7, 16, Swizzle::SW_64KB_D), + desc(100, 60, 7, 4, Swizzle::SW_64KB_D), + desc(250, 175, 8, 8, Swizzle::SW_4KB_S), + desc(33, 17, 6, 1, Swizzle::SW_4KB_D), + desc(40, 9, 3, 2, Swizzle::SW_64KB_S), + desc(30, 20, 5, 4, Swizzle::LINEAR), + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let mut seen = vec![false; l.size as usize]; + let mut tiled = vec![0u8; l.size as usize]; + let n = d.element_bytes as usize; + let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; + for slice in 0..slices { + for mip in 0..d.mips { + let m = l.mips[mip as usize]; + let row = m.width as usize * n; + let plane = row * m.height as usize; + let linear: Vec<u8> = (0..plane * m.depth as usize) + .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8) + .collect(); + l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap(); + let mut back = vec![0u8; linear.len()]; + l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap(); + assert_eq!(back, linear, "{d:?} mip {mip}"); + for z in 0..m.depth { + for y in 0..m.height { + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap() as usize; + assert!(at + n <= seen.len(), "{d:?} mip {mip} outside"); + assert!(at.is_multiple_of(n)); + assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice"); + seen[at] = true; + } + } + } + } + } + } + } + + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to + /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, + /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. + #[test] + fn hand_checked_addresses() { + let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2)); + assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6)); + assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7)); + assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8)); + assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14))); + let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.block, [16, 16, 1]); + assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4)); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6)); + // Blocks row by row: (16, 0) is the second block, (0, 16) the third. + assert_eq!(l.offset(0, 16, 0, 0), Ok(4096)); + assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); + } + + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, + /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. + #[test] + fn mip_tail_comes_first() { + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.first_tail_mip, 1); + assert_eq!(l.size, 2 * 65536); + assert_eq!(l.mips[0].offset, 65536); + assert_eq!( + l.mips[1].tail, + Some(Tail { + offset: 32768, + x: 32, + y: 0 + }) + ); + assert_eq!(l.offset(1, 0, 0, 0), Ok(32768)); + // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside. + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.first_tail_mip, 3); + assert_eq!(l.mips[2].offset, 4096); + assert_eq!(l.mips[1].offset, 8192); + assert_eq!(l.mips[0].offset, 8192 + 16384); + } + + #[test] + fn depth_stencil_is_two_planes() { + let t = Texture::new(&TextureDesc { + dimension: Dimension::Tex2d, + width: 1920, + height: 1080, + depth_or_array: 1, + mips: 1, + format: 20, + samples: 1, + swizzle: Swizzle::SW_64KB_Z_X, + }) + .unwrap(); + assert_eq!(t.planes.len(), 2); + // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks. + assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4); + assert_eq!(t.planes[1].offset, t.planes[0].layout.size); + assert_eq!(t.planes[1].layout.size, 2048 * 1280); + assert!(!t.planes[0].layout.addressable()); + } + + #[test] + fn bad_descriptions_and_buffers_are_refused() { + assert_eq!( + Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 4, Swizzle(3))), + Err(Error::Invalid) + ); + let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap(); + let mut out = vec![0; 64 * 64 * 4]; + assert_eq!( + l.detile(&[0; 100], 0, 0, &mut out, 256, 0), + Err(Error::TooSmall) + ); + assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); + } +} diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs new file mode 100644 index 0000000..06aa427 --- /dev/null +++ b/crates/victory-formats/src/xma.rs @@ -0,0 +1,1206 @@ +//! XMA2, the console's hardware audio codec: mono or stereo WMA Pro frames of +//! 512 samples per channel, packed into 2048-byte packets. +//! +//! A packet starts with a 32-bit header (MSB first): the number of frames +//! that begin in it (6 bits), the number of bits that finish the previous +//! frame before the first new one (15), metadata (3) and how many packets of +//! other streams follow before this stream's next packet (8). Every frame +//! starts with its length in bits (15) and ends with a "more frames" bit. +//! +//! The frame decoder follows FFmpeg's `wmaprodec.c` (LGPL-2.1-or-later, used +//! under GPL-3.0-or-later) restricted to what XMA needs: at most two +//! channels, four subframe sizes (512 down to 128), no LFE channel. + +mod tables; + +use std::sync::OnceLock; + +use tables::*; + +pub const PACKET_BYTES: usize = 2048; +const PACKET_BITS: usize = PACKET_BYTES * 8; +const HEADER_BITS: usize = 32; +/// Samples per channel in one frame. +pub const FRAME_SAMPLES: usize = 512; +/// Samples per channel in one subframe, the unit of skips and loop ends. +pub const SUBFRAME_SAMPLES: usize = 128; +const LENGTH_BITS: u32 = 15; +/// 512 >> 2: the smallest subframe. +const MIN_SUBFRAME: usize = SUBFRAME_SAMPLES; +const BLOCK_SIZES: usize = 3; +const MAX_BANDS: usize = 29; +const MAX_SUBFRAMES: usize = 32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "XMA: {}", self.0) + } +} + +impl std::error::Error for Error {} + +// Packets. + +/// A packet's header fields. +#[derive(Debug, Clone, Copy)] +pub struct Packet { + pub frames: u32, + pub first_frame_bit: u32, + pub skip: u32, +} + +pub fn packet(data: &[u8], index: usize) -> Option<Packet> { + let b = data.get(index * PACKET_BYTES..index * PACKET_BYTES + 4)?; + let h = u32::from_be_bytes([b[0], b[1], b[2], b[3]]); + Some(Packet { + frames: h >> 26, + first_frame_bit: (h >> 11) & 0x7fff, + skip: h & 0xff, + }) +} + +/// One frame's bits gathered out of its packets. +#[derive(Debug, Clone)] +pub struct Frame { + /// The frame from its length field on, MSB first. + pub data: Vec<u8>, + pub bits: usize, + /// Bit offset in the buffer where it starts, and where the next frame + /// starts (`None` when the buffer has no further frame). + pub start: usize, + pub next: Option<usize>, +} + +/// Bit positions in a buffer of packets, skipping each packet's header and +/// the packets of other streams. +struct Cursor<'a> { + data: &'a [u8], + pos: usize, +} + +impl Cursor<'_> { + fn bit(&mut self) -> Option<u32> { + if self.pos.is_multiple_of(PACKET_BITS) { + // Leaving a packet: jump over the other streams' packets. + let previous = self.pos / PACKET_BITS; + if previous > 0 { + let skip = packet(self.data, previous - 1)?.skip as usize; + self.pos = (previous + skip) * PACKET_BITS; + } + self.pos += HEADER_BITS; + } + let byte = *self.data.get(self.pos / 8)?; + let bit = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Some(bit as u32) + } + + fn bits(&mut self, n: u32) -> Option<u32> { + (0..n).try_fold(0, |v, _| Some(v << 1 | self.bit()?)) + } +} + +/// Reads the frame starting at bit `start` (a frame start inside a packet's +/// payload) of `data`, a buffer of whole packets of one stream. +pub fn read_frame(data: &[u8], start: usize) -> Option<Frame> { + let mut cursor = Cursor { data, pos: start }; + let bits = cursor.bits(LENGTH_BITS)? as usize; + if bits <= LENGTH_BITS as usize || bits == 0x7fff { + return None; + } + let mut out = vec![0u8; bits.div_ceil(8)]; + let mut cursor = Cursor { data, pos: start }; + for i in 0..bits { + out[i / 8] |= (cursor.bit()? as u8) << (7 - i % 8); + } + let end = cursor.pos; + let next = next_frame(data, start, end); + Some(Frame { + data: out, + bits, + start, + next, + }) +} + +/// Where the frame after the one at `start`..`end` begins: right after it, +/// unless it was the last frame to begin in its packet and the rest of that +/// packet is padding. +fn next_frame(data: &[u8], start: usize, end: usize) -> Option<usize> { + let index = start / PACKET_BITS; + let header = packet(data, index)?; + let mut at = index * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + let mut number = 0; + while at < start { + let mut cursor = Cursor { data, pos: at }; + at += cursor.bits(LENGTH_BITS)? as usize; + number += 1; + } + let last = number + 1 >= header.frames; + let mut end = end; + if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { + // The next frame begins in the next packet of this stream. + let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let header = packet(data, next)?; + end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + } + (end / 8 < data.len()).then_some(end) +} + +// Bitstream reading inside a frame. + +struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl Bits<'_> { + fn peek32(&self) -> u32 { + let mut v = 0u64; + let byte = self.pos / 8; + for i in 0..5 { + v = v << 8 | *self.data.get(byte + i).unwrap_or(&0) as u64; + } + (v << (24 + self.pos % 8) >> 32) as u32 + } + + fn read(&mut self, n: u32) -> u32 { + if n == 0 { + return 0; + } + let v = self.peek32() >> (32 - n); + self.pos += n as usize; + v + } + + fn bit(&mut self) -> bool { + self.read(1) != 0 + } + + fn signed(&mut self, n: u32) -> i32 { + ((self.read(n) << (32 - n)) as i32) >> (32 - n) + } + + fn consumed(&self) -> usize { + self.pos + } + + fn overread(&self) -> bool { + self.pos > self.end + } +} + +/// A prefix code built like FFmpeg's `ff_vlc_init_from_lengths`: codes are +/// handed out in table order, each the next free one of its length. +struct Vlc { + /// Left-aligned code, length, symbol; sorted by code. + codes: Vec<(u32, u8, i32)>, +} + +impl Vlc { + fn new(entries: impl Iterator<Item = (i32, u8)>) -> Vlc { + let mut code = 0u64; + let mut codes = Vec::new(); + for (symbol, len) in entries { + codes.push((code as u32, len, symbol)); + code += 1 << (32 - len); + } + Vlc { codes } + } + + fn read(&self, bits: &mut Bits) -> i32 { + let v = bits.peek32(); + let i = self.codes.partition_point(|c| c.0 <= v) - 1; + let (_, len, symbol) = self.codes[i]; + bits.pos += len as usize; + symbol + } +} + +struct Codes { + scale: Vlc, + scale_rl: Vlc, + coef: [Vlc; 2], + vec4: Vlc, + vec2: Vlc, + vec1: Vlc, +} + +fn codes() -> &'static Codes { + static CODES: OnceLock<Codes> = OnceLock::new(); + CODES.get_or_init(|| { + let pairs = |t: &'static [(u16, u8)], offset: i32| { + Vlc::new(t.iter().map(move |&(s, l)| (s as i32 + offset, l))) + }; + Codes { + scale: pairs(&SCALE, -60), + scale_rl: pairs(&SCALE_RL, 0), + coef: [ + Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), + pairs(&COEF1, 0), + ], + vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), + vec2: pairs(&VEC2, -1), + vec1: pairs(&VEC1, 0), + } + }) +} + +/// `ff_wma_get_large_val`. +fn large_value(bits: &mut Bits) -> u32 { + let mut n = 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 7; + } + } + } + bits.read(n) +} + +fn log2(v: usize) -> u32 { + usize::BITS - 1 - v.max(1).leading_zeros() +} + +// The inverse transform. + +/// Half-length inverse MDCT as FFmpeg defines it (`av_tx` MDCT, inverse): +/// `n` coefficients to the middle `n` samples of the 2n-sample window, +/// negated and scaled by `scale`. Computed as a DCT-IV through an +/// n/2-point complex FFT. +fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) { + let n = input.len(); + let m = n / 2; + let mut re = vec![0f64; m]; + let mut im = vec![0f64; m]; + for k in 0..m { + let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (re[k], im[k]) = (a * c - b * s, a * s + b * c); + } + fft(&mut re, &mut im); + for k in 0..m { + let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); + // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. + out[n - 1 - 2 * k] = (wr as f32) * scale; + out[2 * k] = -(wi as f32) * scale; + } +} + +/// In-place radix-2 forward DFT (`exp(-2πi nk/N)`). +fn fft(re: &mut [f64], im: &mut [f64]) { + let n = re.len(); + let mut j = 0; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= n { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + for start in (0..n).step_by(len) { + let (mut cr, mut ci) = (1.0, 0.0); + for k in 0..len / 2 { + let (a, b) = (start + k, start + k + len / 2); + let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); + (re[b], im[b]) = (re[a] - tr, im[a] - ti); + (re[a], im[a]) = (re[a] + tr, im[a] + ti); + (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); + } + } + len <<= 1; + } +} + +/// `ff_sine_windows`: the rising half of a sine window of length `n`. +fn sine_window(n: usize) -> Vec<f32> { + (0..n) + .map(|i| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin() as f32) + .collect() +} + +// The frame decoder. + +#[derive(Clone)] +struct Channel { + prev_block_len: usize, + transmit_coefs: bool, + num_subframes: usize, + subframe_len: [usize; MAX_SUBFRAMES], + cur_subframe: usize, + decoded_samples: usize, + quant_step: i32, + reuse_sf: bool, + scale_factor_step: i32, + max_scale_factor: i32, + saved_scale_factors: [[i32; MAX_BANDS]; 2], + scale_factor_idx: usize, + /// Which of the two saved sets is in use for this subframe. + scale_factors: usize, + table_idx: usize, + num_vec_coeffs: usize, + coeffs: [f32; FRAME_SAMPLES], + /// The frame's output, then half a frame of overlap for the next one. + out: [f32; FRAME_SAMPLES + FRAME_SAMPLES / 2], +} + +impl Channel { + fn new() -> Self { + Channel { + prev_block_len: FRAME_SAMPLES, + transmit_coefs: false, + num_subframes: 0, + subframe_len: [0; MAX_SUBFRAMES], + cur_subframe: 0, + decoded_samples: 0, + quant_step: 0, + reuse_sf: false, + scale_factor_step: 1, + max_scale_factor: 0, + saved_scale_factors: [[0; MAX_BANDS]; 2], + scale_factor_idx: 0, + scale_factors: 0, + table_idx: 0, + num_vec_coeffs: 0, + coeffs: [0.0; FRAME_SAMPLES], + out: [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2], + } + } +} + +/// Decodes the frames of one mono or stereo stream. +#[derive(Clone)] +pub struct Decoder { + channels: usize, + num_sfb: [usize; BLOCK_SIZES], + sfb_offsets: [[usize; MAX_BANDS + 1]; BLOCK_SIZES], + sf_offsets: [[[usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES], + ch: [Channel; 2], + // Per subframe. + subframe_len: usize, + channels_for_cur_subframe: usize, + channel_indexes: [usize; 2], + num_bands: usize, + table_idx: usize, + esc_len: u32, + transmit_num_vec_coeffs: bool, + transform: bool, + transform_band: [bool; MAX_BANDS], + parsed_all_subframes: bool, +} + +/// What the decoder needs from the stream format: the channel count and +/// the sample rate, which sets the scale factor band layout. +impl Decoder { + pub fn new(channels: usize, sample_rate: u32) -> Decoder { + let channels = channels.clamp(1, 2); + let rate = match sample_rate { + r if r > 44_100 => 48_000, + r if r > 32_000 => 44_100, + r if r > 24_000 => 32_000, + _ => 24_000, + }; + let mut sfb_offsets = [[0usize; MAX_BANDS + 1]; BLOCK_SIZES]; + let mut num_sfb = [0usize; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + let subframe_len = FRAME_SAMPLES >> i; + let offsets = &mut sfb_offsets[i]; + let mut band = 1; + for &freq in CRITICAL_FREQ.iter().take(MAX_BANDS - 1) { + if offsets[band - 1] >= subframe_len { + break; + } + let offset = ((subframe_len * 2 * freq as usize) / rate + 2) & !3; + if offset > offsets[band - 1] { + offsets[band] = offset; + band += 1; + } + if offset >= subframe_len { + break; + } + } + offsets[band - 1] = subframe_len; + num_sfb[i] = band - 1; + } + let mut sf_offsets = [[[0usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + for b in 0..num_sfb[i] { + let offset = ((sfb_offsets[i][b] + sfb_offsets[i][b + 1] - 1) << i) >> 1; + for x in 0..BLOCK_SIZES { + let mut v = 0; + while v + 1 < MAX_BANDS && (sfb_offsets[x][v + 1] << x) < offset { + v += 1; + } + sf_offsets[i][x][b] = v; + } + } + } + Decoder { + channels, + num_sfb, + sfb_offsets, + sf_offsets, + ch: [Channel::new(), Channel::new()], + subframe_len: FRAME_SAMPLES, + channels_for_cur_subframe: 0, + channel_indexes: [0, 1], + num_bands: 0, + table_idx: 0, + esc_len: 0, + transmit_num_vec_coeffs: false, + transform: false, + transform_band: [false; MAX_BANDS], + parsed_all_subframes: false, + } + } + + pub fn channels(&self) -> usize { + self.channels + } + + /// Forgets the overlap with earlier frames (a new stream or a seek). + pub fn reset(&mut self) { + self.ch = [Channel::new(), Channel::new()]; + } + + /// Decodes one frame (`frame.data`, `frame.bits`) and appends + /// `FRAME_SAMPLES` interleaved samples per channel to `out`. + pub fn decode(&mut self, data: &[u8], bits: usize, out: &mut Vec<i16>) -> Result<(), Error> { + let mut b = Bits { + data, + pos: 0, + end: bits, + }; + let len = b.read(LENGTH_BITS) as usize; + let result = self.frame(&mut b, len); + if result.is_err() { + // Whatever the frame held is lost; keep the stream's timing. + for c in 0..self.channels { + self.ch[c].out = [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2]; + } + } + for i in 0..FRAME_SAMPLES { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + for c in 0..self.channels { + self.ch[c].out.copy_within(FRAME_SAMPLES.., 0); + } + result + } + + /// The overlap left after the last frame, then silence: half a frame of + /// samples per channel. + pub fn flush(&mut self, out: &mut Vec<i16>) { + for i in 0..FRAME_SAMPLES / 2 { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + self.reset(); + } + + fn frame(&mut self, b: &mut Bits, len: usize) -> Result<(), Error> { + self.tile_header(b)?; + // Post-processing transform. + if self.channels > 1 && b.bit() && b.bit() { + b.read((self.channels * self.channels * 4) as u32); + } + // Dynamic range compression gain, unused. + b.read(8); + if b.bit() { + // Trim at start and end, which only WMA Pro files apply. + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + } + self.parsed_all_subframes = false; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + ch.decoded_samples = 0; + ch.cur_subframe = 0; + ch.reuse_sf = false; + } + while !self.parsed_all_subframes { + self.subframe(b)?; + } + // FFmpeg flags `len != consumed + 2` but keeps the samples; so do we. + if b.overread() || b.consumed() > len { + return Err(Error("frame overread")); + } + Ok(()) + } + + fn subframe_length(&self, b: &mut Bits, offset: usize) -> Result<usize, Error> { + if offset == FRAME_SAMPLES - MIN_SUBFRAME { + return Ok(MIN_SUBFRAME); + } + // Four subframe sizes: a 1-bit "not maximal", then 1 bit of shift. + let shift = if b.bit() { 1 + b.read(1) } else { 0 }; + let len = FRAME_SAMPLES >> shift; + if len < MIN_SUBFRAME { + return Err(Error("subframe length")); + } + Ok(len) + } + + fn tile_header(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut num_samples = [0usize; 2]; + let mut contains = [false; 2]; + let mut channels_for_cur_subframe = self.channels; + let mut min_channel_len = 0; + for c in 0..self.channels { + self.ch[c].num_subframes = 0; + } + let fixed = b.bit(); + loop { + for c in 0..self.channels { + contains[c] = num_samples[c] == min_channel_len + && (fixed + || channels_for_cur_subframe == 1 + || min_channel_len == FRAME_SAMPLES - MIN_SUBFRAME + || b.bit()); + } + let subframe_len = self.subframe_length(b, min_channel_len)?; + min_channel_len += subframe_len; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + if contains[c] { + if ch.num_subframes >= MAX_SUBFRAMES { + return Err(Error("too many subframes")); + } + ch.subframe_len[ch.num_subframes] = subframe_len; + num_samples[c] += subframe_len; + ch.num_subframes += 1; + if num_samples[c] > FRAME_SAMPLES { + return Err(Error("channel longer than a frame")); + } + } else if num_samples[c] <= min_channel_len { + if num_samples[c] < min_channel_len { + channels_for_cur_subframe = 0; + min_channel_len = num_samples[c]; + } + channels_for_cur_subframe += 1; + } + } + if min_channel_len >= FRAME_SAMPLES || b.overread() { + break; + } + } + if b.overread() { + return Err(Error("tile header")); + } + Ok(()) + } + + fn channel_transform(&mut self, b: &mut Bits) -> Result<(), Error> { + self.transform = false; + if self.channels == 1 { + return Ok(()); + } + if b.bit() { + return Err(Error("channel transform bit")); + } + // One group holding every channel of the subframe. + if self.channels_for_cur_subframe == 2 { + if b.bit() { + if b.bit() { + return Err(Error("channel transform type")); + } + } else { + self.transform = true; + } + } + if self.transform { + if !b.bit() { + for i in 0..self.num_bands { + self.transform_band[i] = b.bit(); + } + } else { + self.transform_band = [true; MAX_BANDS]; + } + } + Ok(()) + } + + fn coefficients(&mut self, b: &mut Bits, c: usize) -> Result<(), Error> { + let codes = codes(); + let table = b.bit() as usize; + let (run, level): (&[u16], &[f32]) = if table == 1 { + (&COEF1_RUN, &COEF1_LEVEL) + } else { + (&COEF0_RUN, &COEF0_LEVEL) + }; + let subframe_len = self.subframe_len; + let ch = &mut self.ch[c]; + let mut rl_mode = false; + let mut cur = 0; + let mut num_zeros = 0; + while (self.transmit_num_vec_coeffs || !rl_mode) && cur + 3 < ch.num_vec_coeffs { + let mut vals = [0u32; 4]; + let idx = codes.vec4.read(b); + if idx < 0 { + for i in (0..4).step_by(2) { + let idx = codes.vec2.read(b); + if idx < 0 { + for v in &mut vals[i..i + 2] { + let mut x = codes.vec1.read(b) as u32; + if x as usize == VEC1.len() - 1 { + x += large_value(b); + } + *v = x; + } + } else { + vals[i] = (idx >> 4) as u32; + vals[i + 1] = (idx & 0xf) as u32; + } + } + } else { + vals = [ + (idx >> 12) as u32, + ((idx >> 8) & 0xf) as u32, + ((idx >> 4) & 0xf) as u32, + (idx & 0xf) as u32, + ]; + } + for v in vals { + if v != 0 { + let negative = !b.bit(); + ch.coeffs[cur] = if negative { -(v as f32) } else { v as f32 }; + num_zeros = 0; + } else { + ch.coeffs[cur] = 0.0; + num_zeros += 1; + rl_mode |= num_zeros > subframe_len >> 8; + } + cur += 1; + } + if b.overread() { + return Err(Error("vector coefficients")); + } + } + if cur < subframe_len { + ch.coeffs[cur..subframe_len].fill(0.0); + // `ff_wma_run_level_decode`, version 1. + let mask = subframe_len - 1; + let mut offset = cur; + while offset < subframe_len { + let code = codes.coef[table].read(b); + if code > 1 { + offset += run[code as usize] as usize; + let negative = !b.bit(); + let v = level[code as usize]; + ch.coeffs[offset & mask] = if negative { -v } else { v }; + } else if code == 1 { + break; + } else { + let value = large_value(b) as i32; + if b.bit() { + if b.bit() { + if b.bit() { + // A broken escape ends the channel's + // coefficients, as in FFmpeg. + break; + } + offset += b.read(self.esc_len) as usize + 4; + } else { + offset += b.read(2) as usize + 1; + } + } + let negative = !b.bit(); + ch.coeffs[offset & mask] = if negative { -value } else { value } as f32; + } + if b.overread() { + return Err(Error("run level coefficients")); + } + offset += 1; + } + } + Ok(()) + } + + fn scale_factors(&mut self, b: &mut Bits) -> Result<(), Error> { + let codes = codes(); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let sf_offsets = self.sf_offsets[self.table_idx][self.ch[c].table_idx]; + let ch = &mut self.ch[c]; + let target = 1 - ch.scale_factor_idx; + ch.scale_factors = target; + if ch.reuse_sf { + let from = ch.saved_scale_factors[ch.scale_factor_idx]; + for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { + *sf = from[offset]; + } + } + if ch.cur_subframe == 0 || b.bit() { + if !ch.reuse_sf { + ch.scale_factor_step = b.read(2) as i32 + 1; + let mut val = 45 / ch.scale_factor_step; + for band in 0..self.num_bands { + val += codes.scale.read(b); + ch.saved_scale_factors[target][band] = val; + } + } else { + let mut band = 0; + while band < self.num_bands { + let idx = codes.scale_rl.read(b); + let (skip, val, negative) = match idx { + 0 => { + let code = b.read(14); + ((code & 0x3f) >> 1, (code >> 6) as i32, code & 1 == 0) + } + 1 => break, + _ => ( + SCALE_RL_RUN[idx as usize] as u32, + SCALE_RL_LEVEL[idx as usize] as i32, + !b.bit(), + ), + }; + band += skip as usize; + if band >= self.num_bands { + return Err(Error("scale factor run")); + } + ch.saved_scale_factors[target][band] += if negative { -val } else { val }; + band += 1; + } + } + ch.scale_factor_idx = target; + ch.table_idx = self.table_idx; + ch.reuse_sf = true; + } + let sf = &ch.saved_scale_factors[ch.scale_factors][..self.num_bands]; + ch.max_scale_factor = sf.iter().copied().max().unwrap_or(0); + } + Ok(()) + } + + fn subframe(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut offset = FRAME_SAMPLES; + let mut subframe_len = FRAME_SAMPLES; + let mut total_samples = FRAME_SAMPLES * self.channels; + for c in 0..self.channels { + let ch = &self.ch[c]; + if offset > ch.decoded_samples { + offset = ch.decoded_samples; + subframe_len = ch.subframe_len[ch.cur_subframe.min(MAX_SUBFRAMES - 1)]; + } + } + self.channels_for_cur_subframe = 0; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + total_samples -= ch.decoded_samples; + if offset == ch.decoded_samples + && ch.cur_subframe < ch.num_subframes + && subframe_len == ch.subframe_len[ch.cur_subframe] + { + total_samples -= subframe_len; + ch.decoded_samples += subframe_len; + self.channel_indexes[self.channels_for_cur_subframe] = c; + self.channels_for_cur_subframe += 1; + } + } + if self.channels_for_cur_subframe == 0 { + return Err(Error("no channel in subframe")); + } + if total_samples == 0 { + self.parsed_all_subframes = true; + } + self.table_idx = log2(FRAME_SAMPLES / subframe_len) as usize; + self.num_bands = self.num_sfb[self.table_idx]; + self.subframe_len = subframe_len; + self.esc_len = log2(subframe_len - 1) + 1; + + // Extended header: fill bits. + if b.bit() { + let mut fill = b.read(2) as usize; + if fill == 0 { + let len = b.read(4); + fill = b.read(len) as usize + 1; + } + b.pos += fill; + } + if b.bit() { + return Err(Error("reserved bit")); + } + self.channel_transform(b)?; + + let mut transmit_coeffs = false; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].transmit_coefs = b.bit(); + transmit_coeffs |= self.ch[c].transmit_coefs; + } + if transmit_coeffs { + self.transmit_num_vec_coeffs = b.bit(); + if self.transmit_num_vec_coeffs { + let num_bits = log2(subframe_len.div_ceil(4)) + 1; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let n = (b.read(num_bits) << 2) as usize; + if n > subframe_len { + return Err(Error("vector coefficient count")); + } + self.ch[c].num_vec_coeffs = n; + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].num_vec_coeffs = subframe_len; + } + } + // Quantisation step (16-bit samples: 90 * 16 >> 4). + let mut quant_step = 90; + let mut step = b.signed(6); + quant_step += step; + if step == -32 || step == 31 { + let negative = step == -32; + let mut quant = 0; + while b.pos + 5 < b.end { + step = b.read(5) as i32; + if step != 31 { + break; + } + quant += 31; + } + quant_step += if negative { -(quant + step) } else { quant + step }; + } + if self.channels_for_cur_subframe == 1 { + self.ch[self.channel_indexes[0]].quant_step = quant_step; + } else { + let modifier_len = b.read(3); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].quant_step = quant_step; + if b.bit() { + self.ch[c].quant_step += if modifier_len > 0 { + b.read(modifier_len) as i32 + 1 + } else { + 1 + }; + } + } + } + self.scale_factors(b)?; + } + + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + if self.ch[c].transmit_coefs && b.pos < b.end { + self.coefficients(b, c)?; + } else { + self.ch[c].coeffs[..subframe_len].fill(0.0); + } + } + + // Where this subframe's samples go in the channel output. + let at = offset + FRAME_SAMPLES / 2; + if transmit_coeffs { + self.inverse_channel_transform(); + // Output in [-1, 1] for 16-bit streams. + let scale = 2.0 / subframe_len as f32 / 32768.0; + let sfb = self.sfb_offsets[self.table_idx]; + let mut tmp = [0f32; FRAME_SAMPLES]; + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + let sf = ch.saved_scale_factors[ch.scale_factors]; + for band in 0..self.num_bands { + let end = sfb[band + 1].min(subframe_len); + let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let quant = 10f32.powf(exp as f32 / 20.0); + for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { + *t = c * quant; + } + } + imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].out[at..at + subframe_len].fill(0.0); + } + } + + // Window and overlap-add with the previous block. + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + let mut winlen = ch.prev_block_len; + let mut start = at - winlen / 2; + if subframe_len < winlen { + start += (winlen - subframe_len) / 2; + winlen = subframe_len; + } + window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); + ch.prev_block_len = subframe_len; + } + + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + if ch.cur_subframe >= ch.num_subframes { + return Err(Error("subframe overrun")); + } + ch.cur_subframe += 1; + } + if b.overread() { + return Err(Error("subframe overread")); + } + Ok(()) + } + + fn inverse_channel_transform(&mut self) { + if !self.transform || self.channels_for_cur_subframe != 2 { + return; + } + let sfb = self.sfb_offsets[self.table_idx]; + let [a, b] = &mut self.ch; + for band in 0..self.num_bands { + let range = sfb[band]..sfb[band + 1].min(self.subframe_len); + if self.transform_band[band] { + for y in range { + let (l, r) = (a.coeffs[y], b.coeffs[y]); + (a.coeffs[y], b.coeffs[y]) = (l - r, l + r); + } + } else { + for y in range { + a.coeffs[y] *= 181.0 / 128.0; + b.coeffs[y] *= 181.0 / 128.0; + } + } + } + } +} + +/// Sine windows for blocks of 128, 256 and 512 samples. +fn windows() -> &'static [Vec<f32>; 3] { + static WINDOWS: OnceLock<[Vec<f32>; 3]> = OnceLock::new(); + WINDOWS.get_or_init(|| [sine_window(128), sine_window(256), sine_window(512)]) +} + +/// FFmpeg's `vector_fmul_window` in place: the first half of `block` holds +/// the previous block's tail, the second half the current block's head. +fn window_overlap(block: &mut [f32], window: &[f32]) { + let len = block.len() / 2; + for k in 0..len { + let (i, j) = (k, 2 * len - 1 - k); + let (s0, s1) = (block[i], block[2 * len - 1 - k]); + let (wi, wj) = (window[i], window[j]); + block[i] = s0 * wj - s1 * wi; + block[j] = s0 * wi + s1 * wj; + } +} + +fn to_i16(v: f32) -> i16 { + (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: + /// the standard formula, negated). + fn imdct_reference(input: &[f32]) -> Vec<f32> { + let n = input.len(); + (0..n) + .map(|j| { + let t = (j + n / 2) as f64 + 0.5 + n as f64 / 2.0; + -(input + .iter() + .enumerate() + .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) + .sum::<f64>() as f32) + }) + .collect() + } + + #[test] + fn fast_imdct_matches_the_direct_sum() { + for n in [128usize, 256, 512] { + let input: Vec<f32> = (0..n).map(|i| ((i * 7919) % 97) as f32 - 48.0).collect(); + let mut fast = vec![0f32; n]; + imdct_half(&input, &mut fast, 1.0); + let reference = imdct_reference(&input); + for (a, b) in fast.iter().zip(&reference) { + assert!((a - b).abs() < 1e-2 * (1.0 + b.abs()), "n {n}: {a} vs {b}"); + } + } + } + + /// Windowed MDCT blocks of a signal, put back together the way the + /// decoder does (half IMDCT, then window and overlap), give the signal. + #[test] + fn imdct_and_window_reconstruct_a_signal() { + let n = 256; + let signal: Vec<f32> = (0..n * 6).map(|i| (i as f32 * 0.05).sin() * 0.3).collect(); + // The 2n-sample sine window; its rising half is `sine_window(n)`. + let window = |i: usize| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin(); + let mut out = vec![0f32; n * 7]; + for block in 0..5 { + let base = block * n; + let coeffs: Vec<f32> = (0..n) + .map(|k| { + (0..2 * n) + .map(|i| { + let t = i as f64 + 0.5 + n as f64 / 2.0; + // FFmpeg's forward MDCT pairs with its inverse + // by sign. + -signal[base + i] as f64 + * window(i) + * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() + }) + .sum::<f64>() as f32 + }) + .collect(); + // The half output is the middle of the 2n window. + let at = base + n / 2; + imdct_half(&coeffs, &mut out[at..at + n], 2.0 / n as f32); + if block > 0 { + window_overlap(&mut out[at - n / 2..at + n / 2], &sine_window(n)); + } + } + for i in n..5 * n { + assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); + } + } + + #[test] + fn packet_headers_and_frame_walk() { + // Two packets: frame A (100 bits) and B (16300 bits, crossing into + // packet 1 by 48 bits), then C (60 bits) in packet 1; the rest is + // padding. + let mut data = vec![0xffu8; 2 * PACKET_BYTES]; + let header = |frames: u32, first: u32| (frames << 26) | (first << 11); + let bits = [(0, header(2, 0), 32), (PACKET_BITS, header(1, 48), 32)]; + let put = |data: &mut Vec<u8>, at: usize, value: u32, width: u32| { + for i in 0..width as usize { + let bit = (value >> (width as usize - 1 - i)) & 1; + let p = at + i; + data[p / 8] = (data[p / 8] & !(1 << (7 - p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for &(at, v, w) in &bits { + put(&mut data, at, v, w); + } + put(&mut data, 32, 100, 15); + put(&mut data, 132, 16300, 15); + let c_start = PACKET_BITS + 32 + 48; + put(&mut data, c_start, 60, 15); + let a = read_frame(&data, 32).unwrap(); + assert_eq!((a.bits, a.next), (100, Some(132))); + let b = read_frame(&data, 132).unwrap(); + assert_eq!((b.bits, b.next), (16300, Some(c_start))); + // Its last bits come from after packet 1's header. + assert_eq!(b.data.len(), 16300usize.div_ceil(8)); + let c = read_frame(&data, c_start).unwrap(); + assert_eq!(c.bits, 60); + // C was packet 1's only frame: the next would be in packet 2. + assert_eq!(c.next, None); + } + + /// Walks and decodes saved input buffers (`VICTORY_XMA_STREAMS=<dir>` of + /// `*.xma` files with their `*.ctx` context words, made outside the + /// repository): the frames walked from the first packet must be the + /// frames the packet headers count, and every frame must decode. + #[test] + #[ignore = "needs streams outside the repository"] + fn walks_saved_streams() { + let dir = std::env::var("VICTORY_XMA_STREAMS").unwrap(); + let mut bad = 0; + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_none_or(|e| e != "xma") { + continue; + } + let data = std::fs::read(&path).unwrap(); + let counted: u32 = (0..data.len() / PACKET_BYTES) + .map(|i| packet(&data, i).unwrap().frames) + .sum(); + // Context word 1: sample rate in bits 27-28, stereo in bit 29. + let ctx = std::fs::read(path.with_extension("ctx")).unwrap(); + let word = u32::from_le_bytes(ctx[4..8].try_into().unwrap()); + let rate = [24_000, 32_000, 44_100, 48_000][(word >> 27 & 3) as usize]; + let mut decoder = Decoder::new(1 + (word >> 29 & 1) as usize, rate); + let (mut walked, mut errors, mut peak, mut pcm) = (0, 0, 0i16, Vec::new()); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + pcm.clear(); + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as u32; + peak = pcm.iter().fold(peak, |p, s| p.max(s.saturating_abs())); + walked += 1; + at = frame.next; + } + println!( + "{}: {} packets, {counted} frames counted, {walked} walked, {errors} bad, peak {peak}", + path.display(), + data.len() / PACKET_BYTES + ); + bad += u32::from(walked != counted || errors > 0); + } + assert_eq!(bad, 0); + } + + /// Decodes a stream's packets and compares with a reference decode of + /// the same file (16-bit PCM): `VICTORY_XMA_REFERENCE=<dir>` holding + /// `mono.xmadata`/`mono.ref` and `stereo.xmadata`/`stereo.ref` (made + /// outside the repository). + #[test] + #[ignore = "needs reference files outside the repository"] + fn matches_a_reference_decoder() { + let dir = std::path::PathBuf::from(std::env::var("VICTORY_XMA_REFERENCE").unwrap()); + for (name, channels) in [("mono", 1), ("stereo", 2)] { + let data = std::fs::read(dir.join(format!("{name}.xmadata"))).unwrap(); + let reference: Vec<i16> = std::fs::read(dir.join(format!("{name}.ref"))) + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|&b| i16::from_le_bytes(b)) + .collect(); + let mut decoder = Decoder::new(channels, 48_000); + let mut pcm = Vec::new(); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + let mut errors = 0; + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as usize; + at = frame.next; + } + // Find the decoder delay, then measure the error. + let best = (0..2048 / channels) + .map(|d| { + let n = reference.len().min(pcm.len() - d * channels); + let e: f64 = (0..n) + .map(|i| (pcm[d * channels + i] as f64 - reference[i] as f64).powi(2)) + .sum(); + (e, d, n) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap(); + let signal: f64 = reference.iter().map(|&s| (s as f64).powi(2)).sum(); + let snr = 10.0 * (signal / best.0.max(1.0)).log10(); + println!( + "{name}: {} samples, {errors} bad frames, delay {} samples, SNR {snr:.1} dB", + pcm.len() / channels, + best.1 + ); + assert!(errors == 0 && snr > 40.0); + } + } +} diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs new file mode 100644 index 0000000..bf8fc43 --- /dev/null +++ b/crates/victory-formats/src/xma/tables.rs @@ -0,0 +1,410 @@ +//! Huffman and level tables of the WMA Pro bitstream that XMA2 frames use, +//! converted from FFmpeg's `libavcodec/wmaprodata.h` (LGPL-2.1-or-later, +//! used here under GPL-3.0-or-later as that licence allows). Pairs are +//! (symbol, code length) in canonical code order. + +pub(super) const CRITICAL_FREQ: [u16; 28] = [ + 100, 200, 300, 400, 510, 630, 770, 920, + 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, + 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, + 20675, 28575, 41375, 63875, +]; + +pub(super) const SCALE: [(u16, u8); 121] = [ + (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), + (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), + (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), + (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), + (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), + (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), + (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), + (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), + (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), + (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), + (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), + (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), + (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), + (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), + (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), + (60, 1), +]; + +pub(super) const SCALE_RL: [(u16, u8); 120] = [ + (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), + (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), + (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), + (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), + (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), + (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), + (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), + (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), + (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), + (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), + (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), + (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), + (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), + (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), + (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), +]; + +pub(super) const SCALE_RL_RUN: [u8; 120] = [ + 0, 0, 0, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 0, + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 0, 1, 0, 1, 0, 1, +]; + +pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ + 0, 0, 1, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 7, 7, 8, 8, 9, 9, +]; + +pub(super) const COEF0_LENS: [u8; 272] = [ + 2, 9, 14, 14, 13, 12, 13, 14, + 15, 15, 12, 10, 10, 10, 13, 14, + 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, + 15, 15, 14, 13, 14, 14, 13, 15, + 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, + 15, 15, 14, 15, 15, 12, 11, 6, + 7, 8, 9, 13, 13, 13, 14, 14, + 11, 10, 7, 8, 14, 14, 14, 14, + 12, 13, 13, 12, 12, 12, 11, 9, + 13, 14, 14, 12, 11, 11, 11, 9, + 8, 7, 14, 15, 15, 14, 14, 12, + 13, 15, 16, 17, 17, 14, 12, 12, + 12, 15, 15, 14, 14, 14, 13, 13, + 9, 9, 11, 11, 10, 7, 6, 13, + 15, 15, 14, 14, 14, 13, 14, 15, + 15, 13, 14, 14, 14, 14, 10, 9, + 10, 10, 11, 11, 10, 8, 9, 13, + 14, 14, 12, 11, 14, 15, 15, 13, + 12, 14, 14, 14, 14, 13, 14, 14, + 3, 5, 8, 10, 10, 15, 15, 14, + 14, 16, 16, 15, 12, 11, 11, 11, + 7, 8, 8, 9, 12, 13, 13, 12, + 14, 15, 15, 13, 10, 11, 11, 13, + 14, 14, 13, 14, 14, 11, 10, 13, + 15, 15, 14, 12, 11, 4, 6, 6, + 8, 12, 12, 12, 13, 13, 12, 13, + 13, 14, 14, 13, 13, 13, 9, 7, + 9, 11, 14, 14, 13, 14, 14, 13, + 10, 8, 7, 5, 9, 12, 13, 14, + 15, 15, 12, 12, 10, 14, 14, 13, + 12, 13, 14, 14, 12, 13, 13, 12, + 12, 12, 9, 7, 6, 3, 4, 4, +]; + +pub(super) const COEF0_SYMS: [u16; 272] = [ + 2, 25, 111, 94, 69, 58, 87, 93, + 136, 135, 59, 37, 34, 36, 82, 182, + 120, 138, 195, 45, 168, 216, 178, 86, + 140, 219, 186, 162, 239, 18, 156, 35, + 127, 236, 109, 85, 180, 253, 88, 147, + 268, 264, 256, 266, 270, 262, 260, 248, + 246, 252, 258, 137, 189, 230, 64, 179, + 146, 208, 101, 118, 238, 163, 46, 9, + 153, 0, 26, 247, 169, 76, 202, 131, + 194, 38, 13, 19, 132, 106, 191, 97, + 65, 198, 77, 62, 66, 164, 48, 27, + 81, 183, 102, 60, 47, 49, 159, 227, + 20, 14, 112, 263, 144, 217, 104, 63, + 79, 209, 269, 250, 254, 203, 241, 196, + 61, 220, 148, 124, 185, 100, 80, 78, + 193, 28, 50, 235, 41, 1, 10, 171, + 226, 150, 103, 114, 115, 170, 105, 211, + 149, 249, 108, 188, 107, 255, 231, 155, + 42, 40, 55, 160, 39, 21, 29, 215, + 234, 184, 228, 51, 116, 142, 145, 172, + 165, 181, 130, 113, 117, 89, 128, 204, + 3, 7, 154, 157, 43, 141, 265, 133, + 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, + 123, 210, 143, 175, 44, 53, 237, 174, + 139, 134, 110, 218, 129, 161, 213, 177, + 267, 151, 125, 67, 223, 5, 11, 192, + 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, + 32, 57, 207, 121, 91, 126, 119, 99, + 158, 24, 212, 8, 33, 70, 92, 205, + 240, 242, 75, 197, 233, 259, 190, 98, + 71, 201, 122, 206, 72, 90, 95, 84, + 167, 245, 229, 17, 12, 4, 152, 6, +]; + +pub(super) const COEF1: [(u16, u8); 244] = [ + (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), + (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), + (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), + (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), + (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), + (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), + (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), + (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), + (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), + (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), + (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), + (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), + (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), + (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), + (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), + (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), + (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), + (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), + (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), + (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), + (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), + (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), + (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), + (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), + (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), + (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), + (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), + (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), + (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), + (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), + (124, 16), (123, 16), (150, 11), (1, 7), +]; + +pub(super) const COEF0_RUN: [u16; 272] = [ + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 132, 133, + 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 145, 146, 147, 148, 149, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, +]; + +pub(super) const COEF0_LEVEL: [f32; 272] = [ + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, + 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, + 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, + 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, + 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, + 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, + 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, +]; + +pub(super) const COEF1_RUN: [u16; 244] = [ + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 5, 0, 1, 2, 0, + 1, 2, 0, 1, 2, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 0, 0, +]; + +pub(super) const COEF1_LEVEL: [f32; 244] = [ + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, + 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, + 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, + 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, + 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, + 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, + 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, + 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, + 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, + 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, + 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, + 49.0, 50.0, 51.0, 52.0, +]; + +pub(super) const VEC4_LENS: [u8; 127] = [ + 1, 6, 8, 10, 10, 10, 10, 8, + 8, 10, 10, 9, 8, 8, 9, 12, + 12, 11, 12, 12, 11, 9, 9, 8, + 8, 9, 9, 8, 8, 9, 9, 12, + 12, 12, 14, 14, 13, 11, 11, 9, + 8, 9, 9, 11, 11, 10, 9, 8, + 6, 6, 6, 6, 6, 6, 11, 11, + 10, 11, 11, 10, 10, 11, 11, 9, + 7, 6, 7, 7, 6, 6, 6, 5, + 7, 11, 11, 10, 9, 8, 6, 9, + 9, 10, 10, 9, 8, 8, 6, 6, + 6, 8, 8, 9, 12, 12, 11, 10, + 8, 8, 8, 10, 10, 10, 10, 9, + 9, 8, 10, 11, 11, 9, 8, 8, + 8, 9, 9, 10, 11, 12, 12, 9, + 9, 9, 8, 8, 7, 7, 7, +]; + +pub(super) const VEC4_SYMS: [u16; 127] = [ + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, + 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, + 5121, 8961, 321, 1041, 51, 4641, 546, 4610, + 530, 513, 8451, 4385, 4130, 33, 8211, 5, + 66, 4161, 1281, 81, 6, 801, 8196, 8481, + 8449, 4611, 531, 561, 769, 12290, 8226, 19, + 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, + 12305, 49, 12321, 260, 4100, 516, 21, 12546, + 8466, 4353, 4371, 4626, 257, 18, 17, 1, + 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, + 276, 50, 785, 4116, 8209, 4099, 273, 4113, + 258, 259, 4609, 35, 1026, 1025, 16401, 305, + 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, + 4129, 545, 306, 36, 4101, 65, 20481, 786, + 4401, 4866, 8721, 291, 8450, 8465, 4115, +]; + +pub(super) const VEC2: [(u16, u8); 137] = [ + (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), + (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), + (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), + (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), + (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), + (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), + (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), + (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), + (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), + (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), + (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), + (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), + (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), + (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), + (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), + (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), + (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), + (34, 4), +]; + +pub(super) const VEC1: [(u16, u8); 101] = [ + (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), + (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), + (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), + (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), + (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), + (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), + (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), + (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), + (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), + (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), + (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), + (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), + (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), +]; + diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index 475e7b2..70a01a9 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -8,13 +8,26 @@ license.workspace = true publish.workspace = true [dependencies] +blake3.workspace = true +miniz_oxide.workspace = true tracing.workspace = true +anyhow.workspace = true +victory-formats.workspace = true +victory-pipeline.workspace = true +victory-shader.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (frame capture, the host debug layer, per-draw data). +diagnostics = [] [lints] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D12", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs new file mode 100644 index 0000000..b886893 --- /dev/null +++ b/crates/victory-gpu/src/capture.rs @@ -0,0 +1,525 @@ +//! Presented frames written to PNG files, to see what reaches the screen: +//! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of +//! two (the frames the log reports) is saved as `frame-<n>.png`, at half +//! size. Only in builds with diagnostics. + +use std::path::PathBuf; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The folder frames go to, if capturing. +pub(crate) fn folder() -> Option<&'static PathBuf> { + static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new(); + FOLDER + .get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from)) + .as_ref() +} + +/// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved +/// too, and their draws traced at debug level. +pub(crate) fn listed(n: u64) -> bool { + static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }) + .contains(&n) +} + +/// Whether frame `n` is saved. +pub(crate) fn wanted(n: u64) -> bool { + folder().is_some() && (n.is_power_of_two() || listed(n)) +} + +/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`. +pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows); +} + +/// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size. +fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + let Some(folder) = folder() else { return }; + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + // Filter byte 0 per row, then RGB of every other pixel of every other row. + let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize); + for y in 0..h as usize { + raw.push(0); + let row = &rows[(2 * y).min(height as usize - 1) * pitch..]; + for x in 0..w as usize { + let p = &row[(2 * x).min(width as usize - 1) * 4..][..3]; + if bgra { + raw.extend([p[2], p[1], p[0]]); + } else { + raw.extend_from_slice(p); + } + } + } + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut header = Vec::new(); + header.extend(w.to_be_bytes()); + header.extend(h.to_be_bytes()); + header.extend([8, 2, 0, 0, 0]); // 8-bit RGB + chunk(&mut png, b"IHDR", &header); + chunk( + &mut png, + b"IDAT", + &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3), + ); + chunk(&mut png, b"IEND", &[]); + let path = folder.join(format!("{name}.png")); + match std::fs::write(&path, png) { + Ok(()) => tracing::info!(path = %path.display(), "frame saved"), + Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), + } +} + +fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) { + png.extend((data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend(kind); + png.extend(data); + let crc = crc32(&png[start..]); + png.extend(crc.to_be_bytes()); +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in bytes { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg()); + } + } + !crc +} + +/// Records a copy of `texture` (in the copy-source state) into a +/// readback buffer. +pub(crate) fn read_back( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: a live texture; outputs for one subresource. + unsafe { + let desc = texture.GetDesc(); + device.GetCopyableFootprints( + &desc, + 0, + 1, + 0, + Some(&mut footprint), + None, + None, + Some(&mut total), + ); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + Some((buffer, footprint)) + } +} + +/// Saves a frame read back by [`read_back`] (8-bit color only). +pub(crate) fn save_read_back( + frame: u64, + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) { + let f = footprint.Footprint; + let bgra = match f.Format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false, + DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true, + other => { + tracing::warn!(format = other.0, "frame not saved: not 8-bit color"); + return; + } + }; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished (every submission is waited for); the + // mapping spans the footprint's rows. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let len = f.RowPitch as usize * f.Height as usize; + let rows = std::slice::from_raw_parts(data.cast::<u8>(), len); + save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows); + buffer.Unmap(0, None); + } +} + +/// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in +/// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved +/// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png` +/// (what each holds at the end of the frame; formats normalized to show +/// structure: floats scaled by their largest value, depth by its range). +static TARGETS: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new()); + +fn dump_on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some()) +} + +/// Notes a title texture the frame being built renders to or writes. +pub(crate) fn note_target(resource: crate::object::This) { + if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) { + return; + } + let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); + if !targets.contains(&(resource as usize)) { + targets.push(resource as usize); + } +} + +/// At the present of frame `frame`: saves the noted targets. +pub(crate) fn dump_targets(frame: u64) { + let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); + let Some(host) = crate::host::host() else { return }; + for (i, &resource) in targets.iter().enumerate() { + let resource = resource as crate::object::This; + let Some(texture) = crate::resource::host_resource(resource) else { + continue; + }; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D { + continue; + } + const COPY_SOURCE: u32 = 0x800; + let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b) + else { + dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d); + continue; + }; + dump_one(host, texture, before, frame, i, resource, &d); + crate::resource::host_transition(resource, before); + } +} + +fn dump_one( + host: &crate::host::Host, + texture: &ID3D12Resource, + state: u32, + frame: u64, + i: usize, + resource: crate::object::This, + d: &D3D12_RESOURCE_DESC, +) { + let Ok(list) = host.new_list() else { return }; + let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32); + let copy = D3D12_RESOURCE_STATE_COPY_SOURCE; + // SAFETY: an open list of ours and a live texture. + let read = unsafe { + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, state, copy)]); + } + let read = read_back(&host.device, &list.list, texture); + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, copy, state)]); + } + read + }; + list.close(); + host.execute(&[&list]); + let Some((buffer, footprint)) = read else { return }; + let f = footprint.Footprint; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let pitch = f.RowPitch as usize; + let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize); + if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { + let name = format!( + "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", + d.Width, d.Height, d.Format.0 + ); + save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba); + } else { + tracing::info!(format = f.Format.0, ?resource, "target not dumped: format"); + } + buffer.Unmap(0, None); + } +} + +fn half(h: u16) -> f32 { + let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + let v = match exp { + 0 => man * 2f32.powi(-24), + 31 => f32::INFINITY, + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + }; + if sign == 1 { -v } else { v } +} + +/// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits +/// (the 11- and 10-bit floats of R11G11B10). +fn small_float(bits: u32, man: u32) -> f32 { + let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32); + match exp { + 0 => m / (1 << man) as f32 * 2f32.powi(-14), + 31 => f32::INFINITY, + e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15), + } +} + +/// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else +/// as channel values scaled so the largest finite one is white (single +/// channels: lowest black, highest white, as grey). `None` for formats not +/// handled. +fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> { + let mut out = Vec::with_capacity(w * h * 4); + let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; + let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); + let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + // Channel values as floats, then scaled. + type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>; + let (n, decode): (usize, Decode) = match format { + 27..=32 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[0], p[1], p[2], 255]); + } + } + return Some(out); + } + 87..=93 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[2], p[1], p[0], 255]); + } + } + return Some(out); + } + 23..=25 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] + })), + 26 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] + })), + 9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), + 1..=2 => (16, Box::new(move |b| { + [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) + })), + 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), + 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), + 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), + // Single channels: shown as grey. + 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), + 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])), + 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])), + 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])), + _ => return None, + }; + let values: Vec<[f32; 3]> = (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| decode(px(x, y, n))) + .collect(); + let grey = matches!(format, 39..=43 | 53..=65); + let finite = values.iter().flatten().copied().filter(|v| v.is_finite()); + let (low, high) = if grey { + finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v))) + } else { + (0.0, finite.fold(0.0f32, f32::max)) + }; + let range = (high - low).max(1e-20); + tracing::info!(format, low, high, "target values"); + for v in values { + let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8); + out.extend([c[0], c[1], c[2], 255]); + } + Some(out) +} + +/// Pixels per side of the grid [`probe`] reads. +const GRID: u32 = 4; +/// Bytes between the grid's pixels in the readback buffer (placement +/// alignment). +const SLOT: u64 = 512; + +/// Records copies of a grid of pixels of `texture` (8-bit color, in the +/// copy-source state) into a readback buffer, to tell black frames. +pub(crate) fn probe( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option<ID3D12Resource> { + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) { + return None; + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SLOT * u64::from(GRID * GRID), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + for i in 0..GRID * GRID { + let (x, y) = ( + (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID), + (2 * (i / GRID) + 1) * d.Height / (2 * GRID), + ); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: SLOT * u64::from(i), + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: d.Format, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let pixel = D3D12_BOX { + left: x, + top: y, + front: 0, + right: x + 1, + bottom: y + 1, + back: 1, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel)); + } + Some(buffer) + } +} + +/// Whether every pixel [`probe`] read is (near) black. +pub(crate) fn black(buffer: &ID3D12Resource) -> bool { + let mut data = std::ptr::null_mut(); + // SAFETY: the copies finished (every submission is waited for). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return false; + } + let bytes = + std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize); + let level = bytes + .chunks(SLOT as usize) + .flat_map(|pixel| pixel[..3].iter().copied()) + .max() + .unwrap_or(0); + buffer.Unmap(0, None); + let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + if levels.len() == 12 { + levels.pop_front(); + } + levels.push_back(level); + level < 8 + } +} + +/// The brightest probed channel of the last frames, oldest first: a fade +/// darkens over several, a glitch drops at once. +static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> = + std::sync::Mutex::new(std::collections::VecDeque::new()); + +pub(crate) fn recent_levels() -> Vec<u8> { + let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + levels.iter().copied().collect() +} + +#[cfg(test)] +mod tests { + #[test] + fn crc_matches_the_png_check_value() { + assert_eq!(super::crc32(b"IEND"), 0xae42_6082); + } +} diff --git a/crates/victory-gpu/src/console.rs b/crates/victory-gpu/src/console.rs new file mode 100644 index 0000000..6070d2d --- /dev/null +++ b/crates/victory-gpu/src/console.rs @@ -0,0 +1,50 @@ +//! Which console the title runs on. Titles pick settings (resolution, +//! memory budgets) by it, so the user chooses; Series X unless told. + +use std::sync::atomic::{AtomicBool, Ordering}; + +const GIB: usize = 1 << 30; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Console { + #[default] + SeriesX, + SeriesS, +} + +impl Console { + /// Title memory in bytes: (GPU-optimal, standard). Series X in the + /// advanced configuration; Series S has one range, counted as standard + /// (7,776 MiB, the published console-mode figure). + // shortcut: later system updates gave Series S titles more (amount not + // published here); Grand Theft Auto VI sizes nothing from this figure + // (it goes by the device type), so update it if a title does. + pub const fn title_memory(self) -> (usize, usize) { + match self { + Console::SeriesX => (10 * GIB, 7 * GIB / 2), + Console::SeriesS => (0, 7_776 << 20), + } + } + + pub const fn name(self) -> &'static str { + match self { + Console::SeriesX => "Xbox Series X", + Console::SeriesS => "Xbox Series S", + } + } +} + +static SERIES_S: AtomicBool = AtomicBool::new(false); + +/// Set before the title starts. +pub fn set(console: Console) { + SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed); +} + +pub fn current() -> Console { + if SERIES_S.load(Ordering::Relaxed) { + Console::SeriesS + } else { + Console::SeriesX + } +} diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs new file mode 100644 index 0000000..8b7d13d --- /dev/null +++ b/crates/victory-gpu/src/copystat.rs @@ -0,0 +1,147 @@ +//! Diagnostics: where the submission copies of title memory go (which +//! ranges, how often, of what memory) and what limits their rate, logged +//! with the frame-rate line. `VICTORY_COPY_MODE=plain` copies without the +//! mapped-page guard, `none` skips the copies (both for timing only). + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Counters since the last line. +pub(crate) enum C { + Submissions, + Copies, + CopyBytes, + Refreshes, + RefreshBytes, + Skipped, + SkippedBytes, + Runs, + RunUs, + Queries, + QueryUs, + MoveUs, + Unmapped, + /// Write-watch askings and their time. + Watches, + WatchUs, + /// Bytes of watched ranges checked, and of those found unchanged. + Checked, + Unchanged, + /// Copies that met an unmapped page. + Fallbacks, + /// Writes taken by the guard on view memory. + GuardFaults, + /// Texture bytes detiled after a watched write; hashed; detiled after a + /// hash change. + TexWatched, + TexHashed, + TexChanged, +} +const COUNTERS: usize = 22; +static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; + +pub(crate) fn add(c: C, n: u64) { + COUNT[c as usize].fetch_add(n, Relaxed); +} + +/// How copies run: 0 guarded (as always), 1 plain, 2 not at all. +pub(crate) fn mode() -> u8 { + static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_COPY_MODE").as_deref() { + Ok("plain") => 1, + Ok("none") => 2, + _ => 0, + }) +} + +/// Per source range (start, length): copies, bytes, microseconds, memory type. +type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; +static RANGES: Mutex<Option<Ranges>> = Mutex::new(None); + +/// A copy of `len` bytes from `src` (memory type `kind`) took `us`. +pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { + let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let e = map + .get_or_insert_with(HashMap::new) + .entry((src, len)) + .or_insert((0, 0, 0, kind)); + e.0 += 1; + e.1 += len as u64; + e.2 += us; +} + +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// Logs the counters per frame over `frames` frames, and the ranges that +/// took most bytes. +pub(crate) fn log(frames: f64) { + static FAULTS: AtomicU64 = AtomicU64::new(0); + let faults = page_faults(); + let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); + let c: Vec<f64> = COUNT + .iter() + .map(|a| a.swap(0, Relaxed) as f64 / frames) + .collect(); + let mb = |v: f64| v / 1e6; + let ms = |v: f64| v / 1e3; + tracing::info!( + "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ + {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ + {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ + unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ + changed, {:.1} MB hashed, {:.1} MB of them changed", + c[C::Submissions as usize], + c[C::Copies as usize], + mb(c[C::CopyBytes as usize]), + c[C::Refreshes as usize], + mb(c[C::RefreshBytes as usize]), + c[C::Skipped as usize], + mb(c[C::SkippedBytes as usize]), + c[C::Runs as usize], + ms(c[C::RunUs as usize]), + c[C::Queries as usize], + ms(c[C::QueryUs as usize]), + ms(c[C::MoveUs as usize]), + mb(c[C::Unmapped as usize]), + faults as f64 / frames, + c[C::Watches as usize], + ms(c[C::WatchUs as usize]), + mb(c[C::Checked as usize]), + mb(c[C::Unchanged as usize]), + c[C::Fallbacks as usize], + c[C::GuardFaults as usize], + mb(c[C::TexWatched as usize]), + mb(c[C::TexHashed as usize]), + mb(c[C::TexChanged as usize]), + ); + let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); + ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); + for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) }; + let kind = info.Type; + tracing::info!( + " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + bytes as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } +} diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index f31a097..9ae83bd 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -10,6 +10,9 @@ use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; use crate::resource::{Memory, PAGEABLE_IIDS}; +#[cfg(windows)] +pub(crate) mod host; + const HEAP_IIDS: [Iid; 4] = [ guid( 0x8efb471d, @@ -31,18 +34,139 @@ pub(crate) struct HeapDesc { nodes: u32, } +/// Newer titles (Grand Theft Auto VI) pass the description followed by +/// memory of their own for the descriptors: an address and its size in +/// bytes, or a null address to have the heap allocate (inferred from the +/// title's call sites; older titles pass the plain description). #[repr(C)] -struct Heap { - object: Object, - desc: HeapDesc, - memory: Memory, +#[derive(Debug, Clone, Copy)] +struct Placement { + address: u64, + size: u64, } -fn heap<'a>(this: This) -> &'a Heap { +#[repr(C)] +pub(crate) struct Heap { + object: Object, + desc: HeapDesc, + /// The first descriptor: in `memory`, or in the title's own memory. + pub(crate) start: u64, + memory: Option<Memory>, + /// Shader-visible view and sampler heaps get a host heap with the same + /// descriptor order when a draw first uses them (decision 0007, step + /// 3); slots written before wait in `pending`. + #[cfg(windows)] + host: std::sync::OnceLock<Option<host::HostHeap>>, + #[cfg(windows)] + pending: std::sync::Mutex<Vec<u32>>, +} + +pub(crate) fn heap<'a>(this: This) -> &'a Heap { // SAFETY: called from descriptor heap methods only. unsafe { &*this.cast::<Heap>() } } +impl Heap { + /// Whether this is a sampler heap. + pub(crate) fn samplers(&self) -> bool { + self.desc.kind == SAMPLERS + } + + /// The host heap, made on first use from what the title wrote so far. + /// Made late because a host view heap the size of Grand Theft Auto VI's + /// costs over 100 MB of commit, which its boot needs for its page pool. + #[cfg(windows)] + pub(crate) fn host(&self) -> Option<&host::HostHeap> { + if let Some(h) = self.host.get() { + return h.as_ref(); + } + if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS) + { + return None; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + let h = self + .host + .get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count)) + .as_ref()?; + let step = u64::from(increment(self.desc.kind)?); + for i in pending.drain(..) { + h.mirror(i, self.start + u64::from(i) * step, false); + } + Some(h) + } + + /// The descriptor index of `handle` in this heap, if it lies in it. + pub(crate) fn index(&self, handle: u64) -> Option<u32> { + let step = u64::from(increment(self.desc.kind)?); + let at = handle.checked_sub(self.start)?; + let index = at / step; + (index < u64::from(self.desc.count)).then_some(index as u32) + } +} + +const VIEWS_KIND: u32 = 0; +const SAMPLERS: u32 = 1; +const SHADER_VISIBLE: u32 = 1; + +/// Shader-visible heaps by address range, for mirroring descriptor writes: +/// start, end, heap. +#[cfg(windows)] +static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new()); + +/// The shader-visible heap holding `handle`, and the descriptor's index. +#[cfg(windows)] +fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + let &(_, _, at) = heaps + .iter() + .find(|&&(start, end, _)| (start..end).contains(&handle))?; + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + Some((heap, heap.index(handle)?)) +} + +/// Makes the host descriptor for what the title wrote at `handle`, if it +/// is in a shader-visible heap. +#[cfg(windows)] +fn mirror(handle: u64) { + let Some((heap, index)) = shader_slot(handle) else { + return; + }; + let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); + match heap.host.get() { + None => pending.push(index), + Some(host) => { + drop(pending); + if let Some(host) = host { + host.mirror(index, handle, false); + } + } + } +} + +/// Gives back dynamic slots of the host heap behind the title heap at +/// `heap`, if that heap still exists. +#[cfg(windows)] +pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { + let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + if heaps.iter().any(|&(_, _, h)| h == heap) + // SAFETY: registered heaps are live (removed when dropped). + && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() + { + host.release(first, n); + } +} + +#[cfg(windows)] +impl Drop for Heap { + fn drop(&mut self) { + let at = std::ptr::from_ref::<Heap>(self) as usize; + let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps.retain(|&(_, _, h)| h != at); + } +} + /// Bytes per descriptor, by heap type (views, samplers, render targets, /// depth). fn increment(kind: u32) -> Option<u32> { @@ -73,12 +197,40 @@ impl RtvRecord { pub(crate) fn desc( &self, ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> { - // SAFETY: 24 bytes in the host's layout. - (self.described != 0).then(|| unsafe { - (&raw const self.desc) - .cast::<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC>() - .read_unaligned() - }) + const TEXTURE_2D: u32 = 4; + self.host_desc(TEXTURE_2D) + } + + /// The depth view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn depth_desc( + &self, + ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> { + const TEXTURE_2D: u32 = 3; + self.host_desc(TEXTURE_2D) + } + + /// The description words as a host type, the format as the host has it. + /// Without one, a typeless host copy gets a 2D view (`dimension`) in + /// the title's format, which the host needs spelled out. + #[cfg(windows)] + fn host_desc<T>(&self, dimension: u32) -> Option<T> { + assert!(size_of::<T>() <= size_of::<[u32; 6]>()); + let mut words = if self.described != 0 { + self.desc + } else { + [ + crate::resource::view_format(self.resource)?, + dimension, + 0, + 0, + 0, + 0, + ] + }; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: both host view descriptions are 24 bytes in this layout. + Some(unsafe { (&raw const words).cast::<T>().read_unaligned() }) } } @@ -104,41 +256,380 @@ pub(crate) extern "system" fn create_rtv( unsafe { (handle as *mut RtvRecord).write_unaligned(record) }; } +/// Device method: a depth view, recorded as render target views are. +pub(crate) extern "system" fn create_dsv( + this: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + create_rtv(this, resource, desc, handle); + if handle != 0 { + // SAFETY: just written by `create_rtv`. + unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) }; + } +} +const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); + +/// A shader view or sampler as the title described it (descriptions in the +/// host's layout, kept as words), for the host to build its own from. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum View { + /// Constant buffer: GPU address and size. + Constant(u64, u32), + /// Shader resource: resource, description (none: the resource's own). + Shader(usize, Option<[u32; 10]>), + /// Unordered access: resource, counter resource, description. + Unordered(usize, usize, Option<[u32; 10]>), + Sampler([u32; 13]), + /// The console's own sampler description: flags, filters per axis, + /// addressing, LOD and anisotropy settings, border color, then + /// console-only tuning words. + ConsoleSampler([u32; 27]), + /// A view of memory without a resource object: whether it is unordered + /// access, the resource description, then the view's (the plain one + /// followed by the memory address and console fields). + Placed(bool, [u32; 14], [u32; 16]), +} + +impl View { + /// Whether the view reads buffer memory (constant buffers, buffer views + /// of resources or of memory) or memory the title placed a texture in: + /// such views get host slots only for draws. + #[cfg(windows)] + fn is_buffer(&self) -> bool { + match self { + View::Constant(..) | View::Placed(..) => true, + View::Shader(r, _) | View::Unordered(r, _, _) => { + crate::resource::buffer_bytes(*r as This).is_some() + } + View::Sampler(_) | View::ConsoleSampler(_) => false, + } + } +} + +/// Every distinct view in use; a descriptor holds a tag, an index into it +/// and the entry's generation, which survive titles copying descriptors as +/// bytes. A view of a resource lives as long as the resource: when the +/// title releases it, its entries are freed for reuse under a new +/// generation, so descriptors (and host slots made from them) naming the +/// old one go stale instead of naming whatever is made at the same address +/// next. +/// shortcut: views without a resource object (constant buffers, memory +/// views, samplers) are kept for the run; they are bounded by the title's +/// memory and sampler states. +struct Views { + /// Each entry's view and generation. + list: Vec<(View, u32)>, + index: std::collections::BTreeMap<View, u32>, + /// Entries naming each resource. + by_resource: std::collections::BTreeMap<usize, Vec<u32>>, + free: Vec<u32>, +} + +static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views { + list: Vec::new(), + index: std::collections::BTreeMap::new(), + by_resource: std::collections::BTreeMap::new(), + free: Vec::new(), +}); +const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); + +impl View { + /// The resource objects the view names. + fn resources(&self) -> [usize; 2] { + match *self { + View::Shader(r, _) => [r, 0], + View::Unordered(r, counter, _) => [r, counter], + _ => [0, 0], + } + } +} + +fn record(handle: u64, view: View) { + if handle == 0 { + return; + } + let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let i = match views.index.get(&view) { + Some(&i) => i, + None => { + let i = match views.free.pop() { + Some(i) => { + views.list[i as usize].0 = view.clone(); + i + } + None => { + views.list.push((view.clone(), 1)); + views.list.len() as u32 - 1 + } + }; + for r in view.resources().into_iter().filter(|&r| r != 0) { + views.by_resource.entry(r).or_default().push(i); + } + views.index.insert(view, i); + i + } + }; + let generation = views.list[i as usize].1; + // SAFETY: the handle is a descriptor slot, at least 16 bytes. + unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) }; + drop(views); + #[cfg(windows)] + mirror(handle); +} + +/// The title released `resource`: the views naming it go stale. +pub(crate) fn forget(resource: usize) { + let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(entries) = views.by_resource.remove(&resource) else { + return; + }; + for i in entries { + let (view, generation) = views.list[i as usize].clone(); + // Entries freed through a view's other resource may hold another + // view by now. + if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { + continue; + } + views.index.remove(&view); + views.list[i as usize].1 = generation.wrapping_add(1).max(1); + // The view's other resource (a counter) keeps a stale entry, which + // `forget` of that resource skips. + views.free.push(i); + } +} + +/// The view of entry `i` if `generation` is still its own. +#[cfg(windows)] +fn view_at(i: u32, generation: u32) -> Option<View> { + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let (view, current) = views.list.get(i as usize)?; + (*current == generation).then(|| view.clone()) +} + +/// The view recorded at `handle`, if one is (and its resource is alive). +pub(crate) fn view(handle: u64) -> Option<View> { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner()); + let (view, current) = views.list.get(i as usize)?; + (tag == VIEW_TAG && *current == generation).then(|| view.clone()) +} + +/// A description of `N` words, if the title passes one. +fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> { + // SAFETY: the title passes a description or null. + (!desc.is_null()).then(|| unsafe { desc.read_unaligned() }) +} + +/// Device method. +pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) { + if let Some([lo, hi, size, _]) = words(desc) { + let address = u64::from(lo) | u64::from(hi) << 32; + record(handle, View::Constant(address, size)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_srv( + _: This, + resource: This, + desc: *const [u32; 10], + handle: u64, +) { + record(handle, View::Shader(resource as usize, words(desc))); +} + +/// Device method. +pub(crate) extern "system" fn create_uav( + _: This, + resource: This, + counter: This, + desc: *const [u32; 10], + handle: u64, +) { + let view = View::Unordered(resource as usize, counter as usize, words(desc)); + record(handle, view); +} + +/// Device methods 0x230 and 0x238: shader resource and unordered access +/// views of memory the title placed itself, `(resource desc, view desc, +/// handle)`. +pub(crate) extern "system" fn create_placed_srv( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(false, resource, desc)); + } +} + +pub(crate) extern "system" fn create_placed_uav( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(true, resource, desc)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::Sampler(desc)); + } +} + +/// Device method 0x1e8. +pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::ConsoleSampler(desc)); + } +} + +/// Device method: `count` descriptors of `kind` from `src` to `dst`. +pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) { + let step = u64::from(increment(kind).unwrap_or(0)); + let len = u64::from(count) * step; + if dst != 0 && src != 0 { + // SAFETY: both ranges are descriptor slots the title owns. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + for i in 0..u64::from(count) { + mirror(dst + i * step); + } + } +} + +/// Device method: ranges of descriptors (start and count each) gathered +/// from the sources and scattered to the destinations, in order. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn copy( + _: This, + dst_ranges: u32, + dst_starts: *const u64, + dst_sizes: *const u32, + src_ranges: u32, + src_starts: *const u64, + src_sizes: *const u32, + kind: u32, +) { + let Some(step) = increment(kind) else { + return; + }; + // Each range as (start, count); a null size array means one descriptor + // per range. + let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> { + (0..n as usize) + .map(|i| { + // SAFETY: the title passes `n` starts and sizes (or null sizes). + unsafe { + ( + *starts.add(i), + if sizes.is_null() { 1 } else { *sizes.add(i) }, + ) + } + }) + .collect() + }; + if dst_starts.is_null() || src_starts.is_null() { + return; + } + let src = ranges(src_ranges, src_starts, src_sizes); + let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter(); + let (mut to, mut room) = dst.next().unwrap_or((0, 0)); + for (mut from, mut left) in src { + while left > 0 { + while room == 0 { + let Some(next) = dst.next() else { return }; + (to, room) = next; + } + let n = left.min(room); + copy_simple(std::ptr::null(), n, to, from, kind); + let bytes = u64::from(n) * u64::from(step); + (to, from, room, left) = (to + bytes, from + bytes, room - n, left - n); + } + } +} + /// The view recorded at `handle`, if one is. pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> { + tagged_record(handle, RTV_TAG) +} + +/// The depth view recorded at `handle`, if one is. +pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> { + tagged_record(handle, DSV_TAG) +} + +fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> { if handle == 0 { return None; } // SAFETY: the handle is a descriptor slot the title passes back. let record = unsafe { (handle as *const RtvRecord).read_unaligned() }; - (record.tag == RTV_TAG).then_some(record) + (record.tag == tag).then_some(record) } /// Device method. pub(crate) extern "system" fn create_heap( _: This, - desc: *const HeapDesc, + desc_ptr: *const HeapDesc, iid: *const Iid, out: *mut This, ) -> HRESULT { // SAFETY: the title passes a description (null is tolerated). - let Some(&desc) = (unsafe { desc.as_ref() }) else { + let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else { return E_INVALIDARG; }; let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1))) else { return E_INVALIDARG; }; - tracing::debug!(?desc, "descriptor heap"); - let memory = match Memory::zeroed(size, 64) { - Ok(memory) => memory, - Err(hr) => return hr, + // SAFETY: read only as a hint: a title that passes the plain + // description has its own stack or data after it. + let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() }; + // shortcut: a placement is recognised by its size matching the count, + // since the plain and extended descriptions share the slot and the + // interface version; find the flag that tells them apart if a title + // trips over this. + let placed = placement.address != 0 && placement.size == size; + tracing::debug!(?desc, placed, "descriptor heap"); + let (start, memory) = if placed { + (placement.address, None) + } else { + match Memory::zeroed(size, 64) { + Ok(memory) => (memory.address(), Some(memory)), + Err(hr) => return hr, + } }; + let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS); let heap = Box::new(Heap { object: Object::new(&FUNCTIONS), desc, + start, memory, + #[cfg(windows)] + host: std::sync::OnceLock::new(), + #[cfg(windows)] + pending: Default::default(), }); + #[cfg(windows)] + if visible { + let at = std::ptr::from_ref::<Heap>(&heap) as usize; + let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner()); + heaps.push((start, start + size, at)); + } + #[cfg(not(windows))] + let _ = visible; object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out) } @@ -157,12 +648,12 @@ extern "system" fn desc(this: This, out: *mut HeapDesc) { } /// The same address for the CPU and the GPU start. extern "system" fn start(this: This) -> u64 { - heap(this).memory.address() + heap(this).start } /// IUnknown 3, object 4, device child 1, heap 3. -static FUNCTIONS: Table<11> = { - let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 11>()); +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 @@ -177,6 +668,16 @@ mod tests { use super::*; use crate::object::{S_OK, slot}; + /// What newer titles pass; tests use it throughout, so that reading the + /// placement stays inside the value. + #[repr(C)] + struct Extended(HeapDesc, Placement); + + fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT { + let extended = Extended(desc, placement); + create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) + } + #[test] fn heaps_hold_count_descriptors_from_their_start() { let null = std::ptr::null(); @@ -186,8 +687,12 @@ mod tests { flags: 1, nodes: 0, }; + let none = Placement { + address: 0, + size: 0, + }; let mut h = null; - assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK); + assert_eq!(create(desc, none, &mut h), S_OK); let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h); assert_eq!(cpu % 64, 0); assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu); @@ -196,6 +701,90 @@ mod tests { unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) }; assert_eq!(increment_size(null, 9), 0); let bad = HeapDesc { kind: 9, ..desc }; - assert_eq!(create_heap(null, &bad, &HEAP_IIDS[0], &mut h), E_INVALIDARG); + assert_eq!(create(bad, none, &mut h), E_INVALIDARG); + } + + #[test] + fn views_survive_copies() { + let null = std::ptr::null(); + let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots + let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64; + let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3)); + create_cbv(null, &[0x1000, 1, 256, 0], s0); + assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256))); + create_srv(null, null, std::ptr::null(), s1); + assert_eq!(view(s1), Some(View::Shader(0, None))); + // The same view twice is one entry. + create_srv(null, null, std::ptr::null(), s2); + // SAFETY: both slots are in `heap`. + assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe { + *(s2 as *const [u32; 3]) + }); + // Two ranges of one into one range of two. + let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]); + copy( + null, + 1, + dst.as_ptr(), + dst_n.as_ptr(), + 2, + src.as_ptr(), + src_n.as_ptr(), + 0, + ); + assert_eq!(view(s2), view(s0)); + assert_eq!(view(s3), view(s1)); + assert_eq!(view(at(0) + 8), None); + heap[0] = 0; + } + + /// A released resource's views go stale; the same view of a new + /// resource at the same address is a new record. + #[test] + fn views_die_with_their_resource() { + let null = std::ptr::null(); + let slots = [0u64; 2 * 4]; + let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32); + let resource = 0x7777_0000usize as This; + create_srv(null, resource, std::ptr::null(), a); + assert_eq!(view(a), Some(View::Shader(0x7777_0000, None))); + forget(0x7777_0000); + assert_eq!(view(a), None, "stale after release"); + create_srv(null, resource, std::ptr::null(), b); + assert_eq!(view(b), Some(View::Shader(0x7777_0000, None))); + // SAFETY: both slots are in `slots`. + let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) }; + assert_ne!(old, new, "a new generation"); + } + + /// Grand Theft Auto VI places its shader-visible heap in its own memory + /// and checks that the heap starts there. + #[test] + fn placed_heaps_start_at_the_title_memory() { + let mut memory = vec![0u8; 64 * 32]; + let address = memory.as_mut_ptr() as u64; + let desc = HeapDesc { + kind: 0, + count: 64, + flags: 1, + nodes: 1, + }; + let mut h = std::ptr::null(); + assert_eq!( + create( + desc, + Placement { + address, + size: 64 * 32 + }, + &mut h + ), + S_OK + ); + assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address); + assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address); + // A size that does not match the count is not a placement. + assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK); + assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address); } } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs new file mode 100644 index 0000000..27655d1 --- /dev/null +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -0,0 +1,731 @@ +//! Host descriptor heaps behind the title's shader-visible heaps (decision +//! 0007, step 3). Translated shaders index the heaps directly at the +//! title's descriptor positions, so each host heap keeps the title heap's +//! order: slot `i` is made from what the title wrote at slot `i`, when it +//! writes it (view creation and descriptor copies) and again when a draw +//! reads it through a table and finds the slot changed. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{VIEW_TAG, View, view_at}; +use crate::host::host; + +pub(crate) struct HostHeap { + pub(crate) heap: ID3D12DescriptorHeap, + cpu: usize, + step: u32, + /// Slots mirroring the title's; view heaps have [`DYNAMIC`] more. + count: u32, + sampler: bool, + /// The record (view index and generation) each slot was last made from. + made: Mutex<Vec<u64>>, + /// Where the search for free dynamic slots starts, and which are taken + /// (by lists not yet reset). + next: Mutex<(u32, Vec<bool>)>, +} + +/// The host's limit for shader-visible view heaps on resource binding +/// tiers 1 and 2; tier 3 hardware may take more. +const PORTABLE_VIEWS: u32 = 1_000_000; + +/// Slots past the title's in a view heap, for tables a draw needs made +/// afresh (constant buffers copied per draw). A list holds the slots it +/// took until it is reset (its submissions have run) or released. +const DYNAMIC: u32 = 1 << 16; + +impl HostHeap { + pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> { + let host = host()?; + let kind = if sampler { + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + } else { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + }; + let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> { + // SAFETY: plain heap creation. + unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + }; + let extra = if sampler { 0 } else { DYNAMIC }; + let (heap, count) = match make(count + extra) { + Ok(heap) => (heap, count), + Err(e) if !sampler && count + extra > PORTABLE_VIEWS => { + // shortcut: descriptors past the host's limit are left out; + // a title that reaches them needs remapping. + tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}"); + (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra) + } + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } + }; + // SAFETY: a live heap. + let (cpu, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + host.device.GetDescriptorHandleIncrementSize(kind), + ) + }; + tracing::debug!(count, sampler, "host descriptor heap"); + let h = HostHeap { + heap, + cpu, + step, + count, + sampler, + made: Mutex::new(vec![0; count as usize]), + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + }; + // A slot never written is undefined: shaders reading one (a slot + // the title wrote in a way we do not know, or a table entry no + // used-resource entry names) read a wild address. Every slot starts + // null instead. + let started = std::time::Instant::now(); + if let Err(e) = h.fill_null(kind, count + extra) { + tracing::warn!(error = %e, "host descriptor heap not made null"); + } + tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); + Some(h) + } + + /// Makes the first `total` slots null: one null slot in a CPU-side heap, + /// doubled by copies to a block, the block copied over the heap. + fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { + const BLOCK: u32 = 1 << 16; + let Some(host) = host() else { return Ok(()) }; + // SAFETY: plain heap creation and copies inside live heaps. + unsafe { + let block: ID3D12DescriptorHeap = + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; + let start = block.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (i * self.step) as usize, + }; + if self.sampler { + null_sampler(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + let mut done = 0; + while done < total { + let n = BLOCK.min(total - done); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + done += n; + } + } + Ok(()) + } + + /// A plain point sampler at slot `index`, for sampler slots without a + /// view. + fn null_sampler(&self, index: u32) { + null_sampler(self.cpu(index)); + } +} + +/// A plain point sampler at `at`. +fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + ..Default::default() + }; + // SAFETY: a slot of a sampler heap of ours. + unsafe { host.device.CreateSampler(&desc, at) }; +} + +impl HostHeap { + /// `n` consecutive free dynamic slots (view heaps only), taken until + /// [`HostHeap::release`]: the first's index. + pub(crate) fn dynamic(&self, n: u32) -> Option<u32> { + if self.sampler || n == 0 || n > DYNAMIC { + return None; + } + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let (next, taken) = &mut *guard; + let n = n as usize; + // Search from `next` on, then from the start. + let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize); + let mut run = 0; + let mut found = None; + let mut last = usize::MAX; + for at in starts { + // A run cannot wrap past the end. + if at != last.wrapping_add(1) { + run = 0; + } + last = at; + run = if taken[at] { 0 } else { run + 1 }; + if run == n { + found = Some(at + 1 - n); + break; + } + } + let Some(first) = found else { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + return None; + }; + taken[first..first + n].fill(true); + *next = ((first + n) % DYNAMIC as usize) as u32; + Some(self.count + first as u32) + } + + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] + /// returned). + /// + /// [`dynamic`]: HostHeap::dynamic + pub(crate) fn release(&self, first: u32, n: u32) { + let Some(at) = first.checked_sub(self.count) else { + return; + }; + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let end = (at + n).min(DYNAMIC) as usize; + if let Some(slots) = guard.1.get_mut(at as usize..end) { + slots.fill(false); + } + } + + /// Makes slot `index` (a dynamic one) from `view`; a null view if the + /// host cannot. + pub(crate) fn make_at(&self, index: u32, view: &View) { + if !make(view, self.cpu(index)) { + null_for(view, self.cpu(index)); + } + } + + /// Makes slot `index` read nothing: a null view, or a plain sampler. + pub(crate) fn make_null(&self, index: u32) { + if self.sampler { + self.null_sampler(index); + } else { + null_view(self.cpu(index)); + } + } + + /// Makes slot `index` (a dynamic one) a constant buffer view of host + /// memory. + pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { + let Some(host) = host() else { return }; + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the memory is the caller's. + unsafe { + host.device + .CreateConstantBufferView(Some(&desc), self.cpu(index)) + }; + } + + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.cpu + index as usize * self.step as usize, + } + } + + /// Makes host slot `index` from the record the title has at `handle` + /// if it changed since, and returns the view recorded there. Buffer + /// views are made only for draws (`for_draw`), which also copy their + /// data: a host copy of a buffer is made on first use. + pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> { + if index >= self.count { + return None; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + // Generations start at 1, so a made slot's key is never 0. + let key = u64::from(generation) << 32 | u64::from(i); + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); + let Some(view) = view else { + // Not a view of ours (never written, or of a resource the + // title released): nothing to read. + if made[index as usize] != 0 { + made[index as usize] = 0; + self.make_null(index); + } + return None; + }; + if made[index as usize] != key { + let later = !for_draw && view.is_buffer(); + made[index as usize] = if later { 0 } else { key }; + if (later || !make(&view, self.cpu(index))) && !self.sampler { + null_for(&view, self.cpu(index)); + } + } + Some(view) + } + + /// The view host slot `index` was made from, in a few words, with the + /// title and host addresses of a buffer view (diagnostics). "null" for + /// a slot never made or left null. + #[cfg(feature = "diagnostics")] + pub(crate) fn describe_slot(&self, index: u32) -> Option<String> { + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + if key == 0 { + return Some("null".into()); + } + let view = view_at(key as u32, (key >> 32) as u32)?; + let mut text: String = format!("{view:?}").chars().take(120).collect(); + if let Some((address, len)) = buffer_range(&view) { + let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address)); + text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}")); + } + Some(text) + } +} + +/// Logs `what` the first time it happens. +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A view description from its words, with the format as the host has it. +fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>() + .read_unaligned() + } +} + +fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>() + .read_unaligned() + } +} + +/// A buffer view of title memory at `address` on its host copy: the first +/// element moves by the copy's offset. +/// Bytes per element of a buffer view. +fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + } +} + +/// The title memory a buffer shader or unordered access view reads: its +/// address and length. +pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { + let (base, words): (u64, &[u32; 10]) = match view { + View::Shader(r, Some(desc)) => ( + crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64, + desc, + ), + View::Placed(false, resource, desc) if resource[0] == 1 => ( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + desc[..10].try_into().ok()?, + ), + View::Unordered(r, _, Some(desc)) => { + let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64; + return unordered_range(base, desc); + } + View::Placed(true, resource, desc) if resource[0] == 1 => { + let base = u64::from(desc[10]) | u64::from(desc[11]) << 32; + return unordered_range(base, desc[..10].try_into().ok()?); + } + _ => return None, + }; + let desc = srv_desc(words); + let element = element_size(&desc); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +/// [`buffer_range`] of an unordered access view of memory at `base`. +fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { + let desc = uav_desc(words); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32)?.0 + }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +fn buffer_srv( + address: u64, + len: u64, + mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> bool { + let Some(shadow) = crate::shadow::find(address, len) else { + return false; + }; + let element = element_size(&desc); + // SAFETY: a buffer view's union member. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + let offset = shadow.offset(address); + if element == 0 || offset % element != 0 { + once!( + offset, + element, + "buffer view not on an element of its host copy" + ); + return false; + } + buffer.FirstElement += offset / element; + let Some(host) = host() else { return false }; + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) + }; + true +} + +/// An unordered access view of title buffer memory at `address` (`len` +/// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be +/// written by shaders (upload memory). +/// shortcut: what shaders write stays in the host copy; title memory (and +/// so the CPU, and copies run on the CPU) does not see it. +fn buffer_uav( + address: u64, + len: u64, + mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> bool { + let Some(shadow) = crate::shadow::find(address, len) else { + return false; + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + once!("unordered access to a buffer whose host copy shaders cannot write"); + return false; + } + // SAFETY: a buffer view's union member. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let offset = shadow.offset(address); + if element == 0 || offset % element != 0 { + once!(offset, element, "unordered buffer view not on an element of its host copy"); + return false; + } + buffer.FirstElement += offset / element; + buffer.CounterOffsetInBytes = 0; + let Some(host) = host() else { return false }; + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + }; + true +} + +/// Whether the host can make a shader (or unordered access) view of +/// `texture` in `format` (none: the texture's own). The console allows any +/// view; the host refuses (and removes the device for) views without the +/// resource's permission, of typed depth, and in another format than a +/// typed resource's. A view of a typed texture in another format of its +/// family takes the texture's format. +/// shortcut: such a view (sRGB of UNORM, say) reads without its +/// conversion; cast with castable formats if colors come out wrong. +fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { + use crate::resource::{DEPTH_FORMATS, family}; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let allowed = if unordered { + d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + } else { + d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0 + }; + let own = d.Format.0 as u32; + if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { + once!( + unordered, + format = own, + flags = d.Flags.0, + "view the host does not allow" + ); + return false; + } + // Every family has more than one format, its typeless one first. + let typeless = family(own) == own && family(own + 1) == own; + if let Some(format) = format.as_deref_mut() + && unordered + && let Some(&(_, linear)) = crate::resource::SRGB + .iter() + .find(|&&(s, _)| s == format.0 as u32) + { + format.0 = linear as i32; + } + let view = format.as_ref().map_or(0, |f| f.0 as u32); + if view == 0 { + return !typeless; + } + if family(view) != family(own) { + once!(view, own, "view format of another family"); + return false; + } + if let Some(format) = format + && !typeless + { + *format = d.Format; + } + true +} + +/// Makes the host descriptor for `view` at `at`; false if it cannot. +fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool { + let Some(host) = host() else { return false }; + let device = &host.device; + match view { + &View::Constant(address, size) => { + let Some(shadow) = crate::shadow::find(address, u64::from(size)) else { + return false; + }; + let gpu = shadow.gpu(address); + if gpu % 256 != 0 { + once!( + address = format_args!("{address:#x}"), + "constant buffer not 256-byte aligned on the host" + ); + return false; + } + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the range lies in the host copy. + unsafe { device.CreateConstantBufferView(Some(&desc), at) }; + true + } + View::Shader(resource, desc) => { + let resource = *resource as crate::object::This; + if let Some(texture) = crate::resource::host_resource(resource) { + let mut desc = desc.as_ref().map(srv_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { + return false; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateShaderResourceView( + texture, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + true + } else if let (Some((data, len)), Some(desc)) = + (crate::resource::buffer_bytes(resource), desc) + { + buffer_srv(data as u64, len, srv_desc(desc), at) + } else { + false + } + } + View::Unordered(resource, _counter, desc) => { + let resource = *resource as crate::object::This; + let Some(texture) = crate::resource::host_resource(resource) else { + return match (crate::resource::buffer_bytes(resource), desc) { + (Some((data, len)), Some(desc)) => { + buffer_uav(data as u64, len, uav_desc(desc), at) + } + _ => false, + }; + }; + let mut desc = desc.as_ref().map(uav_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { + return false; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateUnorderedAccessView( + texture, + None::<&ID3D12Resource>, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + true + } + View::Sampler(words) => { + // SAFETY: 13 words in the host's layout. + let desc = unsafe { + std::ptr::from_ref(words) + .cast::<D3D12_SAMPLER_DESC>() + .read_unaligned() + }; + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + true + } + View::ConsoleSampler(words) => { + let desc = crate::sampler::console(words); + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + true + } + View::Placed(unordered, resource, desc) => { + if let Some(view) = placed_texture(view) { + return make(&view, at); + } + const BUFFER: u32 = 1; + if resource[0] != BUFFER { + // shortcut: unordered access to a texture the title placed + // itself is not mirrored; give it a resource as shader + // views of such textures get when a dispatch writes one. + once!(dimension = resource[0], "placed unordered texture view not mirrored"); + return false; + } + // The resource description's width, after the alignment. + let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + if *unordered { + buffer_uav(address, len, uav_desc(words), at) + } else { + buffer_srv(address, len, srv_desc(words), at) + } + } + } +} + +/// A shader view of a texture the title placed in memory itself, as a view +/// of the resource made for that memory (on first use). +pub(crate) fn placed_texture(view: &View) -> Option<View> { + const BUFFER: u32 = 1; + let View::Placed(false, resource, desc) = view else { + return None; + }; + if resource[0] == BUFFER { + return None; + } + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let texture = crate::resource::texture_at(address, resource)?; + Some(View::Shader(texture as usize, desc[..10].try_into().ok())) +} + +/// A null view of the kind `view` is, for a slot whose view the host +/// cannot make: unordered access (to a buffer or a 2D texture) or a shader +/// view. Writes to it are dropped, reads give zeros. +fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let buffer = match view { + View::Unordered(r, _, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_some(), + View::Placed(true, resource, _) => resource[0] == 1, + _ => return null_view(at), + }; + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: if buffer { + D3D12_UAV_DIMENSION_BUFFER + } else { + D3D12_UAV_DIMENSION_TEXTURE2D + }, + ..Default::default() + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) + }; +} + +/// A view that reads zeros, for slots whose view the host cannot make. +fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Dynamic slots stay taken until given back, and runs do not wrap. + #[test] + fn dynamic_slots_are_held_until_released() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let a = heap.dynamic(DYNAMIC - 100).unwrap(); + let b = heap.dynamic(60).unwrap(); + assert_eq!((a, b), (4, 4 + DYNAMIC - 100)); + // 40 left at the end: 50 do not fit until something is given back. + assert_eq!(heap.dynamic(50), None); + heap.release(a, 50); + assert_eq!(heap.dynamic(50), Some(4)); + assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40)); + } +} diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index 9e52a80..39a38a0 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -28,8 +28,72 @@ pub static IID: Iid = guid( [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], ); -/// The interface version these layouts were checked against (2.4, what -/// Minecraft passes). Newer titles may lay objects out differently. +/// The levels the device answers to, as on PC: `ID3D12Device1` to +/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates +/// its device as. Each level's table is the one before plus its methods. +const LEVEL_IIDS: [Iid; 9] = [ + guid( + 0x77acce80, + 0x638e, + 0x4e65, + [0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e], + ), + guid( + 0x30baa41e, + 0xb15b, + 0x475c, + [0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28], + ), + guid( + 0x81dadc15, + 0x2bad, + 0x4392, + [0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98], + ), + guid( + 0xe865df17, + 0xa9ee, + 0x46f9, + [0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5], + ), + guid( + 0x8b4f173b, + 0x2fea, + 0x4b80, + [0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d], + ), + guid( + 0xc70b221b, + 0x40e4, + 0x4a17, + [0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc], + ), + guid( + 0x5c014b53, + 0x68a1, + 0x4b9b, + [0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b], + ), + guid( + 0x728f1fa2, + 0xea11, + 0x4a9f, + [0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9], + ), + guid( + 0x5405c344, + 0xd457, + 0x444e, + [0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39], + ), +]; + +fn is_device(iid: *const Iid) -> bool { + object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS) +} + +/// The interface version these layouts were checked against (2.4). Both +/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it. pub const CHECKED_VERSION: u32 = 0x0002_0004; /// Feature level 12_2, what the console hardware supports. @@ -78,19 +142,34 @@ pub extern "system" fn create( "device layouts were checked against {CHECKED_VERSION:#x} only" ); } - if *iid != IID { + if !is_device(iid) { tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface"); return E_NOINTERFACE; } if out.is_null() { return S_FALSE; } + if *iid == LEVEL_IIDS[8] { + NEWER.store(true, std::sync::atomic::Ordering::Relaxed); + } object::answer(object::DEVICE, iid, Some(device()), out) } +/// Set when the title creates the device as `ID3D12Device11`. Its lists and +/// queues then have the newer layouts (two more methods each; see +/// `list` and `queue`), although the interface version stays 2.4. +/// shortcut: the creation interface is the only sign of the newer layouts +/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022); +/// look for a better one if a title breaks the rule. +static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn newer() -> bool { + NEWER.load(std::sync::atomic::Ordering::Relaxed) +} + /// The device, or its DXGI side. extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT { - let found = if object::is(iid, &[IID]) { + let found = if is_device(iid) { Some(this) } else if object::is(iid, &dxgi::DEVICE_IIDS) { Some(dxgi::device()) @@ -100,6 +179,55 @@ extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) object::answer(object::DEVICE, iid, found, out) } +/// What `D3D12ConfigureVirtualMemoryX` takes and fills in. +#[repr(C)] +pub struct VirtualMemory { + flags: u32, + /// GPU page table size in 4 MiB pages. + page_table_pages: u32, + /// Memory kept across title processes for the frame buffer. + preserved_bytes: u32, + /// Out: the range graphics addresses fall in. + lowest: u64, + highest: u64, +} +const _: () = assert!(size_of::<VirtualMemory>() == 0x20); + +/// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics +/// allocation. The inputs size console structures we do not have; the +/// range out is all of user space, since GPU addresses are CPU addresses. +pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT { + // SAFETY: the title passes its configuration (null is tolerated). + let Some(config) = (unsafe { config.as_mut() }) else { + return E_INVALIDARG; + }; + tracing::info!( + flags = config.flags, + page_table_pages = config.page_table_pages, + preserved_bytes = config.preserved_bytes, + "graphics virtual memory" + ); + (config.lowest, config.highest) = user_space(); + S_OK +} + +fn user_space() -> (u64, u64) { + #[cfg(windows)] + { + use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO}; + // SAFETY: plain data, filled in by the call. + let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer. + unsafe { GetSystemInfo(&mut info) }; + ( + info.lpMinimumApplicationAddress as u64, + info.lpMaximumApplicationAddress as u64, + ) + } + #[cfg(not(windows))] + (0x1_0000, 0x7fff_fffe_ffff) +} + extern "system" fn node_count(_: This) -> u32 { 1 } @@ -217,9 +345,13 @@ fn feature_levels(data: *mut c_void) -> HRESULT { } } -/// IUnknown 3, object methods 4, device methods 76. -static FUNCTIONS: Table<83> = { - let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>()); +/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the +/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, +/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of +/// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown. +/// Every slot exists so that a call to one we have not written logs it. +static FUNCTIONS: Table<160> = { + let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>()); f[0] = query_interface as *const (); // 0x00 f[7] = node_count as *const (); // 0x38 f[8] = queue::create as *const (); // 0x40 @@ -231,8 +363,16 @@ static FUNCTIONS: Table<83> = { f[14] = descriptor::create_heap as *const (); // 0x70 f[15] = descriptor::increment_size as *const (); // 0x78 f[16] = root::create as *const (); // 0x80 + f[17] = descriptor::create_cbv as *const (); // 0x88 + f[18] = descriptor::create_srv as *const (); // 0x90 + f[19] = descriptor::create_uav as *const (); // 0x98 f[20] = descriptor::create_rtv as *const (); // 0xa0 + f[21] = descriptor::create_dsv as *const (); // 0xa8 + f[22] = descriptor::create_sampler as *const (); // 0xb0 + f[23] = descriptor::copy as *const (); // 0xb8 + f[24] = descriptor::copy_simple as *const (); // 0xc0 f[25] = resource::allocation_info as *const (); // 0xc8 + f[26] = resource::custom_heap_properties as *const (); // 0xd0 f[27] = resource::create_committed as *const (); // 0xd8 f[28] = resource::create_heap as *const (); // 0xe0 f[29] = resource::create_placed as *const (); // 0xe8 @@ -240,12 +380,26 @@ static FUNCTIONS: Table<83> = { f[38] = resource::copyable_footprints as *const (); // 0x130 f[39] = query::create as *const (); // 0x138 f[41] = signature::create as *const (); // 0x148 + f[48] = queue::create_x as *const (); // 0x180 + f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 + f[62] = pipeline::create_compute_x as *const (); // 0x1f0 f[69] = object::ignore as *const (); // 0x228 debug error filter + f[70] = descriptor::create_placed_srv as *const (); // 0x230 + f[71] = descriptor::create_placed_uav as *const (); // 0x238 f[73] = list::create_list_x as *const (); // 0x248 + f[74] = resource::register_page_pool as *const (); // 0x250 + f[75] = resource::unregister_page_pool as *const (); // 0x258 + // CreateCommittedResourceX: its description is PC's plus DCC options, + // which we have no use for (the AMD upscaler's, on Series S). + f[76] = resource::create_committed as *const (); // 0x260 f[78] = frame::set_interval as *const (); // 0x270 f[79] = frame::schedule as *const (); // 0x278 f[80] = frame::wait as *const (); // 0x280 f[81] = frame::statistics as *const (); // 0x288 + f[86] = pipeline::create_stream as *const (); // 0x2b0 + f[108] = resource::allocation_info2 as *const (); // 0x360 + f[127] = resource::create_committed3 as *const (); // 0x3f8 + f[133] = resource::create_at_address as *const (); // 0x428 Table(f) }; @@ -274,10 +428,39 @@ mod tests { slot::<extern "system" fn(This) -> u32>(device, 0x38)(device), 1 ); - let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x88); + let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0); assert_eq!(missing(), E_NOTIMPL); } + #[test] + fn newer_device_levels_are_the_same_device() { + // ID3D12Device11, as Grand Theft Auto VI asks for it. + let (hr, device) = create_as(&LEVEL_IIDS[8]); + assert_eq!((hr, device), (S_OK, super::device())); + let mut same = std::ptr::null(); + assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK); + assert_eq!(same, device); + // A Device8 method we have not written fails without crashing. + let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x3a0); + assert_eq!(missing(), E_NOTIMPL); + } + + #[test] + fn virtual_memory_configuration_reports_user_space() { + let mut config = VirtualMemory { + flags: 0, + page_table_pages: 7, + preserved_bytes: 0, + lowest: 0, + highest: 0, + }; + assert_eq!(configure_virtual_memory(&mut config), S_OK); + assert!(0 < config.lowest && config.lowest < config.highest); + let heap = Box::new(0u8); + assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64))); + assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG); + } + #[test] fn feature_levels_pick_the_highest_supported() { type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs new file mode 100644 index 0000000..e7a3ec4 --- /dev/null +++ b/crates/victory-gpu/src/draw.rs @@ -0,0 +1,987 @@ +//! Draws on the host GPU (decision 0007, step 3). A list keeps the state +//! the title sets for its draws (pipeline, descriptor heaps, root +//! arguments, vertex and index buffers, targets); each draw then brings the +//! host list up to date: the host pipeline and our root signature, the +//! user data the translated shaders read, the host copies of the buffers +//! and descriptors they read, and the states of the textures involved. +//! State the host keeps across draws (viewports, scissors, blend factor, +//! stencil reference, topology, targets) is set on the host list as the +//! title sets it. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use victory_shader::{ResourceType, RootType, UsedResource}; + +use crate::descriptor::View; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::Interface; + +use crate::host::HostList; +use crate::object::This; +use crate::pipeline::host::HostPipeline; + +/// A root argument as the title set it. +#[derive(Debug, Clone, Default)] +enum Root { + #[default] + None, + /// A descriptor table's first descriptor (an address in a heap). + Table(u64), + Constants(Vec<u32>), + /// A root view's GPU address. + View(u64), +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct VertexView { + address: u64, + size: u32, + stride: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct IndexView { + address: u64, + size: u32, + format: u32, +} + +/// What one title list has set, and what its host list was last given. +#[derive(Default)] +pub(crate) struct State { + pipeline: usize, + /// View heap, sampler heap. + heaps: [usize; 2], + graphics: Vec<Root>, + compute: Vec<Root>, + vertex: [VertexView; 32], + index: IndexView, + /// Bound render target and depth resources, for their host states. + targets: Vec<usize>, + depth: usize, + /// The title's primitive topology (the host's may differ). + topology: u32, + /// What the host list has: pipeline, root signature, heaps. + host_pipeline: usize, + /// Graphics, compute. + host_roots: [usize; 2], + host_heaps: [usize; 2], + /// Tables made afresh in this list: (table, what it holds) → first + /// dynamic slot. + fresh_tables: std::collections::HashMap<(u64, u64), u32>, + /// The dynamic slots the list holds: title heap, first, count; given + /// back when the list is reset or released. + dynamic: Vec<(usize, u32, u32)>, +} + +impl Drop for State { + fn drop(&mut self) { + for &(heap, first, n) in &self.dynamic { + crate::descriptor::release_dynamic(heap, first, n); + } + } +} + +/// Draws recorded on the host GPU since the last frame line. +static DRAWN: AtomicU64 = AtomicU64::new(0); + +/// Draws run on the host so far. +pub(crate) fn drawn() -> u64 { + DRAWN.load(Ordering::Relaxed) +} + +/// The draws traced since the last present (diagnostics builds, with +/// debug logging for this module): logged when the frame comes out black. +#[cfg(feature = "diagnostics")] +static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); + +/// The draws traced since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn take_frame() -> Vec<String> { + std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// Marks the last traced draw as not run on the host. +#[cfg(feature = "diagnostics")] +fn dropped() { + if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { + last.push_str(" DROPPED"); + } +} + +/// Dispatches run on the host so far. +static DISPATCHED: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn dispatched() -> u64 { + DISPATCHED.load(Ordering::Relaxed) +} + +/// The host address of a root view: its buffer's host copy, or for a +/// constant buffer not 256-byte aligned there (the console needs 16) a +/// copy in upload memory. +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB, +/// other views as 1 MiB (both cut at their buffer's end). +fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> { + let shadow = crate::shadow::find(address, 1)?; + let len = shadow + .left(address) + .min(if srv { 1 << 20 } else { 1 << 16 }); + let gpu = shadow.gpu(address); + if srv || gpu % 256 == 0 { + shadow.refresh(list, address, len); + return Some(gpu); + } + let (gpu, to) = list.scratch(len)?; + list.defer_fill(to, address as *const u8, len as usize); + Some(gpu) +} + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +fn set(roots: &mut Vec<Root>, slot: u32, root: Root) { + let slot = slot as usize; + if roots.len() <= slot { + roots.resize(slot + 1, Root::None); + } + roots[slot] = root; +} + +impl State { + pub(crate) fn reset(&mut self, pipeline: This) { + *self = State::default(); + self.pipeline = pipeline as usize; + } + + /// The title's topology; console-only ones become host lists (see + /// [`crate::primitive`]). + pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { + self.topology = topology; + let host = match topology { + RECTANGLES => 4, + TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { + once!(topology, "console topology drawn as a triangle list"); + 4 + } + t => t, + }; + // SAFETY: an open list. + unsafe { + list.list + .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32)) + }; + } + + pub(crate) fn set_pipeline(&mut self, pipeline: This) { + self.pipeline = pipeline as usize; + } + + pub(crate) fn set_heaps(&mut self, heaps: &[This]) { + self.heaps = [0; 2]; + for &h in heaps { + if !h.is_null() { + let samplers = crate::descriptor::heap(h).samplers(); + self.heaps[usize::from(samplers)] = h as usize; + } + } + } + + fn roots(&mut self, compute: bool) -> &mut Vec<Root> { + if compute { + &mut self.compute + } else { + &mut self.graphics + } + } + + pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) { + set(self.roots(compute), slot, Root::Table(handle)); + } + + pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) { + set(self.roots(compute), slot, Root::View(address)); + } + + pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) { + let roots = self.roots(compute); + let s = slot as usize; + if !matches!(roots.get(s), Some(Root::Constants(_))) { + set(roots, slot, Root::Constants(Vec::new())); + } + if let Root::Constants(c) = &mut roots[s] { + let end = offset as usize + values.len(); + if c.len() < end { + c.resize(end, 0); + } + c[offset as usize..end].copy_from_slice(values); + } + } + + pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) { + for (i, v) in views.iter().enumerate() { + if let Some(slot) = self.vertex.get_mut(start as usize + i) { + *slot = *v; + } + } + } + + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { + self.index = view.copied().unwrap_or_default(); + } + + /// Render targets and depth, set on the host list at once. + pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { + let Some(host) = crate::host::host() else { + return; + }; + self.targets.clear(); + let mut rtvs = Vec::new(); + for &h in handles { + let Some(record) = crate::descriptor::rtv_record(h) else { + once!( + handle = format_args!("{h:#x}"), + "render target without a recorded view" + ); + continue; + }; + let Some(texture) = crate::resource::host_resource(record.resource) else { + continue; + }; + self.targets.push(record.resource as usize); + #[cfg(feature = "diagnostics")] + crate::capture::note_target(record.resource); + rtvs.push(host.rtv(texture, record.desc().as_ref())); + } + self.depth = 0; + let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { + let texture = crate::resource::host_resource(record.resource)?; + self.depth = record.resource as usize; + #[cfg(feature = "diagnostics")] + crate::capture::note_target(record.resource); + Some(host.dsv(texture, record.depth_desc().as_ref())) + }); + // SAFETY: an open list; the views were just made. + unsafe { + list.list.OMSetRenderTargets( + rtvs.len() as u32, + (!rtvs.is_empty()).then_some(rtvs.as_ptr()), + false, + dsv.as_ref().map(std::ptr::from_ref), + ) + }; + } + + /// The user-data value of a root argument, as translated shaders read + /// it: a table's byte offset in its heap, a constant's value. + fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { + match (self.roots_ref(compute).get(usize::from(slot)), root) { + (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { + Some(heap) => (handle - heap.start) as u32, + None => { + once!( + handle = format_args!("{handle:#x}"), + "descriptor table outside the bound heaps" + ); + 0 + } + }, + (Some(Root::Constants(c)), RootType::Constants) => { + c.get(dword as usize).copied().unwrap_or(0) + } + _ => { + once!( + slot, + ?root, + "a shader reads a root argument the title did not set" + ); + 0 + } + } + } + + /// The bound heap holding `handle`. + fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { + self.heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| h.index(handle).is_some()) + } + + /// Brings the host list up to date for a draw; false if the draw cannot + /// run on the host. + fn prepare(&mut self, list: &HostList, indexed: bool) -> bool { + self.prepare_for(list, indexed, false) + } + + /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches. + fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + if p.compute || p.mesh != mesh { + once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); + return false; + } + self.bind(list, p, false); + let l = &list.list; + // Vertex buffers the input layout reads. + let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; + let mut count = 0; + for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() { + if p.slots & 1 << slot == 0 { + continue; + } + count = slot + 1; + if v.address == 0 || v.size == 0 { + continue; + } + let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + continue; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + *view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + StrideInBytes: v.stride, + }; + } + // SAFETY: an open list; the views name live host buffers. + unsafe { + if count > 0 { + l.IASetVertexBuffers(0, Some(&views[..count])); + } + } + if indexed { + let v = self.index; + let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else { + return false; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + Format: DXGI_FORMAT(v.format as i32), + }; + // SAFETY: an open list; the view names a live host buffer. + unsafe { l.IASetIndexBuffer(Some(&view)) }; + } + const RENDER_TARGET: u32 = 0x4; + const DEPTH_WRITE: u32 = 0x10; + for &t in &self.targets { + crate::list::ensure_state(list, t as This, RENDER_TARGET); + } + if self.depth != 0 { + crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE); + } + true + } + + /// A descriptor a shader reads through a table: its host slot made if + /// it changed, constant data copied, textures made readable. + /// What draws and dispatches share: heaps, our root signature, the + /// pipeline, and per stage the user data, root views and the + /// descriptors its tables hold. + fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) { + let l = &list.list; + // Heaps first: a root signature with directly indexed heaps must be + // set after them. + if self.host_heaps != self.heaps { + let heaps: Vec<Option<ID3D12DescriptorHeap>> = self + .heaps + .iter() + .filter(|&&h| h != 0) + .filter_map(|&h| crate::descriptor::heap(h as This).host()) + .map(|h| Some(h.heap.clone())) + .collect(); + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + self.host_heaps = self.heaps; + self.host_roots = [0; 2]; + } + let root = p.root.as_raw() as usize; + if self.host_roots[usize::from(compute)] != root { + // SAFETY: an open list and a live root signature. + unsafe { + if compute { + l.SetComputeRootSignature(&p.root); + } else { + l.SetGraphicsRootSignature(&p.root); + } + } + self.host_roots[usize::from(compute)] = root; + } + if self.host_pipeline != self.pipeline { + // SAFETY: an open list and a live pipeline. + unsafe { l.SetPipelineState(&p.pso) }; + self.host_pipeline = self.pipeline; + list.used_pipeline(&p.name); + } + for stage in &p.stages { + let t = stage.translated(); + let made = self.tables(list, &t.used, compute); + if let Some((param, dwords)) = stage.user_data { + let mut values = vec![0u32; dwords as usize]; + for u in &t.host.user_data { + let fresh = made + .iter() + .find(|m| m.0 == u.slot && u.root == RootType::Table); + values[u.index as usize] = match fresh { + Some(&(_, offset)) => offset, + None => self.user_value(compute, u.slot, u.root, u.dword), + }; + } + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } else { + l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } + } + } + for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { + for &(slot, param) in views { + let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + else { + once!(slot, "a shader reads a root view the title did not set"); + continue; + }; + let Some(gpu) = root_view(list, *address, srv) else { + continue; + }; + // SAFETY: an open list; the address is in live memory. + unsafe { + match (compute, srv) { + (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), + (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), + (true, false) => l.SetComputeRootConstantBufferView(param, gpu), + (true, true) => l.SetComputeRootShaderResourceView(param, gpu), + } + } + } + } + } + } + + /// Runs a dispatch on the host. + pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + once!( + pipeline = format_args!("{:#x}", self.pipeline), + "a dispatch without a host pipeline dropped" + ); + return; + }; + if !p.compute { + once!("a dispatch with a graphics pipeline"); + return; + } + self.bind(list, p, true); + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); + // SAFETY: an open list with everything set. + unsafe { list.list.Dispatch(x, y, z) }; + DISPATCHED.fetch_add(1, Ordering::Relaxed); + } + + /// What a draw or dispatch runs, for the device-removed report + /// (diagnostics): the pipeline, then per stage the user data it gets + /// (with the view at that heap index, if one is), the host addresses + /// of its root views and the views its tables name. + #[cfg(feature = "diagnostics")] + fn op_text(&self, kind: String, compute: bool) -> String { + use std::fmt::Write; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return kind; + }; + let mut text = format!("{kind} {}", p.name); + let views = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten(); + for stage in &p.stages { + let t = stage.translated(); + let _ = write!(text, " | {}:", stage.shader.hash); + for u in &t.host.user_data { + let v = self.user_value(compute, u.slot, u.root, u.dword); + let _ = write!(text, " u{}={v:#x}", u.index); + let index = if u.root == RootType::Table { v / 32 } else { v }; + if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { + let _ = write!(text, " [heap {index}: {slot}]"); + } + } + for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) { + if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { + let host = crate::shadow::find(*address, 1) + .map(|s| (s.gpu(*address), s.left(*address))); + let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); + } + } + } + let _ = write!(text, " tables {:?}", self.reads(compute)); + text + } + + /// Runs a mesh dispatch of `x` groups on the host (the title's mesh + /// programs are one-dimensional). + pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + #[cfg(feature = "diagnostics")] + self.trace("mesh", x, 0); + let ran = self.prepare_for(list, false, true) + && match list.list.cast::<ID3D12GraphicsCommandList6>() { + Ok(l6) => { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("mesh {x}"), false)); + // SAFETY: an open list with everything set. + unsafe { l6.DispatchMesh(x, 1, 1) }; + DRAWN.fetch_add(1, Ordering::Relaxed); + true + } + Err(_) => false, + }; + #[cfg(feature = "diagnostics")] + if !ran { + dropped(); + } + #[cfg(not(feature = "diagnostics"))] + let _ = ran; + } + + fn roots_ref(&self, compute: bool) -> &Vec<Root> { + if compute { + &self.compute + } else { + &self.graphics + } + } + + fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) { + let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + return; + }; + let handle = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(handle) else { + return; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { + return; + }; + if let Some(view) = host.mirror(index, handle, true) { + readable(list, u, &view); + } + } + + /// The descriptors a shader reads through tables. Tables holding a + /// constant buffer are made afresh for the draw in dynamic slots, with + /// the constant data copied to upload memory when the list is + /// submitted: the host wants constant buffers 256-byte aligned, the + /// console only 16. Returns those tables' new byte offsets by root + /// parameter; the other tables' slots are made from the title's. + /// + /// Within a list, the same table holding the same descriptors is made + /// once: its constant data is copied at submission either way, and the + /// big tables the world binds would otherwise take hundreds of slots per + /// draw, wrapping the dynamic slots onto lists not yet submitted. + fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> { + let tables = |u: &&UsedResource| u.root == RootType::Table; + let mut fresh: Vec<u8> = used + .iter() + .filter(tables) + .filter(|u| u.kind == ResourceType::Cbv) + .map(|u| u.slot) + .collect(); + fresh.sort_unstable(); + fresh.dedup(); + for u in used.iter().filter(tables) { + if !fresh.contains(&u.slot) { + self.table_entry(list, u, compute); + } + } + let mut made = Vec::new(); + for slot in fresh { + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { + continue; + }; + let entries: Vec<&UsedResource> = used + .iter() + .filter(tables) + .filter(|u| u.slot == slot) + .collect(); + let Some(heap) = self.heap_of(table) else { + continue; + }; + let Some(host) = heap.host() else { + continue; + }; + let n = entries + .iter() + .map(|u| u.table_offset_dwords / 8 + 1) + .max() + .unwrap_or(1); + // The table and what its entries hold (record words). + let key = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for k in 0..n { + let at = table + u64::from(k) * 32; + // SAFETY: a descriptor slot in title memory. + unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + } + (table, h.finish()) + }; + if let Some(&first) = self.fresh_tables.get(&key) { + for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { + let handle = table + u64::from(u.table_offset_dwords) * 4; + if let Some(view) = crate::descriptor::view(handle) { + readable(list, u, &view); + } + } + made.push((slot, first * 32)); + continue; + } + let Some(first) = host.dynamic(n) else { + continue; + }; + self.fresh_tables.insert(key, first); + self.dynamic + .push((std::ptr::from_ref(heap) as usize, first, n)); + // The whole range: a shader may index past the entries its + // used-resource list names (descriptor arrays). + for k in 0..n { + let index = first + k; + let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); + match crate::descriptor::view(table + u64::from(k) * 32) { + Some(View::Constant(address, size)) => { + let Some((gpu, to)) = list.scratch(u64::from(size)) else { + host.make_null(index); + continue; + }; + list.defer_fill(to, address as *const u8, size as usize); + host.constant_at(index, gpu, size); + } + Some(view) => { + host.make_at(index, &view); + if let Some(u) = used { + readable(list, u, &view); + } + } + None => { + host.make_null(index); + if used.is_some() { + once!(slot, "a table entry without a view"); + } + } + } + } + made.push((slot, first * 32)); + } + made + } + + /// The first draws, at debug level: what they bind and read + /// (diagnostics builds). + #[cfg(feature = "diagnostics")] + fn trace(&self, kind: &str, count: u32, first: u32) { + static TRACED: AtomicU64 = AtomicU64::new(0); + if !tracing::enabled!(tracing::Level::DEBUG) { + return; + } + let listed = crate::capture::listed(crate::queue::presented() + 1); + let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64; + let targets: Vec<String> = self + .targets + .iter() + .filter_map(|&t| crate::resource::host_resource(t as This)) + .map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + format!("{}x{} f{}", d.Width, d.Height, d.Format.0) + }) + .collect(); + let v = self.vertex[0]; + let line = format!( + "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}", + self.topology, + self.pipeline, + v.address, + v.size, + v.stride, + self.reads(false) + ); + if logged { + tracing::debug!("draw {line}"); + } + let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if frame.len() < 256 { + frame.push(line); + } + } + + /// What a draw's shaders read, one line per used resource (diagnostics + /// builds). + #[cfg(feature = "diagnostics")] + fn reads(&self, compute: bool) -> Vec<String> { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return vec!["no host pipeline".into()]; + }; + let mut out = Vec::new(); + for stage in &p.stages { + let t = stage.translated(); + for u in &t.used { + let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) { + (RootType::Table, Some(Root::Table(table))) => { + let handle = table + u64::from(u.table_offset_dwords) * 4; + describe(crate::descriptor::view(handle).as_ref()) + } + (root, _) => format!("{root:?}"), + }; + out.push(format!( + "{} {:?} s{}+{}: {what}", + stage.shader.hash, u.kind, u.slot, u.table_offset_dwords + )); + } + } + out + } + + pub(crate) fn draw( + &mut self, + list: &HostList, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + #[cfg(feature = "diagnostics")] + self.trace("draw", vertices, first); + let rects = self.topology == RECTANGLES; + let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first)); + if ran { + // Rectangles were expanded into their own vertex buffers. + let (count, from) = if rects { + (vertices / 3 * 6, 0) + } else { + (vertices, first) + }; + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawInstanced(count, instances, from, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + #[cfg(feature = "diagnostics")] + if !ran { + dropped(); + } + } + + /// Binds vertex buffers holding the rectangles of vertices `first..first + /// + count` as triangles, made when the list is submitted. + fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + let rects = u64::from(count / 3); + for slot in 0..32 { + let elements: Vec<(u32, u32)> = p + .inputs + .iter() + .filter(|e| e.slot == slot && !e.per_instance) + .map(|e| (e.offset, e.format)) + .collect(); + if elements.is_empty() { + continue; + } + let v = self.vertex[slot as usize]; + let stride = u64::from(v.stride); + let from = v.address + u64::from(first) * stride; + if v.address == 0 + || stride == 0 + || u64::from(first + count) * stride > u64::from(v.size) + || crate::shadow::find(from, rects * 3 * stride).is_none() + { + once!(slot, "rectangle vertices outside their buffer"); + return false; + } + let Some((gpu, to)) = list.scratch(rects * 6 * stride) else { + return false; + }; + let (from, to, stride) = (from as usize, to as usize, stride as usize); + let n = rects as usize; + list.defer_host(move || { + // SAFETY: the vertices lie in a title buffer (checked when + // recorded) and the scratch memory is the list's. + let (src, dst) = unsafe { + ( + std::slice::from_raw_parts(from as *const u8, n * 3 * stride), + std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride), + ) + }; + crate::primitive::expand_rects(src, dst, stride, &elements); + }); + let view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: (rects * 6 * stride as u64) as u32, + StrideInBytes: v.stride, + }; + // SAFETY: an open list; the view names live scratch memory. + unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) }; + } + true + } + + pub(crate) fn draw_indexed( + &mut self, + list: &HostList, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + #[cfg(feature = "diagnostics")] + self.trace("indexed", indices, first); + if self.topology == RECTANGLES { + once!("indexed rectangles not drawn"); + } + let ran = self.topology != RECTANGLES && self.prepare(list, true); + if ran { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawIndexedInstanced(indices, instances, first, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + #[cfg(feature = "diagnostics")] + if !ran { + dropped(); + } + } +} + +/// Gets what a shader reads or writes through a view ready: buffer data +/// copied, textures moved to the state they need. +fn readable(list: &HostList, u: &UsedResource, view: &View) { + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + const UNORDERED_ACCESS: u32 = 0x8; + let placed = crate::descriptor::host::placed_texture(view); + let view = placed.as_ref().unwrap_or(view); + // Buffer views read title memory: their range is copied at submission; + // what shaders write through unordered access goes back to it after. + if let Some((address, len)) = crate::descriptor::host::buffer_range(view) + && len > 0 + && let Some(shadow) = crate::shadow::find(address, len) + { + shadow.refresh(list, address, len); + if u.kind == ResourceType::Uav { + shadow.gpu_writes(list, address, len); + } + } + match (view, u.kind) { + (View::Shader(resource, _), ResourceType::Srv) => { + if let Some(t) = crate::resource::host_resource(*resource as This) + && crate::texture::title_written(t) + { + crate::texture::upload(list, *resource as This, t); + } + crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE); + #[cfg(feature = "diagnostics")] + if let Some(t) = crate::resource::host_resource(*resource as This) { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + if d.Flags.0 & 7 == 0 { + tracing::debug!( + resource = format_args!("{resource:#x}"), + ?d, + "a shader reads a texture the title fills" + ); + } + } + } + (View::Unordered(resource, _, _), ResourceType::Uav) => { + #[cfg(feature = "diagnostics")] + crate::capture::note_target(*resource as This); + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } + _ => {} + } +} + +/// A view in a few words (diagnostics builds). +#[cfg(feature = "diagnostics")] +fn describe(view: Option<&View>) -> String { + let texture = |r: This| { + crate::resource::host_resource(r).map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0) + }) + }; + match view { + None => "no view".into(), + Some(v @ View::Shader(r, _)) => texture(*r as This) + .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), + Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)), + Some(View::Placed(u, r, d)) => format!( + "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", + r[0], + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[11], + u64::from(d[10]) | u64::from(d[11]) << 32 + ), + // The first four values, as a colour rectangle's constants are. + Some(View::Constant(address, size)) + if *size >= 16 && crate::texture::committed(*address as *const u8, 16) => + { + // SAFETY: 16 committed bytes of title memory. + let v = unsafe { (*address as *const [f32; 4]).read_unaligned() }; + format!("Constant({address:#x}, {size}) {v:?}") + } + Some(v) => format!("{v:?}").chars().take(60).collect(), + } +} + +/// The console's own primitive topologies. +const TRIANGLE_FAN: u32 = 6; +const RECTANGLES: u32 = 17; +const LINE_LOOP: u32 = 18; +const QUADS: u32 = 19; +const QUAD_STRIP: u32 = 20; + +/// Fixed-function state, straight onto the host list. +pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetViewports(viewports) }; +} + +pub(crate) fn scissors(list: &HostList, rects: &[RECT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetScissorRects(rects) }; +} + +pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { + // SAFETY: an open list. + unsafe { list.list.OMSetBlendFactor(factor) }; +} + +pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + // SAFETY: an open list. + unsafe { list.list.OMSetStencilRef(reference) }; +} diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index 61ad2a5..1ce11c7 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -4,8 +4,8 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use crate::object::{ - self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, NOT_FOUND, OUTPUT, Object, - S_OK, Table, This, guid, + self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, MORE_DATA, NOT_FOUND, OUTPUT, + Object, S_OK, Table, This, guid, }; /// The DXGI device interfaces, base first (as on PC). @@ -132,7 +132,6 @@ struct AdapterDescription { const _: () = assert!(size_of::<AdapterDescription>() == 0x130); const AMD: u32 = 0x1002; -const GIB: usize = 1 << 30; extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT { if out.is_null() { @@ -142,17 +141,18 @@ extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) { *slot = unit; } - // shortcut: memory sizes are the Series X game split (10 GiB fast, - // 3.5 GiB standard), not measured; revisit once memory is emulated. + // shortcut: memory sizes are the title's split (GPU-optimal, standard), + // not measured; revisit once memory is emulated. + let (gpu_optimal, standard) = crate::console::current().title_memory(); let description = AdapterDescription { name, vendor: AMD, device: 0, subsystem: 0, revision: 0, - dedicated_video_memory: 10 * GIB, + dedicated_video_memory: gpu_optimal, dedicated_system_memory: 0, - shared_system_memory: 7 * GIB / 2, + shared_system_memory: standard, luid: [1, 0], }; // SAFETY: checked non-null; the title passes room for the description. @@ -178,8 +178,8 @@ extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HR } /// IUnknown 3, object 4, device 5 + 2 + 3. -static DEVICE_FUNCTIONS: Table<17> = { - let mut f = object::missing_table::<DXGI_DEVICE, 17>(); +static DEVICE_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<DXGI_DEVICE, 32>(); f[0] = device_query as *const (); f[6] = device_parent as *const (); // 0x30 f[7] = device_adapter as *const (); // 0x38 @@ -187,8 +187,8 @@ static DEVICE_FUNCTIONS: Table<17> = { }; /// IUnknown 3, object 4, adapter 3 + 1 + 1. -static ADAPTER_FUNCTIONS: Table<12> = { - let mut f = object::missing_table::<ADAPTER, 12>(); +static ADAPTER_FUNCTIONS: Table<24> = { + let mut f = object::missing_table::<ADAPTER, 24>(); f[0] = adapter_query as *const (); f[6] = adapter_parent as *const (); // 0x30 f[7] = adapter_outputs as *const (); // 0x38 @@ -197,19 +197,71 @@ static ADAPTER_FUNCTIONS: Table<12> = { }; /// IUnknown 3, object 4, factory 5 + 2 + 11. -static FACTORY_FUNCTIONS: Table<25> = { - let mut f = object::missing_table::<FACTORY, 25>(); +static FACTORY_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<FACTORY, 32>(); f[0] = factory_query as *const (); f[7] = factory_adapters as *const (); // 0x38 f[12] = factory_adapters as *const (); // 0x60, the same for version 1 Table(f) }; +/// A display mode as the console lists it: size, refresh rate (numerator, +/// denominator), format, scanline order, scaling, flags. +#[repr(C)] +struct Mode { + width: u32, + height: u32, + refresh: [u32; 2], + format: u32, + scanlines: u32, + scaling: u32, + flags: u32, +} +const _: () = assert!(size_of::<Mode>() == 32); + +/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks +/// for a 120 Hz one to allow 120 Hz frame intervals). +/// shortcut: fixed mode, not the host display's; report the host's rates if +/// a title paces by them. +extern "system" fn modes( + _: This, + _format: u32, + _flags: u32, + count: *mut u32, + out: *mut Mode, +) -> HRESULT { + // SAFETY: the title passes its count (null is tolerated). + let Some(count) = (unsafe { count.as_mut() }) else { + return E_INVALIDARG; + }; + if out.is_null() { + *count = 1; + return S_OK; + } + if *count < 1 { + return MORE_DATA; + } + *count = 1; + let mode = Mode { + width: 3840, + height: 2160, + refresh: [60, 1], + format: 0, + scanlines: 1, // progressive + scaling: 0, + flags: 0, + }; + // SAFETY: checked non-null; room for `count` >= 1 modes. + unsafe { out.write(mode) }; + S_OK +} + /// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones). -static OUTPUT_FUNCTIONS: Table<22> = { - let mut f = object::missing_table::<OUTPUT, 22>(); +static OUTPUT_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::<OUTPUT, 32>(); f[0] = output_query as *const (); f[6] = output_parent as *const (); // 0x30 + f[21] = modes as *const (); // 0xa8 Table(f) }; diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 11c692b..285e7bd 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -24,7 +24,10 @@ pub(crate) const FENCE_IIDS: [Iid; 4] = [ #[repr(C)] struct Fence { object: Object, + /// Titles also read it straight from memory, at the fence's GPU + /// address. value: AtomicU64, + flags: u32, /// Events to set once the value reaches theirs (handles as integers). waiters: Mutex<Vec<(u64, usize)>>, } @@ -45,6 +48,7 @@ pub(crate) extern "system" fn create( let fence = Box::new(Fence { object: Object::new(&FUNCTIONS), value: AtomicU64::new(initial), + flags, waiters: Mutex::new(Vec::new()), }); object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) @@ -106,15 +110,26 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { S_OK } -/// IUnknown 3, object 4, device child 1, fence 3. -static FUNCTIONS: Table<11> = { - let mut f = object::d3d12_object(object::missing_table::<FENCE, 11>()); +extern "system" fn creation_flags(this: This) -> u32 { + fence(this).flags +} +/// Where the value lives (GPU addresses are CPU addresses). +extern "system" fn gpu_address(this: This) -> u64 { + (&raw const fence(this).value) as u64 +} + +/// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console +/// one among them). +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<FENCE, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 f[8] = completed as *const (); // 0x40 f[9] = set_event_on_completion as *const (); // 0x48 f[10] = signal as *const (); // 0x50 + f[11] = creation_flags as *const (); // 0x58 + f[12] = gpu_address as *const (); // 0x60 Table(f) }; @@ -147,6 +162,10 @@ mod tests { // SAFETY: as above. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); + // Grand Theft Auto VI reads the value at the fence's address. + let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f); + // SAFETY: the fence's value. + assert_eq!(unsafe { *(at as *const u64) }, 5); // SAFETY: ours. unsafe { CloseHandle(event) }; assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0); diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs index 842b894..837dfbc 100644 --- a/crates/victory-gpu/src/frame.rs +++ b/crates/victory-gpu/src/frame.rs @@ -1,25 +1,35 @@ //! Frame pacing: the title sets a frame interval and waits for each frame //! to begin. Ours is a clock started by the first interval set, ticking -//! once per interval; the token is the frame number. +//! once per interval; the token is the frame number. Each event kind +//! (origin, vblank, flip) happens once per tick, so two waits for the same +//! kind never end on the same tick: Grand Theft Auto VI polls the origin +//! with "token on time-out" (starting its next frame at once) and is paced +//! by a blocking wait for the flip before each present. //! -//! shortcut: event offsets and display events are not told apart (all -//! waits end on the next tick); tie the clock to presentation once frames -//! reach the screen. +//! shortcut: event offsets are ignored (every event is at the tick); tie +//! the clock to presentation if a title paces by them. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; -use crate::object::{HRESULT, S_OK, This}; +use crate::object::{HRESULT, S_FALSE, S_OK, This}; -/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. -const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32; +/// What a wait returns when its time is up first. +const TIMEOUT: HRESULT = S_FALSE; +/// The frame-origin event: the one that starts frames and makes tokens. +const ORIGIN: u32 = 0; +/// Make the frame's token even if the wait times out (the title starts the +/// frame early). +const TOKEN_ON_TIMEOUT: u32 = 2; const SIXTIETH: Duration = Duration::from_micros(16_667); struct Clock { start: Instant, interval: Duration, + /// The tick number at `start` (ticks go on across interval changes). + first: u64, } static CLOCK: Mutex<Option<Clock>> = Mutex::new(None); @@ -29,29 +39,32 @@ fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> { CLOCK.lock().unwrap_or_else(|e| e.into_inner()) } -/// Device method: `periods` intervals of `length` microseconds per frame. +/// Device method: a frame every `length` microseconds. The period is how +/// many intervals a frame may take to reach the display (pipeline depth), +/// not part of the rate. pub(crate) extern "system" fn set_interval( _: This, _output: This, length: u32, - periods: u32, + _period: u32, _flags: u32, ) -> HRESULT { - let interval = match u64::from(length) * u64::from(periods.max(1)) { + let interval = match length { 0 => SIXTIETH, - us => Duration::from_micros(us), + us => Duration::from_micros(u64::from(us)), }; tracing::info!(?interval, "frame interval"); - let mut clock = clock(); - match clock.as_mut() { - Some(c) => c.interval = interval, - None => { - *clock = Some(Clock { - start: Instant::now(), - interval, - }) - } - } + // A new interval starts from now, after the last tick handed out. + let first = LAST + .iter() + .map(|t| t.load(Ordering::Relaxed)) + .max() + .unwrap_or(0); + *clock() = Some(Clock { + start: Instant::now(), + interval, + first, + }); S_OK } @@ -66,42 +79,84 @@ pub(crate) extern "system" fn schedule( S_OK } -/// How long until the next tick. -fn until_next_tick() -> Duration { +/// Frames begun so far (frame waits that ended). +pub(crate) fn current() -> u64 { + FRAME.load(Ordering::Relaxed) +} + +/// Per event kind (origin, vblank, flip and later kinds): the last tick a +/// wait for it ended on. +static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +fn last(kind: u32) -> &'static AtomicU64 { + &LAST[(kind as usize).min(LAST.len() - 1)] +} + +/// The next tick after now and after the last one a wait for `kind` ended +/// on (an event happens once per tick: a wait woken a little early must not +/// let the next one end on the same tick), and how long until it. +fn next_tick(kind: u32) -> (u64, Duration) { let mut clock = clock(); let c = clock.get_or_insert_with(|| Clock { start: Instant::now(), interval: SIXTIETH, + first: 0, }); let elapsed = c.start.elapsed().as_nanos(); let interval = c.interval.as_nanos().max(1); - let next = (elapsed / interval + 1) * interval; - Duration::from_nanos((next - elapsed) as u64) + let tick = + (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + let at = u128::from(tick - c.first) * interval; + ( + tick, + Duration::from_nanos(at.saturating_sub(elapsed) as u64), + ) } -/// Device method: blocks until the next tick, then hands out the frame's -/// token. +/// Device method: blocks until the next tick (or the time-out); an origin +/// wait then hands out the new frame's token. Other events keep the token +/// the title passes. Ticks are absolute (start plus whole intervals), so +/// lateness never accumulates. pub(crate) extern "system" fn wait( _: This, - _kind: u32, + kind: u32, timeout_ms: u32, _list: *const u8, - _flags: u32, + flags: u32, token: *mut u64, ) -> HRESULT { - let wait = until_next_tick(); + let origin = kind == ORIGIN; + let (tick, wait) = next_tick(kind); let limit = Duration::from_millis(u64::from(timeout_ms)); - if wait > limit { + let hr = if wait > limit { std::thread::sleep(limit); - return TIMEOUT; + TIMEOUT + } else { + std::thread::sleep(wait); + last(kind).fetch_max(tick, Ordering::Relaxed); + S_OK + }; + // A frame begun on a time-out takes no tick: its flip still does. + if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { + // Tokens count frames (consecutive), not ticks. + let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; + if !token.is_null() { + // SAFETY: checked non-null; the title passes its token. + unsafe { token.write(frame) }; + } } - std::thread::sleep(wait); - let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; - if !token.is_null() { - // SAFETY: checked non-null; the title passes its token. - unsafe { token.write(frame) }; - } - S_OK + #[cfg(feature = "diagnostics")] + tracing::debug!( + kind, + timeout_ms, + flags, + hr, + tick, + wait_us = wait.as_micros() as u64, + frame = current(), + "frame wait" + ); + hr } /// Device method: no statistics are kept, so none are returned. @@ -135,5 +190,37 @@ mod tests { assert!(second > first); assert!(before.elapsed() <= Duration::from_millis(50)); assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); + // Tokens count frames, a frame started early on a time-out too. + let mut early = 0; + let flags = TOKEN_ON_TIMEOUT; + assert_eq!( + wait(null, 0, 0, std::ptr::null(), flags, &mut early), + TIMEOUT + ); + let mut next = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK); + assert!(early == second + 1 && next == early + 1); + assert!(LAST[0].load(Ordering::Relaxed) >= 2); + + // The title's loop (the clock is global, so in the same test): an + // origin poll that times out (and starts the frame), then a + // blocking flip wait. Each flip takes its own tick. + const FLIP: u32 = 2; + assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + let mut token = 0; + let flips: Vec<u64> = (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect(); + assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); + // Even when a flip wait begins on the tick another just ended on. + let (tick, _) = next_tick(FLIP); + assert!(tick > flips[3]); } } diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index a130169..476ce4d 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -44,7 +44,12 @@ pub(crate) struct Host { event: HANDLE, rtvs: ID3D12DescriptorHeap, rtv_size: u32, - /// With `VICTORY_D3D12_DEBUG` set: the debug layer's messages. + /// A ring of depth views, used as `rtvs`. + dsvs: ID3D12DescriptorHeap, + dsv_size: u32, + next_dsv: AtomicU32, + /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug + /// layer's messages. messages: Option<ID3D12InfoQueue>, next_rtv: AtomicU32, presenter: Mutex<Option<Presenter>>, @@ -56,6 +61,56 @@ unsafe impl Send for Host {} // SAFETY: as above. unsafe impl Sync for Host {} +/// Time spent in submissions since the last frame-rate line, in +/// microseconds: preparing them on the CPU (title memory copies, texture +/// detiling), then waiting for the GPU. +static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// Of the preparing: title memory copies (microseconds, bytes) and texture +/// refreshes (microseconds, bytes hashed), since the last frame-rate line. +pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; + +/// What the runtime does when the host GPU fails for good: report it like a +/// crash and end the run. The console has no such state, and carrying on +/// draws nothing at seconds per frame. +static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new(); + +/// Sets what a host GPU failure does (the runtime's crash report). +pub fn on_failure(report: fn(&str) -> !) { + let _ = ON_FAILURE.set(report); +} + +/// Ends the run on a host GPU failure: what failed, the removal reason and +/// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a +/// diagnostics build names the command). +pub(crate) fn fail(what: std::fmt::Arguments) -> ! { + let mut text = what.to_string(); + if let Some(host) = host() { + // SAFETY: a plain query. + if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { + text.push_str(&format!("; device removed: {e}")); + } + match host.log_messages() { + Some(first) => text.push_str(&format!("; debug layer: {first}")), + None if host.messages.is_none() => text.push_str( + "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command", + ), + None => {} + } + } + tracing::error!("{text}"); + match ON_FAILURE.get() { + Some(report) => report(&text), + None => std::process::abort(), + } +} + /// The host GPU, created on first use; `None` without one (a run then /// behaves as before: nothing executes). pub(crate) fn host() -> Option<&'static Host> { @@ -73,7 +128,9 @@ pub(crate) fn host() -> Option<&'static Host> { fn create() -> windows::core::Result<Host> { // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { - let debug = std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); + // The debug layer only in builds with diagnostics. + let debug = + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); if debug { let mut layer: Option<ID3D12Debug> = None; match D3D12GetDebugInterface(&mut layer) { @@ -81,8 +138,29 @@ fn create() -> windows::core::Result<Host> { Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), } } + // Diagnostics: device-removed data (the command that faulted, the + // faulting address), read when the device is removed. + if dred_on() { + let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None; + if D3D12GetDebugInterface(&mut dred).is_ok() + && let Some(dred) = dred + { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + } let mut device: Option<ID3D12Device> = None; - D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + // Diagnostics: the software adapter, on which a shader's wild access + // is an access violation in this process (a crash report with the + // address and instruction) instead of a GPU fault and driver reset. + if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; + tracing::info!("host device on the software adapter (WARP)"); + } else { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + } let device = device.ok_or_else(windows::core::Error::empty)?; let messages = debug .then(|| device.cast::<ID3D12InfoQueue>().ok()) @@ -100,6 +178,13 @@ fn create() -> windows::core::Result<Host> { ..Default::default() })?; let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + let dsvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); tracing::info!("host D3D12 device ready"); Ok(Host { device, @@ -109,6 +194,9 @@ fn create() -> windows::core::Result<Host> { event, rtvs, rtv_size, + dsvs, + dsv_size, + next_dsv: AtomicU32::new(0), messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), @@ -122,21 +210,131 @@ pub(crate) struct HostList { pub(crate) list: ID3D12GraphicsCommandList, /// Work for submission time, in recorded order. deferred: Mutex<Deferred>, - /// Set when closing failed: the list must not run until reset. - broken: std::sync::atomic::AtomicBool, + /// Upload memory for data the list's draws make (expanded vertices), + /// reused after a reset. + scratch: Mutex<Scratch>, + /// Host texture states the list assumes, by title resource: at its + /// start and at its end. Lists are recorded on many threads and run in + /// submission order, so the transitions from a texture's real state are + /// made at submission, in `prelude`. + states: Mutex<std::collections::HashMap<usize, (u32, u32)>>, + /// The list that runs those transitions just before this one. + prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), + /// The pipelines the list binds, for reports of slow submissions. + pipelines: Mutex<std::collections::BTreeSet<String>>, + /// The texts of the markers `note_op` set, in order (for device-removed + /// data without marker texts). + #[cfg(feature = "diagnostics")] + notes: Mutex<Vec<String>>, +} + +/// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics +/// builds). +pub(crate) fn dred_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() + }) +} + +/// Names a host object for the device-removed report, which names the +/// allocations a page fault hit (only with device-removed data on). +pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { + if dred_on() + && let Ok(object) = object.cast::<ID3D12Object>() + { + // SAFETY: a plain call on a live object. + let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; + } +} + +/// Upload chunks handed out front to back: the chunks, the one in use and +/// the bytes used in it. +#[derive(Default)] +struct Scratch { + chunks: Vec<(ID3D12Resource, usize, u64)>, + current: usize, + used: u64, +} + +// SAFETY: the chunk pointers are persistent mappings of upload buffers. +unsafe impl Send for Scratch {} + +const SCRATCH_CHUNK: u64 = 4 << 20; + +/// One piece of submission-time work, in recorded order. +enum Step { + /// A copy into title memory (destination, source, bytes): the title's + /// buffer copies, which later refreshes must see. + Copy(usize, usize, usize), + /// A copy of title memory into the list's own upload memory. + Fill(usize, usize, usize), + /// Brings a range (address, bytes) of a buffer's host copy up to date: + /// once per submission, whichever lists ask, until a `Copy` or `Run` + /// intervenes. + Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize), + /// Work that may write title memory. + Run(Box<dyn Fn() + Send>), + /// Work that writes host memory only. + Host(Box<dyn Fn() + Send>), + /// Shaders write a range (address, bytes) of a buffer's host copy. + GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize), } /// What a list does on the CPU when it is submitted: copies between host -/// memory regions (title buffers and upload buffers), and the upload -/// buffers its GPU copies read, kept until the list is reset. +/// memory regions (title buffers, upload buffers and buffer copies), and +/// the upload buffers its GPU commands read, kept until the list is reset. #[derive(Default)] struct Deferred { /// Destination, source, bytes. - copies: Vec<(usize, usize, usize)>, + copies: Vec<Step>, uploads: Vec<ID3D12Resource>, + /// Buffer ranges refreshed since the last title copy (host copy, + /// address, bytes): refreshing them again would find the same bytes. + refreshed: std::collections::HashSet<(usize, usize, usize)>, + /// Textures whose contents the list brings up to date. + textures: std::collections::HashSet<usize>, + /// Bottom-of-pipe writes, done once the list has run: address, what, + /// bytes. + writes: Vec<(usize, crate::queue::Written, usize)>, } impl Host { + /// Whether the host runs mesh shaders at shader model 6.6 (translated + /// mesh shaders need both); logged once. + pub(crate) fn mesh_shaders(&self) -> bool { + static MESH: OnceLock<bool> = OnceLock::new(); + *MESH.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: each query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && self + .device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + .is_ok() + }; + let mesh = ok + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + tracing::info!(mesh, "host mesh shader support"); + mesh + }) + } + /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> { // SAFETY: plain object creation. @@ -150,30 +348,48 @@ impl Host { &allocator, None, )?; + let prelude_allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &prelude_allocator, + None, + )?; + prelude.Close()?; Ok(HostList { allocator, list, deferred: Mutex::default(), - broken: Default::default(), + scratch: Mutex::default(), + states: Mutex::default(), + prelude: (prelude_allocator, prelude), + pipelines: Mutex::default(), + #[cfg(feature = "diagnostics")] + notes: Mutex::default(), }) } } /// Runs closed lists and waits for them. - pub(crate) fn execute(&self, lists: &[&HostList]) { - // A list that failed to close would remove the device. - let lists: Vec<&HostList> = lists - .iter() - .copied() - .filter(|l| !l.broken.load(Ordering::Relaxed)) - .collect(); - for list in &lists { - list.run_deferred(); + pub(crate) fn execute(&self, runs: &[&HostList]) { + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Submissions, 1); + let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len()); + let mut batch = Batch::default(); + for list in runs { + list.run_deferred(&mut batch); + if let Some(prelude) = list.prelude() { + lists.push(Some(prelude)); + } + lists.push(list.list.cast().ok()); } - let lists: Vec<Option<ID3D12CommandList>> = - lists.iter().map(|l| l.list.cast().ok()).collect(); + batch.flush(); let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); *submitted += 1; + let prepared = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. unsafe { self.queue.ExecuteCommandLists(&lists); @@ -188,14 +404,134 @@ impl Host { Err(e) => tracing::warn!(error = %e, "host submission not waited for"), } } + let gpu = prepared.elapsed(); + SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); + SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + // The host resets a device whose submission runs for about 2 s. + if gpu > std::time::Duration::from_millis(250) { + let pipelines: std::collections::BTreeSet<String> = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); + } + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + fail(format_args!( + "host GPU device removed after a submission of {} lists{}{}", + runs.len(), + self.removal_data(runs), + last_notes(runs) + )); + } + for list in runs { + let deferred = list.deferred(); + // Before the bottom-of-pipe writes, which tell the title the + // GPU is done. + for step in &deferred.copies { + if let Step::GpuWrite(shadow, address, len) = step { + shadow.copy_back(*address, *len); + } + } + for &(at, what, bytes) in &deferred.writes { + what.write(at as *mut u8, bytes); + } + } self.log_messages(); } - /// Moves the debug layer's messages into our log. - pub(crate) fn log_messages(&self) { - let Some(queue) = &self.messages else { - return; + /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations + /// it lies in (by the names we give them) or the title memory copy just + /// below it; for each list that did not finish, the command it stopped + /// at and what the draws and dispatches in flight there run (or, in + /// lists that never started, the pipelines they bind). + fn removal_data(&self, runs: &[&HostList]) -> String { + let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else { + return String::new(); }; + let mut text = String::new(); + // SAFETY: the outputs are the runtime's, valid while the device + // lives; nodes are walked as linked, histories have their counts. + unsafe { + if let Ok(fault) = dred.GetPageFaultAllocationOutput1() + && fault.PageFaultVA != 0 + { + let va = fault.PageFaultVA; + text.push_str(&format!("; page fault at {va:#x}")); + for (what, head) in [ + ("inside", fault.pHeadExistingAllocationNode), + ("inside freed", fault.pHeadRecentFreedAllocationNode), + ] { + let mut names = Vec::new(); + let mut node = head; + while let Some(n) = node.as_ref() + && names.len() < 8 + { + let name = if n.ObjectNameW.is_null() { + "unnamed".to_owned() + } else { + n.ObjectNameW.to_string().unwrap_or_default() + }; + names.push(format!("{name} (type {})", n.AllocationType.0)); + node = n.pNext; + } + if !names.is_empty() { + text.push_str(&format!("; {what} {names:?}")); + } + } + text.push_str(&crate::shadow::near(va)); + } + // The plain output: the extended one (with marker texts) came + // back without stopped lists on this host. + let Ok(crumbs) = dred.GetAutoBreadcrumbsOutput() else { + return text; + }; + let mut plain = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = plain.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() { + let history = + std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize); + text.push_str(&format!( + "; a list stopped at command {done} of {} (op {})", + p.BreadcrumbCount, history[done as usize].0 + )); + let list = p.pCommandList.as_ref().map(|l| l.as_raw()); + let run = runs.iter().find(|r| Some(r.list.as_raw()) == list); + // The k-th marker command is the k-th note. + #[cfg(feature = "diagnostics")] + let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + history + .iter() + .enumerate() + .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .zip(notes.iter()) + .map(|((at, _), note)| (at as u32, note.clone())) + .collect() + }); + #[cfg(not(feature = "diagnostics"))] + let markers: Vec<(u32, String)> = Vec::new(); + if done > 0 { + text.push_str(&in_flight(history, &markers, done as usize)); + } else if let Some(r) = run { + let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + text.push_str(&format!(", its pipelines {pipelines:?}")); + } + } + plain = p.pNext; + } + } + text + } + + /// Moves the debug layer's messages into our log; returns the first + /// error among them. + pub(crate) fn log_messages(&self) -> Option<String> { + let Some(queue) = &self.messages else { + return None; + }; + let mut first_error = None; // SAFETY: each message is read into a buffer of the size the queue // reports, then the queue is emptied. unsafe { @@ -210,16 +546,16 @@ impl Host { let m = &*message; let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); let text = String::from_utf8_lossy(text); - tracing::warn!( - id = m.ID.0, - severity = m.Severity.0, - "D3D12: {}", - text.trim_end_matches('\0') - ); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } } } queue.ClearStoredMessages(); } + first_error } /// A host render target view of `resource`, valid until it is recorded. @@ -238,17 +574,32 @@ impl Host { handle } } + + /// A host depth view of `resource`, valid until it is recorded. + pub(crate) fn dsv( + &self, + resource: &ID3D12Resource, + desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>, + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING; + // SAFETY: a slot of our heap and a live resource. + unsafe { + let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart(); + handle.ptr += (slot * self.dsv_size) as usize; + self.device + .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle); + handle + } + } } impl HostList { pub(crate) fn close(&self) { // SAFETY: our list. if let Err(e) = unsafe { self.list.Close() } { - self.broken.store(true, Ordering::Relaxed); - tracing::warn!(error = %e, "host command list did not close"); - if let Some(host) = host() { - host.log_messages(); - } + fail(format_args!( + "a host command list did not close ({e}): a command recorded into it was invalid" + )); } } @@ -256,7 +607,14 @@ impl HostList { /// for). pub(crate) fn reset(&self) { *self.deferred() = Deferred::default(); - self.broken.store(false, Ordering::Relaxed); + self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); + #[cfg(feature = "diagnostics")] + self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); + { + let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + (scratch.current, scratch.used) = (0, 0); + } // SAFETY: the list is not executing. let reset = unsafe { self.allocator @@ -264,7 +622,96 @@ impl HostList { .and_then(|()| self.list.Reset(&self.allocator, None)) }; if let Err(e) = reset { - tracing::warn!(error = %e, "host command list did not reset"); + fail(format_args!("a host command list did not reset ({e})")); + } + } + + /// Moves a title texture's host copy to `wanted` (a host state) in this + /// list: the host texture and the state it leaves, if that is a change. + /// The list's first use of a texture records nothing: its prelude brings + /// the texture there at submission. + pub(crate) fn transition( + &self, + resource: crate::object::This, + wanted: u32, + ) -> Option<(&'static ID3D12Resource, u32)> { + let texture = crate::resource::host_resource(resource)?; + let wanted = legal_state(texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(resource as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted)); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then_some((texture, before)) + } + } + } + + /// At submission: the list that moves each texture this list uses from + /// its real state to the one the list starts with; the textures' real + /// states become those the list ends with. + fn prelude(&self) -> Option<ID3D12CommandList> { + let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + let barriers: Vec<D3D12_RESOURCE_BARRIER> = states + .iter() + .filter_map(|(&resource, &(first, last))| { + let resource = resource as crate::object::This; + let texture = crate::resource::host_resource(resource)?; + let real = crate::resource::swap_host_state(resource, last); + (real != first).then(|| { + transition( + texture, + D3D12_RESOURCE_STATES(real as i32), + D3D12_RESOURCE_STATES(first as i32), + ) + }) + }) + .collect(); + if barriers.is_empty() { + return None; + } + let (allocator, list) = &self.prelude; + // SAFETY: the prelude is not executing (every submission is waited + // for); the textures are live. + let recorded = unsafe { + allocator.Reset().and_then(|()| { + list.Reset(allocator, None)?; + list.ResourceBarrier(&barriers); + list.Close() + }) + }; + if let Err(e) = recorded { + fail(format_args!("a host state prelude did not record ({e})")); + } + list.cast().ok() + } + + /// Notes what the command about to be recorded does, as a marker + /// command whose text the list keeps (diagnostics, with device-removed + /// data on): the report pairs the breadcrumbs' marker commands with the + /// texts in order and names the commands a fault stopped among. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_op(&self, what: impl FnOnce() -> String) { + if dred_on() { + let what = what(); + let text: Vec<u16> = what.encode_utf16().chain([0]).collect(); + const UNICODE: u32 = 0; + // SAFETY: an open list; the marker is copied when recorded. + unsafe { + self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) + }; + self.notes.lock().unwrap_or_else(|e| e.into_inner()).push(what); + } + } + + /// Notes a pipeline the list binds. + pub(crate) fn used_pipeline(&self, name: &str) { + let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + if !pipelines.contains(name) { + pipelines.insert(name.to_owned()); } } @@ -274,9 +721,55 @@ impl HostList { /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { + let mut deferred = self.deferred(); + deferred + .copies + .push(Step::Copy(dst as usize, src as usize, len)); + deferred.refreshed.clear(); + } + + /// Copies `len` bytes of title memory at `src` into the list's upload + /// memory at `dst` when the list is submitted. + pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { self.deferred() .copies - .push((dst as usize, src as usize, len)); + .push(Step::Fill(dst as usize, src as usize, len)); + } + + /// Brings `[address, address + len)` of a buffer's host copy up to date + /// when the list is submitted (once per range until a title copy + /// intervenes), keeping the copy alive until the list is reset. + pub(crate) fn defer_refresh( + &self, + shadow: &std::sync::Arc<crate::shadow::Shadow>, + address: usize, + len: usize, + ) { + let mut deferred = self.deferred(); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + if deferred.refreshed.insert(key) { + deferred + .copies + .push(Step::Refresh(shadow.clone(), address, len)); + } + } + + /// Shaders of the list write `[address, address + len)` of a buffer's + /// host copy: copied back into title memory once the list has run. + pub(crate) fn defer_gpu_write( + &self, + shadow: &std::sync::Arc<crate::shadow::Shadow>, + address: usize, + len: usize, + ) { + self.deferred() + .copies + .push(Step::GpuWrite(shadow.clone(), address, len)); + } + + /// Stores `what` (`bytes` of it) at `dst` once the list has run. + pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { + self.deferred().writes.push((dst as usize, what, bytes)); } /// A mapped upload buffer of `size` bytes, alive until the list is @@ -289,18 +782,250 @@ impl HostList { Some((buffer, data)) } - fn run_deferred(&self) { - for &(dst, src, len) in &self.deferred().copies { - // SAFETY: both ranges were checked against their resources when - // recorded; titles keep resources alive until their work ends. - unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; + /// `len` bytes of upload memory (256-byte aligned) until the list is + /// reset: the host GPU address and the CPU pointer. + pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { + let host = host()?; + let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + let len = len.max(1).next_multiple_of(256); + if len > SCRATCH_CHUNK { + let (buffer, data) = host.upload_buffer(len)?; + name(&buffer, || format!("list scratch {len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + self.deferred().uploads.push(buffer); + return Some((gpu, data)); } + if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() { + (s.current, s.used) = (s.current + 1, 0); + } + if s.current == s.chunks.len() { + let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?; + name(&buffer, || "list scratch".into()); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + s.chunks.push((buffer, data as usize, gpu)); + s.used = 0; + } + let (_, data, gpu) = s.chunks[s.current]; + let at = s.used; + s.used += len; + Some((gpu + at, (data + at as usize) as *mut u8)) + } + + /// Whether this is the first time since the reset that the list asks + /// about `key` (a texture to bring up to date). + pub(crate) fn first_use(&self, key: usize) -> bool { + self.deferred().textures.insert(key) + } + + /// 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) { + self.deferred().copies.push(Step::Run(Box::new(work))); + self.deferred().refreshed.clear(); + } + + /// As [`HostList::defer`], for work that writes only host memory. + pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Host(Box::new(work))); + } + + /// Runs the list's submission-time steps; refreshes go into `batch` + /// (the title's big buffers, a 174 MB one among them, are read by most + /// lists of a submission, through many ranges). + fn run_deferred(&self, batch: &mut Batch) { + #[cfg(feature = "diagnostics")] + use crate::copystat::{C, add}; + for step in &self.deferred().copies { + let started = std::time::Instant::now(); + let copied = match step { + &Step::Copy(dst, src, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + } + batch.flush(); + copy_mapped(dst as *mut u8, src as *const u8, len, true); + len + } + &Step::Fill(dst, src, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + } + copy_mapped(dst as *mut u8, src as *const u8, len, false); + len + } + Step::Refresh(shadow, address, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Refreshes, 1); + add(C::RefreshBytes, *len as u64); + } + batch.add(shadow, *address, *len); + continue; + } + Step::Run(work) | Step::Host(work) => { + if matches!(step, Step::Run(_)) { + batch.flush(); + } + work(); + #[cfg(feature = "diagnostics")] + { + add(C::Runs, 1); + add(C::RunUs, started.elapsed().as_micros() as u64); + } + continue; + } + Step::GpuWrite(shadow, address, len) => { + // The shaders start from the title's data. + batch.flush(); + shadow.writing(*address, *len); + continue; + } + }; + PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + } + } +} + +/// A submission's refreshes not done yet, merged per buffer copy into the +/// range that covers them: done before a step that writes title memory or +/// gives a range to shaders, and before the lists run. +#[derive(Default)] +struct Batch(Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>); + +impl Batch { + fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) { + let end = address + len; + match self.0.iter_mut().find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)), + None => self.0.push((shadow.clone(), address, end)), + } + } + + fn flush(&mut self) { + for (shadow, from, to) in self.0.drain(..) { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + PREPARING[0].fetch_add(us, Ordering::Relaxed); + PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); + } + } +} + +/// Copies title memory at submission. The ranges were checked against their +/// resources when recorded, but the title may since have unmapped pages of +/// them (tiled memory, page mappings), which read as zeros here; a title +/// destination (`title_dst`) that is not all mapped is left alone. +/// +/// The source is read through the kernel (`ReadProcessMemory`), which +/// reports an unmapped page instead of faulting. Asking `VirtualQuery` first +/// cost about 2 ms per copy in the title's big pools (it walks the page +/// tables to the region's end), which made copies run at 100-200 MB/s. +pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) { + #[cfg(feature = "diagnostics")] + match crate::copystat::mode() { + 1 => { + // SAFETY: timing only: the caller vouches for the source. + unsafe { std::ptr::copy(src, dst, len) }; + return; + } + 2 => return, + _ => {} + } + if len == 0 || title_dst && !crate::texture::committed(dst, len) { + return; + } + if title_dst { + // The kernel writes the destination: it must not be guarded. + crate::watch::writing(dst as usize, len); + } + #[cfg(feature = "diagnostics")] + let moved = std::time::Instant::now(); + let whole = read(src, dst, len); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); + if whole { + return; + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Fallbacks, 1); + // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece + // that fails), zeros for what cannot be read. + for_pieces(src as usize, len, 64 << 10, |at, n| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + for_pieces(at, n, 4 << 10, |at, n| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; + } + }); + } + }); +} + +/// Copies `len` bytes from `src` to `dst` unless a source page is not +/// readable. +fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut done = 0; + // SAFETY: the destination is mapped writable memory of `len` bytes; the + // kernel checks the source. + unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } +} + +/// Copies host memory into title memory after a submission (what shaders +/// wrote), leaving pages that are not mapped alone. +pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let write = |at: usize, n: usize| { + let from = src.wrapping_add(at - dst as usize); + let mut done = 0; + // SAFETY: the source is our mapped host copy; the kernel checks the + // destination. + unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } + }; + if len == 0 || write(dst as usize, len) { + return; + } + for_pieces(dst as usize, len, 64 << 10, |at, n| { + if !write(at, n) { + for_pieces(at, n, 4 << 10, |at, n| { + write(at, n); + }); + } + }); +} + +/// Calls `f` with the pieces of `[start, start + len)` cut at multiples of +/// `step`. +fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) { + let end = start + len; + let mut at = start; + while at < end { + let next = ((at / step + 1) * step).min(end); + f(at, next - at); + at = next; } } impl Host { /// A buffer in the upload heap, mapped for writing. - fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() @@ -366,16 +1091,113 @@ struct Presenter { height: u32, format: DXGI_FORMAT, copy: HostList, + hwnd: HWND, + meter: Meter, +} + +/// The frame rate, shown in the window's caption every second and logged +/// every few seconds. +struct Meter { + since: std::time::Instant, + frames: u32, + drawn: u64, + logged: std::time::Instant, + /// The caption the window had, once read. + caption: Option<Vec<u16>>, +} + +impl Meter { + fn new() -> Self { + let now = std::time::Instant::now(); + Meter { + since: now, + frames: 0, + drawn: crate::draw::drawn(), + logged: now, + caption: None, + } + } + + /// Counts a presented frame. + fn frame(&mut self, hwnd: HWND) { + #[cfg(feature = "diagnostics")] + tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); + self.frames += 1; + let elapsed = self.since.elapsed(); + if elapsed < std::time::Duration::from_secs(1) { + return; + } + let drawn = crate::draw::drawn(); + let frames = f64::from(self.frames); + let fps = frames / elapsed.as_secs_f64(); + let ms = elapsed.as_secs_f64() * 1000.0 / frames; + let draws = (drawn - self.drawn) as f64 / frames; + (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); + // Of a frame, ms preparing submissions and ms waiting for the GPU. + let [cpu, gpu] = [0, 1].map(|i| { + SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames + }); + let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { + let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; + PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames + }); + if self.logged.elapsed() >= std::time::Duration::from_secs(5) { + self.logged = std::time::Instant::now(); + tracing::info!( + "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ + {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ + GPU), {draws:.0} draws/frame" + ); + #[cfg(feature = "diagnostics")] + crate::copystat::log(frames); + } + if self.caption.is_none() { + // The window's own text, read without a message. + let mut buffer = vec![0u16; 512]; + // SAFETY: a window handle and a buffer of that length. + let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; + buffer.truncate(n.max(0) as usize); + self.caption = Some(buffer); + } + let Some(caption) = &self.caption else { return }; + let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); + let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect(); + text.push(0); + // Setting the text waits for the window's thread (a title thread, + // which may not pump for a while), so a thread of ours does it and + // presenting never waits; it takes the newest text when free. + static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None); + static SETTER: std::sync::Once = std::sync::Once::new(); + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); + SETTER.call_once(|| { + let _ = std::thread::Builder::new() + .name("victory-caption".into()) + .spawn(|| { + loop { + let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); + match next { + // SAFETY: a window handle and a NUL-terminated text. + Some((hwnd, text)) => unsafe { + let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); + }, + None => std::thread::sleep(std::time::Duration::from_millis(100)), + } + } + }); + }); + } } impl Host { - /// Shows `texture`, which is in `state` (a host state) and stays in it. - pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32) { + /// Shows `texture`, which is in `state` (a host state) and stays in it, + /// as frame `frame` (saved if captures are on). `None` if nothing was + /// shown; else, in diagnostics builds, whether the frame was black. + pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { tracing::warn!(format = desc.Format.0, "cannot present this format"); - return; + return None; }; let (width, height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); @@ -384,13 +1206,11 @@ impl Host { Ok(p) => Some(p), Err(e) => { tracing::warn!(error = %e, "no swap chain"); - return; + return None; } }; } - let Some(p) = presenter.as_mut() else { - return; - }; + let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { @@ -401,7 +1221,7 @@ impl Host { Ok(()) => (p.width, p.height, p.format) = (width, height, format), Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); - return; + return None; } } } @@ -410,7 +1230,7 @@ impl Host { unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else { - return; + return None; }; p.copy.reset(); let list = &p.copy.list; @@ -423,6 +1243,14 @@ impl Host { ), ]); list.CopyResource(&back, texture); + #[cfg(feature = "diagnostics")] + let capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + #[cfg(feature = "diagnostics")] + let probe = crate::capture::probe(&self.device, list, texture); + #[cfg(not(feature = "diagnostics"))] + let _ = frame; list.ResourceBarrier(&[ transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), transition( @@ -433,7 +1261,16 @@ impl Host { ]); p.copy.close(); self.execute(&[&p.copy]); + #[cfg(feature = "diagnostics")] + if let Some((buffer, footprint)) = capture { + crate::capture::save_read_back(frame, &buffer, &footprint); + } let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + p.meter.frame(p.hwnd); + #[cfg(feature = "diagnostics")] + return Some(probe.is_some_and(|b| crate::capture::black(&b))); + #[cfg(not(feature = "diagnostics"))] + Some(false) } } @@ -475,6 +1312,8 @@ impl Host { height, format, copy, + hwnd, + meter: Meter::new(), }) } } @@ -503,6 +1342,136 @@ fn title_window() -> Option<HWND> { found } +/// `state` without the bits the host texture's flags forbid: the console +/// lets the title name states its own resources allow (unordered access on +/// a depth target, whose host copy cannot have both). +pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { + // SAFETY: a plain query. + legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) +} + +/// [`legal_state`] for a texture with resource flags `flags`. +pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { + // (flag, set or clear forbids, state bits): render target, unordered + // access, depth, denied shader resource. + const FORBIDDEN: [(u32, bool, u32); 4] = [ + (0x1, false, 0x4), + (0x4, false, 0x8), + (0x2, false, 0x10 | 0x20), + (0x8, true, 0x40 | 0x80), + ]; + FORBIDDEN + .iter() + .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) + .fold(state, |s, &(_, _, bits)| s & !bits) +} + +impl Host { + /// A buffer in system memory that the CPU maps (write-back, so reading + /// it is fast too) and shaders read and write: for host copies of title + /// memory that shaders write, which upload memory cannot be. Starts in + /// the common state (buffers move out of it implicitly). + pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option<ID3D12Resource> = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no shared buffer"); + None + } + } + } +} + +/// For adapters without device-removed data (the software one): the last +/// commands each list of the failed submission noted (diagnostics, with +/// `VICTORY_D3D12_DRED`). +fn last_notes(runs: &[&HostList]) -> String { + #[cfg(feature = "diagnostics")] + { + let mut text = String::new(); + for (i, r) in runs.iter().enumerate() { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + for n in notes.iter().rev().take(6).rev() { + text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); + } + } + text + } + #[cfg(not(feature = "diagnostics"))] + { + let _ = runs; + String::new() + } +} + +/// The commands that may have been running where a list stopped at +/// command `done`: those between the barriers around it (work between +/// barriers overlaps on the GPU), by kind, and what the markers just +/// before them say (`HostList::note_op`: diagnostics builds with +/// device-removed data on). +fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { + let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; + let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); + let to = history[done..] + .iter() + .position(barrier) + .map_or(history.len(), |b| (done + b).max(done + 1)); + let mut text = format!(", commands {from}..{to} between its barriers:"); + let mut shown = 0; + for i in from..to { + let op = history[i]; + if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { + continue; + } + shown += 1; + let marker = i + .checked_sub(1) + .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m)) + .map_or("no marker", |(_, s)| s.as_str()); + text.push_str(&format!("; command {i} (op {}): {marker}", op.0)); + } + text +} + pub(crate) fn transition( resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index ad6a787..7558568 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -12,10 +12,18 @@ //! descriptor heaps, [`root`] root signatures, [`query`] query heaps, //! [`signature`] command signatures, [`pipeline`] pipeline states, //! [`frame`] frame pacing, [`object`] what all console graphics objects -//! share. Planned: `present` (swap chain). +//! share, [`console`] which console model the title sees. Planned: +//! `present` (swap chain). +#[cfg(all(windows, feature = "diagnostics"))] +mod capture; +pub mod console; +#[cfg(all(windows, feature = "diagnostics"))] +mod copystat; pub mod descriptor; pub mod device; +#[cfg(windows)] +mod draw; pub mod dxgi; pub mod fence; pub mod frame; @@ -24,8 +32,25 @@ mod host; pub mod list; pub mod object; pub mod pipeline; +#[cfg(windows)] +mod primitive; pub mod query; pub mod queue; pub mod resource; pub mod root; +#[cfg(windows)] +mod sampler; +#[cfg(windows)] +pub mod shader_cache; +#[cfg(windows)] +mod shadow; pub mod signature; +#[cfg(windows)] +mod texture; +#[cfg(windows)] +mod watch; + +#[cfg(windows)] +pub use host::on_failure; +#[cfg(windows)] +pub use watch::{title_memory_remapped, writing as kernel_will_write}; diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index 7328609..6f11cc7 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -5,9 +5,9 @@ //! lists keep the pointer and every limit at zero, so every command reaches //! the table as a call. //! -//! shortcut: the methods record nothing yet; unwritten ones log once, so a -//! run lists what to translate. Translate them onto host command lists -//! (TODO.md, GPU). +//! Each list records onto a host command list as its methods are called +//! (decision 0007); draw state lives in [`crate::draw`]. Methods not +//! written yet log once with their caller, so a run lists what to do next. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::mem::offset_of; @@ -15,6 +15,7 @@ use std::mem::offset_of; use crate::object::{ self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, }; +use crate::queue::Written; use crate::resource::PAGEABLE_IIDS; const ALLOCATOR_IIDS: [Iid; 4] = [ @@ -29,9 +30,11 @@ const ALLOCATOR_IIDS: [Iid; 4] = [ PAGEABLE_IIDS[2], ]; -/// The list interfaces whose ids are the same as on PC, then the device -/// child's. -const LIST_IIDS: [Iid; 8] = [ +/// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has +/// all their slots): those whose ids are the same as on PC, the console's +/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the +/// device child's. +const LIST_IIDS: [Iid; 10] = [ guid( 0x7116d91c, 0xe7e4, @@ -68,6 +71,18 @@ const LIST_IIDS: [Iid; 8] = [ 0x4541, [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74], ), + guid( + 0x55050859, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), + guid( + 0xc3827890, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), PAGEABLE_IIDS[1], PAGEABLE_IIDS[2], ]; @@ -91,14 +106,33 @@ struct List { graphics_root_headers: [u32; 128], compute_root_headers: [u32; 128], pipeline_shadow: [u32; 8], - /// Ours, after the console layout: the host list the calls record - /// into (decision 0007). + /// Newer titles' lists are larger: Grand Theft Auto VI's state flush + /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and + /// tests +0x548, so its layout runs past 0x560. Its size is unknown; + /// this keeps our fields clear of whatever the title writes there. + newer: [u32; 256], + /// Ours, after the console layout: memory handed out by + /// [`allocate_upload`], kept until the list is reset; the host list the + /// calls record into (decision 0007), and the draw state the title set. + uploads: std::sync::Mutex<Vec<Vec<u8>>>, #[cfg(windows)] host: Option<crate::host::HostList>, + #[cfg(windows)] + state: std::sync::Mutex<crate::draw::State>, } const _: () = assert!(offset_of!(List, put) == 0x18); const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); +/// Runs `f` with the host list and draw state of a title list, if there +/// is a host GPU. +#[cfg(windows)] +fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { + let Some(list) = host_list(this) else { return }; + // SAFETY: the title passes one of our lists. + let state = unsafe { &(*this.cast::<List>()).state }; + f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); +} + /// The host list behind a title list, if there is a host GPU. #[cfg(windows)] pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { @@ -168,13 +202,19 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES } tracing::debug!(kind, "command list"); let list = Box::new(List { - object: Object::new(&LIST_FUNCTIONS), + object: if crate::device::newer() { + Object::new(&NEWER_LIST_FUNCTIONS) + } else { + Object::new(&LIST_FUNCTIONS) + }, kind, put: [0; 5], reserved: [0; 64], graphics_root_headers: [0; 128], compute_root_headers: [0; 128], pipeline_shadow: [0; 8], + newer: [0; 256], + uploads: Default::default(), #[cfg(windows)] host: crate::host::host().and_then(|h| match h.new_list() { Ok(list) => Some(list), @@ -183,6 +223,8 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES None } }), + #[cfg(windows)] + state: Default::default(), }); object::hand_out(LIST, list, iid, &LIST_IIDS, out) } @@ -216,14 +258,21 @@ extern "system" fn close(this: This) -> HRESULT { } S_OK } -extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT { +extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT { if allocator.is_null() { return E_INVALIDARG; } + // Every submission of the list has run (submissions are waited for). + // SAFETY: the title passes one of our lists. + let uploads = unsafe { &(*this.cast::<List>()).uploads }; + uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(windows)] - if let Some(host) = host_list(this) { + with_state(this, |host, state| { host.reset(); - } + state.reset(pipeline); + }); + #[cfg(not(windows))] + let _ = (this, pipeline); S_OK } @@ -243,7 +292,7 @@ pub(crate) struct Barrier { /// The barrier on host resources, or `None` if it names a resource the host /// GPU does not have (buffers so far). #[cfg(windows)] -fn host_barrier(b: &Barrier) -> Option<Barrier> { +fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> { use windows::core::Interface; let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast()); match b.kind { @@ -253,16 +302,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> { if b.flags & BEGIN_ONLY != 0 { return None; } - // shortcut: whole resources, from the state we tracked (see - // `host_transition`); subresources are not told apart. + // shortcut: whole resources, from the state the list tracked + // (`HostList::transition`); subresources are not told apart. let wanted = crate::host::texture_state(b.last as u32); - let (resource, before) = crate::resource::host_transition(b.first, wanted)?; + let (texture, before) = list.transition(b.first, wanted)?; Some(Barrier { kind: 0, flags: 0, - first: resource.cast_const().cast(), + first: texture.as_raw().cast_const().cast(), second: 0xffff_ffff | (u64::from(before) << 32), - last: u64::from(wanted), + last: u64::from(crate::host::legal_state(texture, wanted)), }) } 1 => Some(Barrier { @@ -290,6 +339,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> { } } +/// An unordered access barrier on every resource: earlier shader writes +/// finish before later work reads or writes. +const UAV_BARRIER: Barrier = Barrier { + kind: 2, + flags: 0, + first: std::ptr::null(), + second: 0, + last: 0, +}; + /// Returns the console's barrier "actions" (none). extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { #[cfg(windows)] @@ -298,7 +357,17 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> { // SAFETY: the title passes `count` barriers. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; - let host: Vec<Barrier> = barriers.iter().filter_map(host_barrier).collect(); + let mut host: Vec<Barrier> = barriers + .iter() + .filter_map(|b| host_barrier(list, b)) + .collect(); + // Buffers have host copies, not resources the barrier can name: + // a barrier on one waits for every shader write before it. + if barriers.iter().any(|b| { + b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() + }) { + host.push(UAV_BARRIER); + } if !host.is_empty() { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>()); @@ -319,11 +388,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> /// Moves a title texture's host copy to `state` in the list, if needed. #[cfg(windows)] -fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { +pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; - if let Some(texture) = crate::resource::host_resource(resource) - && let Some((_, before)) = crate::resource::host_transition(resource, state) - { + if let Some((texture, before)) = list.transition(resource, state) { + let state = crate::host::legal_state(texture, state); let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); // SAFETY: an open list and a live texture. unsafe { list.list.ResourceBarrier(&[barrier]) }; @@ -380,6 +448,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { ) { ensure_state(list, dst, COPY_DEST); ensure_state(list, src, COPY_SOURCE); + crate::texture::host_written(dst); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("copy resource {src:?} to {dst:?}")); // SAFETY: an open list and live textures. unsafe { list.list.CopyResource(to, from) }; } else if let (Some((to, a)), Some((from, b))) = ( @@ -461,9 +532,26 @@ extern "system" fn copy_texture_region( from.resource = texture.as_raw().cast_const().cast(); } ensure_state(list, dst.resource, COPY_DEST); + crate::texture::host_written(dst.resource); let mut to_location = dst; to_location.resource = to.as_raw().cast_const().cast(); let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>()); + #[cfg(feature = "diagnostics")] + list.note_op(|| { + // SAFETY: a live texture; the box is the title's or null. + let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) }; + format!( + "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}", + dst.resource, + d.Width, + d.Height, + d.Format.0, + dst.kind, + src.resource, + src.kind, + (src.kind == FOOTPRINT).then_some(src.footprint) + ) + }); const _: () = assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>()); // SAFETY: an open list; both locations in the host's layout, naming @@ -522,6 +610,9 @@ extern "system" fn resolve( const RESOLVE_SOURCE: u32 = 0x2000; ensure_state(list, dst, RESOLVE_DEST); ensure_state(list, src, RESOLVE_SOURCE); + crate::texture::host_written(dst); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); // SAFETY: an open list and live textures; the region is inside both. unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); @@ -594,9 +685,7 @@ extern "system" fn clear_rtv( let rtv = host.rtv(texture, record.desc().as_ref()); // SAFETY: an open list, a fresh view of a live texture. unsafe { - if let Some((_, before)) = - crate::resource::host_transition(record.resource, RENDER_TARGET) - { + if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; list.list.ResourceBarrier(&[crate::host::transition( texture, @@ -611,9 +700,137 @@ extern "system" fn clear_rtv( let _ = (this, handle, color, count, rects); } +/// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`; +/// flags: 1 depth, 2 stencil. +extern "system" fn clear_dsv( + this: This, + handle: u64, + flags: u32, + depth: f32, + stencil: u8, + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS; + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }); + const DEPTH_WRITE: u32 = 0x10; + ensure_state(list, record.resource, DEPTH_WRITE); + let dsv = host.dsv(texture, record.depth_desc().as_ref()); + // SAFETY: an open list, a fresh view of a live texture. + unsafe { + list.list + .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) + }; + } + #[cfg(not(windows))] + let _ = (this, handle, flags, depth, stencil, count, rects); +} + +/// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses +/// are title memory, copied at submission like buffer copies (if mapped). +extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && dst != 0 + && src != 0 + { + let len = len as usize; + list.defer(move || { + if crate::texture::committed(src as *const u8, len) + && crate::texture::committed(dst as *const u8, len) + { + // SAFETY: both ranges are committed title memory. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; + } + }); + } + #[cfg(not(windows))] + let _ = (this, dst, src, len); +} + +/// `DriverHintX(feature, value)`: no hints for the host. +extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 { + 0 +} + +/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the +/// host has no use for (the ray-tracing builder dispatches this way). +extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { + #[cfg(windows)] + state::dispatch(this, x, y, z); + #[cfg(not(windows))] + { + let _ = (this, x, y, z); + count_dispatch(); + } +} + +/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when +/// resolved. +extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} + +/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes +/// each query's result into the buffer once the list has run. Timestamps +/// (type 2) are the GPU clock then; occlusion counts (0) say a million +/// samples passed and binary occlusion (1) visible, so nothing is culled +/// by a query. +/// shortcut: no query runs on the host GPU; results are plausible values, +/// not measured ones (time spans come out as the submission's length). +extern "system" fn resolve_queries( + this: This, + _heap: This, + kind: u32, + _first: u32, + count: u32, + buffer: This, + offset: u64, +) { + const OCCLUSION: u32 = 0; + const BINARY: u32 = 1; + const TIMESTAMP: u32 = 2; + const PIPELINE_STATISTICS: u32 = 3; + let Some((data, size)) = crate::resource::buffer_bytes(buffer) else { + return; + }; + let (what, bytes) = match kind { + OCCLUSION => (Written::Value(1 << 20), 8), + BINARY => (Written::Value(1), 8), + TIMESTAMP => (Written::GpuTimestamp, 8), + PIPELINE_STATISTICS => (Written::Value(0), 88), + _ => (Written::Value(0), 16), + }; + if offset + u64::from(count) * bytes > size { + return; + } + for i in 0..u64::from(count) { + // Wider results are written as 8-byte pieces. + for piece in 0..bytes / 8 { + // SAFETY: inside the buffer, checked above. + let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) }; + let what = if piece == 0 { what } else { Written::Value(0) }; + defer_write(this, at as u64, what, 8); + } + } +} + /// IUnknown 3, object 4, device child 1, allocator 2. -static ALLOCATOR_FUNCTIONS: Table<10> = { - let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 10>()); +static ALLOCATOR_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>()); f[0] = allocator_query as *const (); f[2] = allocator_release as *const (); f[7] = object::parent_device as *const (); // 0x38 @@ -622,26 +839,472 @@ static ALLOCATOR_FUNCTIONS: Table<10> = { Table(f) }; -/// IUnknown 3, object 4, device child 1, list 1, graphics list 96 (59 as -/// on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 + 13). -static LIST_FUNCTIONS: Table<140> = { - let mut f = object::d3d12_object(object::missing_table::<LIST, 140>()); - f[0] = list_query as *const (); - f[2] = list_release as *const (); - f[7] = object::parent_device as *const (); // 0x38 - f[8] = list_type as *const (); // 0x40 - f[9] = close as *const (); // 0x48 - f[10] = reset as *const (); // 0x50 - f[15] = copy_buffer_region as *const (); // 0x78 - f[16] = copy_texture_region as *const (); // 0x80 - f[17] = copy_resource as *const (); // 0x88 - f[19] = resolve as *const (); // 0x98 - f[26] = barrier as *const (); // 0xd0 - f[83] = copy_texture_region_x as *const (); // 0x298 - f[84] = copy_resource_x as *const (); // 0x2a0 - f[52] = clear_rtv as *const (); // 0x1a0 - Table(f) -}; +extern "system" fn set_pipeline(this: This, pipeline: This) { + crate::pipeline::bound(pipeline); + #[cfg(windows)] + with_state(this, |_, state| state.set_pipeline(pipeline)); + #[cfg(not(windows))] + let _ = this; +} + +/// Pipeline syncs: waits for earlier work and cache flushes, at the top or +/// bottom of the pipe `(flags, control, address, size)`. Host lists order +/// their own work and every submission is waited for, so there is nothing +/// to do. +extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} + +/// Reset with console flags `(allocator, pipeline, flags)`; the flags only +/// tune the console's command memory. +extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { + reset(this, allocator, pipeline) +} + +/// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list +/// owns until it is reset, which the CPU writes and the GPU reads at the +/// same address; null on failure. Grand Theft Auto VI's BVH builder puts +/// its instance descriptions there (and wrote through our old +/// `E_NOTIMPL` as a pointer). +extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { + let align = usize::try_from(alignment).unwrap_or(0).max(16); + let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { + return std::ptr::null_mut(); + }; + if this.is_null() || !align.is_power_of_two() { + return std::ptr::null_mut(); + } + let mut block = vec![0u8; len]; + let start = block.as_mut_ptr(); + // SAFETY: the offset is below `align`, so `size` bytes fit after it. + let at = unsafe { start.add(start.align_offset(align)) }; + // SAFETY: the title passes one of our lists. + let uploads = unsafe { &(*this.cast::<List>()).uploads }; + // Moving the vector keeps its heap block where it is. + uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); + at +} + +/// Draw state the host has no use for (root signatures: ours come with +/// the pipeline; depth bounds, depth order and shading rate hints): any +/// arguments, nothing returned. +extern "system" fn ignored_state(_: This) {} + +/// The title's draw state (decision 0007, step 3), kept for its draws or +/// set on the host list at once. Without a host GPU these do nothing. +#[cfg(windows)] +mod state { + use super::{This, host_list, with_state}; + use crate::draw::{IndexView, VertexView}; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; + + /// `count` items at `items`, or none. + fn items<'a, T>(items: *const T, count: u32) -> &'a [T] { + if items.is_null() || count == 0 { + return &[]; + } + // SAFETY: the title passes `count` items. + unsafe { std::slice::from_raw_parts(items, count as usize) } + } + + pub(super) extern "system" fn topology(this: This, topology: u32) { + with_state(this, |list, s| s.set_topology(list, topology)); + } + pub(super) extern "system" fn viewports( + this: This, + count: u32, + viewports: *const D3D12_VIEWPORT, + ) { + if let Some(list) = host_list(this) { + crate::draw::viewports(list, items(viewports, count)); + } + } + pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { + if let Some(list) = host_list(this) { + crate::draw::scissors(list, items(rects, count)); + } + } + pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { + if let Some(list) = host_list(this) { + // SAFETY: the title passes four floats or null. + crate::draw::blend_factor(list, unsafe { factor.as_ref() }); + } + } + pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { + if let Some(list) = host_list(this) { + crate::draw::stencil_ref(list, reference); + } + } + pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { + with_state(this, |_, s| s.set_heaps(items(heaps, count))); + } + pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(true, slot, handle)); + } + pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(false, slot, handle)); + } + pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) { + with_state(this, |_, s| s.set_constants(true, slot, &[value], offset)); + } + pub(super) extern "system" fn graphics_constant( + this: This, + slot: u32, + value: u32, + offset: u32, + ) { + with_state(this, |_, s| s.set_constants(false, slot, &[value], offset)); + } + pub(super) extern "system" fn compute_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(true, slot, items(values, count), offset) + }); + } + pub(super) extern "system" fn graphics_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(false, slot, items(values, count), offset) + }); + } + /// Root constant buffer, shader resource and unordered access views. + pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(true, slot, address)); + } + pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(false, slot, address)); + } + pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) { + // SAFETY: the title passes a view or null. + with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() })); + } + pub(super) extern "system" fn vertex_buffers( + this: This, + start: u32, + count: u32, + views: *const VertexView, + ) { + with_state(this, |_, s| { + s.set_vertex_buffers(start, items(views, count)) + }); + } + /// `(count, handles, one range, depth)`: with one range, the handles + /// follow the first at the render target view size (128 bytes). + pub(super) extern "system" fn targets( + this: This, + count: u32, + handles: *const u64, + one_range: i32, + depth: *const u64, + ) { + let handles: Vec<u64> = if one_range != 0 && !handles.is_null() { + // SAFETY: the title passes the first handle. + let first = unsafe { *handles }; + (0..u64::from(count)).map(|i| first + 128 * i).collect() + } else { + items(handles, count).to_vec() + }; + // SAFETY: the title passes a handle or null. + let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0); + with_state(this, |list, s| s.set_targets(list, &handles, depth)); + } + pub(super) extern "system" fn draw( + this: This, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw(list, vertices, instances, first, first_instance) + }); + } + pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) { + super::count_dispatch(); + with_state(this, |list, s| s.dispatch(list, x, y, z)); + } + /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh + /// programs take `x` groups only. + pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { + super::count_draw(); + if y * z != 1 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); + } + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. + /// shortcut: dispatches whose group count is in GPU memory (indirect) + /// are dropped; make them ExecuteIndirect when the title uses them. + pub(super) extern "system" fn dispatch_mesh_x( + this: This, + x: u32, + _flags: u64, + indirect: u64, + _payload: u64, + ) { + super::count_draw(); + if indirect != 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); + return; + } + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + pub(super) extern "system" fn draw_indexed( + this: This, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw_indexed(list, indices, instances, first, base, first_instance) + }); + } +} + +/// Without a host GPU every draw state call is ignored. +#[cfg(not(windows))] +mod state { + pub(super) use super::dispatch; + pub(super) use super::draw; + pub(super) use super::draw as draw_indexed; + pub(super) use super::draw as dispatch_mesh; + pub(super) use super::draw as dispatch_mesh_x; + pub(super) use super::ignored_state as blend_factor; + pub(super) use super::ignored_state as compute_constant; + pub(super) use super::ignored_state as compute_constants; + pub(super) use super::ignored_state as compute_table; + pub(super) use super::ignored_state as compute_view; + pub(super) use super::ignored_state as graphics_constant; + pub(super) use super::ignored_state as graphics_constants; + pub(super) use super::ignored_state as graphics_table; + pub(super) use super::ignored_state as graphics_view; + pub(super) use super::ignored_state as heaps; + pub(super) use super::ignored_state as index_buffer; + pub(super) use super::ignored_state as scissors; + pub(super) use super::ignored_state as stencil_ref; + pub(super) use super::ignored_state as targets; + pub(super) use super::ignored_state as topology; + pub(super) use super::ignored_state as vertex_buffers; + pub(super) use super::ignored_state as viewports; +} + +fn count_draw() { + DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Draws of the kinds the host does not run yet (indirect, mesh), and +/// dispatches, counted per frame for the log. +/// shortcut: dropped until their shaders translate (decision 0007). +extern "system" fn draw(_: This) { + count_draw(); +} +fn count_dispatch() { + DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} +#[cfg(not(windows))] +extern "system" fn dispatch(_: This) { + count_dispatch(); +} +static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Draws (any kind, mesh and indirect included) and compute dispatches +/// recorded since the last call. +pub(crate) fn take_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) +} + +/// A GPU wait for a memory value `(address, comparison, reference, ...)`. +/// Lists run one after another and to completion, so a value another queue +/// or the CPU has to write first cannot be waited for; nothing to do. +extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {} + +/// The enhanced barriers `(group count, groups)`: buffer, texture and +/// global barriers with layouts instead of states. Every host use of a +/// title texture (clears, copies) moves its host copy to the state it needs +/// first, so only their ordering matters: one barrier on every shader +/// write (the title's buffer barriers order compute passes). +extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + #[cfg(windows)] + if count > 0 + && let Some(list) = host_list(this) + { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + #[cfg(not(windows))] + let _ = (this, count); +} + +/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and +/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the +/// GPU timestamp instead (64-bit form), flag 2 the system timestamp. +extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { + defer_write(this, address, Written::Value(u64::from(value)), 4); +} +extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { + const GPU_TIMESTAMP: u32 = 1; + const SYSTEM_TIMESTAMP: u32 = 2; + let what = match flags { + GPU_TIMESTAMP => Written::GpuTimestamp, + SYSTEM_TIMESTAMP => Written::SystemTimestamp, + _ => Written::Value(value), + }; + defer_write(this, address, what, 8); +} + +fn defer_write(this: This, address: u64, what: Written, bytes: usize) { + if address == 0 { + return; + } + #[cfg(windows)] + if let Some(list) = host_list(this) { + list.defer_write(address as *mut u8, what, bytes); + return; + } + let _ = this; + // Without a host GPU nothing runs later: write now. + what.write(address as *mut u8, bytes); +} + +/// The list methods by their slot in older titles' lists (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 +/// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 +/// + 13): 140 slots. +const METHODS: [(usize, *const ()); 52] = [ + (0, list_query as *const ()), + (2, list_release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (8, list_type as *const ()), // 0x40 + (9, close as *const ()), // 0x48 + (10, reset as *const ()), // 0x50 + (12, state::draw as *const ()), // 0x60 instanced + (13, state::draw_indexed as *const ()), // 0x68 indexed + (14, state::dispatch as *const ()), // 0x70 + (15, copy_buffer_region as *const ()), // 0x78 + (16, copy_texture_region as *const ()), // 0x80 + (17, copy_resource as *const ()), // 0x88 + (19, resolve as *const ()), // 0x98 + (20, state::topology as *const ()), // 0xa0 + (21, state::viewports as *const ()), // 0xa8 + (22, state::scissors as *const ()), // 0xb0 + (23, state::blend_factor as *const ()), // 0xb8 + (24, state::stencil_ref as *const ()), // 0xc0 + (25, set_pipeline as *const ()), // 0xc8 + (26, barrier as *const ()), // 0xd0 + (32, state::heaps as *const ()), // 0x100 + (33, ignored_state as *const ()), // 0x108 compute root signature + (34, ignored_state as *const ()), // 0x110 graphics root signature + (35, state::compute_table as *const ()), // 0x118 + (36, state::graphics_table as *const ()), // 0x120 + (37, state::compute_constant as *const ()), // 0x128 + (38, state::graphics_constant as *const ()), // 0x130 + (39, state::compute_constants as *const ()), // 0x138 + (40, state::graphics_constants as *const ()), // 0x140 + (41, state::compute_view as *const ()), // 0x148 CBV + (42, state::graphics_view as *const ()), // 0x150 CBV + (43, state::compute_view as *const ()), // 0x158 SRV + (44, state::graphics_view as *const ()), // 0x160 SRV + (45, state::compute_view as *const ()), // 0x168 UAV + (46, state::graphics_view as *const ()), // 0x170 UAV + (47, state::index_buffer as *const ()), // 0x178 + (48, state::vertex_buffers as *const ()), // 0x180 + (50, state::targets as *const ()), // 0x190 + (51, clear_dsv as *const ()), // 0x198 + (52, clear_rtv as *const ()), // 0x1a0 + (59, draw as *const ()), // 0x1d8 indirect + (60, copy_memory as *const ()), // 0x1e0 + (68, ignored_state as *const ()), // 0x220 depth bounds + (69, write32 as *const ()), // 0x228 + (70, write64 as *const ()), // 0x230 + (71, wait_value as *const ()), // 0x238, 32 bits + (72, wait_value as *const ()), // 0x240, 64 bits + (73, ignored_state as *const ()), // 0x248 pixel shader depth order + (83, copy_texture_region_x as *const ()), // 0x298 + (84, copy_resource_x as *const ()), // 0x2a0 + (124, ignored_state as *const ()), // 0x3e0 shading rate + (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch +]; +/// The rest of [`METHODS`], kept apart only to stay readable. +const MORE_METHODS: [(usize, *const ()); 9] = [ + (28, query_mark as *const ()), // 0xe0 BeginQuery + (29, query_mark as *const ()), // 0xe8 EndQuery + (30, resolve_queries as *const ()), // 0xf0 + (78, dispatch_x as *const ()), // 0x270 + (98, state::dispatch_mesh_x as *const ()), // 0x310 + (99, driver_hint as *const ()), // 0x318 + // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410. + (129, sync as *const ()), + (130, sync as *const ()), + (137, reset_x as *const ()), // 0x448 +]; + +/// Newer titles' lists have two more methods in the console part of the +/// base list, after the clears (0x198/0x1a0 as before) and before +/// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8 +/// on is two later (taken here as starting exactly at 0x1d8). Inferred from +/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe +/// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate +/// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure). +const fn newer_slot(slot: usize) -> usize { + if slot >= 59 { slot + 2 } else { slot } +} + +/// Methods only newer titles' lists have. 0x490: the enhanced barrier +/// `(group count, groups)`, with 16-byte groups `(type, count, barriers)` +/// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`, +/// called from Grand Theft Auto VI's state flush with its result unused. +/// shortcut: 0x470's purpose is unknown; ignored until a title shows it +/// matters. +const NEWER_METHODS: [(usize, *const ()); 3] = [ + (142, ignored_state as *const ()), + (146, barrier_groups as *const ()), + (148, allocate_upload as *const ()), +]; + +const fn list_table(newer: bool) -> [*const (); 160] { + let mut f = object::d3d12_object(object::missing_table::<LIST, 160>()); + let mut i = 0; + while i < METHODS.len() + MORE_METHODS.len() { + let (slot, method) = if i < METHODS.len() { + METHODS[i] + } else { + MORE_METHODS[i - METHODS.len()] + }; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + let mut i = 0; + while newer && i < NEWER_METHODS.len() { + f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1; + i += 1; + } + f +} + +/// Every slot up to the limit exists and logs, for the methods newer +/// titles add. +static LIST_FUNCTIONS: Table<160> = Table(list_table(false)); +static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true)); #[cfg(test)] mod tests { @@ -666,11 +1329,25 @@ mod tests { (at(0x18), at(0x28), at(0x30)) }; assert!(put >= draw_limit && put >= api_limit); + // The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks. + let mut same = null; + assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); + assert_eq!(same, list); + assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1); assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0); assert_eq!( slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list), S_OK ); + // List-owned upload memory: aligned, writable, gone at reset. + let p = allocate_upload(list, 40, 0x100); + assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); + // SAFETY: 40 bytes were handed out. + unsafe { p.write_bytes(0xab, 40) }; + assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); + assert_eq!(reset(list, allocator, null), S_OK); + // SAFETY: the list is ours. + assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty()); let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o); assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); diff --git a/crates/victory-gpu/src/object.rs b/crates/victory-gpu/src/object.rs index 669e874..3d48fe3 100644 --- a/crates/victory-gpu/src/object.rs +++ b/crates/victory-gpu/src/object.rs @@ -18,7 +18,7 @@ pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; /// What D3D and DXGI return for a missing item (adapter, output, private /// data). pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32; -const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32; +pub(crate) const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32; pub type Iid = [u8; 16]; @@ -275,19 +275,54 @@ const MAX_SLOTS: usize = 160; static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] = [const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()]; -/// Logged once per slot. Wrong for a slot that returns a value instead of +/// Logged once per slot, with the caller's offset in its module (the title +/// image for title calls). Wrong for a slot that returns a value instead of /// an `HRESULT`. extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT { if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) { tracing::warn!( object = KINDS[KIND], slot = format_args!("{:#x}", SLOT * 8), + caller = caller(), "method not implemented" ); } E_NOTIMPL } +/// The return address of whoever called our caller, as `+offset` into its +/// module. +#[inline(never)] +fn caller() -> String { + #[cfg(windows)] + { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleHandleExW, + }; + let mut frame = std::ptr::null_mut(); + // SAFETY: room for one frame; skips this function and its caller. + if unsafe { RtlCaptureStackBackTrace(2, 1, &mut frame, std::ptr::null_mut()) } == 1 { + let mut module = std::ptr::null_mut(); + // SAFETY: looks up the module holding the address, no reference. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS + | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + frame as *const u16, + &mut module, + ) + }; + if found != 0 { + return format!("+{:#x}", frame as usize - module as usize); + } + return format!("{frame:?}"); + } + } + String::new() +} + /// Accepts and ignores (debug-only settings). pub(crate) extern "system" fn ignore() -> HRESULT { S_OK @@ -298,6 +333,8 @@ macro_rules! missing { } /// A table of `N` slots that log and fail; callers fill in what they have. +/// Tables are made longer than the interfaces we know, so that a method a +/// newer title adds logs instead of jumping into whatever follows the table. pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*const (); N] { let all = missing!(KIND; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 341b0f8..ad450cc 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -1,15 +1,24 @@ //! Pipeline states. Both descriptions start as on PC: the root signature, -//! then the shader stages (five for graphics, one for compute); only those -//! are read so far. +//! then the shader stages (five for graphics, one for compute); streams +//! carry the rest of the graphics state as subobjects of the standard +//! types. //! -//! shortcut: the console shader containers are kept, not translated, and -//! the rest of the description is ignored. Translate through the cache -//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte +//! Host pipelines are made on a pipeline's first draw, not at creation: +//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20 +//! seconds and draws with a few dozen (decision 0007, step 3). Shader +//! containers are shared by content hash and translated once, on first +//! use (decision 0003). +//! +//! shortcut: only vertex plus pixel pipelines from streams and compute +//! pipelines get host pipelines; mesh, tessellation and geometry stages, +//! and the plain graphics description, keep their containers only. The 32-byte //! packet after the header stays zero: titles only copy it inline, which //! our null command-list limits keep from running. #![allow(clippy::not_unsafe_ptr_arg_deref)] +use std::collections::HashMap; use std::mem::offset_of; +use std::sync::{Arc, Mutex, OnceLock}; use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; use crate::resource::PAGEABLE_IIDS; @@ -45,30 +54,183 @@ pub(crate) struct ComputeHead { stage: Bytecode, } +/// A shader container a title passed, shared by every pipeline with the +/// same bytes. +pub(crate) struct Shader { + pub(crate) stage: &'static str, + /// The first 8 bytes of its BLAKE3, as logged. + pub(crate) hash: String, + container: Vec<u8>, + #[cfg(windows)] + translated: OnceLock<Option<Translated>>, +} + +impl std::fmt::Debug for Shader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} {}", self.stage, self.hash) + } +} + +/// Every container seen, by full content hash. +static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None); + +/// The shared container for `bytes`. +fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> { + let full = blake3::hash(bytes); + let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner()); + shaders + .get_or_insert_with(HashMap::new) + .entry(*full.as_bytes()) + .or_insert_with(|| { + Arc::new(Shader { + stage, + hash: full.to_hex()[..16].to_owned(), + container: bytes.to_vec(), + #[cfg(windows)] + translated: OnceLock::new(), + }) + }) + .clone() +} + +/// A translated shader and the console resources its code reads. +#[cfg(windows)] +pub(crate) struct Translated { + pub(crate) host: victory_shader::emit::HostShader, + pub(crate) used: Vec<victory_shader::UsedResource>, +} + +#[cfg(windows)] +impl Shader { + /// The translation, made on first use; a shader that does not + /// translate is logged once. + pub(crate) fn translated(&self) -> Option<&Translated> { + self.translated + .get_or_init(|| { + let done = translate(&self.container); + match &done { + Ok(t) => tracing::info!( + stage = self.stage, + hash = %self.hash, + user_data = t.host.user_data.len(), + samplers = t.host.samplers.len(), + "shader translated" + ), + Err(e) => tracing::warn!( + stage = self.stage, + hash = %self.hash, + error = %e, + "shader does not translate; its pipelines' draws are dropped" + ), + } + done.ok() + }) + .as_ref() + } +} + +#[cfg(windows)] +fn translate(container: &[u8]) -> Result<Translated, String> { + use victory_shader::{Container, FourCC, HwStage}; + let host = crate::shader_cache::host_shader(container)?; + let c = Container::parse(container).map_err(|e| e.to_string())?; + let used = match c.part(FourCC::DXIL) { + Some(part) => victory_shader::native_programs(part.data) + .map_err(|e| e.to_string())? + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs + ) + }) + .map(|p| p.used) + .unwrap_or_default(), + None => Vec::new(), + }; + Ok(Translated { host, used }) +} + #[repr(C)] struct Pipeline { object: Object, packet: [u32; 8], - /// Each stage's container, empty when the stage is unused. - shaders: Vec<Vec<u8>>, + /// Each used stage's container. + shaders: Vec<Arc<Shader>>, + /// Whether a list has bound it yet (its shaders are logged then). + bound: std::sync::atomic::AtomicBool, + /// The rest of a stream's graphics state, for the host pipeline. + #[cfg(windows)] + graphics: Option<Box<host::GraphicsState>>, + #[cfg(windows)] + host: OnceLock<Option<host::HostPipeline>>, } const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); -fn copy(stage: &Bytecode) -> Vec<u8> { - if stage.code.is_null() || stage.size == 0 { - return Vec::new(); - } - // SAFETY: the title passes `size` bytes of shader code. - unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec() +/// Stage names, in description order. +const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"]; + +fn pipeline<'a>(this: This) -> &'a Pipeline { + // SAFETY: the title passes one of our pipelines. + unsafe { &*this.cast::<Pipeline>() } } -fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT { - let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect(); - tracing::debug!(?sizes, "pipeline state"); +/// List method: logs each pipeline's shaders the first time a list binds +/// it, so a run lists the shaders its frames need first. +pub(crate) fn bound(this: This) { + if this.is_null() { + return; + } + let p = pipeline(this); + if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + let frame = crate::frame::current(); + for shader in &p.shaders { + tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind"); + } +} + +/// The host pipeline of a title pipeline, made on first use; `None` if one +/// of its shaders does not translate or the host refuses it. +#[cfg(windows)] +pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + let p = pipeline(this); + p.host + .get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref())) + .as_ref() +} + +/// The stage's container, if it has one. +fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> { + if code.code.is_null() || code.size == 0 { + return None; + } + // SAFETY: the title passes `size` bytes of shader code. + Some(shader(stage, unsafe { + std::slice::from_raw_parts(code.code, code.size) + })) +} + +fn hand_out( + shaders: Vec<Arc<Shader>>, + #[cfg(windows)] graphics: Option<Box<host::GraphicsState>>, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::trace!(?shaders, "pipeline state"); let pipeline = Box::new(Pipeline { object: Object::new(&FUNCTIONS), packet: [0; 8], shaders, + bound: std::sync::atomic::AtomicBool::new(false), + #[cfg(windows)] + graphics, + #[cfg(windows)] + host: OnceLock::new(), }); object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out) } @@ -84,7 +246,15 @@ pub(crate) extern "system" fn create_graphics( let Some(desc) = (unsafe { desc.as_ref() }) else { return E_INVALIDARG; }; - hand_out(desc.stages.iter().map(copy).collect(), iid, out) + let stages = GRAPHICS_STAGES.iter().zip(&desc.stages); + let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect(); + hand_out( + shaders, + #[cfg(windows)] + None, + iid, + out, + ) } /// Device method. @@ -98,7 +268,115 @@ pub(crate) extern "system" fn create_compute( let Some(desc) = (unsafe { desc.as_ref() }) else { return E_INVALIDARG; }; - hand_out(vec![copy(&desc.stage)], iid, out) + hand_out( + copy("compute", &desc.stage).into_iter().collect(), + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// Device method 0x1f0: the plain compute description plus console +/// extensions `(desc, extension count, extensions, iid, out)`. +/// shortcut: the extensions (console shader settings) are ignored, as is +/// the rest of the description. +pub(crate) extern "system" fn create_compute_x( + this: This, + desc: *const ComputeHead, + _extensions: u32, + _extended: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + create_compute(this, desc, iid, out) +} + +/// A pipeline described as a stream: its size and the subobjects, each a +/// type then its data, padded to 8 bytes. +#[repr(C)] +pub(crate) struct StreamDesc { + size: usize, + stream: *const u8, +} + +/// A subobject type's size (type included), and the stage it is if it is a +/// shader. The console numbers amplification and mesh shaders 23 and 24 +/// (PC: 24 and 25); its own types from 25 on are not sized yet. +fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> { + let stage = |name| Some((24, Some(name))); + match kind { + 1 => stage("vertex"), + 2 => stage("pixel"), + 3 => stage("domain"), + 4 => stage("hull"), + 5 => stage("geometry"), + 6 => stage("compute"), + 23 => stage("amplification"), + 24 => stage("mesh"), + 0 => Some((16, None)), + 12 | 19 => Some((24, None)), + 7 | 15 => Some((40, None)), + 8 => Some((336, None)), + 10 => Some((48, None)), + 11 => Some((56, None)), + 17 => Some((16, None)), + 21 => Some((64, None)), + 22 => Some((32, None)), + 9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)), + _ => None, + } +} + +/// Device method: a pipeline from a stream; the shaders are kept, and the +/// graphics state for the host pipeline. +pub(crate) extern "system" fn create_stream( + _: This, + desc: *const StreamDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.stream.is_null() { + return E_INVALIDARG; + } + let mut shaders = Vec::new(); + #[cfg(windows)] + let mut graphics = host::GraphicsState::default(); + let mut at = 0; + while at + 8 <= desc.size { + // SAFETY: inside the stream the title passes. + let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() }; + let Some((size, stage)) = subobject(kind) else { + tracing::warn!( + kind, + at, + "pipeline subobject of unknown size; the rest is ignored" + ); + break; + }; + if let Some(stage) = stage { + // SAFETY: a shader subobject has its bytecode at +8. + let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() }; + shaders.extend(copy(stage, code)); + } + #[cfg(windows)] + // SAFETY: a whole subobject of this kind lies at `at`. + unsafe { + graphics.read(kind, desc.stream.add(at)) + }; + at += size; + } + hand_out( + shaders, + #[cfg(windows)] + Some(Box::new(graphics)), + iid, + out, + ) } extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { @@ -110,19 +388,30 @@ extern "system" fn release(this: This) -> u32 { } /// IUnknown 3, object 4, device child 1, pipeline 3. -static FUNCTIONS: Table<11> = { - let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>()); +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 Table(f) }; +#[cfg(windows)] +pub(crate) mod host; + #[cfg(test)] mod tests { use super::*; use crate::object::{S_OK, slot}; + fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> { + pipeline(p) + .shaders + .iter() + .map(|s| (s.stage, s.container.clone())) + .collect() + } + #[test] fn pipelines_keep_their_shaders() { let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); @@ -151,11 +440,71 @@ mod tests { create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), S_OK ); - // SAFETY: one of our pipelines. - let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders }; - assert_eq!(shaders[0], vs); - assert_eq!(shaders[1], ps); - assert!(shaders[2].is_empty()); + assert_eq!( + shaders(p), + [("vertex", vs.to_vec()), ("pixel", ps.to_vec())] + ); + // A second pipeline with the same pixel shader shares its container. + let mut q = std::ptr::null(); + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q); + assert!(Arc::ptr_eq( + &pipeline(p).shaders[1], + &pipeline(q).shaders[1] + )); assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0); } + + /// The stream layout Grand Theft Auto VI builds (title+0x86f090): root + /// signature, five shader slots (the first a mesh shader), blend, sample + /// mask, rasterizer, depth-stencil 1, sample description, input layout, + /// topology, render target and depth formats: 0x2b0 bytes. + #[test] + fn streams_yield_their_shaders() { + let (ms, ps) = ([9u8; 7], [4u8; 5]); + let mut stream = vec![0u8; 0x2b0]; + let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes()); + for (at, kind) in [ + (0x10, 24), + (0x28, 2), + (0x40, 3), + (0x58, 4), + (0x70, 5), + (0x88, 8), + (0x1d8, 9), + (0x1e0, 10), + (0x210, 21), + (0x250, 17), + (0x260, 12), + (0x278, 14), + (0x280, 15), + (0x2a8, 16), + ] { + put(at, kind); + } + put(0x18, ms.as_ptr() as u64); + put(0x20, ms.len() as u64); + put(0x30, ps.as_ptr() as u64); + put(0x38, ps.len() as u64); + // Topology type 3 (triangles), one render target of format 28. + put(0x278, 14 | 3 << 32); + put(0x280, 15 | 28 << 32); + put(0x2a0, 1 << 32); + let desc = StreamDesc { + size: stream.len(), + stream: stream.as_ptr(), + }; + let mut p = std::ptr::null(); + let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); + assert_eq!(hr, S_OK); + assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); + #[cfg(windows)] + { + let g = pipeline(p).graphics.as_deref().unwrap(); + assert_eq!(g.topology.0, 3); + assert_eq!( + (g.targets.NumRenderTargets, g.targets.RTFormats[0].0), + (1, 28) + ); + } + } } diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs new file mode 100644 index 0000000..fd413f1 --- /dev/null +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -0,0 +1,594 @@ +//! Host pipelines for title pipelines (decision 0007, step 3): the +//! title's graphics state with the translated shaders, under a root +//! signature of our own that the translated shaders' bindings define +//! (`victory_shader::emit`): per stage one block of root constants for the +//! user data, root views for the title's root views, static samplers for +//! the immediate samplers, and directly indexed heaps. + +use std::ffi::{CStr, CString}; +use std::sync::Arc; + +use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::PCSTR; + +use super::{Shader, Translated}; +use crate::host::host; + +/// A stream's graphics state, owned (the title's stream lives only for the +/// creation call). Subobjects the stream leaves out keep D3D12's defaults. +pub(crate) struct GraphicsState { + blend: D3D12_BLEND_DESC, + sample_mask: u32, + rasterizer: D3D12_RASTERIZER_DESC, + depth: D3D12_DEPTH_STENCIL_DESC, + /// Input elements, their names pointing into `names`. + inputs: Vec<D3D12_INPUT_ELEMENT_DESC>, + names: Vec<CString>, + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + pub(crate) targets: D3D12_RT_FORMAT_ARRAY, + depth_format: DXGI_FORMAT, + samples: DXGI_SAMPLE_DESC, +} + +impl Default for GraphicsState { + fn default() -> Self { + let target = D3D12_RENDER_TARGET_BLEND_DESC { + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_ZERO, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ONE, + DestBlendAlpha: D3D12_BLEND_ZERO, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + LogicOp: D3D12_LOGIC_OP_NOOP, + RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, + ..Default::default() + }; + let keep = D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D12_STENCIL_OP_KEEP, + StencilPassOp: D3D12_STENCIL_OP_KEEP, + StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS, + }; + GraphicsState { + blend: D3D12_BLEND_DESC { + RenderTarget: [target; 8], + ..Default::default() + }, + sample_mask: u32::MAX, + rasterizer: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_BACK, + DepthClipEnable: true.into(), + ..Default::default() + }, + depth: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS, + StencilReadMask: 0xff, + StencilWriteMask: 0xff, + FrontFace: keep, + BackFace: keep, + ..Default::default() + }, + inputs: Vec::new(), + names: Vec::new(), + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED, + targets: D3D12_RT_FORMAT_ARRAY::default(), + depth_format: DXGI_FORMAT_UNKNOWN, + samples: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + } + } +} + +impl GraphicsState { + /// Takes in one subobject of a stream: its type, then its data at +4 + /// (+8 for those holding pointers). + /// + /// # Safety + /// `at` points at a whole subobject of type `kind`. + pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) { + // SAFETY: the caller passes a whole subobject. + unsafe { + let data = at.add(4); + match kind { + 8 => self.blend = data.cast::<D3D12_BLEND_DESC>().read_unaligned(), + 9 => self.sample_mask = data.cast::<u32>().read_unaligned(), + 10 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(), + 11 => self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned(), + 21 => { + // shortcut: the depth bounds test is dropped (the host + // pipeline uses the plain description); bring it back + // with a stream if a title enables it. + let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned(); + self.depth = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + }; + } + 12 => { + let layout = at.add(8).cast::<D3D12_INPUT_LAYOUT_DESC>().read_unaligned(); + if layout.pInputElementDescs.is_null() { + return; + } + let elements = std::slice::from_raw_parts( + layout.pInputElementDescs, + layout.NumElements as usize, + ); + self.names = elements + .iter() + .map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned()) + .collect(); + self.inputs = elements + .iter() + .zip(&self.names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + Format: DXGI_FORMAT( + crate::resource::pc_format(e.Format.0 as u32) as i32 + ), + ..*e + }) + .collect(); + } + 13 => { + self.strip_cut = + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::<i32>().read_unaligned()) + } + 14 => { + self.topology = + D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::<i32>().read_unaligned()) + } + 15 => { + self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned(); + for f in &mut self.targets.RTFormats { + f.0 = crate::resource::pc_format(f.0 as u32) as i32; + } + } + 16 => { + let f = data.cast::<u32>().read_unaligned(); + self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32); + } + 17 => self.samples = data.cast::<DXGI_SAMPLE_DESC>().read_unaligned(), + _ => {} + } + } + } + + /// The vertex buffer slots the input layout reads. + fn slots(&self) -> u32 { + self.inputs + .iter() + .fold(0, |m, e| m | 1 << e.InputSlot.min(31)) + } + + /// The input elements with their byte offsets worked out. + fn elements(&self) -> Vec<Input> { + let mut next = [0u32; 32]; + self.inputs + .iter() + .map(|e| { + let slot = e.InputSlot.min(31) as usize; + let format = e.Format.0 as u32; + let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { + next[slot] + } else { + e.AlignedByteOffset + }; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + next[slot] = offset + bytes; + Input { + slot: slot as u32, + offset, + format, + per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, + } + }) + .collect() + } +} + +/// One input element: vertex buffer slot, byte offset, format. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Input { + pub(crate) slot: u32, + pub(crate) offset: u32, + pub(crate) format: u32, + pub(crate) per_instance: bool, +} + +/// The console's own primitive topology types. +const RECTANGLES: i32 = 19; +const QUADS: i32 = 32; + +/// One stage of a host pipeline and where its bindings go. +pub(crate) struct Stage { + pub(crate) shader: Arc<Shader>, + /// The root parameter of its user data, and its size in dwords. + pub(crate) user_data: Option<(u32, u32)>, + /// Root parameters of its root views: (title root parameter, ours). + pub(crate) root_cbvs: Vec<(u8, u32)>, + pub(crate) root_srvs: Vec<(u8, u32)>, +} + +impl Stage { + pub(crate) fn translated(&self) -> &Translated { + self.shader + .translated() + .expect("host pipelines are made from translated shaders") + } +} + +pub(crate) struct HostPipeline { + /// A compute pipeline (else graphics). + pub(crate) compute: bool, + /// A mesh pipeline (graphics without vertex input). + pub(crate) mesh: bool, + pub(crate) pso: ID3D12PipelineState, + pub(crate) root: ID3D12RootSignature, + /// Vertex, then pixel stage, or the compute stage. + pub(crate) stages: Vec<Stage>, + /// The vertex buffer slots it reads (bit per slot). + pub(crate) slots: u32, + pub(crate) inputs: Vec<Input>, + /// Its shaders, for reports of slow submissions. + pub(crate) name: String, +} + +/// Logs a pipeline that gets no host pipeline, once per reason. +fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline> { + static SEEN: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&reason) { + seen.push(reason); + tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)"); + } + None +} + +impl HostPipeline { + /// A host pipeline for vertex and pixel shaders with the graphics + /// state `g`, or for one compute shader. + pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> { + let find = |stage| shaders.iter().find(|s| s.stage == stage); + let compute = match shaders { + [cs] if cs.stage == "compute" => Some(cs), + _ => None, + }; + if compute.is_none() + && shaders + .iter() + .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh")) + { + return refuse( + "only vertex, mesh, pixel and compute stages are translated", + shaders, + ); + } + let mesh = find("mesh"); + let stages = if let Some(cs) = compute { + vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] + } else { + let first = match (mesh, find("vertex")) { + (Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH), + (None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (None, None) => return refuse("no vertex or mesh shader", shaders), + }; + let mut stages = vec![first]; + stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + stages + }; + if mesh.is_some() && !host()?.mesh_shaders() { + return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); + } + for (s, _) in &stages { + s.translated()?; + } + let host = host()?; + + // The root signature the translated shaders' bindings define. + let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new(); + let mut samplers = Vec::new(); + let mut bound = Vec::new(); + for &(shader, visibility) in &stages { + let t = &shader.translated()?.host; + let mut stage = Stage { + shader: shader.clone(), + user_data: None, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + }; + let dwords = t.user_data_dwords(); + if dwords > 0 { + stage.user_data = Some((params.len() as u32, dwords)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); + } + for (slots, kind, out) in [ + ( + &t.root_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.root_cbvs, + ), + ( + &t.root_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.root_srvs, + ), + ] { + for &slot in slots { + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } + for (n, s) in t.static_samplers.iter().enumerate() { + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(s.filter as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), + MipLODBias: s.mip_lod_bias, + MaxAnisotropy: s.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), + MinLOD: s.min_lod, + MaxLOD: s.max_lod, + ShaderRegister: n as u32, + RegisterSpace: SAMPLER_SPACE, + ShaderVisibility: visibility, + }); + } + bound.push(stage); + } + let root = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host root signature refused"); + return None; + } + }; + let code = |i: usize| { + stages.get(i).and_then(|(s, _)| s.translated()).map_or( + D3D12_SHADER_BYTECODE::default(), + |t| D3D12_SHADER_BYTECODE { + pShaderBytecode: t.host.dxil.as_ptr().cast(), + BytecodeLength: t.host.dxil.len(), + }, + ) + }; + if compute.is_some() { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + CS: code(0), + ..Default::default() + }; + // SAFETY: the description points at live data. + let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + return Some(HostPipeline { + compute: true, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + }); + } + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + if mesh.is_some() { + let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host mesh pipeline"); + return Some(HostPipeline { + compute: false, + mesh: true, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + }); + } + + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(0), + PS: code(1), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: g.inputs.as_ptr(), + NumElements: g.inputs.len() as u32, + }, + IBStripCutValue: g.strip_cut, + // The console's rectangle and quad types draw as triangles on + // the host (see `draw`). + PrimitiveTopologyType: match g.topology.0 { + RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + _ => g.topology, + }, + NumRenderTargets: g.targets.NumRenderTargets, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + // SAFETY: the description points at live data. + let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + tracing::debug!( + ?shaders, + depth = ?g.depth, + dsv = g.depth_format.0, + targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize], + blend = ?g.blend.RenderTarget[0], + cull = g.rasterizer.CullMode.0, + "host graphics state" + ); + Some(HostPipeline { + compute: false, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: g.slots(), + inputs: g.elements(), + }) + } +} + +/// A mesh pipeline from the title's graphics state: the pipeline-state +/// stream form (no input layout or topology). +fn mesh_pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, + ms: D3D12_SHADER_BYTECODE, + ps: D3D12_SHADER_BYTECODE, + g: &GraphicsState, +) -> windows::core::Result<ID3D12PipelineState> { + use windows::core::Interface; + /// A stream subobject: its type, then its description, pointer-aligned. + #[repr(C, align(8))] + struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub<D3D12_SHADER_BYTECODE>, + ps: Sub<D3D12_SHADER_BYTECODE>, + blend: Sub<D3D12_BLEND_DESC>, + mask: Sub<u32>, + raster: Sub<D3D12_RASTERIZER_DESC>, + depth: Sub<D3D12_DEPTH_STENCIL_DESC>, + targets: Sub<D3D12_RT_FORMAT_ARRAY>, + dsv: Sub<DXGI_FORMAT>, + samples: Sub<DXGI_SAMPLE_DESC>, + } + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::<Stream>(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + // SAFETY: the stream holds whole subobjects pointing at live data. + unsafe { device.cast::<ID3D12Device2>()?.CreatePipelineState(&desc) } +} + +fn root_signature( + device: &ID3D12Device, + params: &[D3D12_ROOT_PARAMETER1], + samplers: &[D3D12_STATIC_SAMPLER_DESC], + compute: bool, +) -> windows::core::Result<ID3D12RootSignature> { + let input = if compute { + D3D12_ROOT_SIGNATURE_FLAG_NONE + } else { + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + }; + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: input + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays; the blob is read in + // full before it is released. + unsafe { + let mut blob: Option<ID3DBlob> = None; + let mut error: Option<ID3DBlob> = None; + if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) { + if let Some(error) = error { + let text = std::slice::from_raw_parts( + error.GetBufferPointer().cast::<u8>(), + error.GetBufferSize(), + ); + tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize()); + device.CreateRootSignature(0, bytes) + } +} diff --git a/crates/victory-gpu/src/primitive.rs b/crates/victory-gpu/src/primitive.rs new file mode 100644 index 0000000..74c6f69 --- /dev/null +++ b/crates/victory-gpu/src/primitive.rs @@ -0,0 +1,162 @@ +//! Console primitive types the host lacks. A rectangle list gives three +//! corners per rectangle, the second the one between the other two, and +//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's +//! full-screen rectangles come as top left, bottom left, bottom right); on +//! the host each rectangle becomes two triangles, with the fourth vertex +//! made from the other three on the CPU. +//! +//! shortcut: the fourth vertex is computed from vertex inputs, not from +//! vertex shader outputs as the hardware does; that is the same for vertex +//! shaders linear in their inputs (blits, 2D quads). Inputs in formats +//! [`components`] does not know keep the first vertex's value. + +/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six +/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both +/// triangles turn the same way. `elements` are (byte offset, format). +pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { + for (rect, out) in src + .chunks_exact(3 * stride) + .zip(dst.chunks_exact_mut(6 * stride)) + { + let v = |i: usize| &rect[i * stride..(i + 1) * stride]; + for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { + out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i)); + } + let fourth = &mut out[5 * stride..]; + fourth.copy_from_slice(v(0)); + for &(offset, format) in elements { + let at = offset as usize; + let Some((n, kind)) = components(format) else { + continue; + }; + for c in 0..n { + let get = |i: usize| kind.read(&v(i)[at..], c); + let value = get(0) + get(2) - get(1); + kind.write(&mut fourth[at..], c, value); + } + } + } +} + +#[derive(Clone, Copy)] +enum Kind { + F32, + F16, + Unorm8, + Unorm16, +} + +/// Component count and kind of the vertex formats rectangles use. +fn components(format: u32) -> Option<(usize, Kind)> { + Some(match format { + 2 => (4, Kind::F32), + 6 => (3, Kind::F32), + 16 => (2, Kind::F32), + 41 => (1, Kind::F32), + 10 => (4, Kind::F16), + 34 => (2, Kind::F16), + 54 => (1, Kind::F16), + 11 => (4, Kind::Unorm16), + 35 => (2, Kind::Unorm16), + 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + _ => return None, + }) +} + +impl Kind { + fn bytes(self) -> usize { + match self { + Kind::F32 => 4, + Kind::F16 | Kind::Unorm16 => 2, + Kind::Unorm8 => 1, + } + } + + fn read(self, at: &[u8], c: usize) -> f32 { + let b = &at[c * self.bytes()..]; + match self { + Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), + Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, + Kind::Unorm8 => f32::from(b[0]) / 255.0, + } + } + + fn write(self, at: &mut [u8], c: usize, v: f32) { + let n = self.bytes(); + let b = &mut at[c * n..(c + 1) * n]; + match self { + Kind::F32 => b.copy_from_slice(&v.to_le_bytes()), + Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()), + Kind::Unorm16 => { + b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) + } + Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + } + } +} + +fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let exp = u32::from((h >> 10) & 0x1f); + let man = u32::from(h & 0x3ff); + let bits = match (exp, man) { + (0, 0) => sign, + // Subnormal: scale the mantissa. + (0, m) => { + let v = m as f32 * 2f32.powi(-24); + return if sign != 0 { -v } else { v }; + } + (31, m) => sign | 0x7f80_0000 | m << 13, + (e, m) => sign | (e + 112) << 23 | m << 13, + }; + f32::from_bits(bits) +} + +fn f32_to_half(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let man = bits & 0x7f_ffff; + if exp >= 31 { + return sign | 0x7c00; // too large: infinity + } + if exp <= 0 { + return sign; // too small: zero + } + sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A rectangle of float2 positions and RGBA8 colors, given as top + /// left, bottom left, bottom right: the fourth corner completes the + /// parallelogram at the top right. + #[test] + fn rectangles_get_their_fourth_corner() { + let vertex = |x: f32, y: f32, r: u8| { + let mut v = Vec::new(); + v.extend(x.to_le_bytes()); + v.extend(y.to_le_bytes()); + v.extend([r, 0, 0, 255]); + v + }; + let src: Vec<u8> = [ + vertex(-1.0, 1.0, 0), + vertex(-1.0, -1.0, 100), + vertex(1.0, -1.0, 150), + ] + .concat(); + let mut dst = vec![0u8; 6 * 12]; + expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]); + assert_eq!(dst[..36], src[..]); + assert_eq!(dst[36..48], src[..12]); + assert_eq!(dst[48..60], src[24..36]); + assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x3e00), 1.5); + assert_eq!(half_to_f32(0xc000), -2.0); + } +} diff --git a/crates/victory-gpu/src/query.rs b/crates/victory-gpu/src/query.rs index b5c109e..f3eb6b0 100644 --- a/crates/victory-gpu/src/query.rs +++ b/crates/victory-gpu/src/query.rs @@ -63,8 +63,8 @@ extern "system" fn release(this: This) -> u32 { } /// IUnknown 3, object 4, device child 1. -static FUNCTIONS: Table<8> = { - let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 8>()); +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index c537a3f..5992fad 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -1,5 +1,5 @@ -//! Command queues. Nothing is executed yet: submitted lists are dropped and -//! fence signals complete at once, as if the GPU were infinitely fast. +//! Command queues. Submitted lists run on the host GPU and are waited for, +//! so fence signals complete at once. #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -54,13 +54,50 @@ pub(crate) extern "system" fn create( }; tracing::debug!(?desc, "command queue"); let queue = Box::new(Queue { - object: Object::new(&FUNCTIONS), + object: if crate::device::newer() { + Object::new(&NEWER_FUNCTIONS) + } else { + Object::new(&FUNCTIONS) + }, kind: desc.kind, desc, }); object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) } +/// The console's queue description: an engine or pipe and a queue on it +/// in place of PC's priority and node mask. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDescX { + kind: u32, + flags: u32, + engine_or_pipe: u32, + queue: u32, +} + +/// Device method `CreateCommandQueueX`. The host picks engines itself, so +/// the queue is created as on PC. +pub(crate) extern "system" fn create_x( + this: This, + desc: *const QueueDescX, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&x) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(desc = ?x, "console command queue"); + let desc = QueueDesc { + kind: x.kind, + priority: 0, + flags: x.flags, + nodes: 1, + }; + create(this, &desc, iid, out) +} + extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { object::answer( QUEUE, @@ -102,6 +139,22 @@ pub(crate) struct Plane { count: u32, resources: *const This, } +/// Submission tagged with the frame it belongs to `(count, lists, frame +/// token, flags)`; frames are paced elsewhere, so it runs as a plain one. +extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { + execute(this, count, lists); +} +/// Signal with sync settings for the top and bottom of the pipe; our +/// submissions are complete when they return, so it signals at once. +extern "system" fn signal2_x( + this: This, + fence: This, + value: u64, + _bottom: *const u8, + _top: *const u8, +) -> HRESULT { + signal(this, fence, value) +} /// Markers and events only matter to profilers. extern "system" fn marker(_: This) {} extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { @@ -114,15 +167,71 @@ extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT { extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT { if fence.is_null() { E_INVALIDARG } else { S_OK } } -/// Ticks per second of GPU timestamps; none are written yet. +/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { if out.is_null() { return E_INVALIDARG; } // SAFETY: checked non-null. - unsafe { out.write(100_000_000) }; + unsafe { out.write(TIMESTAMP_FREQUENCY) }; S_OK } +const TIMESTAMP_FREQUENCY: u64 = 100_000_000; + +/// What a list's bottom-of-pipe write stores when the list has run. +#[derive(Debug, Clone, Copy)] +pub(crate) enum Written { + Value(u64), + /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the + /// process started (our GPU work is done on the CPU's timeline). + GpuTimestamp, + /// The CPU's performance counter. + SystemTimestamp, +} + +impl Written { + /// Stores the low `bytes` (4 or 8) of the value at `at`. + pub(crate) fn write(self, at: *mut u8, bytes: usize) { + let value = match self { + Written::Value(v) => v, + Written::GpuTimestamp => { + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); + (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + } + Written::SystemTimestamp => system_timestamp(), + }; + // SAFETY: the title names writable GPU memory (unified with ours). + unsafe { + if bytes == 4 { + at.cast::<u32>().write_unaligned(value as u32); + } else { + at.cast::<u64>().write_unaligned(value); + } + } + } +} + +fn system_timestamp() -> u64 { + #[cfg(windows)] + { + let mut count = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) }; + count as u64 + } + #[cfg(not(windows))] + 0 +} + +/// Frames presented so far. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() -> u64 { + FRAMES.load(Ordering::Relaxed) +} + /// Shows the first plane's first resource in our window. /// /// shortcut: one plane, no scaling or placement, the source expected in @@ -133,10 +242,38 @@ extern "system" fn present( plane_parameters: *const Plane, _parameters: *const u8, ) -> HRESULT { - static FRAMES: AtomicU64 = AtomicU64::new(0); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; if frame.is_power_of_two() { - tracing::info!(frame, "frame presented"); + let (draws, dispatches) = crate::list::take_counts(); + #[cfg(windows)] + let (drawn, dispatched) = { + static DRAWN: AtomicU64 = AtomicU64::new(0); + static DISPATCHED: AtomicU64 = AtomicU64::new(0); + let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed); + ( + since(&DRAWN, crate::draw::drawn()), + since(&DISPATCHED, crate::draw::dispatched()), + ) + }; + #[cfg(not(windows))] + let (drawn, dispatched) = (0, 0); + tracing::info!( + frame, + draws, + drawn, + dispatches, + dispatched, + "frame presented (since the last line: draws and dispatches, and those run on the host)" + ); + #[cfg(windows)] + if frame >= 256 { + let (hits, misses) = crate::shader_cache::counts(); + tracing::info!(hits, misses, "shaders from the cache and translated so far"); + } + } + #[cfg(all(windows, feature = "diagnostics"))] + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); } #[cfg(windows)] if planes > 0 @@ -152,13 +289,125 @@ extern "system" fn present( const COPY_SOURCE: u32 = 0x800; let state = crate::resource::host_transition(resource, COPY_SOURCE) .map_or(COPY_SOURCE, |(_, before)| before); - host.present(texture, state); + let shown = host.present(texture, state, frame); crate::resource::host_transition(resource, state); + #[cfg(feature = "diagnostics")] + blinks(frame, resource, state, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = shown; } #[cfg(not(windows))] let _ = (planes, plane_parameters); S_OK } +/// Diagnostics: logs a presented frame that is black after one that was +/// not, with what was presented and how many draws ran since. +#[cfg(all(windows, feature = "diagnostics"))] +fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) { + static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0)); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let drawn = crate::draw::drawn(); + let black = shown.unwrap_or(false); + let draws = crate::draw::take_frame(); + if black && !last.0 { + last.2 += 1; + tracing::warn!( + frame, + resource = ?resource, + state = format_args!("{state:#x}"), + draws = drawn - last.1, + copied = shown.is_some(), + black_frames = last.2, + levels = ?crate::capture::recent_levels(), + "a black frame after a frame that was not" + ); + for d in draws { + tracing::warn!("black frame {frame}: {d}"); + } + AFTER.store(frame + 6, Ordering::Relaxed); + } + // Six frames on: the levels around it (a fade or a single drop). + static AFTER: AtomicU64 = AtomicU64::new(0); + if AFTER.load(Ordering::Relaxed) == frame { + tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame"); + } + *last = (black, drawn, last.2); +} + +/// A run of destination pages: how they are mapped (0 pool pages from +/// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are) +/// and how many. +#[repr(C)] +pub(crate) struct PageRange { + kind: u32, + start: u32, + count: u32, +} + +/// The ranges mapped from a destination address on. +#[repr(C)] +pub(crate) struct PageBatch { + destination: u64, + count: u32, + ranges: *const PageRange, +} + +/// Bytes per mapped page. +const PAGE: u64 = 64 << 10; + +/// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps +/// pages of a pool (memory the title mapped physical pages into) at the +/// batches' addresses. Grand Theft Auto VI streams textures into pool pages +/// and maps them into its tiled heap this way (title+0xf2c470, ranges of +/// one constant page or of unmapped pages). Done at once: every earlier +/// submission has run. +extern "system" fn copy_page_mappings( + _: This, + count: u32, + batches: *const PageBatch, + pool: u64, + pool_pages: u32, + _flags: u32, +) -> HRESULT { + let Some(map) = crate::resource::page_mapper() else { + return E_INVALIDARG; + }; + if batches.is_null() && count > 0 { + return E_INVALIDARG; + } + let batches = (count > 0).then(|| { + // SAFETY: the title passes `count` batches. + unsafe { std::slice::from_raw_parts(batches, count as usize) } + }); + let mut ok = true; + for b in batches.into_iter().flatten() { + if b.ranges.is_null() { + continue; + } + // SAFETY: each batch holds `count` ranges. + let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) }; + let mut at = b.destination; + for r in ranges { + let len = u64::from(r.count) * PAGE; + let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages); + let source = pool + u64::from(r.start) * PAGE; + ok &= match r.kind { + 0 if inside(r.count) => map(at, source, len), + 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)), + 2 => map(at, 0, len), + 3 => true, + _ => false, + }; + at += len; + } + } + if !ok { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); + } + S_OK +} + extern "system" fn desc(this: This, out: *mut QueueDesc) { if !out.is_null() { // SAFETY: checked non-null; the title passes room for a description. @@ -166,30 +415,70 @@ extern "system" fn desc(this: This, out: *mut QueueDesc) { } } -/// IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, then -/// console ones). -static FUNCTIONS: Table<34> = { - let mut f = object::d3d12_object(object::missing_table::<QUEUE, 34>()); - f[0] = query as *const (); - f[2] = release as *const (); - f[7] = object::parent_device as *const (); // 0x38 - f[10] = execute as *const (); // 0x50 - f[11] = marker as *const (); // 0x58 set marker - f[12] = marker as *const (); // 0x60 begin event - f[13] = marker as *const (); // 0x68 end event - f[14] = signal as *const (); // 0x70 - f[15] = wait as *const (); // 0x78 - f[16] = timestamp_frequency as *const (); // 0x80 - f[26] = desc as *const (); // 0xd0 - f[30] = present as *const (); // 0xf0 - Table(f) -}; +/// The queue methods by their slot in older titles' queues (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, +/// then console ones). +const METHODS: [(usize, *const ()); 15] = [ + (0, query as *const ()), + (2, release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (10, execute as *const ()), // 0x50 + (11, marker as *const ()), // 0x58 set marker + (12, marker as *const ()), // 0x60 begin event + (13, marker as *const ()), // 0x68 end event + (14, signal as *const ()), // 0x70 + (15, wait as *const ()), // 0x78 + (16, timestamp_frequency as *const ()), // 0x80 + (26, desc as *const ()), // 0xd0 + (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch + (30, present as *const ()), // 0xf0 + (33, execute_x as *const ()), // 0x108 + (32, signal2_x as *const ()), // 0x100 +]; + +/// Newer titles' queues have two more methods before Signal, which moved +/// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as +/// starting exactly at 0x70, the methods before it kept in place). +/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence, +/// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume +/// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, +/// lists, token, flags)` (title+0x24821dd). +const fn newer_slot(slot: usize) -> usize { + if slot >= 14 { slot + 2 } else { slot } +} + +const fn queue_table(newer: bool) -> [*const (); 36] { + let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>()); + let mut i = 0; + while i < METHODS.len() { + let (slot, method) = METHODS[i]; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + f +} + +static FUNCTIONS: Table<36> = Table(queue_table(false)); +static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); #[cfg(test)] mod tests { use super::*; use crate::object::slot; + /// Where a queue's signal is: newer layouts have it two slots later. + /// Another test may switch layouts while this one runs, so the queue's + /// own table decides. + fn signal_slot(q: This) -> usize { + // SAFETY: one of our queues; its first field is the table. + let table = unsafe { *q.cast::<*const *const ()>() }; + if table == NEWER_FUNCTIONS.0.as_ptr() { + 0x80 + } else { + 0x70 + } + } + #[test] fn queue_signals_complete_at_once() { let null = std::ptr::null(); @@ -209,7 +498,7 @@ mod tests { crate::fence::create(null, 0, 0, fence_iid, &mut fence), S_OK ); - let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, 0x70); + let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q)); assert_eq!(signal(q, fence, 7), S_OK); assert_eq!( slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence), @@ -217,4 +506,42 @@ mod tests { ); assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0); } + + /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + #[test] + fn console_queues_are_created_as_on_pc() { + let null = std::ptr::null(); + let desc = QueueDescX { + kind: 2, + flags: 0, + engine_or_pipe: 1, + queue: 0, + }; + let mut q = null; + assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + assert_eq!(queue(q).desc.kind, 2); + let none = std::ptr::null(); + assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG); + } + + #[test] + fn newer_queues_have_their_methods_two_slots_later() { + let (old, new) = (queue_table(false), queue_table(true)); + assert_eq!(old[10], new[10]); // submission stays at 0x50 + assert_eq!(old[14], new[16]); // signal 0x70 → 0x80 + assert_eq!(old[30], new[32]); // present 0xf0 → 0x100 + assert_eq!(new[35], execute_x as *const ()); // 0x118 + } + + #[test] + fn timestamps_and_values_are_written() { + let mut at = [0u64; 2]; + Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4); + assert_eq!(at[0], 2); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + let first = at[1]; + std::thread::sleep(std::time::Duration::from_millis(2)); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + assert!(at[1] > first); + } } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 28ed947..828113e 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -1,15 +1,16 @@ //! Heaps, committed and placed resources, and resource sizes. //! -//! shortcut: heaps and resources are plain host memory and a resource's -//! GPU address is its CPU address, as on the console. Rewrite them on host -//! D3D12 heaps and resources once the command-stream decoder needs the host -//! GPU to see them (TODO.md, GPU). +//! Heaps and resources are host memory and a resource's GPU address is its +//! CPU address, as on the console; textures also get a host copy, and +//! buffers a host copy when a draw reads them (`shadow`). #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::alloc::{Layout, alloc_zeroed, dealloc}; use std::ffi::c_void; use std::ptr::NonNull; +use victory_formats::texture; + use crate::object::{ self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This, guid, @@ -112,29 +113,83 @@ const BUFFER: u32 = 1; const TEXTURE_3D: u32 = 4; /// Bytes per element and the element's width in texels (4 for block -/// compression), by DXGI format number. `None` for 1-bit, video and -/// console-only formats. -fn element(format: u32) -> Option<(u64, u64)> { +/// compression), by DXGI format number. `None` for 1-bit and video +/// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit +/// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed +/// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color). +pub(crate) fn element(format: u32) -> Option<(u64, u64)> { Some(match format { 1..=4 => (16, 1), 5..=8 => (12, 1), 9..=22 => (8, 1), - 23..=47 | 67 | 87..=93 => (4, 1), + 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1), + 118..=120 => (3, 1), 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1), - 60..=65 => (1, 1), + 60..=65 | 190 => (1, 1), 70..=72 | 79..=81 => (8, 4), 73..=78 | 82..=84 | 94..=99 => (16, 4), _ => return None, }) } -/// Bytes and alignment a resource takes in our layout: every mip of every -/// array slice and sample, packed, rounded up to 64 KiB. -/// -/// shortcut: an unpadded bound, not the console's tiled layout. Titles that -/// write console-tiled data straight into memory may need more; revisit with -/// the texture layouts (TODO.md, formats). +/// A texture's layout in console memory, as the console's layout library +/// gives it (`victory-hle`'s `xg` serves the same): the description's +/// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick. +pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> { + use texture::{Dimension, Swizzle, TextureDesc}; + const TEXTURE_1D: u32 = 2; + const TEXTURE_2D: u32 = 3; + const RENDER_TARGET: u32 = 1; + const DEPTH: u32 = 2; + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + TEXTURE_2D => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR, + 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X, + 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X, + 0 => Swizzle::SW_4KB_S, + 1 => Swizzle::LINEAR, + l if l & !0xff == 0x100 => Swizzle(l & 0xff), + _ => return None, + }; + texture::Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array_size), + mips: u32::from(desc.mip_levels), + format: desc.format, + samples: desc.sample_count.max(1), + swizzle, + }) + .ok() +} + +/// Bytes and alignment a resource takes: buffers their width (64 KiB +/// aligned), textures their console layout (formats it does not know: +/// every mip of every array slice and sample, packed, 64 KiB aligned), +/// rounded up to the alignment. fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> { + if desc.dimension != BUFFER + && let Some(t) = texture_layout(desc) + { + // As the console: the layout's own alignment unless more is asked + // (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto + // VI keeps these sizes in its texture tables, and its streaming + // asserts when they disagree with the streamed layout. + let alignment = desc.alignment.max(t.alignment); + if !alignment.is_power_of_two() { + return None; + } + return Some(AllocationInfo { + size: t.size.checked_next_multiple_of(alignment)?, + alignment, + }); + } let bytes = if desc.dimension == BUFFER { desc.width } else { @@ -171,6 +226,72 @@ fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> { }) } +/// A format as the host has it. The console's 16-bit depth with stencil +/// (and its typeless views) has no PC format: the 24-bit ones stand in. +pub(crate) fn pc_format(format: u32) -> u32 { + match format { + 118 => 45, + 119 => 46, + 120 => 47, + other => other, + } +} + +/// The typeless format of a format's family (itself if it has none). +pub(crate) fn family(format: u32) -> u32 { + const FAMILIES: [(u32, u32); 22] = [ + (1, 4), + (5, 8), + (9, 14), + (15, 18), + (19, 22), + (23, 25), + (27, 32), + (33, 38), + (39, 43), + (44, 47), + (48, 52), + (53, 59), + (60, 65), + (70, 72), + (73, 75), + (76, 78), + (79, 81), + (82, 84), + (90, 91), + (92, 93), + (94, 96), + (97, 99), + ]; + match format { + 87 => 90, + 88 => 92, + f => FAMILIES + .iter() + .find(|&&(first, last)| (first..=last).contains(&f)) + .map_or(f, |&(first, _)| first), + } +} + +/// sRGB formats and their linear twins. +pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; + +/// The format a view of a title texture must name when its host copy is +/// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if +/// the host copy is typed. +pub(crate) fn view_format(this: This) -> Option<u32> { + let own = pc_format(resource(this).desc.format); + let host = host_resource(this)?; + // SAFETY: a live resource. + let format = unsafe { host.GetDesc() }.Format.0 as u32; + (format != own).then_some(own) +} + +/// Depth formats with their typeless family: depth textures that shaders +/// read are made typeless on the host, which only allows views of +/// typeless depth resources. +pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)]; + /// Mip levels, the full chain for 0. fn mip_count(desc: &ResourceDesc) -> u32 { let depth = if desc.dimension == TEXTURE_3D { @@ -342,34 +463,170 @@ pub(crate) extern "system" fn allocation_info( // SAFETY: the title passes `count` descriptions. unsafe { std::slice::from_raw_parts(descs, count as usize) } }; + // SAFETY: the caller passes room for the value. + unsafe { out.write(place(descs.iter(), |_, _| ())) }; + out +} + +/// The newer description: the plain one, then a sampler feedback mip +/// region (width, height, depth). +#[repr(C)] +pub(crate) struct ResourceDesc1 { + desc: ResourceDesc, + mip_region: [u32; 3], +} +const _: () = assert!(size_of::<ResourceDesc1>() == 72); + +/// Where one resource goes in [`allocation_info2`]'s placement. +#[repr(C)] +pub(crate) struct AllocationInfo1 { + offset: u64, + alignment: u64, + size: u64, +} + +/// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer +/// descriptions, also telling where each resource goes. +pub(crate) extern "system" fn allocation_info2( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc1, + each: *mut AllocationInfo1, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + let total = place(descs.iter().map(|d| &d.desc), |i, info| { + if !each.is_null() { + // SAFETY: the title passes room for `count` entries. + unsafe { each.add(i).write(info) }; + } + }); + // SAFETY: the caller passes room for the value. + unsafe { out.write(total) }; + out +} + +/// Resources placed one after another: the whole footprint, telling `each` +/// where every resource goes. Unknown sizes give the documented `u64::MAX`. +fn place<'a>( + descs: impl Iterator<Item = &'a ResourceDesc>, + mut each: impl FnMut(usize, AllocationInfo1), +) -> AllocationInfo { let mut total = AllocationInfo { size: 0, alignment: KIB_64, }; - for desc in descs { + for (i, desc) in descs.enumerate() { let Some(one) = footprint(desc) else { tracing::warn!(?desc, "no size for this resource"); - total = AllocationInfo { + each( + i, + AllocationInfo1 { + offset: u64::MAX, + alignment: 0, + size: u64::MAX, + }, + ); + return AllocationInfo { size: u64::MAX, alignment: 0, }; - break; }; - total.size = total.size.next_multiple_of(one.alignment) + one.size; + tracing::debug!(?desc, ?one, "allocation info"); + let offset = total.size.next_multiple_of(one.alignment); + each( + i, + AllocationInfo1 { + offset, + alignment: one.alignment, + size: one.size, + }, + ); + total.size = offset + one.size; total.alignment = total.alignment.max(one.alignment); } - // SAFETY: the caller passes room for the value. - unsafe { out.write(total) }; - out + total } /// Zeroed host memory standing in for GPU memory. pub(crate) struct Memory { ptr: NonNull<u8>, layout: Layout, + /// Set when the memory came from the title's allocator, with these + /// allocation attributes (it goes back there). + attributes: Option<u64>, +} + +pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; +pub type FreeRoutine = extern "system" fn(*mut c_void, u64); +static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new(); + +/// Committed resources get their memory from the title's general +/// allocator, as on the console, where titles hook it to place graphics +/// memory themselves (Grand Theft Auto VI places its back buffers in a +/// block of its own and checks they fill it). The runtime names it before +/// the device exists. +pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) { + let _ = ALLOCATOR.set((alloc, free)); +} + +/// Maps the physical pages behind one range of title memory at another, +/// `(to, from, len)` (`from` 0 unmaps); false on failure. +pub type PageMapper = fn(u64, u64, u64) -> bool; +static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new(); + +/// The runtime's page mapper, for the queues' page-mapping copies (memory +/// is the runtime's, as on the console). +pub fn use_page_mapper(mapper: PageMapper) { + let _ = PAGE_MAPPER.set(mapper); +} + +pub(crate) fn page_mapper() -> Option<PageMapper> { + PAGE_MAPPER.get().copied() +} + +/// Allocation attributes for resource memory: allocator id, page size +/// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2 +/// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only +/// heaps, cacheable for the CPU-visible ones). +/// shortcut: the console runtime's own choice of page size and memory type +/// is not known; this is the plausible one. +fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 { + const GRAPHICS_ALLOCATOR: u64 = 128 << 16; + const DEFAULT_HEAP: u32 = 1; + let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 }; + let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 }; + let alignment = u64::from(info.alignment.max(1).trailing_zeros()); + GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29 } impl Memory { + /// A committed resource's memory: from the title's allocator if the + /// runtime named one, else our own; zeroed either way. + fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> { + let Some(&(alloc, _)) = ALLOCATOR.get() else { + return Memory::new(info); + }; + let layout = Layout::from_size_align(info.size as usize, info.alignment as usize) + .map_err(|_| E_INVALIDARG)?; + let attributes = resource_attributes(info, heap_kind); + let ptr = + NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?; + // SAFETY: the allocator handed out `size` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + Ok(Memory { + ptr, + layout, + attributes: Some(attributes), + }) + } + /// `size` zeroed bytes aligned to `alignment` (a power of two). pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> { Memory::new(AllocationInfo { size, alignment }) @@ -388,14 +645,21 @@ impl Memory { .ok_or(E_INVALIDARG)?; // SAFETY: the size is non-zero. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; - Ok(Memory { ptr, layout }) + Ok(Memory { + ptr, + layout, + attributes: None, + }) } } impl Drop for Memory { fn drop(&mut self) { - // SAFETY: allocated in `new` with this layout. - unsafe { dealloc(self.ptr.as_ptr(), self.layout) }; + match (self.attributes, ALLOCATOR.get()) { + (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes), + // SAFETY: allocated in `new` with this layout. + _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) }, + } } } @@ -458,7 +722,12 @@ extern "system" fn heap_desc(this: This, out: *mut HeapDesc) { /// to. enum Backing { Committed(Memory), - Placed { heap: This, offset: u64 }, + Placed { + heap: This, + offset: u64, + }, + /// Memory the title mapped itself, at this address. + Address(*mut u8), } impl Drop for Backing { @@ -499,6 +768,15 @@ pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u (before != wanted).then(|| (host.as_raw(), before)) } +/// Sets the state the host texture is in after a submission; returns the +/// one it was in. +#[cfg(windows)] +pub(crate) fn swap_host_state(this: This, state: u32) -> u32 { + resource(this) + .host_state + .swap(state, std::sync::atomic::Ordering::Relaxed) +} + /// The host GPU's copy of a title resource, if it has one. #[cfg(windows)] pub(crate) fn host_resource<'a>( @@ -528,6 +806,35 @@ fn host_texture( d.layout = 0; d.alignment = 0; d.flags &= PC_FLAGS; + // PC refuses depth targets that are also unordered-access (the console + // allows both; Grand Theft Auto VI's shadow maps ask for it). + // shortcut: the host copy loses UAV use; give it a second view-only + // copy if draws write it as a UAV. + const DEPTH: u32 = 2; + const UNORDERED: u32 = 4; + if d.flags & DEPTH != 0 { + d.flags &= !UNORDERED; + } + d.format = pc_format(d.format); + const DENY_SHADER_RESOURCE: u32 = 8; + if d.flags & DENY_SHADER_RESOURCE == 0 + && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) + { + d.format = typeless; + } + // The host has no sRGB unordered access: such textures are typeless, + // their unordered access views plain UNORM. + if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { + d.format = family(d.format); + } + // The clear value names the format too: format, then color or depth + // and stencil (5 words). + let clear_value = (!clear.is_null()).then(|| { + // SAFETY: the title passes a whole clear value. + let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; + value[0] = pc_format(value[0]); + value + }); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() @@ -540,18 +847,34 @@ fn host_texture( &heap, D3D12_HEAP_FLAG_NONE, (&raw const d).cast(), - D3D12_RESOURCE_STATES(crate::host::texture_state(state) as i32), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), // The same layout: format, then color or depth and stencil. - (!clear.is_null()).then_some(clear.cast()), + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), &mut texture, ) }; if let Err(e) = made { tracing::warn!(error = %e, desc = ?d, "no host texture"); } + if let Some(t) = &texture { + crate::host::name(t, || { + format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + }); + } texture } +/// A texture's console memory and description; `None` for buffers. +pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) +} + /// A buffer's host memory and size; `None` for textures. pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { if this.is_null() { @@ -573,6 +896,7 @@ impl Resource { .as_ptr() .add(offset as usize) }, + Backing::Address(at) => at, } } } @@ -596,6 +920,8 @@ fn hand_out_resource( ) -> HRESULT { #[cfg(not(windows))] let _ = (state, clear); + #[cfg(windows)] + let host = host_texture(&desc, state, clear); let resource = Box::new(Resource { object: Object::new(&RESOURCE_FUNCTIONS), desc, @@ -603,13 +929,35 @@ fn hand_out_resource( heap_flags, backing, #[cfg(windows)] - host: host_texture(&desc, state, clear), + host_state: host + .as_ref() + .map_or(0, |t| crate::host::legal_state(t, crate::host::texture_state(state))) + .into(), #[cfg(windows)] - host_state: crate::host::texture_state(state).into(), + host, }); + #[cfg(windows)] + if desc.dimension == BUFFER { + let at = std::ptr::from_ref::<Resource>(&resource) as usize; + crate::shadow::register(at, resource.data() as u64, desc.width); + } object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out) } +#[cfg(windows)] +impl Drop for Resource { + fn drop(&mut self) { + crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize); + crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize); + if self.desc.dimension == BUFFER { + crate::shadow::unregister( + std::ptr::from_ref::<Resource>(self) as usize, + self.data() as u64, + ); + } + } +} + pub(crate) extern "system" fn create_committed( _: This, heap: *const HeapProperties, @@ -634,7 +982,7 @@ pub(crate) extern "system" fn create_committed( heap = heap.kind, "committed resource" ); - let memory = match Memory::new(info) { + let memory = match Memory::for_resource(info, heap.kind) { Ok(memory) => memory, Err(hr) => return hr, }; @@ -650,6 +998,159 @@ pub(crate) extern "system" fn create_committed( ) } +/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls +/// (title+0x193e1b4: its back buffers, heap flag "allow display"): the +/// committed resource creation of the enhanced-barrier interfaces, +/// `(heap, heap flags, desc1, initial layout, clear value, protected +/// session, castable format count, castable formats, iid, out)`. The host +/// copy starts in the common state, as layouts are not tracked. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn create_committed3( + this: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + _layout: u32, + clear: *const c_void, + _protected: This, + _castable_count: u32, + _castable: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + const COMMON: u32 = 0; + create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out) +} + +/// Registered page pools (64 KiB pages the title maps into tiled +/// resources by page index): first address and page count; a handle is an +/// index plus one, a removed pool leaves `None`. +static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new()); + +fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> { + PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method 0x250: `(address, page count, handle out)`. +pub(crate) extern "system" fn register_page_pool( + _: This, + address: u64, + pages: u32, + out: *mut usize, +) -> HRESULT { + if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) { + return E_INVALIDARG; + } + tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool"); + let mut pools = page_pools(); + pools.push(Some((address, pages))); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(pools.len()) }; + S_OK +} + +/// Device method 0x258. +pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT { + match page_pools().get_mut(handle.wrapping_sub(1)) { + Some(pool @ Some(_)) => { + *pool = None; + S_OK + } + _ => E_INVALIDARG, + } +} + +/// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` +/// additions. From Grand Theft Auto VI's call: a resource at a virtual +/// address the title mapped itself, `(address, desc1, initial barrier +/// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with +/// enhanced barriers. GPU addresses are CPU addresses, so the resource is +/// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain +/// description; its sampler feedback region is not needed. +pub(crate) extern "system" fn create_at_address( + _: This, + address: u64, + desc: *const ResourceDesc, + layout: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if address == 0 { + return E_INVALIDARG; + } + tracing::debug!( + address = format_args!("{address:#x}"), + dimension = desc.dimension, + width = desc.width, + layout, + "resource at an address" + ); + const COMMON: u32 = 0; + const DEFAULT: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 1, + visible_nodes: 1, + }; + hand_out_resource( + desc, + DEFAULT, + 0, + Backing::Address(address as *mut u8), + COMMON, + clear, + iid, + out, + ) +} + +/// Textures the title placed in its own memory and views without a +/// resource object (device 0x230, Grand Theft Auto VI's streamed and +/// interface textures), by address and description: a resource at that +/// address, made the first time a draw reads one. +/// shortcut: never released (one host texture per distinct address and +/// description viewed); release them when the title unmaps or reuses the +/// memory once streaming grows VRAM use. +#[cfg(windows)] +static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// The resource for a texture placed at `address` with the resource +/// description `desc` (as words), made on first use. +#[cfg(windows)] +pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> { + let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&r) = map.get(&(address, *desc)) { + return Some(r as This); + } + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + let mut out = std::ptr::null(); + let made = create_at_address( + std::ptr::null(), + address, + &d, + 0, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut out, + ); + if made != S_OK { + return None; + } + map.insert((address, *desc), out as usize); + resource(out).host.is_some().then_some(out) +} + pub(crate) extern "system" fn create_placed( _: This, heap: This, @@ -725,8 +1226,59 @@ extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { unsafe { out.write(resource(this).desc) }; } } +/// Device method `GetCustomHeapProperties`, returning its struct through a +/// hidden first argument: what a standard heap type is as a custom heap. +/// Memory is unified and cache-coherent (as the architecture query says), +/// so every type is in pool L0, default heaps are not CPU-visible and the +/// others are write-back. +pub(crate) extern "system" fn custom_heap_properties( + out: *mut HeapProperties, + _: This, + nodes: u32, + kind: u32, +) -> *mut HeapProperties { + const CUSTOM: u32 = 4; + const NOT_AVAILABLE: u32 = 1; + const WRITE_BACK: u32 = 3; + const L0: u32 = 1; + let nodes = nodes.max(1); + let cpu_pages = match kind { + 1 => NOT_AVAILABLE, + 2 | 3 => WRITE_BACK, + _ => 0, + }; + let properties = HeapProperties { + kind: CUSTOM, + cpu_pages, + pool: if cpu_pages == 0 { 0 } else { L0 }, + creation_nodes: nodes, + visible_nodes: nodes, + }; + // SAFETY: the title passes room for the result (null is tolerated). + if let Some(out) = unsafe { out.as_mut() } { + *out = properties; + } + out +} + extern "system" fn gpu_address(this: This) -> u64 { - resource(this).data() as u64 + let r = resource(this); + let at = r.data() as u64; + // The console's GPU addresses fit in 40 bits; its ray-tracing builder + // refuses others (diagnostics: which memory breaks that). + #[cfg(feature = "diagnostics")] + if at >> 40 != 0 { + static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; + let backing = match r.backing { + Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes), + Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"), + Backing::Address(_) => "at a title address".into(), + }; + ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| { + tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits") + }); + } + at } extern "system" fn heap_properties( this: This, @@ -747,8 +1299,8 @@ extern "system" fn heap_properties( } /// IUnknown 3, object 4, device child 1, heap 1. -static HEAP_FUNCTIONS: Table<9> = { - let mut f = object::d3d12_object(object::missing_table::<HEAP, 9>()); +static HEAP_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>()); f[0] = heap_query as *const (); f[2] = heap_release as *const (); f[7] = object::parent_device as *const (); // 0x38 @@ -758,8 +1310,8 @@ static HEAP_FUNCTIONS: Table<9> = { /// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3 /// console ones). -static RESOURCE_FUNCTIONS: Table<18> = { - let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 18>()); +static RESOURCE_FUNCTIONS: Table<32> = { + let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>()); f[0] = resource_query as *const (); f[2] = resource_release as *const (); f[7] = object::parent_device as *const (); // 0x38 @@ -856,15 +1408,114 @@ mod tests { ); } + #[test] + fn device_setup_heap_properties_and_resources_at_addresses() { + let device = crate::device::device(); + // GetCustomHeapProperties (0xd0): the struct comes back through the + // hidden first argument, which is also returned. + type Custom = + extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties; + let mut p = PROPERTIES; + let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2); + assert_eq!(back, &raw mut p); + assert_eq!( + ( + p.kind, + p.cpu_pages, + p.pool, + p.creation_nodes, + p.visible_nodes + ), + (4, 3, 1, 1, 1), + "upload: custom, write-back, L0" + ); + slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1); + assert_eq!(p.cpu_pages, 1, "default: not CPU-visible"); + + // 0x428: a buffer over memory the title owns, as GTA VI asks. + type At = extern "system" fn( + This, + u64, + *const ResourceDesc, + u32, + *const c_void, + *const Iid, + *mut This, + ) -> HRESULT; + let memory = vec![0u8; 0x1_0000]; + let address = memory.as_ptr() as u64; + let mut r = std::ptr::null(); + let create = slot::<At>(device, 0x428); + let desc = buffer(0x1_0000); + let null = std::ptr::null(); + assert_eq!( + create( + device, + address, + &desc, + u32::MAX, + null, + &RESOURCE_IIDS[0], + &mut r + ), + 0 + ); + assert_eq!(slot::<Address>(r, 0x58)(r), address); + assert_eq!(slot::<Release>(r, 0x10)(r), 0); + // The title's memory is still there after the release. + assert_eq!(memory[0xffff], 0); + assert_ne!( + create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r), + 0 + ); + } + #[test] fn sizes_cover_every_mip() { let size = |d: &ResourceDesc| footprint(d).map(|i| i.size); assert_eq!(size(&buffer(256)), Some(KIB_64)); - // 256x256 RGBA8, full chain: 4/3 of 256 KiB, rounded up. - assert_eq!(size(&texture(256, 256, 28, 0)), Some(384 << 10)); + // Textures take their console layout and its alignment (4 KiB + // standard swizzle when the description leaves it to the library): + // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on + // the console. + let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size; + let rgba = texture(256, 256, 28, 0); + assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096))); + let bc7 = footprint(&texture(512, 512, 98, 10)); + let console = AllocationInfo { + size: 0x56000, + alignment: 0x1000, + }; + assert_eq!(bc7, Some(console)); + assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip"); // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB. assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10)); assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format"); + // Linear layout (1) and an explicit mode (64 KiB display, 0x10a). + let linear = ResourceDesc { + layout: 1, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&linear).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 0 + ); + let display = ResourceDesc { + layout: 0x10a, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&display).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 10 + ); let mut info = AllocationInfo { size: 0, @@ -875,7 +1526,7 @@ mod tests { assert_eq!( info, AllocationInfo { - size: (64 + 384) << 10, + size: KIB_64 + size(&descs[1]).unwrap(), alignment: KIB_64 } ); diff --git a/crates/victory-gpu/src/root.rs b/crates/victory-gpu/src/root.rs index ce25137..0c6b698 100644 --- a/crates/victory-gpu/src/root.rs +++ b/crates/victory-gpu/src/root.rs @@ -1,12 +1,12 @@ //! Root signatures. //! -//! Serializing goes to the host's `D3D12SerializeRootSignature`: the -//! description is laid out as on PC, and the blob it returns works as the -//! console's, whose two methods sit in the same slots. The console's own -//! flags (bit 24 and up) are dropped first. +//! Serializing goes to the host's `D3D12SerializeRootSignature` (or its +//! versioned form): the description is laid out as on PC, and the blob it +//! returns works as the console's, whose two methods sit in the same slots. +//! The console's own flags (bit 24 and up) are dropped first. #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::ffi::c_void; +use std::ffi::{CStr, c_void}; use std::sync::OnceLock; use crate::object::{ @@ -37,23 +37,32 @@ pub struct Desc { flags: u32, } +/// Every version's description starts with the fields of [`Desc`]. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VersionedDesc { + version: u32, + desc: Desc, +} + type Serialize = unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; +type SerializeVersioned = + unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT; -/// The host's serializer, from `d3d12.dll` in System32. -fn host_serializer() -> Option<Serialize> { - static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); - let address = *FUNCTION.get_or_init(|| { +/// An export of the host's `d3d12.dll` in System32, looked up once. +fn host_export(cache: &OnceLock<Option<usize>>, name: &CStr) -> Option<usize> { + *cache.get_or_init(|| { #[cfg(windows)] { use windows_sys::Win32::System::LibraryLoader::{ GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, }; - let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect(); + let dll: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect(); // SAFETY: a NUL-terminated name; System32 only. let module = unsafe { LoadLibraryExW( - name.as_ptr(), + dll.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32, ) @@ -62,14 +71,24 @@ fn host_serializer() -> Option<Serialize> { return None; } // SAFETY: a loaded module and a NUL-terminated name. - unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) } - .map(|f| f as usize) + unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize) } #[cfg(not(windows))] None - }); - // SAFETY: the export has this signature. - address.map(|a| unsafe { std::mem::transmute::<usize, Serialize>(a) }) + }) +} + +fn without_console_flags(desc: Desc) -> Desc { + if desc.flags & CONSOLE_FLAGS != 0 { + tracing::debug!( + flags = format_args!("{:#x}", desc.flags), + "console root signature flags dropped" + ); + } + Desc { + flags: desc.flags & !CONSOLE_FLAGS, + ..desc + } } /// `d3d12_xs!D3D12SerializeRootSignature`. @@ -83,22 +102,68 @@ pub extern "system" fn serialize( let Some(&desc) = (unsafe { desc.as_ref() }) else { return E_INVALIDARG; }; - if desc.flags & CONSOLE_FLAGS != 0 { - tracing::debug!( - flags = format_args!("{:#x}", desc.flags), - "console root signature flags dropped" - ); - } - let desc = Desc { - flags: desc.flags & !CONSOLE_FLAGS, - ..desc - }; - let Some(serialize) = host_serializer() else { + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") else { tracing::warn!("no host d3d12.dll to serialize root signatures"); return E_NOTIMPL; }; - // SAFETY: the host function takes the same arguments the title passed. - unsafe { serialize(&desc, version, blob, error) } + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { + std::mem::transmute::<usize, Serialize>(address)( + &without_console_flags(desc), + version, + blob, + error, + ) + } +} + +/// `d3d12_xs!D3D12SerializeVersionedRootSignature`. +pub extern "system" fn serialize_versioned( + desc: *const VersionedDesc, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + let desc = VersionedDesc { + desc: without_console_flags(desc.desc), + ..desc + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::<usize, SerializeVersioned>(address)(&desc, blob, error) } +} + +type Deserialize = + unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT; + +/// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the +/// host's serialization, so the host's deserializer reads them, and its +/// object (IUnknown, then the description getter) is laid out as the +/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id. +pub extern "system" fn create_deserializer( + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut *mut c_void, +) -> HRESULT { + if blob.is_null() || out.is_null() { + return E_INVALIDARG; + } + static FUNCTION: OnceLock<Option<usize>> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else { + tracing::warn!("no host d3d12.dll to deserialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::<usize, Deserialize>(address)(blob, size, iid, out) } } #[repr(C)] @@ -139,8 +204,8 @@ extern "system" fn release(this: This) -> u32 { } /// IUnknown 3, object 4, device child 1. -static FUNCTIONS: Table<8> = { - let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 8>()); +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 @@ -193,4 +258,67 @@ mod tests { assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0); slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); } + + /// The host's deserializer reads our blobs back (the upscaler's call). + #[cfg(windows)] + #[test] + fn our_blobs_deserialize_on_the_host() { + use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer; + use windows::core::Interface; + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 1, + }, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::<Object>(); + let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob); + let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob); + let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes(); + let iid = guid( + u32::from_be_bytes(iid[0..4].try_into().unwrap()), + u16::from_be_bytes(iid[4..6].try_into().unwrap()), + u16::from_be_bytes(iid[6..8].try_into().unwrap()), + iid[8..16].try_into().unwrap(), + ); + let mut out = std::ptr::null_mut(); + assert_eq!(create_deserializer(data, size, &iid, &mut out), S_OK); + // SAFETY: the host handed out this interface. + let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) }; + // SAFETY: valid while the deserializer lives. + let read = unsafe { &*deserializer.GetRootSignatureDesc() }; + assert_eq!((read.NumParameters, read.Flags.0), (0, 1)); + slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); + } + + /// Version 1.0 through the versioned entry point, with a console flag. + #[cfg(windows)] + #[test] + fn versioned_descriptions_serialize_on_the_host() { + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0200_0001, + }, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::<Object>(); + assert!(slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob) > 0); + slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob); + assert_eq!( + serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error), + E_INVALIDARG + ); + } } diff --git a/crates/victory-gpu/src/sampler.rs b/crates/victory-gpu/src/sampler.rs new file mode 100644 index 0000000..ee95da3 --- /dev/null +++ b/crates/victory-gpu/src/sampler.rs @@ -0,0 +1,119 @@ +//! Samplers as the host describes them, from the console's sampler +//! description (`CreateSamplerX`), which names the hardware's sampler +//! fields. (Immediate samplers in shader code come decoded with the +//! translation.) + +use windows::Win32::Graphics::Direct3D12::*; + +/// The fields both forms share. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Fields { + /// Point 0, bilinear 1, anisotropic point 2, anisotropic bilinear 3. + mag: u32, + min: u32, + /// None 0, point 1, linear 2. + mip: u32, + /// Plain 0, minimum 1, maximum 2. + mode: u32, + /// Host address modes. + address: [u32; 3], + anisotropy: u32, + /// Host comparison function. + compare: u32, + min_lod: f32, + max_lod: f32, + bias: f32, + border: [f32; 4], +} + +impl Fields { + fn host(&self) -> D3D12_SAMPLER_DESC { + let linear = |f: u32| u32::from(f == 1 || f == 3); + let aniso = self.mag >= 2 || self.min >= 2; + // The console compares when the instruction says so, with the + // sampler's function; the host needs a comparison sampler for that. + // A sampler given a real test (less ... greater-or-equal) is one; + // never, always and none are plain samplers. + const LESS: u32 = 2; + const GREATER_EQUAL: u32 = 7; + let compares = (LESS..=GREATER_EQUAL).contains(&self.compare); + let reduction = match self.mode { + 1 => 2, + 2 => 3, + _ => u32::from(compares), + }; + let filter = if aniso { + 0x55 + } else { + linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) + }; + D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER((reduction << 7 | filter) as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), + MipLODBias: self.bias, + MaxAnisotropy: if aniso { + self.anisotropy.clamp(1, 16) + } else { + 1 + }, + ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), + BorderColor: self.border, + MinLOD: self.min_lod, + // Without a mip filter the console samples mip 0 only. + MaxLOD: if self.mip == 0 { + self.min_lod + } else { + self.max_lod + }, + } + } +} + +/// The console's sampler description (27 words): flags, magnification, +/// minification, mip and depth filters, filter mode, three address modes, +/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias +/// and threshold, comparison, border color, then tuning words. +pub(crate) fn console(words: &[u32; 27]) -> D3D12_SAMPLER_DESC { + let f = |i: usize| f32::from_bits(words[i]); + Fields { + mag: words[1], + min: words[2], + mip: words[3], + mode: words[5], + address: [words[6], words[7], words[8]], + min_lod: f(9), + max_lod: f(10), + bias: f(11), + anisotropy: words[13], + compare: words[16], + border: [f(17), f(18), f(19), f(20)], + } + .host() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_descriptions_decode() { + let mut w = [0u32; 27]; + w[1] = 1; // bilinear magnification + w[2] = 0; // point minification + w[3] = 2; // linear mips + w[6..9].copy_from_slice(&[3, 3, 3]); + w[10] = 1000.0f32.to_bits(); + let d = console(&w); + assert_eq!(d.Filter.0, 0x5, "min point, mag and mip linear"); + assert_eq!(d.AddressW, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + assert_eq!(d.MaxLOD, 1000.0); + // A less-or-equal test makes a comparison sampler; never does not. + w[16] = 4; + assert_eq!(console(&w).Filter.0, 0x85); + assert_eq!(console(&w).ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + w[16] = 1; + assert_eq!(console(&w).Filter.0, 0x5); + } +} diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs new file mode 100644 index 0000000..b52d7f0 --- /dev/null +++ b/crates/victory-gpu/src/shader_cache.rs @@ -0,0 +1,347 @@ +//! Translated shaders kept on disk (decision 0003): under the configured +//! cache folder, keyed by the container's content and by the VIctory build +//! that translated it (the BLAKE3 of our executable), so a rebuilt +//! translator never serves an old translation. Entries go through +//! `victory-pipeline`'s content-addressed cache, which writes them +//! atomically; an entry that does not read back is translated again. +//! +//! The entry is our own encoding of [`HostShader`]: a field added to it +//! must be added to [`encode`] and [`decode`] too (entries of older builds +//! are ignored anyway). + +use std::path::PathBuf; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use victory_pipeline::{Cache, Converter}; +use victory_shader::emit::{HostShader, StaticSampler, UserData}; +use victory_shader::{HwStage, RootType}; + +static CACHE: OnceLock<Cache> = OnceLock::new(); +static HITS: AtomicU64 = AtomicU64::new(0); +static MISSES: AtomicU64 = AtomicU64::new(0); + +/// Keeps translated shaders in `dir` from now on. +pub fn use_shader_cache(dir: PathBuf) { + match Cache::open(dir) { + Ok(cache) => { + let _ = CACHE.set(cache); + } + Err(e) => tracing::warn!(error = %e, "no shader cache"), + } +} + +/// Shaders found in the cache and translated since the start. +pub(crate) fn counts() -> (u64, u64) { + (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) +} + +/// What identifies this build: the BLAKE3 of our executable file. +fn build() -> &'static [u8; 32] { + static BUILD: OnceLock<[u8; 32]> = OnceLock::new(); + BUILD.get_or_init(|| { + let exe = std::env::current_exe().and_then(std::fs::read); + match exe { + Ok(bytes) => *blake3::hash(&bytes).as_bytes(), + Err(e) => { + // Without it no entry can be trusted: a fresh key per run. + tracing::warn!(error = %e, "cannot read our executable; shader cache unused"); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + *blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes() + } + } + }) +} + +/// The translation of a console shader container, from the cache when +/// there is one. +pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> { + let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string()); + match CACHE.get() { + Some(cache) => cached(cache, build(), container, translate), + None => translate(container), + } +} + +/// The cache entry's converter: the build and the container in, the +/// encoded translation out. `ran` tells a miss from a hit. +struct Translate<F> { + translate: F, + ran: AtomicBool, +} + +impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> { + fn id(&self) -> &'static str { + "shader.dxil" + } + fn version(&self) -> u32 { + // The build fingerprint in the input does the versioning. + 1 + } + fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> { + self.ran.store(true, Ordering::Relaxed); + let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; + Ok(encode(&shader)) + } +} + +fn cached( + cache: &Cache, + build: &[u8; 32], + container: &[u8], + translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync, +) -> Result<HostShader, String> { + let input = [&build[..], container].concat(); + let converter = Translate { + translate, + ran: AtomicBool::new(false), + }; + for _ in 0..2 { + let path = cache + .get_or_convert(&converter, &input) + .map_err(|e| format!("{e:#}"))?; + if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { + let (counter, what) = if converter.ran.load(Ordering::Relaxed) { + (&MISSES, "translated and cached") + } else { + (&HITS, "from the cache") + }; + counter.fetch_add(1, Ordering::Relaxed); + tracing::debug!(path = %path.display(), "shader {what}"); + return Ok(shader); + } + tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again"); + let _ = std::fs::remove_file(&path); + } + MISSES.fetch_add(1, Ordering::Relaxed); + (converter.translate)(container) +} + +const MAGIC: &[u8; 4] = b"VSH1"; +const STAGES: [HwStage; 8] = [ + HwStage::Ls, + HwStage::Hs, + HwStage::Es, + HwStage::Gs, + HwStage::Vs, + HwStage::Ps, + HwStage::Ms, + HwStage::Cs, +]; + +fn root_code(r: RootType) -> u32 { + match r { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 2, + RootType::ImmediateSampler => 3, + RootType::ResourceHeap => 4, + RootType::SamplerHeap => 5, + RootType::Other(x) => 6 + x, + } +} + +fn root_type(code: u32) -> RootType { + match code { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + x => RootType::Other(x - 6), + } +} + +/// Little-endian words and length-prefixed lists. +fn encode(s: &HostShader) -> Vec<u8> { + let mut out = MAGIC.to_vec(); + let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes()); + let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32; + word(&mut out, stage); + word(&mut out, s.dxil.len() as u32); + out.extend(&s.dxil); + word(&mut out, s.user_data.len() as u32); + for u in &s.user_data { + for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { + word(&mut out, v); + } + } + word(&mut out, s.samplers.len() as u32); + for sampler in &s.samplers { + for &v in sampler { + word(&mut out, v); + } + } + word(&mut out, s.static_samplers.len() as u32); + for t in &s.static_samplers { + let [u, v, w] = t.address; + let words = [ + t.filter, + u, + v, + w, + t.mip_lod_bias.to_bits(), + t.max_anisotropy, + t.comparison, + t.border, + t.min_lod.to_bits(), + t.max_lod.to_bits(), + ]; + for v in words { + word(&mut out, v); + } + } + for slots in [&s.root_cbvs, &s.root_srvs] { + word(&mut out, slots.len() as u32); + out.extend(slots); + } + out +} + +fn decode(bytes: &[u8]) -> Option<HostShader> { + struct Reader<'a>(&'a [u8]); + impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let (head, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(head) + } + fn word(&mut self) -> Option<u32> { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + fn list(&mut self) -> Option<Vec<u8>> { + let n = self.word()? as usize; + Some(self.take(n)?.to_vec()) + } + } + let mut r = Reader(bytes); + if r.take(4)? != MAGIC { + return None; + } + let stage = *STAGES.get(r.word()? as usize)?; + let dxil = r.list()?; + let n = r.word()? as usize; + let mut user_data = Vec::with_capacity(n.min(256)); + for _ in 0..n { + user_data.push(UserData { + index: r.word()?, + slot: u8::try_from(r.word()?).ok()?, + root: root_type(r.word()?), + dword: r.word()?, + }); + } + let n = r.word()? as usize; + let mut samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]); + } + let n = r.word()? as usize; + let mut static_samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + static_samplers.push(StaticSampler { + filter: r.word()?, + address: [r.word()?, r.word()?, r.word()?], + mip_lod_bias: f32::from_bits(r.word()?), + max_anisotropy: r.word()?, + comparison: r.word()?, + border: r.word()?, + min_lod: f32::from_bits(r.word()?), + max_lod: f32::from_bits(r.word()?), + }); + } + let root_cbvs = r.list()?; + let root_srvs = r.list()?; + r.0.is_empty().then_some(HostShader { + stage, + dxil, + user_data, + samplers, + static_samplers, + root_cbvs, + root_srvs, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shader() -> HostShader { + HostShader { + stage: HwStage::Ps, + dxil: b"DXBC and the rest".to_vec(), + user_data: vec![UserData { + index: 8, + slot: 1, + root: RootType::Table, + dword: 0, + }], + samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]], + static_samplers: vec![StaticSampler::from_words([ + 0x400, + 0xc0_0000, + 0x18f0_0000, + 0, + ])], + root_cbvs: vec![2], + root_srvs: vec![0, 3], + } + } + + #[test] + fn translations_come_back_from_the_cache() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let build = [7u8; 32]; + let container = b"a console container".as_slice(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Ok(shader()) + }; + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); + + // Another build translates again. + assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 2); + + // A damaged entry is a miss, translated and stored again. + for e in walk(dir.path()) { + std::fs::write(e, b"VSH1 broken").unwrap(); + } + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + + // Failures are not stored. + let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned()); + assert!(cached(&cache, &build, b"other", fail).is_err()); + } + + fn walk(dir: &std::path::Path) -> Vec<PathBuf> { + let mut files = Vec::new(); + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.path().is_dir() { + files.extend(walk(&e.path())); + } else { + files.push(e.path()); + } + } + files + } + + #[test] + fn entries_round_trip_and_reject_damage() { + let bytes = encode(&shader()); + assert_eq!(decode(&bytes), Some(shader())); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + assert_eq!(decode(b"VSH0"), None); + } +} diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs new file mode 100644 index 0000000..e2793e1 --- /dev/null +++ b/crates/victory-gpu/src/shadow.rs @@ -0,0 +1,363 @@ +//! Host copies of title buffers (decision 0007, step 3 and "Copies of title +//! memory"). Title buffers are title memory, which the host GPU cannot +//! read, so a buffer a draw uses gets a persistent host buffer of its size +//! on first use (system memory shaders may also write), and the ranges each +//! submission reads (vertex, index and constant data, buffer views) are +//! brought up to date from title memory before it runs: the 64 KiB pages +//! the title wrote since they were last copied ([`crate::watch`]: write +//! watching, or read-only guards on physical-page views), all of it where +//! neither works. A title GPU address inside the buffer is the same offset +//! in its copy. Ranges shaders write go back to title memory after the +//! submission ([`Shadow::gpu_writes`]). +//! +//! shortcut: only the ranges draws are known to read are brought up to +//! date (vertex and index buffer views, constant buffers in tables, root +//! descriptors, buffer views in tables); buffers read through directly +//! indexed heaps keep what their first use copied. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::ID3D12Resource; + +use crate::host::{HostList, host}; +use crate::watch::PAGE; + +/// A title buffer's host copy. +pub(crate) struct Shadow { + pub(crate) buffer: ID3D12Resource, + data: *mut u8, + gpu: u64, + /// Where the title buffer starts and how long it is. + start: u64, + len: u64, + /// Per page of title memory from `start`'s on: the write-watch asking + /// after which it was last copied (0: never). + copied: Mutex<Vec<u64>>, + /// Whether the memory is write-watched: unknown, yes, no. + watched: AtomicU8, + /// Ranges shaders of a submission not yet copied back may be writing: + /// title memory there is older than the copy. + pending: Mutex<Vec<(usize, usize)>>, +} + +const NOT_WATCHED: u8 = 2; + +// SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping +// written only on the submitting thread. +unsafe impl Send for Shadow {} +// SAFETY: as above. +unsafe impl Sync for Shadow {} + +impl Shadow { + /// The host GPU address of a title address inside the buffer. + pub(crate) fn gpu(&self, address: u64) -> u64 { + self.gpu + (address - self.start) + } + + /// Bytes from a title address to the buffer's end. + pub(crate) fn left(&self, address: u64) -> u64 { + (self.start + self.len).saturating_sub(address) + } + + /// Offset of a title address from the buffer's start. + pub(crate) fn offset(&self, address: u64) -> u64 { + address - self.start + } + + /// Brings `len` bytes at `address` up to date when `list` is submitted, + /// and keeps the copy alive until the list is reset. + pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { + let len = len.min(self.start + self.len - address); + list.defer_refresh(self, address as usize, len as usize); + } + + fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { + let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + Shadow { + buffer, + data, + gpu, + start, + len, + copied: Mutex::new(vec![0; pages as usize]), + watched: AtomicU8::new(0), + pending: Mutex::default(), + } + } + + /// Shaders of `list` may write `[address, address + len)` of the copy + /// (unordered access): after the list's submission has run, the range + /// is copied back into title memory, where the title reads it; until + /// then no refresh copies title memory over it. Call after the + /// [`Shadow::refresh`] that gives the shaders the title's data. + /// + /// shortcut: the whole range goes back after every submission that + /// declares it; copy back only what shaders wrote (a GPU-side dirty + /// mask) if big unordered-access buffers make it slow. + pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) { + let len = len.min(self.left(address)); + list.defer_gpu_write(self, address as usize, len as usize); + } + + /// At submission: a submitted list's shaders write this range. + pub(crate) fn writing(&self, address: usize, len: usize) { + self.pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((address, address + len)); + } + + /// After the submission ran: copies what its shaders may have written + /// back into title memory (unmapped pages left alone). Pages wholly + /// written are current in this copy, so our own write is not taken for + /// the title's. + pub(crate) fn copy_back(&self, address: usize, len: usize) { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from < to { + // SAFETY: inside the mapping. + let at = unsafe { self.data.add(from - start) }; + crate::watch::writing(from, to - from); + crate::host::write_mapped(from as *mut u8, at, to - from); + let (first, last) = (from.div_ceil(PAGE), to / PAGE); + if first < last + && self.watched.load(Ordering::Relaxed) != NOT_WATCHED + && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true) + { + let base = start / PAGE; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + copied[first - base..last - base].fill(now); + } + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(i) = pending.iter().position(|&r| r == (address, address + len)) { + pending.swap_remove(i); + } + } + + /// At submission: copies what changed of `[address, address + len)` + /// since it was last copied (all of it if the memory is not + /// write-watched). Returns the bytes copied. + pub(crate) fn update(&self, address: usize, len: usize) -> usize { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return 0; + } + let mut busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .copied() + .filter(|&(a, e)| a < to && e > from) + .collect(); + if !busy.is_empty() { + // Rare: around ranges shaders are writing, everything is copied. + busy.sort_unstable(); + let (mut at, mut bytes) = (from, 0); + for (a, e) in busy { + if a > at { + bytes += self.copy(at, a); + } + at = at.max(e); + } + if at < to { + bytes += self.copy(at, to); + } + return bytes; + } + if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { + if let Some((now, written)) = crate::watch::writes(from, to, true) { + self.watched.store(1, Ordering::Relaxed); + let copied = self.copy_stale(from, to, now, &written); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from).saturating_sub(copied) as u64); + } + return copied; + } + self.watched.store(NOT_WATCHED, Ordering::Relaxed); + } + self.copy(from, to); + to - from + } + + /// Copies the pages of `[from, to)` written after their last copy + /// (`written`: last writes by page, in page order; `now`: this + /// asking), whole pages within the buffer. + fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { + let base = self.start as usize / PAGE; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let mut writes = written.iter().peekable(); + let (mut bytes, mut run) = (0, None); + let last = (to - 1) / PAGE; + for page in from / PAGE..=last { + let write = match writes.peek() { + Some(&&(p, w)) if p == page => { + writes.next(); + w + } + _ => 0, + }; + let at = &mut copied[page - base]; + if *at == 0 || write > *at { + *at = now; + run.get_or_insert(page); + } else if let Some(first) = run.take() { + bytes += self.copy(first * PAGE, page * PAGE); + } + } + if let Some(first) = run { + bytes += self.copy(first * PAGE, (last + 1) * PAGE); + } + bytes + } + + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. + fn copy(&self, from: usize, to: usize) -> usize { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (from.max(start), to.min(end)); + // SAFETY: inside the mapping (`from` and `to` are within the buffer). + let at = unsafe { self.data.add(from - start) }; + crate::host::copy_mapped(at, from as *const u8, to - from, false); + to - from + } +} + +struct Entry { + end: u64, + shadow: Option<Arc<Shadow>>, +} + +/// Title buffers by (start address, resource), with their copy once made. +static BUFFERS: Mutex<BTreeMap<(u64, usize), Entry>> = Mutex::new(BTreeMap::new()); + +fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A title buffer exists at `start` (`len` bytes). +pub(crate) fn register(resource: usize, start: u64, len: u64) { + buffers().insert( + (start, resource), + Entry { + end: start + len, + shadow: None, + }, + ); +} + +/// The title released it; lists that still hold its copy keep it alive. +pub(crate) fn unregister(resource: usize, start: u64) { + buffers().remove(&(start, resource)); +} + +/// The copy of the innermost title buffer holding `[address, address + +/// len)`, made on first use. +pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> { + let end = address.checked_add(len.max(1))?; + let mut map = buffers(); + let key = map + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end >= end) + .map(|(k, _)| *k); + let Some(key) = key else { + drop(map); + return loose(address, end); + }; + let entry = map.get_mut(&key)?; + if entry.shadow.is_none() { + let len = entry.end - key.0; + // Rounded up so that views ending in the buffer's last 256 bytes fit. + // Shaders write some buffers (unordered access), so not upload memory. + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?; + crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + if len >= 16 << 20 { + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "large buffer copied to the host" + ); + } else { + tracing::debug!( + start = format_args!("{:#x}", key.0), + len, + "buffer copied to the host" + ); + } + entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len))); + } + entry.shadow.clone() +} + +/// Titles also use memory outside any buffer object as GPU memory (Grand +/// Theft Auto VI's interface vertices, from its own allocator). Such memory +/// gets copies of the aligned windows it touches. +/// shortcut: copies of windows are never freed; key them to the title's +/// allocations if memory use grows. +const WINDOW: u64 = 4 << 20; + +/// Copies of title memory outside buffers, by (start, length). +static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new()); + +fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> { + let start = address & !(WINDOW - 1); + let len = end.next_multiple_of(WINDOW) - start; + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(shadow) = map.get(&(start, len)) { + return Some(shadow.clone()); + } + let (buffer, data) = host()?.shared_buffer(len)?; + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + tracing::debug!( + start = format_args!("{start:#x}"), + len, + "loose memory copied to the host" + ); + let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len)); + map.insert((start, len), shadow.clone()); + Some(shadow) +} + +/// For device-removed reports: the copy of title memory whose host range +/// starts closest below host GPU address `va`, and where `va` is in it. +pub(crate) fn near(va: u64) -> String { + let mut all: Vec<(u64, u64, u64)> = buffers() + .values() + .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len))) + .collect(); + all.extend( + LOOSE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .map(|s| (s.gpu, s.start, s.len)), + ); + let below = all.iter().filter(|c| c.0 <= va).max(); + let above = all.iter().filter(|c| c.0 > va).min(); + let mut text = match below { + Some(&(gpu, start, len)) => format!( + "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}", + va - gpu + ), + None => "; no title memory copy below it".into(), + }; + if let Some(&(gpu, start, len)) = above { + text.push_str(&format!( + "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)", + all.len() + )); + } + text +} diff --git a/crates/victory-gpu/src/signature.rs b/crates/victory-gpu/src/signature.rs index adeacdb..dd5b3d7 100644 --- a/crates/victory-gpu/src/signature.rs +++ b/crates/victory-gpu/src/signature.rs @@ -74,8 +74,8 @@ extern "system" fn release(this: This) -> u32 { } /// IUnknown 3, object 4, device child 1. -static FUNCTIONS: Table<8> = { - let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 8>()); +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 24>()); f[0] = query as *const (); f[2] = release as *const (); f[7] = object::parent_device as *const (); // 0x38 diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs new file mode 100644 index 0000000..0a8de93 --- /dev/null +++ b/crates/victory-gpu/src/texture.rs @@ -0,0 +1,303 @@ +//! Texture contents the title writes itself (decision 0007, "Texture +//! memory"): streamed pages, layout-library copies, movie frames, glyph +//! atlases. Such a texture lives in console memory in its tiled layout; +//! before a submission samples its host copy, the memory is detiled into a +//! staging buffer when its content changed, and the staging buffer is +//! copied into the host texture. +//! +//! "Changed" means a page of the memory was written since the last detiling +//! ([`crate::watch`]), in write-watched memory; in physical-page views, +//! which cannot be watched, a content hash of the whole memory at every +//! submission that samples it. +//! +//! shortcut: a change detiles the whole texture, not the pages written. +//! Only textures read through descriptor tables are brought up to date +//! (directly indexed views are not known per draw); plane 0 is uploaded +//! (every mip and array slice), depth and stencil planes are not. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::{HostList, host}; +use crate::object::This; + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A texture's upload state: the staging buffer laid out as the host +/// texture's subresources, and what was last detiled. +struct Staging { + buffer: ID3D12Resource, + data: *mut u8, + footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>, + rows: Vec<u32>, + layout: victory_formats::texture::Layout, + /// Mips per array slice. + mips: u32, + memory: *const u8, + last: Mutex<Last>, +} + +/// What a texture's staging buffer holds: the hash of the memory detiled +/// (memory not watched), or the write-watch asking it was detiled after, +/// with room to read the memory into. +#[derive(Default)] +struct Last { + hash: Option<blake3::Hash>, + asked: u64, + read: Vec<u8>, +} + +// SAFETY: the staging mapping is written only at submission, under +// `last`'s lock; the title memory is only read. +unsafe impl Send for Staging {} +// SAFETY: as above. +unsafe impl Sync for Staging {} + +static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None); + +/// Textures the host GPU wrote by a copy or resolve: their contents are on +/// the host, not in title memory, which stays as it was. +static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None); + +/// A host copy or resolve writes `resource`. +pub(crate) fn host_written(resource: This) { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default) + .insert(resource as usize); +} + +/// The title released a resource. +pub(crate) fn forget(resource: usize) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&resource); + } + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(set) = set.as_mut() { + set.remove(&resource); + } +} + +/// Whether `resource`'s host copy takes its contents from title memory: +/// a texture the host GPU does not render to or write. +pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { + const TARGET_DEPTH_UNORDERED: i32 = 0x7; + // SAFETY: a live resource. + unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0 +} + +/// Records, once per list, the copy of `resource`'s staging buffer into +/// its host copy, and the detiling that refreshes the staging buffer at +/// submission if the memory changed. Leaves the texture in the copy +/// destination state. +pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { + let host_written = HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&(resource as usize))); + // shortcut: a texture the host copied into keeps the host's contents + // even if the title later writes its memory too. + if host_written || !list.first_use(resource as usize) { + return; + } + let Some(staging) = staging(resource, texture) else { + return; + }; + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + for (i, footprint) in staging.footprints.iter().enumerate() { + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *footprint, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + list.defer_host(move || staging.refresh()); +} + +impl Staging { + /// Detiles the texture memory into the staging buffer if it changed + /// since the last time (and is mapped at all). + fn refresh(&self) { + use std::sync::atomic::Ordering::Relaxed; + let started = std::time::Instant::now(); + let read = self.refresh_now(); + let preparing = &crate::host::PREPARING; + preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); + preparing[3].fetch_add(read as u64, Relaxed); + } + + /// Returns the bytes of title memory read. + fn refresh_now(&self) -> usize { + let size = self.layout.size as usize; + let start = self.memory as usize; + let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner()); + let last = &mut *last; + if let Some((now, written)) = crate::watch::writes(start, start + size, false) { + if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { + return 0; + } + last.asked = now; + // Read through the copy, which stands unmapped pages: memory of + // big pools is too slow to ask page by page. + last.read.resize(size, 0); + crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false); + self.detile(&last.read); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexWatched, size as u64); + return size; + } + if !committed(self.memory, size) { + #[cfg(feature = "diagnostics")] + tracing::debug!( + memory = ?self.memory, + size, + desc = ?self.layout.desc, + "a sampled texture's memory is not committed" + ); + return 0; + } + // SAFETY: committed memory of the texture's layout size. + let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; + let hash = blake3::hash(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + if last.hash == Some(hash) { + return size; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + } + + /// Detiles `tiled` (the texture's memory) into the staging buffer. + fn detile(&self, tiled: &[u8]) { + #[cfg(feature = "diagnostics")] + if tiled.iter().all(|&b| b == 0) { + tracing::debug!( + memory = ?self.memory, + desc = ?self.layout.desc, + "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" + ); + } + for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { + let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped staging buffer. + let linear = unsafe { + std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) + }; + if let Err(e) = + self.layout + .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) + { + tracing::warn!(?e, mip, slice, "texture not detiled"); + return; + } + } + } +} + +/// Whether `[at, at + len)` is committed memory (streamed textures may be +/// unmapped until their pages arrive). +pub(crate) fn committed(at: *const u8, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let mut p = at as usize; + let end = p + len; + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.State != MEM_COMMIT { + return false; + } + p = info.BaseAddress as usize + info.RegionSize; + } + true +} + +/// The staging state of a title texture, made on first use. +fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + if let Some(s) = map.get(&(resource as usize)) { + return Some(s.clone()); + } + let (memory, desc) = crate::resource::texture_memory(resource)?; + let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone()) + else { + once!( + ?desc, + "texture contents without a console layout not uploaded" + ); + return None; + }; + if layout.desc.swizzle.xor() { + once!(?desc, "texture contents in an XOR mode not uploaded"); + return None; + } + let host = host()?; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + u32::from(d.MipLevels) + } else { + u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + }; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut rows = vec![0u32; count as usize]; + let mut total = 0; + // SAFETY: outputs for `count` subresources. + unsafe { + host.device.GetCopyableFootprints( + &d, + 0, + count, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ); + } + let (buffer, data) = host.upload_buffer(total)?; + tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + let s = Arc::new(Staging { + buffer, + data, + footprints, + rows, + layout, + mips: u32::from(d.MipLevels), + memory, + last: Mutex::default(), + }); + map.insert(resource as usize, s.clone()); + Some(s) +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs new file mode 100644 index 0000000..a64e3e3 --- /dev/null +++ b/crates/victory-gpu/src/watch.rs @@ -0,0 +1,367 @@ +//! Which title memory the title wrote since a host copy took it (decision +//! 0007, "Copies of title memory"). The runtime reserves title GPU memory +//! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit +//! per 4 KiB page; asking for a range's written pages also clears them. Host +//! copies of the same memory can overlap (nested buffers, textures in +//! buffers), so what one asks is kept here for the others: a journal of +//! each page's last write, numbered by the asking. +//! +//! Physical-page views (xmem's sections) cannot be write-watched. There a +//! copy leaves each 64 KiB block it took read-only, and our vectored handler +//! takes the first write to it: it notes the block as written and gives the +//! write access back. The runtime tells us when it maps or unmaps views +//! ([`title_memory_remapped`]), which resets their protection. +//! +//! shortcut: writes into physical pages through another view (xmem's +//! `write_physical`, DirectStorage's page destinations) are not seen at +//! the guarded addresses; they go to the texture pool, whose textures are +//! hashed, not guarded. A system call writing into a guarded block fails +//! (none is known to). + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Mutex; + +/// The unit tracked and copied: 64 KiB, the console's page (the kernel's +/// 4 KiB pages fold into it). Finer units made the checks of the world's +/// big buffers cost more than the copies they saved. +pub(crate) const PAGE: usize = 64 << 10; +/// The kernel's page, the unit of its answers. +const KERNEL_PAGE: usize = 4096; + +struct Journal { + /// Numbers the askings; 0 is "never". + asked: u64, + /// Page number → the asking that last found it written. + written: BTreeMap<usize, u64>, + /// Room for the kernel's answer. + found: Vec<usize>, +} + +static JOURNAL: Mutex<Journal> = Mutex::new(Journal { + asked: 0, + written: BTreeMap::new(), + found: Vec::new(), +}); + +/// The pages of `[start, end)` (whole pages) as last written, for pages +/// written since tracking began: `(page number, asking)` in page order, and +/// this asking's number, which is higher than any in the list but those the +/// kernel just reported. `None` if the memory is not write-watched (nor, +/// with `guarded`, view memory, which is then guarded). +pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + let guarded = if failed { + count = 0; + if !guarded { + return None; + } + guard(first * PAGE, last * PAGE)? + } else { + Vec::new() + }; + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + } + j.asked += 1; + let now = j.asked; + let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded); + for page in pages.collect::<Vec<_>>() { + j.written.insert(page, now); + } + Some(( + now, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )) +} + +/// Guarded blocks of view memory. +const BLOCK: usize = PAGE; + +struct Guards { + /// Blocks we made read-only. + protected: BTreeSet<usize>, + /// Of those, the ones not written since a copy took them. + clean: BTreeSet<usize>, +} + +static GUARDS: Mutex<Guards> = Mutex::new(Guards { + protected: BTreeSet::new(), + clean: BTreeSet::new(), +}); + +fn guards() -> std::sync::MutexGuard<'static, Guards> { + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// For view memory: the pages of `[start, end)`'s blocks written since +/// they were last guarded (all of a block's pages), guarding them again +/// before the caller copies them. `None` if the memory is not a view. +fn guard(start: usize, end: usize) -> Option<Vec<usize>> { + use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.Type != MEM_MAPPED { + return None; + } + install(); + let mut g = guards(); + let mut written = Vec::new(); + let mut run: Option<usize> = None; + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + for block in first..=last { + let open = block < last && !g.clean.contains(&block); + if open { + written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); + if g.protected.contains(&block) { + // Written through the runtime, still read-only. + g.clean.insert(block); + } else { + run.get_or_insert(block); + continue; + } + } + if let Some(from) = run.take() { + protect(&mut g, from, block); + } + } + Some(written) +} + +/// Makes blocks `[from, to)` read-only and notes them guarded and clean; +/// block by block if they span views, leaving out any that fail (unmapped). +fn protect(g: &mut Guards, from: usize, to: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + let set = |from: usize, to: usize| { + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + unsafe { + VirtualProtect( + (from * BLOCK) as *const _, + (to - from) * BLOCK, + PAGE_READONLY, + &mut old, + ) != 0 + } + }; + let note = |g: &mut Guards, from: usize, to: usize| { + g.protected.extend(from..to); + g.clean.extend(from..to); + }; + if set(from, to) { + note(g, from, to); + return; + } + for block in from..to { + if set(block, block + 1) { + note(g, block, block + 1); + } + } +} + +/// Gives write access back to the guarded blocks of `[start, end)` and +/// notes them written; true if any was guarded. +fn open(g: &mut Guards, start: usize, end: usize) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + let blocks: Vec<usize> = g + .protected + .range(start / BLOCK..end.div_ceil(BLOCK)) + .copied() + .collect(); + for &block in &blocks { + g.protected.remove(&block); + g.clean.remove(&block); + let mut old = 0; + // SAFETY: a block we made read-only. + unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + } + !blocks.is_empty() +} + +/// Before our own write into title memory `[at, at + len)` through the +/// kernel (which does not fault into our handler): opens its guarded blocks. +/// The runtime calls it (as `kernel_will_write`) before the title's kernel +/// reads into its own memory. +pub fn writing(at: usize, len: usize) { + open(&mut guards(), at, at + len); +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`: what it +/// shows is new and read-write, so it is no longer guarded. +pub fn title_memory_remapped(at: usize, len: usize) { + let mut g = guards(); + let blocks: Vec<usize> = g + .protected + .range(at / BLOCK..(at + len).div_ceil(BLOCK)) + .copied() + .collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } +} + +/// Registers the handler that takes writes to guarded blocks, once, ahead +/// of the crash reporter's. +fn install() { + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, + EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + let r = unsafe { &*(*info).ExceptionRecord }; + const WRITE: usize = 1; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS + || r.NumberParameters < 2 + || r.ExceptionInformation[0] != WRITE + { + return EXCEPTION_CONTINUE_SEARCH; + } + let at = r.ExceptionInformation[1]; + if open(&mut guards(), at, at + 1) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardFaults, 1); + return EXCEPTION_CONTINUE_EXECUTION; + } + // Another thread may have opened the block since this one faulted. + if writable(at) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: the handler only touches our guard state and protections. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_write)); + }); +} + +/// Whether `at` is committed read-write memory now. +fn writable(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + #[test] + fn written_pages_are_reported_to_every_asker() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 4 * PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(p, 0); + let (start, end) = (p, p + 4 * PAGE); + let (_, before) = writes(start, end, false).expect("watched"); + assert!(before.is_empty()); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; + let (now, after) = writes(start, end, false).expect("watched"); + assert_eq!(after, [(p / PAGE + 1, now)]); + // Another asker after the kernel's bit was cleared still sees it. + let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); + assert!(later > now); + assert_eq!(again, [(p / PAGE + 1, now)]); + let mut plain = vec![0u8; PAGE]; + assert!( + writes( + plain.as_mut_ptr() as usize, + plain.as_ptr() as usize + PAGE, + true + ) + .is_none() + ); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + + /// A kernel read into a guarded view block fails; opened first, it + /// lands and the block counts as written. + #[test] + fn kernel_reads_into_guarded_blocks_after_opening() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize + }; + assert_ne!(view, 0); + assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"from the disk").unwrap(); + // `ReadFile` inside: the kernel writes the view. + let read = |file: &mut std::fs::File| { + file.rewind().unwrap(); + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; + file.read(into).is_ok_and(|n| n == 13) + }; + assert!(!read(&mut file), "the kernel does not fault into our handler"); + writing(view + 100, 13); + assert!(read(&mut file)); + // SAFETY: the bytes just read. + assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk"); + assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect())); + // SAFETY: our view. + unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; + title_memory_remapped(view, 2 * BLOCK); + } +} diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index 8a9581f..e8d6baf 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -11,23 +11,45 @@ publish.workspace = true victory-gpu.workspace = true victory-loader.workspace = true victory-pe.workspace = true +victory-formats.workspace = true +opus-pure.workspace = true +miniz_oxide.workspace = true tracing.workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = [ "Win32_Foundation", "Win32_Globalization", + "Win32_Media", + "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", "Win32_System_LibraryLoader", "Win32_System_Memory", + "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_Threading", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_XboxController", "Win32_UI_WindowsAndMessaging", ] } +# Diagnostics only: recording our own audio (`modules::audio::capture`). +windows = { workspace = true, optional = true, features = [ + "Win32_Media_Audio", + "Win32_System_Com", + "Win32_System_Com_StructuredStorage", + "Win32_System_Threading", + "Win32_System_Variant", +] } +# `#[implement]` names it. +windows-core = { workspace = true, optional = true } [dev-dependencies] tempfile.workspace = true +[features] +# Debugging switches (scripted keys and the like). +diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"] + [lints] workspace = true diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 244fc3d..8a2a875 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -27,12 +27,12 @@ impl Default for HostPolicy { "ucrtbase.dll", "vcruntime140*", "msvcp140*", + // Off-machine traffic is refused in `modules::net`. "ws2_32.dll", "bcrypt.dll", "crypt32.dll", "ncrypt.dll", "winhttp.dll", - "dnsapi.dll", "sspicli.dll", "cabinet.dll", "avrt.dll", @@ -44,6 +44,13 @@ impl Default for HostPolicy { "ole32.dll", "advapi32.dll", "iphlpapi.dll", + // The title's crash handler writes minidumps with it (loaded by name). + "dbghelp.dll", + // Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create + // on both); Media Foundation reads local media files. + "xaudio2_9.dll", + "mfplat.dll", + "mfreadwrite.dll", ]; HostPolicy { allow: allow.iter().map(|s| s.to_string()).collect(), diff --git a/crates/victory-hle/src/lib.rs b/crates/victory-hle/src/lib.rs index ae83541..ed5b632 100644 --- a/crates/victory-hle/src/lib.rs +++ b/crates/victory-hle/src/lib.rs @@ -18,6 +18,7 @@ pub mod runtime; pub use host::HostPolicy; pub use registry::{HleExport, HleModule, registry}; +pub use victory_gpu::console; use victory_loader::{ImportResolver, Provenance, Resolution}; use victory_pe::ImportSymbol; @@ -101,7 +102,10 @@ mod tests { Some(Provenance::Host) ); // Console-only DLLs never pass through. - assert_eq!(r.classify("xmem.dll", &name("XMemAllocDefault")), None); + assert_eq!( + r.classify("xmem.dll", &name("XMemSetAllocationHooks")), + None + ); } #[cfg(windows)] diff --git a/crates/victory-hle/src/modules/apu.rs b/crates/victory-hle/src/modules/apu.rs new file mode 100644 index 0000000..0668f0d --- /dev/null +++ b/crates/victory-hle/src/modules/apu.rs @@ -0,0 +1,524 @@ +//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out. +//! +//! A title connects once for one kind of processing, gets a block of memory +//! for its packets and output, and then queues per-stream commands +//! (activate, process, reset, deactivate) and dequeues one result per +//! command. We decode each command when it is queued, so its result is ready +//! at once; the order of results is the order of commands. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::sync::Mutex; + +use opus_pure::OpusDecoder; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent}; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32; +/// No result yet, which titles poll for. +pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; +const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32; +const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32; +const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32; +const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32; + +/// Processing kinds; only plain decoding is implemented. +const DECODE_OPUS: u32 = 1; + +const ACTIVATE: u32 = 1; +const DEACTIVATE: u32 = 2; +const PROCESS: u32 = 3; +const NOTIFY: u32 = 4; +const RESET: u32 = 5; + +/// Command option: signal the connection's event when the result is ready. +const SIGNAL: u32 = 1; +/// Connect options. +const DEINTERLEAVED_OUTPUT: u32 = 4; +const RESULT_EVENT: u32 = 8; + +/// The longest Opus packet duration at 48 kHz (120 ms). +const MAX_FRAMES: usize = 5760; + +#[repr(C)] +pub struct ConnectInput { + process: u32, + streams: u32, + commands_per_stream: u32, + memory: u32, + frames_per_output: u32, + options: u32, +} + +#[repr(C)] +pub struct ConnectOutput { + memory: *mut c_void, + result_event: HANDLE, +} + +/// What every command starts with, and what its result echoes. +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct CommandId { + kind: u32, + stream: u32, + sequence: u32, + options: u32, + context: u64, +} + +#[repr(C, packed)] +struct Activate { + id: CommandId, + channels: u32, + init_length: u32, + init: *const c_void, + start_pitch: f32, + processing_length: u32, + processing: *mut c_void, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Process { + id: CommandId, + pitch_ramp: f32, + target_pitch: f32, + first_frame: u32, + frame_count: u32, + input_length: u32, + input: *const u8, + output_length: u32, + output: *mut u8, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct ApuResult { + id: CommandId, + state: u32, + state_data: u64, + usec: u64, + error: HRESULT, + frames: u32, + output_length: u32, + output: *mut u8, + pitch: f32, + input_length: u32, + input: *const u8, +} + +// SAFETY: the raw pointers are title addresses carried through, never +// dereferenced after the result is made. +unsafe impl Send for ApuResult {} + +pub struct Connection { + memory: *mut u8, + layout: Layout, + event: HANDLE, + options: u32, + per_stream: u32, + state: Mutex<State>, +} + +struct State { + streams: Vec<Option<OpusDecoder>>, + /// Results not yet dequeued, per stream. + queued: Vec<u32>, + results: VecDeque<ApuResult>, + commands: u32, + dequeued: u32, +} + +fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> { + c.state.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub extern "system" fn XApuConnect( + input: *const ConnectInput, + output: *mut ConnectOutput, + handle: *mut *mut Connection, +) -> HRESULT { + if input.is_null() || output.is_null() || handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + let input = unsafe { &*input }; + if !(1..=500).contains(&input.streams) + || !(1..=16).contains(&input.commands_per_stream) + || input.memory == 0 + { + return E_INVALIDARG; + } + if input.process != DECODE_OPUS { + // shortcut: rate conversion (decode-convert, PCM convert) is not + // implemented; add a resampler if a title connects for it. + tracing::warn!( + process = input.process, + "audio decoder: processing kind not implemented" + ); + return E_NOTIMPL; + } + if input.frames_per_output != 0 { + return E_INVALIDARG; + } + let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else { + return E_INVALIDARG; + }; + // SAFETY: non-zero size. + let memory = unsafe { std::alloc::alloc_zeroed(layout) }; + if memory.is_null() { + return E_OUTOFMEMORY; + } + let event = if input.options & RESULT_EVENT != 0 { + // SAFETY: plain auto-reset event, no name. + unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } + } else { + std::ptr::null_mut() + }; + let streams = input.streams as usize; + tracing::info!( + streams, + memory = input.memory, + options = input.options, + "audio decoder connected" + ); + let connection = Box::new(Connection { + memory, + layout, + event, + options: input.options, + per_stream: input.commands_per_stream, + state: Mutex::new(State { + streams: (0..streams).map(|_| None).collect(), + queued: vec![0; streams], + results: VecDeque::new(), + commands: 0, + dequeued: 0, + }), + }); + // SAFETY: checked non-null. + unsafe { + output.write(ConnectOutput { + memory: memory.cast(), + result_event: event, + }); + handle.write(Box::into_raw(connection)); + } + S_OK +} + +pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT { + if handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XApuConnect`; disconnected once. + let connection = unsafe { Box::from_raw(handle) }; + if !connection.event.is_null() { + // SAFETY: our event. + unsafe { CloseHandle(connection.event) }; + } + // SAFETY: allocated in `XApuConnect` with this layout. + unsafe { std::alloc::dealloc(connection.memory, connection.layout) }; + S_OK +} + +pub extern "system" fn XApuEnqueueCommand( + handle: *mut Connection, + command: *const CommandId, + total: *mut u32, +) -> HRESULT { + if handle.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`; every command starts with an id. + let (connection, id) = unsafe { (&*handle, command.read_unaligned()) }; + let mut state = lock(connection); + let stream = id.stream as usize; + if stream >= state.streams.len() { + return INVALID_STREAM; + } + if state.queued[stream] >= connection.per_stream { + return QUEUE_FULL; + } + let mut result = ApuResult { + id, + state: 0, + state_data: 0, + usec: 0, + error: S_OK, + frames: 0, + output_length: 0, + output: std::ptr::null_mut(), + pitch: 1.0, + input_length: 0, + input: std::ptr::null(), + }; + let decoder = &mut state.streams[stream]; + match id.kind { + ACTIVATE => { + // SAFETY: an activate command is this struct. + let channels = unsafe { command.cast::<Activate>().read_unaligned() }.channels; + tracing::debug!(stream, channels, "Opus stream activated"); + result.error = if decoder.is_some() { + ALREADY_ACTIVE + } else { + match OpusDecoder::new(48_000, channels as usize) { + Ok(d) if (1..=2).contains(&channels) => { + *decoder = Some(d); + S_OK + } + _ => E_INVALIDARG, + } + }; + } + DEACTIVATE => *decoder = None, + RESET => { + if let Some(d) = decoder { + let _ = d.reset_state(); + } + } + NOTIFY => {} + PROCESS => { + // SAFETY: a process command is this struct. + let command = unsafe { command.cast::<Process>().read_unaligned() }; + match decoder { + Some(d) => process(d, connection.options, &command, &mut result), + None => result.error = INVALID_STREAM, + } + } + _ => return INVALID_COMMAND, + } + state.queued[stream] += 1; + state.commands = state.commands.wrapping_add(1); + state.results.push_back(result); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.commands) }; + } + if id.options & SIGNAL != 0 && !connection.event.is_null() { + // SAFETY: our event. + unsafe { SetEvent(connection.event) }; + } + S_OK +} + +/// Decodes one packet into the command's output buffer, keeping the frames +/// from `first_frame` on, at most `frame_count` of them. +fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) { + let channels = decoder.channels(); + let (input, input_length) = (command.input, command.input_length); + let (output, output_length) = (command.output, command.output_length); + result.input = input; + result.input_length = input_length; + result.output = output; + if input.is_null() || output.is_null() || input_length == 0 { + result.error = E_INVALIDARG; + return; + } + // SAFETY: the title's packet in its connection memory. + let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; + let mut pcm = vec![0f32; MAX_FRAMES * channels]; + let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) { + Ok(n) => n, + Err(_) => { + result.error = BAD_PACKET; + return; + } + }; + let first = (command.first_frame as usize).min(decoded); + let frames = (decoded - first) + .min(command.frame_count as usize) + .min(output_length as usize / (4 * channels)); + let kept = &pcm[first * channels..(first + frames) * channels]; + // SAFETY: the title's output buffer holds `output_length` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(output.cast::<f32>(), frames * channels) }; + if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + (out[i], out[frames + i]) = (frame[0], frame[1]); + } + } else { + out.copy_from_slice(kept); + } + result.frames = frames as u32; + result.output_length = (frames * channels * 4) as u32; +} + +pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { + if handle.is_null() || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`. + let mut state = lock(unsafe { &*handle }); + let Some(result) = state.results.pop_front() else { + return PENDING_RESULTS; + }; + let stream = result.id.stream as usize; + state.queued[stream] -= 1; + state.dequeued = state.dequeued.wrapping_add(1); + // SAFETY: the title passes room for one result. + unsafe { out.write_unaligned(result) }; + S_OK +} + +pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 { + if handle.is_null() { + return 0; + } + // SAFETY: a connection from `XApuConnect`. + let state = lock(unsafe { &*handle }); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.dequeued) }; + } + state.results.len() as u32 +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "apu", + dlls: &["xapu.dll"], + exports: vec![ + hle_export!(XApuConnect), + hle_export!(XApuDisconnect), + hle_export!(XApuEnqueueCommand), + hle_export!(XApuDequeueResult), + hle_export!(XApuGetResultCount), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opus_pure::{Application, OpusEncoder}; + + fn id(kind: u32, stream: u32) -> CommandId { + CommandId { + kind, + stream, + sequence: 7, + options: 0, + context: 0x1234, + } + } + + #[test] + fn decodes_opus_as_the_title_drives_it() { + assert_eq!(size_of::<ApuResult>(), 0x50); + // 256 mono/stereo streams, two commands each, as the title connects. + let input = ConnectInput { + process: DECODE_OPUS, + streams: 256, + commands_per_stream: 2, + memory: 0x10_4000, + frames_per_output: 0, + options: 1, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::<u8>(); + + let activate = Activate { + id: id(ACTIVATE, 3), + channels: 2, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + + // A 20 ms stereo packet of a 440 Hz tone. + let tone: Vec<f32> = (0..960 * 2) + .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .collect(); + let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut packet = [0u8; 1500]; + let n = encoder.encode(&tone, 960, &mut packet).unwrap(); + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let process = Process { + id: id(PROCESS, 3), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: n as u32, + input: base, + output_length: 0xf00 * 2, + output: base.wrapping_add(0x14000), + }; + let mut total = 0; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + S_OK + ); + assert_eq!(total, 2); + // Two results queued for stream 3: its queue is full. + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + QUEUE_FULL + ); + assert_eq!(XApuGetResultCount(handle, std::ptr::null_mut()), 2); + + let mut result = std::mem::MaybeUninit::<ApuResult>::zeroed(); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let first = unsafe { result.assume_init() }; + let (kind, error, context) = (first.id.kind, first.error, first.id.context); + assert_eq!((kind, error, context), (ACTIVATE, S_OK, 0x1234)); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let decoded = unsafe { result.assume_init() }; + let (kind, error, frames, length) = ( + decoded.id.kind, + decoded.error, + decoded.frames, + decoded.output_length, + ); + assert_eq!((kind, error, frames, length), (PROCESS, S_OK, 960, 960 * 8)); + // SAFETY: the decoder wrote 960 stereo frames there. + let pcm = + unsafe { std::slice::from_raw_parts(base.wrapping_add(0x14000).cast::<f32>(), 1920) }; + let energy: f32 = pcm.iter().map(|s| s * s).sum::<f32>() / 1920.0; + assert!(energy > 0.01, "decoded a tone, energy {energy}"); + assert_eq!( + XApuDequeueResult(handle, result.as_mut_ptr()), + PENDING_RESULTS + ); + let mut dequeued = 0; + assert_eq!(XApuGetResultCount(handle, &mut dequeued), 0); + assert_eq!(dequeued, 2); + + // A process on a stream that was never activated fails in its result. + let mut stray = process; + stray.id.stream = 4; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const stray).cast(), &mut total), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let error = unsafe { result.assume_init() }.error; + assert_eq!(error, INVALID_STREAM); + assert_eq!(XApuDisconnect(handle), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index ced4194..0a11195 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -1,35 +1,36 @@ -//! The console's audio hardware (`AcpHal.dll`, `xapu.dll`), enough for -//! middleware to start and then mix in software: +//! The console's audio hardware (`AcpHal.dll`): //! //! * the APU heap: host memory with 32-bit device addresses; //! * SHAPE context arrays allocated from it; //! * the audio coprocessor's command and message queues, where every //! command completes at once and is acknowledged as the hardware would; -//! * the APU decoder's connections, which accept no work. +//! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours +//! into their output rings, like the hardware does. //! -//! What the hardware computes (XMA decoding, hardware rate conversion, EQ, -//! mixing, Opus decoding) is not emulated, so voices that need it stay -//! silent. Software-decoded audio plays through the host's WASAPI, which -//! middleware reaches through COM like on PC. fmod's console build sets -//! all of this up inside `System_Create` and waits there for its first -//! command to be acknowledged. +//! SHAPE's other units (rate conversion, EQ, filters, mixing through +//! flowgraphs) are not emulated, so voices that need them stay silent. +//! Mixed audio leaves through the host's WASAPI, which titles and +//! middleware reach through COM like on PC. fmod's console build sets up +//! the coprocessor inside `System_Create` and waits there for its first +//! command to be acknowledged; Grand Theft Auto VI uses only XMA contexts. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::alloc::Layout; use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; -use std::sync::{Mutex, MutexGuard}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard}; use std::time::Instant; use super::xasync::E_INVALIDARG; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleModule, hle_export}; +#[cfg(all(windows, feature = "diagnostics"))] +pub mod capture; + const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; -/// The decoder's "no result yet", which fmod checks for. -const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) @@ -46,40 +47,110 @@ struct Block { struct Heap { /// By host address. blocks: BTreeMap<usize, Block>, - next_apu: u32, + /// Host address by device address. + by_apu: BTreeMap<u32, usize>, + /// Free device address ranges, start to end, merged with neighbours. + free: BTreeMap<u32, u32>, + /// Set by `ApuCreateHeap` or the first allocation: the heap exists. + created: bool, } static HEAP: Mutex<Heap> = Mutex::new(Heap { blocks: BTreeMap::new(), - next_apu: 0x0001_0000, + by_apu: BTreeMap::new(), + free: BTreeMap::new(), + created: false, }); +/// Device addresses start above 0, which means "none" to titles. +const APU_BASE: u32 = 0x0001_0000; + +impl Heap { + /// First fit in the free ranges. + fn take(&mut self, size: u32, align: u32) -> Option<u32> { + if self.free.is_empty() && !self.created { + self.free.insert(APU_BASE, u32::MAX); + } + self.created = true; + let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| { + let apu = start.checked_next_multiple_of(align)?; + (apu.checked_add(size)? <= end).then_some((start, end, apu)) + })?; + self.free.remove(&start); + if start < apu { + self.free.insert(start, apu); + } + if apu + size < end { + self.free.insert(apu + size, end); + } + Some(apu) + } + + fn give_back(&mut self, mut start: u32, mut end: u32) { + if let Some((&before, &before_end)) = self.free.range(..start).next_back() + && before_end == start + { + self.free.remove(&before); + start = before; + } + if let Some(after_end) = self.free.remove(&end) { + end = after_end; + } + self.free.insert(start, end); + } +} + /// Zeroed host memory and its device address. -// shortcut: device addresses are handed out once and never reused, so the -// 32-bit space runs out after 4 GiB of allocations in total; reuse freed -// ranges if a title streams that much through the heap. fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?; let mut heap = lock(&HEAP); - let apu = heap.next_apu.checked_next_multiple_of(align as u32)?; - let next = apu.checked_add(u32::try_from(layout.size()).ok()?)?; + let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?; // SAFETY: non-zero size. let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; if ptr.is_null() { + heap.give_back(apu, apu + layout.size() as u32); return None; } - heap.next_apu = next; heap.blocks .insert(ptr as usize, Block { size, apu, layout }); + heap.by_apu.insert(apu, ptr as usize); Some((ptr, apu)) } fn heap_free(ptr: *mut u8) { - let block = lock(&HEAP).blocks.remove(&(ptr as usize)); - if let Some(block) = block { - // SAFETY: allocated by `heap_alloc` with this layout. - unsafe { std::alloc::dealloc(ptr, block.layout) }; + let mut heap = lock(&HEAP); + let Some(block) = heap.blocks.remove(&(ptr as usize)) else { + return; + }; + heap.by_apu.remove(&block.apu); + heap.give_back(block.apu, block.apu + block.layout.size() as u32); + drop(heap); + // SAFETY: allocated by `heap_alloc` with this layout. + unsafe { std::alloc::dealloc(ptr, block.layout) }; +} + +/// Sizes the heap once, before anything is allocated from it. The console +/// reserves both parts up front; we allocate per block, so the sizes only +/// decide whether the call is valid. +// shortcut: the cached and non-cached sizes are not enforced as limits; +// enforce them if a title relies on running out. +pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT { + const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32; + if cached == 0 { + return E_INVALIDARG; } + let mut heap = lock(&HEAP); + if heap.created { + return ALREADY_ALLOCATED; + } + heap.created = true; + heap.free.insert(APU_BASE, u32::MAX); + S_OK +} + +/// The host address of a device address, null outside the heap. +pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void { + heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast()) } /// The device address of any byte of a heap block, 0 elsewhere. @@ -96,10 +167,22 @@ fn heap_map(ptr: usize) -> u32 { /// The host address of a device address, if a heap block holds it. fn heap_unmap(apu: u32) -> Option<*mut u8> { let heap = lock(&HEAP); - heap.blocks - .iter() - .find(|(_, b)| (b.apu..b.apu.saturating_add(b.size as u32)).contains(&apu)) - .map(|(&start, b)| (start + (apu - b.apu) as usize) as *mut u8) + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let block = &heap.blocks[&host]; + (apu < start.saturating_add(block.size.max(1) as u32)) + .then(|| (host + (apu - start) as usize) as *mut u8) +} + +/// `len` bytes of title memory at a device address, if one heap block holds +/// them all. +fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> { + let heap = lock(&HEAP); + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let offset = (apu - start) as usize; + (offset + len <= heap.blocks[&host].size) + // SAFETY: inside a live heap block, which the title and the audio + // hardware share like on the console. + .then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) }) } pub extern "system" fn ApuAlloc( @@ -183,12 +266,16 @@ pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses); } *allocated = Some(arrays.map(|p| p as usize)); + let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner()); + xma.array = arrays[4] as usize; + xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect(); S_OK } pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { match lock(&CONTEXTS).take() { Some(arrays) => { + *XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY; arrays.iter().for_each(|&p| heap_free(p as *mut u8)); S_OK } @@ -196,6 +283,410 @@ pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { } } +// The XMA decoder. +// +// An XMA context (16 words in the shared context array) names up to two +// input buffers of 2 KiB packets, a ring of 256-byte output blocks the +// hardware fills with 16-bit PCM, and the read offset the title advances +// by command. Words and bit fields, as titles write them: +// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever), +// valid inputs (20-21), output size in blocks (22-26), write block +// (27-31, hardware); +// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes +// to skip (17-19), subframes to skip at the start (24-26), sample rate +// (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31); +// 2: read position in bits (0-25), error status (26-30), error (31); +// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input +// (31); 5, 6: input addresses; 7: output address; 8: overlap buffer; +// 9: read block (0-4). +// Titles read back only the write block, "writable" and the read block, +// and take whatever lies between read and write. +// shortcut: each enabled context decodes from a cold state and the overlap +// buffer is ignored (titles copy it between consecutive contexts of one +// voice); keep decoder state there if a title's seams turn out audible. + +use victory_formats::xma; + +const ENABLE_XMA: u32 = 5; +const ENABLE_XMAS: u32 = 6; +const DISABLE_XMA: u32 = 7; +const DISABLE_XMAS: u32 = 8; +const ADVANCE_XMA_READ: u32 = 18; + +const BLOCK_BYTES: usize = 256; +const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2; +/// Error status: the input ran out. +const INPUT_INVALID: u32 = 4; + +struct Voice { + decoder: Option<xma::Decoder>, + pcm: VecDeque<i16>, + /// Samples per channel still to drop (start or loop subframe skips). + skip: usize, + ended: bool, + trace: Trace, +} + +/// What a voice did, for the debug log when it is disabled. +struct Trace { + since: Instant, + /// Samples per channel written to the ring. + produced: usize, + /// Blocks the title took (command 18), how often, and how often it + /// found the ring less than full. + taken: usize, + takes: u32, + partial_takes: u32, + frames: u32, + bad_frames: u32, + /// The loudest sample written. + peak: i16, + /// Milliseconds after enabling when the input ran out. + ended_ms: Option<u128>, +} + +struct Xma { + /// Host address of the context array. + array: usize, + /// One entry per context, `Some` while enabled. Each has its own lock, + /// so a command for one voice never waits for others to decode (the + /// title sends them from its time-critical mixer thread). + voices: Vec<Mutex<Option<Voice>>>, +} + +impl Xma { + const EMPTY: Xma = Xma { + array: 0, + voices: Vec::new(), + }; +} + +/// Written only when the context arrays are allocated or released. +static XMA: RwLock<Xma> = RwLock::new(Xma::EMPTY); + +fn xma() -> RwLockReadGuard<'static, Xma> { + XMA.read().unwrap_or_else(|e| e.into_inner()) +} + +/// A context's words in title memory. +#[derive(Clone, Copy)] +struct Context(*mut u32); + +impl Context { + fn get(self, word: usize) -> u32 { + // SAFETY: inside the context array; the title reads and writes it + // concurrently, like the hardware's. + unsafe { self.0.add(word).read_volatile() } + } + + fn set(self, word: usize, value: u32) { + // SAFETY: as above. + unsafe { self.0.add(word).write_volatile(value) } + } + + fn field(self, word: usize, shift: u32, bits: u32) -> u32 { + (self.get(word) >> shift) & ((1 << bits) - 1) + } + + fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) { + let mask = ((1u32 << bits) - 1) << shift; + self.set(word, (self.get(word) & !mask) | ((value << shift) & mask)); + } + + fn channels(self) -> usize { + 1 + self.field(1, 29, 1) as usize + } +} + +impl Xma { + fn context(&self, index: u32) -> Option<Context> { + ((index as usize) < self.voices.len() && self.array != 0) + .then(|| Context((self.array + index as usize * 64) as *mut u32)) + } + + fn enable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let mut slot = lock(&self.voices[index as usize]); + context.set_field(2, 26, 6, 0); + tracing::debug!( + index, + words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::<Vec<_>>(), + "XMA voice enabled" + ); + #[cfg(feature = "diagnostics")] + dump_input(index, context); + *slot = Some(Voice { + decoder: None, + pcm: VecDeque::new(), + skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES, + ended: false, + trace: Trace { + since: Instant::now(), + produced: 0, + taken: 0, + takes: 0, + partial_takes: 0, + frames: 0, + bad_frames: 0, + peak: 0, + ended_ms: None, + }, + }); + drop(slot); + wake_decoder(); + } + + fn disable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let Some(voice) = lock(&self.voices[index as usize]).take() else { + return; + }; + let t = &voice.trace; + tracing::debug!( + index, + ms = t.since.elapsed().as_millis(), + produced = t.produced, + taken = t.taken * SAMPLES_PER_BLOCK / context.channels(), + takes = t.takes, + partial_takes = t.partial_takes, + frames = t.frames, + bad_frames = t.bad_frames, + peak = t.peak, + input_ended_ms = ?t.ended_ms, + read_bit = context.field(2, 0, 26), + input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8, + "XMA voice disabled" + ); + } + + /// Moves the title's read block on, which frees output space. + fn advance_read(&self, index: u32, blocks: u32) { + let Some(context) = self.context(index) else { + return; + }; + // The decoder writes the same words. + let mut slot = lock(&self.voices[index as usize]); + let size = context.field(0, 22, 5).max(1); + let read = (context.field(9, 0, 5) + blocks) % size; + context.set_field(9, 0, 5, read); + if blocks > 0 { + context.set_field(1, 31, 1, 1); + } + if let Some(voice) = &mut *slot { + let t = &mut voice.trace; + t.taken += blocks as usize; + t.takes += 1; + t.partial_takes += u32::from(blocks < size); + } + drop(slot); + wake_decoder(); + } + + /// Fills every enabled context's output as far as it has room. + fn pump(&self) { + let start = Instant::now(); + let mut active = 0; + for index in 0..self.voices.len() as u32 { + if let (Some(context), Some(voice)) = + (self.context(index), &mut *lock(&self.voices[index as usize])) + { + pump(context, voice); + active += 1; + } + } + let took = start.elapsed(); + if took.as_millis() >= 4 { + tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass"); + } + } +} + +fn pump(context: Context, voice: &mut Voice) { + let size = context.field(0, 22, 5); + if size == 0 { + return; + } + while context.field(1, 31, 1) == 1 { + if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + return; + } + let write = context.field(0, 27, 5); + let address = context.get(7) as usize + write as usize * BLOCK_BYTES; + let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else { + return; + }; + for pair in out.as_chunks_mut::<2>().0 { + let sample = voice.pcm.pop_front().unwrap_or(0); + voice.trace.peak = voice.trace.peak.max(sample.saturating_abs()); + pair.copy_from_slice(&sample.to_le_bytes()); + } + voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); + let write = (write + 1) % size; + context.set_field(0, 27, 5, write); + if write == context.field(9, 0, 5) { + // Full: nothing more until the title advances its read block. + context.set_field(1, 31, 1, 0); + } + } +} + +/// Decodes the next frame of the current input into `voice.pcm`; false +/// when there is nothing left to decode. +fn decode(context: Context, voice: &mut Voice) -> bool { + if voice.ended { + return false; + } + let channels = context.channels(); + let mut current = context.field(4, 31, 1); + let valid = context.field(0, 20, 2); + if valid & (1 << current) == 0 { + if valid & (1 << (1 - current)) == 0 { + // Out of input: the overlap tail, then nothing. + if let Some(decoder) = &mut voice.decoder { + let mut tail = Vec::new(); + decoder.flush(&mut tail); + voice.pcm.extend(tail); + } + voice.ended = true; + voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis()); + context.set_field(2, 26, 5, INPUT_INVALID); + context.set_field(2, 31, 1, 1); + return !voice.pcm.is_empty(); + } + current = 1 - current; + context.set_field(4, 31, 1, current); + context.set_field(2, 0, 26, 0); + } + let (address, packets) = match current { + 0 => (context.get(5), context.field(0, 0, 12)), + _ => (context.get(6), context.field(1, 0, 12)), + }; + let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else { + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let mut at = context.field(2, 0, 26) as usize; + if at < 32 { + at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize); + } + let Some(frame) = xma::read_frame(data, at) else { + // This input is used up. + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let decoder = voice.decoder.get_or_insert_with(|| { + const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000]; + xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize]) + }); + let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels); + voice.trace.frames += 1; + if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) { + voice.trace.bad_frames += 1; + if voice.trace.bad_frames <= 2 { + tracing::debug!( + at, + bits = frame.bits, + head = ?&frame.data[..frame.data.len().min(8)], + %e, + "XMA frame did not decode" + ); + } + } + let mut next = frame.next.unwrap_or(0); + let loops = context.field(0, 12, 8); + let loop_end = context.field(4, 0, 26) as usize; + let ends_loop = loop_end != 0 + && (frame.start == loop_end + || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); + if loops > 0 && ends_loop { + let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; + pcm.truncate(keep); + next = context.field(3, 0, 26) as usize; + voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; + if loops != 255 { + context.set_field(0, 12, 8, loops - 1); + } + } + let skip = (voice.skip * channels).min(pcm.len()); + voice.skip -= skip / channels; + voice.pcm.extend(&pcm[skip..]); + if next == 0 { + context.set_field(0, 20 + current, 1, 0); + } + context.set_field(2, 0, 26, next as u32); + true +} + +/// `VICTORY_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`) +/// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test +/// the decoder on a title's streams outside the title. +#[cfg(feature = "diagnostics")] +fn dump_input(index: u32, context: Context) { + static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else { + return; + }; + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if n >= 32 { + return; + } + let dir = std::path::PathBuf::from(dir); + let words: Vec<u8> = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect(); + let input = heap_bytes( + context.get(5) & !0x7ff, + context.field(0, 0, 12) as usize * xma::PACKET_BYTES, + ); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); +} + +/// Starts the decoding thread on the first enabled voice, and has it fill +/// rings now: a voice just enabled or read from. +fn wake_decoder() { + static DECODER: OnceLock<std::thread::Thread> = OnceLock::new(); + DECODER + .get_or_init(|| { + std::thread::Builder::new() + .name("victory XMA decoder".into()) + .spawn(|| { + loop { + xma().pump(); + // A 256-byte output block lasts 2.7 ms at 48 kHz mono. + std::thread::park_timeout(std::time::Duration::from_millis(2)); + } + }) + .map_or_else(|_| std::thread::current(), |h| h.thread().clone()) + }) + .unpark(); +} + +/// Runs an XMA command; false for one this does not know. +fn xma_command(command: u32, word: impl Fn(usize) -> Option<u32>) -> bool { + let xma = xma(); + match command { + ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)), + DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)), + ENABLE_XMAS | DISABLE_XMAS => { + for i in 0..xma.voices.len() as u32 { + if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 { + match command { + ENABLE_XMAS => xma.enable(i), + _ => xma.disable(i), + } + } + } + } + ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)), + _ => return false, + } + true +} + // The audio coprocessor. const LOAD_FLOWGRAPH: u32 = 1; @@ -223,6 +714,10 @@ struct State { /// Message kinds the title registered for. mask: u32, messages: VecDeque<Message>, + /// Queue size given to `connect`. + capacity: usize, + /// Messages lost to a full queue since the last one queued. + dropped: u32, since: Instant, } @@ -235,15 +730,20 @@ impl State { (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32 } - // shortcut: the queue is unbounded and never reports dropped messages; - // bound it at the size given to `connect` if a title relies on drops. + /// Queues a registered message; a full queue drops it and counts it in + /// the next one that fits. fn post(&mut self, kind: u32, data: &[u8]) { if self.mask & kind == 0 { return; } + if self.messages.len() >= self.capacity { + self.dropped = self.dropped.saturating_add(1); + tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped"); + return; + } let mut message = Message { kind, - dropped: 0, + dropped: std::mem::take(&mut self.dropped), usec: self.usec() as u32, data: [0; 16], }; @@ -284,11 +784,13 @@ fn state(this: *mut Acp) -> MutexGuard<'static, State> { lock(unsafe { &(*this).state }) } -extern "system" fn connect(this: *mut Acp, commands: u32, _messages: u32) -> HRESULT { +extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT { if commands == 0 { return E_INVALIDARG; } - state(this).connected = true; + let mut state = state(this); + state.connected = true; + state.capacity = messages as usize; S_OK } @@ -330,6 +832,10 @@ extern "system" fn submit( let flowgraph = word(1).unwrap_or(0); state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes()); } + _ if xma_command(command, word) => {} + // shortcut: context updates and the other SHAPE units' commands are + // acknowledged but not carried out; add them when a title sends + // them (each kind is logged once above). _ => {} } if id != 0 { @@ -378,6 +884,8 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { connected: false, mask: 0, messages: VecDeque::new(), + capacity: 0, + dropped: 0, since: Instant::now(), }), }); @@ -386,98 +894,20 @@ pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { S_OK } -// The APU decoder: connections get their memory, commands are refused. - -#[repr(C)] -pub struct ConnectInput { - process: u32, - streams: u32, - commands_per_stream: u32, - memory: u32, - frames_per_output: u32, - options: u32, -} - -#[repr(C)] -pub struct ConnectOutput { - memory: *mut c_void, - result_event: *mut c_void, -} - -/// The memory a connection hands out. -pub struct Connection(*mut u8, Layout); - -pub extern "system" fn XApuConnect( - input: *const ConnectInput, - output: *mut ConnectOutput, - handle: *mut *mut Connection, -) -> HRESULT { - const RESULT_READY_EVENT: u32 = 8; - if input.is_null() || output.is_null() || handle.is_null() { - return E_INVALIDARG; - } - // SAFETY: checked non-null. - let input = unsafe { &*input }; - if input.options & RESULT_READY_EVENT != 0 { - // shortcut: no event to signal, since no result ever comes; create - // one if a title asks for it. - return E_FAIL; - } - let Ok(layout) = Layout::from_size_align(input.memory.max(16) as usize, 16) else { - return E_INVALIDARG; - }; - // SAFETY: non-zero size. - let memory = unsafe { std::alloc::alloc_zeroed(layout) }; - if memory.is_null() { - return E_OUTOFMEMORY; - } - // SAFETY: checked non-null. - unsafe { - output.write(ConnectOutput { - memory: memory.cast(), - result_event: std::ptr::null_mut(), - }); - handle.write(Box::into_raw(Box::new(Connection(memory, layout)))); - } - S_OK -} - -/// Nothing is decoded: the stream fails instead of waiting forever. -pub extern "system" fn XApuEnqueueCommand() -> HRESULT { - E_FAIL -} - -pub extern "system" fn XApuDequeueResult() -> HRESULT { - PENDING_RESULTS -} - -pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT { - if handle.is_null() { - return E_INVALIDARG; - } - // SAFETY: made by `XApuConnect`; disconnected once. - let Connection(memory, layout) = *unsafe { Box::from_raw(handle) }; - // SAFETY: allocated in `XApuConnect` with this layout. - unsafe { std::alloc::dealloc(memory, layout) }; - S_OK -} - pub(crate) fn module() -> HleModule { HleModule { name: "audio", - dlls: &["acphal.dll", "xapu.dll"], + dlls: &["acphal.dll"], exports: vec![ hle_export!(AcpHalAllocateShapeContexts), hle_export!(AcpHalReleaseShapeContexts), hle_export!(AcpHalCreate), hle_export!(ApuAlloc), + hle_export!(ApuCreateHeap), hle_export!(ApuFree), hle_export!(ApuIsVirtualAddressValid), + hle_export!(ApuMapApuAddress), hle_export!(ApuMapVirtualAddress), - hle_export!(XApuConnect), - hle_export!(XApuEnqueueCommand), - hle_export!(XApuDequeueResult), - hle_export!(XApuDisconnect), ], } } @@ -488,6 +918,7 @@ mod tests { #[test] fn heap_maps_every_byte_of_a_block() { + let _serial = lock(&CONTEXT_TESTS); let (mut ptr, mut apu) = (std::ptr::null_mut(), 0); assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK); assert!(apu != 0 && apu.is_multiple_of(128)); @@ -500,8 +931,185 @@ mod tests { assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG); } + /// The context arrays and the heap exist once per process: tests that + /// allocate from them run one at a time (a concurrent allocation could + /// take a freed range a test expects back). + static CONTEXT_TESTS: Mutex<()> = Mutex::new(()); + + #[test] + fn heap_reuses_freed_addresses() { + let _serial = lock(&CONTEXT_TESTS); + let (mut a, mut b, mut c) = ( + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ); + let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0); + assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK); + assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK); + ApuFree(a); + assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK); + // The freed range is free again, whichever part `c` took. + assert!( + lock(&HEAP) + .free + .iter() + .any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e) + || apu_c == apu_a + ); + assert_eq!( + ApuMapApuAddress(apu_b + 8), + b.cast::<u8>().wrapping_add(8).cast() + ); + assert!(ApuMapApuAddress(0).is_null()); + assert_eq!( + ApuCreateHeap(64 << 20, 0), + 0x8ACA_0001_u32 as i32, + "too late" + ); + ApuFree(b); + ApuFree(c); + } + + /// Two packets of three silent mono frames each: a fixed one-subframe + /// layout, no transmitted coefficients. + fn silent_stream() -> Vec<u8> { + let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES]; + let mut put = |at: usize, value: u32, width: usize| { + for i in 0..width { + let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1); + data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for packet in 0..2 { + let base = packet * xma::PACKET_BYTES * 8; + put(base, 3 << 26, 32); + for frame in 0..3 { + let at = base + 32 + frame * 31; + put(at, 31, 15); // length + put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe + put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe + } + } + data + } + + #[test] + fn xma_contexts_decode_into_their_output_rings() { + let _serial = lock(&CONTEXT_TESTS); + let mut request = ShapeContexts { + counts: [0, 0, 0, 0, 4, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16)); + + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); + assert_eq!( + ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2), + S_OK + ); + // SAFETY: the ring was just allocated. + unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) }; + + // As the title sets one up: two packets, input 0 valid, a ring of + // four blocks, writable, 48 kHz mono, reading from the first frame. + context.set(0, 2 | 1 << 20 | 4 << 22); + context.set(1, 1 << 31 | 3 << 27); + context.set(2, 32); + context.set(5, input_apu); + context.set(7, output_apu); + + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); + let submit = |command: u32, words: &[u32]| { + assert_eq!( + (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), + S_OK + ); + }; + submit(ENABLE_XMA, &[1]); + xma().pump(); + // Full: all four blocks written (silence), the write block wrapped + // onto the read block, and the ring no longer writable. + assert_eq!(context.field(0, 27, 5), 0); + assert_eq!(context.field(1, 31, 1), 0); + // SAFETY: the ring. + let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) }; + assert!(ring.iter().all(|&b| b == 0)); + + // Read four blocks at a time until the input has run out and the + // ring keeps room (the decoding thread may fill it too). + for _ in 0..20 { + submit(ADVANCE_XMA_READ, &[1, 4]); + xma().pump(); + if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 { + break; + } + } + // Six frames and the flushed tail: 3,328 samples, 26 blocks. + let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced); + assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK)); + assert_eq!(context.field(0, 20, 2), 0, "input used up"); + assert_eq!(context.field(2, 26, 5), INPUT_INVALID); + + submit(DISABLE_XMA, &[1]); + assert_eq!(produced(&xma()), None); + (m.release)(acp); + ApuFree(input); + ApuFree(output); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } + + #[test] + fn full_message_queues_count_drops() { + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 16, 2), S_OK); + let mask = COMMAND_COMPLETED; + assert_eq!( + (m.submit)( + acp, + REGISTER_MESSAGES, + 0, + u32::MAX, + (&raw const mask).cast(), + 0 + ), + S_OK + ); + for id in 1..=4 { + assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK); + } + assert_eq!((m.message_count)(acp), 2); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message)); + assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK); + assert!((m.pop_message)(acp, &mut message)); + let dropped = message.dropped; + assert_eq!(dropped, 2); + (m.release)(acp); + } + #[test] fn startup_as_fmod_does_it() { + let _serial = lock(&CONTEXT_TESTS); // Context arrays: rate conversion, DMA and XMA. let mut request = ShapeContexts { counts: [0x200, 0, 0, 0x400, 0x200, 0], diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs new file mode 100644 index 0000000..f39bb3d --- /dev/null +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -0,0 +1,229 @@ +//! Debugging aid: `VICTORY_AUDIO_CAPTURE=<file.wav>` records what the title +//! plays, 48 kHz stereo 16-bit, through process loopback: our own process +//! tree only, never the rest of the host's mix. Stretches where nothing was +//! played are written as silence, so the file keeps real time. +//! +//! The recorder runs in a child copy of this executable: an audio client +//! in the title's process raises that process's timer resolution, which +//! changes how the title's own waits behave. + +use std::fs::File; +use std::io::{Seek, SeekFrom, Write}; +use std::path::Path; +use std::time::{Duration, Instant}; + +use windows::Win32::Media::Audio::{ + AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, + AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0, + AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, + ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, + IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl, + IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, +}; +use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; +use windows::Win32::Foundation::WAIT_OBJECT_0; +use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, +}; +use windows::core::{HRESULT, IUnknown, Interface, Ref, implement}; + +const RATE: u32 = 48_000; +const FRAME_BYTES: usize = 4; + +/// Activation completes asynchronously; the recording thread polls for it. +#[implement(IActivateAudioInterfaceCompletionHandler)] +struct Activated; + +impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl { + fn ActivateCompleted( + &self, + _: Ref<IActivateAudioInterfaceAsyncOperation>, + ) -> windows::core::Result<()> { + Ok(()) + } +} + +/// Names the process to record, in the recorder's environment. +const TARGET: &str = "VICTORY_AUDIO_CAPTURE_OF"; + +/// Starts the recorder if `VICTORY_AUDIO_CAPTURE` names a file. With this +/// module's debug log, also logs once a second what a `Sleep(1)` takes in +/// this process (the title's millisecond waits get the same). +pub fn start() { + if tracing::enabled!(tracing::Level::DEBUG) { + let _ = std::thread::Builder::new() + .name("victory timing probe".into()) + .spawn(|| { + loop { + std::thread::sleep(Duration::from_secs(1)); + let at = Instant::now(); + // SAFETY: plain wait. + unsafe { Sleep(1) }; + let ms = at.elapsed().as_secs_f32() * 1000.0; + tracing::debug!(ms, "Sleep(1) took"); + } + }); + } + if std::env::var_os("VICTORY_AUDIO_CAPTURE").is_some() + && let Err(e) = std::env::current_exe().and_then(|exe| { + std::process::Command::new(exe) + .env(TARGET, std::process::id().to_string()) + .spawn() + }) + { + tracing::warn!("audio capture not started: {e}"); + } +} + +/// In the recorder (a child started by [`start`]): records until the +/// target exits and returns true; false in any other process. +pub fn child() -> bool { + let (Some(pid), Some(path)) = ( + std::env::var(TARGET).ok().and_then(|p| p.parse().ok()), + std::env::var_os("VICTORY_AUDIO_CAPTURE"), + ) else { + return false; + }; + if let Err(e) = record(pid, Path::new(&path)) { + tracing::warn!("audio capture stopped: {e}"); + } + true +} + +fn header(frames: u64) -> [u8; 44] { + let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36); + let mut h = [0u8; 44]; + let fields: [(&[u8], usize); 11] = [ + (b"RIFF", 0), + (&(36 + data).to_le_bytes(), 4), + (b"WAVEfmt ", 8), + (&16u32.to_le_bytes(), 16), + (&1u16.to_le_bytes(), 20), + (&2u16.to_le_bytes(), 22), + (&RATE.to_le_bytes(), 24), + (&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28), + (&(FRAME_BYTES as u16).to_le_bytes(), 32), + (&16u16.to_le_bytes(), 34), + (b"data", 36), + ]; + for (bytes, at) in fields { + h[at..at + bytes.len()].copy_from_slice(bytes); + } + h[40..].copy_from_slice(&data.to_le_bytes()); + h +} + +fn record(pid: u32, path: &Path) -> Result<(), Box<dyn std::error::Error>> { + // SAFETY: COM calls with parameters built here; buffers are used only + // between `GetBuffer` and `ReleaseBuffer`. + unsafe { + CoInitializeEx(None, COINIT_MULTITHREADED).ok()?; + let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?; + let params = AUDIOCLIENT_ACTIVATION_PARAMS { + ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, + Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { + ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS { + TargetProcessId: pid, + ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + }, + }, + }; + /// A `PROPVARIANT` holding a blob (`VT_BLOB`). + #[repr(C)] + struct Blob { + vt: u16, + reserved: [u16; 3], + size: u32, + data: *const AUDIOCLIENT_ACTIVATION_PARAMS, + } + let blob = Blob { + vt: 0x41, + reserved: [0; 3], + size: size_of_val(¶ms) as u32, + data: ¶ms, + }; + let handler: IActivateAudioInterfaceCompletionHandler = Activated.into(); + let operation = ActivateAudioInterfaceAsync( + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, + &IAudioClient::IID, + Some((&raw const blob).cast()), + &handler, + )?; + let client = loop { + let (mut hr, mut client) = (HRESULT(0), None::<IUnknown>); + // Fails (`E_ILLEGAL_METHOD_CALL`) until activation completes. + if operation.GetActivateResult(&mut hr, &mut client).is_ok() { + hr.ok()?; + break client.ok_or("no audio client")?.cast::<IAudioClient>()?; + } + std::thread::sleep(Duration::from_millis(10)); + }; + let format = WAVEFORMATEX { + wFormatTag: WAVE_FORMAT_PCM as u16, + nChannels: 2, + nSamplesPerSec: RATE, + nAvgBytesPerSec: RATE * FRAME_BYTES as u32, + nBlockAlign: FRAME_BYTES as u16, + wBitsPerSample: 16, + cbSize: 0, + }; + client.Initialize( + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, + 10_000_000, + 0, + &format, + None, + )?; + let capture: IAudioCaptureClient = client.GetService()?; + let mut file = File::create(path)?; + file.write_all(&header(0))?; + client.Start()?; + tracing::info!(path = %path.display(), "recording the title's audio"); + + let (mut written, mut first) = (0u64, None); + let mut patched = Instant::now(); + loop { + std::thread::sleep(Duration::from_millis(10)); + let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0; + while capture.GetNextPacketSize()? > 0 { + let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0); + capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?; + // Where this packet belongs, from its time stamp (100 ns). + let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000; + if at > written + u64::from(RATE / 500) { + tracing::debug!( + ms = (at - written) * 1000 / u64::from(RATE), + "audio capture: nothing played" + ); + let silence = vec![0u8; (at - written) as usize * FRAME_BYTES]; + file.write_all(&silence)?; + written = at; + } + let bytes = frames as usize * FRAME_BYTES; + if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 { + file.write_all(&vec![0u8; bytes])?; + } else { + file.write_all(std::slice::from_raw_parts(data, bytes))?; + } + if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 { + tracing::debug!("audio capture: discontinuity"); + } + written += u64::from(frames); + capture.ReleaseBuffer(frames)?; + } + if ended || patched.elapsed() >= Duration::from_secs(1) { + // Valid sizes at any time: runs end by being killed. + file.seek(SeekFrom::Start(0))?; + file.write_all(&header(written))?; + file.seek(SeekFrom::End(0))?; + patched = Instant::now(); + } + if ended { + return Ok(()); + } + } + } +} diff --git a/crates/victory-hle/src/modules/d3d12x.rs b/crates/victory-hle/src/modules/d3d12x.rs index 9c38f44..ef8b231 100644 --- a/crates/victory-hle/src/modules/d3d12x.rs +++ b/crates/victory-hle/src/modules/d3d12x.rs @@ -1,23 +1,76 @@ -//! `d3d12_xs.dll`: device creation. The device and everything it creates -//! live in `victory-gpu`. +//! `d3d12_xs.dll`: virtual memory setup, device creation, root signature +//! serialization. The device and everything it creates live in +//! `victory-gpu`. + +use std::ffi::c_void; use victory_gpu::device; +use victory_gpu::object::{HRESULT, Iid, Object}; use crate::{HleExport, HleModule}; +/// Device creation; first hands the device the title's general allocator +/// (`XMemAlloc`, which honours the title's hooks) for resource memory. +extern "system" fn create_device( + adapter: *const c_void, + parameters: *const u32, + iid: *const Iid, + out: *mut *const Object, +) -> HRESULT { + victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); + victory_gpu::resource::use_page_mapper(super::xmem::map_alias); + #[cfg(windows)] + victory_gpu::on_failure(host_gpu_failed); + device::create(adapter, parameters, iid, out) +} + +/// A host GPU failure ends the run like a crash: reported to the crash log, +/// then the process ends as the console ends a title. +#[cfg(windows)] +fn host_gpu_failed(what: &str) -> ! { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + victory_loader::log_crash(&format!("VIctory: host GPU failure: {what}")); + const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005; + // SAFETY: ends our own process. + unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) }; + unreachable!("the process has ended") +} + +/// Keeps the host's translations of the title's shaders in `dir` (a +/// folder of the cache) across runs. +pub fn use_shader_cache(dir: std::path::PathBuf) { + #[cfg(windows)] + victory_gpu::shader_cache::use_shader_cache(dir); + #[cfg(not(windows))] + let _ = dir; +} + pub(crate) fn module() -> HleModule { HleModule { name: "d3d12x", dlls: &["d3d12_xs.dll"], exports: vec![ + HleExport { + name: "D3D12ConfigureVirtualMemoryX", + address: device::configure_virtual_memory as *const () as usize, + }, HleExport { name: "D3D12XboxCreateDevice", - address: device::create as *const () as usize, + address: create_device as *const () as usize, }, HleExport { name: "D3D12SerializeRootSignature", address: victory_gpu::root::serialize as *const () as usize, }, + HleExport { + name: "D3D12SerializeVersionedRootSignature", + address: victory_gpu::root::serialize_versioned as *const () as usize, + }, + // The AMD upscaler's (Series S). + HleExport { + name: "D3D12CreateRootSignatureDeserializer", + address: victory_gpu::root::create_deserializer as *const () as usize, + }, // A data import: the title reads the id at this address. HleExport { name: "IID_ID3D12Device", diff --git a/crates/victory-hle/src/modules/display.rs b/crates/victory-hle/src/modules/display.rs new file mode 100644 index 0000000..41f9cbd --- /dev/null +++ b/crates/victory-hle/src/modules/display.rs @@ -0,0 +1,195 @@ +//! The display and what the system shell does for a title: HDR mode, screen +//! timeout deferrals, launching URIs, screenshots. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text, +}; + +/// HDR mode; asked for with this interface id since 2020. +pub const HDR_PROVIDER: Guid = Guid::new( + 0x03f0_fe74, + 0xfdd9, + 0x4e5c, + [0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5], +); +pub const HDR_IID: Guid = Guid::new( + 0x35f0_7670, + 0x706e, + 0x4bfb, + [0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3], +); +/// Launching URIs and screen timeout deferrals; the interface id is the +/// provider's. +pub const SHELL: Guid = Guid::new( + 0x1b33_9674, + 0x328d, + 0x4283, + [0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39], +); +/// Screenshots and clips. +pub const CAPTURE_PROVIDER: Guid = Guid::new( + 0xa4f1_aee2, + 0x4bf1, + 0x4485, + [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], +); +/// As Grand Theft Auto VI (2026) asks for it; it calls 0x28 (take a +/// screenshot) with the public API's arguments. +pub const CAPTURE_IID_2026: Guid = Guid::new( + 0x22e6_72d7, + 0xb4e3, + 0x406c, + [0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e], +); + +pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE); +pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE); +pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (HDR_PROVIDER, HDR_IID, &HDR_OBJECT), + (SHELL, SHELL, &SHELL_OBJECT), + (CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT), +]; + +type This = *const Object; + +/// 2: disabled. We present in SDR, so the title must render SDR. +// shortcut: HDR output is not done (see the presentation items in +// `TODO.md`); report enabled, with the host display's luminance, once the +// swap chain can present HDR. +extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 { + tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); + 2 +} + +/// Nothing launches URIs for the title: no store, browser or console app +/// exists here, and the console's are online services. +extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT { + tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched"); + NOT_SUPPORTED +} + +/// A deferral keeps the host display on, as on the console, through a +/// power request; the handle is that request. +#[cfg(windows)] +extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { + use windows_sys::Win32::System::Power::{ + PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest, + }; + use windows_sys::Win32::System::Threading::{ + POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, + }; + if out.is_null() { + return super::xasync::E_INVALIDARG; + } + let mut reason: Vec<u16> = "Title display deferral\0".encode_utf16().collect(); + let mut context = REASON_CONTEXT { + Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, + ..Default::default() + }; + context.Reason.SimpleReasonString = reason.as_mut_ptr(); + // SAFETY: a valid context; the string is copied by the call. + let request = unsafe { PowerCreateRequest(&context) }; + if request as isize == -1 { + return last_error(); + } + // SAFETY: the request we just created. + if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { + let hr = last_error(); + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; + } + put(out, request) +} + +#[cfg(windows)] +extern "system" fn close_deferral(_: This, handle: *mut c_void) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired}; + if !handle.is_null() { + // SAFETY: a request from `acquire_deferral`. + unsafe { + PowerClearRequest(handle, PowerRequestDisplayRequired); + CloseHandle(handle); + } + } +} + +#[cfg(windows)] +fn last_error() -> HRESULT { + // SAFETY: no preconditions. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + (0x8007_0000 | (code & 0xffff)) as i32 +} + +// shortcut: screenshots fail as if capture were unavailable. Taking one needs +// a hook in the GPU side: the last presented frame read back as BGRA8 (size, +// row pitch, bytes) on request, e.g. `victory_gpu::last_frame() -> +// Option<Frame>`, copied from the back buffer after `PresentX`. +extern "system" fn take_screenshot(_: This, _user: *const c_void, _result: *mut c_void) -> HRESULT { + tracing::info!("screenshot not taken"); + NOT_SUPPORTED +} + +static HDR_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), + try_enable_hdr as *const (), // 0x20 +]); + +#[cfg(windows)] +static SHELL_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), // 0x18 + acquire_deferral as *const (), // 0x20 + close_deferral as *const (), // 0x28 +]); +#[cfg(not(windows))] +static SHELL_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), +]); + +static CAPTURE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 diagnostic screenshot + missing::<4> as *const (), // 0x20 diagnostic clip + take_screenshot as *const (), // 0x28 +]); + +#[cfg(all(test, windows))] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn sdr_and_display_deferrals() { + type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32; + assert_eq!( + method::<Hdr>(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()), + 2 + ); + type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; + type Close = extern "system" fn(This, *mut c_void); + let mut handle = std::ptr::null_mut(); + assert_eq!( + method::<Acquire>(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + method::<Close>(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); + } +} diff --git a/crates/victory-hle/src/modules/dsp.rs b/crates/victory-hle/src/modules/dsp.rs new file mode 100644 index 0000000..87c456a --- /dev/null +++ b/crates/victory-hle/src/modules/dsp.rs @@ -0,0 +1,314 @@ +//! The console's audio DSP (`chad.dll`): streams that convolve blocks of +//! float samples with an impulse response (reverb), or run other block +//! transforms, on a coprocessor. +//! +//! A title connects once with a memory block for the DSP, activates +//! streams, and submits one command per block (gains, an input and an +//! output buffer). Activation hands back a status block whose second word is +//! the ticket of the last completed command and whose fourth is its result; +//! the title checks it one block later and treats a late command as an +//! overrun. Commands complete when submitted here. +//! +//! The transforms themselves are not computed: the hardware takes impulse +//! responses already in its own partitioned frequency-domain layout, which +//! is not known. Outputs are silence, so reverb returns are dry. +// shortcut: no convolution or block transform; outputs are zeros. Needs the +// coprocessor's impulse response and spectrum layouts to do better. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; + +const CONVOLUTION: u32 = 1; +/// Option bits that need a stereo stream, and one convolution refuses. +const STEREO_OPTIONS: u32 = 2 | 8; +const NOT_FOR_CONVOLUTION: u32 = 4; + +pub struct Dsp { + max_streams: u32, + active: Mutex<u32>, +} + +/// What activation describes. +#[repr(C, packed)] +pub struct StreamDesc { + kind: u32, + options: u32, + frames: u32, + channels: u32, + ir_floats: u32, + ir: *const f32, +} + +/// The status block a stream's owner polls. +#[repr(C)] +pub struct Status { + submitted: u32, + completed: u32, + reserved: u32, + result: HRESULT, +} + +pub struct Stream { + dsp: *mut Dsp, + frames: u32, + channels: u32, + status: Box<Status>, +} + +/// One block of work. +#[repr(C)] +pub struct Command { + gains: [f32; 2], + input: *const f32, + output: *mut f32, + reserved: u64, +} + +pub extern "system" fn XDspConnectWithMaximumStreamLimit( + base: *mut c_void, + base_length: u32, + ir_seconds: u32, + max_streams: u32, + max_channels: u32, + out: *mut *mut Dsp, +) -> HRESULT { + if base.is_null() + || !(0x1_0000..=0x1F40_0000).contains(&base_length) + || ir_seconds > 0x80 + || max_streams > 0x100 + || max_channels > 2 + { + return E_INVALIDARG; + } + if out.is_null() { + return E_POINTER; + } + tracing::info!( + base_length, + ir_seconds, + max_streams, + max_channels, + "audio DSP connected" + ); + let dsp = Box::new(Dsp { + max_streams, + active: Mutex::new(0), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(dsp)) }; + S_OK +} + +pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { + if dsp.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected + // once, after its streams. + drop(unsafe { Box::from_raw(dsp) }); + S_OK +} + +fn valid(desc: &StreamDesc) -> bool { + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + let shape = if kind == CONVOLUTION { + (1..=2).contains(&channels) + && matches!(frames, 0x200 | 0x400) + && options & NOT_FOR_CONVOLUTION == 0 + } else { + channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800) + }; + shape && (options & STEREO_OPTIONS == 0 || channels == 2) +} + +pub extern "system" fn XDspActivate( + dsp: *mut Dsp, + desc: *const StreamDesc, + status: *mut *const Status, + stream: *mut *mut Stream, +) -> HRESULT { + if status.is_null() || stream.is_null() { + return E_POINTER; + } + if dsp.is_null() || desc.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its description. + let desc = unsafe { &*desc }; + if !valid(desc) { + return E_INVALIDARG; + } + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + tracing::debug!( + kind, + options, + frames, + channels, + "audio DSP stream activated" + ); + { + // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. + let dsp = unsafe { &*dsp }; + let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); + if *active >= dsp.max_streams { + return E_OUTOFMEMORY; + } + *active += 1; + } + let new = Box::new(Stream { + dsp, + frames: desc.frames, + channels: desc.channels, + status: Box::new(Status { + submitted: 0, + completed: 0, + reserved: 0, + result: S_OK, + }), + }); + // SAFETY: checked non-null. + unsafe { + status.write(&*new.status); + stream.write(Box::into_raw(new)); + } + S_OK +} + +pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { + if stream.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspActivate`; deactivated once. + let stream = unsafe { Box::from_raw(stream) }; + // SAFETY: the connection outlives its streams. + let dsp = unsafe { &*stream.dsp }; + *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; + S_OK +} + +/// Completes the command at once: its output block is silence. +pub extern "system" fn XDspSubmitCommand( + stream: *mut Stream, + command: *const Command, + ticket: *mut u32, +) -> HRESULT { + if stream.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a stream from `XDspActivate`, the title's command. + let (stream, command) = unsafe { (&mut *stream, &*command) }; + if !command.output.is_null() { + let samples = (stream.frames * stream.channels) as usize; + // SAFETY: the title's output buffer holds one block of the stream. + unsafe { std::ptr::write_bytes(command.output, 0, samples) }; + } + let status = &mut *stream.status; + let next = status.submitted.wrapping_add(1); + // SAFETY: the status block is read by title code on other threads. + unsafe { + std::ptr::write_volatile(&mut status.submitted, next); + std::ptr::write_volatile(&mut status.result, S_OK); + std::ptr::write_volatile(&mut status.completed, next); + } + if !ticket.is_null() { + // SAFETY: optional out parameter. + unsafe { ticket.write(next) }; + } + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dsp", + dlls: &["chad.dll"], + exports: vec![ + hle_export!(XDspConnectWithMaximumStreamLimit), + hle_export!(XDspDisconnect), + hle_export!(XDspActivate), + hle_export!(XDspDeactivate), + hle_export!(XDspSubmitCommand), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convolution_stream_as_the_title_drives_it() { + let mut base = vec![0u8; 0x10_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x10_0000, + 24, + 0x80, + 1, + &mut dsp + ), + S_OK + ); + let ir = vec![0f32; 0x800]; + // Stereo convolution with option 2, as the title asks for. + let desc = StreamDesc { + kind: CONVOLUTION, + options: 2, + frames: 0x400, + channels: 2, + ir_floats: 0x800, + ir: ir.as_ptr(), + }; + let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); + assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); + let mut output = vec![1f32; 0x800]; + let input = vec![0.5f32; 0x800]; + let command = Command { + gains: [1.0, 1.0], + input: input.as_ptr(), + output: output.as_mut_ptr(), + reserved: 0, + }; + let mut ticket = 0; + assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); + // SAFETY: the stream's status block. + let (completed, result) = unsafe { ((*status).completed, (*status).result) }; + assert_eq!((completed, result), (ticket, S_OK)); + assert!(output.iter().all(|&s| s == 0.0)); + assert_eq!(XDspDeactivate(stream), S_OK); + + // Mono streams refuse stereo options; transforms are mono only. + let bad = StreamDesc { + channels: 1, + ..desc + }; + assert_eq!( + XDspActivate(dsp, &bad, &mut status, &mut stream), + E_INVALIDARG + ); + let transform = StreamDesc { + kind: 2, + options: 0, + channels: 1, + ir_floats: 0, + ir: std::ptr::null(), + ..desc + }; + assert_eq!( + XDspActivate(dsp, &transform, &mut status, &mut stream), + S_OK + ); + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } +} diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs new file mode 100644 index 0000000..302dcbe --- /dev/null +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -0,0 +1,1476 @@ +//! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files +//! and creates request queues and status arrays the title polls. Its +//! interfaces have grown since 2020 (new interface ids, new slots); the +//! slots here are the ones Grand Theft Auto VI calls, read from its call +//! sites. Slots nobody has needed yet log their offset. +//! +//! Submitted requests of every queue run on one pool of workers, as the +//! console's hardware runs them: in parallel, started in queue order, +//! queues served by weighted round robin over their priorities (about 10x +//! per level, counted in bytes), with at most the staging buffer's worth of +//! compressed source in flight. Each request reads its source (a file or +//! memory), inflates zlib data and/or unpacks BCPack data, and writes the +//! destination (an address, or physical pages). Completion is what stays +//! in order: a status entry is written once every request enqueued before +//! it on its queue has finished, with the first failure (in queue order) +//! since the previous status entry, or success. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::fs::FileExt; +use std::os::windows::io::FromRawHandle; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use victory_formats::bcpack::{self, Tables}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING}; +use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put}; +use crate::{HleModule, hle_export}; + +/// The factory interface Grand Theft Auto VI asks for. +const FACTORY: Guid = Guid::new( + 0x6295_9d11, + 0xd45f, + 0x4884, + [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae], +); +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)`: the source ends early. +const END_OF_FILE: HRESULT = 0x8007_0026_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_INVALID_DATA)`: a bad compressed stream. +const INVALID_DATA: HRESULT = 0x8007_000D_u32 as i32; + +type Out = *mut *mut c_void; + +static FACTORY_OBJECT: Object = Object::new("dstorage factory", &FACTORY_VTABLE); + +pub extern "system" fn DStorageGetFactory(iid: *const Guid, out: Out) -> HRESULT { + // SAFETY: the title passes a GUID (null tolerated). + match unsafe { iid.as_ref() } { + Some(&iid) if iid == FACTORY => { + put(out, std::ptr::from_ref(&FACTORY_OBJECT).cast_mut().cast()) + } + iid => { + tracing::warn!(iid = ?iid.map(Guid::to_string), "DStorageGetFactory: unknown interface"); + E_NOINTERFACE + } + } +} + +/// One of our objects with state: the runtime's object header (method +/// table first), a reference count, then `T`. +#[repr(C)] +struct Instance<T> { + base: Object, + refs: AtomicU32, + state: T, +} + +impl<T> Instance<T> { + fn create(base: Object, state: T) -> *mut c_void { + Box::into_raw(Box::new(Instance { + base, + refs: AtomicU32::new(1), + state, + })) + .cast() + } +} + +extern "system" fn add_ref_instance<T>(this: *const Instance<T>) -> u32 { + // SAFETY: an instance we created and the title still holds. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release<T>(this: *mut Instance<T>) -> u32 { + // SAFETY: as above. + let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference; created by `Instance::create`. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +fn iid_text(iid: *const Guid) -> String { + // SAFETY: the title passes a GUID (null tolerated). + unsafe { iid.as_ref() }.map_or_else(|| "null".into(), Guid::to_string) +} + +/// `HRESULT_FROM_WIN32` of a host error. +fn from_win32(error: &std::io::Error) -> HRESULT { + error + .raw_os_error() + .map_or(E_INVALIDARG, |e| (0x8007_0000 | (e as u32 & 0xffff)) as i32) +} + +// The factory. + +type Factory = *const Object; + +/// Opens `path` for reading; the file object owns the handle. +extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT { + const GENERIC_READ: u32 = 0x8000_0000; + const FILE_SHARE_READ: u32 = 1; + const OPEN_EXISTING: u32 = 3; + if path.is_null() { + return E_INVALIDARG; + } + // Goes through `files`, so paths on our virtual drives work too. + let handle = super::files::CreateFileW( + path, + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + // SAFETY: the title passes a NUL-terminated path. + let name = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(path, len)) + }; + if handle as isize == -1 { + let error = std::io::Error::last_os_error(); + tracing::warn!(path = name, %error, "dstorage: opening a file failed"); + return from_win32(&error); + } + tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); + // SAFETY: a handle we just opened and nobody else owns. + let file = unsafe { std::fs::File::from_raw_handle(handle) }; + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + put(out, file) +} + +/// `(capacity, name, iid, out)`. +extern "system" fn create_status_array( + _: Factory, + capacity: u32, + name: *const c_char, + iid: *const Guid, + out: Out, +) -> HRESULT { + tracing::info!( + capacity, + name = text(name), + iid = iid_text(iid), + "dstorage: status array" + ); + let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect(); + let array = Instance::create( + Object::new("dstorage status array", &STATUS_VTABLE), + StatusArray { entries }, + ); + put(out, array) +} + +/// The queue's description: as in 2020 (source type, capacity, priority, +/// name), plus a field Grand Theft Auto VI sets to 1. +#[repr(C)] +struct QueueDesc { + source_type: u64, + capacity: u16, + priority: i8, + name: *const c_char, + unknown: u64, +} + +extern "system" fn create_queue( + _: Factory, + desc: *const QueueDesc, + iid: *const Guid, + out: Out, +) -> HRESULT { + // SAFETY: the title passes its description (null tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let name = text(desc.name); + tracing::info!( + source = desc.source_type, + capacity = desc.capacity, + priority = desc.priority, + name, + unknown = desc.unknown, + iid = iid_text(iid), + "dstorage: queue" + ); + let Some(scheduler) = scheduler() else { + return E_OUTOFMEMORY; + }; + let mut lanes = scheduler.lock(); + let id = lanes.next_id; + lanes.next_id += 1; + let lane = Lane::new(desc.priority, desc.capacity); + lanes.lanes.insert(id, lane); + drop(lanes); + put( + out, + Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), Queue { id }), + ) +} + +/// Grand Theft Auto VI asks for 32 MiB and stops if this fails. +extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { + tracing::info!(size, "dstorage: staging buffer size"); + if let Some(scheduler) = scheduler() { + scheduler.lock().staging = u64::from(size); + } + S_OK +} + +fn text(name: *const c_char) -> String { + if name.is_null() { + return String::new(); + } + // SAFETY: a NUL-terminated name from the title. + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() +} + +static FACTORY_VTABLE: Methods<16> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 (2020: queue creation) + open_file as *const (), // 0x20 + create_status_array as *const (), // 0x28 + missing::<6> as *const (), // 0x30 (2020: CPU affinity) + missing::<7> as *const (), // 0x38 (2020: debug flags) + set_staging_buffer_size as *const (), // 0x40 + missing::<9> as *const (), + create_queue as *const (), // 0x50 + missing::<11> as *const (), + missing::<12> as *const (), + missing::<13> as *const (), + missing::<14> as *const (), + missing::<15> as *const (), +]); + +// Files. + +struct File { + file: std::fs::File, +} + +static FILE_VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref_instance::<File> as *const (), + release::<File> as *const (), + missing::<3> as *const (), + missing::<4> as *const (), + missing::<5> as *const (), + missing::<6> as *const (), + missing::<7> as *const (), +]); + +// Status arrays. + +struct StatusArray { + entries: Box<[AtomicI32]>, +} + +type Array = *mut Instance<StatusArray>; + +/// The result of the requests before entry `index`: pending, the first +/// failure, or success. +extern "system" fn status_result(this: Array, index: u32) -> HRESULT { + // SAFETY: an array we created and the title still holds. + let entries = &unsafe { &*this }.state.entries; + entries + .get(index as usize) + .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) +} + +/// Grand Theft Auto VI polls this (entry 0, a `Sleep(1)` loop) and never +/// reads the result itself. +extern "system" fn is_complete(this: Array, index: u32) -> bool { + status_result(this, index) != E_PENDING +} + +static STATUS_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref_instance::<StatusArray> as *const (), + release::<StatusArray> as *const (), + is_complete as *const (), // 0x18 + status_result as *const (), // 0x20 +]); + +// Queues. + +/// A queue object: its lane in the scheduler. +struct Queue { + id: u64, +} + +impl Drop for Queue { + fn drop(&mut self) { + close_lane(self.id); + } +} + +type QueueRef = *const Instance<Queue>; + +/// Every queue's requests, run by a pool of workers. +struct Scheduler { + lanes: Mutex<Lanes>, + /// Requests to start, or staging space freed. + work: Condvar, + /// A request finished (for full queues and `close`). + finished: Condvar, +} + +/// Priority weights per class (low, normal, high and real-time), as the +/// console's: about 10x per level, counted against request sizes. +const COST: [u64; 3] = [100, 10, 1]; +/// The console's default staging buffer. +const STAGING: u64 = 32 << 20; + +struct Lanes { + lanes: HashMap<u64, Lane>, + next_id: u64, + /// Submission order over all queues. + next_seq: u64, + /// Bytes of staging held by running requests, and the limit. + staged: u64, + staging: u64, + /// A start waited for staging space since the last finish. + starved: bool, + /// Weighted round robin: each class's virtual time (bytes × cost), and + /// the time of the last start; within a class, the lane clock of the + /// last start. + clock: [u64; 3], + now: u64, + lane_now: [u64; 3], + /// Since the last debug summary: requests, bytes written, time spent + /// running them. + done: (u64, u64, std::time::Duration), + refused: u64, + /// BCPack bytes written and time spent on them. + bcpack: (u64, std::time::Duration), + since: Option<std::time::Instant>, +} + +/// A queue's requests in the scheduler. +struct Lane { + class: usize, + capacity: usize, + /// Bytes started, for round robin among the lanes of a class. + clock: u64, + /// Enqueued, not yet submitted. + unsubmitted: Vec<Command>, + /// Submitted, by sequence number: reads not started, status entries + /// not written, reads running, and failures not yet reported. + reads: VecDeque<(u64, Request)>, + statuses: VecDeque<(u64, Status)>, + running: BTreeSet<u64>, + failures: BTreeMap<u64, HRESULT>, + closed: bool, +} + +// SAFETY: requests point into title memory and our own objects, which stay +// valid until the title has seen them complete; status arrays count their +// references atomically. +unsafe impl Send for Lane {} + +/// A read a worker runs. +struct Job { + lane: u64, + seq: u64, + request: Request, + staging: u64, +} + +// SAFETY: as for `Lane`. +unsafe impl Send for Job {} + +/// The scheduler, with its workers started on first use; `None` if not +/// even one worker could start. +fn scheduler() -> Option<&'static Scheduler> { + static SCHEDULER: OnceLock<Option<Scheduler>> = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let scheduler = SCHEDULER + .get_or_init(|| { + Some(Scheduler { + lanes: Mutex::new(Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging: STAGING, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + }), + work: Condvar::new(), + finished: Condvar::new(), + }) + }) + .as_ref()?; + STARTED.call_once(|| { + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let started = (0..workers) + .filter(|i| { + std::thread::Builder::new() + .name(format!("dstorage {i}")) + .spawn(|| work(scheduler)) + .is_ok() + }) + .count(); + tracing::info!(workers = started, "dstorage: workers"); + }); + Some(scheduler) +} + +impl Scheduler { + fn lock(&self) -> MutexGuard<'_, Lanes> { + self.lanes.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// A worker: runs the next read of the most deserving queue. +fn work(scheduler: &'static Scheduler) { + let mut lanes = scheduler.lock(); + loop { + let Some(job) = lanes.start() else { + lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); + continue; + }; + drop(lanes); + let started = std::time::Instant::now(); + let result = execute(&job.request); + lanes = scheduler.lock(); + lanes.finish(&job, result); + lanes.count(&job, started); + if std::mem::take(&mut lanes.starved) { + scheduler.work.notify_all(); + } + scheduler.finished.notify_all(); + } +} + +impl Lanes { + /// Counts a finished request; every 5 s a debug line sums them up. + fn count(&mut self, job: &Job, started: std::time::Instant) { + let (requests, bytes, busy) = &mut self.done; + *requests += 1; + *bytes += u64::from(job.request.destination_size); + *busy += started.elapsed(); + if job.request.options & BCPACK != 0 { + self.bcpack.0 += u64::from(job.request.destination_size); + self.bcpack.1 += started.elapsed(); + } + let since = *self.since.get_or_insert(started); + let elapsed = since.elapsed(); + if elapsed.as_secs() >= 5 { + let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum(); + let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9; + tracing::debug!( + requests = *requests, + mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6), + busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()), + reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), + staging_waits = std::mem::take(&mut self.refused), + bcpack_mb = self.bcpack.0 / 1_000_000, + bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + waiting, + "dstorage: last {:.1} s", + elapsed.as_secs_f64() + ); + self.done = Default::default(); + self.bcpack = Default::default(); + self.since = None; + } + } + + /// Starts the next read of the class with the least virtual time, from + /// its lane that has started the fewest bytes, if the staging buffer + /// has room for it (or nothing else holds any). + fn start(&mut self) -> Option<Job> { + let busy = || self.lanes.iter().filter(|(_, l)| !l.reads.is_empty()); + let (_, class) = busy().map(|(_, l)| (self.clock[l.class], l.class)).min()?; + let (_, _, id) = busy() + .filter(|(_, l)| l.class == class) + .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id))) + .min()?; + let lane = self.lanes.get_mut(&id)?; + let &(seq, request) = lane.reads.front()?; + let staging = staging_bytes(&request); + if self.staged > 0 && self.staged + staging > self.staging { + self.starved = true; + self.refused += 1; + return None; + } + lane.reads.pop_front(); + lane.running.insert(seq); + self.staged += staging; + let size = u64::from(request.destination_size.max(request.source_size)).max(1); + self.now = self.clock[class]; + self.clock[class] += size * COST[class]; + self.lane_now[class] = lane.clock; + lane.clock += size; + Some(Job { + lane: id, + seq, + request, + staging, + }) + } + + fn finish(&mut self, job: &Job, result: Result<(), HRESULT>) { + self.staged -= job.staging; + if let Some(lane) = self.lanes.get_mut(&job.lane) { + lane.running.remove(&job.seq); + if let Err(hr) = result { + lane.failures.insert(job.seq, hr); + } + lane.flush(); + } + } + + /// Moves a queue's enqueued commands to the workers. + fn submit(&mut self, id: u64) { + let Some(class) = self.lanes.get(&id).map(|l| l.class) else { + return; + }; + // A class that had nothing waiting starts from now, not from the + // credit it left behind. + if !self + .lanes + .values() + .any(|l| l.class == class && !l.reads.is_empty()) + { + self.clock[class] = self.clock[class].max(self.now); + } + let Some(lane) = self.lanes.get_mut(&id) else { + return; + }; + if lane.reads.is_empty() { + lane.clock = lane.clock.max(self.lane_now[class]); + } + for command in std::mem::take(&mut lane.unsubmitted) { + let seq = self.next_seq; + self.next_seq += 1; + match command { + Command::Read(request) => lane.reads.push_back((seq, request)), + Command::Status(status) => lane.statuses.push_back((seq, status)), + } + } + lane.flush(); + } +} + +impl Lane { + fn new(priority: i8, capacity: u16) -> Lane { + Lane { + class: priority.clamp(-1, 1).wrapping_add(1) as usize, + capacity: usize::from(capacity), + clock: 0, + unsubmitted: Vec::new(), + reads: VecDeque::new(), + statuses: VecDeque::new(), + running: BTreeSet::new(), + failures: BTreeMap::new(), + closed: false, + } + } + + /// Requests and status entries held, submitted or not. + fn entries(&self) -> usize { + self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + } + + /// Writes the status entries whose earlier reads have all finished. + fn flush(&mut self) { + while let Some(&(seq, _)) = self.statuses.front() { + let waiting = self.reads.front().map(|r| r.0); + if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { + return; + } + let Some((_, status)) = self.statuses.pop_front() else { + return; + }; + let later = self.failures.split_off(&seq); + let first = std::mem::replace(&mut self.failures, later) + .into_values() + .next(); + status + .entry() + .store(first.unwrap_or(S_OK), Ordering::Release); + } + } +} + +/// Staging bytes a request holds while it runs: what it buffers between +/// the file and the destination. Raw reads go straight to their +/// destination, memory sources need none (as on the console). +fn staging_bytes(request: &Request) -> u64 { + let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0; + if buffered && request.options & MEMORY_SOURCE == 0 { + u64::from(request.source_size) + } else { + 0 + } +} + +/// Ends a queue: what was not started is dropped, and this waits for the +/// reads already running (they write title memory). +fn close_lane(id: u64) { + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.closed = true; + lane.unsubmitted.clear(); + lane.reads.clear(); + lane.statuses.clear(); // releases their arrays + while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + lanes.lanes.remove(&id); + scheduler.finished.notify_all(); +} + +/// A read request as the title builds it, 0x48 bytes. +#[repr(C)] +#[derive(Clone, Copy)] +struct Request { + options: u64, + /// An address, or with `PAGE_DESTINATION` an array of 64 KiB page + /// numbers. + destination: *mut c_void, + /// With `PAGE_DESTINATION`, the low 16 bits are where in the first page + /// the destination starts. + page_offset: u64, + destination_size: u32, + /// Our file object, or with `MEMORY_SOURCE` an address. + source: *const c_void, + offset: u64, + source_size: u32, + /// Compressed size between two decompression stages; unused here. + intermediate_size: u32, + /// Matched by cancellation; Grand Theft Auto VI leaves it 0. + tag: u64, + name: *const c_char, +} + +// Request options. +/// Inflate zlib (RFC 1950) data. +const ZLIB: u64 = 1; +/// Bits 1-4: decode BCPack data of this BC format number (0: none). +const BCPACK: u64 = 0xf << 1; +const PAGE_DESTINATION: u64 = 1 << 21; +const MEMORY_SOURCE: u64 = 1 << 22; +// Bits 5-20 select a further transform, bit 23 a source in physical pages; +// Grand Theft Auto VI's packages need neither, so requests with them fail. + +const PAGE: usize = 64 * 1024; + +enum Command { + Read(Request), + Status(Status), +} + + +/// A status entry to write, holding a reference on its array. +struct Status { + array: Array, + index: u32, +} + +impl Drop for Status { + fn drop(&mut self) { + release(self.array); + } +} + +impl Status { + fn entry(&self) -> &AtomicI32 { + // SAFETY: we hold a reference; the index was checked when enqueued. + &unsafe { &*self.array }.state.entries[self.index as usize] + } +} + +extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { + // SAFETY: the title passes its request (null tolerated). + let Some(&request) = (unsafe { request.as_ref() }) else { + return; + }; + queue(this, Command::Read(request)); +} + +extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { + // SAFETY: the title passes an array we created (null tolerated). + let Some(entries) = (unsafe { array.as_ref() }).map(|a| &a.state.entries) else { + return; + }; + let Some(entry) = entries.get(index as usize) else { + tracing::warn!(index, "dstorage: status entry out of range"); + return; + }; + entry.store(E_PENDING, Ordering::Release); + add_ref_instance(array); + queue(this, Command::Status(Status { array, index })); +} + +/// Adds a command to the queue; blocks while the queue is full, and +/// submits on its own once half of it is enqueued, as the console does. +fn queue(this: QueueRef, command: Command) { + // SAFETY: a queue we created and the title still holds. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + loop { + let Some(lane) = lanes.lanes.get(&id).filter(|l| !l.closed) else { + return; // closed: dropped (a status releases its array) + }; + // One slot stays free, as the console's count of empty slots says. + if lane.entries() + 1 < lane.capacity.max(2) { + break; + } + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.unsubmitted.push(command); + if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { + lanes.submit(id); + scheduler.work.notify_all(); + } +} + +extern "system" fn submit(this: QueueRef) { + // SAFETY: as above. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + tracing::debug!(commands = pending, "dstorage: submit"); + lanes.submit(id); + scheduler.work.notify_all(); +} + +/// Ends the queue whatever its reference count: what was not started never +/// completes, and this returns once the reads already running have +/// finished. Grand Theft Auto VI calls this, not `Release`. +extern "system" fn close(this: QueueRef) { + // SAFETY: as above. + close_lane(unsafe { &*this }.state.id); +} + +/// Reads, inflates and/or unpacks, and writes one request. +fn execute(request: &Request) -> Result<(), HRESULT> { + let options = request.options; + let fail = |hr: HRESULT, why: &str| { + tracing::warn!( + options = format_args!("{options:#x}"), + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + intermediate_size = request.intermediate_size, + tag = request.tag, + name = text(request.name), + hr = format_args!("{:#010x}", hr as u32), + "dstorage: request failed: {why}" + ); + hr + }; + if options & !(ZLIB | BCPACK | PAGE_DESTINATION | MEMORY_SOURCE) != 0 { + return Err(fail(E_NOTIMPL, "unsupported options")); + } + if request.source.is_null() || request.destination.is_null() { + return Err(fail(E_INVALIDARG, "no source or destination")); + } + let bc = ((options & BCPACK) >> 1) as u8; + let size = request.destination_size as usize; + if options & (ZLIB | BCPACK) == 0 { + if request.source_size > request.destination_size { + return Err(fail(E_INVALIDARG, "source larger than destination")); + } + let size = request.source_size as usize; + return into_destination(request, size, |out| read_into(request, out).map(|()| size)) + .map_err(|hr| fail(hr, "copying")); + } + let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; + let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; + // The console's order: zlib first, then BCPack. + let source = if bc != 0 && options & ZLIB != 0 { + let mut packed = vec![0; request.intermediate_size as usize]; + let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; + packed.truncate(n); + Cow::Owned(packed) + } else { + source + }; + into_destination(request, size, |out| match tables { + Some(tables) => bcpack::decode(bc, &source, out, tables) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string())), + None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + })?; + tracing::trace!( + options = format_args!("{options:#x}"), + offset = request.offset, + size, + "dstorage: request done" + ); + Ok(()) +} + +/// Inflates a zlib stream into `out`, returning the bytes written. A stream +/// that ends short of `out` passes: the title's chunks fill it exactly, and +/// nothing says that is required. +fn inflate(source: &[u8], out: &mut [u8]) -> Result<usize, HRESULT> { + miniz_oxide::inflate::decompress_slice_iter_to_slice(out, std::iter::once(source), true, false) + .map_err(|status| { + tracing::debug!(?status, "dstorage: zlib stream"); + INVALID_DATA + }) +} + +/// The BCPack format's constant tables, parsed once for the process. If +/// they do not parse every BCPack request fails: one warning, then debug. +fn bcpack_tables() -> Result<&'static Tables, HRESULT> { + static TABLES: OnceLock<Result<Tables, String>> = OnceLock::new(); + static WARNED: AtomicBool = AtomicBool::new(false); + match TABLES.get_or_init(load_bcpack_tables) { + Ok(tables) => Ok(tables), + Err(why) if !WARNED.swap(true, Ordering::Relaxed) => { + tracing::warn!("dstorage: BCPack requests fail: {why} (more at debug)"); + Err(E_NOTIMPL) + } + Err(_) => { + tracing::debug!("dstorage: BCPack request failed: no tables"); + Err(E_NOTIMPL) + } + } +} + +/// The tables VIctory ships with. +#[cfg(not(test))] +fn load_bcpack_tables() -> Result<Tables, String> { + Tables::builtin().map_err(|e| format!("the built-in BCPack tables: {e}")) +} + +/// Tests decode streams made against tables of their own, from this folder. +#[cfg(test)] +static BCPACK_DIR: OnceLock<std::path::PathBuf> = OnceLock::new(); + +#[cfg(test)] +fn use_bcpack_tables(dir: std::path::PathBuf) { + let _ = BCPACK_DIR.set(dir); +} + +#[cfg(test)] +fn load_bcpack_tables() -> Result<Tables, String> { + let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; + let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; + Tables::parse(&bytes).map_err(|e| e.to_string()) +} + +/// A compressed request's source: borrowed from memory, or read from the +/// file. +fn read_source(request: &Request) -> Result<Cow<'static, [u8]>, HRESULT> { + let size = request.source_size as usize; + if request.options & MEMORY_SOURCE != 0 { + // SAFETY: the title's source holds `size` bytes until completion. + let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; + return Ok(Cow::Borrowed(bytes)); + } + let mut bytes = vec![0; size]; + read_into(request, &mut bytes)?; + Ok(Cow::Owned(bytes)) +} + +/// Nanoseconds workers spent reading files, for the debug summary. +static READING: AtomicU64 = AtomicU64::new(0); + +/// Fills `out` (the source size) from the request's file or memory. +fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { + if request.options & MEMORY_SOURCE != 0 { + // SAFETY: the title's source holds `out.len()` bytes until completion. + out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + return Ok(()); + } + // SAFETY: a file object we created; the title keeps it open. + let file = &unsafe { &*request.source.cast::<Instance<File>>() } + .state + .file; + let started = std::time::Instant::now(); + let mut done = 0; + let result = loop { + if done == out.len() { + break Ok(()); + } + match file.seek_read(&mut out[done..], request.offset + done as u64) { + Ok(0) => break Err(END_OF_FILE), + Ok(n) => done += n, + Err(error) => break Err(from_win32(&error)), + } + }; + READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + result +} + +/// Runs `fill` on the destination's first `len` bytes; `fill` returns how +/// many it produced. GPU-visible destinations are host memory like the +/// rest (GPU address = CPU address), so an address is written in place; +/// physical pages go through a buffer. +fn into_destination( + request: &Request, + len: usize, + fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>, +) -> Result<(), HRESULT> { + if request.options & PAGE_DESTINATION == 0 { + // Raw reads land through the kernel, which does not fault into the + // GPU side's guard on title buffers; open them first. + victory_gpu::kernel_will_write(request.destination as usize, len); + // SAFETY: the title's destination holds `destination_size` bytes, at + // least `len`, and nothing else writes it until completion. + let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) }; + return fill(out).map(drop); + } + let mut data = vec![0; len]; + let n = fill(&mut data)?; + let offset = (request.page_offset & 0xffff) as usize; + let pages = (offset + n).div_ceil(PAGE); + // SAFETY: the title passes a page number per 64 KiB of destination. + let pages = unsafe { std::slice::from_raw_parts(request.destination.cast::<usize>(), pages) }; + if super::xmem::write_physical(pages, offset, &data[..n]) { + Ok(()) + } else { + Err(E_INVALIDARG) + } +} + +/// Slots by the 2020 order, which the argument shapes at Grand Theft Auto +/// VI's call sites match (0x18, 0x20, 0x30 and 0x40 are called). +static QUEUE_VTABLE: Methods<12> = Methods([ + missing::<0> as *const (), + add_ref_instance::<Queue> as *const (), + release::<Queue> as *const (), + enqueue_request as *const (), // 0x18 + enqueue_status as *const (), // 0x20 + missing::<5> as *const (), // 0x28 (2020: fence signal) + submit as *const (), // 0x30 + missing::<7> as *const (), // 0x38 (2020: cancel by tag) + close as *const (), // 0x40 + missing::<9> as *const (), // 0x48 (2020: error event) + missing::<10> as *const (), // 0x50 (2020: error record) + missing::<11> as *const (), // 0x58 (2020: queue info) +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dstorage", + dlls: &["xcrdapi.dll"], + exports: vec![hle_export!(DStorageGetFactory)], + } +} + +#[cfg(test)] +mod tests { + use std::os::windows::ffi::OsStrExt; + use std::time::{Duration, Instant}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn call<F: Copy>(object: *mut c_void, slot: usize) -> F { + // SAFETY: every object here starts with the runtime header. + method(unsafe { &*object.cast::<Object>() }, slot) + } + + fn factory() -> *mut c_void { + let mut factory = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&FACTORY, &mut factory), S_OK); + factory + } + + fn open(path: &std::path::Path) -> *mut c_void { + let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect(); + let open: extern "system" fn(*mut c_void, *const u16, *const Guid, Out) -> HRESULT = + call(factory(), 0x20); + let mut file = std::ptr::null_mut(); + assert_eq!( + open(factory(), wide.as_ptr(), std::ptr::null(), &mut file), + S_OK + ); + file + } + + fn status_array(capacity: u32) -> *mut c_void { + let create: extern "system" fn( + *mut c_void, + u32, + *const c_char, + *const Guid, + Out, + ) -> HRESULT = call(factory(), 0x28); + let mut array = std::ptr::null_mut(); + let name = c"test".as_ptr(); + assert_eq!( + create(factory(), capacity, name, std::ptr::null(), &mut array), + S_OK + ); + array + } + + fn new_queue(source_type: u64) -> *mut c_void { + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type, + capacity: 0x80, + priority: 0, + name: c"test".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + queue + } + + fn request( + options: u64, + destination: *mut c_void, + destination_size: usize, + source: *const c_void, + offset: u64, + source_size: usize, + ) -> Request { + Request { + options, + destination, + page_offset: 0, + destination_size: destination_size as u32, + source, + offset, + source_size: source_size as u32, + intermediate_size: 0, + tag: 0, + name: std::ptr::null(), + } + } + + fn enqueue(queue: *mut c_void, request: &Request) { + let f: extern "system" fn(*mut c_void, *const Request) = call(queue, 0x18); + f(queue, request); + } + + fn enqueue_status(queue: *mut c_void, array: *mut c_void, index: u32) { + let f: extern "system" fn(*mut c_void, *mut c_void, u32) = call(queue, 0x20); + f(queue, array, index); + } + + fn void(object: *mut c_void, slot: usize) { + let f: extern "system" fn(*mut c_void) = call(object, slot); + f(object); + } + + fn result(array: *mut c_void, index: u32) -> HRESULT { + let f: extern "system" fn(*mut c_void, u32) -> HRESULT = call(array, 0x20); + f(array, index) + } + + /// Polls as the title does, then returns the entry's result. + fn wait(array: *mut c_void, index: u32) -> HRESULT { + let done: extern "system" fn(*mut c_void, u32) -> bool = call(array, 0x18); + let start = Instant::now(); + while !done(array, index) { + assert!(start.elapsed() < Duration::from_secs(10), "never completed"); + std::thread::sleep(Duration::from_millis(1)); + } + result(array, index) + } + + fn file_with(bytes: &[u8]) -> (tempfile::TempDir, *mut c_void) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, bytes).unwrap(); + let file = open(&path); + (dir, file) + } + + fn pattern(n: usize) -> Vec<u8> { + (0..n).map(|i| (i * 7 + i / 251) as u8).collect() + } + + #[test] + fn request_layout_is_the_titles() { + assert_eq!(size_of::<Request>(), 0x48); + assert_eq!(std::mem::offset_of!(Request, destination_size), 0x18); + assert_eq!(std::mem::offset_of!(Request, source), 0x20); + assert_eq!(std::mem::offset_of!(Request, source_size), 0x30); + assert_eq!(std::mem::offset_of!(Request, name), 0x40); + assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); + } + + #[test] + fn raw_and_zlib_reads_from_a_file() { + let plain = pattern(300_000); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let mut contents = plain.clone(); + contents.extend_from_slice(&packed); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(1)); + + let mut raw = vec![0u8; 1000]; + let mut inflated = vec![0u8; plain.len()]; + let at = |b: &mut Vec<u8>| b.as_mut_ptr().cast(); + enqueue(queue, &request(0, at(&mut raw), 1000, file, 5000, 1000)); + let offset = plain.len() as u64; + let zlib = request( + ZLIB, + at(&mut inflated), + plain.len(), + file, + offset, + packed.len(), + ); + enqueue(queue, &zlib); + enqueue_status(queue, array, 0); + assert_eq!(result(array, 0), E_PENDING, "pending until done"); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(raw, plain[5000..6000]); + assert_eq!(inflated, plain); + void(queue, 0x40); + } + + #[test] + fn memory_sources_inflate_too() { + let plain = pattern(70_000); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let (queue, array) = (new_queue(1), status_array(1)); + let mut out = vec![0u8; plain.len()]; + let options = ZLIB | MEMORY_SOURCE; + let r = request( + options, + out.as_mut_ptr().cast(), + out.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain); + } + + #[test] + fn statuses_complete_in_order_with_the_first_failure() { + let contents = pattern(4096); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(3)); + // Requests in flight together run in any order, so none of them + // shares a destination (failed ones leave theirs undefined). + let mut buffers = [[0u8; 16]; 5]; + let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + + // Segment 0: a read past the end, then a bad stream; the first wins. + enqueue(queue, &request(0, failed, 16, file, 4090, 16)); + enqueue(queue, &request(ZLIB, failed_too, 16, file, 0, 16)); + enqueue_status(queue, array, 0); + // Segment 1: two reads. + enqueue(queue, &request(0, other, 16, file, 0, 16)); + enqueue(queue, &request(0, out, 16, file, 100, 16)); + enqueue_status(queue, array, 1); + void(queue, 0x30); + // Segment 2: a BCPack request (BC7) whose stream is empty fails. + with_test_tables(); + enqueue(queue, &request(7 << 1, bcpack, 16, file, 0, 0)); + enqueue_status(queue, array, 2); + void(queue, 0x30); + + assert_eq!(wait(array, 2), INVALID_DATA); + assert_eq!(result(array, 0), END_OF_FILE); + assert_eq!(result(array, 1), S_OK); + assert_eq!(buffers[2], contents[100..116]); + assert_eq!(buffers[3], contents[..16]); + } + + #[test] + fn half_a_queue_submits_itself() { + let (_dir, file) = file_with(&pattern(64)); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"small".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); + enqueue_status(queue, array, 0); // the second of four: no submit needed + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, pattern(64)[8..24]); + } + + /// Lanes without workers: what `start` picks, and when statuses land. + fn lanes(staging: u64) -> Lanes { + Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + } + } + + fn read(lanes: &mut Lanes, id: u64, options: u64, size: u32) { + let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0); + (r.destination_size, r.source_size) = (size, size); + let lane = lanes.lanes.get_mut(&id).unwrap(); + lane.unsubmitted.push(Command::Read(r)); + } + + #[test] + fn priorities_share_by_bytes_about_tenfold() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 4096)); + l.lanes.insert(1, Lane::new(1, 4096)); + l.lanes.insert(2, Lane::new(2, 4096)); // real-time: as high + for _ in 0..400 { + for id in 0..3 { + read(&mut l, id, 0, 4096); + } + } + (0..3).for_each(|id| l.submit(id)); + let mut started = [0u32; 3]; + for _ in 0..330 { + let job = l.start().unwrap(); + started[job.lane as usize] += 1; + l.finish(&job, Ok(())); + } + // Normal gets about a tenth of what high and real-time get together. + assert_eq!(started[1] + started[2], 300, "{started:?}"); + assert_eq!(started[0], 30, "{started:?}"); + assert!(started[1].abs_diff(started[2]) <= 1, "{started:?}"); + } + + #[test] + fn staging_bounds_compressed_bytes_in_flight() { + let mut l = lanes(100); + l.lanes.insert(0, Lane::new(0, 64)); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, 0, 1000); // raw: straight to its destination + l.submit(0); + let first = l.start().unwrap(); + assert!(l.start().is_none(), "60 + 60 > 100"); + l.finish(&first, Ok(())); + let second = l.start().unwrap(); + let raw = l.start().unwrap(); + assert_eq!((second.staging, raw.staging), (60, 0)); + // Alone, a request larger than the buffer still runs. + read(&mut l, 0, ZLIB, 500); + l.submit(0); + assert!(l.start().is_none()); + l.finish(&second, Ok(())); + assert!(l.start().is_some()); + } + + #[test] + fn a_status_waits_for_every_earlier_read() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(2).cast::<Instance<StatusArray>>(); + let status = |index| { + add_ref_instance(array); + Command::Status(Status { array, index }) + }; + read(&mut l, 0, 0, 16); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(0)); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(1)); + // SAFETY: an array we created. + for entry in unsafe { &(*array).state.entries }.iter() { + entry.store(E_PENDING, Ordering::Release); + } + l.submit(0); + let jobs: Vec<Job> = (0..3).map(|_| l.start().unwrap()).collect(); + // The last read and the first finish; the second then fails. + l.finish(&jobs[2], Ok(())); + l.finish(&jobs[0], Ok(())); + let results = || (result(array.cast(), 0), result(array.cast(), 1)); + assert_eq!(results(), (E_PENDING, E_PENDING)); + l.finish(&jobs[1], Err(INVALID_DATA)); + assert_eq!(results(), (INVALID_DATA, S_OK)); + } + + #[test] + fn zlib_then_bcpack() { + with_test_tables(); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&BC4_STREAM, 6); + let (_dir, file) = file_with(&packed); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + let options = ZLIB | 4 << 1; + let mut r = request(options, out.as_mut_ptr().cast(), 16, file, 0, packed.len()); + r.intermediate_size = BC4_STREAM.len() as u32; + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits, + /// next 3 bits), in a folder kept for the test process. + fn with_test_tables() { + static DIR: OnceLock<()> = OnceLock::new(); + DIR.get_or_init(|| { + let mut t = Vec::new(); + for m in 0..128 { + let g = m / 16; + for b in 0..9 { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend([0; 256 + 64 + 256]); + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); + t.resize(bcpack::TABLES_SIZE, 0); + let dir = tempfile::tempdir().unwrap().keep(); + std::fs::write(dir.join("tables.bin"), t).unwrap(); + use_bcpack_tables(dir); + }); + } + + /// Two BC4 blocks from the format's test encoder: endpoints 10, -3 with + /// indices p -> p & 7, then the same block plus 1 everywhere. + const BC4_STREAM: [u8; 88] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 0x10, 0x10, 0x10, 0x10, 2, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24, + 0x24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 0x10, 0x10, 0x10, 0x10, 0, 0, 0, 0, + 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + + /// What `BC4_STREAM` unpacks to. + fn bc4_blocks() -> [u8; 16] { + let code = [0u64, 2, 3, 4, 5, 6, 7, 1]; + let block = |e0: u64, e1: u64, add: usize| { + let bits = (0..16).fold(0, |a, p| a | code[(p + add) & 7] << (16 + 3 * p)); + (e0 | e1 << 8 | bits).to_le_bytes() + }; + let mut out = [0; 16]; + out[..8].copy_from_slice(&block(138, 125, 0)); + out[8..].copy_from_slice(&block(139, 126, 1)); + out + } + + #[test] + fn bcpack_requests_unpack_into_the_destination() { + with_test_tables(); + let mut contents = pattern(100); + contents.extend_from_slice(&BC4_STREAM); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + #[test] + fn a_closed_queue_completes_nothing() { + let (_dir, file) = file_with(&pattern(64)); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 0, 16)); + enqueue_status(queue, array, 0); + void(queue, 0x40); + void(queue, 0x30); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(result(array, 0), E_PENDING); + assert_eq!(out, [0; 16]); + } + + #[test] + fn physical_page_destinations() { + use crate::modules::xmem; + let mut pages = [0usize; 2]; + let mut n = 2; + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), + 1 + ); + // Where the title would see them: a reservation of 64 KiB pages. + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), + mapped + ); + + let plain = pattern(100); + let (queue, array) = (new_queue(1), status_array(1)); + let mut r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + r.page_offset = (PAGE - 40) as u64; // across the page boundary + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + // SAFETY: both pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE - 40), 100) }; + assert_eq!(seen, plain); + } +} diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index a0c9eeb..8806ff8 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -33,6 +33,7 @@ macro_rules! host { unsafe { std::mem::transmute::<usize, $ty>(address) } }}; } +pub(crate) use host; /// Mounted drives: upper-case letter and host root (UTF-16, no trailing /// separator, no NUL). @@ -45,10 +46,7 @@ fn drives() -> MutexGuard<'static, Vec<(u16, Vec<u16>)>> { /// Gives the host folder `root` a drive letter (the same one if it already /// has one): the highest letter neither the host nor another mount uses. pub fn mount(root: &Path) -> Option<char> { - let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect(); - while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { - wide.pop(); - } + let wide = root_wide(root); let mut drives = drives(); if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) { return char::from_u32(letter.into()); @@ -63,15 +61,81 @@ pub fn mount(root: &Path) -> Option<char> { Some(letter.into()) } +/// Gives the host folder `root` a drive letter the console fixes (titles +/// open their package as `G:\..` and temporary files as `T:\..`). A host +/// drive of that letter is hidden from the title. +pub fn mount_at(letter: char, root: &Path) { + let letter = letter.to_ascii_uppercase(); + let Some(index) = u32::from(letter) + .checked_sub(u32::from('A')) + .filter(|i| *i < 26) + else { + return; + }; + // SAFETY: no arguments. + let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0; + tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive"); + let mut drives = drives(); + drives.retain(|(l, _)| u32::from(*l) != u32::from(letter)); + drives.push((letter as u16, root_wide(root))); +} + +/// `root` as UTF-16, absolute, without trailing separators (a drive root +/// keeps its own). +fn root_wide(root: &Path) -> Vec<u16> { + let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); + let mut wide: Vec<u16> = root.as_os_str().encode_wide().collect(); + while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { + wide.pop(); + } + wide +} + const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; +/// Host paths from this length on take the `\\?\` form, which lifts the +/// host's MAX_PATH limit (248 characters for a directory, 260 for a file). +const LONG: usize = 248; + +/// `root` and the title's `tail` as a `\\?\` path. That form turns off the +/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved +/// here (`..` stops at the root). +fn verbatim(root: &[u16], tail: &[u16]) -> Vec<u16> { + let backslash = u16::from(b'\\'); + let mut out = if root.starts_with(&VERBATIM) { + root.to_vec() + } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { + let mut out = VERBATIM.to_vec(); + out.extend("UNC\\".encode_utf16()); + out.extend_from_slice(unc); + out + } else { + [&VERBATIM[..], root].concat() + }; + while out.last() == Some(&backslash) { + out.pop(); + } + let dot = u16::from(b'.'); + let mut parts: Vec<&[u16]> = Vec::new(); + for part in tail.split(|c| SEPARATORS.contains(c)) { + match part { + [] => {} + [d] if *d == dot => {} + [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), + _ => parts.push(part), + } + } + for part in parts { + out.push(backslash); + out.extend_from_slice(part); + } + out +} + /// The host path, NUL-terminated, for `path` (without its NUL) if it is on /// a virtual drive. -// shortcut: host roots are not made verbatim, so a long host root can push a -// title path past MAX_PATH; switch to `\\?\` paths (normalising `..` and `/` -// ourselves) if a title's paths get that long. -fn translate(path: &[u16]) -> Option<Vec<u16>> { +pub(crate) fn translate(path: &[u16]) -> Option<Vec<u16>> { let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { Some(rest) => (&VERBATIM[..], rest), None => (&[][..], path), @@ -87,6 +151,11 @@ fn translate(path: &[u16]) -> Option<Vec<u16>> { let drives = drives(); let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; let tail = &rest[2..]; + if prefix.is_empty() && root.len() + tail.len() >= LONG { + let mut out = verbatim(root, tail); + out.push(0); + return Some(out); + } let mut out = prefix.to_vec(); out.extend_from_slice(root); // `X:` and `X:name` are relative to the root. @@ -124,7 +193,18 @@ fn wide(path: *const u16) -> Wide { let len = (0..).take_while(|&i| *path.add(i) != 0).count(); std::slice::from_raw_parts(path, len) }; - Wide(path, translate(path_slice)) + let host = translate(path_slice); + trace(path_slice, host.as_deref()); + Wide(path, host) +} + +/// Every title path at debug level, with the host path if rewritten. +fn trace(path: &[u16], host: Option<&[u16]>) { + tracing::debug!( + path = %String::from_utf16_lossy(path), + host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])), + "title path" + ); } /// A narrow path (ANSI code page, as the host decodes it) on a virtual @@ -138,7 +218,10 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> { // The drive part is ASCII in every code page; decode only candidates. match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { [letter, b':', ..] if letter.is_ascii_alphabetic() => {} - _ => return None, + _ => { + tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); + return None; + } } let len = i32::try_from(bytes.len()).ok()?; // SAFETY: sizing call, then a call with room for `n` units. @@ -148,7 +231,9 @@ fn narrow(path: *const c_char) -> Option<Vec<u16>> { MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); wide }; - translate(&wide) + let host = translate(&wide); + trace(&wide, host.as_deref()); + host } /// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call. @@ -220,6 +305,24 @@ pub extern "system" fn CreateFileA( } } +/// Used by Bink. +pub extern "system" fn CreateFile2( + path: *const u16, + access: u32, + share: u32, + disposition: u32, + params: *const c_void, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)( + p.ptr(), + access, + share, + disposition, + params, + ) +} + pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { match narrow(path) { Some(p) => { @@ -231,6 +334,35 @@ pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { } } +pub extern "system" fn DeleteFileW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 { + let p = wide(path); + host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)( + p.ptr(), + attributes, + ) +} + +pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 { + match narrow(path) { + Some(p) => GetFileAttributesW(p.as_ptr()), + None => { + host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)( + path, + ) + } + } +} + pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 { let p = wide(path); host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( @@ -252,6 +384,11 @@ pub extern "system" fn GetFileAttributesExW( ) } +pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr()) +} + pub extern "system" fn GetDiskFreeSpaceExW( path: *const u16, available: *mut u64, @@ -369,6 +506,34 @@ pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> Fi ) } +// Kernel reads into title memory. The GPU side leaves blocks of title GPU +// buffers read-only to see the title's next write, and the kernel's writes +// fail there instead of faulting into its handler; Grand Theft Auto VI's +// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned +// destinations and retry a failed `ReadFile` forever. So the destination +// is opened first. + +pub extern "system" fn ReadFile( + file: *mut c_void, + buffer: *mut u8, + len: u32, + read: *mut u32, + overlapped: *mut c_void, +) -> i32 { + victory_gpu::kernel_will_write(buffer as usize, len as usize); + host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + file, buffer, len, read, overlapped, + ) +} + +/// The host CRT reads large requests straight into the caller's buffer. +pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { + victory_gpu::kernel_will_write(buffer as usize, size.saturating_mul(count)); + host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize)( + buffer, size, count, stream, + ) +} + pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { match narrow(path) { Some(p) => _wfopen(p.as_ptr(), widen(mode).as_ptr()), @@ -391,6 +556,31 @@ pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_ch } } +/// `_open(path, flags[, mode])` is variadic; on x64 the optional integer +/// travels in the same register either way, so it is passed on as is. +pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.as_ptr(), + flags, + mode, + ), + None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)( + path, flags, mode, + ), + } +} + +/// See [`_open`]; used by libHttpClient. +pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.ptr(), + flags, + mode, + ) +} + pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 { let p = wide(path); host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat) @@ -435,17 +625,22 @@ pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 { // The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`. const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z"; +const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z"; + +/// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File { + let p = wide(path); + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.ptr(), + mode, + protection, + ) +} /// `_Fiopen(const char* path, ios_base::openmode, int protection)`. extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { match narrow(path) { - Some(p) => { - host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( - p.as_ptr(), - mode, - protection, - ) - } + Some(p) => fiopen_wide(p.as_ptr(), mode, protection), None => { host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( path, mode, protection, @@ -469,10 +664,18 @@ pub(crate) fn module() -> HleModule { "msvcp140.dll", ], exports: vec![ + hle_export!(ReadFile), + hle_export!(fread), hle_export!(CreateFileW), hle_export!(CreateFileA), + hle_export!(CreateFile2), hle_export!(DeleteFileA), + hle_export!(DeleteFileW), + hle_export!(RemoveDirectoryW), + hle_export!(SetFileAttributesW), + hle_export!(GetFileAttributesA), hle_export!(CreateDirectoryW), + hle_export!(GetFileAttributesW), hle_export!(GetFileAttributesExW), hle_export!(GetDiskFreeSpaceExW), hle_export!(GetDiskFreeSpaceW), @@ -485,6 +688,8 @@ pub(crate) fn module() -> HleModule { hle_export!(_wfsopen), hle_export!(fopen), hle_export!(fopen_s), + hle_export!(_open), + hle_export!(_wopen), hle_export!(_wstat64), hle_export!(_stat64i32), hle_export!(remove), @@ -494,6 +699,10 @@ pub(crate) fn module() -> HleModule { name: FIOPEN, address: fiopen as *const () as usize, }, + HleExport { + name: FIOPEN_WIDE, + address: fiopen_wide as *const () as usize, + }, ], } } @@ -506,6 +715,19 @@ mod tests { s.encode_utf16().chain([0]).collect() } + #[test] + fn kernel_reads_reach_the_buffer() { + use std::os::windows::io::AsRawHandle; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, b"0123456789").unwrap(); + let file = std::fs::File::open(&path).unwrap(); + let (mut out, mut n) = ([0u8; 10], 0); + let handle = file.as_raw_handle().cast(); + assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); + assert_eq!((&out, n), (b"0123456789", 10)); + } + fn text(v: &[u16]) -> String { String::from_utf16_lossy(&v[..v.len() - 1]) } @@ -535,6 +757,45 @@ mod tests { assert_eq!(tr(r"C:\Windows".into()), None); assert_eq!(tr("relative/path".into()), None); assert_eq!(tr(String::new()), None); + + // Fixed letters, as the console's package drive; a later mount of + // the same letter replaces the earlier one. + let package = tempfile::tempdir().unwrap(); + mount_at('g', dir.path()); + mount_at('G', package.path()); + assert_eq!( + tr(r"G:\appdata0.rpf".into()), + Some(format!(r"{}\appdata0.rpf", package.path().display())) + ); + assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones"); + + // Long ones take the `\\?\` form, cleaned up as the host would. + let long = "d".repeat(250); + assert_eq!( + tr(format!(r"G:/a/./b/../{long}//f")), + Some(format!(r"\\?\{}\a\{long}\f", package.path().display())) + ); + assert_eq!( + verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]), + w(r"\\?\UNC\server\share\y")[..22].to_vec() + ); + } + + #[test] + fn long_title_paths_work_on_the_host() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100)); + let null = std::ptr::null_mut(); + let first = w(&deep[..203]); + assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0); + assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0); + let file = format!("{deep}/../{}/f.txt", "b".repeat(100)); + let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr()); + assert!(!f.is_null(), "{file}"); + host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f); + assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0); + assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0); } #[test] @@ -576,6 +837,27 @@ mod tests { assert_eq!(remove(path.as_ptr().cast()), 0); assert!(!dir.path().join("stream.txt").exists()); + let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("wide.txt").is_file()); + + const OPEN_EXISTING: u32 = 3; + let path = w(&format!(r"{letter}:\created.bin")); + let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null); + assert_ne!(h as isize, -1); + close(h); + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES); + + const O_WRONLY: i32 = 1; + const O_CREAT: i32 = 0x100; + const S_IWRITE: i32 = 0x80; + let path = format!("{letter}:/low.bin\0"); + let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE); + assert!(fd >= 0); + host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd); + assert!(dir.path().join("low.bin").is_file()); // Other paths pass through untouched. let host_path = format!("{}\0", dir.path().join("plain.txt").display()); diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index f84e714..a411bd0 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -1,51 +1,556 @@ -//! `gameinput.dll`: input devices. For now nothing is ever connected: -//! readings and device lookups fail as they do with no device plugged in, -//! callbacks are accepted and never called. +//! `gameinput.dll`: input devices from the host. Gamepads come from XInput +//! (host slots 0-3); while none is connected, the keyboard drives one +//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! too. A poll thread turns host state into readings (a new one per change) +//! and runs device callbacks on connect and disconnect. #![allow(non_snake_case)] -// Title code calls these through the object, passing pointers the real API +// Title code calls these through the objects, passing pointers the real API // would trust. #![allow(clippy::not_unsafe_ptr_arg_deref)] +use std::collections::VecDeque; use std::ffi::c_void; -use std::sync::LazyLock; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Instant; +use std::ops::Deref; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::thread::ThreadId; +use std::time::{Duration, Instant}; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::{HleExport, HleModule}; -/// The documented "no such reading" and "no such device" errors. -pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +/// The documented errors. +pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32; pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; +pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +pub const REFERENCE_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32; const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +/// Input kinds (bits) our devices have. +const KEYBOARD_KIND: u32 = 0x10; +const GAMEPAD_KIND: u32 = 0x4_0000; +/// Device status of a connected device: connected, input enabled. +const STATUS_CONNECTED: u32 = 0x3; +const ASYNC_ENUMERATION: u32 = 1; + +/// Gamepad buttons; the title maps each bit to one of its pad buttons. +const MENU: u32 = 0x1; +const VIEW: u32 = 0x2; +const A: u32 = 0x4; +const B: u32 = 0x8; +const X: u32 = 0x10; +const Y: u32 = 0x20; +const UP: u32 = 0x40; +const DOWN: u32 = 0x80; +const LEFT: u32 = 0x100; +const RIGHT: u32 = 0x200; +const LEFT_SHOULDER: u32 = 0x400; +const RIGHT_SHOULDER: u32 = 0x800; +const LEFT_STICK: u32 = 0x1000; +const RIGHT_STICK: u32 = 0x2000; + +/// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. +const PADS: usize = 4; +const FALLBACK: usize = PADS; +const KEYBOARD: usize = PADS + 1; +const DEVICES: usize = PADS + 2; + +/// Readings kept per device for next/previous lookups. +const HISTORY: usize = 32; +const POLL: Duration = Duration::from_millis(8); + +/// The keyboard's stand-in gamepad (virtual key, button); README lists it. +/// Sticks: W/A/S/D left, I/J/K/L right; triggers Z and C. +const FALLBACK_BUTTONS: [(u8, u32); 14] = [ + (0x1B, MENU), // Esc + (0x09, VIEW), // Tab + (0x0D, A), // Enter + (0x08, B), // Backspace + (b'X', X), + (b'Y', Y), + (0x26, UP), // arrows + (0x28, DOWN), + (0x25, LEFT), + (0x27, RIGHT), + (b'Q', LEFT_SHOULDER), + (b'E', RIGHT_SHOULDER), + (b'F', LEFT_STICK), + (b'H', RIGHT_STICK), +]; + +/// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive). #[repr(C)] -pub struct Object { - vtable: &'static Vtable, +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct PadState { + buttons: u32, + left_trigger: f32, + right_trigger: f32, + left_x: f32, + left_y: f32, + right_x: f32, + right_y: f32, +} + +/// One key held down: scan code (0xE0xx when extended), character, key. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct KeyState { + scan_code: u32, + code_point: u32, + virtual_key: u8, + dead_key: bool, +} + +const _: () = assert!(size_of::<KeyState>() == 12 && size_of::<PadState>() == 28); + +/// Host input, or a fake in tests. +trait Source: Send { + /// The pad in host slot `slot`, `None` when the slot is empty. + fn pad(&mut self, slot: usize) -> Option<PadState>; + /// Keys held down; none while the title's window lacks focus. + fn keys(&mut self) -> Vec<KeyState>; + /// Motor speeds: low frequency (left), high frequency (right). + fn rumble(&mut self, slot: usize, low: u16, high: u16); +} + +fn fallback(keys: &[KeyState]) -> PadState { + let on = |vk: u8| { + if keys.iter().any(|k| k.virtual_key == vk) { + 1.0 + } else { + 0.0 + } + }; + PadState { + buttons: FALLBACK_BUTTONS + .iter() + .filter(|(vk, _)| on(*vk) != 0.0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: on(b'Z'), + right_trigger: on(b'C'), + left_x: on(b'D') - on(b'A'), + left_y: on(b'W') - on(b'S'), + right_x: on(b'L') - on(b'J'), + right_y: on(b'I') - on(b'K'), + } } #[repr(C)] -struct Vtable([*const (); 22]); +struct Table<const N: usize>([*const (); N]); // SAFETY: function addresses only. -unsafe impl Sync for Vtable {} +unsafe impl<const N: usize> Sync for Table<N> {} -static OBJECT: Object = Object { vtable: &VTABLE }; +/// The input object; one per hub. +#[repr(C)] +pub struct Object { + vtable: &'static Table<22>, + hub: *const Hub, +} + +#[repr(C)] +pub struct Device { + vtable: &'static Table<21>, + hub: *const Hub, + index: usize, + info: DeviceInfo, +} + +/// What a device says about itself. The title reads `id` (+0x20); the rest +/// follows the public layout and is zero where we have nothing to say. +#[repr(C)] +#[derive(Default)] +#[allow(dead_code)] // read by title code +struct DeviceInfo { + size: u32, + vendor: u16, + product: u16, + revision: u16, + interface: u8, + collection: u8, + usage: [u16; 2], + versions: [u16; 8], + id: [u8; 32], + root_id: [u8; 32], + family: i32, + capabilities: u32, + supported_input: u32, + rumble_motors: u32, + /// Counts and optional detail pointers. + rest: [u64; 26], +} + +const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20); + +fn kind(index: usize) -> u32 { + if index == KEYBOARD { + KEYBOARD_KIND + } else { + GAMEPAD_KIND + } +} + +impl Device { + fn new(index: usize) -> Device { + let mut id = [0; 32]; + id[..7].copy_from_slice(b"victory"); + id[31] = index as u8 + 1; + let info = DeviceInfo { + size: size_of::<DeviceInfo>() as u32, + id, + root_id: id, + supported_input: kind(index), + // Low and high frequency. + rumble_motors: if index < PADS { 0x3 } else { 0 }, + ..Default::default() + }; + Device { + vtable: &DEVICE, + hub: std::ptr::null(), + index, + info, + } + } + + fn hub(&self) -> &'static Hub { + // SAFETY: set by `Hub::new`; hubs are never freed. + unsafe { &*self.hub } + } +} + +#[derive(PartialEq)] +enum Value { + Pad(PadState), + Keys(Vec<KeyState>), +} + +#[repr(C)] +pub struct Reading { + vtable: &'static Table<25>, + refs: AtomicU32, + device: *const Device, + sequence: u64, + timestamp: u64, + value: Value, +} + +impl Reading { + fn kind(&self) -> u32 { + match self.value { + Value::Pad(_) => GAMEPAD_KIND, + Value::Keys(_) => KEYBOARD_KIND, + } + } +} + +/// A counted reference to a reading. +struct Ref(NonNull<Reading>); + +impl Ref { + fn new(reading: Reading) -> Ref { + Ref(NonNull::from(Box::leak(Box::new(reading)))) + } + + /// Another reference, for the title. + fn share(&self) -> *const Reading { + reading_add_ref(self.0.as_ptr()); + self.0.as_ptr() + } +} + +impl Deref for Ref { + type Target = Reading; + fn deref(&self) -> &Reading { + // SAFETY: we hold a reference, so it is alive. + unsafe { self.0.as_ref() } + } +} + +impl Drop for Ref { + fn drop(&mut self) { + reading_release(self.0.as_ptr()); + } +} + +type DeviceCallback = extern "system" fn(u64, *mut c_void, *const Device, u64, u32, u32); + +#[derive(Clone, Copy)] +struct Registration { + token: u64, + /// One device's address, or 0 for any. + device: usize, + kind: u32, + status: u32, + context: usize, + callback: DeviceCallback, +} + +impl Registration { + fn matches(&self, devices: &[Device; DEVICES], index: usize) -> bool { + kind(index) & self.kind != 0 + && (self.device == 0 || self.device == &devices[index] as *const Device as usize) + } + + fn event(&self, device: usize, timestamp: u64, current: u32, previous: u32) -> Event { + Event { + registration: *self, + device, + timestamp, + current, + previous, + } + } +} + +struct Event { + registration: Registration, + device: usize, + timestamp: u64, + current: u32, + previous: u32, +} + +#[derive(Default)] +struct Slot { + connected: bool, + sequence: u64, + history: VecDeque<Ref>, +} + +struct State { + slots: [Slot; DEVICES], + callbacks: Vec<Registration>, + /// Asynchronous enumerations, delivered by the next poll. + pending: Vec<Event>, + /// Device callbacks running now: token and thread. + running: Vec<(u64, ThreadId)>, +} + +pub struct Hub { + object: Object, + devices: [Device; DEVICES], + /// Apart from the state: XInput can be slow, and the title reads + /// readings every frame. + source: Mutex<Box<dyn Source>>, + state: Mutex<State>, + /// A device callback returned. + returned: Condvar, +} + +fn lock<T: ?Sized>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +// SAFETY: the back pointers are set before the hub is shared and never +// change; what changes sits behind the mutex or is atomic. +unsafe impl Send for Hub {} +// SAFETY: as above. +unsafe impl Sync for Hub {} + +static START: LazyLock<Instant> = LazyLock::new(Instant::now); + +/// Microseconds, the clock of every timestamp we hand out. +fn now() -> u64 { + START.elapsed().as_micros() as u64 +} + +impl Hub { + fn new(source: Box<dyn Source>) -> &'static Hub { + let hub = Box::into_raw(Box::new(Hub { + object: Object { + vtable: &INPUT, + hub: std::ptr::null(), + }, + devices: std::array::from_fn(Device::new), + source: Mutex::new(source), + state: Mutex::new(State { + slots: Default::default(), + callbacks: Vec::new(), + pending: Vec::new(), + running: Vec::new(), + }), + returned: Condvar::new(), + })); + // SAFETY: just allocated and never freed; nothing else sees it yet. + unsafe { + (*hub).object.hub = hub; + for device in &mut (*hub).devices { + device.hub = hub; + } + &*hub + } + } + + /// A hub over the host's input, polled from now on. + fn start(source: Box<dyn Source>) -> &'static Hub { + let hub = Hub::new(source); + hub.poll(); + std::thread::spawn(move || { + loop { + std::thread::sleep(POLL); + hub.poll(); + } + }); + hub + } + + fn state(&self) -> MutexGuard<'_, State> { + lock(&self.state) + } + + /// Reads the host once; device callbacks run on the calling thread. + fn poll(&self) { + let (pads, keys) = { + let mut source = lock(&self.source); + let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); + (pads, source.keys()) + }; + let events = self.state().poll(&self.devices, pads, keys); + self.deliver(events); + } + + /// Runs callbacks, never under our lock: they call back into us. One + /// unregistered since the event was taken does not run, and + /// `UnregisterCallback` waits for one that runs. + fn deliver(&self, events: Vec<Event>) { + let me = std::thread::current().id(); + for e in events { + let r = e.registration; + { + let mut state = self.state(); + if !state.callbacks.iter().any(|c| c.token == r.token) { + continue; + } + state.running.push((r.token, me)); + } + (r.callback)( + r.token, + r.context as *mut c_void, + &self.devices[e.device], + e.timestamp, + e.current, + e.previous, + ); + let mut state = self.state(); + if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) { + state.running.swap_remove(i); + } + self.returned.notify_all(); + } + } + + fn index(&self, device: *const Device) -> Option<usize> { + self.devices.iter().position(|d| std::ptr::eq(d, device)) + } +} + +impl State { + fn poll( + &mut self, + devices: &[Device; DEVICES], + pads: [Option<PadState>; PADS], + keys: Vec<KeyState>, + ) -> Vec<Event> { + let now = now(); + let mut events = std::mem::take(&mut self.pending); + let any_pad = pads.iter().any(Option::is_some); + for (slot, pad) in pads.into_iter().enumerate() { + self.update(devices, slot, pad.map(Value::Pad), now, &mut events); + } + let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); + self.update(devices, FALLBACK, fallback, now, &mut events); + self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); + events + } + + /// Records a device's state: a reading when it changed, callbacks when + /// the device came or went. + fn update( + &mut self, + devices: &[Device; DEVICES], + index: usize, + value: Option<Value>, + now: u64, + events: &mut Vec<Event>, + ) { + let slot = &mut self.slots[index]; + let was = slot.connected; + slot.connected = value.is_some(); + if let Some(value) = value + && (!was || slot.history.back().is_none_or(|r| r.value != value)) + { + slot.sequence += 1; + if slot.history.len() == HISTORY { + slot.history.pop_front(); + } + slot.history.push_back(Ref::new(Reading { + vtable: &READING, + refs: AtomicU32::new(1), + device: &devices[index], + sequence: slot.sequence, + timestamp: now, + value, + })); + } + if was != slot.connected { + tracing::info!(device = index, connected = !was, "input device"); + let (current, previous) = if was { + (0, STATUS_CONNECTED) + } else { + (STATUS_CONNECTED, 0) + }; + events.extend( + self.callbacks + .iter() + .filter(|r| r.matches(devices, index) && r.status & STATUS_CONNECTED != 0) + .map(|r| r.event(index, now, current, previous)), + ); + } + } +} + +#[cfg(windows)] +fn host() -> Box<dyn Source> { + Box::new(host::Host::default()) +} + +#[cfg(not(windows))] +fn host() -> Box<dyn Source> { + struct Nothing; + impl Source for Nothing { + fn pad(&mut self, _: usize) -> Option<PadState> { + None + } + fn keys(&mut self) -> Vec<KeyState> { + Vec::new() + } + fn rumble(&mut self, _: usize, _: u16, _: u16) {} + } + Box::new(Nothing) +} + +static HUB: LazyLock<&'static Hub> = LazyLock::new(|| Hub::start(host())); type This = *const Object; type Out = *mut *const c_void; /// The DLL's only export (ordinal 1): the input object, static and shared. pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT { - tracing::info!("GameInputCreate: no input devices"); + tracing::info!("GameInputCreate"); if out.is_null() { return E_INVALIDARG; } // SAFETY: checked non-null; the title passes room for a pointer. - unsafe { out.write(&OBJECT) }; + unsafe { out.write(&HUB.object) }; S_OK } +fn hub(this: This) -> &'static Hub { + // SAFETY: `this` is a hub's object; hubs are never freed. + unsafe { &*(*this).hub } +} + /// Clears a COM out pointer and returns `hr`. fn fail(out: Out, hr: HRESULT) -> HRESULT { if !out.is_null() { @@ -55,45 +560,146 @@ fn fail(out: Out, hr: HRESULT) -> HRESULT { hr } -extern "system" fn query_interface(_: This, _iid: *const c_void, out: Out) -> HRESULT { +/// Gives the title a reference to `reading`, or fails as with none. +fn hand(out: Out, reading: Option<&Ref>) -> HRESULT { + match reading { + _ if out.is_null() => E_INVALIDARG, + Some(reading) => { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(reading.share().cast()) }; + S_OK + } + None => fail(out, READING_NOT_FOUND), + } +} + +extern "system" fn no_interface(_: *const c_void, _iid: *const c_void, out: Out) -> HRESULT { tracing::warn!("input QueryInterface not implemented"); fail(out, E_NOINTERFACE) } -extern "system" fn add_ref(_: This) -> u32 { +/// The input object and devices live as long as the process. +extern "system" fn add_ref(_: *const c_void) -> u32 { 1 } -static START: LazyLock<Instant> = LazyLock::new(Instant::now); - -/// Microseconds; only ever compared with readings, and there are none. extern "system" fn timestamp(_: This) -> u64 { - START.elapsed().as_micros() as u64 + now() } extern "system" fn current_reading( - _: This, - _kind: u32, - _device: *const c_void, + this: This, + kind: u32, + device: *const Device, out: Out, ) -> HRESULT { - fail(out, READING_NOT_FOUND) + let hub = hub(this); + let state = hub.state(); + let newest = |i: usize| { + state.slots[i] + .history + .back() + .filter(|r| r.kind() & kind != 0) + }; + let found = if device.is_null() { + (0..DEVICES) + .filter(|&i| state.slots[i].connected) + .filter_map(newest) + .max_by_key(|r| r.timestamp) + } else { + match hub.index(device) { + None => return fail(out, E_INVALIDARG), + Some(i) if !state.slots[i].connected => return fail(out, DEVICE_DISCONNECTED), + Some(i) => newest(i), + } + }; + tracing::trace!( + kind = format_args!("{kind:#x}"), + device = ?hub.index(device), + sequence = found.map(|r| r.sequence), + "current reading" + ); + hand(out, found) } -extern "system" fn relative_reading( - _: This, - _reference: *const c_void, - _kind: u32, - _device: *const c_void, + +/// The reading after (`forward`) or before `reference` on its device. +fn relative( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, + forward: bool, +) -> HRESULT { + if reference.is_null() { + return fail(out, E_INVALIDARG); + } + let hub = hub(this); + // SAFETY: a reading we handed out and the title still holds. + let reference = unsafe { &*reference }; + // shortcut: with no device given only the reference's device is walked, + // not every device's readings in time order; Grand Theft Auto VI walks + // only keyboard readings (one device) and the current pad's previous one. + let Some(index) = hub.index(reference.device) else { + return fail(out, E_INVALIDARG); + }; + if !device.is_null() && !std::ptr::eq(device, reference.device) { + return fail(out, E_INVALIDARG); + } + let state = hub.state(); + let history = &state.slots[index].history; + if history + .front() + .is_none_or(|oldest| reference.sequence < oldest.sequence) + { + return fail(out, REFERENCE_TOO_OLD); + } + let wanted = |r: &&Ref| r.kind() & kind != 0; + let found = if forward { + history + .iter() + .filter(|r| r.sequence > reference.sequence) + .find(wanted) + } else { + history + .iter() + .rev() + .filter(|r| r.sequence < reference.sequence) + .find(wanted) + }; + hand(out, found) +} +extern "system" fn next_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, out: Out, ) -> HRESULT { - fail(out, READING_NOT_FOUND) + relative(this, reference, kind, device, out, true) } +extern "system" fn previous_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + relative(this, reference, kind, device, out, false) +} +/// The device's reading at `time`, among those still kept. extern "system" fn temporal_reading( - _: This, - _time: u64, - _device: *const c_void, + this: This, + time: u64, + device: *const Device, out: Out, ) -> HRESULT { - fail(out, READING_NOT_FOUND) + let hub = hub(this); + let Some(index) = hub.index(device) else { + return fail(out, E_INVALIDARG); + }; + let state = hub.state(); + let history = &state.slots[index].history; + hand(out, history.iter().rev().find(|r| r.timestamp <= time)) } static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); @@ -106,6 +712,8 @@ fn token(out: *mut u64) -> HRESULT { S_OK } +// shortcut: reading callbacks never run; Grand Theft Auto VI registers none +// (it polls). extern "system" fn register_reading( _: This, _device: *const c_void, @@ -115,26 +723,65 @@ extern "system" fn register_reading( _callback: *const c_void, out: *mut u64, ) -> HRESULT { + tracing::warn!("input reading callbacks are never called"); token(out) } -/// Enumerating existing devices finds none, so the callback never runs. + +/// Device callbacks run on our poll thread when a device comes or goes. +/// Enumeration reports the devices already there: blocking on the caller's +/// thread before we return (the title registers holding a lock its callback +/// takes again), asynchronous on the next poll. extern "system" fn register_device( - _: This, - _device: *const c_void, + this: This, + device: *const Device, kind: u32, - _status: u32, - _enumeration: u32, - _context: *mut c_void, - _callback: *const c_void, + status: u32, + enumeration: u32, + context: *mut c_void, + callback: Option<DeviceCallback>, out: *mut u64, ) -> HRESULT { - tracing::info!( - kind = format_args!("{kind:#x}"), - "input device callback: no devices" - ); - token(out) + let Some(callback) = callback else { + return E_INVALIDARG; + }; + let hub = hub(this); + let registration = Registration { + token: NEXT_TOKEN.fetch_add(1, Ordering::Relaxed), + device: device as usize, + kind, + status, + context: context as usize, + callback, + }; + let mut found = Vec::new(); + { + let mut state = hub.state(); + if enumeration != 0 && status & STATUS_CONNECTED != 0 { + let now = now(); + found = (0..DEVICES) + .filter(|&i| state.slots[i].connected && registration.matches(&hub.devices, i)) + .map(|i| registration.event(i, now, STATUS_CONNECTED, 0)) + .collect(); + } + tracing::info!( + kind = format_args!("{kind:#x}"), + enumeration, + devices = found.len(), + "input device callback" + ); + state.callbacks.push(registration); + if enumeration == ASYNC_ENUMERATION { + state.pending.append(&mut found); + } + } + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(registration.token) }; + } + hub.deliver(found); + S_OK } -/// Guide button and keyboard layout callbacks. +/// Guide button and keyboard layout callbacks: neither ever changes here. extern "system" fn register_other( _: This, _device: *const c_void, @@ -144,12 +791,46 @@ extern "system" fn register_other( ) -> HRESULT { token(out) } -extern "system" fn stop_callback(_: This, _token: u64) {} -extern "system" fn unregister_callback(_: This, _token: u64, _timeout: u64) -> bool { - true + +fn forget(this: This, token: u64) { + let mut state = hub(this).state(); + state.callbacks.retain(|r| r.token != token); + state.pending.retain(|e| e.registration.token != token); +} +extern "system" fn stop_callback(this: This, token: u64) { + forget(this, token); +} +/// Stops the callback, then waits up to `timeout` µs for a call of it that +/// is running; false on time-out, or from inside that callback (it cannot +/// wait for itself), as documented. Either way it is never called again. +extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> bool { + forget(this, token); + let hub = hub(this); + let me = std::thread::current().id(); + let deadline = Instant::now().checked_add(Duration::from_micros(timeout)); + let mut state = hub.state(); + loop { + let running = state.running.iter().filter(|r| r.0 == token); + if running.clone().any(|r| r.1 == me) { + return false; + } + if running.count() == 0 { + return true; + } + state = match deadline { + None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), + Some(deadline) => { + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return false; + }; + let waited = hub.returned.wait_timeout(state, left); + waited.unwrap_or_else(PoisonError::into_inner).0 + } + }; + } } -/// Dispatcher and aggregate device: not needed while nothing is connected. +/// Dispatcher and aggregate device: no title of ours asks for them. extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT { tracing::warn!("input dispatcher not implemented"); fail(out, E_NOTIMPL) @@ -158,7 +839,23 @@ extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT { tracing::warn!("aggregate input device not implemented"); fail(out, E_NOTIMPL) } -/// Lookup by id, object, platform handle or platform string. +extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRESULT { + if id.is_null() || out.is_null() { + return fail(out, E_INVALIDARG); + } + // SAFETY: checked non-null; the title passes a device id. + let id = unsafe { &*id }; + match hub(this).devices.iter().find(|d| d.info.id == *id) { + Some(device) => { + // SAFETY: checked non-null. + unsafe { out.write((device as *const Device).cast()) }; + S_OK + } + None => fail(out, DEVICE_NOT_FOUND), + } +} +/// Lookup by object, platform handle or platform string: our devices have +/// none of these. extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT { fail(out, DEVICE_NOT_FOUND) } @@ -173,14 +870,14 @@ extern "system" fn enable_oem_device( } extern "system" fn set_focus_policy(_: This, _policy: u32) {} -static VTABLE: Vtable = Vtable([ - query_interface as *const (), // 0x00 +static INPUT: Table<22> = Table([ + no_interface as *const (), // 0x00 add_ref as *const (), // 0x08 AddRef - add_ref as *const (), // 0x10 Release: the object is static + add_ref as *const (), // 0x10 Release timestamp as *const (), // 0x18 current_reading as *const (), // 0x20 - relative_reading as *const (), // 0x28 next - relative_reading as *const (), // 0x30 previous + next_reading as *const (), // 0x28 + previous_reading as *const (), // 0x30 temporal_reading as *const (), // 0x38 register_reading as *const (), // 0x40 register_device as *const (), // 0x48 @@ -190,7 +887,7 @@ static VTABLE: Vtable = Vtable([ unregister_callback as *const (), // 0x68 create_dispatcher as *const (), // 0x70 create_aggregate as *const (), // 0x78 - find_device as *const (), // 0x80 by id + find_by_id as *const (), // 0x80 find_device as *const (), // 0x88 by object find_device as *const (), // 0x90 by platform handle find_device as *const (), // 0x98 by platform string @@ -198,6 +895,166 @@ static VTABLE: Vtable = Vtable([ set_focus_policy as *const (), // 0xa8 ]); +extern "system" fn device_info(this: *const Device) -> *const DeviceInfo { + // SAFETY: one of our devices. + unsafe { &(*this).info } +} +extern "system" fn device_status(this: *const Device) -> u32 { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.hub().state().slots[device.index].connected { + STATUS_CONNECTED + } else { + 0 + } +} +// shortcut: trigger motors are dropped (XInput has none). The host API that +// drives them without a redistributable is Windows.Gaming.Input (WinRT +// `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside +// diagnostics builds; Grand Theft Auto VI sends trigger levels in slot 0x50. +extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.index >= PADS { + return; + } + let [low, high, ..] = if params.is_null() { + [0.0; 4] + } else { + // SAFETY: checked non-null; four motor levels. + unsafe { *params } + }; + let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); +} +extern "system" fn unsupported<const SLOT: usize>(_: *const c_void) -> HRESULT { + tracing::warn!( + slot = format_args!("{SLOT:#x}"), + "input device method not implemented" + ); + E_NOTIMPL +} + +static DEVICE: Table<21> = Table([ + no_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release + device_info as *const (), // 0x18 + device_status as *const (), // 0x20 + unsupported::<0x28> as *const (), // battery + unsupported::<0x30> as *const (), // force feedback + unsupported::<0x38> as *const (), // + unsupported::<0x40> as *const (), // + unsupported::<0x48> as *const (), // haptics + set_rumble as *const (), // 0x50 + unsupported::<0x58> as *const (), // input synchronization + unsupported::<0x60> as *const (), // + unsupported::<0x68> as *const (), // power off + unsupported::<0x70> as *const (), // raw device access + unsupported::<0x78> as *const (), // + unsupported::<0x80> as *const (), // + unsupported::<0x88> as *const (), // + unsupported::<0x90> as *const (), // + unsupported::<0x98> as *const (), // + unsupported::<0xa0> as *const (), // +]); + +fn reading<'a>(this: *const Reading) -> &'a Reading { + // SAFETY: a reading we handed out and the title still holds. + unsafe { &*this } +} +extern "system" fn reading_add_ref(this: *const Reading) -> u32 { + reading(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} +extern "system" fn reading_release(this: *const Reading) -> u32 { + let left = reading(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference is gone; `Ref::new` boxed it. + drop(unsafe { Box::from_raw(this.cast_mut()) }); + } + left +} +extern "system" fn input_kind(this: *const Reading) -> u32 { + reading(this).kind() +} +extern "system" fn sequence_number(this: *const Reading, kind: u32) -> u64 { + let reading = reading(this); + if reading.kind() & kind != 0 { + reading.sequence + } else { + 0 + } +} +extern "system" fn reading_timestamp(this: *const Reading) -> u64 { + reading(this).timestamp +} +extern "system" fn reading_device(this: *const Reading, out: *mut *const Device) { + if !out.is_null() { + // SAFETY: checked non-null; devices need no reference. + unsafe { out.write(reading(this).device) }; + } +} +extern "system" fn key_count(this: *const Reading) -> u32 { + match &reading(this).value { + Value::Keys(keys) => keys.len() as u32, + Value::Pad(_) => 0, + } +} +extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 { + let Value::Keys(keys) = &reading(this).value else { + return 0; + }; + if out.is_null() { + return 0; + } + let n = keys.len().min(count as usize); + // SAFETY: the title passes room for `count` keys. + unsafe { std::ptr::copy_nonoverlapping(keys.as_ptr(), out, n) }; + n as u32 +} +extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bool { + match &reading(this).value { + Value::Pad(state) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(*state) }; + true + } + _ => false, + } +} +/// Kinds our devices do not have: no count, no state. +extern "system" fn nothing(_: *const c_void) -> usize { + 0 +} + +static READING: Table<25> = Table([ + no_interface as *const (), // 0x00 + reading_add_ref as *const (), // 0x08 + reading_release as *const (), // 0x10 + input_kind as *const (), // 0x18 + sequence_number as *const (), // 0x20 + reading_timestamp as *const (), // 0x28 + reading_device as *const (), // 0x30 + nothing as *const (), // 0x38 raw report + nothing as *const (), // 0x40 controller axes, buttons, switches + nothing as *const (), // 0x48 + nothing as *const (), // 0x50 + nothing as *const (), // 0x58 + nothing as *const (), // 0x60 + nothing as *const (), // 0x68 + key_count as *const (), // 0x70 + key_state as *const (), // 0x78 + nothing as *const (), // 0x80 mouse + nothing as *const (), // 0x88 touch + nothing as *const (), // 0x90 + nothing as *const (), // 0x98 motion + nothing as *const (), // 0xa0 arcade stick + nothing as *const (), // 0xa8 flight stick + gamepad_state as *const (), // 0xb0 + nothing as *const (), // 0xb8 racing wheel + nothing as *const (), // 0xc0 UI navigation +]); + pub(crate) fn module() -> HleModule { HleModule { name: "gameinput", @@ -210,21 +1067,341 @@ pub(crate) fn module() -> HleModule { } } +/// Host input: XInput pads, the keyboard while our process has focus. +#[cfg(windows)] +mod host { + use std::time::{Duration, Instant}; + + use windows_sys::Win32::System::Threading::GetCurrentProcessId; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + }; + use windows_sys::Win32::UI::Input::XboxController::{ + XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, + XINPUT_GAMEPAD_DPAD_DOWN, XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_UP, XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_LEFT_THUMB, + XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_RIGHT_THUMB, XINPUT_GAMEPAD_START, + XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y, XINPUT_STATE, XINPUT_VIBRATION, XInputGetState, + XInputSetState, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetForegroundWindow, GetWindowThreadProcessId, + }; + + use super::*; + + /// Asking XInput about an empty slot is slow; look again this often. + const EMPTY_SLOT_RECHECK: Duration = Duration::from_secs(1); + + const BUTTONS: [(u16, u32); 14] = [ + (XINPUT_GAMEPAD_START, MENU), + (XINPUT_GAMEPAD_BACK, VIEW), + (XINPUT_GAMEPAD_A, A), + (XINPUT_GAMEPAD_B, B), + (XINPUT_GAMEPAD_X, X), + (XINPUT_GAMEPAD_Y, Y), + (XINPUT_GAMEPAD_DPAD_UP, UP), + (XINPUT_GAMEPAD_DPAD_DOWN, DOWN), + (XINPUT_GAMEPAD_DPAD_LEFT, LEFT), + (XINPUT_GAMEPAD_DPAD_RIGHT, RIGHT), + (XINPUT_GAMEPAD_LEFT_SHOULDER, LEFT_SHOULDER), + (XINPUT_GAMEPAD_RIGHT_SHOULDER, RIGHT_SHOULDER), + (XINPUT_GAMEPAD_LEFT_THUMB, LEFT_STICK), + (XINPUT_GAMEPAD_RIGHT_THUMB, RIGHT_STICK), + ]; + + /// Raw values, no dead zone: titles apply their own. + pub(super) fn convert(pad: &XINPUT_GAMEPAD) -> PadState { + let stick = |v: i16| (f32::from(v) / 32767.0).max(-1.0); + PadState { + buttons: BUTTONS + .iter() + .filter(|(host, _)| pad.wButtons & host != 0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: f32::from(pad.bLeftTrigger) / 255.0, + right_trigger: f32::from(pad.bRightTrigger) / 255.0, + left_x: stick(pad.sThumbLX), + left_y: stick(pad.sThumbLY), + right_x: stick(pad.sThumbRX), + right_y: stick(pad.sThumbRY), + } + } + + #[derive(Default)] + pub(super) struct Host { + empty_until: [Option<Instant>; PADS], + } + + impl Source for Host { + fn pad(&mut self, slot: usize) -> Option<PadState> { + if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { + return None; + } + let mut state = XINPUT_STATE::default(); + // SAFETY: room for the state. + if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { + self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); + return None; + } + self.empty_until[slot] = None; + Some(convert(&state.Gamepad)) + } + + fn keys(&mut self) -> Vec<KeyState> { + #[cfg(feature = "diagnostics")] + let mut down = scripted(); + #[cfg(not(feature = "diagnostics"))] + let mut down = Vec::new(); + if focused() { + // Left/right modifier keys only, as devices report them; no + // mouse buttons (below 0x08). + let held: Vec<u8> = (0x08..=0xFE_u8) + .filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk)) + // SAFETY: plain queries. + .filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0) + .collect(); + down.extend(held); + } + down.into_iter() + .map(|vk| KeyState { + // SAFETY: plain query. + scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, + virtual_key: vk, + // shortcut: no characters (code point 0); Grand Theft + // Auto VI reads scan codes and virtual keys only. + ..Default::default() + }) + .collect() + } + + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + let speeds = XINPUT_VIBRATION { + wLeftMotorSpeed: low, + wRightMotorSpeed: high, + }; + // SAFETY: a valid vibration; an empty slot just fails. + unsafe { XInputSetState(slot as u32, &speeds) }; + } + } + + /// Debugging aid: `VICTORY_KEYS=<seconds>:<key>,...` holds each key for + /// 0.2 s that long after input starts, with or without focus. A key is a + /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, + /// `Left`, `Right` (the stand-in pad's table maps them to buttons). + #[cfg(feature = "diagnostics")] + fn scripted() -> Vec<u8> { + static SCRIPT: LazyLock<(Instant, Vec<(Duration, u8)>)> = LazyLock::new(|| { + let list = std::env::var("VICTORY_KEYS").unwrap_or_default(); + let keys = list.split(',').filter_map(|entry| { + let (at, key) = entry.split_once(':')?; + let vk = match key.trim() { + "Enter" => 0x0D, + "Esc" => 0x1B, + "Tab" => 0x09, + "Back" => 0x08, + "Up" => 0x26, + "Down" => 0x28, + "Left" => 0x25, + "Right" => 0x27, + k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => { + k.as_bytes()[0].to_ascii_uppercase() + } + _ => return None, + }; + Some(( + Duration::try_from_secs_f64(at.trim().parse().ok()?).ok()?, + vk, + )) + }); + (Instant::now(), keys.collect()) + }); + let (start, keys) = &*SCRIPT; + let now = start.elapsed(); + keys.iter() + .filter(|&&(at, _)| (at..at + Duration::from_millis(200)).contains(&now)) + .map(|&(_, vk)| vk) + .collect() + } + + /// The foreground window is one of ours (the title's or our fallback). + fn focused() -> bool { + let mut process = 0; + // SAFETY: plain queries; a null window gives process 0. + unsafe { + GetWindowThreadProcessId(GetForegroundWindow(), &mut process); + process == GetCurrentProcessId() + } + } + + #[test] + fn host_pads_convert_to_console_pads() { + let pad = XINPUT_GAMEPAD { + wButtons: XINPUT_GAMEPAD_A | XINPUT_GAMEPAD_START | XINPUT_GAMEPAD_DPAD_LEFT, + bLeftTrigger: 255, + sThumbLX: -32768, + sThumbLY: 32767, + ..Default::default() + }; + let state = convert(&pad); + assert_eq!(state.buttons, A | MENU | LEFT); + assert_eq!( + ( + state.left_trigger, + state.left_x, + state.left_y, + state.right_x + ), + (1.0, -1.0, 1.0, 0.0) + ); + } +} + #[cfg(test)] mod tests { + use std::sync::Arc; + use super::*; use crate::HleResolver; use crate::HostPolicy; use victory_loader::Provenance; use victory_pe::ImportSymbol; - fn slot<F: Copy>(object: This, offset: usize) -> F { - // SAFETY: `object` is ours. - let f = unsafe { (*object).vtable.0[offset / 8] }; + #[derive(Default)] + struct FakeHost { + pads: [Option<PadState>; PADS], + keys: Vec<KeyState>, + rumble: Vec<(usize, u16, u16)>, + } + + struct Fake(Arc<Mutex<FakeHost>>); + + impl Source for Fake { + fn pad(&mut self, slot: usize) -> Option<PadState> { + self.0.lock().unwrap().pads[slot] + } + fn keys(&mut self) -> Vec<KeyState> { + self.0.lock().unwrap().keys.clone() + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + self.0.lock().unwrap().rumble.push((slot, low, high)); + } + } + + fn fake() -> (&'static Hub, Arc<Mutex<FakeHost>>) { + let host = Arc::new(Mutex::new(FakeHost::default())); + let hub = Hub::new(Box::new(Fake(Arc::clone(&host)))); + hub.poll(); + (hub, host) + } + + fn key(virtual_key: u8) -> KeyState { + KeyState { + scan_code: u32::from(virtual_key) + 0x100, + virtual_key, + ..Default::default() + } + } + + fn slot<F: Copy, T>(object: *const T, offset: usize) -> F { + // SAFETY: our objects start with their table, which has the slot. + let f = unsafe { *(*(object as *const *const *const ())).add(offset / 8) }; // SAFETY: the caller names the slot's signature. unsafe { std::mem::transmute_copy(&f) } } + /// Device callbacks seen: device index, current and previous status. + type Log = Mutex<Vec<(usize, u32, u32)>>; + + extern "system" fn record( + _token: u64, + context: *mut c_void, + device: *const Device, + _timestamp: u64, + current: u32, + previous: u32, + ) { + // SAFETY: the test passes its log and one of the hub's devices. + let (log, index) = unsafe { (&*(context as *const Log), (*device).index) }; + log.lock().unwrap().push((index, current, previous)); + } + + fn register(hub: &Hub, kind: u32, enumeration: u32, log: &Log) -> u64 { + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option<DeviceCallback>, + *mut u64, + ) -> HRESULT; + let mut token = 0; + let context = log as *const Log as *mut c_void; + let register = slot::<Register, _>(&hub.object, 0x48); + let hr = register( + &hub.object, + std::ptr::null(), + kind, + 1, + enumeration, + context, + Some(record), + &mut token, + ); + assert_eq!(hr, S_OK); + assert_ne!(token, 0); + token + } + + fn result(hr: HRESULT, out: *const c_void) -> Result<*const Reading, HRESULT> { + if hr == S_OK { + Ok(out.cast()) + } else { + assert!(out.is_null()); + Err(hr) + } + } + + fn current(hub: &Hub, kind: u32, device: usize) -> Result<*const Reading, HRESULT> { + type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let hr = slot::<Current, _>(&hub.object, 0x20)( + &hub.object, + kind, + &hub.devices[device], + &mut out, + ); + result(hr, out) + } + + fn walk(hub: &Hub, offset: usize, from: *const Reading) -> Result<*const Reading, HRESULT> { + type Walk = extern "system" fn(This, *const Reading, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let device = reading(from).device; + let hr = + slot::<Walk, _>(&hub.object, offset)(&hub.object, from, GAMEPAD_KIND, device, &mut out); + result(hr, out) + } + + fn pad(reading: *const Reading) -> PadState { + let mut state = PadState::default(); + let get = + slot::<extern "system" fn(*const Reading, *mut PadState) -> bool, _>(reading, 0xb0); + assert!(get(reading, &mut state)); + state + } + + fn stamp(reading: *const Reading) -> (u64, u64) { + let time = slot::<extern "system" fn(*const Reading) -> u64, _>(reading, 0x28); + let sequence = slot::<extern "system" fn(*const Reading, u32) -> u64, _>(reading, 0x20); + (time(reading), sequence(reading, GAMEPAD_KIND)) + } + + fn release(reading: *const Reading) { + slot::<extern "system" fn(*const Reading) -> u32, _>(reading, 0x10)(reading); + } + #[test] fn ordinal_one_resolves_to_create() { let r = HleResolver::new(HostPolicy::none()); @@ -236,40 +1413,203 @@ mod tests { } #[test] - fn startup_sees_no_devices() { + fn pads_connect_report_and_disconnect() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + // Blocking enumeration ran before registration returned: with no + // host pad the keyboard's stand-in is the only one. + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + left_x: 0.5, + ..Default::default() + }); + hub.poll(); + assert_eq!( + log.lock().unwrap()[1..], + [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + + let first = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(first).buttons, A); + assert_eq!(pad(first).left_x, 0.5); + // No change, no new reading. + hub.poll(); + let again = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(again, first); + release(again); + + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[1].as_mut().unwrap().buttons = B; + hub.poll(); + let second = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(second).buttons, B); + let (t1, s1) = stamp(first); + let (t2, s2) = stamp(second); + assert!(t2 > t1 && s2 == s1 + 1); + assert!(t2 <= now()); + + // The title's edge check: previous of current, and back again. + assert_eq!(walk(hub, 0x30, second), Ok(first)); + assert_eq!(walk(hub, 0x28, first), Ok(second)); + assert_eq!(walk(hub, 0x28, second), Err(READING_NOT_FOUND)); + assert_eq!(walk(hub, 0x30, first), Err(READING_NOT_FOUND)); + for r in [first, first, second, second] { + release(r); + } + + host.lock().unwrap().pads[1] = None; + hub.poll(); + assert_eq!( + log.lock().unwrap()[3..], + [(1, 0, STATUS_CONNECTED), (FALLBACK, STATUS_CONNECTED, 0)] + ); + assert_eq!(current(hub, GAMEPAD_KIND, 1), Err(DEVICE_DISCONNECTED)); + // The stand-in is back, at rest. + let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + } + + #[test] + fn keys_feed_the_keyboard_and_the_stand_in_pad() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, KEYBOARD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(KEYBOARD, STATUS_CONNECTED, 0)]); + + let keys = vec![key(b'W'), key(0x0D), key(b'L'), key(b'C')]; + host.lock().unwrap().keys = keys.clone(); + hub.poll(); + let r = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); + let count = slot::<extern "system" fn(*const Reading) -> u32, _>(r, 0x70); + let state = + slot::<extern "system" fn(*const Reading, u32, *mut KeyState) -> u32, _>(r, 0x78); + assert_eq!(count(r), 4); + let mut got = [KeyState::default(); 8]; + assert_eq!(state(r, 8, got.as_mut_ptr()), 4); + assert_eq!(got[..4], keys[..]); + release(r); + + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(r), + PadState { + buttons: A, + left_y: 1.0, + right_x: 1.0, + right_trigger: 1.0, + ..Default::default() + } + ); + release(r); + // A keyboard reading is no gamepad reading. + assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); + } + + #[test] + fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() { + let (hub, host) = fake(); + let log = Log::default(); + let token = register(hub, GAMEPAD_KIND, ASYNC_ENUMERATION, &log); + assert!(log.lock().unwrap().is_empty()); + hub.poll(); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68); + assert!(unregister(&hub.object, token, 5000)); + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap().len(), 1); + } + + #[test] + fn unregistering_waits_for_a_running_callback() { + use std::sync::atomic::AtomicBool; + static INSIDE: AtomicBool = AtomicBool::new(false); + static LEAVE: AtomicBool = AtomicBool::new(false); + static FROM_INSIDE: AtomicU32 = AtomicU32::new(0); + extern "system" fn slow( + token: u64, + context: *mut c_void, + _: *const Device, + _: u64, + _: u32, + _: u32, + ) { + // From inside its own callback, unregistering fails at once. + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(context, 0x68); + if !unregister(context.cast(), token, 0) { + FROM_INSIDE.fetch_add(1, Ordering::SeqCst); + } + INSIDE.store(true, Ordering::SeqCst); + while !LEAVE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + let (hub, host) = fake(); type Register = extern "system" fn( This, - *const c_void, + *const Device, u32, u32, u32, *mut c_void, - *const c_void, + Option<DeviceCallback>, *mut u64, ) -> HRESULT; - type Reading = extern "system" fn(This, u32, *const c_void, Out) -> HRESULT; - type Find = extern "system" fn(This, *const c_void, Out) -> HRESULT; - - let mut input = std::ptr::null(); - assert_eq!(GameInputCreate(&mut input), S_OK); - assert!(!input.is_null()); - + let register = slot::<Register, _>(&hub.object, 0x48); let mut token = 0; - let register = slot::<Register>(input, 0x48); - let null = std::ptr::null_mut(); + let context = (&raw const hub.object).cast_mut().cast(); assert_eq!( - register(input, null, 0x40130, 1, 1, null, null, &mut token), + register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), S_OK ); - assert_ne!(token, 0); + host.lock().unwrap().pads[1] = Some(PadState::default()); + let poller = std::thread::spawn(|| hub.poll()); + while !INSIDE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + let unregister = slot::<extern "system" fn(This, u64, u64) -> bool, _>(&hub.object, 0x68); + assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); + let leave = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(50)); + LEAVE.store(true, Ordering::SeqCst); + }); + let start = Instant::now(); + assert!(unregister(&hub.object, token, u64::MAX), "waits for it"); + assert!(start.elapsed() >= Duration::from_millis(40)); + assert_eq!(FROM_INSIDE.load(Ordering::SeqCst), 1); + poller.join().unwrap(); + leave.join().unwrap(); + } - let mut out = 0x1234 as *const c_void; - let reading = slot::<Reading>(input, 0x20); - assert_eq!(reading(input, 4, null, &mut out), READING_NOT_FOUND); - assert!(out.is_null()); - out = 0x1234 as *const c_void; - let find = slot::<Find>(input, 0x80); - assert_eq!(find(input, null, &mut out), DEVICE_NOT_FOUND); + #[test] + fn devices_are_found_by_id_and_rumble_reaches_the_host() { + let (hub, host) = fake(); + host.lock().unwrap().pads[2] = Some(PadState::default()); + hub.poll(); + let device = &hub.devices[2] as *const Device; + let info = slot::<extern "system" fn(*const Device) -> *const u8, _>(device, 0x18); + // SAFETY: the info has the id at +0x20. + let id = unsafe { *(info(device).add(0x20) as *const [u8; 32]) }; + assert_ne!(id, [0; 32]); + + type Find = extern "system" fn(This, *const [u8; 32], Out) -> HRESULT; + let find = slot::<Find, _>(&hub.object, 0x80); + let mut out = std::ptr::null(); + assert_eq!(find(&hub.object, &id, &mut out), S_OK); + assert_eq!(out, device.cast()); + assert_eq!(find(&hub.object, &[1; 32], &mut out), DEVICE_NOT_FOUND); assert!(out.is_null()); + + type Rumble = extern "system" fn(*const Device, *const [f32; 4]); + let rumble = slot::<Rumble, _>(device, 0x50); + rumble(device, &[0.5, 1.0, 1.0, 1.0]); + rumble(&hub.devices[FALLBACK], &[1.0; 4]); + rumble(device, std::ptr::null()); + assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); } } diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 19210b0..3ab3067 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -146,8 +146,14 @@ pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void { /// Looks up our implementations behind a pseudo handle; real modules go to /// the host. pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { + // `NULL` is the process's exe, which for the title is its own image. + let module = if module.is_null() { + runtime::main_image().unwrap_or(0) as *mut c_void + } else { + module + }; let Some(m) = registry().iter().find(|m| handle(m) == module) else { - return host::get_proc_address(module, name); + return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); }; // Values below 0x10000 are ordinals; we export by name only. if (name as usize) < 0x1_0000 { @@ -169,6 +175,25 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * } } +/// What a host module's `name` (or ordinal) is bound to at import binding +/// when we override it: a title that looks a function up by name must not +/// get past our overrides (the network guard, path rewriting). +fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> { + if module.is_null() || runtime::image_path(module as usize).is_some() { + return None; + } + let symbol = if (name as usize) < 0x1_0000 { + format!("#{}", name as usize) + } else { + narrow(name) + }; + let mut path = [0u16; 260]; + let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize; + let path = String::from_utf16_lossy(&path[..len.min(path.len())]); + let file = path.rsplit('\\').next()?; + crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void) +} + /// Our pseudo modules and the title's images stay loaded: `LoadLibrary` /// took no reference on them, so the host's count must not drop. pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { @@ -189,14 +214,18 @@ pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 { /// Title debug output goes to our log (no debugger needs to be attached). pub extern "system" fn OutputDebugStringA(text: *const u8) { if !text.is_null() { - tracing::info!(target: "title", "{}", narrow(text).trim_end()); + let text = narrow(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); } } /// See [`OutputDebugStringA`]. pub extern "system" fn OutputDebugStringW(text: *const u16) { if !text.is_null() { - tracing::info!(target: "title", "{}", wide(text).trim_end()); + let text = wide(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); } } @@ -226,6 +255,28 @@ pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { host::abort() } +/// The title's unhandled-exception filter. Ours stands in front of it and +/// reports the crash first; the title still gets its own back. +static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { + host::set_unhandled_exception_filter(report_unhandled); + TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel) +} + +extern "system" fn report_unhandled(info: *const c_void) -> i32 { + host::report_unhandled(info); + match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { + 0 => 0, // EXCEPTION_CONTINUE_SEARCH + filter => { + type Filter = extern "system" fn(*const c_void) -> i32; + // SAFETY: the title registered this filter. + let filter: Filter = unsafe { std::mem::transmute(filter) }; + filter(info) + } + } +} + /// See [`exit`]; only the current process is logged. pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 { if process as isize == -1 { @@ -240,7 +291,9 @@ fn handle(m: &HleModule) -> *mut c_void { } /// The title's images and our console modules by name; `None` leaves the -/// name to the host. With `load`, a title DLL not mapped yet is mapped now. +/// name to the host, which only DLLs `HostPolicy` passes through get (as at +/// import binding); others fail. With `load`, a title DLL not mapped yet is +/// mapped now. fn find_module(path: &str, load: bool) -> Option<*mut c_void> { let file = path.rsplit(['\\', '/']).next().unwrap_or(path); // As the Windows loader does, a name without extension means a DLL. @@ -249,29 +302,49 @@ fn find_module(path: &str, load: bool) -> Option<*mut c_void> { } else { format!("{file}.dll") }; + // Loads go through the title DLL loader first: it waits for a DLL that + // another thread is still initialising, as the Windows loader lock does. + if load { + match runtime::load_title_dll(&file) { + Ok(Some(base)) => return Some(base as *mut c_void), + Ok(None) => {} + // Not the host: it would load the unpatched DLL from the title's folder. + Err(error) => { + tracing::error!(dll = file, %error, "mapping a title DLL failed"); + host::set_last_error(ERROR_MOD_NOT_FOUND); + return Some(std::ptr::null_mut()); + } + } + } if let Some(base) = runtime::image_named(&file) { return Some(base as *mut c_void); } // DLLs the host has too are real host modules, whatever `--strict` says. - if !HostPolicy::default().allows(&file) - && let Some(m) = registry().iter().find(|m| m.serves(&file)) - { + let host_dll = HostPolicy::default().allows(&file); + if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) { if load { tracing::info!(dll = file, "loaded as a pseudo module"); } return Some(handle(m)); } - if !load { + if host_dll { return None; } - match runtime::load_title_dll(&file) { - Ok(base) => base.map(|b| b as *mut c_void), - // Not the host: it would load the unpatched DLL from the title's folder. - Err(error) => { - tracing::error!(dll = file, %error, "mapping a title DLL failed"); - host::set_last_error(ERROR_MOD_NOT_FOUND); - Some(std::ptr::null_mut()) - } + // Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and + // the console does not have it. + refuse(&file); + host::set_last_error(ERROR_MOD_NOT_FOUND); + Some(std::ptr::null_mut()) +} + +/// Logs a DLL name the title is refused, once. +fn refuse(file: &str) { + static REFUSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); + let file = file.to_ascii_lowercase(); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if !refused.contains(&file) { + tracing::warn!(dll = file, "a host DLL outside the host policy: refused"); + refused.push(file); } } @@ -286,6 +359,7 @@ pub(crate) fn module() -> HleModule { "api-ms-win-core-libraryloader-*", "api-ms-win-core-processthreads-*", "api-ms-win-core-debug-*", + "api-ms-win-core-errorhandling-*", "api-ms-win-crt-runtime-*", ], exports: vec![ @@ -307,10 +381,17 @@ pub(crate) fn module() -> HleModule { hle_export!(terminate), hle_export!(_invalid_parameter_noinfo_noreturn), hle_export!(TerminateProcess), + hle_export!(SetUnhandledExceptionFilter), ], } } +/// The return addresses above the caller, as `module+rva`, for logs. +#[cfg(feature = "diagnostics")] +pub(crate) fn callers() -> String { + host::callers() +} + #[cfg(windows)] mod host { use std::ffi::c_void; @@ -405,6 +486,27 @@ mod host { unsafe { TerminateProcess(process, code) } } + pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) { + // SAFETY: our filter takes the exception pointers as an opaque pointer. + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter( + std::mem::transmute::< + extern "system" fn(*const c_void) -> i32, + windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER, + >(filter), + ) + }; + } + + pub(super) fn report_unhandled(info: *const c_void) { + // SAFETY: the system's exception pointers, passed to the filter. + unsafe { victory_loader::report_unhandled(info.cast()) }; + } + + pub(super) fn note_title_output(line: &str) { + victory_loader::note_title_output(line); + } + /// Our caller's callers, as `module+rva`. pub(super) fn callers() -> String { let mut frames = [std::ptr::null_mut(); 12]; @@ -479,6 +581,12 @@ mod host { std::process::exit(code as i32) } + pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {} + + pub(super) fn report_unhandled(_: *const c_void) {} + + pub(super) fn note_title_output(_: &str) {} + pub(super) fn callers() -> String { String::new() } @@ -511,6 +619,41 @@ mod tests { text.encode_utf16().chain(Some(0)).collect() } + #[cfg(windows)] + #[test] + fn host_lookups_by_name_get_our_overrides() { + let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); + assert!(!kernel32.is_null()); + let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap(); + assert_eq!( + GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize, + ours + ); + // A plain name stays the host's. + let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast()); + assert!(!host.is_null()); + assert_eq!( + GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()), + host + ); + // Host DLLs outside the host policy do not exist for the title. + assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null()); + assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null()); + assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null()); + assert_eq!( + // SAFETY: reads this thread's last error. + unsafe { windows_sys::Win32::Foundation::GetLastError() }, + ERROR_MOD_NOT_FOUND + ); + assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null()); + // By ordinal too (ws2_32 #4 is `connect`). + let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr()); + assert_eq!( + GetProcAddress(ws2, 4 as *const u8) as usize, + crate::registry::lookup("ws2_32.dll", "connect").unwrap() + ); + } + #[test] fn title_dlls_and_pseudo_modules_are_found_by_name() { let base = 0x7100_0000_0000usize; diff --git a/crates/victory-hle/src/modules/lifecycle.rs b/crates/victory-hle/src/modules/lifecycle.rs index 309103f..6ab93ea 100644 --- a/crates/victory-hle/src/modules/lifecycle.rs +++ b/crates/victory-hle/src/modules/lifecycle.rs @@ -1,7 +1,8 @@ //! The title's life cycle. A console title is never told it is closing: -//! quitting it first suspends it (its suspend routines run, and it has a -//! second to save) and then ends the process. Closing the title's window -//! does the same here. +//! quitting it or launching a new game first suspends it (its suspend +//! routines run, and it has a second to save) and then ends the process. +//! Closing the title's window does the same here; a new launch then starts +//! `victory` again, which waits for this process to be gone. #![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] #![allow(clippy::too_many_arguments)] @@ -11,7 +12,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Mutex, MutexGuard}; use std::time::Duration; -use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM}; use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU}; use windows_sys::core::{PCSTR, PCWSTR, w}; @@ -72,7 +73,8 @@ pub extern "system" fn CreateWindowExW( instance: HINSTANCE, param: *const c_void, ) -> HWND { - // SAFETY: the title's own arguments, forwarded. + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). let hwnd = unsafe { wm::CreateWindowExW( ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, @@ -97,7 +99,8 @@ pub extern "system" fn CreateWindowExA( instance: HINSTANCE, param: *const c_void, ) -> HWND { - // SAFETY: the title's own arguments, forwarded. + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). let hwnd = unsafe { wm::CreateWindowExA( ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, @@ -107,6 +110,44 @@ pub extern "system" fn CreateWindowExA( hwnd } +/// A console title sizes its window to its render target (Grand Theft +/// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen. +/// A top-level window larger than the work area is shrunk to fit, keeping +/// its proportions, and centred; what it shows is scaled to it (the swap +/// chain stretches). +fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) { + let mut area = RECT::default(); + // SAFETY: `area` receives the primary monitor's work area. + let known = + unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) }; + let fitted = fit_into(&area, width, height); + if !parent.is_null() || known == 0 || fitted == (width, height) { + return (x, y, width, height); + } + tracing::info!(width, height, to = ?fitted, "title window fitted to the screen"); + let (w, h) = fitted; + let left = area.left + (area.right - area.left - w) / 2; + let top = area.top + (area.bottom - area.top - h) / 2; + (left, top, w, h) +} + +/// `width` x `height` scaled down to fit `area`, or unchanged if it fits +/// (or is `CW_USEDEFAULT`). +fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { + let (aw, ah) = (area.right - area.left, area.bottom - area.top); + if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) { + return (width, height); + } + let scale = f64::min( + f64::from(aw) / f64::from(width), + f64::from(ah) / f64::from(height), + ); + ( + (f64::from(width) * scale) as i32, + (f64::from(height) * scale) as i32, + ) +} + /// Puts our procedure in front of the title's. fn hook(hwnd: HWND) { if hwnd.is_null() { @@ -130,7 +171,7 @@ extern "system" fn window_proc( // A user close (close button, Alt+F4, window or taskbar menu); a // console title never sees one, nor a WM_CLOSE from it. if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize { - quit(); + end_title("window closed", Box::new(|| {})); return 0; } // SAFETY: the procedure `hook` stored, called the way the system would. @@ -144,30 +185,97 @@ extern "system" fn window_proc( } } -/// Suspends the title as the console would on quit, then ends the process. -fn quit() { - static QUITTING: AtomicBool = AtomicBool::new(false); - if QUITTING.swap(true, Ordering::Relaxed) { +/// Suspends the title as the console does when it ends it, runs `then` +/// (once), then ends the process. Returns at once; later calls do nothing. +pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) { + static ENDING: AtomicBool = AtomicBool::new(false); + if ENDING.swap(true, Ordering::SeqCst) { return; } let suspend = routines().clone(); - tracing::info!(routines = suspend.len(), "window closed: suspending the title"); - // Not on the window thread: titles hand the suspend to that thread and - // wait for it inside the routine. + tracing::info!(routines = suspend.len(), "{why}: suspending the title"); + // Whoever comes first (the routines or the deadline) runs `then`; the + // other waits for it, so the process never ends halfway through. + let then = std::sync::Arc::new(Mutex::new(Some(then))); + let finish = move |how: &str| { + let mut then = then.lock().unwrap_or_else(|e| e.into_inner()); + tracing::info!("{how}; ending the title"); + if let Some(then) = then.take() { + then(); + } + end(); + }; + let late = finish.clone(); + // Not on the calling thread: titles hand the suspend to their window + // thread and wait for it inside the routine. std::thread::spawn(move || { for (_, routine, context) in suspend { routine(1, context as *mut c_void); } - tracing::info!("title suspended; ending it"); - end(); + finish("title suspended"); }); - std::thread::spawn(|| { + std::thread::spawn(move || { std::thread::sleep(SUSPEND_DEADLINE); - tracing::warn!("title did not finish suspending in time; ending it"); - end(); + late("title did not finish suspending in time"); }); } +/// Set in the environment of a relaunched `victory`: an inherited handle +/// of the process it replaces. +const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM"; + +/// Starts `victory` again with `args` (after the title has suspended); the +/// new process waits until this one has ended. +pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) { + use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; + let mut me: HANDLE = std::ptr::null_mut(); + // SAFETY: an inheritable duplicate of our own process handle. + let duplicated = unsafe { + DuplicateHandle( + GetCurrentProcess(), + GetCurrentProcess(), + GetCurrentProcess(), + &mut me, + 0, + 1, + DUPLICATE_SAME_ACCESS, + ) + } != 0; + let spawned = std::env::current_exe().and_then(|exe| { + let mut command = std::process::Command::new(exe); + command.args(&args); + if duplicated { + command.env(RELAUNCHED_FROM, (me as usize).to_string()); + } + command.spawn() + }); + match spawned { + Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"), + Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"), + } +} + +/// In a relaunched `victory`: waits (30 s at most) for the process it +/// replaces to be gone, so the two never share the title's files. +pub fn wait_for_previous() { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + let Some(handle) = std::env::var(RELAUNCHED_FROM) + .ok() + .and_then(|h| h.parse::<usize>().ok()) + else { + return; + }; + // SAFETY: removing our own variable before any other thread reads it. + unsafe { std::env::remove_var(RELAUNCHED_FROM) }; + let handle = handle as HANDLE; + // SAFETY: the inherited process handle the previous process gave us. + unsafe { + WaitForSingleObject(handle, 30_000); + CloseHandle(handle); + } +} + fn end() { // SAFETY: ends this process, as the console ends a suspended title. unsafe { TerminateProcess(GetCurrentProcess(), 0) }; @@ -211,6 +319,22 @@ mod tests { assert_eq!(left, [b]); } + #[test] + fn oversized_windows_shrink_to_the_screen() { + let area = RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1040, + }; + assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040)); + assert_eq!(fit_into(&area, 1280, 720), (1280, 720)); + assert_eq!( + fit_into(&area, wm::CW_USEDEFAULT, 0), + (wm::CW_USEDEFAULT, 0) + ); + } + #[test] fn hooked_windows_still_reach_the_title_procedure() { let null = std::ptr::null_mut(); diff --git a/crates/victory-hle/src/modules/media.rs b/crates/victory-hle/src/modules/media.rs new file mode 100644 index 0000000..aa6e91c --- /dev/null +++ b/crates/victory-hle/src/modules/media.rs @@ -0,0 +1,531 @@ +//! Media Foundation is the host's (`mfplat.dll` passes through), except for +//! the source resolver: the host's would fetch `http`, `rtsp` and other +//! URLs over the network, past `modules::net`. Titles get a proxy that +//! opens local files only, with paths on our virtual drives rewritten to +//! their host folders, and forwards everything else to the host's resolver. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashSet; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use super::files; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +/// What Media Foundation answers for a URL scheme it has no handler for. +const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32; + +const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]); +const IID_RESOLVER: [u8; 16] = guid( + 0xFBE5_A32D, + 0xA497, + 0x4B61, + [0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3], +); + +const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +// The URL rule. + +/// Where a resolver may read `url` from: `Ok` with the NUL-terminated +/// string to hand to the host, or `Err((scheme, host))` for anything that +/// is not a local file. +fn local(url: &[u16]) -> Result<Vec<u16>, (String, String)> { + let text = String::from_utf16_lossy(url); + let drive = |s: &str| { + let b = s.as_bytes(); + b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' + }; + let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string(); + let path = if let Some(rest) = text.strip_prefix(r"\\?\") { + if !drive(rest) { + return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); + } + text.clone() + } else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) { + return Err(("unc".into(), host_of(rest))); + } else if drive(&text) { + text.clone() + } else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| { + s.len() > 1 + && s.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c)) + }) { + let scheme = scheme.to_ascii_lowercase(); + let authority = rest.strip_prefix("//"); + if scheme != "file" { + return Err((scheme, authority.map(host_of).unwrap_or_default())); + } + let path = match authority { + Some(rest) => { + let host = host_of(rest); + if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { + return Err((scheme, host)); + } + &rest[host.len()..] + } + None => rest, + }; + let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\"); + if !drive(&path) { + // A local file without a drive: the host resolves it as is. + return Ok(with_nul(url)); + } + path + } else { + // A relative path. + return Ok(with_nul(url)); + }; + let wide: Vec<u16> = path.encode_utf16().collect(); + Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide))) +} + +fn with_nul(s: &[u16]) -> Vec<u16> { + s.iter().copied().chain([0]).collect() +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = b + .get(i + 1..i + 3) + .and_then(|h| std::str::from_utf8(h).ok()); + match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) { + (b'%', Some(v)) => { + out.push(v); + i += 3; + } + (c, _) => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The URL to give the host, or the refusal (logged once per scheme and +/// host). +fn checked(url: *const u16) -> Result<Vec<u16>, HRESULT> { + if url.is_null() { + return Err(E_POINTER); + } + // SAFETY: a NUL-terminated wide string from the title. + let len = (0..) + .take_while(|&i| unsafe { url.add(i).read() } != 0) + .count(); + // SAFETY: as above, `len` characters before the NUL. + let wide = unsafe { std::slice::from_raw_parts(url, len) }; + local(wide).map_err(|(scheme, host)| { + static REFUSED: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if refused + .get_or_insert_with(HashSet::new) + .insert((scheme.clone(), host.clone())) + { + tracing::warn!( + scheme, + host, + "media: refused a URL that is not a local file" + ); + } + UNSUPPORTED_SCHEME + }) +} + +// The proxy resolver. + +/// The host's resolver, called through its method table. +#[repr(C)] +struct Host { + vtable: *const usize, +} + +impl Host { + /// Method `n` of the host object, typed by the caller. + unsafe fn method<F: Copy>(this: *mut Host, n: usize) -> F { + // SAFETY: the caller names the slot's real signature; `this` is the + // host's live resolver. + unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) } + } +} + +#[repr(C)] +pub struct Resolver { + vtable: &'static Methods, + host: *mut Host, + refs: AtomicU32, +} + +type Unknown = *mut c_void; + +#[repr(C)] +struct Methods { + query_interface: + extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT, + add_ref: extern "system" fn(*mut Resolver) -> u32, + release: extern "system" fn(*mut Resolver) -> u32, + create_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + create_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + begin_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + begin_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT, +} + +static METHODS: Methods = Methods { + query_interface, + add_ref, + release, + create_from_url, + create_from_stream, + begin_from_url, + end_from_url, + begin_from_stream, + end_from_stream, + cancel, +}; + +fn host(this: *mut Resolver) -> *mut Host { + // SAFETY: title code calls methods on a proxy we made, alive until its + // last release. + unsafe { (*this).host } +} + +/// Only the resolver's own interfaces: anything else could hand out the +/// host object unguarded. +extern "system" fn query_interface( + this: *mut Resolver, + iid: *const [u8; 16], + out: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || out.is_null() { + return E_POINTER; + } + // SAFETY: checked non-null. + let iid = unsafe { *iid }; + let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER; + // SAFETY: checked non-null. + unsafe { + out.write(if found { + this.cast() + } else { + std::ptr::null_mut() + }) + }; + if !found { + return E_NOINTERFACE; + } + add_ref(this); + S_OK +} + +extern "system" fn add_ref(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 } +} + +extern "system" fn release(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1; + if left == 0 { + // SAFETY: made by `MFCreateSourceResolver`; this was the last + // reference, to the proxy and to the host object it holds. + let proxy = unsafe { Box::from_raw(this) }; + // SAFETY: slot 2 is `Release`. + let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) }; + release(proxy.host); + } + left +} + +extern "system" fn create_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => { + if !object.is_null() { + // SAFETY: the title's out parameter. + unsafe { object.write(std::ptr::null_mut()) }; + } + return error; + } + }; + let host = host(this); + // SAFETY: slot 3 is `CreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 3) }; + f(host, url.as_ptr(), flags, props, kind, object) +} + +extern "system" fn begin_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => return error, + }; + let host = host(this); + // SAFETY: slot 5 is `BeginCreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 5) }; + f(host, url.as_ptr(), flags, props, cookie, callback, state) +} + +extern "system" fn create_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 4 is `CreateObjectFromByteStream`; the URL is only a + // hint for picking a handler. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 4) }; + f(host, stream, url, flags, props, kind, object) +} + +extern "system" fn end_from_url( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 6 is `EndCreateObjectFromURL`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 6) }; + f(host, result, kind, object) +} + +#[allow(clippy::too_many_arguments)] +extern "system" fn begin_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 7 is `BeginCreateObjectFromByteStream`. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 7) }; + f(host, stream, url, flags, props, cookie, callback, state) +} + +extern "system" fn end_from_stream( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 8 is `EndCreateObjectFromByteStream`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 8) }; + f(host, result, kind, object) +} + +extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT { + let host = host(this); + // SAFETY: slot 9 is `CancelObjectCreation`. + let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) }; + f(host, cookie) +} + +/// The host's resolver behind our proxy. +pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + static CREATE: OnceLock<Option<usize>> = OnceLock::new(); + let Some(create) = + *CREATE.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateSourceResolver")) + else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: the host's `MFCreateSourceResolver(IMFSourceResolver**)`. + let create: extern "system" fn(*mut *mut Host) -> HRESULT = + unsafe { std::mem::transmute(create) }; + let mut host = std::ptr::null_mut(); + let hr = create(&mut host); + if hr < 0 || host.is_null() { + return hr; + } + let proxy = Box::new(Resolver { + vtable: &METHODS, + host, + refs: AtomicU32::new(1), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(proxy)) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "media", + dlls: &["mfplat.dll"], + exports: vec![hle_export!(MFCreateSourceResolver)], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wide(s: &str) -> Vec<u16> { + s.encode_utf16().collect() + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v)) + } + + #[test] + fn only_local_files_reach_the_host() { + // Network schemes and shares are refused, naming scheme and host. + let refused = |url: &str| local(&wide(url)).unwrap_err(); + assert_eq!( + refused("https://cdn.example.com/a.mp4"), + ("https".into(), "cdn.example.com".into()) + ); + assert_eq!(refused("RTSP://10.0.0.1:554/x").0, "rtsp"); + assert_eq!(refused("mms://h/x").0, "mms"); + assert_eq!( + refused(r"\\server\share\a.mp4"), + ("unc".into(), "server".into()) + ); + assert_eq!( + refused("file://server/share/a.mp4"), + ("file".into(), "server".into()) + ); + + // A path on a virtual drive goes to its host folder, also as a + // `file:` URL; other local files pass as they are. + // Checked by opening the files: `files` may spell the host root + // differently (absolute, `\\?\` for long paths) from the temp dir. + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("movies")).unwrap(); + std::fs::write(dir.path().join("movies").join("intro.mp4"), b"1").unwrap(); + std::fs::write(dir.path().join("movies").join("intro a.mp4"), b"2").unwrap(); + let letter = files::mount(dir.path()).expect("a free drive letter"); + let host = text(&local(&wide(&format!(r"{letter}:\movies\intro.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&host).ok().as_deref(), + Some(&b"1"[..]), + "{host}" + ); + let from_url = + text(&local(&wide(&format!("file:///{letter}:/movies/intro%20a.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&from_url).ok().as_deref(), + Some(&b"2"[..]), + "{from_url}" + ); + assert_eq!( + text(&local(&wide("file:///C:/Windows/a.wav")).unwrap()), + r"C:\Windows\a.wav" + ); + assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4"); + } + + #[test] + fn interface_ids_are_the_resolvers() { + assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); + assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]); + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 39bd303..51e3590 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -8,20 +8,37 @@ //! `file` (package paths), `thread` (TLS callbacks for title threads), //! `xaudio2`, `xstore` stubs. +#[cfg(windows)] +pub mod apu; pub mod audio; pub mod d3d12x; +pub mod display; +pub mod dsp; +#[cfg(windows)] +pub mod dstorage; #[cfg(windows)] pub mod files; pub mod gameinput; pub mod kernel; #[cfg(windows)] pub mod lifecycle; +#[cfg(windows)] +pub mod media; +#[cfg(windows)] +pub mod net; +pub mod speech; pub mod storage; pub mod xasync; +pub mod xg; pub mod xgame; pub mod xgameruntime; +pub mod xgamesave; +pub mod xgameui; #[cfg(windows)] pub mod xmem; +pub mod xnetworking; +pub mod xpackage; +pub mod xstore; pub mod xsystem; pub mod xuser; @@ -34,12 +51,24 @@ pub(crate) fn all() -> Vec<HleModule> { gameinput::module(), d3d12x::module(), audio::module(), + dsp::module(), + xg::module(), ]; #[cfg(windows)] + all.push(apu::module()); + #[cfg(windows)] + all.push(media::module()); + #[cfg(windows)] + all.push(dstorage::module()); + #[cfg(windows)] all.push(files::module()); #[cfg(windows)] all.push(lifecycle::module()); #[cfg(windows)] + all.push(net::module()); + #[cfg(windows)] all.push(xmem::module()); + #[cfg(windows)] + all.push(xsystem::module()); all } diff --git a/crates/victory-hle/src/modules/net.rs b/crates/victory-hle/src/modules/net.rs new file mode 100644 index 0000000..6f61a27 --- /dev/null +++ b/crates/victory-hle/src/modules/net.rs @@ -0,0 +1,1065 @@ +//! A console without a network cable: the title reaches loopback only. +//! +//! Every way out of Winsock and WinHTTP a title can import or look up by +//! name is vetted here; the rest of both DLLs is the host's own. +//! +//! * Connects (also by name, by list, `ConnectEx` from `WSAIoctl`) and +//! datagram sends to anything but 127.0.0.0/8 and ::1 fail with +//! `WSAENETUNREACH`. +//! * Forward lookups other than `localhost` and IP literals fail with +//! `WSAHOST_NOT_FOUND`; reverse lookups of other addresses come back +//! numeric, or fail if a name is required, as with no network. +//! * `WinHttpConnect` to a host that is not loopback fails with +//! `ERROR_WINHTTP_CANNOT_CONNECT`, so no request (or WebSocket) handle can +//! exist for one. Proxies are off and proxy auto-detection (WPAD, PAC +//! downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`. +//! * A bind to all interfaces is narrowed to loopback, so nothing on the +//! network can connect in. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::SetLastError; + +use crate::modules::files::host; +use crate::{HleExport, HleModule, hle_export}; + +const SOCKET_ERROR: i32 = -1; +const INVALID_SOCKET: Socket = !0; +const WSAEINVAL: i32 = 10022; +const WSAEADDRNOTAVAIL: i32 = 10049; +const WSAENETUNREACH: i32 = 10051; +const WSASERVICE_NOT_FOUND: i32 = 10108; +const WSAHOST_NOT_FOUND: i32 = 11001; +const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029; +const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180; +const AF_INET: u16 = 2; +const AF_INET6: u16 = 23; +const NI_NUMERICHOST: i32 = 0x02; +const NI_NAMEREQD: i32 = 0x04; +const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006; +const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024; +const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1; +const WINHTTP_OPTION_PROXY: u32 = 38; + +#[repr(C)] +#[derive(Clone, Copy, PartialEq, Eq)] +struct Guid(u32, u16, u16, [u8; 8]); + +const WSAID_CONNECTEX: Guid = Guid( + 0x25a2_07b9, + 0xddf3, + 0x4660, + [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e], +); +const WSAID_WSASENDMSG: Guid = Guid( + 0xa441_e712, + 0x754f, + 0x43ca, + [0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d], +); + +type Socket = usize; +type Handle = *mut c_void; + +/// Logs `what` for `destination` the first time (no payload, ever). +fn once(what: &'static str, destination: String) { + static SEEN: Mutex<Vec<(&str, String)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.iter().any(|(w, d)| *w == what && *d == destination) { + tracing::info!(%destination, "{what}"); + seen.push((what, destination)); + } +} + +fn wsa_error(code: i32) { + host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code); +} + +fn narrow(text: *const c_char) -> Option<String> { + (!text.is_null()).then(|| { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text) } + .to_string_lossy() + .into_owned() + }) +} + +fn wide(text: *const u16) -> Option<String> { + // SAFETY: the title passes a NUL-terminated string or null. + (!text.is_null()).then(|| unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }) +} + +/// An IPv4 or IPv6 `sockaddr` of `len` bytes. +fn socket_addr(addr: *const u8, len: i32) -> Option<SocketAddr> { + let len = usize::try_from(len).ok()?; + if addr.is_null() || len < 4 { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr, len) }; + let port = u16::from_be_bytes([b[2], b[3]]); + match u16::from_le_bytes([b[0], b[1]]) { + AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()), + AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()), + _ => None, + } +} + +/// A raw address of family `kind` (`gethostbyaddr` style). +fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option<IpAddr> { + let len = usize::try_from(len).ok()?; + if addr.is_null() { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr.cast::<u8>(), len) }; + match (u16::try_from(kind).ok()?, len) { + (AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()), + (AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()), + _ => None, + } +} + +fn loopback(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +/// `localhost` or a loopback literal (bracketed IPv6 too). +fn loopback_name(name: &str) -> bool { + let bare = name.trim_start_matches('[').trim_end_matches(']'); + bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback) +} + +fn shown(addr: Option<impl ToString>) -> String { + addr.map_or_else(|| "not an IP address".into(), |a| a.to_string()) +} + +/// True for a loopback `sockaddr`; otherwise logs it and sets +/// `WSAENETUNREACH`. Other address families count as off the machine. +fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool { + match socket_addr(addr, len) { + Some(a) if loopback(a.ip()) => true, + a => { + once(what, shown(a)); + wsa_error(WSAENETUNREACH); + false + } + } +} + +/// Connecting by name: only to loopback. A name would need a lookup +/// (`WSAHOST_NOT_FOUND`), an address a route (`WSAENETUNREACH`). +fn reachable_name(name: Option<String>) -> bool { + match name { + Some(name) if !loopback_name(&name) => { + let literal = name.parse::<IpAddr>().is_ok(); + once("network connect blocked", name); + wsa_error(if literal { + WSAENETUNREACH + } else { + WSAHOST_NOT_FOUND + }); + false + } + // No name: the host rejects the call itself. + _ => true, + } +} + +/// Names answered without asking the network: none, `localhost`, IP +/// literals (connecting to one is vetted separately). +fn resolvable(name: Option<String>) -> bool { + match name { + Some(name) + if !(name.is_empty() + || name.eq_ignore_ascii_case("localhost") + || name.parse::<IpAddr>().is_ok()) => + { + once("network name lookup blocked", name); + wsa_error(WSAHOST_NOT_FOUND); + false + } + _ => true, + } +} + +/// Reverse lookups ask DNS unless the address is loopback. +fn reverse_resolvable(ip: Option<IpAddr>) -> bool { + match ip { + Some(ip) if loopback(ip) => true, + ip => { + once("network reverse lookup blocked", shown(ip)); + false + } + } +} + +/// `getnameinfo` flags that keep a host name lookup on the machine: the +/// numeric form, as without a network, or `None` if a name is required. +fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option<i32> { + if !host_wanted + || flags & NI_NUMERICHOST != 0 + || reverse_resolvable(socket_addr(sa, len).map(|a| a.ip())) + { + Some(flags) + } else if flags & NI_NAMEREQD != 0 { + wsa_error(WSAHOST_NOT_FOUND); + None + } else { + Some(flags | NI_NUMERICHOST) + } +} + +// Connects. + +pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len) +} + +pub extern "system" fn WSAConnect( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + ) +} + +pub extern "system" fn WSAConnectByNameA( + s: Socket, + node: *const c_char, + service: *const c_char, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(narrow(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +pub extern "system" fn WSAConnectByNameW( + s: Socket, + node: *const u16, + service: *const u16, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(wide(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +/// `SOCKET_ADDRESS`; a `SOCKET_ADDRESS_LIST` is an `i32` count, then these +/// (pointer aligned). +#[repr(C)] +struct SocketAddress { + addr: *const u8, + len: i32, +} + +/// Every candidate must be loopback. +pub extern "system" fn WSAConnectByList( + s: Socket, + list: *const u8, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !list.is_null() { + // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`. + let entries = unsafe { + let count = usize::try_from(list.cast::<i32>().read()).unwrap_or(0); + std::slice::from_raw_parts(list.add(8).cast::<SocketAddress>(), count) + }; + if !entries + .iter() + .all(|e| reachable("network connect blocked", e.addr, e.len)) + { + return 0; + } + } + host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, list, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +pub extern "system" fn WSAJoinLeaf( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, + flags: u32, +) -> Socket { + if !reachable("network connect blocked", name, len) { + return INVALID_SOCKET; + } + host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + flags, + ) +} + +/// `ConnectEx` as `WSAIoctl` hands it out: vetted, then the socket's own. +extern "system" fn connect_ex( + s: Socket, + name: *const u8, + len: i32, + send: *const c_void, + send_len: u32, + sent: *mut u32, + overlapped: *mut c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return 0; + } + let (mut real, mut size) = (0usize, 0u32); + let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32); + let guid = WSAID_CONNECTEX; + let found = ioctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut real).cast(), + 8, + &mut size, + std::ptr::null_mut(), + std::ptr::null(), + ); + if found != 0 || real == 0 { + return 0; + } + // SAFETY: the provider's `ConnectEx` for this socket. + let real = unsafe { + std::mem::transmute::< + usize, + extern "system" fn( + Socket, + *const u8, + i32, + *const c_void, + u32, + *mut u32, + *mut c_void, + ) -> i32, + >(real) + }; + real(s, name, len, send, send_len, sent, overlapped) +} + +/// The `ConnectEx` and `WSASendMsg` pointers it hands out are ours; the +/// multi-pointer query (Registered I/O, whose `RIOSendEx` takes any +/// address) is refused as by an old system. Other controls pass through. +pub extern "system" fn WSAIoctl( + s: Socket, + code: u32, + input: *const c_void, + input_len: u32, + output: *mut c_void, + output_len: u32, + returned: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER { + wsa_error(WSAEINVAL); + return SOCKET_ERROR; + } + let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, code, input, input_len, output, output_len, returned, overlapped, completion, + ); + if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 { + // SAFETY: the host just read a GUID from `input` and wrote a pointer to `output`. + unsafe { + let ours = match input.cast::<Guid>().read_unaligned() { + WSAID_CONNECTEX => connect_ex as *const () as usize, + WSAID_WSASENDMSG => WSASendMsg as *const () as usize, + _ => return result, + }; + output.cast::<usize>().write_unaligned(ours); + } + } + result +} + +// Datagram sends. + +/// Without an address it sends to the connected peer, which `connect` vetted; +/// so does a stream socket whatever `to` says (Winsock ignores it there). +pub extern "system" fn sendto( + s: Socket, + buf: *const u8, + len: i32, + flags: i32, + to: *const u8, + to_len: i32, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)( + s, buf, len, flags, to, to_len, + ) +} + +pub extern "system" fn WSASendTo( + s: Socket, + buffers: *const c_void, + count: u32, + sent: *mut u32, + flags: u32, + to: *const u8, + to_len: i32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)( + s, buffers, count, sent, flags, to, to_len, overlapped, completion, + ) +} + +/// A connection-oriented socket, whose sends go to the peer `connect` vetted. +fn stream(s: Socket) -> bool { + const SOL_SOCKET: i32 = 0xffff; + const SO_TYPE: i32 = 0x1008; + const SOCK_STREAM: i32 = 1; + let (mut kind, mut len) = (0i32, 4i32); + let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32); + getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM +} + +/// The start of a `WSAMSG`: the destination. +#[repr(C)] +struct MessageName { + name: *const u8, + len: i32, +} + +pub extern "system" fn WSASendMsg( + s: Socket, + message: *const c_void, + flags: u32, + sent: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + // SAFETY: the title passes a `WSAMSG` or null. + if let Some(m) = unsafe { message.cast::<MessageName>().as_ref() } + && !m.name.is_null() + && !reachable("network datagram blocked", m.name, m.len) + { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, message, flags, sent, overlapped, completion, + ) +} + +/// All interfaces become loopback, the only one an unplugged console has; +/// any other address is not ours (`WSAEADDRNOTAVAIL`). +// shortcut: `[::]` becomes `[::1]`, so a dual-stack listener no longer hears +// 127.0.0.1; bind both families if a title relies on that. +pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 { + let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32); + match socket_addr(name, len) { + Some(a) if loopback(a.ip()) => host_bind(s, name, len), + Some(a) if a.ip().is_unspecified() => { + once("network bind narrowed to loopback", a.to_string()); + // SAFETY: `socket_addr` checked `len` readable bytes. + let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec(); + match a { + SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]), + SocketAddr::V6(_) => local[23] = 1, + } + host_bind(s, local.as_ptr(), len) + } + a => { + once("network bind blocked", shown(a)); + wsa_error(WSAEADDRNOTAVAIL); + SOCKET_ERROR + } + } +} + +// Forward lookups. + +pub extern "system" fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(narrow(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoW( + node: *const u16, + service: *const u16, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(wide(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoExA( + name: *const c_char, + service: *const c_char, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(narrow(name)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( + name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, + ) +} + +pub extern "system" fn GetAddrInfoExW( + name: *const u16, + service: *const u16, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(wide(name)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( + name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, + ) +} + +pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name) +} + +pub extern "system" fn WSAAsyncGetHostByName( + window: Handle, + message: u32, + name: *const c_char, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)( + window, message, name, buf, buf_len, + ) +} + +/// Name-space queries (DNS, also network lists and Bluetooth) are refused +/// as a console without a network answers them. +// shortcut: local name spaces are refused too; pass those through if a title +// needs one. +pub extern "system" fn WSALookupServiceBeginA( + _restrictions: *const c_void, + _flags: u32, + _lookup: *mut Handle, +) -> i32 { + once("network name-space query blocked", "any".into()); + wsa_error(WSASERVICE_NOT_FOUND); + SOCKET_ERROR +} + +/// See [`WSALookupServiceBeginA`]. +pub extern "system" fn WSALookupServiceBeginW( + restrictions: *const c_void, + flags: u32, + lookup: *mut Handle, +) -> i32 { + WSALookupServiceBeginA(restrictions, flags, lookup) +} + +// Reverse lookups. + +pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)( + addr, len, kind, + ) +} + +pub extern "system" fn WSAAsyncGetHostByAddr( + window: Handle, + message: u32, + addr: *const c_char, + len: i32, + kind: i32, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)( + window, message, addr, len, kind, buf, buf_len, + ) +} + +pub extern "system" fn getnameinfo( + sa: *const u8, + sa_len: i32, + host: *mut c_char, + host_len: u32, + serv: *mut c_char, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +pub extern "system" fn GetNameInfoW( + sa: *const u8, + sa_len: i32, + host: *mut u16, + host_len: u32, + serv: *mut u16, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +// WinHTTP. + +/// The one door to a server: requests, uploads and WebSockets all hang off +/// the handle this returns. +pub extern "system" fn WinHttpConnect( + session: Handle, + server: *const u16, + port: u16, + reserved: u32, +) -> Handle { + if let Some(name) = wide(server) + && !loopback_name(&name) + { + once("HTTP connection blocked", format!("{name}:{port}")); + // SAFETY: no pointers. + unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) }; + return std::ptr::null_mut(); + } + host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)( + session, server, port, reserved, + ) +} + +/// Sessions never use a proxy: only loopback is reachable, and a proxy +/// (named, or found by auto-detection) would carry it off the machine. +pub extern "system" fn WinHttpOpen( + agent: *const u16, + access: u32, + _proxy: *const u16, + _bypass: *const u16, + flags: u32, +) -> Handle { + if access != WINHTTP_ACCESS_TYPE_NO_PROXY { + once("HTTP proxy ignored", format!("access type {access}")); + } + host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)( + agent, + WINHTTP_ACCESS_TYPE_NO_PROXY, + std::ptr::null(), + std::ptr::null(), + flags, + ) +} + +/// See [`WinHttpOpen`]: a proxy set later is accepted and not used. +pub extern "system" fn WinHttpSetOption( + handle: Handle, + option: u32, + buffer: *const c_void, + len: u32, +) -> i32 { + if option == WINHTTP_OPTION_PROXY { + once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into()); + return 1; + } + host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)( + handle, option, buffer, len, + ) +} + +/// Proxy auto-detection asks the network (DHCP, DNS, a PAC download). +fn no_auto_proxy() -> u32 { + once("HTTP proxy auto-detection blocked", "WPAD/PAC".into()); + ERROR_WINHTTP_AUTODETECTION_FAILED +} + +pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrl( + _session: Handle, + _url: *const u16, + _options: *const c_void, + _info: *mut c_void, +) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrlEx( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxyForUrlEx2( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _selection_len: u32, + _selection: *const u8, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxySettingsEx( + _resolver: Handle, + _kind: i32, + _params: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +/// Winsock imports by ordinal; the Winsock 1.1 numbers are fixed. +fn ordinal(name: &'static str, f: usize) -> HleExport { + HleExport { name, address: f } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "net", + dlls: &["ws2_32.dll", "winhttp.dll"], + exports: vec![ + hle_export!(connect), + hle_export!(WSAConnect), + hle_export!(WSAConnectByNameA), + hle_export!(WSAConnectByNameW), + hle_export!(WSAConnectByList), + hle_export!(WSAJoinLeaf), + hle_export!(WSAIoctl), + hle_export!(sendto), + hle_export!(WSASendTo), + hle_export!(WSASendMsg), + hle_export!(bind), + hle_export!(getaddrinfo), + hle_export!(GetAddrInfoW), + hle_export!(GetAddrInfoExA), + hle_export!(GetAddrInfoExW), + hle_export!(gethostbyname), + hle_export!(WSAAsyncGetHostByName), + hle_export!(WSALookupServiceBeginA), + hle_export!(WSALookupServiceBeginW), + hle_export!(gethostbyaddr), + hle_export!(WSAAsyncGetHostByAddr), + hle_export!(getnameinfo), + hle_export!(GetNameInfoW), + hle_export!(WinHttpConnect), + hle_export!(WinHttpOpen), + hle_export!(WinHttpSetOption), + hle_export!(WinHttpDetectAutoProxyConfigUrl), + hle_export!(WinHttpGetProxyForUrl), + hle_export!(WinHttpGetProxyForUrlEx), + hle_export!(WinHttpGetProxyForUrlEx2), + hle_export!(WinHttpGetProxySettingsEx), + ordinal("#2", bind as *const () as usize), + ordinal("#4", connect as *const () as usize), + ordinal("#20", sendto as *const () as usize), + ordinal("#51", gethostbyaddr as *const () as usize), + ordinal("#52", gethostbyname as *const () as usize), + ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize), + ordinal("#103", WSAAsyncGetHostByName as *const () as usize), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use victory_pe::ImportSymbol; + + fn v4(ip: [u8; 4], port: u16) -> [u8; 16] { + let mut a = [0u8; 16]; + a[..2].copy_from_slice(&AF_INET.to_le_bytes()); + a[2..4].copy_from_slice(&port.to_be_bytes()); + a[4..8].copy_from_slice(&ip); + a + } + + // TEST-NET-1 (192.0.2.0/24): never routed, and never tried here. + const AWAY: [u8; 4] = [192, 0, 2, 1]; + const HOME: [u8; 4] = [127, 0, 0, 1]; + + #[test] + fn only_loopback_is_reachable() { + // Also starts Winsock for the raw calls below. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket); + let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32); + let last_error = host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32); + let null = std::ptr::null_mut::<c_void>(); + + // Connects. + let s = socket(2, 1, 6); + assert_ne!(s, INVALID_SOCKET); + assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR); + assert_eq!(last_error(), WSAENETUNREACH); + let n = null.cast(); + assert_eq!( + WSAConnectByNameA( + s, + c"example.com".as_ptr(), + c"80".as_ptr(), + n, + null, + n, + null, + null, + null + ), + 0 + ); + assert_eq!(last_error(), WSAHOST_NOT_FOUND); + assert_eq!(connect(s, v4(HOME, port).as_ptr(), 16), 0); + listener.accept().unwrap(); + // A stream socket sends to its vetted peer whatever `to` says. + assert_eq!(sendto(s, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), 1); + close(s); + + // `ConnectEx` from `WSAIoctl` is the vetted one. + let s = socket(2, 1, 6); + let mut f = 0usize; + let mut size = 0u32; + let guid = WSAID_CONNECTEX; + let got = WSAIoctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut f).cast(), + 8, + &mut size, + null, + null, + ); + assert_eq!((got, f), (0, connect_ex as *const () as usize)); + assert_eq!( + connect_ex(s, v4(AWAY, 80).as_ptr(), 16, null, 0, n, null), + 0 + ); + assert_eq!(last_error(), WSAENETUNREACH); + close(s); + + // Datagram sends. + let u = socket(2, 2, 17); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), + SOCKET_ERROR + ); + assert_eq!(last_error(), WSAENETUNREACH); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16), + 1 + ); + close(u); + + // Forward and reverse lookups. + let mut result = null; + assert_eq!( + getaddrinfo( + c"example.com".as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let name: Vec<u16> = "example.com\0".encode_utf16().collect(); + assert_eq!( + GetAddrInfoW( + name.as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let mut text = [0 as c_char; 64]; + let away = v4(AWAY, 80); + assert_eq!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + 0 + ), + 0 + ); + // SAFETY: NUL-terminated by `getnameinfo`. + let numeric = unsafe { CStr::from_ptr(text.as_ptr()) }; + assert_eq!(numeric.to_str(), Ok("192.0.2.1")); + assert_eq!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + NI_NAMEREQD + ), + WSAHOST_NOT_FOUND + ); + assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null()); + + // WinHTTP. + assert!(WinHttpConnect(null, name.as_ptr(), 443, 0).is_null()); + // SAFETY: no arguments. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + assert_eq!(error, ERROR_WINHTTP_CANNOT_CONNECT); + assert_eq!( + WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0), + ERROR_WINHTTP_AUTODETECTION_FAILED + ); + + // The ordinals we override name the functions they stand for. + let m = module(); + for e in m.exports.iter().filter(|e| e.name.starts_with('#')) { + let named = m + .exports + .iter() + .find(|n| n.address == e.address && !n.name.starts_with('#')) + .unwrap(); + let by_ordinal = ImportSymbol::Ordinal(e.name[1..].parse().unwrap()); + assert_eq!( + crate::HostPolicy::default().resolve("ws2_32.dll", &by_ordinal), + crate::host::function("ws2_32.dll", named.name), + "{} is not {}", + e.name, + named.name + ); + } + // Every override names a real export of its DLL. + for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { + let dll = if e.name.starts_with("WinHttp") { + "winhttp.dll" + } else { + "ws2_32.dll" + }; + assert!( + crate::host::function(dll, e.name).is_some(), + "{dll} lacks {}", + e.name + ); + } + } +} diff --git a/crates/victory-hle/src/modules/speech.rs b/crates/victory-hle/src/modules/speech.rs new file mode 100644 index 0000000..15e8eca --- /dev/null +++ b/crates/victory-hle/src/modules/speech.rs @@ -0,0 +1,151 @@ +//! Accessibility: speech synthesis for the title's narration. No voice is +//! installed here, and every stream is valid WAVE audio of no length, so +//! narration is silent. +// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT +// speech synthesis) needs COM bindings this crate has only in diagnostics +// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the +// title then plays the empty stream and goes on. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +/// Closed captions, high contrast, speech to text and synthesis. +pub const PROVIDER: Guid = Guid::new( + 0x3e24_1977, + 0x6237, + 0x41e9, + [0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1], +); +/// Unchanged since 2020. +pub const IID: Guid = Guid::new( + 0xd722_b373, + 0x8c4d, + 0x4692, + [0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d], +); + +pub static OBJECT: Object = Object::new("accessibility", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; + +/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36, +/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s, +/// block 2, 16 bits), an empty data chunk. +const SILENCE: [u8; 44] = + *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; + +/// Synthesizers and streams hold nothing, so their handles are fixed +/// addresses and closing them is free. +static SYNTHESIZER: u8 = 0; +static STREAM: u8 = 0; + +type This = *const Object; + +/// No voice is installed, so the callback never runs. +extern "system" fn enumerate_voices( + _: This, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT { + put(out, &raw const SYNTHESIZER) +} +extern "system" fn close(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { + S_OK +} +extern "system" fn create_stream( + _: This, + _: *const u8, + words: *const c_char, + out: *mut *const u8, +) -> HRESULT { + tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); + put(out, &raw const STREAM) +} +extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { + put(out, SILENCE.len()) +} +extern "system" fn stream_data( + _: This, + _: *const u8, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + if buffer.is_null() || size < SILENCE.len() { + return super::xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(SILENCE.len()) }; + } + S_OK +} + +static VTABLE: Methods<22> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 closed captions + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 high contrast + missing::<6> as *const (), // 0x30 speech to text + missing::<7> as *const (), // 0x38 + enumerate_voices as *const (), // 0x40 + create as *const (), // 0x48 + close as *const (), // 0x50 + set_default_voice as *const (), // 0x58 + set_custom_voice as *const (), // 0x60 + create_stream as *const (), // 0x68 from text + close as *const (), // 0x70 a stream + stream_size as *const (), // 0x78 + stream_data as *const (), // 0x80 + missing::<17> as *const (), // 0x88 speech to text + missing::<18> as *const (), // 0x90 + missing::<19> as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + create_stream as *const (), // 0xa8 from SSML +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn streams_are_empty_wave_files() { + let this: This = &OBJECT; + type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; + type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; + type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; + type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; + let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); + assert_eq!(method::<Create>(&OBJECT, 0x48)(this, &mut synth), S_OK); + let say = method::<Stream>(&OBJECT, 0x68); + assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); + assert_eq!(method::<Size>(&OBJECT, 0x78)(this, stream, &mut size), S_OK); + let mut wav = vec![0u8; size]; + let mut used = 0; + let data = method::<Data>(&OBJECT, 0x80); + assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); + assert_eq!( + (&wav[..4], &wav[8..16], &wav[36..40]), + (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) + ); + assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); + assert_eq!(used, 44); + } +} diff --git a/crates/victory-hle/src/modules/storage.rs b/crates/victory-hle/src/modules/storage.rs index d30d099..c8863fb 100644 --- a/crates/victory-hle/src/modules/storage.rs +++ b/crates/victory-hle/src/modules/storage.rs @@ -26,8 +26,17 @@ pub const IID: Guid = Guid::new( [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], ); +/// As Grand Theft Auto VI (2026) asks for it; it calls 0x20 (path) and 0x28 +/// (space) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x41a4_e10c, + 0x5a7e, + 0x41d9, + [0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6], +); + pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); -pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; type This = *const Object; @@ -87,14 +96,38 @@ fn used_bytes(dir: &Path) -> u64 { .sum() } +/// What the host disk under `dir` has free (unlimited if unknown). +pub(crate) fn disk_free(dir: &Path) -> u64 { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + let wide: Vec<u16> = dir.as_os_str().encode_wide().chain([0]).collect(); + let mut free = 0; + let null = std::ptr::null_mut(); + // SAFETY: a NUL-terminated path and a valid output. + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW( + wide.as_ptr(), + &mut free, + null, + null, + ) + }; + if ok != 0 { + return free; + } + } + let _ = dir; + u64::MAX +} + fn space() -> SpaceInfo { let title = runtime::title(); let used = used_bytes(&title.storage); let free = title.storage_bytes.saturating_sub(used); - // shortcut: the host disk's free space is not checked; do so if a title - // fills its quota on a nearly full disk. SpaceInfo { - available_free: free, + // Writable now: the quota's rest, as far as the host disk allows. + available_free: free.min(disk_free(&title.storage)), total_free: free, used, total: title.storage_bytes, @@ -153,6 +186,7 @@ mod tests { id: 1, storage: dir.path().to_owned(), storage_bytes: 1000, + ..Default::default() }); // The path is a drive root, never the host folder. diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index f73d828..6795057 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -100,13 +100,15 @@ impl Port { ready: Condvar::new(), }); if mode == Mode::Serialized { - // shortcut: the worker lives as long as the process, even after - // the queue closes; join it on close if titles churn queues. + // The worker ends once it holds the last reference (every queue + // using the port is closed) and nothing is left to run. let worker = port.clone(); std::thread::spawn(move || { loop { - if let Some(task) = worker.take(INFINITE) { - task.run(false); + match worker.take(1000) { + Some(task) => task.run(false), + None if Arc::strong_count(&worker) == 1 => break, + None => {} } } }); @@ -117,9 +119,7 @@ impl Port { fn submit(&self, task: Task) { match self.mode { Mode::Immediate => task.run(false), - // shortcut: a thread per callback, not a pool; fine at startup - // rates, pool them if a title submits thousands per frame. - Mode::ThreadPool => drop(std::thread::spawn(move || task.run(false))), + Mode::ThreadPool => POOL.submit(task), Mode::Manual | Mode::Serialized => { lock(&self.tasks).push_back(task); self.ready.notify_one(); @@ -145,6 +145,49 @@ impl Port { } } +/// The thread pool behind thread-pool ports: idle workers are reused, and a +/// new one starts whenever more tasks wait than workers idle, so a callback +/// that blocks on another never starves it. Workers stay for reuse. +struct Pool { + /// Queued tasks and the number of idle workers. + state: Mutex<(VecDeque<Task>, usize)>, + ready: Condvar, +} + +static POOL: Pool = Pool { + state: Mutex::new((VecDeque::new(), 0)), + ready: Condvar::new(), +}; + +impl Pool { + fn submit(&'static self, task: Task) { + let mut state = lock(&self.state); + state.0.push_back(task); + if state.0.len() > state.1 { + std::thread::spawn(move || self.work()); + } else { + self.ready.notify_one(); + } + } + + fn work(&self) { + let mut state = lock(&self.state); + loop { + while state.0.is_empty() { + state.1 += 1; + state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); + state.1 -= 1; + } + let task = state.0.pop_front(); + drop(state); + if let Some(task) = task { + task.run(false); + } + state = lock(&self.state); + } + } +} + /// A queue handle is `Arc::into_raw` of this; duplicating and closing a /// handle add and drop a reference. pub struct Queue { @@ -641,16 +684,167 @@ pub fn XAsyncGetResult( /// Starts a call on `block` that is already over: it completes with `hr` /// and no result data, through the block's completion port as usual. pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT { + finished_with( + block, + identity, + if hr < 0 { Err(hr) } else { Ok(Vec::new()) }, + ) +} + +/// Like [`finished`], with the bytes `XAsyncGetResult` hands out for +/// `identity` (an error has none). +pub fn finished_with( + block: *mut AsyncBlock, + identity: *const c_void, + result: Result<Vec<u8>, HRESULT>, +) -> HRESULT { + type Data = Result<Vec<u8>, HRESULT>; extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { - // SAFETY: the runtime passes valid provider data. + // SAFETY: the runtime passes valid provider data; the context is the + // boxed result until cleanup frees it. let data = unsafe { &*data }; - if op == OP_BEGIN { - XAsyncComplete(data.block, data.context as usize as u32 as i32, 0); + let result = data.context.cast::<Data>(); + match op { + // SAFETY: boxed in `finished_with`; nothing runs after cleanup. + OP_CLEANUP => drop(unsafe { Box::from_raw(result) }), + OP_BEGIN => { + // SAFETY: as above. Copied out: completing may clean up. + let (hr, len) = match unsafe { &*result } { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + XAsyncComplete(data.block, hr, len); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + if let Ok(bytes) = &*result { + data.buffer + .cast::<u8>() + .copy_from(bytes.as_ptr(), bytes.len()); + } + }, + _ => {} } S_OK } - let context = hr as u32 as usize as *mut c_void; - XAsyncBegin(block, context, identity, std::ptr::null(), Some(provider)) + let context = Box::into_raw(Box::new(result)); + let hr = XAsyncBegin( + block, + context.cast(), + identity, + std::ptr::null(), + Some(provider), + ); + if hr < 0 { + // Refused before the call existed, so no cleanup will come. + // SAFETY: still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// Like [`finished_with`], but the result comes from `work`, run on a +/// thread of ours; the call stays pending until it returns (a dialog, say). +pub fn pending_with( + block: *mut AsyncBlock, + identity: *const c_void, + work: impl FnOnce() -> Result<Vec<u8>, HRESULT> + Send + 'static, +) -> HRESULT { + type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data; the context is the + // boxed state until cleanup frees it. + let data = unsafe { &*data }; + let state = data.context.cast::<Data>(); + match op { + // SAFETY: boxed in `pending_with`; nothing runs after cleanup. + OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), + OP_BEGIN => { + // SAFETY: as above; cleanup waits for completion. + let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); + let (block, state) = (data.block as usize, state as usize); + std::thread::spawn(move || { + let result = work.map_or(Err(E_ABORT), |work| work()); + let (hr, len) = match &result { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + if let Ok(bytes) = result { + // SAFETY: the call is pending, so its state lives. + let state = unsafe { &*(state as *const Data) }; + state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes; + } + XAsyncComplete(block as *mut AsyncBlock, hr, len); + }); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + let state = (*state).lock().unwrap_or_else(|e| e.into_inner()); + data.buffer + .cast::<u8>() + .copy_from(state.1.as_ptr(), state.1.len()); + }, + _ => {} + } + S_OK + } + let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); + let context = Box::into_raw(state); + let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); + if hr < 0 { + // SAFETY: refused before the call existed; still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// The result of a call begun with [`finished_with`] for `identity`, as a +/// `T` written through `out`. +pub fn result<T>(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT { + XAsyncGetResult( + block, + identity, + size_of::<T>(), + out.cast(), + std::ptr::null_mut(), + ) +} + +/// The bytes of a value, for [`finished_with`]. +pub fn bytes<T: Copy>(value: T) -> Vec<u8> { + // SAFETY: a `Copy` value is plain data; padding bytes are never read. + unsafe { std::slice::from_raw_parts((&raw const value).cast::<u8>(), size_of::<T>()) }.to_vec() +} + +type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT; + +/// Runs `work` on the block's work port as an async call of its own; its +/// return value is the call's result. +pub fn XAsyncRun(block: *mut AsyncBlock, work: Option<Work>) -> HRESULT { + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + // SAFETY: the context is the `Work` given to `XAsyncRun`. + let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) }; + work(data.block) + } + _ => S_OK, + } + } + let Some(work) = work else { + return E_INVALIDARG; + }; + let identity = XAsyncRun as *const c_void; + XAsyncBegin( + block, + work as *mut c_void, + identity, + std::ptr::null(), + Some(provider), + ) } // The object `QueryApiImpl` returns. Each method takes the object first, @@ -671,6 +865,9 @@ extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usiz extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) { XAsyncCancel(b) } +extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option<Work>) -> HRESULT { + XAsyncRun(b, work) +} extern "system" fn m_begin( _: This, b: *mut AsyncBlock, @@ -787,7 +984,7 @@ static VTABLE: Methods<31> = Methods([ m_get_status as *const (), // 0x18 m_get_result_size as *const (), // 0x20 m_cancel as *const (), // 0x28 - missing::<6> as *const (), // 0x30 run a work callback as a call + m_run as *const (), // 0x30 m_begin as *const (), // 0x38 missing::<8> as *const (), // 0x40 m_schedule as *const (), // 0x48 @@ -927,6 +1124,61 @@ mod tests { XTaskQueueCloseHandle(q); } + #[test] + fn run_returns_the_work_result() { + extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { + E_ABORT + } + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + slot::<extern "system" fn(This, *mut AsyncBlock, Option<Work>) -> HRESULT>(0x30)( + &OBJECT, + &mut block, + Some(work) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT); + } + + #[test] + fn pool_callbacks_may_wait_for_each_other() { + static SECOND: AtomicBool = AtomicBool::new(false); + static FIRST: AtomicBool = AtomicBool::new(false); + extern "system" fn waits(_: *mut c_void, _: bool) { + let start = std::time::Instant::now(); + while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst); + } + extern "system" fn releases(_: *mut c_void, _: bool) { + SECOND.store(true, Ordering::SeqCst); + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK); + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)), + S_OK + ); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)), + S_OK + ); + let start = std::time::Instant::now(); + while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(FIRST.load(Ordering::SeqCst)); + XTaskQueueCloseHandle(q); + } + #[test] fn terminate_cancels_what_is_queued() { static TERMINATED: AtomicBool = AtomicBool::new(false); diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs new file mode 100644 index 0000000..46912d7 --- /dev/null +++ b/crates/victory-hle/src/modules/xg.rs @@ -0,0 +1,780 @@ +//! `xg_xs.dll`: the console's texture layout library. Titles ask it which +//! swizzle mode a texture should use, how large it is, where each mip and +//! slice lies, and to copy linear data into tiled memory and back. Served +//! from `victory_formats::texture`. +//! +//! Grand Theft Auto VI imports `XGCreateTextureComputer` and +//! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08), +//! the layout (0x10), copies into (0x40) and out of (0x48) a subresource, +//! and the 64 KiB tiling (0x50). The other slots log and fail. +#![allow(non_snake_case)] +// Title code passes pointers the real library would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicU32, Ordering}; + +use victory_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + +/// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle +/// mode` on the console (1 row major, 0 "pick one"). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ResourceDesc { + pub dimension: u32, + pub alignment: u64, + pub width: u64, + pub height: u32, + pub depth_or_array: u16, + pub mips: u16, + pub format: u32, + pub samples: u32, + pub quality: u32, + pub layout: u32, + pub flags: u32, +} +const _: () = assert!(size_of::<ResourceDesc>() == 0x38); + +const SWIZZLED: u32 = 0x100; +const ROW_MAJOR: u32 = 1; +const ALLOW_RENDER_TARGET: u32 = 1; +const ALLOW_DEPTH_STENCIL: u32 = 2; +const TEXTURE_1D: u32 = 2; +const TEXTURE_3D: u32 = 4; + +/// The mode the console's library picks for a description: linear for 1D, +/// the XOR render and depth modes for targets, else 4 KiB standard +/// (`.ttpf` textures without a mode of their own use it). +/// +/// shortcut: the rule of the library's older optimal-mode function (any +/// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer +/// than every copy we could check. Revisit if streamed textures come out +/// scrambled. +fn suggested(desc: &ResourceDesc) -> Swizzle { + if desc.dimension == TEXTURE_1D { + Swizzle::LINEAR + } else if desc.flags & ALLOW_DEPTH_STENCIL != 0 { + Swizzle::SW_64KB_Z_X + } else if desc.flags & ALLOW_RENDER_TARGET != 0 { + Swizzle::SW_64KB_R_X + } else { + Swizzle::SW_4KB_S + } +} + +/// `(desc, flags, out layout)`; the title passes flags 0 and puts the +/// result in the description's layout field. +pub extern "system" fn XGSuggestSwizzleMode( + desc: *const ResourceDesc, + _flags: u32, + out: *mut u32, +) -> HRESULT { + // SAFETY: the title passes a description and room for the layout + // (either may be null). + match unsafe { (desc.as_ref(), out.as_mut()) } { + (Some(desc), Some(out)) => { + *out = SWIZZLED | suggested(desc).0; + S_OK + } + _ => E_INVALIDARG, + } +} + +#[repr(C)] +pub struct Computer { + vtable: &'static Vtable, + refs: AtomicU32, + desc: ResourceDesc, + mips: u32, + texture: Texture, +} + +type This = *mut Computer; + +fn computer<'a>(this: This) -> &'a Computer { + // SAFETY: called from computer methods only. + unsafe { &*this } +} + +pub extern "system" fn XGCreateTextureComputer( + desc: *const ResourceDesc, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description and room for a pointer. + let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else { + return E_INVALIDARG; + }; + let Some(texture) = texture(&desc) else { + tracing::warn!(?desc, "no texture layout"); + return E_INVALIDARG; + }; + tracing::debug!( + width = desc.width, + height = desc.height, + format = desc.format, + layout = format_args!("{:#x}", desc.layout), + size = texture.size, + "texture computer" + ); + let mips = texture.planes[0].layout.mips.len() as u32; + let computer = Box::new(Computer { + vtable: &VTABLE, + refs: AtomicU32::new(1), + desc, + mips, + texture, + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(computer)) }; + S_OK +} + +fn texture(desc: &ResourceDesc) -> Option<Texture> { + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + 3 => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 => suggested(desc), + ROW_MAJOR => Swizzle::LINEAR, + l if l & !0xff == SWIZZLED => Swizzle(l & 0xff), + _ => return None, + }; + let texture = Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array), + mips: u32::from(desc.mips), + format: desc.format, + samples: desc.samples.max(1), + swizzle, + }) + .ok()?; + // The layout struct has room for 15 mips. + (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) +} + +const MIPS: usize = 15; + +/// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and +/// 0x1c are read by Grand Theft Auto VI; the rest follow the library's +/// older public shape). +#[repr(C)] +#[derive(Debug, Default, Clone, Copy)] +pub struct MipOut { + pub size: u64, + pub offset: u64, + pub slice_size: u64, + pub pitch_texels: u32, + pub pitch_bytes: u32, + pub alignment: u32, + /// Width, height in elements, depth or array size. + pub padded: [u32; 3], + pub elements: [u32; 2], + pub texels: [u32; 2], + pub depth_or_array: u32, + pub samples: u32, + pub swizzle: u32, + pub bank_rotation: [u64; 2], + pub slice_depth: u32, + pub in_tail: u32, + /// Where a tail mip starts in elements: x bits 0-10, y 11-21. + pub tail_position: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PlaneOut { + /// 1 data, 7 depth, 8 stencil (metadata planes are not made). + pub usage: u32, + pub size: u64, + pub slice_size: u64, + pub offset: u64, + pub alignment: u64, + pub element_bytes: u32, + pub standard_mips: u32, + pub tail_mips: u32, + pub mips: [MipOut; MIPS], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct LayoutOut { + pub size: u64, + pub alignment: u64, + pub mips: u32, + pub planes: u32, + pub plane: [PlaneOut; 4], + pub dimension: u32, +} +const _: () = assert!(size_of::<MipOut>() == 0x70); +const _: () = assert!(size_of::<PlaneOut>() == 0x6c8); +const _: () = assert!(size_of::<LayoutOut>() == 0x1b40); + +/// The mode a tail mip is reported in: the 256-byte one of its kind (3 for +/// the render kind, which GFX10 lacks), the depth mode itself. +fn tail_swizzle(swizzle: Swizzle) -> u32 { + match swizzle.0 { + 2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0, + 23 | 27 => 3, + 24 => swizzle.0, + _ => Swizzle::SW_256B_S.0, + } +} + +fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut { + let m = &l.mips[i]; + let bpe = u64::from(l.desc.element_bytes); + let block = l.desc.block; + let three_d = desc.dimension == TEXTURE_3D; + let array = u32::from(desc.depth_or_array).max(1); + let mut out = MipOut { + pitch_texels: m.pitch * block, + pitch_bytes: m.pitch * l.desc.element_bytes, + padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }], + elements: [m.width, m.height], + texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)], + depth_or_array: if three_d { m.depth } else { array }, + samples: l.desc.samples, + slice_depth: l.block[2], + ..MipOut::default() + }; + let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe; + let depth = u64::from(if three_d { m.depth_pitch } else { 1 }); + match m.tail { + None => { + out.offset = m.offset; + out.slice_size = slice * u64::from(l.desc.samples); + out.size = out.slice_size * depth; + out.alignment = l.alignment as u32; + out.swizzle = l.desc.swizzle.0; + } + Some(t) => { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if l.thick { + // A 3D tail mip is placed by position, not by offset. + out.slice_size = l.alignment / u64::from(l.block[2]); + out.tail_position = t.x | t.y << 11; + } else { + out.offset = u64::from(t.offset); + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + } + out +} + +extern "system" fn add_ref(this: This) -> u32 { + computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release(this: This) -> u32 { + let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the + // last reference is gone. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let c = computer(this); + // SAFETY: the title passes room for the layout; every field is plain + // data, so zeroes are a valid start. + let out = unsafe { + out.write_bytes(0, 1); + &mut *out + }; + out.size = c.texture.size; + out.alignment = c.texture.alignment; + out.mips = c.mips; + out.planes = c.texture.planes.len() as u32; + out.dimension = c.desc.dimension; + // The library calls a depth plane "depth" only beside stencil or + // without mips. + let depth = + c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1); + for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) { + let l = &p.layout; + plane.usage = match (p.stencil, depth) { + (true, _) => 8, + (false, true) => 7, + (false, false) => 1, + }; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = p.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c.mips - l.first_tail_mip; + for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() { + *mip = mip_out(&c.desc, l, i); + } + } + S_OK +} + +/// The plane, its mip and array slice for a subresource index, and the +/// tiled bytes and the linear bytes the copy touches. +struct CopyArgs<'a> { + layout: &'a Layout, + mip: u32, + slice: u32, + tiled: usize, + linear: usize, +} + +fn copy_args( + c: &Computer, + plane: u32, + subresource: u32, + row: u32, + depth: u32, +) -> Option<CopyArgs<'_>> { + let p = c.texture.planes.get(plane as usize)?; + let l = &p.layout; + let (mip, slice) = (subresource % c.mips, subresource / c.mips); + let m = l.mips.get(mip as usize)?; + let bytes = m.width as usize * l.desc.element_bytes as usize; + let depths = l.subresource_depth(mip) as usize; + let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; + Some(CopyArgs { + layout: l, + mip, + slice, + tiled: (p.offset + l.size) as usize, + linear, + }) +} + +fn result(r: Result<(), Error>) -> HRESULT { + match r { + Ok(()) => S_OK, + Err(Error::Unsupported) => E_NOTIMPL, + Err(_) => E_INVALIDARG, + } +} + +/// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`. +extern "system" fn copy_into( + this: This, + tiled: *mut u8, + plane: u32, + subresource: u32, + linear: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts(linear, a.linear), + ) + }; + let r = a + .layout + .tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed"); + } + result(r) +} + +/// `(linear, plane, subresource, sample, tiled base, row pitch, depth +/// pitch)`. +#[allow(clippy::too_many_arguments)] +extern "system" fn copy_from( + this: This, + linear: *mut u8, + plane: u32, + subresource: u32, + _sample: u32, + tiled: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts_mut(linear, a.linear), + ) + }; + let r = a + .layout + .detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed"); + } + result(r) +} + +#[repr(C)] +pub struct PackedMips { + pub standard: u8, + pub packed: u8, + pub tiles: u32, + pub start: u32, +} + +#[repr(C)] +pub struct SubresourceTiling { + pub width: u32, + pub height: u16, + pub depth: u16, + pub start: u32, +} + +const TILE: u64 = 64 << 10; + +/// `(total tiles, packed mips, tile shape in texels, in: room / out: +/// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D +/// 64 KiB modes only (others fail, as on the console). The mip tail is the +/// packed part, tile 0 of each slice; tilings list the standard mips of +/// every slice in turn. With a tail the console's library lists two slices +/// at most and zeroes all but the first; so do we (the title reads slice 0 +/// only). +extern "system" fn tiling( + this: This, + tiles: *mut u32, + packed: *mut PackedMips, + shape: *mut [u32; 3], + count: *mut u32, + first: u32, + out: *mut SubresourceTiling, +) -> HRESULT { + let c = computer(this); + let l = &c.texture.planes[0].layout; + if l.alignment != TILE { + return E_FAIL; + } + if l.thick { + return E_NOTIMPL; + } + let standard = l.first_tail_mip; + let tail = standard < c.mips; + let tail_tiles = match standard { + 0 => l.slice_size / TILE, + s if s < c.mips => l.mips[s as usize - 1].offset / TILE, + _ => 0, + }; + let block = l.desc.block; + // SAFETY: each output is null or room for its value; `out` has room + // for `*count` entries. + unsafe { + if let Some(t) = tiles.as_mut() { + *t = (l.size / TILE) as u32; + } + if let Some(p) = packed.as_mut() { + *p = PackedMips { + standard: standard as u8, + packed: (c.mips - standard) as u8, + tiles: tail_tiles as u32, + start: 0, + }; + } + if let Some(s) = shape.as_mut() { + *s = [l.block[0] * block, l.block[1] * block, l.block[2]]; + } + if let Some(n) = count.as_mut() { + let slices = if tail { l.slices.min(2) } else { l.slices }; + let wanted = (standard * slices).saturating_sub(first).min(*n); + for i in 0..wanted { + let (slice, mip) = ((first + i) / standard, (first + i) % standard); + let m = &l.mips[mip as usize]; + let entry = if tail && slice > 0 { + SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + } + } else { + SubresourceTiling { + width: m.pitch / l.block[0], + height: (m.rows / l.block[1]) as u16, + depth: 1, + start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, + } + }; + out.add(i as usize).write(entry); + } + *n = wanted; + } + } + S_OK +} + +/// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an +/// element's byte offset from the texture's start. Grand Theft Auto VI reads +/// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90); +/// an error returned as an offset made it read wild memory. 0 if outside. +extern "system" fn element_offset( + this: This, + plane: u32, + mip: u32, + x: u64, + y: u32, + z: u32, + _sample: u32, + bit: *mut u32, +) -> u64 { + if !bit.is_null() { + // SAFETY: the caller passes room for the bit position or null. + unsafe { bit.write(0) }; + } + let Some(p) = computer(this).texture.planes.get(plane as usize) else { + return 0; + }; + let x = u32::try_from(x).unwrap_or(u32::MAX); + match p.layout.offset(mip, x, y, z) { + Ok(at) => p.offset + at, + Err(e) => { + tracing::warn!(?e, mip, x, y, z, "texel outside its texture"); + 0 + } + } +} + +/// Slots the title does not call: size, alignment, offsets, coordinates, +/// view descriptor, tiled-resource query. +extern "system" fn unused(this: This) -> HRESULT { + tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method"); + E_NOTIMPL +} + +#[repr(C)] +struct Vtable([*const (); 13]); +// SAFETY: function addresses only. +unsafe impl Sync for Vtable {} + +static VTABLE: Vtable = Vtable([ + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset + element_offset as *const (), // 0x30 + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xg", + dlls: &["xg_xs.dll"], + exports: vec![ + hle_export!(XGCreateTextureComputer), + hle_export!(XGSuggestSwizzleMode), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc { + ResourceDesc { + dimension: 3, + alignment: 0, + width, + height, + depth_or_array: 1, + mips, + format, + samples: 1, + quality: 0, + layout, + flags: 0, + } + } + + /// Method `index` of a computer, as the title calls it. + fn slot<T: Copy>(c: This, index: usize) -> T { + // SAFETY: the computer is live; T is the slot's function type. + unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) } + } + + fn create(d: &ResourceDesc) -> This { + let mut c = std::ptr::null_mut(); + assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK); + c + } + + /// Element offsets: linear rows of 1 KiB (128 elements), 0 outside. + #[test] + fn element_offsets_follow_the_layout() { + type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let c = create(&desc(128, 4, 1, 11, 0x100)); + let offset: Offset = slot(c, 6); + let mut bit = 7; + assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8); + assert_eq!(bit, 0); + assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0); + slot::<extern "system" fn(This) -> u32>(c, 1)(c); + } + + #[test] + fn suggestions_follow_the_use() { + let mut out = 0; + let mut d = desc(256, 256, 1, 98, 0); + assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK); + assert_eq!(out, 0x105); + d.flags = ALLOW_RENDER_TARGET; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x11b); + d.flags = ALLOW_DEPTH_STENCIL; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x118); + } + + /// The title's calls: layout, then a copy in and out of each mip. + #[test] + fn layout_and_copies_through_the_object() { + // 256x256 BC7, full chain, 64 KiB display mode. + let c = create(&desc(256, 256, 0, 98, 0x10a)); + // SAFETY: plain data, filled by the call. + let mut l: Box<LayoutOut> = Box::new(unsafe { std::mem::zeroed() }); + let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2); + assert_eq!(get(c, &mut *l), S_OK); + assert_eq!( + (l.size, l.alignment, l.mips, l.planes), + (131072, 65536, 9, 1) + ); + let p = &l.plane[0]; + assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16)); + assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024)); + assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1)); + + type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type From = + extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT; + let (into, from): (Into, From) = (slot(c, 8), slot(c, 9)); + let mut tiled = vec![0u8; l.size as usize]; + for mip in 0..9u32 { + let m = &p.mips[mip as usize]; + let row = m.elements[0] * 16; + let rows: Vec<u8> = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect(); + assert_eq!( + into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0), + S_OK + ); + let mut back = vec![0u8; rows.len()]; + assert_eq!( + from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0), + S_OK + ); + assert_eq!(back, rows, "mip {mip}"); + } + // 0x50: one tile for the tail, one for mip 0. + type Tiling = extern "system" fn( + This, + *mut u32, + *mut PackedMips, + *mut [u32; 3], + *mut u32, + u32, + *mut SubresourceTiling, + ) -> HRESULT; + let tiling: Tiling = slot(c, 10); + let (mut tiles, mut shape, mut n) = (0, [0; 3], 4); + let mut packed = PackedMips { + standard: 0, + packed: 0, + tiles: 0, + start: 0, + }; + let mut subs: Vec<SubresourceTiling> = (0..4) + .map(|_| SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + }) + .collect(); + assert_eq!( + tiling( + c, + &mut tiles, + &mut packed, + &mut shape, + &mut n, + 0, + subs.as_mut_ptr() + ), + S_OK + ); + assert_eq!( + (tiles, packed.standard, packed.packed, packed.tiles), + (2, 1, 8, 1) + ); + assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1)); + assert_eq!(release(c), 0); + + // 4 KiB modes have no 64 KiB tiling. + let null = std::ptr::null_mut::<u8>(); + let c = create(&desc(256, 256, 0, 98, 0x105)); + assert_eq!( + tiling( + c, + &mut tiles, + null.cast(), + null.cast(), + null.cast(), + 0, + null.cast() + ), + E_FAIL + ); + assert_eq!(release(c), 0); + } + + #[test] + fn bad_descriptions_fail() { + let mut c = std::ptr::null_mut(); + let bad = desc(256, 256, 1, 0, 0x10a); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + let bad = desc(256, 256, 1, 28, 0x103); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + assert!(module().exports.len() == 2); + } +} diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index ff242c0..c54f837 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -6,7 +6,7 @@ use std::ffi::{CStr, c_char, c_void}; use super::xgameruntime::{ - Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, token, + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token, }; use crate::runtime; @@ -62,12 +62,65 @@ extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { put(out, runtime::title().id) } +/// As documented: the title ends (suspended first, as on any end) and the +/// game starts again in a new process; this never returns. Grand Theft +/// Auto VI relaunches itself (its own path from `GetModuleFileNameA`) with +/// arguments from its configuration. The new `victory run` gets the same +/// options, the new executable, and the title's arguments after `--` +/// (the title reads the whole command line). +extern "system" fn launch_new_game( + _: This, + exe: *const c_char, + args: *const c_char, + _user: *const c_void, +) { + let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); + tracing::info!(exe, args, "XLaunchNewGame"); + let current = runtime::main_image() + .and_then(runtime::image_path) + .unwrap_or_default(); + let ours: Vec<_> = std::env::args_os().skip(1).collect(); + let command = relaunch_args(ours, current.as_os_str(), &exe, &args); + super::lifecycle::end_title( + "XLaunchNewGame", + Box::new(move || super::lifecycle::relaunch(command)), + ); + loop { + std::thread::park(); + } +} + +/// Our own arguments for the relaunch: the title's executable replaced by +/// `exe`, earlier title arguments dropped, `args` after `--`. +fn relaunch_args( + ours: Vec<std::ffi::OsString>, + current: &std::ffi::OsStr, + exe: &str, + args: &str, +) -> Vec<std::ffi::OsString> { + let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect(); + if !exe.is_empty() + && let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current) + { + *slot = exe.into(); + } + if !args.trim().is_empty() { + out.push("--".into()); + out.extend(args.split_whitespace().map(Into::into)); + } + out +} + /// Runtime areas by number, in the public feature list's order, that we -/// serve: async calls and providers (2, 3), game (5), invites (6), -/// persistent local storage (12), system (15), task queues (16), users -/// (18), error reports (19), game events (20). Not the others: store, game -/// saves, UI, networking, packages, streaming, threads... -const AVAILABLE: [u32; 10] = [2, 3, 5, 6, 12, 15, 16, 18, 19, 20]; +/// serve: accessibility (0), app capture (1), async calls and providers +/// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8), +/// launcher (9), networking (10), packages (11), persistent local storage +/// (12), speech synthesis (13), store (14), system (15), task queues (16), +/// users (18), error reports (19), game events (20). Not threads (17) or +/// game streaming (21). +const AVAILABLE: [u32; 20] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, +]; extern "system" fn is_feature_available(_: This, feature: u32) -> bool { AVAILABLE.contains(&feature) @@ -109,8 +162,8 @@ static TITLE_VTABLE: Methods<5> = Methods([ missing::<0> as *const (), add_ref as *const (), add_ref as *const (), - title_id as *const (), // 0x18 - missing::<4> as *const (), // 0x20 launch another title (returns nothing) + title_id as *const (), // 0x18 + launch_new_game as *const (), // 0x20 ]); static FEATURES_VTABLE: Methods<4> = Methods([ @@ -140,12 +193,28 @@ mod tests { use super::*; use crate::modules::xgameruntime::method; + #[test] + fn a_relaunch_keeps_our_options() { + let ours: Vec<std::ffi::OsString> = + ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] + .map(Into::into) + .into(); + let current = std::ffi::OsStr::new("G:/game.exe"); + let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); + let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; + assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); + assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); + let other = relaunch_args(ours, current, "G:/other.exe", ""); + assert_eq!(other.len(), 5); + assert_eq!(other[1], "G:/other.exe"); + } + #[test] fn served_areas_are_available_others_not() { type Check = extern "system" fn(This, u32) -> bool; let check = method::<Check>(&FEATURES_OBJECT, 0x18); assert!(check(&FEATURES_OBJECT, 18), "users"); - assert!(!check(&FEATURES_OBJECT, 14), "store"); + assert!(!check(&FEATURES_OBJECT, 21), "game streaming"); type Register = extern "system" fn( This, diff --git a/crates/victory-hle/src/modules/xgameruntime.rs b/crates/victory-hle/src/modules/xgameruntime.rs index 66bbee1..3201a90 100644 --- a/crates/victory-hle/src/modules/xgameruntime.rs +++ b/crates/victory-hle/src/modules/xgameruntime.rs @@ -8,10 +8,13 @@ //! releases it. Until an area is implemented its query fails, and the call //! returns that error without touching the object. An area's interface id //! changes when its method table does, so each object answers only the ids -//! whose slots we know. Implemented: task queues and async blocks -//! (`xasync`), one offline user (`xuser`), system information (`xsystem`), -//! title id, feature checks, invites and events (`xgame`), persistent local -//! storage (`storage`). +//! whose slots we know. Implemented, as an offline retail console with one +//! signed-in user: task queues and async blocks (`xasync`), the user +//! (`xuser`), system information (`xsystem`), title id, feature checks, +//! invites and events (`xgame`), persistent local storage (`storage`), game +//! saves (`xgamesave`), networking (`xnetworking`), the package +//! (`xpackage`), the store (`xstore`), system dialogs (`xgameui`), speech +//! (`speech`), HDR, URIs, display deferrals and screenshots (`display`). #![allow(non_snake_case)] // Title code calls these through its import table, passing pointers the real // API would trust. @@ -21,7 +24,10 @@ use std::ffi::{CStr, c_char, c_void}; use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; -use super::{storage, xasync, xgame, xsystem, xuser}; +use super::{ + display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore, + xsystem, xuser, +}; use crate::{HleModule, hle_export}; pub type HRESULT = i32; @@ -91,12 +97,19 @@ unsafe impl<const N: usize> Sync for Methods<N> {} /// A (provider, interface id) pair a title may ask for, and our object. pub type Interface = (Guid, Guid, &'static Object); -const AREAS: [&[Interface]; 5] = [ +const AREAS: &[&[Interface]] = &[ xasync::INTERFACES, xuser::INTERFACES, xsystem::INTERFACES, xgame::INTERFACES, storage::INTERFACES, + xnetworking::INTERFACES, + xpackage::INTERFACES, + display::INTERFACES, + xgamesave::INTERFACES, + xstore::INTERFACES, + xgameui::INTERFACES, + speech::INTERFACES, ]; /// `AddRef` and `Release`. @@ -146,6 +159,12 @@ pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> S_OK } +/// The title's NUL-terminated string, if any. +pub fn text(s: *const c_char) -> Option<String> { + // SAFETY: the title passes a NUL-terminated string or null. + (!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned()) +} + /// A new registration token for callbacks we never call (events nobody /// raises offline). pub fn token() -> u64 { @@ -181,6 +200,19 @@ pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) S_OK } +/// The stub prefers this one when present. It passes the same three values +/// and a pointer to the title's initialisation options, null unless the +/// title initialises with options (Grand Theft Auto VI does not). +pub extern "system" fn InitializeApiImplEx2( + version: u64, + build: u64, + flags: u64, + options: *const c_void, +) -> HRESULT { + tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2"); + S_OK +} + pub extern "system" fn UninitializeApiImpl() { tracing::info!("UninitializeApiImpl"); } @@ -198,6 +230,17 @@ pub extern "system" fn QueryApiImpl( else { return NOT_SUPPORTED; }; + #[cfg(feature = "diagnostics")] + if tracing::enabled!(tracing::Level::DEBUG) { + // Each runtime call site once: which title code uses which area, when. + static CALLS: Mutex<Vec<String>> = Mutex::new(Vec::new()); + let from = super::kernel::callers(); + let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if !calls.contains(&from) { + tracing::debug!(%provider, %iid, %from, "runtime call"); + calls.push(from); + } + } let found = AREAS .iter() .flat_map(|area| area.iter()) @@ -236,6 +279,7 @@ pub(crate) fn module() -> HleModule { hle_export!(XGameRuntimeUninitialize), hle_export!(InitializeApiImpl), hle_export!(InitializeApiImplEx), + hle_export!(InitializeApiImplEx2), hle_export!(UninitializeApiImpl), hle_export!(QueryApiImpl), hle_export!(XErrorReport), @@ -257,6 +301,7 @@ mod tests { for name in [ c"InitializeApiImpl", c"InitializeApiImplEx", + c"InitializeApiImplEx2", c"QueryApiImpl", c"UninitializeApiImpl", c"XErrorReport", diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs new file mode 100644 index 0000000..7282284 --- /dev/null +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -0,0 +1,1291 @@ +//! XGameSave: the user's game saves, kept on the host under the title's +//! data directory, next to persistent local storage (`runtime::Title:: +//! saves`), never in the cache. A provider is a folder per user and +//! service configuration, a container a folder in it. +//! +//! An update is all or nothing, as documented: each one writes a complete +//! new version of the container (`v<N>.new/`, unchanged blobs hard-linked +//! from the previous version), flushed to disk, and one directory rename +//! commits it (`v<N>`); the highest committed version is the container. +//! A crash leaves the old version or the new one, never a mix; leftovers +//! are removed on sight. Deleting a container renames it away first. +//! +//! Names are exact: a version's `manifest` holds the container's name, its +//! display name and the blob names (blob `i` is the file `i`), so case, +//! characters the host forbids, reserved device names and length never +//! reach a file name. A container's folder is its name made safe (and +//! shortened) plus a hash of the exact name, so names differing only in +//! case get different folders. Offline there is no cloud copy, so nothing +//! ever needs a sync. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CString, c_char, c_void}; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use super::xasync::{self, AsyncBlock, E_INVALIDARG}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; +use super::{storage, xuser}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x704c_3f58, + 0xe629, + 0x4cc2, + [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], +); +/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// the public API's arguments in the same order as under the provider's +/// own id (older titles). +pub const IID_2026: Guid = Guid::new( + 0x1bff_f3af, + 0xf14a, + 0x40a3, + [0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9], +); + +pub static OBJECT: Object = Object::new("game save", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +// The public API's error codes. +pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32; +pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32; +pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32; +pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32; +pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32; +pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32; +pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32; + +/// Per user and title, as documented. +const QUOTA: u64 = 256 << 20; +/// What one update may write in all, as documented. +const MAX_UPDATE: usize = 16 << 20; +const MANIFEST: &str = "manifest"; +/// Readable part of a container's folder name, at most. +const READABLE: usize = 100; + +/// Every save operation, so none sees another's half-made version. +static SAVES: Mutex<()> = Mutex::new(()); + +fn saves_lock() -> std::sync::MutexGuard<'static, ()> { + SAVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `name` as a file name: letters, digits, `-` and `_` stay, every other +/// byte becomes `%XX`. The result never contains a dot. +fn file_name(name: &str) -> String { + name.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +/// The name behind a file name from [`file_name`]; `None` for other files. +fn decode(file: &str) -> Option<String> { + if file.contains('.') { + return None; + } + let mut out = Vec::new(); + let mut bytes = file.bytes(); + while let Some(b) = bytes.next() { + if b == b'%' { + let hex = [bytes.next()?, bytes.next()?]; + out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?); + } else { + out.push(b); + } + } + String::from_utf8(out).ok() +} + +/// The container's folder: its name made safe, cut short, then `~` and a +/// hash of the exact name (64-bit FNV-1a, stable across builds). +fn container_dir(root: &Path, name: &str) -> PathBuf { + let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + let mut readable = file_name(name); + readable.truncate(READABLE); // ASCII only + root.join(format!("{readable}~{hash:016x}")) +} + +/// Documented: the path part (up to the last `/`) letters, digits, `_` and +/// `/`; the file part letters, digits, `_`, `.` and `-`, not empty, not +/// ending in `.`, no `..`; 256 characters at most. +fn valid_container(name: &str) -> bool { + let (path, file) = name.rsplit_once('/').unwrap_or(("", name)); + name.len() <= 256 + && path + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/') + && !file.is_empty() + && !file.ends_with('.') + && !file.contains("..") + && file + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) +} + +/// A committed version of a container. +struct Version { + dir: PathBuf, + number: u64, + name: String, + display: String, + /// Blob names; blob `i` is the file `i`. + blobs: Vec<String>, +} + +impl Version { + fn blob(&self, i: usize) -> PathBuf { + self.dir.join(i.to_string()) + } + + fn sizes(&self) -> Vec<(String, u64)> { + let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len()); + let blobs = self.blobs.iter().enumerate(); + blobs.map(|(i, n)| (n.clone(), size(i))).collect() + } +} + +/// The manifest: length-prefixed strings (u32 LE): container name, display +/// name, then each blob name. +fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec<u8> { + let mut out = Vec::new(); + for s in [name, display].into_iter().chain(blobs.iter().copied()) { + out.extend_from_slice(&(s.len() as u32).to_le_bytes()); + out.extend_from_slice(s.as_bytes()); + } + out +} + +fn parse_manifest(bytes: &[u8]) -> Option<Vec<String>> { + let mut out = Vec::new(); + let mut rest = bytes; + while !rest.is_empty() { + let (len, tail) = rest.split_first_chunk::<4>()?; + let len = u32::from_le_bytes(*len) as usize; + out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?); + rest = &tail[len..]; + } + (out.len() >= 2).then_some(out) +} + +/// The container's newest committed version, if any. Removes what a crash +/// left: unfinished versions and older ones. +fn current(dir: &Path) -> std::io::Result<Option<Version>> { + let mut committed = Vec::new(); + for entry in std::fs::read_dir(dir)?.flatten() { + let file = entry.file_name(); + let file = file.to_string_lossy(); + if file.ends_with(".new") { + std::fs::remove_dir_all(entry.path())?; + } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::<u64>().ok()) { + committed.push(n); + } + } + committed.sort_unstable(); + let Some(&number) = committed.last() else { + return Ok(None); + }; + for old in &committed[..committed.len() - 1] { + std::fs::remove_dir_all(dir.join(format!("v{old}")))?; + } + let version = dir.join(format!("v{number}")); + let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest"); + let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?; + let blobs = names.split_off(2); + let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?; + Ok(Some(Version { + dir: version, + number, + name, + display, + blobs, + })) +} + +/// The version of container `name` in `dir`; none for a missing container +/// or another name that hashes alike. +fn current_named(dir: &Path, name: &str) -> std::io::Result<Option<Version>> { + match current(dir) { + Ok(v) => Ok(v.filter(|v| v.name == name)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Where a crash test stops the process (test builds only). +fn step() { + #[cfg(test)] + tests::crash_point(); +} + +/// A blob of a new version: new data, or the previous version's file. +enum Source<'a> { + Data(&'a [u8]), + Kept(PathBuf), +} + +/// Writes version `number` of the container in `dir` and commits it. +fn commit( + dir: &Path, + number: u64, + name: &str, + display: &str, + blobs: &[(&str, Source<'_>)], +) -> std::io::Result<()> { + let staged = dir.join(format!("v{number}.new")); + if staged.exists() { + std::fs::remove_dir_all(&staged)?; + } + std::fs::create_dir_all(&staged)?; + let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + file.write_all(data)?; + file.sync_all() + }; + for (i, (_, source)) in blobs.iter().enumerate() { + let path = staged.join(i.to_string()); + match source { + Source::Data(data) => write(path, data)?, + // Files are never changed in place, so sharing one is safe. + Source::Kept(from) => std::fs::hard_link(from, &path) + .or_else(|_| std::fs::copy(from, &path).map(drop))?, + } + step(); + } + let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect(); + write(staged.join(MANIFEST), &manifest(name, display, &names))?; + step(); + std::fs::rename(&staged, dir.join(format!("v{number}")))?; + step(); + Ok(()) +} + +/// The containers under a provider's root, by exact name; containers in +/// the old one-file-per-blob layout are converted first. +fn containers(root: &Path) -> Vec<(String, PathBuf)> { + let mut out = Vec::new(); + for entry in std::fs::read_dir(root).into_iter().flatten().flatten() { + let path = entry.path(); + let file = entry.file_name().to_string_lossy().into_owned(); + if !path.is_dir() { + continue; + } + if file.ends_with(".gone") { + let _ = std::fs::remove_dir_all(&path); + } else if file.contains('~') { + if let Ok(Some(v)) = current(&path) { + out.push((v.name, path)); + } + } else if let Some(name) = decode(&file) + && let Some(dir) = migrate(root, &name, &path) + { + out.push((name, dir)); + } + } + out.sort(); + out +} + +/// Moves a container of the old layout (blob files named by encoded name, +/// a `.display` file) into a committed version, then removes it. +fn migrate(root: &Path, name: &str, old: &Path) -> Option<PathBuf> { + let dir = container_dir(root, name); + let done = current_named(&dir, name).ok()?.is_some(); // a crash after the commit + if !done { + let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default(); + let mut blobs: Vec<(String, Vec<u8>)> = std::fs::read_dir(old) + .ok()? + .flatten() + .filter_map(|e| { + let blob = decode(e.file_name().to_str()?)?; + Some((blob, std::fs::read(e.path()).ok()?)) + }) + .collect(); + blobs.sort(); + let sources: Vec<_> = blobs + .iter() + .map(|(n, d)| (n.as_str(), Source::Data(d))) + .collect(); + commit(&dir, 1, name, &display, &sources).ok()?; + } + std::fs::remove_dir_all(old).ok()?; + tracing::info!(container = name, "game save moved to the versioned layout"); + Some(dir) +} + +fn used_bytes(root: &Path) -> u64 { + containers(root) + .iter() + .filter_map(|(name, dir)| current_named(dir, name).ok().flatten()) + .map(|v| v.sizes().iter().map(|(_, size)| size).sum::<u64>()) + .sum() +} + +struct Provider { + root: PathBuf, +} +struct Container { + name: String, + dir: PathBuf, +} +struct Update { + name: String, + dir: PathBuf, + display: Option<String>, + /// Blob writes (`Some`) and deletions (`None`), in order. + changes: Vec<(String, Option<Vec<u8>>)>, +} + +/// A handle we gave out. +fn get<'a, T>(handle: *const T) -> Option<&'a T> { + // SAFETY: handles are boxes we created and the title has not closed. + unsafe { handle.as_ref() } +} +fn give<T>(value: T) -> *mut T { + Box::into_raw(Box::new(value)) +} +fn take<T>(handle: *mut T) { + if !handle.is_null() { + // SAFETY: as in `get`; closing ends the handle. + drop(unsafe { Box::from_raw(handle) }); + } +} + +impl Provider { + /// The provider for the only user and `config` (the service + /// configuration id), under `saves`. + fn open(saves: &Path, config: Option<&str>) -> Result<Provider, HRESULT> { + let root = saves + .join(format!("{:016X}", xuser::XUID)) + .join(file_name(config.unwrap_or("default"))); + std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?; + let _saves = saves_lock(); + containers(&root); // converts old containers now + Ok(Provider { root }) + } + + fn remaining(&self) -> u64 { + let _saves = saves_lock(); + remaining(&self.root) + } + + fn container(&self, name: &str) -> Container { + Container { + name: name.to_owned(), + dir: container_dir(&self.root, name), + } + } +} + +/// Quota left under a provider's root, or less if the host disk is fuller. +fn remaining(root: &Path) -> u64 { + QUOTA + .saturating_sub(used_bytes(root)) + .min(storage::disk_free(root)) +} + +fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT { + tracing::warn!(dir = %dir.display(), %e, "game save"); + if e.kind() == std::io::ErrorKind::StorageFull { + OUT_OF_LOCAL_STORAGE + } else { + NO_ACCESS + } +} + +impl Update { + /// Applies the update as one new version of the container. + fn submit(&self) -> HRESULT { + let _saves = saves_lock(); + let current = match current(&self.dir) { + Ok(v) => v, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return io_error(&self.dir, &e), + }; + if current.as_ref().is_some_and(|v| v.name != self.name) { + // Another container's name hashes alike: never mix the two. + return NO_ACCESS; + } + // The blobs after the update: name → new data or the kept file. + let mut blobs: Vec<(&str, Source<'_>)> = current + .iter() + .flat_map(|v| { + let kept = v.blobs.iter().enumerate(); + kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i)))) + }) + .collect(); + for (name, data) in &self.changes { + blobs.retain(|(n, _)| n != name); + if let Some(data) = data { + blobs.push((name, Source::Data(data))); + } + } + blobs.sort_by(|a, b| a.0.cmp(b.0)); + let written: usize = blobs + .iter() + .map(|(_, s)| match s { + Source::Data(d) => d.len(), + Source::Kept(_) => 0, + }) + .sum(); + if written > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + let replaced: u64 = current.as_ref().map_or(0, |v| { + let sizes = v.sizes(); + let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + changed.map(|(_, size)| size).sum() + }); + let root = self.dir.parent().unwrap_or(&self.dir); + if written as u64 > remaining(root) + replaced { + return QUOTA_EXCEEDED; + } + let display = self.display.as_deref(); + let display = display.or(current.as_ref().map(|v| v.display.as_str())); + let number = current.as_ref().map_or(1, |v| v.number + 1); + if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) { + return io_error(&self.dir, &e); + } + // The old version is garbage now; a crash here leaves it for later. + if let Some(old) = ¤t { + let _ = std::fs::remove_dir_all(&old.dir); + step(); + } + S_OK + } +} + +/// Deletes a container: renamed away (one step), then removed. +fn delete(root: &Path, name: &str) -> HRESULT { + let _saves = saves_lock(); + let dir = container_dir(root, name); + match current_named(&dir, name) { + Ok(Some(_)) => {} + Ok(None) => return S_OK, + Err(e) => return io_error(&dir, &e), + } + let gone = dir.with_extension("gone"); + let _ = std::fs::remove_dir_all(&gone); + step(); + if let Err(e) = std::fs::rename(&dir, &gone) { + return io_error(&dir, &e); + } + step(); + let _ = std::fs::remove_dir_all(&gone); + S_OK +} + +/// Reads the named blobs (all of them for `None`) of a container. +fn read(c: &Container, names: Option<Vec<String>>) -> Result<Vec<(String, Vec<u8>)>, HRESULT> { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name) + .map_err(|e| io_error(&c.dir, &e))? + .ok_or(BLOB_NOT_FOUND)?; + let names = names.unwrap_or_else(|| version.blobs.clone()); + names + .into_iter() + .map(|name| { + let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?; + let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?; + Ok((name, data)) + }) + .collect() +} + +/// One blob as the public API lays it out: name, size, data. +const BLOB: usize = 24; + +/// Blobs laid out as the title reads them: the blob array, then each name +/// (NUL-terminated) and its data, with pointers `base` plus offset. +fn layout(blobs: &[(String, Vec<u8>)], base: usize) -> Vec<u8> { + let mut out = vec![0u8; blobs.len() * BLOB]; + for (i, (name, data)) in blobs.iter().enumerate() { + let name_at = base + out.len(); + out.extend_from_slice(name.as_bytes()); + out.push(0); + let data_at = base + out.len(); + out.extend_from_slice(data); + let entry = &mut out[i * BLOB..(i + 1) * BLOB]; + entry[..8].copy_from_slice(&name_at.to_le_bytes()); + entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes()); + entry[16..].copy_from_slice(&data_at.to_le_bytes()); + } + out +} + +/// The names a title passes (`count` strings, or all blobs if null). +fn names(names: *const *const c_char, count: u32) -> Option<Vec<String>> { + if names.is_null() { + return None; + } + // SAFETY: the title passes `count` strings. + let names = unsafe { std::slice::from_raw_parts(names, count as usize) }; + Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect()) +} + +type This = *const Object; +type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool; +type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool; + +#[repr(C)] +pub struct ContainerInfo { + pub name: *const c_char, + pub display_name: *const c_char, + pub blob_count: u32, + pub total_size: u64, + pub last_modified: i64, + pub needs_sync: bool, +} + +#[repr(C)] +pub struct BlobInfo { + pub name: *const c_char, + pub size: u32, +} + +/// Calls `callback` with the information of each container that passes +/// `keep` until it returns false; never under our lock (it may call us). +fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) { + let infos: Vec<(CString, CString, u32, u64, i64)> = { + let _saves = saves_lock(); + containers(root) + .into_iter() + .filter(|(name, _)| keep(name)) + .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten()) + .map(|v| { + let modified = std::fs::metadata(v.dir.join(MANIFEST)) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs() as i64); + let size = v.sizes().iter().map(|(_, s)| s).sum(); + let count = v.blobs.len() as u32; + (cstring(&v.name), cstring(&v.display), count, size, modified) + }) + .collect() + }; + for (name, display, blob_count, total_size, last_modified) in &infos { + let info = ContainerInfo { + name: name.as_ptr(), + display_name: display.as_ptr(), + blob_count: *blob_count, + total_size: *total_size, + last_modified: *last_modified, + needs_sync: false, + }; + if !callback(&info, context) { + break; + } + } +} + +fn cstring(s: &str) -> CString { + CString::new(s.replace('\0', "")).unwrap_or_default() +} + +static INIT: u8 = 0; +static QUOTA_CALL: u8 = 0; +static DELETE: u8 = 0; +static READ: u8 = 0; +static SUBMIT: u8 = 0; + +extern "system" fn initialize_async( + _: This, + _user: *const c_void, + config: *const c_char, + _sync_on_demand: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let saves = runtime::title().saves(); + let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) { + Err(NO_ACCESS) + } else { + Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p))) + }; + xasync::finished_with(block, (&raw const INIT).cast(), result) +} +extern "system" fn initialize_result( + _: This, + block: *mut AsyncBlock, + out: *mut *mut Provider, +) -> HRESULT { + xasync::result(block, (&raw const INIT).cast(), out) +} +extern "system" fn close_provider(_: This, provider: *mut Provider) { + take(provider); +} + +extern "system" fn quota_async( + _: This, + provider: *const Provider, + block: *mut AsyncBlock, +) -> HRESULT { + let result = get(provider) + .ok_or(E_INVALIDARG) + .map(|p| xasync::bytes(p.remaining() as i64)); + xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result) +} +extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT { + xasync::result(block, (&raw const QUOTA_CALL).cast(), out) +} + +extern "system" fn delete_async( + _: This, + provider: *const Provider, + name: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let hr = match (get(provider), text(name)) { + (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name), + (Some(_), Some(_)) => INVALID_CONTAINER_NAME, + _ => E_INVALIDARG, + }; + xasync::finished(block, (&raw const DELETE).cast(), hr) +} +extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast()) +} + +/// Reports the container if it exists; a missing one is no error, the +/// callback just does not run. +extern "system" fn container_info( + _: This, + provider: *const Provider, + name: *const c_char, + context: *mut c_void, + callback: Option<ContainerCallback>, +) -> HRESULT { + let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + report(&p.root, |n| n == name, context, callback); + S_OK +} + +extern "system" fn enumerate_containers( + _: This, + provider: *const Provider, + context: *mut c_void, + callback: Option<ContainerCallback>, +) -> HRESULT { + let (Some(p), Some(callback)) = (get(provider), callback) else { + return E_INVALIDARG; + }; + report(&p.root, |_| true, context, callback); + S_OK +} + +/// The container exists once an update to it is submitted. +extern "system" fn create_container( + _: This, + provider: *const Provider, + name: *const c_char, + out: *mut *mut Container, +) -> HRESULT { + let (Some(p), Some(name)) = (get(provider), text(name)) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + put(out, give(p.container(&name))) +} +extern "system" fn close_container(_: This, container: *mut Container) { + take(container); +} + +extern "system" fn enumerate_blobs( + _: This, + container: *const Container, + prefix: *const c_char, + context: *mut c_void, + callback: Option<BlobCallback>, +) -> HRESULT { + let (Some(c), Some(callback)) = (get(container), callback) else { + return E_INVALIDARG; + }; + let prefix = text(prefix).unwrap_or_default(); + let blobs = { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name).ok().flatten(); + version.map(|v| v.sizes()).unwrap_or_default() + }; + for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) { + let name = cstring(&name); + let info = BlobInfo { + name: name.as_ptr(), + size: size as u32, + }; + if !callback(&info, context) { + break; + } + } + S_OK +} + +extern "system" fn read_blobs( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: *mut u32, + size: usize, + out: *mut u8, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + // SAFETY: the title passes its count. + let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0); + let blobs = match read(c, names(blob_names, wanted)) { + Ok(blobs) => blobs, + Err(hr) => return hr, + }; + let bytes = layout(&blobs, out as usize); + if out.is_null() || size < bytes.len() { + return BUFFER_TOO_SMALL; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) }; + put(count, blobs.len() as u32) +} + +/// Read at once; the result holds the layout with pointers relative to the +/// title's buffer, fixed up when the title takes it. +extern "system" fn read_async( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: u32, + block: *mut AsyncBlock, +) -> HRESULT { + let result = match get(container) { + Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)), + None => Err(E_INVALIDARG), + }; + xasync::finished_with(block, (&raw const READ).cast(), result) +} +extern "system" fn read_result( + _: This, + block: *mut AsyncBlock, + size: usize, + out: *mut u8, + count: *mut u32, +) -> HRESULT { + let mut used = 0; + let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used); + if hr < 0 { + return hr; + } + // The first name follows the blob array, so its offset gives the count. + let blobs = if used == 0 { + 0 + } else { + // SAFETY: the result holds at least one blob entry. + unsafe { out.cast::<usize>().read_unaligned() / BLOB } + }; + for i in 0..blobs { + for field in [0, 16] { + // SAFETY: within the blob array just written. + unsafe { + let p = out.add(i * BLOB + field).cast::<usize>(); + p.write_unaligned(p.read_unaligned() + out as usize); + } + } + } + put(count, blobs as u32) +} + +extern "system" fn create_update( + _: This, + container: *const Container, + display: *const c_char, + out: *mut *mut Update, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + put( + out, + give(Update { + name: c.name.clone(), + dir: c.dir.clone(), + display: text(display), + changes: Vec::new(), + }), + ) +} +extern "system" fn close_update(_: This, update: *mut Update) { + take(update); +} + +extern "system" fn write_blob( + _: This, + update: *mut Update, + name: *const c_char, + data: *const u8, + size: usize, +) -> HRESULT { + // SAFETY: a handle we gave out; the title does not use it concurrently. + let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else { + return E_INVALIDARG; + }; + if name.is_empty() || (data.is_null() && size > 0) { + return E_INVALIDARG; + } + if size > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + let data = if size == 0 { + Vec::new() + } else { + // SAFETY: the title passes `size` bytes. + unsafe { std::slice::from_raw_parts(data, size) }.to_vec() + }; + update.changes.push((name, Some(data))); + S_OK +} + +extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT { + // SAFETY: as in `write_blob`. + match (unsafe { update.as_mut() }, text(name)) { + (Some(update), Some(name)) if !name.is_empty() => { + update.changes.push((name, None)); + S_OK + } + _ => E_INVALIDARG, + } +} + +extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT { + let hr = get(update).map_or(E_INVALIDARG, Update::submit); + xasync::finished(block, (&raw const SUBMIT).cast(), hr) +} +extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<30> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 initialize (blocking) + initialize_async as *const (), // 0x20 + initialize_result as *const (), // 0x28 + close_provider as *const (), // 0x30 + missing::<7> as *const (), // 0x38 remaining quota (blocking) + quota_async as *const (), // 0x40 + quota_result as *const (), // 0x48 + missing::<10> as *const (), // 0x50 delete (blocking) + delete_async as *const (), // 0x58 + delete_result as *const (), // 0x60 + container_info as *const (), // 0x68 + enumerate_containers as *const (), // 0x70 + missing::<15> as *const (), // 0x78 by name prefix + create_container as *const (), // 0x80 + close_container as *const (), // 0x88 + missing::<18> as *const (), // 0x90 all blob info + enumerate_blobs as *const (), // 0x98 by name prefix + read_blobs as *const (), // 0xa0 + read_async as *const (), // 0xa8 + read_result as *const (), // 0xb0 + create_update as *const (), // 0xb8 + close_update as *const (), // 0xc0 + write_blob as *const (), // 0xc8 + delete_blob as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 submit (blocking) + submit_async as *const (), // 0xe0 + submit_result as *const (), // 0xe8 +]); + +#[cfg(test)] +mod tests { + use std::io::BufRead; + use std::sync::atomic::{AtomicU32, Ordering}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + static STEPS: AtomicU32 = AtomicU32::new(0); + + /// In a child process of the crash test, stops for good at the step + /// `VICTORY_SAVE_STOP` names and says so. + pub(super) fn crash_point() { + let Ok(stop) = std::env::var("VICTORY_SAVE_STOP") else { + return; + }; + if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) { + println!("STOPPED"); + let _ = std::io::stdout().flush(); + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + } + + fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT { + Update { + name: "Slot".into(), + dir: container_dir(root, "Slot"), + display: Some(display.into()), + changes: changes + .iter() + .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec()))) + .collect(), + } + .submit() + } + + /// The container `Slot`: display name and blobs. + fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> { + let c = Provider { root: root.into() }.container("Slot"); + let display = current_named(&c.dir, "Slot").unwrap()?.display; + let blobs = read(&c, None).unwrap(); + let text = |(n, d): (String, Vec<u8>)| (n, String::from_utf8(d).unwrap()); + Some((display, blobs.into_iter().map(text).collect())) + } + + fn old_state() -> Option<(String, Vec<(String, String)>)> { + Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) + } + + /// Run by the crash test in a child process; does nothing otherwise. + #[test] + fn crash_child() { + let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else { + return; + }; + let root = PathBuf::from(root); + let hr = if op == "update" { + update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) + } else { + delete(&root, "Slot") + }; + assert_eq!(hr, S_OK); + println!("FINISHED"); + } + + /// Kills a process in the middle of an update (and of a deletion) at + /// every step: what is left is the whole old container or the whole + /// new one. + #[test] + fn a_kill_at_any_step_leaves_old_or_new() { + let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); + for (op, after) in [("update", new), ("delete", None)] { + let mut seen = (0, 0); + for stop in 1.. { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) + .args(["--test-threads=1"]) + .env("VICTORY_SAVE_CHILD", root) + .env("VICTORY_SAVE_OP", op) + .env("VICTORY_SAVE_STOP", stop.to_string()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let out = std::io::BufReader::new(child.stdout.take().unwrap()); + let mut finished = false; + for line in out.lines() { + let line = line.unwrap(); + if line.contains("STOPPED") { + break; + } + finished |= line.contains("FINISHED"); + } + let _ = child.kill(); + child.wait().unwrap(); + let left = state(root); + if left == old_state() { + seen.0 += 1; + } else { + assert_eq!(left, after, "{op}, killed at step {stop}"); + seen.1 += 1; + } + if finished { + break; + } + } + assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}"); + } + } + + #[test] + fn names_are_exact() { + for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] { + let file = file_name(name); + assert!(!file.contains(['.', '/', ' ']), "{file}"); + assert_eq!(decode(&file).as_deref(), Some(name)); + } + assert_eq!(decode("x.new"), None); + for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { + assert!(valid_container(good), "{good}"); + } + for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { + assert!(!valid_container(bad), "{bad}"); + } + + // Containers and blobs differing only in case, reserved device + // names, characters the host forbids, long names: all distinct. + let dir = tempfile::tempdir().unwrap(); + let p = Provider { root: dir.path().into() }; + let long = "n".repeat(300); + let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; + for container in ["Save", "save", "SAVE/CON.x"] { + let c = p.container(container); + let u = Update { + name: c.name.clone(), + dir: c.dir.clone(), + display: None, + changes: blobs + .iter() + .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes()))) + .collect(), + }; + assert_eq!(u.submit(), S_OK, "{container}"); + } + let _saves = saves_lock(); + let names: Vec<String> = containers(dir.path()).into_iter().map(|c| c.0).collect(); + drop(_saves); + assert_eq!(names, ["SAVE/CON.x", "Save", "save"]); + for container in ["Save", "save", "SAVE/CON.x"] { + let read = read(&p.container(container), None).unwrap(); + let mut expected: Vec<_> = blobs + .iter() + .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes())) + .collect(); + expected.sort(); + assert_eq!(read, expected, "{container}"); + } + } + + #[test] + fn the_old_layout_moves_over() { + let saves = tempfile::tempdir().unwrap(); + let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); + let old = root.join("Player"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); + std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap(); + std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap(); + std::fs::write(old.join(".display"), b"Chapter 1").unwrap(); + let p = Provider::open(saves.path(), Some("scid")).unwrap(); + assert!(!old.exists()); + let c = p.container("Player"); + let blobs = read(&c, None).unwrap(); + assert_eq!( + blobs, + [ + ("Save Game Data".into(), b"data".to_vec()), + ("Save Game Header".into(), b"header".to_vec()) + ] + ); + let v = current_named(&c.dir, "Player").unwrap().unwrap(); + assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); + } + + #[test] + fn saves_persist_across_providers() { + let this: This = &OBJECT; + let saves = tempfile::tempdir().unwrap(); + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + + // Write two blobs through an update. + let mut container = std::ptr::null_mut(); + type Create = extern "system" fn( + This, + *const Provider, + *const c_char, + *mut *mut Container, + ) -> HRESULT; + let create = method::<Create>(&OBJECT, 0x80); + assert_eq!( + create(this, provider, c"bad name".as_ptr(), &mut container), + INVALID_CONTAINER_NAME + ); + assert_eq!( + create(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut update = std::ptr::null_mut(); + type Update_ = + extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT; + assert_eq!( + method::<Update_>(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update), + S_OK + ); + type Write = + extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT; + let write = method::<Write>(&OBJECT, 0xc8); + assert_eq!( + write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5), + S_OK + ); + assert_eq!( + write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2), + S_OK + ); + assert_eq!( + write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1), + S_OK + ); + type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; + assert_eq!(method::<Delete>(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); + type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; + let mut b = block(); + assert_eq!(method::<Submit>(&OBJECT, 0xe0)(this, update, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + close_update(this, update); + close_container(this, container); + close_provider(this, provider); + + // A new provider sees the container and reads both blobs back. + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool { + // SAFETY: valid during the callback; the context is the test's vector. + let (info, out) = unsafe { + ( + &*info, + &mut *context.cast::<Vec<(String, String, u32, u64)>>(), + ) + }; + out.push(( + text(info.name).unwrap(), + text(info.display_name).unwrap(), + info.blob_count, + info.total_size, + )); + true + } + let mut found: Vec<(String, String, u32, u64)> = Vec::new(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]); + + let mut container = std::ptr::null_mut(); + assert_eq!( + create_container(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut b = block(); + let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()]; + assert_eq!( + read_async(this, container, wanted.as_ptr(), 2, &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut size = 0; + assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK); + assert_eq!( + size, + 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len() + ); + let mut buffer = vec![0u64; size.div_ceil(8)]; + let mut count = 0; + assert_eq!( + read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count), + S_OK + ); + assert_eq!(count, 2); + let blob = |i: usize| { + // SAFETY: the layout the call wrote. + unsafe { + let entry = buffer.as_ptr().cast::<u8>().add(i * BLOB); + let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap(); + let len = entry.add(8).cast::<u32>().read_unaligned() as usize; + let data = std::slice::from_raw_parts( + entry.add(16).cast::<*const u8>().read_unaligned(), + len, + ); + (name, data.to_vec()) + } + }; + assert_eq!(blob(0), ("world".into(), b"hello".to_vec())); + assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec())); + + let missing = [c"nothing".as_ptr()]; + let mut one = 1; + let mut small = [0u8; 8]; + let read_now = method::< + extern "system" fn( + This, + *const Container, + *const *const c_char, + *mut u32, + usize, + *mut u8, + ) -> HRESULT, + >(&OBJECT, 0xa0); + assert_eq!( + read_now( + this, + container, + missing.as_ptr(), + &mut one, + 8, + small.as_mut_ptr() + ), + BLOB_NOT_FOUND + ); + assert_eq!( + read_now( + this, + container, + wanted.as_ptr(), + &mut 2, + 8, + small.as_mut_ptr() + ), + BUFFER_TOO_SMALL + ); + + // Quota counts the blobs; deleting the container frees it. + let mut b = block(); + assert_eq!(quota_async(this, provider, &mut b), S_OK); + let mut left = 0i64; + assert_eq!(quota_result(this, &mut b, &mut left), S_OK); + assert!(left as u64 <= QUOTA - 7); + let mut b = block(); + assert_eq!( + delete_async(this, provider, c"Slot_1".as_ptr(), &mut b), + S_OK + ); + assert_eq!(delete_result(this, &mut b), S_OK); + found.clear(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert!(found.is_empty()); + close_container(this, container); + close_provider(this, provider); + } +} diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs new file mode 100644 index 0000000..ab2d9e0 --- /dev/null +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -0,0 +1,321 @@ +//! System dialogs a title opens (XGameUi). A profile card has nothing to +//! show and closes at once. Text entry opens a small host dialog (title, +//! description, default text, the length limit) on a thread of its own and +//! completes the call with what the user typed, or as cancelled (`E_ABORT`) +//! when the dialog is dismissed or cannot open. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xdfcd_4649, + 0x4ff8, + 0x4043, + [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], +); +/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x38, +/// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order. +pub const IID_2026: Guid = Guid::new( + 0xeaf6_69df, + 0x5542, + 0x4590, + [0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc], +); + +pub static OBJECT: Object = Object::new("game ui", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +type This = *const Object; + +static PROFILE: u8 = 0; +static TEXT: u8 = 0; + +extern "system" fn profile_card_async( + _: This, + block: *mut AsyncBlock, + _user: *const c_void, + xuid: u64, +) -> HRESULT { + tracing::info!(xuid, "profile card: nothing to show"); + xasync::finished(block, (&raw const PROFILE).cast(), S_OK) +} +extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) +} + +/// Grand Theft Auto VI treats `E_ABORT` as cancelled and goes on; any +/// other failure as an error. +extern "system" fn text_entry_async( + _: This, + block: *mut AsyncBlock, + title: *const c_char, + description: *const c_char, + default: *const c_char, + _scope: u32, + max_length: u32, +) -> HRESULT { + let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); + tracing::info!(title, description, max_length, "text entry"); + xasync::pending_with(block, (&raw const TEXT).cast(), move || { + match ask(&title, &description, &default, max_length) { + Some(typed) => { + tracing::info!(length = typed.chars().count(), "text entry: done"); + let mut bytes = limit(&typed, max_length).into_bytes(); + bytes.push(0); + Ok(bytes) + } + None => { + tracing::info!("text entry: cancelled"); + Err(E_ABORT) + } + } + }) +} +/// Bytes of the result, its NUL included. +extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT { + let mut size = 0; + let hr = xasync::XAsyncGetResultSize(block, &mut size); + if hr < 0 { + return hr; + } + put(out, size as u32) +} +extern "system" fn text_entry_result( + _: This, + block: *mut AsyncBlock, + size: u32, + buffer: *mut c_char, + used: *mut u32, +) -> HRESULT { + let mut written = 0; + let identity = (&raw const TEXT).cast(); + let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written); + if hr < 0 || used.is_null() { + return hr; + } + put(used, written as u32) +} + +/// At most `max` characters (0: no limit). +fn limit(typed: &str, max: u32) -> String { + match max { + 0 => typed.to_owned(), + max => typed.chars().take(max as usize).collect(), + } +} + +/// Asks the user in a modal host dialog; `None` if dismissed. +#[cfg(not(test))] +fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> { + dialog::ask(title, description, default, max) +} + +/// Tests answer for the user: "typed" for a title starting with "Type", +/// cancelled otherwise. +#[cfg(test)] +fn ask(title: &str, _: &str, default: &str, _: u32) -> Option<String> { + title.starts_with("Type").then(|| format!("{default}typed")) +} + +mod dialog { + use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus; + use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE}; + + const EDIT: i32 = 100; + // Edit control messages (the controls headers). + const EM_SETSEL: u32 = 0xb1; + const EM_LIMITTEXT: u32 = 0xc5; + + /// The dialog's state, behind its user data while it runs. + struct Entry { + max: u32, + typed: Option<String>, + } + + /// The description, an edit box with the default text, OK and Cancel, + /// from an in-memory template (dialog units, the system font); Enter + /// accepts, Esc cancels. + #[allow(dead_code)] // unused in test builds + pub(super) fn ask(title: &str, description: &str, default: &str, max: u32) -> Option<String> { + let mut t: Vec<u16> = Vec::new(); + fn dword(t: &mut Vec<u16>, v: u32) { + t.extend([v as u16, (v >> 16) as u16]); + } + fn text(t: &mut Vec<u16>, s: &str) { + t.extend(s.encode_utf16().filter(|&c| c != 0)); + t.push(0); + } + let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU; + let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32; + dword(&mut t, style | flags); + dword(&mut t, wm::WS_EX_TOPMOST); + t.extend([4, 0, 0, 240, 62, 0, 0]); // items, x, y, cx, cy, no menu, default class + text(&mut t, title); + let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| { + if t.len() % 2 == 1 { + t.push(0); // items start on a DWORD + } + dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style); + dword(&mut t, 0); + t.extend(rect); + t.extend([id, 0xffff, class]); + text(&mut t, caption); + t.push(0); // no creation data + }; + let (button, edit, label) = (0x80, 0x81, 0x82); + let tab = wm::WS_TABSTOP; + item(0, [7, 7, 226, 10], 0xffff, label, description); + let edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32; + item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default); + let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; + item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); + let cancel = wm::BS_PUSHBUTTON as u32 | tab; + item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); + // The template must start on a DWORD. + let template: Vec<u32> = t + .chunks(2) + .map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16) + .collect(); + let mut entry = Entry { max, typed: None }; + // SAFETY: a complete template and our dialog procedure; `entry` + // outlives the modal dialog. + unsafe { + wm::DialogBoxIndirectParamW( + GetModuleHandleW(std::ptr::null()), + template.as_ptr().cast::<DLGTEMPLATE>(), + std::ptr::null_mut(), + Some(procedure), + (&raw mut entry) as LPARAM, + ); + } + entry.typed + } + + extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { + // SAFETY: our dialog; its user data is the `Entry` from `ask`, + // stored at WM_INITDIALOG. + unsafe { + let edit = wm::GetDlgItem(dialog, EDIT); + match message { + wm::WM_INITDIALOG => { + wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam); + let entry = &*(lparam as *const Entry); + wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0); + wm::SendMessageW(edit, EM_SETSEL, 0, -1); + SetFocus(edit); + 0 // focus set here + } + wm::WM_COMMAND => { + let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + match (wparam & 0xffff) as i32 { + wm::IDOK => { + let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + wm::EndDialog(dialog, 1); + } + wm::IDCANCEL => { + wm::EndDialog(dialog, 0); + } + _ => return 0, + } + 1 + } + _ => 0, + } + } + } +} + +static VTABLE: Methods<20> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 message dialog + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 send invite + missing::<6> as *const (), // 0x30 + profile_card_async as *const (), // 0x38 + profile_card_result as *const (), // 0x40 + missing::<9> as *const (), // 0x48 achievements + missing::<10> as *const (), // 0x50 + missing::<11> as *const (), // 0x58 player picker + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + missing::<14> as *const (), // 0x70 error dialog + missing::<15> as *const (), // 0x78 + missing::<16> as *const (), // 0x80 notification position + text_entry_async as *const (), // 0x88 + text_entry_size as *const (), // 0x90 + text_entry_result as *const (), // 0x98 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn dialogs_end_with_what_was_typed() { + let this: This = &OBJECT; + let mut b = block(); + type Card = extern "system" fn(This, *mut AsyncBlock, *const c_void, u64) -> HRESULT; + type Done = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + assert_eq!( + method::<Card>(&OBJECT, 0x38)(this, &mut b, std::ptr::null(), 1), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::<Done>(&OBJECT, 0x40)(this, &mut b), S_OK); + + type Entry = extern "system" fn( + This, + *mut AsyncBlock, + *const c_char, + *const c_char, + *const c_char, + u32, + u32, + ) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + let null = std::ptr::null(); + let entry = method::<Entry>(&OBJECT, 0x88); + // Dismissed: cancelled. + let mut b = block(); + assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); + let mut size = 0; + assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); + // Typed: the text, cut to the limit, with its NUL. + let mut b = block(); + let default = c"abc".as_ptr(); + assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::<Size>(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); + assert_eq!(size, 7); + let mut out = [0 as c_char; 7]; + let mut used = 0; + let result = method::<Result_>(&OBJECT, 0x98); + assert_eq!(result(this, &mut b, 7, out.as_mut_ptr(), &mut used), S_OK); + assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); + assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); + } +} diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 55ef50c..bcd3222 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -8,14 +8,18 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::alloc::{Layout, alloc, dealloc}; +use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; -use windows_sys::Win32::Foundation::HANDLE; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; use windows_sys::Win32::System::Memory::{ - MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE, - MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS, - PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx, + CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, + MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, + UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, }; use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; use windows_sys::Win32::System::Threading::GetCurrentProcess; @@ -24,11 +28,6 @@ use windows_sys::core::BOOL; use crate::{HleModule, hle_export}; const MIB: usize = 1 << 20; -const GIB: usize = 1 << 30; -/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of -/// GPU-optimal and 3.5 GiB of standard memory. -const GPU_OPTIMAL_LIMIT: usize = 10 * GIB; -const STANDARD_LIMIT: usize = 7 * GIB / 2; /// Standard memory the title has handed to the system. static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); @@ -39,6 +38,7 @@ static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); const PAGES_2M: u32 = 0x2000_0000; /// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory. const PAGES_64K_BIT: u32 = 0x40_0000; +const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT; /// The host's protection constants and `PAGE_GUARD`. Above them the console /// adds GPU access bits (0x800-0x40000). Write-combining and uncached are /// dropped too: our GPU side reads this memory through the CPU. @@ -47,16 +47,23 @@ const HOST_PROTECTION: u32 = 0x1ff; const GRAPHICS: u64 = 3; /// XMem flag bit of 32-bit graphics memory. const ADDRESS_32BIT: u64 = 4; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; -/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or -/// 46 down to 40 bits from the field at bit 12. -fn highest_address(flags: u64) -> usize { +/// The addresses XMem `flags` allow, first and last: the low 4 GiB for +/// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the +/// title's big pools would otherwise crowd out) up to 46 down to 40 bits +/// from the field at bit 12, or 40 bits without one: the console keeps +/// title memory there, and its ray-tracing structures must be (Grand Theft +/// Auto VI's BVH builder refuses one above; the title asks for its GPU heap +/// with no field). Decision 0001. +fn address_range(flags: u64) -> (usize, usize) { let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { - (0, 0) => return 0, + (0, 0) => 40, (0, field) => 47 - field, - _ => 32, + _ => return (0, u32::MAX as usize), }; - (1 << bits) - 1 + (1 << 32, (1 << bits) - 1) } pub extern "system" fn XMemVirtualAlloc( @@ -66,42 +73,78 @@ pub extern "system" fn XMemVirtualAlloc( flags: u64, protect: u32, ) -> *mut c_void { + let (lowest, highest) = address_range(flags); let mut requirements = MEM_ADDRESS_REQUIREMENTS { - HighestEndingAddress: highest_address(flags) as *mut c_void, + LowestStartingAddress: lowest as *mut c_void, + HighestEndingAddress: highest as *mut c_void, Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { 2 * MIB } else { 0 }, - ..Default::default() }; - let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT); - let protect = match protect & HOST_PROTECTION { + let mut protect = match protect & HOST_PROTECTION { 0 => PAGE_NOACCESS, p => p, }; + // A reservation of 64 KiB pages takes physical pages later + // (`XMemMapPhysicalPages`); on the host only a placeholder can. + // shortcut: committing part of such a reservation later would fail + // (Grand Theft Auto VI's 23 calls never do); replace that part of the + // placeholder then. + let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; + if placeholder { + if kind & MEM_REPLACE_PLACEHOLDER != 0 { + // Part of a placeholder the title split: it stays one. + return base; + } + protect = PAGE_NOACCESS; + } + let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT); + if placeholder { + kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER; + } let mut parameter = MEM_EXTENDED_PARAMETER::default(); parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); // Address requirements apply to reservations at an address of our choice. - let constrained = base.is_null() - && (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0); + let constrained = base.is_null(); if constrained { kind |= MEM_RESERVE; + // The GPU side copies only the pages the title wrote since its last + // copy (`victory_gpu`, decision 0007); placeholders cannot be + // watched (their physical-page views are copied whole). + if kind & MEM_RESERVE_PLACEHOLDER == 0 { + kind |= MEM_WRITE_WATCH; + } } // SAFETY: the title's own arguments, cleaned of console bits; the // parameter points at `requirements`, which outlives the call. - unsafe { + let at = unsafe { VirtualAlloc2( GetCurrentProcess(), base, size, kind, protect, - if constrained { &mut parameter } else { std::ptr::null_mut() }, + if constrained { + &mut parameter + } else { + std::ptr::null_mut() + }, constrained.into(), ) + }; + if base.is_null() { + tracing::debug!( + size, + kind = format_args!("{kind:#x}"), + flags = format_args!("{flags:#x}"), + at = format_args!("{at:p}"), + "XMemVirtualAlloc" + ); } + at } /// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the @@ -115,8 +158,9 @@ pub struct BasicInformation { } // shortcut: every committed page reports graphics memory and no tag, since -// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc` -// regions if a title tells CPU-only memory apart. +// all of it is GPU-reachable here (Grand Theft Auto VI's BVH builder, the +// only caller, wants graphics memory); remember the flags of +// `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. pub extern "system" fn XMemVirtualQuery( process: HANDLE, address: *const c_void, @@ -130,7 +174,11 @@ pub extern "system" fn XMemVirtualQuery( return 0; } let info = &mut *out; - info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 }; + info.flags = if info.host.State == MEM_COMMIT { + GRAPHICS + } else { + 0 + }; info.tag_code = 0; info.tag = [0; 4]; } @@ -151,10 +199,66 @@ fn layout(size: usize, attributes: u64) -> Option<Layout> { Layout::from_size_align(size.checked_add(align)?, align).ok() } -/// The title's general allocator, for middleware too. -// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title -// exports) are not called; no title we have sets them. +type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; +type FreeRoutine = extern "system" fn(*mut c_void, u64); + +/// The allocation and free routines the title's exe exports as +/// `__XMemAllocationHooks__` (Grand Theft Auto VI does): `XMemAlloc` and +/// `XMemFree` call them, for the title's own calls and its middleware's; +/// the `…Default` exports do not. +fn hooks() -> [usize; 2] { + static AT: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + let at = match AT.get() { + Some(&at) => at, + // Looked up once the title is mapped, which is before it runs. + None => match crate::runtime::main_image() { + Some(base) => *AT.get_or_init(|| { + use windows_sys::Win32::System::LibraryLoader::GetProcAddress; + // SAFETY: a mapped image and a NUL-terminated name. + let at = unsafe { + GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast()) + } + .map_or(0, |f| f as usize); + tracing::info!(found = at != 0, "xmem allocation hooks"); + at + }), + None => 0, + }, + }; + if at == 0 { + return [0; 2]; + } + // SAFETY: the export is two routine pointers. + unsafe { (at as *const [usize; 2]).read() } +} + +/// The title's general allocator, for middleware too: its hook if it has +/// one, else [`XMemAllocDefault`]. pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { + match hooks()[0] { + 0 => XMemAllocDefault(size, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) }; + alloc(size, attributes) + } + } +} + +/// See [`XMemAlloc`]. +pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { + match hooks()[1] { + 0 => XMemFreeDefault(address, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let free: FreeRoutine = unsafe { std::mem::transmute(hook) }; + free(address, attributes) + } + } +} + +/// The system allocator behind [`XMemAlloc`]. +pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void { if attributes & ALLOC_32BIT != 0 { return XMemVirtualAlloc( std::ptr::null_mut(), @@ -167,6 +271,10 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { let Some(layout) = layout(size, attributes) else { return std::ptr::null_mut(); }; + // shortcut: the host heap's addresses lie above 2^40, unlike the + // console's; nothing seen builds ray-tracing structures in this memory + // (Grand Theft Auto VI uses its GPU heap). Sub-allocate from a + // reservation below 2^40 if one does. // SAFETY: the layout has a non-zero size. let block = unsafe { alloc(layout) }; if block.is_null() { @@ -183,8 +291,8 @@ pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { } } -/// Frees what [`XMemAlloc`] returned, given the same attributes. -pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { +/// Frees what [`XMemAllocDefault`] returned, given the same attributes. +pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { if address.is_null() { return; } @@ -204,6 +312,383 @@ pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { } } +/// A retail console has no tools memory. +pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { + 0 +} + +// Physical pages: on the console, 64 KiB frames a title maps into its own +// reservations, at more than one address if it likes. Here each allocation +// is a pagefile-backed section, its pages are 64 KiB slices of it, and a +// mapping is a view of consecutive slices in place of a host placeholder. + +const PAGE: usize = 64 << 10; + +struct Section(HANDLE); + +// SAFETY: a section handle may be used from any thread. +unsafe impl Send for Section {} +// SAFETY: as above. +unsafe impl Sync for Section {} + +impl Drop for Section { + fn drop(&mut self) { + // SAFETY: our handle; views keep the section alive on their own. + unsafe { CloseHandle(self.0) }; + } +} + +/// Where a page lives, or what a view starts with: a section and a page +/// index in it. +#[derive(Clone)] +struct Slice { + section: Arc<Section>, + index: usize, +} + +#[derive(Default)] +struct Physical { + next_page: usize, + pages: HashMap<usize, Slice>, + /// Mapped views by address: their length and what they show. + views: BTreeMap<usize, (usize, Slice)>, +} + +static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| { + Mutex::new(Physical { + // Page numbers are opaque to titles; 0 stays unused. + next_page: 0x10_0000, + ..Default::default() + }) +}); + +fn physical() -> MutexGuard<'static, Physical> { + PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `count` is in and out (pages wanted, pages given); all or nothing here. +pub extern "system" fn XMemAllocatePhysicalPages( + flags: u64, + count: *mut usize, + pages: *mut usize, +) -> BOOL { + if count.is_null() || pages.is_null() { + return 0; + } + // SAFETY: checked non-null. + let n = unsafe { *count }; + let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else { + return 0; + }; + // A pagefile-backed section of `size` bytes, its pages committed when + // first mapped or written (`commit`): Grand Theft Auto VI asks for 6.1 + // GiB at once, which a busy host often cannot commit (error 1450). + // SAFETY: plain section creation. + let handle = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_RESERVE, + (size as u64 >> 32) as u32, + size as u32, + std::ptr::null(), + ) + }; + if handle.is_null() { + let error = std::io::Error::last_os_error(); + tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); + // SAFETY: checked non-null. + unsafe { count.write(0) }; + return 0; + } + tracing::debug!( + n, + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages" + ); + let section = Arc::new(Section(handle)); + let mut physical = physical(); + let first = physical.next_page; + physical.next_page += n * FRAMES; + for index in 0..n { + let slice = Slice { + section: section.clone(), + index, + }; + let number = first + index * FRAMES; + physical.pages.insert(number, slice); + // SAFETY: the title passes room for `n` page numbers. + unsafe { pages.add(index).write(number) }; + } + 1 +} + +/// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of +/// 16: Grand Theft Auto VI keeps them as 21-bit `number >> 4` and rebuilds +/// them with `<< 4` (128 GiB of pages at most). +const FRAMES: usize = PAGE >> 12; + +/// Pages still mapped stay readable through their views until unmapped. +pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { + if pages.is_null() { + return 0; + } + let mut physical = physical(); + for i in 0..n { + // SAFETY: the title passes `n` page numbers. + physical.pages.remove(&unsafe { *pages.add(i) }); + } + 1 +} + +/// Copies `data` into physical pages, from `offset` bytes into the first, +/// whether or not they are mapped anywhere (DirectStorage destinations). +/// False if a page is unknown or the host fails. +pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile}; + let mut done = 0; + while done < data.len() { + let (page, within) = ((offset + done) / PAGE, (offset + done) % PAGE); + let Some(slice) = pages + .get(page) + .and_then(|p| physical().pages.get(p).cloned()) + else { + return false; + }; + let at = (slice.index * PAGE) as u64; + // SAFETY: one page of a section we own, mapped for the copy only. + let view = unsafe { + MapViewOfFile( + slice.section.0, + FILE_MAP_WRITE, + (at >> 32) as u32, + at as u32, + PAGE, + ) + }; + if view.Value.is_null() { + return false; + } + if !commit(view.Value as usize, PAGE) { + // SAFETY: our view. + unsafe { UnmapViewOfFile(view) }; + return false; + } + let n = (PAGE - within).min(data.len() - done); + // SAFETY: the view holds `PAGE` bytes; `within + n <= PAGE`. + unsafe { + view.Value + .cast::<u8>() + .add(within) + .copy_from_nonoverlapping(data[done..].as_ptr(), n); + UnmapViewOfFile(view); + } + done += n; + } + true +} + +/// Maps `n` pages at `address`, in place of what is mapped there; null +/// `pages` unmaps. Returns `address`, or null if a page or the host fails. +pub extern "system" fn XMemMapPhysicalPages( + address: *mut c_void, + n: usize, + pages: *const usize, +) -> *mut c_void { + let base = address as usize; + let mut physical = physical(); + unmap(&mut physical, base, n * PAGE); + if pages.is_null() { + return address; + } + // SAFETY: the title passes `n` page numbers. + let pages = unsafe { std::slice::from_raw_parts(pages, n) }; + let mut i = 0; + while i < n { + let Some(first) = physical.pages.get(&pages[i]).cloned() else { + tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); + return std::ptr::null_mut(); + }; + // One view per run of consecutive slices of one section. + let run = 1 + pages[i + 1..] + .iter() + .zip(1..) + .take_while(|&(page, k)| { + physical.pages.get(page).is_some_and(|s| { + Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k + }) + }) + .count(); + if !map(&mut physical, base + i * PAGE, run * PAGE, first) { + return std::ptr::null_mut(); + } + i += run; + } + address +} + +/// One page at each address; null `pages`, or a page number 0, unmaps +/// (Grand Theft Auto VI passes 0 for addresses to clear). +pub extern "system" fn XMemMapPhysicalPagesScatter( + addresses: *const *mut c_void, + n: usize, + pages: *const usize, +) -> BOOL { + if addresses.is_null() { + return 0; + } + for i in 0..n { + // SAFETY: the title passes `n` addresses and, unless null, `n` pages. + let (address, page) = unsafe { + ( + *addresses.add(i), + if pages.is_null() || *pages.add(i) == 0 { + std::ptr::null() + } else { + pages.add(i) + }, + ) + }; + if XMemMapPhysicalPages(address, 1, page).is_null() { + return 0; + } + } + 1 +} + +/// Maps the physical pages shown at `[from, from + len)` at `to` as well, +/// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping +/// copies (`victory_gpu`, queue `CopyPageMappingsBatchX`): Grand Theft Auto +/// VI maps pages into a pool view, then has the GPU map them into its tiled +/// heap. Page by page; false if a source page is not mapped physical memory. +pub fn map_alias(to: u64, from: u64, len: u64) -> bool { + let (to, from, len) = (to as usize, from as usize, len as usize); + let mut physical = physical(); + unmap(&mut physical, to, len); + for k in (0..len).step_by(PAGE) { + if from == 0 { + break; + } + let at = from + k; + let Some(slice) = physical + .views + .range(..=at) + .next_back() + .filter(|(base, (size, _))| at < *base + size) + .map(|(base, (_, s))| Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) + else { + return false; + }; + if !map(&mut physical, to + k, PAGE, slice) { + return false; + } + } + true +} + +/// Maps `slice` and the slices after it over `[base, base + len)`, which +/// must lie in one placeholder. +fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { + // SAFETY: splits the placeholder around the range (failing harmlessly + // when the range is the whole placeholder), then maps the section + // there; both act only on placeholders. + let view = unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + slice.section.0, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + if view.Value as usize != base { + tracing::warn!( + address = format_args!("{base:#x}"), + len, + error = %std::io::Error::last_os_error(), + "mapping physical pages failed (not a placeholder?)" + ); + return false; + } + if !commit(base, len) { + // SAFETY: the view just mapped, back to a placeholder. + unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; + return false; + } + // New contents, read-write: the GPU side's copies no longer guard it. + victory_gpu::title_memory_remapped(base, len); + physical.views.insert(base, (len, slice)); + true +} + +/// Commits the section pages a view shows (once per page, whichever view). +fn commit(base: usize, len: usize) -> bool { + // SAFETY: `[base, base + len)` is a view of a reserved section. + let done = + !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null(); + if !done { + tracing::warn!( + len, + error = %std::io::Error::last_os_error(), + "committing physical pages failed" + ); + } + done +} + +/// Returns `[base, base + len)` to placeholders; views reaching past it +/// are mapped again outside it. +fn unmap(physical: &mut Physical, base: usize, len: usize) { + let end = base + len; + // Views do not overlap: the one holding `base`, then those starting + // inside (the GPU's page mappings make one view per page). + let first = physical + .views + .range(..=base) + .next_back() + .filter(|(at, (size, _))| *at + size > base) + .map(|(at, _)| *at); + let hit: Vec<usize> = first + .into_iter() + .chain(physical.views.range(base + 1..end).map(|(at, _)| *at)) + .collect(); + for at in hit { + let Some((size, slice)) = physical.views.remove(&at) else { + continue; + }; + victory_gpu::title_memory_remapped(at, size); + // SAFETY: a view we mapped; it becomes a placeholder again. + unsafe { + UnmapViewOfFile2( + GetCurrentProcess(), + MEMORY_MAPPED_VIEW_ADDRESS { + Value: at as *mut c_void, + }, + MEM_PRESERVE_PLACEHOLDER, + ) + }; + if at < base { + map(physical, at, base - at, slice.clone()); + } + if at + size > end { + let index = slice.index + (end - at) / PAGE; + map(physical, end, at + size - end, Slice { index, ..slice }); + } + } +} + /// The oldest layout we know; newer titles pass other flag values (Minecraft /// 0x20000001) and read the same leading fields. #[repr(C)] @@ -238,10 +723,11 @@ pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut Workin }; // SAFETY: our own process and a sized structure. unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; + let (gpu_optimal, standard) = victory_gpu::console::current().title_memory(); let stats = WorkingSet { - title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed), + title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed), title_used: counters.PagefileUsage, - gpu_optimal_limit: GPU_OPTIMAL_LIMIT, + gpu_optimal_limit: gpu_optimal, ..Default::default() }; // SAFETY: checked non-null; the title passes room for the structure. @@ -260,10 +746,11 @@ pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { let Some(size) = size.checked_next_multiple_of(2 * MIB) else { return 0; }; + let standard = victory_gpu::console::current().title_memory().1; let moved = kind == TITLE_TO_SYSTEM && TRANSFERRED .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| { - t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT) + t.checked_add(size).filter(|&t| t <= standard) }) .is_ok(); moved.into() @@ -276,6 +763,13 @@ pub(crate) fn module() -> HleModule { exports: vec![ hle_export!(XMemAlloc), hle_export!(XMemFree), + hle_export!(XMemAllocDefault), + hle_export!(XMemFreeDefault), + hle_export!(XMemIsToolsMemAvailable), + hle_export!(XMemAllocatePhysicalPages), + hle_export!(XMemFreePhysicalPages), + hle_export!(XMemMapPhysicalPages), + hle_export!(XMemMapPhysicalPagesScatter), hle_export!(XMemVirtualAlloc), hle_export!(XMemVirtualQuery), hle_export!(XMemGetWorkingSetStatistics), @@ -330,9 +824,36 @@ mod tests { assert_eq!(info.host.State, MEM_COMMIT); assert_eq!(info.host.Protect, PAGE_READWRITE); assert_eq!(info.flags & GRAPHICS, GRAPHICS); + // Write-watched, for the GPU side's copies. + let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0); + // SAFETY: room for `count` addresses. + let watched = unsafe { + windows_sys::Win32::System::Memory::GetWriteWatch( + 0, + p, + 4 * MIB, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + }; + assert_eq!(watched, 0); // SAFETY: our own reservation. assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); assert_eq!(query(p).flags, 0); + // No address field: above the 32-bit range and below 2^40, where + // the console keeps it. + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 16 << 30, + MEM_RESERVE, + GRAPHICS, + PAGE_NOACCESS, + ); + assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}"); + assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}"); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); } #[test] @@ -342,7 +863,8 @@ mod tests { assert!(before.title_used > 0); assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); - assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget"); + let standard = victory_gpu::console::current().title_memory().1; + assert_eq!(XMemTransferMemory(0, standard), 0, "over budget"); let mut after = WorkingSet::default(); XMemGetWorkingSetStatistics(0x2000_0001, &mut after); assert_eq!(before.title_limit - after.title_limit, 128 * MIB); @@ -354,4 +876,81 @@ mod tests { assert_eq!(size_of::<BasicInformation>(), 0x40); assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28); } + + #[test] + fn physical_pages_map_alias_and_unmap() { + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + assert_eq!(n, 3); + // Packed into 21 bits as `number >> 4`, as the title keeps them. + for p in pages { + assert_eq!((p >> 4 & 0x1f_ffff) << 4, p); + } + // Reservations of 64 KiB pages, as titles make them for mapping. + let reserve = || { + XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ) + }; + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + + // The same page at a second address shows the same bytes. + assert_eq!( + XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()), + at(b, 1) + ); + // SAFETY: both pages are mapped read-write. + unsafe { + at(a, 2).cast::<u8>().write(7); + assert_eq!(at(b, 1).cast::<u8>().read(), 7); + a.cast::<u8>().write(1); + } + // Writes into pages (DirectStorage's) show through their views. + assert!(write_physical(&pages[2..], 1, &[9])); + // SAFETY: mapped read-write. + assert_eq!(unsafe { at(b, 1).cast::<u8>().add(1).read() }, 9); + + // Unmapping the middle page keeps its neighbours. + assert_eq!( + XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()), + at(a, 1) + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { at(a, 2).cast::<u8>().read() }, 7); + + // A scattered page lands in the hole. + let addresses = [at(a, 1)]; + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()), + 1 + ); + // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`. + assert_eq!(unsafe { at(a, 1).cast::<u8>().read() }, 1); + // Page number 0 unmaps. + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()), + 1 + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`. + assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64)); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::<u8>().read() }, 7); + assert!(map_alias(b as u64, 0, PAGE as u64)); + assert_eq!(query(b).host.State, MEM_RESERVE); + assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64)); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + assert_eq!(XMemIsToolsMemAvailable(), 0); + } } diff --git a/crates/victory-hle/src/modules/xnetworking.rs b/crates/victory-hle/src/modules/xnetworking.rs new file mode 100644 index 0000000..8670ff2 --- /dev/null +++ b/crates/victory-hle/src/modules/xnetworking.rs @@ -0,0 +1,210 @@ +//! XNetworking as an offline console answers it: the network stack is up +//! (titles wait for that before anything else) but reaches nothing, the +//! connectivity hint never changes, and the title's security allow list, +//! which comes from the service, cannot be fetched. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token, +}; + +pub const PROVIDER: Guid = Guid::new( + 0x37e5_6907, + 0x2f10, + 0x41e8, + [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], +); + +/// As Grand Theft Auto VI (2026) asks for it; the slots it calls (0x18-0x88) +/// take the same arguments as under the provider's own id (older titles). +pub const IID_2026: Guid = Guid::new( + 0xbf23_46b2, + 0x39af, + 0x4658, + [0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3], +); + +pub static OBJECT: Object = Object::new("networking", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +/// `HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)`: what needs the service. +pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32; + +/// The documented default for the preferred local UDP multiplayer port. +const UDP_PORT: u16 = 3074; + +/// The connectivity hint: level, cost, interface type, then four flags. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConnectivityHint { + pub level: u32, + pub cost: u32, + pub interface_type: u32, + pub initialized: bool, + pub approaching_data_limit: bool, + pub over_data_limit: bool, + pub roaming: bool, +} + +/// Initialized, no connectivity (level 1), cost unknown (0). +const OFFLINE: ConnectivityHint = ConnectivityHint { + level: 1, + cost: 0, + interface_type: 0, + initialized: true, + approaching_data_limit: false, + over_data_limit: false, + roaming: false, +}; + +type This = *const Object; + +extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT { + put(out, UDP_PORT) +} + +/// Tells our port queries apart from other calls on the same block. +static PORT: u8 = 0; + +extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT))) +} +extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT { + xasync::result(block, (&raw const PORT).cast(), out) +} + +static SECURITY: u8 = 0; + +/// The allow list comes from the service: unreachable offline. +extern "system" fn security_info_async( + _: This, + url: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + url = text(url).unwrap_or_default(), + "security information: offline" + ); + xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE) +} +extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn security_info_result( + _: This, + block: *mut AsyncBlock, + size: usize, + used: *mut usize, + buffer: *mut u8, + _info: *mut *const c_void, +) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const SECURITY).cast(), + size, + buffer.cast(), + used, + ) +} + +/// No security information can exist offline, so no certificate passes. +extern "system" fn verify_certificate( + _: This, + _request: *mut c_void, + _info: *const c_void, +) -> HRESULT { + UNREACHABLE +} + +extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT { + put(out, OFFLINE) +} + +/// The hint never changes offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<18> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + udp_port as *const (), // 0x18 + udp_port_async as *const (), // 0x20 + udp_port_result as *const (), // 0x28 + missing::<6> as *const (), // 0x30 port changed + missing::<7> as *const (), // 0x38 + security_info_async as *const (), // 0x40 + security_info_size as *const (), // 0x48 + security_info_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 the same for UTF-16 URLs + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + verify_certificate as *const (), // 0x70 + connectivity_hint as *const (), // 0x78 + register as *const (), // 0x80 hint changed (never) + unregister as *const (), // 0x88 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn offline_but_initialized() { + let this: This = &OBJECT; + type Hint = extern "system" fn(This, *mut ConnectivityHint) -> HRESULT; + let mut hint = OFFLINE; + hint.initialized = false; + assert_eq!(method::<Hint>(&OBJECT, 0x78)(this, &mut hint), S_OK); + assert!(hint.initialized && hint.level == 1); + assert_eq!(size_of::<ConnectivityHint>(), 16); + + type Begin = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + type Port = extern "system" fn(This, *mut AsyncBlock, *mut u16) -> HRESULT; + let mut b = block(); + assert_eq!(method::<Begin>(&OBJECT, 0x20)(this, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut port = 0; + assert_eq!(method::<Port>(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK); + assert_eq!(port, 3074); + + type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT; + let mut b = block(); + let url = c"https://example.invalid/"; + assert_eq!( + method::<Url>(&OBJECT, 0x40)(this, url.as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE); + let mut size = 0; + assert_eq!( + method::<Size>(&OBJECT, 0x48)(this, &mut b, &mut size), + UNREACHABLE + ); + } +} diff --git a/crates/victory-hle/src/modules/xpackage.rs b/crates/victory-hle/src/modules/xpackage.rs new file mode 100644 index 0000000..4f03635 --- /dev/null +++ b/crates/victory-hle/src/modules/xpackage.rs @@ -0,0 +1,371 @@ +//! XPackage: the title's own installation, complete and launchable, with +//! every chunk ready; no other package (content, add-ons) is installed. +//! The package is the folder of the title's executable (`G:` to the title). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; +use std::path::Path; +use std::sync::OnceLock; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xaf40_6016, + 0xe850, + 0x4aa8, + [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], +); + +/// As Grand Theft Auto VI (2026) asks for it. Its slots up to 0xd0 take the +/// arguments the public API lists in the same order; 0x110 uninstalls a +/// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages. +pub const IID_2026: Guid = Guid::new( + 0x0b9d_556e, + 0xab70, + 0x43f4, + [0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40], +); + +pub static OBJECT: Object = Object::new("package", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +/// The documented "could not resolve an identifier for the package". +pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32; + +/// Our installation's identifier: the title id in hex (titles keep it in 33 +/// bytes and hand it back to us). +pub fn identifier() -> String { + format!("{:08X}", runtime::title().id) +} + +fn is_ours(id: *const c_char) -> bool { + text(id).is_some_and(|id| id == identifier()) +} + +/// Bytes in the package folder, counted once. +fn package_bytes() -> u64 { + fn size(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => size(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() + } + static BYTES: OnceLock<u64> = OnceLock::new(); + *BYTES.get_or_init(|| { + let exe = runtime::main_image().and_then(runtime::image_path); + exe.as_deref().and_then(Path::parent).map_or(0, size) + }) +} + +type This = *const Object; + +extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT { + put_string(&identifier(), size, buffer, std::ptr::null_mut()) +} + +extern "system" fn is_packaged(_: This) -> bool { + true +} + +/// Installation monitors all watch the same finished installation, so the +/// handle is a fixed address. +static MONITOR: u8 = 0; +fn monitor() -> *const c_void { + (&raw const MONITOR).cast() +} + +extern "system" fn create_monitor( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _queue: *const c_void, + out: *mut *const c_void, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, monitor()) +} +extern "system" fn close_monitor(_: This, _: *const c_void) {} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Progress { + pub total_bytes: u64, + pub installed_bytes: u64, + pub launch_bytes: u64, + pub launchable: bool, + pub completed: bool, +} + +extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) { + let bytes = package_bytes(); + put( + out, + Progress { + total_bytes: bytes, + installed_bytes: bytes, + launch_bytes: bytes, + launchable: true, + completed: true, + }, + ); +} + +/// The installation is complete, so progress never changes. +extern "system" fn register_progress( + _: This, + _monitor: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} + +/// 0: ready. +// shortcut: every selector counts as installed, including ones the +// package's layout does not have (the console answers those with an +// invalid-selector error); Grand Theft Auto VI asks only about its own +// chunks, which a full install has. +extern "system" fn find_availability( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + out: *mut u32, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, 0) +} + +extern "system" fn change_order( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +static INSTALL: u8 = 0; + +/// Everything is installed: done at once, the result is a monitor. +extern "system" fn install_chunks_async( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _suppress_confirmation: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let result = if is_ours(id) { + Ok(xasync::bytes(monitor())) + } else { + Err(NO_PACKAGE) + }; + xasync::finished_with(block, (&raw const INSTALL).cast(), result) +} +extern "system" fn install_chunks_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const INSTALL).cast(), out) +} + +/// Nothing to download. +extern "system" fn estimate_download( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + bytes: *mut u64, + confirm: *mut bool, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + if !confirm.is_null() { + // SAFETY: checked non-null. + unsafe { confirm.write(false) }; + } + put(bytes, 0) +} + +// shortcut: accepted but nothing is removed (the package folder is the +// user's), so the chunks stay ready; Grand Theft Auto VI's one call site +// (title+0x293b4b0, its chunk manager) would then see them still installed. +extern "system" fn uninstall_chunks( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +/// Mount handles only come from mounting another package, and there is +/// none. +extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT { + xasync::E_INVALIDARG +} +extern "system" fn close_mount(_: This, _: *const c_void) {} + +/// Only other packages are uninstalled this way, and none is installed. +extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool { + tracing::info!( + id = text(id).unwrap_or_default(), + "package uninstall refused" + ); + false +} + +static MOUNT: u8 = 0; + +extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT { + tracing::info!( + id = text(id).unwrap_or_default(), + "package mount: not installed" + ); + xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE) +} +extern "system" fn mount_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const MOUNT).cast(), out) +} + +/// Titles enumerate content packages (kind 1); there are none. +// shortcut: the game kind (0) also lists nothing, not this installation; +// Grand Theft Auto VI enumerates only content (kind 1, title+0x2937bf0). +extern "system" fn enumerate( + _: This, + kind: u32, + _scope: u32, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + tracing::debug!(kind, "packages enumerated: none"); + S_OK +} + +static VTABLE: Methods<40> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + current_identifier as *const (), // 0x18 + is_packaged as *const (), // 0x20 + create_monitor as *const (), // 0x28 + close_monitor as *const (), // 0x30 + progress as *const (), // 0x38 + missing::<8> as *const (), // 0x40 update a monitor + register_progress as *const (), // 0x48 + missing::<10> as *const (), // 0x50 unregister it + missing::<11> as *const (), // 0x58 user locale + find_availability as *const (), // 0x60 + missing::<13> as *const (), // 0x68 enumerate chunk availability + change_order as *const (), // 0x70 + missing::<15> as *const (), // 0x78 install chunks + install_chunks_async as *const (), // 0x80 + install_chunks_result as *const (), // 0x88 + estimate_download as *const (), // 0x90 + uninstall_chunks as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + missing::<21> as *const (), // 0xa8 + missing::<22> as *const (), // 0xb0 + missing::<23> as *const (), // 0xb8 mount (deprecated) + missing::<24> as *const (), // 0xc0 mount path size + mount_path as *const (), // 0xc8 + close_mount as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 + missing::<28> as *const (), // 0xe0 enumerate packages (older) + missing::<29> as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + missing::<33> as *const (), // 0x108 + uninstall_package as *const (), // 0x110 + missing::<35> as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + mount_async as *const (), // 0x128 + mount_result as *const (), // 0x130 + enumerate as *const (), // 0x138 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn the_installation_is_complete_and_alone() { + let this: This = &OBJECT; + type Id = extern "system" fn(This, usize, *mut u8) -> HRESULT; + let mut id = [0u8; 33]; + assert_eq!(method::<Id>(&OBJECT, 0x18)(this, 33, id.as_mut_ptr()), S_OK); + let len = id.iter().position(|&b| b == 0).unwrap(); + assert_eq!(std::str::from_utf8(&id[..len]).unwrap(), identifier()); + assert!(method::<extern "system" fn(This) -> bool>(&OBJECT, 0x20)( + this + )); + + type Find = + extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT; + let mut availability = 9; + let ours = format!("{}\0", identifier()); + let find = method::<Find>(&OBJECT, 0x60); + let none = std::ptr::null(); + assert_eq!( + find(this, ours.as_ptr().cast(), 0, none, &mut availability), + S_OK + ); + assert_eq!(availability, 0, "ready"); + assert_eq!( + find(this, c"dlc".as_ptr(), 0, none, &mut availability), + NO_PACKAGE + ); + + type Progress_ = extern "system" fn(This, *const c_void, *mut Progress); + let mut p = Progress { + total_bytes: 1, + installed_bytes: 0, + launch_bytes: 0, + launchable: false, + completed: false, + }; + method::<Progress_>(&OBJECT, 0x38)(this, monitor(), &mut p); + assert!(p.completed && p.launchable && p.installed_bytes == p.total_bytes); + + type Mount = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + method::<Mount>(&OBJECT, 0x128)(this, c"dlc".as_ptr(), &mut block), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), NO_PACKAGE); + } +} diff --git a/crates/victory-hle/src/modules/xstore.rs b/crates/victory-hle/src/modules/xstore.rs new file mode 100644 index 0000000..3e29422 --- /dev/null +++ b/crates/victory-hle/src/modules/xstore.rs @@ -0,0 +1,479 @@ +//! XStore as an offline console answers it: the game's own licence is +//! local and active (a full, owned game); the user owns no add-ons; what +//! needs the store service (catalog, consumables, purchase and update +//! pages, collection ids, update checks) fails with the documented store +//! network error. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use super::xpackage; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x0dd1_12ac, + 0x7c24, + 0x448c, + [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], +); +/// As Grand Theft Auto VI (2026) asks for it; every slot it calls takes +/// the public API's arguments in the 2020 order. +pub const IID_2026: Guid = Guid::new( + 0xb09d_803c, + 0x2414, + 0x4a05, + [0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44], +); +/// The same table extended by durables licensing (0x238, 0x240). +pub const DURABLES_IID: Guid = Guid::new( + 0x2d42_fea5, + 0xe71d, + 0x4b76, + [0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d], +); + +pub static OBJECT: Object = Object::new("store", &VTABLE); +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID_2026, &OBJECT), + (PROVIDER, DURABLES_IID, &OBJECT), +]; + +/// The documented "failed to communicate with the store network". +pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32; + +type This = *const Object; +type Handle = *const c_void; + +/// Contexts and product queries hold nothing (queries are always empty), +/// so their handles are fixed addresses. A licence handle says whether it +/// is valid by which address it is. +static CONTEXT: u8 = 0; +static QUERY: u8 = 0; +static VALID: u8 = 0; +static INVALID: u8 = 0; +fn handle(of: &'static u8) -> Handle { + (of as *const u8).cast() +} + +/// Identifies our calls on a block: one per result shape. +static FAILED: u8 = 0; +static QUERY_CALL: u8 = 0; +static LICENSE_CALL: u8 = 0; +static GAME_LICENSE: u8 = 0; + +fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT { + tracing::info!(what, "store call: offline"); + xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR) +} +/// The result functions of calls that failed: their status. +extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT { + put(out, handle(&CONTEXT)) +} +extern "system" fn close(_: This, _: Handle) {} + +extern "system" fn associated_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "associated products") +} + +/// The user owns no add-ons: an empty query. +extern "system" fn entitled_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished_with( + block, + (&raw const QUERY_CALL).cast(), + Ok(xasync::bytes(handle(&QUERY))), + ) +} +extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const QUERY_CALL).cast(), out) +} +/// Empty, so the callback never runs. +extern "system" fn enumerate_products( + _: This, + _: Handle, + _: *mut c_void, + _: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn has_more_pages(_: This, _: Handle) -> bool { + false +} +/// There is no next page to ask for. +extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL) +} + +fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT { + let license = handle(if owned { &VALID } else { &INVALID }); + xasync::finished_with( + block, + (&raw const LICENSE_CALL).cast(), + Ok(xasync::bytes(license)), + ) +} +/// Only the game's own package is installed, so only its licence is valid. +extern "system" fn license_for_package_async( + _: This, + _: Handle, + package: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let ours = text(package).is_some_and(|p| p == xpackage::identifier()); + license_for(ours, block) +} +/// The user owns no durables: their licences are not valid. +extern "system" fn license_for_durables_async( + _: This, + _: Handle, + store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + store_id = text(store_id).unwrap_or_default(), + "durable not owned" + ); + license_for(false, block) +} +extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const LICENSE_CALL).cast(), out) +} +extern "system" fn is_license_valid(_: This, license: Handle) -> bool { + license == handle(&VALID) +} + +/// The game licence, as the public API lays it out. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct GameLicense { + pub sku_store_id: [u8; 18], + pub is_active: bool, + pub is_trial_owned_by_this_user: bool, + pub is_disc_license: bool, + pub is_trial: bool, + pub trial_seconds_remaining: u32, + pub trial_unique_id: [u8; 64], + pub expiration: i64, +} + +/// A full, active licence for the game's SKU (`<store id>/0010`, the +/// store's first SKU), not a trial, without expiry. +fn game_license() -> GameLicense { + let mut sku = [0u8; 18]; + let id = format!("{}/0010", runtime::title().store_id); + let len = id.len().min(sku.len() - 1); + sku[..len].copy_from_slice(&id.as_bytes()[..len]); + GameLicense { + sku_store_id: sku, + is_active: true, + is_trial_owned_by_this_user: false, + is_disc_license: false, + is_trial: false, + trial_seconds_remaining: 0, + trial_unique_id: [0; 64], + expiration: 0, + } +} + +extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + let license = xasync::bytes(game_license()); + xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license)) +} +extern "system" fn game_license_result( + _: This, + block: *mut AsyncBlock, + out: *mut GameLicense, +) -> HRESULT { + xasync::result(block, (&raw const GAME_LICENSE).cast(), out) +} + +extern "system" fn consumable_balance_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable balance") +} +extern "system" fn report_fulfillment_async( + _: This, + _: Handle, + _store_id: *const c_char, + _quantity: u32, + _tracking_id: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable fulfillment") +} +/// Collections and purchase ids alike. +extern "system" fn user_id_async( + _: This, + _: Handle, + _ticket: *const c_char, + _publisher_user_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "user store id") +} +extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn string_status( + _: This, + block: *mut AsyncBlock, + _: usize, + _: *mut c_char, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn array_status( + _: This, + block: *mut AsyncBlock, + _: u32, + _: *mut c_void, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn purchase_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + _name: *const c_char, + _json: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "purchase page") +} +extern "system" fn product_page_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "product page") +} +extern "system" fn redeem_ui_async( + _: This, + _: Handle, + _token: *const c_char, + _allowed: *const *const c_char, + _allowed_count: usize, + _disallow_csv: bool, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "redeem page") +} +extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + offline(block, "update check") +} +/// Installing updates or packages by id alike. +extern "system" fn install_async( + _: This, + _: Handle, + _ids: *const *const c_char, + _count: usize, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "package download") +} + +/// The game's own store id maps to its installation; nothing else is +/// installed. +extern "system" fn package_identifier( + _: This, + store_id: *const c_char, + size: usize, + buffer: *mut u8, +) -> HRESULT { + let title = runtime::title(); + match text(store_id) { + Some(id) if !title.store_id.is_empty() && id == title.store_id => { + put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut()) + } + _ => xpackage::NO_PACKAGE, + } +} + +/// Licences never change offline, so these callbacks never run. +extern "system" fn register( + _: This, + _: Handle, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<76> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + create_context as *const (), // 0x18 + close as *const (), // 0x20 + associated_products_async as *const (), // 0x28 + query_result as *const (), // 0x30 + missing::<7> as *const (), // 0x38 products by id + missing::<8> as *const (), // 0x40 + entitled_products_async as *const (), // 0x48 + query_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 product for the game + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 product for a package + missing::<14> as *const (), // 0x70 + enumerate_products as *const (), // 0x78 + has_more_pages as *const (), // 0x80 + next_page_async as *const (), // 0x88 + query_result as *const (), // 0x90 + close as *const (), // 0x98 a product query + license_for_package_async as *const (), // 0xa0 + license_result as *const (), // 0xa8 + is_license_valid as *const (), // 0xb0 + close as *const (), // 0xb8 a licence + missing::<24> as *const (), // 0xc0 can acquire for store id + missing::<25> as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 can acquire for package + missing::<27> as *const (), // 0xd8 + game_license_async as *const (), // 0xe0 + game_license_result as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 add-on licences + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + consumable_balance_async as *const (), // 0x108 + status as *const (), // 0x110 + report_fulfillment_async as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + user_id_async as *const (), // 0x128 collections id + size_status as *const (), // 0x130 + string_status as *const (), // 0x138 + user_id_async as *const (), // 0x140 purchase id + size_status as *const (), // 0x148 + string_status as *const (), // 0x150 + missing::<43> as *const (), // 0x158 licence token + missing::<44> as *const (), // 0x160 + missing::<45> as *const (), // 0x168 + missing::<46> as *const (), // 0x170 + missing::<47> as *const (), // 0x178 + missing::<48> as *const (), // 0x180 + purchase_ui_async as *const (), // 0x188 + missing::<50> as *const (), // 0x190 + missing::<51> as *const (), // 0x198 rate and review + missing::<52> as *const (), // 0x1a0 + redeem_ui_async as *const (), // 0x1a8 + missing::<54> as *const (), // 0x1b0 + updates_async as *const (), // 0x1b8 + count_status as *const (), // 0x1c0 + array_status as *const (), // 0x1c8 + missing::<58> as *const (), // 0x1d0 download updates + missing::<59> as *const (), // 0x1d8 + install_async as *const (), // 0x1e0 updates + status as *const (), // 0x1e8 + install_async as *const (), // 0x1f0 packages by store id + count_status as *const (), // 0x1f8 + array_status as *const (), // 0x200 + package_identifier as *const (), // 0x208 + register as *const (), // 0x210 game licence changed + unregister as *const (), // 0x218 + register as *const (), // 0x220 package licence lost + unregister as *const (), // 0x228 + missing::<70> as *const (), // 0x230 + license_for_durables_async as *const (), // 0x238 + license_result as *const (), // 0x240 + missing::<73> as *const (), // 0x248 associated products page + missing::<74> as *const (), // 0x250 + product_page_ui_async as *const (), // 0x258 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn the_game_is_licensed_and_the_store_is_offline() { + let this: This = &OBJECT; + assert_eq!(size_of::<GameLicense>(), 104); + type Begin = extern "system" fn(This, Handle, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock, *mut GameLicense) -> HRESULT; + let mut b = block(); + assert_eq!( + method::<Begin>(&OBJECT, 0xe0)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut license = std::mem::MaybeUninit::<GameLicense>::zeroed(); + assert_eq!( + method::<Result>(&OBJECT, 0xe8)(this, &mut b, license.as_mut_ptr()), + S_OK + ); + // SAFETY: written by the call. + let license = unsafe { license.assume_init() }; + assert!(license.is_active && !license.is_trial); + + let mut b = block(); + assert_eq!( + method::<Begin>(&OBJECT, 0x1b8)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + type Count = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + assert_eq!( + method::<Count>(&OBJECT, 0x1c0)(this, &mut b, &mut 0), + NETWORK_ERROR + ); + + type Durable = extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT; + type License = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + let mut b = block(); + let durable = method::<Durable>(&OBJECT, 0x238); + assert_eq!( + durable(this, handle(&CONTEXT), c"9XYZ".as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut l = std::ptr::null(); + assert_eq!( + method::<License>(&OBJECT, 0x240)(this, &mut b, &mut l), + S_OK + ); + assert!(!method::<extern "system" fn(This, Handle) -> bool>( + &OBJECT, 0xb0 + )(this, l)); + } +} diff --git a/crates/victory-hle/src/modules/xsystem.rs b/crates/victory-hle/src/modules/xsystem.rs index e6bc740..a3a1d62 100644 --- a/crates/victory-hle/src/modules/xsystem.rs +++ b/crates/victory-hle/src/modules/xsystem.rs @@ -1,5 +1,6 @@ //! XSystem: the console's identity and sandbox, and how analytics describe -//! the device. Fixed values: one offline retail Xbox Series X. +//! the device. Fixed values: one offline retail console, the model the user +//! chose ([`victory_gpu::console`]). #![allow(clippy::not_unsafe_ptr_arg_deref)] use super::xgameruntime::{ @@ -40,8 +41,18 @@ const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; pub static OBJECT: Object = Object::new("system", &VTABLE); pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); +/// The interface as Grand Theft Auto VI (2026) asks for it; it calls the +/// same three slots (0x18, 0x20, 0x28) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x1861_cf2e, + 0xe18b, + 0x4834, + [0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf], +); + pub const INTERFACES: &[Interface] = &[ (PROVIDER, IID, &OBJECT), + (PROVIDER, IID_2026, &OBJECT), (ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT), ]; @@ -96,7 +107,7 @@ extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut Anal os: OS, hosting_os: OS, family: text("Xbox"), - form: text("Xbox Series X"), + form: text(victory_gpu::console::current().name()), }; // SAFETY: the caller passes room for the struct. unsafe { out.write(info) }; @@ -119,6 +130,241 @@ static ANALYTICS_VTABLE: Methods<4> = Methods([ analytics_info as *const (), // 0x18 ]); +/// The device type is not a runtime call: code linked into the title reads +/// `ConsoleMode` from this key (`RegOpenKeyW`, `RegQueryValueExW`) and +/// takes a missing value for a PC. +#[cfg(windows)] +mod device_type { + #![allow(non_snake_case)] + + use std::ffi::c_void; + + use victory_gpu::console::{self, Console}; + + use crate::modules::files::host; + use crate::{HleModule, hle_export}; + + type Key = *mut c_void; + const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key; + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM"; + const VALUE: &str = "ConsoleMode"; + const SUCCESS: u32 = 0; + const FILE_NOT_FOUND: u32 = 2; + const INVALID_PARAMETER: u32 = 87; + const MORE_DATA: u32 = 234; + const DWORD: u32 = 4; + + /// Stands for the key; never a host handle value. + static OEM: u8 = 0; + fn oem() -> Key { + (&raw const OEM).cast_mut().cast() + } + + /// What the title's code maps to each model's device type. + pub(super) fn console_mode(console: Console) -> u32 { + match console { + Console::SeriesX => 0x64, + Console::SeriesS => 0x60, + } + } + + fn is(text: *const u16, expected: &str) -> bool { + if text.is_null() { + return false; + } + // SAFETY: the title passes a NUL-terminated string. + let text = unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }; + text.eq_ignore_ascii_case(expected) + } + + /// Opens our key for its path; the key has no subkeys. `None`: not + /// ours, ask the host. + fn open(root: Key, sub: *const u16, out: *mut Key) -> Option<u32> { + if root == oem() { + return Some(FILE_NOT_FOUND); + } + if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { + // SAFETY: checked non-null; the title passes room for a key. + unsafe { out.write(oem()) }; + return Some(SUCCESS); + } + None + } + + // Our titles import only these registry functions (and `RegOpenKeyExW` + // below), so no other call can reach the host with our key. + pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)( + root, sub, out, + ) + }) + } + + pub extern "system" fn RegOpenKeyExW( + root: Key, + sub: *const u16, + options: u32, + access: u32, + out: *mut Key, + ) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn( + Key, *const u16, u32, u32, *mut Key, + ) -> u32)(root, sub, options, access, out) + }) + } + + pub extern "system" fn RegQueryValueExW( + key: Key, + name: *const u16, + reserved: *mut u32, + kind: *mut u32, + data: *mut u8, + size: *mut u32, + ) -> u32 { + if key != oem() { + return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn( + Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32, + ) -> u32)(key, name, reserved, kind, data, size); + } + if !is(name, VALUE) { + return FILE_NOT_FOUND; + } + if !data.is_null() && size.is_null() { + return INVALID_PARAMETER; + } + // SAFETY: the title passes valid or null pointers, sized by `size`. + unsafe { + if !kind.is_null() { + kind.write(DWORD); + } + if size.is_null() { + return SUCCESS; + } + let room = size.read(); + size.write(4); + if data.is_null() { + return SUCCESS; + } + if room < 4 { + return MORE_DATA; + } + data.cast::<u32>() + .write_unaligned(console_mode(console::current())); + } + tracing::debug!(console = console::current().name(), "device type read"); + SUCCESS + } + + pub extern "system" fn RegCloseKey(key: Key) -> u32 { + if key == oem() { + return SUCCESS; + } + host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key) + } + + pub(crate) fn module() -> HleModule { + HleModule { + name: "device type", + dlls: &["advapi32.dll", "api-ms-win-core-registry-*"], + exports: vec![ + hle_export!(RegOpenKeyW), + hle_export!(RegOpenKeyExW), + hle_export!(RegQueryValueExW), + hle_export!(RegCloseKey), + ], + } + } + + #[cfg(test)] + mod tests { + use super::*; + + fn w(s: &str) -> Vec<u16> { + s.encode_utf16().chain([0]).collect() + } + + #[test] + fn titles_read_the_chosen_model() { + assert_eq!(console_mode(Console::SeriesX), 0x64); + assert_eq!(console_mode(Console::SeriesS), 0x60); + let mut key = std::ptr::null_mut(); + let path = w(&KEY.to_ascii_lowercase()); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + let (mut kind, mut value, mut size) = (0, 0u32, 4); + let name = w(VALUE); + let query = |data: *mut u32, size: *mut u32, kind: *mut u32| { + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + kind, + data.cast(), + size, + ) + }; + assert_eq!(query(&mut value, &mut size, &mut kind), SUCCESS); + assert_eq!((kind, size), (DWORD, 4)); + assert_eq!(value, console_mode(console::current())); + let mut small = 2; + assert_eq!(query(&mut value, &mut small, &mut kind), MORE_DATA); + assert_eq!(small, 4); + let other = w("Other"); + assert_eq!( + RegQueryValueExW( + key, + other.as_ptr(), + std::ptr::null_mut(), + &mut kind, + std::ptr::null_mut(), + &mut size + ), + FILE_NOT_FOUND + ); + let mut sub = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(key, other.as_ptr(), 0, 1, &mut sub), + FILE_NOT_FOUND + ); + assert_eq!(RegCloseKey(key), SUCCESS); + let mut again = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(LOCAL_MACHINE, path.as_ptr(), 0, 1, &mut again), + SUCCESS + ); + assert_eq!(again, oem()); + } + + #[test] + fn other_keys_reach_the_host() { + let mut key = std::ptr::null_mut(); + let path = w(r"Software\Microsoft\Windows NT\CurrentVersion"); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + assert_ne!(key, oem()); + let (mut size, name) = (0, w("ProductName")); + assert_eq!( + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut size + ), + SUCCESS + ); + assert!(size > 0); + assert_eq!(RegCloseKey(key), SUCCESS); + } + } +} +#[cfg(windows)] +pub(crate) use device_type::module; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/victory-hle/src/modules/xuser.rs b/crates/victory-hle/src/modules/xuser.rs index 18bfc35..33c05d6 100644 --- a/crates/victory-hle/src/modules/xuser.rs +++ b/crates/victory-hle/src/modules/xuser.rs @@ -4,11 +4,11 @@ //! input device is associated with the user (there are none, `gameinput`). #![allow(clippy::not_unsafe_ptr_arg_deref)] -use std::ffi::c_void; +use std::ffi::{c_char, c_void}; use super::xasync::{self, AsyncBlock, ProviderData}; use super::xgameruntime::{ - Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, token, + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, }; /// The user provider. @@ -81,6 +81,9 @@ pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); pub const INTERFACES: &[Interface] = &[ (PROVIDER, IID, &OBJECT), + // Grand Theft Auto VI (2026) asks with the provider's id; its thunks call + // the same slots with the same arguments (0x108/0x110 change events). + (PROVIDER, PROVIDER, &OBJECT), (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), (DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT), ]; @@ -178,6 +181,65 @@ extern "system" fn check_privilege( put(has, true) } +/// 3: adult. +extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 3) +} + +static RESOLVE: u8 = 0; +static TOKEN: u8 = 0; + +/// Every privilege is granted, so there is nothing to resolve. +extern "system" fn resolve_privilege_async( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished(block, (&raw const RESOLVE).cast(), S_OK) +} +extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast()) +} + +/// The documented "failed to get token": tokens come from the service. +pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32; + +#[allow(clippy::too_many_arguments)] +extern "system" fn token_async( + _: This, + _: Handle, + _options: u32, + _method: *const c_char, + url: *const c_char, + _header_count: usize, + _headers: *const c_void, + _body_size: usize, + _body: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::info!( + url = text(url).unwrap_or_default(), + "token and signature: offline" + ); + xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN) +} +extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn token_result( + _: This, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + _data: *mut *const c_void, + used: *mut usize, +) -> HRESULT { + xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used) +} + /// The user never changes and no device is ever associated, so these /// callbacks are never called. extern "system" fn register( @@ -198,43 +260,44 @@ extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Hand USER_NOT_FOUND } -// Unset slots: gamer pictures, token and signature, issue resolution. +// Unset slots (no title seen calls them): maximum users, gamer pictures, +// the UTF-16 token calls, issue resolution. static VTABLE: Methods<35> = Methods([ - missing::<0> as *const (), // 0x00 QueryInterface - add_ref as *const (), // 0x08 AddRef - add_ref as *const (), // 0x10 Release: the object is static - duplicate as *const (), // 0x18 - close as *const (), // 0x20 - compare as *const (), // 0x28 - missing::<6> as *const (), // 0x30 maximum users - add_async as *const (), // 0x38 - add_result as *const (), // 0x40 - get_local_id as *const (), // 0x48 - find_by_local_id as *const (), // 0x50 - get_id as *const (), // 0x58 - find_by_id as *const (), // 0x60 - get_is_guest as *const (), // 0x68 - get_state as *const (), // 0x70 - get_gamertag as *const (), // 0x78 older gamertag slot - missing::<16> as *const (), // 0x80 gamer picture: begin - missing::<17> as *const (), // 0x88 result size - missing::<18> as *const (), // 0x90 result - missing::<19> as *const (), // 0x98 age group - check_privilege as *const (), // 0xa0 - missing::<21> as *const (), // 0xa8 resolve privilege with UI: begin - missing::<22> as *const (), // 0xb0 result - missing::<23> as *const (), // 0xb8 token and signature: begin - missing::<24> as *const (), // 0xc0 result size - missing::<25> as *const (), // 0xc8 result - missing::<26> as *const (), // 0xd0 the same, UTF-16: begin - missing::<27> as *const (), // 0xd8 result size - missing::<28> as *const (), // 0xe0 result - missing::<29> as *const (), // 0xe8 resolve issue with UI: begin - missing::<30> as *const (), // 0xf0 result - missing::<31> as *const (), // 0xf8 the same, UTF-16: begin - missing::<32> as *const (), // 0x100 result - register as *const (), // 0x108 change event - unregister as *const (), // 0x110 + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + duplicate as *const (), // 0x18 + close as *const (), // 0x20 + compare as *const (), // 0x28 + missing::<6> as *const (), // 0x30 maximum users + add_async as *const (), // 0x38 + add_result as *const (), // 0x40 + get_local_id as *const (), // 0x48 + find_by_local_id as *const (), // 0x50 + get_id as *const (), // 0x58 + find_by_id as *const (), // 0x60 + get_is_guest as *const (), // 0x68 + get_state as *const (), // 0x70 + get_gamertag as *const (), // 0x78 older gamertag slot + missing::<16> as *const (), // 0x80 gamer picture: begin + missing::<17> as *const (), // 0x88 result size + missing::<18> as *const (), // 0x90 result + get_age_group as *const (), // 0x98 + check_privilege as *const (), // 0xa0 + resolve_privilege_async as *const (), // 0xa8 with UI + resolve_privilege_result as *const (), // 0xb0 + token_async as *const (), // 0xb8 token and signature + token_size as *const (), // 0xc0 + token_result as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 the same, UTF-16: begin + missing::<27> as *const (), // 0xd8 result size + missing::<28> as *const (), // 0xe0 result + missing::<29> as *const (), // 0xe8 resolve issue with UI: begin + missing::<30> as *const (), // 0xf0 result + missing::<31> as *const (), // 0xf8 the same, UTF-16: begin + missing::<32> as *const (), // 0x100 result + register as *const (), // 0x108 change event + unregister as *const (), // 0x110 ]); static GAMERTAG_VTABLE: Methods<4> = Methods([ @@ -294,5 +357,43 @@ mod tests { get(this, handle, 0, 2, name.as_mut_ptr(), &mut used), E_NOT_SUFFICIENT_BUFFER ); + + type Age = extern "system" fn(This, Handle, *mut u32) -> HRESULT; + let mut age = 0; + assert_eq!(slot::<Age>(&OBJECT, 0x98)(this, handle, &mut age), S_OK); + assert_eq!(age, 3, "adult"); + type Token = extern "system" fn( + This, + Handle, + u32, + *const c_char, + *const c_char, + usize, + *const c_void, + usize, + *const c_void, + *mut AsyncBlock, + ) -> HRESULT; + let (null, url) = (std::ptr::null(), c"https://example.invalid/"); + let token = slot::<Token>(&OBJECT, 0xb8); + assert_eq!( + token( + this, + handle, + 0, + c"GET".as_ptr(), + url.as_ptr(), + 0, + null, + 0, + null, + &mut block + ), + S_OK + ); + assert_eq!( + xasync::XAsyncGetStatus(&mut block, true), + FAILED_TO_GET_TOKEN + ); } } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index 8c8f3f8..c8479c5 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -32,6 +32,12 @@ pub fn set_image_path(base: usize, path: &Path) { paths.push((base, path)); } +/// Forgets a title image that was unmapped again. +pub fn forget_image(base: usize) { + let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths.retain(|(b, _)| *b != base); +} + pub fn image_path(base: usize) -> Option<PathBuf> { let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); paths @@ -70,33 +76,88 @@ pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> { #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Title { pub id: u32, + /// The store's product id (empty if the manifest has none). + pub store_id: String, /// Persistent local storage: our folder for it and the title's quota. + /// Game saves live beside it ([`Title::saves`]). pub storage: PathBuf, pub storage_bytes: u64, } impl Title { - /// Title id and storage quota from the manifest's text (zero where it - /// has none); the storage folder is left for the caller to choose. - // shortcut: finds the two elements by text, not as XML; parse properly - // once more of the manifest is needed. + /// Id, store id and storage quota from the manifest (zero or empty + /// where it has none); the storage folder is left for the caller. pub fn from_manifest(text: &str) -> Title { - fn element<'a>(text: &'a str, tag: &str) -> Option<&'a str> { - let start = text.find(&format!("<{tag}>"))? + tag.len() + 2; - let len = text[start..].find('<')?; - Some(text[start..start + len].trim()) - } - let id = element(text, "TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); - let storage_mb = text - .find("<PersistentLocalStorage>") - .and_then(|at| element(&text[at..], "SizeMB")) - .and_then(|v| v.parse::<u64>().ok()); + let elements = elements(text); + let get = |path: &str| { + elements + .iter() + .find(|(p, _)| p == path) + .map(|(_, text)| text.as_str()) + }; + let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); Title { id: id.unwrap_or(0), + store_id: get("Game/StoreId").unwrap_or_default().to_owned(), storage: PathBuf::new(), storage_bytes: storage_mb.unwrap_or(0) << 20, } } + + /// Where game saves live: next to persistent local storage, under the + /// data directory, never the cache. + pub fn saves(&self) -> PathBuf { + self.storage.with_file_name("saves") + } +} + +/// Each element of an XML text as its path from the root (`Game/TitleId`) +/// and its trimmed text up to the first child, the predefined entities +/// decoded; comments, CDATA sections, declarations and attributes are +/// skipped. +fn elements(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut path: Vec<&str> = Vec::new(); + let mut rest = text; + while let Some(open) = rest.find('<') { + rest = &rest[open..]; + let end = if rest.starts_with("<!--") { + rest.find("-->").map(|e| e + 3) + } else if rest.starts_with("<![CDATA[") { + rest.find("]]>").map(|e| e + 3) + } else { + rest.find('>').map(|e| e + 1) + }; + let Some(end) = end else { break }; + let tag = &rest[1..end - 1]; + rest = &rest[end..]; + if tag.starts_with(['!', '?']) { + continue; + } + if let Some(name) = tag.strip_prefix('/') { + if let Some(at) = path.iter().rposition(|n| *n == name.trim()) { + path.truncate(at); + } + continue; + } + let closed = tag.ends_with('/'); + let name = tag + .trim_end_matches('/') + .split_whitespace() + .next() + .unwrap_or(""); + path.push(name); + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + out.push((path.join("/"), body)); + if closed { + path.pop(); + } + } + out } static TITLE: Mutex<Option<Title>> = Mutex::new(None); @@ -114,17 +175,52 @@ pub fn title() -> Title { .unwrap_or_default() } +/// Gives the process the console's millisecond timers. Titles pace +/// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps +/// about 4 ms per 5.3 ms block) and cannot tune the timer on the console; +/// a desktop process waits in 15.6 ms ticks unless it asks for finer ones, +/// and Windows 11 drops that request while the window is hidden unless the +/// process opts out. Process-wide, for the whole run. +#[cfg(windows)] +pub fn use_console_timers() { + use windows_sys::Win32::Media::timeBeginPeriod; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, + ProcessPowerThrottling, SetProcessInformation, + }; + let keep = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + // SAFETY: plain process settings; `keep` outlives the call. + unsafe { + SetProcessInformation( + GetCurrentProcess(), + ProcessPowerThrottling, + (&raw const keep).cast(), + size_of_val(&keep) as u32, + ); + timeBeginPeriod(1); + } +} + #[cfg(test)] mod tests { use super::*; #[test] - fn reads_title_id_and_storage_quota() { - let text = "<Game><Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\ + fn reads_title_id_store_id_and_storage_quota() { + let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\ + <!-- <TitleId>00000000</TitleId> -->\ + <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\ + <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&C</StoreId><Other><SizeMB>7</SizeMB></Other>\ <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\ </PersistentLocalStorage></Game>"; let t = Title::from_manifest(text); assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20)); + assert_eq!(t.store_id, "9&C"); assert_eq!(Title::from_manifest("").storage_bytes, 0); } } diff --git a/crates/victory-loader/Cargo.toml b/crates/victory-loader/Cargo.toml index a95f559..637253a 100644 --- a/crates/victory-loader/Cargo.toml +++ b/crates/victory-loader/Cargo.toml @@ -20,6 +20,7 @@ windows-sys = { workspace = true, features = [ "Wdk_System_Threading", "Win32_Foundation", "Win32_System_Diagnostics_Debug", + "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", @@ -29,5 +30,9 @@ windows-sys = { workspace = true, features = [ [dev-dependencies] tempfile.workspace = true +[features] +# Debugging switches (scheduled stack dumps and the like). +diagnostics = [] + [lints] workspace = true diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 03755b2..bb14107 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -1,77 +1,330 @@ //! Names the faulting code when title code crashes. //! -//! A vectored handler sees every exception first, so it only logs the kinds -//! that end a process (access violations and the like) and leaves handling -//! to the title's own handlers. +//! A vectored handler sees every exception first, so it only prints the +//! kinds that end a process (access violations and the like, and +//! breakpoints: titles assert with `int3`, fatal without a debugger) as +//! first-chance, since a handler may still take them (ntdll's loader does +//! with its own probes). What nobody handles, of any kind (an uncaught C++ +//! exception too), is reported from the unhandled-exception filter +//! (`report_unhandled`, which the runtime calls ahead of the title's own) +//! and appended to the crash log, with the title's last debug output, which +//! often states the reason. Panics of ours go to the crash log too. +use std::ptr::null_mut; use windows_sys::Win32::Foundation::{ - EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_INT_DIVIDE_BY_ZERO, - EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE, + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE, }; + use windows_sys::Win32::System::Diagnostics::Debug::{ - AddVectoredExceptionHandler, EXCEPTION_POINTERS, + AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, RtlLookupFunctionEntry, + RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER, }; use windows_sys::Win32::System::LibraryLoader::{ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW, }; +use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits; const EXCEPTION_CONTINUE_SEARCH: i32 = 0; -/// Stack slots scanned for return addresses into a module. -const STACK_SCAN: usize = 64; +/// Frames listed per report. +pub(crate) const MAX_FRAMES: usize = 40; -/// Installs the handler; call once before running title code. -pub fn report_crashes() { - // SAFETY: registers a handler that only reads the exception it is given. - unsafe { AddVectoredExceptionHandler(0, Some(handler)) }; +/// Memory saved to files when a crash is reported: (address, length, file). +#[cfg(feature = "diagnostics")] +static SAVE: std::sync::OnceLock<Vec<(usize, usize, std::path::PathBuf)>> = + std::sync::OnceLock::new(); + +/// Debugging aid: on a reported crash, also write each `[address, address +/// + len)` (readable title memory, e.g. an engine table) to its file. +#[cfg(feature = "diagnostics")] +pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) { + let _ = SAVE.set(ranges); } +/// The file crash reports are appended to, besides being printed. +static LOG: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new(); + +/// Also appends every unhandled-exception report and panic to `file`, so a +/// crash can be read after the console is gone. +pub fn log_crashes_to(file: std::path::PathBuf) { + if LOG.set(file).is_ok() { + let print = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + print(info); + append_to_log(&format!( + "VIctory: panic on thread {:?}: {info}\n{}", + std::thread::current().name().unwrap_or("?"), + title_output() + )); + })); + } +} + +/// Appends a failure that is not an exception (the host GPU's) to the crash +/// log, with the title's last debug output, and prints it. +pub fn log_crash(text: &str) { + let text = format!("{text} +{}", title_output()); + eprint!("{text}"); + append_to_log(&text); +} + +fn append_to_log(text: &str) { + use std::io::Write; + let Some(file) = LOG.get() else { return }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); + if let Ok(mut f) = opened { + let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); + } +} + +/// The title's last lines of debug output, kept for crash reports. +static SAID: std::sync::Mutex<std::collections::VecDeque<String>> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +const SAID_LINES: usize = 8; + +/// Keeps a line of the title's debug output for the next crash report. +pub fn note_title_output(line: &str) { + if line.is_empty() { + return; + } + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if said.len() == SAID_LINES { + said.pop_front(); + } + said.push_back(line.to_owned()); +} + +/// The kept lines, one per report line; nothing if another thread holds +/// them (it may be the one that faulted). +fn title_output() -> String { + let Ok(said) = SAID.try_lock() else { + return String::new(); + }; + said.iter().map(|l| format!(" title said: {l}\n")).collect() +} + +/// Installs the handlers; call once before running title code. +pub fn report_crashes() { + unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + unsafe { report_unhandled(info) }; + EXCEPTION_CONTINUE_SEARCH + } + // SAFETY: registers handlers that only read the exception they are + // given; the title's own filter, once it sets one, takes the place of + // ours and calls `report_unhandled` first. + unsafe { + AddVectoredExceptionHandler(0, Some(handler)); + SetUnhandledExceptionFilter(Some(filter)); + } +} + +/// What the vectored handler reports as it happens. +const FATAL: [i32; 6] = [ + EXCEPTION_ACCESS_VIOLATION, + EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_PRIV_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, + EXCEPTION_STACK_OVERFLOW, + EXCEPTION_BREAKPOINT, +]; + unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes valid exception pointers. + if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) { + // SAFETY: as above. + unsafe { report("first-chance exception", info, false) }; + } + EXCEPTION_CONTINUE_SEARCH +} + +/// For an unhandled-exception filter: reports the exception that is about +/// to end the process, and appends it to the crash log. +/// +/// # Safety +/// `info` comes from the system, for an exception being dispatched. +pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { + // SAFETY: forwarded from the caller. + unsafe { report("unhandled exception", info, true) }; +} + +/// MSVC's code for a C++ `throw`, and its magic first parameter. +const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32; +const CPP_MAGIC: usize = 0x1993_0520; + +/// What a C++ throw threw: the decorated name of its type, then its value +/// where that names the cause (an integer, e.g. an HRESULT; a standard +/// exception's message). +/// +/// # Safety +/// `p` are the parameters of a live MSVC throw (`p[0]` the magic). +unsafe fn thrown(p: &[usize]) -> String { + // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable + // type array at +12 (count, then type RVAs), each type's descriptor at + // +4, whose decorated name starts at +16; the object is at `p[1]`. + unsafe { + let rva = |at: usize| (at as *const u32).read_unaligned() as usize; + let types = p[3] + rva(p[2] + 12); + let name = |i: usize| { + let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) + .to_string_lossy() + }; + let first = name(0); + let value = match &*first { + // int, unsigned, long (HRESULT), unsigned long + ".H" | ".I" | ".J" | ".K" if p[1] != 0 => { + format!(" = {:#010x}", (p[1] as *const u32).read_unaligned()) + } + // std::exception keeps its message after the table pointer. + _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => { + let message = (p[1] as *const *const std::ffi::c_char).add(1).read(); + if message.is_null() { + String::new() + } else { + format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy()) + } + } + _ => String::new(), + }; + format!("{first}{value}") + } +} + +/// # Safety +/// See [`report_unhandled`]. +unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { // SAFETY: the system passes valid exception pointers. let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) }; let code = record.ExceptionCode; - if ![ - EXCEPTION_ACCESS_VIOLATION, - EXCEPTION_ILLEGAL_INSTRUCTION, - EXCEPTION_PRIV_INSTRUCTION, - EXCEPTION_INT_DIVIDE_BY_ZERO, - EXCEPTION_STACK_OVERFLOW, - ] - .contains(&code) - { - return EXCEPTION_CONTINUE_SEARCH; - } let at = record.ExceptionAddress as usize; - let access = if code == EXCEPTION_ACCESS_VIOLATION { - let kind = match record.ExceptionInformation[0] { + let p = record.ExceptionInformation; + let detail = if code == EXCEPTION_ACCESS_VIOLATION { + let kind = match p[0] { 0 => "read", 1 => "write", _ => "execute", }; - format!(" ({kind} {:#x})", record.ExceptionInformation[1]) + format!(" ({kind} {:#x})", p[1]) + } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC { + // SAFETY: a live MSVC throw. + format!(" (C++ {} thrown)", unsafe { thrown(&p) }) } else { String::new() }; - eprintln!( - "VIctory: exception {:#010x} at {}{access}", + // Printed line by line (a fault while unwinding must not lose the + // lines before it), and kept for the file. + let mut text = String::new(); + let mut line = |l: String| { + eprintln!("{l}"); + text.push_str(&l); + text.push('\n'); + }; + line(format!( + "VIctory: {what} {:#010x} at {}{detail}", code as u32, locate(at) - ); - eprintln!( - " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x}", - context.Rax, context.Rbx, context.Rcx, context.Rdx, context.Rsi, context.Rdi, context.Rsp - ); - // shortcut: a stack scan, not an unwind; it lists stale return - // addresses too. Use RtlVirtualUnwind if this misleads. - let stack = context.Rsp as *const usize; - for i in 0..STACK_SCAN { - // SAFETY: slots just above the faulting RSP are committed stack. - let value = unsafe { stack.add(i).read_unaligned() }; - if let Some(name) = module_of(value) { - eprintln!(" [rsp+{:#x}] {name}", i * 8); + )); + line(format!( + " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}", + context.Rax, + context.Rbx, + context.Rcx, + context.Rdx, + context.Rsi, + context.Rdi, + context.Rsp, + context.Rbp + )); + line(format!( + " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}", + context.R8, + context.R9, + context.R10, + context.R11, + context.R12, + context.R13, + context.R14, + context.R15 + )); + for (i, pc) in unwind(*context).into_iter().enumerate() { + line(format!(" #{i:<2} {}", locate(pc as usize))); + } + if to_file { + let said = title_output(); + eprint!("{said}"); + text.push_str(&said); + append_to_log(&text); + } + #[cfg(feature = "diagnostics")] + for (address, len, file) in SAVE.get().into_iter().flatten() { + // SAFETY: the caller of `save_on_crash` named readable memory. + let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) }; + let saved = std::fs::write(file, bytes); + eprintln!( + " saved {address:#x}+{len:#x} to {} ({saved:?})", + file.display() + ); + } +} + +/// Return addresses of the faulting thread's frames, from the faulting +/// instruction up, by the unwind data of each image (the Windows loader +/// registered it for title images too). Code without unwind data (our +/// thunks, leaf functions) is taken to have its return address at `rsp`. +fn unwind(context: CONTEXT) -> Vec<u64> { + let (mut low, mut high) = (0, 0); + // SAFETY: writes the current thread's stack bounds. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + let mut frames = Vec::with_capacity(MAX_FRAMES); + unwind_into(context, low, high, &mut frames); + frames +} + +/// [`unwind`] for any thread of the process, its stack being `low..high`; +/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames` +/// has that capacity (another thread may be suspended holding the heap). +pub(crate) fn unwind_into(mut context: CONTEXT, low: usize, high: usize, frames: &mut Vec<u64>) { + frames.push(context.Rip); + while frames.len() < MAX_FRAMES { + // Stop where reading the stack would fault inside this handler. + let rsp = context.Rsp as usize; + if rsp < low || rsp + 8 > high { + break; } + let mut image = 0; + // SAFETY: looks up the function table entry covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // SAFETY: `rsp` is inside this thread's stack. + context.Rip = unsafe { (rsp as *const u64).read() }; + context.Rsp += 8; + } else { + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our copy. + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + &mut context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + break; + } + frames.push(context.Rip); } - EXCEPTION_CONTINUE_SEARCH } /// `module+rva`, or the bare address. @@ -99,3 +352,32 @@ fn module_of(address: usize) -> Option<String> { let name = path.rsplit('\\').next().unwrap_or(&path); Some(format!("{name}+{:#x}", address - module as usize)) } + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Diagnostics::Debug::{ + RtlCaptureContext, RtlCaptureStackBackTrace, + }; + + #[test] + #[inline(never)] + fn unwinds_like_the_system_walk() { + // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. + let (frames, walked) = unsafe { + let mut context: CONTEXT = std::mem::zeroed(); + RtlCaptureContext(&mut context); + let mut walked = [null_mut(); 8]; + let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut()); + (unwind(context), walked[..usize::from(n)].to_vec()) + }; + // Frame 0 differs (two call sites in this function); callers agree. + assert!(walked.len() >= 4, "{walked:?}"); + let ours: Vec<_> = frames[1..walked.len()] + .iter() + .map(|&f| f as usize) + .collect(); + let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect(); + assert_eq!(ours, system); + } +} diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 11f9793..5a98cae 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -25,6 +25,8 @@ mod crash; pub mod prepare; pub mod resolve; +#[cfg(all(windows, feature = "diagnostics"))] +mod stacks; #[cfg(windows)] mod threads; #[cfg(windows)] @@ -35,9 +37,15 @@ mod tls; mod windows; #[cfg(windows)] -pub use crash::{locate, report_crashes}; +pub use crash::{ + locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, +}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use stacks::{dump_stacks, dump_stacks_on_schedule}; #[cfg(windows)] pub use threads::disable_thread_calls; #[cfg(windows)] @@ -49,3 +57,5 @@ pub use windows::{ /// `DLL_PROCESS_ATTACH`, for TLS callbacks. pub const DLL_PROCESS_ATTACH: u32 = 1; +/// `DLL_PROCESS_DETACH`. +pub const DLL_PROCESS_DETACH: u32 = 0; diff --git a/crates/victory-loader/src/stacks.rs b/crates/victory-loader/src/stacks.rs new file mode 100644 index 0000000..1d30910 --- /dev/null +++ b/crates/victory-loader/src/stacks.rs @@ -0,0 +1,224 @@ +//! Where every thread is: `VICTORY_STACKS=<seconds>[,<seconds>...]` prints +//! each thread's unwound stack as `module+rva` that many seconds after +//! [`dump_stacks_on_schedule`], to find what a title waits on. + +use std::ffi::c_void; + +use windows_sys::Wdk::System::Threading::{ + NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress, +}; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, + SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +use crate::crash::{MAX_FRAMES, locate, unwind_into}; + +/// Reads `VICTORY_STACKS` and, if set, starts a thread that prints every +/// thread's stack at each listed time (seconds from now). +pub fn dump_stacks_on_schedule() { + let Ok(list) = std::env::var("VICTORY_STACKS") else { + return; + }; + let mut times: Vec<f64> = list + .split(',') + .filter_map(|t| t.trim().parse().ok()) + .collect(); + times.sort_by(f64::total_cmp); + let start = std::time::Instant::now(); + std::thread::spawn(move || { + for t in times { + let at = std::time::Duration::from_secs_f64(t.max(0.0)); + std::thread::sleep(at.saturating_sub(start.elapsed())); + dump_stacks(); + } + }); +} + +/// `THREAD_BASIC_INFORMATION` (ntddk). +#[repr(C)] +struct BasicInfo { + exit_status: i32, + teb: *const usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, +} + +/// `GetThreadContext` wants a 16-byte aligned context. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Prints every other thread's stack to stderr. Each thread is suspended +/// only while its context is read and unwound into a buffer allocated +/// beforehand (it may hold the heap lock). +pub fn dump_stacks() { + // SAFETY: plain queries and a snapshot of this process's threads. + let (me, process, snapshot) = unsafe { + ( + GetCurrentThreadId(), + GetCurrentProcessId(), + CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), + ) + }; + if snapshot == INVALID_HANDLE_VALUE { + return; + } + let mut ids = Vec::new(); + // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use. + let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() }; + entry.dwSize = size_of::<THREADENTRY32>() as u32; + // SAFETY: `snapshot` is open; `entry` is sized. + let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0; + while more { + if entry.th32OwnerProcessID == process && entry.th32ThreadID != me { + ids.push(entry.th32ThreadID); + } + // SAFETY: as above. + more = unsafe { Thread32Next(snapshot, &mut entry) } != 0; + } + // SAFETY: we opened it. + unsafe { CloseHandle(snapshot) }; + eprintln!("VIctory: stacks of {} threads", ids.len()); + for id in ids { + // SAFETY: opens a thread of our own process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + if thread.is_null() { + continue; + } + let (frames, (priority, base)) = frames_of(thread); + eprintln!( + " thread {id} \"{}\" start {} priority {priority} (base {base})", + name_of(thread), + locate(start_of(thread)) + ); + for (i, pc) in frames.into_iter().enumerate() { + eprintln!(" #{i:<2} {}", locate(pc as usize)); + } + // SAFETY: we opened it. + unsafe { CloseHandle(thread) }; + } +} + +/// The thread's frames and its current and base scheduling priority (0-31). +fn frames_of(thread: HANDLE) -> (Vec<u64>, (i32, i32)) { + let mut frames = Vec::with_capacity(MAX_FRAMES); + let mut info: BasicInfo = BasicInfo { + exit_status: 0, + teb: std::ptr::null(), + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `info`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + ThreadBasicInformation, + (&raw mut info).cast(), + size_of::<BasicInfo>() as u32, + std::ptr::null_mut(), + ) + }; + if status != 0 || info.teb.is_null() { + return (frames, (0, 0)); + } + // SAFETY: the TEB of a live thread of this process: its NT_TIB holds + // the stack base at +8 and the stack limit at +0x10. + let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; + // SAFETY: zeroed is a valid CONTEXT. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + context.0.ContextFlags = CONTEXT_FULL_AMD64; + // SAFETY: suspends, reads and resumes a thread that is not this one; + // nothing between suspend and resume allocates or takes a lock the + // thread could hold besides the unwinder's own. + unsafe { + if SuspendThread(thread) == u32::MAX { + return (frames, (info.priority, info.base_priority)); + } + if GetThreadContext(thread, &mut context.0) != 0 { + unwind_into(context.0, low, high, &mut frames); + } + ResumeThread(thread); + } + (frames, (info.priority, info.base_priority)) +} + +fn start_of(thread: HANDLE) -> usize { + let mut start = 0usize; + // SAFETY: writes one pointer-sized start address. + unsafe { + NtQueryInformationThread( + thread, + ThreadQuerySetWin32StartAddress, + (&raw mut start).cast(), + size_of::<usize>() as u32, + std::ptr::null_mut(), + ) + }; + start +} + +fn name_of(thread: HANDLE) -> String { + let mut name = std::ptr::null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut name) < 0 || name.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len)); + LocalFree(name.cast::<c_void>()); + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn another_threads_stack_unwinds_to_its_start() { + let (tx, rx) = std::sync::mpsc::channel(); + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let parked = std::thread::spawn(move || { + // SAFETY: plain query. + tx.send(unsafe { GetCurrentThreadId() }).unwrap(); + stop_rx.recv().ok(); + }); + let id = rx.recv().unwrap(); + // SAFETY: a thread of this process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + assert!(!thread.is_null()); + let (frames, _) = frames_of(thread); + // Waiting in the kernel, several frames down from the thread start. + assert!(frames.len() >= 3, "{frames:?}"); + assert!(start_of(thread) != 0); + // SAFETY: opened above. + unsafe { CloseHandle(thread) }; + dump_stacks(); + stop_tx.send(()).unwrap(); + parked.join().unwrap(); + } +} diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index b0e9b10..a4333b2 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -6,9 +6,11 @@ //! callbacks, then a DLL's `DllMain`. use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::Duration; -use crate::LoadedImage; +use crate::{DLL_PROCESS_DETACH, LoadedImage}; const DLL_THREAD_ATTACH: u32 = 2; const DLL_THREAD_DETACH: u32 = 3; @@ -41,9 +43,143 @@ pub(crate) fn mapped(image: &LoadedImage) { }); } +/// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is +/// the Windows loader's initialisation order. pub(crate) fn attached(base: usize) { - if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) { + let mut images = images(); + if let Some(i) = images.iter().position(|m| m.image.base() == base) { + let mut m = images.remove(i); m.attached = true; + images.push(m); + } + static AT_EXIT: std::sync::Once = std::sync::Once::new(); + // Registered before the title's own exit functions, so it runs after + // them, as `ExitProcess` follows `exit`'s functions on Windows. + // SAFETY: registers a function with the host CRT's exit table. + AT_EXIT.call_once(|| unsafe { + atexit(detach_all); + }); +} + +pub(crate) fn detached(base: usize) { + if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) { + m.attached = false; + } +} + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// Set once the process is ending: no more thread notices. +static EXITING: AtomicBool = AtomicBool::new(false); + +/// How long title images may take to detach before the process ends anyway +/// (a thread ended while holding a lock their detach code wants). +const DETACH_DEADLINE: Duration = Duration::from_secs(5); + +/// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s +/// order: the title's exit functions have run; every other thread ends +/// (title threads and ours); every attached image gets +/// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the +/// exe's TLS callbacks; then the CRT ends the process. +extern "C" fn detach_all() { + let attached: Vec<_> = images() + .iter_mut() + .filter(|m| m.attached) + .map(|m| { + m.attached = false; + m.image.clone() + }) + .collect(); + let (dlls, exes): (Vec<_>, Vec<_>) = + attached.into_iter().rev().partition(|i| i.info().is_dll()); + tracing::info!( + images = dlls.len() + exes.len(), + "process exit: ending other threads, detaching title images" + ); + EXITING.store(true, Ordering::SeqCst); + end_other_threads(); + // As on Windows, a lock a thread held when it ended stays taken; detach + // code that waits for one would hang the exit. + std::thread::spawn(|| { + std::thread::sleep(DETACH_DEADLINE); + tracing::warn!("process exit: title images did not detach in time; ending"); + // SAFETY: ends this process, which is exiting anyway. + unsafe { + windows_sys::Win32::System::Threading::TerminateProcess( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + 1, + ) + }; + }); + for image in dlls.iter().chain(&exes) { + // SAFETY: attached images are bound. A non-null third argument + // tells the entry points the process is ending. + unsafe { + image.notify( + DLL_PROCESS_DETACH, + true, + std::ptr::without_provenance_mut(1), + ) + }; + } +} + +/// Ends every thread of the process but this one (and the ones started +/// while doing so), as `ExitProcess` does first; except the system's +/// thread-pool workers, which `TerminateThread` refuses (the process fails +/// fast) and which run no title code (no title image uses that pool). +fn end_other_threads() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, + THREAD_QUERY_INFORMATION, + }; + // SAFETY: plain queries of the calling process and thread. + let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; + let mut ended = std::collections::HashSet::new(); + loop { + // SAFETY: a snapshot of every thread, walked with a sized entry. + let others: Vec<u32> = unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + break; + } + let mut entry = THREADENTRY32 { + dwSize: size_of::<THREADENTRY32>() as u32, + ..std::mem::zeroed() + }; + let mut ids = Vec::new(); + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process && entry.th32ThreadID != me { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + ids + }; + let new: Vec<u32> = others.into_iter().filter(|id| ended.insert(*id)).collect(); + if new.is_empty() { + break; + } + for id in new { + // SAFETY: a thread of this process, which is exiting. + unsafe { + let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id); + if !thread.is_null() { + if !starts_in(thread, c"ntdll.dll") { + TerminateThread(thread, 0); + } + CloseHandle(thread); + } + } + } } } @@ -71,65 +207,174 @@ pub fn disable_thread_calls(base: usize) -> Option<bool> { static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { - if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH || started_by_rust() { + if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH { return; } + if EXITING.load(Ordering::SeqCst) { + return; // our exit watchdog, or threads ending with the process + } // A snapshot: title code may map and attach another DLL from here. let notify: Vec<_> = images() .iter() .filter(|m| m.attached) .map(|m| (m.image.clone(), !m.quiet)) .collect(); + if notify.is_empty() { + return; + } + // Rust's std sets its threads up after this callback and aborts the + // process if their per-thread state was touched first (the current + // thread's id, which our logging asks for when title code calls us). + // That state is put back as the thread started. + let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save); // Starts in load order, ends in reverse, as the Windows loader does. let notify_one = |(image, dll_main): &(Arc<LoadedImage>, bool)| { // SAFETY: attached images have their imports bound. - unsafe { image.notify(reason, *dll_main) }; + unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) }; }; if reason == DLL_THREAD_ATTACH { notify.iter().for_each(notify_one); } else { notify.iter().rev().for_each(notify_one); } + if let Some(saved) = saved { + saved.restore(); + } +} + +/// Our own image's static TLS block on this thread (Rust's std keeps its +/// per-thread state there), as copied before title code ran. +struct OwnTls { + block: *mut u8, + saved: Vec<u8>, +} + +/// The TLS directory the linker emits for our image (the CRT's symbol). +#[repr(C)] +struct TlsDirectory { + start: usize, + end: usize, + index: *const u32, + callbacks: usize, + zero_fill: u32, + characteristics: u32, +} + +unsafe extern "C" { + static _tls_used: TlsDirectory; +} + +impl OwnTls { + fn save() -> OwnTls { + let array: *const *mut u8; + // SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our + // image's, and Windows set up its block on this thread before + // calling TLS callbacks. + let (block, len) = unsafe { + std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly)); + let dir = &raw const _tls_used; + let block = *array.add((*dir).index.read() as usize); + (block, (*dir).end - (*dir).start + (*dir).zero_fill as usize) + }; + // SAFETY: the block is `len` bytes, live for the thread's life. + let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec(); + OwnTls { block, saved } + } + + fn restore(self) { + // SAFETY: the same block on the same thread, no reference to it held. + unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) }; + } } /// Whether Rust's std started this thread (its start routine is in our -/// exe): the title's main thread and our runtime's workers. They get no -/// notices: std aborts the process if anything on such a thread asks for -/// the current thread (as stdout and stderr locks do) before its start -/// routine has run, and title code may call our runtime, which logs. -// shortcut: title code on our workers (xasync callbacks) runs without -// thread notices; send them from the worker's start if a title needs them. +/// exe): the title's main thread and our runtime's workers, which run +/// title callbacks. fn started_by_rust() -> bool { + // SAFETY: the calling thread's pseudo handle. + starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") +} + +/// Whether `thread`'s start routine lies in the module named `module` +/// (empty: our exe). +fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool { use windows_sys::Wdk::System::Threading::{ NtQueryInformationThread, ThreadQuerySetWin32StartAddress, }; use windows_sys::Win32::System::LibraryLoader::{ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - GetModuleHandleExW, GetModuleHandleW, + GetModuleHandleA, GetModuleHandleExW, }; - use windows_sys::Win32::System::Threading::GetCurrentThread; let mut start = 0usize; // SAFETY: writes one pointer-sized start address. let status = unsafe { NtQueryInformationThread( - GetCurrentThread(), + thread, ThreadQuerySetWin32StartAddress, (&raw mut start).cast(), size_of::<usize>() as u32, std::ptr::null_mut(), ) }; - let mut module = std::ptr::null_mut(); + let mut found = std::ptr::null_mut(); + let name = if module.is_empty() { + std::ptr::null() + } else { + module.as_ptr().cast() + }; // SAFETY: looks up the module containing an address, taking no reference. status == 0 && unsafe { GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, start as *const u16, - &mut module, + &mut found, ) } != 0 - // SAFETY: our own exe's handle. - && module == unsafe { GetModuleHandleW(std::ptr::null()) } + // SAFETY: a module handle by name (or our exe's); no reference taken. + && found == unsafe { GetModuleHandleA(name) } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering}; + use std::time::Duration; + + /// In a child process of the next test: ends the other threads and + /// checks that a busy one stopped. + #[test] + fn exit_child() { + if std::env::var_os("VICTORY_EXIT_CHILD").is_none() { + return; + } + static TICKS: AtomicU64 = AtomicU64::new(0); + std::thread::spawn(|| { + loop { + TICKS.fetch_add(1, Ordering::SeqCst); + std::thread::yield_now(); + } + }); + while TICKS.load(Ordering::SeqCst) == 0 { + std::thread::yield_now(); + } + super::end_other_threads(); + let at = TICKS.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(50)); + let ended = TICKS.load(Ordering::SeqCst) == at; + // The test harness's threads are gone too: leave at once. + println!("{}", if ended { "ENDED" } else { "STILL RUNNING" }); + std::process::exit(0); + } + + #[test] + fn exit_ends_the_other_threads_first() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "threads::tests::exit_child", "--nocapture"]) + .env("VICTORY_EXIT_CHILD", "1") + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && text.contains("ENDED"), "{text}"); + } } diff --git a/crates/victory-loader/src/tls.rs b/crates/victory-loader/src/tls.rs index 588a871..a234183 100644 --- a/crates/victory-loader/src/tls.rs +++ b/crates/victory-loader/src/tls.rs @@ -82,8 +82,9 @@ fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { let c = &code[i..i + LOAD_LEN]; let rex = c[1]; let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; - // shortcut: a byte match, not a decode; a false hit inside other - // bytes is unlikely at 9 specific bytes. Decode .text if one shows. + // shortcut: a byte match, not a decode. In Grand Theft Auto VI all + // 53,246 hits are instruction starts and none is missed (checked + // against a full disassembly); decode .text if a title shows one. if c[0] == 0x65 && (rex == 0x48 || rex == 0x4C) && c[2] == 0x8B diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 890d3a8..67845f1 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -14,7 +14,10 @@ use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; -use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare}; +use crate::{ + DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution, + prepare, +}; /// A title image mapped into this process. A clone names the same mapping /// (no reference of its own): unload one copy only. @@ -308,13 +311,20 @@ impl LoadedImage { /// # Safety /// Runs title code. Imports must be bound first. pub unsafe fn run_tls_callbacks(&self, reason: u32) { + // SAFETY: forwarded from the caller. + unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) } + } + + /// # Safety + /// See [`Self::run_tls_callbacks`]. + unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) { let Some(tls) = &self.info.tls else { return }; for &rva in &tls.callback_rvas { type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); // SAFETY: the RVA came from the image's own TLS directory. let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) }; // SAFETY: the caller guarantees imports are bound. - unsafe { callback(self.module, reason, std::ptr::null_mut()) }; + unsafe { callback(self.module, reason, reserved) }; } } @@ -327,22 +337,39 @@ impl LoadedImage { /// depends on attached. pub unsafe fn attach(&self) -> Result<()> { // SAFETY: forwarded from the caller. - if unsafe { self.notify(DLL_PROCESS_ATTACH, true) } == Some(0) { + if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) { bail!("DllMain returned FALSE"); } crate::threads::attached(self.base()); Ok(()) } + /// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then + /// `DllMain`); the image hears of no more threads. + /// + /// # Safety + /// Runs title code. The image must have been attached (or its attach + /// failed), and no other thread may be using it. + pub unsafe fn detach(&self) { + crate::threads::detached(self.base()); + // SAFETY: forwarded from the caller. + unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) }; + } + /// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and /// the image is a DLL with an entry point, its `DllMain`, whose result - /// is returned. + /// is returned. `reserved` is the entry points' third argument. /// /// # Safety /// Runs title code. Imports must be bound first. - pub(crate) unsafe fn notify(&self, reason: u32, dll_main: bool) -> Option<i32> { + pub(crate) unsafe fn notify( + &self, + reason: u32, + dll_main: bool, + reserved: *mut c_void, + ) -> Option<i32> { // SAFETY: forwarded from the caller. - unsafe { self.run_tls_callbacks(reason) }; + unsafe { self.tls_callbacks(reason, reserved) }; if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { return None; } @@ -351,7 +378,7 @@ impl LoadedImage { let main: DllMain = unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; // SAFETY: forwarded from the caller. - Some(unsafe { main(self.module, reason, std::ptr::null_mut()) }) + Some(unsafe { main(self.module, reason, reserved) }) } /// Starts the title: on a new thread with the stack size from the image diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 4c90b82..6d75d23 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -39,7 +39,10 @@ fn build_probe() -> PathBuf { extern "system" fn fake_xgameruntime_initialize() -> i32 { 0x1234 } +/// Asks for the current thread, as our logging does: on a thread std is +/// still starting, that must not abort the process. extern "system" fn fake_get_tick_count() -> u32 { + let _ = std::thread::current().id(); 777 } extern "system" fn fake_delayed() -> u32 { @@ -192,8 +195,18 @@ fn loads_binds_and_calls_probe() { image.attach().unwrap(); let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts")); let before = f(); - // Starting in title code, as a title's threads do (ours start in - // our exe and are left out); the extra argument is ignored. + // A thread std starts, as our runtime's workers are: notified + // before std sets it up, which must still find its state pristine. + let worker = std::thread::Builder::new() + .name("probe-worker".into()) + .spawn(|| std::thread::current().name().map(str::to_owned)) + .unwrap(); + assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker")); + let mid = f(); + assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32); + let before = mid; + // Starting in title code, as a title's threads do; the extra + // argument is ignored. let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = std::mem::transmute(call("probe_pid")); let thread = CreateThread( @@ -223,6 +236,11 @@ fn loads_binds_and_calls_probe() { ); assert_eq!(victory_loader::disable_thread_calls(1), None); + // `FreeLibrary`'s notice, as a failed late load sends it. + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches")); + assert_eq!(f(), 0); + image.detach(); + assert_eq!(f(), 1); image.unload(); } } diff --git a/crates/victory-shader/Cargo.toml b/crates/victory-shader/Cargo.toml index d3f8c2c..edfd1b9 100644 --- a/crates/victory-shader/Cargo.toml +++ b/crates/victory-shader/Cargo.toml @@ -11,5 +11,30 @@ publish.workspace = true thiserror.workspace = true miniz_oxide.workspace = true +[features] +# Host D3D12 pipeline checks (`emit::host`). +host = ["dep:windows"] +# Debugging switches (emitted-module dumps and the like). +diagnostics = [] + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] } +windows = { workspace = true, optional = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + +[target.'cfg(windows)'.dev-dependencies] +windows = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + [lints] workspace = true diff --git a/crates/victory-shader/src/dxbc.rs b/crates/victory-shader/src/dxbc.rs index 605037f..7a20963 100644 --- a/crates/victory-shader/src/dxbc.rs +++ b/crates/victory-shader/src/dxbc.rs @@ -22,6 +22,8 @@ impl FourCC { pub const PSV0: FourCC = FourCC(*b"PSV0"); pub const ISG1: FourCC = FourCC(*b"ISG1"); pub const OSG1: FourCC = FourCC(*b"OSG1"); + /// Per-primitive outputs of a mesh shader. + pub const PSG1: FourCC = FourCC(*b"PSG1"); pub const SFI0: FourCC = FourCC(*b"SFI0"); pub const HASH: FourCC = FourCC(*b"HASH"); pub const ILDB: FourCC = FourCC(*b"ILDB"); diff --git a/crates/victory-shader/src/emit/bitcode.rs b/crates/victory-shader/src/emit/bitcode.rs new file mode 100644 index 0000000..8b555ad --- /dev/null +++ b/crates/victory-shader/src/emit/bitcode.rs @@ -0,0 +1,986 @@ +//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated +//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`). +//! +//! Values are symbolic while the module is built ([`V`]) and numbered when +//! it is written: functions, then constants (all at module level), then the +//! instructions of `main` in block order. + +use std::collections::HashMap; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) struct Ty(u32); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum TypeDef { + Void, + Int(u32), + Float, + /// Pointee and address space. + Ptr(Ty, u32), + Struct(Option<String>, Vec<Ty>), + Array(u32, Ty), + Func(Ty, Vec<Ty>), +} + +/// A value: a global variable, a function, a module constant, or an +/// instruction result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) enum V { + Global(u32), + Func(u32), + Const(u32), + Inst(u32), +} + +/// A global variable declaration (thread-group shared memory). +struct Global { + name: String, + ty: Ty, + /// Its pointer type. + ptr: Ty, + space: u32, + /// An internal constant with this initialiser (a constant table). + init: Option<u32>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Const { + Int(i64), + Float(u32), + Undef, + Aggregate(Vec<u32>), +} + +/// LLVM binary opcodes (the same codes serve the float forms). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Bin { + Add = 0, + Sub = 1, + Mul = 2, + UDiv = 3, + SDiv = 4, + URem = 5, + Shl = 7, + LShr = 8, + AShr = 9, + And = 10, + Or = 11, + Xor = 12, +} + +/// `atomicrmw` operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Rmw { + Xchg = 0, + Add = 1, + Sub = 2, + And = 3, + Or = 5, + Xor = 6, + Max = 7, + Min = 8, + UMax = 9, + UMin = 10, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Cast { + Trunc = 0, + ZExt = 1, + SExt = 2, + FpToUi = 3, + FpToSi = 4, + UiToFp = 5, + SiToFp = 6, + Bitcast = 11, +} + +/// Compare predicates: floats 0-15, integers 32-41. +pub(crate) mod pred { + pub const FALSE: u8 = 0; + pub const OEQ: u8 = 1; + pub const OGT: u8 = 2; + pub const OGE: u8 = 3; + pub const OLT: u8 = 4; + pub const OLE: u8 = 5; + pub const ONE: u8 = 6; + pub const ORD: u8 = 7; + pub const UNO: u8 = 8; + pub const UEQ: u8 = 9; + pub const UGT: u8 = 10; + pub const UGE: u8 = 11; + pub const ULT: u8 = 12; + pub const ULE: u8 = 13; + pub const UNE: u8 = 14; + pub const TRUE: u8 = 15; + pub const EQ: u8 = 32; + pub const NE: u8 = 33; + pub const IUGT: u8 = 34; + pub const IUGE: u8 = 35; + pub const IULT: u8 = 36; + pub const IULE: u8 = 37; + pub const SGT: u8 = 38; + pub const SGE: u8 = 39; + pub const SLT: u8 = 40; + pub const SLE: u8 = 41; +} + +#[derive(Debug, Clone)] +enum Op { + Bin(Bin, V, V), + Cast(Cast, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec<V>), + /// Filled in later: (value, block). + Phi(Vec<(V, usize)>), + /// `getelementptr` over the pointee type, from a pointer. + Gep(Ty, V, Vec<V>), + Load(V), + /// Pointer, value. + Store(V, V), + AtomicRmw(Rmw, V, V), + /// Pointer, expected, new; returns `{i32, i1}`. + CmpXchg(V, V, V), +} + +#[derive(Debug, Clone)] +struct Inst { + ty: Ty, + op: Op, +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Term { + Br(usize), + CondBr(V, usize, usize), + Ret, +} + +#[derive(Debug, Clone, Default)] +struct Block { + phis: Vec<u32>, + body: Vec<u32>, + term: Option<Term>, +} + +/// Function attributes of a `dx.op` declaration. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Attr { + ReadNone = 1, + NoUnwind = 2, + ReadOnly = 3, + /// Barriers. + NoDuplicate = 4, +} + +struct Func { + name: String, + ty: Ty, + attr: Option<Attr>, + body: bool, +} + +/// A metadata node operand. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Md(u32); + +enum MdDef { + Str(String), + Value(Ty, V), + Node(Vec<Option<Md>>), +} + +#[derive(Default)] +pub(crate) struct Module { + types: Vec<TypeDef>, + type_ids: HashMap<TypeDef, u32>, + consts: Vec<(Ty, Const)>, + const_ids: HashMap<(Ty, Const), u32>, + globals: Vec<Global>, + funcs: Vec<Func>, + func_ids: HashMap<String, u32>, + insts: Vec<Inst>, + blocks: Vec<Block>, + mds: Vec<MdDef>, + named: Vec<(String, Vec<Md>)>, +} + +impl Module { + fn ty(&mut self, def: TypeDef) -> Ty { + if let Some(&t) = self.type_ids.get(&def) { + return Ty(t); + } + let t = self.types.len() as u32; + self.types.push(def.clone()); + self.type_ids.insert(def, t); + Ty(t) + } + + pub fn void(&mut self) -> Ty { + self.ty(TypeDef::Void) + } + pub fn int(&mut self, bits: u32) -> Ty { + self.ty(TypeDef::Int(bits)) + } + pub fn float(&mut self) -> Ty { + self.ty(TypeDef::Float) + } + pub fn ptr(&mut self, to: Ty) -> Ty { + self.ty(TypeDef::Ptr(to, 0)) + } + pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty { + self.ty(TypeDef::Ptr(to, space)) + } + pub fn array(&mut self, n: u32, of: Ty) -> Ty { + self.ty(TypeDef::Array(n, of)) + } + pub fn named_struct(&mut self, name: &str, fields: Vec<Ty>) -> Ty { + self.ty(TypeDef::Struct(Some(name.into()), fields)) + } + pub fn func_ty(&mut self, ret: Ty, params: Vec<Ty>) -> Ty { + self.ty(TypeDef::Func(ret, params)) + } + + fn is_void(&self, t: Ty) -> bool { + self.types[t.0 as usize] == TypeDef::Void + } + + fn constant(&mut self, ty: Ty, c: Const) -> V { + if let Some(&i) = self.const_ids.get(&(ty, c.clone())) { + return V::Const(i); + } + let i = self.consts.len() as u32; + self.consts.push((ty, c.clone())); + self.const_ids.insert((ty, c), i); + V::Const(i) + } + + pub fn int_const(&mut self, ty: Ty, v: i64) -> V { + self.constant(ty, Const::Int(v)) + } + pub fn i32(&mut self, v: u32) -> V { + let t = self.int(32); + self.int_const(t, i64::from(v as i32)) + } + pub fn i8(&mut self, v: u8) -> V { + let t = self.int(8); + self.int_const(t, i64::from(v as i8)) + } + pub fn bool(&mut self, v: bool) -> V { + let t = self.int(1); + self.int_const(t, -i64::from(v)) + } + pub fn f32(&mut self, bits: u32) -> V { + let t = self.float(); + self.constant(t, Const::Float(bits)) + } + pub fn undef(&mut self, ty: Ty) -> V { + self.constant(ty, Const::Undef) + } + /// A constant struct or array of constants. + pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V { + let ids = fields + .iter() + .map(|f| match f { + V::Const(i) => *i, + _ => panic!("aggregate of a non-constant"), + }) + .collect(); + self.constant(ty, Const::Aggregate(ids)) + } + + /// Gives constant `old` the content of `new` (both stay valid). + pub fn replace_const(&mut self, old: V, new: V) { + if let (V::Const(o), V::Const(n)) = (old, new) { + self.consts[o as usize] = self.consts[n as usize].clone(); + } + } + + /// A function declaration (or `main` with `body`), found by name. + pub fn function(&mut self, name: &str, ty: Ty, attr: Option<Attr>, body: bool) -> V { + if let Some(&i) = self.func_ids.get(name) { + return V::Func(i); + } + let i = self.funcs.len() as u32; + self.funcs.push(Func { + name: name.into(), + ty, + attr, + body, + }); + self.func_ids.insert(name.into(), i); + V::Func(i) + } + + /// An external global of type `ty` in address space `space` (DXIL + /// declares thread-group shared memory this way). + pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V { + let ptr = self.ptr_in(ty, space); + self.globals.push(Global { + name: name.into(), + ty, + ptr, + space, + init: None, + }); + V::Global(self.globals.len() as u32 - 1) + } + + /// An internal constant global initialised with the constant `init`. + pub fn constant_global(&mut self, name: &str, init: V) -> V { + let V::Const(i) = init else { + panic!("a global initialised with a non-constant") + }; + let ty = self.consts[i as usize].0; + let g = self.global(name, ty, 0); + if let V::Global(n) = g { + self.globals[n as usize].init = Some(i); + } + g + } + + pub fn new_block(&mut self) -> usize { + self.blocks.push(Block::default()); + self.blocks.len() - 1 + } + + pub fn type_of(&self, v: V) -> Ty { + match v { + V::Global(i) => self.globals[i as usize].ptr, + V::Const(i) => self.consts[i as usize].0, + V::Inst(i) => self.insts[i as usize].ty, + V::Func(i) => { + let t = self.funcs[i as usize].ty; + *self + .type_ids + .get(&TypeDef::Ptr(t, 0)) + .map(|t| Ty(*t)) + .as_ref() + .expect("function pointer type") + } + } + } + + fn push(&mut self, block: usize, ty: Ty, op: Op) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { ty, op }); + // Terminators are kept apart, so a block can still grow at its end. + self.blocks[block].body.push(i); + V::Inst(i) + } + + pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V { + let ty = self.type_of(a); + self.push(block, ty, Op::Bin(op, a, b)) + } + pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V { + self.push(block, to, Op::Cast(op, v)) + } + pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V { + let t = self.int(1); + self.push(block, t, Op::Cmp(pred, a, b)) + } + pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V { + let ty = self.type_of(t); + self.push(block, ty, Op::Select(c, t, f)) + } + pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V { + let ty = match &self.types[self.type_of(agg).0 as usize] { + TypeDef::Struct(_, f) => f[index as usize], + TypeDef::Array(_, t) => *t, + t => panic!("extractvalue from {t:?}"), + }; + self.push(block, ty, Op::Extract(agg, index)) + } + pub fn call(&mut self, block: usize, f: V, args: Vec<V>) -> V { + let V::Func(i) = f else { + panic!("call of a non-function") + }; + let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else { + unreachable!() + }; + self.push(block, ret, Op::Call(i, args)) + } + /// A phi at the top of `block`; incoming values come with [`Module::set_phi`]. + pub fn phi(&mut self, block: usize, ty: Ty) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { + ty, + op: Op::Phi(Vec::new()), + }); + self.blocks[block].phis.push(i); + V::Inst(i) + } + /// The address of element `index` of the array `ptr` points to. + pub fn element(&mut self, block: usize, ptr: V, index: V) -> V { + let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else { + panic!("element of a non-pointer") + }; + let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else { + panic!("element of a non-array") + }; + let ty = self.ptr_in(elem, space); + let zero = self.i32(0); + self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index])) + } + pub fn load(&mut self, block: usize, ptr: V) -> V { + let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else { + panic!("load from a non-pointer") + }; + self.push(block, ty, Op::Load(ptr)) + } + pub fn store(&mut self, block: usize, ptr: V, value: V) { + let void = self.void(); + self.push(block, void, Op::Store(ptr, value)); + } + pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V { + let ty = self.type_of(value); + self.push(block, ty, Op::AtomicRmw(op, ptr, value)) + } + /// The old value of a compare-exchange. + pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V { + let (i32t, i1) = (self.type_of(new), self.int(1)); + let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1])); + let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new)); + self.extract(block, r, 0) + } + + pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) { + let V::Inst(i) = phi else { panic!() }; + self.insts[i as usize].op = Op::Phi(incoming); + } + pub fn terminate(&mut self, block: usize, t: Term) { + self.blocks[block].term = Some(t); + } + + pub fn md_str(&mut self, s: &str) -> Md { + self.mds.push(MdDef::Str(s.into())); + Md(self.mds.len() as u32 - 1) + } + pub fn md_value(&mut self, v: V) -> Md { + let ty = self.type_of(v); + self.mds.push(MdDef::Value(ty, v)); + Md(self.mds.len() as u32 - 1) + } + pub fn md_node(&mut self, ops: Vec<Option<Md>>) -> Md { + self.mds.push(MdDef::Node(ops)); + Md(self.mds.len() as u32 - 1) + } + pub fn named_md(&mut self, name: &str, nodes: Vec<Md>) { + self.named.push((name.into(), nodes)); + } + + /// The module as bitcode. + pub fn write(&self) -> Vec<u8> { + let mut w = Writer::default(); + w.bytes(b"BC\xC0\xDE"); + w.enter(MODULE_BLOCK, 3); + w.record(1, &[1]); // VERSION: relative value ids + + // Attribute groups 1-4 and one list per group. + w.enter(PARAMATTR_GROUP_BLOCK, 3); + for (id, kinds) in [ + (1, &[18u64, 20][..]), + (2, &[18]), + (3, &[18, 21]), + (4, &[12, 18]), + ] { + let mut r = vec![id, 0xFFFF_FFFF]; + for &k in kinds { + r.extend([0, k]); + } + w.record(3, &r); + } + w.exit(); + w.enter(PARAMATTR_BLOCK, 3); + for id in 1..=4 { + w.record(2, &[id]); + } + w.exit(); + + w.enter(TYPE_BLOCK, 4); + w.record(1, &[self.types.len() as u64]); + for t in &self.types { + match t { + TypeDef::Void => w.record(2, &[]), + TypeDef::Float => w.record(3, &[]), + TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), + TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), + TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), + TypeDef::Struct(name, fields) => { + let mut r = vec![0]; + r.extend(fields.iter().map(|f| u64::from(f.0))); + match name { + Some(n) => { + w.record(19, &chars(n)); + w.record(20, &r); + } + None => w.record(18, &r), + } + } + TypeDef::Func(ret, params) => { + let mut r = vec![0, u64::from(ret.0)]; + r.extend(params.iter().map(|p| u64::from(p.0))); + w.record(21, &r); + } + } + } + w.exit(); + + w.record(2, &chars("dxil-ms-dx")); + w.record( + 3, + &chars( + "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", + ), + ); + let first_const = (self.globals.len() + self.funcs.len()) as u64; + for g in &self.globals { + // [type, address space << 2 | explicit type | constant, init id + // + 1, linkage (external 0, internal 3), log2 alignment + 1, + // section] + let (constant, init, linkage) = match g.init { + Some(i) => (1, first_const + u64::from(i) + 1, 3), + None => (0, 0, 0), + }; + w.record( + 7, + &[ + u64::from(g.ty.0), + u64::from(g.space) << 2 | 2 | constant, + init, + linkage, + 3, + 0, + ], + ); + } + for f in &self.funcs { + // [type, cc, isproto, linkage, paramattr, align, section, + // visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix] + let attr = f.attr.map_or(0, |a| a as u64); + w.record( + 8, + &[ + u64::from(f.ty.0), + 0, + u64::from(!f.body), + 0, + attr, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + ); + } + + // Value ids: globals, functions, constants, instructions. + let globals = self.globals.len() as u32; + let funcs = globals + self.funcs.len() as u32; + let const_id = |i: u32| u64::from(funcs + i); + w.enter(CONSTANTS_BLOCK, 4); + let mut current = None; + for (ty, c) in &self.consts { + if current != Some(*ty) { + w.record(1, &[u64::from(ty.0)]); + current = Some(*ty); + } + match c { + Const::Undef => w.record(3, &[]), + Const::Int(v) => w.record(4, &[signed(*v)]), + Const::Float(bits) => w.record(6, &[u64::from(*bits)]), + Const::Aggregate(ids) => { + let r: Vec<u64> = ids.iter().map(|&i| const_id(i)).collect(); + w.record(7, &r); + } + } + } + w.exit(); + + // Phis nothing reads are left out (one register per phi makes many). + let mut live = vec![false; self.insts.len()]; + let mark = |live: &mut Vec<bool>, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + return true; + } + false + }; + let operands = |op: &Op| -> Vec<V> { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + vec![*a, *b] + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => vec![*v], + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => vec![*a, *b, *c], + Op::Call(_, args) => args.clone(), + Op::Phi(inc) => inc.iter().map(|x| x.0).collect(), + Op::Gep(_, p, idx) => std::iter::once(*p).chain(idx.iter().copied()).collect(), + } + }; + for b in &self.blocks { + for &i in &b.body { + live[i as usize] = true; + } + if let Some(Term::CondBr(c, ..)) = b.term { + mark(&mut live, c); + } + } + let mut changed = true; + while changed { + changed = false; + for (i, inst) in self.insts.iter().enumerate() { + if live[i] { + for v in operands(&inst.op) { + changed |= mark(&mut live, v); + } + } + } + } + + // Blocks are laid out in reverse postorder, so every block follows + // its forward predecessors (drivers take a branch to an earlier + // block for a loop's back edge). + let succs = |b: usize| match self.blocks[b].term { + Some(Term::Br(t)) => vec![t], + Some(Term::CondBr(_, t, f)) => vec![t, f], + _ => vec![], + }; + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in post.iter().enumerate() { + pos[b] = n as u64; + } + // An empty latch (only a branch back to its loop header) is folded + // into its one predecessor, so the exiting block is the latch as in + // DXC's loops; the AMD driver hangs on divergent loops otherwise. + let mut preds = vec![Vec::new(); self.blocks.len()]; + for &b in &post { + for s in succs(b) { + preds[s].push(b); + } + } + let mut fold = vec![None; self.blocks.len()]; + for &b in &post { + let blk = &self.blocks[b]; + if let (Some(Term::Br(h)), true, [p]) = ( + blk.term, + blk.phis.is_empty() && blk.body.is_empty(), + &preds[b][..], + ) && pos[h] < pos[b] + && !succs(*p).contains(&h) + { + fold[b] = Some((*p, h)); + } + } + let layout: Vec<usize> = post.into_iter().filter(|&b| fold[b].is_none()).collect(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in layout.iter().enumerate() { + pos[b] = n as u64; + } + // Branch targets and phi blocks through folded latches. + let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]); + let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]); + + // Instruction value ids, in layout order. + let base = funcs + self.consts.len() as u32; + let mut ids = vec![u32::MAX; self.insts.len()]; + let mut next = base; + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + if !self.is_void(self.insts[i as usize].ty) { + ids[i as usize] = next; + next += 1; + } + } + } + let abs = |v: V| -> u32 { + match v { + V::Global(i) => i, + V::Func(i) => globals + i, + V::Const(i) => funcs + i, + V::Inst(i) => { + let id = ids[i as usize]; + assert_ne!(id, u32::MAX, "use of a void value"); + id + } + } + }; + + w.enter(METADATA_BLOCK, 3); + for m in &self.mds { + match m { + MdDef::Str(s) => w.record(1, &chars(s)), + MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]), + MdDef::Node(ops) => { + let r: Vec<u64> = ops + .iter() + .map(|o| o.map_or(0, |m| u64::from(m.0) + 1)) + .collect(); + w.record(3, &r); + } + } + } + for (name, nodes) in &self.named { + w.record(4, &chars(name)); + let r: Vec<u64> = nodes.iter().map(|m| u64::from(m.0)).collect(); + w.record(10, &r); + } + w.exit(); + // The metadata kinds an LLVM 3.7 module declares, as DXC writes them. + w.enter(METADATA_BLOCK, 3); + for (id, kind) in [ + "dbg", + "tbaa", + "prof", + "fpmath", + "range", + "tbaa.struct", + "invariant.load", + "alias.scope", + "noalias", + "nontemporal", + "llvm.mem.parallel_loop_access", + "nonnull", + "dereferenceable", + "dereferenceable_or_null", + ] + .into_iter() + .enumerate() + { + let mut r = vec![id as u64]; + r.extend(chars(kind)); + w.record(6, &r); + } + w.exit(); + + w.enter(VALUE_SYMTAB_BLOCK, 4); + let names = self.globals.iter().map(|g| &g.name); + for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() { + let mut r = vec![i as u64]; + r.extend(chars(name)); + w.record(1, &r); + } + w.exit(); + + w.enter(FUNCTION_BLOCK, 4); + w.record(1, &[layout.len() as u64]); + let mut inst_id = base; + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + let inst = &self.insts[i as usize]; + let rel = |v: V| { + let a = abs(v); + assert!(a < inst_id, "forward reference outside a phi"); + u64::from(inst_id - a) + }; + match &inst.op { + Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]), + Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]), + Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]), + Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]), + Op::Call(f, args) => { + let mut r = vec![0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]; + r.push(rel(V::Func(*f))); + r.extend(args.iter().map(|&a| rel(a))); + w.record(34, &r); + } + Op::Phi(incoming) => { + let mut r = vec![u64::from(inst.ty.0)]; + for &(v, b) in incoming { + r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); + r.push(from(b)); + } + w.record(16, &r); + } + Op::Gep(ty, p, idx) => { + let mut r = vec![0, u64::from(ty.0), rel(*p)]; + r.extend(idx.iter().map(|&i| rel(i))); + w.record(43, &r); + } + // Alignment 4 (log2 + 1), not volatile. + Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]), + Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]), + // Sequentially consistent, across threads. + Op::AtomicRmw(op, p, v) => { + w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1]) + } + Op::CmpXchg(p, c, n) => { + w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]); + } + } + if !self.is_void(inst.ty) { + inst_id += 1; + } + } + match b.term.expect("unterminated block") { + Term::Ret => w.record(10, &[]), + Term::Br(t) => w.record(11, &[target(t)]), + Term::CondBr(c, t, f) => { + let a = abs(c); + assert!(a < inst_id); + w.record(11, &[target(t), target(f), u64::from(inst_id - a)]); + } + } + } + w.exit(); + w.exit(); + w.finish() + } +} + +const MODULE_BLOCK: u64 = 8; +const PARAMATTR_BLOCK: u64 = 9; +const PARAMATTR_GROUP_BLOCK: u64 = 10; +const CONSTANTS_BLOCK: u64 = 11; +const FUNCTION_BLOCK: u64 = 12; +const VALUE_SYMTAB_BLOCK: u64 = 14; +const METADATA_BLOCK: u64 = 15; +const TYPE_BLOCK: u64 = 17; + +fn chars(s: &str) -> Vec<u64> { + s.bytes().map(u64::from).collect() +} + +/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0. +fn signed(v: i64) -> u64 { + if v >= 0 { + (v as u64) << 1 + } else { + (v.unsigned_abs() << 1) | 1 + } +} + +/// The bitstream: little-endian 32-bit words filled from bit 0. +#[derive(Default)] +struct Writer { + words: Vec<u32>, + cur: u64, + bits: u32, + /// Per open block: abbreviation width, index of its length word. + stack: Vec<(u32, usize)>, +} + +impl Writer { + fn width(&self) -> u32 { + self.stack.last().map_or(2, |b| b.0) + } + + fn emit(&mut self, v: u64, width: u32) { + debug_assert!(width == 64 || v >> width == 0); + self.cur |= v << self.bits; + self.bits += width; + while self.bits >= 32 { + self.words.push(self.cur as u32); + self.cur >>= 32; + self.bits -= 32; + } + } + + fn vbr(&mut self, mut v: u64, width: u32) { + let hi = 1u64 << (width - 1); + while v >= hi { + self.emit(v & (hi - 1) | hi, width); + v >>= width - 1; + } + self.emit(v, width); + } + + fn align(&mut self) { + if self.bits > 0 { + self.words.push(self.cur as u32); + self.cur = 0; + self.bits = 0; + } + } + + fn bytes(&mut self, b: &[u8]) { + for &x in b { + self.emit(u64::from(x), 8); + } + } + + fn enter(&mut self, id: u64, width: u32) { + self.emit(1, self.width()); // ENTER_SUBBLOCK + self.vbr(id, 8); + self.vbr(u64::from(width), 4); + self.align(); + self.words.push(0); + self.stack.push((width, self.words.len())); + } + + fn exit(&mut self) { + self.emit(0, self.width()); // END_BLOCK + self.align(); + let (_, start) = self.stack.pop().expect("open block"); + self.words[start - 1] = (self.words.len() - start) as u32; + } + + /// An unabbreviated record. + fn record(&mut self, code: u64, ops: &[u64]) { + self.emit(3, self.width()); + self.vbr(code, 6); + self.vbr(ops.len() as u64, 6); + for &o in ops { + self.vbr(o, 6); + } + } + + fn finish(mut self) -> Vec<u8> { + self.align(); + self.words.iter().flat_map(|w| w.to_le_bytes()).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vbr_and_blocks() { + let mut w = Writer::default(); + w.vbr(5, 6); + w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3 + assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12)); + let mut w = Writer::default(); + w.enter(8, 3); + w.record(1, &[1]); + w.exit(); + let bytes = w.finish(); + // header word, length word, one record word, end word. + assert_eq!(bytes.len() % 4, 0); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1); + assert_eq!(signed(-3), 7); + assert_eq!(signed(2), 4); + } +} diff --git a/crates/victory-shader/src/emit/container.rs b/crates/victory-shader/src/emit/container.rs new file mode 100644 index 0000000..b0d30f9 --- /dev/null +++ b/crates/victory-shader/src/emit/container.rs @@ -0,0 +1,380 @@ +//! The PC container around emitted DXIL: feature flags (`SFI0`), the +//! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the +//! program (`DXIL`), laid out as validator version 1.6 lays them out, plus +//! the container hash that D3D12 checks. + +/// One signature element: one row (D3D12 links stages by semantic). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SigElement { + pub name: String, + pub index: u32, + /// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...). + pub kind: u8, + /// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1). + pub comp: u8, + /// DXIL interpolation mode (0 for none). + pub interp: u8, + /// Start row, if the element has a register. + pub row: Option<u32>, + pub col: u8, + pub cols: u8, + /// Components read (inputs) or written (outputs), relative to `col`. + pub usage: u8, + /// 16-bit on the console (declared 32-bit here). + pub half: bool, +} + +impl SigElement { + fn system_value(&self) -> u32 { + match self.kind { + 1 => 6, // vertex id + 2 => 8, // instance id + 3 => 1, // position + 4 => 4, // render target array index + 5 => 5, // viewport array index + 6 => 2, // clip distance + 7 => 3, // cull distance + 10 => 7, // primitive id + 12 => 10, + 13 => 9, // front face + 14 => 66, + 15 => 70, + 16 => 64, // target + 17 => 65, // depth + 18 => 68, + 19 => 67, + 20 => 69, + 30 => 25, // cull primitive + _ => 0, + } + } + + fn sig_comp(&self) -> u32 { + match self.comp { + 1 | 5 => 1, // bool and u32 + 4 => 2, + 9 => 3, + _ => 0, + } + } + + fn mask(&self) -> u8 { + ((1u8 << self.cols) - 1) << self.col + } +} + +/// `ISG1`/`OSG1`: 32-byte rows, then the names. +pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> { + let mut out = Vec::new(); + out.extend((elements.len() as u32).to_le_bytes()); + out.extend(8u32.to_le_bytes()); + // Validator 1.6 writes one name per element in element order, repeats + // included, except that system values share theirs (it keys names by + // the semantic's string, which is one static string per system value); + // the rows sorted by register (unallocated last). + let mut offsets: Vec<u32> = Vec::new(); + let mut next = 8 + 32 * elements.len() as u32; + let mut names = Vec::new(); + for (i, e) in elements.iter().enumerate() { + let shared = (e.kind != 0) + .then(|| (0..i).find(|&j| elements[j].kind == e.kind)) + .flatten(); + match shared { + Some(j) => offsets.push(offsets[j]), + None => { + offsets.push(next); + next += e.name.len() as u32 + 1; + names.push(&e.name); + } + } + } + let mut order: Vec<usize> = (0..elements.len()).collect(); + order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col)); + for i in order { + let (e, offset) = (&elements[i], offsets[i]); + let used = e.usage << e.col; + let rw = if input { used } else { !used & 0xf }; + for v in [ + 0, + offset, + e.index, + e.system_value(), + e.sig_comp(), + e.row.unwrap_or(u32::MAX), + ] { + out.extend(v.to_le_bytes()); + } + out.extend([e.mask(), rw, 0, 0]); + out.extend(0u32.to_le_bytes()); + } + for name in names { + out.extend(name.as_bytes()); + out.push(0); + } + out +} + +/// A resource bound by register, as `PSV0` lists it. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Binding { + /// PSV resource type: 1 sampler, 2 CBV. + pub kind: u32, + pub space: u32, + pub register: u32, + /// DXIL resource kind (13 cbuffer, 14 sampler). + pub dxil_kind: u32, +} + +pub(crate) struct Psv<'a> { + /// PSV shader kind: 0 pixel, 1 vertex, 5 compute. + pub stage: u8, + /// Vertex: writes `SV_Position`. Pixel: writes depth. + pub flag: bool, + pub inputs: &'a [SigElement], + pub outputs: &'a [SigElement], + /// Mesh: per-primitive outputs. + pub prims: &'a [SigElement], + /// Mesh: its state and the group-shared bytes it declares. + pub mesh: Option<(super::shader::Mesh, u32)>, + pub bindings: &'a [Binding], + /// Compute: thread-group size and required wave size. + pub threads: [u32; 3], + pub wave_size: Option<u32>, +} + +/// `PSV0` with runtime info version 2 (validator 1.6). +pub(crate) fn psv(p: &Psv) -> Vec<u8> { + let vectors = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0) + }; + let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs)); + let mut out = Vec::new(); + let u32s = |out: &mut Vec<u8>, vs: &[u32]| { + for v in vs { + out.extend(v.to_le_bytes()); + } + }; + u32s(&mut out, &[48]); + let mut info = [0u8; 48]; + info[0] = u8::from(p.flag); + let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n)); + info[16..20].copy_from_slice(&min.to_le_bytes()); + info[20..24].copy_from_slice(&max.to_le_bytes()); + info[24] = p.stage; + for (k, n) in p.threads.into_iter().enumerate() { + info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes()); + } + info[28] = p.inputs.len() as u8; + info[29] = p.outputs.len() as u8; + info[31] = in_vectors as u8; + info[32] = out_vectors as u8; + if let Some((mesh, shared)) = p.mesh { + info[0..4].copy_from_slice(&shared.to_le_bytes()); + info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes()); + info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes()); + info[26] = vectors(p.prims) as u8; + info[27] = mesh.topology; + info[30] = p.prims.len() as u8; + } + out.extend(info); + u32s(&mut out, &[p.bindings.len() as u32]); + if !p.bindings.is_empty() { + u32s(&mut out, &[24]); + for b in p.bindings { + u32s( + &mut out, + &[b.kind, b.space, b.register, b.register, b.dxil_kind, 0], + ); + } + } + // Names of arbitrary semantics (system values use ""), then indices. + let mut strings = vec![0u8]; + let mut indices: Vec<u32> = Vec::new(); + let mut elements = Vec::new(); + for e in p.inputs.iter().chain(p.outputs).chain(p.prims) { + let name = if e.kind == 0 { + let needle: Vec<u8> = e.name.bytes().chain([0]).collect(); + match find(&strings, &needle) { + Some(at) => at, + None => { + strings.extend(&needle); + strings.len() - needle.len() + } + } + } else { + 0 + }; + let index = match indices.iter().position(|&i| i == e.index) { + Some(at) => at, + None => { + indices.push(e.index); + indices.len() - 1 + } + }; + let (start, alloc) = match e.row { + Some(r) => (r as u8, 0x40 | (e.col << 4)), + None => (0, 0), + }; + elements.push((name as u32, index as u32, start, e.cols | alloc, e)); + } + strings.resize(strings.len().next_multiple_of(4), 0); + u32s(&mut out, &[strings.len() as u32]); + out.extend(&strings); + u32s(&mut out, &[indices.len() as u32]); + u32s(&mut out, &indices); + if !elements.is_empty() { + u32s(&mut out, &[16]); + for (name, index, start, cols, e) in elements { + u32s(&mut out, &[name, index]); + out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]); + } + } + // Input-to-output dependencies, as the view-id state declares them: + // every output scalar on every input scalar. + if in_vectors > 0 && out_vectors > 0 { + let scalars = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols))) + .max() + .unwrap_or(0) + }; + let (ni, no) = (scalars(p.inputs), scalars(p.outputs)); + let per = (out_vectors * 4).div_ceil(32); + for i in 0..in_vectors * 4 { + for k in 0..per { + let bits = if i < ni { + no.saturating_sub(32 * k).min(32) + } else { + 0 + }; + let mask = if bits == 32 { + u32::MAX + } else { + (1u32 << bits) - 1 + }; + u32s(&mut out, &[mask]); + } + } + } + out +} + +fn find(hay: &[u8], needle: &[u8]) -> Option<usize> { + hay.windows(needle.len()).position(|w| w == needle) +} + +/// The container: parts in order, hashed. +pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> { + let table = 0x20 + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>(); + let mut out = Vec::with_capacity(total); + out.extend(b"DXBC"); + out.extend([0; 16]); + out.extend(1u16.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + out.extend((total as u32).to_le_bytes()); + out.extend((parts.len() as u32).to_le_bytes()); + let mut offset = table; + for (_, d) in parts { + out.extend((offset as u32).to_le_bytes()); + offset += 8 + d.len(); + } + for (fourcc, d) in parts { + out.extend(*fourcc); + out.extend((d.len() as u32).to_le_bytes()); + out.extend(*d); + } + let digest = hash(&out[20..]); + out[4..20].copy_from_slice(&digest); + out +} + +/// The container hash D3D12 checks: MD5 whose last block carries the bit +/// count first and `2 × bytes + 1` last instead of standard padding. +pub(crate) fn hash(data: &[u8]) -> [u8; 16] { + let len = data.len(); + let left = len % 64; + let mut tail = Vec::with_capacity(128); + if left < 56 { + tail.extend(((len as u32) << 3).to_le_bytes()); + tail.extend(&data[len - left..]); + tail.push(0x80); + tail.resize(60, 0); + } else { + tail.extend(&data[len - left..]); + tail.push(0x80); + tail.resize(64, 0); + tail.extend(((len as u32) << 3).to_le_bytes()); + tail.resize(124, 0); + } + tail.extend(((len as u32) << 1 | 1).to_le_bytes()); + let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476]; + for block in data[..len - left] + .as_chunks::<64>() + .0 + .iter() + .chain(tail.as_chunks::<64>().0) + { + md5_block(&mut state, block); + } + let mut out = [0; 16]; + for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) { + o.copy_from_slice(&s.to_le_bytes()); + } + out +} + +fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) { + const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]; + let x: Vec<u32> = block + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes(*c)) + .collect(); + let [mut a, mut b, mut c, mut d] = *state; + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32; + let rotated = a + .wrapping_add(f) + .wrapping_add(k) + .wrapping_add(x[g]) + .rotate_left(S[(i / 16) * 4 + i % 4]); + (a, b, c, d) = (d, b.wrapping_add(rotated), b, c); + } + for (s, v) in state.iter_mut().zip([a, b, c, d]) { + *s = s.wrapping_add(v); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn md5_core_matches_the_standard() { + // Standard MD5 of "abc" with standard padding, through md5_block. + let mut block = b"abc".to_vec(); + block.push(0x80); + block.resize(56, 0); + block.extend(24u64.to_le_bytes()); + let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476]; + md5_block(&mut state, block.as_slice().try_into().unwrap()); + let hex: String = state + .iter() + .flat_map(|s| s.to_le_bytes()) + .map(|b| format!("{b:02x}")) + .collect(); + assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72"); + } +} diff --git a/crates/victory-shader/src/emit/diff_tests.rs b/crates/victory-shader/src/emit/diff_tests.rs new file mode 100644 index 0000000..a5ad838 --- /dev/null +++ b/crates/victory-shader/src/emit/diff_tests.rs @@ -0,0 +1,1267 @@ +//! Differential tests: HLSL compiled by the console's shader compiler and +//! translated, against the same HLSL compiled for PC, both drawn (or +//! dispatched) on the host GPU with the same inputs. +//! +//! Needs `VICTORY_CONSOLE_DXC` (the console SDK's `dxc.exe`) and a PC +//! `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's); skipped +//! without them. Set `VICTORY_WARP=1` to draw on WARP. + +use std::path::{Path, PathBuf}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::host::{Draw, Host, Root}; +use super::{HostShader, RootType, translate}; + +const RS: &str = "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), \ + RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), \ + StaticSampler(s1, filter=FILTER_MIN_MAG_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_WRAP, addressV=TEXTURE_ADDRESS_MIRROR), \ + StaticSampler(s2, filter=FILTER_MIN_MAG_LINEAR_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_BORDER, addressV=TEXTURE_ADDRESS_CLAMP, \ + borderColor=STATIC_BORDER_COLOR_OPAQUE_WHITE, mipLODBias=0.5)"; + +const COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +SamplerState smp : register(s0); +struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float4 col : COLOR0; }; +[RootSignature(RS)] +V vs(float4 p : POSITION, float2 uv : TEXCOORD0) { + V o; + o.pos = p; + o.uv = uv; + o.col = float4(uv * k.xy, p.x * k.z, 1); + return o; +} +"#; + +/// Pixel shaders, each `ps`. +const CASES: &[(&str, &str)] = &[ + ( + "constant", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return float4(0.25, 0.5, 1, 0.75); }", + ), + ( + "interpolated", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return i.col * 2 - float4(i.uv, 0, 0); }", + ), + ( + "sample and branch", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float4 t = tex.Sample(smp, i.uv); + float4 r = t * i.col + k.w; + if (i.uv.x > 0.5) r.xy = sin(r.yx * 3.0); + else r.z = rcp(r.z + 2.0); + return r; + }"#, + ), + // A wave-wide range scalarises a per-pixel loop (as the title's light + // lists do): the console's 64-lane sections become host wave operations; + // the result is the same for any wave the pixel lands in. + ( + "wave range", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint idx = uint(i.pos.x * 0.37 + i.pos.y * 0.21) & 15; + uint lo = WaveActiveMin(idx), hi = WaveActiveMax(idx); + float s = 0; + for (uint n = lo; n <= hi; n++) if (n == idx) s += n * k.x; + return float4(s, lo <= idx, hi >= idx, WaveActiveCountBits(true) > 0); + }"#, + ), + ( + "uniform loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float s = 0; + for (uint n = 0; n < (asuint(k.x) & 7); n++) s += i.uv.y * n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "bit loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = p.y; + for (uint n = 0; n < (p.x & 7); n++) s = (s ^ (s << 3)) + n; + return float4(s & 255, 0, 0, 1); + }"#, + ), + ( + "integer loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "discard", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + return i.col; + }"#, + ), + ( + "immediate samplers", + r#"SamplerState point_wrap : register(s1); + SamplerState linear_border : register(s2); + [RootSignature(RS)] float4 ps(V i) : SV_Target { + return tex.Sample(point_wrap, i.uv * 3 - 1) + 2 * tex.Sample(linear_border, i.uv * 2.5 - 0.7); + }"#, + ), + ( + "loop, discard and loads", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + float4 t = tex.Load(int3(p & 3, 0)); + return float4(s, frac(i.uv.x * 7.3), max(t.x, t.y) * k.y, sqrt(abs(i.col.x)) + exp2(i.uv.y)); + }"#, + ), + ( + "level of detail", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + return float4(tex.CalculateLevelOfDetail(smp, i.uv * 4), + tex.CalculateLevelOfDetailUnclamped(smp, i.uv * 7), 0, 1); + }"#, + ), + // 16-bit outputs and inputs (one value per dword with the 2020 + // compiler; Grand Theft Auto VI's two per dword cannot be compiled + // here) and the front face. + ( + "16-bit varyings and front face", + r#"struct V16 { float4 pos : SV_Position; half2 uv : TEXCOORD0; float4 col : COLOR0; half4 h : TEXCOORD1; }; + [RootSignature(RS)] V16 vs16(float4 p : POSITION, float2 uv : TEXCOORD0) { + V16 o; + o.pos = p; + o.uv = half2(uv * k.xy); + o.col = float4(uv, p.x * k.z, 1); + o.h = half4(uv.yx * 3 - 1, k.w, p.y); + return o; + } + [RootSignature(RS)] float4 ps(V16 i, bool f : SV_IsFrontFace) : SV_Target { + float4 c = i.col * float4(i.uv, i.h.xy) + float4(i.h.zw, 0, 0); + return f ? c : -c; + }"#, + ), +]; + +const CS_RS: &str = "RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0, numDescriptors=4)), DescriptorTable(Sampler(s0)), \ + DescriptorTable(UAV(u0, numDescriptors=4)), CBV(b1), SRV(t4), \ + DescriptorTable(SRV(t0, space=2, numDescriptors=9)), \ +\ + StaticSampler(s3, filter=FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, \ + comparisonFunc=COMPARISON_LESS_EQUAL, \ + addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)"; + +const CS_COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +Buffer<float4> typed : register(t1); +struct S { float a; uint b; float2 c; }; +StructuredBuffer<S> structured : register(t2); +ByteAddressBuffer raw : register(t3); +SamplerState smp : register(s0); +SamplerComparisonState cmp : register(s3); +RWByteAddressBuffer outb : register(u0); +RWTexture2D<float4> outt : register(u1); +cbuffer R : register(b1) { float4 table[16]; }; +ByteAddressBuffer rootraw : register(t4); +// `raw`'s bytes in typed views (the formats the console's typed loads name). +Buffer<float4> unorm8x4 : register(t0, space2); +Buffer<float4> snorm16x2 : register(t1, space2); +Buffer<uint4> uint8x4 : register(t2, space2); +Buffer<float4> unorm10x3_2 : register(t3, space2); +Buffer<uint4> uint16x4 : register(t4, space2); +Buffer<float> unorm8 : register(t5, space2); +Buffer<float> half16 : register(t6, space2); +Buffer<float4> snorm8x4 : register(t7, space2); +RWTexture2D<uint> ut : register(u2); +TextureCube cubet : register(t8, space2); +#define FMT(numeric, data) ((numeric) << 4 | (data)) +#define CS [RootSignature(RS)] [numthreads(8, 8, 1)] \ + void cs(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, \ + uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) +"#; + +/// Compute shaders, each `cs`, dispatched as 2×2 groups of 8×8 threads +/// over a 16×16 texture and a 256-dword buffer. +const CS_CASES: &[(&str, &str)] = &[ + ( + "ids and stores", + r#"CS { + outb.Store(4 * (d.y * 16 + d.x), asuint(d.x * k.x + d.y)); + outt[d.xy] = float4(g.x, g.y, t.x, t.y + i); + }"#, + ), + ( + "shared memory and barrier", + r#"groupshared float lds[64]; + groupshared uint cnt; + CS { + if (i == 0) cnt = 0; + lds[i] = d.x * k.x + d.y; + GroupMemoryBarrierWithGroupSync(); + InterlockedAdd(cnt, i); + float v = lds[63 - i] + lds[(i + 9) & 63]; + GroupMemoryBarrierWithGroupSync(); + outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + outt[d.xy] = float4(v, cnt, 0, 1); + }"#, + ), + ( + "sample and divergent store", + r#"CS { + float4 s = tex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + if ((d.x ^ d.y) & 1) outt[d.xy] = s * k.y; + else outb.Store(4 * (d.y * 16 + d.x), asuint(s.x + s.w)); + }"#, + ), + ( + "buffers and root views", + r#"CS { + float4 a = typed[i & 15]; + S s = structured[(i * 3) & 7]; + uint r = raw.Load(4 * (i & 31)); + float4 c = table[d.x & 15]; + uint q = rootraw.Load(4 * ((i + 5) & 31)); + outb.Store(4 * (d.y * 16 + d.x), asuint(a.x + a.w * s.a) ^ s.b ^ r ^ q); + outt[d.xy] = c + float4(s.c, a.yz); + }"#, + ), + // (The 2020 compiler branches around every narrowed region, so these + // become branches, not guards.) + ( + "conditional memory access", + r#"CS { + float v = d.x * k.x + d.y; + if (i & 1) v = v * 3 + 1; + if (i & 4) v += tex.Load(int3(d.xy & 3, 0)).y; + if (i & 2) outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + if (i & 8) outt[d.xy] = float4(v, 0, 0, 1); + }"#, + ), + // Each side of a per-group branch leaves a compare in VCC; the select + // after the join reads the joined mask (as `postfx_splines` does). + ( + "select on joined compares", + r#"CS { + float v = d.x * k.x + d.y; + float r; + bool ok; + [branch] if ((g.x ^ g.y) & 1) { + r = sqrt(v) * k.z + sin(v * k.w); + ok = r < 5; + } else { + r = v * k.y + 1; + ok = r > -4; + } + float o = ok ? r : -1; + outb.Store(4 * (d.y * 16 + d.x), asuint(o)); + outt[d.xy] = float4(o, r, v, 1); + }"#, + ), + // One host wave of 32 lanes holds the group, as the console's wave of 64 + // does, so lane numbers agree with the PC compile. + ( + "lane reads", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID) { + float v = d.x * k.x + d.y; + float w = WaveReadLaneAt(v, 5); + uint lane = WaveGetLaneIndex(); + uint q = QuadReadAcrossX(lane * 10) + QuadReadAcrossDiagonal(lane); + outb.Store(4 * (d.y * 16 + d.x), q); + outt[d.xy] = float4(v, w, QuadReadAcrossY(v), lane); + }"#, + ), + // Bytes and halves: SDWA operand and result selection, byte permutes, + // f16 conversions. + ( + "sub-dword operations", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + float a = float(x >> 16) + float((y >> 8) & 255) * k.x; + float b = f16tof32(x >> 16) + f16tof32(y); + uint p = (x & 0xff) | ((y & 0xff) << 8) | (x & 0xff0000) | ((y >> 8) << 24); + uint q = f32tof16(a) | (f32tof16(b) << 16); + int s = int(x << 24) >> 24; + uint u = (x & 0xffff) + (y >> 16) + ((x >> 24) ^ (y & 0xffff)) + asuint(k.w) * 1000 + 77; + outb.Store4(16 * n, uint4(asuint(a), asuint(b) ^ p, q, asuint(float(s)) + u)); + }"#, + ), + // 64-bit additions (VALU carries as lane masks) and explicit gradients. + ( + "carries and gradients", + r#"CS { + uint n = d.y * 16 + d.x; + uint64_t a = (uint64_t(raw.Load(4 * (n & 31))) << 32) | raw.Load(4 * ((n * 3) & 31)); + uint64_t b = (uint64_t(raw.Load(4 * ((n * 5) & 31))) << 32) | raw.Load(4 * ((n * 7) & 31)); + uint64_t s = a + b, u = a - b; + float4 gr = tex.SampleGrad(smp, (d.xy + 0.5) / 16.0, float2(k.x, 0) * 0.1, float2(0, k.z) * 0.1); + outb.Store4(16 * n, uint4(uint(s), uint(s >> 32) ^ uint(u), uint(u >> 32), asuint(gr.x + gr.y * 3))); + }"#, + ), + // Comparison sampling at level 0 with an immediate comparison sampler. + ( + "comparison sampling", + r#"CS { + float r = tex.SampleCmpLevelZero(cmp, (d.xy + 0.25) / 15.0, k.x * d.x / 16.0); + outb.Store(4 * (d.y * 16 + d.x), asuint(r)); + }"#, + ), + // 16-bit texture results, two channels per register (`d16`). + ( + "16-bit texture reads", + r#"Texture2D<half4> htex : register(t0); + CS { + half4 a = htex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + half3 b = htex.Load(int3(d.xy & 3, 0)).xyz; + outb.Store4(16 * (d.y * 16 + d.x), uint4(asuint(float(a.x) + a.w), + asuint(float(a.y) * a.z), asuint(float(b.x)), asuint(float(b.y) - b.z))); + }"#, + ), + // Sizes: the console compiler computes them from descriptor bits + // (width, height, levels, record counts). + ( + "sizes from descriptors", + r#"CS { + uint w, h, l, n, b, ns, st; + tex.GetDimensions(0, w, h, l); + typed.GetDimensions(n); + raw.GetDimensions(b); + structured.GetDimensions(ns, st); + // Read too: the translation takes the views' kinds from those reads. + float r = tex.Load(int3(d.xy & 3, 0)).x + typed[i & 15].y + structured[i & 7].a; + outb.Store4(16 * (d.y * 16 + d.x), + uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); + }"#, + ), + // Typed loads (`tbuffer_load_format_*`, Grand Theft Auto VI's vertex + // fetch) convert by the format the instruction names: the PC reads the + // same bytes through typed views in those formats. Channels past the + // format's read (0, 0, 0, 1); a byte format at unaligned offsets. + ( + "typed loads", + r#"CS { + uint n = d.y * 16 + d.x, e = n & 31, f = n >> 5; + uint4 a, b, c, dd, ee, ff, gg, hh; + #ifdef CONSOLE + a = raw.XB_TypedLoad4(4 * e, FMT(0, 10)); + b = raw.XB_TypedLoad4(4 * e, FMT(1, 5)); + c = raw.XB_TypedLoad4(4 * e, FMT(4, 10)); + dd = raw.XB_TypedLoad4(4 * e, FMT(0, 9)); + ee = raw.XB_TypedLoad4(8 * (e & 15), FMT(4, 12)); + ff = uint4(raw.XB_TypedLoad((3 * e) & 127, FMT(0, 1)), 0, 0, 0); + gg = uint4(raw.XB_TypedLoad2(2 * e, FMT(7, 2)), 0, 0); + hh = raw.XB_TypedLoad4(4 * e, FMT(1, 10)); + #else + a = asuint(unorm8x4[e]); + b = asuint(snorm16x2[e]); + c = uint8x4[e]; + dd = asuint(unorm10x3_2[e]); + ee = uint16x4[e & 15]; + ff = uint4(asuint(unorm8[(3 * e) & 127]), 0, 0, 0); + gg = uint4(asuint(half16[e]), 0, 0, 0); + hh = asuint(snorm8x4[e]); + #endif + uint4 v = f == 0 ? a : f == 1 ? b : f == 2 ? c : f == 3 ? dd + : f == 4 ? ee : f == 5 ? ff : f == 6 ? gg : hh; + outb.Store4(16 * n, v); + }"#, + ), + // Wave operations: the console expands them into whole-wave sections + // (DPP, `v_permlanex16`, lane reads) and lane masks read as numbers + // (`s_bcnt1`, `s_ff1`, `v_mbcnt`). 32 threads: one wave on the console + // (lanes 32-63 inactive) and on the host; the branch leaves lanes out. + ( + "wave operations", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) { + uint n = d.y * 16 + d.x; + float v = d.x * k.x + d.y; + uint u = raw.Load(4 * (i & 31)); + uint4 o = 0; + if (u & 3) { + o.x = WaveActiveSum(u >> 8) + WaveActiveCountBits((u & 4) != 0); + o.y = asuint(WaveActiveMax(v)) ^ WaveActiveMin(u) ^ WaveActiveBitOr(u) + ^ WaveActiveBitAnd(u | 1) ^ asuint(WaveActiveMin(v)) ^ WaveActiveMax(int(u)); + o.z = WavePrefixSum(u & 255) + WavePrefixCountBits(v > 2) * 1000; + // (The PC compile evaluates a wave operation in a `?:` arm + // in that arm's lanes only, so it stays outside.) + o.w = asuint(WaveActiveSum(v)) + (WaveIsFirstLane() ? WaveReadLaneFirst(u) : 0); + } + outb.Store4(16 * n, o); + }"#, + ), + // Atomics the console aggregates per wave (one add of the lane count, + // each lane's offset from `v_mbcnt`), and texture atomics. Results + // that depend on the lanes' order are left out. + ( + "aggregated and texture atomics", + r#"CS { + uint u = raw.Load(4 * (i & 31)), r, q; + outb.InterlockedAdd(0, 1, r); + outb.InterlockedAdd(4 * (1 + r % 8), 1); + if (u & 1) outb.InterlockedAdd(64, u & 255); + uint2 p = d.xy & 3; + InterlockedMax(ut[p], u); + InterlockedOr(ut[p + uint2(4, 0)], u >> (i & 7)); + InterlockedMin(ut[p + uint2(8, 0)], u); + InterlockedAdd(ut[p + uint2(12, 0)], u & 15, q); + InterlockedXor(ut[p + uint2(0, 4)], u); + }"#, + ), + // A loop whose count comes from a view that reads zeros (as a null or + // not yet mirrored one does) runs four billion times on the console; + // the translation leaves it after `LOOP_LIMIT` iterations. Run on WARP + // only (`VICTORY_WARP=1`), ours only: without the limit it would hang + // the GPU. + ( + "terminates on zero data", + r#"CS { + uint cnt = outb.Load(4 * 1000), s = d.x; + for (uint j = 0; j != cnt - 1; j++) s = s * 3 + raw.Load(4 * (j & 31)); + outb.Store(4 * (d.y * 16 + d.x), s); + }"#, + ), + // Cube sampling: the console computes face coordinates (`v_cube*`) + // and samples the face; the host samples the direction rebuilt from + // them. Every face and texel: a major axis of ±2 and the others at + // texel centres, so both sides compute them exactly. + ( + "cube sampling", + r#"CS { + float sg = (i & 8) ? -2 : 2; + float a = (d.x & 3) - 1.5, b = (d.y & 3) - 1.5; + uint ax = i % 3; + float3 dir = ax == 0 ? float3(sg, a, b) : ax == 1 ? float3(a, sg, b) : float3(a, b, sg); + float4 p = cubet.SampleLevel(smp, dir, 0); + float4 q = cubet.SampleLevel(smp, -dir.zxy, 0); + outb.Store4(16 * (d.y * 16 + d.x), asuint(p + q * 3)); + }"#, + ), + // A local array indexed per lane (M0-relative VGPR moves), bit fields + // and first bits from the top. + ( + "indexed registers and bit fields", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 5) & 31)); + uint arr[24]; + [unroll] for (uint j = 0; j < 24; j++) arr[j] = x ^ (j * 0x01010101); + [loop] for (uint m = 0; m < (y & 3); m++) arr[(y >> (m * 5)) % 24] = y + m; + uint v = arr[(x >> 3) % 24]; + uint w = asuint(k.x) & 31, o = n & 15; + uint bf = (x & ((1u << w) - 1)) << o; + uint fb = firstbithigh(asuint(k.y)) + firstbithigh(x) * 3 + firstbithigh(int(y)) * 7; + outb.Store4(16 * n, uint4(v, bf, fb, arr[n % 24])); + }"#, + ), + // Size queries at a level known per lane (`image_get_resinfo`). + ( + "size queries", + r#"CS { + uint w, h, l, cw, ch, cl; + tex.GetDimensions(d.x >> 4, w, h, l); + cubet.GetDimensions(d.y >> 4, cw, ch, cl); + float r = tex.Load(int3(d.xy & 3, 0)).x; + outb.Store4(16 * (d.y * 16 + d.x), uint4(w * 7 + h, l + asuint(r), cw * 3 + ch, cl)); + }"#, + ), + // Gathers with offsets computed per lane (programmable offsets). + ( + "gather with offsets", + r#"CS { + int2 o = int2(int(d.x & 7) - 4, int(d.y % 5) - 2); + float4 r = tex.GatherRed(smp, (d.xy + 0.5) / 16.0, o); + float4 q = tex.GatherGreen(smp, (d.yx + 0.25) / 16.0, -o); + outb.Store4(16 * (d.y * 16 + d.x), asuint(r + q * 3)); + }"#, + ), + // Constant arrays: the console compiler appends them to the code and + // reads them through `s_getpc_b64` (scalar loads for a uniform index, + // global loads per lane, 16-bit ones too). + ( + "constant tables", + r#"static const uint tbl[16] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3 }; + static const float ftbl[8] = { 0.5, -1, 2.25, 3, -4.5, 6, 7.75, -8 }; + // (16-bit types: compiled with half precision enabled.) + static const uint16_t stbl[12] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 65535 }; + CS { + uint n = d.y * 16 + d.x; + uint u = asuint(k.x) & 15; + uint a = tbl[i & 15] ^ tbl[u] << 8; + float f = ftbl[(i * 3) & 7] * ftbl[u & 7]; + uint h = stbl[(n * 5) % 12] + stbl[u % 12]; + outb.Store4(16 * n, uint4(a, asuint(f), h, tbl[(n + u) & 15])); + }"#, + ), + // 16-bit arithmetic (scalar and packed), 16-bit compares, typed stores + // of halves (`buffer_store_format_d16`), 64-bit shifts and compares. + ( + "16-bit and 64-bit arithmetic", + r#"RWBuffer<half4> hb : register(u3); + CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + half a = half(d.x * k.x - 2), b = half(d.y + k.y), c = half(k.z); + half2 p = half2(a, b) * half2(b, c) + half2(c, a); + half m = max(a, b) - min(a, c) * a; + bool lt = a < b, ge = p.x >= p.y; + hb[n] = half4(p.x, m, lt ? a : b, ge ? p.y : a - b); + uint64_t q = (uint64_t(x) << (n & 31)) | y, w = uint64_t(y) << 3; + uint z = q < w ? 1 : q == w ? 2 : 3; + outb.Store2(8 * n, uint2(uint(q >> 7) ^ z, uint(w >> (n & 15)))); + }"#, + ), +]; + +const MS_COMMON: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0)" +cbuffer K : register(b0) { float4 k; }; +struct V { float4 pos : SV_Position; float4 col : COLOR0; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] float4 mps(V i) : SV_Target { return i.col + float4(i.uv, 0, 0); } +#define MS_ATTR [RootSignature(RS)] [outputtopology("triangle")] +"#; + +/// Mesh shaders, each `ms` (the console runs one thread per output lane, so +/// groups of 32 run as 64 lanes there), with their group counts. Drawn +/// with `mps` into 16×16 targets. The 2020 compiler's containers do not +/// record the thread count, so cases reading the group id keep +/// max(threads, vertices, primitives) at the lane count (see `emit`). +const MS_CASES: &[(&str, u32, &str)] = &[ + ( + "one triangle", + 1, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[3], out indices uint3 tris[1]) { + SetMeshOutputCounts(3, 1); + if (i < 3) { + verts[i].pos = float4(i == 1 ? 3 : -1, i == 2 ? 3 : -1, 0.5, 1); + verts[i].col = float4(k.x * i, k.y, k.z * (i == 2), 1); + verts[i].uv = float2(i * 0.5, k.w); + } + if (i == 0) tris[0] = uint3(0, 1, 2); + }"#, + ), + // A quad per group in its quadrant; a run-time vertex count, and a + // primitive count per group whose third triangle is culled. + ( + "groups, counts and culling", + 4, + r#"struct P { bool cull : SV_CullPrimitive; }; + MS_ATTR [numthreads(64, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[8], + out indices uint3 tris[4], out primitives P prims[4]) { + uint nv = 4 + (k.z > 1); + uint np = 2 + (g.x & 1); + SetMeshOutputCounts(nv, np); + float2 o = float2(g.x & 1, g.x >> 1) - 1; + if (i < nv) { + float2 p = i < 4 ? float2(i & 1, i >> 1) : float2(-0.75, 0.5); + verts[i].pos = float4(o + p, 0.5, 1); + verts[i].col = float4(k.x * i, g.x * 0.25, k.z, 1); + verts[i].uv = float2(i, g.x); + } + if (i < np) { + tris[i] = i == 0 ? uint3(0, 1, 2) : i == 1 ? uint3(1, 3, 2) : uint3(1, 4, 3); + prims[i].cull = i == 2; + } + }"#, + ), + // Two waves per group, as Grand Theft Auto VI's mesh programs run: the + // second wave's lanes are threads 64-127. + ( + "two waves", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(p.x * k.x, p.y, (i & 7) * 0.125, 1); + verts[i].uv = float2(i, k.y); + } + uint c = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); + }"#, + ), + // Quad reads (DPP quad permutations on the console; Grand Theft Auto VI's + // tessellating mesh programs swizzle within quads too). + ( + "quad reads", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + float w = i * k.x + k.y; + float a = QuadReadLaneAt(w, 0); + float b = QuadReadLaneAt(w, 2); + float c = QuadReadAcrossX(w); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(a, b, c, 1); + verts[i].uv = float2(i, k.y); + } + uint cc = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(cc + 1, cc + 10, cc + 9) : uint3(cc, cc + 1, cc + 9); + }"#, + ), + // Vertices and indices written by other threads than their lanes: the + // console passes them through shared memory, with a loop and barriers. + ( + "grid through shared memory", + 2, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[36], + out indices uint3 tris[64]) { + SetMeshOutputCounts(36, 50); + for (uint v = i; v < 36; v += 32) { + float2 p = float2(v % 6, v / 6) / 5.0; + verts[v].pos = float4(p.x - g.x, p.y * 2 - 1, 0.5, 1); + verts[v].col = float4(p * k.x, k.z * g.x, 1); + verts[v].uv = float2(v, k.y); + } + if (i < 25) { + uint c = i % 5 + i / 5 * 6; + tris[2 * i] = uint3(c, c + 1, c + 6); + tris[2 * i + 1] = uint3(c + 1, c + 7, c + 6); + } + }"#, + ), +]; + +fn tools() -> Option<(PathBuf, PathBuf)> { + let console = PathBuf::from(std::env::var_os("VICTORY_CONSOLE_DXC")?); + let pc = match std::env::var_os("VICTORY_PC_DXC") { + Some(p) => PathBuf::from(p), + None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"), + }; + (console.exists() && pc.exists()).then_some((console, pc)) +} + +fn compile(dxc: &Path, dir: &Path, src: &str, entry: &str, profile: &str) -> Vec<u8> { + let input = dir.join("t.hlsl"); + let output = dir.join(format!("{entry}.bin")); + let text = if entry == "cs" { + format!("#define RS \"{CS_RS}\"\n{CS_COMMON}\n{src}\n") + } else if entry.starts_with('m') { + format!("{MS_COMMON}\n{src}\n") + } else { + format!("#define RS \"{RS}\"\n{COMMON}\n{src}\n") + }; + std::fs::write(&input, text).unwrap(); + let out = std::process::Command::new(dxc) + .args(["-T", profile, "-E", entry, "-Fo"]) + .arg(&output) + .arg(&input) + .args(src.contains("half").then_some("-enable-16bit-types")) + // `CONSOLE` marks the console compile (cases spell console-only + // intrinsics there). + .args( + std::env::var_os("VICTORY_CONSOLE_DXC") + .is_some_and(|c| Path::new(&c) == dxc) + .then_some("-DCONSOLE"), + ) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(output).unwrap() +} + +/// Root arguments for a translated stage: user data from the root values. +fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec<u32> { + let mut data = vec![0; (s.user_data_dwords() as usize).max(1)]; + for u in &s.user_data { + data[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => k[u.dword as usize], + // The texture and sampler tables start at heap index 1, the UAV + // table (compute) at 5, in the console's units. + (RootType::Table, 1) => 32, + (RootType::Table, 2) => 16, + (RootType::Table, 3) => 5 * 32, + // The typed views of `raw` (compute) from 9. + (RootType::Table, 6) => 9 * 32, + other => panic!("unexpected user data {other:?}"), + }; + } + data +} + +#[test] +fn translated_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| { + [ + i as f32 / 16.0, + (i % 4) as f32 * 0.3, + 1.0 - i as f32 / 20.0, + 0.5, + ] + }) + .collect(); + let dummy = [[9.0f32; 4]]; + let sampler = |filter, address| D3D12_SAMPLER_DESC { + Filter: filter, + AddressU: address, + AddressV: address, + AddressW: address, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let samplers = [ + sampler( + D3D12_FILTER_MIN_MAG_MIP_POINT, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ), + sampler( + D3D12_FILTER_MIN_MAG_MIP_LINEAR, + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + ), + ]; + // A full-screen triangle: POSITION (4 floats), TEXCOORD0 (2 floats). + let vertices = [ + -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // + -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, // + 3.0, -1.0, 0.5, 1.0, 2.0, 1.0, + ]; + let textures: [(u32, u32, &[[f32; 4]]); 2] = [(1, 1, &dummy), (4, 4, &texels)]; + let draw = |roots| Draw { + roots, + textures: &textures, + samplers: &samplers, + vertices: &vertices, + stride: 24, + size: (16, 16), + mesh_groups: 0, + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + for (name, src) in CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + // A case may bring its own vertex shader. + let vs = if src.contains(" vs16(") { "vs16" } else { "vs" }; + let vs_c = translate(&compile(&console, &dir, src, vs, "vs_6_5")).unwrap(); + let ps_c = match translate(&compile(&console, &dir, src, "ps", "ps_6_5")) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write( + format!("{out}/{stem}.ps.cdxil"), + compile(&console, &dir, src, "ps", "ps_6_5"), + ) + .unwrap(); + std::fs::write(format!("{out}/{stem}.ps.dxil"), &ps_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + for s in [&vs_c, &ps_c] { + v.validate(&mut s.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + let (root_t, pso_t) = host.pipeline(&vs_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw(vec![ + (0, Root::Constants(user_data(&vs_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ]), + ) + .unwrap(); + + let (vs_p, ps_p) = ( + compile(&pc, &dir, src, vs, "vs_6_5"), + compile(&pc, &dir, src, "ps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ps_p) }.unwrap(); + let pso_p = host.pipeline_with(&root_p, &vs_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![ + (0, Root::Constants(k.to_vec())), + ( + 1, + Root::Table { + sampler: false, + index: 1, + }, + ), + ( + 2, + Root::Table { + sampler: true, + index: 1, + }, + ), + ]), + ) + .unwrap(); + + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + eprintln!( + "{name}: worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 { + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +#[test] +fn translated_mesh_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-ms-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let draw = |roots, mesh_groups| Draw { + roots, + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups, + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + for &(name, groups, src) in MS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + let console_ms = compile(&console, &dir, src, "ms", "ms_6_5"); + let ms_c = match translate(&console_ms) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + let ps_c = translate(&compile(&console, &dir, src, "mps", "ps_6_5")).unwrap(); + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.ms.cdxil"), &console_ms).unwrap(); + std::fs::write(format!("{out}/{stem}.ms.dxil"), &ms_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut ms_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = host.mesh_pipeline(&ms_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw( + vec![ + (0, Root::Constants(user_data(&ms_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ], + groups, + ), + ) + .unwrap(); + let (ms_p, ps_p) = ( + compile(&pc, &dir, src, "ms", "ms_6_5"), + compile(&pc, &dir, src, "mps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ms_p) }.unwrap(); + let pso_p = host.mesh_pipeline_with(&root_p, &ms_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![(0, Root::Constants(k.to_vec()))], groups), + ) + .unwrap(); + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + let drawn = theirs.iter().filter(|t| t[3] != 0.0).count(); + eprintln!( + "{name}: {drawn} texels drawn; worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 || drawn == 0 { + // Which texels each drew (alpha set), row by row. + for (o, t) in ours.chunks(16).zip(theirs.chunks(16)) { + let row = |r: &[[f32; 4]]| -> String { + r.iter() + .map(|x| if x[3] != 0.0 { '#' } else { '.' }) + .collect() + }; + eprintln!(" {} {}", row(o), row(t)); + } + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Where PC code and the console differ by design, the translation must +/// give the console's results: float-to-int conversions saturate and give +/// 0 for NaN (`v_cvt_i32/u32_f32`), and the legacy multiply the compiler +/// uses for `*` gives 0 for 0 × NaN. +#[test] +fn float_semantics_are_the_consoles() { + use super::host::{Dispatch, View}; + let Some((console, _)) = tools() else { + eprintln!("no console compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-float-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let src = r#"[RootSignature(RS)] [numthreads(4, 1, 1)] + void cs(uint i : SV_GroupIndex) { + float x = i == 0 ? k.x : i == 1 ? -k.x : i == 2 ? k.y : k.z; + outb.Store(4 * i, asuint(int(x))); + outb.Store(16 + 4 * i, uint(x)); + outb.Store(32 + 4 * i, asuint(x * k.w)); + }"#; + let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap(); + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + // 1e30, NaN, 3.5, 0. + let k = [1e30f32.to_bits(), 0x7FC0_0000, 3.5f32.to_bits(), 0]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::RawUav(12), + View::TextureUav(1, 1), + ]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(user_data(&cs, &k)))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + out[0], + [ + 0x7FFF_FFFF, + 0x8000_0000, + 0, + 3, // int + u32::MAX, + 0, + 0, + 3, // uint + 0, + 0, + 0, + 0, // x * 0, NaN included + ] + ); +} + +/// Equal bits, both zero (the console's legacy multiply gives +0 where PC +/// code gives -0), or two normal floats within 1e-3 relative. +fn close(a: u32, b: u32) -> bool { + let (x, y) = (f32::from_bits(a), f32::from_bits(b)); + a == b + || x == 0.0 && y == 0.0 + || x.is_normal() && y.is_normal() && (x - y).abs() <= 1e-3 * y.abs().max(1.0) +} + +#[test] +fn translated_compute_matches_pc() { + use super::host::{Dispatch, Stride, View}; + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("victory-diff-cs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| [i as f32 / 16.0, (i % 4) as f32 * 0.3, 0.5, 1.0]) + .collect(); + let dummy = [[9.0f32; 4]]; + let cube_texels: Vec<[f32; 4]> = (0..96) + .map(|i| { + [ + (i / 16) as f32, + (i % 4) as f32 * 0.25, + (i / 4 % 4) as f32 * 0.25, + 1.0, + ] + }) + .collect(); + // Buffers: 16 float4, 8 structures of 16 bytes, 32 raw dwords; the + // root CBV's 16 float4 and the root SRV's 32 dwords. + let floats = |n: usize, scale: f32| -> Vec<u32> { + (0..n).map(|i| (i as f32 * scale - 3.0).to_bits()).collect() + }; + let typed_data = floats(64, 0.25); + let structured_data: Vec<u32> = (0..32u32) + .map(|i| { + if i % 4 == 1 { + i * 0x0101_0101 + } else { + (i as f32 * 0.5).to_bits() + } + }) + .collect(); + let raw_data: Vec<u32> = (0..32u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect(); + let views = [ + View::Texture(1, 1, &dummy), + View::Texture(4, 4, &texels), + View::Buffer { + data: &typed_data, + stride: Stride::Typed, + }, + View::Buffer { + data: &structured_data, + stride: Stride::Structured(16), + }, + View::Buffer { + data: &raw_data, + stride: Stride::Raw, + }, + View::RawUav(1024), + View::TextureUav(16, 16), + View::UintTextureUav(16, 16), + View::HalfUav(256), + ]; + let typed_view = |format, bytes| View::Buffer { + data: &raw_data, + stride: Stride::Format(format, bytes), + }; + let views: Vec<View> = views + .into_iter() + .chain([ + typed_view(DXGI_FORMAT_R8G8B8A8_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16_SNORM, 4), + typed_view(DXGI_FORMAT_R8G8B8A8_UINT, 4), + typed_view(DXGI_FORMAT_R10G10B10A2_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16B16A16_UINT, 8), + typed_view(DXGI_FORMAT_R8_UNORM, 1), + typed_view(DXGI_FORMAT_R16_FLOAT, 2), + typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4), + View::Cube(4, &cube_texels), + ]) + .collect(); + let root_cbv = floats(64, -0.125); + let root_srv: Vec<u32> = (0..32u32).map(|i| i * 0x0001_0003 + 7).collect(); + let samplers = [D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_POINT, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; 2]; + let dispatch = |roots| Dispatch { + roots, + views: &views, + samplers: &samplers, + groups: [2, 2, 1], + }; + let mut failures = Vec::new(); + let only = std::env::var("VICTORY_DIFF_ONLY").ok(); + let warp = std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); + for (name, src) in CS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + .filter(|c| warp || !c.0.starts_with("terminates")) + { + let console_cs = compile(&console, &dir, src, "cs", "cs_6_5"); + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.cdxil"), &console_cs).unwrap(); + } + let cs_c = match translate(&console_cs) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("VICTORY_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.dxil"), &cs_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut cs_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = match host.compute_pipeline(&cs_c) { + Ok(p) => p, + // WARP runs no fixed wave size of 64. + Err(e) if std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1") => { + eprintln!("{name}: skipped on WARP ({e})"); + continue; + } + Err(e) => panic!("{name}: {e}"), + }; + // Our root views follow the user data in root parameter order. + let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))]; + let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); + root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); + root_views.sort_unstable(); + for (n, (slot, srv)) in root_views.into_iter().enumerate() { + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + let data = if srv { + root_srv.clone() + } else { + root_cbv.clone() + }; + roots.push((1 + n as u32, Root::View { srv, data })); + } + let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots)); + if name.starts_with("terminates") { + match ours { + Ok(_) => eprintln!("{name}: finished"), + Err(e) => failures.push(format!("{name}: {e}")), + } + continue; + } + let ours = ours.unwrap(); + let cs_p = compile(&pc, &dir, src, "cs", "cs_6_5"); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &cs_p) }.unwrap(); + let pso_p = host.compute_pipeline_with(&root_p, &cs_p).unwrap(); + let table = |sampler, index| Root::Table { sampler, index }; + let theirs = host + .dispatch( + &root_p, + &pso_p, + &dispatch(vec![ + (0, Root::Constants(k.to_vec())), + (1, table(false, 1)), + (2, table(true, 1)), + (3, table(false, 5)), + ( + 4, + Root::View { + srv: false, + data: root_cbv.clone(), + }, + ), + ( + 5, + Root::View { + srv: true, + data: root_srv.clone(), + }, + ), + (6, table(false, 9)), + ]), + ) + .unwrap(); + let mismatch = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .find(|(_, (a, b))| !close(**a, **b)); + match mismatch { + None => eprintln!("{name}: equal"), + Some((at, (a, b))) => failures.push(format!( + "{name}: word {at}: {a:#x} ({}) vs {b:#x} ({})", + f32::from_bits(*a), + f32::from_bits(*b) + )), + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/victory-shader/src/emit/host.rs b/crates/victory-shader/src/emit/host.rs new file mode 100644 index 0000000..dabd4a4 --- /dev/null +++ b/crates/victory-shader/src/emit/host.rs @@ -0,0 +1,1381 @@ +//! Host D3D12 checks for emitted shaders: pipeline creation and, for +//! tests, drawing a full-screen triangle and reading the target back. + +use std::ffi::CString; + +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::{Interface, PCSTR}; + +use super::HostShader; +use super::container::SigElement; +use crate::dxbc::{Container, FourCC}; + +pub struct Host { + pub device: ID3D12Device, +} + +/// What the stage declares that a pipeline must match. +fn sig(dxil: &[u8], fourcc: FourCC) -> Result<Vec<SigElement>, String> { + let c = Container::parse(dxil).map_err(|e| e.to_string())?; + match c.part(fourcc) { + Some(p) => super::signature(p.data).map_err(|e| e.to_string()), + None => Ok(Vec::new()), + } +} + +fn format(e: &SigElement) -> DXGI_FORMAT { + let i = usize::from(e.cols.clamp(1, 4)) - 1; + match e.comp { + 9 => [ + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32B32A32_FLOAT, + ][i], + 4 => [ + DXGI_FORMAT_R32_SINT, + DXGI_FORMAT_R32G32_SINT, + DXGI_FORMAT_R32G32B32_SINT, + DXGI_FORMAT_R32G32B32A32_SINT, + ][i], + _ => [ + DXGI_FORMAT_R32_UINT, + DXGI_FORMAT_R32G32_UINT, + DXGI_FORMAT_R32G32B32_UINT, + DXGI_FORMAT_R32G32B32A32_UINT, + ][i], + } +} + +fn target_format(e: &SigElement) -> DXGI_FORMAT { + match e.comp { + 9 => DXGI_FORMAT_R32G32B32A32_FLOAT, + 4 => DXGI_FORMAT_R32G32B32A32_SINT, + _ => DXGI_FORMAT_R32G32B32A32_UINT, + } +} + +fn err(e: windows::core::Error) -> String { + e.message().to_string() +} + +impl Host { + /// The default adapter, or WARP with `warp` (or `VICTORY_WARP=1`). + pub fn new(warp: bool) -> Result<Self, String> { + let warp = warp || std::env::var("VICTORY_WARP").is_ok_and(|v| v == "1"); + // SAFETY: plain D3D12/DXGI calls with valid out pointers. + unsafe { + let mut device: Option<ID3D12Device> = None; + if warp { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + } else { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + } + let device = device.ok_or("no device")?; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + .map_err(err)?; + if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return Err(format!( + "the device supports SM {:#x} only", + sm.HighestShaderModel.0 + )); + } + Ok(Host { device }) + } + } + + /// The root signature translated shaders expect: user data per stage + /// at `b0`, immediate samplers per stage at `s<n>`, heaps directly + /// indexed. + pub fn root_signature( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result<ID3D12RootSignature, String> { + self.root_signature_for(&[ + (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) + } + + /// The root signature for these stages: user data of stage k is root + /// parameter k, root views follow. + pub fn root_signature_for( + &self, + stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], + ) -> Result<ID3D12RootSignature, String> { + let mut params: Vec<D3D12_ROOT_PARAMETER1> = stages + .iter() + .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: super::USER_DATA_SPACE, + Num32BitValues: s.user_data_dwords().max(1), + }, + }, + ShaderVisibility: vis, + }) + .collect(); + let mut views: Vec<(u8, bool)> = stages + .iter() + .flat_map(|(s, _)| { + let cbvs = s.root_cbvs.iter().map(|&r| (r, false)); + cbvs.chain(s.root_srvs.iter().map(|&r| (r, true))) + }) + .collect(); + views.sort_unstable(); + views.dedup(); + for (slot, srv) in views { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: if srv { + D3D12_ROOT_PARAMETER_TYPE_SRV + } else { + D3D12_ROOT_PARAMETER_TYPE_CBV + }, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: super::ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let mut samplers = Vec::new(); + for &(s, vis) in stages { + for (n, d) in s.static_samplers.iter().enumerate() { + let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(d.filter as i32), + AddressU: u, + AddressV: v, + AddressW: w, + MipLODBias: d.mip_lod_bias, + MaxAnisotropy: d.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(d.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(d.border as i32), + MinLOD: d.min_lod, + MaxLOD: d.max_lod, + ShaderRegister: n as u32, + RegisterSpace: super::SAMPLER_SPACE, + ShaderVisibility: vis, + }); + } + } + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays. + unsafe { + let mut blob = None; + let mut error = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) + .map_err(err)?; + let blob: ID3DBlob = blob.ok_or("no root signature blob")?; + let bytes = std::slice::from_raw_parts( + blob.GetBufferPointer().cast::<u8>(), + blob.GetBufferSize(), + ); + self.device.CreateRootSignature(0, bytes).map_err(err) + } + } + + /// A compute pipeline; user data is root parameter 0. + pub fn compute_pipeline( + &self, + cs: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)])?; + let pso = self.compute_pipeline_with(&root, &cs.dxil)?; + Ok((root, pso)) + } + + pub fn compute_pipeline_with( + &self, + root: &ID3D12RootSignature, + cs: &[u8], + ) -> Result<ID3D12PipelineState, String> { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + // SAFETY: the description points at live data. + unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(err) + } + + /// A graphics pipeline from a vertex and a pixel shader, with float or + /// integer 32-bit targets as the pixel shader writes them. + pub fn pipeline( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature(vs, ps)?; + let pso = self.pipeline_with(&root, &vs.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A graphics pipeline with the given root signature; vertex inputs + /// packed in register order. + pub fn pipeline_with( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + let inputs = sig(vs, FourCC::ISG1)?; + let names: Vec<CString> = inputs + .iter() + .map(|e| CString::new(e.name.clone()).unwrap()) + .collect(); + let layout: Vec<D3D12_INPUT_ELEMENT_DESC> = inputs + .iter() + .zip(&names) + .filter(|(e, _)| e.kind == 0) + .map(|(e, n)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(n.as_ptr().cast()), + SemanticIndex: e.index, + Format: format(e), + InputSlot: 0, + AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }) + .collect(); + let outputs = sig(ps, FourCC::OSG1)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: layout.as_ptr(), + NumElements: layout.len() as u32, + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + for rt in &mut desc.BlendState.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + desc.RTVFormats[n] = target_format(o); + desc.NumRenderTargets = desc.NumRenderTargets.max(n as u32 + 1); + } + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + desc.DepthStencilState.StencilEnable = true.into(); + } + // SAFETY: the description points at live data. + let pso = unsafe { self.device.CreateGraphicsPipelineState(&desc) }; + pso.map_err(err) + } + + /// A mesh pipeline from a mesh and a pixel shader (user data of the mesh + /// stage is root parameter 0, the pixel stage's 1). + pub fn mesh_pipeline( + &self, + ms: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[ + (ms, D3D12_SHADER_VISIBILITY_MESH), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ])?; + let pso = self.mesh_pipeline_with(&root, &ms.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A mesh pipeline with the given root signature: the pipeline-state + /// stream form, with the targets [`Host::pipeline_with`] would use. + pub fn mesh_pipeline_with( + &self, + root: &ID3D12RootSignature, + ms: &[u8], + ps: &[u8], + ) -> Result<ID3D12PipelineState, String> { + /// A stream subobject: its type, then its description, pointer-aligned. + #[repr(C, align(8))] + struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub<D3D12_SHADER_BYTECODE>, + ps: Sub<D3D12_SHADER_BYTECODE>, + blend: Sub<D3D12_BLEND_DESC>, + mask: Sub<u32>, + raster: Sub<D3D12_RASTERIZER_DESC>, + depth: Sub<D3D12_DEPTH_STENCIL_DESC>, + targets: Sub<D3D12_RT_FORMAT_ARRAY>, + dsv: Sub<DXGI_FORMAT>, + samples: Sub<DXGI_SAMPLE_DESC>, + } + let outputs = sig(ps, FourCC::OSG1)?; + let mut blend = D3D12_BLEND_DESC::default(); + for rt in &mut blend.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + let mut targets = D3D12_RT_FORMAT_ARRAY::default(); + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + targets.RTFormats[n] = target_format(o); + targets.NumRenderTargets = targets.NumRenderTargets.max(n as u32 + 1); + } + let mut depth = D3D12_DEPTH_STENCIL_DESC::default(); + let mut dsv = DXGI_FORMAT_UNKNOWN; + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + dsv = DXGI_FORMAT_D32_FLOAT; + depth.DepthEnable = true.into(); + depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + dsv = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth.StencilEnable = true.into(); + } + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + ), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, depth), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + targets, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + dsv, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::<Stream>(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let device: ID3D12Device2 = self.device.cast().map_err(err)?; + // SAFETY: the stream points at live data and outlives the call. + unsafe { device.CreatePipelineState(&desc) }.map_err(err) + } +} + +/// A vertex shader that feeds `ps`'s inputs (zeros) and a position. +pub fn stub_vs(ps: &HostShader) -> Result<HostShader, String> { + let inputs = sig(&ps.dxil, FourCC::ISG1)?; + let mut outputs: Vec<SigElement> = inputs + .into_iter() + .filter(|e| matches!(e.kind, 0 | 3 | 6 | 7)) + .collect(); + if !outputs.iter().any(|e| e.kind == 3) { + let row = outputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + outputs.push(SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + }); + } + Ok(stub(false, outputs)) +} + +/// A pixel shader that reads nothing and writes target 0. +pub fn stub_ps() -> HostShader { + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }; + stub(true, vec![target]) +} + +fn stub(pixel: bool, outputs: Vec<SigElement>) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(pixel); + let b = s.entry; + for (id, e) in outputs.iter().enumerate() { + for col in 0..e.cols { + let (suffix, zero) = if e.comp == 9 { + (".f32", s.m.f32(0)) + } else { + (".i32", s.m.i32(0)) + }; + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(col), zero]; + s.op( + b, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &args, + ); + } + } + s.outputs = outputs + .into_iter() + .map(|mut e| { + e.usage = (1 << e.cols) - 1; + e + }) + .collect(); + s.m.terminate(b, Term::Ret); + HostShader { + stage: if pixel { + crate::native::HwStage::Ps + } else { + crate::native::HwStage::Vs + }, + dxil: s.finish(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + } +} + +/// A root argument for [`Host::draw`]. +#[cfg(test)] +pub enum Root { + Constants(Vec<u32>), + /// A table starting at this heap index. + Table { + sampler: bool, + index: usize, + }, + /// A root CBV (or with `srv`, a root SRV) over a buffer of these + /// dwords ([`Host::dispatch`] only). + View { + srv: bool, + data: Vec<u32>, + }, +} + +/// Bindings for [`Host::draw`]: root arguments and the heap contents. +#[cfg(test)] +pub struct Draw<'a> { + pub roots: Vec<(u32, Root)>, + /// RGBA32F textures (width, height, texels) at view-heap indices 0.. + pub textures: &'a [(u32, u32, &'a [[f32; 4]])], + /// Samplers at sampler-heap indices 0.. + pub samplers: &'a [D3D12_SAMPLER_DESC], + /// Three vertices of stride bytes (none for position-free layouts). + pub vertices: &'a [f32], + pub stride: u32, + pub size: (u32, u32), + /// Mesh thread groups to dispatch instead of drawing (0: draw). + pub mesh_groups: u32, +} + +#[cfg(test)] +impl Host { + /// Draws one triangle into an RGBA32F target and returns its texels. + pub fn draw( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Draw, + ) -> Result<Vec<[f32; 4]>, String> { + let dev = &self.device; + let (w, h) = d.size; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // are kept alive until the fence says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso) + .map_err(err)?; + let tex_desc = |w: u32, h: u32, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }; + let buf_desc = |size: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = |t| D3D12_HEAP_PROPERTIES { + Type: t, + ..Default::default() + }; + let make = |props: D3D12_HEAP_TYPE, + desc: &D3D12_RESOURCE_DESC, + state, + clear: Option<&D3D12_CLEAR_VALUE>| { + let mut r: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &heap(props), + D3D12_HEAP_FLAG_NONE, + desc, + state, + clear.map(|c| c as *const _), + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let target = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc(w, h, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }), + )?; + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .map_err(err)?; + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&target, None, rtv); + let views: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: d.textures.len().max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let sampler_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: d.samplers.len().max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + for (i, &(tw, th, texels)) in d.textures.iter().enumerate() { + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc(tw, th, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let pitch = (tw as usize * 16).next_multiple_of(256); + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc((pitch * th as usize) as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + for y in 0..th as usize { + let row = &texels[y * tw as usize..(y + 1) * tw as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::<u8>(), + p.cast::<u8>().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&tex), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: tw, + Height: th, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + dev.CreateShaderResourceView(&tex, None, at); + keep.push(tex); + keep.push(upload); + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = sampler_heap.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + let vb = if d.vertices.is_empty() { + None + } else { + let bytes = d.vertices.len() * 4; + let vb = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(bytes as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + vb.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping( + d.vertices.as_ptr().cast::<u8>(), + p.cast::<u8>(), + bytes, + ); + vb.Unmap(0, None); + Some(vb) + }; + list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); + list.SetGraphicsRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetGraphicsRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (heap, size) = if *sampler { + (&sampler_heap, sampler_size) + } else { + (&views, view_size) + }; + let mut at = heap.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetGraphicsRootDescriptorTable(*param, at); + } + Root::View { .. } => return Err("root views in a draw".into()), + } + } + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: w as f32, + Height: h as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + right: w as i32, + bottom: h as i32, + ..Default::default() + }]); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if let Some(vb) = &vb { + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vb.GetGPUVirtualAddress(), + SizeInBytes: (d.vertices.len() * 4) as u32, + StrideInBytes: d.stride, + }]), + ); + } + if d.mesh_groups > 0 { + let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(err)?; + list6.DispatchMesh(d.mesh_groups, 1, 1); + } else { + list.DrawInstanced(3, 1, 0, 0); + } + list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = (w as usize * 16).next_multiple_of(256); + let readback = make( + D3D12_HEAP_TYPE_READBACK, + &buf_desc((pitch * h as usize) as u64), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: w, + Height: h, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if dev.GetDeviceRemovedReason().is_err() { + return Err(format!( + "device removed: {}", + err(dev.GetDeviceRemovedReason().unwrap_err()) + )); + } + std::thread::yield_now(); + } + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(err)?; + let mut out = Vec::with_capacity((w * h) as usize); + for y in 0..h as usize { + let row = std::slice::from_raw_parts( + p.cast::<u8>().add(y * pitch).cast::<[f32; 4]>(), + w as usize, + ); + out.extend_from_slice(row); + } + readback.Unmap(0, None); + drop(keep); + Ok(out) + } + } +} + +#[cfg(test)] +fn transition( + r: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A view in the heap for [`Host::dispatch`]. +#[cfg(test)] +pub enum View<'a> { + /// An RGBA32F texture SRV (width, height, texels). + Texture(u32, u32, &'a [[f32; 4]]), + /// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z). + Cube(u32, &'a [[f32; 4]]), + /// A raw buffer UAV of this many dwords, zeroed. + RawUav(u32), + /// An RGBA32F texture UAV (width, height), zeroed. + TextureUav(u32, u32), + /// An R32_UINT texture UAV (width, height), zeroed (atomics). + UintTextureUav(u32, u32), + /// A typed RGBA16F buffer UAV of this many elements, zeroed. + HalfUav(u32), + /// A constant buffer of these dwords. + Cbv(&'a [u32]), + /// A buffer SRV over these dwords. + Buffer { data: &'a [u32], stride: Stride }, +} + +/// How [`View::Buffer`] is viewed. +#[cfg(test)] +#[derive(Clone, Copy)] +pub enum Stride { + Raw, + /// RGBA32F elements. + Typed, + /// Structured, elements of this many bytes. + Structured(u32), + /// Typed, elements in this format of this many bytes. + Format(DXGI_FORMAT, u32), +} + +/// Bindings for [`Host::dispatch`]: root arguments, the view heap in order, +/// the sampler heap, and the group counts. +#[cfg(test)] +pub struct Dispatch<'a> { + pub roots: Vec<(u32, Root)>, + pub views: &'a [View<'a>], + pub samplers: &'a [D3D12_SAMPLER_DESC], + pub groups: [u32; 3], +} + +#[cfg(test)] +impl Host { + /// Runs a compute pipeline and returns each UAV's contents in heap + /// order (texels as float bits, row by row). + pub fn dispatch( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Dispatch, + ) -> Result<Vec<Vec<u32>>, String> { + let dev = &self.device; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // stay alive until the fence says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso) + .map_err(err)?; + let make = |heap: D3D12_HEAP_TYPE, desc: &D3D12_RESOURCE_DESC, state| { + let mut r: Option<ID3D12Resource> = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + None, + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let sample = DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }; + let texture_as = |w: u32, h: u32, flags, format| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: sample, + Flags: flags, + ..Default::default() + }; + let texture = |w, h, flags| texture_as(w, h, flags, DXGI_FORMAT_R32G32B32A32_FLOAT); + let buffer = |size: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: sample, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + // Texel words: 4 for RGBA32F, 1 for R32_UINT. + let footprint_as = + |r: &ID3D12Resource, w: u32, h: u32, words: u32| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: if words == 1 { + DXGI_FORMAT_R32_UINT + } else { + DXGI_FORMAT_R32G32B32A32_FLOAT + }, + Width: w, + Height: h, + Depth: 1, + RowPitch: (w * 4 * words).next_multiple_of(256), + }, + }, + }, + }; + let footprint = |r: &ID3D12Resource, w: u32, h: u32| footprint_as(r, w, h, 4); + let subresource = |r: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let heap = |ty, n: usize| -> Result<ID3D12DescriptorHeap, String> { + dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: n.max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err) + }; + // An upload buffer holding `data` (sized for a constant buffer). + let upload = |data: &[u32]| -> Result<ID3D12Resource, String> { + let size = (data.len() * 4).next_multiple_of(256); + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer(size as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::<u32>(), data.len()); + b.Unmap(0, None); + Ok(b) + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.views.len())?; + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.len())?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + // UAVs: (resource, dwords or texture size, readback buffer). + let mut uavs = Vec::new(); + for (i, v) in d.views.iter().enumerate() { + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + match *v { + View::Texture(..) | View::Cube(..) => { + let (w, h, texels, faces) = match *v { + View::Texture(w, h, t) => (w, h, t, 1), + View::Cube(n, t) => (n, n, t, 6), + _ => unreachable!(), + }; + let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE); + desc.DepthOrArraySize = faces as u16; + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let pitch = (w as usize * 16).next_multiple_of(256); + for face in 0..faces as usize { + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + let texels = &texels[face * (w * h) as usize..]; + for y in 0..h as usize { + let row = &texels[y * w as usize..(y + 1) * w as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::<u8>(), + p.cast::<u8>().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let mut at_face = subresource(&tex); + at_face.Anonymous.SubresourceIndex = face as u32; + list.CopyTextureRegion( + &at_face, + 0, + 0, + 0, + &footprint(&upload, w, h), + None, + ); + keep.push(upload); + } + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let cube = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURECUBE, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + TextureCube: D3D12_TEXCUBE_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + dev.CreateShaderResourceView( + &tex, + (faces == 6).then_some(&cube as *const _), + at, + ); + keep.push(tex); + } + View::RawUav(_) | View::HalfUav(_) => { + // (dwords, format, elements, flags) + let (n, format, elements, flags) = match *v { + View::HalfUav(e) => ( + 2 * e, + DXGI_FORMAT_R16G16B16A16_FLOAT, + e, + D3D12_BUFFER_UAV_FLAG_NONE, + ), + View::RawUav(n) => { + (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) + } + _ => unreachable!(), + }; + let bytes = u64::from(n) * 4; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + )?; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: elements, + Flags: flags, + ..Default::default() + }, + }, + }; + dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, n, rb)); + } + View::TextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 16).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 4, rb)); + } + View::UintTextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture_as( + w, + h, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + DXGI_FORMAT_R32_UINT, + ), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 4).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 1, rb)); + } + View::Cbv(data) => { + let b = upload(data)?; + dev.CreateConstantBufferView( + Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: b.GetGPUVirtualAddress(), + SizeInBytes: (data.len() * 4).next_multiple_of(256) as u32, + }), + at, + ); + keep.push(b); + } + View::Buffer { data, stride } => { + let b = upload(data)?; + let (format, elements, stride, flags) = match stride { + Stride::Raw => ( + DXGI_FORMAT_R32_TYPELESS, + data.len(), + 0, + D3D12_BUFFER_SRV_FLAG_RAW, + ), + Stride::Typed => ( + DXGI_FORMAT_R32G32B32A32_FLOAT, + data.len() / 4, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Structured(s) => ( + DXGI_FORMAT_UNKNOWN, + data.len() * 4 / s as usize, + s, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Format(f, bytes) => ( + f, + data.len() * 4 / bytes as usize, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: elements as u32, + StructureByteStride: stride, + Flags: flags, + }, + }, + }; + dev.CreateShaderResourceView(&b, Some(&desc), at); + keep.push(b); + } + } + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]); + list.SetComputeRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetComputeRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (h, size) = if *sampler { + (&samplers, sampler_size) + } else { + (&views, view_size) + }; + let mut at = h.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetComputeRootDescriptorTable(*param, at); + } + Root::View { srv, data } => { + let b = upload(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetComputeRootShaderResourceView(*param, va); + } else { + list.SetComputeRootConstantBufferView(*param, va); + } + keep.push(b); + } + } + } + let [x, y, z] = d.groups; + list.Dispatch(x, y, z); + for (r, size, n, rb) in &uavs { + // (Buffers were promoted from the common state by the dispatch.) + list.ResourceBarrier(&[transition( + r, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + match size { + Some((w, h)) => list.CopyTextureRegion( + &footprint_as(rb, *w, *h, *n), + 0, + 0, + 0, + &subresource(r), + None, + ), + None => list.CopyBufferRegion(rb, 0, r, 0, u64::from(*n) * 4), + } + } + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + std::thread::yield_now(); + } + let mut out = Vec::new(); + for (_, size, n, rb) in &uavs { + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(err)?; + let words = match size { + Some((w, h)) => { + let words = *n as usize; + let pitch = (*w as usize * 4 * words).next_multiple_of(256); + (0..*h as usize) + .flat_map(|y| { + std::slice::from_raw_parts( + p.cast::<u8>().add(y * pitch).cast::<u32>(), + *w as usize * words, + ) + .to_vec() + }) + .collect() + } + None => std::slice::from_raw_parts(p.cast::<u32>(), *n as usize).to_vec(), + }; + rb.Unmap(0, None); + out.push(words); + } + drop(keep); + Ok(out) + } + } +} diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs new file mode 100644 index 0000000..9a8ac9c --- /dev/null +++ b/crates/victory-shader/src/emit/lower.rs @@ -0,0 +1,6500 @@ +//! IR to DXIL, one machine instruction at a time (decision 0003). +//! +//! Every register dword is an `i32` (SCC an `i1`); float operations bitcast +//! their operands. Lane masks exist only as the per-lane booleans of +//! structurisation; branches and guards are built from them. A value the +//! emitter cannot express is `Missing` with a reason, and only fails the +//! program when something with an effect (an export, a branch) needs it. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use super::UserData; +use super::bitcode::{Attr, Bin, Cast, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Shader, flags}; +use crate::ShaderError; +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; +use crate::resource::{Address, CODE, Resources, Role, Site, Source}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +type Why = &'static str; + +#[derive(Debug, Clone, Copy)] +enum Val { + I32(V), + Bit(V), + Missing(Why), +} + +pub(crate) struct Lowered { + pub dxil: Vec<u8>, + /// Bit n: immediate sampler n is used for comparisons. + pub cmp_samplers: u64, + pub root_cbvs: Vec<u8>, + pub root_srvs: Vec<u8>, + pub user_data: Vec<UserData>, + pub samplers: Vec<[u32; 4]>, +} + +pub(crate) struct Parts<'a> { + pub native: &'a NativeProgram, + pub p: &'a Program, + pub st: &'a Structured, + pub io: &'a Io, + pub res: &'a Resources, + pub inputs: Vec<SigElement>, + pub outputs: Vec<SigElement>, + pub prims: Vec<SigElement>, + /// Mesh: what the group id arrives multiplied by. + pub mesh_stride: u32, +} + +enum Stop { + /// A phi whose incoming value has no DXIL form was read: redo with it missing. + Retry(Value, Why), + Fail(ShaderError), +} + +pub(crate) fn lower(parts: &Parts) -> Result<Lowered, ShaderError> { + let mut bad = HashMap::new(); + loop { + match Lower::new(parts, &bad).run() { + Ok(l) => return Ok(l), + Err(Stop::Retry(v, why)) => { + if bad.insert(v, why).is_some() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a phi that does not settle", + }); + } + } + Err(Stop::Fail(e)) => return Err(e), + } + } +} + +const TWO_PI: f32 = std::f32::consts::TAU; +/// `s_sendmsg` id of a mesh or NGG stage's output allocation request. +const GS_ALLOC_REQ: u16 = 9; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Numeric { + Unorm, + Snorm, + Uscaled, + Sscaled, + Uint, + Sint, + Float, +} + +/// A GFX10 buffer format (the unified format of typed buffer loads): the +/// channel widths from the lowest bits up, and how the channels convert. +/// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names +/// list channels from the highest bits), each with its numeric formats in +/// the order unorm, snorm, uscaled, sscaled, uint, sint, float. +fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> { + use Numeric::*; + const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint]; + const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float]; + const WIDE: &[Numeric] = &[Uint, Sint, Float]; + // `None`: a family not decoded (packed floats, 10_10_10_2). + const FAMILIES: [(Option<&[u32]>, &[Numeric]); 14] = [ + (Some(&[8]), NORM), + (Some(&[16]), ALL), + (Some(&[8, 8]), NORM), + (Some(&[32]), WIDE), + (Some(&[16, 16]), ALL), + (None, ALL), // 10_11_11 + (None, ALL), // 11_11_10 + (None, NORM), // 10_10_10_2 + (Some(&[10, 10, 10, 2]), NORM), // 2_10_10_10 + (Some(&[8, 8, 8, 8]), NORM), + (Some(&[32, 32]), WIDE), + (Some(&[16, 16, 16, 16]), ALL), + (Some(&[32, 32, 32]), WIDE), + (Some(&[32, 32, 32, 32]), WIDE), + ]; + let mut n = usize::from(format.checked_sub(1)?); + for (bits, numerics) in FAMILIES { + if n < numerics.len() { + return Some((bits?, numerics[n])); + } + n -= numerics.len(); + } + None +} + +struct Lower<'a> { + s: Shader, + x: &'a Parts<'a>, + bad: &'a HashMap<Value, Why>, + lane_fail: HashMap<Value, Why>, + vals: HashMap<Value, Val>, + floats: HashMap<Value, V>, + /// DXIL block per IR block (unreachable: none). + block: Vec<Option<usize>>, + cur: usize, + bools: HashMap<(usize, Bool), V>, + lane_bits: HashMap<Value, V>, + /// IR phi location by value. + phi_at: HashMap<Value, (usize, usize)>, + mask_phis: HashMap<Value, V>, + pending_masks: Vec<(V, usize, usize)>, + data_phis: Vec<(V, usize, usize)>, + read_phis: HashSet<Value>, + params: HashMap<Value, (usize, u32)>, + user_data: Option<V>, + user_reads: BTreeMap<u32, UserData>, + samplers: Vec<[u32; 4]>, + descriptors: HashMap<(Site, bool), &'a Source>, + scalar: HashMap<Site, Address>, + exports: HashMap<Site, &'a Export>, + interps: HashMap<Site, &'a Interp>, + handles: HashMap<(usize, Site, u8, bool, u32), V>, + /// Blocks splitting the edge from one IR block to another. + edges: HashMap<(usize, usize), usize>, + /// Per IR block: a `done` export is behind every lane entering it. + exported: Vec<bool>, + /// Reverse-postorder index per IR block. + rpo: Vec<usize>, + /// DXIL block each IR block ends in (guarded stores split blocks). + tail: Vec<Option<usize>>, + /// The program writes UAVs: barriers fence them too. + writes_uavs: bool, + /// src0 of the current instruction as DPP fetched it. + src0: Option<V>, + /// Compute code that reads other lanes: thread ids follow the host + /// lanes, so lane n is console lane n. + console_lanes: bool, + /// Mesh: the thread index in the group (made in the entry block). + flat: Option<V>, + /// Mesh: IR blocks whose `s_barrier` is left out. + no_barrier: HashSet<usize>, + /// Vertex and mesh outputs holding 16-bit values: row, whether two per + /// dword, and the row packed after it. + half_outputs: HashMap<u8, (bool, Option<u8>)>, + /// How lane masks become data. + mask_data: MaskData, + /// The instruction being lowered may read lane masks as data. + mask_ok: bool, + /// Ballots of masks read as data, by low dword: (low, high). + ballots: HashMap<Value, (V, V)>, + /// Block writing each value. + def_block: HashMap<Value, usize>, + /// IR block being lowered. + cur_ir: usize, + /// Whole-wave sections by block and start index. + sections: HashMap<usize, HashMap<usize, super::wave::Section>>, + /// Values written in a section that code outside it reads. + section_out: HashSet<Value>, + /// The program's constant table (the code from the first byte read + /// through `s_getpc_b64` on): global, first byte, dwords. + code_table: Option<(V, u32, u32)>, + /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by + /// IR block, and its incoming (value, DXIL block) pairs. + counters: HashMap<usize, (V, Vec<(V, usize)>)>, + /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. + abort: Option<usize>, +} + +/// Iterations after which a loop is left (per entry into it). The console +/// runs a loop as long as its data says; data the host has not mirrored +/// yet (a null view reads zeros) can make that four billion iterations, +/// which hangs the host GPU until the driver resets it. A lane that +/// reaches the limit leaves the program as killed (a pixel discards). +// shortcut: a genuine loop of more iterations than this is cut short too. +const LOOP_LIMIT: u32 = 1 << 20; + +/// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar +/// compares, bit tests) are ballots of the lanes' booleans, taken where the +/// mask is written: structurisation's `active` masks hold only lanes that +/// reach that block, so the ballot misses none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MaskData { + /// Compute: host lane n is console lane n (the program declares the + /// console's wave size), so ballots are the console's masks bit for bit + /// and any use is exact. + Console, + /// Pixel and vertex programs: ballots over the host's wave, whatever its + /// size. Only uses that mean the same on any wave are allowed: counts, + /// the first lane, the count below a lane, equality (the HLSL wave + /// operations the console compiler expands). Lane numbers stay host + /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane). + Host, + /// Mesh programs: their lanes and waves (LDS per console wave) are the + /// console's but no host wave size can be declared. + None, +} + +/// What a value holding a lane mask read as a number stops with. +const LANE_MASK: Why = "a lane mask read as data"; + +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. +fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let ops: Vec<&Operand> = match &i.fields { + // A mask operation (its result a mask) is no data use. + Fields::Sop { .. } + if i.writes + .iter() + .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) => + { + return false; + } + Fields::Sop { src, .. } => src.iter().collect(), + Fields::Valu(v) + if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") => + { + v.src.iter().collect() + } + _ => return false, + }; + ops.into_iter().any(|op| match *op { + Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask), + _ => false, + }) +} + +/// Where half `h` (dword h / 2, the high half when odd) of a parameter +/// packing 16-bit rows `a` and `b` two per dword comes from: a row and +/// channel of `elements`, none for padding. Channel c of `a` is half c; +/// `b` starts at the dword after `a`'s last channel. +fn packed_half(elements: &[SigElement], a: u8, b: Option<u8>, h: u8) -> Option<(u8, u8)> { + let extent = |r: u8| { + elements + .iter() + .filter(|e| e.row == Some(u32::from(r))) + .map(|e| e.col + e.cols) + .max() + }; + let na = extent(a)?; + let a_halves = na.div_ceil(2) * 2; + if h < a_halves { + return (h < na).then_some((a, h)); + } + let b = b?; + let c = h - a_halves; + (c < extent(b)?).then_some((b, c)) +} + +/// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]): +/// a packed row's partner is the next 16-bit row of the signature that no +/// output entry names, taken in row order. +fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap<u8, (bool, Option<u8>)> { + let entries = match io { + StageIo::Vs { outputs, .. } => outputs, + StageIo::Ms(ms) => &ms.outputs, + _ => return HashMap::new(), + }; + let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0); + let mut free: Vec<u8> = outputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !per_vertex().any(|o| o.row == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect(); + halves.sort_by_key(|o| o.row); + halves + .into_iter() + .map(|o| { + let b = o + .pack2 + .then(|| free.iter().position(|&r| r > o.row)) + .flatten(); + (o.row, (o.pack2, b.map(|i| free.remove(i)))) + }) + .collect() +} + +fn unsupported(offset: usize, what: Why) -> Stop { + Stop::Fail(ShaderError::Unsupported { offset, what }) +} + +impl<'a> Lower<'a> { + fn new(x: &'a Parts<'a>, bad: &'a HashMap<Value, Why>) -> Self { + let p = x.p; + let mut phi_at = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phi_at.insert(phi.value, (b, i)); + } + } + let mut s = Shader::new(x.native.stage == HwStage::Ps); + s.inputs = x.inputs.clone(); + s.outputs = x.outputs.clone(); + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + let writes_uavs = insts().any(|i| { + matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) + && (i.name().contains("store") || i.name().contains("atomic")) + }); + let mut console_lanes = false; + if let StageIo::Cs(cs) = x.native.io { + s.threads = Some(cs.threads); + s.lds_dwords = cs.lds_bytes() / 4; + // Code reading other lanes needs the console's wave size and + // lane order; so do lane masks read as numbers, and LDS shared + // within one wave, where the console compiler leaves out barriers. + console_lanes = insts().any(|i| { + let n = i.name(); + n.starts_with("ds_swizzle") + || n.contains("permute") + || n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) + || reads_mask_as_data(x.st, i) + }) || { + // Masks held as numbers or constant lane sets: the lane + // tests its own bit by its console lane. + let whens = x.st.exits.iter().filter_map(|e| match *e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }); + let mut all: Vec<Bool> = + x.st.guards + .iter() + .flatten() + .flatten() + .copied() + .chain(whens) + .collect(); + all.sort_unstable(); + all.dedup(); + all.into_iter().any(|g| { + x.st.bools + .support(g) + .iter() + .any(|a| matches!(a, Atom::Opaque(_) | Atom::Constant(_))) + }) + }; + let wave = if x.native.wave64 { 64 } else { 32 }; + let one_wave = cs.threads.iter().product::<u32>() <= wave; + if console_lanes || one_wave && s.lds_dwords > 0 { + s.wave_size = Some(wave); + } + } + let mut no_barrier = HashSet::new(); + if let StageIo::Ms(ms) = &x.native.io { + s.prims = x.prims.clone(); + s.threads = Some([ms.threads, 1, 1]); + s.lds_dwords = ms.lds_bytes.div_ceil(4); + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); + // Barriers order the lanes' LDS accesses; the console's + // allocation request needs them too, but the host does not. One + // lane sends that request, and what it dominates (the path for + // counts out of range) runs in that lane alone, so its barrier + // would hang the host. + let order = crate::ir::reverse_postorder(&p.blocks); + let mut index = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + index[b] = n; + } + let idom = crate::ir::idoms(&p.blocks, &order, &index); + let alloc: Vec<usize> = (0..p.blocks.len()) + .filter(|&b| { + p.blocks[b].insts.iter().any(|i| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ) + }) + }) + .collect(); + for &b in &order { + let mut d = b; + let dominated = loop { + if alloc.contains(&d) { + break true; + } + if idom[d] == d || idom[d] == usize::MAX { + break false; + } + d = idom[d]; + }; + if ms.lds_bytes == 0 || dominated { + no_barrier.insert(b); + } + } + } + Lower { + s, + x, + bad, + lane_fail: HashMap::new(), + vals: HashMap::new(), + floats: HashMap::new(), + block: vec![None; p.blocks.len()], + cur: 0, + bools: HashMap::new(), + lane_bits: HashMap::new(), + phi_at, + mask_phis: HashMap::new(), + pending_masks: Vec::new(), + data_phis: Vec::new(), + read_phis: HashSet::new(), + params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), + user_data: None, + user_reads: BTreeMap::new(), + samplers: Vec::new(), + descriptors: x + .res + .descriptors + .iter() + .map(|d| ((d.site, d.role == Role::Sampler), &d.source)) + .collect(), + scalar: x.res.scalar.iter().copied().collect(), + exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), + interps: x.io.interps.iter().map(|(s, i)| (*s, i)).collect(), + handles: HashMap::new(), + edges: HashMap::new(), + exported: vec![false; p.blocks.len()], + rpo: vec![usize::MAX; p.blocks.len()], + tail: vec![None; p.blocks.len()], + writes_uavs, + src0: None, + console_lanes, + flat: None, + no_barrier, + half_outputs: half_outputs(&x.native.io, &x.outputs), + mask_data: match x.native.stage { + HwStage::Cs => MaskData::Console, + HwStage::Ps | HwStage::Vs => MaskData::Host, + _ => MaskData::None, + }, + mask_ok: false, + ballots: HashMap::new(), + def_block: p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b))) + .chain(block.phis.iter().map(move |phi| (phi.value, b))) + }) + .collect(), + cur_ir: 0, + sections: HashMap::new(), + section_out: HashSet::new(), + code_table: None, + counters: HashMap::new(), + abort: None, + } + } + + /// The dword of the program's code at byte `byte` (a constant table + /// the compiler appends to the code), as an internal constant array. + // shortcut: an index outside the table reads its last dword (the + // console would read whatever memory follows the code). + fn code_dword(&mut self, byte: V) -> Result<V, Why> { + let (g, base, len) = match self.code_table { + Some(t) => t, + None => { + let first = self + .x + .res + .scalar + .iter() + .map(|s| s.1) + .chain(self.x.res.descriptors.iter().flat_map(|d| { + d.source.leaves().into_iter().filter_map(|l| match l { + Source::Built { address, .. } => Some(*address), + _ => None, + }) + })) + .filter(|a| a.param == CODE) + .map(|a| a.offset & !3) + .min() + .ok_or("a code table")?; + let code = &self.x.native.code; + let words: Vec<u32> = code + .get(first as usize..) + .ok_or("a code table past the code")? + .chunks(4) + .map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + }) + .collect(); + if words.is_empty() { + return Err("a code table past the code"); + } + let elems: Vec<V> = words.iter().map(|&w| self.s.m.i32(w)).collect(); + let arr = self.s.m.array(words.len() as u32, self.s.t.i32); + let init = self.s.m.aggregate(arr, &elems); + let g = self.s.m.constant_global("code", init); + let t = (g, first, words.len() as u32); + self.code_table = Some(t); + t + } + }; + let c = self.cur; + let k = self.s.m.i32(base); + let rel = self.s.m.bin(c, Bin::Sub, byte, k); + let two = self.s.m.i32(2); + let index = self.s.m.bin(c, Bin::LShr, rel, two); + let last = self.s.m.i32(len - 1); + let over = self.s.m.cmp(c, pred::IUGT, index, last); + let index = self.s.m.select(c, over, last, index); + let at = self.s.m.element(c, g, index); + Ok(self.s.m.load(c, at)) + } + + /// A global memory load (`global_load_*`): from the program's constant + /// table, or from a root SRV at the address the title sets. + fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { dst, .. } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let rest = name + .strip_prefix("global_load_") + .ok_or("a global memory write")?; + let (n, sub) = match rest { + "dword" => (1, None), + "dwordx2" => (2, None), + "dwordx3" => (3, None), + "dwordx4" => (4, None), + "ubyte" => (1, Some((8, false))), + "sbyte" => (1, Some((8, true))), + "ushort" => (1, Some((16, false))), + "sshort" => (1, Some((16, true))), + _ => return Err(name), + }; + let a = *self + .scalar + .get(&(b, i)) + .ok_or("an untracked global address")?; + let guard = self.guard(b, i)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let c = self.cur; + let mut off = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + off = self.s.m.bin(c, Bin::Add, off, d); + } + let h = if a.param == CODE { + None + } else { + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + Some(self.handle((b, i), &src, false, (11, 0))?) + }; + let dword = |l: &mut Self, byte: V| -> Result<V, Why> { + match h { + None => l.code_dword(byte), + Some(h) => { + let c = l.cur; + let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4)); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, byte, u, mask, al], + ); + let x = l.s.m.extract(c, r, 0); + Ok(l.as_int(x)) + } + } + }; + for k in 0..n { + let x = match sub { + None => { + let four = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, off, four); + dword(self, at)? + } + Some((width, signed)) => { + // shortcut: the field is taken not to cross a dword. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = dword(self, at)?; + let byte = self.s.m.bin(c, Bin::And, off, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let left = self.s.m.i32(32 - width); + let x = self.s.m.bin(c, Bin::Shl, x, left); + self.s + .m + .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) + } + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// Finds the whole-wave sections and the values they leave. + fn find_sections(&mut self) { + let p = self.x.p; + let mut inside: HashMap<Value, (usize, usize, usize)> = HashMap::new(); + for b in 0..p.blocks.len() { + let found = super::wave::sections(p, b); + for (&start, sec) in &found { + for i in start + 1..sec.end { + for &(_, w) in &p.blocks[b].insts[i].writes { + inside.insert(w, (b, start, sec.end)); + } + } + } + if !found.is_empty() { + self.sections.insert(b, found); + } + } + if inside.is_empty() { + return; + } + for (b, block) in p.blocks.iter().enumerate() { + for phi in &block.phis { + self.section_out + .extend(phi.args.iter().filter(|a| inside.contains_key(a))); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, r) in &inst.reads { + if let Some(&(sb, start, end)) = inside.get(&r) + && !(sb == b && i > start && i < end) + { + self.section_out.insert(r); + } + } + } + } + } + + /// An instruction inside a whole-wave section: the values that leave + /// the section are made from what the simulation found them to be. + fn section_inst(&mut self, b: usize, i: usize, start: usize) { + const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; + let inst = &self.x.p.blocks[b].insts[i]; + for &(_, w) in &inst.writes { + let val = if self.section_out.contains(&w) { + let shape = self.sections[&b][&start].shapes.get(&w).copied(); + match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh)) { + Ok(x) => Val::I32(x), + Err(why) => Val::Missing(why), + } + } else { + Val::Missing(UNKNOWN) + }; + self.vals.insert(w, val); + } + } + + /// A value a whole-wave section leaves, as DXIL wave operations over the + /// host's active lanes: the console's result with console lanes; on + /// another wave size, what the HLSL wave operation the console compiler + /// expanded gives on that wave. + fn shape(&mut self, shape: super::wave::Shape) -> Result<V, Why> { + use super::wave::{Op, Shape}; + let (op, src, mask, ident, prefix) = match shape { + Shape::K(k) => return Ok(self.s.m.i32(k)), + Shape::Value(v) => return self.i32_of(v), + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::Masked(src, mask, ident) => { + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + return Ok(self.s.m.select(c, on, x, id)); + } + Shape::Prefix(op, src, mask, ident, inclusive) => { + (op, src, mask, ident, Some(inclusive)) + } + }; + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + let x = self.s.m.select(c, on, x, id); + self.s.flags |= flags::WAVE_OPS; + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let arg = if float { self.as_float(x) } else { x }; + let ty = if float { f32t } else { i32t }; + let sfx = if float { "f32" } else { "i32" }; + let r = match (op, prefix) { + (Op::AddU | Op::AddF, Some(inclusive)) => { + let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); + let r = self.s.op( + c, + &format!("wavePrefixOp.{sfx}"), + Attr::NoUnwind, + ty, + 121, + &[arg, k0, k1], + ); + if inclusive { + self.s.m.bin(c, Bin::Add, r, arg) + } else { + r + } + } + (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), + (Op::Or | Op::And | Op::Xor, None) => { + let k = self.s.m.i8(match op { + Op::And => 0, + Op::Or => 1, + _ => 2, + }); + self.s + .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) + } + (_, None) => { + let (code, unsigned) = match op { + Op::AddU => (0, 1), + Op::AddF => (0, 0), + Op::MinU => (2, 1), + Op::MaxU => (3, 1), + Op::MinI | Op::MinF => (2, 0), + _ => (3, 0), + }; + let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); + self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k, u], + ) + } + }; + Ok(if float { self.as_int(r) } else { r }) + } + + fn run(mut self) -> Result<Lowered, Stop> { + let p = self.x.p; + let order = crate::ir::reverse_postorder(&p.blocks); + for (n, &b) in order.iter().enumerate() { + self.rpo[b] = n; + } + for (n, &b) in order.iter().enumerate() { + self.block[b] = Some(if n == 0 { + self.s.entry + } else { + self.s.m.new_block() + }); + } + // Loop headers count iterations (`LOOP_LIMIT`). + for &b in &order { + let header = p.blocks[b] + .preds + .iter() + .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]); + if header { + let blk = self.block[b].expect("reachable"); + let phi = self.s.m.phi(blk, self.s.t.i32); + self.counters.insert(b, (phi, Vec::new())); + } + } + self.cur = self.s.entry; + self.find_sections(); + self.inputs()?; + if let Some(mesh) = self.s.mesh { + self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; + self.block[order[0]] = Some(self.cur); + } + for &b in &order { + self.cur = self.block[b].expect("reachable"); + self.cur_ir = b; + let preds: Vec<usize> = p.blocks[b] + .preds + .iter() + .copied() + .filter(|&q| self.block[q].is_some()) + .collect(); + self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + let val = match phi.reg { + Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), + Reg::Scc => { + let v = self.s.m.phi(self.cur, self.s.t.i1); + self.data_phis.push((v, b, i)); + Val::Bit(v) + } + _ => { + let v = self.s.m.phi(self.cur, self.s.t.i32); + self.data_phis.push((v, b, i)); + Val::I32(v) + } + }; + self.vals.insert(phi.value, val); + } + let mut i = 0; + while i < p.blocks[b].insts.len() { + self.inst(b, i)?; + if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) { + for j in i + 1..end { + self.section_inst(b, j, i); + } + i = end; + continue; + } + i += 1; + } + self.mask_ok = self.mask_data == MaskData::Console; + self.tail[b] = Some(self.cur); + self.exit(b)?; + } + self.fill_phis()?; + let user_data = self.user_reads.values().copied().collect(); + self.s.samplers = self.samplers.len() as u32; + let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); + let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); + let cmp_samplers = self.s.cmp_samplers; + Ok(Lowered { + cmp_samplers, + root_cbvs, + root_srvs, + dxil: self.s.finish(), + user_data, + samplers: self.samplers, + }) + } + + fn exported_out(&self, b: usize) -> bool { + self.exported[b] || self.has_done_export(b) + } + + fn has_done_export(&self, b: usize) -> bool { + (0..self.x.p.blocks[b].insts.len()) + .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done)) + } + + /// Values of the program's input registers. + fn inputs(&mut self) -> Result<(), Stop> { + let io_inputs: HashMap<Value, Input> = self.x.io.inputs.iter().copied().collect(); + for &(reg, v) in &self.x.p.inputs { + let val = match reg { + Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use + Reg::S(_) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + None => Val::Missing("a hardware SGPR input"), + }, + Reg::Scc => Val::Missing("SCC on entry"), + Reg::V(_) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + // Registers no one set read as zero (the validator + // refuses reads of undef). + None => Val::I32(self.s.m.i32(0)), + }, + }; + self.vals.insert(v, val); + } + Ok(()) + } + + fn input(&mut self, input: Input) -> Val { + let (kind, col) = match input { + Input::VertexId => (1, 0), + Input::InstanceId => (2, 0), + Input::Position(c) => (3, c), + Input::Attribute { row, channel } => { + return match self.find_input(row, channel) { + Some((id, col)) => self.load_input(id, col), + None => Val::Missing("a vertex input the signature lacks"), + }; + } + Input::Barycentric { .. } => return Val::Missing("barycentrics read directly"), + Input::PrimitiveId => return Val::Missing("the primitive id"), + // The console code tests it against 0 (`v_cmp_ne_u32`), as the + // host's value can be. + Input::FrontFace => (13, 0), + Input::ThreadIdInGroup(c) => return self.thread_id(c), + Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), + Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), + Input::MeshGroup => { + let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let n = self.s.m.i32(self.x.mesh_stride); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n)); + } + Input::MergedWaveInfo => { + // shortcut: only the wave index (bits 24-27) is set; the + // console's other bits (lane counts) are read by no program. + let f = self.mesh_thread(); + let shift = self.s.m.i32(self.wave().trailing_zeros()); + let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift); + let k24 = self.s.m.i32(24); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24)); + } + _ => return Val::Missing("a pixel system input"), + }; + let free = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + let id = match self.s.inputs.iter().position(|e| e.kind == kind) { + Some(id) => { + if kind != 3 { + self.s.inputs[id].row.get_or_insert(free); + } + id + } + None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"), + None => { + // The console signature leaves out vertex and instance ids; PC + // gives them a row after the others. + let row = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + self.s.inputs.push(SigElement { + name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + self.load_input(id, col) + } + + /// A component of a compute thread or group id, read in the entry block. + fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val { + let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c))); + Val::I32( + self.s + .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]), + ) + } + + fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> { + self.s.inputs.iter().enumerate().find_map(|(id, e)| { + let r = e.row?; + (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols) + .then_some((id, channel - e.col)) + }) + } + + fn load_input(&mut self, id: usize, col: u8) -> Val { + if self.s.inputs[id].half { + // shortcut: 16-bit vertex inputs (the fetch routine's) are not + // unpacked; pixel inputs are (`interp`). + return Val::Missing("a 16-bit input"); + } + self.load_any_input(id, col) + } + + /// An input element's channel as declared (16-bit ones as 32-bit floats). + fn load_any_input(&mut self, id: usize, col: u8) -> Val { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let (int, bit) = (e.comp != 9, e.comp == 1); + let ty = if bit { + self.s.t.i1 + } else if int { + self.s.t.i32 + } else { + self.s.t.f32 + }; + let suffix = if bit { + ".i1" + } else if int { + ".i32" + } else { + ".f32" + }; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.undef(self.s.t.i32), + ]; + let v = self.s.op( + entry, + &format!("loadInput{suffix}"), + Attr::ReadNone, + ty, + 4, + &args, + ); + if bit { + let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32); + Val::I32(z) + } else if int { + Val::I32(v) + } else { + Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32)) + } + } + + /// The DXIL form of an IR value. + fn get(&mut self, v: Value) -> Result<Val, Why> { + if self.phi_at.contains_key(&v) { + self.read_phis.insert(v); + } + let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v); + match self.vals.get(&v) { + Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => { + return self.mask_dword(v).map(Val::I32); + } + Some(&Val::Missing(w)) => return Err(w), + Some(&val) => return Ok(val), + None => {} + } + if let Some(&(param, dword)) = self.params.get(&v) { + let val = self.user(param, dword); + self.vals.insert(v, val); + return Ok(val); + } + Err("a value defined after its use") + } + + fn i32_of(&mut self, v: Value) -> Result<V, Why> { + match self.get(v)? { + Val::I32(x) => Ok(x), + Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)), + Val::Missing(w) => Err(w), + } + } + + /// A user-data dword: a root parameter's value. + fn user(&mut self, param: usize, dword: u32) -> Val { + let rp = self.x.native.layout[param]; + match rp.root { + RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), + RootType::Constants | RootType::Table => {} + _ => return Val::Missing("a root descriptor"), + } + let index = u32::from(rp.user_data) + dword; + self.user_reads.insert( + index, + UserData { + index, + slot: rp.slot, + root: rp.root, + dword, + }, + ); + self.s.user_data = self.s.user_data.max(index + 1); + let h = match self.user_data { + Some(h) => h, + None => { + let h = self.s.user_data_handle(); + self.user_data = Some(h); + h + } + }; + let entry = self.s.entry; + let row = self.s.m.i32(index / 4); + let r = self.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + Val::I32(self.s.m.extract(entry, r, index % 4)) + } + + /// A dword of a lane mask as a number: the ballot of the lanes' bits, + /// taken in the block that writes the mask (see [`MaskData`]). + fn mask_dword(&mut self, v: Value) -> Result<V, Why> { + let (lo, high) = match self.x.st.highs.get(&v) { + Some(&lo) => (lo, true), + None => (v, false), + }; + let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; + if !self.x.st.active.contains(&lo) { + return Err("a lane mask holding lanes elsewhere read as data"); + } + let (x, y) = match self.ballots.get(&lo) { + Some(&xy) => xy, + None => { + let at = match self.def_block.get(&lo) { + // Program inputs (EXEC on entry). + None => self.s.entry, + Some(&b) if b == self.cur_ir => self.cur, + Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + let bit = self.boolean(m, at)?; + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self + .s + .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); + self.s.flags |= flags::WAVE_OPS; + let xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + self.ballots.insert(lo, xy); + xy + } + }; + Ok(if high { y } else { x }) + } + + // ---- operands ---- + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Result<V, Why> { + match *op { + Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)), + Operand::Scalar { code, .. } => { + let v = inst.read(Reg::S(code)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Vector { reg, .. } => { + let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Const(c) => crate::resource::inline(c) + .map(|x| self.s.m.i32(x)) + .ok_or("a special operand (vccz, execz, scc, lds_direct)"), + Operand::Literal(x) => Ok(self.s.m.i32(x)), + Operand::Attr { .. } => Err("an attribute operand"), + } + } + + fn as_float(&mut self, x: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) + } + + fn as_int(&mut self, f: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32) + } + + /// The SDWA operand selection of source `k`: a byte or word of the + /// dword, zero- or sign-extended (none: the whole dword). + fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + let sel = *s.src_sel.get(k)?; + let sext = s.sext >> k & 1 != 0; + (sel < 6).then_some((sel, sext)) + } + + /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended. + fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8, 8 * sel) + } else { + (16, 16 * (sel - 4)) + }; + let left = self.s.m.i32(u32::from(32 - width - at)); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - u32::from(width)); + let op = if sext { Bin::AShr } else { Bin::LShr }; + self.s.m.bin(c, op, t, right) + } + + /// A float source with its abs/neg modifiers. + fn fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let selected = Self::sdwa_src(inst, k); + let mut f = match op { + _ if selected.is_some() => { + let (sel, sext) = selected.expect("checked"); + let x = self.operand(inst, &op)?; + let x = self.select_bits(x, sel, sext); + self.as_float(x) + } + _ if k == 0 && self.src0.is_some() => { + let x = self.src0.expect("checked"); + self.as_float(x) + } + Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. } + if !matches!(op, Operand::Scalar { code: NULL, .. }) => + { + let r = if matches!(op, Operand::Vector { .. }) { + Reg::V(reg) + } else { + Reg::S(reg) + }; + let val = inst.read(r).ok_or("an unread operand")?; + match self.floats.get(&val) { + Some(&f) => f, + None => { + let x = self.i32_of(val)?; + self.as_float(x) + } + } + } + _ => { + let x = self.operand(inst, &op)?; + self.as_float(x) + } + }; + if v.abs >> k & 1 != 0 { + f = self.unary(6, f); + } + if v.neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + fn src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 { + return Err("integer operand modifiers"); + } + match self.src0 { + Some(x) if k == 0 => Ok(x), + _ => { + let x = self.operand(inst, &op)?; + Ok(match Self::sdwa_src(inst, k) { + Some((sel, sext)) => self.select_bits(x, sel, sext), + None => x, + }) + } + } + } + + fn unary(&mut self, op: u32, f: V) -> V { + self.s.op( + self.cur, + "unary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[f], + ) + } + + fn binary(&mut self, op: u32, a: V, b: V) -> V { + self.s.op( + self.cur, + "binary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[a, b], + ) + } + + fn fmad(&mut self, a: V, b: V, c: V) -> V { + self.s.op( + self.cur, + "tertiary.f32", + Attr::ReadNone, + self.s.t.f32, + 46, + &[a, b, c], + ) + } + + /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even + /// conversion, one step back toward zero where it rounded away (which + /// also turns an overflow to infinity into the largest finite half). + fn f16_toward_zero(&mut self, f: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + let back = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]); + let (fa, ba) = (self.unary(6, f), self.unary(6, back)); + // Ordered: never for NaN. + let away = self.s.m.cmp(c, pred::OGT, ba, fa); + let one = self.s.m.i32(1); + let stepped = self.s.m.bin(c, Bin::Sub, h, one); + self.s.m.select(c, away, stepped, h) + } + + /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's + /// top bit when `signed`; widths from 32 on take every bit. + fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V { + let c = self.cur; + let (k31, k32, zero, one, ones) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(0), + self.s.m.i32(1), + self.s.m.i32(u32::MAX), + ); + let off = self.s.m.bin(c, Bin::And, off, k31); + let shifted = self.s.m.bin(c, Bin::LShr, a, off); + let full = self.s.m.cmp(c, pred::IUGE, width, k32); + let w = self.s.m.bin(c, Bin::And, width, k31); + let mask = self.s.m.bin(c, Bin::Shl, one, w); + let mask = self.s.m.bin(c, Bin::Sub, mask, one); + let mask = self.s.m.select(c, full, ones, mask); + let r = self.s.m.bin(c, Bin::And, shifted, mask); + if !signed { + return r; + } + // Sign-extend a field narrower than 32 bits (none for width 0). + let left = self.s.m.bin(c, Bin::Sub, k32, w); + let left = self.s.m.bin(c, Bin::And, left, k31); + let t = self.s.m.bin(c, Bin::Shl, r, left); + let t = self.s.m.bin(c, Bin::AShr, t, left); + let is0 = self.s.m.cmp(c, pred::EQ, w, zero); + let keep = self.s.m.bin(c, Bin::Or, full, is0); + self.s.m.select(c, keep, r, t) + } + + /// The high dword of a 32 × 32-bit product. + fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { + let c = self.cur; + let i64t = self.s.m.int(64); + let ext = if signed { Cast::SExt } else { Cast::ZExt }; + let a = self.s.m.cast(c, ext, a, i64t); + let b = self.s.m.cast(c, ext, b, i64t); + let m = self.s.m.bin(c, Bin::Mul, a, b); + let k32 = self.s.m.int_const(i64t, 32); + let hi = self.s.m.bin(c, Bin::LShr, m, k32); + self.s.flags |= flags::INT64; + self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) + } + + /// `0 × anything = 0`, as in D3D9. + fn legacy_mul(&mut self, a: V, b: V) -> V { + let c = self.cur; + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + let az = self.s.m.cmp(c, pred::OEQ, a, zero); + let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let z = self.s.m.bin(c, Bin::Or, az, bz); + self.s.m.select(c, z, zero, m) + } + + // ---- lane booleans ---- + + fn boolean(&mut self, b: Bool, at: usize) -> Result<V, Why> { + if b == Bool::TRUE || b == Bool::FALSE { + return Ok(self.s.m.bool(b == Bool::TRUE)); + } + if let Some(&v) = self.bools.get(&(at, b)) { + return Ok(v); + } + let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant"); + let a = self.atom(atom, at)?; + let m = &mut self.s.m; + let v = match (lo, hi) { + (Bool::FALSE, Bool::TRUE) => a, + (Bool::TRUE, Bool::FALSE) => { + let t = m.bool(true); + m.bin(at, Bin::Xor, a, t) + } + (Bool::FALSE, h) => { + let h = self.boolean(h, at)?; + self.s.m.bin(at, Bin::And, a, h) + } + (l, Bool::TRUE) => { + let l = self.boolean(l, at)?; + self.s.m.bin(at, Bin::Or, a, l) + } + (l, h) => { + let l = self.boolean(l, at)?; + let h = self.boolean(h, at)?; + self.s.m.select(at, a, h, l) + } + }; + self.bools.insert((at, b), v); + Ok(v) + } + + fn atom(&mut self, atom: Atom, at: usize) -> Result<V, Why> { + match atom { + Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| { + self.lane_fail + .get(&v) + .copied() + .unwrap_or("a lane mask from a carry") + }), + Atom::Uniform(v) => match self.get(v)? { + Val::Bit(x) => Ok(x), + Val::I32(x) => { + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, x, z)) + } + Val::Missing(w) => Err(w), + }, + Atom::Phi(id) => { + if let Some(&v) = self.mask_phis.get(&id) { + return Ok(v); + } + let &(b, i) = self + .phi_at + .get(&id) + .ok_or("a lane-mask join without a phi")?; + let blk = self.block[b].ok_or("an unreachable join")?; + let v = self.s.m.phi(blk, self.s.t.i1); + self.mask_phis.insert(id, v); + self.pending_masks.push((v, b, i)); + Ok(v) + } + // shortcut: "some lane of the quad is set" is taken as true: the + // lanes it adds only feed derivatives, and exports keep their own + // masks. Wrong if such a section had a side effect. + Atom::Quad(_) => Ok(self.s.m.bool(true)), + // With console lanes, a mask held as a number is the console's: + // the lane tests its own bit. + Atom::Opaque(v) if self.console_lanes => { + let hi = match self.pair_high(v) { + Some(h) => Some(self.get(h)?), + None => None, + }; + let lo = self.get(v)?; + let word = |w: Val| match w { + Val::I32(x) => Ok(x), + _ => Err("an opaque lane mask"), + }; + let lo = word(lo)?; + let hi = hi.map(word).transpose()?; + Ok(self.lane_bit(at, lo, hi)) + } + Atom::Constant(k) if self.console_lanes => { + let lo = self.s.m.i32(k as u32); + let hi = self.s.m.i32((k >> 32) as u32); + Ok(self.lane_bit(at, lo, Some(hi))) + } + Atom::Opaque(_) => Err("an opaque lane mask"), + Atom::Constant(_) => Err("a constant lane mask"), + } + } + + /// This lane's bit of the mask `lo`, `hi` (wave64). + fn lane_bit(&mut self, at: usize, lo: V, hi: Option<V>) -> V { + let lane = self.s.op( + at, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ); + let (k31, k32, one, z) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(1), + self.s.m.i32(0), + ); + let word = match hi { + Some(hi) => { + let low = self.s.m.cmp(at, pred::IULT, lane, k32); + self.s.m.select(at, low, lo, hi) + } + None => lo, + }; + let sh = self.s.m.bin(at, Bin::And, lane, k31); + let t = self.s.m.bin(at, Bin::LShr, word, sh); + let t = self.s.m.bin(at, Bin::And, t, one); + self.s.m.cmp(at, pred::NE, t, z) + } + + /// The value of the high dword of the wave64 register pair whose low + /// dword holds `lo` (none in wave32). + fn pair_high(&self, lo: Value) -> Option<Value> { + if !self.x.native.wave64 { + return None; + } + let p = self.x.p; + let pick = |reg: Reg| match reg { + Reg::S(c) => Some(Reg::S(c + 1)), + _ => None, + }; + if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) { + let h = pick(reg)?; + return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1); + } + if let Some(&(b, i)) = self.phi_at.get(&lo) { + let h = pick(p.blocks[b].phis[i].reg)?; + return p.blocks[b] + .phis + .iter() + .find(|q| q.reg == h) + .map(|q| q.value); + } + let b = *self.def_block.get(&lo)?; + let inst = p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == lo))?; + let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?; + inst.write(pick(reg)?) + } + + fn guard(&mut self, b: usize, i: usize) -> Result<Option<V>, Why> { + match self.x.st.guards[b][i] { + None => Ok(None), + Some(g) => Ok(Some(self.boolean(g, self.cur)?)), + } + } + + // ---- results ---- + + fn set(&mut self, v: Option<Value>, val: Val) { + if let Some(v) = v { + self.vals.insert(v, val); + } + } + + /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`. + fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) { + let x = match (Self::sdwa_dst(inst), reg) { + (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused), + _ => x, + }; + self.write_placed(inst, reg, x, guard); + } + + /// [`Self::write`] of a dword already placed (SDWA applied). + fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option<V>) { + let Some(new) = inst.write(reg) else { return }; + let x = match (guard, reg) { + (Some(g), Reg::V(_)) => { + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + // The validator refuses reads of undef. + _ => self.s.m.i32(0), + }; + self.s.m.select(self.cur, g, x, old) + } + _ => x, + }; + self.vals.insert(new, Val::I32(x)); + } + + /// The SDWA destination selection: a byte or word, and what the other + /// bits get (0 zeros, 1 the sign above the field, 2 the old bits). + fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused)) + } + + /// The low byte or word of `x` placed at `sel` in VGPR `reg`. + fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8u32, 8 * u32::from(sel)) + } else { + (16, 16 * u32::from(sel - 4)) + }; + let left = self.s.m.i32(32 - width); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - width - at); + if unused == 1 { + // Bits below the field shift in as zeros. + return self.s.m.bin(c, Bin::AShr, t, right); + } + let field = self.s.m.bin(c, Bin::LShr, t, right); + if unused != 2 { + return field; + } + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; + let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at)); + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, field) + } + + fn write_f(&mut self, inst: &Inst, f: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut f = f; + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let c = self.s.m.f32(factor.to_bits()); + f = self.s.m.bin(self.cur, Bin::Mul, f, c); + } + } + if v.clamp { + f = self.unary(7, f); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a float result outside a VGPR"); + }; + let x = self.as_int(f); + self.write(inst, Reg::V(reg), x, guard); + if guard.is_none() + && Self::sdwa_dst(inst).is_none() + && let Some(new) = inst.write(Reg::V(reg)) + { + self.floats.insert(new, f); + } + Ok(()) + } + + fn write_i(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.clamp || v.omod != 0 { + return Err("integer output modifiers"); + } + match v.dst { + Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard), + Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None), + _ => return Err("a result without a register"), + } + Ok(()) + } + + /// Starts code only the lanes where `guard` holds run (a store under a + /// lane guard): returns where it started and the join block. + fn begin_guarded(&mut self, guard: Option<V>) -> Option<(usize, usize)> { + let g = guard?; + let (then, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(self.cur, Term::CondBr(g, then, join)); + let head = self.cur; + self.cur = then; + Some((head, join)) + } + + /// Ends guarded code; each (value inside, value outside) becomes a phi. + fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec<V> { + let Some((head, join)) = at else { + return values.iter().map(|v| v.0).collect(); + }; + let then = self.cur; + self.s.m.terminate(then, Term::Br(join)); + self.cur = join; + values + .iter() + .map(|&(inside, outside)| { + let ty = self.s.m.type_of(inside); + let phi = self.s.m.phi(join, ty); + self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]); + phi + }) + .collect() + } + + /// Code that depends on the lane layout: wave operations, and in compute + /// the console's wave size (lanes are thread ids in group order there). + /// Pixel lanes match only within a quad. + fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { + if self.s.mesh.is_some() { + // shortcut: no wave size for mesh shaders in SM 6.6, so host + // lanes cannot follow the console's; emulate through group-shared + // memory if mesh programs turn out to need these. + return Err("a cross-lane operation in a mesh shader"); + } + if self.s.threads.is_none() && !(quad && self.s.pixel) { + return Err("a cross-lane operation outside compute"); + } + debug_assert!(self.s.threads.is_none() || self.console_lanes); + self.s.flags |= flags::WAVE_OPS; + Ok(()) + } + + /// Component `c` of the thread id in the group. With console lanes, the + /// thread is relabelled so that its host lane is its console lane: the + /// flat id is the wave's first lane's, rounded down to the wave size, + /// plus the lane index. (A bijection while each host wave holds a + /// wave-aligned run of flat ids, as the console's waves do.) + fn thread_id(&mut self, c: u8) -> Val { + if !self.console_lanes { + return self.compute_id("threadIdInGroup.i32", 95, c); + } + let [x, y, _] = self.s.threads.expect("compute"); + let e = self.s.entry; + let i32t = self.s.t.i32; + let flat = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + i32t, + 96, + &[], + ); + let first = self.s.op( + e, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + i32t, + 118, + &[flat], + ); + let wave = self.s.wave_size.expect("set with console lanes"); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + let lane = self.lane_index(); + let f = self.s.m.bin(e, Bin::Add, base, lane); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }) + } + + /// Mesh: the counts and the primitives no lane exports. The console's + /// counts come from one lane's allocation request, which DXIL cannot + /// express (one call, dominating every output write). + // shortcut: the counts are the declared maxima and each lane first culls + // its primitive (all indices 0, zero area), so primitives past the + // program's count are culled and vertices past it unused; this costs + // the host the unused vertex and primitive slots. Pass the program's own + // counts if that shows in frame time. + fn mesh_prologue(&mut self, mesh: super::shader::Mesh) -> Result<(), Why> { + let threads = self.s.threads.expect("mesh")[0]; + if mesh.topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { + return Err("a mesh shader beyond the host's limits"); + } + let e = self.s.entry; + let void = self.s.t.void; + let (v, p) = ( + self.s.m.i32(mesh.max_vertices), + self.s.m.i32(mesh.max_primitives), + ); + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + let flat = self.mesh_thread(); + let guard = (threads > mesh.max_primitives).then(|| self.s.m.cmp(e, pred::IULT, flat, p)); + let at = self.begin_guarded(guard); + let z = self.s.m.i32(0); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[flat, z, z, z], + ); + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: the thread's index in the group, which is its vertex and + /// primitive index. + fn mesh_thread(&mut self) -> V { + if let Some(f) = self.flat { + return f; + } + let e = self.s.entry; + let f = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + self.s.t.i32, + 96, + &[], + ); + self.flat = Some(f); + f + } + + /// The console wave size. + fn wave(&self) -> u32 { + if self.x.native.wave64 { 64 } else { 32 } + } + + fn lane_index(&mut self) -> V { + if self.s.mesh.is_some() { + // The console's lane: mesh code reads no other lanes, so host + // waves need not match the console's. + let f = self.mesh_thread(); + let m = self.s.m.i32(self.wave() - 1); + return self.s.m.bin(self.s.entry, Bin::And, f, m); + } + self.s.op( + self.cur, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ) + } + + /// `x` of lane `src` (in this lane's quad) through quad reads, whose + /// lane must be a constant. + fn quad_pick(&mut self, x: V, src: V) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let three = self.s.m.i32(3); + let q = self.s.m.bin(c, Bin::And, src, three); + let mut r = x; + for n in 0..4 { + let kn = self.s.m.i32(n); + let read = self.s.op( + c, + "quadReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 122, + &[x, kn], + ); + let is = self.s.m.cmp(c, pred::EQ, q, kn); + r = self.s.m.select(c, is, read, r); + } + r + } + + fn read_lane(&mut self, x: V, lane: V) -> V { + self.s.op( + self.cur, + "waveReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 117, + &[x, lane], + ) + } + + /// The float value of a register value. + fn float_of(&mut self, v: Value) -> Result<V, Why> { + if let Some(&f) = self.floats.get(&v) { + return Ok(f); + } + let x = self.i32_of(v)?; + Ok(self.as_float(x)) + } + + /// The values of VGPRs `reg..reg + n` as `inst` reads them. + fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result<Vec<V>, Why> { + let Operand::Vector { reg, .. } = *op else { + return Err("a vector operand"); + }; + (0..n) + .map(|k| { + let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?; + self.i32_of(v) + }) + .collect() + } + + /// LDS (thread-group shared memory) and `ds_swizzle`. + fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Ds { + dst, + addr, + data, + offset0, + offset1, + gds, + } = &inst.fields + else { + unreachable!() + }; + if *gds { + return Err("GDS"); + } + let name = inst.name(); + let guard = self.guard(b, i)?; + let c = self.cur; + let offset = u32::from(*offset0) | u32::from(*offset1) << 8; + let dst_reg = match dst { + Some(Operand::Vector { reg, .. }) => Some(*reg), + _ => None, + }; + if name == "ds_swizzle_b32" { + // Bit 15 set: each lane of a quad picks a lane of it; else lanes + // of each group of 32 combine their index with and/or/xor masks. + let quad = offset & 0x8000 != 0 + || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; + // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the + // console's, so quad-local swizzles read through quad operations. + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + // The source sits in the address field. + let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0]; + let lane = self.lane_index(); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let src = if offset & 0x8000 != 0 { + let (three, one) = (k(self, 3), k(self, 1)); + let sel = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, sel, one); + let pattern = k(self, offset & 0xFF); + let pick = self.s.m.bin(c, Bin::LShr, pattern, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let not3 = k(self, !3); + let base = self.s.m.bin(c, Bin::And, lane, not3); + self.s.m.bin(c, Bin::Or, base, pick) + } else { + let and = k(self, offset & 0x1F | !0x1F); + let or = k(self, offset >> 5 & 0x1F); + let xor = k(self, offset >> 10 & 0x1F); + let t = self.s.m.bin(c, Bin::And, lane, and); + let t = self.s.m.bin(c, Bin::Or, t, or); + self.s.m.bin(c, Bin::Xor, t, xor) + }; + let r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let reg = dst_reg.ok_or("a swizzle result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } + if self.s.lds_dwords == 0 { + return Err("LDS the program does not allocate"); + } + let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0]; + // shortcut: LDS addresses are taken as dword-aligned and in bounds + // (out-of-bounds console accesses read 0 and drop writes). + let dword = |l: &mut Self, bytes: u32| -> V { + let c = l.cur; + let o = l.s.m.i32(bytes); + let at = l.s.m.bin(c, Bin::Add, a, o); + let two = l.s.m.i32(2); + let index = l.s.m.bin(c, Bin::LShr, at, two); + let lds = l.s.lds(); + l.s.m.element(c, lds, index) + }; + let width = |n: &str| match n.rsplit('_').next() { + Some("b64") => 2, + Some("b96") => 3, + Some("b128") => 4, + _ => 1, + }; + // (byte offset, dwords) per element; read2/write2 scale their two + // offsets by the element size (×64 for st64). + let pair = |n: &str| -> Vec<(u32, u32)> { + let w = width(n); + let scale = 4 * w * if n.contains("st64") { 64 } else { 1 }; + vec![ + (u32::from(*offset0) * scale, w), + (u32::from(*offset1) * scale, w), + ] + }; + if let Some(rest) = name.strip_prefix("ds_read") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS read of bytes or halves"); + }; + let reg = dst_reg.ok_or("an LDS read result")?; + let mut n = 0; + for (off, w) in elements { + for k in 0..w { + let p = dword(self, off + 4 * k); + let x = self.s.m.load(self.cur, p); + self.write(inst, Reg::V(reg + n), x, guard); + n += 1; + } + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_write") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS write of bytes or halves"); + }; + let mut stores = Vec::new(); + for (e, (off, w)) in elements.into_iter().enumerate() { + let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?; + for (k, x) in vals.into_iter().enumerate() { + stores.push((off + 4 * k as u32, x)); + } + } + let at = self.begin_guarded(guard); + for (off, x) in stores { + let p = dword(self, off); + self.s.m.store(self.cur, p, x); + } + self.end_guarded(at, &[]); + return Ok(()); + } + // Atomics: the old value returns with `_rtn`. + let op = name + .strip_prefix("ds_") + .map(|n| n.replace("_rtn", "")) + .ok_or("an LDS operation")?; + use super::bitcode::Rmw; + let rmw = match op.as_str() { + "add_u32" => Some(Rmw::Add), + "sub_u32" => Some(Rmw::Sub), + "and_b32" => Some(Rmw::And), + "or_b32" => Some(Rmw::Or), + "xor_b32" => Some(Rmw::Xor), + "min_i32" => Some(Rmw::Min), + "max_i32" => Some(Rmw::Max), + "min_u32" => Some(Rmw::UMin), + "max_u32" => Some(Rmw::UMax), + "wrxchg_b32" => Some(Rmw::Xchg), + "cmpst_b32" => None, + _ => return Err("an LDS operation"), + }; + let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; + let v1 = match data.get(1) { + Some(d) => Some(self.vgprs(inst, d, 1)?[0]), + None => None, + }; + let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v))); + let outside = match old_reg { + Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)), + None => self.s.m.i32(0), + }; + let p = dword(self, offset); + let at = self.begin_guarded(guard); + let r = match rmw { + Some(op) => self.s.m.atomic(self.cur, op, p, v0), + // Compare with data0, store data1. + None => self + .s + .m + .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?), + }; + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + Ok(()) + } + + // ---- instructions ---- + + fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; + let offset = inst.machine.offset; + let name = inst.name(); + self.mask_ok = match self.mask_data { + MaskData::Console => true, + MaskData::Host => { + name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_") + || matches!( + name, + "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" + ) + } + MaskData::None => false, + }; + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || name == "s_barrier" + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + let r = match &inst.fields { + Fields::Sop { .. } => self.sop(inst), + Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), + Fields::Sopp { .. } if name == "s_barrier" => { + // Thread-group sync with a shared-memory fence, and a UAV + // fence when the program writes UAVs (the waits before an + // s_barrier make those writes visible on the console). + let mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + let mode = self.s.m.i32(mode); + let void = self.s.t.void; + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + Ok(()) + } + Fields::Sopp { .. } => Ok(()), + Fields::Smem { .. } => self.smem(inst, (b, i)), + Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), + Fields::Valu(_) => self.valu(inst, b, i), + Fields::Vintrp { .. } => self.interp(inst, (b, i)), + Fields::Image { .. } => self.image(inst, b, i), + Fields::Buffer { .. } => self.buffer(inst, b, i), + Fields::Exp { .. } => self.export(b, i), + Fields::Ds { .. } => self.ds(inst, b, i), + Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), + Fields::Flat { .. } => Err("flat memory"), + }; + match r { + Ok(()) => Ok(()), + Err(why) if effect => Err(unsupported(offset, why)), + Err(why) => { + for &(_, v) in &inst.writes { + self.vals.insert(v, Val::Missing(why)); + } + Ok(()) + } + } + } + + fn is_mask(&self, v: Option<Value>) -> bool { + v.is_some_and(|v| self.x.st.masks.contains_key(&v)) + } + + fn sop(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Sop { dst, src, imm } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let scc = inst.write(Reg::Scc); + let dst_code = match dst { + Some(Operand::Scalar { code, .. }) => Some(*code), + _ => None, + }; + let lo = dst_code.and_then(|c| inst.write(Reg::S(c))); + if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) { + return Err(LANE_MASK); + } + if matches!( + name, + "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version" + ) || name.starts_with("s_waitcnt") + { + // shortcut: the float MODE register is not modelled; s_swappc_b64 is the + // vertex fetch call, whose results arrive as inputs. + return Err("a register the emitter does not model"); + } + let c = self.cur; + let src32 = |l: &mut Self, k: usize| -> Result<V, Why> { + // SOPK arithmetic reads its destination as the first source. + if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") { + let d = dst.as_ref().ok_or("a missing operand")?; + return l.operand(inst, d); + } + let op = src.get(k).ok_or("a missing operand")?; + l.operand(inst, op) + }; + let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32); + // Dword `h` of 64-bit source `k` (inline constants sign-extend). + let half = |l: &mut Self, k: usize, h: u8| -> Result<V, Why> { + match src.get(k) { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?; + l.i32_of(v) + } + Some(op) if h == 0 => l.operand(inst, op), + Some(Operand::Const(k)) => { + let x = crate::resource::inline(*k).ok_or("a special operand")?; + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } + _ => Ok(l.s.m.i32(0)), + } + }; + if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) { + // eq and lg only: both dwords. + let mut r = None; + for h in 0..2 { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let e = self.s.m.cmp(c, pred::EQ, a, b); + r = Some(match r { + Some(x) => self.s.m.bin(c, Bin::And, x, e), + None => e, + }); + } + let mut r = r.expect("two dwords"); + if op.starts_with("lg") { + let t = self.s.m.bool(true); + r = self.s.m.bin(c, Bin::Xor, r, t); + } + self.set(scc, Val::Bit(r)); + return Ok(()); + } + if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) { + let (a, b) = if name.starts_with("s_cmpk_") { + let b = if op.ends_with("_i32") { + sext16(self) + } else { + self.s.m.i32(u32::from(imm.unwrap_or(0))) + }; + (src32(self, 0)?, b) + } else { + if op.ends_with("64") { + return Err("a 64-bit scalar compare"); + } + (src32(self, 0)?, src32(self, 1)?) + }; + let signed = op.ends_with("_i32"); + let p = match &op[..2] { + "eq" => pred::EQ, + "lg" => pred::NE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "lt" => pred::IULT, + "le" => pred::IULE, + _ => return Err("a scalar compare"), + }; + let r = self.s.m.cmp(c, p, a, b); + self.set(scc, Val::Bit(r)); + return Ok(()); + } + let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); + if wide { + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + let nonzero = |l: &mut Self, a: V, b: V| { + let o = l.s.m.bin(c, Bin::Or, a, b); + let z = l.s.m.i32(0); + l.s.m.cmp(c, pred::NE, o, z) + }; + return match name { + "s_bcnt1_i32_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let na = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]); + let nb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]); + let r = self.s.m.bin(c, Bin::Add, na, nb); + self.set(lo, Val::I32(r)); + let z = self.s.m.i32(0); + let s = self.s.m.cmp(c, pred::NE, r, z); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_ff1_i32_b64" => { + // The lowest set bit; -1 for none (as DXIL's first bit low). + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let fa = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]); + let fb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + let fb32 = self.s.m.bin(c, Bin::Add, fb, k32); + let none = self.s.m.cmp(c, pred::EQ, b, z); + let fb = self.s.m.select(c, none, fb, fb32); + let low = self.s.m.cmp(c, pred::NE, a, z); + let r = self.s.m.select(c, low, fa, fb); + self.set(lo, Val::I32(r)); + Ok(()) + } + "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64" + | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => { + let ones = self.s.m.i32(u32::MAX); + let mut r = Vec::new(); + for h in 0..2u8 { + let a = half(self, 0, h)?; + let x = if name == "s_not_b64" { + self.s.m.bin(c, Bin::Xor, a, ones) + } else { + let mut b = half(self, 1, h)?; + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") { + self.s.m.bin(c, Bin::Xor, x, ones) + } else { + x + } + }; + r.push(x); + } + self.set(lo, Val::I32(r[0])); + self.set(hi, Val::I32(r[1])); + let s = nonzero(self, r[0], r[1]); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let n = src32(self, 1)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let k32 = self.s.m.int_const(i64t, 32); + let b = self.s.m.bin(c, Bin::Shl, b, k32); + let x = self.s.m.bin(c, Bin::Or, a, b); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "s_lshl_b64" => Bin::Shl, + "s_lshr_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32); + let rh = self.s.m.bin(c, Bin::LShr, r, k32); + let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32); + self.set(lo, Val::I32(rl)); + self.set(hi, Val::I32(rh)); + let s = nonzero(self, rl, rh); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_mov_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + self.set(lo, Val::I32(a)); + self.set(hi, Val::I32(b)); + Ok(()) + } + "s_cselect_b64" => { + let cond = self.scc_in(inst)?; + for (h, v) in [(0, lo), (1, hi)] { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let r = self.s.m.select(c, cond, a, b); + self.set(v, Val::I32(r)); + } + Ok(()) + } + _ => Err(name), + }; + } + let m = &mut self.s.m; + let _ = m; + let (r, carry): (V, Option<V>) = match name { + "s_mov_b32" => (src32(self, 0)?, None), + "s_movk_i32" => (sext16(self), None), + "s_cselect_b32" => { + let cond = self.scc_in(inst)?; + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.s.m.select(c, cond, a, b), None) + } + "s_brev_b32" => { + let a = src32(self, 0)?; + let r = self + .s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]); + (r, None) + } + "s_not_b32" => { + let a = src32(self, 0)?; + let ones = self.s.m.i32(u32::MAX); + (self.s.m.bin(c, Bin::Xor, a, ones), None) + } + "s_add_u32" | "s_add_i32" | "s_addk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_addk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + let r = self.s.m.bin(c, Bin::Add, a, b); + let carry = if name == "s_add_u32" { + Some(self.s.m.cmp(c, pred::IULT, r, a)) + } else { + None + }; + (r, carry) + } + "s_sub_u32" | "s_sub_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let r = self.s.m.bin(c, Bin::Sub, a, b); + let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); + (r, carry) + } + "s_addc_u32" | "s_subb_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let cin = self.scc_in(inst)?; + let cin32 = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); + let op = if name == "s_addc_u32" { + Bin::Add + } else { + Bin::Sub + }; + let t = self.s.m.bin(c, op, a, b); + let r = self.s.m.bin(c, op, t, cin32); + (r, None) + } + "s_mul_i32" | "s_mulk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_mulk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + (self.s.m.bin(c, Bin::Mul, a, b), None) + } + "s_mul_hi_u32" | "s_mul_hi_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.mul_hi(a, b, name.ends_with("i32")), None) + } + "s_flbit_i32_b32" | "s_flbit_i32" => { + // The first bit from the top (differing from the sign for + // the signed form), -1 for none: DXIL's first-bit-high. + let a = src32(self, 0)?; + let op = if name == "s_flbit_i32_b32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => { + // First set bit (-1 for zero, as DXIL's), or the bit count. + let a = src32(self, 0)?; + let op = if name == "s_ff1_i32_b32" { 32 } else { 31 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_bfe_u32" | "s_bfe_i32" => { + // src1: offset in bits 0-4, width in bits 16-22. + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F)); + let w = self.s.m.bin(c, Bin::LShr, b, k16); + let w = self.s.m.bin(c, Bin::And, w, k127); + (self.bfe(a, b, w, name == "s_bfe_i32"), None) + } + "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32" + | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => { + let (a, mut b) = (src32(self, 0)?, src32(self, 1)?); + let ones = self.s.m.i32(u32::MAX); + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let mut r = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") { + r = self.s.m.bin(c, Bin::Xor, r, ones); + } + (r, None) + } + "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let op = match name { + "s_lshl_b32" => Bin::Shl, + "s_lshr_b32" => Bin::LShr, + _ => Bin::AShr, + }; + (self.s.m.bin(c, op, a, b), None) + } + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0')); + let t = self.s.m.bin(c, Bin::Shl, a, k); + (self.s.m.bin(c, Bin::Add, t, b), None) + } + "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let p = match name { + "s_min_u32" => pred::IULT, + "s_max_u32" => pred::IUGT, + "s_min_i32" => pred::SLT, + _ => pred::SGT, + }; + let t = self.s.m.cmp(c, p, a, b); + (self.s.m.select(c, t, a, b), None) + } + "s_abs_i32" => { + let a = src32(self, 0)?; + let z = self.s.m.i32(0); + let neg = self.s.m.cmp(c, pred::SLT, a, z); + let n = self.s.m.bin(c, Bin::Sub, z, a); + (self.s.m.select(c, neg, n, a), None) + } + "s_bitset0_b32" | "s_bitset1_b32" => { + // Sets (clears) bit src[4:0] of the destination it reads. + let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?; + let a = src32(self, 0)?; + let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1)); + let a = self.s.m.bin(c, Bin::And, a, k31); + let bit = self.s.m.bin(c, Bin::Shl, one, a); + if name == "s_bitset1_b32" { + (self.s.m.bin(c, Bin::Or, old, bit), None) + } else { + let ones = self.s.m.i32(u32::MAX); + let nb = self.s.m.bin(c, Bin::Xor, bit, ones); + (self.s.m.bin(c, Bin::And, old, nb), None) + } + } + "s_bfm_b32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let one = self.s.m.i32(1); + let a = self.s.m.bin(c, Bin::And, a, k31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + (self.s.m.bin(c, Bin::Shl, m, b), None) + } + _ => return Err(name), + }; + self.set(lo, Val::I32(r)); + if let Some(scc) = scc { + let val = match carry { + Some(k) => Val::Bit(k), + None if matches!( + name, + "s_mov_b32" + | "s_movk_i32" + | "s_cselect_b32" + | "s_brev_b32" + | "s_mul_i32" + | "s_mulk_i32" + ) => + { + return Ok(()); + } + None if name.starts_with("s_add") || name.starts_with("s_sub") => { + Val::Missing("the carry of a scalar operation") + } + None => { + let z = self.s.m.i32(0); + Val::Bit(self.s.m.cmp(c, pred::NE, r, z)) + } + }; + self.vals.insert(scc, val); + } + Ok(()) + } + + fn scc_in(&mut self, inst: &Inst) -> Result<V, Why> { + let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + match self.get(v)? { + Val::Bit(x) => Ok(x), + _ => Err("SCC without a value"), + } + } + + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Fields::Smem { + data, + offset, + soffset, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { + return self.code_smem(inst, a); + } + let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { + return self.descriptor_data(inst, site); + }; + let count = match rest { + "" => 1, + "x2" => 2, + "x4" => 4, + "x8" => 8, + "x16" => 16, + _ => return Err("a scalar buffer load"), + }; + let Some(Operand::Scalar { code, .. }) = *data else { + return Err("a scalar buffer load"); + }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked descriptor")?; + let kind = self.used_kind(src); + let c = self.cur; + let (base, extra) = self.built_offset(src)?; + let offset = &((*offset as u32).wrapping_add(base) as i32); + let mut addr = self.s.m.i32(*offset as u32); + if let Some(x) = extra { + addr = self.s.m.bin(c, Bin::Add, addr, x); + } + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(inst, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + if matches!(src, Source::Built { address, .. } if address.param == CODE) { + // A descriptor built around a table in the code. + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(a)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let h = self.handle(site, src, false, (11, 0))?; + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + let x = self.as_int(x); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let constant = match addr { + V::Const(_) + if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() => + { + Some(*offset as u32) + } + _ => None, + }; + let mut rows: HashMap<u32, V> = HashMap::new(); + for k in 0..count { + let x = match constant { + Some(base) => { + let byte = base + 4 * k; + let row = match rows.get(&(byte >> 4)) { + Some(&r) => r, + None => { + let ri = self.s.m.i32(byte >> 4); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + rows.insert(byte >> 4, r); + r + } + }; + self.s.m.extract(c, row, (byte >> 2) & 3) + } + None => { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + self.cbuffer_dword(h, a) + } + }; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords + /// the code also reads as numbers: the console compiler computes sizes + /// from descriptor bits (an image's width, height, depth, levels; a + /// buffer's record count) instead of querying them. Those fields are + /// rebuilt from the host view's dimensions in the GFX10 layout (image + /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits + /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at + /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). + // shortcut: the base level reads 0 (the host view starts at its own + // level 0, so sizes the code shifts by it come out right) and the other + // dwords (addresses, formats, tiling) have no host value: reading them + // stops the program. + fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + const OTHER: Why = "a descriptor's address or format read as data"; + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory read as data"), + }; + // How the program uses the descriptor tells the view's kind. + let use_at = self + .x + .res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .find_map(|d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == site => Some((d.site, first)), + _ => None, + }) + }); + let Some((at, first)) = use_at else { + return Err("a descriptor read only as data"); + }; + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + ((kind | u, 0x409), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + (10 | u, 0x409) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + return Err("a constant buffer's descriptor read as data"); + } + (props, None) + } + _ => return Err("a scalar memory read as data"), + }; + let h = self.handle(site, &src, false, props)?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = if image.is_some() && !uav { + self.s.m.i32(0) + } else { + self.s.m.undef(i32t) + }; + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); + let words: Vec<(u32, V)> = match image { + Some(kind) => { + let one = self.s.m.i32(1); + let w = field(self, 0); + let (height, depth) = match kind { + 1 => (one, one), + 2 => (field(self, 1), one), + 6 => (one, field(self, 1)), + _ => (field(self, 1), field(self, 2)), + }; + let levels = if uav { one } else { field(self, 3) }; + let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); + let (w, height, depth, levels) = ( + less(self, w), + less(self, height), + less(self, depth), + less(self, levels), + ); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k30, k2, k14, k16, mask) = ( + k(self, 30), + k(self, 2), + k(self, 14), + k(self, 16), + k(self, 0x3FFF), + ); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; + let base = k(self, 0xFAC | ty << 28); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, base, last); + vec![(1, d1), (2, d2), (3, d3), (4, depth)] + } + None => vec![(2, field(self, 0))], + }; + for k in 0..count { + let rel = k.wrapping_sub(u32::from(first)); + match words.iter().find(|w| w.0 == rel) { + Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), + None => { + if let Some(v) = inst.write(Reg::S(code + k as u8)) { + self.vals.insert(v, Val::Missing(OTHER)); + } + } + } + } + Ok(()) + } + + /// `s_load_dword*` from the program's constant table. + fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar load"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar load from the code"), + }; + let c = self.cur; + let mut addr = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + addr = self.s.m.bin(c, Bin::Add, addr, d); + } + for k in 0..count { + let off = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(at)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// The dword at a computed byte address of a constant buffer. + fn cbuffer_dword(&mut self, h: V, a: V) -> V { + let c = self.cur; + let four = self.s.m.i32(4); + let ri = self.s.m.bin(c, Bin::LShr, a, four); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + let two = self.s.m.i32(2); + let three = self.s.m.i32(3); + let comp = self.s.m.bin(c, Bin::LShr, a, two); + let comp = self.s.m.bin(c, Bin::And, comp, three); + let mut x = self.s.m.extract(c, r, 0); + for j in 1..4 { + let e = self.s.m.extract(c, r, j); + let jc = self.s.m.i32(j); + let is = self.s.m.cmp(c, pred::EQ, comp, jc); + x = self.s.m.select(c, is, e, x); + } + x + } + + /// `channels` channels of the element at byte `off` of raw buffer `h`, + /// converted from the GFX10 buffer format `format` as the hardware's + /// typed loads do (channels past the format's read 0, 0, 0, 1). + // shortcut: the descriptor's channel swizzle is taken as the identity + // (it is for raw views and the descriptors code builds), elements of 4 + // bytes or more as dword-aligned, and the packed float and 10_10_10_2 + // layouts are refused; decode them when a program needs them. Norm + // formats divide, which the AMD driver does 1 ULP off the hardware's + // correctly rounded conversion for some values; correct it with an + // integer check if a title compares converted values exactly. + fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> { + let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let total: u32 = bits.iter().sum(); + let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let load = |l: &mut Self, at: V, n: u32| -> Vec<V> { + let mask = l.s.m.i8((1u8 << n) - 1); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, u, mask, align], + ); + (0..n) + .map(|k| { + let x = l.s.m.extract(c, r, k); + l.as_int(x) + }) + .collect() + }; + let words = if total < 32 { + // A byte or half inside the dword that holds it. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = load(self, at, 1)[0]; + let byte = self.s.m.bin(c, Bin::And, off, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + vec![self.s.m.bin(c, Bin::LShr, w, sh)] + } else { + load(self, off, total / 32) + }; + let float = |l: &mut Self, f: V| l.as_int(f); + let mut out = Vec::new(); + let mut at = 0; + for &w in bits { + let word = words[(at / 32) as usize]; + let field = if w == 32 { + word + } else { + let sh = self.s.m.i32(at % 32); + let t = self.s.m.bin(c, Bin::LShr, word, sh); + let m = self.s.m.i32((1 << w) - 1); + self.s.m.bin(c, Bin::And, t, m) + }; + at += w; + // Sign-extended from the field's top bit. + let signed = |l: &mut Self| { + if w == 32 { + return field; + } + let k = l.s.m.i32(32 - w); + let t = l.s.m.bin(c, Bin::Shl, field, k); + l.s.m.bin(c, Bin::AShr, t, k) + }; + let f32t = self.s.t.f32; + let x = match numeric { + Numeric::Unorm => { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + float(self, q) + } + Numeric::Snorm => { + let s = signed(self); + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + let lo = self.s.m.f32((-1.0f32).to_bits()); + let q = self.binary(35, q, lo); + float(self, q) + } + Numeric::Uscaled => { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + float(self, f) + } + Numeric::Sscaled => { + let s = signed(self); + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + float(self, f) + } + Numeric::Uint => field, + Numeric::Sint => signed(self), + Numeric::Float if w == 32 => field, + Numeric::Float => { + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[field]); + float(self, f) + } + }; + out.push(x); + } + let one = match numeric { + Numeric::Uint | Numeric::Sint => 1, + _ => 1.0f32.to_bits(), + }; + for k in out.len() as u32..channels { + out.push(self.s.m.i32(if k == 3 { one } else { 0 })); + } + out.truncate(channels as usize); + Ok(out) + } + + /// The byte offset a buffer descriptor built around a root descriptor adds + /// (constant and computed parts); none for other descriptors. + fn built_offset(&mut self, src: &Source) -> Result<(u32, Option<V>), Why> { + match src { + Source::Built { address, .. } => { + let x = match address.dynamic { + Some(v) => Some(self.i32_of(v)?), + None => None, + }; + Ok((address.offset, x)) + } + _ => Ok((0, None)), + } + } + + /// The used-resource entry a descriptor loaded from a table falls in. + fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { + if let Source::Phi { args, .. } = src { + return self.used_kind(args.first()?); + } + if let Source::Built { address, .. } = src { + let rp = self.x.native.layout.get(address.param)?; + return self + .x + .native + .used + .iter() + .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data); + } + let Source::Loaded { load, first } = src else { + return None; + }; + let a = self.scalar.get(load)?; + let rp = self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table { + return None; + } + let dword = (a.offset / 4) + u32::from(*first); + self.x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords) + } + + /// A handle for the descriptor `src` read at `site`. + fn handle( + &mut self, + site: Site, + src: &Source, + sampler: bool, + props: (u32, u32), + ) -> Result<V, Why> { + match src { + Source::Loaded { load, first } => { + let key = (self.cur, *load, *first, sampler, props.0); + if let Some(&h) = self.handles.get(&key) { + return Ok(h); + } + let index = self.heap_index(*load, *first, sampler)?; + let h = self.s.heap_handle(self.cur, index, sampler, props); + self.handles.insert(key, h); + Ok(h) + } + Source::Constant(words) if sampler => { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + if props.0 & 0x8000 != 0 { + // shortcut: one sampler used with and without comparison + // would need two static samplers; it becomes a comparison one. + self.s.cmp_samplers |= 1 << n; + } + Ok(self.s.sampler_handle(self.cur, n as u32)) + } + Source::Constant(_) => Err("a constant resource descriptor"), + Source::Built { address, .. } => { + let rp = *self + .x + .native + .layout + .get(address.param) + .ok_or("a descriptor built around a table in the code")?; + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + match (rp.root, kind, props.0) { + (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => { + Ok(self.s.root_cbv_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 11) => { + Ok(self.s.root_srv_handle(rp.slot)) + } + _ => Err("a root UAV or typed root view"), + } + } + Source::Phi { block, args } => { + // Each predecessor computes its heap index at its end; the + // join picks one with a phi. + let _ = site; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let (Some(tail), Source::Loaded { load, first }) = (self.tail[q], arg) else { + return Err("a descriptor chosen by control flow"); + }; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + incoming.push((index?, at)); + } + let join = self.block[*block].ok_or("a descriptor chosen by control flow")?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(self.s.heap_handle(self.cur, phi, sampler, props)) + } + } + } + + /// The heap index of the descriptor at dword `first` of what the scalar + /// load at `load` reads, computed in the current block. + fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result<V, Why> { + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Smem { + base, + offset, + soffset, + .. + } = &li.fields + else { + return Err("a descriptor load"); + }; + let Operand::Scalar { code, .. } = *base else { + return Err("a descriptor load"); + }; + let c = self.cur; + let base = li.read(Reg::S(code)).ok_or("a descriptor load")?; + let mut addr = self.i32_of(base)?; + let k = self + .s + .m + .i32((*offset as u32).wrapping_add(4 * u32::from(first))); + addr = self.s.m.bin(c, Bin::Add, addr, k); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(li, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, addr, shift)) + } + + fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { + let r = if v.dpp.is_some() { + Err("a compare with DPP") + } else { + self.compare(inst, rest) + }; + if let Err(why) = r { + for &(_, w) in &inst.writes { + self.lane_fail.insert(w, why); + } + } + return r; + } + let mut guard = self.guard(b, i)?; + if let Some(d) = v.dpp { + let (x, enable) = self.dpp(inst, d)?; + guard = match (guard, enable) { + (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)), + (g, e) => g.or(e), + }; + self.src0 = Some(x); + } + let r = self.valu_op(inst, guard); + self.src0 = None; + r + } + + /// DPP: src0 as read from another lane, and which lanes write their + /// result (none: all). + fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option<V>), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(&Operand::Vector { reg, .. }) = v.src.first() else { + return Err("a DPP operand"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; + // Quad permutations and DPP8 stay in groups the pixel layout shares. + let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + let c = self.cur; + let lane = self.lane_index(); + let k = |l: &mut Self, n: u32| l.s.m.i32(n); + let (sixteen_mask, low) = (k(self, !15), k(self, 15)); + let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask); + let pos = self.s.m.bin(c, Bin::And, lane, low); + // Source lane, and whether it lies in the row. + let (src, inside, masks, zero) = match dpp { + Dpp::Lanes { sel, .. } => { + let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3)); + let p = self.s.m.bin(c, Bin::And, lane, seven); + let sh = self.s.m.bin(c, Bin::Mul, p, three); + let sel = k(self, sel); + let pick = self.s.m.bin(c, Bin::LShr, sel, sh); + let pick = self.s.m.bin(c, Bin::And, pick, seven); + let base = self.s.m.bin(c, Bin::And, lane, not7); + (self.s.m.bin(c, Bin::Or, base, pick), None, None, false) + } + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let n = u32::from(ctrl & 15); + let (src, inside) = match ctrl { + 0..=0xFF => { + let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3)); + let p = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, p, one); + let perm = k(self, u32::from(ctrl)); + let pick = self.s.m.bin(c, Bin::LShr, perm, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let base = self.s.m.bin(c, Bin::And, lane, not3); + (self.s.m.bin(c, Bin::Or, base, pick), None) + } + 0x101..=0x10F | 0x111..=0x11F => { + let nn = k(self, n); + let left = ctrl < 0x110; + let (op, p) = if left { + (Bin::Add, pred::IULT) + } else { + (Bin::Sub, pred::IUGE) + }; + let s = self.s.m.bin(c, op, lane, nn); + // Left: pos + n < 16; right: pos >= n. + let bound = if left { k(self, 16 - n) } else { nn }; + (s, Some(self.s.m.cmp(c, p, pos, bound))) + } + 0x121..=0x12F => { + let nn = k(self, n); + let t = self.s.m.bin(c, Bin::Sub, pos, nn); + let t = self.s.m.bin(c, Bin::And, t, low); + (self.s.m.bin(c, Bin::Or, row, t), None) + } + 0x140 | 0x141 => { + let m = k(self, if ctrl == 0x140 { 15 } else { 7 }); + let t = self.s.m.bin(c, Bin::Xor, lane, m); + (t, None) + } + 0x150..=0x15F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Or, row, nn), None) + } + 0x160..=0x16F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Xor, lane, nn), None) + } + _ => return Err("a DPP lane pattern"), + }; + let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask)); + (src, inside, masks, bound_ctrl) + } + }; + let mut r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let mut enable = None; + if let Some(inside) = inside { + if zero { + let z = k(self, 0); + r = self.s.m.select(c, inside, r, z); + } else { + enable = Some(inside); + } + } + if let Some((rows, banks)) = masks { + // Row (16 lanes) and bank (4 lanes of a row) write masks. + let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3)); + let ri = self.s.m.bin(c, Bin::LShr, lane, four); + let ri = self.s.m.bin(c, Bin::And, ri, three); + let bi = self.s.m.bin(c, Bin::LShr, lane, two); + let bi = self.s.m.bin(c, Bin::And, bi, three); + let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks))); + let rb = self.s.m.bin(c, Bin::LShr, rm, ri); + let bb = self.s.m.bin(c, Bin::LShr, bm, bi); + let both = self.s.m.bin(c, Bin::And, rb, bb); + let (one, z) = (k(self, 1), k(self, 0)); + let both = self.s.m.bin(c, Bin::And, both, one); + let on = self.s.m.cmp(c, pred::NE, both, z); + enable = Some(match enable { + Some(e) => self.s.m.bin(c, Bin::And, e, on), + None => on, + }); + } + Ok((r, enable)) + } + + fn valu_op(&mut self, inst: &Inst, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let c = self.cur; + let f = |l: &mut Self, k| l.fsrc(inst, k); + let s = |l: &mut Self, k| l.src(inst, k); + let float = |l: &mut Self, r: V| l.write_f(inst, r, guard); + let int = |l: &mut Self, r: V| l.write_i(inst, r, guard); + if let Some(r) = self.valu16(inst, name, guard) { + return r; + } + if let Some(op) = name.strip_prefix("v_pk_") { + return self.packed16(inst, op, guard); + } + match name { + "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { + let n = s(self, 0)?; + let x = self.src64(inst, 1)?; + let i64t = self.s.m.int(64); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "v_lshlrev_b64" => Bin::Shl, + "v_lshrrev_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + Ok(()) + } + "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => { + // Cube-map face coordinates (AMD's ISA): the major axis is z + // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, + // else x. + let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z)); + let zx = self.s.m.cmp(c, pred::OGE, az, ax); + let zy = self.s.m.cmp(c, pred::OGE, az, ay); + let zmaj = self.s.m.bin(c, Bin::And, zx, zy); + let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax); + let zero = self.s.m.f32(0); + let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero); + let minus = |l: &mut Self, v: V| { + let z = l.s.m.f32(0x8000_0000); + l.s.m.bin(c, Bin::Sub, z, v) + }; + let pick = |l: &mut Self, zv: V, yv: V, xv: V| { + let t = l.s.m.select(c, ymaj, yv, xv); + l.s.m.select(c, zmaj, zv, t) + }; + let r = match name { + "v_cubeid_f32" => { + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x)); + let (f5, f4, f3, f2, f1, f0) = ( + k(self, 5.0), + k(self, 4.0), + k(self, 3.0), + k(self, 2.0), + k(self, 1.0), + k(self, 0.0), + ); + let zf = self.s.m.select(c, nz, f5, f4); + let yf = self.s.m.select(c, ny, f3, f2); + let xf = self.s.m.select(c, nx, f1, f0); + pick(self, zf, yf, xf) + } + "v_cubesc_f32" => { + let (nz, nx) = (neg(self, z), neg(self, x)); + let (mx, mz) = (minus(self, x), minus(self, z)); + let zf = self.s.m.select(c, nz, mx, x); + let xf = self.s.m.select(c, nx, z, mz); + pick(self, zf, x, xf) + } + "v_cubetc_f32" => { + let ny = neg(self, y); + let (my, mz) = (minus(self, y), minus(self, z)); + let yf = self.s.m.select(c, ny, mz, z); + pick(self, my, yf, my) + } + _ => { + let t = pick(self, z, y, x); + let two = self.s.m.f32(2.0f32.to_bits()); + self.s.m.bin(c, Bin::Mul, t, two) + } + }; + float(self, r) + } + "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => { + // M0 indexes the source (movrels), the destination (movreld) + // or both, from the encoded register up to the program's + // VGPR count (the registers the instruction reads or writes). + let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?; + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("an M0-relative move"); + }; + let indexed_src = name != "v_movreld_b32"; + let value = if indexed_src { + let mut r = self.s.m.i32(0); + for k in 0..=255u8.saturating_sub(sreg) { + let Some(x) = inst.read(Reg::V(sreg + k)) else { + break; + }; + let x = self.i32_of(x)?; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + r = self.s.m.select(c, is, x, r); + } + r + } else { + s(self, 0)? + }; + if name == "v_movrels_b32" { + return int(self, value); + } + for k in 0..=255u8.saturating_sub(dreg) { + let Some(_) = inst.write(Reg::V(dreg + k)) else { + break; + }; + let old = match inst.read(Reg::V(dreg + k)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + let x = self.s.m.select(c, is, value, old); + self.write_placed(inst, Reg::V(dreg + k), x, guard); + } + Ok(()) + } + "v_ffbh_u32" | "v_ffbh_i32" => { + // Counted from the top bit, -1 when none (DXIL's too). + let a = s(self, 0)?; + let op = if name == "v_ffbh_u32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + int(self, r) + } + "v_mov_b32" => { + if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 { + let a = f(self, 0)?; + return float(self, a); + } + let a = s(self, 0)?; + int(self, a) + } + "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32" + | "v_max_f32" | "v_min_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let r = match name { + "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb), + "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb), + "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a), + "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb), + "v_mul_legacy_f32" => self.legacy_mul(a, bb), + "v_max_f32" => self.binary(35, a, bb), + _ => self.binary(36, a, bb), + }; + float(self, r) + } + "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => { + // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse. + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = self.fmad(a, bb, cc); + float(self, r) + } + "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?; + let acc = match self.floats.get(&acc) { + Some(&x) => x, + None => { + let x = self.i32_of(acc)?; + self.as_float(x) + } + }; + let r = match name { + "v_fmac_f32" => self.fmad(a, bb, acc), + "v_mac_f32" => { + let m = self.s.m.bin(c, Bin::Mul, a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + _ => { + let m = self.legacy_mul(a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + }; + float(self, r) + } + "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = if name == "v_mad_legacy_f32" { + self.legacy_mul(a, bb) + } else { + self.s.m.bin(c, Bin::Mul, a, bb) + }; + let r = self.s.m.bin(c, Bin::Add, m, cc); + float(self, r) + } + "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = match name { + "v_max3_f32" => { + let t = self.binary(35, a, bb); + self.binary(35, t, cc) + } + "v_min3_f32" => { + let t = self.binary(36, a, bb); + self.binary(36, t, cc) + } + _ => { + let lo = self.binary(36, a, bb); + let hi = self.binary(35, a, bb); + let t = self.binary(36, hi, cc); + self.binary(35, lo, t) + } + }; + float(self, r) + } + "v_rcp_f32" | "v_rcp_iflag_f32" => { + // shortcut: the hardware reciprocal is approximate (1 ULP); this divides. + let a = f(self, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + let r = self.s.m.bin(c, Bin::SDiv, one, a); + float(self, r) + } + "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32" + | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32" + | "v_cos_f32" => { + let mut a = f(self, 0)?; + let op = match name { + "v_rsq_f32" => 25, + "v_sqrt_f32" => 24, + "v_log_f32" => 23, + "v_exp_f32" => 21, + "v_fract_f32" => 22, + "v_trunc_f32" => 29, + "v_floor_f32" => 27, + "v_ceil_f32" => 28, + "v_rndne_f32" => 26, + "v_sin_f32" => 13, + _ => 12, + }; + if op == 13 || op == 12 { + // The hardware takes revolutions. + let k = self.s.m.f32(TWO_PI.to_bits()); + a = self.s.m.bin(c, Bin::Mul, a, k); + } + let r = self.unary(op, a); + float(self, r) + } + "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { + let mut a = f(self, 0)?; + if name == "v_cvt_rpi_i32_f32" { + let h = self.s.m.f32(0.5f32.to_bits()); + a = self.s.m.bin(c, Bin::Add, a, h); + } + if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" { + a = self.unary(27, a); + } + // D3D's conversions saturate and give 0 for NaN, as the + // hardware does (checked on the RX 6700 XT and WARP). + let op = if name == "v_cvt_u32_f32" { + Cast::FpToUi + } else { + Cast::FpToSi + }; + let r = self.s.m.cast(c, op, a, self.s.t.i32); + int(self, r) + } + "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" + | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { + let mut a = s(self, 0)?; + if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") { + let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0')); + let ff = self.s.m.i32(0xff); + a = self.s.m.bin(c, Bin::LShr, a, sh); + a = self.s.m.bin(c, Bin::And, a, ff); + } + let op = if name == "v_cvt_f32_i32" { + Cast::SiToFp + } else { + Cast::UiToFp + }; + let r = self.s.m.cast(c, op, a, self.s.t.f32); + float(self, r) + } + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + // Each source is f32, or with op_sel_hi the low (op_sel: high) + // f16 half; neg_hi is the absolute value here. + let mut xs = Vec::new(); + for i in 0..3 { + let op = v.src.get(i).ok_or("a missing operand")?; + let x = self.operand(inst, op)?; + let mut x = if v.opsel_hi >> i & 1 != 0 { + let h = if v.opsel >> i & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) + } else { + self.as_float(x) + }; + if v.neg_hi >> i & 1 != 0 { + x = self.unary(6, x); + } + if v.neg >> i & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + x = self.s.m.bin(c, Bin::Sub, z, x); + } + xs.push(x); + } + let mut r = self.fmad(xs[0], xs[1], xs[2]); + if name == "v_fma_mix_f32" { + return float(self, r); + } + if v.clamp { + r = self.unary(7, r); + } + // The f16 result goes to one half; the other half stays. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a mixed-precision result"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]); + let (keep, h) = if name == "v_fma_mixhi_f16" { + let k16 = self.s.m.i32(16); + (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16)) + } else { + (0xFFFF_0000, h) + }; + let keep = self.s.m.i32(keep); + let old = self.s.m.bin(c, Bin::And, old, keep); + let x = self.s.m.bin(c, Bin::Or, old, h); + self.write(inst, Reg::V(reg), x, guard); + Ok(()) + } + "v_cvt_pkrtz_f16_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let lo = self.f16_toward_zero(a); + let hi = self.f16_toward_zero(bb); + let sh = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, sh); + let r = self.s.m.bin(c, Bin::Or, lo, hi); + int(self, r) + } + "v_cvt_f16_f32" if v.opsel == 0 => { + // Rounded to nearest even (the MODE default) into the low half. + let a = f(self, 0)?; + let r = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let r = self.low_half(inst, reg, r); + int(self, r) + } + "v_pack_b32_f16" => { + // Two f16 sources (op_sel: their high halves; abs and neg on + // the sign bit) into the low and high half. + let mut halves = Vec::new(); + for k in 0..2 { + let op = v.src.get(k).ok_or("a missing operand")?; + let mut x = self.operand(inst, op)?; + if v.opsel >> k & 1 != 0 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF }; + let mask = self.s.m.i32(mask); + x = self.s.m.bin(c, Bin::And, x, mask); + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000); + x = self.s.m.bin(c, Bin::Xor, x, sign); + } + halves.push(x); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + int(self, r) + } + "v_cvt_f32_f16" if v.opsel == 0 => { + let a = s(self, 0)?; + let r = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]); + float(self, r) + } + "v_cndmask_b32" => { + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let m = mask + .and_then(|m| self.x.st.masks.get(&m).copied()) + .ok_or("a select on an untracked mask")?; + let cond = self.boolean(m, c)?; + if v.abs != 0 || v.neg != 0 { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let r = self.s.m.select(c, cond, bb, a); + return float(self, r); + } + let (a, bb) = (s(self, 0)?, s(self, 1)?); + let r = self.s.m.select(c, cond, bb, a); + int(self, r) + } + "v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" | "v_add_co_ci_u32" + | "v_sub_co_ci_u32" | "v_subrev_co_ci_u32" => { + // The carry (borrow) out is a lane mask: this lane's bit. + let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?); + if name.contains("subrev") { + std::mem::swap(&mut a, &mut bb); + } + let cin = if name.ends_with("_ci_u32") { + let m = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let m = m + .and_then(|m| self.x.st.masks.get(&m).copied()) + .ok_or("a carry-in from an untracked mask")?; + Some(self.boolean(m, c)?) + } else { + None + }; + let add = name.starts_with("v_add"); + let op = if add { Bin::Add } else { Bin::Sub }; + let mut r = self.s.m.bin(c, op, a, bb); + // Without a carry in: a + b wraps below a; a - b borrows when a < b. + let mut carry = if add { + self.s.m.cmp(c, pred::IULT, r, a) + } else { + self.s.m.cmp(c, pred::IULT, a, bb) + }; + if let Some(cin) = cin { + let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); + let t = r; + r = self.s.m.bin(c, op, t, one); + // The carry in carries on when the partial result is all + // ones (add) or zero (sub). + let edge = self.s.m.i32(if add { u32::MAX } else { 0 }); + let at_edge = self.s.m.cmp(c, pred::EQ, t, edge); + let more = self.s.m.bin(c, Bin::And, cin, at_edge); + carry = self.s.m.bin(c, Bin::Or, carry, more); + } + int(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_readlane_b32" => { + let (a, lane) = (s(self, 0)?, s(self, 1)?); + // A computed lane in a pixel or vertex program is a host lane + // (from a mask or `v_mbcnt`); a constant one is the console's. + if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + self.s.flags |= flags::WAVE_OPS; + } else { + self.cross_lane(false)?; + } + let r = self.read_lane(a, lane); + int(self, r) + } + "v_writelane_b32" => { + // The lane given takes the scalar; the others keep their value. + let (a, lane) = (s(self, 0)?, s(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a lane write"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + self.cross_lane(false)?; + let me = self.lane_index(); + let is = self.s.m.cmp(c, pred::EQ, me, lane); + let r = self.s.m.select(c, is, a, old); + int(self, r) + } + "v_readfirstlane_b32" => { + let a = s(self, 0)?; + self.s.flags |= flags::WAVE_OPS; + let r = self.s.op( + c, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + self.s.t.i32, + 118, + &[a], + ); + int(self, r) + } + _ => { + let r = self.integer(inst, name)?; + int(self, r) + } + } + } + + /// A 64-bit source (a register pair; inline constants sign-extend). + fn src64(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let c = self.cur; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<V, Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + let lo = l.s.m.cast(c, Cast::ZExt, lo, i64t); + let hi = l.s.m.cast(c, Cast::ZExt, hi, i64t); + let k32 = l.s.m.int_const(i64t, 32); + let hi = l.s.m.bin(c, Bin::Shl, hi, k32); + Ok(l.s.m.bin(c, Bin::Or, lo, hi)) + }; + match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)), + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1)) + } + Operand::Const(k @ 128..=208) => { + let x = crate::resource::inline(k).ok_or("a special operand")?; + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } + _ => { + // Literals and the null register: zero-extended. + let x = self.operand(inst, &op)?; + Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) + } + } + } + + /// The low and high dwords of an i64. + fn split64(&mut self, x: V) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let k32 = self.s.m.int_const(i64t, 32); + let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + let hi = self.s.m.bin(c, Bin::LShr, x, k32); + let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32); + (lo, hi) + } + + /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0): + /// op_sel (or an SDWA word select) picks the high half; inline float + /// constants are f16 values here. + fn half_src(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let mut high = v.opsel >> k & 1 != 0; + if let Some(sd) = v.sdwa { + match sd.src_sel.get(k).copied().unwrap_or(6) { + 4 => {} + 5 => high = true, + 6 => {} + _ => return Err("a byte select on a 16-bit operation"), + } + } + let x = match (op, self.src0) { + (_, Some(x)) if k == 0 => x, + (Operand::Const(c @ 240..=248), _) => { + let h = [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)]; + self.s.m.i32(h) + } + _ => self.operand(inst, &op)?, + }; + let c = self.cur; + let x = if high { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// An f16 source as an f32 (exact), with its abs/neg modifiers. + fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let h = self.half_src(inst, k)?; + let f32t = self.s.t.f32; + let mut f = self + .s + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + if v.abs >> k & 1 != 0 { + f = self.unary(6, f); + } + if v.neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + /// Writes a 16-bit result (low bits of `x`) into the destination's low + /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select); + /// the other half is kept (GFX10). + fn write_half(&mut self, inst: &Inst, x: V, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let mut high = v.opsel >> 3 & 1 != 0; + // SDWA: the word written, the other one kept (preserve) or zero + // (pad; a sign extension above the high word adds nothing). + let mut keep = true; + if let Some(sd) = v.sdwa { + match (sd.dst_sel, sd.dst_unused) { + (4, 2) => {} + (5, 2) => high = true, + (4 | 6, _) => keep = false, + (5, _) => (high, keep) = (true, false), + _ => return Err("an SDWA destination of a 16-bit operation"), + } + } + let c = self.cur; + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) if keep => o, + _ => self.s.m.i32(0), + }; + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let x = self.s.m.bin(c, Bin::And, x, low); + let r = if high { + let o = self.s.m.bin(c, Bin::And, old, low); + let x = self.s.m.bin(c, Bin::Shl, x, k16); + self.s.m.bin(c, Bin::Or, o, x) + } else { + let keep = self.s.m.i32(0xFFFF_0000); + let o = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, o, x) + }; + self.write_placed(inst, Reg::V(reg), r, guard); + Ok(()) + } + + /// 16-bit operations, computed in f32 or i32: f16 sums, differences and + /// products are exact there and round once to f16 (f32 has the 2 x 11 + + /// 2 bits that make double rounding harmless); `None` if `name` is none. + fn valu16(&mut self, inst: &Inst, name: &str, guard: Option<V>) -> Option<Result<(), Why>> { + const FLOAT2: &[&str] = &[ + "v_add_f16", + "v_sub_f16", + "v_subrev_f16", + "v_mul_f16", + "v_max_f16", + "v_min_f16", + ]; + const FLOAT3: &[&str] = &[ + "v_fma_f16", + "v_mad_f16", + "v_fmac_f16", + "v_mac_f16", + "v_max3_f16", + "v_min3_f16", + "v_med3_f16", + ]; + const FLOAT1: &[&str] = &[ + "v_rcp_f16", + "v_sqrt_f16", + "v_rsq_f16", + "v_log_f16", + "v_exp_f16", + "v_fract_f16", + "v_trunc_f16", + "v_floor_f16", + "v_ceil_f16", + "v_rndne_f16", + "v_sin_f16", + "v_cos_f16", + "v_cvt_f16_u16", + "v_cvt_f16_i16", + ]; + const INT: &[&str] = &[ + "v_add_nc_u16", + "v_sub_nc_u16", + "v_subrev_nc_u16", + "v_mul_lo_u16", + "v_lshlrev_b16", + "v_lshrrev_b16", + "v_ashrrev_i16", + "v_max_u16", + "v_max_i16", + "v_min_u16", + "v_min_i16", + "v_cvt_u16_f16", + "v_cvt_i16_f16", + ]; + let all = [FLOAT1, FLOAT2, FLOAT3, INT]; + if !all.iter().any(|l| l.contains(&name)) + && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16") + { + return None; + } + Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3)) + } + + #[allow(clippy::too_many_arguments)] + fn valu16_op( + &mut self, + inst: &Inst, + name: &str, + guard: Option<V>, + float1: &[&str], + float2: &[&str], + float3: &[&str], + ) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let i32t = self.s.t.i32; + let f32t = self.s.t.f32; + if name == "v_cvt_f32_f16" { + let f = self.half_fsrc(inst, 0)?; + return self.write_f(inst, f, guard); + } + let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { + if v.omod != 0 { + return Err("an output modifier on a 16-bit operation"); + } + if v.clamp { + f = l.unary(7, f); + } + let h = + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + l.write_half(inst, h, guard) + }; + if name == "v_cvt_f16_f32" { + let f = self.fsrc(inst, 0)?; + return float_result(self, f); + } + if float2.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let r = match name { + "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_max_f16" => self.binary(35, a, b), + _ => self.binary(36, a, b), + }; + return float_result(self, r); + } + if float3.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") { + // The accumulator is the destination's half that is written. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?; + let x = if v.opsel >> 3 & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, m); + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.half_fsrc(inst, 2)? + }; + let r = match name { + // shortcut: fused f16 multiply-adds as FMad in f32 (the + // product is exact; the sum rounds twice). + "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc), + "v_max3_f16" => { + let t = self.binary(35, a, b); + self.binary(35, t, acc) + } + "v_min3_f16" => { + let t = self.binary(36, a, b); + self.binary(36, t, acc) + } + _ => { + let lo = self.binary(36, a, b); + let hi = self.binary(35, a, b); + let t = self.binary(36, hi, acc); + self.binary(35, lo, t) + } + }; + return float_result(self, r); + } + if float1.contains(&name) { + let r = match name { + "v_cvt_f16_u16" | "v_cvt_f16_i16" => { + let mut x = self.half_src(inst, 0)?; + let op = if name == "v_cvt_f16_i16" { + let k16 = self.s.m.i32(16); + let t = self.s.m.bin(c, Bin::Shl, x, k16); + x = self.s.m.bin(c, Bin::AShr, t, k16); + Cast::SiToFp + } else { + Cast::UiToFp + }; + self.s.m.cast(c, op, x, f32t) + } + "v_rcp_f16" => { + let a = self.half_fsrc(inst, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + self.s.m.bin(c, Bin::SDiv, one, a) + } + _ => { + let mut a = self.half_fsrc(inst, 0)?; + let op = match name { + "v_sqrt_f16" => 24, + "v_rsq_f16" => 25, + "v_log_f16" => 23, + "v_exp_f16" => 21, + "v_fract_f16" => 22, + "v_trunc_f16" => 29, + "v_floor_f16" => 27, + "v_ceil_f16" => 28, + "v_rndne_f16" => 26, + "v_sin_f16" => 13, + _ => 12, + }; + if op == 13 || op == 12 { + let k = self.s.m.f32(TWO_PI.to_bits()); + a = self.s.m.bin(c, Bin::Mul, a, k); + } + self.unary(op, a) + } + }; + return float_result(self, r); + } + // 16-bit integers: computed on the low halves, the low 16 bits kept. + if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = match name { + "v_cvt_u16_f16" | "v_cvt_i16_f16" => { + // shortcut: converted through 32 bits, so out-of-range values + // wrap instead of saturating at 16 bits. + let a = self.half_fsrc(inst, 0)?; + let op = if name == "v_cvt_u16_f16" { + Cast::FpToUi + } else { + Cast::FpToSi + }; + self.s.m.cast(c, op, a, i32t) + } + _ => { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if name.ends_with("_i16") { + a = sext(self, a); + b = sext(self, b); + } + let k15 = self.s.m.i32(15); + match name { + "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { + // src0 is the shift (4 bits), src1 the value. + let sh = self.s.m.bin(c, Bin::And, a, k15); + let x = if name == "v_ashrrev_i16" { + sext(self, b) + } else { + b + }; + let op = match name { + "v_lshlrev_b16" => Bin::Shl, + "v_lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, x, sh) + } + _ => { + let p = match name { + "v_max_u16" => pred::IUGT, + "v_min_u16" => pred::IULT, + "v_max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + } + } + }; + self.write_half(inst, r, guard) + } + + /// Half `high` of source `k` of a packed (VOP3P) operation, in the low + /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the + /// half the high result reads. Inline float constants are f16 values. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; + let x = match op { + Operand::Const(c @ 240..=248) => { + let h = [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)]; + // shortcut: taken to fill both halves. + self.s.m.i32(h | h << 16) + } + _ => self.operand(inst, &op)?, + }; + let c = self.cur; + let x = if sel { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// Packed 16-bit operations (`v_pk_*`): each half computed as the + /// 16-bit operation does, f16 through f32 as in [`Self::valu16`]. + fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let float = op.ends_with("_f16"); + let n = match op { + "fma_f16" | "mad_u16" | "mad_i16" => 3, + "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16" + | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" + | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, + _ => return Err("a packed 16-bit operation"), + }; + if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) { + return Err("modifiers on a packed integer operation"); + } + let c = self.cur; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let mut halves = Vec::new(); + for high in [false, true] { + let mut xs = Vec::new(); + for k in 0..n { + let h = self.packed_src(inst, k, high)?; + if float { + let mut f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + let neg = if high { v.neg_hi } else { v.neg }; + if neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(c, Bin::Sub, z, f); + } + xs.push(f); + } else { + xs.push(h); + } + } + let r = if float { + let mut f = match op { + "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), + "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), + "min_f16" => self.binary(36, xs[0], xs[1]), + "max_f16" => self.binary(35, xs[0], xs[1]), + // shortcut: FMad in f32, as v_fma_f16. + _ => self.fmad(xs[0], xs[1], xs[2]), + }; + if v.clamp { + f = self.unary(7, f); + } + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + } else { + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if op.ends_with("_i16") { + for x in &mut xs { + *x = sext(self, *x); + } + } + let k15 = self.s.m.i32(15); + match op { + "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), + "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]), + "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), + "mad_u16" | "mad_i16" => { + let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]); + self.s.m.bin(c, Bin::Add, m, xs[2]) + } + "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => { + let sh = self.s.m.bin(c, Bin::And, xs[0], k15); + let o = match op { + "lshlrev_b16" => Bin::Shl, + "lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + let x = if op == "ashrrev_i16" { + sext(self, xs[1]) + } else { + xs[1] + }; + self.s.m.bin(c, o, x, sh) + } + _ => { + let p = match op { + "max_u16" => pred::IUGT, + "min_u16" => pred::IULT, + "max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, xs[0], xs[1]); + self.s.m.select(c, t, xs[0], xs[1]) + } + } + }; + let m = self.s.m.i32(0xFFFF); + halves.push(self.s.m.bin(c, Bin::And, r, m)); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a packed result outside a VGPR"); + }; + self.write(inst, Reg::V(reg), r, guard); + Ok(()) + } + + fn integer(&mut self, inst: &Inst, name: &'static str) -> Result<V, Why> { + let c = self.cur; + let s = |l: &mut Self, k| l.src(inst, k); + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let m31 = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + l.s.m.bin(c, Bin::And, x, k31) + }; + Ok(match name { + "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32" + | "v_subrev_nc_u32" | "v_mul_lo_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (op, a, b) = match name { + "v_and_b32" => (Bin::And, a, b), + "v_or_b32" => (Bin::Or, a, b), + "v_xor_b32" => (Bin::Xor, a, b), + "v_add_nc_u32" => (Bin::Add, a, b), + "v_sub_nc_u32" => (Bin::Sub, a, b), + "v_subrev_nc_u32" => (Bin::Sub, b, a), + _ => (Bin::Mul, a, b), + }; + self.s.m.bin(c, op, a, b) + } + "v_not_b32" => { + let a = s(self, 0)?; + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, a, ones) + } + "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => { + let (sh, a) = (s(self, 0)?, s(self, 1)?); + let sh = m31(self, sh); + let op = match name { + "v_lshlrev_b32" => Bin::Shl, + "v_lshrrev_b32" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, a, sh) + } + "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32" + | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + match name { + "v_lshl_add_u32" | "v_lshl_or_b32" => { + let b = m31(self, b); + let t = self.s.m.bin(c, Bin::Shl, a, b); + let op = if name == "v_lshl_add_u32" { + Bin::Add + } else { + Bin::Or + }; + self.s.m.bin(c, op, t, d) + } + "v_add_lshl_u32" => { + let t = self.s.m.bin(c, Bin::Add, a, b); + let d = m31(self, d); + self.s.m.bin(c, Bin::Shl, t, d) + } + _ => { + let (o1, o2) = match name { + "v_and_or_b32" => (Bin::And, Bin::Or), + "v_or3_b32" => (Bin::Or, Bin::Or), + "v_xad_u32" => (Bin::Xor, Bin::Add), + "v_add3_u32" => (Bin::Add, Bin::Add), + _ => (Bin::Xor, Bin::Xor), + }; + let t = self.s.m.bin(c, o1, a, b); + self.s.m.bin(c, o2, t, d) + } + } + } + "v_mul_u32_u24" | "v_mul_i32_i24" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mul_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.s.m.bin(c, Bin::Mul, a, b) + } + "v_bfe_u32" | "v_bfe_i32" => { + let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let w = m31(self, w); + self.bfe(a, off, w, name == "v_bfe_i32") + } + "v_bfi_b32" => { + let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let ones = k(self, u32::MAX); + let nm = self.s.m.bin(c, Bin::Xor, m, ones); + let x = self.s.m.bin(c, Bin::And, m, a); + let y = self.s.m.bin(c, Bin::And, nm, b); + self.s.m.bin(c, Bin::Or, x, y) + } + "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let p = match name { + "v_max_i32" => pred::SGT, + "v_min_i32" => pred::SLT, + "v_max_u32" => pred::IUGT, + _ => pred::IULT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + "v_mul_hi_u32" | "v_mul_hi_i32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + self.mul_hi(a, b, name == "v_mul_hi_i32") + } + "v_alignbit_b32" | "v_alignbyte_b32" => { + // The low dword of {a, b} >> shift. + let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let sh = if name == "v_alignbyte_b32" { + let three = k(self, 3); + let t = self.s.m.bin(c, Bin::And, sh, three); + let k3 = k(self, 3); + self.s.m.bin(c, Bin::Shl, t, k3) + } else { + m31(self, sh) + }; + let k32 = k(self, 32); + let lo = self.s.m.bin(c, Bin::LShr, b, sh); + let left = self.s.m.bin(c, Bin::Sub, k32, sh); + let left = m31(self, left); + let hi = self.s.m.bin(c, Bin::Shl, a, left); + let zero = k(self, 0); + let none = self.s.m.cmp(c, pred::EQ, sh, zero); + let hi = self.s.m.select(c, none, zero, hi); + self.s.m.bin(c, Bin::Or, lo, hi) + } + "v_bfrev_b32" => { + let a = s(self, 0)?; + self.s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]) + } + "v_bcnt_u32_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]); + self.s.m.bin(c, Bin::Add, n, b) + } + "v_mad_u32_u24" | "v_mad_i32_i24" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mad_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + let m = self.s.m.bin(c, Bin::Mul, a, b); + self.s.m.bin(c, Bin::Add, m, d) + } + "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" + | "v_med3_u32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let signed = name.ends_with("i32"); + let (lt, gt) = if signed { + (pred::SLT, pred::SGT) + } else { + (pred::IULT, pred::IUGT) + }; + let pick = |l: &mut Self, p, x, y| { + let t = l.s.m.cmp(c, p, x, y); + l.s.m.select(c, t, x, y) + }; + match &name[2..6] { + "min3" => { + let t = pick(self, lt, a, b); + pick(self, lt, t, d) + } + "max3" => { + let t = pick(self, gt, a, b); + pick(self, gt, t, d) + } + _ => { + let lo = pick(self, lt, a, b); + let hi = pick(self, gt, a, b); + let t = pick(self, lt, hi, d); + pick(self, gt, lo, t) + } + } + } + "v_perm_b32" => { + // Byte i of the result is byte S of {src0, src1} (src1 the + // low dword) for selector byte S below 8; 8-11 repeat the + // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00, + // higher 0xFF. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let sel = match v.src.get(2) { + Some(&Operand::Literal(x)) => x, + Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?, + _ => { + // A computed selector: each byte picked at run time. + let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let wa = self.s.m.cast(c, Cast::ZExt, a, i64t); + let wb = self.s.m.cast(c, Cast::ZExt, b, i64t); + let k32 = self.s.m.int_const(i64t, 32); + let wa = self.s.m.bin(c, Bin::Shl, wa, k32); + let both = self.s.m.bin(c, Bin::Or, wa, wb); + let mut r = k(self, 0); + for i in 0..4u32 { + let (sh, ff) = (k(self, 8 * i), k(self, 0xFF)); + let sel = self.s.m.bin(c, Bin::LShr, sv, sh); + let sel = self.s.m.bin(c, Bin::And, sel, ff); + // Bytes 0-7 of {src0, src1}. + let k3 = k(self, 3); + let bits = self.s.m.bin(c, Bin::Shl, sel, k3); + let bits = self.s.m.cast(c, Cast::ZExt, bits, i64t); + let x = self.s.m.bin(c, Bin::LShr, both, bits); + let x = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + let mut byte = self.s.m.bin(c, Bin::And, x, ff); + // 8-11: the sign of bytes 1, 3 of src1, then of src0. + for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)] + { + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let t = self.s.m.bin(c, Bin::And, t, ff); + let kn = k(self, n); + let is = self.s.m.cmp(c, pred::EQ, sel, kn); + byte = self.s.m.select(c, is, t, byte); + } + let (k12, z) = (k(self, 12), k(self, 0)); + let is12 = self.s.m.cmp(c, pred::EQ, sel, k12); + byte = self.s.m.select(c, is12, z, byte); + let above = self.s.m.cmp(c, pred::IUGT, sel, k12); + byte = self.s.m.select(c, above, ff, byte); + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + return Ok(r); + } + }; + let (a, b) = (s(self, 0)?, s(self, 1)?); + let mut r = k(self, 0); + for i in 0..4 { + let pick = sel >> (8 * i) & 0xFF; + let byte = match pick { + 0..=7 => { + let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) }; + let sh = k(self, 8 * n); + let t = self.s.m.bin(c, Bin::LShr, src, sh); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 8..=11 => { + let src = if pick < 10 { b } else { a }; + let bit = if pick % 2 == 0 { 15 } else { 31 }; + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 12 => continue, + _ => k(self, 0xFF), + }; + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + r + } + "v_bfm_b32" => { + // ((1 << src0[4:0]) - 1) << src1[4:0] + let (a, b) = (s(self, 0)?, s(self, 1)?); + let one = k(self, 1); + let (a, b) = (m31(self, a), m31(self, b)); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + self.s.m.bin(c, Bin::Shl, m, b) + } + "v_cvt_pk_u8_f32" => { + // src0 rounded to nearest even and saturated to a byte, into + // byte src1[1:0] of src2. + let f = self.fsrc(inst, 0)?; + let (b, d) = (s(self, 1)?, s(self, 2)?); + let f = self.unary(26, f); + let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits())); + let f = self.binary(35, f, zero); + let f = self.binary(36, f, max); + let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32); + let (three, k3) = (k(self, 3), k(self, 3)); + let sh = self.s.m.bin(c, Bin::And, b, three); + let sh = self.s.m.bin(c, Bin::Shl, sh, k3); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let ff = k(self, 0xFF); + let hole = self.s.m.bin(c, Bin::Shl, ff, sh); + let ones = k(self, u32::MAX); + let hole = self.s.m.bin(c, Bin::Xor, hole, ones); + let d = self.s.m.bin(c, Bin::And, d, hole); + self.s.m.bin(c, Bin::Or, d, x) + } + "v_ffbl_b32" => { + // -1 for zero, as DXIL's first-bit-low. + let a = s(self, 0)?; + self.s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a]) + } + "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => { + // Bits of the mask's low (high) half below this lane, plus src1: + // with an all-ones mask, the lane index. + let (a, b) = (s(self, 0)?, s(self, 1)?); + // Mesh lanes are the console's by construction; pixel and + // vertex lanes are the host's, as their masks are. + if self.mask_data == MaskData::Host { + // Host lanes: the mask must be one (a ballot) or all lanes. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let host = match v.src.first() { + Some(&Operand::Const(193)) => true, + Some(&Operand::Scalar { code, .. }) => { + inst.read(Reg::S(code)).is_some_and(|m| { + self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m) + }) + } + _ => false, + }; + if !host { + return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); + } + self.s.flags |= flags::WAVE_OPS; + } else if self.s.mesh.is_none() { + self.cross_lane(false)?; + } + let lane = self.lane_index(); + let below = if name == "v_mbcnt_lo_u32_b32" { + lane + } else { + let (k32, z) = (k(self, 32), k(self, 0)); + let t = self.s.m.bin(c, Bin::Sub, lane, k32); + let low = self.s.m.cmp(c, pred::IULT, lane, k32); + self.s.m.select(c, low, z, t) + }; + // (1 << below) - 1, all ones from 32 on. + let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX)); + let sh = m31(self, below); + let m = self.s.m.bin(c, Bin::Shl, one, sh); + let m = self.s.m.bin(c, Bin::Sub, m, one); + let full = self.s.m.cmp(c, pred::IUGE, below, k32); + let m = self.s.m.select(c, full, ones, m); + let x = self.s.m.bin(c, Bin::And, a, m); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]); + self.s.m.bin(c, Bin::Add, n, b) + } + _ => return Err(name), + }) + } + + fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> { + let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?; + let c = self.cur; + let r = match ty { + "f32" if op == "class" => { + // Bit k of src1 tests class k: signalling NaN, quiet NaN, + // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. + let x = self.fsrc(inst, 0)?; + let x = self.as_int(x); + let mask = self.src(inst, 1)?; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k23, k31, kff, mant, quiet) = ( + k(self, 23), + k(self, 31), + k(self, 0xFF), + k(self, 0x7F_FFFF), + k(self, 0x40_0000), + ); + let e = self.s.m.bin(c, Bin::LShr, x, k23); + let e = self.s.m.bin(c, Bin::And, e, kff); + let m = self.s.m.bin(c, Bin::And, x, mant); + let neg = self.s.m.bin(c, Bin::LShr, x, k31); + let zero = k(self, 0); + let (e0, e255) = ( + self.s.m.cmp(c, pred::EQ, e, zero), + self.s.m.cmp(c, pred::EQ, e, kff), + ); + let m0 = self.s.m.cmp(c, pred::EQ, m, zero); + let q = self.s.m.bin(c, Bin::And, x, quiet); + let q = self.s.m.cmp(c, pred::NE, q, zero); + // Positive classes 6-9; negative ones are 11 minus those. + let (normal, inf, zero_c, denorm) = + (k(self, 8), k(self, 9), k(self, 6), k(self, 7)); + let t = self.s.m.select(c, m0, zero_c, denorm); + let t = self.s.m.select(c, e0, t, normal); + let t = self.s.m.select(c, e255, inf, t); + let eleven = k(self, 11); + let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t); + let is_neg = self.s.m.cmp(c, pred::NE, neg, zero); + let t = self.s.m.select(c, is_neg, mirrored, t); + let (one, snan) = (k(self, 1), k(self, 0)); + let nan_class = self.s.m.select(c, q, one, snan); + let yes = self.s.m.bool(true); + let nan = self.s.m.bin(c, Bin::Xor, m0, yes); + let nan = self.s.m.bin(c, Bin::And, nan, e255); + let t = self.s.m.select(c, nan, nan_class, t); + let bit = self.s.m.bin(c, Bin::LShr, mask, t); + let bit = self.s.m.bin(c, Bin::And, bit, one); + self.s.m.cmp(c, pred::NE, bit, zero) + } + "f32" | "f16" => { + let (a, b) = if ty == "f16" { + (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) + } else { + (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) + }; + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "lg" => pred::ONE, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } + "u64" | "i64" => { + let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); + let signed = ty == "i64"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + _ => return Err("a 64-bit compare"), + }; + self.s.m.cmp(c, p, a, b) + } + "u32" | "i32" | "u16" | "i16" => { + let (a, b) = if ty.ends_with("16") { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + if ty == "i16" { + let k16 = self.s.m.i32(16); + for x in [&mut a, &mut b] { + let t = self.s.m.bin(c, Bin::Shl, *x, k16); + *x = self.s.m.bin(c, Bin::AShr, t, k16); + } + } + (a, b) + } else { + (self.src(inst, 0)?, self.src(inst, 1)?) + }; + let signed = ty == "i32" || ty == "i16"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "f" | "t" => { + self.lane(inst, Some(op == "t")); + return Ok(()); + } + _ => return Err("an integer compare"), + }; + self.s.m.cmp(c, p, a, b) + } + _ => return Err(inst.name()), + }; + self.lane_bits_for(inst, r); + Ok(()) + } + + fn lane(&mut self, inst: &Inst, value: Option<bool>) { + let b = self.s.m.bool(value == Some(true)); + self.lane_bits_for(inst, b); + } + + fn lane_bits_for(&mut self, inst: &Inst, r: V) { + let Fields::Valu(v) = &inst.fields else { + return; + }; + let code = if inst.name().starts_with("v_cmpx") { + Some(EXEC) + } else { + match v.dst { + Some(Operand::Scalar { code, .. }) => Some(code), + _ => None, + } + }; + if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) { + self.lane_bits.insert(lo, r); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + } + + fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Some(&interp) = self.interps.get(&site) else { + return Err("the first half of an interpolation"); + }; + let (attribute, mode) = match interp { + Interp::Interpolated { + attribute, + barycentric, + .. + } => ( + attribute, + match barycentric { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return Err("pull-model interpolation"), + }, + ), + // P0, the provoking vertex: a flat (nointerpolation) input. + Interp::Vertex { + attribute, + vertex: 2, + } => (attribute, 1), + Interp::Vertex { .. } => return Err("a non-provoking vertex value"), + }; + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => *dst, + Fields::Valu(v) => v.dst.ok_or("an interpolation")?, + _ => unreachable!(), + }; + let Operand::Vector { reg, .. } = dst else { + return Err("an interpolation"); + }; + // A channel of an input element, interpolated as `mode` says. + let channel = |l: &mut Self, row: u8, ch: u8| -> Result<V, Why> { + let (id, col) = l + .find_input(row, ch) + .ok_or("an input the signature lacks")?; + let e = &mut l.s.inputs[id]; + if e.interp != mode && e.usage != 0 { + return Err("one input interpolated two ways"); + } + e.interp = mode; + match l.load_any_input(id, col) { + Val::I32(x) => Ok(x), + _ => Err("an input"), + } + }; + let packing = match &self.x.native.io { + StageIo::Ps { inputs, .. } => inputs + .iter() + .find(|i| i.row == attribute.row && i.fp16) + .map(|i| (i.pack2, (i.row2 != i.row).then_some(i.row2))), + _ => None, + }; + let f16 = inst.name().ends_with("_f16"); + let x = match packing { + None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"), + None => channel(self, attribute.row, attribute.channel)?, + Some((pack2, b)) => { + // 16-bit values: one in the low half of each dword, or two + // per dword (`packed_half`); the host's are 32-bit floats. + let half = |l: &mut Self, h: u8| -> Result<Option<V>, Why> { + let src = if pack2 { + packed_half(&l.s.inputs, attribute.row, b, h) + } else { + h.is_multiple_of(2).then_some((attribute.row, h / 2)) + }; + let Some((row, ch)) = src else { + return Ok(None); + }; + let x = channel(l, row, ch)?; + let f = l.as_float(x); + let i32t = l.s.t.i32; + Ok(Some(l.s.op( + l.cur, + "legacyF32ToF16", + Attr::ReadNone, + i32t, + 130, + &[f], + ))) + }; + let h = 2 * attribute.channel; + let c = self.cur; + if f16 { + let lo = half(self, h + u8::from(attribute.high))? + .ok_or("a packed input half no element holds")?; + self.low_half(inst, reg, lo) + } else if mode == 1 { + // The whole dword of a flat input: both halves. + let z = self.s.m.i32(0); + let lo = half(self, h)?.unwrap_or(z); + let hi = half(self, h + 1)?.unwrap_or(z); + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } else { + return Err("32-bit interpolation of a 16-bit input"); + } + } + }; + // A pixel interpolates in every lane; guards only hide inactive ones. + self.write(inst, Reg::V(reg), x, None); + Ok(()) + } + + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit + /// results keep the register's high half (GFX10). + fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { + let c = self.cur; + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; + let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); + let old = self.s.m.bin(c, Bin::And, old, high); + let x = self.s.m.bin(c, Bin::And, x, low); + self.s.m.bin(c, Bin::Or, old, x) + } + + fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + dmask, + dim, + unorm, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *tfe || *lwe { + return Err("an image access with tfe or lwe"); + } + let name = inst.name(); + if *a16 && name.starts_with("image_sample_b") { + return Err("a biased image sample with 16-bit coordinates"); + } + // A load or sample with no channel enabled returns the first. + let dmask = if *dmask == 0 { &1 } else { dmask }; + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let (kind, coords) = match dim { + 0 => (1, 1), + 1 => (2, 2), + 2 => (4, 3), + // Sampled (face coordinates and face, see `cube_direction`) or + // sized only. + 3 if name.starts_with("image_sample") + || name.starts_with("image_gather") + || name == "image_get_resinfo" => + { + (5, 3) + } + 4 => (6, 2), + 5 => (7, 3), + _ => return Err("an image dimension (cube loads or MSAA)"), + }; + // Address VGPRs in order. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + // With a16, two 16-bit components per VGPR, low half first. + let addr_val = |l: &mut Self, k: usize| -> Result<V, Why> { + let r = *regs + .get(if *a16 { k / 2 } else { k }) + .ok_or("an image address")?; + let v = inst.read(Reg::V(r)).ok_or("an image address")?; + let x = l.i32_of(v)?; + if !*a16 { + return Ok(x); + } + let c = l.cur; + let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF)); + let x = l.s.m.bin(c, Bin::LShr, x, sh); + Ok(l.s.m.bin(c, Bin::And, x, mask)) + }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked image")?; + let store = name.starts_with("image_store"); + let uav = store + || self + .used_kind(src) + .is_some_and(|u| u.kind == ResourceType::Uav); + let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + if let Some(op) = name.strip_prefix("image_atomic_") { + // DXIL's atomic operations on a 32-bit integer texture UAV; the + // old value returns with glc. Sub is the add of the negation. + let code = match op { + "add" | "sub" => 0, + "and" => 1, + "or" => 2, + "xor" => 3, + "smin" => 4, + "smax" => 5, + "umin" => 6, + "umax" => 7, + "swap" => 8, + "cmpswap" => u32::MAX, + _ => return Err(name), + }; + let Fields::Image { cache, .. } = &inst.fields else { + unreachable!() + }; + if *d16 || *a16 { + return Err("a 16-bit image atomic"); + } + // dmask: the data dwords (cmpswap: twice the value's). + // shortcut: 64-bit image atomics (two dwords, an R32G32 view) + // need the host's 64-bit typed atomics; they stop the program. + if *dmask != if code == u32::MAX { 3 } else { 1 } { + return Err("a 64-bit image atomic"); + } + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image atomic data"); + }; + let vals = self.vgprs(inst, data, if code == u32::MAX { 2 } else { 1 })?; + let mut value = vals[0]; + if op == "sub" { + let z = self.s.m.i32(0); + value = self.s.m.bin(c, Bin::Sub, z, value); + } + let old = match inst.read(Reg::V(reg)) { + Some(v) if cache.glc => self.i32_of(v)?, + _ => self.s.m.i32(0), + }; + let h = self.handle(site, src, false, (kind | 0x1000, 0x105))?; + let at = self.begin_guarded(guard); + let i32t = self.s.t.i32; + let mut args = vec![h]; + let r = if code == u32::MAX { + // cmpswap: data is (new, compare). + args.extend(cs); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } else { + args.push(self.s.m.i32(code)); + args.extend(cs); + args.push(value); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + }; + let r = self.end_guarded(at, &[(r, old)])[0]; + if cache.glc { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + if store { + if name != "image_store" { + return Err("an image store to a mip level"); + } + // shortcut: stores are taken to write all four channels of a + // float format (the console converts by the view's format). + if *dmask != 0xF { + return Err("an image store of some channels"); + } + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image store data"); + }; + let mut vals = Vec::new(); + for k in 0..4u8 { + // d16: two f16 channels per VGPR, low half first. + let r = if *d16 { k / 2 } else { k }; + let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?; + vals.push(if *d16 { + let mut x = self.i32_of(v)?; + if k % 2 == 1 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(self.cur, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + self.s + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.float_of(v)? + }); + } + let h = self.handle(site, src, false, props)?; + let at = self.begin_guarded(guard); + let mut args = vec![h]; + args.extend(cs); + args.extend(vals); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.f32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } + let (op, sample) = match name { + "image_sample" => (60, true), + "image_sample_lz" | "image_sample_l" => (62, true), + "image_sample_b" => (61, true), + "image_sample_c_lz" => (65, true), + "image_sample_d" => (63, true), + "image_get_lod" if self.s.pixel => (81, true), + // Implicit derivatives: pixel shaders only. + "image_sample_c" if self.s.pixel => (64, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" => (73, true), + "image_load" | "image_load_mip" => (66, false), + "image_get_resinfo" => (72, false), + _ => return Err(name), + }; + if op == 72 { + // Width, height, depth or layers, levels (per dmask) of the level + // in the first address: DXIL's dimensions; a channel DXIL leaves + // out reads 1 (UAVs: one level). + let h = self.handle(site, src, false, props)?; + let mip = if uav { + self.s.m.undef(self.s.t.i32) + } else { + addr_val(self, 0)? + }; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let one = self.s.m.i32(1); + let present = match kind { + 1 => [true, false, false, true], + 2 | 5 | 6 => [true, true, false, true], + _ => [true, true, true, true], + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let x = if ch == 3 && uav || !present[ch as usize] { + one + } else { + self.s.m.extract(c, d, ch) + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + if uav && op != 66 { + return Err("sampling a UAV"); + } + let h = self.handle(site, src, false, props)?; + let fu = self.s.m.undef(self.s.t.f32); + let iu = self.s.m.undef(self.s.t.i32); + let r = if sample { + let ss = self + .descriptors + .get(&(site, true)) + .copied() + .ok_or("an untracked sampler")?; + // Comparison: the reference value is the first address after + // the bias, and the sampler is a comparison sampler. + let cmp = matches!(op, 64 | 65); + if cmp && (*a16 || dmask.count_ones() != 1) { + return Err("a comparison sample of 16-bit coordinates or several channels"); + } + let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; + // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, + // signed (programmable offsets: gathers only). + let offset_word = name.ends_with("_o"); + let first = + usize::from(offset_word) + usize::from(name == "image_sample_b") + usize::from(cmp); + // Coordinates the size divides (not the array slice); explicit + // gradients (x then y) come before the coordinates. + let spatial = coords - usize::from(kind == 6 || kind == 7); + let grads = if op == 63 { 2 * spatial } else { 0 }; + let mut cs = vec![fu; 4]; + // With a16, sampling coordinates and LOD are f16. + let to_float = |l: &mut Self, x: V| { + if *a16 { + let f = l.s.t.f32; + l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x]) + } else { + l.as_float(x) + } + }; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + let x = addr_val(self, first + grads + k)?; + *slot = to_float(self, x); + } + if kind == 5 { + if *unorm || op == 63 || op == 81 { + return Err("a cube sample with texel coordinates, gradients or a level query"); + } + let dir = self.cube_direction(cs[0], cs[1], cs[2]); + cs[..3].copy_from_slice(&dir); + } + if *unorm { + // Texel coordinates: divided by the size of level 0. + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + for (k, slot) in cs.iter_mut().enumerate().take(spatial) { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32); + *slot = self.s.m.bin(c, Bin::SDiv, *slot, n); + } + } + if op == 81 { + // The clamped then the unclamped level of detail. + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let f32t = self.s.t.f32; + for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let clamped = self.s.m.bool(ch == 0); + let lod = self.s.op( + c, + "calculateLOD.f32", + Attr::ReadOnly, + f32t, + 81, + &[h, sh, cs[0], cs[1], cs[2], clamped], + ); + let x = self.as_int(lod); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let offsets = if kind == 5 { + 0 + } else { + (coords - usize::from(kind == 6 || kind == 7)).min(3) + }; + let zero = self.s.m.i32(0); + let mut os = vec![iu; 3]; + for o in os.iter_mut().take(offsets) { + *o = zero; + } + let mut args = vec![h, sh]; + args.extend(&cs); + match op { + 60 => { + args.extend(&os); + args.push(fu); + self.s + .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) + } + 61 => { + let bias = addr_val(self, 0)?; + let bias = self.as_float(bias); + args.extend(&os); + args.extend([bias, fu]); + self.s.op( + c, + "sampleBias.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 61, + &args, + ) + } + 63 => { + let mut g = vec![fu; 6]; + for k in 0..spatial { + let x = addr_val(self, first + k)?; + g[k] = to_float(self, x); + let y = addr_val(self, first + spatial + k)?; + g[3 + k] = to_float(self, y); + } + args.extend(&os); + args.extend(g); + args.push(fu); + self.s.op( + c, + "sampleGrad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 63, + &args, + ) + } + 64 | 65 => { + let reference = addr_val(self, first - 1)?; + let reference = self.as_float(reference); + args.extend(&os); + args.push(reference); + let name = if op == 64 { + args.push(fu); + "sampleCmp.f32" + } else { + "sampleCmpLevelZero.f32" + }; + self.s + .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) + } + 62 => { + let lod = if name == "image_sample_l" { + let x = addr_val(self, coords)?; + to_float(self, x) + } else { + self.s.m.f32(0) + }; + args.extend(&os); + args.push(lod); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + _ => { + if name == "image_gather4" { + return Err("a gather with implicit level"); + } + if dmask.count_ones() != 1 { + return Err("a gather of several channels"); + } + if offset_word { + let w = addr_val(self, 0)?; + for (k, at) in [(0, 26), (1, 18)] { + // Bits at..at+5 sign-extended: shift up, then down. + let left = self.s.m.i32(at); + let t = self.s.m.bin(c, Bin::Shl, w, left); + let k26 = self.s.m.i32(26); + os[k] = self.s.m.bin(c, Bin::AShr, t, k26); + } + } + args.extend(&os[..2]); + args.push(self.s.m.i32(dmask.trailing_zeros())); + self.s.op( + c, + "textureGather.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 73, + &args, + ) + } + } + } else { + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let mip = if name == "image_load_mip" { + addr_val(self, coords)? + } else if uav { + // Our declarations have four channels. + self.s.flags |= flags::TYPED_UAV_LOADS; + iu + } else { + self.s.m.i32(0) + }; + let mut args = vec![h, mip]; + args.extend(&cs); + args.extend([iu, iu, iu]); + self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &args, + ) + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let channels: Vec<u32> = if op == 73 { + vec![0, 1, 2, 3] + } else { + (0..4).filter(|ch| dmask >> ch & 1 != 0).collect() + }; + let mut xs = Vec::new(); + for ch in channels { + let x = self.s.m.extract(c, r, ch); + xs.push(if *d16 { + // shortcut: d16 results are taken as floats (rounded to + // nearest even); integer formats would keep 16 bits. + let i32t = self.s.t.i32; + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) + } else { + self.as_int(x) + }); + } + if *d16 { + // Two channels per VGPR, low half first (an odd last high half 0). + let k16 = self.s.m.i32(16); + xs = xs + .chunks(2) + .map(|p| match *p { + [lo, hi] => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + _ => p[0], + }) + .collect(); + } + for (k, x) in xs.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// The direction a cube sample's face coordinates stand for: the + /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over + /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the + /// host's cube sampling turns back into the same texel. + // shortcut: the view is taken as a cube, not a cube array (whose face + // operand adds 8 × the slice). + fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] { + let c = self.cur; + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (two, three) = (k(self, 2.0), k(self, 3.0)); + let u = self.s.m.bin(c, Bin::Mul, s, two); + let u = self.s.m.bin(c, Bin::Sub, u, three); + let v = self.s.m.bin(c, Bin::Mul, t, two); + let v = self.s.m.bin(c, Bin::Sub, v, three); + let z = self.s.m.f32(0x8000_0000); + let (nu, nv) = ( + self.s.m.bin(c, Bin::Sub, z, u), + self.s.m.bin(c, Bin::Sub, z, v), + ); + let (one, mone) = (k(self, 1.0), k(self, -1.0)); + let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32); + // Per face +x, -x, +y, -y, +z, -z. + let table = [ + [one, mone, u, u, u, nu], + [nv, nv, one, mone, nv, nv], + [nu, u, v, nv, one, mone], + ]; + table.map(|row| { + let mut r = row[0]; + for (n, &x) in row.iter().enumerate().skip(1) { + let kn = self.s.m.i32(n as u32); + let is = self.s.m.cmp(c, pred::EQ, f, kn); + r = self.s.m.select(c, is, x, r); + } + r + }) + } + + fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Buffer { + data, + addr, + soffset, + offset, + offen, + idxen, + format, + lds, + tfe, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if *lds || *tfe { + return Err("a buffer access to LDS or with tfe"); + } + if format.is_some() && !name.starts_with("tbuffer_load_format_") { + return Err(name); + } + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let store = name.starts_with("buffer_store_"); + // DXIL atomic operations: add, and, or, xor, signed and unsigned + // min and max, exchange; compare-exchange apart. + let atomic = match name.strip_prefix("buffer_atomic_") { + None => None, + Some("add") => Some(0), + Some("and") => Some(1), + Some("or") => Some(2), + Some("xor") => Some(3), + Some("smin") => Some(4), + Some("smax") => Some(5), + Some("umin") => Some(6), + Some("umax") => Some(7), + Some("swap") => Some(8), + Some("cmpswap") => Some(u32::MAX), + Some(_) => return Err(name), + }; + // d16: two 16-bit channels per VGPR, low half first. + let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + let plain = name.replace("_format_d16_", "_format_"); + let (typed, count) = match plain + .strip_prefix("buffer_load_") + .or(plain.strip_prefix("buffer_store_")) + .or(plain.strip_prefix("tbuffer_load_")) + { + _ if atomic.is_some() => (false, 1), + Some("dword") => (false, 1), + Some("dwordx2") => (false, 2), + Some("dwordx3") => (false, 3), + Some("dwordx4") => (false, 4), + Some("format_x") => (true, 1), + Some("format_xy") => (true, 2), + Some("format_xyz") => (true, 3), + Some("format_xyzw") => (true, 4), + _ => return Err(name), + }; + let Operand::Vector { reg: areg, .. } = *addr else { + return Err("a buffer address"); + }; + let vaddr = |l: &mut Self, k: u8| -> Result<V, Why> { + let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?; + l.i32_of(v) + }; + let index = if *idxen { Some(vaddr(self, 0)?) } else { None }; + let mut off = self.s.m.i32(u32::from(*offset)); + if *offen { + let o = vaddr(self, u8::from(*idxen))?; + off = self.s.m.bin(c, Bin::Add, off, o); + } + if !matches!( + soffset, + Operand::Scalar { code: NULL, .. } | Operand::Const(128) + ) { + let so = self.operand(inst, soffset)?; + off = self.s.m.bin(c, Bin::Add, off, so); + } + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked buffer")?; + let used = self.used_kind(src); + let (base, extra) = self.built_offset(src)?; + if base != 0 { + let b = self.s.m.i32(base); + off = self.s.m.bin(c, Bin::Add, off, b); + } + if let Some(x) = extra { + off = self.s.m.bin(c, Bin::Add, off, x); + } + if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { + // A constant buffer read per lane (a dynamically indexed array). + // shortcut: the console's CBV descriptor is taken to have a 16-byte + // stride, as the vector loads of whole rows suggest. + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let byte = match index { + Some(i) => { + let sixteen = self.s.m.i32(16); + let rows = self.s.m.bin(c, Bin::Mul, i, sixteen); + self.s.m.bin(c, Bin::Add, rows, off) + } + None => off, + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for k in 0..count { + let four = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, byte, four); + let x = self.cbuffer_dword(h, a); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let iu = self.s.m.undef(self.s.t.i32); + if let Some(op) = atomic { + let d = data.as_ref().ok_or("buffer atomic data")?; + let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; + let (h, coords) = match index { + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + (h, [index, off, iu]) + } + None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]), + }; + let Operand::Vector { reg, .. } = *d else { + return Err("buffer atomic data"); + }; + let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc); + let old = match inst.read(Reg::V(reg)) { + Some(v) if returns => self.i32_of(v)?, + _ => self.s.m.i32(0), + }; + let at = self.begin_guarded(guard); + let i32t = self.s.t.i32; + let r = if op == u32::MAX { + // cmpswap: data is (new, compare). + let mut args = vec![h]; + args.extend(coords); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } else { + let mut args = vec![h, self.s.m.i32(op)]; + args.extend(coords); + args.push(vals[0]); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + }; + let r = self.end_guarded(at, &[(r, old)])[0]; + if returns { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + if store { + let regs = if d16 { count.div_ceil(2) } else { count }; + let mut vals = + self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + if d16 { + // shortcut: d16 data is taken as f16 (integer formats would + // keep 16 bits), widened for the 32-bit float store. + let mut wide = Vec::new(); + for k in 0..count { + let mut x = vals[(k / 2) as usize]; + if k % 2 == 1 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + wide.push(self.as_int(f)); + } + vals = wide; + } + let mut args = Vec::new(); + let (op, name) = if typed { + // shortcut: typed stores are taken to write all four channels + // of a float format. + if count != 4 || *offen || *offset != 0 { + return Err("a typed buffer store of some channels or at an offset"); + } + args.push(self.handle(site, src, false, (10 | u, 0x409))?); + args.extend([index.unwrap_or(self.s.m.i32(0)), iu]); + for x in vals { + args.push(self.as_float(x)); + } + (69, "bufferStore.f32") + } else { + match index { + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + args.push(self.handle(site, src, false, (12 | u, stride))?); + args.extend([index, off]); + } + None => { + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([off, iu]); + } + } + args.extend(&vals); + args.resize(3 + 4, iu); + (140, "rawBufferStore.i32") + }; + args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 })); + if !typed { + args.push(self.s.m.i32(4)); + } + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + if let Some(f) = *format { + if index.is_some() { + return Err("a typed-format load by index"); + } + let h = self.handle(site, src, false, (11 | u, 0))?; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let r = if typed { + if *offen || matches!(off, V::Inst(_)) || *offset != 0 { + return Err("a typed buffer load at an offset"); + } + if uav { + self.s.flags |= flags::TYPED_UAV_LOADS; + } + let h = self.handle(site, src, false, (10 | u, 0x409))?; + let index = index.unwrap_or(self.s.m.i32(0)); + self.s.op( + c, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ) + } else { + let mask = self.s.m.i8((1u8 << count) - 1); + let align = self.s.m.i32(4); + match index { + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, index, off, mask, align], + ) + } + None => { + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, off, iu, mask, align], + ) + } + } + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + if d16 { + // Two f16 channels per VGPR (an odd last high half 0). + let k16 = self.s.m.i32(16); + let i32t = self.s.t.i32; + for k in 0..count.div_ceil(2) { + let mut x = None; + for ch in (2 * k..(2 * k + 2).min(count)).rev() { + let f = self.s.m.extract(c, r, ch); + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + x = Some(match x { + Some(hi) => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, h, hi) + } + None => h, + }); + } + self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard); + } + return Ok(()); + } + for k in 0..count { + let x = self.s.m.extract(c, r, k); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + fn export(&mut self, b: usize, i: usize) -> Result<(), Why> { + let e = *self + .exports + .get(&(b, i)) + .ok_or("an export I/O raising did not see")?; + if e.compressed { + return Err("a compressed export"); + } + let guard = self.guard(b, i)?; + let mesh = self.s.mesh.is_some(); + let c = self.cur; + if let Some(g) = guard + && !mesh + { + if !(e.done && self.s.pixel) { + return Err("a conditional export"); + } + let t = self.s.m.bool(true); + let kill = self.s.m.bin(c, Bin::Xor, g, t); + self.s + .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); + } + if mesh && e.target == Target::Primitive { + return self.emit_indices(e, guard); + } + let param_row = |usage: Usage, row: u8| match usage { + // The 2020 compiler leaves a mesh program's first entry zeroed + // (usage "position"): its row is the one no other entry names. + Usage::Other(0) if mesh => self.unnamed_row(), + _ => Some(row), + }; + // (output element, channel) per exported channel; per-primitive + // outputs are elements of `prims`. + let mut stores = Vec::new(); + let primitive = matches!(e.target, Target::PrimitiveParam { .. }); + let outputs = if primitive { + &self.s.prims + } else { + &self.s.outputs + }; + let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); + // 16-bit vertex outputs: the halves each dword carries, as (output + // element, channel, high half) per channel. + let halves = match e.target { + Target::Param { usage, row } => { + param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h))) + } + _ => None, + }; + if let Some((row, (pack2, b))) = halves { + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + for high in [false, true] { + let h = 2 * ch + u8::from(high); + let src = if pack2 { + packed_half(outputs, row, b, h) + } else { + (!high).then_some((row, ch)) + }; + let found = src.and_then(|(r, c)| { + outputs.iter().position(|o| { + o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols + }) + }); + if let Some(id) = found { + let col = src.expect("found").1 - outputs[id].col; + stores.push((id, col, value, Some(high))); + } + } + } + } + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + if halves.is_some() { + break; + } + let found = match e.target { + Target::Color(n) => outputs + .iter() + .position(|o| o.kind == 16 && o.row == Some(u32::from(n))) + .map(|id| (id, ch)), + Target::Position(0) => by_kind(3).map(|id| (id, ch)), + Target::Depth => match ch { + 0 => by_kind(17) + .or(by_kind(18)) + .or(by_kind(19)) + .map(|id| (id, 0)), + 1 => by_kind(20).map(|id| (id, 0)), + 2 => by_kind(14).map(|id| (id, 0)), + _ => None, + }, + Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => { + let row = param_row(usage, row); + outputs + .iter() + .position(|o| { + row.is_some_and(|r| o.row == Some(u32::from(r))) + && ch >= o.col + && ch < o.col + o.cols + }) + .map(|id| (id, ch - outputs[id].col)) + } + Target::Null | Target::Unread => None, + Target::Position(n @ 1..=2) => { + // shortcut: without the misc vector (point size, render + // target or viewport index) pos1 and pos2 carry the clip + // then cull distances, in semantic order. + if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) { + return Err("render-target or viewport index exports"); + } + let mut dists: Vec<usize> = (0..outputs.len()) + .filter(|&i| matches!(outputs[i].kind, 6 | 7)) + .collect(); + dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index)); + let flat: Vec<(usize, u8)> = dists + .iter() + .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c))) + .collect(); + // Channels past the distances the signature declares are + // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`). + let k = usize::from(n - 1) * 4 + usize::from(ch); + flat.get(k).copied() + } + Target::Position(_) => return Err("clip, cull or point-size exports"), + Target::Primitive => return Err("a primitive export"), + }; + if let Some((id, col)) = found { + stores.push((id, col, value, None)); + } + } + fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec<SigElement> { + if primitive { + &mut l.s.prims + } else { + &mut l.s.outputs + } + } + if stores + .iter() + .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half) + { + return Err("a 16-bit output the stage data does not mark"); + } + // A mesh lane writes its own vertex or primitive, where it exports. + let at = if mesh { + self.begin_guarded(guard) + } else { + None + }; + let (name, opcode) = match (mesh, primitive) { + (false, _) => ("storeOutput", 5), + (true, false) => ("storeVertexOutput", 171), + (true, true) => ("storePrimitiveOutput", 172), + }; + for (id, col, value, half) in stores { + let mut x = self.i32_of(value)?; + if let Some(high) = half { + // An f16 half, declared a 32-bit float on the host. + let c = self.cur; + if high { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + x = self.as_int(f); + } + let el = &mut elements(self, primitive)[id]; + el.usage |= 1 << col; + let (suffix, x) = match el.comp { + 9 if half.is_some() => (".f32", self.as_float(x)), + 9 => { + let f = match self.floats.get(&value) { + Some(&f) => f, + None => self.as_float(x), + }; + (".f32", f) + } + _ => (".i32", x), + }; + let mut args = vec![ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + x, + ]; + if mesh { + args.push(self.mesh_thread()); + } + let void = self.s.t.void; + self.s.op( + self.cur, + &format!("{name}{suffix}"), + Attr::NoUnwind, + void, + opcode, + &args, + ); + } + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all + /// indices 0: no area). + fn emit_indices(&mut self, e: &Export, guard: Option<V>) -> Result<(), Why> { + let v = e.values[0].ok_or("a primitive export without its indices")?; + let x = self.i32_of(v)?; + let at = self.begin_guarded(guard); + let c = self.cur; + let z = self.s.m.i32(0); + let culled = self.s.m.cmp(c, pred::SLT, x, z); + let mut args = vec![self.mesh_thread()]; + for k in 0..3 { + let (shift, mask) = (self.s.m.i32(10 * k), self.s.m.i32(0x3FF)); + let i = self.s.m.bin(c, Bin::LShr, x, shift); + let i = self.s.m.bin(c, Bin::And, i, mask); + args.push(self.s.m.select(c, culled, z, i)); + } + let void = self.s.t.void; + self.s + .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); + self.end_guarded(at, &[]); + Ok(()) + } + + /// The per-vertex arbitrary row no mesh output entry names but one + /// (the 2020 compiler's zeroed entry). + fn unnamed_row(&self) -> Option<u8> { + let StageIo::Ms(ms) = &self.x.native.io else { + return None; + }; + let named = |r: u32| { + ms.outputs + .iter() + .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) + }; + let free: std::collections::BTreeSet<u32> = self + .s + .outputs + .iter() + .filter(|o| o.kind == 0) + .filter_map(|o| o.row) + .filter(|&r| !named(r)) + .collect(); + match free.into_iter().collect::<Vec<_>>()[..] { + [r] => u8::try_from(r).ok(), + _ => None, + } + } + + fn exit(&mut self, b: usize) -> Result<(), Stop> { + let offset = self.x.p.blocks[b] + .insts + .last() + .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset); + let term = match self.x.st.exits[b] { + LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => { + let ok = self.count_iteration(t, pred::IULT); + let abort = self.abort_block(); + Term::CondBr(ok, self.block[t].expect("reachable"), abort) + } + LaneExit::Jump(t) => { + self.enter_loop(b, t, self.cur); + Term::Br(self.block[t].expect("reachable")) + } + LaneExit::Branch { + when, + taken, + not_taken, + } => { + // A negated condition branches the other way round. + let (cond, taken, not_taken) = match self.x.st.bools.node(when) { + Some((atom, Bool::TRUE, Bool::FALSE)) => { + let a = self + .atom(atom, self.cur) + .map_err(|w| unsupported(offset, w))?; + (a, not_taken, taken) + } + _ => { + let c = self + .boolean(when, self.cur) + .map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } + }; + // A back edge is taken only below the iteration limit. + let back = + |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; + // (No `xor` of a compare: a loop exit testing one hung the + // AMD driver.) + let cond = if back(self, taken) { + let ok = self.count_iteration(taken, pred::IULT); + self.s.m.bin(self.cur, Bin::And, cond, ok) + } else if back(self, not_taken) { + let stop = self.count_iteration(not_taken, pred::IUGE); + self.s.m.bin(self.cur, Bin::Or, cond, stop) + } else { + cond + }; + // Critical edges get a block of their own, so loops have + // dedicated exits and preheaders as DXC emits them. + let (t, f) = (self.edge(b, taken), self.edge(b, not_taken)); + for (to, via) in [(taken, t), (not_taken, f)] { + if !back(self, to) { + // From an edge block, or from here. + let from = if Some(via) == self.block[to] { + self.cur + } else { + via + }; + self.enter_loop(b, to, from); + } + } + Term::CondBr(cond, t, f) + } + LaneExit::End => { + if self.s.pixel && !self.exported[b] && !self.has_done_export(b) { + // A lane leaving without its final export was killed. + let t = self.s.m.bool(true); + self.s + .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + Term::Ret + } + LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), + }; + let _ = Exit::End; + self.s.m.terminate(self.cur, term); + Ok(()) + } + + /// A forward edge into loop header `to` (from DXIL block `via`) starts + /// its count at 0. + fn enter_loop(&mut self, _from: usize, to: usize, via: usize) { + if let Some((_, incoming)) = self.counters.get_mut(&to) { + let z = self.s.m.i32(0); + incoming.push((z, via)); + } + } + + /// A back edge to header `to` (a back edge keeps its block, no + /// critical-edge block): the count goes up; the result compares it with + /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop). + fn count_iteration(&mut self, to: usize, p: u8) -> V { + let c = self.cur; + let (phi, _) = self.counters[&to]; + let one = self.s.m.i32(1); + let next = self.s.m.bin(c, Bin::Add, phi, one); + let limit = self.s.m.i32(LOOP_LIMIT); + self.counters + .get_mut(&to) + .expect("header") + .1 + .push((next, c)); + self.s.m.cmp(c, p, next, limit) + } + + /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. + fn abort_block(&mut self) -> usize { + if let Some(a) = self.abort { + return a; + } + let a = self.s.m.new_block(); + if self.s.pixel { + let t = self.s.m.bool(true); + self.s + .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + self.s.m.terminate(a, Term::Ret); + self.abort = Some(a); + a + } + + /// The DXIL block a branch from IR block `from` to `to` goes to. + fn edge(&mut self, from: usize, to: usize) -> usize { + let target = self.block[to].expect("reachable"); + let preds = self.x.p.blocks[to] + .preds + .iter() + .filter(|&&q| self.block[q].is_some()) + .count(); + // Back edges stay as they are: the exiting block is the latch. + if preds < 2 || self.rpo[to] <= self.rpo[from] { + return target; + } + let e = self.s.m.new_block(); + self.s.m.terminate(e, Term::Br(target)); + self.edges.insert((from, to), e); + e + } + + fn fill_phis(&mut self) -> Result<(), Stop> { + let p = self.x.p; + for (v, b, i) in std::mem::take(&mut self.data_phis) { + let phi = &p.blocks[b].phis[i]; + let bit = phi.reg == Reg::Scc; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let arg = phi.args[n]; + let x = match (self.vals.get(&arg).copied(), bit) { + (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); + } + (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, why)); + } + _ if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "a join of mismatched values")); + } + _ if bit => self.s.m.bool(false), + _ => self.s.m.i32(0), + }; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { + self.s.m.set_phi(phi, incoming); + } + while let Some((v, b, i)) = self.pending_masks.pop() { + let phi = &p.blocks[b].phis[i]; + let offset = p.blocks[b].offset; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let m = + *self.x.st.masks.get(&phi.args[n]).ok_or_else(|| { + unsupported(offset, "a lane-mask join of an untracked mask") + })?; + let x = self.boolean(m, qb).map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::{Numeric, buffer_format}; + + #[test] + fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, a packed float, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(36), None); + assert_eq!(buffer_format(78), None); + } +} diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs new file mode 100644 index 0000000..a283545 --- /dev/null +++ b/crates/victory-shader/src/emit/mod.rs @@ -0,0 +1,452 @@ +//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute +//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts. +//! Compute shaders keep the console's thread-group size; one that depends +//! on the lane layout (cross-lane operations) declares the console's wave +//! size (`WaveSize`), so the host device must support it. +//! +//! What the host binds for a translated shader ([`HostShader`]): +//! +//! * **User data** at `b0, space 0` (32-bit root constants or a constant +//! buffer, per stage): dword `index` holds a root parameter's value, as +//! [`UserData`] lists. A root-constant dword is the constant. A +//! descriptor table is the byte offset of its first descriptor in its +//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16 +//! for sampler tables (the console's descriptor sizes; the code adds +//! offsets in those units). The heap bases of dynamic resources are 0 +//! and not listed. +//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and +//! `SamplerDescriptorHeap[]`, at the index the console address gives, so +//! the host heaps keep the title's descriptor order. The root signature +//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and +//! `SAMPLER_HEAP_DIRECTLY_INDEXED`. +//! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the +//! position in [`HostShader::samplers`] (the console sampler words) and +//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static +//! sampler description). Comparison sampling (added 2026-11-23): an +//! immediate sampler it uses has a comparison filter there (bit 0x80); +//! a heap sampler it uses must be a comparison sampler on the host. +//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors +//! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter +//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the +//! address the title sets is the buffer's. +//! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and +//! vertex programs fetch vertices themselves with typed-format loads +//! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, +//! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the +//! instruction, so the translation reads raw bytes and converts them +//! itself. Their descriptors are built around a root SRV (stride 1, no +//! record limit): the host binds the root SRV `t<slot>` above with the +//! address the title sets, nothing more. The vertex index, the stride +//! and the attribute offset are the shader's own arithmetic on data in +//! that buffer (per-stream headers), not descriptor fields. +//! * **Buffer views in the heap** are declared by how the shader reads +//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and +//! typed-format loads without an index; structured with the used-resource +//! entry's stride when indexed; typed with four 32-bit float channels for +//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at +//! that index must be of that kind and start at the console descriptor's +//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the +//! title's view description says. Typed-format loads from heap +//! descriptors (1,024 world compute programs, ray-tracing material +//! resolves) read raw views this way. +//! +//! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses +//! atomically is declared a 32-bit unsigned single-channel view; the +//! host's view at that index must be an R32 integer view (64-bit atomics +//! stop the translation). Global loads from a root SRV read it raw. +//! +//! Entry points: [`translate`] (container bytes as the title passes them +//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the +//! earlier stages already run). The root constants of each stage must +//! cover [`HostShader::user_data_dwords`]. Stability: these types and the +//! binding scheme are what pipeline creation builds on; changes are +//! announced. +//! * **Signatures** as the console container has them (same semantics, +//! registers and masks), so the input layout and stage linking are the +//! title's; pixel outputs are plain 32-bit values. +//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and +//! descriptors as above (the root constants visible to the mesh stage); +//! the pipeline is a mesh pipeline (pipeline-state stream, no input +//! layout) with the title's pixel shader. The thread group is the +//! console's in lanes (`[numthreads]` in the DXIL), the vertex and +//! primitive maxima its own, triangles only, no wave size required. The +//! console numbers groups in x only: the draw path passes the title's +//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are +//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the +//! console never exports them). + +mod bitcode; +mod container; +#[cfg(all(test, windows))] +mod diff_tests; +#[cfg(all(windows, any(test, feature = "host")))] +pub mod host; +mod lower; +mod sampler; +mod shader; +#[cfg(windows)] +pub mod validator; +mod wave; + +use crate::dxbc::{Container, FourCC}; +use crate::native::{HwStage, NativeProgram, RootType}; +use crate::{ShaderError, io, ir, resource, structure}; + +pub use sampler::StaticSampler; +pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; + +/// A translated shader and what the host binds for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostShader { + pub stage: HwStage, + /// The DXIL container, hashed as D3D12 expects. + pub dxil: Vec<u8>, + /// The user-data dwords the shader reads. + pub user_data: Vec<UserData>, + /// Immediate samplers: the four sampler words of `s<n>`. + pub samplers: Vec<[u32; 4]>, + /// The same samplers decoded, `s<n>` at position n: the static sampler + /// descriptions the host's root signature declares. + pub static_samplers: Vec<StaticSampler>, + /// Root CBVs the shader reads: root parameter indices, each bound as + /// `b<index>` in [`ROOT_CBV_SPACE`]. + pub root_cbvs: Vec<u8>, + /// Root SRVs (raw buffers) the shader reads: `t<index>` in + /// [`ROOT_CBV_SPACE`]. + pub root_srvs: Vec<u8>, +} + +impl HostShader { + /// Size of the user-data buffer the shader declares, in dwords (a + /// multiple of 4; 0 when it reads none). Root constants must cover it. + pub fn user_data_dwords(&self) -> u32 { + let n = self + .user_data + .iter() + .map(|u| u.index + 1) + .max() + .unwrap_or(0); + n.next_multiple_of(4) + } +} + +/// One dword of user data and the root parameter that fills it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UserData { + /// Dword in the user-data buffer (the console's user-data index). + pub index: u32, + /// Root parameter index in the title's root signature. + pub slot: u8, + /// `Constants` or `Table` (see the module notes for the value). + pub root: RootType, + /// Dword within the parameter. + pub dword: u32, +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container. +pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> { + let c = Container::parse(container)?; + let dxil = c + .part(FourCC::DXIL) + .ok_or(ShaderError::Malformed("no DXIL part"))?; + let native = crate::native_programs(dxil.data)? + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms + ) + }) + .ok_or(ShaderError::Unsupported { + offset: 0, + what: "a container without a vertex, pixel, compute or mesh program", + })?; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + emit(&c, &native, &p, &st, &io, &res) +} + +/// Emits a program whose earlier stages already ran. +pub fn emit( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<HostShader, ShaderError> { + let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> { + match c.part(fourcc) { + Some(part) => signature(part.data), + None => Ok(Vec::new()), + } + }; + let pixel = native.stage == HwStage::Ps; + let mut inputs = sig(FourCC::ISG1)?; + let mut outputs = sig(FourCC::OSG1)?; + // Interpolation as DXC declares it by default; pixel inputs that are + // read get the mode their barycentrics say. + let interpolated = if pixel { &mut inputs } else { &mut outputs }; + for e in interpolated { + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + // Constant, as DXC declares it (the AMD compiler crashed on a + // front face without a mode). + (13, _) => 1, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + } + // Per-primitive outputs are constant. The console never exports a + // primitive id or cull flag a mesh shader writes (it culls with the + // primitive export), so those rows are left out. + let mut prims = sig(FourCC::PSG1)?; + prims.retain(|e| !matches!(e.kind, 10 | 30)); + for e in &mut prims { + e.interp = 1; + } + // A mesh group's id arrives multiplied by max(threads, vertices, + // primitives) (the code divides by that); the thread count is in PSV0 + // from runtime info version 2 on. + // shortcut: older containers fall back to the group's lane count, right + // when the HLSL group fills its waves (Grand Theft Auto VI's do). + let mesh_stride = match &native.io { + crate::native::StageIo::Ms(ms) => { + let psv = c.part(FourCC::PSV0).map(|p| p.data); + let threads = psv + .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48)) + .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok()); + threads.map_or(ms.threads, |t| { + t.max(ms.max_vertices).max(ms.max_primitives) + }) + } + _ => 0, + }; + let l = lower::lower(&lower::Parts { + native, + p, + st, + io, + res, + inputs, + outputs, + prims, + mesh_stride, + })?; + Ok(HostShader { + stage: native.stage, + dxil: l.dxil, + user_data: l.user_data, + static_samplers: l + .samplers + .iter() + .enumerate() + .map(|(n, &w)| { + let mut s = StaticSampler::from_words(w); + if l.cmp_samplers >> n & 1 != 0 { + s.filter |= 0x80; + } + s + }) + .collect(), + samplers: l.samplers, + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + }) +} + +/// The rows of an `ISG1`/`OSG1` part. +fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> { + use crate::dxbc::u32_at; + let count = u32_at(part, 0)? as usize; + let base = u32_at(part, 4)? as usize; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let at = base + 32 * i; + let name_at = u32_at(part, at + 4)? as usize; + let name = part + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let mask = *part + .get(at + 24) + .ok_or(ShaderError::Malformed("truncated"))?; + if u32_at(part, at + 28)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a minimum-precision signature element", + }); + } + if u32_at(part, at)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a signature element of another stream", + }); + } + let kind = match u32_at(part, at + 12)? { + 0 => 0, + 1 => 3, + 2 => 6, + 3 => 7, + 4 => 4, + 5 => 5, + 6 => 1, + 7 => 10, + 8 => 2, + 9 => 13, + 10 => 12, + 64 => 16, + 65 => 17, + 66 => 14, + 67 => 19, + 68 => 18, + 69 => 20, + 70 => 15, + 25 => 30, // cull primitive + _ => { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a system value in the signature", + }); + } + }; + // 16-bit elements are declared 32-bit; reading or writing one + // converts (16-bit values travel packed on the console). + let raw = u32_at(part, at + 16)?; + let comp = match (kind, raw) { + // DXIL declares the front face a uint (the validator insists). + (13, _) => 5, + (_, 1 | 4) => 5, + (_, 2 | 5) => 4, + (_, 3 | 6) => 9, + (_, c) => { + return Err(ShaderError::Unsupported { + offset: 0, + what: match c { + 0 => "a signature element of unknown type", + _ => "a 64-bit signature element", + }, + }); + } + }; + let register = u32_at(part, at + 20)?; + out.push(container::SigElement { + name: String::from_utf8_lossy(name).into_owned(), + index: u32_at(part, at + 8)?, + kind, + comp, + interp: 0, + row: (register != u32::MAX).then_some(register), + col: mask.trailing_zeros().min(3) as u8, + cols: mask.count_ones().max(1) as u8, + usage: 0, + half: (4..=6).contains(&raw), + }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::bitcode::Attr; + use super::container::SigElement; + use super::shader::Shader; + + /// A pixel shader writing a constant colour. + fn constant_color() -> Vec<u8> { + let mut s = Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() { + let args = [ + s.m.i32(0), + s.m.i32(0), + s.m.i8(c as u8), + s.m.f32(v.to_bits()), + ]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, super::bitcode::Term::Ret); + s.finish() + } + + #[test] + #[cfg(windows)] + fn stub_pipeline_is_created() { + let Ok(host) = super::host::Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let ps = super::HostShader { + stage: crate::HwStage::Ps, + dxil: constant_color(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + }; + let file = |var: &str, stage| { + std::env::var(var).ok().map(|p| super::HostShader { + stage, + dxil: std::fs::read(p).unwrap(), + user_data: Vec::new(), + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + }) + }; + let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps); + let vs = file("VICTORY_REF_VS", crate::HwStage::Vs) + .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap()); + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + } + host.pipeline(&vs, &ps).unwrap(); + // The runtime checks the container hash: no hash or a wrong one is + // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass + // value; ours works with older ones too.) + let mut wrong = ps.dxil[4..20].to_vec(); + wrong[0] ^= 1; + for digest in [&[0u8; 16][..], &wrong] { + let mut other = ps.clone(); + other.dxil[4..20].copy_from_slice(digest); + assert!( + host.pipeline(&vs, &other).is_err(), + "digest {digest:02x?} accepted" + ); + } + } + + #[test] + #[cfg(windows)] + fn constant_color_validates() { + let mut c = constant_color(); + let path = super::validator::Validator::default_path(); + let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else { + eprintln!("no dxil.dll; skipped"); + return; + }; + let ours = c[4..20].to_vec(); + v.validate(&mut c).unwrap(); + assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); + } +} diff --git a/crates/victory-shader/src/emit/sampler.rs b/crates/victory-shader/src/emit/sampler.rs new file mode 100644 index 0000000..e10c0c1 --- /dev/null +++ b/crates/victory-shader/src/emit/sampler.rs @@ -0,0 +1,125 @@ +//! Immediate samplers: the console's four sampler words (the GPU's public +//! `SQ_IMG_SAMP_WORD0-3` layout) as a D3D12 static sampler. +//! +//! Word 0: address modes x, y, z (bits 0-8, 3 each), log2 of the maximum +//! anisotropy (9-11), comparison function (12-14), reduction (29-30: 0 +//! filtering, 1 minimum, 2 maximum). Word 1: minimum and maximum LOD +//! (0-11, 12-23, unsigned 4.8). Word 2: LOD bias (0-13, signed 5.8), +//! magnification and minification filters (20-21, 22-23: point, linear, +//! anisotropic point, anisotropic linear), mip filter (26-27: none, point, +//! linear). Word 3: border colour (30-31: transparent black, opaque black, +//! opaque white, custom). +//! +//! Comparison is the sampling instruction's, not the sampler's: the console +//! encodes a comparison function in every sampler (D3D's default, less or +//! equal, when unused). + +/// A static sampler in D3D12 terms; the integers are the `D3D12_FILTER`, +/// `D3D12_TEXTURE_ADDRESS_MODE`, `D3D12_COMPARISON_FUNC` and +/// `D3D12_STATIC_BORDER_COLOR` values. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct StaticSampler { + pub filter: u32, + /// U, V, W. + pub address: [u32; 3], + pub mip_lod_bias: f32, + pub max_anisotropy: u32, + pub comparison: u32, + pub border: u32, + pub min_lod: f32, + pub max_lod: f32, +} + +// The floats come from fixed-point fields: never NaN. +impl Eq for StaticSampler {} + +impl StaticSampler { + /// Decodes the four sampler words. + pub fn from_words(w: [u32; 4]) -> Self { + let bits = |word: u32, at: u32, n: u32| word >> at & ((1 << n) - 1); + // wrap, mirror, clamp, mirror once; the half-border modes have no + // D3D form and become their nearest. + let address = |m: u32| [1, 2, 3, 5, 3, 5, 4, 5][m as usize]; + let (mag, min, mip) = (bits(w[2], 20, 2), bits(w[2], 22, 2), bits(w[2], 26, 2)); + let reduction = match bits(w[0], 29, 2) { + 1 => 2, + 2 => 3, + _ => 0, + }; + let filter = if mag >= 2 || min >= 2 { + 0x55 | reduction << 7 + } else { + (min & 1) << 4 | (mag & 1) << 2 | u32::from(mip == 2) | reduction << 7 + }; + let lod = |v: u32| v as f32 / 256.0; + // Without a mip filter the base level is sampled. + let (min_lod, max_lod) = if mip == 0 { + (0.0, 0.0) + } else { + (lod(bits(w[1], 0, 12)), lod(bits(w[1], 12, 12))) + }; + StaticSampler { + filter, + address: [0, 3, 6].map(|at| address(bits(w[0], at, 3))), + mip_lod_bias: ((bits(w[2], 0, 14) << 18) as i32 >> 18) as f32 / 256.0, + max_anisotropy: 1 << bits(w[0], 9, 3).min(4), + comparison: bits(w[0], 12, 3) + 1, + // shortcut: a custom border colour (type 3, a table entry) becomes + // transparent black; upgrade when a title uses one. + border: bits(w[3], 30, 2) % 3, + min_lod, + max_lod, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_compiled_samplers_decode() { + // Words the console compiler wrote for static samplers of known + // descriptions. + let point = StaticSampler::from_words([0x3088, 0x0054_0100, 0x1400_0080, 0x8000_0000]); + assert_eq!( + point, + StaticSampler { + filter: 0, + address: [1, 2, 3], + mip_lod_bias: 0.5, + max_anisotropy: 1, + comparison: 4, + border: 2, + min_lod: 1.0, + max_lod: 5.25, + } + ); + let aniso = StaticSampler::from_words([0x369E, 0x00FF_F000, 0x18F0_3E00, 0x8000_0000]); + assert_eq!( + (aniso.filter, aniso.address, aniso.max_anisotropy), + (0x55, [4, 5, 3], 8) + ); + assert_eq!((aniso.mip_lod_bias, aniso.max_lod), (-2.0, 4095.0 / 256.0)); + let compare = StaticSampler::from_words([0x3006, 0x00FF_F000, 0x1450_0000, 0x4000_0000]); + assert_eq!( + (compare.filter, compare.address, compare.border), + (0x14, [4, 1, 1], 1) + ); + let minimum = + StaticSampler::from_words([0x2000_3003, 0x00FF_F000, 0x1850_0000, 0x8000_0000]); + assert_eq!((minimum.filter, minimum.address[0]), (0x115, 5)); + let mag_mip = StaticSampler::from_words([0x3002, 0, 0x1810_0000, 0x8000_0000]); + assert_eq!((mag_mip.filter, mag_mip.max_lod), (0x05, 0.0)); + let max_aniso = + StaticSampler::from_words([0x4000_3800, 0x00FF_F000, 0x18F0_0F00, 0x8000_0000]); + assert_eq!( + ( + max_aniso.filter, + max_aniso.max_anisotropy, + max_aniso.mip_lod_bias + ), + (0x1D5, 16, 15.0) + ); + } +} diff --git a/crates/victory-shader/src/emit/shader.rs b/crates/victory-shader/src/emit/shader.rs new file mode 100644 index 0000000..8389c17 --- /dev/null +++ b/crates/victory-shader/src/emit/shader.rs @@ -0,0 +1,645 @@ +//! A DXIL vertex, pixel, compute or mesh shader under construction: the module, +//! the `dx.op` declarations it calls, its signatures and bound resources, +//! and the metadata and container that wrap it up (SM 6.6, validator 1.6). + +use super::bitcode::{Attr, Md, Module, Ty, V}; +use super::container::{self, Binding, Psv, SigElement}; + +/// Where the shader reads its user data: `b0` in this space. +pub const USER_DATA_SPACE: u32 = 0; +/// Where immediate samplers are bound: `s<n>` in this space. +pub const SAMPLER_SPACE: u32 = 0; +/// Where root CBVs and SRVs are bound: `b<root parameter index>` and +/// `t<root parameter index>` in this space. +pub const ROOT_CBV_SPACE: u32 = 1; + +/// `ShaderFlags` bits (metadata) and their `SFI0` feature bits. +pub(crate) mod flags { + pub const RAW_BUFFERS: u64 = 1 << 4; + pub const TYPED_UAV_LOADS: u64 = 1 << 13; + pub const WAVE_OPS: u64 = 1 << 19; + pub const INT64: u64 = 1 << 20; + pub const RESOURCE_HEAP: u64 = 1 << 30; + pub const SAMPLER_HEAP: u64 = 1 << 31; +} + +pub(crate) struct Types { + pub void: Ty, + pub i1: Ty, + pub i32: Ty, + pub f32: Ty, + pub handle: Ty, + pub props: Ty, + pub bind: Ty, + pub cbuf_ret: Ty, + pub res_ret: Ty, +} + +/// What a mesh shader declares beyond its thread-group size. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Mesh { + pub max_vertices: u32, + pub max_primitives: u32, + /// 1 lines, 2 triangles. + pub topology: u8, +} + +pub(crate) struct Shader { + pub m: Module, + pub t: Types, + pub pixel: bool, + pub inputs: Vec<SigElement>, + pub outputs: Vec<SigElement>, + /// A mesh shader's per-primitive outputs. + pub prims: Vec<SigElement>, + /// A mesh shader (`threads` is its thread-group size). + pub mesh: Option<Mesh>, + /// Dwords of user data the shader reads (0: no user-data buffer). + pub user_data: u32, + /// Immediate samplers, bound as `s0..` in [`SAMPLER_SPACE`]. + pub samplers: u32, + /// Bit n: immediate sampler n is a comparison sampler. + pub cmp_samplers: u64, + /// Root CBVs read, by root parameter index, with their handles. + pub root_cbvs: Vec<(u8, V)>, + /// Root SRVs (raw buffers) read, likewise. + pub root_srvs: Vec<(u8, V)>, + pub flags: u64, + /// A compute shader with this thread-group size. + pub threads: Option<[u32; 3]>, + /// The wave size a compute shader requires (`WaveSize`). + pub wave_size: Option<u32>, + /// Thread-group shared memory, in dwords. + pub lds_dwords: u32, + lds: Option<V>, + main: V, + pub entry: usize, +} + +impl Shader { + pub fn new(pixel: bool) -> Self { + let mut m = Module::default(); + let void = m.void(); + let i1 = m.int(1); + let i8 = m.int(8); + let i32 = m.int(32); + let f32 = m.float(); + let i8p = m.ptr(i8); + let handle = m.named_struct("dx.types.Handle", vec![i8p]); + let props = m.named_struct("dx.types.ResourceProperties", vec![i32, i32]); + let bind = m.named_struct("dx.types.ResBind", vec![i32, i32, i32, i8]); + let cbuf_ret = m.named_struct("dx.types.CBufRet.i32", vec![i32, i32, i32, i32]); + let res_ret = m.named_struct("dx.types.ResRet.f32", vec![f32, f32, f32, f32, i32]); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + let main = m.function("main", main_ty, None, true); + let entry = m.new_block(); + Shader { + m, + t: Types { + void, + i1, + i32, + f32, + handle, + props, + bind, + cbuf_ret, + res_ret, + }, + pixel, + inputs: Vec::new(), + outputs: Vec::new(), + prims: Vec::new(), + mesh: None, + user_data: 0, + samplers: 0, + cmp_samplers: 0, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + flags: 0, + threads: None, + wave_size: None, + lds_dwords: 0, + lds: None, + main, + entry, + } + } + + /// The thread-group shared memory: `[lds_dwords x i32]` in address + /// space 3. + pub fn lds(&mut self) -> V { + if let Some(g) = self.lds { + return g; + } + let arr = self.m.array(self.lds_dwords, self.t.i32); + let g = self.m.global("lds", arr, 3); + self.lds = Some(g); + g + } + + /// Calls `dx.op.<name>` (class and overload) with `opcode` and `args`. + pub fn op( + &mut self, + block: usize, + name: &str, + attr: Attr, + ret: Ty, + opcode: u32, + args: &[V], + ) -> V { + let mut params = vec![self.t.i32]; + params.extend(args.iter().map(|&a| self.m.type_of(a))); + let fty = self.m.func_ty(ret, params); + self.m.ptr(fty); + let f = self + .m + .function(&format!("dx.op.{name}"), fty, Some(attr), false); + let mut all = vec![self.m.i32(opcode)]; + all.extend(args); + self.m.call(block, f, all) + } + + /// The handle of the user-data constant buffer, made in the entry block. + pub fn user_data_handle(&mut self) -> V { + let bind = [ + self.m.i32(0), + self.m.i32(0), + self.m.i32(USER_DATA_SPACE), + self.m.i8(2), // CBV + ]; + let bind = self.m.aggregate(self.t.bind, &bind); + let block = self.entry; + let (i, f) = (self.m.i32(0), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, i, f], + ); + // The size is known in `finish`, which fixes this placeholder. + self.annotate(block, h, 13, u32::MAX) + } + + /// The handle of the root CBV of root parameter `slot`, made in the + /// entry block. + pub fn root_cbv_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_cbvs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(2)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 13, 65536); + self.root_cbvs.push((slot, h)); + h + } + + /// The handle of the root SRV (a raw buffer) of root parameter `slot`. + pub fn root_srv_handle(&mut self, slot: u8) -> V { + if let Some(&(_, h)) = self.root_srvs.iter().find(|r| r.0 == slot) { + return h; + } + let r = self.m.i32(u32::from(slot)); + let bind = [r, r, self.m.i32(ROOT_CBV_SPACE), self.m.i8(0)]; + let bind = self.m.aggregate(self.t.bind, &bind); + let f = self.m.bool(false); + let block = self.entry; + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, r, f], + ); + let h = self.annotate(block, h, 11, 0); + self.flags |= flags::RAW_BUFFERS; + self.root_srvs.push((slot, h)); + h + } + + /// The handle of immediate sampler `n` (a comparison sampler when its + /// bit in `cmp_samplers` is set). + pub fn sampler_handle(&mut self, block: usize, n: u32) -> V { + let bind = [ + self.m.i32(n), + self.m.i32(n), + self.m.i32(SAMPLER_SPACE), + self.m.i8(3), // sampler + ]; + let bind = self.m.aggregate(self.t.bind, &bind); + let (i, f) = (self.m.i32(n), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromBinding", + Attr::ReadNone, + self.t.handle, + 217, + &[bind, i, f], + ); + let cmp = if self.cmp_samplers >> n & 1 != 0 { + 0x8000 + } else { + 0 + }; + self.annotate(block, h, 14 | cmp, 0) + } + + pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V { + let p = [self.m.i32(props0), self.m.i32(props1)]; + let p = self.m.aggregate(self.t.props, &p); + self.op( + block, + "annotateHandle", + Attr::ReadNone, + self.t.handle, + 216, + &[h, p], + ) + } + + /// A descriptor heap handle, annotated with `props`. + pub fn heap_handle(&mut self, block: usize, index: V, sampler: bool, props: (u32, u32)) -> V { + self.flags |= if sampler { + flags::SAMPLER_HEAP + } else { + flags::RESOURCE_HEAP + }; + let (s, n) = (self.m.bool(sampler), self.m.bool(false)); + let h = self.op( + block, + "createHandleFromHeap", + Attr::ReadNone, + self.t.handle, + 218, + &[index, s, n], + ); + self.annotate(block, h, props.0, props.1) + } + + /// The finished container. + pub fn finish(mut self) -> Vec<u8> { + let ud_size = (self.user_data * 4).next_multiple_of(16); + self.fix_user_data_size(ud_size); + let mut resources = None; + let mut bindings = Vec::new(); + let i32c = |s: &mut Self, v: u32| { + let c = s.m.i32(v); + s.m.md_value(c) + }; + if self.user_data > 0 + || self.samplers > 0 + || !self.root_cbvs.is_empty() + || !self.root_srvs.is_empty() + { + let empty = self.m.md_str(""); + let mut cbvs = None; + let mut cbv_list = Vec::new(); + if self.user_data > 0 { + let arr = self.m.array(self.user_data.next_multiple_of(4), self.t.i32); + let ty = self.m.named_struct("UserData", vec![arr]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let ops = vec![ + Some(i32c(&mut self, 0)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, USER_DATA_SPACE)), + Some(i32c(&mut self, 0)), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, ud_size)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: USER_DATA_SPACE, + register: 0, + dxil_kind: 13, + }); + } + let blob = self.m.array(16384, self.t.i32); + let ty = self.m.named_struct("RootCbv", vec![blob]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + for (slot, _) in self.root_cbvs.clone() { + let ops = vec![ + Some(i32c(&mut self, cbv_list.len() as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 65536)), + None, + ]; + cbv_list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 2, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 13, + }); + } + if !cbv_list.is_empty() { + cbvs = Some(self.m.md_node(cbv_list)); + } + let mut srvs = None; + if !self.root_srvs.is_empty() { + let ty = self + .m + .named_struct("struct.ByteAddressBuffer", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let mut list = Vec::new(); + for (n, (slot, _)) in self.root_srvs.clone().into_iter().enumerate() { + let ops = vec![ + Some(i32c(&mut self, n as u32)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, ROOT_CBV_SPACE)), + Some(i32c(&mut self, u32::from(slot))), + Some(i32c(&mut self, 1)), + Some(i32c(&mut self, 11)), + Some(i32c(&mut self, 0)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 4, + space: ROOT_CBV_SPACE, + register: u32::from(slot), + dxil_kind: 11, + }); + } + srvs = Some(self.m.md_node(list)); + } + let mut samplers = None; + if self.samplers > 0 { + let ty = self.m.named_struct("struct.SamplerState", vec![self.t.i32]); + let p = self.m.ptr(ty); + let u = self.m.undef(p); + let mut list = Vec::new(); + for n in 0..self.samplers { + let kind = (self.cmp_samplers >> n & 1) as u32; + let ops = vec![ + Some(i32c(&mut self, n)), + Some(self.m.md_value(u)), + Some(empty), + Some(i32c(&mut self, SAMPLER_SPACE)), + Some(i32c(&mut self, n)), + Some(i32c(&mut self, 1)), + // Sampler kind: 1 comparison. + Some(i32c(&mut self, kind)), + None, + ]; + list.push(Some(self.m.md_node(ops))); + bindings.push(Binding { + kind: 1, + space: SAMPLER_SPACE, + register: n, + dxil_kind: 14, + }); + } + samplers = Some(self.m.md_node(list)); + } + resources = Some(self.m.md_node(vec![srvs, None, cbvs, samplers])); + // PSV0 lists them as the module does: CBVs, samplers, SRVs. + bindings.sort_by_key(|b| match b.kind { + 2 => 0, + 1 => 1, + _ => 2, + }); + } + if let Some(r) = resources { + self.m.named_md("dx.resources", vec![r]); + } + + let graphics = self.threads.is_none() || self.mesh.is_some(); + if graphics { + // shortcut: every output is declared to depend on every input; the + // exact sets need a dependence pass. Drivers read this state. + let scalars = |els: &[SigElement]| { + els.iter() + .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols))) + .max() + .unwrap_or(0) + }; + let (ni, no) = (scalars(&self.inputs), scalars(&self.outputs)); + let mut view = vec![ni, no]; + // Mesh shaders have no inputs: then the primitive outputs' count. + if self.mesh.is_some() { + view.push(scalars(&self.prims)); + } + for _ in 0..ni { + for k in 0..no.div_ceil(32) { + let bits = (no - 32 * k).min(32); + view.push(if bits == 32 { + u32::MAX + } else { + (1 << bits) - 1 + }); + } + } + let arr = self.m.array(view.len() as u32, self.t.i32); + let elems: Vec<V> = view.iter().map(|&v| self.m.i32(v)).collect(); + let arr = self.m.aggregate(arr, &elems); + let arr = self.m.md_value(arr); + let view_node = self.m.md_node(vec![Some(arr)]); + self.m.named_md("dx.viewIdState", vec![view_node]); + } + + let sigs = if graphics { + let ins = self.signature_md(self.inputs.clone()); + let outs = self.signature_md(self.outputs.clone()); + let prims = self.signature_md(self.prims.clone()); + Some(self.m.md_node(vec![ins, outs, prims])) + } else { + None + }; + // Entry properties: shader flags (tag 0), thread-group size (4), + // wave size (11). + let mut props = Vec::new(); + if self.flags != 0 { + props.push(i32c(&mut self, 0)); + let i64t = self.m.int(64); + let f = self.m.int_const(i64t, self.flags as i64); + props.push(self.m.md_value(f)); + } + if let Some(threads) = self.threads { + let t = threads.map(|n| Some(i32c(&mut self, n))); + let t = self.m.md_node(t.to_vec()); + match self.mesh { + // Mesh state (tag 9): threads, maximum vertices and + // primitives, topology, payload bytes. + Some(mesh) => { + props.push(i32c(&mut self, 9)); + let state = [ + mesh.max_vertices, + mesh.max_primitives, + mesh.topology.into(), + 0, + ] + .map(|n| Some(i32c(&mut self, n))); + let mut node = vec![Some(t)]; + node.extend(state); + props.push(self.m.md_node(node)); + } + None => { + props.push(i32c(&mut self, 4)); + props.push(t); + } + } + } + if let Some(n) = self.wave_size { + props.push(i32c(&mut self, 11)); + let n = Some(i32c(&mut self, n)); + props.push(self.m.md_node(vec![n])); + } + let props = + (!props.is_empty()).then(|| self.m.md_node(props.into_iter().map(Some).collect())); + let main = self.m.md_value(self.main); + let name = self.m.md_str("main"); + let entry = self + .m + .md_node(vec![Some(main), Some(name), sigs, resources, props]); + + let ident = self.m.md_str("victory"); + let ident = self.m.md_node(vec![Some(ident)]); + self.m.named_md("llvm.ident", vec![ident]); + let one = i32c(&mut self, 1); + let six = i32c(&mut self, 6); + let version = self.m.md_node(vec![Some(one), Some(six)]); + self.m.named_md("dx.version", vec![version]); + self.m.named_md("dx.valver", vec![version]); + // Program kinds: 0 pixel, 1 vertex, 5 compute, 13 mesh. + let (name, kind) = match (self.threads, self.pixel) { + _ if self.mesh.is_some() => ("ms", 13u32), + (Some(_), _) => ("cs", 5u32), + (None, true) => ("ps", 0), + (None, false) => ("vs", 1), + }; + let name = self.m.md_str(name); + let sm = self.m.md_node(vec![Some(name), Some(six), Some(six)]); + self.m.named_md("dx.shaderModel", vec![sm]); + self.m.named_md("dx.entryPoints", vec![entry]); + + let bitcode = self.m.write(); + let mut dxil = Vec::with_capacity(24 + bitcode.len()); + dxil.extend((kind << 16 | 0x66).to_le_bytes()); + dxil.extend((((24 + bitcode.len()) / 4) as u32).to_le_bytes()); + dxil.extend(b"DXIL"); + dxil.extend(0x106u32.to_le_bytes()); + dxil.extend(16u32.to_le_bytes()); + dxil.extend((bitcode.len() as u32).to_le_bytes()); + dxil.extend(&bitcode); + + let mut features = 0u64; + if self.flags & flags::TYPED_UAV_LOADS != 0 { + features |= 0x800; + } + if self.flags & flags::WAVE_OPS != 0 { + features |= 0x4000; + } + if self.flags & flags::INT64 != 0 { + features |= 0x8000; + } + if self.flags & flags::RESOURCE_HEAP != 0 { + features |= 0x200_0000; + } + if self.flags & flags::SAMPLER_HEAP != 0 { + features |= 0x400_0000; + } + let sfi0 = features.to_le_bytes(); + let isg1 = container::signature(&self.inputs, true); + let osg1 = container::signature(&self.outputs, false); + let flag = if self.pixel { + self.outputs.iter().any(|o| (17..=19).contains(&o.kind)) + } else { + self.outputs.iter().any(|o| o.kind == 3) + }; + let psv0 = container::psv(&Psv { + stage: kind as u8, + flag: flag && self.threads.is_none(), + inputs: &self.inputs, + outputs: &self.outputs, + prims: &self.prims, + mesh: self.mesh.map(|m| (m, self.lds_dwords * 4)), + bindings: &bindings, + threads: self.threads.unwrap_or_default(), + wave_size: self.wave_size, + }); + let hash = [0u8; 20]; + let psg1 = container::signature(&self.prims, false); + let mut parts: Vec<(&[u8; 4], &[u8])> = + vec![(b"SFI0", &sfi0), (b"ISG1", &isg1), (b"OSG1", &osg1)]; + if self.mesh.is_some() { + parts.push((b"PSG1", &psg1)); + } + parts.extend([(b"PSV0", &psv0[..]), (b"HASH", &hash), (b"DXIL", &dxil)]); + container::build(&parts) + } + + /// The user-data buffer's annotation carries its size, known only now. + fn fix_user_data_size(&mut self, size: u32) { + let old = [self.m.i32(13), self.m.i32(u32::MAX)]; + let old = self.m.aggregate(self.t.props, &old); + let new = [self.m.i32(13), self.m.i32(size)]; + let new = self.m.aggregate(self.t.props, &new); + self.m.replace_const(old, new); + } + + fn signature_md(&mut self, elements: Vec<SigElement>) -> Option<Md> { + if elements.is_empty() { + return None; + } + let mut list = Vec::new(); + for (id, e) in elements.iter().enumerate() { + let c32 = |s: &mut Self, v: u32| { + let c = s.m.i32(v); + Some(s.m.md_value(c)) + }; + let c8 = |s: &mut Self, v: u8| { + let c = s.m.i8(v); + Some(s.m.md_value(c)) + }; + let idx = c32(self, e.index); + let indices = Some(self.m.md_node(vec![idx])); + let usage = if e.usage != 0 { + let (tag, mask) = (c32(self, 3), c32(self, u32::from(e.usage))); + Some(self.m.md_node(vec![tag, mask])) + } else { + None + }; + let ops = vec![ + c32(self, id as u32), + Some(self.m.md_str(&e.name)), + c8(self, e.comp), + c8(self, e.kind), + indices, + c8(self, e.interp), + c32(self, 1), + c8(self, e.cols), + c32(self, e.row.unwrap_or(u32::MAX)), + c8(self, if e.row.is_some() { e.col } else { u8::MAX }), + usage, + ]; + list.push(Some(self.m.md_node(ops))); + } + Some(self.m.md_node(list)) + } +} diff --git a/crates/victory-shader/src/emit/validator.rs b/crates/victory-shader/src/emit/validator.rs new file mode 100644 index 0000000..2f4108a --- /dev/null +++ b/crates/victory-shader/src/emit/validator.rs @@ -0,0 +1,221 @@ +//! The DXIL validator in `dxil.dll` (`IDxcValidator`), for tests and the +//! offline batch. Translated shaders do not need it: they carry the +//! container hash we compute ([`super::container::hash`]). +//! +//! The DLL is found at `VICTORY_DXIL` if set, else the newest Windows SDK's +//! `bin\<version>\x64\dxil.dll`, else wherever `LoadLibrary` finds it. + +use std::ffi::c_void; +use std::path::PathBuf; + +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; + +type Hresult = i32; + +#[repr(C)] +struct Guid(u32, u16, u16, [u8; 8]); + +const CLSID_DXC_VALIDATOR: Guid = Guid( + 0x8ca3_e215, + 0xf728, + 0x4cf3, + [0x8c, 0xdd, 0x88, 0xaf, 0x91, 0x75, 0x87, 0xa1], +); +const IID_IDXC_VALIDATOR: Guid = Guid( + 0xa6e8_2bd2, + 0x1fd7, + 0x4826, + [0x98, 0x11, 0x28, 0x57, 0xe7, 0x97, 0xf4, 0x9a], +); +/// `DxcValidatorFlags_InPlaceEdit`: sign the container we pass. +const IN_PLACE_EDIT: u32 = 1; + +type CreateInstance = + unsafe extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult; + +/// COM object: a pointer to a table of method pointers. +type Object = *mut *const usize; + +unsafe fn method<F: Copy>(obj: Object, slot: usize) -> F { + // SAFETY: the caller names a slot of the object's interface. + unsafe { std::mem::transmute_copy(&*(*obj).add(slot)) } +} + +unsafe fn release(obj: Object) { + if !obj.is_null() { + // SAFETY: slot 2 of every COM interface is Release. + unsafe { method::<unsafe extern "system" fn(Object) -> u32>(obj, 2)(obj) }; + } +} + +/// An `IDxcBlob` over our bytes: QueryInterface, AddRef, Release, +/// GetBufferPointer, GetBufferSize. Lives on the caller's stack. +#[repr(C)] +struct Blob { + vtable: *const BlobVtable, + data: *mut u8, + len: usize, +} + +/// IUnknown and IDxcBlob, as raw GUID bytes. +const IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46]; +const IDXC_BLOB: [u8; 16] = [ + 0x08, 0xfb, 0xa5, 0x8b, 0x95, 0x51, 0xe2, 0x40, 0xac, 0x58, 0x0d, 0x98, 0x9c, 0x3a, 0x01, 0x02, +]; + +unsafe extern "system" fn blob_qi( + this: *mut Blob, + iid: *const [u8; 16], + out: *mut *mut c_void, +) -> Hresult { + // SAFETY: the validator passes valid pointers. + unsafe { + if *iid == IUNKNOWN || *iid == IDXC_BLOB { + *out = this.cast(); + 0 + } else { + *out = std::ptr::null_mut(); + 0x8000_4002_u32 as i32 // E_NOINTERFACE + } + } +} +unsafe extern "system" fn blob_ref(_: *mut Blob) -> u32 { + 1 +} +unsafe extern "system" fn blob_ptr(this: *mut Blob) -> *mut u8 { + // SAFETY: `this` is our blob. + unsafe { (*this).data } +} +unsafe extern "system" fn blob_len(this: *mut Blob) -> usize { + // SAFETY: `this` is our blob. + unsafe { (*this).len } +} + +#[repr(C)] +struct BlobVtable { + qi: unsafe extern "system" fn(*mut Blob, *const [u8; 16], *mut *mut c_void) -> Hresult, + add_ref: unsafe extern "system" fn(*mut Blob) -> u32, + release: unsafe extern "system" fn(*mut Blob) -> u32, + ptr: unsafe extern "system" fn(*mut Blob) -> *mut u8, + len: unsafe extern "system" fn(*mut Blob) -> usize, +} + +static BLOB_VTABLE: BlobVtable = BlobVtable { + qi: blob_qi, + add_ref: blob_ref, + release: blob_ref, + ptr: blob_ptr, + len: blob_len, +}; + +pub struct Validator { + object: Object, +} + +// SAFETY: the validator object is free-threaded (DXC's validator has no +// thread affinity); calls are serialised by `&mut self`. +unsafe impl Send for Validator {} + +impl Validator { + /// Where `dxil.dll` is looked for. + pub fn default_path() -> Option<PathBuf> { + if let Some(p) = std::env::var_os("VICTORY_DXIL") { + return Some(p.into()); + } + let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin"); + let mut versions: Vec<PathBuf> = std::fs::read_dir(&kits) + .ok()? + .filter_map(Result::ok) + .map(|e| e.path().join(r"x64\dxil.dll")) + .filter(|p| p.exists()) + .collect(); + versions.sort(); + versions.pop() + } + + /// Loads `path`'s validator (or `dxil.dll` from the DLL search path). + pub fn load(path: Option<&std::path::Path>) -> Result<Self, String> { + let name: Vec<u16> = path + .map_or_else(|| "dxil.dll".into(), |p| p.as_os_str().to_owned()) + .to_string_lossy() + .encode_utf16() + .chain([0]) + .collect(); + // SAFETY: plain Win32 calls with a NUL-terminated name. + unsafe { + let module = LoadLibraryW(name.as_ptr()); + if module.is_null() { + return Err(format!("cannot load {}", String::from_utf16_lossy(&name))); + } + let create = GetProcAddress(module, c"DxcCreateInstance".as_ptr().cast()) + .ok_or("dxil.dll lacks DxcCreateInstance")?; + let create: CreateInstance = std::mem::transmute(create); + let mut object = std::ptr::null_mut(); + let hr = create(&CLSID_DXC_VALIDATOR, &IID_IDXC_VALIDATOR, &mut object); + if hr < 0 || object.is_null() { + return Err(format!("DxcCreateInstance(validator) failed: {hr:#x}")); + } + Ok(Validator { + object: object.cast(), + }) + } + } + + /// Validates `container` and signs it in place; the error text if it + /// is rejected. + pub fn validate(&mut self, container: &mut [u8]) -> Result<(), String> { + let mut blob = Blob { + vtable: &BLOB_VTABLE, + data: container.as_mut_ptr(), + len: container.len(), + }; + // SAFETY: IDxcValidator::Validate (slot 3) with our blob; then + // IDxcOperationResult GetStatus (3) and GetErrorBuffer (5), and + // IDxcBlob GetBufferPointer (3) / GetBufferSize (4). + unsafe { + let mut result: Object = std::ptr::null_mut(); + let validate: unsafe extern "system" fn( + Object, + *mut Blob, + u32, + *mut Object, + ) -> Hresult = method(self.object, 3); + let hr = validate(self.object, &mut blob, IN_PLACE_EDIT, &mut result); + if hr < 0 || result.is_null() { + return Err(format!("Validate failed: {hr:#x}")); + } + let mut status = 0; + let get_status: unsafe extern "system" fn(Object, *mut Hresult) -> Hresult = + method(result, 3); + get_status(result, &mut status); + let mut text = String::new(); + if status < 0 { + let mut errors: Object = std::ptr::null_mut(); + let get_errors: unsafe extern "system" fn(Object, *mut Object) -> Hresult = + method(result, 5); + if get_errors(result, &mut errors) >= 0 && !errors.is_null() { + let ptr: unsafe extern "system" fn(Object) -> *const u8 = method(errors, 3); + let len: unsafe extern "system" fn(Object) -> usize = method(errors, 4); + let bytes = std::slice::from_raw_parts(ptr(errors), len(errors)); + text = String::from_utf8_lossy(bytes) + .trim_end_matches('\0') + .trim() + .into(); + release(errors); + } + if text.is_empty() { + text = format!("rejected ({status:#x})"); + } + } + release(result); + if status < 0 { Err(text) } else { Ok(()) } + } + } +} + +impl Drop for Validator { + fn drop(&mut self) { + // SAFETY: we own one reference. + unsafe { release(self.object) }; + } +} diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs new file mode 100644 index 0000000..f114db1 --- /dev/null +++ b/crates/victory-shader/src/emit/wave.rs @@ -0,0 +1,679 @@ +//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1` +//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's +//! wave, the inactive ones included, which is how the compiler expands +//! HLSL wave reductions and prefix sums (an identity put into the inactive +//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane` +//! steps). A host lane that is elsewhere cannot run that code, so each +//! section is simulated on the console's lanes with symbolic values, and a +//! value it leaves is lowered by what it turned out to be: the reduction or +//! prefix of one operation over the lanes' (masked) inputs, which DXIL's +//! wave operations compute over the host's active lanes. No instruction +//! sequence is matched; any step the simulation does not model leaves the +//! values it writes unknown. + +use std::collections::HashMap; + +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +use crate::ir::{EXEC, Inst, Program, Reg, Value}; + +/// An associative operation and its identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Op { + AddU, + AddF, + MinU, + MaxU, + MinI, + MaxI, + MinF, + MaxF, + Or, + And, + Xor, +} + +impl Op { + fn of(name: &str) -> Option<Op> { + Some(match name { + "v_add_nc_u32" => Op::AddU, + "v_add_f32" => Op::AddF, + "v_min_u32" => Op::MinU, + "v_max_u32" => Op::MaxU, + "v_min_i32" => Op::MinI, + "v_max_i32" => Op::MaxI, + "v_min_f32" => Op::MinF, + "v_max_f32" => Op::MaxF, + "v_or_b32" => Op::Or, + "v_and_b32" => Op::And, + "v_xor_b32" => Op::Xor, + _ => return None, + }) + } + + /// Whether `k` leaves the other operand unchanged. + fn identity(self, k: u32) -> bool { + match self { + Op::AddU | Op::Or | Op::Xor | Op::MaxU => k == 0, + Op::AddF => k == 0 || k == 0x8000_0000, + Op::MinU | Op::And => k == u32::MAX, + Op::MinI => k == 0x7FFF_FFFF, + Op::MaxI => k == 0x8000_0000, + Op::MinF => k == 0x7F80_0000, + Op::MaxF => k == 0xFF80_0000, + } + } + + /// Counting a lane twice changes the result. + fn counts(self) -> bool { + matches!(self, Op::AddU | Op::AddF | Op::Xor) + } +} + +/// A lane's value inside a section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Sym { + Unknown, + K(u32), + /// The lane's own value of a VGPR value from before the section. + Own(Value), + /// A uniform value from before the section. + Uni(Value), + /// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane). + Red { + op: Option<Op>, + src: Value, + mask: Value, + ident: u32, + lanes: u64, + }, +} + +/// What a value a section leaves holds in every lane. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Shape { + K(u32), + Value(Value), + /// The lane's own `mask ? src : ident`. + Masked(Value, Value, u32), + /// `op` over every lane. + Active(Op, Value, Value, u32), + /// `op` over the lanes below (`inclusive`: and including) each lane. + Prefix(Op, Value, Value, u32, bool), +} + +/// The section starting at instruction `start` of a block: its restore +/// index and the shapes of the values it writes. +pub(crate) struct Section { + pub end: usize, + pub shapes: HashMap<Value, Shape>, +} + +/// Every whole-wave section of `block`, by start index. +pub(crate) fn sections(p: &Program, block: usize) -> HashMap<usize, Section> { + let insts = &p.blocks[block].insts; + let wave: u32 = if p.wave64 { 64 } else { 32 }; + let mut out = HashMap::new(); + let mut i = 0; + while i < insts.len() { + let inst = &insts[i]; + // EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`. + let all = match inst.name() { + "s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)), + "s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)), + _ => None, + }; + let start = all.is_some_and( + |k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)), + ); + let saved = match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } if start => inst.write(Reg::S(*code)), + _ => None, + }; + let Some(saved) = saved else { + i += 1; + continue; + }; + let end = (i + 1..insts.len()).find(|&j| { + insts[j].write(Reg::S(EXEC)).is_some() + && insts[j].read(Reg::S(saved_code(inst))) == Some(saved) + }); + let Some(end) = end else { + break; + }; + let shapes = simulate(&insts[i + 1..end], wave, saved); + out.insert(i, Section { end, shapes }); + i = end + 1; + } + out +} + +fn saved_code(inst: &Inst) -> u8 { + match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } => *code, + _ => NULL, + } +} + +/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it +/// writes; `None` for patterns not modelled. +fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> { + match d { + Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)), + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15)); + let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0; + let (src, inside) = match ctrl { + 0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true), + 0x101..=0x10F => (l + n, pos + n < 16), + 0x111..=0x11F => (l.wrapping_sub(n), pos >= n), + 0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true), + 0x140 => (l ^ 15, true), + 0x141 => (l ^ 7, true), + 0x150..=0x15F => (row | n, true), + 0x160..=0x16F => (l ^ n, true), + _ => return None, + }; + match (inside, bound_ctrl) { + (true, _) => Some((src, false, enabled)), + (false, true) => Some((l, true, enabled)), + (false, false) => Some((l, false, false)), + } + } + } +} + +fn combine(op: Op, a: Sym, b: Sym) -> Sym { + match (a, b) { + (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x, + ( + Sym::Red { + op: oa, + src, + mask, + ident, + lanes: la, + }, + Sym::Red { + op: ob, + src: sb, + mask: mb, + ident: ib, + lanes: lb, + }, + ) if (src, mask, ident) == (sb, mb, ib) + && op.identity(ident) + && oa.is_none_or(|o| o == op) + && ob.is_none_or(|o| o == op) + && (!op.counts() || la & lb == 0) => + { + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes: la | lb, + } + } + _ => Sym::Unknown, + } +} + +fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap<Value, Shape> { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut exec = all; + let mut vec: HashMap<Value, Vec<Sym>> = HashMap::new(); + let mut uni: HashMap<Value, Sym> = HashMap::new(); + // Masks the section derives from the saved EXEC (`s_and` with it). + let mut masked = vec![saved]; + for inst in insts { + let name = inst.name(); + if inst.write(Reg::S(EXEC)).is_some() { + // Constant lane sets (prefix sums); anything else ends what + // the simulation can follow. + let lo = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten(); + let Some(k) = lo else { + return shapes(vec, uni, wave); + }; + exec = if name == "s_mov_b64" { + k + } else { + exec & !0xFFFF_FFFF | k & 0xFFFF_FFFF + }; + continue; + } + if inst.write(Reg::S(EXEC + 1)).is_some() { + let Some(k) = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten() + else { + return shapes(vec, uni, wave); + }; + exec = exec & 0xFFFF_FFFF | k << 32; + continue; + } + if let Fields::Sop { src, .. } = &inst.fields { + if name.starts_with("s_and_b") + && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) + && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) + { + masked.push(w); + } + for &(_, w) in &inst.writes { + uni.entry(w).or_insert(Sym::Unknown); + } + continue; + } + let Fields::Valu(v) = &inst.fields else { + for &(_, w) in &inst.writes { + vec.insert(w, vec![Sym::Unknown; wave as usize]); + } + continue; + }; + let lanes = |op: &Operand, + vec: &HashMap<Value, Vec<Sym>>, + uni: &HashMap<Value, Sym>| + -> Vec<Sym> { + let one = |s: Sym| vec![s; wave as usize]; + match *op { + Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) { + Some(x) => vec + .get(&x) + .cloned() + .unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()), + None => one(Sym::Unknown), + }, + Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) { + Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + None => one(Sym::Unknown), + }, + Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)), + Operand::Literal(x) => one(Sym::K(x)), + _ => one(Sym::Unknown), + } + }; + let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some(); + if name == "v_readlane_b32" { + let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) = + (v.dst, v.src.first(), v.src.get(1)) + else { + continue; + }; + let l = match *lane { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(x) => Some(x), + _ => None, + }; + let x = lanes(src, &vec, &uni); + if let Some(w) = inst.write(Reg::S(code)) { + let s = l + .and_then(|l| x.get(l as usize).copied()) + .unwrap_or(Sym::Unknown); + uni.insert(w, s); + } + continue; + } + let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { + for &(_, w) in &inst.writes { + uni.insert(w, Sym::Unknown); + } + continue; + }; + let Some(dst) = inst.write(Reg::V(dreg)) else { + continue; + }; + let old = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + // src0 as each lane fetches it (DPP), with the lanes that write. + let src0 = v.src.first().map(|o| lanes(o, &vec, &uni)); + let mut writes = exec; + let fetched: Option<Vec<Sym>> = match (v.dpp, &src0) { + (Some(d), Some(s)) => { + if exec != all { + vec.insert(dst, vec![Sym::Unknown; wave as usize]); + continue; + } + let mut f = Vec::with_capacity(wave as usize); + let mut ok = true; + for l in 0..wave { + match dpp_lane(d, l) { + Some((src, zero, on)) if src < wave => { + f.push(if zero { Sym::K(0) } else { s[src as usize] }); + if !on { + writes &= !(1u64 << l); + } + } + _ => ok = false, + } + } + ok.then_some(f) + } + (None, Some(s)) => Some(s.clone()), + _ => None, + }; + let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni)); + let result: Vec<Sym> = match (name, fetched) { + _ if modifiers => vec![Sym::Unknown; wave as usize], + ("v_mov_b32", Some(a)) => a, + ("v_bfrev_b32", Some(a)) => a + .into_iter() + .map(|s| match s { + Sym::K(k) => Sym::K(k.reverse_bits()), + _ => Sym::Unknown, + }) + .collect(), + ("v_cndmask_b32", Some(a)) => { + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied(), mask) { + (Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => { + Sym::Red { + op: None, + src: x, + mask: m, + ident, + lanes: 1 << l, + } + } + _ => Sym::Unknown, + }) + .collect() + } + ("v_permlanex16_b32", Some(a)) => { + // Lanes of each row read the other row of their half; lane + // i's pick is nibble i of {src2, src1}. + let sel = |k: usize| match v.src.get(k) { + Some(&Operand::Const(c)) => crate::resource::inline(c), + Some(&Operand::Literal(x)) => Some(x), + _ => None, + }; + match (sel(1), sel(2)) { + (Some(s1), Some(s2)) => { + let s = u64::from(s1) | u64::from(s2) << 32; + (0..wave) + .map(|l| { + let other = (l & !31) | ((l & 16) ^ 16); + let pick = (s >> (4 * (l & 15)) & 15) as u32; + a[(other | pick) as usize] + }) + .collect() + } + _ => vec![Sym::Unknown; wave as usize], + } + } + ("v_sub_nc_u32", Some(a)) => { + // A prefix sum less the lane's own term: the exclusive one. + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied()) { + ( + Sym::Red { + op: None | Some(Op::AddU), + src, + mask, + ident: 0, + lanes, + }, + Some(Sym::Red { + op: None | Some(Op::AddU), + src: s2, + mask: m2, + ident: 0, + lanes: l2, + }), + ) if (src, mask) == (s2, m2) && lanes & l2 == l2 => { + let rest = lanes & !l2; + if rest == 0 { + Sym::K(0) + } else { + Sym::Red { + op: Some(Op::AddU), + src, + mask, + ident: 0, + lanes: rest, + } + } + } + _ => Sym::Unknown, + }) + .collect() + } + (n, Some(a)) => match (Op::of(n), src(1)) { + (Some(op), Some(b)) => (0..wave as usize) + .map(|l| combine(op, a[l], b[l])) + .collect(), + _ => vec![Sym::Unknown; wave as usize], + }, + _ => vec![Sym::Unknown; wave as usize], + }; + let merged = (0..wave as usize) + .map(|l| { + if writes >> l & 1 != 0 { + result[l] + } else { + old[l] + } + }) + .collect(); + vec.insert(dst, merged); + } + shapes(vec, uni, wave) +} + +fn constant(inst: &Inst) -> Option<u64> { + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + match *src.first()? { + Operand::Const(c) => { + let x = crate::resource::inline(c)?; + Some(if (x as i32) < 0 { + u64::MAX + } else { + u64::from(x) + }) + } + Operand::Literal(x) => Some(u64::from(x)), + _ => None, + } +} + +/// The shape of each value, where every lane agrees on one. +fn shapes( + vec: HashMap<Value, Vec<Sym>>, + uni: HashMap<Value, Sym>, + wave: u32, +) -> HashMap<Value, Shape> { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut out = HashMap::new(); + let single = |s: Sym| match s { + Sym::K(k) => Some(Shape::K(k)), + Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + _ => None, + }; + for (v, s) in uni { + if let Some(sh) = single(s) { + out.insert(v, sh); + } + } + for (v, lanes) in vec { + if let Some(sh) = per_lane(&lanes, all) { + out.insert(v, sh); + } + } + out +} + +fn per_lane(lanes: &[Sym], all: u64) -> Option<Shape> { + let first = lanes[0]; + let own = |l: usize, s: Sym| match s { + Sym::Red { + op: None, + src, + mask, + ident, + lanes, + } if lanes == 1 << l => Some((src, mask, ident)), + _ => None, + }; + if let Some(m) = own(0, first) + && lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m)) + { + return Some(Shape::Masked(m.0, m.1, m.2)); + } + if lanes.iter().all(|&s| s == first) { + return match first { + Sym::K(k) => Some(Shape::K(k)), + Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + _ => None, + }; + } + // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). + let mut found: Option<(Op, Value, Value, u32, bool)> = None; + for (l, &s) in lanes.iter().enumerate() { + let below = (1u64 << l) - 1; + let (op, src, mask, ident, set) = match s { + Sym::Red { + op, + src, + mask, + ident, + lanes, + } => (op, src, mask, ident, lanes), + // Lane 0 of an exclusive prefix holds the identity. + Sym::K(_) if l == 0 => continue, + _ => return None, + }; + let inclusive = set == below | 1 << l; + if !inclusive && set != below { + return None; + } + let op = match (op, found) { + (Some(o), _) => o, + (None, Some(f)) => f.0, + (None, None) => continue, + }; + let me = (op, src, mask, ident, inclusive); + match found { + None => found = Some(me), + Some(f) if f == me => {} + _ => return None, + } + } + let (op, src, mask, ident, inclusive) = found?; + if let Sym::K(k) = lanes[0] + && (inclusive || k != ident) + { + return None; + } + Some(Shape::Prefix(op, src, mask, ident, inclusive)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dpp_lanes_follow_the_isa() { + // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. + let shr = Dpp::Row { + ctrl: 0x111, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(shr, 16), Some((16, true, true))); + assert_eq!(dpp_lane(shr, 17), Some((16, false, true))); + // row_mirror: lane 3 reads lane 12. + let mirror = Dpp::Row { + ctrl: 0x140, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(mirror, 3), Some((12, false, true))); + // dpp8 [1,0,3,2,5,4,7,6] swaps neighbours. + let swap = Dpp::Lanes { + sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21, + fi: false, + }; + assert_eq!(dpp_lane(swap, 8), Some((9, false, true))); + } + + #[test] + fn prefixes_are_recognised() { + let (x, m) = (Value(1), Value(2)); + let red = |lanes: u64| Sym::Red { + op: Some(Op::AddU), + src: x, + mask: m, + ident: 0, + lanes, + }; + let inclusive: Vec<Sym> = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect(); + assert_eq!( + per_lane(&inclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, true)) + ); + let mut exclusive: Vec<Sym> = (0..64).map(|l| red((1u64 << l) - 1)).collect(); + exclusive[0] = Sym::K(0); + assert_eq!( + per_lane(&exclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, false)) + ); + assert_eq!( + per_lane(&vec![red(u64::MAX); 64], u64::MAX), + Some(Shape::Active(Op::AddU, x, m, 0)) + ); + } +} diff --git a/crates/victory-shader/src/io.rs b/crates/victory-shader/src/io.rs new file mode 100644 index 0000000..0b7f45b --- /dev/null +++ b/crates/victory-shader/src/io.rs @@ -0,0 +1,693 @@ +//! I/O raising (decision 0003): what a program's input registers, its +//! interpolation and its exports mean. +//! +//! Pixel shaders get the VGPRs `SPI_PS_INPUT_ADDR` enables, in a fixed +//! order (barycentrics, then position, front face...). `v_interp_p1` and +//! `v_interp_p2` (and their f16 forms) evaluate an attribute from a pair of +//! barycentrics; `v_interp_mov` reads one vertex's value. After the 32-bit +//! export patch ([`NativeProgram::patched_code`]) exports carry plain +//! 32-bit values: `mrt<n>` is render target n, `mrtz` depth, stencil and +//! sample mask, `null` nothing. A lane whose EXEC bit is clear at the +//! export that ends the program (`done`) is discarded: that export's guard +//! after structurisation. +//! +//! Vertex shaders that run as the hardware VS get the vertex id in v0, the +//! primitive id in v2 and the instance id in v3; the fetch shader loads +//! channel k of each attribute into its VGPR + k. `exp pos0` is the +//! position, `exp param<n>` the output with parameter n. +//! +//! Attributes and outputs are named by their row: a register of the +//! container's signature part. +//! +//! Compute programs get the thread id in the group in v0-v2 and the group +//! id in the SGPRs after the user data, as `COMPUTE_PGM_RSRC2` enables them. +//! +//! Mesh programs run as one NGG stage. The program computes its thread +//! index from the wave index (s3 bits 24-27) and the lane (`v_mbcnt`), and +//! its group id from v5 of the first lane (`v_readfirstlane`: the group +//! times the group size). Lane n exports vertex n (`exp pos`, `exp param`) +//! and primitive n (`exp prim`: 10-bit vertex indices at bits 0, 10, 20, +//! bit 31 culls); `param` entries with bit 7 are per-primitive outputs. One +//! lane sends the output counts (`s_sendmsg` GS_ALLOC_REQ, m0 = vertices | +//! primitives << 12). + +use crate::ShaderError; +use crate::gfx10::{Fields, Operand}; +use crate::ir::{Inst, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, PsInput, StageIo, Usage}; +use crate::resource::Site; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Input { + VertexId, + PrimitiveId, + InstanceId, + /// A vertex attribute the fetch shader loads. + Attribute { + row: u8, + channel: u8, + }, + /// `index` 0 is i, 1 is j (2 the pull model's w). + Barycentric { + kind: Barycentric, + index: u8, + }, + /// Pixel position channel (0-3: x, y, z, w). + Position(u8), + FrontFace, + /// Sample id and other bits. + Ancillary, + SampleCoverage, + FixedPosition, + LineStipple, + /// Compute: thread-group id component (an SGPR). + GroupId(u8), + /// Compute: thread id within the group, component (a VGPR). + ThreadIdInGroup(u8), + /// Compute: the thread-group info SGPR (wave index and count). + GroupInfo, + /// Mesh: v5, the group id times the group size (read as uniform). + MeshGroup, + /// Mesh: s3, the wave's index in the group in bits 24-27. + MergedWaveInfo, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Barycentric { + PerspectiveSample, + PerspectiveCenter, + PerspectiveCentroid, + PerspectivePullModel, + LinearSample, + LinearCenter, + LinearCentroid, +} + +/// The pixel input VGPRs in hardware order: one entry per +/// `SPI_PS_INPUT_ADDR` bit. +const PS_VGPRS: [(u8, Option<Barycentric>); 16] = [ + (2, Some(Barycentric::PerspectiveSample)), + (2, Some(Barycentric::PerspectiveCenter)), + (2, Some(Barycentric::PerspectiveCentroid)), + (3, Some(Barycentric::PerspectivePullModel)), + (2, Some(Barycentric::LinearSample)), + (2, Some(Barycentric::LinearCenter)), + (2, Some(Barycentric::LinearCentroid)), + (1, None), // line stipple + (1, None), // position x + (1, None), // y + (1, None), // z + (1, None), // w + (1, None), // front face + (1, None), // ancillary + (1, None), // sample coverage + (1, None), // fixed-point position +]; + +fn ps_system(bit: usize) -> Input { + match bit { + 7 => Input::LineStipple, + 8..=11 => Input::Position(bit as u8 - 8), + 12 => Input::FrontFace, + 13 => Input::Ancillary, + 14 => Input::SampleCoverage, + _ => Input::FixedPosition, + } +} + +/// An attribute channel of the input signature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Attribute { + pub usage: Usage, + pub row: u8, + pub channel: u8, + /// The upper f16 half of the channel (packed fp16 inputs). + pub high: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Interp { + /// This site's result (`v_interp_p2*`) is the attribute interpolated + /// with `barycentric`; `first` are the `v_interp_p1*` halves it + /// completes (one per path where the compiler shares a first half). + Interpolated { + attribute: Attribute, + barycentric: Barycentric, + first: Vec<Site>, + }, + /// One vertex's value (`v_interp_mov_f32`), as encoded: 0 for P10, + /// 1 for P20, 2 for P0 (the provoking vertex). + Vertex { attribute: Attribute, vertex: u8 }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Target { + Color(u8), + /// Depth, stencil, sample mask (channels as `DB_SHADER_CONTROL` enables). + Depth, + Null, + Position(u8), + Param { + usage: Usage, + row: u8, + }, + /// `param0` of a vertex shader without outputs: the hardware wants one + /// parameter export regardless. + Unread, + /// The primitive export of a merged or mesh stage. + Primitive, + /// A mesh program's per-primitive output (a row of `PSG1`). + PrimitiveParam { + usage: Usage, + row: u8, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Export { + pub site: Site, + pub target: Target, + /// Per channel, as the instruction enables them. + pub values: [Option<Value>; 4], + /// Two f16 values per dword. + pub compressed: bool, + /// The program's last export (for pixels: kills the lanes not in EXEC). + pub done: bool, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Io { + /// Input values the hardware loads, with their meaning; other VGPRs + /// read before written hold undefined values. + pub inputs: Vec<(Value, Input)>, + pub interps: Vec<(Site, Interp)>, + pub exports: Vec<Export>, +} + +/// Raises the I/O of `p`, built from `native`'s patched code. Fails for +/// stages whose stage data is not read and on constructs not covered yet. +pub fn raise(p: &Program, native: &NativeProgram) -> Result<Io, ShaderError> { + let unsupported = |offset, what| ShaderError::Unsupported { offset, what }; + let (loaded, ps_inputs, params) = match (&native.io, native.stage) { + ( + StageIo::Ps { + inputs, input_addr, .. + }, + HwStage::Ps, + ) => { + // A pixel shader exports no parameters; `[]` never reaches `Unread`. + let loaded = ps_vgprs(*input_addr) + .into_iter() + .map(|(r, i)| (Reg::V(r), i)) + .collect(); + (loaded, &inputs[..], &[][..]) + } + (StageIo::Vs { inputs, outputs }, HwStage::Vs) => { + let mut loaded = vec![ + (Reg::V(0), Input::VertexId), + (Reg::V(2), Input::PrimitiveId), + (Reg::V(3), Input::InstanceId), + ]; + for i in inputs { + for channel in (0..4).filter(|c| i.mask >> c & 1 != 0) { + let input = Input::Attribute { + row: i.row, + channel, + }; + loaded.push((Reg::V(i.vgpr + channel), input)); + } + } + (loaded, &[][..], &outputs[..]) + } + // Compute: thread ids in v0-v2, group ids and the group info in the + // SGPRs after the user data. + (StageIo::Cs(cs), HwStage::Cs) => { + let (ids, info) = cs.system_sgprs(); + let mut loaded: Vec<(Reg, Input)> = (0..cs.thread_id_vgprs()) + .map(|c| (Reg::V(c), Input::ThreadIdInGroup(c))) + .collect(); + for (c, s) in ids.into_iter().enumerate() { + if let Some(s) = s { + loaded.push((Reg::S(s), Input::GroupId(c as u8))); + } + } + loaded.extend(info.map(|s| (Reg::S(s), Input::GroupInfo))); + (loaded, &[][..], &[][..]) + } + (StageIo::Ms(ms), HwStage::Ms) => { + let group = p.inputs.iter().find(|i| i.0 == Reg::V(5)).map(|i| i.1); + // The group input holds the same value in every lane only as the + // first lane reads it; a VGPR write reads its old value too. + let per_lane = p.blocks.iter().flat_map(|b| &b.insts).find(|i| { + group.is_some_and(|g| i.reads.contains(&(Reg::V(5), g))) + && i.name() != "v_readfirstlane_b32" + && i.write(Reg::V(5)).is_none() + }); + if let Some(i) = per_lane { + return Err(unsupported( + i.machine.offset, + "the mesh group input read per lane", + )); + } + let loaded = vec![ + (Reg::V(5), Input::MeshGroup), + (Reg::S(3), Input::MergedWaveInfo), + ]; + (loaded, &[][..], &ms.outputs[..]) + } + _ => return Err(unsupported(0, "I/O of this stage")), + }; + let inputs: Vec<(Value, Input)> = p + .inputs + .iter() + .filter_map(|&(reg, v)| loaded.iter().find(|l| l.0 == reg).map(|l| (v, l.1))) + .collect(); + let input_of = |v: Value| inputs.iter().find(|i| i.0 == v).map(|i| i.1); + let attribute = |inst: &Inst, attr: &Operand| match *attr { + Operand::Attr { index, chan, high } => ps_inputs + .iter() + .find(|i: &&PsInput| i.attr == index) + .map(|i| Attribute { + usage: i.usage, + row: i.row, + channel: chan, + high, + }) + .ok_or(unsupported( + inst.machine.offset, + "an interpolated attribute the stage data does not list", + )), + _ => Err(unsupported(inst.machine.offset, "an interpolation operand")), + }; + // A VGPR value's barycentric kind and index, if it is one as loaded. + let barycentric = |v: Option<Value>| match v.and_then(input_of) { + Some(Input::Barycentric { kind, index }) => Some((kind, index)), + _ => None, + }; + + let mut io = Io { + inputs: inputs.clone(), + ..Io::default() + }; + let defs: std::collections::HashMap<Value, Site> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .enumerate() + .flat_map(move |(i, inst)| inst.writes.iter().map(move |w| (w.1, (b, i)))) + }) + .collect(); + let phis: std::collections::HashMap<Value, (usize, usize)> = p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .phis + .iter() + .enumerate() + .map(move |(i, phi)| (phi.value, (b, i))) + }) + .collect(); + let halves = Halves { + p, + defs: &defs, + phis: &phis, + }; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let at = inst.machine.offset; + let name = inst.name(); + match &inst.fields { + Fields::Vintrp { dst, src, attr } => { + let attribute = attribute(inst, attr)?; + match (name, *src) { + ("v_interp_mov_f32", Operand::Const(vertex)) => { + io.interps + .push((site, Interp::Vertex { attribute, vertex })); + } + ("v_interp_p1_f32", _) => {} + ("v_interp_p2_f32", Operand::Vector { reg, .. }) => { + let Operand::Vector { reg: d, .. } = *dst else { + return Err(unsupported(at, "an interpolation operand")); + }; + // The first half's result is this one's old dst. + let interp = halves + .pair( + attr, + inst.read(Reg::V(d)), + inst.read(Reg::V(reg)), + &barycentric, + ) + .map_err(|what| unsupported(at, what))?; + io.interps.push((site, interp.with(attribute))); + } + _ => return Err(unsupported(at, "an interpolation form")), + } + } + Fields::Valu(v) if name.starts_with("v_interp_") => match name { + "v_interp_p1ll_f16" => {} + "v_interp_p2_f16" => { + let attribute = attribute(inst, &v.src[0])?; + let read = |k: usize| match v.src.get(k) { + Some(&Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), + _ => None, + }; + let interp = halves + .pair(&v.src[0], read(2), read(1), &barycentric) + .map_err(|what| unsupported(at, what))?; + io.interps.push((site, interp.with(attribute))); + } + _ => return Err(unsupported(at, "an interpolation form")), + }, + Fields::Exp { + target, + src, + compr, + done, + .. + } => { + let target = match *target { + t @ 0..=7 => Target::Color(t), + 8 => Target::Depth, + 9 => Target::Null, + t @ 12..=16 => Target::Position(t - 12), + 20 => Target::Primitive, + 32 if params.is_empty() => Target::Unread, + t @ 32..=63 => { + // Bit 7: a mesh program's per-primitive output. + let o = params.iter().find(|o| o.param & 0x7F == t - 32).ok_or( + unsupported(at, "a parameter export the stage data does not list"), + )?; + let (usage, row) = (o.usage, o.row); + if o.param & 0x80 != 0 { + Target::PrimitiveParam { usage, row } + } else { + Target::Param { usage, row } + } + } + _ => return Err(unsupported(at, "an export target")), + }; + let values = src.map(|s| match s { + Some(Operand::Vector { reg, .. }) => inst.read(Reg::V(reg)), + _ => None, + }); + io.exports.push(Export { + site, + target, + values, + compressed: *compr, + done: *done, + }); + } + _ => {} + } + } + } + Ok(io) +} + +/// The pixel input VGPRs that `addr` enables, with their meaning. +fn ps_vgprs(addr: u32) -> Vec<(u8, Input)> { + let mut out = Vec::new(); + let mut next = 0u8; + for (bit, &(count, kind)) in PS_VGPRS.iter().enumerate() { + if addr >> bit & 1 == 0 { + continue; + } + for index in 0..count { + let input = match kind { + Some(kind) => Input::Barycentric { kind, index }, + None => ps_system(bit), + }; + out.push((next + index, input)); + } + next += count; + } + out +} + +/// An interpolation before its attribute is known. +struct Pair { + barycentric: Barycentric, + first: Vec<Site>, +} + +impl Pair { + fn with(self, attribute: Attribute) -> Interp { + Interp::Interpolated { + attribute, + barycentric: self.barycentric, + first: self.first, + } + } +} + +/// Finds the first halves of interpolations. +struct Halves<'a> { + p: &'a Program, + defs: &'a std::collections::HashMap<Value, Site>, + phis: &'a std::collections::HashMap<Value, (usize, usize)>, +} + +impl Halves<'_> { + /// The interpolation whose second half reads the first half's result + /// `acc`, the barycentric `j`, and attribute `attr`: every first half + /// must read the same attribute channel and the same kind's i. + fn pair( + &self, + attr: &Operand, + acc: Option<Value>, + j: Option<Value>, + barycentric: &impl Fn(Option<Value>) -> Option<(Barycentric, u8)>, + ) -> Result<Pair, &'static str> { + let mut first = Vec::new(); + self.sites( + acc.ok_or("an interpolation without its first half")?, + &mut Vec::new(), + &mut first, + )?; + let Some((kind, 1)) = barycentric(j) else { + return Err("an interpolation with computed barycentrics"); + }; + for &(b, i) in &first { + let inst = &self.p.blocks[b].insts[i]; + let (a, i) = match &inst.fields { + Fields::Vintrp { + src: Operand::Vector { reg, .. }, + attr, + .. + } if inst.name() == "v_interp_p1_f32" => (*attr, inst.read(Reg::V(*reg))), + Fields::Valu(v) if inst.name() == "v_interp_p1ll_f16" => match v.src.get(1) { + Some(&Operand::Vector { reg, .. }) => (v.src[0], inst.read(Reg::V(reg))), + _ => return Err("an interpolation without its first half"), + }, + _ => return Err("an interpolation without its first half"), + }; + if a != *attr { + return Err("interpolation halves of different attributes"); + } + if barycentric(i) != Some((kind, 0)) { + return Err("an interpolation with computed barycentrics"); + } + } + Ok(Pair { + barycentric: kind, + first, + }) + } + + /// The instructions `v` comes from, through phis (`seen`: phis on the + /// way; a loop back to one adds nothing). + fn sites( + &self, + v: Value, + seen: &mut Vec<Value>, + out: &mut Vec<Site>, + ) -> Result<(), &'static str> { + if let Some(&site) = self.defs.get(&v) { + if !out.contains(&site) { + out.push(site); + } + return Ok(()); + } + let &(b, i) = self + .phis + .get(&v) + .ok_or("an interpolation without its first half")?; + if !seen.contains(&v) { + seen.push(v); + for &a in &self.p.blocks[b].phis[i].args { + self.sites(a, seen, out)?; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::ExportPatch; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn program(words: &[u32]) -> Program { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + crate::ir::build(&code, false, 256).unwrap() + } + + fn pixel(inputs: Vec<PsInput>, input_addr: u32) -> NativeProgram { + NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs, + input_addr, + db_shader_control: 0, + patches: Vec::<ExportPatch>::new(), + }, + code: vec![], + } + } + + const TEXCOORD: PsInput = PsInput { + usage: Usage::Generic, + row: 1, + mask: 3, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 1, + }; + + #[test] + fn interpolation_pairs_and_color_exports() { + // Blit's pixel shader: TEXCOORD.xy from the perspective-center i/j + // in v0/v1, then exported unconverted to MRT0. + let p = program(&[ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0302_0102, // exp mrt0, v2, v1, v2, v3 done vm + S_ENDPGM, + ]); + let io = raise(&p, &pixel(vec![TEXCOORD], 2)).unwrap(); + let input = |reg| p.inputs.iter().find(|i| i.0 == Reg::V(reg)).unwrap().1; + let center = |index| Input::Barycentric { + kind: Barycentric::PerspectiveCenter, + index, + }; + assert!(io.inputs.contains(&(input(0), center(0)))); + assert!(io.inputs.contains(&(input(1), center(1)))); + // v2 and v3 are read before written but hold nothing. + assert!(!io.inputs.iter().any(|i| i.0 == input(3))); + assert_eq!( + io.interps, + [( + (0, 1), + Interp::Interpolated { + attribute: Attribute { + usage: Usage::Generic, + row: 1, + channel: 0, + high: false + }, + barycentric: Barycentric::PerspectiveCenter, + first: vec![(0, 0)], + } + )] + ); + let [e] = &io.exports[..] else { + panic!("{:?}", io.exports) + }; + assert_eq!( + (e.target, e.done, e.compressed), + (Target::Color(0), true, false) + ); + assert_eq!(e.values[0], p.blocks[0].insts[1].write(Reg::V(2))); + } + + #[test] + fn unpaired_or_unknown_interpolation_fails() { + // p2 alone: its old dst is no p1's result. + let lone = program(&[0xC809_0001, S_ENDPGM]); // v_interp_p2_f32 v2, v1, attr0.x + assert!(raise(&lone, &pixel(vec![TEXCOORD], 2)).is_err()); + // attr1 is not in the stage data. + let other = program(&[0xC808_0400, S_ENDPGM]); // v_interp_p1_f32 v2, v0, attr1.x + assert!(raise(&other, &pixel(vec![TEXCOORD], 2)).is_err()); + } + + #[test] + fn mesh_inputs_and_primitive_export() { + let mesh = |words: &[u32]| { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, true, 256).unwrap(); + let native = NativeProgram { + stage: HwStage::Ms, + wave64: true, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Ms(crate::native::MeshIo { + outputs: vec![], + clip_cntl: 0, + threads: 128, + max_vertices: 128, + max_primitives: 128, + topology: 2, + lds_bytes: 0, + }), + code, + }; + raise(&p, &native) + }; + let io = mesh(&[ + 0x7E04_0505, // v_readfirstlane_b32 s2, v5 + 0xF800_0941, + 0x0000_0009, // exp prim, v9, off, off, off done + S_ENDPGM, + ]) + .unwrap(); + assert!(io.inputs.iter().any(|i| i.1 == Input::MeshGroup)); + assert_eq!(io.exports[0].target, Target::Primitive); + // The group input is uniform only as the first lane reads it. + assert!(mesh(&[0x7E02_0305, S_ENDPGM]).is_err()); // v_mov_b32 v1, v5 + } + + #[test] + fn pixel_vgprs_follow_the_input_address() { + // Linear center (bit 5), then position x and y (bits 8, 9). + let v = ps_vgprs(1 << 5 | 1 << 8 | 1 << 9); + assert_eq!( + v, + [ + ( + 0, + Input::Barycentric { + kind: Barycentric::LinearCenter, + index: 0 + } + ), + ( + 1, + Input::Barycentric { + kind: Barycentric::LinearCenter, + index: 1 + } + ), + (2, Input::Position(0)), + (3, Input::Position(1)), + ] + ); + } +} diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index ac4be42..2b90661 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -360,7 +360,32 @@ pub(crate) fn irreducible_edge( index: &[usize], ) -> Option<(usize, usize)> { let &entry = order.first()?; + let idom = idoms(blocks, order, index); + for &b in order { + for s in blocks[b].exit.successors() { + if index[s] > index[b] { + continue; + } + let mut d = b; + while d != s && d != entry { + d = idom[d]; + } + if d != s { + return Some((b, s)); + } + } + } + None +} + +/// Each block's immediate dominator (the entry's is itself, unreachable +/// blocks' `usize::MAX`); `order` is reverse postorder, `index` each +/// block's position in it. +pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec<usize> { let mut idom = vec![usize::MAX; blocks.len()]; + let Some(&entry) = order.first() else { + return idom; + }; idom[entry] = entry; let intersect = |idom: &[usize], mut a: usize, mut b: usize| { while a != b { @@ -391,21 +416,7 @@ pub(crate) fn irreducible_edge( } } } - for &b in order { - for s in blocks[b].exit.successors() { - if index[s] > index[b] { - continue; - } - let mut d = b; - while d != s && d != entry { - d = idom[d]; - } - if d != s { - return Some((b, s)); - } - } - } - None + idom } /// Node splitting, before SSA. While a loop is entered at several blocks @@ -692,6 +703,13 @@ fn effects( } if let Some(d) = dst { regs(d, &mut w)?; + // These change (or may keep) the destination's old value. + if name.starts_with("s_bitset") + || name.starts_with("s_cmov") + || matches!(name, "s_addk_i32" | "s_mulk_i32") + { + regs(d, &mut r)?; + } } if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32") || name.starts_with("s_cselect_") @@ -1063,6 +1081,25 @@ mod tests { } } + #[test] + fn in_place_scalar_ops_read_their_destination() { + let p = build_words( + &[ + 0xBE8D_1D94, // s_bitset1_b32 s13, 20 + 0xB78E_0010, // s_addk_i32 s14, 0x10 + 0xBE8F_0380, // s_mov_b32 s15, 0 + S_ENDPGM, + ], + false, + ); + let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else { + panic!("{:?}", p.blocks[0].insts) + }; + assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13)))); + assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14)))); + assert_eq!(mov.read(Reg::S(15)), None); + } + #[test] fn loops_carry_values_through_phis() { let p = build_words( diff --git a/crates/victory-shader/src/lib.rs b/crates/victory-shader/src/lib.rs index 4cb8928..8d8c164 100644 --- a/crates/victory-shader/src/lib.rs +++ b/crates/victory-shader/src/lib.rs @@ -8,14 +8,19 @@ pub mod dxbc; pub mod dxil; +pub mod emit; pub mod gfx10; +pub mod io; pub mod ir; pub mod native; +pub mod resource; pub mod structure; pub use dxbc::{Container, FourCC, Part}; pub use dxil::{DxilProgram, ShaderKind, XboxExtras}; -pub use native::{HwStage, NativeProgram, native_programs}; +pub use native::{ + HwStage, NativeProgram, ResourceType, RootParam, RootType, UsedResource, native_programs, +}; #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum ShaderError { diff --git a/crates/victory-shader/src/native.rs b/crates/victory-shader/src/native.rs index ab43d3f..dd62c2f 100644 --- a/crates/victory-shader/src/native.rs +++ b/crates/victory-shader/src/native.rs @@ -17,9 +17,52 @@ //! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF //! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative), //! +0x14 u32 flags: bit 5 wave32 (else wave64) +//! +0x28 u64 root layout table, +0x30 u64 used-resource table +//! (payload-relative), +0x38 u32 and +0x3c u32 their counts //! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used +//! layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs, +//! u32 base register, u8 first user-data dword, u8 root slot, +//! u16 0 +//! used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset +//! (dwords), u32 lower bound, u32 stride, u8 descriptor +//! dwords, u8 first user-data dword, u8 root slot, u8 0 //! ``` //! +//! Stage data follows the record; offsets from its end (E = record + 0x54): +//! +//! ```text +//! PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel +//! mask, u8 attribute (v_interp `attr`), u8 default, u8 second +//! row (of a packed pair), u8 parameter slot, u8 flags (bit 0 +//! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count +//! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL +//! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per +//! MRT: u32 code offset (dwords, -1 none), then the export code +//! for each color format in 10 slots of 10 dwords (ZERO, 32_R, +//! 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR) +//! VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR +//! of channel 0 (channel k in VGPR + k), u8 highest channel; +//! E+0xc4 u32 count +//! E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp +//! param<n>`), u8 row again, u8 slot, u8 flags (bit 0 fp16, +//! bit 1 two fp16 values per dword); E+0x188 u32 count +//! CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size +//! MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a +//! per-primitive output (`PSG1` row); the 3 bytes more are the +//! second row of a packed pair, a slot, flags (bit 0 fp16, bit 1 +//! two fp16 elements packed) +//! E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT, +//! PA_CL_VS_OUT_CNTL, VGT_STRMOUT_CONFIG, SPI_SHADER_PGM_RSRC2_GS, +//! VGT_GS_OUT_PRIM_TYPE, VGT_GS_INSTANCE_CNT, SPI_SHADER_IDX_FORMAT +//! E+0x448 u16 thread-group size in lanes, u16 maximum vertices, +//! u16 maximum primitives, u8 user SGPRs, u8 output topology +//! (2 triangles); code follows at E+0x45c +//! record +0x4c u32 LDS bytes (`lds_byte_size`; mesh programs read it here) +//! ``` +//! +//! Rows are registers of the container's signature parts (`ISG1`, `OSG1`). +//! Merged stages keep their stage data in another layout (not read). +//! //! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), //! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and //! 0x12 16-byte blobs (0x10 is the shader hash). @@ -52,6 +95,31 @@ const RECORD_SIZE: u64 = 0x54; const RECORD_FLAGS: usize = 0x14; const FLAG_WAVE32: u32 = 1 << 5; const RECORD_REGS: usize = 0x50; +const RECORD_LAYOUT: usize = 0x28; +const RECORD_USED: usize = 0x30; +const RECORD_COUNTS: usize = 0x38; +const ENTRY_SIZE: u64 = 20; +const MAX_SEMANTICS: u32 = 32; +const PS_INPUTS: usize = 0x24; +const PS_INPUT_COUNT: usize = 0x124; +const PS_INPUT_ADDR: usize = 0x134; +const PS_DB_SHADER_CONTROL: usize = 0x138; +const PS_PATCH_SIZE: usize = 0x148; +const PS_PATCHES: usize = 0x14c; +const PATCH_SLOT_DWORDS: usize = 10; +/// The variant that exports every channel as a raw 32-bit value. +const PATCH_FULL: usize = 9; +const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4; +const MRTS: usize = 8; +const VS_INPUTS: usize = 0x24; +const VS_INPUT_COUNT: usize = 0xc4; +const VS_OUTPUTS: usize = 0xc8; +const VS_OUTPUT_COUNT: usize = 0x188; +const CS_RSRC2: usize = 0x24; +const CS_THREADS: usize = 0x28; +const RECORD_LDS: usize = 0x4c; +const MS_CLIP_CNTL: usize = 0x194; +const MS_INFO: usize = 0x448; /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. const MAX_UNPACKED: u64 = 16 << 20; @@ -69,6 +137,17 @@ pub enum HwStage { Cs, } +impl HwStage { + /// The SGPR holding user-data dword `index`: merged stages (and mesh + /// shaders, which run as one) have 8 system SGPRs first. + pub fn user_sgpr(self, index: u8) -> u8 { + match self { + HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8, + HwStage::Vs | HwStage::Ps | HwStage::Cs => index, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct NativeProgram { pub stage: HwStage, @@ -76,10 +155,251 @@ pub struct NativeProgram { pub wave64: bool, /// VGPRs the program uses (v0 up to this), the bound of indexed access. pub vgprs: u16, - /// GFX10 machine code. + /// Where the root signature's parameters arrive (user SGPRs). + pub layout: Vec<RootParam>, + /// The descriptors the program reads, by root parameter. + pub used: Vec<UsedResource>, + pub io: StageIo, + /// GFX10 machine code, as stored. pub code: Vec<u8>, } +impl NativeProgram { + /// The code with each render target's export patched for its full + /// 32-bit format, so exports carry the shader's values unconverted (as + /// the console does at pipeline creation for that format). + pub fn patched_code(&self) -> Vec<u8> { + let mut code = self.code.clone(); + if let StageIo::Ps { patches, .. } = &self.io { + for p in patches { + let at = p.offset as usize * 4; + for (i, word) in p.code.iter().enumerate() { + code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes()); + } + } + } + code + } +} + +/// What a semantic is, as the stage data names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Usage { + Generic, + ClipDistance, + Other(u8), +} + +impl Usage { + fn from_raw(raw: u8) -> Self { + match raw { + 6 => Usage::Generic, + 7 => Usage::ClipDistance, + n => Usage::Other(n), + } + } +} + +/// A pixel shader input: what `v_interp` of attribute `attr` reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PsInput { + pub usage: Usage, + /// Register in the input signature. + pub row: u8, + pub mask: u8, + pub attr: u8, + pub flat: bool, + pub fp16: bool, + /// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the + /// second element's register. + pub pack2: bool, + pub row2: u8, +} + +/// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsInput { + pub usage: Usage, + pub row: u8, + pub mask: u8, + pub vgpr: u8, +} + +/// What `exp param<param>` of a vertex shader writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsOutput { + pub usage: Usage, + /// Register in the output signature. + pub row: u8, + pub param: u8, + /// 16-bit values, one per dword (low half) unless `pack2`: then two per + /// dword, channel c of this row in dword c / 2 (odd channels in the + /// high half), then a second 16-bit row from the next whole dword (the + /// next 16-bit row of the signature no entry names). + pub fp16: bool, + pub pack2: bool, +} + +/// The export code of one render target for its full 32-bit format. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExportPatch { + pub mrt: u8, + /// Where it goes in the code, in dwords. + pub offset: u32, + pub code: Vec<u32>, +} + +/// Inputs and outputs, for the stages whose stage data is read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum StageIo { + #[default] + None, + Vs { + inputs: Vec<VsInput>, + outputs: Vec<VsOutput>, + }, + Ps { + inputs: Vec<PsInput>, + /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. + input_addr: u32, + /// `DB_SHADER_CONTROL`: depth export, kill. + db_shader_control: u32, + patches: Vec<ExportPatch>, + }, + Cs(ComputeIo), + Ms(MeshIo), +} + +/// A mesh program's outputs and limits. It runs as one hardware NGG stage: +/// lane n of the group (`threads` lanes) exports vertex n (`exp pos`, +/// `exp param`) and primitive n (`exp prim`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshIo { + /// `exp param<n>` targets; `param` bit 7 set: a per-primitive output, + /// `row` then a row of the primitive signature (`PSG1`). + pub outputs: Vec<VsOutput>, + /// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry. + pub clip_cntl: u32, + /// Thread-group size in lanes (the HLSL group rounded up to waves). + pub threads: u32, + pub max_vertices: u32, + pub max_primitives: u32, + /// 1 lines, 2 triangles. + pub topology: u8, + pub lds_bytes: u32, +} + +/// A compute program's dispatch settings. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ComputeIo { + /// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs + /// follow them, LDS size. + pub rsrc2: u32, + /// Thread-group size (`numthreads`). + pub threads: [u32; 3], +} + +impl ComputeIo { + /// User SGPRs before the system ones. + pub fn user_sgprs(&self) -> u8 { + (self.rsrc2 >> 1 & 0x1F) as u8 + } + + /// The SGPR of each enabled thread-group id component, in order after + /// the user SGPRs, then the thread-group info SGPR if enabled. + pub fn system_sgprs(&self) -> ([Option<u8>; 3], Option<u8>) { + let mut next = self.user_sgprs(); + let mut take = |bit: u32| { + (self.rsrc2 >> bit & 1 != 0).then(|| { + next += 1; + next - 1 + }) + }; + let ids = [take(7), take(8), take(9)]; + (ids, take(10)) + } + + /// Thread id components in v0, v1, v2 (1 to 3). + pub fn thread_id_vgprs(&self) -> u8 { + (self.rsrc2 >> 11 & 3) as u8 + 1 + } + + /// LDS bytes per thread group (512-byte granules). + pub fn lds_bytes(&self) -> u32 { + (self.rsrc2 >> 15 & 0x1FF) * 512 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum RootType { + Constants, + /// A 64-bit buffer address. + Descriptor, + /// The 32-bit heap address of a descriptor table range. + Table, + /// A sampler the root signature fixes. + ImmediateSampler, + /// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources). + ResourceHeap, + /// The 32-bit address of the sampler heap. + SamplerHeap, + Other(u32), +} + +impl RootType { + fn from_raw(raw: u32) -> Self { + match raw { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 3 => RootType::Table, + 4 => RootType::ImmediateSampler, + 5 => RootType::ResourceHeap, + 6 => RootType::SamplerHeap, + n => RootType::Other(n), + } + } +} + +/// One root parameter (or table range) and the user SGPRs holding it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootParam { + pub root: RootType, + /// Of the range within its table. + pub table_offset_dwords: u32, + /// User SGPRs from `user_data` on. + pub sgprs: u32, + /// Shader register of the first descriptor (`b`/`t`/`u`/`s` number). + pub base_register: u32, + /// First user-data dword ([`HwStage::user_sgpr`]). + pub user_data: u8, + /// Index of the parameter in the root signature. + pub slot: u8, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResourceType { + Srv, + Sampler, + Cbv, + Uav, + Other(u8), +} + +/// A descriptor range the program reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UsedResource { + pub kind: ResourceType, + pub root: RootType, + pub table_offset_dwords: u32, + /// Shader register of the first descriptor read. + pub lower_bound: u32, + pub stride: u32, + /// Size of the descriptor (4 or 8). + pub dwords: u8, + pub user_data: u8, + pub slot: u8, +} + /// The native programs in a `DXIL` part's data; empty for the PC layout. pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { @@ -141,28 +461,198 @@ fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> { } let mut out = Vec::new(); for (stage, at) in SLOTS { - let record = u64_at(payload, at)?; - if record == ABSENT { + let start = u64_at(payload, at)?; + if start == ABSENT { continue; } let record = - bytes(payload, record, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; + bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) .ok_or(Malformed("native code out of bounds"))?; let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; if vgprs > 256 { return Err(Malformed("implausible VGPR count")); } + let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> { + let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?); + if len == 0 { + return Ok(&[]); + } + bytes(payload, u64_at(record, at)?, len) + .ok_or(Malformed("FSSM root table out of bounds")) + }; + let layout = table(RECORD_LAYOUT, RECORD_COUNTS)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| RootParam { + root: RootType::from_raw(le32(e, 0)), + table_offset_dwords: le32(e, 4), + sgprs: le32(e, 8), + base_register: le32(e, 12), + user_data: e[16], + slot: e[17], + }) + .collect(); + let used = table(RECORD_USED, RECORD_COUNTS + 4)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| UsedResource { + kind: match e[0] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root: RootType::from_raw(e[1].into()), + table_offset_dwords: le32(e, 4), + lower_bound: le32(e, 8), + stride: le32(e, 12), + dwords: e[16], + user_data: e[17], + slot: e[18], + }) + .collect(); + // The record is in bounds, so its end is too. + let stage_data = &payload[(start + RECORD_SIZE) as usize..]; + let io = match stage { + HwStage::Ps => ps_io(stage_data, code.len())?, + HwStage::Vs => vs_io(stage_data)?, + HwStage::Cs => StageIo::Cs(ComputeIo { + rsrc2: u32_at(stage_data, CS_RSRC2)?, + threads: [ + u32_at(stage_data, CS_THREADS)?, + u32_at(stage_data, CS_THREADS + 4)?, + u32_at(stage_data, CS_THREADS + 8)?, + ], + }), + HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, + _ => StageIo::None, + }; out.push(NativeProgram { stage, wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, vgprs, + layout, + used, + io, code: code.to_vec(), }); } Ok(out) } +/// The entries of `size` bytes from `at`, with their count at `count_at`. +fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> { + let count = u32_at(data, count_at)?; + if count > MAX_SEMANTICS { + return Err(Malformed("implausible semantic count")); + } + data.get(at..at + size * count as usize) + .ok_or(Malformed("stage data out of bounds")) +} + +fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> { + let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)? + .as_chunks::<8>() + .0 + .iter() + .map(|e| PsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + attr: e[3], + flat: e[7] & 1 != 0, + fp16: e[7] & 8 != 0, + pack2: e[7] & 0x10 != 0, + row2: e[5], + }) + .collect(); + let size = u32_at(data, PS_PATCH_SIZE)? as usize; + if size > PATCH_SLOT_DWORDS { + return Err(Malformed("implausible export patch size")); + } + let mut patches = Vec::new(); + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + let offset = u32_at(data, at)?; + if offset == u32::MAX { + continue; + } + if (offset as usize + size) * 4 > code_len { + return Err(Malformed("export patch outside the code")); + } + let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + let code = (0..size) + .map(|i| u32_at(data, full + 4 * i)) + .collect::<Result<_, _>>()?; + patches.push(ExportPatch { + mrt: mrt as u8, + offset, + code, + }); + } + Ok(StageIo::Ps { + inputs, + input_addr: u32_at(data, PS_INPUT_ADDR)?, + db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?, + patches, + }) +} + +fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> { + let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? + .as_chunks::<5>() + .0 + .iter() + .map(|e| VsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + vgpr: e[3], + }) + .collect(); + let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? + .as_chunks::<6>() + .0 + .iter() + .map(|e| VsOutput { + usage: Usage::from_raw(e[0]), + row: e[1], + param: e[2], + fp16: e[5] & 1 != 0, + pack2: e[5] & 2 != 0, + }) + .collect(); + Ok(StageIo::Vs { inputs, outputs }) +} + +fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> { + let StageIo::Vs { outputs, .. } = vs_io(data)? else { + unreachable!() + }; + let info = data + .get(MS_INFO..MS_INFO + 8) + .ok_or(Malformed("stage data out of bounds"))?; + let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]])); + Ok(StageIo::Ms(MeshIo { + outputs, + clip_cntl: u32_at(data, MS_CLIP_CNTL)?, + threads: half(0), + max_vertices: half(2), + max_primitives: half(4), + topology: info[7], + lds_bytes, + })) +} + +/// For entries already sized by `as_chunks`. +fn le32(entry: &[u8], at: usize) -> u32 { + u32::from_le_bytes(entry[at..at + 4].try_into().unwrap()) +} + /// `data[offset..offset + len]` with untrusted 64-bit bounds. fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> { let start = usize::try_from(offset).ok()?; @@ -181,6 +671,25 @@ mod tests { SLOTS.iter().find(|s| s.0 == stage).unwrap().1 } + /// Stage data: no semantics, and every export patch absent. + const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES; + + fn empty_stage_data() -> Vec<u8> { + let mut data = vec![0; STAGE_DATA]; + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + data + } + + /// Where a one-program blob's stage data starts. + fn stage_data_at(blob: &[u8], stage: HwStage) -> usize { + FSSM_HEADER + + u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize + + RECORD_SIZE as usize + } + /// FSSM blob with `programs` as (stage, code) pairs. fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> { let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec(); @@ -192,13 +701,15 @@ mod tests { let slot = slot(stage); let record = payload.len() as u64; payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes()); - payload.extend_from_slice(&(record + RECORD_SIZE).to_le_bytes()); + let code_at = record + RECORD_SIZE + STAGE_DATA as u64; + payload.extend_from_slice(&code_at.to_le_bytes()); payload.extend_from_slice(&(code.len() as u64).to_le_bytes()); let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 }; payload.extend_from_slice(&[0; 4]); payload.extend_from_slice(&flags.to_le_bytes()); payload.resize(record as usize + RECORD_REGS, 0); payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes()); + payload.extend_from_slice(&empty_stage_data()); payload.extend_from_slice(code); } let mut out = b"FSSM".to_vec(); @@ -249,18 +760,131 @@ mod tests { stage: HwStage::Vs, wave64: true, vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Vs { + inputs: vec![], + outputs: vec![], + }, code: VS_CODE.to_vec() }, NativeProgram { stage: HwStage::Ps, wave64: false, vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, code: PS_CODE.to_vec() }, ] ); } + #[test] + fn reads_root_tables() { + let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); + let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize; + let tables = (blob.len() - FSSM_HEADER) as u64; + // A table range in s9 (root slot 1), and an SRV read from it. + for v in [3u32, 2, 1, 5] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]); + for v in [2u32, 5, 4] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[8, 9, 1, 0]); + let payload = (blob.len() - FSSM_HEADER) as u64; + blob[8..16].copy_from_slice(&payload.to_le_bytes()); + blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes()); + blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes()); + blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + assert_eq!( + p.layout, + [RootParam { + root: RootType::Table, + table_offset_dwords: 2, + sgprs: 1, + base_register: 5, + user_data: 9, + slot: 1 + }] + ); + assert_eq!( + p.used, + [UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 2, + lower_bound: 5, + stride: 4, + dwords: 8, + user_data: 9, + slot: 1 + }] + ); + + blob[record + RECORD_COUNTS] = 9; + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + + #[test] + fn reads_pixel_io_and_applies_the_full_export_patch() { + let code = [0xBF80_0000u32; 4]; // s_nop + let bytes: Vec<u8> = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let mut blob = fssm(&[(HwStage::Ps, &bytes)]); + let e = stage_data_at(&blob, HwStage::Ps); + // TEXCOORD in row 1 (xy), read as attr0, flat. + blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]); + blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes()); + blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes()); + blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes()); + // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`. + let patch = e + PS_PATCHES + PATCH_BYTES; + blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes()); + let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let StageIo::Ps { + inputs, + input_addr, + patches, + .. + } = &p.io + else { + panic!("{:?}", p.io) + }; + let input = PsInput { + usage: Usage::Generic, + row: 1, + mask: 3, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }; + assert_eq!((&inputs[..], *input_addr), (&[input][..], 2)); + assert_eq!(patches.len(), 1); + assert_eq!((patches[0].mrt, patches[0].offset), (1, 1)); + let patched = p.patched_code(); + assert_eq!(patched[..4], p.code[..4]); + assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + assert_eq!(patched[12..], p.code[12..]); + + blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + #[test] fn finds_mesh_and_compute_programs() { for stage in [HwStage::Ms, HwStage::Cs] { @@ -271,6 +895,59 @@ mod tests { } } + #[test] + fn reads_mesh_outputs_and_limits() { + let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Ms); + // param0 is row 1 per vertex, param2 row 0 of the primitive signature. + blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]); + blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); + blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes()); + // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles. + blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]); + let record = e - RECORD_SIZE as usize; + blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes()); + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let out = |row, param| VsOutput { + usage: Usage::Generic, + row, + param, + fp16: false, + pack2: false, + }; + assert_eq!( + p.io, + StageIo::Ms(MeshIo { + outputs: vec![out(1, 0), out(0, 0x82)], + clip_cntl: 0x0040_000F, + threads: 128, + max_vertices: 128, + max_primitives: 64, + topology: 2, + lds_bytes: 16, + }) + ); + } + + #[test] + fn compute_dispatch_settings() { + // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.user_sgprs(), 5); + assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024)); + // 6 user SGPRs, all three group ids, v0-v2, no LDS. + let cs = ComputeIo { + rsrc2: 0x138C, + threads: [8, 8, 1], + }; + assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); + } + #[test] fn reads_every_native_blob() { let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs new file mode 100644 index 0000000..46cf891 --- /dev/null +++ b/crates/victory-shader/src/resource.rs @@ -0,0 +1,1116 @@ +//! Resource tracking (decision 0003): where each descriptor a program uses +//! comes from, in terms of the root signature. +//! +//! Root parameters arrive in user SGPRs ([`RootParam`]): a descriptor table +//! as the 32-bit heap address of its range (the code sets the high half to +//! 0), a root descriptor as a 64-bit buffer address, root constants as +//! themselves. A root signature with dynamic resources (SM 6.6) adds the +//! 32-bit base addresses of both heaps; a descriptor is then loaded from +//! one of them at an index the code computes (from a root constant, say). The code loads table descriptors from heap memory with +//! `s_load_dword*`, and builds a buffer descriptor around a root +//! descriptor's address itself. Each descriptor operand and each scalar +//! memory address is traced through the SSA values back to those +//! parameters, by data flow: copies, phis that agree, and additions. + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{Inst, Program, Reg, Value}; +use crate::native::{HwStage, RootParam, RootType}; + +/// An instruction: block and index in [`crate::ir::Block::insts`]. +pub type Site = (usize, usize); + +/// A byte address: a root parameter's, plus a constant and at most one +/// value the program computes (an index times a stride, say). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Address { + /// Index into the layout, or [`CODE`]. + pub param: usize, + /// Added modulo 2^32 (with carry into the high half of a root + /// descriptor's address). + pub offset: u32, + pub dynamic: Option<Value>, +} + +/// [`Address::param`] of the program's own code: a constant table the +/// compiler appends after the code and reads through `s_getpc_b64`; the +/// offset is then the byte offset in the code. +pub const CODE: usize = usize::MAX; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + /// Dwords `first..` of what the scalar load at `load` reads (see + /// [`Resources::scalar`] for its address). + Loaded { load: Site, first: u8 }, + /// A buffer descriptor built around an address: `bits` OR-ed into + /// dword 1 (stride, swizzle), dwords 2 and 3 as given. + Built { + address: Address, + bits: u32, + words: [u32; 2], + }, + /// Fixed in the code (an immediate sampler, say). + Constant(Vec<u32>), + /// Chosen by control flow: one source per predecessor of `block`, in + /// [`crate::ir::Block::preds`] order. + Phi { block: usize, args: Vec<Source> }, +} + +impl Source { + /// The sources this one picks from (itself unless a phi). + pub fn leaves(&self) -> Vec<&Source> { + match self { + Source::Phi { args, .. } => args.iter().flat_map(Source::leaves).collect(), + s => vec![s], + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Image, buffer or `s_buffer_load` resource. + Resource, + Sampler, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Descriptor { + pub site: Site, + pub role: Role, + pub source: Source, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Resources { + /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and + /// every global memory access (`global_*`, the dynamic term per lane). + pub scalar: Vec<(Site, Address)>, + pub descriptors: Vec<Descriptor>, + /// User SGPRs holding root parameters: value on entry, layout index, + /// dword within the parameter. + pub params: Vec<(Value, usize, u32)>, +} + +/// Traces every descriptor and scalar address of `p`, which runs as +/// `stage`, to the root parameters in `layout`. Fails on the first one it +/// cannot trace. +pub fn track(p: &Program, layout: &[RootParam], stage: HwStage) -> Result<Resources, ShaderError> { + let t = Tracer::new(p, layout, stage)?; + let mut out = Resources { + params: p + .inputs + .iter() + .filter_map(|&(reg, v)| { + let (param, dword) = t.param_of(reg)?; + Some((v, param, dword)) + }) + .collect(), + ..Resources::default() + }; + for (b, block) in p.blocks.iter().enumerate() { + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let fail = |what| ShaderError::Unsupported { + offset: inst.machine.offset, + what, + }; + let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { + let source = t.descriptor(inst, op).map_err(fail)?; + out.descriptors.push(Descriptor { site, role, source }); + Ok(()) + }; + match &inst.fields { + Fields::Image { rsrc, sampler, .. } => { + descriptor(rsrc, Role::Resource)?; + if let Some(s) = sampler { + descriptor(s, Role::Sampler)?; + } + } + Fields::Buffer { rsrc, .. } => descriptor(rsrc, Role::Resource)?, + Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => { + descriptor(base, Role::Resource)?; + } + Fields::Smem { + base, + offset, + soffset, + .. + } if inst.name().contains("_load_") || inst.name().contains("_store_") => { + let address = t.smem_address(inst, base, *offset, soffset).map_err(fail)?; + out.scalar.push((site, address)); + } + Fields::Flat { + addr, + saddr, + offset, + .. + } if inst.name().starts_with("global_") => { + let address = t + .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + .map_err(fail)?; + out.scalar.push((site, address)); + } + _ => {} + } + } + } + Ok(out) +} + +/// A dword after copy propagation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Term { + Const(u32), + Value(Value), +} + +/// A 32-bit sum: optional root parameter (as its first dword), constant, +/// optional computed term. +struct Sum { + base: Option<Value>, + offset: u32, + dynamic: Option<Value>, +} + +struct Tracer<'a> { + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + /// Defining instruction per value (phis and inputs have none). + defs: Vec<Option<Site>>, + /// Block and index of each phi value. + phis: Vec<Option<(usize, usize)>>, + /// Register per input value. + inputs: Vec<Option<Reg>>, + origin: Vec<Term>, +} + +const MAX_ROUNDS: usize = 64; +const MAX_JOINS: usize = 8; + +impl<'a> Tracer<'a> { + fn new(p: &'a Program, layout: &'a [RootParam], stage: HwStage) -> Result<Self, ShaderError> { + let all = || { + p.inputs + .iter() + .map(|i| i.1) + .chain(p.blocks.iter().flat_map(|b| { + b.phis + .iter() + .map(|phi| phi.value) + .chain(b.insts.iter().flat_map(|i| i.writes.iter().map(|w| w.1))) + })) + }; + let n = all().map(|v| v.0 as usize + 1).max().unwrap_or(0); + let mut defs = vec![None; n]; + let mut phis = vec![None; n]; + let mut inputs = vec![None; n]; + for &(reg, v) in &p.inputs { + inputs[v.0 as usize] = Some(reg); + } + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phis[phi.value.0 as usize] = Some((b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs[v.0 as usize] = Some((b, i)); + } + } + } + let mut t = Tracer { + p, + layout, + stage, + defs, + phis, + inputs, + origin: Vec::new(), + }; + t.origin = t.propagate_copies(n)?; + Ok(t) + } + + /// Optimistic copy propagation: a move's result is its source's + /// origin, a phi's the one origin its arguments agree on. + fn propagate_copies(&self, n: usize) -> Result<Vec<Term>, ShaderError> { + let mut o: Vec<Option<Term>> = vec![None; n]; + for &(_, v) in &self.p.inputs { + o[v.0 as usize] = Some(Term::Value(v)); + } + let order = crate::ir::reverse_postorder(&self.p.blocks); + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for &b in &order { + let block = &self.p.blocks[b]; + for phi in &block.phis { + let own = Term::Value(phi.value); + let mut args = phi + .args + .iter() + .filter_map(|a| o[a.0 as usize]) + .filter(|&t| t != own); + let new = args + .next() + .map(|first| if args.all(|t| t == first) { first } else { own }); + if new.is_some() && new != o[phi.value.0 as usize] { + o[phi.value.0 as usize] = new; + changed = true; + } + } + for inst in &block.insts { + for (k, &(_, v)) in inst.writes.iter().enumerate() { + let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + Some(Moved::Const(c)) => Some(Term::Const(c)), + Some(Moved::Value(s)) => o[s.0 as usize], + None => Some(Term::Value(v)), + }; + if new.is_some() && new != o[v.0 as usize] { + o[v.0 as usize] = new; + changed = true; + } + } + } + } + if !changed { + return Ok(o + .into_iter() + .enumerate() + .map(|(v, t)| t.unwrap_or(Term::Value(Value(v as u32)))) + .collect()); + } + } + Err(ShaderError::Unsupported { + offset: 0, + what: "copies that do not settle", + }) + } + + fn inst(&self, (b, i): Site) -> &'a Inst { + &self.p.blocks[b].insts[i] + } + + fn def(&self, v: Value) -> Option<&'a Inst> { + self.defs[v.0 as usize].map(|s| self.inst(s)) + } + + fn origin(&self, v: Value) -> Term { + self.origin[v.0 as usize] + } + + /// The origin of a one-dword operand as `inst` reads it. + fn term(&self, inst: &Inst, op: &Operand) -> Option<Term> { + match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code))?)), + Operand::Const(c) => inline(c).map(Term::Const), + Operand::Literal(x) => Some(Term::Const(x)), + _ => None, + } + } + + /// Layout index and dword of the root parameter `reg` holds on entry. + fn param_of(&self, reg: Reg) -> Option<(usize, u32)> { + let Reg::S(code) = reg else { return None }; + self.layout.iter().enumerate().find_map(|(i, p)| { + let first = self.stage.user_sgpr(p.user_data); + let dword = u32::from(code).checked_sub(first.into())?; + (dword < p.sgprs).then_some((i, dword)) + }) + } + + /// The SOP2 operands of `v` if an `s_add` with one of `names` wrote it. + fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { + let inst = self.def(v)?; + if !names.contains(&inst.name()) || inst.writes.first()?.1 != v { + return None; + } + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + Some(( + inst, + [ + self.term(inst, src.first()?)?, + self.term(inst, src.get(1)?)?, + ], + )) + } + + fn sum(&self, t: Term) -> Sum { + let v = match t { + Term::Const(c) => { + return Sum { + base: None, + offset: c, + dynamic: None, + }; + } + Term::Value(v) => v, + }; + let dynamic = Sum { + base: None, + offset: 0, + dynamic: Some(v), + }; + if let Some(reg) = self.inputs[v.0 as usize] { + return match self.param_of(reg) { + Some((_, 0)) => Sum { + base: Some(v), + offset: 0, + dynamic: None, + }, + _ => dynamic, + }; + } + if self.getpc(v).is_some() { + return Sum { + base: Some(v), + offset: 0, + dynamic: None, + }; + } + let Some([a, b]) = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v)) + else { + return dynamic; + }; + let (x, y) = (self.sum(a), self.sum(b)); + if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { + return dynamic; + } + Sum { + base: x.base.or(y.base), + offset: x.offset.wrapping_add(y.offset), + dynamic: x.dynamic.or(y.dynamic), + } + } + + /// The `s_getpc_b64` writing `lo` as its low dword. + fn getpc(&self, lo: Value) -> Option<&'a Inst> { + let inst = self.def(lo)?; + (inst.name() == "s_getpc_b64" && inst.writes.first().is_some_and(|w| w.1 == lo)) + .then_some(inst) + } + + /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`) + /// writing `v`, through VGPR copies of scalars. + fn vadd(&self, v: Value) -> Option<[Term; 2]> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32") + || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. })) + || inst.write(Reg::V(match f.dst? { + Operand::Vector { reg, .. } => reg, + _ => return None, + })) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + Some([ + self.vterm(inst, f.src.first()?)?, + self.vterm(inst, f.src.get(1)?)?, + ]) + } + + /// The origin of a VALU operand. + fn vterm(&self, inst: &Inst, op: &Operand) -> Option<Term> { + match *op { + Operand::Vector { reg, .. } => Some(self.vorigin(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// A VGPR value's origin through `v_mov_b32` copies. + fn vorigin(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s)) + { + return t; + } + self.origin(v) + } + + /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR + /// pair. + fn flat_address( + &self, + inst: &Inst, + addr: Option<&Operand>, + saddr: Option<&Operand>, + offset: i16, + ) -> Result<Address, &'static str> { + let Some(&Operand::Vector { reg, .. }) = addr else { + return Err("a global address not in VGPRs"); + }; + let off = offset as i32 as u32; + match saddr { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let v = inst.read(Reg::V(reg)).ok_or("a global address")?; + let mut extra = self.sum(self.vorigin(v)); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(off); + self.address(lo, hi, extra) + } + _ => { + let word = |k| inst.read(Reg::V(reg + k)).map(|v| self.vorigin(v)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("a global address"); + }; + self.address( + lo, + hi, + Sum { + base: None, + offset: off, + dynamic: None, + }, + ) + } + } + } + + /// The address `lo` and `hi` hold, plus `extra` (an instruction's + /// immediate and offset register). + fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result<Address, &'static str> { + let s = self.sum(lo); + if s.dynamic.is_some() && extra.dynamic.is_some() { + return Err("an address with two computed terms"); + } + let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?; + if let Some(pc) = self.getpc(base) { + // A table in the code: the base is the next instruction's offset. + let high = pc.writes.get(1).map(|w| w.1); + if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { + return Err("an address with an untracked high half"); + } + return Ok(Address { + param: CODE, + offset: (pc.machine.offset as u32 + 4) + .wrapping_add(s.offset) + .wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }); + } + let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?; + let (param, _) = self + .param_of(reg) + .ok_or("an address not from a root parameter")?; + let high = match self.layout[param].root { + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None, + RootType::Descriptor => { + let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1); + let input = self.p.inputs.iter().find(|i| i.0 == high); + Some(input.ok_or("a root descriptor without its high half")?.1) + } + _ => return Err("an address from a root parameter that is no address"), + }; + // shortcut: with a computed term, a high half that adds anything to the + // base's is taken as the carry of that term (offsets below 4 GB). + let dynamic = s.dynamic.or(extra.dynamic); + if !self.high_half(hi, high) + && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h))) + { + return Err("an address with an untracked high half"); + } + Ok(Address { + param, + offset: s.offset.wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }) + } + + /// `hi` is `high` (0 for a table), possibly plus a carry. + fn high_half(&self, hi: Term, high: Option<Value>) -> bool { + let want = high.map_or(Term::Const(0), Term::Value); + hi == want + || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( + |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) + )) + } + + /// `hi` adds something (with carry) to `high`: `s_addc_u32` or + /// `v_add_co_ci_u32` with `high` as an operand. + fn carried(&self, hi: Term, high: Value) -> bool { + let Term::Value(v) = hi else { return false }; + if v == high { + return true; + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return self.carried(a, high) || self.carried(b, high); + } + let Some(inst) = self.def(v) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high))) + } + + fn why_no_base(&self, dynamic: Option<Value>) -> &'static str { + let Some(v) = dynamic else { + return "a constant address"; + }; + if self.inputs[v.0 as usize].is_some() { + return "an address in an SGPR that is no root parameter"; + } + if self + .leaves(v) + .any(|l| self.def(l).is_some_and(|i| i.name() == "s_getpc_b64")) + { + return "an address relative to the program counter"; + } + match self.def(v).map(|i| i.name()) { + Some(n) if n.starts_with("s_load_") => "an address loaded from memory", + None => "an address from a phi", + _ => "an address not from a root parameter", + } + } + + /// The terms of the additions that compute `v`. + fn leaves(&self, v: Value) -> Box<dyn Iterator<Item = Value> + '_> { + match self.sop2(v, &["s_add_u32", "s_add_i32"]) { + Some((_, terms)) => Box::new(terms.into_iter().flat_map(move |t| match t { + Term::Value(x) => self.leaves(x), + Term::Const(_) => Box::new(std::iter::empty()), + })), + None => Box::new(std::iter::once(v)), + } + } + + fn smem_address( + &self, + inst: &Inst, + base: &Operand, + offset: i32, + soffset: &Operand, + ) -> Result<Address, &'static str> { + let Operand::Scalar { code, .. } = *base else { + return Err("an address not in SGPRs"); + }; + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let mut extra = self.sum( + self.term(inst, soffset) + .ok_or("an unknown offset operand")?, + ); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(offset as u32); + self.address(lo, hi, extra) + } + + fn descriptor(&self, inst: &Inst, op: &Operand) -> Result<Source, &'static str> { + let Operand::Scalar { code, dwords } = *op else { + return Err("a descriptor not in SGPRs"); + }; + let words = (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::<Option<Vec<_>>>() + .ok_or("a descriptor not in SGPRs")?; + self.classify(&words, &mut Vec::new()) + } + + /// The source of a descriptor's words; `joins` are the phi blocks + /// being resolved. + fn classify(&self, words: &[Term], joins: &mut Vec<usize>) -> Result<Source, &'static str> { + if let Some(source) = self.phi(words, joins)? { + return Ok(source); + } + if let Some(consts) = words + .iter() + .map(|w| match *w { + Term::Const(c) => Some(c), + Term::Value(_) => None, + }) + .collect::<Option<Vec<_>>>() + { + return Ok(Source::Constant(consts)); + } + if let Some(source) = self.loaded(words) { + return Ok(source); + } + if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words { + let (mut hi, mut bits) = (hi, 0); + while let Term::Value(v) = hi + && let Some((x, more)) = self.set_bits(v) + { + (hi, bits) = (x, bits | more); + } + let address = self.address( + lo, + hi, + Sum { + base: None, + offset: 0, + dynamic: None, + }, + )?; + return Ok(Source::Built { + address, + bits, + words: [w2, w3], + }); + } + let loaded = |w: &Term| { + matches!(*w, Term::Value(v) + if self.def(v).is_some_and(|i| i.name().starts_with("s_load_"))) + }; + Err(if words.iter().any(loaded) { + "a descriptor changed after loading" + } else { + "a descriptor neither loaded nor built" + }) + } + + /// Words that phis of one block join, traced per predecessor (words + /// defined before the join hold on every edge). + fn phi(&self, words: &[Term], joins: &mut Vec<usize>) -> Result<Option<Source>, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + // Each level multiplies the sources by the predecessor count. + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let args = (0..self.p.blocks[block].preds.len()) + .map(|j| { + let edge: Vec<Term> = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect(); + self.classify(&edge, joins) + }) + .collect::<Result<_, _>>(); + joins.pop(); + Ok(Some(Source::Phi { block, args: args? })) + } + + /// `v` as some other dword with constant bits set. + fn set_bits(&self, v: Value) -> Option<(Term, u32)> { + if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) = + self.sop2(v, &["s_or_b32"]) + { + return Some((x, bits)); + } + let inst = self.def(v)?; + let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + src, + .. + } = &inst.fields + else { + return None; + }; + match (inst.name(), self.term(inst, src.first()?)?) { + ("s_bitset1_b32", Term::Const(bit)) => { + Some((self.origin(inst.read(Reg::S(*code))?), 1 << (bit & 31))) + } + _ => None, + } + } + + /// Consecutive dwords of one scalar load. + fn loaded(&self, words: &[Term]) -> Option<Source> { + let Term::Value(v0) = words[0] else { + return None; + }; + let load = self.defs[v0.0 as usize]?; + let inst = self.inst(load); + if !inst.name().starts_with("s_load_") { + return None; + } + let first = inst.writes.iter().position(|w| w.1 == v0)?; + let same = words.iter().enumerate().all(|(k, w)| { + inst.writes + .get(first + k) + .is_some_and(|x| *w == Term::Value(x.1)) + }); + same.then_some(Source::Loaded { + load, + first: first as u8, + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Moved { + Const(u32), + Value(Value), +} + +impl Tracer<'_> { + /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that + /// lane, found by following the VGPR's `v_writelane_b32` writes. + fn restored(&self, inst: &Inst) -> Option<Moved> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + if inst.name() != "v_readlane_b32" { + return None; + } + let [Operand::Vector { reg, .. }, lane] = v.src[..] else { + return None; + }; + self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + .ok() + .flatten() + } + + /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in + /// `seen` (already being resolved), `Err` if not a spilled SGPR. + fn spilled(&self, v: Value, lane: u32, seen: &mut Vec<Value>) -> Result<Option<Moved>, ()> { + if let Some((b, i)) = self.phis[v.0 as usize] { + if seen.contains(&v) { + return Ok(None); + } + seen.push(v); + let mut found = None; + for &a in &self.p.blocks[b].phis[i].args { + if let Some(m) = self.spilled(a, lane, seen)? { + if found.is_some_and(|f| f != m) { + return Err(()); + } + found = Some(m); + } + } + return Ok(found); + } + let inst = self.def(v).ok_or(())?; + let Fields::Valu(w) = &inst.fields else { + return Err(()); + }; + let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { + return Err(()); + }; + if inst.name() != "v_writelane_b32" { + return Err(()); + } + if lane_of(*at).ok_or(())? != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + } + match *value { + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).map(Moved::Value) + } + Operand::Literal(x) => Some(Moved::Const(x)), + Operand::Const(c) => inline(c).map(Moved::Const), + _ => None, + } + .map(Some) + .ok_or(()) + } +} + +/// A lane select given as a constant. +fn lane_of(op: Operand) -> Option<u32> { + match op { + Operand::Const(c) => inline(c), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +/// What dword `k` of a move's result copies. +fn copy_source(inst: &Inst, k: usize) -> Option<Moved> { + let Fields::Sop { src, imm, .. } = &inst.fields else { + return None; + }; + if inst.name() == "s_movk_i32" { + return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); + } + let src = src.first()?; + match (inst.name(), *src) { + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { + inst.read(Reg::S(code + k as u8)).map(Moved::Value) + } + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)), + ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)), + ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const), + // shortcut: only the one-operand ways the compiler makes a constant + // that has no inline form; fold more if descriptors need it. + ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), + ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), + // 64-bit inline integers are sign-extended. + ("s_mov_b64", Operand::Const(c @ 128..=208)) => { + let low = inline(c)?; + Some(Moved::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + _ => None, + } +} + +/// The 32-bit value of an inline constant operand. +pub(crate) fn inline(code: u8) -> Option<u32> { + let float = |f: f32| Some(f.to_bits()); + match code { + 128..=192 => Some(u32::from(code) - 128), + 193..=208 => Some((192 - i32::from(code)) as u32), + 240 => float(0.5), + 241 => float(-0.5), + 242 => float(1.0), + 243 => float(-1.0), + 244 => float(2.0), + 245 => float(-2.0), + 246 => float(4.0), + 247 => float(-4.0), + 248 => Some(0x3E22_F983), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::RootType::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources { + let code: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + track(&crate::ir::build(&code, false, 256).unwrap(), layout, stage).unwrap() + } + + fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot: 0, + } + } + + fn at(param: usize, offset: u32) -> Address { + Address { + param, + offset, + dynamic: None, + } + } + + #[test] + fn table_descriptors_are_loaded_from_their_range() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0204, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF080_0F08, + 0x0040_0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11] + S_ENDPGM, + ], + &[param(Table, 8, 1), param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0)), ((0, 4), at(1, 0))]); + let roles: Vec<_> = r.descriptors.iter().map(|d| (d.role, &d.source)).collect(); + assert_eq!( + roles, + [ + ( + Role::Resource, + &Source::Loaded { + load: (0, 4), + first: 0 + } + ), + ( + Role::Sampler, + &Source::Loaded { + load: (0, 3), + first: 0 + } + ), + ] + ); + } + + #[test] + fn root_descriptors_are_built_in_code() { + let r = track_words( + &[ + 0x8801_FF0B, + 0x0010_0000, // s_or_b32 s1, s11, 0x100000 + 0xBE80_030A, // s_mov_b32 s0, s10 + 0xBE82_03C1, // s_mov_b32 s2, -1 + 0xBE83_03FF, + 0x1101_4FAC, // s_mov_b32 s3, 0x11014fac + 0xF430_0000, + 0xFA00_0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null + S_ENDPGM, + ], + &[param(Descriptor, 10, 2)], + HwStage::Vs, + ); + assert_eq!( + r.descriptors[0].source, + Source::Built { + address: at(0, 0), + bits: 0x10_0000, + words: [u32::MAX, 0x1101_4FAC] + } + ); + assert_eq!( + r.params.iter().map(|p| (p.1, p.2)).collect::<Vec<_>>(), + [(0, 0), (0, 1)] + ); + } + + #[test] + fn heap_indices_from_root_constants_in_a_merged_stage() { + // User data starts at s8: the constant (index 6) is s14, the heap + // (index 10) s18. + let r = track_words( + &[ + 0x8F08_850E, // s_lshl_b32 s8, s14, 5 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0xF408_0209, + 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000_2000, + 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + ], + &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)], + HwStage::Ms, + ); + let index = r.params.iter().find(|p| p.1 == 0).unwrap().0; + let shift = r.scalar[0].1.dynamic.unwrap(); + assert_eq!(r.scalar[0].1.param, 1); + // The computed term is the shifted constant, not the constant itself. + assert_ne!(shift, index); + assert_eq!( + r.descriptors[0].source, + Source::Loaded { + load: (0, 2), + first: 0 + } + ); + } + + #[test] + fn spilled_sgprs_are_followed_through_vgpr_lanes() { + let r = track_words( + &[ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); + } + + #[test] + fn descriptors_joined_by_control_flow_are_traced_per_edge() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0003, // s_cbranch_scc1 -> 0x1c + 0xF408_0001, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null + 0xBF82_0002, // s_branch -> 0x24 + 0xF408_0001, + 0xFA00_0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10 + 0xF420_0100, + 0xFA00_0000, // 0x24: s_buffer_load_dword s4, s[0:3], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Phi { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + let offsets: Vec<_> = args + .iter() + .map(|a| match a { + Source::Loaded { load, .. } => { + r.scalar.iter().find(|s| s.0 == *load).unwrap().1.offset + } + a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets.len(), 2); + assert!( + offsets.contains(&0) && offsets.contains(&0x10), + "{offsets:?}" + ); + } + + #[test] + fn untraceable_addresses_fail_with_a_reason() { + let code: Vec<u8> = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 0, + what: "an address in an SGPR that is no root parameter" + } + ); + } +} diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index bcabd96..c557a03 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -308,6 +308,12 @@ pub struct Structured { pub guards: Vec<Vec<Option<Bool>>>, /// The lane's bit of each lane-mask value, by its low dword's value. pub masks: HashMap<Value, Bool>, + /// Wave64 masks: low dword's value by the high dword's. + pub highs: HashMap<Value, Value>, + /// Masks (low dwords) set only in lanes whose EXEC bit is set where + /// they are written: every such lane reaches the writing block, so a + /// ballot there gives the mask as data. + pub active: HashSet<Value>, } /// Builds the per-lane form of `program`. @@ -356,6 +362,8 @@ struct Lanes<'a> { first: Vec<Bool>, /// Per block ending in a branch: when a lane takes it. when: Vec<Option<Bool>>, + /// See [`Structured::active`]. + active: HashSet<Value>, } /// A mask join taken as `value` in every lane that reaches `block`: each @@ -418,6 +426,7 @@ impl<'a> Lanes<'a> { joins: Vec::new(), first: vec![Bool::FALSE; blocks.len()], when: vec![None; blocks.len()], + active: HashSet::new(), }) } @@ -429,6 +438,7 @@ impl<'a> Lanes<'a> { self.joins.clear(); self.first.fill(Bool::FALSE); self.when.fill(None); + self.active.clear(); } /// Lane masks, branch conditions and forward-edge knowledge, block by @@ -443,6 +453,7 @@ impl<'a> Lanes<'a> { lo }; self.masks.insert((lo, hi), Bool::TRUE); + self.active.insert(lo); } let mut execs: Vec<Vec<Option<Bool>>> = p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect(); @@ -457,11 +468,24 @@ impl<'a> Lanes<'a> { } } self.first[b] = c; + // EXEC joined at the block's entry holds the lanes that arrive. + for phi in &p.blocks[b].phis { + if phi.reg == Reg::S(EXEC) { + self.active.insert(phi.value); + } + } + // EXEC where known in this block (read or written so far). + let mut now = None; for (i, inst) in p.blocks[b].insts.iter().enumerate() { if inst.read(Reg::S(EXEC)).is_some() { - execs[b][i] = Some(self.exec(inst)); + let e = self.exec(inst); + execs[b][i] = Some(e); + now = Some(e); + } + self.step(inst, now); + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + now = self.masks.get(&k).or(self.other.get(&k)).copied(); } - self.step(inst); } if let Exit::Branch { .. } = p.blocks[b].exit && let Some(last) = p.blocks[b].insts.last() @@ -553,6 +577,13 @@ impl<'a> Lanes<'a> { } Ok(Structured { masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), + highs: self + .masks + .keys() + .filter(|(lo, hi)| lo != hi) + .map(|&(lo, hi)| (hi, lo)) + .collect(), + active: self.active, bools: self.b, exits, guards, @@ -828,8 +859,8 @@ impl<'a> Lanes<'a> { }) } - /// Records the masks `inst` defines. - fn step(&mut self, inst: &Inst) { + /// Records the masks `inst` defines; `exec` is EXEC there, if known. + fn step(&mut self, inst: &Inst, exec: Option<Bool>) { let name = inst.name(); match &inst.fields { Fields::Sop { src, .. } => { @@ -850,6 +881,12 @@ impl<'a> Lanes<'a> { { for (k, m) in r.dst.into_iter().chain(r.exec) { self.masks.insert(k, m); + // EXEC itself holds the lanes that run here. + if r.exec.is_some_and(|e| e.0 == k) + || exec.is_some_and(|e| self.b.implies(m, e)) + { + self.active.insert(k.0); + } } if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) { self.scc_lane.insert(scc, m); @@ -883,7 +920,17 @@ impl<'a> Lanes<'a> { let a = l.b.atom(Atom::Lane(k.0), born); let m = l.b.and(exec, a); l.masks.insert(k, m); + l.active.insert(k.0); }; + // A select reads a mask nothing else may: a join of compare + // results is resolved here, as for EXEC. + if name == "v_cndmask_b32" + && let Some(&Operand::Scalar { code, .. }) = v.src.get(2) + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + self.mask(k); + } if name.starts_with("v_cmpx") { if let Some(k) = self.key(|r| inst.write(r), EXEC) { lane(self, k); diff --git a/docs/architecture.md b/docs/architecture.md index 336721e..a4a95f2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,7 +35,7 @@ Converting them ahead of time from files is only a warm-up. | `victory-hle` | console API implementations, host pass-through policy | | `victory-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | | `victory-shader` | Xbox shader containers → host shaders | -| `victory-formats` | texture layouts, BCPack, audio codecs (skeleton) | +| `victory-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | | `victory-pipeline` | converter trait, content-addressed cache | | `victory-game` | Grand Theft Auto VI-specific formats, build identities, hooks | | `apps/victory` | command-line front end | @@ -59,9 +59,12 @@ For every `dll!function` the title imports, in order: `LoadLibrary*` of a console-only DLL we implement (e.g. `xgameruntime.dll`) returns a pseudo handle; `GetProcAddress` on it finds our functions. `LoadLibrary*` of a title DLL returns its mapped image, mapping it first if -nothing imports it. -`QueryApiImpl` hands out our runtime objects by provider (task queues and -async blocks so far, `victory-hle::modules::xasync`). +nothing imports it. By name, as by import, a title gets only host DLLs +`HostPolicy` passes through, and `GetProcAddress` on one returns our +override where import binding would. +`QueryApiImpl` hands out our runtime objects by provider and interface id +(`victory-hle::modules::xgameruntime` lists the areas); online areas answer +as an offline console. Game saves are files under `VICTORY_DATA_DIR`. Title storage is a drive on the console, and titles build paths on that. `victory-hle::modules::files` binds every path-taking title import @@ -72,7 +75,8 @@ a folder under `VICTORY_DATA_DIR`. Other paths reach the host unchanged. An exe's code reaches its static TLS as slot 0; mapped as a DLL it gets another slot, so the loader redirects those loads (`victory-loader::tls`). `victory run --execute` installs a crash reporter that names faults as -`module+rva` (`victory-loader::crash`). +`module+rva` and unwinds the faulting thread's stack +(`victory-loader::crash`). `victory census` shows this classification without running anything (it does not map title DLLs; `victory run` without `--execute` does). @@ -83,6 +87,8 @@ does not map title DLLs; `victory run` without `--execute` does). instruction per machine instruction. `victory_shader::structure` then removes EXEC: lane masks become per-lane booleans, wave-wide mask tests become per-lane branches, and vector instructions keep a guard only where -a lane can reach them with its EXEC bit clear. `victory translate` runs -every shader it finds (containers, SGD5 files) through both and lists what -they cannot handle yet. +a lane can reach them with its EXEC bit clear. `victory_shader::resource` +traces each descriptor and scalar memory address to the root parameter it +comes from (table, heap, root descriptor or constant). `victory translate` +runs every shader it finds (containers, SGD5 files) through these and +lists what they cannot handle yet. diff --git a/docs/asset-policy.md b/docs/asset-policy.md index b4f9fe0..f87c84f 100644 --- a/docs/asset-policy.md +++ b/docs/asset-policy.md @@ -23,6 +23,17 @@ In any form (files, string literals, fixtures, snapshots, docs): * small interoperability constants (magic numbers, enum values) we write; * synthetic test data generated by our own code. +## The one exception + +`crates/victory-formats/src/bcpack-tables.bin` (about 78 KB): the constant +tables of the BCPack format (entropy models, index rank tables, control +codes, per-format dictionaries). A BCPack stream cannot be decoded without +exactly these tables and they cannot be derived, so they ship with VIctory +by the project owner's decision (2026-11-23), entered as an exception in +`xtask/src/policy.rs`. They are part of the format, not our work, and the +repository's licence does not cover them. Nothing else of this kind is +accepted. + ## Where data lives Outside the repository, configured in `victory.toml`: `game_dir` (the diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs index ec9d791..1eca794 100644 --- a/tests/fixtures/hle-probe/src/lib.rs +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -90,15 +90,29 @@ unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) #[unsafe(link_section = ".CRT$XLB")] static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; -/// Called by the CRT's DLL entry point: counts thread starts too. +/// Called by the CRT's DLL entry point: counts thread starts too, and calls +/// an import the resolver overrides, as title code calls our runtime. #[unsafe(no_mangle)] pub extern "system" fn DllMain(_: *mut c_void, reason: u32, _: *mut c_void) -> i32 { if reason == DLL_THREAD_ATTACH { MAIN_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); + unsafe { GetTickCount() }; + } + if reason == DLL_PROCESS_DETACH { + DETACHES.fetch_add(1, Ordering::Relaxed); } 1 } +const DLL_PROCESS_DETACH: u32 = 0; +static DETACHES: AtomicU32 = AtomicU32::new(0); + +/// `DLL_PROCESS_DETACH` notices seen by `DllMain`. +#[unsafe(no_mangle)] +pub extern "system" fn probe_detaches() -> u32 { + DETACHES.load(Ordering::Relaxed) +} + /// Thread starts seen by the TLS callback (high half) and `DllMain` (low). #[unsafe(no_mangle)] pub extern "system" fn probe_thread_starts() -> u64 { diff --git a/xtask/src/policy.rs b/xtask/src/policy.rs index e0960dc..9bcf24c 100644 --- a/xtask/src/policy.rs +++ b/xtask/src/policy.rs @@ -28,7 +28,10 @@ const ALLOWED_NAMES: &[&str] = &[ ]; /// Paths explicitly exempted, with a reason. Keep this empty if at all possible. -const EXCEPTIONS: &[(&str, &str)] = &[]; +const EXCEPTIONS: &[(&str, &str)] = &[( + "crates/victory-formats/src/bcpack-tables.bin", + "the BCPack format's constant tables: nothing decodes without them and they cannot be derived (owner's decision, 2026-11-23; docs/asset-policy.md)", +)]; /// Signatures of formats that must never be committed. const FORBIDDEN_MAGIC: &[(&[u8], &str)] = &[