From c72978834b49393c7c49d42fe048a6d30ae6fa5b Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:55:09 -0500 Subject: [PATCH 01/11] Tests: a conformance title checks the runtime against the public reference docs/acceptance.md plans an acceptance and benchmark layer that needs no title, no game data and no SDK: a stand-in title written from Microsoft's public GDK reference, run through VIctory's own loader and runtime, that calls each platform area as a title does and checks what the reference says the call does. The Microsoft GDK is not used: its license limits it to Windows titles for Windows and forbids reverse engineering it. tests/fixtures/conformance is that title (a cdylib outside the workspace, like hle-probe). crates/victory-hle/tests/conformance.rs builds it, binds it with HleResolver and runs its 82 checks (TAP): - runtime initialisation, and QueryApiImpl found as a title's stub finds it; - task queues and async calls: dispatch modes and ports, delayed submits, termination, XAsyncRun, provider operation order, cancellation; - system information: analytics family, console id and its errors; - physical pages mapped at two addresses stay coherent and unmap; - DirectStorage from memory: raw and zlib, completion order, a failed read not blocking later notifications, request reuse, automatic submission; - game saves: container names, updates, the 16 MB update limit and all-or-nothing updates. 80 pass. Two answers differ from the reference and are listed in the test with why, reported rather than failed (one passing fails the test, so the list stays true): a retail console id is documented as 00000000.00000000.00000000.00000000.00 (VIctory: 38 digits ending in 1), and a DirectStorage queue submits itself once an Enqueue fills more than half its capacity (VIctory: at half). An ignored test runs the streaming workload and prints its throughput. --- crates/victory-hle/tests/conformance.rs | 150 +++++ docs/acceptance.md | 146 +++++ tests/fixtures/conformance/Cargo.lock | 25 + tests/fixtures/conformance/Cargo.toml | 22 + tests/fixtures/conformance/src/dstorage.rs | 409 +++++++++++++ tests/fixtures/conformance/src/lib.rs | 57 ++ tests/fixtures/conformance/src/rt.rs | 96 +++ tests/fixtures/conformance/src/tap.rs | 45 ++ tests/fixtures/conformance/src/xasync.rs | 624 ++++++++++++++++++++ tests/fixtures/conformance/src/xgamesave.rs | 276 +++++++++ tests/fixtures/conformance/src/xmem.rs | 132 +++++ tests/fixtures/conformance/src/xsystem.rs | 126 ++++ 12 files changed, 2108 insertions(+) create mode 100644 crates/victory-hle/tests/conformance.rs create mode 100644 docs/acceptance.md create mode 100644 tests/fixtures/conformance/Cargo.lock create mode 100644 tests/fixtures/conformance/Cargo.toml create mode 100644 tests/fixtures/conformance/src/dstorage.rs create mode 100644 tests/fixtures/conformance/src/lib.rs create mode 100644 tests/fixtures/conformance/src/rt.rs create mode 100644 tests/fixtures/conformance/src/tap.rs create mode 100644 tests/fixtures/conformance/src/xasync.rs create mode 100644 tests/fixtures/conformance/src/xgamesave.rs create mode 100644 tests/fixtures/conformance/src/xmem.rs create mode 100644 tests/fixtures/conformance/src/xsystem.rs diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs new file mode 100644 index 0000000000..10191cb304 --- /dev/null +++ b/crates/victory-hle/tests/conformance.rs @@ -0,0 +1,150 @@ +//! The conformance title (tests/fixtures/conformance, docs/acceptance.md) +//! run through VIctory's loader and runtime, as `victory run` runs a title: +//! its checks are what Microsoft's public GDK reference says each call does. +//! No game data and no SDK. +#![cfg(windows)] + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use victory_hle::{HleResolver, HostPolicy}; +use victory_loader::{UnimplementedPolicy, prepare}; + +/// Checks VIctory is known to answer differently from the public reference, +/// each with why: reported, not failed. A check here that passes fails the +/// test, so the list stays true. +const KNOWN: &[(&str, &str)] = &[ + ( + "xsystem: a retail console id is the documented zero id", + "VIctory returns 38 digits ending in 1; the reference gives \ + 00000000.00000000.00000000.00000000.00 for retail and PC", + ), + ( + "dstorage: a queue filled to half its capacity is not submitted on its own", + "VIctory submits once half the capacity is enqueued; the overview \ + says an Enqueue that fills more than half submits", + ), +]; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +/// Builds the fixture into its own target dir (the outer cargo holds the +/// lock on the main one while tests run). +fn build_fixture() -> PathBuf { + let manifest = workspace_root().join("tests/fixtures/conformance/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("conformance"); + let status = Command::new(env!("CARGO")) + .args(["build", "--quiet", "--manifest-path"]) + .arg(&manifest) + .arg("--target-dir") + .arg(&target) + .status() + .expect("running cargo"); + assert!(status.success(), "building the conformance title failed"); + target.join("debug").join("conformance.dll") +} + +/// The title loaded and bound once per test process (the runtime's state +/// is global: one title at a time); `call(name)` runs one of its report +/// exports. +fn call(name: &str) -> String { + static EXPORTS: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new(); + static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let &(run, bench) = EXPORTS.get_or_init(|| { + let dll = build_fixture(); + let original = std::fs::read(&dll).unwrap(); + let prepared = prepare(&original).unwrap(); + let images = tempfile::tempdir().unwrap().keep(); + let image = victory_loader::load(&prepared, &images).unwrap(); + victory_hle::runtime::set_main_image(image.base()); + victory_hle::runtime::set_image_path(image.base(), &dll); + // Persistent local storage (game saves live beside it), as `victory + // run` gives a title. + let data = tempfile::tempdir().unwrap().keep(); + victory_hle::runtime::set_title(victory_hle::runtime::Title { + id: 0x1234_5678, + storage: data.join("storage"), + storage_bytes: 64 << 20, + ..Default::default() + }); + let resolver = HleResolver::new(HostPolicy::default()); + let report = image + .bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + assert!( + report.missing.is_empty(), + "imports VIctory does not serve: {:?}", + report.missing.iter().map(|m| &m.symbol).collect::>() + ); + // SAFETY: its imports are bound; it depends on no title DLL. + unsafe { image.attach() }.unwrap(); + let exports = ( + image.export("conformance_run").expect("conformance_run"), + image + .export("conformance_bench") + .expect("conformance_bench"), + ); + // Stays loaded for the rest of the process. + std::mem::forget(image); + exports + }); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let at = if name == "conformance_bench" { + bench + } else { + run + }; + // SAFETY: the exports' signature in the fixture; the report stays valid + // until the next call, which the lock holds off. + unsafe { + let f: extern "system" fn(*mut usize) -> *const u8 = std::mem::transmute(at); + let mut len = 0; + let report = f(&mut len); + String::from_utf8_lossy(std::slice::from_raw_parts(report, len)).into_owned() + } +} + +/// The streaming workload (docs/acceptance.md): throughput, printed. Run +/// with `cargo test --release -p victory-hle --test conformance -- /// --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run on demand"] +fn workloads() { + println!("{}", call("conformance_bench")); +} + +#[test] +fn the_conformance_title_runs_through_victory() { + let tap = call("conformance_run"); + println!("{tap}"); + + let failed: Vec<&str> = tap + .lines() + .filter_map(|l| l.strip_prefix("not ok ")) + .filter_map(|l| l.split_once(" - ").map(|(_, name)| name)) + .collect(); + let passed: Vec<&str> = tap + .lines() + .filter_map(|l| l.strip_prefix("ok ")) + .filter_map(|l| l.split_once(" - ").map(|(_, name)| name)) + .collect(); + let known = |name: &str| KNOWN.iter().find(|(k, _)| *k == name); + for name in &failed { + if let Some((_, why)) = known(name) { + println!("known divergence: {name}: {why}"); + } + } + let unexpected: Vec<&&str> = failed.iter().filter(|n| known(n).is_none()).collect(); + let fixed: Vec<&str> = KNOWN + .iter() + .map(|(k, _)| *k) + .filter(|k| passed.contains(k)) + .collect(); + assert!(passed.len() + failed.len() > 0, "no checks ran:\n{tap}"); + assert!(unexpected.is_empty(), "checks that failed: {unexpected:#?}"); + assert!( + fixed.is_empty(), + "known divergences that now pass (take them off KNOWN): {fixed:#?}" + ); +} diff --git a/docs/acceptance.md b/docs/acceptance.md new file mode 100644 index 0000000000..474c8b079b --- /dev/null +++ b/docs/acceptance.md @@ -0,0 +1,146 @@ +# Acceptance and benchmark suite (plan and inventory) + +VIctory is checked today by unit tests inside each crate and by runs of the +title. This document plans a third layer that needs neither the title nor any +game data: a **conformance title** we write ourselves, run through VIctory +like a real one, that exercises each platform area the way a large +open-world GDK title does, checks the behaviour public documentation states, +and measures the workloads such a title puts on the platform. + +## Rules + +- **Public sources only.** Microsoft Learn's public GDK reference, public + Win32/D3D12/DirectStorage documentation, AMD's public RDNA2 ISA guide, + public conference talks and hardware disclosures. Nothing from game + binaries, leaked SDKs or NDA documentation. +- **No Microsoft GDK in the suite.** The GDK's license (Microsoft Public Game + Development Kit License Agreement, Section 3(a)) allows its use only to + develop and test Windows titles for Windows, and excludes software for + Xbox Series consoles; Section 4(d) forbids reverse engineering it. The + conformance title therefore does not link the GDK's libraries or include + its headers. It calls the runtime the way VIctory already documents + (`crates/victory-hle/src/modules/xgameruntime.rs`: `QueryApiImpl`, area + objects by provider and interface id), with declarations written from the + public reference pages. +- **Asset policy as for the rest of the tree** (`docs/asset-policy.md`): + nothing proprietary is committed; workloads are generated. + +## Oracles + +What tells a test the right answer, strongest first: + +| Oracle | Covers | Source | +|---|---|---| +| Public reference text (return codes, limits, ordering) | every runtime area | learn.microsoft.com/gaming/gdk/docs/reference | +| Open-source implementations of the same API (MIT) | XTaskQueue / XAsync: `Source/Task` of libHttpClient; GDeflate: DirectStorage's reference codec | github.com/microsoft/libHttpClient, github.com/microsoft/DirectStorage | +| Reference decoders | Opus (libopus), zlib (RFC 1950/1951) | public | +| Host reference renderer | GPU output (WARP, the D3D12 software adapter) | Windows | +| Hardware numbers | throughput and latency targets | Hot Chips 32, Xbox Wire, GDK overview pages | + +Areas whose reference pages are restricted (XMem, XAPU, D3D12.X) have no +public oracle beyond their published error codes and the Win32 +equivalents; their tests check only properties VIctory itself states and +the cross-area invariants below (memory written by one path reads back +through another). + +## Platform areas + +`hle` = the VIctory module (`crates/victory-hle/src/modules/`); `unit` = +its `#[test]` count on main at 940d32f. + +| Area | hle | unit | Documented behaviour to check (public reference) | +|---|---|---|---| +| Runtime init | xgameruntime | 1 | Initialize S_OK and repeatable per module; E_GAMERUNTIME_* codes (0x89240100…) | +| Task queues, async | xasync | 7 | dispatch modes (Manual, ThreadPool, SerializedThreadPool, Immediate) per port; `XTaskQueueDispatch` true only when it ran a call; Terminate cancels pending callbacks (`canceled=true`), later submits E_ABORT; `XAsyncGetStatus` E_PENDING until done; cancel then E_ABORT; provider op order Begin, DoWork (E_PENDING reschedules), GetResult, Cancel, Cleanup | +| User | xuser | 2 | AddDefaultUserSilently returns the same user each call; gamertag component buffer maxima (16/97/15/101 bytes), E_INSUFFICIENT_BUFFER; handles closed once; `XUserCompare`, local id equality | +| Game saves | xgamesave | 7 | 16 MB per update (E_GS_UPDATE_TOO_BIG 0x80830005), 256 MB quota (E_GS_QUOTA_EXCEEDED 0x80830006), atomic updates, one change per blob per update, container name charset (E_GS_INVALID_CONTAINER_NAME), submit consumes the update | +| Package | xpackage | 1 | identifier length bound; invalid chunk selector E_GAMEPACKAGE_INVALID_SELECTOR; mount, mount path size and path, close | +| Store | xstore | 1 | context, game license query, product query paging (`HasMorePages`) | +| System | xsystem | 4 | device type values (Series S 6, Series X 7); callable before init; console id format and E_INSUFFICIENT_BUFFER below `XSystemConsoleIdBytes`; analytics family "Xbox" | +| Threads | kernel | 3 | `XThreadSetTimeSensitive`/`XThreadIsTimeSensitive`; APIs unsafe on such threads return E_TIME_CRITICAL_THREAD (game saves: E_GS_ASYNC_FUNCTION_REQUIRED) | +| System UI | xgameui | 1 | text entry: length 0 means 1024, console cap 1024; result size then result | +| Networking | xnetworking | 1 | connectivity hint (offline by design: `networkInitialized` set, no connectivity), safe on time-sensitive threads | +| Display | display | 1 | `XDisplayTryEnableHdrMode` result values and defaults (0.01/1000/1000 nits) | +| Errors | xgameruntime | 1 | `XErrorSetOptions` values; callback set and called | +| Speech | speech | 1 | synthesizer create, voices, stream size then data | +| Input | gameinput | 7 | kinds (gamepad 0x40000, keyboard 0x4, mouse 0x8); readings are reference-counted (same pointer: no new input); history walkable for about 0.5 s; disconnect fails current reading | +| DirectStorage (console) | dstorage | 13 | FIFO completion per queue; auto-submit past half capacity; capacity bounds; 16-byte file offsets for zlib and BCPack; 32 MiB destination limit (1 GiB with 64 KiB/2 MiB pages); request reusable after enqueue; cancel by tag completes as success; error record | +| Files | files | 5 | Win32/CRT file semantics against the host itself (native run of the same test as the oracle) | +| Memory | xmem | 10 | (restricted reference) alignment attributes; physical 64 KiB pages mapped more than once read back the same bytes through every alias; 32-bit allocations below 4 GiB | +| Audio | audio, apu, dsp | 7 | (restricted reference) XAPU/XDSP error codes; decoded Opus equals libopus | +| Media | media | 2 | video decode of a generated clip | +| Upscaling | fidelityfx | 3 | FSR passes run and match the PC FSR output within tolerance | + +## Workloads (benchmarks) + +Sized from public figures ([S]) where they exist, otherwise estimates ([E]). +Each runs through VIctory and, where the API exists on Windows, natively, +and reports the metrics listed. + +| Workload | Shape | Pass | Metrics | Basis | +|---|---|---|---|---| +| Streaming | generated 8-16 GiB package of 64-512 KiB chunks, zlib, zlib+BCPack and raw; 4 priority queues; open-loop 50K requests/s; cancels by tag | every byte equals the reference decode; FIFO; cancelled requests succeed | raw GB/s per 250 ms window (console minimum 2.0), decoded GB/s (4.8 at 2:1), submit-thread CPU, p99 latency per priority, bytes/s into title memory | [S] GDK DirectStorage overview, Xbox Wire Velocity Architecture, Hot Chips 32 | +| Title-memory churn | 2,000 map/unmap of 64 KiB physical pages per frame; CPU writes 50-200 MB/frame across a 6 GiB GPU-visible heap at 30 fps | reads through every alias, CPU and GPU, equal the writes | copy/scan ms per frame (target 3) | [S] 64 KiB pages; [E] rates | +| Job system | 14 workers on 7 cores x 2 SMT, 160 fibers, 20K-50K jobs/frame, graphs 6-10 deep | affinity and CPU sets honoured; fiber-local state survives switches; no lost wake-ups | wake latency, 1 ms timer jitter, throughput vs native | [S] 8 Zen 2 cores (7 for titles, weakly sourced); [E] job counts | +| GPU-driven geometry | meshlets of 128 vertices / 256 primitives, amplification culling 50-100M to 5-10M triangles, ExecuteIndirect with GPU counts, 10K-50K records | image equals WARP | GPU ms at 1440p (frame budget 33 ms) | [S] AMD mesh shader guidance; [E] counts | +| Ray tracing | 10K instances, 3-5M triangles; 200-500 BLAS refits and ~50 rebuilds per frame; 1 GI + 1 reflection ray per pixel at half 1440p | hits equal a CPU reference | BVH ms, trace ms | [S] RT GI and reflections on Series X; [E] sizes | +| Wave64 on 32-lane hosts | ballots, readlane, prefix sums, quad ops | bit-exact against the RDNA2 ISA definitions | translation success rate | [S] AMD RDNA2 ISA guide | +| Texture streaming | MinMip feedback, 1,000-4,000 tile maps per frame from BCPack loads | detiled texels equal the reference for each swizzle mode | ms per frame | [S] 64 KiB tiles | +| Audio | 300 Opus streams at 48 kHz, 128-256 XMA voices, 8-12 convolution channels for 10 minutes | no underruns; PCM equals libopus | host CPU % | [S] Series X audio block: 300+ channels | +| Frame pacing | 30 fps presents at 60 Hz and VRR | frame-time deviation under 1 ms, no frame over 50 ms | pad-to-photon latency | [S] 33 ms frames at launch | +| Saves | 16 MB updates with the process killed at random points | all-or-nothing; exact error codes past the limits | save time | [S] GDK game-save limits | +| Pipelines | ~27,000 pipelines created on workers under a 30 fps loop | no frame over 50 ms | creation throughput | README counts | + +## Status + +`cargo test -p victory-hle --test conformance` builds the conformance title +(`tests/fixtures/conformance`), loads and binds it through VIctory as +`victory run` does, and runs its checks; the TAP report is printed with +`-- --nocapture`. Checks VIctory is known to answer differently from the +reference are listed in the test (`KNOWN`), each with why, and reported +rather than failed; one of them passing fails the test, so the list stays +true. `-- --ignored` runs the workloads. + +Covered so far: runtime initialisation, task queues and async calls, +system information, physical-page aliasing, DirectStorage (memory sources) +and game saves: 82 checks, 80 pass. The two divergences found: + +| Check | Reference | VIctory | +|---|---|---| +| `XSystemGetConsoleId` on retail | `00000000.00000000.00000000.00000000.00` | 38 digits ending in 1 | +| DirectStorage automatic submission | when an Enqueue fills more than half the capacity | at half the capacity | + +Gaps seen while writing them (documented features VIctory's tables leave +unimplemented, not yet tested): DirectStorage cancel by tag and the error +event and record; the documented request limits (32 MiB destination, 16-byte +offsets for compressed sources), whose behaviour when broken the reference +does not state. + +The streaming workload so far reads from memory only (no file source), +with synthetic data that compresses about 3.5:1; on an RTX 5070 Ti machine +(Ryzen 9 7900X), release build: raw 18-25 GB/s, zlib 12 GB/s out (3.5 GB/s +in), far above the console's 2.0 GB/s raw minimum and 4.8 GB/s decompressed, +because no storage is read. File sources and BCPack come next. + +## Build order + +1. The conformance title and its harness: a test registry, TAP output, a + `victory run` invocation per area, and the same tests compiled natively + where an oracle runs on Windows. First areas: system, task queues and + async (with libHttpClient's implementation as the second oracle), game + saves (limits and atomicity), DirectStorage ordering and limits. +2. Streaming and title-memory workloads, the stated load bottleneck. +3. The GPU frame workloads against WARP, and wave64 correctness. +4. Audio, frame pacing, input. + +## Sources + +- GDK reference and error codes: https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/ +- DirectStorage on Xbox (overview, limits): https://learn.microsoft.com/gaming/gdk/_content/gc/system/overviews/directstorage/directstorage-overview +- Game saves: https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/system/overviews/game-save/game-saves +- libHttpClient (XTaskQueue/XAsync implementation, MIT): https://github.com/microsoft/libHttpClient +- DirectStorage reference codecs (MIT): https://github.com/microsoft/DirectStorage +- AMD RDNA2 ISA: https://www.amd.com/system/files/TechDocs/rdna2-shader-instruction-set-architecture.pdf +- Xbox Series X SoC, Hot Chips 32: https://hc32.hotchips.org/assets/program/conference/day1/HotChips2020_GPU_Microsoft_Jeff_Andrews_v2.pdf +- Xbox Velocity Architecture: https://news.xbox.com/en-us/2020/07/14/a-closer-look-at-xbox-velocity-architecture/ +- Mesh shaders (AMD guidance): https://gpuopen.com/learn/mesh_shaders/mesh_shaders-optimization_and_best_practices/ diff --git a/tests/fixtures/conformance/Cargo.lock b/tests/fixtures/conformance/Cargo.lock new file mode 100644 index 0000000000..d781415b5b --- /dev/null +++ b/tests/fixtures/conformance/Cargo.lock @@ -0,0 +1,25 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "conformance" +version = "0.0.0" +dependencies = [ + "miniz_oxide", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] diff --git a/tests/fixtures/conformance/Cargo.toml b/tests/fixtures/conformance/Cargo.toml new file mode 100644 index 0000000000..4ababbfac3 --- /dev/null +++ b/tests/fixtures/conformance/Cargo.toml @@ -0,0 +1,22 @@ +# The conformance title: a stand-in for an Xbox title, written by us from +# public documentation only (docs/acceptance.md). It is NOT a workspace +# member: crates/victory-hle/tests/conformance.rs builds it on demand and +# runs it through VIctory's own loader and runtime. It links no SDK. +[package] +name = "conformance" +version = "0.0.0" +edition = "2024" +license = "GPL-3.0-or-later" +publish = false + +[lib] +crate-type = ["cdylib"] + +[profile.dev] +panic = "abort" + +[workspace] + +[dependencies] +# Compresses the zlib requests DirectStorage inflates. +miniz_oxide = "0.9.1" diff --git a/tests/fixtures/conformance/src/dstorage.rs b/tests/fixtures/conformance/src/dstorage.rs new file mode 100644 index 0000000000..e7cf2422b3 --- /dev/null +++ b/tests/fixtures/conformance/src/dstorage.rs @@ -0,0 +1,409 @@ +//! DirectStorage on the console (`XCRDAPI.dll`): memory-sourced requests, +//! zlib, completion order, request reuse and automatic submission. +//! +//! Public reference: reference/system/dstorage (DSTORAGE_REQUEST, +//! DSTORAGE_REQUEST_SOURCE_TYPE, DSTORAGE_PRIORITY) and the DirectStorage +//! overview (_content/gc/system/overviews/directstorage). Quoted there: +//! - "all requests are completed in order"; "Notifications aren't signaled +//! until all previous enqueued requests on the queue have completed." +//! - "If a read causes an error, that read is marked as completed. Future +//! notifications in the queue aren't blocked from signaling." +//! - "The structure can be reused as soon as `EnqueueRequest` returns." +//! - an Enqueue that "filled more than half of the queue's capacity since +//! last submission ... triggers an automatic submission." +//! - "Memory-sourced queues must be created with real-time priority." +//! +//! The factory's interface id, the method slots and the request option bits +//! are VIctory's (`crates/victory-hle/src/modules/dstorage.rs`). + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, S_OK}; +use crate::tap::Tap; + +const FACTORY: Guid = Guid( + 0x6295_9d11, + 0xd45f, + 0x4884, + [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae], +); +const E_PENDING: Hresult = 0x8000_000A_u32 as i32; + +const SOURCE_MEMORY: u64 = 1; +const PRIORITY_REALTIME: i8 = 2; +/// Request options: inflate zlib; the source is an address. +const ZLIB: u64 = 1; +const MEMORY_SOURCE: u64 = 1 << 22; + +#[link(name = "xcrdapi", kind = "raw-dylib")] +unsafe extern "system" { + fn DStorageGetFactory(iid: *const Guid, out: *mut *mut c_void) -> Hresult; +} + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + fn Sleep(ms: u32); +} + +#[repr(C)] +struct QueueDesc { + source_type: u64, + capacity: u16, + priority: i8, + name: *const u8, + unknown: u64, +} + +/// DSTORAGE_REQUEST as VIctory lays it out (0x48 bytes). +#[repr(C)] +#[derive(Clone, Copy)] +struct Request { + options: u64, + destination: *mut c_void, + page_offset: u64, + destination_size: u32, + source: *const c_void, + offset: u64, + source_size: u32, + intermediate_size: u32, + tag: u64, + name: *const u8, +} + +impl Request { + fn memory(options: u64, source: &[u8], destination: &mut [u8]) -> Request { + Request { + options: options | MEMORY_SOURCE, + destination: destination.as_mut_ptr().cast(), + page_offset: 0, + destination_size: destination.len() as u32, + source: source.as_ptr().cast(), + offset: 0, + source_size: source.len() as u32, + intermediate_size: 0, + tag: 0, + name: std::ptr::null(), + } + } +} + +/// A COM-style object: method table first. +#[derive(Clone, Copy)] +struct Com(*mut c_void); + +impl Com { + /// # Safety + /// `F` is the slot's signature. + unsafe fn method(self, offset: usize) -> F { + // SAFETY: (caller) the object's first word is its method table. + unsafe { + std::mem::transmute_copy(&*(*self.0.cast::<*const *const c_void>()).add(offset / 8)) + } + } + fn release(self) { + // SAFETY: Release. + let f: extern "system" fn(*mut c_void) -> u32 = unsafe { self.method(0x10) }; + f(self.0); + } +} + +struct Storage { + factory: Com, +} + +impl Storage { + fn status_array(&self, capacity: u32) -> Com { + let mut out = std::ptr::null_mut(); + // SAFETY: (all methods) the slot's signature in VIctory's table. + let f: extern "system" fn( + *mut c_void, + u32, + *const u8, + *const Guid, + *mut *mut c_void, + ) -> Hresult = unsafe { self.factory.method(0x28) }; + f( + self.factory.0, + capacity, + c"conformance".as_ptr().cast(), + std::ptr::null(), + &mut out, + ); + Com(out) + } + fn queue(&self, capacity: u16) -> Com { + let desc = QueueDesc { + source_type: SOURCE_MEMORY, + capacity, + priority: PRIORITY_REALTIME, + name: c"conformance".as_ptr().cast(), + unknown: 0, + }; + let mut out = std::ptr::null_mut(); + let f: extern "system" fn( + *mut c_void, + *const QueueDesc, + *const Guid, + *mut *mut c_void, + ) -> Hresult = unsafe { self.factory.method(0x50) }; + f(self.factory.0, &desc, std::ptr::null(), &mut out); + Com(out) + } +} + +fn enqueue(q: Com, r: &Request) { + let f: extern "system" fn(*mut c_void, *const Request) = unsafe { q.method(0x18) }; + f(q.0, r) +} +fn enqueue_status(q: Com, array: Com, index: u32) { + let f: extern "system" fn(*mut c_void, *mut c_void, u32) = unsafe { q.method(0x20) }; + f(q.0, array.0, index) +} +fn submit(q: Com) { + let f: extern "system" fn(*mut c_void) = unsafe { q.method(0x30) }; + f(q.0) +} +fn close(q: Com) { + let f: extern "system" fn(*mut c_void) = unsafe { q.method(0x40) }; + f(q.0) +} +fn status(array: Com, index: u32) -> Hresult { + let f: extern "system" fn(*mut c_void, u32) -> Hresult = unsafe { array.method(0x20) }; + f(array.0, index) +} + +/// Waits up to `ms` for status entry `index`; its result. +fn wait(array: Com, index: u32, ms: u32) -> Hresult { + for _ in 0..ms { + let hr = status(array, index); + if hr != E_PENDING { + return hr; + } + // SAFETY: a plain call. + unsafe { Sleep(1) }; + } + status(array, index) +} + +fn pattern(n: usize, seed: u32) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761).max(1); + (0..n) + .map(|i| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + // Runs of repeated bytes, so zlib has something to find. + if i % 64 < 48 { (i / 64) as u8 } else { x as u8 } + }) + .collect() +} + +pub fn run(t: &mut Tap) { + let mut out = std::ptr::null_mut(); + // SAFETY: a plain call. + let hr = unsafe { DStorageGetFactory(&FACTORY, &mut out) }; + t.check( + hr == S_OK && !out.is_null(), + "dstorage: DStorageGetFactory gives the factory", + || format!("{hr:#010x}"), + ); + if out.is_null() { + return; + } + let s = Storage { factory: Com(out) }; + let array = s.status_array(16); + let q = s.queue(64); + + // A memory-to-memory copy and a zlib inflate. + let raw = pattern(1 << 20, 1); + let mut copied = vec![0u8; raw.len()]; + enqueue(q, &Request::memory(0, &raw, &mut copied)); + let plain = pattern(256 << 10, 2); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let mut inflated = vec![0u8; plain.len()]; + enqueue(q, &Request::memory(ZLIB, &packed, &mut inflated)); + enqueue_status(q, array, 0); + submit(q); + t.eq( + wait(array, 0, 5000), + S_OK, + "dstorage: memory-sourced requests complete", + ); + t.check( + copied == raw, + "dstorage: a raw request copies its bytes", + || "bytes differ".into(), + ); + t.check( + inflated == plain, + "dstorage: a zlib request inflates to the original bytes", + || "bytes differ".into(), + ); + + // Completion in order: a status is not signaled before every request + // enqueued before it has completed, whatever their sizes. + let sources: Vec> = (0..8) + .map(|i| pattern(if i % 2 == 0 { 4 << 20 } else { 4 << 10 }, 10 + i)) + .collect(); + let mut destinations: Vec> = sources.iter().map(|s| vec![0u8; s.len()]).collect(); + for (i, (src, dst)) in sources.iter().zip(destinations.iter_mut()).enumerate() { + enqueue(q, &Request::memory(0, src, dst)); + enqueue_status(q, array, 1 + i as u32); + } + submit(q); + let mut in_order = true; + for _ in 0..5000 { + let done: Vec = (1..9).map(|i| status(array, i) != E_PENDING).collect(); + // Done entries form a prefix. + in_order &= done.windows(2).all(|w| w[0] || !w[1]); + if done.iter().all(|&d| d) { + break; + } + // SAFETY: a plain call. + unsafe { Sleep(1) }; + } + t.check( + in_order, + "dstorage: status entries are signaled in queue order", + || "a later entry was signaled first".into(), + ); + t.check( + (1..9).all(|i| status(array, i) == S_OK), + "dstorage: ... and all succeed", + || "not all S_OK".into(), + ); + t.check( + sources == destinations, + "dstorage: every ordered request wrote its bytes", + || "bytes differ".into(), + ); + + // A failed read does not block later notifications. + let broken = vec![0x78, 0x9c, 0xff, 0xff, 0xff, 0xff]; + let mut sink = vec![0u8; 4096]; + enqueue(q, &Request::memory(ZLIB, &broken, &mut sink)); + enqueue_status(q, array, 9); + let after = pattern(64 << 10, 3); + let mut after_copy = vec![0u8; after.len()]; + enqueue(q, &Request::memory(0, &after, &mut after_copy)); + enqueue_status(q, array, 10); + submit(q); + t.check( + wait(array, 9, 5000) != E_PENDING, + "dstorage: a failed read is marked completed", + || "still pending".into(), + ); + t.eq( + wait(array, 10, 5000), + S_OK, + "dstorage: a notification after a failed read still signals", + ); + t.check( + after_copy == after, + "dstorage: ... and the read after it wrote its bytes", + || "bytes differ".into(), + ); + + // The request structure can be reused as soon as EnqueueRequest returns. + let first = pattern(32 << 10, 4); + let second = pattern(32 << 10, 5); + let (mut to_first, mut to_second) = (vec![0u8; first.len()], vec![0u8; second.len()]); + let mut r = Request::memory(0, &first, &mut to_first); + enqueue(q, &r); + r = Request::memory(0, &second, &mut to_second); + enqueue(q, &r); + enqueue_status(q, array, 11); + submit(q); + t.eq( + wait(array, 11, 5000), + S_OK, + "dstorage: requests from one reused structure complete", + ); + t.check( + to_first == first && to_second == second, + "dstorage: a reused request structure does not change the enqueued request", + || "bytes differ".into(), + ); + close(q); + + // Automatic submission once more than half the capacity is enqueued. + let small = s.queue(8); + let bytes = pattern(4096, 6); + let mut sinks = vec![vec![0u8; 4096]; 5]; + for sink in sinks.iter_mut().take(3) { + enqueue(small, &Request::memory(0, &bytes, sink)); + } + // Four of eight entries: half, not more than half. + enqueue_status(small, array, 12); + t.eq( + wait(array, 12, 300), + E_PENDING, + "dstorage: a queue filled to half its capacity is not submitted on its own", + ); + enqueue(small, &Request::memory(0, &bytes, &mut sinks[3])); + t.eq( + wait(array, 12, 5000), + S_OK, + "dstorage: filling more than half the capacity submits on its own", + ); + submit(small); + close(small); + small.release(); + q.release(); + array.release(); +} + +/// The streaming workload (docs/acceptance.md, Workloads): memory-sourced +/// requests through one real-time queue, raw and zlib, in the chunk sizes +/// the DirectStorage overview recommends (64 KiB to 512 KiB). A report of +/// throughput per kind; the console's own figures are 2.0 GB/s raw (its +/// minimum) and 4.8 GB/s decompressed at 2:1. +pub fn bench() -> String { + let mut out = std::ptr::null_mut(); + // SAFETY: a plain call. + if unsafe { DStorageGetFactory(&FACTORY, &mut out) } != S_OK || out.is_null() { + return "no factory\n".into(); + } + let s = Storage { factory: Com(out) }; + let array = s.status_array(4); + let q = s.queue(1024); + let mut report = String::new(); + for (kind, chunk, total) in [ + ("raw", 64usize << 10, 512usize << 20), + ("raw", 512 << 10, 512 << 20), + ("zlib", 64 << 10, 256 << 20), + ("zlib", 512 << 10, 256 << 20), + ] { + let plain = pattern(chunk, chunk as u32); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let (source, options) = if kind == "zlib" { + (&packed, ZLIB) + } else { + (&plain, 0) + }; + // A ring of destinations, as a streaming title reuses its buffers. + let mut ring: Vec> = (0..64).map(|_| vec![0u8; chunk]).collect(); + let n = total / chunk; + let started = std::time::Instant::now(); + for i in 0..n { + enqueue(q, &Request::memory(options, source, &mut ring[i % 64])); + } + enqueue_status(q, array, 0); + submit(q); + let hr = wait(array, 0, 120_000); + let seconds = started.elapsed().as_secs_f64(); + let ok = hr == S_OK && ring[0] == plain; + report.push_str(&format!( + "{kind:>4} {:>4} KiB chunks: {:>6.2} GB/s out, {:>6.2} GB/s in, {:>8.0} requests/s{}\n", + chunk >> 10, + total as f64 / seconds / 1e9, + (n * source.len()) as f64 / seconds / 1e9, + n as f64 / seconds, + if ok { "" } else { " (FAILED)" }, + )); + } + close(q); + q.release(); + array.release(); + report +} diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs new file mode 100644 index 0000000000..4e025bc148 --- /dev/null +++ b/tests/fixtures/conformance/src/lib.rs @@ -0,0 +1,57 @@ +//! The conformance title (docs/acceptance.md): calls the console runtime as +//! a title does and checks what Microsoft's public GDK reference says each +//! call does. Results are TAP lines, read by the harness through +//! `conformance_run`. +//! +//! How a title reaches the runtime is VIctory's own description +//! (`crates/victory-hle/src/modules/xgameruntime.rs`): code linked into the +//! title loads `xgameruntime.dll`, asks `QueryApiImpl` for an area's object +//! by provider and interface id, and calls one of its methods. The ids and +//! method slots below are the ones VIctory implements, so these tests check +//! behaviour, not that binary interface (only the title itself can check +//! that). Everything else (the behaviour, the constants, the structure +//! layouts) is from the public reference, cited per test. + +#![allow(clippy::missing_safety_doc)] +// The harness calls the report exports as title code would, with pointers +// the real API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +mod dstorage; +mod rt; +mod tap; +mod xasync; +mod xgamesave; +mod xmem; +mod xsystem; + +/// Runs every test; returns the TAP report (valid until the next call). +#[unsafe(no_mangle)] +pub extern "system" fn conformance_run(len: *mut usize) -> *const u8 { + let mut t = tap::Tap::default(); + rt::init(&mut t); + xasync::run(&mut t); + xsystem::run(&mut t); + xmem::run(&mut t); + dstorage::run(&mut t); + xgamesave::run(&mut t); + let report = t.finish(); + // SAFETY: the harness passes room for the length. + unsafe { len.write(report.len()) }; + report.as_ptr() +} + +/// Runs the workloads; returns their report (valid until the next call). +#[unsafe(no_mangle)] +pub extern "system" fn conformance_bench(len: *mut usize) -> *const u8 { + static REPORT: std::sync::Mutex = std::sync::Mutex::new(String::new()); + let mut report = REPORT.lock().unwrap_or_else(|e| e.into_inner()); + *report = format!( + "streaming (DirectStorage, memory sources) +{}", + dstorage::bench() + ); + // SAFETY: the harness passes room for the length. + unsafe { len.write(report.len()) }; + report.as_ptr() +} diff --git a/tests/fixtures/conformance/src/rt.rs b/tests/fixtures/conformance/src/rt.rs new file mode 100644 index 0000000000..8169d4c621 --- /dev/null +++ b/tests/fixtures/conformance/src/rt.rs @@ -0,0 +1,96 @@ +//! Reaching the runtime as code linked into a title does: load +//! `xgameruntime.dll`, initialise, then ask `QueryApiImpl` for each area's +//! object. + +use std::ffi::c_void; +use std::sync::OnceLock; + +use crate::tap::Tap; + +pub type Hresult = i32; +pub const S_OK: Hresult = 0; + +#[repr(C)] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Guid(pub u32, pub u16, pub u16, pub [u8; 8]); + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + fn LoadLibraryExA(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void; + fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void; +} + +#[link(name = "xgameruntime", kind = "raw-dylib")] +unsafe extern "system" { + /// Public: XGameRuntimeInitialize (reference/system/xgameruntimeinit). + fn XGameRuntimeInitialize() -> Hresult; +} + +type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> Hresult; + +static QUERY: OnceLock> = OnceLock::new(); + +pub fn init(t: &mut Tap) { + // Public: XGameRuntimeInitialize returns S_OK, and every module of a + // process calls it, so a second call succeeds too. + // SAFETY: plain calls into the runtime. + let (first, second) = unsafe { (XGameRuntimeInitialize(), XGameRuntimeInitialize()) }; + t.eq(first, S_OK, "runtime: XGameRuntimeInitialize succeeds"); + t.eq( + second, + S_OK, + "runtime: XGameRuntimeInitialize succeeds again (each module calls it)", + ); + let query = QUERY.get_or_init(|| { + // SAFETY: NUL-terminated names; the flag is LOAD_LIBRARY_SEARCH_SYSTEM32. + unsafe { + let module = LoadLibraryExA( + c"xgameruntime.dll".as_ptr().cast(), + std::ptr::null_mut(), + 0x800, + ); + if module.is_null() { + return None; + } + let f = GetProcAddress(module, c"QueryApiImpl".as_ptr().cast()); + (!f.is_null()).then(|| std::mem::transmute::<*mut c_void, Query>(f)) + } + }); + t.check( + query.is_some(), + "runtime: the title's stub finds QueryApiImpl", + || "not found".into(), + ); +} + +/// An area's object: its method table's slots, from `QueryInterface` at 0. +pub struct Object(*mut c_void); + +impl Object { + /// The method at byte offset `offset` of the table, as `F`. + /// + /// # Safety + /// `F` is the slot's signature. + pub unsafe fn method(&self, offset: usize) -> F { + // SAFETY: (caller) an object's first word is its method table. + unsafe { + let table = *self.0.cast::<*const *const c_void>(); + std::mem::transmute_copy(&*table.add(offset / 8)) + } + } + + pub fn this(&self) -> *mut c_void { + self.0 + } +} + +pub fn area(provider: Guid, iid: Guid) -> Result { + let Some(Some(query)) = QUERY.get() else { + return Err(-1); + }; + let mut out = std::ptr::null_mut(); + match query(&provider, &iid, &mut out) { + S_OK if !out.is_null() => Ok(Object(out)), + hr => Err(hr), + } +} diff --git a/tests/fixtures/conformance/src/tap.rs b/tests/fixtures/conformance/src/tap.rs new file mode 100644 index 0000000000..ba72dd9438 --- /dev/null +++ b/tests/fixtures/conformance/src/tap.rs @@ -0,0 +1,45 @@ +//! Test Anything Protocol output. + +use std::sync::Mutex; + +#[derive(Default)] +pub struct Tap { + lines: Vec, + n: usize, + failed: usize, +} + +impl Tap { + /// One check: `ok` or `not ok`, with what was seen when it failed. + pub fn check(&mut self, ok: bool, name: &str, detail: impl FnOnce() -> String) { + self.n += 1; + if ok { + self.lines.push(format!("ok {} - {name}", self.n)); + } else { + self.failed += 1; + self.lines.push(format!("not ok {} - {name}", self.n)); + for line in detail().lines() { + self.lines.push(format!(" # {line}")); + } + } + } + + pub fn eq(&mut self, seen: T, want: T, name: &str) { + let ok = seen == want; + self.check(ok, name, || format!("seen {seen:?}, want {want:?}")); + } + + pub fn finish(self) -> &'static str { + static REPORT: Mutex = Mutex::new(String::new()); + let mut report = REPORT.lock().unwrap_or_else(|e| e.into_inner()); + *report = format!( + "TAP version 13\n1..{}\n{}\n# failed {}\n", + self.n, + self.lines.join("\n"), + self.failed + ); + // SAFETY: the string lives in a static and is replaced only by the + // next run, which the harness does not start while reading this one. + unsafe { &*(report.as_str() as *const str) } + } +} diff --git a/tests/fixtures/conformance/src/xasync.rs b/tests/fixtures/conformance/src/xasync.rs new file mode 100644 index 0000000000..daec3976b2 --- /dev/null +++ b/tests/fixtures/conformance/src/xasync.rs @@ -0,0 +1,624 @@ +//! Task queues and async calls. +//! +//! Public reference: reference/system/xtaskqueue, reference/system/xasync, +//! reference/system/xasyncprovider (XAsyncBlock, XAsyncOp, the dispatch +//! modes and ports, XTaskQueueDispatch, XTaskQueueTerminate, XAsyncCancel). +//! Microsoft's open-source implementation of the same API is libHttpClient's +//! `Source/Task` (MIT), a second oracle where the reference is brief. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use crate::rt::{Guid, Hresult, Object, S_OK, area}; +use crate::tap::Tap; + +/// The task-queue area (VIctory's `xasync::PROVIDER`, also the interface id). +const AREA: Guid = Guid( + 0x073b_7dcb, + 0x1fcf, + 0x4030, + [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28], +); + +const E_PENDING: Hresult = 0x8000_000A_u32 as i32; +const E_ABORT: Hresult = 0x8000_4004_u32 as i32; + +// XTaskQueueDispatchMode and XTaskQueuePort. +const MANUAL: u32 = 0; +const THREAD_POOL: u32 = 1; +const IMMEDIATE: u32 = 3; +const WORK: u32 = 0; +const COMPLETION: u32 = 1; + +// XAsyncOp. +const BEGIN: u32 = 0; +const DO_WORK: u32 = 1; +const GET_RESULT: u32 = 2; +const CANCEL: u32 = 3; +const CLEANUP: u32 = 4; + +type Queue = *mut c_void; +type Callback = extern "system" fn(*mut c_void, bool); +type Done = extern "system" fn(*mut Block); + +/// XAsyncBlock. +#[repr(C)] +pub struct Block { + queue: Queue, + context: *mut c_void, + callback: Option, + internal: [usize; 4], +} + +impl Block { + /// A block on the process task queue, with no completion callback. + pub fn on_process_queue() -> Block { + Block::new(std::ptr::null_mut(), std::ptr::null_mut(), None) + } + + fn new(queue: Queue, context: *mut c_void, callback: Option) -> Block { + Block { + queue, + context, + callback, + internal: [0; 4], + } + } +} + +/// XAsyncProviderData. +#[repr(C)] +struct ProviderData { + block: *mut Block, + buffer_size: usize, + buffer: *mut c_void, + context: *mut c_void, +} + +type Provider = extern "system" fn(u32, *const ProviderData) -> Hresult; + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + fn GetCurrentThreadId() -> u32; + fn Sleep(ms: u32); +} + +/// The area's methods, by their slots in VIctory's table. +struct Api(Object); + +impl Api { + fn create(&self, work: u32, completion: u32) -> Result { + let mut q = std::ptr::null_mut(); + // SAFETY: (all methods) the slot's signature in VIctory's table. + let f: extern "system" fn(*mut c_void, u32, u32, *mut Queue) -> Hresult = + unsafe { self.0.method(0x60) }; + match f(self.0.this(), work, completion, &mut q) { + S_OK => Ok(q), + hr => Err(hr), + } + } + fn dispatch(&self, q: Queue, port: u32, timeout: u32) -> bool { + let f: extern "system" fn(*mut c_void, Queue, u32, u32) -> bool = + unsafe { self.0.method(0x80) }; + f(self.0.this(), q, port, timeout) + } + fn close(&self, q: Queue) { + let f: extern "system" fn(*mut c_void, Queue) = unsafe { self.0.method(0x88) }; + f(self.0.this(), q) + } + fn submit(&self, q: Queue, port: u32, context: *mut c_void, cb: Callback) -> Hresult { + let f: extern "system" fn( + *mut c_void, + Queue, + u32, + *mut c_void, + Option, + ) -> Hresult = unsafe { self.0.method(0x90) }; + f(self.0.this(), q, port, context, Some(cb)) + } + fn submit_delayed( + &self, + q: Queue, + port: u32, + delay: u32, + context: *mut c_void, + cb: Callback, + ) -> Hresult { + let f: extern "system" fn( + *mut c_void, + Queue, + u32, + u32, + *mut c_void, + Option, + ) -> Hresult = unsafe { self.0.method(0x98) }; + f(self.0.this(), q, port, delay, context, Some(cb)) + } + fn terminate( + &self, + q: Queue, + wait: bool, + context: *mut c_void, + cb: extern "system" fn(*mut c_void), + ) -> Hresult { + let f: extern "system" fn( + *mut c_void, + Queue, + u8, + *mut c_void, + Option, + ) -> Hresult = unsafe { self.0.method(0xb0) }; + f(self.0.this(), q, u8::from(wait), context, Some(cb)) + } + fn process_queue(&self) -> (bool, Queue) { + let mut q = std::ptr::null_mut(); + let f: extern "system" fn(*mut c_void, *mut Queue) -> bool = unsafe { self.0.method(0xc8) }; + (f(self.0.this(), &mut q), q) + } + fn status(&self, b: *mut Block, wait: bool) -> Hresult { + let f: extern "system" fn(*mut c_void, *mut Block, u8) -> Hresult = + unsafe { self.0.method(0x18) }; + f(self.0.this(), b, u8::from(wait)) + } + fn result_size(&self, b: *mut Block) -> (Hresult, usize) { + let mut n = 0; + let f: extern "system" fn(*mut c_void, *mut Block, *mut usize) -> Hresult = + unsafe { self.0.method(0x20) }; + (f(self.0.this(), b, &mut n), n) + } + fn cancel(&self, b: *mut Block) { + let f: extern "system" fn(*mut c_void, *mut Block) = unsafe { self.0.method(0x28) }; + f(self.0.this(), b) + } + fn run(&self, b: *mut Block, work: extern "system" fn(*mut Block) -> Hresult) -> Hresult { + let f: extern "system" fn( + *mut c_void, + *mut Block, + Option Hresult>, + ) -> Hresult = unsafe { self.0.method(0x30) }; + f(self.0.this(), b, Some(work)) + } + fn begin( + &self, + b: *mut Block, + context: *mut c_void, + identity: *const c_void, + provider: Provider, + ) -> Hresult { + let f: extern "system" fn( + *mut c_void, + *mut Block, + *mut c_void, + *const c_void, + *const u8, + Option, + ) -> Hresult = unsafe { self.0.method(0x38) }; + f( + self.0.this(), + b, + context, + identity, + c"conformance".as_ptr().cast(), + Some(provider), + ) + } + fn schedule(&self, b: *mut Block, delay: u32) -> Hresult { + let f: extern "system" fn(*mut c_void, *mut Block, u32) -> Hresult = + unsafe { self.0.method(0x48) }; + f(self.0.this(), b, delay) + } + fn complete(&self, b: *mut Block, hr: Hresult, size: usize) { + let f: extern "system" fn(*mut c_void, *mut Block, Hresult, usize) = + unsafe { self.0.method(0x50) }; + f(self.0.this(), b, hr, size) + } + fn result( + &self, + b: *mut Block, + identity: *const c_void, + buffer: &mut [u8], + ) -> (Hresult, usize) { + let mut used = 0; + let f: extern "system" fn( + *mut c_void, + *mut Block, + *const c_void, + usize, + *mut c_void, + *mut usize, + ) -> Hresult = unsafe { self.0.method(0x58) }; + ( + f( + self.0.this(), + b, + identity, + buffer.len(), + buffer.as_mut_ptr().cast(), + &mut used, + ), + used, + ) + } +} + +// SAFETY: the object is the runtime's, callable from any thread. +unsafe impl Sync for Api {} +// SAFETY: as above. +unsafe impl Send for Api {} + +static API: OnceLock = OnceLock::new(); + +/// Waits for an async call; its status (XAsyncGetStatus with wait set). +pub fn wait(b: &mut Block) -> Hresult { + api().status(b, true) +} + +fn api() -> &'static Api { + API.get().expect("the task-queue area") +} + +/// What a submitted callback saw: its thread and `canceled`. +#[derive(Default)] +struct Seen { + calls: AtomicU32, + thread: AtomicU32, + canceled: AtomicBool, +} + +extern "system" fn note(context: *mut c_void, canceled: bool) { + // SAFETY: tests pass a live `Seen`. + let seen = unsafe { &*context.cast::() }; + // SAFETY: a plain call. + seen.thread + .store(unsafe { GetCurrentThreadId() }, Ordering::SeqCst); + seen.canceled.store(canceled, Ordering::SeqCst); + seen.calls.fetch_add(1, Ordering::SeqCst); +} + +extern "system" fn terminated(context: *mut c_void) { + // SAFETY: tests pass a live `AtomicU32`. + unsafe { &*context.cast::() }.fetch_add(1, Ordering::SeqCst); +} + +fn ctx(value: &T) -> *mut c_void { + std::ptr::from_ref(value).cast_mut().cast() +} + +/// Waits up to `ms` for `done`. +fn wait_for(ms: u32, done: impl Fn() -> bool) -> bool { + for _ in 0..ms / 5 { + if done() { + return true; + } + // SAFETY: a plain call. + unsafe { Sleep(5) }; + } + done() +} + +pub fn run(t: &mut Tap) { + match area(AREA, AREA) { + Ok(object) => { + let _ = API.set(Api(object)); + } + Err(hr) => { + t.check(false, "xasync: the task-queue area is served", || { + format!("QueryApiImpl {hr:#010x}") + }); + return; + } + } + let a = api(); + // SAFETY: a plain call. + let me = unsafe { GetCurrentThreadId() }; + + // Manual dispatch: nothing runs until XTaskQueueDispatch, which runs one + // callback on the calling thread and returns true; false when empty. + let q = a.create(MANUAL, MANUAL).expect("manual queue"); + let seen = Seen::default(); + t.eq( + a.submit(q, WORK, ctx(&seen), note), + S_OK, + "xasync: XTaskQueueSubmitCallback succeeds", + ); + t.eq( + seen.calls.load(Ordering::SeqCst), + 0, + "xasync: a manual port runs nothing before dispatch", + ); + t.eq( + a.dispatch(q, WORK, 0), + true, + "xasync: XTaskQueueDispatch returns true when it ran a callback", + ); + t.eq( + seen.calls.load(Ordering::SeqCst), + 1, + "xasync: the dispatched callback ran once", + ); + t.eq( + seen.thread.load(Ordering::SeqCst), + me, + "xasync: a manual dispatch runs on the calling thread", + ); + t.eq( + seen.canceled.load(Ordering::SeqCst), + false, + "xasync: a dispatched callback is not canceled", + ); + t.eq( + a.dispatch(q, WORK, 0), + false, + "xasync: XTaskQueueDispatch returns false on an empty port", + ); + t.eq( + a.dispatch(q, WORK, 20), + false, + "xasync: a dispatch with a timeout returns false when nothing comes", + ); + + // A delayed callback is not there before its delay, and is after. + let delayed = Seen::default(); + t.eq( + a.submit_delayed(q, WORK, 100, ctx(&delayed), note), + S_OK, + "xasync: XTaskQueueSubmitDelayedCallback succeeds", + ); + t.eq( + a.dispatch(q, WORK, 0), + false, + "xasync: a delayed callback is not dispatched before its delay", + ); + t.eq( + a.dispatch(q, WORK, 2000), + true, + "xasync: a delayed callback is dispatched after its delay", + ); + t.eq( + delayed.calls.load(Ordering::SeqCst), + 1, + "xasync: the delayed callback ran once", + ); + + // Terminate: pending callbacks are called with canceled set, new ones + // are refused, and the termination callback comes last. + let pending = Seen::default(); + let ends = AtomicU32::new(0); + a.submit(q, WORK, ctx(&pending), note); + t.eq( + a.terminate(q, false, ctx(&ends), terminated), + S_OK, + "xasync: XTaskQueueTerminate succeeds", + ); + let late = Seen::default(); + t.check( + a.submit(q, WORK, ctx(&late), note) != S_OK, + "xasync: a terminated queue refuses new callbacks", + || "accepted".into(), + ); + while a.dispatch(q, WORK, 0) || a.dispatch(q, COMPLETION, 0) {} + t.eq( + pending.calls.load(Ordering::SeqCst), + 1, + "xasync: a pending callback is still called on terminate", + ); + t.eq( + pending.canceled.load(Ordering::SeqCst), + true, + "xasync: ... with canceled set", + ); + t.eq( + late.calls.load(Ordering::SeqCst), + 0, + "xasync: a refused callback is never called", + ); + t.check( + wait_for(2000, || ends.load(Ordering::SeqCst) == 1), + "xasync: the termination callback is called once", + || format!("called {} times", ends.load(Ordering::SeqCst)), + ); + a.close(q); + + // Immediate runs on the submitting thread, during the submit; the + // thread pool runs elsewhere. + let q = a.create(IMMEDIATE, IMMEDIATE).expect("immediate queue"); + let seen = Seen::default(); + a.submit(q, WORK, ctx(&seen), note); + t.eq( + seen.calls.load(Ordering::SeqCst), + 1, + "xasync: an immediate port runs the callback during the submit", + ); + t.eq( + seen.thread.load(Ordering::SeqCst), + me, + "xasync: ... on the submitting thread", + ); + a.close(q); + let q = a + .create(THREAD_POOL, THREAD_POOL) + .expect("thread-pool queue"); + let seen = Seen::default(); + a.submit(q, WORK, ctx(&seen), note); + t.check( + wait_for(2000, || seen.calls.load(Ordering::SeqCst) == 1), + "xasync: a thread-pool port runs the callback", + || "not run".into(), + ); + t.check( + seen.thread.load(Ordering::SeqCst) != me, + "xasync: ... on another thread", + || "ran on the submitting thread".into(), + ); + a.close(q); + + // The process has a default queue (a thread pool). + let (has, q) = a.process_queue(); + t.check( + has && !q.is_null(), + "xasync: there is a process task queue", + || format!("{has} {q:?}"), + ); + if has && !q.is_null() { + a.close(q); + } + + async_calls(t); +} + +static OPS: Mutex> = Mutex::new(Vec::new()); + +/// A provider that schedules its work, completes with 8 bytes, and hands +/// them over on GetResult. +extern "system" fn eight_bytes(op: u32, data: *const ProviderData) -> Hresult { + OPS.lock().unwrap().push(op); + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + let a = api(); + match op { + BEGIN => a.schedule(data.block, 0), + DO_WORK => { + a.complete(data.block, S_OK, 8); + S_OK + } + GET_RESULT => { + // SAFETY: the runtime passes the caller's buffer of `buffer_size`. + unsafe { + std::ptr::copy_nonoverlapping( + 0x1122_3344_5566_7788_u64.to_le_bytes().as_ptr(), + data.buffer.cast(), + 8, + ) + }; + S_OK + } + _ => S_OK, + } +} + +/// A provider that never finishes on its own; canceled, it completes with +/// E_ABORT. +extern "system" fn forever(op: u32, data: *const ProviderData) -> Hresult { + OPS.lock().unwrap().push(op); + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + if op == CANCEL { + api().complete(data.block, E_ABORT, 0); + } + S_OK +} + +extern "system" fn work_ok(_: *mut Block) -> Hresult { + S_OK +} + +extern "system" fn done(b: *mut Block) { + // SAFETY: tests put a live `AtomicU32` in the block's context. + unsafe { &*(*b).context.cast::() }.fetch_add(1, Ordering::SeqCst); +} + +fn async_calls(t: &mut Tap) { + let a = api(); + let q = a.create(MANUAL, MANUAL).expect("manual queue"); + let dispatch_all = || while a.dispatch(q, WORK, 0) || a.dispatch(q, COMPLETION, 0) {}; + + // XAsyncRun: E_PENDING until its work has run, then the work's result; + // the completion callback runs on the completion port. + let calls = AtomicU32::new(0); + let mut block = Block::new(q, ctx(&calls), Some(done)); + let b: *mut Block = &mut block; + t.eq(a.run(b, work_ok), S_OK, "xasync: XAsyncRun succeeds"); + t.eq( + a.status(b, false), + E_PENDING, + "xasync: XAsyncGetStatus is E_PENDING before the work runs", + ); + dispatch_all(); + t.eq( + a.status(b, false), + S_OK, + "xasync: XAsyncGetStatus is the work's result once it ran", + ); + t.eq( + calls.load(Ordering::SeqCst), + 1, + "xasync: the completion callback ran once", + ); + + // A provider: Begin, DoWork, then GetResult and Cleanup on XAsyncGetResult. + OPS.lock().unwrap().clear(); + let calls = AtomicU32::new(0); + let mut block = Block::new(q, ctx(&calls), Some(done)); + let b: *mut Block = &mut block; + let identity = eight_bytes as *const c_void; + t.eq( + a.begin(b, std::ptr::null_mut(), identity, eight_bytes), + S_OK, + "xasync: XAsyncBegin succeeds", + ); + dispatch_all(); + t.eq( + a.status(b, false), + S_OK, + "xasync: a provider's call succeeds once it completes", + ); + t.eq( + a.result_size(b), + (S_OK, 8), + "xasync: XAsyncGetResultSize is the size the provider completed with", + ); + let mut buffer = [0u8; 8]; + t.eq( + a.result(b, identity, &mut buffer), + (S_OK, 8), + "xasync: XAsyncGetResult copies the result", + ); + t.eq( + u64::from_le_bytes(buffer), + 0x1122_3344_5566_7788, + "xasync: ... the provider's bytes", + ); + t.eq( + OPS.lock().unwrap().clone(), + vec![BEGIN, DO_WORK, GET_RESULT, CLEANUP], + "xasync: provider operations come in order", + ); + t.eq( + calls.load(Ordering::SeqCst), + 1, + "xasync: the provider call's completion callback ran once", + ); + + // Cancel: the provider is asked to cancel; the call ends with E_ABORT and + // its completion callback still runs. + OPS.lock().unwrap().clear(); + let calls = AtomicU32::new(0); + let mut block = Block::new(q, ctx(&calls), Some(done)); + let b: *mut Block = &mut block; + a.begin(b, std::ptr::null_mut(), forever as *const c_void, forever); + t.eq( + a.status(b, false), + E_PENDING, + "xasync: an unfinished call is E_PENDING", + ); + a.cancel(b); + dispatch_all(); + t.eq( + a.status(b, false), + E_ABORT, + "xasync: a canceled call's status is E_ABORT", + ); + t.eq( + calls.load(Ordering::SeqCst), + 1, + "xasync: a canceled call's completion callback still runs", + ); + let ops = OPS.lock().unwrap().clone(); + t.check( + ops.first() == Some(&BEGIN) && ops.contains(&CANCEL) && ops.last() == Some(&CLEANUP), + "xasync: a canceled provider sees Begin, Cancel, then Cleanup", + || format!("ops {ops:?}"), + ); + a.close(q); +} diff --git a/tests/fixtures/conformance/src/xgamesave.rs b/tests/fixtures/conformance/src/xgamesave.rs new file mode 100644 index 0000000000..75b038bc1c --- /dev/null +++ b/tests/fixtures/conformance/src/xgamesave.rs @@ -0,0 +1,276 @@ +//! Game saves: containers, blobs, updates. +//! +//! Public reference: reference/system/xgamesave and the game-save overview +//! (_content/gc/system/overviews/game-save/game-saves): one update writes at +//! most 16 MB (E_GS_UPDATE_TOO_BIG, 0x80830005); an update is all or +//! nothing; container names outside the allowed characters are +//! E_GS_INVALID_CONTAINER_NAME (0x80830001); XGameSaveBlob is the blob's +//! info (name, size) and a pointer to its data. +//! +//! The area's ids and method slots are VIctory's (`crates/victory-hle/src/ +//! modules/xgamesave.rs`). + +use std::ffi::{CStr, c_char, c_void}; + +use crate::rt::{Guid, Hresult, Object, S_OK, area}; +use crate::tap::Tap; +use crate::xasync::{Block, wait}; + +const PROVIDER: Guid = Guid( + 0x704c_3f58, + 0xe629, + 0x4cc2, + [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], +); + +const E_GS_INVALID_CONTAINER_NAME: Hresult = 0x8083_0001_u32 as i32; +const E_GS_UPDATE_TOO_BIG: Hresult = 0x8083_0005_u32 as i32; + +type Handle = *mut c_void; + +/// XGameSaveBlob. +#[repr(C)] +struct Blob { + name: *const c_char, + size: u32, + data: *const u8, +} + +struct Saves(Object); + +impl Saves { + fn this(&self) -> *mut c_void { + self.0.this() + } + fn provider(&self) -> Result { + let mut block = Block::on_process_queue(); + // SAFETY: (all methods) the slot's signature in VIctory's table. + let begin: extern "system" fn( + *mut c_void, + *const c_void, + *const c_char, + bool, + *mut Block, + ) -> Hresult = unsafe { self.0.method(0x20) }; + let hr = begin( + self.this(), + std::ptr::null(), + c"conformance-scid".as_ptr(), + false, + &mut block, + ); + if hr != S_OK { + return Err(hr); + } + let hr = wait(&mut block); + if hr != S_OK { + return Err(hr); + } + let mut provider = std::ptr::null_mut(); + let result: extern "system" fn(*mut c_void, *mut Block, *mut Handle) -> Hresult = + unsafe { self.0.method(0x28) }; + match result(self.this(), &mut block, &mut provider) { + S_OK => Ok(provider), + hr => Err(hr), + } + } + fn close_provider(&self, p: Handle) { + let f: extern "system" fn(*mut c_void, Handle) = unsafe { self.0.method(0x30) }; + f(self.this(), p) + } + fn container(&self, p: Handle, name: &CStr) -> Result { + let mut out = std::ptr::null_mut(); + let f: extern "system" fn(*mut c_void, Handle, *const c_char, *mut Handle) -> Hresult = + unsafe { self.0.method(0x80) }; + match f(self.this(), p, name.as_ptr(), &mut out) { + S_OK => Ok(out), + hr => Err(hr), + } + } + fn close_container(&self, c: Handle) { + let f: extern "system" fn(*mut c_void, Handle) = unsafe { self.0.method(0x88) }; + f(self.this(), c) + } + /// Writes `blobs` in one update and submits it; the first failure. + fn update(&self, c: Handle, blobs: &[(&CStr, &[u8])]) -> Hresult { + let mut u = std::ptr::null_mut(); + let create: extern "system" fn(*mut c_void, Handle, *const c_char, *mut Handle) -> Hresult = + unsafe { self.0.method(0xb8) }; + let hr = create(self.this(), c, c"Conformance".as_ptr(), &mut u); + if hr != S_OK { + return hr; + } + let write: extern "system" fn( + *mut c_void, + Handle, + *const c_char, + *const u8, + usize, + ) -> Hresult = unsafe { self.0.method(0xc8) }; + let close: extern "system" fn(*mut c_void, Handle) = unsafe { self.0.method(0xc0) }; + for (name, data) in blobs { + let hr = write(self.this(), u, name.as_ptr(), data.as_ptr(), data.len()); + if hr != S_OK { + close(self.this(), u); + return hr; + } + } + let mut block = Block::on_process_queue(); + let submit: extern "system" fn(*mut c_void, Handle, *mut Block) -> Hresult = + unsafe { self.0.method(0xe0) }; + let result: extern "system" fn(*mut c_void, *mut Block) -> Hresult = + unsafe { self.0.method(0xe8) }; + let mut hr = submit(self.this(), u, &mut block); + if hr == S_OK { + wait(&mut block); + hr = result(self.this(), &mut block); + } + close(self.this(), u); + hr + } + /// Reads `names`; each blob's bytes, or the failure. + fn read(&self, c: Handle, names: &[&CStr]) -> Result>, Hresult> { + let pointers: Vec<*const c_char> = names.iter().map(|n| n.as_ptr()).collect(); + let mut count = names.len() as u32; + let mut buffer = vec![0u64; (1 << 20) / 8]; + let f: extern "system" fn( + *mut c_void, + Handle, + *const *const c_char, + *mut u32, + usize, + *mut u8, + ) -> Hresult = unsafe { self.0.method(0xa0) }; + let hr = f( + self.this(), + c, + pointers.as_ptr(), + &mut count, + buffer.len() * 8, + buffer.as_mut_ptr().cast(), + ); + if hr != S_OK { + return Err(hr); + } + let blobs = buffer.as_ptr().cast::(); + Ok((0..count as usize) + .map(|i| { + // SAFETY: the call wrote `count` blobs whose data lies in the buffer. + unsafe { + let b = &*blobs.add(i); + std::slice::from_raw_parts(b.data, b.size as usize).to_vec() + } + }) + .collect()) + } +} + +pub fn run(t: &mut Tap) { + let saves = match area(PROVIDER, PROVIDER) { + Ok(object) => Saves(object), + Err(hr) => { + t.check(false, "xgamesave: the game-save area is served", || { + format!("QueryApiImpl {hr:#010x}") + }); + return; + } + }; + let provider = match saves.provider() { + Ok(p) => p, + Err(hr) => { + t.check( + false, + "xgamesave: XGameSaveInitializeProviderAsync succeeds", + || format!("{hr:#010x}"), + ); + return; + } + }; + t.check( + true, + "xgamesave: XGameSaveInitializeProviderAsync succeeds", + String::new, + ); + t.eq( + saves.container(provider, c"bad name*").err(), + Some(E_GS_INVALID_CONTAINER_NAME), + "xgamesave: a container name with forbidden characters is E_GS_INVALID_CONTAINER_NAME", + ); + let container = match saves.container(provider, c"conformance/slot_1") { + Ok(c) => c, + Err(hr) => { + t.check( + false, + "xgamesave: a container with letters, digits, _ and / opens", + || format!("{hr:#010x}"), + ); + return; + } + }; + t.check( + true, + "xgamesave: a container with letters, digits, _ and / opens", + String::new, + ); + + let a: Vec = (0..1024u32).map(|i| i as u8).collect(); + let b: Vec = (0..2048u32).map(|i| (i * 7) as u8).collect(); + t.eq( + saves.update(container, &[(c"a", &a), (c"b", &b)]), + S_OK, + "xgamesave: an update of two blobs submits", + ); + t.eq( + saves.read(container, &[c"a", c"b"]).ok(), + Some(vec![a.clone(), b.clone()]), + "xgamesave: both blobs read back", + ); + + // Over 16 MB in one update: refused, and nothing of it lands. + let big = vec![0x5au8; 9 << 20]; + let hr = saves.update( + container, + &[(c"a", &[1, 2, 3]), (c"big1", &big), (c"big2", &big)], + ); + t.eq( + hr, + E_GS_UPDATE_TOO_BIG, + "xgamesave: an update over 16 MB is E_GS_UPDATE_TOO_BIG", + ); + t.eq( + saves.read(container, &[c"a", c"b"]).ok(), + Some(vec![a.clone(), b]), + "xgamesave: a refused update changes nothing (all or nothing)", + ); + t.check( + saves.read(container, &[c"big1"]).is_err(), + "xgamesave: ... and none of its blobs exist", + || "big1 exists".into(), + ); + // Exactly 16 MB is allowed. + let limit = vec![0xa5u8; 16 << 20]; + t.eq( + saves.update(container, &[(c"limit", &limit)]), + S_OK, + "xgamesave: an update of exactly 16 MB submits", + ); + saves.close_container(container); + + // A second container handle sees what the first one committed. + match saves.container(provider, c"conformance/slot_1") { + Ok(again) => { + t.eq( + saves.read(again, &[c"a"]).ok(), + Some(vec![a]), + "xgamesave: a reopened container has its committed blobs", + ); + saves.close_container(again); + } + Err(hr) => t.check( + false, + "xgamesave: a reopened container has its committed blobs", + || format!("{hr:#010x}"), + ), + } + saves.close_provider(provider); +} diff --git a/tests/fixtures/conformance/src/xmem.rs b/tests/fixtures/conformance/src/xmem.rs new file mode 100644 index 0000000000..960b86b649 --- /dev/null +++ b/tests/fixtures/conformance/src/xmem.rs @@ -0,0 +1,132 @@ +//! Console memory: physical pages mapped at more than one address. +//! +//! XMem's reference pages are not public, so these checks are invariants, +//! not documented answers: the same 64 KiB physical pages mapped at two +//! addresses show the same bytes, and an unmapped range is gone. The +//! constants and signatures are VIctory's (`crates/victory-hle/src/modules/ +//! xmem.rs`); `MEM_RESERVE` and `PAGE_READWRITE` are Win32's. + +use std::ffi::c_void; + +use crate::tap::Tap; + +const PAGE: usize = 64 << 10; +const MEM_RESERVE: u32 = 0x2000; +const PAGE_READWRITE: u32 = 4; +/// 64 KiB pages (VIctory's `PAGES_64K`). +const PAGES_64K: u32 = 0x2000_0000 | 0x40_0000; + +#[link(name = "xmem", kind = "raw-dylib")] +unsafe extern "system" { + fn XMemAllocatePhysicalPages(flags: u64, count: *mut usize, pages: *mut usize) -> i32; + fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> i32; + fn XMemMapPhysicalPages(address: *mut c_void, n: usize, pages: *const usize) -> *mut c_void; + fn XMemVirtualAlloc( + base: *mut c_void, + size: usize, + kind: u32, + flags: u64, + protect: u32, + ) -> *mut c_void; +} + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + fn VirtualFree(address: *mut c_void, size: usize, kind: u32) -> i32; + fn VirtualQuery(address: *const c_void, info: *mut [usize; 6], size: usize) -> usize; +} + +pub fn run(t: &mut Tap) { + let mut pages = [0usize; 4]; + let mut n = pages.len(); + // SAFETY: (all calls) room for `n` page numbers; reservations we made. + unsafe { + let ok = XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()); + t.check( + ok != 0 && n == 4, + "xmem: four physical pages are allocated", + || format!("ok {ok}, n {n}"), + ); + if ok == 0 { + return; + } + let reserve = || { + XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ) + }; + let (a, b) = (reserve(), reserve()); + t.check( + !a.is_null() && !b.is_null(), + "xmem: 64 KiB-page reservations are made", + || format!("{a:?} {b:?}"), + ); + if a.is_null() || b.is_null() { + XMemFreePhysicalPages(n, pages.as_ptr()); + return; + } + t.eq( + XMemMapPhysicalPages(a, 4, pages.as_ptr()), + a, + "xmem: pages map at the first address", + ); + // The second mapping takes the pages in another order. + let reversed: Vec = pages.iter().rev().copied().collect(); + t.eq( + XMemMapPhysicalPages(b, 4, reversed.as_ptr()), + b, + "xmem: the same pages map at a second address", + ); + let at = |base: *mut c_void, page: usize, offset: usize| { + base.cast::().add(page * PAGE + offset) + }; + for page in 0..4 { + at(a, page, 123).write_volatile(0x40 + page as u8); + } + let seen: Vec = (0..4) + .map(|page| at(b, 3 - page, 123).read_volatile()) + .collect(); + t.eq( + seen, + vec![0x40, 0x41, 0x42, 0x43], + "xmem: a write through one mapping reads back through the other", + ); + at(b, 0, PAGE - 1).write_volatile(0x77); + t.eq( + at(a, 3, PAGE - 1).read_volatile(), + 0x77, + "xmem: ... in both directions, to a page's last byte", + ); + // Unmapping (no page list) leaves the range without memory. + t.eq( + XMemMapPhysicalPages(b, 4, std::ptr::null()), + b, + "xmem: a range unmaps", + ); + let mut info = [0usize; 6]; + VirtualQuery(b, &mut info, size_of_val(&info)); + // MEMORY_BASIC_INFORMATION.State (offset 32): MEM_COMMIT is 0x1000. + t.check( + (info[4] & 0xffff_ffff) != 0x1000, + "xmem: an unmapped range is not committed memory", + || format!("state {:#x}", info[4] & 0xffff_ffff), + ); + t.eq( + at(a, 2, 123).read_volatile(), + 0x42, + "xmem: the other mapping keeps its bytes", + ); + XMemMapPhysicalPages(a, 4, std::ptr::null()); + t.check( + XMemFreePhysicalPages(n, pages.as_ptr()) != 0, + "xmem: physical pages are freed", + || "refused".into(), + ); + VirtualFree(a, 0, 0x8000); + VirtualFree(b, 0, 0x8000); + } +} diff --git a/tests/fixtures/conformance/src/xsystem.rs b/tests/fixtures/conformance/src/xsystem.rs new file mode 100644 index 0000000000..329976a858 --- /dev/null +++ b/tests/fixtures/conformance/src/xsystem.rs @@ -0,0 +1,126 @@ +//! System information. +//! +//! Public reference: reference/system/xsystem (XSystemGetConsoleId, +//! XSystemGetAnalyticsInfo, XSystemAnalyticsInfo). + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, S_OK, area}; +use crate::tap::Tap; + +/// VIctory's `xsystem::PROVIDER` and `IID`, and its analytics area. +const PROVIDER: Guid = Guid( + 0xe349_bd1a, + 0xfc20, + 0x4e40, + [0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f], +); +const IID: Guid = Guid( + 0x6fd7_1f09, + 0x7513, + 0x49f0, + [0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52], +); +const ANALYTICS: Guid = Guid( + 0xb884_675d, + 0xb738, + 0x4a9c, + [0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b], +); + +/// HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER). +const INSUFFICIENT_BUFFER: Hresult = 0x8007_007A_u32 as i32; + +/// "In RETAIL, this function will always return +/// 00000000.00000000.00000000.00000000.00" (XSystemGetConsoleId). +const RETAIL_CONSOLE_ID: &str = "00000000.00000000.00000000.00000000.00"; + +/// XVersion. +#[repr(C)] +#[derive(Clone, Copy)] +struct Version { + major: u16, + minor: u16, + build: u16, + revision: u16, +} + +/// XSystemAnalyticsInfo. +#[repr(C)] +struct AnalyticsInfo { + os: Version, + hosting_os: Version, + family: [u8; 64], + form: [u8; 64], +} + +fn text(bytes: &[u8]) -> String { + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).into_owned() +} + +pub fn run(t: &mut Tap) { + match area(ANALYTICS, ANALYTICS) { + Ok(object) => { + let mut info = std::mem::MaybeUninit::::zeroed(); + // SAFETY: the slot's signature in VIctory's table (the struct is + // returned through a hidden pointer, as the ABI does for it). + let get: extern "system" fn(*mut c_void, *mut AnalyticsInfo) -> *mut AnalyticsInfo = + unsafe { object.method(0x18) }; + get(object.this(), info.as_mut_ptr()); + // SAFETY: written by the call (zeroed before). + let info = unsafe { info.assume_init() }; + t.eq( + text(&info.family).as_str(), + "Xbox", + "xsystem: analytics family is \"Xbox\" on a console", + ); + t.check( + !text(&info.form).is_empty(), + "xsystem: analytics form names the hardware", + || "empty".into(), + ); + t.check( + info.os.major != 0 || info.os.build != 0, + "xsystem: analytics OS version is set", + || "zero".into(), + ); + let _ = info.hosting_os; + } + Err(hr) => t.check(false, "xsystem: the analytics area is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } + + match area(PROVIDER, IID) { + Ok(object) => { + // SAFETY: the slot's signature in VIctory's table. + let get: extern "system" fn(*mut c_void, usize, *mut u8, *mut usize) -> Hresult = + unsafe { object.method(0x18) }; + let mut buffer = [0u8; 64]; + let mut used = 0; + let hr = get(object.this(), buffer.len(), buffer.as_mut_ptr(), &mut used); + t.eq(hr, S_OK, "xsystem: XSystemGetConsoleId succeeds"); + t.eq( + text(&buffer).as_str(), + RETAIL_CONSOLE_ID, + "xsystem: a retail console id is the documented zero id", + ); + t.eq( + used, + RETAIL_CONSOLE_ID.len() + 1, + "xsystem: ... and its size counts the NUL", + ); + let mut short = [0u8; 8]; + let hr = get(object.this(), short.len(), short.as_mut_ptr(), &mut used); + t.eq( + hr, + INSUFFICIENT_BUFFER, + "xsystem: a short console id buffer is ERROR_INSUFFICIENT_BUFFER", + ); + } + Err(hr) => t.check(false, "xsystem: the system area is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } +} From 48febf8ee215a2ebf9996026fd60d6049bcc2b37 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:08:18 -0500 Subject: [PATCH 02/11] Tests: the conformance title covers users, files, storage, network, package, HDR The conformance title (tests/fixtures/conformance) now runs 143 checks through VIctory, each from Microsoft's public reference: - the user: silent default user added twice is the same user, handle duplication and comparison, local and network ids found back, state, age group, privileges, gamertag components within their documented sizes and the short-buffer error; - DirectStorage from files: raw reads at an offset, zlib at 16-byte aligned offsets, a missing file refused; - files on the console's drives (package at G:, temporary storage at T:) through every path-taking import VIctory binds: CreateFileW/-A/2, attributes, FindFirstFileW, fopen, _wfopen, _wstat64, directories, writes, MoveFileExW, deletes, and Win32's errors for missing paths; - persistent local storage: the path and its size, consistent space figures within the declared quota, a written file counted as used; - networking hints and the documented default UDP port (sync and async), XPackageIsPackagedProcess and the identifier, HDR mode results. 139 pass. Two more answers differ from the reference and join the list in the test: XUserFindUserByLocalId of no user returns E_GAMEUSER_USER_NOT_FOUND (the reference: HRESULT_FROM_WIN32 (ERROR_NOT_FOUND)), and XUserGetGamertag answers an invalid component with the gamertag (the reference: E_INVALIDARG). The harness mounts G: and T: and makes the storage folder, as `victory run` does. --- crates/victory-hle/tests/conformance.rs | 24 ++ docs/acceptance.md | 14 +- tests/fixtures/conformance/src/dstorage.rs | 116 ++++++- tests/fixtures/conformance/src/files.rs | 367 +++++++++++++++++++++ tests/fixtures/conformance/src/lib.rs | 8 + tests/fixtures/conformance/src/pls.rs | 112 +++++++ tests/fixtures/conformance/src/system.rs | 189 +++++++++++ tests/fixtures/conformance/src/xuser.rs | 294 +++++++++++++++++ 8 files changed, 1119 insertions(+), 5 deletions(-) create mode 100644 tests/fixtures/conformance/src/files.rs create mode 100644 tests/fixtures/conformance/src/pls.rs create mode 100644 tests/fixtures/conformance/src/system.rs create mode 100644 tests/fixtures/conformance/src/xuser.rs diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index 10191cb304..2a578aaad9 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -24,6 +24,14 @@ const KNOWN: &[(&str, &str)] = &[ "VIctory submits once half the capacity is enqueued; the overview \ says an Enqueue that fills more than half submits", ), + ( + "xuser: XUserFindUserByLocalId of no user is HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", + "VIctory returns E_GAMEUSER_USER_NOT_FOUND (0x89245104); the XUserFindUserByLocalId page gives HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", + ), + ( + "xuser: an invalid gamertag component is E_INVALIDARG", + "VIctory answers any component other than ModernSuffix with the gamertag; the XUserGetGamertag page gives E_INVALIDARG", + ), ]; fn workspace_root() -> PathBuf { @@ -63,12 +71,28 @@ fn call(name: &str) -> String { // Persistent local storage (game saves live beside it), as `victory // run` gives a title. let data = tempfile::tempdir().unwrap().keep(); + // `victory run` makes the folder before the title starts. + std::fs::create_dir_all(data.join("storage")).unwrap(); victory_hle::runtime::set_title(victory_hle::runtime::Title { id: 0x1234_5678, storage: data.join("storage"), storage_bytes: 64 << 20, ..Default::default() }); + // The console's drives: the package at G: (holding the file the + // title checks), temporary storage at T:. + let package = data.join("package"); + std::fs::create_dir_all(&package).unwrap(); + std::fs::write( + package.join("conformance.txt"), + b"conformance: public documentation only +", + ) + .unwrap(); + let temp = data.join("temp"); + std::fs::create_dir_all(&temp).unwrap(); + victory_hle::modules::files::mount_at('G', &package); + victory_hle::modules::files::mount_at('T', &temp); let resolver = HleResolver::new(HostPolicy::default()); let report = image .bind_imports(&resolver, UnimplementedPolicy::ReturnZero) diff --git a/docs/acceptance.md b/docs/acceptance.md index 474c8b079b..14ccb29e24 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -102,19 +102,27 @@ rather than failed; one of them passing fails the test, so the list stays true. `-- --ignored` runs the workloads. Covered so far: runtime initialisation, task queues and async calls, -system information, physical-page aliasing, DirectStorage (memory sources) -and game saves: 82 checks, 80 pass. The two divergences found: +system information, physical-page aliasing, DirectStorage (memory and file +sources), game saves, the user, networking hints, the package, HDR mode, +files on the console's `G:` and `T:` drives through every path import +VIctory binds, and persistent local storage: 143 checks, 139 pass. The +four divergences found: | Check | Reference | VIctory | |---|---|---| | `XSystemGetConsoleId` on retail | `00000000.00000000.00000000.00000000.00` | 38 digits ending in 1 | | DirectStorage automatic submission | when an Enqueue fills more than half the capacity | at half the capacity | +| `XUserFindUserByLocalId`, no such user | `HRESULT_FROM_WIN32(ERROR_NOT_FOUND)` | `E_GAMEUSER_USER_NOT_FOUND` (0x89245104) | +| `XUserGetGamertag`, invalid component | `E_INVALIDARG` | the gamertag | Gaps seen while writing them (documented features VIctory's tables leave unimplemented, not yet tested): DirectStorage cancel by tag and the error event and record; the documented request limits (32 MiB destination, 16-byte offsets for compressed sources), whose behaviour when broken the reference -does not state. +does not state. System dialogs: text entry opens a real host dialog, which +an unattended test cannot answer; the message and error dialogs, and +thread time-sensitivity (`XThreadSetTimeSensitive`), are unimplemented +slots in VIctory's tables. The streaming workload so far reads from memory only (no file source), with synthetic data that compresses about 3.5:1; on an RTX 5070 Ti machine diff --git a/tests/fixtures/conformance/src/dstorage.rs b/tests/fixtures/conformance/src/dstorage.rs index e7cf2422b3..4dd8c49b37 100644 --- a/tests/fixtures/conformance/src/dstorage.rs +++ b/tests/fixtures/conformance/src/dstorage.rs @@ -29,7 +29,9 @@ const FACTORY: Guid = Guid( ); const E_PENDING: Hresult = 0x8000_000A_u32 as i32; +const SOURCE_FILE: u64 = 0; const SOURCE_MEMORY: u64 = 1; +const PRIORITY_NORMAL: i8 = 0; const PRIORITY_REALTIME: i8 = 2; /// Request options: inflate zlib; the source is an address. const ZLIB: u64 = 1; @@ -132,10 +134,13 @@ impl Storage { Com(out) } fn queue(&self, capacity: u16) -> Com { + self.queue_of(SOURCE_MEMORY, PRIORITY_REALTIME, capacity) + } + fn queue_of(&self, source_type: u64, priority: i8, capacity: u16) -> Com { let desc = QueueDesc { - source_type: SOURCE_MEMORY, + source_type, capacity, - priority: PRIORITY_REALTIME, + priority, name: c"conformance".as_ptr().cast(), unknown: 0, }; @@ -151,6 +156,112 @@ impl Storage { } } +impl Storage { + /// IDStorageFactoryX::OpenFile. + fn open(&self, path: &std::path::Path) -> Result { + use std::os::windows::ffi::OsStrExt; + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + let mut out = std::ptr::null_mut(); + // SAFETY: the slot's signature in VIctory's table. + let f: extern "system" fn( + *mut c_void, + *const u16, + *const Guid, + *mut *mut c_void, + ) -> Hresult = unsafe { self.factory.method(0x20) }; + match f(self.factory.0, wide.as_ptr(), std::ptr::null(), &mut out) { + S_OK if !out.is_null() => Ok(Com(out)), + S_OK => Err(-1), + hr => Err(hr), + } + } +} + +/// A request reading `size` bytes of `file` at `offset`. +fn from_file(options: u64, file: Com, offset: u64, size: usize, destination: &mut [u8]) -> Request { + Request { + options, + destination: destination.as_mut_ptr().cast(), + page_offset: 0, + destination_size: destination.len() as u32, + source: file.0, + offset, + source_size: size as u32, + intermediate_size: 0, + tag: 0, + name: std::ptr::null(), + } +} + +/// File sources: raw reads at an offset, zlib at a 16-byte aligned offset +/// (the overview: FileOffset must be 16-byte aligned for compressed data), +/// and a missing file refused. +fn files(t: &mut Tap, s: &Storage, array: Com) { + let plain = pattern(300_000, 7); + let packed = miniz_oxide::deflate::compress_to_vec_zlib(&plain, 6); + let mut contents = plain.clone(); + contents.resize(contents.len().next_multiple_of(16), 0); + let zlib_at = contents.len() as u64; + contents.extend_from_slice(&packed); + let path = std::env::temp_dir().join(format!("victory-conformance-{}.bin", std::process::id())); + if let Err(e) = std::fs::write(&path, &contents) { + t.check(false, "dstorage: a test file is written", || e.to_string()); + return; + } + let file = match s.open(&path) { + Ok(f) => f, + Err(hr) => { + t.check( + false, + "dstorage: IDStorageFactoryX::OpenFile opens a file", + || format!("{hr:#010x}"), + ); + let _ = std::fs::remove_file(&path); + return; + } + }; + t.check( + true, + "dstorage: IDStorageFactoryX::OpenFile opens a file", + String::new, + ); + let q = s.queue_of(SOURCE_FILE, PRIORITY_NORMAL, 32); + let mut raw = vec![0u8; 1000]; + let mut inflated = vec![0u8; plain.len()]; + enqueue(q, &from_file(0, file, 5000, 1000, &mut raw)); + enqueue( + q, + &from_file(ZLIB, file, zlib_at, packed.len(), &mut inflated), + ); + enqueue_status(q, array, 13); + submit(q); + t.eq( + wait(array, 13, 5000), + S_OK, + "dstorage: file-sourced requests complete", + ); + t.check( + raw == plain[5000..6000], + "dstorage: a raw file read returns the bytes at its offset", + || "bytes differ".into(), + ); + t.check( + inflated == plain, + "dstorage: a zlib file read inflates to the original bytes", + || "bytes differ".into(), + ); + close(q); + q.release(); + file.release(); + let _ = std::fs::remove_file(&path); + let missing = std::env::temp_dir().join("victory-conformance-no-such-file.bin"); + t.check( + s.open(&missing).is_err(), + "dstorage: opening a missing file fails", + || "opened".into(), + ); +} + fn enqueue(q: Com, r: &Request) { let f: extern "system" fn(*mut c_void, *const Request) = unsafe { q.method(0x18) }; f(q.0, r) @@ -350,6 +461,7 @@ pub fn run(t: &mut Tap) { close(small); small.release(); q.release(); + files(t, &s, array); array.release(); } diff --git a/tests/fixtures/conformance/src/files.rs b/tests/fixtures/conformance/src/files.rs new file mode 100644 index 0000000000..fc2639f988 --- /dev/null +++ b/tests/fixtures/conformance/src/files.rs @@ -0,0 +1,367 @@ +//! Files on the console's drives: the package at `G:` (read-only), and +//! temporary storage at `T:`. +//! +//! The behaviour checked is Win32's and the CRT's (Microsoft Learn, +//! fileapi.h and the CRT reference), reached through the paths a console +//! title uses: every path-taking import VIctory binds (CreateFileW, -A, +//! CreateFile2, GetFileAttributes*, FindFirstFile*, DeleteFileW, +//! MoveFileExW, CreateDirectoryW, RemoveDirectoryW, fopen, _wfopen, +//! _wstat64) must reach the folder behind the drive letter. The harness +//! mounts both drives; `G:\conformance.txt` holds `CONTENTS`. + +use std::ffi::c_void; + +use crate::tap::Tap; + +pub const CONTENTS: &[u8] = b"conformance: public documentation only\n"; + +const GENERIC_READ: u32 = 0x8000_0000; +const GENERIC_WRITE: u32 = 0x4000_0000; +const FILE_SHARE_READ: u32 = 1; +const CREATE_ALWAYS: u32 = 2; +const OPEN_EXISTING: u32 = 3; +const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; +const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10; +const ERROR_FILE_NOT_FOUND: u32 = 2; +const ERROR_PATH_NOT_FOUND: u32 = 3; +const MOVEFILE_REPLACE_EXISTING: u32 = 1; +const INVALID_HANDLE: *mut c_void = -1isize as *mut c_void; + +#[repr(C)] +struct FindData { + attributes: u32, + times: [u32; 6], + size_high: u32, + size_low: u32, + reserved: [u32; 2], + name: [u16; 260], + alternate: [u16; 14], + // Obsolete fields some headers declare; room for them. + _rest: [u32; 4], +} + +/// _stat64: the fields we read, and room for the rest. +#[repr(C)] +struct Stat64 { + dev: u32, + ino: u16, + mode: u16, + nlink: i16, + uid: i16, + gid: i16, + rdev: u32, + size: i64, + times: [i64; 3], +} + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + fn CreateFileW( + name: *const u16, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: *mut c_void, + ) -> *mut c_void; + fn CreateFileA( + name: *const u8, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: *mut c_void, + ) -> *mut c_void; + fn CreateFile2( + name: *const u16, + access: u32, + share: u32, + disposition: u32, + params: *const c_void, + ) -> *mut c_void; + fn ReadFile( + file: *mut c_void, + buffer: *mut u8, + size: u32, + read: *mut u32, + overlapped: *mut c_void, + ) -> i32; + fn WriteFile( + file: *mut c_void, + buffer: *const u8, + size: u32, + written: *mut u32, + overlapped: *mut c_void, + ) -> i32; + fn CloseHandle(handle: *mut c_void) -> i32; + fn GetFileAttributesW(name: *const u16) -> u32; + fn GetFileAttributesA(name: *const u8) -> u32; + fn FindFirstFileW(name: *const u16, data: *mut FindData) -> *mut c_void; + fn FindClose(find: *mut c_void) -> i32; + fn DeleteFileW(name: *const u16) -> i32; + fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32; + fn CreateDirectoryW(name: *const u16, security: *const c_void) -> i32; + fn RemoveDirectoryW(name: *const u16) -> i32; + fn GetLastError() -> u32; +} + +#[link(name = "ucrtbase", kind = "raw-dylib")] +unsafe extern "C" { + fn fopen(name: *const u8, mode: *const u8) -> *mut c_void; + fn _wfopen(name: *const u16, mode: *const u16) -> *mut c_void; + fn fread(buffer: *mut u8, size: usize, count: usize, file: *mut c_void) -> usize; + fn fclose(file: *mut c_void) -> i32; + fn _wstat64(name: *const u16, stat: *mut Stat64) -> i32; +} + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() +} + +fn narrow(s: &str) -> Vec { + s.bytes().chain(Some(0)).collect() +} + +/// Reads all of an open handle (closing it). +/// +/// # Safety +/// A file handle open for reading. +unsafe fn read_all(file: *mut c_void) -> Vec { + let mut out = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + let mut n = 0; + // SAFETY: (caller) an open handle; our buffer. + let ok = unsafe { + ReadFile( + file, + buffer.as_mut_ptr(), + buffer.len() as u32, + &mut n, + std::ptr::null_mut(), + ) + }; + if ok == 0 || n == 0 { + break; + } + out.extend_from_slice(&buffer[..n as usize]); + } + // SAFETY: (caller) ours to close. + unsafe { CloseHandle(file) }; + out +} + +pub fn run(t: &mut Tap) { + // SAFETY: (all calls) NUL-terminated paths; handles we opened. + unsafe { + let file = CreateFileW( + wide(r"G:\conformance.txt").as_ptr(), + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + t.check( + file != INVALID_HANDLE, + r"files: CreateFileW opens G:\conformance.txt", + || format!("error {}", GetLastError()), + ); + if file != INVALID_HANDLE { + t.eq( + read_all(file).as_slice(), + CONTENTS, + "files: ReadFile returns the package file's bytes", + ); + } + let file = CreateFileA( + narrow("G:/conformance.txt").as_ptr(), + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + t.check( + file != INVALID_HANDLE, + "files: CreateFileA opens the same file with forward slashes", + || format!("error {}", GetLastError()), + ); + if file != INVALID_HANDLE { + CloseHandle(file); + } + let file = CreateFile2( + wide(r"\\?\G:\conformance.txt").as_ptr(), + GENERIC_READ, + FILE_SHARE_READ, + OPEN_EXISTING, + std::ptr::null(), + ); + t.check( + file != INVALID_HANDLE, + r"files: CreateFile2 opens it as \\?\G:\...", + || format!("error {}", GetLastError()), + ); + if file != INVALID_HANDLE { + CloseHandle(file); + } + let missing = CreateFileW( + wide(r"G:\no-such-file").as_ptr(), + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + let error = GetLastError(); + t.check( + missing == INVALID_HANDLE && error == ERROR_FILE_NOT_FOUND, + "files: a missing file is INVALID_HANDLE_VALUE and ERROR_FILE_NOT_FOUND", + || format!("{missing:?} error {error}"), + ); + + t.eq( + GetFileAttributesW(wide(r"G:\conformance.txt").as_ptr()) & FILE_ATTRIBUTE_DIRECTORY, + 0, + "files: GetFileAttributesW sees a file", + ); + t.check( + GetFileAttributesA(narrow(r"G:\").as_ptr()) & FILE_ATTRIBUTE_DIRECTORY != 0, + r"files: GetFileAttributesA sees G:\ as a folder", + || "not a folder".into(), + ); + let attributes = GetFileAttributesW(wide(r"G:\no\such\file").as_ptr()); + let error = GetLastError(); + t.check( + attributes == INVALID_FILE_ATTRIBUTES + && (error == ERROR_PATH_NOT_FOUND || error == ERROR_FILE_NOT_FOUND), + "files: GetFileAttributesW of a missing path is INVALID_FILE_ATTRIBUTES", + || format!("{attributes:#x} error {error}"), + ); + + let mut data: FindData = std::mem::zeroed(); + let find = FindFirstFileW(wide(r"G:\conformance.*").as_ptr(), &mut data); + let name = String::from_utf16_lossy( + &data.name[..data.name.iter().position(|&c| c == 0).unwrap_or(0)], + ); + t.check( + find != INVALID_HANDLE + && name == "conformance.txt" + && data.size_low as usize == CONTENTS.len(), + "files: FindFirstFileW finds the file by pattern, with its size", + || format!("{find:?} {name:?} {}", data.size_low), + ); + if find != INVALID_HANDLE { + FindClose(find); + } + + let f = fopen( + narrow(r"G:\conformance.txt").as_ptr(), + narrow("rb").as_ptr(), + ); + t.check(!f.is_null(), "files: fopen opens the package file", || { + "null".into() + }); + if !f.is_null() { + let mut buffer = [0u8; 128]; + let n = fread(buffer.as_mut_ptr(), 1, buffer.len(), f); + t.eq(&buffer[..n], CONTENTS, "files: fread reads its bytes"); + fclose(f); + } + let f = _wfopen(wide(r"G:\conformance.txt").as_ptr(), wide("rb").as_ptr()); + t.check( + !f.is_null(), + "files: _wfopen opens the package file", + || "null".into(), + ); + if !f.is_null() { + fclose(f); + } + let mut stat: Stat64 = std::mem::zeroed(); + t.check( + _wstat64(wide(r"G:\conformance.txt").as_ptr(), &mut stat) == 0 + && stat.size as usize == CONTENTS.len(), + "files: _wstat64 gives the file's size", + || format!("size {}", stat.size), + ); + + // Temporary storage: make a folder, write, rename over, delete. + t.check( + CreateDirectoryW(wide(r"T:\conformance").as_ptr(), std::ptr::null()) != 0, + r"files: CreateDirectoryW makes T:\conformance", + || format!("error {}", GetLastError()), + ); + let path = wide(r"T:\conformance\a.bin"); + let file = CreateFileW( + path.as_ptr(), + GENERIC_WRITE, + 0, + std::ptr::null(), + CREATE_ALWAYS, + 0, + std::ptr::null_mut(), + ); + let mut written = 0; + let ok = file != INVALID_HANDLE + && WriteFile( + file, + CONTENTS.as_ptr(), + CONTENTS.len() as u32, + &mut written, + std::ptr::null_mut(), + ) != 0; + if file != INVALID_HANDLE { + CloseHandle(file); + } + t.check( + ok && written as usize == CONTENTS.len(), + "files: WriteFile writes a file on T:", + || format!("error {}", GetLastError()), + ); + let renamed = wide(r"T:\conformance\b.bin"); + t.check( + MoveFileExW(path.as_ptr(), renamed.as_ptr(), MOVEFILE_REPLACE_EXISTING) != 0, + "files: MoveFileExW renames it", + || format!("error {}", GetLastError()), + ); + t.eq( + GetFileAttributesW(path.as_ptr()), + INVALID_FILE_ATTRIBUTES, + "files: the old name is gone", + ); + let file = CreateFileW( + renamed.as_ptr(), + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + t.check( + file != INVALID_HANDLE && read_all(file) == CONTENTS, + "files: the new name has the bytes", + || "missing or different".into(), + ); + t.check( + DeleteFileW(renamed.as_ptr()) != 0, + "files: DeleteFileW deletes it", + || format!("error {}", GetLastError()), + ); + t.check( + RemoveDirectoryW(wide(r"T:\conformance").as_ptr()) != 0, + "files: RemoveDirectoryW removes the emptied folder", + || format!("error {}", GetLastError()), + ); + t.eq( + GetFileAttributesW(wide(r"T:\conformance").as_ptr()), + INVALID_FILE_ATTRIBUTES, + "files: the folder is gone", + ); + } +} diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs index 4e025bc148..42cd4e7024 100644 --- a/tests/fixtures/conformance/src/lib.rs +++ b/tests/fixtures/conformance/src/lib.rs @@ -18,12 +18,16 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] mod dstorage; +mod files; +mod pls; mod rt; +mod system; mod tap; mod xasync; mod xgamesave; mod xmem; mod xsystem; +mod xuser; /// Runs every test; returns the TAP report (valid until the next call). #[unsafe(no_mangle)] @@ -35,6 +39,10 @@ pub extern "system" fn conformance_run(len: *mut usize) -> *const u8 { xmem::run(&mut t); dstorage::run(&mut t); xgamesave::run(&mut t); + xuser::run(&mut t); + system::run(&mut t); + files::run(&mut t); + pls::run(&mut t); let report = t.finish(); // SAFETY: the harness passes room for the length. unsafe { len.write(report.len()) }; diff --git a/tests/fixtures/conformance/src/pls.rs b/tests/fixtures/conformance/src/pls.rs new file mode 100644 index 0000000000..2a1574b6cf --- /dev/null +++ b/tests/fixtures/conformance/src/pls.rs @@ -0,0 +1,112 @@ +//! Persistent local storage. +//! +//! Public reference: reference/system/xpersistentlocalstorage: +//! XPersistentLocalStorageGetPathSize, XPersistentLocalStorageGetPath (size, +//! buffer, used), XPersistentLocalStorageGetSpaceInfo filling +//! XPersistentLocalStorageSpaceInfo (availableFreeBytes, totalFreeBytes, +//! usedBytes, totalBytes). The title writes its own files under the path. +//! +//! The area's ids and slots are VIctory's (`crates/victory-hle/src/modules/ +//! storage.rs`). The harness gives the title a 64 MiB quota. + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, S_OK, area}; +use crate::tap::Tap; + +const PROVIDER: Guid = Guid( + 0xf4fa_f4d4, + 0x2d04, + 0x4fce, + [0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84], +); +const IID: Guid = Guid( + 0xd294_11df, + 0x0794, + 0x4553, + [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], +); + +/// XPersistentLocalStorageSpaceInfo. +#[repr(C)] +#[derive(Default, Debug, Clone, Copy)] +struct SpaceInfo { + available_free: u64, + total_free: u64, + used: u64, + total: u64, +} + +pub fn run(t: &mut Tap) { + let o = match area(PROVIDER, IID) { + Ok(o) => o, + Err(hr) => { + t.check( + false, + "pls: the persistent local storage area is served", + || format!("QueryApiImpl {hr:#010x}"), + ); + return; + } + }; + // SAFETY: (all slots) the signatures in VIctory's table. + let size_of: extern "system" fn(*mut c_void, *mut usize) -> Hresult = unsafe { o.method(0x18) }; + let path_of: extern "system" fn(*mut c_void, usize, *mut u8, *mut usize) -> Hresult = + unsafe { o.method(0x20) }; + let space_of: extern "system" fn(*mut c_void, *mut SpaceInfo) -> Hresult = + unsafe { o.method(0x28) }; + let mut size = 0; + t.eq( + size_of(o.this(), &mut size), + S_OK, + "pls: XPersistentLocalStorageGetPathSize succeeds", + ); + let mut buffer = vec![0u8; size.max(1)]; + let mut used = 0; + let hr = path_of(o.this(), buffer.len(), buffer.as_mut_ptr(), &mut used); + t.check( + hr == S_OK && used == size && buffer.last() == Some(&0), + "pls: XPersistentLocalStorageGetPath fills exactly the size it gave, NUL included", + || format!("{hr:#010x} used {used} size {size}"), + ); + let path = String::from_utf8_lossy(&buffer[..buffer.len().saturating_sub(1)]).into_owned(); + let mut before = SpaceInfo::default(); + t.eq( + space_of(o.this(), &mut before), + S_OK, + "pls: XPersistentLocalStorageGetSpaceInfo succeeds", + ); + t.check( + before.available_free <= before.total_free + && before.total_free <= before.total + && before.used <= before.total + && before.total > 0, + "pls: the space figures are consistent (available <= free <= total, used <= total)", + || format!("{before:?}"), + ); + t.check( + before.total <= 64 << 20, + "pls: the total is at most the title's declared quota", + || format!("{before:?}"), + ); + + // A file the title writes under its path is there, and counts. + let file = std::path::Path::new(&path).join("conformance.bin"); + let written = std::fs::write(&file, vec![0x5au8; 1 << 20]); + t.check( + written.is_ok(), + "pls: the title writes a file under its storage path", + || format!("{path:?}: {written:?}"), + ); + let back = std::fs::read(&file).map(|b| b.len()); + t.eq(back.ok(), Some(1 << 20), "pls: ... and reads it back"); + let mut after = SpaceInfo::default(); + space_of(o.this(), &mut after); + t.check( + after.used >= before.used + (1 << 20) + && after.total_free + (1 << 20) <= before.total_free + 4096, + "pls: a 1 MiB file adds to the used bytes and takes from the free ones", + || format!("before {before:?}, after {after:?}"), + ); + let _ = std::fs::remove_file(&file); +} diff --git a/tests/fixtures/conformance/src/system.rs b/tests/fixtures/conformance/src/system.rs new file mode 100644 index 0000000000..65e91c3fd3 --- /dev/null +++ b/tests/fixtures/conformance/src/system.rs @@ -0,0 +1,189 @@ +//! Networking hints, the package and HDR display mode. +//! +//! Public reference: +//! - reference/networking/xnetworking: XNetworkingConnectivityHint (level, +//! cost, IANA interface type, networkInitialized, three flags); levels +//! Unknown 0 to ConstrainedInternetAccess 4, costs Unknown 0 to Variable 3; +//! the preferred local UDP multiplayer port "defaults to UDP 3074". +//! - reference/system/xpackage: XPackageIsPackagedProcess is true for a +//! process with an installation identity; the identifier is a string. +//! - reference/system/xdisplay: XDisplayTryEnableHdrMode returns Unknown 0, +//! Enabled 1 or Disabled 2; enabled, its info defaults to 0.01, 1000 and +//! 1000 nits. +//! +//! The areas' ids and method slots are VIctory's (`xnetworking.rs`, +//! `xpackage.rs`, `display.rs` in `crates/victory-hle/src/modules/`). + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, S_OK, area}; +use crate::tap::Tap; +use crate::xasync::{Block, wait}; + +const NETWORKING: Guid = Guid( + 0x37e5_6907, + 0x2f10, + 0x41e8, + [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], +); +const PACKAGE: Guid = Guid( + 0xaf40_6016, + 0xe850, + 0x4aa8, + [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], +); +const PACKAGE_IID: Guid = Guid( + 0x0b9d_556e, + 0xab70, + 0x43f4, + [0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40], +); +const HDR: Guid = Guid( + 0x03f0_fe74, + 0xfdd9, + 0x4e5c, + [0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5], +); +const HDR_IID: Guid = Guid( + 0x35f0_7670, + 0x706e, + 0x4bfb, + [0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3], +); + +/// XNetworkingConnectivityHint. +#[repr(C)] +#[derive(Default, Debug)] +struct Hint { + level: u32, + cost: u32, + iana_interface_type: u32, + network_initialized: bool, + approaching_data_limit: bool, + over_data_limit: bool, + roaming: bool, +} + +/// XDisplayHdrModeInfo. +#[repr(C)] +#[derive(Default, Debug, PartialEq)] +struct HdrInfo { + min_tone_map_luminance: f32, + max_tone_map_luminance: f32, + max_full_frame_tone_map_luminance: f32, +} + +pub fn run(t: &mut Tap) { + match area(NETWORKING, NETWORKING) { + Ok(o) => { + let mut hint = Hint::default(); + // SAFETY: (all slots) the signatures in VIctory's tables. + let get: extern "system" fn(*mut c_void, *mut Hint) -> Hresult = + unsafe { o.method(0x78) }; + t.eq( + get(o.this(), &mut hint), + S_OK, + "xnetworking: XNetworkingGetConnectivityHint succeeds", + ); + t.check( + hint.network_initialized, + "xnetworking: the hint says the network is initialised", + || format!("{hint:?}"), + ); + t.check( + hint.level <= 4 && hint.cost <= 3, + "xnetworking: the level and cost hints are documented values", + || format!("{hint:?}"), + ); + let mut port = 0u16; + let sync: extern "system" fn(*mut c_void, *mut u16) -> Hresult = + unsafe { o.method(0x18) }; + t.eq( + (sync(o.this(), &mut port), port), + (S_OK, 3074), + "xnetworking: the preferred local UDP multiplayer port is the documented default 3074", + ); + let mut block = Block::on_process_queue(); + let begin: extern "system" fn(*mut c_void, *mut Block) -> Hresult = + unsafe { o.method(0x20) }; + let result: extern "system" fn(*mut c_void, *mut Block, *mut u16) -> Hresult = + unsafe { o.method(0x28) }; + let mut port = 0u16; + let hr = begin(o.this(), &mut block); + if hr == S_OK { + wait(&mut block); + } + t.eq( + (hr, result(o.this(), &mut block, &mut port), port), + (S_OK, S_OK, 3074), + "xnetworking: the async port query gives the same port", + ); + } + Err(hr) => t.check(false, "xnetworking: the networking area is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } + + match area(PACKAGE, PACKAGE_IID) { + Ok(o) => { + let packaged: extern "system" fn(*mut c_void) -> bool = unsafe { o.method(0x20) }; + t.eq( + packaged(o.this()), + true, + "xpackage: XPackageIsPackagedProcess is true for an installed title", + ); + let id: extern "system" fn(*mut c_void, usize, *mut u8) -> Hresult = + unsafe { o.method(0x18) }; + let mut buffer = [0u8; 128]; + let hr = id(o.this(), buffer.len(), buffer.as_mut_ptr()); + let len = buffer.iter().position(|&b| b == 0); + t.check( + hr == S_OK && len.is_some_and(|n| n > 0), + "xpackage: the package identifier is a non-empty string", + || format!("{hr:#010x} {len:?}"), + ); + let mut short = [0u8; 1]; + t.check( + id(o.this(), short.len(), short.as_mut_ptr()) != S_OK, + "xpackage: an identifier buffer too small for it is refused", + || "accepted".into(), + ); + } + Err(hr) => t.check(false, "xpackage: the package area is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } + + match area(HDR, HDR_IID) { + Ok(o) => { + let mut info = HdrInfo::default(); + let try_enable: extern "system" fn(*mut c_void, u32, *mut HdrInfo) -> u32 = + unsafe { o.method(0x20) }; + let result = try_enable(o.this(), 0, &mut info); + t.check( + result == 1 || result == 2, + "xdisplay: XDisplayTryEnableHdrMode says Enabled or Disabled", + || format!("{result}"), + ); + if result == 1 { + t.eq( + info, + HdrInfo { + min_tone_map_luminance: 0.01, + max_tone_map_luminance: 1000.0, + max_full_frame_tone_map_luminance: 1000.0, + }, + "xdisplay: enabled HDR reports the documented default luminances", + ); + } + t.check( + (try_enable(o.this(), 1, std::ptr::null_mut()) as i32) <= 2, + "xdisplay: the mode info is optional", + || "out of range".into(), + ); + } + Err(hr) => t.check(false, "xdisplay: the HDR area is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } +} diff --git a/tests/fixtures/conformance/src/xuser.rs b/tests/fixtures/conformance/src/xuser.rs new file mode 100644 index 0000000000..b96e601752 --- /dev/null +++ b/tests/fixtures/conformance/src/xuser.rs @@ -0,0 +1,294 @@ +//! The signed-in user. +//! +//! Public reference: reference/system/xuser: XUserAddOptions (None 0, +//! AddDefaultUserSilently 1); a known default user added silently again "will +//! return that same user"; XUserCompare "Returns 0 if the handles are for the +//! same user"; XUserGetGamertag components (Classic 0, Modern 1, +//! ModernSuffix 2, UniqueModern 3) with sizes including the NUL of 16, 97, +//! 15 and 101 bytes, E_INSUFFICIENT_BUFFER for a short buffer, E_INVALIDARG +//! for an invalid component; XUserFindUserByLocalId: no such user is +//! HRESULT_FROM_WIN32(ERROR_NOT_FOUND); XUserState (SignedIn 0); XUserAgeGroup +//! (Unknown 0 to Adult 3). +//! +//! The area's ids and method slots are VIctory's (`crates/victory-hle/src/ +//! modules/xuser.rs`). + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, Object, S_OK, area}; +use crate::tap::Tap; +use crate::xasync::{Block, wait}; + +const PROVIDER: Guid = Guid( + 0x01ac_d177, + 0x91f9, + 0x4763, + [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0], +); +const IID: Guid = Guid( + 0xeb9b_f948, + 0x18dc, + 0x4d82, + [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0], +); +const GAMERTAG_IID: Guid = Guid( + 0xcef4_fac0, + 0x7676, + 0x4a94, + [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74], +); + +const ADD_DEFAULT_USER_SILENTLY: u32 = 1; +/// E_INSUFFICIENT_BUFFER, HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER). +const E_INSUFFICIENT_BUFFER: Hresult = 0x8007_007A_u32 as i32; +const E_INVALIDARG: Hresult = 0x8007_0057_u32 as i32; +/// HRESULT_FROM_WIN32(ERROR_NOT_FOUND). +const NOT_FOUND: Hresult = 0x8007_0490_u32 as i32; +/// Gamertag components and their sizes including the NUL. +const COMPONENTS: [(u32, usize, &str); 4] = [ + (0, 16, "Classic"), + (1, 97, "Modern"), + (2, 15, "ModernSuffix"), + (3, 101, "UniqueModern"), +]; + +type User = *mut c_void; + +struct Users(Object); + +impl Users { + fn this(&self) -> *mut c_void { + self.0.this() + } + fn add(&self, options: u32) -> Result { + let mut block = Block::on_process_queue(); + // SAFETY: (all methods) the slot's signature in VIctory's table. + let begin: extern "system" fn(*mut c_void, u32, *mut Block) -> Hresult = + unsafe { self.0.method(0x38) }; + let hr = begin(self.this(), options, &mut block); + if hr != S_OK { + return Err(hr); + } + wait(&mut block); + let mut user = std::ptr::null_mut(); + let result: extern "system" fn(*mut c_void, *mut Block, *mut User) -> Hresult = + unsafe { self.0.method(0x40) }; + match result(self.this(), &mut block, &mut user) { + S_OK => Ok(user), + hr => Err(hr), + } + } + fn duplicate(&self, user: User) -> Result { + let mut out = std::ptr::null_mut(); + let f: extern "system" fn(*mut c_void, User, *mut User) -> Hresult = + unsafe { self.0.method(0x18) }; + match f(self.this(), user, &mut out) { + S_OK => Ok(out), + hr => Err(hr), + } + } + fn close(&self, user: User) { + let f: extern "system" fn(*mut c_void, User) = unsafe { self.0.method(0x20) }; + f(self.this(), user) + } + fn compare(&self, a: User, b: User) -> i32 { + let f: extern "system" fn(*mut c_void, User, User) -> i32 = unsafe { self.0.method(0x28) }; + f(self.this(), a, b) + } + fn u64_of(&self, offset: usize, user: User) -> (Hresult, u64) { + let mut out = 0; + let f: extern "system" fn(*mut c_void, User, *mut u64) -> Hresult = + unsafe { self.0.method(offset) }; + (f(self.this(), user, &mut out), out) + } + fn u32_of(&self, offset: usize, user: User) -> (Hresult, u32) { + let mut out = 0; + let f: extern "system" fn(*mut c_void, User, *mut u32) -> Hresult = + unsafe { self.0.method(offset) }; + (f(self.this(), user, &mut out), out) + } + fn find(&self, offset: usize, id: u64) -> Result { + let mut out = std::ptr::null_mut(); + let f: extern "system" fn(*mut c_void, u64, *mut User) -> Hresult = + unsafe { self.0.method(offset) }; + match f(self.this(), id, &mut out) { + S_OK => Ok(out), + hr => Err(hr), + } + } + fn privilege(&self, user: User, privilege: u32) -> (Hresult, bool, u32) { + let (mut has, mut reason) = (false, 0xffff_ffff); + let f: extern "system" fn(*mut c_void, User, u32, u32, *mut bool, *mut u32) -> Hresult = + unsafe { self.0.method(0xa0) }; + let hr = f(self.this(), user, 0, privilege, &mut has, &mut reason); + (hr, has, reason) + } +} + +/// XUserGetGamertag through the gamertag interface. +fn gamertag(o: &Object, user: User, component: u32, size: usize) -> (Hresult, String, usize) { + let mut buffer = vec![0u8; size]; + let mut used = 0; + // SAFETY: the slot's signature in VIctory's table. + let f: extern "system" fn(*mut c_void, User, u32, usize, *mut u8, *mut usize) -> Hresult = + unsafe { o.method(0x18) }; + let hr = f( + o.this(), + user, + component, + size, + buffer.as_mut_ptr(), + &mut used, + ); + let end = buffer.iter().position(|&b| b == 0).unwrap_or(0); + ( + hr, + String::from_utf8_lossy(&buffer[..end]).into_owned(), + used, + ) +} + +pub fn run(t: &mut Tap) { + let users = match area(PROVIDER, IID) { + Ok(o) => Users(o), + Err(hr) => { + t.check(false, "xuser: the user area is served", || { + format!("QueryApiImpl {hr:#010x}") + }); + return; + } + }; + let first = match users.add(ADD_DEFAULT_USER_SILENTLY) { + Ok(u) => u, + Err(hr) => { + t.check( + false, + "xuser: XUserAddAsync adds the default user silently", + || format!("{hr:#010x}"), + ); + return; + } + }; + t.check( + !first.is_null(), + "xuser: XUserAddAsync adds the default user silently", + || "null".into(), + ); + let second = users.add(ADD_DEFAULT_USER_SILENTLY); + t.check( + second.is_ok_and(|s| users.compare(first, s) == 0), + "xuser: adding the default user silently again returns the same user", + || format!("{second:?}"), + ); + if let Ok(s) = second { + users.close(s); + } + match users.duplicate(first) { + Ok(d) => { + t.eq( + users.compare(first, d), + 0, + "xuser: XUserCompare is 0 for a duplicated handle", + ); + users.close(d); + } + Err(hr) => t.check(false, "xuser: XUserDuplicateHandle succeeds", || { + format!("{hr:#010x}") + }), + } + + let (hr, local) = users.u64_of(0x48, first); + t.eq(hr, S_OK, "xuser: XUserGetLocalId succeeds"); + match users.find(0x50, local) { + Ok(found) => { + t.eq( + users.compare(first, found), + 0, + "xuser: XUserFindUserByLocalId finds the user by its local id", + ); + users.close(found); + } + Err(hr) => t.check( + false, + "xuser: XUserFindUserByLocalId finds the user by its local id", + || format!("{hr:#010x}"), + ), + } + t.eq( + users.find(0x50, local ^ 0x5a5a_0000).err(), + Some(NOT_FOUND), + "xuser: XUserFindUserByLocalId of no user is HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", + ); + let (hr, xuid) = users.u64_of(0x58, first); + t.check( + hr == S_OK && xuid != 0, + "xuser: XUserGetId gives a user id", + || format!("{hr:#010x} {xuid:#x}"), + ); + match users.find(0x60, xuid) { + Ok(found) => { + t.eq( + users.compare(first, found), + 0, + "xuser: XUserFindUserById finds the user by its id", + ); + users.close(found); + } + Err(hr) => t.check( + false, + "xuser: XUserFindUserById finds the user by its id", + || format!("{hr:#010x}"), + ), + } + t.eq( + users.u32_of(0x70, first), + (S_OK, 0), + "xuser: the added user's state is SignedIn", + ); + let (hr, age) = users.u32_of(0x98, first); + t.check( + hr == S_OK && age <= 3, + "xuser: XUserGetAgeGroup is one of Unknown, Child, Teen, Adult", + || format!("{hr:#010x} {age}"), + ); + // XUserPrivilege Multiplayer (254). Offline, either + // answer is allowed; the call must succeed and fill both outputs. + let (hr, has, reason) = users.privilege(first, 254); + t.check( + hr == S_OK && (has || reason != 0xffff_ffff), + "xuser: XUserCheckPrivilege answers with a privilege or a deny reason", + || format!("{hr:#010x} {has} {reason:#x}"), + ); + + match area(PROVIDER, GAMERTAG_IID) { + Ok(o) => { + for (component, max, name) in COMPONENTS { + let (hr, text, used) = gamertag(&o, first, component, max); + t.check( + hr == S_OK && used <= max && text.len() < max, + &format!("xuser: the {name} gamertag fits its documented {max} bytes"), + || format!("{hr:#010x} {text:?} used {used}"), + ); + } + let (hr, text, _) = gamertag(&o, first, 1, 97); + if hr == S_OK && !text.is_empty() { + let (hr, _, _) = gamertag(&o, first, 1, text.len()); + t.eq( + hr, + E_INSUFFICIENT_BUFFER, + "xuser: a gamertag buffer without room for the NUL is E_INSUFFICIENT_BUFFER", + ); + } + let (hr, _, _) = gamertag(&o, first, 7, 128); + t.eq( + hr, + E_INVALIDARG, + "xuser: an invalid gamertag component is E_INVALIDARG", + ); + } + Err(hr) => t.check(false, "xuser: the gamertag interface is served", || { + format!("QueryApiImpl {hr:#010x}") + }), + } + users.close(first); +} From 612b36a15483783ed7d9832d6e5bcd07be900224 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:10:43 -0500 Subject: [PATCH 03/11] Tests: task-queue edge cases in the conformance title Nine more checks from the public reference: a SerializedThreadPool port runs its callbacks one at a time and a ThreadPool port in parallel; a composite queue's callback is dispatched from the queue owning its port; XAsyncGetResult with another identity than XAsyncBegin's is E_INVALIDARG; with the process task queue set to nullptr there is none, and it is put back after. One more answer differs from the reference and joins the list in the test: with no process task queue, an async call whose block names no queue runs anyway, where XTaskQueueSetCurrentProcessTaskQueue's page says APIs needing a queue fail with E_NO_TASK_QUEUE. 152 checks, 147 pass. --- crates/victory-hle/tests/conformance.rs | 11 +- docs/acceptance.md | 5 +- tests/fixtures/conformance/src/xasync.rs | 168 +++++++++++++++++++++++ 3 files changed, 180 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index 2a578aaad9..f72431a8df 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -14,6 +14,11 @@ use victory_loader::{UnimplementedPolicy, prepare}; /// each with why: reported, not failed. A check here that passes fails the /// test, so the list stays true. const KNOWN: &[(&str, &str)] = &[ + ( + "xasync: an async call with no queue and no process queue is E_NO_TASK_QUEUE", + "VIctory runs the call anyway; XTaskQueueSetCurrentProcessTaskQueue's \ + page says APIs needing a queue then fail with E_NO_TASK_QUEUE", + ), ( "xsystem: a retail console id is the documented zero id", "VIctory returns 38 digits ending in 1; the reference gives \ @@ -26,11 +31,13 @@ const KNOWN: &[(&str, &str)] = &[ ), ( "xuser: XUserFindUserByLocalId of no user is HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", - "VIctory returns E_GAMEUSER_USER_NOT_FOUND (0x89245104); the XUserFindUserByLocalId page gives HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", + "VIctory returns E_GAMEUSER_USER_NOT_FOUND (0x89245104); the \ + XUserFindUserByLocalId page gives HRESULT_FROM_WIN32(ERROR_NOT_FOUND)", ), ( "xuser: an invalid gamertag component is E_INVALIDARG", - "VIctory answers any component other than ModernSuffix with the gamertag; the XUserGetGamertag page gives E_INVALIDARG", + "VIctory answers any component other than ModernSuffix with the \ + gamertag; the XUserGetGamertag page gives E_INVALIDARG", ), ]; diff --git a/docs/acceptance.md b/docs/acceptance.md index 14ccb29e24..eb400f3fe2 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -105,8 +105,8 @@ Covered so far: runtime initialisation, task queues and async calls, system information, physical-page aliasing, DirectStorage (memory and file sources), game saves, the user, networking hints, the package, HDR mode, files on the console's `G:` and `T:` drives through every path import -VIctory binds, and persistent local storage: 143 checks, 139 pass. The -four divergences found: +VIctory binds, and persistent local storage: 152 checks, 147 pass. The +five divergences found: | Check | Reference | VIctory | |---|---|---| @@ -114,6 +114,7 @@ four divergences found: | DirectStorage automatic submission | when an Enqueue fills more than half the capacity | at half the capacity | | `XUserFindUserByLocalId`, no such user | `HRESULT_FROM_WIN32(ERROR_NOT_FOUND)` | `E_GAMEUSER_USER_NOT_FOUND` (0x89245104) | | `XUserGetGamertag`, invalid component | `E_INVALIDARG` | the gamertag | +| Async call with no queue, process queue set to nullptr | fails with `E_NO_TASK_QUEUE` | runs the call | Gaps seen while writing them (documented features VIctory's tables leave unimplemented, not yet tested): DirectStorage cancel by tag and the error diff --git a/tests/fixtures/conformance/src/xasync.rs b/tests/fixtures/conformance/src/xasync.rs index daec3976b2..d3c3d06fcf 100644 --- a/tests/fixtures/conformance/src/xasync.rs +++ b/tests/fixtures/conformance/src/xasync.rs @@ -27,7 +27,11 @@ const E_ABORT: Hresult = 0x8000_4004_u32 as i32; // XTaskQueueDispatchMode and XTaskQueuePort. const MANUAL: u32 = 0; const THREAD_POOL: u32 = 1; +const SERIALIZED_THREAD_POOL: u32 = 2; const IMMEDIATE: u32 = 3; +/// E_NO_TASK_QUEUE (reference/errorcodes). +const E_NO_TASK_QUEUE: Hresult = 0x8007_01AB_u32 as i32; +const E_INVALIDARG: Hresult = 0x8007_0057_u32 as i32; const WORK: u32 = 0; const COMPLETION: u32 = 1; @@ -88,6 +92,27 @@ unsafe extern "system" { struct Api(Object); impl Api { + fn port(&self, q: Queue, port: u32) -> *mut c_void { + let mut out = std::ptr::null_mut(); + // SAFETY: (these methods) the slot's signature in VIctory's table. + let f: extern "system" fn(*mut c_void, Queue, u32, *mut *mut c_void) -> Hresult = + unsafe { self.0.method(0x70) }; + f(self.0.this(), q, port, &mut out); + out + } + fn composite(&self, work: *mut c_void, completion: *mut c_void) -> Result { + let mut q = std::ptr::null_mut(); + let f: extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *mut Queue) -> Hresult = + unsafe { self.0.method(0x68) }; + match f(self.0.this(), work, completion, &mut q) { + S_OK => Ok(q), + hr => Err(hr), + } + } + fn set_process_queue(&self, q: Queue) { + let f: extern "system" fn(*mut c_void, Queue) = unsafe { self.0.method(0xd0) }; + f(self.0.this(), q) + } fn create(&self, work: u32, completion: u32) -> Result { let mut q = std::ptr::null_mut(); // SAFETY: (all methods) the slot's signature in VIctory's table. @@ -465,6 +490,7 @@ pub fn run(t: &mut Tap) { } async_calls(t); + edges(t); } static OPS: Mutex> = Mutex::new(Vec::new()); @@ -622,3 +648,145 @@ fn async_calls(t: &mut Tap) { ); a.close(q); } + +/// Counts callbacks running at once (and the most seen). +#[derive(Default)] +struct Overlap { + running: AtomicU32, + most: AtomicU32, + done: AtomicU32, +} + +extern "system" fn slow(context: *mut c_void, _: bool) { + // SAFETY: tests pass a live `Overlap`. + let o = unsafe { &*context.cast::() }; + let now = o.running.fetch_add(1, Ordering::SeqCst) + 1; + o.most.fetch_max(now, Ordering::SeqCst); + // SAFETY: a plain call. + unsafe { Sleep(2) }; + o.running.fetch_sub(1, Ordering::SeqCst); + o.done.fetch_add(1, Ordering::SeqCst); +} + +/// reference/system/xtaskqueue: SerializedThreadPool "executes the calls in +/// serial, one at a time, on the thread pool"; XTaskQueueCreateComposite +/// "Creates a task queue composed of ports of other task queues"; with the +/// process task queue set to nullptr, "XTaskQueueGetCurrentProcessTaskQueue +/// will also return nullptr" and APIs needing a queue "error with +/// E_NO_TASK_QUEUE if null was provided". reference/system/xasyncprovider: +/// XAsyncGetResult with another identity than XAsyncBegin's is a call +/// mismatch, E_INVALIDARG. +fn edges(t: &mut Tap) { + let a = api(); + + let q = a + .create(SERIALIZED_THREAD_POOL, SERIALIZED_THREAD_POOL) + .expect("serialized queue"); + let overlap = Overlap::default(); + for _ in 0..16 { + a.submit(q, WORK, ctx(&overlap), slow); + } + t.check( + wait_for(5000, || overlap.done.load(Ordering::SeqCst) == 16), + "xasync: a serialized thread-pool port runs every callback", + || format!("{} of 16", overlap.done.load(Ordering::SeqCst)), + ); + t.eq( + overlap.most.load(Ordering::SeqCst), + 1, + "xasync: ... one at a time", + ); + a.close(q); + let q = a + .create(THREAD_POOL, THREAD_POOL) + .expect("thread-pool queue"); + let parallel = Overlap::default(); + for _ in 0..16 { + a.submit(q, WORK, ctx(¶llel), slow); + } + wait_for(5000, || parallel.done.load(Ordering::SeqCst) == 16); + t.check( + parallel.most.load(Ordering::SeqCst) > 1, + "xasync: a thread-pool port runs callbacks in parallel", + || "never more than one at a time".into(), + ); + a.close(q); + + // A composite of a manual queue's work port: its callbacks are + // dispatched from that queue. + let base = a.create(MANUAL, MANUAL).expect("manual queue"); + let port = a.port(base, WORK); + match a.composite(port, port) { + Ok(c) => { + let seen = Seen::default(); + a.submit(c, WORK, ctx(&seen), note); + t.eq( + a.dispatch(base, WORK, 0), + true, + "xasync: a composite queue's callback is dispatched from the queue owning its port", + ); + t.eq( + seen.calls.load(Ordering::SeqCst), + 1, + "xasync: ... and runs once", + ); + a.close(c); + } + Err(hr) => t.check(false, "xasync: XTaskQueueCreateComposite succeeds", || { + format!("{hr:#010x}") + }), + } + + // A call mismatch: another identity than XAsyncBegin's. + let mut block = Block::new(base, std::ptr::null_mut(), None); + let b: *mut Block = &mut block; + a.begin( + b, + std::ptr::null_mut(), + eight_bytes as *const c_void, + eight_bytes, + ); + while a.dispatch(base, WORK, 0) || a.dispatch(base, COMPLETION, 0) {} + let mut buffer = [0u8; 8]; + t.eq( + a.result(b, forever as *const c_void, &mut buffer).0, + E_INVALIDARG, + "xasync: XAsyncGetResult with another identity is E_INVALIDARG", + ); + a.result(b, eight_bytes as *const c_void, &mut buffer); + a.close(base); + + // No process task queue: Get says none, and an async call with no queue + // of its own fails with E_NO_TASK_QUEUE. The queue is put back after. + let (had, previous) = a.process_queue(); + a.set_process_queue(std::ptr::null_mut()); + let (has, none) = a.process_queue(); + t.check( + !has && none.is_null(), + "xasync: with the process task queue set to nullptr, there is none", + || format!("{has} {none:?}"), + ); + let mut block = Block::on_process_queue(); + let hr = a.run(&mut block, work_ok); + t.eq( + hr, + E_NO_TASK_QUEUE, + "xasync: an async call with no queue and no process queue is E_NO_TASK_QUEUE", + ); + if hr == S_OK { + wait(&mut block); + } + if had { + a.set_process_queue(previous); + a.close(previous); + } + let (back, q) = a.process_queue(); + t.check( + back == had, + "xasync: the process task queue is put back", + || format!("had {had}, now {back}"), + ); + if back { + a.close(q); + } +} From d506402cc1c84179c16d61d3f9c9a76ac3d03d57 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:22:34 -0500 Subject: [PATCH 04/11] Tests: the conformance report must hold every check its plan announces Review (#2057): the report check passed when a known divergence's check was gone, also with the TAP plan lowered to match, and when the report was cut short of its plan. `accept` now requires the results to be numbered 1 to the plan's count, in order, each known divergence's check to be there exactly once and to fail, and nothing else to fail; it returns the known divergences seen. `reports_missing_or_cut_short_checks_are_refused` runs it on made-up reports: all present, a skipped check, a known check gone (plan lowered to match), a report cut short of its plan, a known divergence that passes, an unknown failure, a known check twice, and no checks. --- crates/victory-hle/tests/conformance.rs | 134 ++++++++++++++++++++---- 1 file changed, 115 insertions(+), 19 deletions(-) diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index f72431a8df..0b34ff43ee 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -149,33 +149,129 @@ fn workloads() { fn the_conformance_title_runs_through_victory() { let tap = call("conformance_run"); println!("{tap}"); + match accept(&tap, KNOWN) { + Ok(known) => { + for (name, why) in known { + println!("known divergence: {name}: {why}"); + } + } + Err(why) => panic!("{why}\n{tap}"), + } +} - let failed: Vec<&str> = tap +/// Checks a TAP report against `known` divergences: every result the plan +/// announces is there (numbered 1 to N, in order), each known divergence +/// is in it exactly once and fails, and nothing else fails. Returns the +/// known divergences seen. +fn accept<'a>(tap: &str, known: &'a [(&str, &str)]) -> Result, String> { + let plan: usize = tap .lines() - .filter_map(|l| l.strip_prefix("not ok ")) - .filter_map(|l| l.split_once(" - ").map(|(_, name)| name)) - .collect(); - let passed: Vec<&str> = tap + .find_map(|l| l.strip_prefix("1..")) + .and_then(|n| n.trim().parse().ok()) + .ok_or("no TAP plan")?; + // (number, passed, name), the name without a skip's reason. + let results: Vec<(usize, bool, &str)> = tap .lines() - .filter_map(|l| l.strip_prefix("ok ")) - .filter_map(|l| l.split_once(" - ").map(|(_, name)| name)) + .filter_map(|l| { + let (passed, rest) = match (l.strip_prefix("not ok "), l.strip_prefix("ok ")) { + (Some(rest), _) => (false, rest), + (None, Some(rest)) => (true, rest), + (None, None) => return None, + }; + let (n, name) = rest.split_once(" - ")?; + let name = name.split_once(" # SKIP").map_or(name, |(name, _)| name); + Some((n.parse().ok()?, passed, name)) + }) .collect(); - let known = |name: &str| KNOWN.iter().find(|(k, _)| *k == name); - for name in &failed { - if let Some((_, why)) = known(name) { - println!("known divergence: {name}: {why}"); + if plan == 0 { + return Err("no checks ran".into()); + } + let numbers: Vec = results.iter().map(|r| r.0).collect(); + if numbers != (1..=plan).collect::>() { + return Err(format!( + "the report has {} results numbered {numbers:?}, its plan 1..{plan}", + results.len() + )); + } + let mut seen = Vec::new(); + for &(name, why) in known { + match results.iter().filter(|r| r.2 == name).collect::>()[..] { + [] => return Err(format!("a known divergence's check is missing: {name}")), + [(_, true, _)] => { + return Err(format!( + "a known divergence now passes (take it off KNOWN): {name}" + )); + } + [_] => seen.push((name, why)), + _ => return Err(format!("a known divergence's check is there twice: {name}")), } } - let unexpected: Vec<&&str> = failed.iter().filter(|n| known(n).is_none()).collect(); - let fixed: Vec<&str> = KNOWN + let unexpected: Vec<&str> = results .iter() - .map(|(k, _)| *k) - .filter(|k| passed.contains(k)) + .filter(|r| !r.1 && !known.iter().any(|(k, _)| *k == r.2)) + .map(|r| r.2) .collect(); - assert!(passed.len() + failed.len() > 0, "no checks ran:\n{tap}"); - assert!(unexpected.is_empty(), "checks that failed: {unexpected:#?}"); + if !unexpected.is_empty() { + return Err(format!("checks that failed: {unexpected:#?}")); + } + Ok(seen) +} + +/// What [`accept`] refuses, on made-up reports (review of #2057): a known +/// divergence whose check is gone, also with the plan lowered to match, or +/// a report cut short of its plan; as before, a known divergence that +/// passes and an unknown failure. +#[test] +fn reports_missing_or_cut_short_checks_are_refused() { + let known = &[("k1", "why 1"), ("k2", "why 2")]; + let report = + |lines: &[&str]| format!("TAP version 13\n1..{}\n{}\n", lines.len(), lines.join("\n")); + let numbered = |lines: &[(&str, bool)]| -> Vec { + lines + .iter() + .enumerate() + .map(|(i, (name, ok))| { + format!("{}ok {} - {name}", if *ok { "" } else { "not " }, i + 1) + }) + .collect() + }; + let all = numbered(&[("a", true), ("k1", false), ("k2", false)]); + let all: Vec<&str> = all.iter().map(String::as_str).collect(); + assert_eq!(accept(&report(&all), known).map(|k| k.len()), Ok(2)); + let skipped = report(&[ + "ok 1 - a # SKIP no device", + "not ok 2 - k1", + "not ok 3 - k2", + ]); + assert!(accept(&skipped, known).is_ok(), "a skipped check counts"); + let gone = numbered(&[("a", true), ("k1", false)]); + let gone: Vec<&str> = gone.iter().map(String::as_str).collect(); + assert!( + accept(&report(&gone), known) + .unwrap_err() + .contains("missing: k2") + ); + let cut = format!("TAP version 13\n1..3\n{}\n", all[0]); + assert!(accept(&cut, known).unwrap_err().contains("plan 1..3")); + let fixed = numbered(&[("a", true), ("k1", true), ("k2", false)]); + let fixed: Vec<&str> = fixed.iter().map(String::as_str).collect(); + assert!( + accept(&report(&fixed), known) + .unwrap_err() + .contains("now passes") + ); + let new = numbered(&[("a", false), ("k1", false), ("k2", false)]); + let new: Vec<&str> = new.iter().map(String::as_str).collect(); + assert!(accept(&report(&new), known).unwrap_err().contains("failed")); + let twice = numbered(&[("k1", false), ("k1", false), ("k2", false)]); + let twice: Vec<&str> = twice.iter().map(String::as_str).collect(); + assert!( + accept(&report(&twice), known) + .unwrap_err() + .contains("twice") + ); assert!( - fixed.is_empty(), - "known divergences that now pass (take them off KNOWN): {fixed:#?}" + accept("TAP version 13\n1..0\n", known).is_err(), + "no checks" ); } From 1434e7254d6d27ecd046e2e60290897497409b8a Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:36:55 -0500 Subject: [PATCH 05/11] Tests: the conformance suite cites the public platform documentation, its notes in the test The conformance title and its harness now say only that they are written from the public platform documentation, without naming the console SDK. docs/acceptance.md is gone: how to run the suite and what KNOWN means are a few lines in crates/victory-hle/tests/conformance.rs's module docs. The fixture's miniz_oxide is the version the workspace already uses. --- crates/victory-hle/tests/conformance.rs | 18 ++- docs/acceptance.md | 155 --------------------- tests/fixtures/conformance/Cargo.toml | 9 +- tests/fixtures/conformance/src/dstorage.rs | 7 +- tests/fixtures/conformance/src/lib.rs | 8 +- 5 files changed, 24 insertions(+), 173 deletions(-) delete mode 100644 docs/acceptance.md diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index 0b34ff43ee..fc3efb0ffa 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -1,7 +1,13 @@ -//! The conformance title (tests/fixtures/conformance, docs/acceptance.md) -//! run through VIctory's loader and runtime, as `victory run` runs a title: -//! its checks are what Microsoft's public GDK reference says each call does. -//! No game data and no SDK. +//! The conformance title (tests/fixtures/conformance) run through VIctory's +//! loader and runtime, as `victory run` runs a title. The title is ours, +//! written from the public platform documentation only: its checks are what +//! those pages say each call does. No game data and no SDK. +//! +//! `cargo test -p victory-hle --test conformance -- --nocapture` builds the +//! title, runs it and prints its TAP report. `KNOWN` lists the checks VIctory +//! is known to answer differently from the documentation, each with why: +//! they are reported, not failed, and one that starts passing fails the test +//! so the list stays true. `-- --ignored` runs the streaming workload. #![cfg(windows)] use std::path::{Path, PathBuf}; @@ -137,8 +143,8 @@ fn call(name: &str) -> String { } } -/// The streaming workload (docs/acceptance.md): throughput, printed. Run -/// with `cargo test --release -p victory-hle --test conformance -- /// --ignored --nocapture`. +/// The streaming workload: throughput, printed. Run with `cargo test +/// --release -p victory-hle --test conformance -- --ignored --nocapture`. #[test] #[ignore = "a benchmark: run on demand"] fn workloads() { diff --git a/docs/acceptance.md b/docs/acceptance.md deleted file mode 100644 index eb400f3fe2..0000000000 --- a/docs/acceptance.md +++ /dev/null @@ -1,155 +0,0 @@ -# Acceptance and benchmark suite (plan and inventory) - -VIctory is checked today by unit tests inside each crate and by runs of the -title. This document plans a third layer that needs neither the title nor any -game data: a **conformance title** we write ourselves, run through VIctory -like a real one, that exercises each platform area the way a large -open-world GDK title does, checks the behaviour public documentation states, -and measures the workloads such a title puts on the platform. - -## Rules - -- **Public sources only.** Microsoft Learn's public GDK reference, public - Win32/D3D12/DirectStorage documentation, AMD's public RDNA2 ISA guide, - public conference talks and hardware disclosures. Nothing from game - binaries, leaked SDKs or NDA documentation. -- **No Microsoft GDK in the suite.** The GDK's license (Microsoft Public Game - Development Kit License Agreement, Section 3(a)) allows its use only to - develop and test Windows titles for Windows, and excludes software for - Xbox Series consoles; Section 4(d) forbids reverse engineering it. The - conformance title therefore does not link the GDK's libraries or include - its headers. It calls the runtime the way VIctory already documents - (`crates/victory-hle/src/modules/xgameruntime.rs`: `QueryApiImpl`, area - objects by provider and interface id), with declarations written from the - public reference pages. -- **Asset policy as for the rest of the tree** (`docs/asset-policy.md`): - nothing proprietary is committed; workloads are generated. - -## Oracles - -What tells a test the right answer, strongest first: - -| Oracle | Covers | Source | -|---|---|---| -| Public reference text (return codes, limits, ordering) | every runtime area | learn.microsoft.com/gaming/gdk/docs/reference | -| Open-source implementations of the same API (MIT) | XTaskQueue / XAsync: `Source/Task` of libHttpClient; GDeflate: DirectStorage's reference codec | github.com/microsoft/libHttpClient, github.com/microsoft/DirectStorage | -| Reference decoders | Opus (libopus), zlib (RFC 1950/1951) | public | -| Host reference renderer | GPU output (WARP, the D3D12 software adapter) | Windows | -| Hardware numbers | throughput and latency targets | Hot Chips 32, Xbox Wire, GDK overview pages | - -Areas whose reference pages are restricted (XMem, XAPU, D3D12.X) have no -public oracle beyond their published error codes and the Win32 -equivalents; their tests check only properties VIctory itself states and -the cross-area invariants below (memory written by one path reads back -through another). - -## Platform areas - -`hle` = the VIctory module (`crates/victory-hle/src/modules/`); `unit` = -its `#[test]` count on main at 940d32f. - -| Area | hle | unit | Documented behaviour to check (public reference) | -|---|---|---|---| -| Runtime init | xgameruntime | 1 | Initialize S_OK and repeatable per module; E_GAMERUNTIME_* codes (0x89240100…) | -| Task queues, async | xasync | 7 | dispatch modes (Manual, ThreadPool, SerializedThreadPool, Immediate) per port; `XTaskQueueDispatch` true only when it ran a call; Terminate cancels pending callbacks (`canceled=true`), later submits E_ABORT; `XAsyncGetStatus` E_PENDING until done; cancel then E_ABORT; provider op order Begin, DoWork (E_PENDING reschedules), GetResult, Cancel, Cleanup | -| User | xuser | 2 | AddDefaultUserSilently returns the same user each call; gamertag component buffer maxima (16/97/15/101 bytes), E_INSUFFICIENT_BUFFER; handles closed once; `XUserCompare`, local id equality | -| Game saves | xgamesave | 7 | 16 MB per update (E_GS_UPDATE_TOO_BIG 0x80830005), 256 MB quota (E_GS_QUOTA_EXCEEDED 0x80830006), atomic updates, one change per blob per update, container name charset (E_GS_INVALID_CONTAINER_NAME), submit consumes the update | -| Package | xpackage | 1 | identifier length bound; invalid chunk selector E_GAMEPACKAGE_INVALID_SELECTOR; mount, mount path size and path, close | -| Store | xstore | 1 | context, game license query, product query paging (`HasMorePages`) | -| System | xsystem | 4 | device type values (Series S 6, Series X 7); callable before init; console id format and E_INSUFFICIENT_BUFFER below `XSystemConsoleIdBytes`; analytics family "Xbox" | -| Threads | kernel | 3 | `XThreadSetTimeSensitive`/`XThreadIsTimeSensitive`; APIs unsafe on such threads return E_TIME_CRITICAL_THREAD (game saves: E_GS_ASYNC_FUNCTION_REQUIRED) | -| System UI | xgameui | 1 | text entry: length 0 means 1024, console cap 1024; result size then result | -| Networking | xnetworking | 1 | connectivity hint (offline by design: `networkInitialized` set, no connectivity), safe on time-sensitive threads | -| Display | display | 1 | `XDisplayTryEnableHdrMode` result values and defaults (0.01/1000/1000 nits) | -| Errors | xgameruntime | 1 | `XErrorSetOptions` values; callback set and called | -| Speech | speech | 1 | synthesizer create, voices, stream size then data | -| Input | gameinput | 7 | kinds (gamepad 0x40000, keyboard 0x4, mouse 0x8); readings are reference-counted (same pointer: no new input); history walkable for about 0.5 s; disconnect fails current reading | -| DirectStorage (console) | dstorage | 13 | FIFO completion per queue; auto-submit past half capacity; capacity bounds; 16-byte file offsets for zlib and BCPack; 32 MiB destination limit (1 GiB with 64 KiB/2 MiB pages); request reusable after enqueue; cancel by tag completes as success; error record | -| Files | files | 5 | Win32/CRT file semantics against the host itself (native run of the same test as the oracle) | -| Memory | xmem | 10 | (restricted reference) alignment attributes; physical 64 KiB pages mapped more than once read back the same bytes through every alias; 32-bit allocations below 4 GiB | -| Audio | audio, apu, dsp | 7 | (restricted reference) XAPU/XDSP error codes; decoded Opus equals libopus | -| Media | media | 2 | video decode of a generated clip | -| Upscaling | fidelityfx | 3 | FSR passes run and match the PC FSR output within tolerance | - -## Workloads (benchmarks) - -Sized from public figures ([S]) where they exist, otherwise estimates ([E]). -Each runs through VIctory and, where the API exists on Windows, natively, -and reports the metrics listed. - -| Workload | Shape | Pass | Metrics | Basis | -|---|---|---|---|---| -| Streaming | generated 8-16 GiB package of 64-512 KiB chunks, zlib, zlib+BCPack and raw; 4 priority queues; open-loop 50K requests/s; cancels by tag | every byte equals the reference decode; FIFO; cancelled requests succeed | raw GB/s per 250 ms window (console minimum 2.0), decoded GB/s (4.8 at 2:1), submit-thread CPU, p99 latency per priority, bytes/s into title memory | [S] GDK DirectStorage overview, Xbox Wire Velocity Architecture, Hot Chips 32 | -| Title-memory churn | 2,000 map/unmap of 64 KiB physical pages per frame; CPU writes 50-200 MB/frame across a 6 GiB GPU-visible heap at 30 fps | reads through every alias, CPU and GPU, equal the writes | copy/scan ms per frame (target 3) | [S] 64 KiB pages; [E] rates | -| Job system | 14 workers on 7 cores x 2 SMT, 160 fibers, 20K-50K jobs/frame, graphs 6-10 deep | affinity and CPU sets honoured; fiber-local state survives switches; no lost wake-ups | wake latency, 1 ms timer jitter, throughput vs native | [S] 8 Zen 2 cores (7 for titles, weakly sourced); [E] job counts | -| GPU-driven geometry | meshlets of 128 vertices / 256 primitives, amplification culling 50-100M to 5-10M triangles, ExecuteIndirect with GPU counts, 10K-50K records | image equals WARP | GPU ms at 1440p (frame budget 33 ms) | [S] AMD mesh shader guidance; [E] counts | -| Ray tracing | 10K instances, 3-5M triangles; 200-500 BLAS refits and ~50 rebuilds per frame; 1 GI + 1 reflection ray per pixel at half 1440p | hits equal a CPU reference | BVH ms, trace ms | [S] RT GI and reflections on Series X; [E] sizes | -| Wave64 on 32-lane hosts | ballots, readlane, prefix sums, quad ops | bit-exact against the RDNA2 ISA definitions | translation success rate | [S] AMD RDNA2 ISA guide | -| Texture streaming | MinMip feedback, 1,000-4,000 tile maps per frame from BCPack loads | detiled texels equal the reference for each swizzle mode | ms per frame | [S] 64 KiB tiles | -| Audio | 300 Opus streams at 48 kHz, 128-256 XMA voices, 8-12 convolution channels for 10 minutes | no underruns; PCM equals libopus | host CPU % | [S] Series X audio block: 300+ channels | -| Frame pacing | 30 fps presents at 60 Hz and VRR | frame-time deviation under 1 ms, no frame over 50 ms | pad-to-photon latency | [S] 33 ms frames at launch | -| Saves | 16 MB updates with the process killed at random points | all-or-nothing; exact error codes past the limits | save time | [S] GDK game-save limits | -| Pipelines | ~27,000 pipelines created on workers under a 30 fps loop | no frame over 50 ms | creation throughput | README counts | - -## Status - -`cargo test -p victory-hle --test conformance` builds the conformance title -(`tests/fixtures/conformance`), loads and binds it through VIctory as -`victory run` does, and runs its checks; the TAP report is printed with -`-- --nocapture`. Checks VIctory is known to answer differently from the -reference are listed in the test (`KNOWN`), each with why, and reported -rather than failed; one of them passing fails the test, so the list stays -true. `-- --ignored` runs the workloads. - -Covered so far: runtime initialisation, task queues and async calls, -system information, physical-page aliasing, DirectStorage (memory and file -sources), game saves, the user, networking hints, the package, HDR mode, -files on the console's `G:` and `T:` drives through every path import -VIctory binds, and persistent local storage: 152 checks, 147 pass. The -five divergences found: - -| Check | Reference | VIctory | -|---|---|---| -| `XSystemGetConsoleId` on retail | `00000000.00000000.00000000.00000000.00` | 38 digits ending in 1 | -| DirectStorage automatic submission | when an Enqueue fills more than half the capacity | at half the capacity | -| `XUserFindUserByLocalId`, no such user | `HRESULT_FROM_WIN32(ERROR_NOT_FOUND)` | `E_GAMEUSER_USER_NOT_FOUND` (0x89245104) | -| `XUserGetGamertag`, invalid component | `E_INVALIDARG` | the gamertag | -| Async call with no queue, process queue set to nullptr | fails with `E_NO_TASK_QUEUE` | runs the call | - -Gaps seen while writing them (documented features VIctory's tables leave -unimplemented, not yet tested): DirectStorage cancel by tag and the error -event and record; the documented request limits (32 MiB destination, 16-byte -offsets for compressed sources), whose behaviour when broken the reference -does not state. System dialogs: text entry opens a real host dialog, which -an unattended test cannot answer; the message and error dialogs, and -thread time-sensitivity (`XThreadSetTimeSensitive`), are unimplemented -slots in VIctory's tables. - -The streaming workload so far reads from memory only (no file source), -with synthetic data that compresses about 3.5:1; on an RTX 5070 Ti machine -(Ryzen 9 7900X), release build: raw 18-25 GB/s, zlib 12 GB/s out (3.5 GB/s -in), far above the console's 2.0 GB/s raw minimum and 4.8 GB/s decompressed, -because no storage is read. File sources and BCPack come next. - -## Build order - -1. The conformance title and its harness: a test registry, TAP output, a - `victory run` invocation per area, and the same tests compiled natively - where an oracle runs on Windows. First areas: system, task queues and - async (with libHttpClient's implementation as the second oracle), game - saves (limits and atomicity), DirectStorage ordering and limits. -2. Streaming and title-memory workloads, the stated load bottleneck. -3. The GPU frame workloads against WARP, and wave64 correctness. -4. Audio, frame pacing, input. - -## Sources - -- GDK reference and error codes: https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/ -- DirectStorage on Xbox (overview, limits): https://learn.microsoft.com/gaming/gdk/_content/gc/system/overviews/directstorage/directstorage-overview -- Game saves: https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/system/overviews/game-save/game-saves -- libHttpClient (XTaskQueue/XAsync implementation, MIT): https://github.com/microsoft/libHttpClient -- DirectStorage reference codecs (MIT): https://github.com/microsoft/DirectStorage -- AMD RDNA2 ISA: https://www.amd.com/system/files/TechDocs/rdna2-shader-instruction-set-architecture.pdf -- Xbox Series X SoC, Hot Chips 32: https://hc32.hotchips.org/assets/program/conference/day1/HotChips2020_GPU_Microsoft_Jeff_Andrews_v2.pdf -- Xbox Velocity Architecture: https://news.xbox.com/en-us/2020/07/14/a-closer-look-at-xbox-velocity-architecture/ -- Mesh shaders (AMD guidance): https://gpuopen.com/learn/mesh_shaders/mesh_shaders-optimization_and_best_practices/ diff --git a/tests/fixtures/conformance/Cargo.toml b/tests/fixtures/conformance/Cargo.toml index 4ababbfac3..f23cfb217a 100644 --- a/tests/fixtures/conformance/Cargo.toml +++ b/tests/fixtures/conformance/Cargo.toml @@ -1,7 +1,7 @@ # The conformance title: a stand-in for an Xbox title, written by us from -# public documentation only (docs/acceptance.md). It is NOT a workspace -# member: crates/victory-hle/tests/conformance.rs builds it on demand and -# runs it through VIctory's own loader and runtime. It links no SDK. +# the public platform documentation only. It is NOT a workspace member: +# crates/victory-hle/tests/conformance.rs builds it on demand and runs it +# through VIctory's own loader and runtime. It links no SDK. [package] name = "conformance" version = "0.0.0" @@ -18,5 +18,6 @@ panic = "abort" [workspace] [dependencies] -# Compresses the zlib requests DirectStorage inflates. +# Compresses the zlib requests DirectStorage inflates; the workspace's own +# version (victory-hle inflates them with it). miniz_oxide = "0.9.1" diff --git a/tests/fixtures/conformance/src/dstorage.rs b/tests/fixtures/conformance/src/dstorage.rs index 4dd8c49b37..638917fa4c 100644 --- a/tests/fixtures/conformance/src/dstorage.rs +++ b/tests/fixtures/conformance/src/dstorage.rs @@ -465,10 +465,9 @@ pub fn run(t: &mut Tap) { array.release(); } -/// The streaming workload (docs/acceptance.md, Workloads): memory-sourced -/// requests through one real-time queue, raw and zlib, in the chunk sizes -/// the DirectStorage overview recommends (64 KiB to 512 KiB). A report of -/// throughput per kind; the console's own figures are 2.0 GB/s raw (its +/// The streaming workload: memory-sourced requests through one real-time +/// queue, raw and zlib, in the chunk sizes the DirectStorage overview +/// recommends (64 KiB to 512 KiB). A report of throughput per kind; the console's own figures are 2.0 GB/s raw (its /// minimum) and 4.8 GB/s decompressed at 2:1. pub fn bench() -> String { let mut out = std::ptr::null_mut(); diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs index 42cd4e7024..dba7515ef2 100644 --- a/tests/fixtures/conformance/src/lib.rs +++ b/tests/fixtures/conformance/src/lib.rs @@ -1,7 +1,7 @@ -//! The conformance title (docs/acceptance.md): calls the console runtime as -//! a title does and checks what Microsoft's public GDK reference says each -//! call does. Results are TAP lines, read by the harness through -//! `conformance_run`. +//! The conformance title: calls the console runtime as a title does and +//! checks what the public platform documentation says each call does. +//! Results are TAP lines, read by the harness +//! (`crates/victory-hle/tests/conformance.rs`) through `conformance_run`. //! //! How a title reaches the runtime is VIctory's own description //! (`crates/victory-hle/src/modules/xgameruntime.rs`): code linked into the From 9330885f9f7de2cee58dc10000d986373890d935 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:18:59 -0500 Subject: [PATCH 06/11] Tests: the conformance title draws a GPU frame through D3D12.X and checks it against WARP The title draws a scene as a title does, from the console device's method slots: device, queue, lists, fence, descriptor heaps, serialised root signatures, a graphics pipeline from a stream and a compute pipeline whose shaders are GFX10 programs assembled by hand from AMD's RDNA2 ISA guide (vertex transform, Blinn-Phong lighting from constant buffers times a sampled texture, a compute blur), in the container layout VIctory reads. Vertex, index and constant buffers in title memory, a texture uploaded by copy, a depth buffer, four indexed draws, a dispatch, a copy to a read-back buffer. The harness draws the same scene (one shared file) natively on WARP from equivalent HLSL; the title checks its frame against it within a small tolerance, plus pixels exact by construction (clear colour, emitted colour, depth). VICTORY_CONFORMANCE_WINDOW= presents the frame, animated, with PresentX; VICTORY_CONFORMANCE_DUMP= saves both frames. --- crates/victory-hle/Cargo.toml | 12 + crates/victory-hle/tests/conformance.rs | 155 +- .../tests/conformance/reference.rs | 553 +++++++ tests/fixtures/conformance/src/gfx10.rs | 578 +++++++ tests/fixtures/conformance/src/gpu.rs | 1380 +++++++++++++++++ tests/fixtures/conformance/src/lib.rs | 38 + tests/fixtures/conformance/src/scene.rs | 365 +++++ 7 files changed, 3059 insertions(+), 22 deletions(-) create mode 100644 crates/victory-hle/tests/conformance/reference.rs create mode 100644 tests/fixtures/conformance/src/gfx10.rs create mode 100644 tests/fixtures/conformance/src/gpu.rs create mode 100644 tests/fixtures/conformance/src/scene.rs diff --git a/crates/victory-hle/Cargo.toml b/crates/victory-hle/Cargo.toml index bfc55917e1..de6c02eeaf 100644 --- a/crates/victory-hle/Cargo.toml +++ b/crates/victory-hle/Cargo.toml @@ -52,6 +52,18 @@ windows-core = { workspace = true, optional = true } [dev-dependencies] tempfile.workspace = true +# The conformance title's GPU frame drawn natively on WARP, its reference +# (tests/conformance/reference.rs). +[target.'cfg(windows)'.dev-dependencies] +windows = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Fxc", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + [features] # Debugging switches (scripted keys and the like). diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows-core"] diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index fc3efb0ffa..eafb32ef30 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -16,6 +16,16 @@ use std::process::Command; use victory_hle::{HleResolver, HostPolicy}; use victory_loader::{UnimplementedPolicy, prepare}; +// The GPU frame drawn natively on WARP (its own folder: a file here is a +// test of its own). +#[path = "conformance/reference.rs"] +mod reference; +// The GPU frame's scene, shared with the title so both draw the same (the +// title alone uses some of it). +#[allow(dead_code)] +#[path = "../../../tests/fixtures/conformance/src/scene.rs"] +mod scene; + /// Checks VIctory is known to answer differently from the public reference, /// each with why: reported, not failed. A check here that passes fails the /// test, so the list stays true. @@ -67,13 +77,42 @@ fn build_fixture() -> PathBuf { target.join("debug").join("conformance.dll") } -/// The title loaded and bound once per test process (the runtime's state -/// is global: one title at a time); `call(name)` runs one of its report -/// exports. +/// The title's report exports. +struct Exports { + run: usize, + bench: usize, + gpu: usize, +} + +/// Calls into the title one at a time: its runtime state, and the reports +/// it hands out, are global. +static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Runs one of the title's report exports (`conformance_run` or +/// `conformance_bench`). fn call(name: &str) -> String { - static EXPORTS: std::sync::OnceLock<(usize, usize)> = std::sync::OnceLock::new(); - static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); - let &(run, bench) = EXPORTS.get_or_init(|| { + let e = exports(); + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let at = if name == "conformance_bench" { + e.bench + } else { + e.run + }; + // SAFETY: the exports' signature in the fixture; the report stays valid + // until the next call, which the lock holds off. + unsafe { + let f: extern "system" fn(*mut usize) -> *const u8 = std::mem::transmute(at); + let mut len = 0; + let report = f(&mut len); + String::from_utf8_lossy(std::slice::from_raw_parts(report, len)).into_owned() + } +} + +/// The title loaded and bound once per test process (the runtime's state +/// is global: one title at a time). +fn exports() -> &'static Exports { + static EXPORTS: std::sync::OnceLock = std::sync::OnceLock::new(); + EXPORTS.get_or_init(|| { let dll = build_fixture(); let original = std::fs::read(&dll).unwrap(); let prepared = prepare(&original).unwrap(); @@ -117,30 +156,102 @@ fn call(name: &str) -> String { ); // SAFETY: its imports are bound; it depends on no title DLL. unsafe { image.attach() }.unwrap(); - let exports = ( - image.export("conformance_run").expect("conformance_run"), - image - .export("conformance_bench") - .expect("conformance_bench"), - ); + let export = |name| image.export(name).unwrap_or_else(|| panic!("{name}")); + let exports = Exports { + run: export("conformance_run"), + bench: export("conformance_bench"), + gpu: export("conformance_gpu"), + }; // Stays loaded for the rest of the process. std::mem::forget(image); exports - }); + }) +} + +/// What `conformance_gpu` takes and hands back (the fixture's `GpuRun`). +#[repr(C)] +struct GpuRun { + reference: *const f32, + reference_len: usize, + window_seconds: u32, + image: *const f32, + image_len: usize, +} + +/// Runs the title's GPU frame against `reference`: its TAP report and the +/// frame it read back. +fn call_gpu(reference: Option<&[f32]>, window_seconds: u32) -> (String, Vec) { + let e = exports(); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - let at = if name == "conformance_bench" { - bench - } else { - run + let mut run = GpuRun { + reference: reference.map_or(std::ptr::null(), <[f32]>::as_ptr), + reference_len: reference.map_or(0, <[f32]>::len), + window_seconds, + image: std::ptr::null(), + image_len: 0, }; - // SAFETY: the exports' signature in the fixture; the report stays valid - // until the next call, which the lock holds off. + // SAFETY: the export's signature in the fixture; the report and image + // stay valid until the next call, which the lock holds off. unsafe { - let f: extern "system" fn(*mut usize) -> *const u8 = std::mem::transmute(at); + let f: extern "system" fn(*mut GpuRun, *mut usize) -> *const u8 = + std::mem::transmute(e.gpu); let mut len = 0; - let report = f(&mut len); - String::from_utf8_lossy(std::slice::from_raw_parts(report, len)).into_owned() + let report = f(&mut run, &mut len); + let report = String::from_utf8_lossy(std::slice::from_raw_parts(report, len)).into_owned(); + let image = if run.image.is_null() { + Vec::new() + } else { + std::slice::from_raw_parts(run.image, run.image_len).to_vec() + }; + (report, image) + } +} + +/// The GPU frame: the title draws a scene +/// through VIctory's console D3D12 with hand-assembled GFX10 shaders, and +/// checks its frame against the same scene drawn natively on WARP. +/// `VICTORY_CONFORMANCE_WINDOW=` keeps presenting it, animated, +/// in a window that long; `VICTORY_CONFORMANCE_DUMP=` saves both +/// frames there as PPM images. +#[test] +fn the_gpu_frame_matches_warp() { + let reference = match reference::render() { + Ok(r) => Some(r), + Err(e) => { + println!("no WARP reference: {e}"); + None + } + }; + let window = std::env::var("VICTORY_CONFORMANCE_WINDOW") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + let (tap, image) = call_gpu(reference.as_deref(), window); + println!("{tap}"); + if let Some(dir) = std::env::var_os("VICTORY_CONFORMANCE_DUMP") { + let dir = PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + save_ppm(&dir.join("victory.ppm"), &image); + if let Some(r) = &reference { + save_ppm(&dir.join("warp.ppm"), r); + } + } + if let Err(why) = accept(&tap, &[]) { + panic!("{why}\n{tap}"); + } +} + +/// An RGBA float frame as a binary PPM (RGB8). +fn save_ppm(path: &Path, image: &[f32]) { + let mut out = format!("P6\n{} {}\n255\n", scene::WIDTH, scene::HEIGHT).into_bytes(); + for p in image.chunks(4) { + out.extend( + p[..3] + .iter() + .map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8), + ); } + std::fs::write(path, out).unwrap(); } /// The streaming workload: throughput, printed. Run with `cargo test diff --git a/crates/victory-hle/tests/conformance/reference.rs b/crates/victory-hle/tests/conformance/reference.rs new file mode 100644 index 0000000000..c1a91331fc --- /dev/null +++ b/crates/victory-hle/tests/conformance/reference.rs @@ -0,0 +1,553 @@ +//! The GPU frame's reference: the conformance title's scene +//! (`tests/fixtures/conformance/src/scene.rs`) drawn natively on WARP, the +//! D3D12 software adapter, from HLSL equivalent to the title's GFX10 +//! shaders, with the same resources and commands. Returns the compute +//! pass's output: RGBA floats per pixel. + +use std::mem::ManuallyDrop; + +use windows::Win32::Foundation::{HANDLE, RECT}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_11_0, ID3DBlob}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; +use windows::core::{Interface, PCSTR, Result, s}; + +use crate::scene::{self, HEIGHT, WIDTH}; + +const GRAPHICS: &str = r#" +#define RS "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), DescriptorTable(CBV(b0)), DescriptorTable(CBV(b1)), DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0))" +cbuffer Scene : register(b0) { float4 vp[4]; float4 light; float4 eye; float4 lightColour; float4 ambient; }; +cbuffer Mesh : register(b1) { float4 world[4]; float4 albedoShininess; float4 specular; float4 emissive; }; +Texture2D tex : register(t0); +SamplerState smp : register(s0); +struct V { float4 pos : SV_Position; float3 wp : TEXCOORD0; float3 n : TEXCOORD1; float2 uv : TEXCOORD2; }; +[RootSignature(RS)] +V vs(float3 p : POSITION, float3 n : NORMAL, float2 uv : TEXCOORD) { + V o; + float4 p1 = float4(p, 1); + o.wp = float3(dot(world[0], p1), dot(world[1], p1), dot(world[2], p1)); + o.n = float3(dot(world[0].xyz, n), dot(world[1].xyz, n), dot(world[2].xyz, n)); + float4 w1 = float4(o.wp, 1); + o.pos = float4(dot(vp[0], w1), dot(vp[1], w1), dot(vp[2], w1), dot(vp[3], w1)); + o.uv = uv; + return o; +} +[RootSignature(RS)] +float4 ps(V i) : SV_Target { + float3 n = i.n * rsqrt(dot(i.n, i.n)); + float3 v = eye.xyz - i.wp; + v = v * rsqrt(dot(v, v)); + float3 h = light.xyz + v; + h = h * rsqrt(dot(h, h)); + float nl = max(dot(light.xyz, n), 0); + float nh = max(dot(h, n), 0); + float s = exp2(albedoShininess.w * log2(nh)); + float4 t = tex.Sample(smp, i.uv); + float3 c = (t.rgb * (ambient.rgb + nl * lightColour.rgb)) * albedoShininess.rgb; + c = c + (specular.rgb * s) * lightColour.rgb; + return float4(emissive.rgb + c, 1); +} +"#; + +const COMPUTE: &str = r#" +#define RS "DescriptorTable(SRV(t0), UAV(u0), UAV(u1))" +Texture2D frame : register(t0); +RWTexture2D shown : register(u0); +RWByteAddressBuffer output : register(u1); +[RootSignature(RS)] +[numthreads(8, 8, 1)] +void cs(uint3 id : SV_DispatchThreadID) { + float4 c = frame.Load(int3(id.xy, 0)); + float4 l = frame.Load(int3(int(id.x) - 1, id.y, 0)); + float4 r = frame.Load(int3(id.x + 1, id.y, 0)); + float4 o = (l + r) * 0.25 + 0.5 * c; + shown[id.xy] = o; + output.Store4((id.y * WIDTH + id.x) * 16, asuint(o)); +} +"#; + +fn compile(source: &str, entry: PCSTR, target: PCSTR) -> Vec { + let source = source.replace("WIDTH", &WIDTH.to_string()); + let (mut code, mut errors): (Option, Option) = (None, None); + // SAFETY: the source and names outlive the call. + let r = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("reference"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + let bytes = |b: &ID3DBlob| { + // SAFETY: the blob's own bytes. + unsafe { std::slice::from_raw_parts(b.GetBufferPointer().cast::(), b.GetBufferSize()) } + .to_vec() + }; + if let Err(e) = r { + panic!( + "compiling the reference shaders: {e}: {}", + String::from_utf8_lossy(&errors.as_ref().map(bytes).unwrap_or_default()) + ); + } + bytes(&code.unwrap()) +} + +fn heap(kind: D3D12_HEAP_TYPE) -> D3D12_HEAP_PROPERTIES { + D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + } +} + +fn buffer(width: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: width, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +fn texture( + width: u32, + height: u32, + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, +) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + } +} + +fn transition( + resource: &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: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// The scene's frame at time 0 drawn on WARP, or why not. +pub fn render() -> Result> { + // SAFETY: D3D12 calls with descriptions that outlive them; every + // resource lives until the fence says the GPU is done with it. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device)?; + let device = device.unwrap(); + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + + let vs = compile(GRAPHICS, s!("vs"), s!("vs_5_1")); + let ps = compile(GRAPHICS, s!("ps"), s!("ps_5_1")); + let cs = compile(COMPUTE, s!("cs"), s!("cs_5_1")); + let graphics_root: ID3D12RootSignature = device.CreateRootSignature(0, &vs)?; + let compute_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs)?; + let element = |name: PCSTR, format, offset| D3D12_INPUT_ELEMENT_DESC { + SemanticName: name, + Format: format, + AlignedByteOffset: offset, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + ..Default::default() + }; + let elements = [ + element(s!("POSITION"), DXGI_FORMAT_R32G32B32_FLOAT, 0), + element(s!("NORMAL"), DXGI_FORMAT_R32G32B32_FLOAT, 12), + element(s!("TEXCOORD"), DXGI_FORMAT_R32G32_FLOAT, 24), + ]; + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&graphics_root), + VS: code(&vs), + PS: code(&ps), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_BACK, + DepthClipEnable: true.into(), + ..Default::default() + }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS, + ..Default::default() + }, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: elements.as_ptr(), + NumElements: elements.len() as u32, + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + let graphics: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + let compute: ID3D12PipelineState = + device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&compute_root), + CS: code(&cs), + ..Default::default() + })?; + + let make = |kind, + desc: D3D12_RESOURCE_DESC, + state, + clear: Option| + -> Result { + let mut r: Option = None; + device.CreateCommittedResource( + &heap(kind), + D3D12_HEAP_FLAG_NONE, + &desc, + state, + clear.as_ref().map(|c| c as *const _), + &mut r, + )?; + Ok(r.unwrap()) + }; + let write = |r: &ID3D12Resource, bytes: &[u8]| -> Result<()> { + let mut at = std::ptr::null_mut(); + r.Map(0, None, Some(&mut at))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), at.cast::(), bytes.len()); + r.Unmap(0, None); + Ok(()) + }; + let geometry = scene::Geometry::new(); + let vertex_bytes = std::slice::from_raw_parts( + geometry.vertices.as_ptr().cast::(), + geometry.vertices.len() * size_of::(), + ); + let index_bytes: Vec = geometry + .indices + .iter() + .flat_map(|i| i.to_le_bytes()) + .collect(); + let upload = D3D12_HEAP_TYPE_UPLOAD; + let read = D3D12_RESOURCE_STATE_GENERIC_READ; + let none = D3D12_RESOURCE_FLAG_NONE; + let vertices = make(upload, buffer(vertex_bytes.len() as u64, none), read, None)?; + write(&vertices, vertex_bytes)?; + let indices = make( + upload, + buffer(index_bytes.len().next_multiple_of(4) as u64, none), + read, + None, + )?; + write(&indices, &index_bytes)?; + let (scene, draws) = scene::frame(0.0); + let mut constants_data = + std::slice::from_raw_parts((&raw const scene).cast::(), 256).to_vec(); + for (_, m) in &draws { + constants_data.extend(std::slice::from_raw_parts( + (&raw const *m).cast::(), + 256, + )); + } + let constants = make( + upload, + buffer(constants_data.len() as u64, none), + read, + None, + )?; + write(&constants, &constants_data)?; + let texels = scene::texels(); + let staging = make(upload, buffer(texels.len() as u64, none), read, None)?; + write(&staging, &texels)?; + let default = D3D12_HEAP_TYPE_DEFAULT; + let rgba8 = DXGI_FORMAT_R8G8B8A8_UNORM; + let tex = make( + default, + texture(scene::TEXTURE, scene::TEXTURE, rgba8, none), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let clear = scene::CLEAR.map(|c| f32::from(c) / 255.0); + let target = make( + default, + texture( + WIDTH, + HEIGHT, + rgba8, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ), + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(D3D12_CLEAR_VALUE { + Format: rgba8, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: clear }, + }), + )?; + let depth = make( + default, + texture( + WIDTH, + HEIGHT, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ), + D3D12_RESOURCE_STATE_DEPTH_WRITE, + Some(D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { + DepthStencil: D3D12_DEPTH_STENCIL_VALUE { + Depth: 1.0, + Stencil: 0, + }, + }, + }), + )?; + let uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let unordered = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + let shown = make(default, texture(WIDTH, HEIGHT, rgba8, uav), unordered, None)?; + let frame_bytes = u64::from(WIDTH * HEIGHT * 16); + let output = make(default, buffer(frame_bytes, uav), unordered, None)?; + let readback = make( + D3D12_HEAP_TYPE_READBACK, + buffer(frame_bytes, none), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + + let heap_of = |kind, count, flags| -> Result { + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + }; + let visible = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + let views = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, visible)?; + let samplers = heap_of(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, visible)?; + let rtvs = heap_of( + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + )?; + let dsvs = heap_of( + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + )?; + let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let cpu = |n: usize| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: views.GetCPUDescriptorHandleForHeapStart().ptr + n * step, + }; + let gpu = |n: u64| D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: views.GetGPUDescriptorHandleForHeapStart().ptr + n * step as u64, + }; + for n in 0..5 { + device.CreateConstantBufferView( + Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: constants.GetGPUVirtualAddress() + 256 * n as u64, + SizeInBytes: 256, + }), + cpu(n), + ); + } + device.CreateShaderResourceView(&tex, None, cpu(5)); + device.CreateShaderResourceView(&target, None, cpu(6)); + device.CreateUnorderedAccessView(&shown, None, None, cpu(7)); + device.CreateUnorderedAccessView( + &output, + None, + Some(&D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: (frame_bytes / 4) as u32, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }), + cpu(8), + ); + device.CreateSampler( + &D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + AddressU: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressV: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + AddressW: D3D12_TEXTURE_ADDRESS_MODE_WRAP, + MaxAnisotropy: 1, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + MaxLOD: f32::MAX, + ..Default::default() + }, + samplers.GetCPUDescriptorHandleForHeapStart(), + ); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + let dsv = dsvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + device.CreateDepthStencilView(&depth, None, dsv); + + // The texture's upload. + let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: rgba8, + Width: scene::TEXTURE, + Height: scene::TEXTURE, + Depth: 1, + RowPitch: scene::TEXTURE * 4, + }, + }; + 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(&staging), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + )]); + + // The draws. + list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]); + list.SetGraphicsRootSignature(&graphics_root); + list.ClearRenderTargetView(rtv, &clear, None); + list.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + list.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetPipelineState(&graphics); + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vertices.GetGPUVirtualAddress(), + SizeInBytes: vertex_bytes.len() as u32, + StrideInBytes: scene::STRIDE, + }]), + ); + list.IASetIndexBuffer(Some(&D3D12_INDEX_BUFFER_VIEW { + BufferLocation: indices.GetGPUVirtualAddress(), + SizeInBytes: index_bytes.len() as u32, + Format: DXGI_FORMAT_R16_UINT, + })); + list.SetGraphicsRootDescriptorTable(0, gpu(0)); + list.SetGraphicsRootDescriptorTable(2, gpu(5)); + list.SetGraphicsRootDescriptorTable(3, samplers.GetGPUDescriptorHandleForHeapStart()); + for (n, &(mesh, _)) in draws.iter().enumerate() { + let m = geometry.meshes[mesh]; + list.SetGraphicsRootDescriptorTable(1, gpu(n as u64 + 1)); + list.DrawIndexedInstanced(m.indices, 1, m.first_index, m.base_vertex, 0); + } + + // The compute pass, then the copy to read back. + list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + list.SetComputeRootSignature(&compute_root); + list.SetPipelineState(&compute); + list.SetComputeRootDescriptorTable(0, gpu(6)); + list.Dispatch(WIDTH / scene::GROUP, HEIGHT / scene::GROUP, 1); + list.ResourceBarrier(&[transition( + &output, + unordered, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + list.CopyBufferRegion(&readback, 0, &output, 0, frame_bytes); + list.Close()?; + queue.ExecuteCommandLists(&[Some(list.cast()?)]); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + queue.Signal(&fence, 1)?; + // A null event: returns once the fence has the value. + fence.SetEventOnCompletion(1, HANDLE::default())?; + device.GetDeviceRemovedReason()?; + + let mut at = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut at))?; + let mut out = vec![0f32; (frame_bytes / 4) as usize]; + std::ptr::copy_nonoverlapping(at.cast::(), out.as_mut_ptr(), out.len()); + readback.Unmap(0, None); + Ok(out) + } +} diff --git a/tests/fixtures/conformance/src/gfx10.rs b/tests/fixtures/conformance/src/gfx10.rs new file mode 100644 index 0000000000..f367e99203 --- /dev/null +++ b/tests/fixtures/conformance/src/gfx10.rs @@ -0,0 +1,578 @@ +//! The GPU frame's shaders, hand-assembled for the console's GPU (RDNA 2, +//! GFX10.3) from AMD's public "RDNA 2 Instruction Set Architecture" +//! reference (encodings: chapter 13; opcodes: its tables), and packed in +//! the shader container a title hands D3D12.X. +//! +//! The container's layout is VIctory's own description of it +//! (`crates/victory-shader/src/native.rs`): a DXBC container whose `DXIL` +//! part holds an `XDAT` index, one entry of which is a zlib-packed blob +//! (`XBCH`) of native programs (`FSSM`), each with a record naming its +//! code, where its root parameters arrive (user SGPRs) and the descriptors +//! it reads, then its stage data (vertex inputs and outputs, pixel inputs, +//! compute thread-group size). Like the runtime's method slots elsewhere in +//! this title, these tests check behaviour, not that binary format (only a +//! real title's shaders can check that). + +/// Operand codes (the ISA's SSRC/SRC encoding): SGPRs 0-105, `m0` 124, +/// integer 0 128, 1-64 129-192, -1 193, 0.5 240, 1.0 242, a literal dword +/// 255, VGPRs 256-511. +const fn v(n: u32) -> u32 { + 256 + n +} +const ZERO: u32 = 128; +const ONE: u32 = 129; +const MINUS_ONE: u32 = 193; +const HALF: u32 = 240; +const F1: u32 = 242; +const LITERAL: u32 = 255; +/// SMEM's SOFFSET "none". +const NULL: u32 = 125; + +#[derive(Default)] +struct Asm(Vec); + +impl Asm { + /// SOP1: `s_mov_b32` is 3. + fn sop1(&mut self, op: u32, sdst: u32, ssrc: u32) { + self.0.push(0xBE80_0000 | sdst << 16 | op << 8 | ssrc); + } + fn s_mov(&mut self, sdst: u32, ssrc: u32) { + self.sop1(3, sdst, ssrc); + } + /// SOP2: `s_lshl_b32` is 0x1e. + fn sop2(&mut self, op: u32, sdst: u32, ssrc0: u32, ssrc1: u32) { + self.0 + .push(0x8000_0000 | op << 23 | sdst << 16 | ssrc1 << 8 | ssrc0); + } + /// SOPK `s_movk_i32` (0): a sign-extended 16-bit constant. + fn s_movk(&mut self, sdst: u32, imm: u16) { + self.0.push(0xB000_0000 | sdst << 16 | u32::from(imm)); + } + /// SOPP: `s_endpgm` 1, `s_waitcnt` 0xc. + fn sopp(&mut self, op: u32, imm: u16) { + self.0.push(0xBF80_0000 | op << 16 | u32::from(imm)); + } + /// `s_waitcnt lgkmcnt(0)` (VM_CNT and EXP_CNT left at their maxima). + fn wait_scalar(&mut self) { + self.sopp(0xc, 0xC07F); + } + /// `s_waitcnt vmcnt(0)`. + fn wait_vector(&mut self) { + self.sopp(0xc, 0x3F70); + } + fn end(&mut self) { + self.sopp(1, 0); + } + /// SMEM: `s_load_dwordx4` 2, `_x8` 3, `s_buffer_load_dwordx16` 0xc; + /// `offset` in bytes. + fn smem(&mut self, op: u32, sdata: u32, sbase: u32, offset: u32) { + self.0 + .push(0xF400_0000 | op << 18 | sdata << 6 | sbase >> 1); + self.0.push(NULL << 25 | offset); + } + /// VOP1: `v_mov_b32` 1, `v_exp_f32` 0x25, `v_log_f32` 0x27, + /// `v_rsq_f32` 0x2e. + fn vop1(&mut self, op: u32, vdst: u32, src0: u32) { + self.0 + .push(0x7E00_0000 | (vdst & 0xFF) << 17 | op << 9 | src0); + } + /// Destinations and `vsrc1` are VGPRs, by number or operand code. + /// VOP2: `v_add_f32` 3, `v_sub_f32` 4, + /// `v_mul_f32` 8, `v_max_f32` 0x10, `v_lshlrev_b32` 0x1a, + /// `v_add_nc_u32` 0x25, `v_fmac_f32` 0x2b (vdst += src0 * vsrc1). + fn vop2(&mut self, op: u32, vdst: u32, src0: u32, vsrc1: u32) { + self.0 + .push(op << 25 | (vdst & 0xFF) << 17 | (vsrc1 & 0xFF) << 9 | src0); + } + fn add(&mut self, d: u32, a: u32, b: u32) { + self.vop2(3, d, a, b); + } + fn sub(&mut self, d: u32, a: u32, b: u32) { + self.vop2(4, d, a, b); + } + fn mul(&mut self, d: u32, a: u32, b: u32) { + self.vop2(8, d, a, b); + } + fn fmac(&mut self, d: u32, a: u32, b: u32) { + self.vop2(0x2b, d, a, b); + } + /// VOP3 (only-VOP3 opcodes): `v_mad_u32_u24` 0x143. + fn vop3(&mut self, op: u32, vdst: u32, src0: u32, src1: u32, src2: u32) { + self.0.push(0xD400_0000 | op << 16 | (vdst & 0xFF)); + self.0.push(src2 << 18 | src1 << 9 | src0); + } + /// VINTRP `v_interp_p1_f32` (0) then `v_interp_p2_f32` (1) of one + /// attribute channel, from the barycentrics i (v`i`) and j (v`i` + 1). + fn interpolate(&mut self, vdst: u32, i: u32, attr: u32, chan: u32) { + for (op, bary) in [(0, i), (1, i + 1)] { + self.0 + .push(0xC800_0000 | vdst << 18 | op << 16 | attr << 10 | chan << 8 | bary); + } + } + /// EXP: target `mrt0` 0, `pos0` 12, `param` 32 + n. + fn export(&mut self, target: u32, enable: u32, done: bool, valid: bool, src: [u32; 4]) { + self.0.push( + 0xF800_0000 | u32::from(valid) << 12 | u32::from(done) << 11 | target << 4 | enable, + ); + self.0 + .push(src[3] << 24 | src[2] << 16 | src[1] << 8 | src[0]); + } + /// MIMG, a 2D image, all four channels: `image_load` 0 (unnormalised), + /// `image_store` 8 (unnormalised), `image_sample` 0x20. + fn image(&mut self, op: u32, vdata: u32, vaddr: u32, srsrc: u32, ssamp: u32) { + let unnormalised = u32::from(op != 0x20); + self.0 + .push(0xF000_0000 | op << 18 | unnormalised << 12 | 0xF << 8 | 1 << 3); + self.0 + .push(ssamp >> 2 << 21 | srsrc >> 2 << 16 | vdata << 8 | vaddr); + } + /// MUBUF `buffer_store_dwordx4` (0x1e) at the byte offset in `vaddr`. + fn store4(&mut self, vdata: u32, vaddr: u32, srsrc: u32) { + self.0.push(0xE000_0000 | 0x1e << 18 | 1 << 12); + self.0 + .push(ZERO << 24 | srsrc >> 2 << 16 | vdata << 8 | vaddr); + } + /// A 64-bit address in SGPRs `pair`, `pair + 1` of the descriptor table + /// whose 32-bit address is in `table` (tables live in the low 4 GiB of + /// the heap's space: the high half is 0). + fn table(&mut self, pair: u32, table: u32) { + self.s_mov(pair, table); + self.s_mov(pair + 1, ZERO); + } +} + +/// The vertex shader (wave32). User data: s0 the scene constants' table, +/// s1 the draw's. Inputs (the fetch shader's VGPRs): position v4-v6, +/// normal v7-v9, texture coordinates v10-v11. Outputs: the world position +/// (param0), the world normal (param1), the coordinates (param2), the clip +/// position (pos0). +pub fn vertex() -> Vec { + let mut a = Asm::default(); + a.table(2, 0); + a.smem(2, 8, 2, 0); // s_load_dwordx4 s[8:11], s[2:3], 0 + a.table(4, 1); + a.smem(2, 12, 4, 0); // s_load_dwordx4 s[12:15], s[4:5], 0 + a.wait_scalar(); + a.smem(0xc, 16, 8, 0); // s_buffer_load_dwordx16 s[16:31]: view-projection rows + a.smem(0xc, 32, 12, 0); // s_buffer_load_dwordx16 s[32:47]: world rows + a.wait_scalar(); + // World position v12-v14: row r . (position, 1). + for r in 0..3 { + let (d, row) = (v(12 + r), 32 + 4 * r); + a.mul(d, row, 4); + a.fmac(d, row + 1, 5); + a.fmac(d, row + 2, 6); + a.add(d, row + 3, 12 + r); + } + // World normal v15-v17: the rows' first three columns . normal. + for r in 0..3 { + let (d, row) = (v(15 + r), 32 + 4 * r); + a.mul(d, row, 7); + a.fmac(d, row + 1, 8); + a.fmac(d, row + 2, 9); + } + // Clip position v18-v21: view-projection row r . (world, 1). + for r in 0..4 { + let (d, row) = (v(18 + r), 16 + 4 * r); + a.mul(d, row, 12); + a.fmac(d, row + 1, 13); + a.fmac(d, row + 2, 14); + a.add(d, row + 3, 18 + r); + } + a.export(32, 0x7, false, false, [12, 13, 14, 14]); + a.export(33, 0x7, false, false, [15, 16, 17, 17]); + a.export(34, 0x3, false, false, [10, 11, 11, 11]); + a.export(12, 0xF, true, false, [18, 19, 20, 21]); + a.end(); + a.0 +} + +/// The pixel shader (wave32). User data: s0 the scene constants' table, s1 +/// the draw's, s2 the texture's, s3 the sampler's, then (s4) the +/// primitive's attribute location. The perspective-centre +/// barycentrics arrive in v0-v1. Colour = texture x (ambient + n.l x +/// light) x albedo + specular x (n.h)^shininess x light + emitted. +pub fn pixel() -> Vec { + let mut a = Asm::default(); + // The primitive's attribute location arrives after the user data; + // interpolation reads it from M0. + a.s_mov(124, 4); + a.table(6, 0); + a.smem(2, 8, 6, 0); // s_load_dwordx4 s[8:11]: scene constants + a.table(60, 1); + a.smem(2, 12, 60, 0); // s_load_dwordx4 s[12:15]: draw constants + a.table(62, 2); + a.smem(3, 48, 62, 0); // s_load_dwordx8 s[48:55]: texture + a.table(64, 3); + a.smem(2, 56, 64, 0); // s_load_dwordx4 s[56:59]: sampler + // World position v2-v4, normal v5-v7, coordinates v8-v9. + for c in 0..3 { + a.interpolate(2 + c, 0, 0, c); + } + for c in 0..3 { + a.interpolate(5 + c, 0, 1, c); + } + for c in 0..2 { + a.interpolate(8 + c, 0, 2, c); + } + a.wait_scalar(); + a.image(0x20, 10, 8, 48, 56); // image_sample v[10:13], v[8:9] + // Light s16-s18, eye s20-s22, light colour s24-s26, ambient s28-s30; + // albedo s32-s34, shininess s35, specular s36-s38, emitted s40-s42. + a.smem(0xc, 16, 8, 0x40); + a.smem(0xc, 32, 12, 0x40); + // Normalise (x, y, z) in VGPRs `x`..`x + 2` with `t` for the length. + let normalise = |a: &mut Asm, x: u32, t: u32| { + a.mul(v(t), v(x), x); + a.fmac(v(t), v(x + 1), x + 1); + a.fmac(v(t), v(x + 2), x + 2); + a.vop1(0x2e, v(t), v(t)); // v_rsq_f32 + for c in 0..3 { + a.mul(v(x + c), v(x + c), t); + } + }; + normalise(&mut a, 5, 14); + a.wait_scalar(); + // View direction v15-v17 = eye - position, then the half vector. + for c in 0..3 { + a.sub(v(15 + c), 20 + c, 2 + c); + } + normalise(&mut a, 15, 18); + for c in 0..3 { + a.add(v(15 + c), 16 + c, 15 + c); + } + normalise(&mut a, 15, 18); + // n.l in v19, n.h in v20, both at least 0. + a.mul(v(19), 16, 5); + a.fmac(v(19), 17, 6); + a.fmac(v(19), 18, 7); + a.vop2(0x10, v(19), ZERO, 19); + a.mul(v(20), v(15), 5); + a.fmac(v(20), v(16), 6); + a.fmac(v(20), v(17), 7); + a.vop2(0x10, v(20), ZERO, 20); + // (n.h)^shininess as 2^(shininess x log2(n.h)). + a.vop1(0x27, v(20), v(20)); + a.mul(v(20), 35, 20); + a.vop1(0x25, v(20), v(20)); + a.wait_vector(); + for c in 0..3 { + let d = 21 + c; + a.vop1(1, v(d), 28 + c); // ambient + a.fmac(v(d), 24 + c, 19); // + n.l x light + a.mul(v(d), v(10 + c), d); // x texture + a.mul(v(d), 32 + c, d); // x albedo + a.mul(v(24), 36 + c, 20); // specular x (n.h)^shininess + a.mul(v(24), 24 + c, 24); // x light + a.add(v(d), v(d), 24); + a.add(v(d), 40 + c, d); // + emitted + } + a.vop1(1, v(24), F1); + a.export(0, 0xF, true, true, [21, 22, 23, 24]); + a.end(); + a.0 +} + +/// The compute shader (wave32, 8 x 8 threads): a horizontal [1 2 1] / 4 +/// blur of the frame. User data: s0 the table of the frame (SRV, at 0), the +/// texture shown (UAV, at 32 bytes) and the read-back buffer (raw UAV, at +/// 64 bytes; four floats per pixel, row after row). The group id arrives +/// in s1-s2, the thread id in v0-v1. A neighbour past the edge reads 0. +pub fn compute() -> Vec { + let mut a = Asm::default(); + a.table(4, 0); + a.smem(3, 8, 4, 0); // s_load_dwordx8 s[8:15]: the frame + a.smem(3, 16, 4, 0x20); // s_load_dwordx8 s[16:23]: the texture shown + a.smem(2, 24, 4, 0x40); // s_load_dwordx4 s[24:27]: the buffer + a.sop2(0x1e, 28, 1, 3 + 128); // s_lshl_b32 s28, s1, 3 + a.sop2(0x1e, 29, 2, 3 + 128); // s_lshl_b32 s29, s2, 3 + a.vop2(0x25, v(2), 28, 0); // x = group x * 8 + thread x + a.vop2(0x25, v(3), 29, 1); + a.vop2(0x25, v(4), MINUS_ONE, 2); // left + a.vop1(1, v(5), v(3)); + a.vop2(0x25, v(6), ONE, 2); // right + a.vop1(1, v(7), v(3)); + a.wait_scalar(); + a.image(0, 8, 2, 8, 0); // image_load v[8:11], v[2:3]: centre + a.image(0, 12, 4, 8, 0); // left + a.image(0, 16, 6, 8, 0); // right + a.wait_vector(); + for c in 0..4 { + let d = 20 + c; + a.add(v(d), v(12 + c), 16 + c); + a.mul(v(d), LITERAL, d); + a.0.push(0.25f32.to_bits()); + a.fmac(v(d), HALF, 8 + c); + } + a.image(8, 20, 2, 16, 0); // image_store v[20:23], v[2:3] + a.s_movk(30, crate::scene::WIDTH as u16); + a.vop3(0x143, 24, v(3), 30, v(2)); // v_mad_u32_u24 v24, y, width, x + a.vop2(0x1a, v(24), 4 + 128, 24); // v_lshlrev_b32 v24, 4, v24 + a.store4(20, 24, 24); + a.end(); + a.0 +} + +/// One element of an `ISG1`/`OSG1` part: name, system value (0 none, 1 +/// position, 64 target), register and component mask. +struct Element(&'static str, u32, u32, u8); + +/// The signature part: elements of 32 bytes (stream, name offset, semantic +/// index, system value, component type 3 = float, register, mask, mask +/// read or written, minimum precision 0), then the names. +fn signature(elements: &[Element], input: bool) -> Vec { + let mut out = Vec::new(); + let mut names = Vec::new(); + let table = 8 + 32 * elements.len(); + out.extend((elements.len() as u32).to_le_bytes()); + out.extend(8u32.to_le_bytes()); + // The semantic index follows the name's last digit (TEXCOORD1 is + // TEXCOORD, index 1). + for e in elements { + let digits = e.0.trim_start_matches(|c: char| !c.is_ascii_digit()); + let base = &e.0[..e.0.len() - digits.len()]; + let index: u32 = digits.parse().unwrap_or(0); + let name_at = (table + names.len()) as u32; + names.extend(base.as_bytes()); + names.push(0); + let used = if input { e.3 } else { 0 }; + for w in [0, name_at, index, e.1, 3, e.2] { + out.extend(w.to_le_bytes()); + } + out.extend([e.3, used, 0, 0]); + out.extend(0u32.to_le_bytes()); + } + out.extend(names); + out.resize(out.len().next_multiple_of(4), 0); + out +} + +/// What a program's record says besides its code. +struct Program { + stage: usize, + code: Vec, + vgprs: u32, + sgprs: u32, + /// Root parameters: (slot, user-data dword), each a descriptor table. + layout: Vec<(u8, u8)>, + /// Descriptors read: (type: 0 SRV, 1 sampler, 2 CBV, 3 UAV; slot, + /// user-data dword, offset in the table in dwords, register, dwords). + used: Vec<(u8, u8, u8, u32, u32, u8)>, + stage_data: Vec, +} + +/// Stage slots in the blob's table of record offsets. +const VS: usize = 0x28; +const PS: usize = 0x30; +const CS: usize = 0x60; +const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF; + +fn put(data: &mut [u8], at: usize, bytes: &[u8]) { + data[at..at + bytes.len()].copy_from_slice(bytes); +} + +/// The `FSSM` blob of one program. +fn fssm(p: &Program) -> Vec { + const RECORD: usize = 0x68; + let mut payload = vec![0u8; RECORD + 0x54]; + put(&mut payload, 0, &6u64.to_le_bytes()); + for at in (8..=CS).step_by(8) { + put(&mut payload, at, &ABSENT.to_le_bytes()); + } + put(&mut payload, p.stage, &(RECORD as u64).to_le_bytes()); + payload.extend(&p.stage_data); + let layout_at = payload.len(); + for &(slot, user_data) in &p.layout { + // Root type 3 (a table), range at 0, one SGPR, register 0. + for w in [3u32, 0, 1, 0] { + payload.extend(w.to_le_bytes()); + } + payload.extend([user_data, slot, 0, 0]); + } + let used_at = payload.len(); + for &(kind, slot, user_data, offset, register, dwords) in &p.used { + payload.extend([kind, 3, 0, 0]); + for w in [offset, register, 0] { + payload.extend(w.to_le_bytes()); + } + payload.extend([dwords, user_data, slot, 0]); + } + payload.resize(payload.len().next_multiple_of(256), 0); + let code_at = payload.len(); + payload.extend(p.code.iter().flat_map(|w| w.to_le_bytes())); + let record = &mut payload[RECORD..RECORD + 0x54]; + put(record, 0, &(code_at as u64).to_le_bytes()); + put(record, 8, &(4 * p.code.len() as u64).to_le_bytes()); + put(record, 0x14, &(1u32 << 5).to_le_bytes()); // wave32 + put(record, 0x28, &(layout_at as u64).to_le_bytes()); + put(record, 0x30, &(used_at as u64).to_le_bytes()); + put(record, 0x38, &(p.layout.len() as u32).to_le_bytes()); + put(record, 0x3c, &(p.used.len() as u32).to_le_bytes()); + put(record, 0x50, &(p.vgprs | p.sgprs << 20).to_le_bytes()); + let mut out = b"FSSM".to_vec(); + out.extend(0x101u32.to_le_bytes()); + out.extend((payload.len() as u64).to_le_bytes()); + out.extend(payload); + out +} + +/// The container: `ISG1`, `OSG1` (if any), and the `DXIL` part (a program +/// header, the `XDAT` index, the packed programs). +fn container(kind: u32, p: &Program, signatures: &[(&[u8; 4], Vec)]) -> Vec { + let unpacked = fssm(p); + let stream = miniz_oxide::deflate::compress_to_vec_zlib(&unpacked, 6); + let mut blob = b"XBCH".to_vec(); + blob.extend(3u32.to_le_bytes()); + blob.extend((stream.len() as u64).to_le_bytes()); + blob.extend((unpacked.len() as u64).to_le_bytes()); + blob.extend(stream); + // Program header: kind and shader model 6.5, size in dwords, "DXIL", + // version 1.5, then (no bitcode) an offset and size of none. + let index = 0x18 + 12 + 12; + let mut dxil = Vec::new(); + let total = (index + blob.len()).next_multiple_of(4); + for w in [kind << 16 | 0x65, (total / 4) as u32] { + dxil.extend(w.to_le_bytes()); + } + dxil.extend(b"DXIL"); + for w in [0x105u32, (total - 8) as u32, 0] { + dxil.extend(w.to_le_bytes()); + } + dxil.extend(b"XDAT"); + for w in [1u32, 0x24, 0x0d, index as u32, blob.len() as u32] { + dxil.extend(w.to_le_bytes()); + } + dxil.extend(blob); + dxil.resize(total, 0); + let mut parts: Vec<(&[u8; 4], &[u8])> = signatures.iter().map(|(f, d)| (*f, &d[..])).collect(); + parts.push((b"DXIL", &dxil)); + let table = 0x20 + 4 * parts.len(); + let size = table + parts.iter().map(|p| 8 + p.1.len()).sum::(); + let mut out = b"DXBC".to_vec(); + out.extend([0; 16]); + out.extend(1u16.to_le_bytes()); + out.extend(0u16.to_le_bytes()); + out.extend((size as u32).to_le_bytes()); + out.extend((parts.len() as u32).to_le_bytes()); + let mut at = table; + for p in &parts { + out.extend((at as u32).to_le_bytes()); + at += 8 + p.1.len(); + } + for (fourcc, data) in parts { + out.extend(fourcc); + out.extend((data.len() as u32).to_le_bytes()); + out.extend(data); + } + out +} + +/// The vertex stage's signatures: what the input layout feeds it and what +/// it hands the pixel shader. +fn vertex_signatures() -> (Vec, Vec) { + let inputs = [ + Element("POSITION", 0, 0, 0x7), + Element("NORMAL", 0, 1, 0x7), + Element("TEXCOORD", 0, 2, 0x3), + ]; + (signature(&inputs, true), signature(&interpolants(), false)) +} + +fn interpolants() -> [Element; 4] { + [ + Element("SV_Position", 1, 0, 0xF), + Element("TEXCOORD0", 0, 1, 0x7), + Element("TEXCOORD1", 0, 2, 0x7), + Element("TEXCOORD2", 0, 3, 0x3), + ] +} + +pub fn vertex_container() -> Vec { + let mut data = vec![0u8; 0x190]; + // Inputs: usage (6 generic), row, mask, first VGPR, highest channel. + let inputs: [[u8; 5]; 3] = [[6, 0, 7, 4, 2], [6, 1, 7, 7, 2], [6, 2, 3, 10, 1]]; + for (i, e) in inputs.iter().enumerate() { + put(&mut data, 0x24 + 5 * i, e); + } + put(&mut data, 0xc4, &3u32.to_le_bytes()); + // Outputs: usage, row, `param` number, row, slot, flags. + for n in 0..3u8 { + put( + &mut data, + 0xc8 + 6 * n as usize, + &[6, n + 1, n, n + 1, n, 0], + ); + } + put(&mut data, 0x188, &3u32.to_le_bytes()); + let p = Program { + stage: VS, + code: vertex(), + vgprs: 24, + sgprs: 48, + layout: vec![(0, 0), (1, 1)], + used: vec![(2, 0, 0, 0, 0, 4), (2, 1, 1, 0, 1, 4)], + stage_data: data, + }; + let (isg, osg) = vertex_signatures(); + container(1, &p, &[(b"ISG1", isg), (b"OSG1", osg)]) +} + +pub fn pixel_container() -> Vec { + let mut data = vec![0u8; 0x14c + 8 * (4 + 400)]; + // Inputs: usage, row, mask, attribute, default, second row, slot, flags. + for n in 0..3u8 { + let mask = if n == 2 { 3 } else { 7 }; + put( + &mut data, + 0x24 + 8 * n as usize, + &[6, n + 1, mask, n, 0, n + 1, n, 0], + ); + } + put(&mut data, 0x124, &3u32.to_le_bytes()); + put(&mut data, 0x134, &2u32.to_le_bytes()); // SPI_PS_INPUT_ADDR: centre i/j + // No export patches: the shader's exports carry 32-bit values. + for mrt in 0..8 { + put(&mut data, 0x14c + mrt * 404, &u32::MAX.to_le_bytes()); + } + let p = Program { + stage: PS, + code: pixel(), + vgprs: 32, + sgprs: 66, + layout: vec![(0, 0), (1, 1), (2, 2), (3, 3)], + used: vec![ + (2, 0, 0, 0, 0, 4), + (2, 1, 1, 0, 1, 4), + (0, 2, 2, 0, 0, 8), + (1, 3, 3, 0, 0, 4), + ], + stage_data: data, + }; + let isg = signature(&interpolants(), true); + let osg = signature(&[Element("SV_Target", 64, 0, 0xF)], false); + container(0, &p, &[(b"ISG1", isg), (b"OSG1", osg)]) +} + +pub fn compute_container() -> Vec { + let mut data = vec![0u8; 0x40]; + // COMPUTE_PGM_RSRC2: one user SGPR, group ids x and y, thread ids x + // and y. + let rsrc2 = 1 << 1 | 1 << 7 | 1 << 8 | 1 << 11; + put(&mut data, 0x24, &(rsrc2 as u32).to_le_bytes()); + for (i, n) in [crate::scene::GROUP, crate::scene::GROUP, 1] + .iter() + .enumerate() + { + put(&mut data, 0x28 + 4 * i, &n.to_le_bytes()); + } + let p = Program { + stage: CS, + code: compute(), + vgprs: 32, + sgprs: 32, + layout: vec![(0, 0)], + used: vec![(0, 0, 0, 0, 0, 8), (3, 0, 0, 8, 0, 8), (3, 0, 0, 16, 1, 4)], + stage_data: data, + }; + container(5, &p, &[]) +} diff --git a/tests/fixtures/conformance/src/gpu.rs b/tests/fixtures/conformance/src/gpu.rs new file mode 100644 index 0000000000..8654b08259 --- /dev/null +++ b/tests/fixtures/conformance/src/gpu.rs @@ -0,0 +1,1380 @@ +//! The GPU frame (docs/acceptance.md, step 3): the scene of [`crate::scene`] +//! drawn as a title draws, through the console's D3D12 (`d3d12_xs.dll`): +//! device, queue, allocators and lists, descriptor heaps, root signatures, +//! a graphics pipeline from a stream and a compute pipeline (their shaders +//! the hand-assembled GFX10 programs of [`crate::gfx10`]), vertex, index +//! and constant buffers in title memory, a texture uploaded with a copy, a +//! depth buffer, four indexed draws, a compute pass, a fence; then the +//! compute pass's output copied to a read-back buffer and read. +//! +//! The device's methods are reached by the byte offsets of their slots, +//! the layout VIctory implements (`crates/victory-gpu/src/device.rs` and +//! beside it): the PC interface's order (public D3D12 reference), console +//! additions after it. Structures are the public D3D12 ones. +//! +//! What is checked: each call's result, then the frame against the same +//! scene drawn natively on WARP by the harness from equivalent HLSL +//! (within a small tolerance), and pixels whose value is exact by +//! construction (the clear colour; the glowing pyramid, where it is in +//! front, and not where a cube hides it). + +use std::ffi::c_void; + +use crate::rt::{Guid, Hresult, S_OK}; +use crate::scene::{self, HEIGHT, WIDTH}; +use crate::tap::Tap; + +type Obj = *mut c_void; + +#[link(name = "d3d12_xs", kind = "raw-dylib")] +unsafe extern "system" { + fn D3D12XboxCreateDevice( + adapter: *const c_void, + parameters: *const u32, + iid: *const Guid, + out: *mut Obj, + ) -> Hresult; + fn D3D12SerializeRootSignature( + desc: *const RootSignatureDesc, + version: u32, + blob: *mut Obj, + errors: *mut Obj, + ) -> Hresult; +} + +/// Calls the method at byte offset `$at` of `$obj`'s table: +/// `call!(obj, 0x40, fn(u32) -> Hresult, 7)`. +macro_rules! call { + ($obj:expr, $at:expr, fn($($t:ty),* $(,)?) $(-> $r:ty)?, $($arg:expr),* $(,)?) => {{ + let obj: Obj = $obj; + // SAFETY: (the caller) `obj` is a live object whose table has this + // method at this offset, with this signature. + unsafe { + let table = *obj.cast::<*const *const c_void>(); + let f: extern "system" fn(Obj $(, $t)*) $(-> $r)? = + std::mem::transmute(*table.add($at / 8)); + f(obj $(, $arg)*) + } + }}; +} + +// Interface ids (public D3D12 headers). +const DEVICE: Guid = Guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], +); +const QUEUE: Guid = Guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], +); +const ALLOCATOR: Guid = Guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], +); +const LIST: Guid = Guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], +); +const HEAP: Guid = Guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], +); +const ROOT: Guid = Guid( + 0xc54a6b66, + 0x72df, + 0x4ee8, + [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14], +); +const RESOURCE: Guid = Guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], +); +const FENCE: Guid = Guid( + 0x0a753dcf, + 0xc4d8, + 0x4b91, + [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], +); +const PIPELINE: Guid = Guid( + 0x765a30f3, + 0xf624, + 0x4c6f, + [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45], +); + +/// The device interface version VIctory's layouts follow (2.4). +const VERSION: u32 = 0x0002_0004; + +// DXGI formats. +const RGBA8: u32 = 28; +const D32: u32 = 40; +const RG32F: u32 = 16; +const RGB32F: u32 = 6; +const R16U: u32 = 57; +const R32_TYPELESS: u32 = 39; + +// Resource states. +const COMMON: u32 = 0; +const UNORDERED: u32 = 0x8; +const RENDER_TARGET: u32 = 0x4; +const DEPTH_WRITE: u32 = 0x10; +const NON_PIXEL: u32 = 0x40; +const PIXEL: u32 = 0x80; +const COPY_DEST: u32 = 0x400; +const COPY_SOURCE: u32 = 0x800; +const GENERIC_READ: u32 = 0xAC3; + +/// Bytes the read-back buffer holds: four floats per pixel. +const FRAME_BYTES: u64 = (WIDTH * HEIGHT * 16) as u64; + +#[repr(C)] +struct HeapProperties { + kind: u32, + cpu_page: u32, + pool: u32, + creation_nodes: u32, + visible_nodes: u32, +} + +#[repr(C)] +struct ResourceDesc { + dimension: u32, + alignment: u64, + width: u64, + height: u32, + depth: u16, + mips: u16, + format: u32, + samples: u32, + quality: u32, + layout: u32, + flags: u32, +} + +#[repr(C)] +struct ClearValue { + format: u32, + value: [f32; 4], +} + +#[repr(C)] +struct Range { + kind: u32, + count: u32, + base: u32, + space: u32, + offset: u32, +} + +/// A root parameter: its type, then (a descriptor table) the ranges' +/// count and address, at 8 and 16 (the union's pointer alignment). +#[repr(C)] +struct Param { + kind: u32, + _pad: u32, + ranges_count: u32, + _pad2: u32, + ranges: *const Range, + visibility: u32, +} + +#[repr(C)] +struct RootSignatureDesc { + count: u32, + params: *const Param, + statics_count: u32, + statics: *const c_void, + flags: u32, +} + +#[repr(C)] +struct Barrier { + kind: u32, + flags: u32, + resource: Obj, + subresource: u32, + before: u32, + after: u32, +} + +#[repr(C)] +struct CopyLocation { + resource: Obj, + kind: u32, + offset: u64, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, +} + +#[repr(C)] +struct BufferView { + address: u64, + size: u32, + stride_or_format: u32, +} + +#[repr(C)] +struct InputElement { + name: *const u8, + index: u32, + format: u32, + slot: u32, + offset: u32, + class: u32, + step: u32, +} + +#[repr(C)] +struct Plane { + token: u64, + count: u32, + resources: *const Obj, +} + +#[repr(C)] +struct ComputeDesc { + root: Obj, + code: *const u8, + size: usize, + nodes: u32, + cached: *const u8, + cached_size: usize, + flags: u32, +} + +/// A pipeline stream (public `D3D12_PIPELINE_STATE_STREAM_DESC`): each +/// subobject a type then its data, aligned to pointers. +#[derive(Default)] +struct Stream(Vec); + +impl Stream { + fn push(&mut self, kind: u32, data: &[u8], pointers: bool) { + self.0.extend(kind.to_le_bytes()); + if pointers { + self.0.extend([0; 4]); + } + self.0.extend(data); + self.0.resize(self.0.len().next_multiple_of(8), 0); + } +} + +fn words(w: &[u32]) -> Vec { + w.iter().flat_map(|w| w.to_le_bytes()).collect() +} + +fn pointer(p: *const u8, size: usize) -> Vec { + let mut out = (p as u64).to_le_bytes().to_vec(); + out.extend((size as u64).to_le_bytes()); + out +} + +/// What the run hands back: the frame read back (RGBA floats per pixel). +pub struct Run { + pub image: Vec, +} + +/// Everything the frame uses. +struct Gpu { + device: Obj, + queue: Obj, + allocators: [Obj; 2], + lists: [Obj; 2], + fence: Obj, + fence_value: u64, + views: Obj, + samplers: Obj, + targets: Obj, + depths: Obj, + view_cpu: u64, + view_gpu: u64, + sampler_gpu: u64, + target_cpu: u64, + depth_cpu: u64, + graphics_root: Obj, + compute_root: Obj, + graphics: Obj, + compute: Obj, + vertices: Obj, + indices: Obj, + constants: Obj, + constants_cpu: *mut u8, + texture: Obj, + upload: Obj, + target: Obj, + depth: Obj, + shown: Obj, + output: Obj, + readback: Obj, + geometry: scene::Geometry, + /// The shader containers (pipelines point at them while created). + _shaders: [Vec; 3], +} + +const VIEW_SIZE: u64 = 32; + +impl Gpu { + fn heap(&self, t: &mut Tap, kind: u32, count: u32, visible: bool, what: &str) -> Obj { + let desc = [kind, count, u32::from(visible), 0]; + let mut heap = std::ptr::null_mut(); + let hr = call!( + self.device, + 0x70, + fn(*const u32, *const Guid, *mut Obj) -> Hresult, + desc.as_ptr(), + &HEAP, + &mut heap + ); + t.eq(hr, S_OK, &format!("gpu: CreateDescriptorHeap ({what})")); + heap + } + + /// A committed resource: `(heap type, description, state, clear)`. + fn resource( + &self, + t: &mut Tap, + heap: u32, + desc: ResourceDesc, + state: u32, + clear: Option, + what: &str, + ) -> Obj { + let props = HeapProperties { + kind: heap, + cpu_page: 0, + pool: 0, + creation_nodes: 0, + visible_nodes: 0, + }; + let clear_ptr = clear + .as_ref() + .map_or(std::ptr::null(), |c| c as *const ClearValue); + let mut out = std::ptr::null_mut(); + let hr = call!( + self.device, + 0xd8, + fn( + *const HeapProperties, + u32, + *const ResourceDesc, + u32, + *const ClearValue, + *const Guid, + *mut Obj, + ) -> Hresult, + &props, + 0, + &desc, + state, + clear_ptr, + &RESOURCE, + &mut out + ); + t.eq(hr, S_OK, &format!("gpu: CreateCommittedResource ({what})")); + out + } + + fn map(&self, resource: Obj) -> *mut u8 { + let mut at = std::ptr::null_mut(); + let hr = call!( + resource, + 0x40, + fn(u32, *const [usize; 2], *mut *mut u8) -> Hresult, + 0, + std::ptr::null(), + &mut at + ); + if hr != S_OK { std::ptr::null_mut() } else { at } + } + + fn address(resource: Obj) -> u64 { + call!(resource, 0x58, fn() -> u64,) + } + + fn barrier(&self, list: Obj, resource: Obj, before: u32, after: u32) { + let b = Barrier { + kind: 0, + flags: 0, + resource, + subresource: u32::MAX, + before, + after, + }; + call!(list, 0xd0, fn(u32, *const Barrier) -> u32, 1, &b); + } + + /// Closes list `n`, runs it and waits for it with the fence; whether the + /// fence reached the value signalled. + fn submit(&mut self, n: usize) -> (Hresult, bool) { + let list = self.lists[n]; + let hr = call!(list, 0x48, fn() -> Hresult,); + call!(self.queue, 0x50, fn(u32, *const Obj), 1, &list); + self.fence_value += 1; + call!( + self.queue, + 0x70, + fn(Obj, u64) -> Hresult, + self.fence, + self.fence_value + ); + // A null event: wait here until the fence reaches the value. + call!( + self.fence, + 0x48, + fn(u64, *mut c_void) -> Hresult, + self.fence_value, + std::ptr::null_mut() + ); + let done = call!(self.fence, 0x40, fn() -> u64,); + (hr, done >= self.fence_value) + } + + fn reset(&self, n: usize, pipeline: Obj) -> Hresult { + call!(self.allocators[n], 0x40, fn() -> Hresult,); + call!( + self.lists[n], + 0x50, + fn(Obj, Obj) -> Hresult, + self.allocators[n], + pipeline + ) + } +} + +fn root_signature(t: &mut Tap, device: Obj, params: &[Param], flags: u32, what: &str) -> Obj { + let desc = RootSignatureDesc { + count: params.len() as u32, + params: params.as_ptr(), + statics_count: 0, + statics: std::ptr::null(), + flags, + }; + let (mut blob, mut errors) = (std::ptr::null_mut(), std::ptr::null_mut()); + // SAFETY: a valid description and out pointers. + let hr = unsafe { D3D12SerializeRootSignature(&desc, 1, &mut blob, &mut errors) }; + t.eq( + hr, + S_OK, + &format!("gpu: D3D12SerializeRootSignature ({what})"), + ); + if hr != S_OK || blob.is_null() { + return std::ptr::null_mut(); + } + let bytes = call!(blob, 0x18, fn() -> *const u8,); + let size = call!(blob, 0x20, fn() -> usize,); + let mut root = std::ptr::null_mut(); + let hr = call!( + device, + 0x80, + fn(u32, *const u8, usize, *const Guid, *mut Obj) -> Hresult, + 0, + bytes, + size, + &ROOT, + &mut root + ); + t.eq(hr, S_OK, &format!("gpu: CreateRootSignature ({what})")); + call!(blob, 0x10, fn() -> u32,); + root +} + +fn table(ranges: &[Range]) -> Param { + Param { + kind: 0, + _pad: 0, + _pad2: 0, + ranges_count: ranges.len() as u32, + ranges: ranges.as_ptr(), + visibility: 0, + } +} + +fn range(kind: u32, base: u32) -> Range { + Range { + kind, + count: 1, + base, + space: 0, + offset: u32::MAX, + } +} + +fn buffer(width: u64, flags: u32) -> ResourceDesc { + ResourceDesc { + dimension: 1, + alignment: 0, + width, + height: 1, + depth: 1, + mips: 1, + format: 0, + samples: 1, + quality: 0, + layout: 1, + flags, + } +} + +fn texture(width: u32, height: u32, format: u32, flags: u32) -> ResourceDesc { + ResourceDesc { + dimension: 3, + alignment: 0, + width: u64::from(width), + height, + depth: 1, + mips: 1, + format, + samples: 1, + quality: 0, + layout: 0, + flags, + } +} + +fn setup(t: &mut Tap) -> Option { + let mut parameters = [0u32; 32]; + parameters[0] = VERSION; + let mut device = std::ptr::null_mut(); + // SAFETY: parameters and out pointers outlive the call. + let hr = unsafe { + D3D12XboxCreateDevice(std::ptr::null(), parameters.as_ptr(), &DEVICE, &mut device) + }; + t.eq(hr, S_OK, "gpu: D3D12XboxCreateDevice"); + if hr != S_OK || device.is_null() { + return None; + } + let mut queue = std::ptr::null_mut(); + let desc = [0u32; 4]; // direct, normal priority + let hr = call!( + device, + 0x40, + fn(*const u32, *const Guid, *mut Obj) -> Hresult, + desc.as_ptr(), + &QUEUE, + &mut queue + ); + t.eq(hr, S_OK, "gpu: CreateCommandQueue"); + let mut allocators = [std::ptr::null_mut(); 2]; + let mut lists = [std::ptr::null_mut(); 2]; + let mut made = 0; + for n in 0..2 { + made += i32::from( + call!( + device, + 0x48, + fn(u32, *const Guid, *mut Obj) -> Hresult, + 0, + &ALLOCATOR, + &mut allocators[n] + ) == S_OK, + ); + made += i32::from( + call!( + device, + 0x60, + fn(u32, u32, Obj, Obj, *const Guid, *mut Obj) -> Hresult, + 0, + 0, + allocators[n], + std::ptr::null_mut(), + &LIST, + &mut lists[n] + ) == S_OK, + ); + } + t.eq( + made, + 4, + "gpu: CreateCommandAllocator and CreateCommandList, twice", + ); + let mut fence = std::ptr::null_mut(); + let hr = call!( + device, + 0x120, + fn(u64, u32, *const Guid, *mut Obj) -> Hresult, + 0, + 0, + &FENCE, + &mut fence + ); + t.eq(hr, S_OK, "gpu: CreateFence"); + if queue.is_null() || fence.is_null() || made != 4 { + return None; + } + + // Root signatures: per draw the scene's constants (b0), the draw's + // (b1), the texture (t0) and its sampler (s0), each a table; for the + // compute pass one table of the frame (t0), the texture shown (u0) and + // the read-back buffer (u1). + let ranges = [range(2, 0), range(2, 1), range(0, 0), range(3, 0)]; + let params: Vec = ranges + .iter() + .map(|r| table(std::slice::from_ref(r))) + .collect(); + // Input-assembler input layout allowed. + let graphics_root = root_signature(t, device, ¶ms, 1, "graphics"); + let compute_ranges = [ + Range { + kind: 0, + count: 1, + base: 0, + space: 0, + offset: 0, + }, + Range { + kind: 1, + count: 1, + base: 0, + space: 0, + offset: 1, + }, + Range { + kind: 1, + count: 1, + base: 1, + space: 0, + offset: 2, + }, + ]; + let compute_root = root_signature(t, device, &[table(&compute_ranges)], 0, "compute"); + + let shaders = [ + crate::gfx10::vertex_container(), + crate::gfx10::pixel_container(), + crate::gfx10::compute_container(), + ]; + // The graphics pipeline, as a stream. + let names = [c"POSITION", c"NORMAL", c"TEXCOORD"]; + let elements: Vec = [(RGB32F, 0), (RGB32F, 12), (RG32F, 24)] + .iter() + .zip(names) + .map(|(&(format, offset), name)| InputElement { + name: name.as_ptr().cast(), + index: 0, + format, + slot: 0, + offset, + class: 0, + step: 0, + }) + .collect(); + let mut s = Stream::default(); + s.push(0, &(graphics_root as u64).to_le_bytes(), true); + s.push(1, &pointer(shaders[0].as_ptr(), shaders[0].len()), true); + s.push(2, &pointer(shaders[1].as_ptr(), shaders[1].len()), true); + // Rasterizer: solid, cull back faces (clockwise is front), depth clip. + s.push(10, &words(&[3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0]), false); + // Depth: test less, write; no stencil. + let keep = [1, 1, 1, 8]; + let mut depth = vec![1, 1, 2, 0, 0xffff]; + depth.extend(keep); + depth.extend(keep); + s.push(11, &words(&depth), false); + let mut layout = pointer(elements.as_ptr().cast(), 0); + layout[8..16].copy_from_slice(&(elements.len() as u64).to_le_bytes()); + s.push(12, &layout, true); + s.push(14, &3u32.to_le_bytes(), false); // triangles + s.push(15, &words(&[RGBA8, 0, 0, 0, 0, 0, 0, 0, 1]), false); + s.push(16, &D32.to_le_bytes(), false); + s.push(17, &words(&[1, 0]), false); + let stream = [s.0.len() as u64, s.0.as_ptr() as u64]; + let mut graphics = std::ptr::null_mut(); + let hr = call!( + device, + 0x2b0, + fn(*const [u64; 2], *const Guid, *mut Obj) -> Hresult, + &stream, + &PIPELINE, + &mut graphics + ); + t.eq( + hr, + S_OK, + "gpu: CreatePipelineState (vertex and pixel shaders, from a stream)", + ); + let desc = ComputeDesc { + root: compute_root, + code: shaders[2].as_ptr(), + size: shaders[2].len(), + nodes: 0, + cached: std::ptr::null(), + cached_size: 0, + flags: 0, + }; + let mut compute = std::ptr::null_mut(); + let hr = call!( + device, + 0x58, + fn(*const ComputeDesc, *const Guid, *mut Obj) -> Hresult, + &desc, + &PIPELINE, + &mut compute + ); + t.eq(hr, S_OK, "gpu: CreateComputePipelineState"); + + let null = std::ptr::null_mut(); + let mut g = Gpu { + device, + queue, + allocators, + lists, + fence, + fence_value: 0, + views: null, + samplers: null, + targets: null, + depths: null, + view_cpu: 0, + view_gpu: 0, + sampler_gpu: 0, + target_cpu: 0, + depth_cpu: 0, + graphics_root, + compute_root, + graphics, + compute, + vertices: null, + indices: null, + constants: null, + constants_cpu: std::ptr::null_mut(), + texture: null, + upload: null, + target: null, + depth: null, + shown: null, + output: null, + readback: null, + geometry: scene::Geometry::new(), + _shaders: shaders, + }; + + // Descriptor heaps: views (0 scene constants, 1-4 the draws', 5 the + // texture, 6 the frame, 7 the texture shown, 8 the read-back buffer), + // one sampler, one render target, one depth buffer. + g.views = g.heap(t, 0, 16, true, "views"); + g.samplers = g.heap(t, 1, 1, true, "samplers"); + g.targets = g.heap(t, 2, 1, false, "render targets"); + g.depths = g.heap(t, 3, 1, false, "depth"); + if [g.views, g.samplers, g.targets, g.depths] + .iter() + .any(|h| h.is_null()) + { + return None; + } + let increment = |kind| call!(device, 0x78, fn(u32) -> u32, kind); + t.eq( + increment(0), + VIEW_SIZE as u32, + "gpu: a view descriptor takes 32 bytes", + ); + // The console's: the handles themselves, not through a pointer. + let start = |heap: Obj, at: usize| call!(heap, at, fn() -> u64,); + g.view_cpu = start(g.views, 0x48); + g.view_gpu = start(g.views, 0x50); + g.sampler_gpu = start(g.samplers, 0x50); + g.target_cpu = start(g.targets, 0x48); + g.depth_cpu = start(g.depths, 0x48); + + // Buffers in upload memory, written by the CPU. + let geometry = &g.geometry; + let vertex_bytes = (geometry.vertices.len() * size_of::()) as u64; + let index_bytes = (geometry.indices.len() * 2).next_multiple_of(4) as u64; + g.vertices = g.resource( + t, + 2, + buffer(vertex_bytes, 0), + GENERIC_READ, + None, + "vertex buffer", + ); + g.indices = g.resource( + t, + 2, + buffer(index_bytes, 0), + GENERIC_READ, + None, + "index buffer", + ); + g.constants = g.resource( + t, + 2, + buffer(256 * 5, 0), + GENERIC_READ, + None, + "constant buffer", + ); + let texel_bytes = u64::from(scene::TEXTURE * scene::TEXTURE * 4); + g.upload = g.resource( + t, + 2, + buffer(texel_bytes, 0), + GENERIC_READ, + None, + "texture upload buffer", + ); + g.texture = g.resource( + t, + 1, + texture(scene::TEXTURE, scene::TEXTURE, RGBA8, 0), + COPY_DEST, + None, + "texture", + ); + let clear = scene::CLEAR.map(|c| f32::from(c) / 255.0); + g.target = g.resource( + t, + 1, + texture(WIDTH, HEIGHT, RGBA8, 1), + RENDER_TARGET, + Some(ClearValue { + format: RGBA8, + value: clear, + }), + "render target", + ); + g.depth = g.resource( + t, + 1, + texture(WIDTH, HEIGHT, D32, 2), + DEPTH_WRITE, + Some(ClearValue { + format: D32, + value: [1.0, 0.0, 0.0, 0.0], + }), + "depth buffer", + ); + g.shown = g.resource( + t, + 1, + texture(WIDTH, HEIGHT, RGBA8, 4), + UNORDERED, + None, + "texture shown", + ); + g.output = g.resource( + t, + 1, + buffer(FRAME_BYTES, 4), + UNORDERED, + None, + "compute output buffer", + ); + g.readback = g.resource( + t, + 3, + buffer(FRAME_BYTES, 0), + COPY_DEST, + None, + "read-back buffer", + ); + let all = [ + g.vertices, + g.indices, + g.constants, + g.upload, + g.texture, + g.target, + g.depth, + g.shown, + g.output, + g.readback, + ]; + if all.iter().any(|r| r.is_null()) { + return None; + } + let write = |r: Obj, bytes: &[u8]| { + let at = g.map(r); + if !at.is_null() { + // SAFETY: the mapping holds the resource's bytes, at least these. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), at, bytes.len()) }; + } + !at.is_null() + }; + // SAFETY: plain data. + let vertex_data = unsafe { + std::slice::from_raw_parts( + geometry.vertices.as_ptr().cast::(), + vertex_bytes as usize, + ) + }; + let index_data: Vec = geometry + .indices + .iter() + .flat_map(|i| i.to_le_bytes()) + .collect(); + let mapped = write(g.vertices, vertex_data) + && write(g.indices, &index_data) + && write(g.upload, &scene::texels()); + g.constants_cpu = g.map(g.constants); + t.check( + mapped && !g.constants_cpu.is_null(), + "gpu: upload buffers map", + || "Map failed".into(), + ); + if !mapped || g.constants_cpu.is_null() { + return None; + } + + // Views. + let view = |n: u64| g.view_cpu + n * VIEW_SIZE; + let constants = Gpu::address(g.constants); + for n in 0..5 { + let desc = [constants + 256 * n, 256]; + call!(device, 0x88, fn(*const [u64; 2], u64), &desc, view(n)); + } + // Format, 2D, the default component mapping, then (from 16 bytes) the + // most detailed level 0 and one level. + let srv = [RGBA8, 4, 0x1688, 0, 0, 1, 0, 0, 0, 0]; + call!( + device, + 0x90, + fn(Obj, *const [u32; 10], u64), + g.texture, + &srv, + view(5) + ); + call!( + device, + 0x90, + fn(Obj, *const [u32; 10], u64), + g.target, + &srv, + view(6) + ); + let uav = [RGBA8, 4, 0, 0, 0, 0, 0, 0, 0, 0]; + call!( + device, + 0x98, + fn(Obj, Obj, *const [u32; 10], u64), + g.shown, + std::ptr::null_mut(), + &uav, + view(7) + ); + // Raw: R32 elements, the raw flag. + let raw = [ + R32_TYPELESS, + 1, + 0, + 0, + (FRAME_BYTES / 4) as u32, + 0, + 0, + 0, + 1, + 0, + ]; + call!( + device, + 0x98, + fn(Obj, Obj, *const [u32; 10], u64), + g.output, + std::ptr::null_mut(), + &raw, + view(8) + ); + // Linear filtering, wrapping. + let mut sampler = [0x15u32, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, f32::MAX.to_bits()]; + sampler[4] = 0f32.to_bits(); + call!( + device, + 0xb0, + fn(*const [u32; 13], u64), + &sampler, + start(g.samplers, 0x48) + ); + call!( + device, + 0xa0, + fn(Obj, *const u8, u64), + g.target, + std::ptr::null(), + g.target_cpu + ); + call!( + device, + 0xa8, + fn(Obj, *const u8, u64), + g.depth, + std::ptr::null(), + g.depth_cpu + ); + Some(g) +} + +impl Gpu { + /// Records and runs one frame at time `at`: the draws, the compute pass + /// (and the texture's upload if `first`); then copies the compute + /// output to the read-back buffer, unless `present`, which leaves the + /// texture shown in the state for presenting instead. + fn frame(&mut self, at: f32, first: bool, present: bool) -> (Hresult, Hresult, bool) { + let (scene, draws) = scene::frame(at); + // SAFETY: the constant buffer is mapped and 1,280 bytes long. + unsafe { + let base = self.constants_cpu; + std::ptr::copy_nonoverlapping((&raw const scene).cast::(), base, 256); + for (n, (_, mesh)) in draws.iter().enumerate() { + std::ptr::copy_nonoverlapping( + (&raw const *mesh).cast::(), + base.add(256 * (n + 1)), + 256, + ); + } + } + let list = self.lists[0]; + if !first { + self.reset(0, std::ptr::null_mut()); + } + if first { + let dst = CopyLocation { + resource: self.texture, + kind: 0, + offset: 0, + format: 0, + width: 0, + height: 0, + depth: 0, + row_pitch: 0, + }; + let src = CopyLocation { + resource: self.upload, + kind: 1, + offset: 0, + format: RGBA8, + width: scene::TEXTURE, + height: scene::TEXTURE, + depth: 1, + row_pitch: scene::TEXTURE * 4, + }; + call!( + list, + 0x80, + fn(*const CopyLocation, u32, u32, u32, *const CopyLocation, *const u32), + &dst, + 0, + 0, + 0, + &src, + std::ptr::null() + ); + self.barrier(list, self.texture, COPY_DEST, PIXEL); + } else if present { + self.barrier(list, self.shown, COMMON, UNORDERED); + } + let heaps = [self.views, self.samplers]; + call!(list, 0x100, fn(u32, *const Obj), 2, heaps.as_ptr()); + call!(list, 0x110, fn(Obj), self.graphics_root); + let clear = scene::CLEAR.map(|c| f32::from(c) / 255.0); + call!( + list, + 0x1a0, + fn(u64, *const [f32; 4], u32, *const [i32; 4]), + self.target_cpu, + &clear, + 0, + std::ptr::null() + ); + call!( + list, + 0x198, + fn(u64, u32, f32, u8, u32, *const [i32; 4]), + self.depth_cpu, + 1, + 1.0, + 0, + 0, + std::ptr::null() + ); + call!( + list, + 0x190, + fn(u32, *const u64, i32, *const u64), + 1, + &self.target_cpu, + 0, + &self.depth_cpu + ); + let viewport = [0.0, 0.0, WIDTH as f32, HEIGHT as f32, 0.0, 1.0f32]; + call!(list, 0xa8, fn(u32, *const [f32; 6]), 1, &viewport); + let scissor = [0, 0, WIDTH as i32, HEIGHT as i32]; + call!(list, 0xb0, fn(u32, *const [i32; 4]), 1, &scissor); + call!(list, 0xa0, fn(u32), 4); // triangle list + call!(list, 0xc8, fn(Obj), self.graphics); + let vertices = BufferView { + address: Gpu::address(self.vertices), + size: (self.geometry.vertices.len() * 32) as u32, + stride_or_format: scene::STRIDE, + }; + call!( + list, + 0x180, + fn(u32, u32, *const BufferView), + 0, + 1, + &vertices + ); + let indices = BufferView { + address: Gpu::address(self.indices), + size: (self.geometry.indices.len() * 2) as u32, + stride_or_format: R16U, + }; + call!(list, 0x178, fn(*const BufferView), &indices); + let table = |n: u64| self.view_gpu + n * VIEW_SIZE; + call!(list, 0x120, fn(u32, u64), 0, table(0)); + call!(list, 0x120, fn(u32, u64), 2, table(5)); + call!(list, 0x120, fn(u32, u64), 3, self.sampler_gpu); + for (n, &(mesh, _)) in draws.iter().enumerate() { + let m = self.geometry.meshes[mesh]; + call!(list, 0x120, fn(u32, u64), 1, table(n as u64 + 1)); + call!( + list, + 0x68, + fn(u32, u32, u32, i32, u32), + m.indices, + 1, + m.first_index, + m.base_vertex, + 0 + ); + } + // The compute pass reads the frame and writes the texture shown and + // the buffer. + self.barrier(list, self.target, RENDER_TARGET, NON_PIXEL); + call!(list, 0x108, fn(Obj), self.compute_root); + call!(list, 0xc8, fn(Obj), self.compute); + call!(list, 0x118, fn(u32, u64), 0, table(6)); + call!( + list, + 0x70, + fn(u32, u32, u32), + WIDTH / scene::GROUP, + HEIGHT / scene::GROUP, + 1 + ); + self.barrier(list, self.target, NON_PIXEL, RENDER_TARGET); + if present { + self.barrier(list, self.shown, UNORDERED, COMMON); + } + let (closed, done) = self.submit(0); + if present { + return (closed, S_OK, done); + } + + // The compute output to the read-back buffer (not while only + // showing frames). + let copy = self.lists[1]; + if !first { + self.reset(1, std::ptr::null_mut()); + } + self.barrier(copy, self.output, UNORDERED, COPY_SOURCE); + call!( + copy, + 0x78, + fn(Obj, u64, Obj, u64, u64), + self.readback, + 0, + self.output, + 0, + FRAME_BYTES + ); + self.barrier(copy, self.output, COPY_SOURCE, UNORDERED); + let (copied, copy_done) = self.submit(1); + (closed, copied, done && copy_done) + } + + fn read(&self) -> Vec { + let at = self.map(self.readback); + if at.is_null() { + return Vec::new(); + } + let mut out = vec![0f32; (FRAME_BYTES / 4) as usize]; + // SAFETY: the mapping holds the buffer's bytes. + unsafe { + std::ptr::copy_nonoverlapping(at, out.as_mut_ptr().cast::(), FRAME_BYTES as usize) + }; + out + } + + /// Begins a frame (waits for the next frame tick): its token. + fn begin(&self) -> u64 { + let mut token = 0; + call!( + self.device, + 0x280, + fn(u32, u32, *const u8, u32, *mut u64) -> Hresult, + 0, + 100, + std::ptr::null(), + 0, + &mut token + ); + token + } + + fn present(&self, token: u64) -> Hresult { + let plane = Plane { + token, + count: 1, + resources: &self.shown, + }; + call!( + self.queue, + 0xf0, + fn(u32, *const Plane, *const u8) -> Hresult, + 1, + &plane, + std::ptr::null() + ) + } +} + +/// A pixel of `image` as RGBA8. +fn pixel(image: &[f32], x: u32, y: u32) -> [u8; 4] { + let at = ((y * WIDTH + x) * 4) as usize; + std::array::from_fn(|c| (image[at + c].clamp(0.0, 1.0) * 255.0).round() as u8) +} + +/// Runs the frame; `reference` is the WARP image (RGBA floats per pixel), +/// `window_seconds` how long to keep presenting it, animated, afterwards. +pub fn run(t: &mut Tap, reference: Option<&[f32]>, window_seconds: u32) -> Run { + let Some(mut g) = setup(t) else { + return Run { image: Vec::new() }; + }; + // Host pipelines are made on first use, by workers; a draw whose + // pipeline is not made within the frame's time is left out (VIctory's + // own budget: a title's frames go on meanwhile). Frames are drawn + // until two in a row read back the same, with the scene in them. + let mut image = Vec::new(); + let mut frames = 0; + let mut calls = (S_OK, S_OK, true); + let background = scene::CLEAR; + while frames < 30 { + g.begin(); + let r = g.frame(0.0, frames == 0, false); + if r != (S_OK, S_OK, true) { + calls = r; + } + frames += 1; + let next = g.read(); + let drawn = !next.is_empty() && pixel(&next, WIDTH / 2, HEIGHT - 8) != background; + let same = next == image; + image = next; + if drawn && same { + break; + } + } + t.eq(calls.0, S_OK, "gpu: Close (draw list)"); + t.eq(calls.1, S_OK, "gpu: Close (copy list)"); + t.check( + calls.2, + "gpu: the fence reaches each value signalled after ExecuteCommandLists", + || "it did not".into(), + ); + t.check( + frames < 30, + "gpu: the frame is drawn (pipelines made) and the same in two frames in a row", + || format!("not after {frames} frames"), + ); + compare(t, &image, reference); + exact(t, &image); + if window_seconds == 0 { + t.check( + true, + "gpu: PresentX # SKIP no window asked for (VICTORY_CONFORMANCE_WINDOW)", + String::new, + ); + } else { + let started = std::time::Instant::now(); + let mut shown = 0; + let mut presented = S_OK; + while started.elapsed().as_secs() < u64::from(window_seconds) { + let token = g.begin(); + g.frame(started.elapsed().as_secs_f32(), false, true); + let hr = g.present(token); + if hr != S_OK { + presented = hr; + } + shown += 1; + } + t.eq(presented, S_OK, &format!("gpu: PresentX ({shown} frames)")); + } + Run { image } +} + +/// The frame against the WARP reference: channels within 4/255, except +/// on a few edge pixels (rasterisation rules leave the GPUs free to +/// differ by a pixel along edges, and filtering by a little). +fn compare(t: &mut Tap, image: &[f32], reference: Option<&[f32]>) { + let name = "gpu: the frame matches WARP's drawing of the same scene from HLSL"; + let Some(reference) = reference else { + t.check(true, &format!("{name} # SKIP no reference"), String::new); + return; + }; + if reference.len() != image.len() { + t.check(false, name, || { + format!("{} values, the reference {}", image.len(), reference.len()) + }); + return; + } + let (mut off, mut worst, mut sum) = (0usize, 0f32, 0f64); + let mut first = None; + for (p, (a, b)) in image.chunks(4).zip(reference.chunks(4)).enumerate() { + let d = (0..4).map(|c| (a[c] - b[c]).abs()).fold(0f32, f32::max); + sum += f64::from(d); + worst = worst.max(d); + if d > 4.0 / 255.0 || d.is_nan() { + off += 1; + first.get_or_insert((p, a.to_vec(), b.to_vec())); + } + } + let pixels = image.len() / 4; + let mean = sum / pixels as f64 * 255.0; + t.check(off * 1000 <= pixels && mean < 0.5, name, || { + format!("{off} of {pixels} pixels differ by more than 4/255 (largest {:.1}/255, mean {mean:.3}/255); first {first:?}", worst * 255.0) + }); +} + +/// Pixels exact by construction: the clear colour above the ground (the +/// blur of equal neighbours is the colour itself), the pyramid's glow +/// where it is nearest, and no glow where a cube in front hides it. +fn exact(t: &mut Tap, image: &[f32]) { + if image.is_empty() { + return; + } + let clear = scene::CLEAR; + let glow = scene::GLOW; + for (x, y) in [(1, 0), (WIDTH - 2, 0), (WIDTH / 2, 2)] { + t.eq( + pixel(image, x, y), + clear, + &format!("gpu: pixel ({x}, {y}) is the clear colour"), + ); + } + let (gx, gy) = scene::GLOW_PIXEL; + t.eq( + pixel(image, gx, gy), + glow, + &format!("gpu: pixel ({gx}, {gy}) is the pyramid's glow"), + ); + let (hx, hy) = scene::HIDDEN_PIXEL; + let hidden = pixel(image, hx, hy); + t.check( + hidden != glow && hidden != clear, + &format!("gpu: pixel ({hx}, {hy}), the pyramid behind a cube, is the cube"), + || format!("seen {hidden:?}"), + ); +} diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs index dba7515ef2..537f28cc03 100644 --- a/tests/fixtures/conformance/src/lib.rs +++ b/tests/fixtures/conformance/src/lib.rs @@ -19,8 +19,11 @@ mod dstorage; mod files; +mod gfx10; +mod gpu; mod pls; mod rt; +pub mod scene; mod system; mod tap; mod xasync; @@ -63,3 +66,38 @@ pub extern "system" fn conformance_bench(len: *mut usize) -> *const u8 { unsafe { len.write(report.len()) }; report.as_ptr() } + +/// What the harness passes [`conformance_gpu`]: the WARP reference image +/// (RGBA floats per pixel, null for none) and how long to keep presenting +/// frames in a window afterwards (0: no window). The frame read back is +/// handed out in `image` (valid until the next call). +#[repr(C)] +pub struct GpuRun { + pub reference: *const f32, + pub reference_len: usize, + pub window_seconds: u32, + pub image: *const f32, + pub image_len: usize, +} + +/// Runs the GPU frame (`gpu`); returns its TAP report (valid until the +/// next call). +#[unsafe(no_mangle)] +pub extern "system" fn conformance_gpu(run: *mut GpuRun, len: *mut usize) -> *const u8 { + static IMAGE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + // SAFETY: the harness passes its parameters. + let run = unsafe { &mut *run }; + let reference = (!run.reference.is_null()) + // SAFETY: the harness passes `reference_len` floats. + .then(|| unsafe { std::slice::from_raw_parts(run.reference, run.reference_len) }); + let mut t = tap::Tap::default(); + let done = gpu::run(&mut t, reference, run.window_seconds); + let mut image = IMAGE.lock().unwrap_or_else(|e| e.into_inner()); + *image = done.image; + run.image = image.as_ptr(); + run.image_len = image.len(); + let report = t.finish(); + // SAFETY: the harness passes room for the length. + unsafe { len.write(report.len()) }; + report.as_ptr() +} diff --git a/tests/fixtures/conformance/src/scene.rs b/tests/fixtures/conformance/src/scene.rs new file mode 100644 index 0000000000..ac0c3091d3 --- /dev/null +++ b/tests/fixtures/conformance/src/scene.rs @@ -0,0 +1,365 @@ +//! The GPU frame's scene (docs/acceptance.md, "GPU frame"): a ground plane, +//! two cubes and a glowing pyramid, lit by one directional light, textured +//! from a generated checkerboard, then blurred by a compute pass. Plain +//! data and arithmetic, shared by the conformance title (which draws it +//! through VIctory) and its harness (which draws it natively on WARP from +//! equivalent HLSL), so both draw exactly the same thing. + +/// The frame's size in pixels. +pub const WIDTH: u32 = 512; +pub const HEIGHT: u32 = 288; +/// The compute pass's thread group (8 x 8 pixels). +pub const GROUP: u32 = 8; +/// The texture's size in texels (RGBA8). +pub const TEXTURE: u32 = 64; + +/// RGBA8 values, each a whole number of 255ths so that they survive the +/// render target's conversion exactly. +pub const CLEAR: [u8; 4] = [40, 48, 64, 255]; +/// The pyramid's emitted colour (it reflects nothing). +pub const GLOW: [u8; 4] = [255, 170, 40, 255]; +/// Pixels of the checked frame: one inside the pyramid where it is +/// nearest (4 pixels from any edge), and one inside its outline where the +/// nearer cube (drawn after it) hides it. +pub const GLOW_PIXEL: (u32, u32) = (252, 143); +pub const HIDDEN_PIXEL: (u32, u32) = (235, 150); + +/// A vertex as the input layout describes it: position (`POSITION`, three +/// floats at 0), normal (`NORMAL`, three at 12), texture coordinates +/// (`TEXCOORD`, two at 24). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Vertex { + pub position: [f32; 3], + pub normal: [f32; 3], + pub uv: [f32; 2], +} +pub const STRIDE: u32 = 32; + +/// A draw: its indices in the index buffer and its first vertex. +#[derive(Clone, Copy, Debug)] +pub struct Draw { + pub first_index: u32, + pub indices: u32, + pub base_vertex: i32, +} + +/// All meshes in one vertex and one index buffer (16-bit indices). +pub struct Geometry { + pub vertices: Vec, + pub indices: Vec, + /// Ground, cube, pyramid. + pub meshes: [Draw; 3], +} + +type V3 = [f32; 3]; + +fn cross(a: V3, b: V3) -> V3 { + [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] +} + +fn dot(a: V3, b: V3) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn normalize(a: V3) -> V3 { + let l = dot(a, a).sqrt(); + [a[0] / l, a[1] / l, a[2] / l] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f32) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +/// Screen right as seen by a viewer looking at a face with outward normal +/// `n` (left-handed: x right, y up, z into the screen), and screen up. +fn face_axes(n: V3) -> (V3, V3) { + let up = if n[1].abs() > 0.5 { + [0.0, 0.0, 1.0] + } else { + [0.0, 1.0, 0.0] + }; + (cross(up, scale(n, -1.0)), up) +} + +impl Geometry { + fn push_quad(&mut self, centre: V3, n: V3, half: f32, uv_scale: f32) { + let (right, up) = face_axes(n); + let base = self.vertices.len() as u16; + // Top left, top right, bottom right, bottom left: clockwise as seen + // from outside, the front face in D3D's default winding. + for (a, b) in [(-1.0, 1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)] { + let p = add(centre, add(scale(right, a * half), scale(up, b * half))); + self.vertices.push(Vertex { + position: p, + normal: n, + uv: [(a + 1.0) * 0.5 * uv_scale, (1.0 - b) * 0.5 * uv_scale], + }); + } + self.indices.extend([0, 1, 2, 0, 2, 3].map(|i| base + i)); + } + + fn mesh(&mut self, build: impl FnOnce(&mut Geometry)) -> Draw { + let first_index = self.indices.len() as u32; + let base_vertex = self.vertices.len() as i32; + let mut part = Geometry { + vertices: Vec::new(), + indices: Vec::new(), + meshes: self.meshes, + }; + build(&mut part); + self.vertices.extend(part.vertices); + self.indices.extend(&part.indices); + Draw { + first_index, + indices: part.indices.len() as u32, + base_vertex, + } + } + + pub fn new() -> Geometry { + let none = Draw { + first_index: 0, + indices: 0, + base_vertex: 0, + }; + let mut g = Geometry { + vertices: Vec::new(), + indices: Vec::new(), + meshes: [none; 3], + }; + // A 16 x 16 ground, the texture repeated 4 times across it. + let ground = g.mesh(|g| g.push_quad([0.0; 3], [0.0, 1.0, 0.0], 8.0, 4.0)); + // A unit cube about its centre. + let cube = g.mesh(|g| { + for n in [ + [1.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, -1.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, 0.0, -1.0], + ] { + g.push_quad(scale(n, 0.5), n, 0.5, 1.0); + } + }); + // A pyramid of height 1 on a unit square, about its centre. + let pyramid = g.mesh(|g| { + g.push_quad([0.0, -0.5, 0.0], [0.0, -1.0, 0.0], 0.5, 1.0); + for d in [ + [1.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, 0.0, -1.0], + ] { + let (right, _) = face_axes(d); + let n = normalize(add(scale(d, 2.0), [0.0, 1.0, 0.0])); + let base = g.vertices.len() as u16; + let corner = |side: f32| { + add( + add(scale(d, 0.5), scale(right, side * 0.5)), + [0.0, -0.5, 0.0], + ) + }; + for (p, uv) in [ + ([0.0, 0.5, 0.0], [0.5, 0.0]), + (corner(1.0), [1.0, 1.0]), + (corner(-1.0), [0.0, 1.0]), + ] { + g.vertices.push(Vertex { + position: p, + normal: n, + uv, + }); + } + g.indices.extend([base, base + 1, base + 2]); + } + }); + g.meshes = [ground, cube, pyramid]; + g + } +} + +impl Default for Geometry { + fn default() -> Self { + Geometry::new() + } +} + +/// A 4 x 4 matrix as four rows; a point p transforms to (row i . p). +pub type Matrix = [[f32; 4]; 4]; + +fn multiply(a: &Matrix, b: &Matrix) -> Matrix { + let mut m = [[0.0; 4]; 4]; + for (i, row) in m.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = (0..4).map(|k| a[i][k] * b[k][j]).sum(); + } + } + m +} + +/// Placement: uniform scale, then a turn about y (radians), then a move. +fn world(at: V3, size: f32, turn: f32) -> Matrix { + let (s, c) = turn.sin_cos(); + [ + [c * size, 0.0, s * size, at[0]], + [0.0, size, 0.0, at[1]], + [-s * size, 0.0, c * size, at[2]], + [0.0, 0.0, 0.0, 1.0], + ] +} + +/// Camera: looking from `eye` at `target`, 60 degrees vertically, depth 0 +/// at 0.1 and 1 at 100 (D3D's clip space). +fn view_projection(eye: V3, target: V3) -> Matrix { + let z = normalize(add(target, scale(eye, -1.0))); + let x = normalize(cross([0.0, 1.0, 0.0], z)); + let y = cross(z, x); + let view = [ + [x[0], x[1], x[2], -dot(x, eye)], + [y[0], y[1], y[2], -dot(y, eye)], + [z[0], z[1], z[2], -dot(z, eye)], + [0.0, 0.0, 0.0, 1.0], + ]; + let (near, far) = (0.1f32, 100.0f32); + let ys = 1.0 / (30.0f32.to_radians()).tan(); + let xs = ys * HEIGHT as f32 / WIDTH as f32; + let q = far / (far - near); + let projection = [ + [xs, 0.0, 0.0, 0.0], + [0.0, ys, 0.0, 0.0], + [0.0, 0.0, q, -near * q], + [0.0, 0.0, 1.0, 0.0], + ]; + multiply(&projection, &view) +} + +/// The per-frame constants (`b0`), 256 bytes: the view-projection rows, +/// then (each a float4) the direction towards the light, the eye, the +/// light's colour and the ambient light. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct SceneConstants { + pub view_projection: Matrix, + pub light: [f32; 4], + pub eye: [f32; 4], + pub light_colour: [f32; 4], + pub ambient: [f32; 4], + pub _pad: [f32; 32], +} + +/// The per-draw constants (`b1`), 256 bytes: the world rows, then the +/// albedo with the specular exponent in w, the specular colour and the +/// emitted colour. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub struct MeshConstants { + pub world: Matrix, + pub albedo_shininess: [f32; 4], + pub specular: [f32; 4], + pub emissive: [f32; 4], + pub _pad: [f32; 36], +} + +const _: () = assert!(size_of::() == 256); +const _: () = assert!(size_of::() == 256); + +/// The frame at time `t` seconds (0 for the checked frame): its constants +/// and, per draw, which mesh it draws and with what constants. Draw order: +/// ground, pyramid, then the cubes (the nearer cube hides part of the +/// pyramid, drawn before it: the depth test decides). +pub fn frame(t: f32) -> (SceneConstants, Vec<(usize, MeshConstants)>) { + let eye = [0.0, 2.6, -4.6]; + let light = normalize([-0.45, 0.8, -0.4]); + let scene = SceneConstants { + view_projection: view_projection(eye, [0.1, 0.55, 0.7]), + light: [light[0], light[1], light[2], 0.0], + eye: [eye[0], eye[1], eye[2], 1.0], + light_colour: [1.0, 0.96, 0.9, 0.0], + ambient: [0.18, 0.2, 0.26, 0.0], + _pad: [0.0; 32], + }; + let mesh = |world, albedo: V3, shininess, specular: V3, emissive: V3| MeshConstants { + world, + albedo_shininess: [albedo[0], albedo[1], albedo[2], shininess], + specular: [specular[0], specular[1], specular[2], 0.0], + emissive: [emissive[0], emissive[1], emissive[2], 0.0], + _pad: [0.0; 36], + }; + let glow = GLOW.map(|c| f32::from(c) / 255.0); + let draws = vec![ + ( + 0, + mesh( + world([0.0; 3], 1.0, 0.0), + [0.9; 3], + 16.0, + [0.15; 3], + [0.0; 3], + ), + ), + ( + 2, + mesh( + world([0.05, 0.55, 1.6], 1.1, 0.4 + t * 0.7), + [0.0; 3], + 1.0, + [0.0; 3], + [glow[0], glow[1], glow[2]], + ), + ), + ( + 1, + mesh( + world([-1.0, 0.6, 0.0], 1.2, 0.5 + t * 0.5), + [0.95, 0.45, 0.35], + 48.0, + [0.8; 3], + [0.0; 3], + ), + ), + ( + 1, + mesh( + world([1.5, 0.5, 1.2], 1.0, -0.35 - t * 0.9), + [0.35, 0.6, 0.95], + 24.0, + [0.5; 3], + [0.0; 3], + ), + ), + ]; + (scene, draws) +} + +/// The texture's texels, rows of RGBA8: a checkerboard of 8-texel cells, +/// light cells and tinted dark ones. +pub fn texels() -> Vec { + let mut out = Vec::with_capacity((TEXTURE * TEXTURE * 4) as usize); + for y in 0..TEXTURE { + for x in 0..TEXTURE { + let (cx, cy) = (x / 8, y / 8); + let texel = if (cx + cy) % 2 == 0 { + [235, 230, 215, 255] + } else { + [ + 60 + 20 * (cx % 4) as u8, + 100 + 15 * (cy % 4) as u8, + 170, + 255, + ] + }; + out.extend(texel); + } + } + out +} From c78ca73ce5cf36af964fbd9abd647bfa68de7b68 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:14:39 -0500 Subject: [PATCH 07/11] Tests: the conformance title's descriptor heaps pass an empty placement The runtime reads 16 bytes past a heap description, as newer titles follow it with memory of their own for the descriptors (address, size): victory-gpu's create_heap takes it as a placement when the size matches the heap's. The title passed the 4-word description alone, so those bytes were whatever its stack held; if they ever looked like a placement the heap would sit at a stray address (the list benchmark in #2820 crashed so, in one build). It now passes the description and a zero placement, as a title that does not place its heaps leaves it. --- tests/fixtures/conformance/src/gpu.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/fixtures/conformance/src/gpu.rs b/tests/fixtures/conformance/src/gpu.rs index 8654b08259..4dcec3552c 100644 --- a/tests/fixtures/conformance/src/gpu.rs +++ b/tests/fixtures/conformance/src/gpu.rs @@ -329,7 +329,10 @@ const VIEW_SIZE: u64 = 32; impl Gpu { fn heap(&self, t: &mut Tap, kind: u32, count: u32, visible: bool, what: &str) -> Obj { - let desc = [kind, count, u32::from(visible), 0]; + // The description, then an empty placement: newer titles follow it + // with memory of their own for the descriptors (address, size), and + // the runtime reads those 16 bytes too. + let desc = [kind, count, u32::from(visible), 0, 0, 0, 0, 0]; let mut heap = std::ptr::null_mut(); let hr = call!( self.device, From 05d53f121a16989627d7b2452003aca9aad11298 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:33:35 -0500 Subject: [PATCH 08/11] Tests: the GPU frame's notes no longer point at docs/acceptance.md The suite's notes moved into the test itself; the GPU frame's module headers still named the document. --- tests/fixtures/conformance/src/gpu.rs | 2 +- tests/fixtures/conformance/src/scene.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/fixtures/conformance/src/gpu.rs b/tests/fixtures/conformance/src/gpu.rs index 4dcec3552c..a17b75aaf9 100644 --- a/tests/fixtures/conformance/src/gpu.rs +++ b/tests/fixtures/conformance/src/gpu.rs @@ -1,4 +1,4 @@ -//! The GPU frame (docs/acceptance.md, step 3): the scene of [`crate::scene`] +//! The GPU frame: the scene of [`crate::scene`] //! drawn as a title draws, through the console's D3D12 (`d3d12_xs.dll`): //! device, queue, allocators and lists, descriptor heaps, root signatures, //! a graphics pipeline from a stream and a compute pipeline (their shaders diff --git a/tests/fixtures/conformance/src/scene.rs b/tests/fixtures/conformance/src/scene.rs index ac0c3091d3..619ba81aff 100644 --- a/tests/fixtures/conformance/src/scene.rs +++ b/tests/fixtures/conformance/src/scene.rs @@ -1,4 +1,4 @@ -//! The GPU frame's scene (docs/acceptance.md, "GPU frame"): a ground plane, +//! The GPU frame's scene: a ground plane, //! two cubes and a glowing pyramid, lit by one directional light, textured //! from a generated checkerboard, then blurred by a compute pass. Plain //! data and arithmetic, shared by the conformance title (which draws it From 7d2a9cd0d5eaac85fc16e2f59bad063baa6c859c Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:03:47 -0500 Subject: [PATCH 09/11] Tests: the conformance test can take a title DLL built already VICTORY_CONFORMANCE_DLL names the title's DLL instead of building it with cargo at run time, for a test binary run where cargo is not: a binary cross-compiled for Windows (cargo xwin) and run under Wine, for example. --- crates/victory-hle/tests/conformance.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index eafb32ef30..6a2edcc69c 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -62,8 +62,13 @@ fn workspace_root() -> PathBuf { } /// Builds the fixture into its own target dir (the outer cargo holds the -/// lock on the main one while tests run). +/// lock on the main one while tests run). `VICTORY_CONFORMANCE_DLL` names +/// one built already instead: for a test binary run where cargo is not, such +/// as a cross-compiled one under Wine. fn build_fixture() -> PathBuf { + if let Some(dll) = std::env::var_os("VICTORY_CONFORMANCE_DLL") { + return PathBuf::from(dll); + } let manifest = workspace_root().join("tests/fixtures/conformance/Cargo.toml"); let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("conformance"); let status = Command::new(env!("CARGO")) From 10f4e700a56fdfbd564081a6cdf1d9283f33dadc Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:16:49 -0500 Subject: [PATCH 10/11] Tests: `cargo conformance` and `cargo demo`, on Windows and on macOS One command each for the acceptance suite and for showing its GPU frame: - `cargo conformance` runs the conformance title's suite; `--window ` then shows the GPU frame for that long. - `cargo demo` shows only the GPU frame, animated, until its window is closed (`--seconds` to stop sooner): to leave running, or to show. - Both draw the window's frames at `--resolution` (720p, 1080p, 1440p, 4k or x; 1440p by default) with VIctory's overlay (frame rate and frame times), and build the test in release. - On Windows they run the test natively. On macOS they cross-compile the title and the test with cargo-xwin and run them under CrossOver (Wine, D3DMetal, Rosetta 2) in a bottle of their own, made on first use. The title draws the window's frames at their own size with a second set of resources and pipelines (the compute pass takes its row width), while the checks stay on the 512x288 frame. The overlay was never drawn into the old 512x288 window: its panel needs 720 lines. `VICTORY_CONFORMANCE_WINDOW=until-closed` presents until VIctory's window is gone, then ends the process. On an M5 Max under CrossOver, in release: about 59 fps at 1440p, 58 at 1080p and 53 at 4K, overlay shown. --- .cargo/config.toml | 4 + README.md | 96 +++++++ crates/victory-hle/tests/conformance.rs | 95 ++++++- tests/fixtures/conformance/src/gfx10.rs | 11 +- tests/fixtures/conformance/src/gpu.rs | 76 ++++-- tests/fixtures/conformance/src/lib.rs | 12 +- xtask/src/conformance.rs | 320 ++++++++++++++++++++++++ xtask/src/main.rs | 10 + 8 files changed, 587 insertions(+), 37 deletions(-) create mode 100644 xtask/src/conformance.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index 9741f113e7..70ce61a3d1 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,6 @@ [alias] xtask = "run --quiet --package xtask --" +# `cargo conformance`: the acceptance suite; `cargo demo`: its GPU frame in +# a window until closed (see xtask/src/conformance.rs). +conformance = "run --quiet --package xtask -- conformance" +demo = "run --quiet --package xtask -- demo" diff --git a/README.md b/README.md index 4bf6e7d983..aa06a3df60 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,102 @@ title's window has focus: | F / H | stick clicks | | Esc, Tab | Menu, View | +## Tests + +Everything below runs without game data. `cargo test --workspace` runs the +unit tests of every crate and the acceptance suite; the shader tests run one +at a time (`cargo test -p victory-shader -- --test-threads=1`, see +[the validator](#windows-shader-test-validator)). + +### The conformance title (acceptance suite) + +`tests/fixtures/conformance` is a small title of our own, built from source +by the test and loaded through VIctory like a real one. It calls the +console runtime the way a title does and checks the answers against what +the public platform documentation says, citing the page per check. It links +no SDK and holds no game data. + +```powershell +cargo conformance # or: cargo test -p victory-hle --test conformance -- --nocapture +``` + +It reports one TAP line per check (189 of them): + +| Area | What it checks | +|---|---| +| Runtime | loading `xgameruntime.dll`, initialising, reaching each area's object | +| Task queues and async calls | dispatch modes, cancellation, status, a provider's call order | +| System information | console id, analytics info | +| Memory | physical pages mapped at two addresses reading back the same bytes (invariants: XMem's pages are not public) | +| DirectStorage | completion order, automatic submission, capacity and size limits, cancel by tag | +| Game saves | update and quota limits, atomic updates, container names | +| User | default user, gamertags, ids, handles | +| Networking, package, display | connectivity hint, package, HDR mode | +| Files | the package drive (read-only) and temporary storage, with Win32 and C runtime semantics | +| Persistent local storage | path size and path | +| GPU frame | see below | + +Checks VIctory is known to answer differently are listed with the reason in +`KNOWN` (`crates/victory-hle/tests/conformance.rs`): reported, not failed. A +listed check that starts passing fails the test, so the list stays true. + +### The GPU frame (a drawing test title) + +The same title draws a frame through VIctory's console D3D12, as a game +would: device, queue, command lists, descriptor heaps, root signatures, a +graphics and a compute pipeline whose shaders are hand-assembled console +(GFX10) programs, vertex, index and constant buffers in title memory, a +texture uploaded by a copy, and a depth buffer. The scene is a ground plane, +two cubes and a glowing pyramid, lit by a directional light, textured from a +checkerboard, then blurred by a compute pass (512x288). The test draws the +same scene natively on WARP from equivalent HLSL and compares the two +images (`the_gpu_frame_matches_warp`). + +```powershell +# Watch it: present the frame, animated, in a window for 10 seconds. +$env:VICTORY_CONFORMANCE_WINDOW = 10 +cargo test -p victory-hle --test conformance the_gpu_frame_matches_warp -- --nocapture +# Save VIctory's and WARP's frames as victory.ppm and warp.ppm. +$env:VICTORY_CONFORMANCE_DUMP = "frames" +``` + +### The demo + +`cargo demo` shows the GPU frame, animated, in a window until you close it, +with VIctory's overlay (frame rate and frame times) in its top left corner: +to leave running, or to show. The checks still run on a 512x288 frame; the +window's frames are drawn at `--resolution`. + +```powershell +cargo demo # 1440p until the window is closed +cargo demo --resolution 4k # 720p, 1080p, 1440p, 4k, or x +cargo demo --seconds 30 --no-overlay +cargo conformance --window 10 --resolution 1080p # the whole suite, then 10 s of frames +``` + +Both build the test in release (`--debug` for the dev profile, whose +frames are much slower). + +### On macOS + +`cargo conformance` and `cargo demo` also run on a Mac with Apple silicon, +under [CrossOver](https://www.codeweavers.com/crossover) (Wine, with Apple's +D3DMetal for Direct3D 12, and Rosetta 2 for the x86-64 code). The title and +the test are cross-compiled for Windows with +[cargo-xwin](https://github.com/rust-cross/cargo-xwin), and run in a +CrossOver bottle named `VIctory`, made on first use: + +```sh +cargo install --locked cargo-xwin # once; its first build downloads Microsoft's CRT and Windows SDK +cargo demo +``` + +`VICTORY_CROSSOVER_BIN` names CrossOver's `bin` folder if the app is not in +`/Applications`. There is no WARP under D3DMetal, so the comparison with +it is skipped; every other check runs. The library crates' own tests run +natively (`cargo test --workspace --exclude victory`); the `victory` +executable, the game itself and GPU timings need Windows. + ## Commands ``` diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index 6a2edcc69c..d722c08529 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -179,19 +179,27 @@ struct GpuRun { reference: *const f32, reference_len: usize, window_seconds: u32, + window_width: u32, + window_height: u32, image: *const f32, image_len: usize, } /// Runs the title's GPU frame against `reference`: its TAP report and the /// frame it read back. -fn call_gpu(reference: Option<&[f32]>, window_seconds: u32) -> (String, Vec) { +fn call_gpu( + reference: Option<&[f32]>, + window_seconds: u32, + (window_width, window_height): (u32, u32), +) -> (String, Vec) { let e = exports(); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut run = GpuRun { reference: reference.map_or(std::ptr::null(), <[f32]>::as_ptr), reference_len: reference.map_or(0, <[f32]>::len), window_seconds, + window_width, + window_height, image: std::ptr::null(), image_len: 0, }; @@ -216,8 +224,10 @@ fn call_gpu(reference: Option<&[f32]>, window_seconds: u32) -> (String, Vec /// through VIctory's console D3D12 with hand-assembled GFX10 shaders, and /// checks its frame against the same scene drawn natively on WARP. /// `VICTORY_CONFORMANCE_WINDOW=` keeps presenting it, animated, -/// in a window that long; `VICTORY_CONFORMANCE_DUMP=` saves both -/// frames there as PPM images. +/// in a window that long (`until-closed`: until the window is closed, which +/// ends the process), drawn at `VICTORY_CONFORMANCE_SIZE=x` +/// (2560x1440 unless set; multiples of 8). `VICTORY_CONFORMANCE_DUMP=` +/// saves both frames there as PPM images. #[test] fn the_gpu_frame_matches_warp() { let reference = match reference::render() { @@ -227,11 +237,16 @@ fn the_gpu_frame_matches_warp() { None } }; - let window = std::env::var("VICTORY_CONFORMANCE_WINDOW") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(0); - let (tap, image) = call_gpu(reference.as_deref(), window); + let window = match std::env::var("VICTORY_CONFORMANCE_WINDOW").ok().as_deref() { + Some("until-closed") => u32::MAX, + Some(seconds) => seconds.parse().unwrap_or(0), + None => 0, + }; + if window > 0 { + end_when_the_window_closes(); + } + let size = window_size(); + let (tap, image) = call_gpu(reference.as_deref(), window, size); println!("{tap}"); if let Some(dir) = std::env::var_os("VICTORY_CONFORMANCE_DUMP") { let dir = PathBuf::from(dir); @@ -397,3 +412,67 @@ fn reports_missing_or_cut_short_checks_are_refused() { "no checks" ); } + +/// The size the window's frames are drawn at: `VICTORY_CONFORMANCE_SIZE` +/// (`x`, each a multiple of the compute pass's 8-pixel +/// groups), 2560x1440 unless set. +fn window_size() -> (u32, u32) { + let Ok(asked) = std::env::var("VICTORY_CONFORMANCE_SIZE") else { + return (2560, 1440); + }; + let size = asked + .split_once(['x', 'X']) + .and_then(|(w, h)| Some((w.trim().parse().ok()?, h.trim().parse().ok()?))); + match size { + Some((w, h)) if w > 0 && h > 0 && w % scene::GROUP == 0 && h % scene::GROUP == 0 => (w, h), + _ => panic!( + "VICTORY_CONFORMANCE_SIZE={asked}: x, multiples of {}", + scene::GROUP + ), + } +} + +/// Ends the process once VIctory's window (class `VIctory`, in this +/// process) has been shown and is gone: closing it destroys it, and the +/// title would otherwise go on presenting to no window. +fn end_when_the_window_closes() { + use windows_sys::Win32::UI::WindowsAndMessaging::{FindWindowExW, GetWindowThreadProcessId}; + fn ours_is_open() -> bool { + let class: Vec = "VIctory\0".encode_utf16().collect(); + let mut after = std::ptr::null_mut(); + loop { + // SAFETY: a null-terminated class name; null parent and window + // name search every top-level window. + let hwnd = unsafe { + FindWindowExW( + std::ptr::null_mut(), + after, + class.as_ptr(), + std::ptr::null(), + ) + }; + if hwnd.is_null() { + return false; + } + let mut process = 0; + // SAFETY: a window handle FindWindowExW just returned. + unsafe { GetWindowThreadProcessId(hwnd, &mut process) }; + if process == std::process::id() { + return true; + } + after = hwnd; + } + } + std::thread::spawn(|| { + let mut seen = false; + loop { + let open = ours_is_open(); + if seen && !open { + println!("the window was closed"); + std::process::exit(0); + } + seen |= open; + std::thread::sleep(std::time::Duration::from_millis(250)); + } + }); +} diff --git a/tests/fixtures/conformance/src/gfx10.rs b/tests/fixtures/conformance/src/gfx10.rs index f367e99203..628ed42ac3 100644 --- a/tests/fixtures/conformance/src/gfx10.rs +++ b/tests/fixtures/conformance/src/gfx10.rs @@ -278,7 +278,7 @@ pub fn pixel() -> Vec { /// texture shown (UAV, at 32 bytes) and the read-back buffer (raw UAV, at /// 64 bytes; four floats per pixel, row after row). The group id arrives /// in s1-s2, the thread id in v0-v1. A neighbour past the edge reads 0. -pub fn compute() -> Vec { +pub fn compute(width: u32) -> Vec { let mut a = Asm::default(); a.table(4, 0); a.smem(3, 8, 4, 0); // s_load_dwordx8 s[8:15]: the frame @@ -305,7 +305,10 @@ pub fn compute() -> Vec { a.fmac(v(d), HALF, 8 + c); } a.image(8, 20, 2, 16, 0); // image_store v[20:23], v[2:3] - a.s_movk(30, crate::scene::WIDTH as u16); + a.s_movk( + 30, + u16::try_from(width).expect("a frame at most 65,535 pixels wide"), + ); a.vop3(0x143, 24, v(3), 30, v(2)); // v_mad_u32_u24 v24, y, width, x a.vop2(0x1a, v(24), 4 + 128, 24); // v_lshlrev_b32 v24, 4, v24 a.store4(20, 24, 24); @@ -553,7 +556,7 @@ pub fn pixel_container() -> Vec { container(0, &p, &[(b"ISG1", isg), (b"OSG1", osg)]) } -pub fn compute_container() -> Vec { +pub fn compute_container(width: u32) -> Vec { let mut data = vec![0u8; 0x40]; // COMPUTE_PGM_RSRC2: one user SGPR, group ids x and y, thread ids x // and y. @@ -567,7 +570,7 @@ pub fn compute_container() -> Vec { } let p = Program { stage: CS, - code: compute(), + code: compute(width), vgprs: 32, sgprs: 32, layout: vec![(0, 0)], diff --git a/tests/fixtures/conformance/src/gpu.rs b/tests/fixtures/conformance/src/gpu.rs index a17b75aaf9..5905a87f15 100644 --- a/tests/fixtures/conformance/src/gpu.rs +++ b/tests/fixtures/conformance/src/gpu.rs @@ -137,7 +137,11 @@ const COPY_SOURCE: u32 = 0x800; const GENERIC_READ: u32 = 0xAC3; /// Bytes the read-back buffer holds: four floats per pixel. -const FRAME_BYTES: u64 = (WIDTH * HEIGHT * 16) as u64; +/// The compute output's bytes for a `width` x `height` frame (four floats a +/// pixel). +fn frame_bytes(width: u32, height: u32) -> u64 { + u64::from(width) * u64::from(height) * 16 +} #[repr(C)] struct HeapProperties { @@ -290,6 +294,9 @@ pub struct Run { /// Everything the frame uses. struct Gpu { + /// The frame's size in pixels. + width: u32, + height: u32, device: Obj, queue: Obj, allocators: [Obj; 2], @@ -548,7 +555,7 @@ fn texture(width: u32, height: u32, format: u32, flags: u32) -> ResourceDesc { } } -fn setup(t: &mut Tap) -> Option { +fn setup(t: &mut Tap, width: u32, height: u32) -> Option { let mut parameters = [0u32; 32]; parameters[0] = VERSION; let mut device = std::ptr::null_mut(); @@ -658,7 +665,7 @@ fn setup(t: &mut Tap) -> Option { let shaders = [ crate::gfx10::vertex_container(), crate::gfx10::pixel_container(), - crate::gfx10::compute_container(), + crate::gfx10::compute_container(width), ]; // The graphics pipeline, as a stream. let names = [c"POSITION", c"NORMAL", c"TEXCOORD"]; @@ -731,6 +738,8 @@ fn setup(t: &mut Tap) -> Option { let null = std::ptr::null_mut(); let mut g = Gpu { + width, + height, device, queue, allocators, @@ -841,7 +850,7 @@ fn setup(t: &mut Tap) -> Option { g.target = g.resource( t, 1, - texture(WIDTH, HEIGHT, RGBA8, 1), + texture(width, height, RGBA8, 1), RENDER_TARGET, Some(ClearValue { format: RGBA8, @@ -852,7 +861,7 @@ fn setup(t: &mut Tap) -> Option { g.depth = g.resource( t, 1, - texture(WIDTH, HEIGHT, D32, 2), + texture(width, height, D32, 2), DEPTH_WRITE, Some(ClearValue { format: D32, @@ -863,7 +872,7 @@ fn setup(t: &mut Tap) -> Option { g.shown = g.resource( t, 1, - texture(WIDTH, HEIGHT, RGBA8, 4), + texture(width, height, RGBA8, 4), UNORDERED, None, "texture shown", @@ -871,7 +880,7 @@ fn setup(t: &mut Tap) -> Option { g.output = g.resource( t, 1, - buffer(FRAME_BYTES, 4), + buffer(frame_bytes(width, height), 4), UNORDERED, None, "compute output buffer", @@ -879,7 +888,7 @@ fn setup(t: &mut Tap) -> Option { g.readback = g.resource( t, 3, - buffer(FRAME_BYTES, 0), + buffer(frame_bytes(width, height), 0), COPY_DEST, None, "read-back buffer", @@ -974,7 +983,7 @@ fn setup(t: &mut Tap) -> Option { 1, 0, 0, - (FRAME_BYTES / 4) as u32, + (frame_bytes(width, height) / 4) as u32, 0, 0, 0, @@ -1111,9 +1120,9 @@ impl Gpu { 0, &self.depth_cpu ); - let viewport = [0.0, 0.0, WIDTH as f32, HEIGHT as f32, 0.0, 1.0f32]; + let viewport = [0.0, 0.0, self.width as f32, self.height as f32, 0.0, 1.0f32]; call!(list, 0xa8, fn(u32, *const [f32; 6]), 1, &viewport); - let scissor = [0, 0, WIDTH as i32, HEIGHT as i32]; + let scissor = [0, 0, self.width as i32, self.height as i32]; call!(list, 0xb0, fn(u32, *const [i32; 4]), 1, &scissor); call!(list, 0xa0, fn(u32), 4); // triangle list call!(list, 0xc8, fn(Obj), self.graphics); @@ -1164,8 +1173,8 @@ impl Gpu { list, 0x70, fn(u32, u32, u32), - WIDTH / scene::GROUP, - HEIGHT / scene::GROUP, + self.width / scene::GROUP, + self.height / scene::GROUP, 1 ); self.barrier(list, self.target, NON_PIXEL, RENDER_TARGET); @@ -1192,7 +1201,7 @@ impl Gpu { 0, self.output, 0, - FRAME_BYTES + frame_bytes(self.width, self.height) ); self.barrier(copy, self.output, COPY_SOURCE, UNORDERED); let (copied, copy_done) = self.submit(1); @@ -1204,11 +1213,10 @@ impl Gpu { if at.is_null() { return Vec::new(); } - let mut out = vec![0f32; (FRAME_BYTES / 4) as usize]; + let bytes = frame_bytes(self.width, self.height); + let mut out = vec![0f32; (bytes / 4) as usize]; // SAFETY: the mapping holds the buffer's bytes. - unsafe { - std::ptr::copy_nonoverlapping(at, out.as_mut_ptr().cast::(), FRAME_BYTES as usize) - }; + unsafe { std::ptr::copy_nonoverlapping(at, out.as_mut_ptr().cast::(), bytes as usize) }; out } @@ -1252,9 +1260,16 @@ fn pixel(image: &[f32], x: u32, y: u32) -> [u8; 4] { } /// Runs the frame; `reference` is the WARP image (RGBA floats per pixel), -/// `window_seconds` how long to keep presenting it, animated, afterwards. -pub fn run(t: &mut Tap, reference: Option<&[f32]>, window_seconds: u32) -> Run { - let Some(mut g) = setup(t) else { +/// `window_seconds` how long to keep presenting it, animated, afterwards, +/// and `window_size` the size it is drawn at there (each a multiple of +/// [`scene::GROUP`]; the checks are of a [`WIDTH`] x [`HEIGHT`] frame). +pub fn run( + t: &mut Tap, + reference: Option<&[f32]>, + window_seconds: u32, + window_size: (u32, u32), +) -> Run { + let Some(mut g) = setup(t, WIDTH, HEIGHT) else { return Run { image: Vec::new() }; }; // Host pipelines are made on first use, by workers; a draw whose @@ -1301,19 +1316,34 @@ pub fn run(t: &mut Tap, reference: Option<&[f32]>, window_seconds: u32) -> Run { String::new, ); } else { + // The window's frames are drawn at its own size, by a second set of + // resources and pipelines (the compute pass knows its row width); + // their own calls were checked above, so they go unreported. + let (width, height) = window_size; + let mut quiet = Tap::default(); + let mut sized = (window_size != (WIDTH, HEIGHT)) + .then(|| setup(&mut quiet, width, height)) + .flatten(); + // New resources need the texture uploaded on their first frame. + let fresh = sized.is_some(); + let g = sized.as_mut().unwrap_or(&mut g); let started = std::time::Instant::now(); let mut shown = 0; let mut presented = S_OK; while started.elapsed().as_secs() < u64::from(window_seconds) { let token = g.begin(); - g.frame(started.elapsed().as_secs_f32(), false, true); + g.frame(started.elapsed().as_secs_f32(), fresh && shown == 0, true); let hr = g.present(token); if hr != S_OK { presented = hr; } shown += 1; } - t.eq(presented, S_OK, &format!("gpu: PresentX ({shown} frames)")); + t.eq( + presented, + S_OK, + &format!("gpu: PresentX ({shown} frames at {}x{})", g.width, g.height), + ); } Run { image } } diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs index 537f28cc03..20629cc50d 100644 --- a/tests/fixtures/conformance/src/lib.rs +++ b/tests/fixtures/conformance/src/lib.rs @@ -69,13 +69,16 @@ pub extern "system" fn conformance_bench(len: *mut usize) -> *const u8 { /// What the harness passes [`conformance_gpu`]: the WARP reference image /// (RGBA floats per pixel, null for none) and how long to keep presenting -/// frames in a window afterwards (0: no window). The frame read back is +/// frames in a window afterwards (0: no window), at +/// `window_width` x `window_height`. The frame read back is /// handed out in `image` (valid until the next call). #[repr(C)] pub struct GpuRun { pub reference: *const f32, pub reference_len: usize, pub window_seconds: u32, + pub window_width: u32, + pub window_height: u32, pub image: *const f32, pub image_len: usize, } @@ -91,7 +94,12 @@ pub extern "system" fn conformance_gpu(run: *mut GpuRun, len: *mut usize) -> *co // SAFETY: the harness passes `reference_len` floats. .then(|| unsafe { std::slice::from_raw_parts(run.reference, run.reference_len) }); let mut t = tap::Tap::default(); - let done = gpu::run(&mut t, reference, run.window_seconds); + let done = gpu::run( + &mut t, + reference, + run.window_seconds, + (run.window_width, run.window_height), + ); let mut image = IMAGE.lock().unwrap_or_else(|e| e.into_inner()); *image = done.image; run.image = image.as_ptr(); diff --git a/xtask/src/conformance.rs b/xtask/src/conformance.rs new file mode 100644 index 0000000000..fdc6fec789 --- /dev/null +++ b/xtask/src/conformance.rs @@ -0,0 +1,320 @@ +//! `cargo xtask conformance`: the acceptance suite (the conformance title, +//! `tests/fixtures/conformance`) in one command, on Windows or on a Mac. +//! +//! On Windows it is `cargo test -p victory-hle --test conformance`. On macOS +//! the title and the test are cross-compiled for Windows with `cargo xwin` +//! and run under CrossOver (Wine, with Apple's D3DMetal for D3D12) in a +//! bottle of their own, created on first use. +//! +//! `--window ` also shows the GPU frame, animated, in a window +//! that long, drawn at `--resolution` (1440p by default) with VIctory's +//! overlay (frame rate, frame times) in its top left corner. +//! +//! `cargo xtask demo` (`cargo demo`) shows only the GPU frame, until its +//! window is closed: to leave running, or to show. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use anyhow::{Context, Result, bail, ensure}; + +/// The Windows target everything is built for. +const TARGET: &str = "x86_64-pc-windows-msvc"; +/// The CrossOver bottle the suite runs in. +const BOTTLE: &str = "VIctory"; + +/// The test that draws (and shows) the GPU frame. +const GPU_TEST: &str = "the_gpu_frame_matches_warp"; + +#[derive(clap::Args)] +pub struct Conformance { + /// Also show the GPU frame, animated, in a window for this many seconds. + #[arg(long, value_name = "SECONDS")] + window: Option, + #[command(flatten)] + shown: Shown, + /// Passed to the test binary: a test name filter, `--ignored`, ... + #[arg(last = true)] + test_args: Vec, +} + +#[derive(clap::Args)] +pub struct Demo { + /// Stop after this many seconds instead of when the window is closed. + #[arg(long, value_name = "SECONDS")] + seconds: Option, + #[command(flatten)] + shown: Shown, +} + +/// How the GPU frame is shown and built. +#[derive(clap::Args)] +struct Shown { + /// The resolution the window's frames are drawn at: 720p, 1080p, + /// 1440p, 4k (2160p), or x (multiples of 8). + #[arg(long, default_value = "1440p", value_parser = resolution)] + resolution: (u32, u32), + /// Leave VIctory's overlay (frame rate and frame times) hidden in the + /// window; Alt+Z still shows it. + #[arg(long)] + no_overlay: bool, + /// Build the test in the dev profile instead of release (much slower + /// frames). + #[arg(long)] + debug: bool, +} + +pub fn conformance(root: &Path, args: Conformance) -> Result<()> { + let window = args.window.map(|s| s.to_string()); + run(root, window.as_deref(), &args.shown, args.test_args) +} + +pub fn demo(root: &Path, args: Demo) -> Result<()> { + let window = args + .seconds + .map_or("until-closed".into(), |s| s.to_string()); + let test_args = vec![GPU_TEST.into(), "--exact".into()]; + run(root, Some(&window), &args.shown, test_args) +} + +/// Runs the conformance test, showing the GPU frame in a window for +/// `window` (seconds, or `until-closed`) if asked. +fn run(root: &Path, window: Option<&str>, shown: &Shown, mut test_args: Vec) -> Result<()> { + let mut env: Vec<(&str, String)> = vec![]; + if let Some(window) = window { + let (width, height) = shown.resolution; + env.push(("VICTORY_CONFORMANCE_WINDOW", window.into())); + env.push(("VICTORY_CONFORMANCE_SIZE", format!("{width}x{height}"))); + env.push(( + "VICTORY_OVERLAY", + if shown.no_overlay { "0" } else { "1" }.into(), + )); + } + if !test_args.iter().any(|a| a == "--nocapture") { + test_args.push("--nocapture".into()); + } + if cfg!(windows) { + windows(root, shown.debug, &env, &test_args) + } else if cfg!(target_os = "macos") { + mac(root, shown.debug, &env, &test_args) + } else { + bail!("the conformance title runs on Windows, or on macOS under CrossOver") + } +} + +/// `720p`, `1080p`, `1440p`, `4k` (`2160p`) or `x`, each a +/// multiple of the GPU frame's 8-pixel compute groups. +fn resolution(s: &str) -> Result<(u32, u32), String> { + let size = match s.to_ascii_lowercase().as_str() { + "720p" | "hd" => (1280, 720), + "1080p" | "fhd" => (1920, 1080), + "1440p" | "qhd" => (2560, 1440), + "4k" | "2160p" | "uhd" => (3840, 2160), + other => other + .split_once('x') + .and_then(|(w, h)| Some((w.trim().parse().ok()?, h.trim().parse().ok()?))) + .ok_or_else(|| format!("`{s}`: 720p, 1080p, 1440p, 4k, or x"))?, + }; + match size { + (w, h) if w > 0 && h > 0 && w % 8 == 0 && h % 8 == 0 && w <= 8192 && h <= 8192 => Ok(size), + (w, h) => Err(format!( + "{w}x{h}: width and height must be multiples of 8, at most 8192" + )), + } +} + +/// On Windows: the test as it is, natively (it builds the title itself). +fn windows(root: &Path, debug: bool, env: &[(&str, String)], test_args: &[String]) -> Result<()> { + let mut cargo = Command::new(cargo_bin()); + cargo + .current_dir(root) + .args(["test", "-p", "victory-hle", "--test", "conformance"]); + if !debug { + cargo.arg("--release"); + } + cargo + .arg("--") + .args(test_args) + .envs(env.iter().map(|(k, v)| (k, v))); + let status = cargo.status().context("running cargo test")?; + ensure!(status.success(), "the conformance suite failed"); + Ok(()) +} + +/// On macOS: cross-compiled, then run under CrossOver with D3DMetal. +fn mac(root: &Path, debug: bool, env: &[(&str, String)], test_args: &[String]) -> Result<()> { + let crossover = crossover()?; + xwin_available()?; + + // The title: a DLL the test loads through VIctory (Wine runs no cargo, + // so it is built here and named by VICTORY_CONFORMANCE_DLL). + println!("building the conformance title for {TARGET}"); + let title_dir = root.join("target/xwin-title"); + let mut cargo = Command::new(cargo_bin()); + cargo + .current_dir(root) + .args(["xwin", "build", "--target", TARGET, "--manifest-path"]); + cargo.arg(root.join("tests/fixtures/conformance/Cargo.toml")); + cargo.arg("--target-dir").arg(&title_dir); + let status = cargo.status().context("running cargo xwin build")?; + ensure!(status.success(), "building the conformance title failed"); + let dll = title_dir.join(TARGET).join("debug/conformance.dll"); + + // The test binary. blake3's build script assembles with MSVC's ml64, + // which cargo-xwin does not provide: CARGO_FEATURE_PURE makes it build + // its portable code instead (it reads that variable, as cargo sets it + // for its `pure` feature). + println!("building the conformance test for {TARGET}"); + let mut cargo = Command::new(cargo_bin()); + cargo + .current_dir(root) + .args(["xwin", "test", "--no-run", "--target", TARGET]); + cargo.args([ + "-p", + "victory-hle", + "--test", + "conformance", + "--message-format=json-render-diagnostics", + ]); + cargo.arg("--target-dir").arg(root.join("target/xwin")); + if !debug { + cargo.arg("--release"); + } + cargo.env("CARGO_FEATURE_PURE", "1"); + let out = cargo + .stderr(std::process::Stdio::inherit()) + .output() + .context("running cargo xwin test")?; + ensure!(out.status.success(), "building the conformance test failed"); + let exe = test_executable(&String::from_utf8_lossy(&out.stdout)) + .context("cargo did not name the conformance test's executable")?; + + ensure_bottle(&crossover)?; + println!( + "running {} in the {BOTTLE} bottle (CrossOver, D3DMetal)", + exe.display() + ); + let mut wine = Command::new(crossover.join("wine")); + wine.args(["--bottle", BOTTLE, "--wait-children", "--"]) + .arg(&exe) + .args(test_args); + wine.env("VICTORY_CONFORMANCE_DLL", wine_path(&dll)) + .env("CX_GRAPHICS_BACKEND", "d3dmetal") + .env("WINEDEBUG", "-all") + .envs(env.iter().map(|(k, v)| (k, v))); + let status = wine.status().context("running wine")?; + ensure!(status.success(), "the conformance suite failed"); + Ok(()) +} + +fn cargo_bin() -> String { + std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()) +} + +/// CrossOver's `bin` folder (`VICTORY_CROSSOVER_BIN`, else the app in +/// /Applications or ~/Applications). +fn crossover() -> Result { + if let Some(bin) = std::env::var_os("VICTORY_CROSSOVER_BIN") { + return Ok(bin.into()); + } + let app = "Applications/CrossOver.app/Contents/SharedSupport/CrossOver/bin"; + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default(); + [PathBuf::from("/").join(app), home.join(app)] + .into_iter() + .find(|bin| bin.join("wine").exists()) + .context("CrossOver not found: install it, or set VICTORY_CROSSOVER_BIN to its bin folder") +} + +fn xwin_available() -> Result<()> { + let ok = Command::new(cargo_bin()) + .args(["xwin", "--version"]) + .output() + .is_ok_and(|o| o.status.success()); + ensure!( + ok, + "cargo-xwin is needed to cross-compile for Windows: `cargo install --locked cargo-xwin` \ + (its first build downloads Microsoft's CRT and Windows SDK, under Microsoft's licence)" + ); + Ok(()) +} + +/// Creates the bottle (Windows 10, 64-bit) unless it is there. +fn ensure_bottle(crossover: &Path) -> Result<()> { + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_default(); + let bottle = home + .join("Library/Application Support/CrossOver/Bottles") + .join(BOTTLE); + if bottle.exists() { + return Ok(()); + } + println!("creating the CrossOver bottle {BOTTLE}"); + let status = Command::new(crossover.join("cxbottle")) + .args(["--bottle", BOTTLE, "--create", "--template", "win10_64"]) + .args(["--description", "VIctory acceptance suite"]) + .status() + .context("running cxbottle")?; + ensure!(status.success(), "creating the CrossOver bottle failed"); + Ok(()) +} + +/// The conformance test's executable among cargo's JSON messages. +fn test_executable(messages: &str) -> Option { + messages + .lines() + .filter(|l| { + l.contains(r#""reason":"compiler-artifact""#) && l.contains(r#""name":"conformance""#) + }) + .find_map(|l| { + let start = l.find(r#""executable":""#)? + r#""executable":""#.len(); + let end = start + l[start..].find('"')?; + Some(PathBuf::from(&l[start..end])) + }) +} + +/// A macOS path as Wine names it: on the Z: drive, with backslashes. +fn wine_path(path: &Path) -> String { + format!("Z:{}", path.display().to_string().replace('/', "\\")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_the_test_executable_in_cargo_messages() { + let messages = concat!( + r#"{"reason":"compiler-artifact","target":{"name":"victory_hle"},"executable":null}"#, + "\n", + r#"{"reason":"compiler-artifact","target":{"kind":["test"],"name":"conformance"},"executable":"/w/target/xwin/x86_64-pc-windows-msvc/release/deps/conformance-0123.exe","fresh":true}"#, + "\n", + r#"{"reason":"build-finished","success":true}"#, + ); + assert_eq!( + test_executable(messages), + Some(PathBuf::from( + "/w/target/xwin/x86_64-pc-windows-msvc/release/deps/conformance-0123.exe" + )) + ); + assert_eq!(test_executable(r#"{"reason":"build-finished"}"#), None); + } + + #[test] + fn resolutions_by_name_and_by_size() { + assert_eq!(resolution("1080p"), Ok((1920, 1080))); + assert_eq!(resolution("1440P"), Ok((2560, 1440))); + assert_eq!(resolution("4k"), Ok((3840, 2160))); + assert_eq!(resolution("2160p"), Ok((3840, 2160))); + assert_eq!(resolution("1280x720"), Ok((1280, 720))); + assert!(resolution("1366x768").is_err(), "not a multiple of 8"); + assert!(resolution("big").is_err()); + } + + #[test] + fn wine_paths_are_on_the_z_drive() { + assert_eq!(wine_path(Path::new("/a/b/c.dll")), r"Z:\a\b\c.dll"); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 911ed8087c..b83a4e3a77 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,5 +1,6 @@ //! Repository maintenance. Run with `cargo xtask `. +mod conformance; mod policy; use std::path::{Path, PathBuf}; @@ -26,12 +27,21 @@ enum Cmd { }, /// Point git at .githooks/ so every commit runs the policy check. InstallHooks, + /// Run the acceptance suite (the conformance title): natively on + /// Windows, under CrossOver on macOS. `--window 10` also shows its GPU + /// frame, animated, with the frame rate. Also `cargo conformance`. + Conformance(conformance::Conformance), + /// Show the conformance title's GPU frame, animated, with the frame + /// rate, until its window is closed. Also `cargo demo`. + Demo(conformance::Demo), } fn main() -> Result<()> { let root = workspace_root(); match Cli::parse().command { Cmd::Policy { staged } => policy::run(&root, staged), + Cmd::Conformance(args) => conformance::conformance(&root, args), + Cmd::Demo(args) => conformance::demo(&root, args), Cmd::InstallHooks => { let status = Command::new("git") .args(["config", "core.hooksPath", ".githooks"]) From 453700e9c3fa0eeeff00dad167ad87f4cb55beb7 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:33:00 -0500 Subject: [PATCH 11/11] Tests: the demo's stress scale and terrain - `--scale ` (VICTORY_CONFORMANCE_SCALE) stresses VIctory rather than the GPU: each step past 1 adds 64 small cubes and pyramids to the window's frame, each a draw whose constants are written into title memory and whose view is made in the shader-visible heap that frame, and one more submission that binds the pass again, as a title's lists do. The title prints the frame rate and the work per frame every 5 seconds. - The window's frames add terrain: ridged Perlin noise around the ground, flat beside it and rising into ridges with distance. It is a mesh of the shared geometry, drawn only in the window; the checked frame and the WARP reference are unchanged. - `--dump ` saves the checked frames and, after a timed window, the window's last frame (window.ppm). The title now tracks the presented texture's state and the copy list's instead of inferring them from the first frame, so a frame can be read back after presenting. Under CrossOver on an M5 Max, 1440p: scales 1 to 16 hold the display's 60 fps (up to 964 draws and 16 submissions a frame); scale 64 (4,036 draws, 64 submissions) takes 42 ms a frame. --- README.md | 15 +- crates/victory-hle/tests/conformance.rs | 52 ++++- tests/fixtures/conformance/src/gpu.rs | 289 +++++++++++++++++++----- tests/fixtures/conformance/src/lib.rs | 11 +- tests/fixtures/conformance/src/scene.rs | 177 ++++++++++++++- xtask/src/conformance.rs | 26 ++- 6 files changed, 489 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index aa06a3df60..b2321a7a56 100644 --- a/README.md +++ b/README.md @@ -205,13 +205,22 @@ $env:VICTORY_CONFORMANCE_DUMP = "frames" `cargo demo` shows the GPU frame, animated, in a window until you close it, with VIctory's overlay (frame rate and frame times) in its top left corner: -to leave running, or to show. The checks still run on a 512x288 frame; the -window's frames are drawn at `--resolution`. +to leave running, or to show. The window's frames add hills of Perlin +noise around the ground; the checks still run on the 512x288 frame, +without them. + +`--scale ` is a stress test of VIctory itself, not of the GPU: each +step past 1 adds 64 small objects to a frame, each a draw with its +constants written into title memory and its view made in the descriptor +heap that frame, and one more submission, as a title's frame grows. Every +5 seconds it prints the frame rate and the work per frame, so runs at +different scales compare. ```powershell cargo demo # 1440p until the window is closed cargo demo --resolution 4k # 720p, 1080p, 1440p, 4k, or x -cargo demo --seconds 30 --no-overlay +cargo demo --scale 64 # 4,037 draws and 64 submissions a frame +cargo demo --seconds 30 --dump frames # then save the last frame as frames/window.ppm cargo conformance --window 10 --resolution 1080p # the whole suite, then 10 s of frames ``` diff --git a/crates/victory-hle/tests/conformance.rs b/crates/victory-hle/tests/conformance.rs index d722c08529..8ffdac26a0 100644 --- a/crates/victory-hle/tests/conformance.rs +++ b/crates/victory-hle/tests/conformance.rs @@ -181,8 +181,11 @@ struct GpuRun { window_seconds: u32, window_width: u32, window_height: u32, + window_scale: u32, image: *const f32, image_len: usize, + window_image: *const f32, + window_image_len: usize, } /// Runs the title's GPU frame against `reference`: its TAP report and the @@ -191,7 +194,8 @@ fn call_gpu( reference: Option<&[f32]>, window_seconds: u32, (window_width, window_height): (u32, u32), -) -> (String, Vec) { + window_scale: u32, +) -> (String, Vec, Vec) { let e = exports(); let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); let mut run = GpuRun { @@ -200,8 +204,11 @@ fn call_gpu( window_seconds, window_width, window_height, + window_scale, image: std::ptr::null(), image_len: 0, + window_image: std::ptr::null(), + window_image_len: 0, }; // SAFETY: the export's signature in the fixture; the report and image // stay valid until the next call, which the lock holds off. @@ -216,7 +223,12 @@ fn call_gpu( } else { std::slice::from_raw_parts(run.image, run.image_len).to_vec() }; - (report, image) + let window_image = if run.window_image.is_null() { + Vec::new() + } else { + std::slice::from_raw_parts(run.window_image, run.window_image_len).to_vec() + }; + (report, image, window_image) } } @@ -226,8 +238,10 @@ fn call_gpu( /// `VICTORY_CONFORMANCE_WINDOW=` keeps presenting it, animated, /// in a window that long (`until-closed`: until the window is closed, which /// ends the process), drawn at `VICTORY_CONFORMANCE_SIZE=x` -/// (2560x1440 unless set; multiples of 8). `VICTORY_CONFORMANCE_DUMP=` -/// saves both frames there as PPM images. +/// (2560x1440 unless set; multiples of 8), with `VICTORY_CONFORMANCE_SCALE` +/// times the work a frame (1 unless set; up to 1024). `VICTORY_CONFORMANCE_DUMP=` +/// saves the checked frames there as PPM images (and the +/// window's last, `window.ppm`, after a timed window). #[test] fn the_gpu_frame_matches_warp() { let reference = match reference::render() { @@ -246,14 +260,19 @@ fn the_gpu_frame_matches_warp() { end_when_the_window_closes(); } let size = window_size(); - let (tap, image) = call_gpu(reference.as_deref(), window, size); + let scale = window_scale(); + let (tap, image, window_image) = call_gpu(reference.as_deref(), window, size, scale); println!("{tap}"); if let Some(dir) = std::env::var_os("VICTORY_CONFORMANCE_DUMP") { let dir = PathBuf::from(dir); std::fs::create_dir_all(&dir).unwrap(); - save_ppm(&dir.join("victory.ppm"), &image); + let checked = (scene::WIDTH, scene::HEIGHT); + save_ppm(&dir.join("victory.ppm"), &image, checked); if let Some(r) = &reference { - save_ppm(&dir.join("warp.ppm"), r); + save_ppm(&dir.join("warp.ppm"), r, checked); + } + if !window_image.is_empty() { + save_ppm(&dir.join("window.ppm"), &window_image, size); } } if let Err(why) = accept(&tap, &[]) { @@ -261,9 +280,9 @@ fn the_gpu_frame_matches_warp() { } } -/// An RGBA float frame as a binary PPM (RGB8). -fn save_ppm(path: &Path, image: &[f32]) { - let mut out = format!("P6\n{} {}\n255\n", scene::WIDTH, scene::HEIGHT).into_bytes(); +/// An RGBA float frame of `width` x `height` as a binary PPM (RGB8). +fn save_ppm(path: &Path, image: &[f32], (width, height): (u32, u32)) { + let mut out = format!("P6\n{width} {height}\n255\n").into_bytes(); for p in image.chunks(4) { out.extend( p[..3] @@ -476,3 +495,16 @@ fn end_when_the_window_closes() { } }); } + +/// The window's stress scale: `VICTORY_CONFORMANCE_SCALE` (1 to 1024), 1 +/// unless set. Each step adds 64 draws to a frame, with as many views made +/// and constants written, and a submission. +fn window_scale() -> u32 { + let Ok(asked) = std::env::var("VICTORY_CONFORMANCE_SCALE") else { + return 1; + }; + match asked.trim().parse() { + Ok(scale @ 1..=1024) => scale, + _ => panic!("VICTORY_CONFORMANCE_SCALE={asked}: 1 to 1024"), + } +} diff --git a/tests/fixtures/conformance/src/gpu.rs b/tests/fixtures/conformance/src/gpu.rs index 5905a87f15..b56f5f098c 100644 --- a/tests/fixtures/conformance/src/gpu.rs +++ b/tests/fixtures/conformance/src/gpu.rs @@ -143,6 +143,18 @@ fn frame_bytes(width: u32, height: u32) -> u64 { u64::from(width) * u64::from(height) * 16 } +/// Draws, and one submission, each step of the demo's stress scale adds. +pub const DRAWS_A_STEP: usize = 64; +/// Views the checked frame's heap holds; the stress scale's come after. +const VIEWS: u64 = 16; +/// The terrain's view (constants slot 5), in the demo's window only. +const TERRAIN_VIEW: u64 = 9; + +/// The draws the stress scale adds to the checked frame's four. +pub fn extra_draws(scale: u32) -> usize { + DRAWS_A_STEP * (scale.max(1) as usize - 1) +} + #[repr(C)] struct HeapProperties { kind: u32, @@ -287,9 +299,12 @@ fn pointer(p: *const u8, size: usize) -> Vec { out } -/// What the run hands back: the frame read back (RGBA floats per pixel). +/// What the run hands back: the checked frame read back (RGBA floats per +/// pixel), and the window's last frame if it ran for a time (empty if not). +#[derive(Default)] pub struct Run { pub image: Vec, + pub window_image: Vec, } /// Everything the frame uses. @@ -297,6 +312,15 @@ struct Gpu { /// The frame's size in pixels. width: u32, height: u32, + /// The demo's stress scale (1: the checked frame's work). + scale: u32, + /// Whether the terrain is drawn (the demo's window; never the checked + /// frame, which the reference draws without it). + scenery: bool, + /// Whether the texture shown was last left in the state for presenting. + shown_common: bool, + /// Whether the copy list has been closed once (it starts open). + copy_closed: bool, device: Obj, queue: Obj, allocators: [Obj; 2], @@ -555,7 +579,7 @@ fn texture(width: u32, height: u32, format: u32, flags: u32) -> ResourceDesc { } } -fn setup(t: &mut Tap, width: u32, height: u32) -> Option { +fn setup(t: &mut Tap, width: u32, height: u32, scale: u32, scenery: bool) -> Option { let mut parameters = [0u32; 32]; parameters[0] = VERSION; let mut device = std::ptr::null_mut(); @@ -740,6 +764,10 @@ fn setup(t: &mut Tap, width: u32, height: u32) -> Option { let mut g = Gpu { width, height, + scale, + scenery, + shown_common: false, + copy_closed: false, device, queue, allocators, @@ -777,7 +805,13 @@ fn setup(t: &mut Tap, width: u32, height: u32) -> Option { // Descriptor heaps: views (0 scene constants, 1-4 the draws', 5 the // texture, 6 the frame, 7 the texture shown, 8 the read-back buffer), // one sampler, one render target, one depth buffer. - g.views = g.heap(t, 0, 16, true, "views"); + g.views = g.heap( + t, + 0, + VIEWS as u32 + extra_draws(scale) as u32, + true, + "views", + ); g.samplers = g.heap(t, 1, 1, true, "samplers"); g.targets = g.heap(t, 2, 1, false, "render targets"); g.depths = g.heap(t, 3, 1, false, "depth"); @@ -824,7 +858,7 @@ fn setup(t: &mut Tap, width: u32, height: u32) -> Option { g.constants = g.resource( t, 2, - buffer(256 * 5, 0), + buffer(256 * (6 + extra_draws(scale) as u64), 0), GENERIC_READ, None, "constant buffer", @@ -948,6 +982,17 @@ fn setup(t: &mut Tap, width: u32, height: u32) -> Option { let desc = [constants + 256 * n, 256]; call!(device, 0x88, fn(*const [u64; 2], u64), &desc, view(n)); } + // The terrain's constants (slot 5) at view 9, for the demo's window. + if scenery { + let desc = [constants + 256 * 5, 256]; + call!( + device, + 0x88, + fn(*const [u64; 2], u64), + &desc, + view(TERRAIN_VIEW) + ); + } // Format, 2D, the default component mapping, then (from 16 bytes) the // most detailed level 0 and one level. let srv = [RGBA8, 4, 0x1688, 0, 0, 1, 0, 0, 0, 0]; @@ -1029,13 +1074,61 @@ fn setup(t: &mut Tap, width: u32, height: u32) -> Option { } impl Gpu { + /// Binds what the frame's draws use on `list`: heaps, root signature, + /// targets, viewport, pipeline, vertex and index buffers, and the + /// tables every draw shares (the scene's constants, the texture, the + /// sampler). + fn bind_pass(&self, list: Obj) { + let heaps = [self.views, self.samplers]; + call!(list, 0x100, fn(u32, *const Obj), 2, heaps.as_ptr()); + call!(list, 0x110, fn(Obj), self.graphics_root); + call!( + list, + 0x190, + fn(u32, *const u64, i32, *const u64), + 1, + &self.target_cpu, + 0, + &self.depth_cpu + ); + let viewport = [0.0, 0.0, self.width as f32, self.height as f32, 0.0, 1.0f32]; + call!(list, 0xa8, fn(u32, *const [f32; 6]), 1, &viewport); + let scissor = [0, 0, self.width as i32, self.height as i32]; + call!(list, 0xb0, fn(u32, *const [i32; 4]), 1, &scissor); + call!(list, 0xa0, fn(u32), 4); // triangle list + call!(list, 0xc8, fn(Obj), self.graphics); + let vertices = BufferView { + address: Gpu::address(self.vertices), + size: (self.geometry.vertices.len() * 32) as u32, + stride_or_format: scene::STRIDE, + }; + call!( + list, + 0x180, + fn(u32, u32, *const BufferView), + 0, + 1, + &vertices + ); + let indices = BufferView { + address: Gpu::address(self.indices), + size: (self.geometry.indices.len() * 2) as u32, + stride_or_format: R16U, + }; + call!(list, 0x178, fn(*const BufferView), &indices); + let table = |n: u64| self.view_gpu + n * VIEW_SIZE; + call!(list, 0x120, fn(u32, u64), 0, table(0)); + call!(list, 0x120, fn(u32, u64), 2, table(5)); + call!(list, 0x120, fn(u32, u64), 3, self.sampler_gpu); + } + /// Records and runs one frame at time `at`: the draws, the compute pass /// (and the texture's upload if `first`); then copies the compute /// output to the read-back buffer, unless `present`, which leaves the /// texture shown in the state for presenting instead. fn frame(&mut self, at: f32, first: bool, present: bool) -> (Hresult, Hresult, bool) { let (scene, draws) = scene::frame(at); - // SAFETY: the constant buffer is mapped and 1,280 bytes long. + // SAFETY: the constant buffer is mapped and at least 1,536 bytes long. unsafe { let base = self.constants_cpu; std::ptr::copy_nonoverlapping((&raw const scene).cast::(), base, 256); @@ -1046,6 +1139,12 @@ impl Gpu { 256, ); } + let terrain = scene::terrain(); + std::ptr::copy_nonoverlapping( + (&raw const terrain).cast::(), + base.add(256 * 5), + 256, + ); } let list = self.lists[0]; if !first { @@ -1084,12 +1183,11 @@ impl Gpu { std::ptr::null() ); self.barrier(list, self.texture, COPY_DEST, PIXEL); - } else if present { + } + if self.shown_common { self.barrier(list, self.shown, COMMON, UNORDERED); + self.shown_common = false; } - let heaps = [self.views, self.samplers]; - call!(list, 0x100, fn(u32, *const Obj), 2, heaps.as_ptr()); - call!(list, 0x110, fn(Obj), self.graphics_root); let clear = scene::CLEAR.map(|c| f32::from(c) / 255.0); call!( list, @@ -1111,44 +1209,9 @@ impl Gpu { 0, std::ptr::null() ); - call!( - list, - 0x190, - fn(u32, *const u64, i32, *const u64), - 1, - &self.target_cpu, - 0, - &self.depth_cpu - ); - let viewport = [0.0, 0.0, self.width as f32, self.height as f32, 0.0, 1.0f32]; - call!(list, 0xa8, fn(u32, *const [f32; 6]), 1, &viewport); - let scissor = [0, 0, self.width as i32, self.height as i32]; - call!(list, 0xb0, fn(u32, *const [i32; 4]), 1, &scissor); - call!(list, 0xa0, fn(u32), 4); // triangle list - call!(list, 0xc8, fn(Obj), self.graphics); - let vertices = BufferView { - address: Gpu::address(self.vertices), - size: (self.geometry.vertices.len() * 32) as u32, - stride_or_format: scene::STRIDE, - }; - call!( - list, - 0x180, - fn(u32, u32, *const BufferView), - 0, - 1, - &vertices - ); - let indices = BufferView { - address: Gpu::address(self.indices), - size: (self.geometry.indices.len() * 2) as u32, - stride_or_format: R16U, - }; - call!(list, 0x178, fn(*const BufferView), &indices); - let table = |n: u64| self.view_gpu + n * VIEW_SIZE; - call!(list, 0x120, fn(u32, u64), 0, table(0)); - call!(list, 0x120, fn(u32, u64), 2, table(5)); - call!(list, 0x120, fn(u32, u64), 3, self.sampler_gpu); + self.bind_pass(list); + let view_gpu = self.view_gpu; + let table = move |n: u64| view_gpu + n * VIEW_SIZE; for (n, &(mesh, _)) in draws.iter().enumerate() { let m = self.geometry.meshes[mesh]; call!(list, 0x120, fn(u32, u64), 1, table(n as u64 + 1)); @@ -1163,6 +1226,71 @@ impl Gpu { 0 ); } + if self.scenery { + let m = self.geometry.meshes[3]; + call!(list, 0x120, fn(u32, u64), 1, table(TERRAIN_VIEW)); + call!( + list, + 0x68, + fn(u32, u32, u32, i32, u32), + m.indices, + 1, + m.first_index, + m.base_vertex, + 0 + ); + } + // The stress scale's objects (none in the checked frame): each a + // draw whose constants are written into title memory and whose view + // is made in the heap this frame, DRAWS_A_STEP to a submission, each + // submission binding the pass again as a title's lists do. + let crowd = scene::crowd(at, extra_draws(self.scale)); + let mut closed = S_OK; + let mut done = true; + let constants = Gpu::address(self.constants); + for (k, chunk) in crowd.chunks(DRAWS_A_STEP).enumerate() { + let (hr, reached) = self.submit(0); + if hr != S_OK { + closed = hr; + } + done &= reached; + self.reset(0, std::ptr::null_mut()); + self.bind_pass(list); + for (j, (mesh, mesh_constants)) in chunk.iter().enumerate() { + let n = k * DRAWS_A_STEP + j; + let slot = 6 + n; + let view = VIEWS + n as u64; + // SAFETY: the constant buffer is mapped, 256 bytes a slot + // for each of the scale's draws after the first 6. + unsafe { + std::ptr::copy_nonoverlapping( + (&raw const *mesh_constants).cast::(), + self.constants_cpu.add(256 * slot), + 256, + ); + } + let desc = [constants + 256 * slot as u64, 256]; + call!( + self.device, + 0x88, + fn(*const [u64; 2], u64), + &desc, + self.view_cpu + view * VIEW_SIZE + ); + let m = self.geometry.meshes[*mesh]; + call!(list, 0x120, fn(u32, u64), 1, table(view)); + call!( + list, + 0x68, + fn(u32, u32, u32, i32, u32), + m.indices, + 1, + m.first_index, + m.base_vertex, + 0 + ); + } + } // The compute pass reads the frame and writes the texture shown and // the buffer. self.barrier(list, self.target, RENDER_TARGET, NON_PIXEL); @@ -1180,8 +1308,11 @@ impl Gpu { self.barrier(list, self.target, NON_PIXEL, RENDER_TARGET); if present { self.barrier(list, self.shown, UNORDERED, COMMON); + self.shown_common = true; } - let (closed, done) = self.submit(0); + let (last, reached) = self.submit(0); + let closed = if last == S_OK { closed } else { last }; + let done = done && reached; if present { return (closed, S_OK, done); } @@ -1189,7 +1320,7 @@ impl Gpu { // The compute output to the read-back buffer (not while only // showing frames). let copy = self.lists[1]; - if !first { + if self.copy_closed { self.reset(1, std::ptr::null_mut()); } self.barrier(copy, self.output, UNORDERED, COPY_SOURCE); @@ -1205,6 +1336,7 @@ impl Gpu { ); self.barrier(copy, self.output, COPY_SOURCE, UNORDERED); let (copied, copy_done) = self.submit(1); + self.copy_closed = true; (closed, copied, done && copy_done) } @@ -1261,16 +1393,20 @@ fn pixel(image: &[f32], x: u32, y: u32) -> [u8; 4] { /// Runs the frame; `reference` is the WARP image (RGBA floats per pixel), /// `window_seconds` how long to keep presenting it, animated, afterwards, -/// and `window_size` the size it is drawn at there (each a multiple of -/// [`scene::GROUP`]; the checks are of a [`WIDTH`] x [`HEIGHT`] frame). +/// `window_size` the size it is drawn at there (each a multiple of +/// [`scene::GROUP`]; the checks are of a [`WIDTH`] x [`HEIGHT`] frame) and +/// `scale` how much work each frame there gives VIctory (1: the checked +/// frame's; each step more [`DRAWS_A_STEP`] draws, as many views made and +/// constants written, and a submission). pub fn run( t: &mut Tap, reference: Option<&[f32]>, window_seconds: u32, window_size: (u32, u32), + scale: u32, ) -> Run { - let Some(mut g) = setup(t, WIDTH, HEIGHT) else { - return Run { image: Vec::new() }; + let Some(mut g) = setup(t, WIDTH, HEIGHT, 1, false) else { + return Run::default(); }; // Host pipelines are made on first use, by workers; a draw whose // pipeline is not made within the frame's time is left out (VIctory's @@ -1309,6 +1445,7 @@ pub fn run( ); compare(t, &image, reference); exact(t, &image); + let mut window_image = Vec::new(); if window_seconds == 0 { t.check( true, @@ -1316,21 +1453,39 @@ pub fn run( String::new, ); } else { - // The window's frames are drawn at its own size, by a second set of - // resources and pipelines (the compute pass knows its row width); - // their own calls were checked above, so they go unreported. + // The window's frames are drawn at its own size, with the terrain + // and the stress scale's work, by a second set of resources and + // pipelines (the compute pass knows its row width); their calls + // were checked above, so they go unreported. let (width, height) = window_size; let mut quiet = Tap::default(); - let mut sized = (window_size != (WIDTH, HEIGHT)) - .then(|| setup(&mut quiet, width, height)) - .flatten(); + let mut sized = setup(&mut quiet, width, height, scale, true); // New resources need the texture uploaded on their first frame. let fresh = sized.is_some(); let g = sized.as_mut().unwrap_or(&mut g); let started = std::time::Instant::now(); - let mut shown = 0; + let mut shown = 0u64; let mut presented = S_OK; + let draws = 4 + usize::from(g.scenery) + extra_draws(g.scale); + let submissions = 1 + extra_draws(g.scale) / DRAWS_A_STEP; + let per_frame = format!( + "{}x{}, scale {}: {draws} draws and {submissions} submissions a frame", + g.width, g.height, g.scale + ); + println!("demo: {per_frame}"); + // A line every 5 seconds: frames shown and time per frame since the + // last (a run until the window closes never reaches the report). + let (mut mark, mut marked) = (std::time::Instant::now(), 0u64); while started.elapsed().as_secs() < u64::from(window_seconds) { + if mark.elapsed().as_secs() >= 5 { + let frames = shown - marked; + let ms = mark.elapsed().as_secs_f64() * 1000.0 / frames.max(1) as f64; + println!( + "demo: {:.1} fps, {ms:.2} ms a frame ({per_frame})", + 1000.0 / ms + ); + (mark, marked) = (std::time::Instant::now(), shown); + } let token = g.begin(); g.frame(started.elapsed().as_secs_f32(), fresh && shown == 0, true); let hr = g.present(token); @@ -1339,13 +1494,23 @@ pub fn run( } shown += 1; } + // The last frame once more, read back (`VICTORY_CONFORMANCE_DUMP`). + g.begin(); + g.frame(started.elapsed().as_secs_f32(), fresh && shown == 0, false); + window_image = g.read(); t.eq( presented, S_OK, - &format!("gpu: PresentX ({shown} frames at {}x{})", g.width, g.height), + &format!( + "gpu: PresentX ({shown} frames, {:.2} ms a frame, at {per_frame})", + started.elapsed().as_secs_f64() * 1000.0 / shown.max(1) as f64 + ), ); } - Run { image } + Run { + image, + window_image, + } } /// The frame against the WARP reference: channels within 4/255, except diff --git a/tests/fixtures/conformance/src/lib.rs b/tests/fixtures/conformance/src/lib.rs index 20629cc50d..2244186d53 100644 --- a/tests/fixtures/conformance/src/lib.rs +++ b/tests/fixtures/conformance/src/lib.rs @@ -70,7 +70,7 @@ pub extern "system" fn conformance_bench(len: *mut usize) -> *const u8 { /// What the harness passes [`conformance_gpu`]: the WARP reference image /// (RGBA floats per pixel, null for none) and how long to keep presenting /// frames in a window afterwards (0: no window), at -/// `window_width` x `window_height`. The frame read back is +/// `window_width` x `window_height`, with `window_scale` times the work. The frame read back is /// handed out in `image` (valid until the next call). #[repr(C)] pub struct GpuRun { @@ -79,8 +79,11 @@ pub struct GpuRun { pub window_seconds: u32, pub window_width: u32, pub window_height: u32, + pub window_scale: u32, pub image: *const f32, pub image_len: usize, + pub window_image: *const f32, + pub window_image_len: usize, } /// Runs the GPU frame (`gpu`); returns its TAP report (valid until the @@ -88,6 +91,7 @@ pub struct GpuRun { #[unsafe(no_mangle)] pub extern "system" fn conformance_gpu(run: *mut GpuRun, len: *mut usize) -> *const u8 { static IMAGE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + static WINDOW_IMAGE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); // SAFETY: the harness passes its parameters. let run = unsafe { &mut *run }; let reference = (!run.reference.is_null()) @@ -99,11 +103,16 @@ pub extern "system" fn conformance_gpu(run: *mut GpuRun, len: *mut usize) -> *co reference, run.window_seconds, (run.window_width, run.window_height), + run.window_scale, ); let mut image = IMAGE.lock().unwrap_or_else(|e| e.into_inner()); *image = done.image; run.image = image.as_ptr(); run.image_len = image.len(); + let mut window_image = WINDOW_IMAGE.lock().unwrap_or_else(|e| e.into_inner()); + *window_image = done.window_image; + run.window_image = window_image.as_ptr(); + run.window_image_len = window_image.len(); let report = t.finish(); // SAFETY: the harness passes room for the length. unsafe { len.write(report.len()) }; diff --git a/tests/fixtures/conformance/src/scene.rs b/tests/fixtures/conformance/src/scene.rs index 619ba81aff..2e8c90744a 100644 --- a/tests/fixtures/conformance/src/scene.rs +++ b/tests/fixtures/conformance/src/scene.rs @@ -48,8 +48,9 @@ pub struct Draw { pub struct Geometry { pub vertices: Vec, pub indices: Vec, - /// Ground, cube, pyramid. - pub meshes: [Draw; 3], + /// Ground, cube, pyramid, and the terrain beyond the ground (drawn + /// only in the demo's window, never in the checked frame). + pub meshes: [Draw; 4], } type V3 = [f32; 3]; @@ -107,6 +108,50 @@ impl Geometry { self.indices.extend([0, 1, 2, 0, 2, 3].map(|i| base + i)); } + /// Hills and mountains around the ground: a heightfield of Perlin + /// noise over x in -48..48 and z in -12..70, flat (just under the + /// ground) beneath and beside it, rising with distance from its edges + /// into a valley of ridges. + fn push_terrain(&mut self) { + const COLUMNS: u16 = 160; + const ROWS: u16 = 128; + let (x0, x1, z0, z1) = (-48.0f32, 48.0f32, -12.0f32, 70.0f32); + let noise = Perlin::new(0x5eed); + let height = |x: f32, z: f32| { + // How far beyond the 16 x 16 ground's far and side edges. + let away = (z - 8.0).max(x.abs() - 8.0).max(0.0); + let rise = smoothstep(0.0, 18.0, away); + let peaks = 2.0 + 11.0 * (away / 55.0).min(1.0); + -0.02 + rise * peaks * noise.ridged(x * 0.045, z * 0.045, 5).powf(1.6) + }; + let base = self.vertices.len() as u16; + let (dx, dz) = ((x1 - x0) / COLUMNS as f32, (z1 - z0) / ROWS as f32); + for row in 0..=ROWS { + for column in 0..=COLUMNS { + let (x, z) = (x0 + column as f32 * dx, z0 + row as f32 * dz); + // The normal from the height's slope across one cell. + let sx = height(x + dx, z) - height(x - dx, z); + let sz = height(x, z + dz) - height(x, z - dz); + self.vertices.push(Vertex { + position: [x, height(x, z), z], + normal: normalize([-sx, 2.0 * dx.min(dz), -sz]), + // One light texel: the terrain takes its albedo only. + uv: [0.02, 0.02], + }); + } + } + let at = |column: u16, row: u16| base + row * (COLUMNS + 1) + column; + for row in 0..ROWS { + for column in 0..COLUMNS { + // As the ground's quad: far left, far right, near right, near + // left (clockwise seen from above). + let (a, b) = (at(column, row + 1), at(column + 1, row + 1)); + let (c, d) = (at(column + 1, row), at(column, row)); + self.indices.extend([a, b, c, a, c, d]); + } + } + } + fn mesh(&mut self, build: impl FnOnce(&mut Geometry)) -> Draw { let first_index = self.indices.len() as u32; let base_vertex = self.vertices.len() as i32; @@ -134,7 +179,7 @@ impl Geometry { let mut g = Geometry { vertices: Vec::new(), indices: Vec::new(), - meshes: [none; 3], + meshes: [none; 4], }; // A 16 x 16 ground, the texture repeated 4 times across it. let ground = g.mesh(|g| g.push_quad([0.0; 3], [0.0, 1.0, 0.0], 8.0, 4.0)); @@ -183,7 +228,8 @@ impl Geometry { g.indices.extend([base, base + 1, base + 2]); } }); - g.meshes = [ground, cube, pyramid]; + let terrain = g.mesh(|g| g.push_terrain()); + g.meshes = [ground, cube, pyramid, terrain]; g } } @@ -341,6 +387,129 @@ pub fn frame(t: f32) -> (SceneConstants, Vec<(usize, MeshConstants)>) { (scene, draws) } +/// Objects the demo's stress scale adds to the frame (none in the checked +/// frame): `count` small cubes and pyramids in a grid over the ground, each +/// turning and bobbing at time `t`, each a draw with constants of its own. +pub fn crowd(t: f32, count: usize) -> Vec<(usize, MeshConstants)> { + let side = (count as f32).sqrt().ceil().max(1.0) as usize; + let (x0, x1, z0, z1) = (-7.0f32, 7.0f32, -1.5f32, 7.5f32); + let (step_x, step_z) = ((x1 - x0) / side as f32, (z1 - z0) / side as f32); + let size = (step_x.min(step_z) * 0.55).min(0.35); + (0..count) + .map(|i| { + let (column, row) = ((i % side) as f32, (i / side) as f32); + let phase = i as f32 * 0.37; + let at = [ + x0 + (column + 0.5) * step_x, + size * 0.5 + size * 0.3 * (t * 2.0 + phase).sin().abs(), + z0 + (row + 0.5) * step_z, + ]; + let turn = phase + t * (0.4 + (i % 7) as f32 * 0.15); + let albedo = hue(i as f32 * 0.618_034 % 1.0); + let constants = MeshConstants { + world: world(at, size, turn), + albedo_shininess: [albedo[0], albedo[1], albedo[2], 24.0], + specular: [0.4, 0.4, 0.4, 0.0], + emissive: [0.0; 4], + _pad: [0.0; 36], + }; + (1 + i % 2, constants) + }) + .collect() +} + +/// The terrain's constants: where it lies (as built) and its colour. +pub fn terrain() -> MeshConstants { + MeshConstants { + world: world([0.0; 3], 1.0, 0.0), + albedo_shininess: [0.36, 0.5, 0.3, 6.0], + specular: [0.04, 0.04, 0.04, 0.0], + emissive: [0.0; 4], + _pad: [0.0; 36], + } +} + +fn smoothstep(from: f32, to: f32, x: f32) -> f32 { + let t = ((x - from) / (to - from)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Ken Perlin's improved gradient noise in two dimensions, with its +/// permutation shuffled from `seed` (the same terrain every run). +struct Perlin { + p: [u8; 512], +} + +impl Perlin { + fn new(seed: u64) -> Perlin { + let mut table: [u8; 256] = std::array::from_fn(|i| i as u8); + let mut state = seed; + for i in (1..256).rev() { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + table.swap(i, (state >> 33) as usize % (i + 1)); + } + Perlin { + p: std::array::from_fn(|i| table[i % 256]), + } + } + + /// Noise at (x, y), about -1 to 1. + fn noise(&self, x: f32, y: f32) -> f32 { + let (xf, yf) = (x.floor(), y.floor()); + let (xi, yi) = ((xf as i32 & 255) as usize, (yf as i32 & 255) as usize); + let (x, y) = (x - xf, y - yf); + let fade = |t: f32| t * t * t * (t * (t * 6.0 - 15.0) + 10.0); + let grad = |hash: u8, x: f32, y: f32| match hash & 7 { + 0 => x + y, + 1 => -x + y, + 2 => x - y, + 3 => -x - y, + 4 => x, + 5 => -x, + 6 => y, + _ => -y, + }; + let p = &self.p; + let corner = |dx: usize, dy: usize| p[p[xi + dx] as usize + yi + dy]; + let (u, v) = (fade(x), fade(y)); + let lerp = |a: f32, b: f32, t: f32| a + t * (b - a); + lerp( + lerp(grad(corner(0, 0), x, y), grad(corner(1, 0), x - 1.0, y), u), + lerp( + grad(corner(0, 1), x, y - 1.0), + grad(corner(1, 1), x - 1.0, y - 1.0), + u, + ), + v, + ) + } + + /// Ridged multifractal noise of `octaves` octaves, 0 to 1: sharp crests + /// where the noise crosses zero, as mountain ridges. + fn ridged(&self, x: f32, y: f32, octaves: u32) -> f32 { + let (mut sum, mut amplitude, mut frequency, mut total) = (0.0, 1.0, 1.0, 0.0); + for _ in 0..octaves { + let ridge = 1.0 - self.noise(x * frequency, y * frequency).abs(); + sum += amplitude * ridge * ridge; + total += amplitude; + amplitude *= 0.5; + frequency *= 2.0; + } + sum / total + } +} + +/// A saturated colour of hue `h` (0 to 1). +fn hue(h: f32) -> V3 { + let channel = |offset: f32| { + let k = (h * 6.0 + offset) % 6.0; + 0.9 - 0.6 * (k.min(4.0 - k).clamp(0.0, 1.0)) + }; + [channel(5.0), channel(3.0), channel(1.0)] +} + /// The texture's texels, rows of RGBA8: a checkerboard of 8-texel cells, /// light cells and tinted dark ones. pub fn texels() -> Vec { diff --git a/xtask/src/conformance.rs b/xtask/src/conformance.rs index fdc6fec789..ecdf31036b 100644 --- a/xtask/src/conformance.rs +++ b/xtask/src/conformance.rs @@ -11,7 +11,9 @@ //! overlay (frame rate, frame times) in its top left corner. //! //! `cargo xtask demo` (`cargo demo`) shows only the GPU frame, until its -//! window is closed: to leave running, or to show. +//! window is closed: to leave running, or to show. `--scale ` multiplies +//! the work each frame gives VIctory (draws, views, constants written into +//! title memory, submissions) to find where the translation layer slows. use std::path::{Path, PathBuf}; use std::process::Command; @@ -54,6 +56,12 @@ struct Shown { /// 1440p, 4k (2160p), or x (multiples of 8). #[arg(long, default_value = "1440p", value_parser = resolution)] resolution: (u32, u32), + /// Stress VIctory's translation layer: each step past 1 adds 64 draws + /// to a frame, each with its constants written into title memory and + /// its view made in the heap that frame, and one more submission + /// (1: the checked frame's work). + #[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..=1024))] + scale: u32, /// Leave VIctory's overlay (frame rate and frame times) hidden in the /// window; Alt+Z still shows it. #[arg(long)] @@ -62,6 +70,10 @@ struct Shown { /// frames). #[arg(long)] debug: bool, + /// Save the checked frames (and, after a timed window, the window's + /// last) in this folder as PPM images. + #[arg(long, value_name = "DIR")] + dump: Option, } pub fn conformance(root: &Path, args: Conformance) -> Result<()> { @@ -85,11 +97,23 @@ fn run(root: &Path, window: Option<&str>, shown: &Shown, mut test_args: Vec