diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000000..80e6a359ed
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,33 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ check:
+ runs-on: windows-latest
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v5
+ # The version and components pinned in rust-toolchain.toml.
+ - run: rustup toolchain install
+ - uses: Swatinem/rust-cache@v2
+ - name: Clippy
+ run: cargo clippy --workspace --all-targets --locked -- -D warnings
+ - name: Clippy, diagnostics build
+ run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
+ # Includes xtask's repository_passes_policy, the asset-policy check.
+ - name: Tests
+ run: cargo test --workspace --locked
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..347a3999c1
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,35 @@
+# Contributing to the Linux lab fork
+
+This branch uses the pinned fxceless rendering baseline described in
+[the lab's baseline record](docs/lab/decision.md). Marvisak/VIctory is the
+original upstream. The source fork reports that the Windows prologue renders
+with incomplete lighting and a low frame rate. The lab's Proton gameplay and
+performance remain unverified.
+
+Anyone can fork this public repository and open a pull request. Direct write
+access is granted individually by the owner; it is not required to contribute.
+Choose an unclaimed item from [the task list](docs/lab/tasks.md), comment on
+its issue to claim it, and name the files you intend to change. Use one branch
+and one PR per task, based on this fork's current default branch. No force
+pushes to shared branches. Coordinate shared GPU files before editing them.
+
+Describe the concrete failure, the resulting behavior, and how it was checked.
+Include the commit, OS, toolchain, GPU, driver, commands, exit codes and relevant
+logs. Distinguish Linux unit tests, Windows cross-builds, Proton execution,
+synthetic GPU checks and gameplay. Mark unperformed checks explicitly.
+
+Run the pinned toolchain's `cargo test --locked --workspace` on a supported
+host, and `cargo xtask policy` before submitting. Linux tests alone do not
+exercise the Windows GPU or loader. A successful cross-build proves no runtime
+or FPS result. Windows/Proton changes need a matching execution report.
+
+Keep game files, derived assets, shaders, prepared images, memory dumps,
+credentials, local paths and SSH configuration out of Git and issue attachments.
+Follow [the upstream asset policy](docs/asset-policy.md). Use synthetic inputs
+in public tests. Preserve GPL-3.0-or-later and attribution. Keep the older XCL
+GPL-2.0-only checkout separate; do not copy its source into this repository.
+
+The lab's performance target is 1920x1080 output, upscaling allowed, no frame
+generation, 1% low at least 30 FPS on three ten-minute routes (urban, fast driving,
+high load), followed by one hour of stability. First obtain correct rendering;
+never skip failed checks or replace images with placeholders to meet a number.
diff --git a/Cargo.lock b/Cargo.lock
index bab4a7e1a6..29bab8c722 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2,12 +2,6 @@
# 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 = "aho-corasick"
version = "1.1.5"
@@ -281,15 +275,6 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
-[[package]]
-name = "miniz_oxide"
-version = "0.9.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
-dependencies = [
- "adler2",
-]
-
[[package]]
name = "nu-ansi-term"
version = "0.50.3"
@@ -681,7 +666,7 @@ name = "victory-game"
version = "0.1.0"
dependencies = [
"memchr",
- "miniz_oxide",
+ "zlib-rs",
]
[[package]]
@@ -690,7 +675,6 @@ version = "0.1.0"
dependencies = [
"anyhow",
"blake3",
- "miniz_oxide",
"tempfile",
"tracing",
"victory-formats",
@@ -698,13 +682,13 @@ dependencies = [
"victory-shader",
"windows",
"windows-sys",
+ "zlib-rs",
]
[[package]]
name = "victory-hle"
version = "0.1.0"
dependencies = [
- "miniz_oxide",
"opus-pure",
"tempfile",
"tracing",
@@ -715,6 +699,7 @@ dependencies = [
"windows",
"windows-core",
"windows-sys",
+ "zlib-rs",
]
[[package]]
@@ -754,10 +739,10 @@ dependencies = [
name = "victory-shader"
version = "0.1.0"
dependencies = [
- "miniz_oxide",
"thiserror",
"windows",
"windows-sys",
+ "zlib-rs",
]
[[package]]
@@ -912,3 +897,9 @@ dependencies = [
"clap",
"walkdir",
]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
diff --git a/Cargo.toml b/Cargo.toml
index 2cf09792c0..4e21b692d6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,7 +37,8 @@ windows = "0.62.2"
windows-core = "0.62.2"
blake3 = "1.8.7"
memchr = "2.8.3"
-miniz_oxide = "0.9.1"
+# SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch).
+zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] }
walkdir = "2.5.1"
tempfile = "3.27.0"
# Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust).
@@ -49,7 +50,19 @@ unused_must_use = "deny"
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
-undocumented_unsafe_blocks = "warn"
+# This fork: two style lints are let through until the newer code is tidied
+# (tuple-heavy signatures and indexed loops in the translator and GPU side).
+type_complexity = "allow"
+needless_range_loop = "allow"
+chunks_exact_to_as_chunks = "allow"
+sliced_string_as_bytes = "allow"
+collapsible_match = "allow"
+manual_clamp = "allow"
+implicit_saturating_sub = "allow"
+min_max = "allow"
+# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in
+# this fork's newer GPU code still lack one.
+undocumented_unsafe_blocks = "allow"
[profile.dev.package."*"]
# Dependencies (hashing, parsing) are hot paths when chewing through
diff --git a/README.md b/README.md
index 3c0b5a93c7..9f65690c94 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,92 @@
+# VIctory fork (work in progress)
+
+A work-in-progress fork of [VIctory](https://github.com/Marvisak/VIctory), a
+compatibility layer that runs an Xbox Series title natively on Windows from
+files the user supplies. This fork follows upstream
+`main` and adds fixes aimed at one goal: getting the game's world to render
+correctly and playably on one particular PC.
+
+**This repository contains no game files, code or assets.** You need your own
+copy of the game. It is not affiliated with or endorsed by the game's
+developer or publisher.
+
+## Credits
+
+- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its
+ contributors is the base of everything here: the loader, the runtime
+ services, the Direct3D 12 back end and the shader recompiler. Licensed
+ GPL-3.0-or-later; so is this fork. Upstream's history is kept intact below
+ the single commit that carries this fork's changes.
+- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors
+ (GPL-2.0-only) was used as a reference for how the same title behaves under
+ another layer. Fixes inspired by it were written anew in VIctory's code.
+- This fork's changes were developed with [Claude Code](https://claude.com/claude-code).
+
+## Linux lab
+
+See [CONTRIBUTING.md](CONTRIBUTING.md) to join the lab and
+[the task list](docs/lab/tasks.md) for open work. The Windows results below
+come from the source fork. The lab has yet to verify gameplay under Proton.
+
+## Status of this fork (2026-11-25)
+
+**Not playable yet: 2.5 to 4 frames per second, and shadowed areas are black.**
+Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB,
+32 GB RAM. The Series X profile is used throughout.
+
+| Stage | State in this fork |
+|-------|--------------------|
+| Boot, menus, start screen | works, 30 fps (as upstream) |
+| Opening cutscene | plays from start to finish, in order, lit: title cards, credits cards, night and dusk shots |
+| Saves | the game autosaves a checkpoint and loads it again |
+| First gameplay scene (the prologue) | renders: characters, textures, sky, sunlit exterior; HUD, pause menu and pad input work |
+| Light in shadow | missing: the game's ray-traced bounce light and ray-traced lamp and sun shadows do not run yet, so anything the sun does not hit directly is black |
+| Frame rate in the world | 2-4 fps: 420-450 ms per frame by default, 240-350 ms with the newer switches (`VICTORY_RELAY=2`, or `VICTORY_LATE_WAIT=3 VICTORY_WIDE_BACK=1 VICTORY_CARD_BUFFERS_MIN_MB=1 VICTORY_CARD_BUFFERS_MB=1024`); it started at 3-6 seconds per frame |
+| Stability | no driver hang or device loss in normal runs (a hang introduced by the wave64 update was found and fixed: its barrier form for 64-lane programs is now off unless `VICTORY_WAVE_WIDE=1`) |
+
+### What this fork changed (summary)
+
+Rendering:
+- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed.
+- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed.
+- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer.
+- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed.
+- Gathers at a named mip level (with and without an offset) read level 0; fixed.
+- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed.
+- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs.
+- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md).
+
+Speed and memory:
+- Waits for memory values, write-watch queries and page queries no longer walk page tables per call.
+- Large title buffers get a copy in card memory, with shader writes found by hashing on the card.
+- Submissions can be sent ahead of the wait for the card (`VICTORY_LATE_WAIT`), with a relay thread that lands results as the card finishes (`VICTORY_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame.
+- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`VICTORY_INPLACE`, first stage only; a probe confirmed the approach on the test GPU).
+- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory.
+- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed.
+
+- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`VICTORY_SHADER_OPT=0` turns them off).
+
+Most of the newer speed changes sit behind environment switches that are off
+by default (`VICTORY_LATE_WAIT`, `VICTORY_RELAY`, `VICTORY_WIDE_BACK`,
+`VICTORY_CARD_BUFFERS_MIN_MB`, `VICTORY_INPLACE`, `VICTORY_BVH_BUILDER`, ...).
+Each is described in a comment where it is read.
+
+### Known problems
+
+- Everything in shadow is black (see above).
+- The interior of the first gameplay room is sometimes not drawn after the cutscene hands over to gameplay.
+- Around 24 GB of memory is in use during play.
+- A few style lints are switched off for this fork in the workspace `Cargo.toml` until the newer code is tidied.
+- Many changes here are specific to this title and this GPU, and some are marked `shortcut:` in the code where they approximate what the console does.
+
+Everything below this line is upstream VIctory's own README, unchanged; its
+status section describes upstream, not this fork.
+
+---
+
# VIctory
-Runs Grand Theft Auto VI (Xbox Series X|S) natively on Windows, from files
+Runs the title (Xbox Series X|S) natively on Windows, from files
the user supplies.
The title's x86-64 code runs unchanged inside our process; VIctory supplies
@@ -19,7 +105,7 @@ loads the world, where rendering fails.
| Intro video with sound | works |
| Start screen, profile and saves | works |
| Loading into the world (about 50 s) | works |
-| The world (first mission's intro) | reached and runs (two minutes without a GPU failure); the picture is black, 1.5-3 s per frame |
+| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame |
Tested on one machine: Windows 11, AMD RX 6700 XT.
@@ -39,7 +125,7 @@ What each part does today and what it still needs:
| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble |
| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title |
| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds |
-| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped) are in | Frames are black (most geometry is drawn indirectly; untranslated shaders drop the rest); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
+| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves |
| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes |
| Series S mode | Runs through the menus to the loading screen | The world, as above |
@@ -50,6 +136,11 @@ Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with
shader model 6.6 (and mesh shaders for the world), Rust (pinned in
`rust-toolchain.toml`).
+The title also needs several GiB of available Windows commit at startup.
+Check **Committed** under **Task Manager → Performance → Memory**. If
+`crashes.log` reports Windows error 1455, close other applications or increase
+the Windows paging file size, then retry.
+
```powershell
cargo xtask install-hooks # asset-policy check on every commit
copy victory.example.toml victory.toml # then set your paths (outside the repo)
@@ -114,10 +205,13 @@ cargo build --profile diag -p victory --features diagnostics # target\diag\vic
| `VICTORY_CAPTURE=
` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=`) |
| `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames |
| `VICTORY_D3D12_DEBUG=1` | host debug layer |
-| `VICTORY_INDIRECT=1` | runs the title's indirect draws and dispatches (off: the world's first frame stalls with it) |
| `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) |
| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight |
+| `VICTORY_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready |
+| `VICTORY_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash |
+| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands |
| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) |
+| `VICTORY_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow |
| `VICTORY_AUDIO_CAPTURE=` | records what the title plays (our process only) |
| `VICTORY_XMA_DUMP=` | saves the first 32 XMA voices' context and input |
diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs
index 31392ffb08..842ce77391 100644
--- a/apps/victory/src/main.rs
+++ b/apps/victory/src/main.rs
@@ -152,7 +152,17 @@ fn main() -> Result<()> {
pipelines,
list,
jobs,
- } => translate::run(paths, validate, pipelines, list, jobs),
+ } => {
+ // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped
+ if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) {
+ victory_shader::emit::set_view_heap_limit(n);
+ }
+ // `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes
+ if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) {
+ victory_shader::emit::set_host_max_wave(n);
+ }
+ translate::run(paths, validate, pipelines, list, jobs)
+ }
Command::Run {
exe,
unimplemented,
@@ -180,6 +190,7 @@ fn show_config() -> Result<()> {
);
println!("game_dir : {}", status(&cfg.game_dir));
println!("cache_dir : {}", cfg.cache_dir.display());
+ println!("data_dir : {}", cfg.data_dir.display());
for t in &cfg.test_titles {
println!("test_title : {}", status(&Some(t.clone())));
}
@@ -187,7 +198,7 @@ fn show_config() -> Result<()> {
.game_dir
.iter()
.chain(&cfg.test_titles)
- .chain([&cfg.cache_dir])
+ .chain([&cfg.cache_dir, &cfg.data_dir])
{
if let Err(e) = victory_core::ensure_outside_repo(p) {
println!("POLICY VIOLATION: {e}");
diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs
index 52131478d7..dc5bf71561 100644
--- a/apps/victory/src/run.rs
+++ b/apps/victory/src/run.rs
@@ -30,6 +30,12 @@ pub fn run(
let images = cfg.cache_subdir("images")?;
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
let image = victory_loader::load(&prepared, &images)?;
+ // The program is mapped from the copy `load` wrote: the file's bytes
+ // and their patched copy are not read again, and were held for the
+ // whole run (two blocks of 114.7 MB each for the title, in
+ // physical memory: run 65's memory map).
+ drop(prepared);
+ drop(original);
victory_hle::runtime::set_main_image(image.base());
victory_hle::runtime::set_image_path(image.base(), exe);
println!(
@@ -186,7 +192,7 @@ fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
}
/// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports,
-/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader.
+/// e.g. The title's upscaler behind its FidelityFX loader.
#[cfg(windows)]
struct LateDlls {
host: victory_hle::HostPolicy,
diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs
index dcaf924bd5..1d13ae2cfc 100644
--- a/apps/victory/src/translate.rs
+++ b/apps/victory/src/translate.rs
@@ -160,6 +160,11 @@ pub fn run(
jobs: Option,
) -> Result<()> {
let paths = crate::default_paths(paths)?;
+ // `VICTORY_HOST_MAX_WAVE=32`: translate as for a host whose waves have
+ // at most 32 lanes (as the runtime does on such a card).
+ if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) {
+ victory_shader::emit::set_host_max_wave(n);
+ }
let dll = validate.then(Validator::default_path).flatten();
if validate {
Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
@@ -312,6 +317,24 @@ fn translate(
let Some(bytes) = source.bytes() else {
return t.fail("corrupt record".into(), example);
};
+ // The hash a run's log names the shader by (`hash=` in "first bind",
+ // "shader does not translate", "host pipeline refused").
+ let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
+ // Diagnostics: `VICTORY_TRANSLATE_ONLY=,...` translates
+ // those containers alone.
+ static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new();
+ let only = ONLY.get_or_init(|| {
+ std::env::var("VICTORY_TRANSLATE_ONLY")
+ .unwrap_or_default()
+ .split(',')
+ .map(|h| h.trim().to_lowercase())
+ .filter(|h| !h.is_empty())
+ .collect()
+ });
+ if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) {
+ return;
+ }
+ let example = || format!("{}{} #{hash}", path.display(), source.label());
t.containers += 1;
let Ok(container) = Container::parse(&bytes) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
@@ -319,21 +342,69 @@ fn translate(
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
return t.fail("no DXIL part (SM5 or older)".into(), example);
};
- if !lock(seen).insert(blake3::hash(dxil)) {
+ // `~`: the hash of the code alone; containers that differ only around
+ // it are translated once, the others listed as duplicates of it.
+ let code = blake3::hash(dxil);
+ let code8 = code.to_hex()[..8].to_owned();
+ let example = || format!("{} ~{code8}", example());
+ // `VICTORY_DUMP_MATCH=;|...`: the containers whose
+ // line holds one of the texts (a name, `#hash`), as the title has them.
+ if let Ok(spec) = std::env::var("VICTORY_DUMP_MATCH")
+ && let Some((dir, texts)) = spec.split_once(';')
+ {
+ let line = example();
+ if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) {
+ let name: String = source
+ .label()
+ .chars()
+ .skip_while(|c| *c != ' ')
+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
+ .take(70)
+ .collect();
+ let _ = std::fs::create_dir_all(dir);
+ let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]);
+ }
+ }
+ if !lock(seen).insert(code) {
t.duplicates += 1;
+ if t.list {
+ t.lines.push(format!("{} duplicate", example()));
+ }
return;
}
let programs = match native_programs(dxil) {
Ok(p) => p,
Err(e) => return t.fail(e.to_string(), example),
};
+ // `VICTORY_FAIL_DUMP=`: the first 3 containers of each failure reason, as the title
+ // has them (`.cdxil`), to work on a translator gap offline
+ let dump = std::env::var_os("VICTORY_FAIL_DUMP");
+ let before: Option> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect());
+ translate_programs(&container, programs, &example, t, checks);
+ if let (Some(dir), Some(before)) = (dump, before) {
+ for (reason, (n, _)) in &t.failed {
+ let was = before.get(reason).copied().unwrap_or(0);
+ if *n > was && was < 3 {
+ let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect();
+ let _ = std::fs::create_dir_all(&dir);
+ let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]);
+ }
+ }
+ }
+}
+
+fn translate_programs(container: &Container, programs: Vec, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) {
for p in programs {
t.programs += 1;
- match ir::build(&p.patched_code(), p.wave64, p.vgprs) {
+ match victory_shader::spill::build(&p) {
Ok(program) => {
t.translated += 1;
t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::();
- let res = match resource::track(&program, &p.layout, p.stage) {
+ // Per-lane descriptors are traced on the per-lane form; its
+ // failure is listed after the resources' and I/O's.
+ let structured = structure::structure(&program);
+ let lanes = structured.as_ref().ok();
+ let res = match resource::track(&program, &p.layout, p.stage, lanes) {
Ok(r) => {
tally_resources(&p, &r, t);
Some(r)
@@ -368,7 +439,7 @@ fn translate(
Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)),
}
}
- let structured = match structure::structure(&program) {
+ let structured = match structured {
Ok(s) => {
tally_structured(&program, &s, t);
Some(s)
@@ -386,8 +457,9 @@ fn translate(
if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
let label = || format!("{} {:?}", example(), p.stage);
*counter(t, p.stage, 0) += 1;
- match emit::emit(&container, &p, &program, &s, &i, &r) {
+ match emit::emit(container, &p, &program, &s, &i, &r) {
Ok(shader) => {
+ census_line(&label(), &p, &program, &shader);
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
}
@@ -410,6 +482,51 @@ fn translate(
}
}
+/// `VICTORY_SHADER_CENSUS=`: one line per emitted program, appended:
+/// its label, the console program's instructions by encoding class (a
+/// static count of the whole program, not of one thread's path), and the
+/// host module's instructions by kind (`emit::census::KINDS`).
+fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) {
+ use std::io::Write;
+ use victory_shader::gfx10::Fields;
+ static OUT: std::sync::OnceLock>> = std::sync::OnceLock::new();
+ let Some(out) = OUT.get_or_init(|| {
+ let path = std::env::var_os("VICTORY_SHADER_CENSUS")?;
+ let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?;
+ Some(Mutex::new(file))
+ }) else {
+ return;
+ };
+ let Some(census) = emit::census::take(&shader.dxil) else {
+ return;
+ };
+ // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other
+ let mut console = [0u32; 9];
+ for inst in p.blocks.iter().flat_map(|b| &b.insts) {
+ console[0] += 1;
+ let k = match &inst.fields {
+ Fields::Valu(_) => 1,
+ Fields::Sop { .. } => 2,
+ Fields::Smem { .. } => 3,
+ Fields::Buffer { .. } | Fields::Flat { .. } => 4,
+ Fields::Image { .. } => 5,
+ Fields::Ds { .. } => 6,
+ Fields::Sopp { .. } => 7,
+ _ => 8,
+ };
+ console[k] += 1;
+ }
+ let mut line = format!("{label}\twave64={}", u8::from(native.wave64));
+ for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) {
+ line.push_str(&format!("\t{name}={n}"));
+ }
+ for (name, n) in emit::census::KINDS.iter().zip(census.counts) {
+ line.push_str(&format!("\t{name}={n}"));
+ }
+ line.push('\n');
+ let _ = lock(out).write_all(line.as_bytes());
+}
+
/// Validates an emitted shader if asked to.
fn check(
mut shader: emit::HostShader,
@@ -521,6 +638,7 @@ fn tally_io(r: &io::Io, t: &mut Tally) {
match i {
io::Interp::Interpolated { .. } => t.interpolated += 1,
io::Interp::Vertex { .. } => t.vertex_values += 1,
+ io::Interp::Weighted { .. } => t.interpolated += 1,
}
}
for e in &r.exports {
@@ -547,7 +665,7 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
let mut traced = HashSet::new();
for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) {
let a = match *leaf {
- resource::Source::Loaded { load, .. } => {
+ resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => {
t.loaded += 1;
address(load)
}
@@ -560,7 +678,12 @@ fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) {
t.constant += 1;
None
}
- resource::Source::Phi { .. } => unreachable!("leaves are no phis"),
+ resource::Source::Phi { .. }
+ | resource::Source::Select { .. }
+ | resource::Source::Lanes { .. }
+ | resource::Source::LanePhi { .. } => {
+ unreachable!("leaves are no phis, selects or per-lane choices")
+ }
};
// Heaps hold dynamic resources, which no used entry lists; code
// tables are no root parameter.
diff --git a/crates/victory-core/src/config.rs b/crates/victory-core/src/config.rs
index 596aa430ae..b65014e7ec 100644
--- a/crates/victory-core/src/config.rs
+++ b/crates/victory-core/src/config.rs
@@ -13,7 +13,7 @@ use crate::policy::ensure_outside_repo;
#[derive(Debug, Default, Clone)]
pub struct Config {
- /// The user's dump of Grand Theft Auto VI.
+ /// The user's dump of the title.
pub game_dir: Option,
/// Root for all derived data. Always outside the repository.
pub cache_dir: PathBuf,
@@ -80,10 +80,10 @@ impl Config {
) -> Result {
let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
let test_titles = match env("VICTORY_TEST_TITLES") {
- Some(v) => std::env::split_paths(&v)
+ Some(v) if !v.is_empty() => std::env::split_paths(&v)
.filter(|p| !p.as_os_str().is_empty())
.collect(),
- None => file.test_titles,
+ _ => file.test_titles,
};
let cache_dir = env_path("VICTORY_CACHE_DIR")
.or(file.cache_dir)
@@ -165,6 +165,29 @@ mod tests {
assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file"));
}
+ #[test]
+ fn empty_test_titles_env_is_ignored() {
+ let file = FilePaths {
+ test_titles: vec!["from-file".into()],
+ ..Default::default()
+ };
+ let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(OsString::new);
+ let cfg = Config::resolve(file, None, env).unwrap();
+ assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]);
+ }
+
+ #[test]
+ fn test_titles_env_splits_paths() {
+ let value = std::env::join_paths(["first", "second"]).unwrap();
+ let file = FilePaths::default();
+ let env = |k: &str| (k == "VICTORY_TEST_TITLES").then(|| value.clone());
+ let cfg = Config::resolve(file, None, env).unwrap();
+ assert_eq!(
+ cfg.test_titles,
+ vec![PathBuf::from("first"), PathBuf::from("second")]
+ );
+ }
+
#[test]
fn example_config_parses() {
let text = include_str!("../../../victory.example.toml");
@@ -181,4 +204,14 @@ mod tests {
};
assert!(cfg.cache_subdir("x").is_err());
}
+
+ #[test]
+ fn data_inside_repo_is_refused() {
+ let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data");
+ let cfg = Config {
+ data_dir: inside,
+ ..Default::default()
+ };
+ assert!(cfg.data_subdir("x").is_err());
+ }
}
diff --git a/crates/victory-formats/src/bcpack.rs b/crates/victory-formats/src/bcpack.rs
index cb4ea5383a..c8d35378df 100644
--- a/crates/victory-formats/src/bcpack.rs
+++ b/crates/victory-formats/src/bcpack.rs
@@ -80,7 +80,12 @@ struct Bc7Ix {
/// The format's constant tables.
pub struct Tables {
freq: [[u32; BUCKETS]; MODELS],
- start: [[u32; BUCKETS]; MODELS],
+ /// Each bucket's first slot; 65536 past the model's last, and one more
+ /// 65536 at the end so a bucket always has a next start.
+ start: [[u32; BUCKETS + 1]; MODELS],
+ /// Per model, the bucket of the first slot of each 256-slot window: the
+ /// search for a slot's bucket starts there and seldom moves on.
+ bucket: Box<[[u8; 256]; MODELS]>,
/// ceil(2^32 / freq): exact division for the offsets inside a bucket.
recip: [[u64; BUCKETS]; MODELS],
rank1: [u8; 256],
@@ -124,15 +129,16 @@ impl Tables {
/// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control
/// words, then 255 dictionary entries per format in format order: BC1
/// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode,
- /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 32 i16).
- /// Little-endian, no padding. Every model must tile 65536.
+ /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B,
+ /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536.
pub fn parse(bytes: &[u8]) -> Result {
if bytes.len() != TABLES_SIZE {
return Err(Error("table file has the wrong size"));
}
let mut r = Reader(bytes);
let mut freq = [[0u32; BUCKETS]; MODELS];
- let mut start = [[0u32; BUCKETS]; MODELS];
+ let mut start = [[0u32; BUCKETS + 1]; MODELS];
+ let mut bucket = Box::new([[0u8; 256]; MODELS]);
let mut recip = [[0u64; BUCKETS]; MODELS];
for m in 0..MODELS {
for f in &mut freq[m] {
@@ -153,6 +159,10 @@ impl Tables {
return Err(Error("a model does not tile 65536"));
}
start[m][used..].fill(1 << 16);
+ for (window, b) in bucket[m].iter_mut().enumerate() {
+ let first = (window as u32) << 8;
+ *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8;
+ }
}
let rank1 = r.bytes();
let rank3a = r.bytes();
@@ -212,7 +222,10 @@ impl Tables {
bits: [r.u8(), r.u8()],
..Default::default()
};
- for v in ix.ix.as_flattened_mut() {
+ // Unused: the widths again in all entries but the first.
+ r.u16();
+ // Only 15 slots for set 1, which no entry uses (0 bits).
+ for v in &mut ix.ix.as_flattened_mut()[..31] {
*v = r.u16() as i16;
}
(ep, ix)
@@ -221,6 +234,7 @@ impl Tables {
Ok(Tables {
freq,
start,
+ bucket,
recip,
rank1,
rank3a,
@@ -342,33 +356,20 @@ impl Lane {
let start = &t.start[usize::from(self.model)];
let slot = x & 0xffff;
// The bucket: starts are ascending, and 65536 past the model's last.
- let b = start[1..].iter().filter(|&&s| s <= slot).count();
- // Buckets 0 and 1 hold one symbol. Elsewhere offset and frequency
- // are below 2^16, where the reciprocal divides exactly.
- let sym = match b {
- 0 => 0,
- 1 => 1,
- _ => {
- let rec = t.recip[usize::from(self.model)][b];
- (1 << (b - 1)) + ((u64::from(slot - start[b]) * rec) >> 32) as u8
- }
- };
- // Slot 0 is never used: symbol 0 owns 1 .. f[0] - 1.
- let (f, c) = if sym == 0 {
- (freq[0] - 1, 1)
+ let b = bucket_of(t, self.model, slot);
+ // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0
+ // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency
+ // f[b] from start[b] on; offset and frequency are below 2^16, where
+ // the reciprocal divides exactly.
+ let (sym, f, rem) = if b == 0 {
+ (0, freq[0] - 1, slot.wrapping_sub(1))
} else {
- let k = (8 - sym.leading_zeros()) as usize;
- let f = freq[k];
- (
- f,
- (u32::from(sym) - (1 << (k - 1)))
- .wrapping_mul(f)
- .wrapping_add(start[k])
- & 0xffff,
- )
+ let offset = slot - start[b];
+ let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32;
+ ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b])
};
- self.x = (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot);
- self.out = Some(sym);
+ self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem);
+ self.out = Some(sym as u8);
} else if self.left != 0 {
// At exactly 2^24 the lane neither reads nor decodes again; only a
// lane that has delivered its symbols may end up there.
@@ -385,6 +386,19 @@ impl Lane {
}
}
+/// The bucket holding `slot` (below 65536): the last whose start is at or
+/// below it. The window table gives the bucket of the window's first slot;
+/// later buckets that start inside the window are stepped over.
+#[inline]
+fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize {
+ let start = &t.start[usize::from(model)];
+ let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]);
+ while start[b + 1] <= slot {
+ b += 1;
+ }
+ b
+}
+
/// Decodes `per` symbols per block on every lane into `records` (one record
/// of `widths.len() * per` symbols per block), taking input from `fetch`
/// (given the lane that takes the byte) in the order of the schedule: each
@@ -409,6 +423,8 @@ fn lanes(
let stride = widths.len() * per;
let full = (1u32 << widths.len()) - 1;
let (mut pos, mut done, mut idle) = (0, 0u32, 0);
+ // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on.
+ let mut at = 0;
while pos < blocks * per {
let (mut taken, mut moved) = (0, false);
for (j, lane) in lanes.iter_mut().enumerate() {
@@ -429,13 +445,18 @@ fn lanes(
if !lane.stalled
&& let Some(sym) = lane.out.take()
{
- records[pos / per * stride + j * per + pos % per] = sym;
+ records[at + j * per] = sym;
done |= bit;
moved = true;
}
}
if done == full {
pos += 1;
+ at += if pos.is_multiple_of(per) {
+ stride - per + 1
+ } else {
+ 1
+ };
done = 0;
moved = true;
}
@@ -1369,6 +1390,183 @@ mod tests {
}
}
+ /// The window table finds the bucket a scan of the starts finds, for
+ /// every slot of every model, in the shipped tables and in ours (whose
+ /// buckets are wide) and in tables whose buckets are one slot wide.
+ #[test]
+ fn bucket_lookup_matches_a_scan_of_the_starts() {
+ let mut narrow = tables();
+ for m in 0..MODELS {
+ // Buckets 1.. of one slot each where they fit; bucket 0 takes the rest.
+ let used = m / 16 + 2;
+ let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::();
+ for b in 0..used {
+ let f = if b == 0 { rest } else { 1 };
+ narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes());
+ }
+ }
+ for t in [
+ Tables::builtin().unwrap(),
+ Tables::parse(&tables()).unwrap(),
+ Tables::parse(&narrow).unwrap(),
+ ] {
+ for model in 0..MODELS as u8 {
+ let start = &t.start[usize::from(model)];
+ for slot in 0..1u32 << 16 {
+ let scan = start[1..].iter().filter(|&&s| s <= slot).count();
+ assert_eq!(
+ bucket_of(&t, model, slot),
+ scan,
+ "model {model} slot {slot}"
+ );
+ }
+ }
+ }
+ }
+
+ /// One rANS decode as first written: scan for the bucket, divide for the
+ /// symbol, rebuild its frequency and start from the symbol.
+ fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) {
+ let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]);
+ let slot = x & 0xffff;
+ let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count();
+ let sym = match b {
+ 0 => 0,
+ 1 => 1,
+ _ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b],
+ } as u8;
+ let (f, c) = if sym == 0 {
+ (freq[0] - 1, 1)
+ } else {
+ let k = (8 - sym.leading_zeros()) as usize;
+ let f = freq[k];
+ (
+ f,
+ ((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff,
+ )
+ };
+ (
+ sym,
+ (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot),
+ )
+ }
+
+ /// A payload step decodes the symbol and state the first version did, for
+ /// every model and slot of the shipped tables and ours, at assorted states.
+ #[test]
+ fn payload_step_matches_the_reference_decode() {
+ for t in [
+ Tables::builtin().unwrap(),
+ Tables::parse(&tables()).unwrap(),
+ ] {
+ for model in 0..MODELS as u8 {
+ for high in [0x100u32, 0x1234, 0xffff] {
+ for slot in 0..1u32 << 16 {
+ let x = high << 16 | slot;
+ if x <= LOW {
+ continue;
+ }
+ let mut lane = Lane {
+ phase: 3,
+ model,
+ x,
+ left: 1,
+ ..Default::default()
+ };
+ lane.step(&t).unwrap();
+ let (sym, next) = reference_decode(&t, model, x);
+ assert_eq!(
+ (lane.out, lane.x),
+ (Some(sym), next),
+ "model {model} x {x:#x}"
+ );
+ }
+ }
+ }
+ }
+ }
+
+ /// Pseudo-random records that fit each lane's alphabet; BC7 keeps control
+ /// code 0 (mode 6), the only one the synthetic tables define.
+ fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec> {
+ let mut seed = 0x9e37_79b9_7f4a_7c15u64;
+ (0..blocks)
+ .map(|_| {
+ let mut r: Vec = (0..widths.len() * per)
+ .map(|k| {
+ seed ^= seed << 13;
+ seed ^= seed >> 7;
+ seed ^= seed << 17;
+ let alphabet = 1u32 << (widths[k / per] + 1);
+ (seed as u32 % alphabet) as u8
+ })
+ .collect();
+ if bc7 {
+ r[30] = 0;
+ r[31] = 0;
+ }
+ r
+ })
+ .collect()
+ }
+
+ /// The fast paths decode exactly what one lane step at a time does, on
+ /// every format's lane layout, with short and long fragments.
+ #[test]
+ fn every_layout_round_trips_through_the_lanes() {
+ let t = Tables::parse(&tables()).unwrap();
+ let layouts: [(&[u8], usize); 6] = [
+ (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1),
+ (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2),
+ (&BC4_LANES, 1),
+ (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2),
+ (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2),
+ (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2),
+ ];
+ for (widths, per) in layouts {
+ for blocks in [1, 2, 17, 300, 1000] {
+ let records = random_records(widths, per, blocks, false);
+ let src = stream(&t, widths, per, &records);
+ let mut got = vec![0u8; records.concat().len()];
+ let mut next = src.iter().copied();
+ lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap();
+ assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks");
+ }
+ }
+ }
+
+ /// Decode throughput on synthetic streams (no game data):
+ /// `cargo test --release -p victory-formats bcpack_throughput -- --ignored --nocapture`.
+ #[test]
+ #[ignore = "benchmark"]
+ fn bcpack_throughput() {
+ let t = Tables::parse(&tables()).unwrap();
+ let cases: [(u8, &[u8], usize, usize); 3] = [
+ (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8),
+ (4, &BC4_LANES, 1, 8),
+ (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16),
+ ];
+ for (bc, widths, per, block) in cases {
+ // One fragment per lane holds at most 65792 bytes.
+ let blocks = 1 << 14;
+ let records = random_records(widths, per, blocks, bc == 7);
+ let src = stream(&t, widths, per, &records);
+ let mut dst = vec![0u8; blocks * block];
+ decode(bc, &src, &mut dst, &t).unwrap();
+ let runs = 40;
+ let started = std::time::Instant::now();
+ for _ in 0..runs {
+ decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap();
+ }
+ let secs = started.elapsed().as_secs_f64() / f64::from(runs);
+ println!(
+ "BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block",
+ (blocks * block) as f64 / secs / 1e6,
+ secs * 1e9 / blocks as f64
+ );
+ }
+ }
+
/// Compares with reference outputs made outside the repository:
/// `VICTORY_BCPACK_TABLES` (the table file) and `VICTORY_BCPACK_CASES`, a
/// directory of `.bc` packed chunks with `.out` beside them.
@@ -1395,4 +1593,16 @@ mod tests {
}
assert!(n > 0);
}
+
+ /// A dictionary entry stands in for a block the decoder made: a set with
+ /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear).
+ #[test]
+ fn bc7_dictionary_indices_line_up() {
+ let t = Tables::builtin().unwrap();
+ for (k, (_, ix)) in t.bc7.iter().enumerate() {
+ let anchor = 0..1 << (ix.bits[0] - 1);
+ let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]);
+ assert!(ok, "entry {k}: {:?}", ix.ix);
+ }
+ }
}
diff --git a/crates/victory-formats/src/texture.rs b/crates/victory-formats/src/texture.rs
index 875244799a..a1f72e4383 100644
--- a/crates/victory-formats/src/texture.rs
+++ b/crates/victory-formats/src/texture.rs
@@ -13,7 +13,7 @@
//! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`,
//! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`,
//! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile
-//! patterns in [`MICRO`] from `gfx10SwizzlePattern.h` (the RB+ tables, as on
+//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on
//! RDNA2). addrlib carries this notice:
//!
//! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved.
@@ -249,6 +249,13 @@ fn spread(bits: &[u32]) -> Vec {
const MAX_MIPS: u32 = 16;
+/// The largest width, height and depth (or array size) accepted, in texels.
+/// GFX10's image descriptors hold at most 16384 texels per side, so no
+/// texture the GPU can use is refused. The bound also keeps every size
+/// computed below within `u64` (and its `u32` steps), which unchecked
+/// values from a title would otherwise overflow.
+const MAX_EXTENT: u32 = 1 << 14;
+
/// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]];
const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]];
@@ -258,9 +265,9 @@ impl Layout {
pub fn new(desc: &Desc) -> Result {
let d = *desc;
let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?;
- let valid = d.width > 0
- && d.height > 0
- && d.depth > 0
+ let valid = (1..=MAX_EXTENT).contains(&d.width)
+ && (1..=MAX_EXTENT).contains(&d.height)
+ && (1..=MAX_EXTENT).contains(&d.depth)
&& (1..=MAX_MIPS).contains(&d.mips)
&& d.element_bytes.is_power_of_two()
&& d.element_bytes <= 16
@@ -587,11 +594,8 @@ impl Layout {
row_pitch: usize,
depth_pitch: usize,
) -> Result<(), Error> {
- let n = self.desc.element_bytes as usize;
- self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
- for (i, len) in runs(t, count, n) {
- linear[l + i * n..][..len].copy_from_slice(&tiled[t[i] as usize..][..len]);
- }
+ self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
+ linear[l..][..len].copy_from_slice(&tiled[t..][..len]);
})
}
@@ -605,16 +609,12 @@ impl Layout {
row_pitch: usize,
depth_pitch: usize,
) -> Result<(), Error> {
- let n = self.desc.element_bytes as usize;
- self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, count| {
- for (i, len) in runs(t, count, n) {
- tiled[t[i] as usize..][..len].copy_from_slice(&linear[l + i * n..][..len]);
- }
+ self.walk(tiled.len(), mip, slice, linear.len(), row_pitch, depth_pitch, |t, l, len| {
+ tiled[t..][..len].copy_from_slice(&linear[l..][..len]);
})
}
- /// Calls `row(tiled offsets, linear offset, elements)` for each row of a
- /// subresource, after checking both buffers are large enough.
+ /// Visits contiguous runs as (tiled byte offset, linear byte offset, length).
#[allow(clippy::too_many_arguments)]
fn walk(
&self,
@@ -624,7 +624,7 @@ impl Layout {
linear_len: usize,
row_pitch: usize,
depth_pitch: usize,
- mut row: impl FnMut(&[u64], usize, usize),
+ mut copy: impl FnMut(usize, usize, usize),
) -> Result<(), Error> {
let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?;
let depth = m.depth;
@@ -644,56 +644,75 @@ impl Layout {
}
let n = self.desc.element_bytes as usize;
let bytes = m.width as usize * n;
- let need = (depth as usize - 1) * depth_pitch + (m.height as usize - 1) * row_pitch + bytes;
+ let need = (depth as usize - 1)
+ .checked_mul(depth_pitch)
+ .zip((m.height as usize - 1).checked_mul(row_pitch))
+ .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset))
+ .and_then(|offset| offset.checked_add(bytes))
+ .ok_or(Error::TooSmall)?;
if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes {
return Err(Error::TooSmall);
}
let linear = self.desc.swizzle == Swizzle::LINEAR;
- let columns: Vec = (0..m.width)
- .map(|x| {
- if linear {
- u64::from(x) * n as u64
- } else {
- self.column(m, x)
+ // The row and depth contribute one common base to every column, so
+ // the same contiguous runs repeat on every row, including mip tails.
+ let mut runs = Vec::new();
+ if !linear {
+ let mut first_linear = 0;
+ let mut first_tiled = self.column(m, 0) as usize;
+ for x in 1..m.width {
+ let offset = self.column(m, x) as usize;
+ let at = x as usize * n;
+ if offset != first_tiled + (at - first_linear) {
+ runs.push((first_tiled, first_linear, at - first_linear));
+ first_tiled = offset;
+ first_linear = at;
}
- })
- .collect();
- let mut offsets = vec![0u64; m.width as usize];
+ }
+ runs.push((first_tiled, first_linear, bytes - first_linear));
+ }
+ // A mip can end partway through the last run. Check the other runs
+ // once so each row can copy them with a compile-time length.
+ let (body, last) = runs.split_at(runs.len().saturating_sub(1));
+ let run_len = body
+ .first()
+ .map(|run| run.2)
+ .filter(|&len| body.iter().all(|run| run.2 == len));
for z in 0..depth {
let (s, inner) = self.split(first + z);
let base = u64::from(s) * self.slice_size + m.offset;
for y in 0..m.height {
- let start = if linear {
- base + u64::from(y) * u64::from(m.pitch) * n as u64
+ let linear_row = z as usize * depth_pitch + y as usize * row_pitch;
+ if linear {
+ let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64;
+ copy(tiled_row as usize, linear_row, bytes);
} else {
- base + self.row(m, y, inner)
- };
- for (o, c) in offsets.iter_mut().zip(&columns) {
- *o = start + c;
+ let tiled_row = (base + self.row(m, y, inner)) as usize;
+ match run_len {
+ Some(8) => copy_runs::<8>(body, tiled_row, linear_row, &mut copy),
+ Some(16) => copy_runs::<16>(body, tiled_row, linear_row, &mut copy),
+ Some(32) => copy_runs::<32>(body, tiled_row, linear_row, &mut copy),
+ _ => copy_runs::<0>(body, tiled_row, linear_row, &mut copy),
+ }
+ copy_runs::<0>(last, tiled_row, linear_row, &mut copy);
}
- row(&offsets, z as usize * depth_pitch + y as usize * row_pitch, m.width as usize);
}
}
Ok(())
}
}
-/// The first `count` element offsets as runs of contiguous memory: (first
-/// element, bytes), so a linear row (or a swizzle's contiguous columns) is
-/// copied at once rather than element by element.
-fn runs(t: &[u64], count: usize, n: usize) -> impl Iterator- + '_ {
- let mut i = 0;
- std::iter::from_fn(move || {
- if i >= count {
- return None;
- }
- let start = i;
- i += 1;
- while i < count && t[i] == t[i - 1] + n as u64 {
- i += 1;
- }
- Some((start, (i - start) * n))
- })
+/// Copy micro-tile runs inline at a known width, or use each run's length for N = 0.
+fn copy_runs
(
+ runs: &[(usize, usize, usize)],
+ tiled_row: usize,
+ linear_row: usize,
+ copy: &mut impl FnMut(usize, usize, usize),
+) {
+ for &(tiled, linear, len) in runs {
+ let len = if N == 0 { len } else { N };
+ copy(tiled_row + tiled, linear_row + linear, len);
+ }
}
/// What a DXGI format stores per element: bytes, texels per element side
@@ -838,6 +857,27 @@ mod tests {
}
}
+ /// Sizes past the hardware's 16384 texels per side are refused instead
+ /// of overflowing the size arithmetic (found by random-input testing).
+ #[test]
+ fn extents_past_the_hardware_limit_are_invalid() {
+ for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] {
+ let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap();
+ assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16);
+ for (w, h) in [
+ (MAX_EXTENT + 1, 1),
+ (1, MAX_EXTENT + 1),
+ (u32::MAX, u32::MAX),
+ ] {
+ let result = Layout::new(&desc(w, h, 1, 16, swizzle));
+ assert_eq!(result, Err(Error::Invalid), "{w}x{h}");
+ }
+ let mut deep = desc(1, 1, 1, 16, swizzle);
+ deep.depth = u32::MAX;
+ assert_eq!(Layout::new(&deep), Err(Error::Invalid));
+ }
+ }
+
#[test]
fn blocks_hold_their_size_in_elements() {
for log2 in [8u32, 12, 16] {
@@ -872,6 +912,11 @@ mod tests {
desc(33, 17, 6, 1, Swizzle::SW_4KB_D),
desc(40, 9, 3, 2, Swizzle::SW_64KB_S),
desc(30, 20, 5, 4, Swizzle::LINEAR),
+ desc(83, 31, 6, 1, Swizzle::SW_256B_S),
+ Desc {
+ block: 4,
+ ..desc(109, 71, 6, 16, Swizzle::SW_256B_D)
+ },
Desc {
depth: 3,
..desc(70, 70, 4, 16, Swizzle::SW_4KB_S)
@@ -891,25 +936,32 @@ mod tests {
for slice in 0..slices {
for mip in 0..d.mips {
let m = l.mips[mip as usize];
- let row = m.width as usize * n;
- let plane = row * m.height as usize;
+ let active = m.width as usize * n;
+ let row = active + 13;
+ let plane = row * m.height as usize + 11;
let linear: Vec = (0..plane * m.depth as usize)
.map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8)
.collect();
l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap();
- let mut back = vec![0u8; linear.len()];
+ let mut back = vec![0xcc; linear.len()];
l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap();
- assert_eq!(back, linear, "{d:?} mip {mip}");
for z in 0..m.depth {
+ let base = z as usize * plane;
for y in 0..m.height {
+ let start = base + y as usize * row;
+ assert_eq!(back[start..start + active], linear[start..start + active]);
+ assert!(back[start + active..start + row].iter().all(|&b| b == 0xcc));
for x in 0..m.width {
let at = l.offset(mip, x, y, slice + z).unwrap() as usize;
+ let source = start + x as usize * n;
+ assert_eq!(tiled[at..at + n], linear[source..source + n]);
assert!(at + n <= seen.len(), "{d:?} mip {mip} outside");
assert!(at.is_multiple_of(n));
assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice");
seen[at] = true;
}
}
+ assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc));
}
}
}
@@ -982,6 +1034,37 @@ mod tests {
assert!(!t.planes[0].layout.addressable());
}
+ #[test]
+ fn texture_copies_reject_overflowing_pitches() {
+ let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap();
+ let mut tiled = vec![0; layout.size as usize];
+ let mut linear = [0; 32];
+ assert_eq!(
+ layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0),
+ Err(Error::TooSmall)
+ );
+ assert_eq!(
+ layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0),
+ Err(Error::TooSmall)
+ );
+ }
+
+ #[test]
+ fn volume_copy_rejects_overflowing_depth_pitch() {
+ let layout = Layout::new(&Desc {
+ dimension: Dimension::Tex3d,
+ depth: 3,
+ ..desc(4, 2, 1, 4, Swizzle::LINEAR)
+ })
+ .unwrap();
+ let tiled = vec![0; layout.size as usize];
+ let mut linear = [0; 96];
+ assert_eq!(
+ layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX),
+ Err(Error::TooSmall)
+ );
+ }
+
#[test]
fn bad_descriptions_and_buffers_are_refused() {
assert_eq!(
diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs
index 4a9e606d09..e6ca931502 100644
--- a/crates/victory-formats/src/xma.rs
+++ b/crates/victory-formats/src/xma.rs
@@ -53,7 +53,8 @@ pub struct Packet {
}
pub fn packet(data: &[u8], index: usize) -> Option {
- let b = data.get(index * PACKET_BYTES..index * PACKET_BYTES + 4)?;
+ let start = index.checked_mul(PACKET_BYTES)?;
+ let b = data.get(start..)?.get(..4)?;
let h = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
Some(Packet {
frames: h >> 26,
@@ -1112,6 +1113,12 @@ mod tests {
}
}
+ #[test]
+ fn packet_rejects_out_of_range_indices_and_partial_headers() {
+ assert!(packet(&[0; 4], usize::MAX / PACKET_BYTES + 1).is_none());
+ assert!(packet(&[0; 3], 0).is_none());
+ }
+
#[test]
fn packet_headers_and_frame_walk() {
// Two packets: frame A (100 bits) and B (16300 bits, crossing into
@@ -1155,11 +1162,13 @@ mod tests {
fn walks_saved_streams() {
let dir = std::env::var("VICTORY_XMA_STREAMS").unwrap();
let mut bad = 0;
+ let mut streams = 0;
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|e| e != "xma") {
continue;
}
+ streams += 1;
let data = std::fs::read(&path).unwrap();
let counted: u32 = (0..data.len() / PACKET_BYTES)
.map(|i| packet(&data, i).unwrap().frames)
@@ -1185,6 +1194,7 @@ mod tests {
);
bad += u32::from(walked != counted || errors > 0);
}
+ assert!(streams > 0, "VICTORY_XMA_STREAMS contains no .xma files");
assert_eq!(bad, 0);
}
diff --git a/crates/victory-game/Cargo.toml b/crates/victory-game/Cargo.toml
index b6239d69d6..92170b42fd 100644
--- a/crates/victory-game/Cargo.toml
+++ b/crates/victory-game/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "victory-game"
-description = "Everything specific to Grand Theft Auto VI: its containers, build identities, patches."
+description = "Everything specific to the title: its containers, build identities, patches."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
@@ -9,7 +9,7 @@ publish.workspace = true
[dependencies]
memchr.workspace = true
-miniz_oxide.workspace = true
+zlib-rs.workspace = true
[lints]
workspace = true
diff --git a/crates/victory-game/src/lib.rs b/crates/victory-game/src/lib.rs
index 008bbc89fb..affa682b48 100644
--- a/crates/victory-game/src/lib.rs
+++ b/crates/victory-game/src/lib.rs
@@ -1,11 +1,11 @@
-//! Everything specific to Grand Theft Auto VI: its container formats, build
+//! Everything specific to the title: its container formats, build
//! identities, and the hooks we place in its code (located by per-build
//! offsets or byte-pattern signatures). What may and may not be stored here
//! is defined in docs/asset-policy.md.
pub mod sgd5;
-/// A specific build of the Grand Theft Auto VI executable we know how to run.
+/// A specific build of the title executable we know how to run.
#[derive(Debug, Clone, Copy)]
pub struct KnownBuild {
/// Our own label, e.g. "1.0.0 retail".
diff --git a/crates/victory-game/src/sgd5.rs b/crates/victory-game/src/sgd5.rs
index 9a2539f376..5605b51622 100644
--- a/crates/victory-game/src/sgd5.rs
+++ b/crates/victory-game/src/sgd5.rs
@@ -29,9 +29,53 @@ pub struct Record<'a> {
impl Record<'_> {
/// The container, or `None` if the stream is corrupt.
pub fn unpack(&self) -> Option> {
- miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size)
- .ok()
- .filter(|out| out.len() == self.unpacked_size)
+ let mut state = zlib_rs::Inflate::new(false, 15);
+ let mut out = Vec::new();
+ let (mut in_pos, mut out_pos) = (0usize, 0usize);
+ loop {
+ if out_pos == self.unpacked_size {
+ let mut extra = [0u8; 1];
+ let status = state
+ .decompress(
+ &self.packed[in_pos..],
+ &mut extra,
+ zlib_rs::InflateFlush::NoFlush,
+ )
+ .ok()?;
+ return (status == zlib_rs::Status::StreamEnd
+ && state.total_out() as usize == self.unpacked_size)
+ .then_some(out);
+ }
+ if out_pos == out.len() {
+ let next_len = if out.is_empty() {
+ self.unpacked_size
+ .min(self.packed.len().saturating_mul(4).max(4096))
+ } else {
+ out.len().saturating_mul(2).min(self.unpacked_size)
+ };
+ out.resize(next_len, 0);
+ }
+ let status = state
+ .decompress(
+ &self.packed[in_pos..],
+ &mut out[out_pos..],
+ zlib_rs::InflateFlush::NoFlush,
+ )
+ .ok()?;
+ let next_in = state.total_in() as usize;
+ let next_out = state.total_out() as usize;
+ match status {
+ zlib_rs::Status::StreamEnd => {
+ out.truncate(next_out);
+ return (next_out == self.unpacked_size).then_some(out);
+ }
+ zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => {
+ in_pos = next_in;
+ out_pos = next_out;
+ }
+ zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None,
+ }
+ }
}
}
@@ -83,7 +127,13 @@ mod tests {
use super::*;
fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec {
- let packed = miniz_oxide::deflate::compress_to_vec(payload, 6);
+ let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())];
+ let config = zlib_rs::DeflateConfig {
+ window_bits: -15,
+ ..zlib_rs::DeflateConfig::new(6)
+ };
+ let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config);
+ assert_eq!(rc, zlib_rs::ReturnCode::Ok);
let n = (packed.len() + 12) as u32;
let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1];
out.extend_from_slice(name.as_bytes());
@@ -91,7 +141,7 @@ mod tests {
for v in [n, 0x000D_DCE7, n, payload.len() as u32] {
out.extend_from_slice(&v.to_le_bytes());
}
- out.extend_from_slice(&packed);
+ out.extend_from_slice(packed);
out
}
@@ -133,4 +183,36 @@ mod tests {
let r = records(&file).next().unwrap();
assert_eq!(r.unpack(), None);
}
+
+ #[test]
+ fn handles_empty_and_rejects_mismatched_or_truncated_streams() {
+ let empty = record_bytes("CS_empty", 0x3c, &[]);
+ assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new()));
+
+ let payload: Vec = (0..16_384u32)
+ .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8)
+ .collect();
+ let good = record_bytes("PS_big", 0x32, &payload);
+ let r = records(&good).next().unwrap();
+ assert_eq!(r.unpack(), Some(payload.clone()));
+
+ // Oversized stream (declared unpacked_size smaller than actual output).
+ let mut smaller = good.clone();
+ smaller[r.offset + 8..r.offset + 12]
+ .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes());
+ assert_eq!(records(&smaller).next().unwrap().unpack(), None);
+
+ // Under-filled stream (declared unpacked_size larger than actual output).
+ let mut larger = good.clone();
+ larger[r.offset + 8..r.offset + 12]
+ .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes());
+ assert_eq!(records(&larger).next().unwrap().unpack(), None);
+
+ // Truncated raw deflate stream.
+ let mut truncated = good[..good.len() - 1].to_vec();
+ let new_n = (truncated.len() - r.offset) as u32;
+ truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes());
+ truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes());
+ assert_eq!(records(&truncated).next().unwrap().unpack(), None);
+ }
}
diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml
index a24dd1a8f5..d380f3a95d 100644
--- a/crates/victory-gpu/Cargo.toml
+++ b/crates/victory-gpu/Cargo.toml
@@ -9,7 +9,7 @@ publish.workspace = true
[dependencies]
blake3.workspace = true
-miniz_oxide.workspace = true
+zlib-rs.workspace = true
tracing.workspace = true
anyhow.workspace = true
victory-formats.workspace = true
diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs
index 28c256949f..19947f3c13 100644
--- a/crates/victory-gpu/src/capture.rs
+++ b/crates/victory-gpu/src/capture.rs
@@ -20,18 +20,139 @@ pub(crate) fn folder() -> Option<&'static PathBuf> {
/// too, and their draws traced at debug level.
pub(crate) fn listed(n: u64) -> bool {
static LIST: std::sync::OnceLock> = std::sync::OnceLock::new();
- LIST.get_or_init(|| {
- let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
+ let named = LIST
+ .get_or_init(|| {
+ let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
+ list.split(',')
+ .filter_map(|f| f.trim().parse().ok())
+ .collect()
+ })
+ .contains(&n);
+ // `VICTORY_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first
+ // one that ran 500 draws or more (a title's first 3D frames: their
+ // numbers depend on how long the menus were shown), and the 30th and
+ // the 80th (the title opens with a cutscene made in the
+ // engine: later shots of it, in case the first is dark by design).
+ //
+ // `VICTORY_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted
+ // from that first one (the title's blue patches show from
+ // about the 118th frame on, when the window's model has arrived and
+ // the reflections hold values: none of the four above has them).
+ static ALSO: std::sync::OnceLock> = std::sync::OnceLock::new();
+ let also = ALSO.get_or_init(|| {
+ let list = std::env::var("VICTORY_CAPTURE_WORLD_ALSO").unwrap_or_default();
list.split(',')
.filter_map(|f| f.trim().parse().ok())
.collect()
- })
- .contains(&n)
+ });
+ let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
+ let after = n.wrapping_sub(first);
+ named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after))
+}
+
+/// With a capture folder, for the frames [`listed`]: `what` is added to
+/// the frame's `frame--ops.txt`, one line per draw, dispatch, copy or
+/// drop in the order recorded (the title records on several threads, so
+/// lines of different lists interleave; each names its list). The file
+/// says which pass writes which target, to find the pass whose output
+/// stays empty.
+#[cfg(feature = "diagnostics")]
+pub(crate) fn op(list: usize, what: impl FnOnce() -> String) {
+ use std::io::Write;
+ let frame = crate::queue::presented() + 1;
+ if !listed(frame) {
+ // Before the world: the last lines are kept, and written out when
+ // it starts (`before-world-ops.txt`): what the title drew just
+ // before (the title shows a title card there, whose text
+ // did not show).
+ if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX {
+ // At most 300 lines of a frame: the world's first frame alone
+ // (thousands of operations, recorded before it is known to be
+ // the world's) pushed everything before it out.
+ static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0));
+ {
+ let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner());
+ if in_frame.0 != frame {
+ *in_frame = (frame, 0);
+ }
+ in_frame.1 += 1;
+ if in_frame.1 > 300 {
+ return;
+ }
+ }
+ let what = what();
+ let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner());
+ if ring.len() >= RING_LINES {
+ ring.pop_front();
+ }
+ ring.push_back(format!("frame {frame} list {list:#x} {what}"));
+ }
+ return;
+ }
+ let Some(folder) = folder() else {
+ return;
+ };
+ static FILE: std::sync::Mutex> = std::sync::Mutex::new(None);
+ let what = what();
+ let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner());
+ if file.as_ref().is_none_or(|f| f.0 != frame) {
+ let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else {
+ return;
+ };
+ *file = Some((frame, 0, made));
+ }
+ if let Some((_, n, f)) = file.as_mut() {
+ *n += 1;
+ let _ = writeln!(f, "{n} list {list:#x} {what}");
+ }
+}
+
+/// The last lines of [`op`] before the world.
+#[cfg(feature = "diagnostics")]
+static RING: std::sync::Mutex> =
+ std::sync::Mutex::new(std::collections::VecDeque::new());
+#[cfg(feature = "diagnostics")]
+const RING_LINES: usize = 6000;
+
+/// Whether `VICTORY_CAPTURE_WORLD` is set.
+fn world_on() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_CAPTURE_WORLD").is_some())
+}
+
+/// The first frame that ran 500 draws or more (`VICTORY_CAPTURE_WORLD`).
+static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
+
+/// At the present of `frame`: the draws run on the host so far.
+pub(crate) fn frame_drew(frame: u64, drawn: u64) {
+ use std::sync::atomic::Ordering::Relaxed;
+ static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let before = LAST.swap(drawn, Relaxed);
+ if world_on()
+ && drawn.saturating_sub(before) >= 500
+ && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok()
+ {
+ tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6);
+ #[cfg(feature = "diagnostics")]
+ if let Some(folder) = folder() {
+ let lines: Vec = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into();
+ let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join("
+"));
+ }
+ }
}
/// Whether frame `n` is saved.
pub(crate) fn wanted(n: u64) -> bool {
- folder().is_some() && (n.is_power_of_two() || listed(n))
+ // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too
+ // (small pictures of menus, loading screens and title cards).
+ let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX;
+ // In the world: every 8th frame's picture, a timeline of the opening
+ // cutscene (its shots do not fall on the same frame numbers from run to
+ // run, so single frames cannot be compared between runs).
+ let first = WORLD.load(std::sync::atomic::Ordering::Relaxed);
+ let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(8);
+ folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world)
}
/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
@@ -63,11 +184,10 @@ fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows:
header.extend(h.to_be_bytes());
header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
chunk(&mut png, b"IHDR", &header);
- chunk(
- &mut png,
- b"IDAT",
- &miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3),
- );
+ let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())];
+ let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3));
+ debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok);
+ chunk(&mut png, b"IDAT", idat);
chunk(&mut png, b"IEND", &[]);
let path = folder.join(format!("{name}.png"));
match std::fs::write(&path, png) {
@@ -102,6 +222,17 @@ pub(crate) fn read_back(
device: &ID3D12Device,
list: &ID3D12GraphicsCommandList,
texture: &ID3D12Resource,
+) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
+ read_back_of(device, list, texture, 0)
+}
+
+/// As [`read_back`], of subresource `sub` (the stencil plane of a
+/// one-level, one-slice depth-stencil texture is subresource 1).
+fn read_back_of(
+ device: &ID3D12Device,
+ list: &ID3D12GraphicsCommandList,
+ texture: &ID3D12Resource,
+ sub: u32,
) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut total = 0;
@@ -110,7 +241,7 @@ pub(crate) fn read_back(
let desc = texture.GetDesc();
device.GetCopyableFootprints(
&desc,
- 0,
+ sub,
1,
0,
Some(&mut footprint),
@@ -161,7 +292,7 @@ pub(crate) fn read_back(
pResource: std::mem::transmute_copy(texture),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
- SubresourceIndex: 0,
+ SubresourceIndex: sub,
},
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
@@ -263,14 +394,27 @@ fn dump_one(
.ResourceBarrier(&[crate::host::transition(texture, state, copy)]);
}
let read = read_back(&host.device, &list.list, texture);
+ // The stencil plane of a depth-stencil target, which the title's
+ // lighting reads (material class in the low bits; 0x08 "inside a
+ // room", which the lamps of a room are multiplied by): the plane
+ // after the depth plane of a one-level, one-slice texture.
+ let stencil = (matches!(d.Format.0, 19..=22 | 44..=47)
+ && d.MipLevels == 1
+ && d.DepthOrArraySize == 1)
+ .then(|| read_back_of(&host.device, &list.list, texture, 1))
+ .flatten();
if state != copy {
list.list
.ResourceBarrier(&[crate::host::transition(texture, copy, state)]);
}
- read
+ (read, stencil)
};
+ let (read, stencil) = read;
list.close();
host.execute(&[&list]);
+ if let Some((buffer, footprint)) = stencil {
+ stencil_values(&buffer, &footprint, frame, resource);
+ }
let Some((buffer, footprint)) = read else { return };
let f = footprint.Footprint;
let mut data = std::ptr::null_mut();
@@ -281,6 +425,26 @@ fn dump_one(
}
let pitch = f.RowPitch as usize;
let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize);
+ // A 24-bit depth plane comes back as 32-bit words: which depth values
+ // (low 24 bits) and which top bytes it holds, the most common first.
+ if matches!(d.Format.0, 44..=47) {
+ let mut depths = std::collections::HashMap::::new();
+ let mut tops = std::collections::HashMap::::new();
+ for y in 0..f.Height as usize {
+ for x in 0..f.Width as usize {
+ let at = y * pitch + x * 4;
+ let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4]));
+ *depths.entry(w & 0xff_ffff).or_default() += 1;
+ *tops.entry(w >> 24).or_default() += 1;
+ }
+ }
+ let most = |m: std::collections::HashMap| {
+ let mut v: Vec<(u32, u32)> = m.into_iter().collect();
+ v.sort_by_key(|e| std::cmp::Reverse(e.1));
+ (v.len(), v.into_iter().take(12).collect::>())
+ };
+ tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)");
+ }
if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
let name = format!(
"frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
@@ -294,6 +458,67 @@ fn dump_one(
}
}
+/// Logs which values a stencil plane read back by [`read_back_of`] holds
+/// (the most common first), how many texels have each of its bits, and the
+/// box of the texels with bit 3 (0x08).
+fn stencil_values(
+ buffer: &ID3D12Resource,
+ footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
+ frame: u64,
+ resource: crate::object::This,
+) {
+ let f = footprint.Footprint;
+ let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize);
+ let mut data = std::ptr::null_mut();
+ // SAFETY: the copy finished; the mapping spans the footprint's rows of
+ // one byte a texel, the last row without its padding.
+ unsafe {
+ if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() {
+ return;
+ }
+ let rows = std::slice::from_raw_parts(data.cast::(), pitch * (h - 1) + w);
+ let mut values = [0u32; 256];
+ let mut bits = [0u32; 8];
+ // Left, top, right, bottom of the texels with bit 3.
+ let mut inside = [u32::MAX, u32::MAX, 0, 0];
+ for y in 0..h {
+ for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() {
+ values[usize::from(v)] += 1;
+ for (bit, count) in bits.iter_mut().enumerate() {
+ *count += u32::from(v >> bit & 1);
+ }
+ if v & 8 != 0 {
+ inside = [
+ inside[0].min(x as u32),
+ inside[1].min(y as u32),
+ inside[2].max(x as u32),
+ inside[3].max(y as u32),
+ ];
+ }
+ }
+ }
+ let mut most: Vec<(usize, u32)> = values
+ .iter()
+ .copied()
+ .enumerate()
+ .filter(|v| v.1 != 0)
+ .collect();
+ most.sort_by_key(|v| std::cmp::Reverse(v.1));
+ most.truncate(16);
+ tracing::info!(
+ frame,
+ ?resource,
+ width = w,
+ height = h,
+ values = ?most,
+ texels_with_bit = ?bits,
+ bit3_box = ?inside,
+ "stencil plane values (value, texels)"
+ );
+ buffer.Unmap(0, None);
+ }
+}
+
fn half(h: u16) -> f32 {
let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
let v = match exp {
@@ -336,7 +561,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
}
return Some(out);
}
- 87..=93 => {
+ // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below).
+ 87 | 88 | 90..=93 => {
for y in 0..h {
for x in 0..w {
let p = px(x, y, 4);
@@ -345,7 +571,7 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
}
return Some(out);
}
- 23..=25 => (4, Box::new(move |b| {
+ 23..=25 | 89 => (4, Box::new(move |b| {
let v = u32_at(b, 0);
[(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
})),
@@ -353,7 +579,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
let v = u32_at(b, 0);
[small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
})),
- 9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
+ 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
+ 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))),
33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
1..=2 => (16, Box::new(move |b| {
[0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
@@ -382,9 +609,90 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option
(0.0, finite.fold(0.0f32, f32::max))
};
let range = (high - low).max(1e-20);
- tracing::info!(format, low, high, "target values");
+ // How much of the target holds anything: a lit scene and one bright
+ // lamp on black have the same highest value.
+ let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count();
+ let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32;
+ tracing::info!(format, low, high, nonzero_percent, "target values");
+ // Small float colour targets (the 1x1 luminance and exposure targets):
+ // every texel's four channels as numbers. The picture has no alpha and
+ // eight bits a channel.
+ if matches!(format, 1..=2 | 9..=10) && w * h <= 16 {
+ for y in 0..h {
+ for x in 0..w {
+ let b = px(x, y, n);
+ let texel: [f32; 4] = if n == 16 {
+ [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i)))
+ } else {
+ [0, 1, 2, 3].map(|i| half(u16_at(b, i)))
+ };
+ tracing::info!(format, x, y, ?texel, "target texel");
+ }
+ }
+ }
+ // R32_UINT targets hold packed light (the title reads them back as
+ // R9G9B9E5): as floats their low, high and share above the lowest say
+ // nothing. How many texels hold any bit, and the highest channel value
+ // of the packed reading.
+ if format == 42 {
+ let (mut set, mut packed_high) = (0usize, 0f32);
+ for y in 0..h {
+ for x in 0..w {
+ let v = u32_at(px(x, y, 4), 0);
+ set += usize::from(v != 0);
+ let scale = 2f32.powi((v >> 27) as i32 - 24);
+ for k in 0..3 {
+ packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale);
+ }
+ }
+ }
+ let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32;
+ tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light");
+ // The same words as plain numbers, by class. Tables of indices and
+ // masks say nothing as floats or as packed light: in the title's
+ // shadow-mask table 0 is a block in full shadow, a word up to 255
+ // one value for the block, above that a block of the atlas, and all
+ // ones a texel never written.
+ let mut classes = [0usize; 6];
+ let mut highest_below_ones = 0u32;
+ for y in 0..h {
+ for x in 0..w {
+ let v = u32_at(px(x, y, 4), 0);
+ classes[match v {
+ 0 => 0,
+ 1..=15 => 1,
+ 16..=255 => 2,
+ 256..=0x00ff_ffff => 3,
+ u32::MAX => 5,
+ _ => 4,
+ }] += 1;
+ if v != u32::MAX {
+ highest_below_ones = highest_below_ones.max(v);
+ }
+ }
+ }
+ tracing::info!(
+ format,
+ width = w,
+ height = h,
+ zero = classes[0],
+ one_to_15 = classes[1],
+ to_255 = classes[2],
+ to_24_bits = classes[3],
+ larger = classes[4],
+ all_ones = classes[5],
+ highest_below_ones,
+ "target values as words"
+ );
+ }
+ // Float colours (scene light) go through a cube root: scaled linearly,
+ // a night scene under one lamp of 50 units came out all black.
+ let curved = matches!(format, 1..=2 | 9..=10 | 26);
for v in values {
- let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
+ let c = v.map(|c| {
+ let t = ((c - low) / range).clamp(0.0, 1.0);
+ ((if curved { t.cbrt() } else { t }) * 255.0) as u8
+ });
out.extend([c[0], c[1], c[2], 255]);
}
Some(out)
@@ -522,4 +830,18 @@ mod tests {
fn crc_matches_the_png_check_value() {
assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
}
+
+ /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2,
+ /// not B8G8R8A8.
+ #[test]
+ fn unorm16_and_xr_bias_targets_decode_as_their_formats() {
+ // Red 0x8000 (a half-float -0), green 0x4000, blue 0.
+ let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff];
+ assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255]));
+ // Red 0x3ff, green 0x1ff, blue 0, alpha 3.
+ let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes();
+ assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255]));
+ // B8G8R8A8 still swaps to RGBA.
+ assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255]));
+ }
}
diff --git a/crates/victory-gpu/src/console.rs b/crates/victory-gpu/src/console.rs
index 6070d2d67f..ab7252c576 100644
--- a/crates/victory-gpu/src/console.rs
+++ b/crates/victory-gpu/src/console.rs
@@ -17,7 +17,7 @@ impl Console {
/// advanced configuration; Series S has one range, counted as standard
/// (7,776 MiB, the published console-mode figure).
// shortcut: later system updates gave Series S titles more (amount not
- // published here); Grand Theft Auto VI sizes nothing from this figure
+ // published here); the title sizes nothing from this figure
// (it goes by the device type), so update it if a title does.
pub const fn title_memory(self) -> (usize, usize) {
match self {
diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs
index 8b7d13df1e..6abd41b36b 100644
--- a/crates/victory-gpu/src/copystat.rs
+++ b/crates/victory-gpu/src/copystat.rs
@@ -37,8 +37,98 @@ pub(crate) enum C {
TexWatched,
TexHashed,
TexChanged,
+ /// Frames presented since the last line (what the line divides by).
+ Frames,
+ /// Calls of list methods that record into a host list, and the
+ /// nanoseconds they took, summed over the title's recording threads.
+ RecordCalls,
+ RecordNs,
+ /// Waiting for host pipelines being made (`pipeline::make`).
+ PipelineWaitUs,
+ /// Dynamic descriptor slots: tables asked for, refused (no free run),
+ /// and the nanoseconds of the searches.
+ DynamicAsked,
+ DynamicRefused,
+ DynamicNs,
+ /// Marker texts for device-removed data (`HostList::note`).
+ NoteNs,
+ /// Ranges given to shaders (steps), their snapshots, and the bytes
+ /// compared after the submission.
+ GpuWrites,
+ SnapshotUs,
+ BackCompared,
+ /// Reading around unmapped pages after a failed bulk read.
+ SparseUs,
+ /// Guarding view memory (part of the write-watch askings' time).
+ GuardUs,
+ /// Bytes copied whole because their memory is neither write-watched
+ /// nor a view (`Shadow::update_free`).
+ WholeBytes,
+ /// Submissions with ranges shaders write (they need the GPU's results
+ /// before they return).
+ BackSubmissions,
+ /// The title's frame waits (`frame::wait`) and the time slept in them,
+ /// over all its threads.
+ PaceWaits,
+ PaceUs,
+ /// After a present: until the title's first list call and until its
+ /// first submission; and from its last submission to its next present.
+ UntilRecordUs,
+ UntilSubmitUs,
+ TailUs,
+ /// Resetting host lists (`HostList::reset`).
+ ResetNs,
+ /// What shaders wrote: finding the 64 KiB pieces that differ, how many
+ /// do, and putting them into title memory.
+ BackScanUs,
+ BackDiffer,
+ BackSyncUs,
+ /// Texture uploads recorded, and left out as unchanged.
+ TexUploads,
+ TexSkipped,
+ /// Held submissions a present ran although their waits were not met.
+ Forced,
+ /// Ranges named through unordered access views by shaders that cannot
+ /// store to buffers, not given to shaders as written, and their bytes.
+ GpuWritesLeftOut,
+ GpuWritesLeftOutBytes,
+ /// Waits for memory values looked at (`list::ValueWait::met`) and the
+ /// nanoseconds the looks took, on every thread.
+ WaitChecks,
+ WaitCheckNs,
+ /// Host lists made (`Host::new_list`: for the lists a queue holds and
+ /// for the parts of lists cut at waits) and the nanoseconds that took.
+ HostLists,
+ HostListNs,
+ /// Parts of held submissions that ran while the part behind them could
+ /// have run with them (its waits were met already).
+ PartsTogether,
+ /// Microseconds of the copies counted in `WholeBytes`.
+ WholeUs,
+ /// Submissions by how long the card was waited for (under 2 ms, 2-8,
+ /// 8-32, longer), and the microseconds waited in each class.
+ CardUnder2,
+ Card2To8,
+ Card8To32,
+ CardOver32,
+ CardUnder2Us,
+ Card2To8Us,
+ Card8To32Us,
+ CardOver32Us,
+ /// Submissions that hand nothing back to the title (no range shaders
+ /// write, no value written when done), and the microseconds the card
+ /// was waited for them.
+ NothingBack,
+ NothingBackUs,
+ /// Waits for every earlier shader write recorded into host lists: for
+ /// the title's barrier groups, for its barriers on buffers, and the
+ /// indirect commands bounded (each a dispatch of ours between two such
+ /// waits).
+ WaitsForGroups,
+ WaitsForBuffers,
+ IndirectBounded,
}
-const COUNTERS: usize = 22;
+const COUNTERS: usize = 80;
static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS];
pub(crate) fn add(c: C, n: u64) {
@@ -59,6 +149,112 @@ pub(crate) fn mode() -> u8 {
type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>;
static RANGES: Mutex> = Mutex::new(None);
+/// Per range copied whole because its memory is not watched (start,
+/// length): copies and microseconds.
+static WHOLE: Mutex >> = Mutex::new(None);
+
+/// `len` bytes at `src`, memory that is not watched, were copied whole in
+/// `us`.
+pub(crate) fn whole(src: usize, len: usize, us: u64) {
+ add(C::WholeUs, us);
+ let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
+ let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0));
+ e.0 += 1;
+ e.1 += us;
+}
+
+/// The longest wait for the card since the last line: microseconds, and
+/// what ran (lists and pipelines).
+static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new()));
+
+/// The waits for the card since the last line by what ran (lists and
+/// pipelines): how many, and their microseconds.
+static WAITS_BY_WORK: Mutex >> = Mutex::new(None);
+
+/// With `VICTORY_GPU_TIMING`: the commands' time on the card since the last
+/// line by what they ran (a pipeline, or the kind of command): how many,
+/// their microseconds, and the longest one's.
+static COMMANDS_BY_WORK: Mutex >> = Mutex::new(None);
+
+/// A command took `ms` on the card (timing run). `op` is its note: the
+/// kind and size first, then the pipeline in brackets, then what it binds.
+pub(crate) fn command_took(op: &str, ms: f64) {
+ let us = (ms * 1e3) as u64;
+ let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner());
+ let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0));
+ e.0 += 1;
+ e.1 += us;
+ e.2 = e.2.max(us);
+}
+
+/// What a command's note is summed under: its pipeline (`[compute ...]`,
+/// `[mesh ..., pixel ...]`) with the command's first word, or without a
+/// pipeline its first two words.
+fn command_key(op: &str) -> String {
+ let head = op.split(" | ").next().unwrap_or(op);
+ let word = head.split(' ').next().unwrap_or("");
+ match (head.find('['), head.find(']')) {
+ (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]),
+ _ => head.split(' ').take(2).collect::>().join(" "),
+ }
+}
+
+/// The card was waited for `us` for a submission; `what` names it if it is
+/// the longest since the last line.
+pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) {
+ let (n, t) = match us {
+ 0..2_000 => (C::CardUnder2, C::CardUnder2Us),
+ 2_000..8_000 => (C::Card2To8, C::Card2To8Us),
+ 8_000..32_000 => (C::Card8To32, C::Card8To32Us),
+ _ => (C::CardOver32, C::CardOver32Us),
+ };
+ add(n, 1);
+ add(t, us);
+ // Every submission is named (some forty a frame): the same lists run
+ // every frame, and the eight longest waits of a line were one list
+ // eight times.
+ let text = what();
+ {
+ let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner());
+ let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0));
+ e.0 += 1;
+ e.1 += us;
+ }
+ let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner());
+ if us > longest.0 {
+ *longest = (us, text);
+ }
+}
+
+/// Whether an experiment on barriers is on (`VICTORY_BARRIER_TEST`): bit 0
+/// for `groups` (the title's barrier groups record no wait for earlier
+/// shader writes), bit 1 for `indirect` (the pass that bounds an indirect
+/// command runs without its two such waits; its state changes stay), both
+/// bits for `both`. For timing only: without the waits a shader may read
+/// what another has not finished writing.
+pub(crate) fn barrier_test() -> u8 {
+ static TEST: std::sync::OnceLock = std::sync::OnceLock::new();
+ *TEST.get_or_init(|| match std::env::var("VICTORY_BARRIER_TEST").as_deref() {
+ Ok("groups") => 1,
+ Ok("indirect") => 2,
+ Ok("both") => 3,
+ _ => 0,
+ })
+}
+
+/// Per range compared after a submission (start, length): times, and the
+/// bytes of it written back to the title.
+static COMPARED: Mutex>> = Mutex::new(None);
+
+/// `len` bytes at `src` were compared after a submission and `written` of
+/// them put back into title memory.
+pub(crate) fn compared(src: usize, len: usize, written: usize) {
+ let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner());
+ let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0));
+ e.0 += 1;
+ e.1 += written as u64;
+}
+
/// A copy of `len` bytes from `src` (memory type `kind`) took `us`.
pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) {
let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner());
@@ -71,6 +267,763 @@ pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) {
e.2 += us;
}
+/// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB,
+/// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of
+/// every crate in the process: in diagnostics builds [`Counting`] stands in
+/// front of the system's heap. The memory map's "process heap segments"
+/// hold the blocks under about half a megabyte of ours, of the graphics
+/// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by
+/// some 2 MB a frame, and nothing said whose): this says which part is
+/// ours. Bigger blocks are allocations of their own in the map.
+static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
+
+/// The class of [`OWN`] a block of `size` bytes counts in.
+fn block_class(size: usize) -> usize {
+ match size {
+ 0..0x1000 => 0,
+ 0x1000..0x1_0000 => 1,
+ 0x1_0000..0x10_0000 => 2,
+ _ => 3,
+ }
+}
+
+fn own(size: usize, made: bool) {
+ let class = block_class(size);
+ if made {
+ OWN[class].fetch_add(size as u64, Relaxed);
+ OWN[4 + class].fetch_add(1, Relaxed);
+ } else {
+ OWN[class].fetch_sub(size as u64, Relaxed);
+ OWN[4 + class].fetch_sub(1, Relaxed);
+ }
+}
+
+/// Our own blocks of [`BIG`] bytes and more alive now: where each is (0:
+/// none) and its bytes. The memory map lists the process's big allocations
+/// by size without saying whose they are (run 65: one of 544 MB, one of
+/// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them
+/// are ours.
+static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64];
+static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64];
+const BIG: usize = 32 << 20;
+
+/// A block of [`BIG`] bytes or more was made at `at`, or released there.
+fn big(at: *mut u8, size: usize, made: bool) {
+ if size < BIG {
+ return;
+ }
+ for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) {
+ if made {
+ if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() {
+ bytes.store(size as u64, Relaxed);
+ return;
+ }
+ } else if place.load(Relaxed) == at as usize {
+ bytes.store(0, Relaxed);
+ place.store(0, Relaxed);
+ return;
+ }
+ }
+}
+
+/// The sizes of our own big blocks alive, largest first, in MB.
+fn big_blocks() -> String {
+ let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect();
+ sizes.sort_unstable_by(|a, b| b.cmp(a));
+ let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect();
+ if text.is_empty() { "none".into() } else { text.join(", ") }
+}
+
+/// The system's allocator with every block counted in [`OWN`] (two atomic
+/// additions per allocation and per release: diagnostics builds only).
+struct Counting;
+
+// SAFETY: every call goes to the system's allocator unchanged; only
+// counters are kept beside it.
+unsafe impl std::alloc::GlobalAlloc for Counting {
+ unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
+ // SAFETY: the caller's contract, passed on.
+ let at = unsafe { std::alloc::System.alloc(layout) };
+ if !at.is_null() {
+ own(layout.size(), true);
+ big(at, layout.size(), true);
+ }
+ at
+ }
+
+ unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 {
+ // SAFETY: the caller's contract, passed on.
+ let at = unsafe { std::alloc::System.alloc_zeroed(layout) };
+ if !at.is_null() {
+ own(layout.size(), true);
+ big(at, layout.size(), true);
+ }
+ at
+ }
+
+ unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) {
+ own(layout.size(), false);
+ big(at, layout.size(), false);
+ // SAFETY: the caller's contract, passed on.
+ unsafe { std::alloc::System.dealloc(at, layout) };
+ }
+
+ unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 {
+ // SAFETY: the caller's contract, passed on.
+ let moved = unsafe { std::alloc::System.realloc(at, layout, size) };
+ if !moved.is_null() {
+ own(layout.size(), false);
+ own(size, true);
+ big(at, layout.size(), false);
+ big(moved, size, true);
+ }
+ moved
+ }
+}
+
+#[global_allocator]
+static HEAP: Counting = Counting;
+
+#[cfg(test)]
+mod command_tests {
+ /// Commands are summed by pipeline and first word; those without a
+ /// pipeline by their first two words.
+ #[test]
+ fn commands_are_named_by_their_pipeline() {
+ use super::command_key;
+ assert_eq!(
+ command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"),
+ "dispatch [compute 24f989b98dcb03f0]"
+ );
+ assert_eq!(
+ command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"),
+ "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]"
+ );
+ assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload");
+ assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy");
+ }
+}
+
+#[cfg(test)]
+mod own_tests {
+ use super::{OWN, block_class};
+ use std::sync::atomic::Ordering::Relaxed;
+
+ #[test]
+ fn blocks_count_in_their_size_class() {
+ assert_eq!(block_class(0), 0);
+ assert_eq!(block_class(4095), 0);
+ assert_eq!(block_class(4096), 1);
+ assert_eq!(block_class(65535), 1);
+ assert_eq!(block_class(65536), 2);
+ assert_eq!(block_class((1 << 20) - 1), 2);
+ assert_eq!(block_class(1 << 20), 3);
+ }
+
+ /// A block of 32 MiB or more is listed by its size while it lives.
+ #[test]
+ fn big_blocks_are_listed_while_they_live() {
+ let size = (48usize << 20) + 4096;
+ let listed = |at: usize| {
+ super::BIG_AT
+ .iter()
+ .zip(&super::BIG_BYTES)
+ .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64)
+ };
+ let block = vec![0u8; size];
+ let at = block.as_ptr() as usize;
+ assert!(listed(at));
+ assert!(super::big_blocks().contains("48.00"));
+ drop(block);
+ assert!(!listed(at));
+ }
+
+ /// A big block shows in the counters while it lives (other tests
+ /// allocate small blocks meanwhile: only the big class is looked at,
+ /// and only for at least this block).
+ #[test]
+ fn a_block_is_counted_while_it_lives() {
+ let block = vec![1u8; 8 << 20];
+ assert!(OWN[3].load(Relaxed) >= 8 << 20);
+ assert!(OWN[7].load(Relaxed) >= 1);
+ drop(block);
+ assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero");
+ }
+}
+
+/// The process's memory in bytes: in physical memory, and committed
+/// (private bytes).
+fn process_memory() -> (u64, u64) {
+ use windows_sys::Win32::System::ProcessStatus::{
+ K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
+ };
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ let mut c = PROCESS_MEMORY_COUNTERS {
+ cb: size_of::() as u32,
+ ..Default::default()
+ };
+ // SAFETY: our own process and a sized structure.
+ unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
+ (c.WorkingSetSize as u64, c.PagefileUsage as u64)
+}
+
+/// The PC's memory in bytes: physical memory free, and what is left to
+/// commit.
+fn system_memory() -> (u64, u64) {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ // SAFETY: plain data the call fills in.
+ let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ m.dwLength = size_of::() as u32;
+ // SAFETY: a sized structure.
+ unsafe { GlobalMemoryStatusEx(&mut m) };
+ (m.ullAvailPhys, m.ullAvailPageFile)
+}
+
+/// Whether the address space is walked for the memory map line
+/// ([`log_memory_map`]). On by default (this module is in diagnostics
+/// builds only); `VICTORY_MEMORY_MAP=0` leaves the walk out.
+fn memory_map() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_MEMORY_MAP").is_none_or(|v| v != "0"))
+}
+
+/// Asks which of the pages in `asked` (address, answer) are in physical
+/// memory and adds the bytes each stands for (kind, bytes) to its kind.
+fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) {
+ use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx;
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ // SAFETY: our own process; `asked` holds that many entries of two
+ // words each, as the call fills them in.
+ let ok = unsafe {
+ K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32)
+ } != 0;
+ if ok {
+ for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) {
+ // Bit 0 of the answer: the page is in the process's memory.
+ if a[1] & 1 != 0 {
+ present[kind] += bytes;
+ }
+ }
+ }
+ asked.clear();
+ stands.clear();
+}
+
+/// Logs what the process has committed by kind, from a walk of its address
+/// space, and how much of each kind is in physical memory (one page in
+/// sixteen is asked about). The kinds tell the title's own memory from
+/// ours: the title's heaps and page views lie at console addresses (below
+/// 1 TiB), everything the host allocates lies far above. Run 30, seen
+/// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in
+/// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB
+/// (windows of title memory), 0.46 GB the pipeline library's file; mapped
+/// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's
+/// shader cache file.
+/// shortcut: the walk takes about 0.6 s on a thread of its own, and a
+/// query of a region of gigabytes holds up other threads' memory calls
+/// for its length (89 ms for the 6.2 GB pool), so it runs with every
+/// sixth memory line only.
+fn log_memory_map() {
+ use windows_sys::Win32::System::Memory::{
+ MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE,
+ VirtualQuery,
+ };
+ const KINDS: [&str; 10] = [
+ "the title's heaps (private, console addresses)",
+ "views of the title's pages (mapped, console addresses)",
+ "the title's page pool (mapped, 1 GB and more)",
+ "process heap segments (private, 15.8 MB each)",
+ "windows of title memory and other 4 MiB allocations",
+ "write-combined (buffers shared with the card)",
+ "other private allocations of 1 MB and more",
+ "other private allocations under 1 MB",
+ "files and other mappings at host addresses",
+ "programs and libraries",
+ ];
+ /// Console addresses lie below this.
+ const HOST: usize = 1 << 40;
+ /// One page asked about stands for this much.
+ const STEP: usize = 64 << 10;
+ let started = std::time::Instant::now();
+ // Allocation, start, bytes, committed, type, protection.
+ type Region = (usize, usize, usize, bool, u32, u32);
+ let mut regions: Vec = Vec::new();
+ let mut at = 0usize;
+ loop {
+ // SAFETY: plain data filled in by the query.
+ let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+ // SAFETY: a valid out pointer of the right size.
+ if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 {
+ break;
+ }
+ if m.State != MEM_FREE {
+ regions.push((
+ m.AllocationBase as usize,
+ m.BaseAddress as usize,
+ m.RegionSize,
+ m.State == MEM_COMMIT,
+ m.Type,
+ m.Protect,
+ ));
+ }
+ let next = (m.BaseAddress as usize).saturating_add(m.RegionSize);
+ if next <= at {
+ break;
+ }
+ at = next;
+ }
+ // Each allocation's whole size, reserved parts included.
+ let mut whole: HashMap = HashMap::new();
+ for r in ®ions {
+ *whole.entry(r.0).or_default() += r.2;
+ }
+ let kind = |r: &Region| -> usize {
+ let size = whole.get(&r.0).copied().unwrap_or(0);
+ let console = r.0 < HOST;
+ if r.4 == MEM_IMAGE {
+ 9
+ } else if r.4 == MEM_MAPPED {
+ match (console, size >= 1 << 30) {
+ (false, _) => 8,
+ (true, true) => 2,
+ (true, false) => 1,
+ }
+ } else if console {
+ 0
+ } else if size == 0xfd_0000 {
+ 3
+ } else if size == 4 << 20 {
+ 4
+ } else if r.5 & PAGE_WRITECOMBINE != 0 {
+ 5
+ } else if size >= 1 << 20 {
+ 6
+ } else {
+ 7
+ }
+ };
+ let mut committed = [0u64; 10];
+ let mut present = [0u64; 10];
+ let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096);
+ let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096);
+ for r in regions.iter().filter(|r| r.3) {
+ let k = kind(r);
+ committed[k] += r.2 as u64;
+ let mut offset = 0;
+ while offset < r.2 {
+ asked.push([r.1 + offset, 0]);
+ stands.push((k, STEP.min(r.2 - offset) as u64));
+ if asked.len() == 4096 {
+ in_memory(&mut asked, &mut stands, &mut present);
+ }
+ offset += STEP;
+ }
+ }
+ if !asked.is_empty() {
+ in_memory(&mut asked, &mut stands, &mut present);
+ }
+ let text: Vec = (0..KINDS.len())
+ .filter(|&k| committed[k] > 0)
+ .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20))
+ .collect();
+ tracing::info!(
+ "memory map ({} regions, {} ms): {}",
+ regions.len(),
+ started.elapsed().as_millis(),
+ text.join("; ")
+ );
+ // The private allocations the kinds above leave as "other" (and the
+ // write-combined ones), grouped by their size: the sizes name their
+ // owners (the pipeline library's file to the byte, a snapshot buffer
+ // of a title heap's size, the driver's blocks). Committed bytes by
+ // allocation first, then allocations by (kind, whole size).
+ let mut by_allocation: HashMap = HashMap::new();
+ for r in regions.iter().filter(|r| r.3) {
+ let k = kind(r);
+ if k == 5 || k == 6 {
+ by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64;
+ }
+ }
+ let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new();
+ for (base, &(k, bytes)) in &by_allocation {
+ let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default();
+ group.0 += 1;
+ group.1 += bytes;
+ }
+ let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect();
+ groups.sort_by_key(|g| std::cmp::Reverse(g.1.1));
+ let biggest: Vec = groups
+ .iter()
+ .take(20)
+ .map(|&((k, size), (n, bytes))| {
+ format!(
+ "{n} of {:.2} MB{}: {} MB",
+ size as f64 / (1 << 20) as f64,
+ if k == 5 { " write-combined" } else { "" },
+ bytes >> 20
+ )
+ })
+ .collect();
+ tracing::info!(
+ "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}",
+ biggest.len(),
+ groups.len(),
+ biggest.join("; ")
+ );
+}
+
+/// Logs where the memory is: the process and the PC, then what this crate
+/// holds by kind (alive now), then the host buffers made since the start.
+fn log_memory() {
+ use std::sync::atomic::Ordering::Relaxed;
+ let mb = |v: u64| v as f64 / (1 << 20) as f64;
+ let (working, private) = process_memory();
+ let (free, left) = system_memory();
+ let copies = crate::shadow::memory();
+ let staged = crate::texture::memory();
+ let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed));
+ let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect();
+ let windows = crate::shadow::windows();
+ let stagings = crate::texture::let_go();
+ let census = crate::resource::census();
+ let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect();
+ let card = crate::host::host()
+ .and_then(|h| h.video_memory())
+ .unwrap_or_default();
+ // What else holds memory: the map, on a thread of its own, with every
+ // sixth line; and what the shader table and the pipeline library keep.
+ static LINES: AtomicU64 = AtomicU64::new(0);
+ static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+ if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) {
+ let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| {
+ log_memory_map();
+ WALKING.store(false, Relaxed);
+ });
+ if walk.is_err() {
+ WALKING.store(false, Relaxed);
+ }
+ }
+ let kept = crate::pipeline::kept();
+ tracing::info!(
+ "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \
+ {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)",
+ kept[0],
+ mb(kept[1]),
+ kept[2],
+ mb(kept[3]),
+ mb(kept[4]),
+ mb(kept[5]),
+ );
+ tracing::info!(
+ "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \
+ host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \
+ fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \
+ {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \
+ room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \
+ shared with it in use",
+ census[2],
+ mb(census[3]),
+ census[0],
+ mb(census[1]),
+ census[4],
+ mb(census[5]),
+ census[6],
+ kinds[2],
+ mb(kinds[3]),
+ kinds[4],
+ mb(kinds[5]),
+ kinds[6],
+ crate::draw::HEAP_TEXTURES_FULL.load(Relaxed),
+ mb(card[1]),
+ mb(card[0]),
+ mb(card[3]),
+ );
+ tracing::info!(
+ "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
+ {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
+ asked for in each",
+ windows[0],
+ mb(windows[1]),
+ stagings[0],
+ mb(stagings[1]),
+ mb(windows[2]),
+ );
+ tracing::info!(
+ "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \
+ left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \
+ outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \
+ textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \
+ {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \
+ {:.0} MB, {} card buffers {:.0} MB",
+ mb(private),
+ mb(working),
+ mb(free),
+ mb(left),
+ copies[0],
+ mb(copies[1]),
+ copies[2],
+ mb(copies[3]),
+ copies[4],
+ mb(copies[5]),
+ staged[0],
+ mb(staged[1]),
+ staged[2],
+ textures[0],
+ mb(textures[1]),
+ crate::resource::placed_textures(),
+ made[0],
+ mb(made[1]),
+ made[2],
+ mb(made[3]),
+ made[4],
+ mb(made[5]),
+ );
+ // What the line above leaves open: what is alive of the buffers "made
+ // so far", what the windows hold and what holds them, and what our own
+ // code has allocated.
+ let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect();
+ let window = crate::shadow::window_use();
+ let views = crate::descriptor::views_kept();
+ let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect();
+ tracing::info!(
+ "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})",
+ alive[0],
+ alive[1],
+ mb(alive[2]),
+ alive[3],
+ mb(alive[4]),
+ alive[5],
+ alive[6],
+ mb(alive[7]),
+ window[7] >> 10,
+ mb(window[0]),
+ window[1],
+ mb(window[2]),
+ window[3],
+ mb(window[4]),
+ window[5],
+ mb(window[6]),
+ crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed),
+ views[0],
+ views[1],
+ mb(views[2]),
+ mb(own[..4].iter().sum()),
+ own[4..].iter().sum::(),
+ mb(own[0]),
+ own[4],
+ mb(own[1]),
+ own[5],
+ mb(own[2]),
+ own[6],
+ mb(own[3]),
+ own[7],
+ );
+ // Round 2: what the view table still holds and what goes around it,
+ // what host lists cost, the card's share that is the layer's own or
+ // the title's no more, and which big blocks are ours.
+ let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect();
+ tracing::info!(
+ "memory, more: views named whole in their records since the start: {} constant buffer \
+ views, {} views of placed memory; of the view table's entries {} are constant buffer \
+ views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \
+ made by the host, {} preludes made for them, private bytes grew {:.0} MB while \
+ lists were made; twins of depth textures: {:.0} MB; host copies of \
+ placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \
+ them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \
+ let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}",
+ views[6],
+ views[7],
+ views[3],
+ views[4],
+ views[5],
+ lists[0],
+ lists[1],
+ lists[2] as i64 as f64 / (1 << 20) as f64,
+ mb(census[7]),
+ mb(census[8]),
+ mb(census[9]),
+ mb(kept[6]),
+ big_blocks(),
+ );
+ // Round 3: whether windows hold the same memory more than once (they
+ // can, once they are cut finer than 4 MiB), and how many host lists
+ // the title made and never used.
+ tracing::info!(
+ "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \
+ memory that is in more than one window, and is copied once for each); host lists never \
+ reset since they were made: {}",
+ mb(copies[3]),
+ mb(crate::shadow::window_cover()),
+ lists[3],
+ );
+}
+
+/// Microseconds since the first call.
+fn now_us() -> u64 {
+ static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new();
+ EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
+}
+
+/// When the last frame was presented and when the last submission returned
+/// ([`now_us`]), and whether a list call and a submission followed that
+/// present yet.
+static PRESENTED_AT: AtomicU64 = AtomicU64::new(0);
+static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0);
+static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
+static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
+
+/// What a thread that submits did between its submissions and in them
+/// (microseconds; list calls in nanoseconds).
+#[derive(Default, Clone, Copy)]
+struct Submitter {
+ submissions: u64,
+ /// From a submission's return to the next one's call: wall time, of it
+ /// the thread running (user, kernel), and inside our list calls.
+ between: u64,
+ between_user: u64,
+ between_kernel: u64,
+ between_ours: u64,
+ /// Waiting for the submission lock; running inside submissions.
+ lock: u64,
+ inside_user: u64,
+ inside_kernel: u64,
+}
+
+/// By thread: the submitting threads, and list-call time (nanoseconds,
+/// calls) of every recording thread.
+static SUBMITTERS: Mutex> = Mutex::new(Vec::new());
+static RECORDERS: Mutex> = Mutex::new(Vec::new());
+
+thread_local! {
+ /// This thread's last submission: when it returned ([`now_us`]) and the
+ /// thread's processor time then (user, kernel).
+ static LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) };
+ /// The thread's processor time when its running submission was called.
+ static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
+ /// List-call nanoseconds of this thread since its last submission.
+ static OURS: std::cell::Cell = const { std::cell::Cell::new(0) };
+ /// List-call time not yet added to `RECORDERS` (nanoseconds, calls).
+ static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) };
+}
+
+fn thread_id() -> u32 {
+ // SAFETY: a plain query.
+ unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }
+}
+
+fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 {
+ (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10
+}
+
+/// This thread's processor time so far (user, kernel), in microseconds.
+fn thread_times() -> (u64, u64) {
+ use windows_sys::Win32::Foundation::FILETIME;
+ use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes};
+ let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
+ let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
+ // SAFETY: our own thread and four valid out pointers.
+ unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) };
+ (micros(user), micros(kernel))
+}
+
+/// The process's processor time so far (user, kernel), in microseconds.
+fn process_times() -> (u64, u64) {
+ use windows_sys::Win32::Foundation::FILETIME;
+ use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};
+ let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
+ let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero);
+ // SAFETY: our own process and four valid out pointers.
+ unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) };
+ (micros(user), micros(kernel))
+}
+
+fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter {
+ let at = match all.iter().position(|s| s.0 == id) {
+ Some(at) => at,
+ None => {
+ all.push((id, Submitter::default()));
+ all.len() - 1
+ }
+ };
+ &mut all[at].1
+}
+
+/// A list call on this thread that began at `started` has returned.
+pub(crate) fn recorded(started: std::time::Instant) {
+ let ns = started.elapsed().as_nanos() as u64;
+ add(C::RecordCalls, 1);
+ add(C::RecordNs, ns);
+ if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) {
+ let began = now_us().saturating_sub(ns / 1000);
+ add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed)));
+ }
+ OURS.with(|o| o.set(o.get() + ns));
+ let (unsent, calls) = UNSENT.with(|u| u.get());
+ let (unsent, calls) = (unsent + ns, calls + 1);
+ // By thread, a couple of milliseconds at a time.
+ if unsent < 2_000_000 {
+ UNSENT.with(|u| u.set((unsent, calls)));
+ return;
+ }
+ UNSENT.with(|u| u.set((0, 0)));
+ let id = thread_id();
+ let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner());
+ match all.iter_mut().find(|r| r.0 == id) {
+ Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls),
+ None => all.push((id, unsent, calls)),
+ }
+}
+
+/// A submission is called on this thread (before it waits for the
+/// submission lock).
+pub(crate) fn submission_begins() {
+ let now = now_us();
+ if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) {
+ add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed)));
+ }
+ let (user, kernel) = thread_times();
+ ENTERED.with(|e| e.set((user, kernel)));
+ let ours = OURS.with(|o| o.replace(0));
+ if let Some((left, u, k)) = LEFT.with(|l| l.get()) {
+ let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
+ let s = submitter(&mut all, thread_id());
+ s.between += now.saturating_sub(left);
+ s.between_user += user.saturating_sub(u);
+ s.between_kernel += kernel.saturating_sub(k);
+ s.between_ours += ours;
+ }
+}
+
+/// The submission returns; it waited `lock` microseconds for the
+/// submission lock.
+pub(crate) fn submission_ends(lock: u64) {
+ let now = now_us();
+ SUBMITTED_AT.store(now, Relaxed);
+ let (user, kernel) = thread_times();
+ let (u, k) = ENTERED.with(|e| e.get());
+ LEFT.with(|l| l.set(Some((now, user, kernel))));
+ OURS.with(|o| o.set(0));
+ let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner());
+ let s = submitter(&mut all, thread_id());
+ s.submissions += 1;
+ s.lock += lock;
+ s.inside_user += user.saturating_sub(u);
+ s.inside_kernel += kernel.saturating_sub(k);
+}
+
+/// The title calls its present (before our own copy to the window runs).
+pub(crate) fn present_begins() {
+ add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)));
+}
+
+/// A frame was presented.
+pub(crate) fn presented() {
+ add(C::Frames, 1);
+ PRESENTED_AT.store(now_us(), Relaxed);
+ RECORDED_SINCE.store(false, Relaxed);
+ SUBMITTED_SINCE.store(false, Relaxed);
+}
+
fn page_faults() -> u64 {
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
@@ -85,9 +1038,14 @@ fn page_faults() -> u64 {
u64::from(c.PageFaultCount)
}
-/// Logs the counters per frame over `frames` frames, and the ranges that
-/// took most bytes.
+/// Logs the counters per frame, and the ranges that took most bytes. The
+/// counters run from line to line, so they are divided by the frames
+/// presented since the last line, not by `frames` (the frames of the last
+/// second or more: a 4 s frame after an unlogged 4 s frame showed two
+/// frames' counts as one's).
pub(crate) fn log(frames: f64) {
+ let counted = COUNT[C::Frames as usize].swap(0, Relaxed);
+ let frames = if counted > 0 { counted as f64 } else { frames };
static FAULTS: AtomicU64 = AtomicU64::new(0);
let faults = page_faults();
let faults = faults - FAULTS.swap(faults, Relaxed).min(faults);
@@ -127,6 +1085,204 @@ pub(crate) fn log(frames: f64) {
mb(c[C::TexHashed as usize]),
mb(c[C::TexChanged as usize]),
);
+ tracing::info!(
+ "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \
+ threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \
+ refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \
+ {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \
+ guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \
+ sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \
+ {:.0} steps {:.1} MB left out",
+ c[C::RecordCalls as usize],
+ c[C::RecordNs as usize] / 1e6,
+ ms(c[C::PipelineWaitUs as usize]),
+ c[C::DynamicAsked as usize],
+ c[C::DynamicRefused as usize],
+ c[C::DynamicNs as usize] / 1e6,
+ c[C::NoteNs as usize] / 1e6,
+ c[C::GpuWrites as usize],
+ c[C::BackSubmissions as usize],
+ ms(c[C::SnapshotUs as usize]),
+ mb(c[C::BackCompared as usize]),
+ ms(c[C::SparseUs as usize]),
+ ms(c[C::GuardUs as usize]),
+ mb(c[C::WholeBytes as usize]),
+ c[C::PaceWaits as usize],
+ ms(c[C::PaceUs as usize]),
+ c[C::GpuWritesLeftOut as usize],
+ mb(c[C::GpuWritesLeftOutBytes as usize]),
+ );
+ // Where the wall clock of a frame goes: the phases of a frame, the
+ // processor time of the whole process, and what each submitting and
+ // recording thread did.
+ static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0));
+ let (user, kernel) = process_times();
+ let (user, kernel) = {
+ let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner());
+ let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1));
+ *last = (user, kernel);
+ (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames)
+ };
+ tracing::info!(
+ "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \
+ until the first submission; {:.1} ms from the last submission to the present call; \
+ lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \
+ all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \
+ putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \
+ submissions run at the present with their waits not met; waits for memory values: \
+ {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \
+ ran alone that the next part could have run with",
+ ms(c[C::UntilRecordUs as usize]),
+ ms(c[C::UntilSubmitUs as usize]),
+ ms(c[C::TailUs as usize]),
+ c[C::ResetNs as usize] / 1e6,
+ ms(c[C::BackScanUs as usize]),
+ c[C::BackDiffer as usize],
+ ms(c[C::BackSyncUs as usize]),
+ c[C::TexUploads as usize],
+ c[C::TexSkipped as usize],
+ c[C::Forced as usize],
+ c[C::WaitChecks as usize],
+ c[C::WaitCheckNs as usize] / 1e6,
+ c[C::HostLists as usize],
+ c[C::HostListNs as usize] / 1e6,
+ c[C::PartsTogether as usize],
+ );
+ // What is copied whole, largest first: memory nobody tells us about.
+ let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let mut whole: Vec<_> = whole.into_iter().flatten().collect();
+ whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
+ tracing::info!(
+ " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow",
+ ms(c[C::WholeUs as usize]),
+ whole.len()
+ );
+ for ((src, len), (n, us)) in whole.into_iter().take(6) {
+ tracing::info!(
+ " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
+ n as f64 / frames,
+ (len as u64 * n) as f64 / 1e6 / frames,
+ us as f64 / 1e3 / frames
+ );
+ }
+ // The waiting for the card: many short waits or a few long ones, how
+ // much of it is for submissions the title gets nothing back from, and
+ // the longest one.
+ let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner()));
+ tracing::info!(
+ " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \
+ ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \
+ nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \
+ {:.1} ms, {}",
+ c[C::CardUnder2 as usize],
+ ms(c[C::CardUnder2Us as usize]),
+ c[C::Card2To8 as usize],
+ ms(c[C::Card2To8Us as usize]),
+ c[C::Card8To32 as usize],
+ ms(c[C::Card8To32Us as usize]),
+ c[C::CardOver32 as usize],
+ ms(c[C::CardOver32Us as usize]),
+ c[C::NothingBack as usize],
+ ms(c[C::NothingBackUs as usize]),
+ longest.0 as f64 / 1e3,
+ longest.1
+ );
+ let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let mut by: Vec<_> = by.into_iter().flatten().collect();
+ by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us));
+ for (what, (n, us)) in by.into_iter().take(12) {
+ tracing::info!(
+ " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}",
+ us as f64 / 1e3 / frames,
+ n as f64 / frames,
+ what.chars().take(700).collect::()
+ );
+ }
+ let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let mut by: Vec<_> = by.into_iter().flatten().collect();
+ by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us));
+ // All of them together, and by their first word: the forty lines below
+ // are the heaviest only (100 of 226 ms waited in run 102), and what the
+ // commands do not account for is the layer's own lists (the card
+ // copies' passes, preludes) and the waits themselves.
+ if !by.is_empty() {
+ let mut kinds: Vec<(String, u64, u64)> = Vec::new();
+ for (what, (n, us, _)) in &by {
+ let word = what.split(' ').next().unwrap_or("").to_owned();
+ match kinds.iter_mut().find(|k| k.0 == word) {
+ Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us),
+ None => kinds.push((word, *n, *us)),
+ }
+ }
+ kinds.sort_by_key(|k| std::cmp::Reverse(k.2));
+ let all: u64 = kinds.iter().map(|k| k.2).sum();
+ let text: Vec =
+ kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect();
+ tracing::info!(
+ " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}",
+ by.len(),
+ all as f64 / 1e3 / frames,
+ text.join(", ")
+ );
+ }
+ for (what, (n, us, longest)) in by.into_iter().take(40) {
+ tracing::info!(
+ " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}",
+ us as f64 / 1e3 / frames,
+ n as f64 / frames,
+ longest as f64 / 1e3
+ );
+ }
+ tracing::info!(
+ " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \
+ for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \
+ such waits each); barrier experiment {}",
+ c[C::WaitsForGroups as usize],
+ c[C::WaitsForBuffers as usize],
+ c[C::IndirectBounded as usize],
+ barrier_test()
+ );
+ // What is compared after submissions, largest first, and how much of
+ // it shaders had written.
+ let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take();
+ let mut compared: Vec<_> = compared.into_iter().flatten().collect();
+ compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n));
+ tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len());
+ for ((src, len), (n, written)) in compared.into_iter().take(8) {
+ tracing::info!(
+ " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back",
+ n as f64 / frames,
+ (len as u64 * n) as f64 / 1e6 / frames,
+ written as f64 / 1e6 / frames
+ );
+ }
+ let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()));
+ submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions));
+ for (id, s) in submitters.into_iter().take(4) {
+ let per = |v: u64| v as f64 / 1e3 / frames;
+ tracing::info!(
+ " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \
+ {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \
+ user + {:.1} ms kernel, {:.1} ms waiting for the submission lock",
+ s.submissions as f64 / frames,
+ per(s.between),
+ per(s.between_user),
+ per(s.between_kernel),
+ s.between_ours as f64 / 1e6 / frames,
+ per(s.inside_user),
+ per(s.inside_kernel),
+ per(s.lock),
+ );
+ }
+ let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner()));
+ recorders.sort_by_key(|r| std::cmp::Reverse(r.1));
+ let busiest: Vec = recorders
+ .iter()
+ .take(6)
+ .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames))
+ .collect();
+ tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", "));
+ log_memory();
let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take();
let mut ranges: Vec<_> = ranges.into_iter().flatten().collect();
ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes));
diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs
index 9ae83bdd24..8485014901 100644
--- a/crates/victory-gpu/src/descriptor.rs
+++ b/crates/victory-gpu/src/descriptor.rs
@@ -34,7 +34,7 @@ pub(crate) struct HeapDesc {
nodes: u32,
}
-/// Newer titles (Grand Theft Auto VI) pass the description followed by
+/// Newer titles (the title) pass the description followed by
/// memory of their own for the descriptors: an address and its size in
/// bytes, or a null address to have the heap allocate (inferred from the
/// title's call sites; older titles pass the plain description).
@@ -73,7 +73,7 @@ impl Heap {
}
/// The host heap, made on first use from what the title wrote so far.
- /// Made late because a host view heap the size of Grand Theft Auto VI's
+ /// Made late because a host view heap the size of the title's
/// costs over 100 MB of commit, which its boot needs for its page pool.
#[cfg(windows)]
pub(crate) fn host(&self) -> Option<&host::HostHeap> {
@@ -85,15 +85,25 @@ impl Heap {
return None;
}
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
- let h = self
- .host
- .get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count))
- .as_ref()?;
+ // A recorder can take the fast path as soon as the OnceLock is
+ // initialized. Publish only after replaying the queued writes.
+ self.host
+ .get_or_init(|| {
+ let step = u64::from(increment(self.desc.kind)?);
+ let h = host::HostHeap::new(self.samplers(), self.desc.count)?;
+ for i in pending.drain(..) {
+ h.mirror(i, self.start + u64::from(i) * step, false);
+ }
+ Some(h)
+ })
+ .as_ref()
+ }
+
+ /// The handle of descriptor `index` of this heap.
+ #[cfg(windows)]
+ pub(crate) fn handle(&self, index: u32) -> Option {
let step = u64::from(increment(self.desc.kind)?);
- for i in pending.drain(..) {
- h.mirror(i, self.start + u64::from(i) * step, false);
- }
- Some(h)
+ (index < self.desc.count).then(|| self.start + u64::from(index) * step)
}
/// The descriptor index of `handle` in this heap, if it lies in it.
@@ -228,7 +238,8 @@ impl RtvRecord {
0,
]
};
- words[0] = crate::resource::pc_format(words[0]);
+ // A target or depth view: of a target, in its stand-in format.
+ words[0] = crate::resource::target_format(crate::resource::pc_format(words[0]));
// SAFETY: both host view descriptions are 24 bytes in this layout.
Some(unsafe { (&raw const words).cast::().read_unaligned() })
}
@@ -315,9 +326,21 @@ impl View {
/// generation, so descriptors (and host slots made from them) naming the
/// old one go stale instead of naming whatever is made at the same address
/// next.
-/// shortcut: views without a resource object (constant buffers, memory
-/// views, samplers) are kept for the run; they are bounded by the title's
-/// memory and sampler states.
+///
+/// Views without a resource object have nothing that releases them, and a
+/// title copies descriptors as bytes, so nothing says when the last
+/// descriptor naming an entry is gone: such entries were kept for the run.
+/// The title writes some 14,000 constant buffer views a frame,
+/// each at the address its constants have that frame: 2,450,139 entries
+/// after four minutes of play, 1,047 MB with the index, and 11,000 more
+/// every second (run 65). So the two kinds that carry an address are not
+/// entries any more: their records name them whole ([`constant_words`],
+/// [`placed_words`]), and the table holds only what is bounded: views of
+/// resource objects (freed with the resource), samplers (as many as there
+/// are sampler states), and the shapes of placed views (their descriptions
+/// without the address: as many as the title has kinds of textures and
+/// buffers, however often it moves them).
+/// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before.
struct Views {
/// Each entry's view and generation.
list: Vec<(View, u32)>,
@@ -325,6 +348,9 @@ struct Views {
/// Entries naming each resource.
by_resource: std::collections::BTreeMap>,
free: Vec,
+ /// The shapes of views of placed memory, and where each is.
+ shapes: Vec,
+ shape_index: std::collections::BTreeMap,
}
static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views {
@@ -332,9 +358,220 @@ static VIEWS: std::sync::Mutex = std::sync::Mutex::new(Views {
index: std::collections::BTreeMap::new(),
by_resource: std::collections::BTreeMap::new(),
free: Vec::new(),
+ shapes: Vec::new(),
+ shape_index: std::collections::BTreeMap::new(),
});
const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
+/// A record is the tag and two words, `i` and `generation` (the host keeps
+/// them as one 64-bit key per slot). The top two bits of `generation` say
+/// what the other 62 bits are: 0, entry `i` of the table at that
+/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a
+/// view of placed memory: its address and the number of its shape.
+const KIND_SHIFT: u32 = 30;
+/// Table generations stay below the kind bits (and above 0).
+const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1;
+const CONSTANT: u32 = 1;
+const PLACED: u32 = 2;
+/// Bits of a constant buffer view's address in its record: any address a
+/// program can have. The 15 bits above them are its size.
+const CONSTANT_ADDRESS_BITS: u32 = 47;
+/// Bits of a placed view's address in its record: placed memory is title
+/// memory, which lies below 1 TiB. The 22 bits above them number its shape.
+const PLACED_ADDRESS_BITS: u32 = 40;
+const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS);
+
+/// A view of placed memory without its address: whether it is unordered
+/// access, the resource description, and the view's words but the two that
+/// hold the address (10 and 11).
+type Shape = (bool, [u32; 14], [u32; 14]);
+
+/// Whether constant buffer views and views of placed memory are named whole
+/// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0`
+/// makes every view a table entry, as before.
+fn inline() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0"))
+}
+
+/// Views named whole in their records since the start: constant buffer
+/// views, views of placed memory (for the memory line).
+static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// The two record words of the 62 bits `payload` of kind `kind`.
+fn kind_words(kind: u32, payload: u64) -> [u32; 2] {
+ [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32]
+}
+
+/// The 62 bits two record words carry beside their kind.
+fn payload(i: u32, generation: u32) -> u64 {
+ u64::from(generation & GENERATIONS) << 32 | u64::from(i)
+}
+
+/// The record words that name the constant buffer view of `size` bytes at
+/// `address` whole; `None` if they cannot: an address past 47 bits, or a
+/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the
+/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a
+/// view is a table entry.
+fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> {
+ if address >> CONSTANT_ADDRESS_BITS != 0 {
+ return None;
+ }
+ let code = if size < 1 << 14 {
+ u64::from(size)
+ } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 {
+ 1 << 14 | u64::from(size >> 8)
+ } else {
+ return None;
+ };
+ Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address))
+}
+
+/// The constant buffer view [`constant_words`] named.
+fn constant_of(i: u32, generation: u32) -> View {
+ let payload = payload(i, generation);
+ let code = (payload >> CONSTANT_ADDRESS_BITS) as u32;
+ let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 };
+ View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size)
+}
+
+/// A placed view's shape and its address.
+fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) {
+ let mut rest = [0u32; 14];
+ rest[..10].copy_from_slice(&desc[..10]);
+ rest[10..].copy_from_slice(&desc[12..]);
+ (
+ (unordered, *resource, rest),
+ u64::from(desc[10]) | u64::from(desc[11]) << 32,
+ )
+}
+
+/// The record words that name the view of placed memory at `address` with
+/// shape number `shape`.
+fn placed_words(shape: u32, address: u64) -> [u32; 2] {
+ kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address)
+}
+
+impl Views {
+ /// The number of `shape`, a new one if it is not there yet; `None` when
+ /// the shapes are full (the view is then a table entry).
+ fn shape(&mut self, shape: Shape) -> Option {
+ if let Some(&at) = self.shape_index.get(&shape) {
+ return Some(at);
+ }
+ if self.shapes.len() >= SHAPES {
+ return None;
+ }
+ let at = self.shapes.len() as u32;
+ self.shapes.push(shape);
+ self.shape_index.insert(shape, at);
+ Some(at)
+ }
+
+ /// The view of placed memory [`placed_words`] named.
+ fn placed_of(&self, i: u32, generation: u32) -> Option {
+ let payload = payload(i, generation);
+ let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1);
+ let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?;
+ let mut desc = [0u32; 16];
+ desc[..10].copy_from_slice(&rest[..10]);
+ (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
+ desc[12..].copy_from_slice(&rest[10..]);
+ Some(View::Placed(unordered, resource, desc))
+ }
+
+ /// The record words of `view` as a table entry: its entry (a new or a
+ /// freed one if the view is not there yet) and that entry's generation.
+ fn entry(&mut self, view: View) -> [u32; 2] {
+ let i = match self.index.get(&view) {
+ Some(&i) => i,
+ None => {
+ let i = match self.free.pop() {
+ Some(i) => {
+ self.list[i as usize].0 = view.clone();
+ i
+ }
+ None => {
+ self.list.push((view.clone(), 1));
+ self.list.len() as u32 - 1
+ }
+ };
+ for r in view.resources().into_iter().filter(|&r| r != 0) {
+ self.by_resource.entry(r).or_default().push(i);
+ }
+ self.index.insert(view, i);
+ i
+ }
+ };
+ [i, self.list[i as usize].1]
+ }
+}
+
+/// The two words that name `view` in a record: the view itself where its
+/// kind allows ([`Views`]), else its table entry.
+fn words_for(view: View) -> [u32; 2] {
+ use std::sync::atomic::Ordering::Relaxed;
+ if inline() {
+ match &view {
+ View::Constant(address, size) => {
+ if let Some(words) = constant_words(*address, *size) {
+ NAMED_WHOLE[0].fetch_add(1, Relaxed);
+ return words;
+ }
+ }
+ View::Placed(unordered, resource, desc) => {
+ let (shape, address) = shape_of(*unordered, resource, desc);
+ if address >> PLACED_ADDRESS_BITS == 0 {
+ let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(shape) = views.shape(shape) {
+ NAMED_WHOLE[1].fetch_add(1, Relaxed);
+ return placed_words(shape, address);
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
+}
+
+/// For the memory line: the distinct views kept ([`Views`]), those of them
+/// free for reuse, and the bytes the table and its index hold for them (an
+/// estimate: an entry of the table, and one of the index with its share of
+/// a tree node; the shapes likewise); then the entries that are constant
+/// buffer views and views of placed memory (those that did not fit a
+/// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of
+/// placed views kept, and the views named whole in their records since the
+/// start: constant buffer views, views of placed memory.
+#[cfg(all(windows, feature = "diagnostics"))]
+pub(crate) fn views_kept() -> [u64; 8] {
+ use std::sync::atomic::Ordering::Relaxed;
+ let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
+ let each = size_of::<(View, u32)>() as u64;
+ let shape = size_of::() as u64;
+ let (mut constants, mut placed) = (0, 0);
+ for (view, _) in &views.list {
+ match view {
+ View::Constant(..) => constants += 1,
+ View::Placed(..) => placed += 1,
+ _ => {}
+ }
+ }
+ [
+ views.list.len() as u64,
+ views.free.len() as u64,
+ views.list.capacity() as u64 * each
+ + views.index.len() as u64 * each * 3 / 2
+ + views.shapes.capacity() as u64 * shape
+ + views.shape_index.len() as u64 * shape * 3 / 2,
+ constants,
+ placed,
+ views.shapes.len() as u64,
+ NAMED_WHOLE[0].load(Relaxed),
+ NAMED_WHOLE[1].load(Relaxed),
+ ]
+}
+
impl View {
/// The resource objects the view names.
fn resources(&self) -> [usize; 2] {
@@ -344,43 +581,122 @@ impl View {
_ => [0, 0],
}
}
+
+ /// The texture object the view is of, if that texture has no host copy
+ /// yet (`crate::resource::host_waits`): a slot written with such a
+ /// view is left null until the texture is first used.
+ #[cfg(windows)]
+ fn waiting_texture(&self) -> Option {
+ match *self {
+ View::Shader(r, _) | View::Unordered(r, _, _)
+ if crate::resource::host_waits(r as This) =>
+ {
+ Some(r)
+ }
+ _ => None,
+ }
+ }
}
-fn record(handle: u64, view: View) {
- if handle == 0 {
- return;
+/// Title slots (their handles) written with a view of a texture object
+/// that had no host copy then, by texture. A title texture gets its host
+/// copy on first use (`resource.rs` `Hosted`), and the title
+/// writes each texture's views into its view heap when it creates the
+/// texture: making those host slots would make every host copy at once.
+/// They are made when the texture is: translated shaders index the heap
+/// directly, so a slot is not always made again by the draw that reads it.
+#[cfg(windows)]
+static WAITING: std::sync::Mutex>> =
+ std::sync::Mutex::new(std::collections::BTreeMap::new());
+
+/// Textures given their host copy since [`make_waiting`] last ran.
+#[cfg(windows)]
+static MADE_LATE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new());
+
+/// Title texture `resource` was given its host copy (called under that
+/// texture's own lock: nothing else is locked here).
+#[cfg(windows)]
+pub(crate) fn texture_made(resource: usize) {
+ MADE_LATE
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .push(resource);
+}
+
+/// The slot at `handle` was written with a view of texture `resource`,
+/// which has no host copy: it waits for one.
+#[cfg(windows)]
+fn wait_for(resource: usize, handle: u64) {
+ /// A texture with more slots waiting than this is in use for all we
+ /// know (its views are being copied about): its host copy is made.
+ const MOST: usize = 64;
+ let many = {
+ let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
+ let slots = waiting.entry(resource).or_default();
+ if !slots.contains(&handle) {
+ slots.push(handle);
+ }
+ slots.len() > MOST
+ };
+ if many {
+ // Makes it, and notes it made.
+ let _ = crate::resource::host_copy(resource as This);
+ } else if !crate::resource::host_waits(resource as This) {
+ // Made by another thread since the slot was looked at: that making
+ // may have been taken by `make_waiting` before this slot was noted.
+ texture_made(resource);
}
- let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
- let i = match views.index.get(&view) {
- Some(&i) => i,
- None => {
- let i = match views.free.pop() {
- Some(i) => {
- views.list[i as usize].0 = view.clone();
- i
- }
- None => {
- views.list.push((view.clone(), 1));
- views.list.len() as u32 - 1
- }
+}
+
+/// Makes the host slots that waited for a texture's host copy, for the
+/// textures made since the last call. Called before a submission runs, by
+/// the thread that submits: a slot is read when a list runs.
+#[cfg(windows)]
+pub(crate) fn make_waiting() {
+ let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner()));
+ for resource in made {
+ let handles = WAITING
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .remove(&resource);
+ for handle in handles.into_iter().flatten() {
+ // Only if the slot still holds a view of that texture: the
+ // title may have written it since (and a view of another
+ // texture without a host copy must go on waiting).
+ // (Looked up first: the handle is read only while its heap is
+ // there.)
+ let Some((heap, index)) = shader_slot(handle) else {
+ continue;
+ };
+ let same = match view(handle) {
+ Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource,
+ _ => false,
};
- for r in view.resources().into_iter().filter(|&r| r != 0) {
- views.by_resource.entry(r).or_default().push(i);
+ if same && let Some(Some(host)) = heap.host.get() {
+ host.mirror(index, handle, true);
}
- views.index.insert(view, i);
- i
}
- };
- let generation = views.list[i as usize].1;
+ }
+}
+
+fn record(handle: u64, view: View) {
+ if handle == 0 {
+ return;
+ }
+ let [i, generation] = words_for(view);
// SAFETY: the handle is a descriptor slot, at least 16 bytes.
unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
- drop(views);
#[cfg(windows)]
mirror(handle);
}
/// The title released `resource`: the views naming it go stale.
pub(crate) fn forget(resource: usize) {
+ #[cfg(windows)]
+ WAITING
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .remove(&resource);
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
let Some(entries) = views.by_resource.remove(&resource) else {
return;
@@ -393,19 +709,27 @@ pub(crate) fn forget(resource: usize) {
continue;
}
views.index.remove(&view);
- views.list[i as usize].1 = generation.wrapping_add(1).max(1);
+ // (Below the bits that say a record is no table entry.)
+ views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1);
// The view's other resource (a counter) keeps a stale entry, which
// `forget` of that resource skips.
views.free.push(i);
}
}
-/// The view of entry `i` if `generation` is still its own.
-#[cfg(windows)]
+/// The view the record words `i` and `generation` name: the one they hold
+/// whole, or the view of entry `i` if `generation` is still its own.
fn view_at(i: u32, generation: u32) -> Option {
- let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
- let (view, current) = views.list.get(i as usize)?;
- (*current == generation).then(|| view.clone())
+ match generation >> KIND_SHIFT {
+ 0 => {
+ let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
+ let (view, current) = views.list.get(i as usize)?;
+ (*current == generation).then(|| view.clone())
+ }
+ CONSTANT => Some(constant_of(i, generation)),
+ PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation),
+ _ => None,
+ }
}
/// The view recorded at `handle`, if one is (and its resource is alive).
@@ -415,9 +739,10 @@ pub(crate) fn view(handle: u64) -> Option {
}
// SAFETY: the handle is a descriptor slot the title passes back.
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
- let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
- let (view, current) = views.list.get(i as usize)?;
- (tag == VIEW_TAG && *current == generation).then(|| view.clone())
+ if tag != VIEW_TAG {
+ return None;
+ }
+ view_at(i, generation)
}
/// A description of `N` words, if the title passes one.
@@ -738,6 +1063,81 @@ mod tests {
heap[0] = 0;
}
+ /// Constant buffer views are named whole in their records: any address
+ /// a program can have, any size below 16 KiB, multiples of 256 bytes
+ /// up to 4 MiB; what does not fit says so.
+ #[test]
+ fn constant_views_fit_their_records() {
+ let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1;
+ for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] {
+ for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] {
+ let [i, generation] = constant_words(address, size).expect("fits");
+ assert_eq!(generation >> KIND_SHIFT, CONSTANT);
+ assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}");
+ }
+ }
+ assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits");
+ assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256");
+ assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB");
+ // Different views never share their words.
+ assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512));
+ assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256));
+ assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64));
+ }
+
+ /// The leak of run 65: a title that writes constant buffer views and
+ /// views of placed memory at ever new addresses adds nothing to the
+ /// table; one shape stands for all the placed views alike.
+ #[test]
+ fn views_at_new_addresses_add_no_entries() {
+ if !inline() {
+ return;
+ }
+ let null = std::ptr::null();
+ let slots = [0u64; 4];
+ let at = slots.as_ptr() as u64;
+ // A resource description and a view no other test uses.
+ let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32);
+ let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32);
+ let mine = |v: &View| match v {
+ View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address),
+ View::Placed(_, r, _) => *r == resource,
+ _ => false,
+ };
+ let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
+ let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
+ for n in 0..20_000u64 {
+ let address = 0x6_0000_0000 + n * 0x100;
+ create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
+ assert_eq!(view(at), Some(View::Constant(address, 512)));
+ let placed = 0xd_4940_0000 + n * 0x1_0000;
+ (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32);
+ create_placed_srv(null, &resource, &desc, at);
+ assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
+ }
+ assert_eq!(entries(), 0, "no table entries");
+ assert_eq!(shapes(), 1, "one shape for 20,000 placed views");
+ // The same shape, unordered: another shape.
+ create_placed_uav(null, &resource, &desc, at);
+ assert_eq!(view(at), Some(View::Placed(true, resource, desc)));
+ assert_eq!(shapes(), 2);
+ // Placed memory past 1 TiB (not title memory) is a table entry.
+ (desc[10], desc[11]) = (0, 0x100);
+ create_placed_srv(null, &resource, &desc, at);
+ assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
+ assert_eq!(entries(), 1);
+ // A record's words are the same for the same view (the host knows
+ // a slot's view by them), and differ with the address.
+ // SAFETY: both handles are slots of 32 bytes above.
+ let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) };
+ let other = [0u64; 4];
+ create_cbv(null, &[0x40, 6, 512, 0], at);
+ create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64);
+ assert_eq!(words(at), words(other.as_ptr() as u64));
+ create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64);
+ assert_ne!(words(at), words(other.as_ptr() as u64));
+ }
+
/// A released resource's views go stale; the same view of a new
/// resource at the same address is a new record.
#[test]
@@ -757,7 +1157,7 @@ mod tests {
assert_ne!(old, new, "a new generation");
}
- /// Grand Theft Auto VI places its shader-visible heap in its own memory
+ /// The title places its shader-visible heap in its own memory
/// and checks that the heap starts there.
#[test]
fn placed_heaps_start_at_the_title_memory() {
diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs
index 3a79aaec4a..b2c27c5342 100644
--- a/crates/victory-gpu/src/descriptor/host.rs
+++ b/crates/victory-gpu/src/descriptor/host.rs
@@ -17,8 +17,12 @@ pub(crate) struct HostHeap {
pub(crate) heap: ID3D12DescriptorHeap,
cpu: usize,
step: u32,
- /// Slots mirroring the title's; view heaps have [`DYNAMIC`] more.
+ /// Slots mirroring the title's; view heaps have `dynamic` more.
count: u32,
+ /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in
+ /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap;
+ /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.)
+ dynamic: u32,
sampler: bool,
/// The record (view index and generation) each slot was last made from.
made: Mutex>,
@@ -30,6 +34,475 @@ pub(crate) struct HostHeap {
/// Where the search for free dynamic slots starts, and which are taken
/// (by lists not yet reset).
next: Mutex<(u32, Vec)>,
+ /// How many dynamic slots are free (changed under `next`'s lock): with
+ /// fewer than a table needs, the search is not made. Once the world
+ /// had taken them all, every later table of the frame searched every
+ /// slot before it was refused.
+ free: std::sync::atomic::AtomicU32,
+ /// The shortest table that found no run of free slots since slots were
+ /// last given back (changed under `next`'s lock; `u32::MAX`: none).
+ /// Until something is given back the free runs only shrink, so a table
+ /// of that length or longer is refused without the search. Enough
+ /// slots were free, but in pieces, and every such table walked the
+ /// whole ring before it was refused: 0.33 ms each with 131,072 slots,
+ /// 1.0 s of the recording threads in a frame that refused 3,143 (run
+ /// 45), under the lock all of them need. (A free run that lies across
+ /// the place the search starts from is seen by neither.)
+ too_long: std::sync::atomic::AtomicU32,
+ /// View heaps: the bytes per element of the buffer view at each title
+ /// slot, for shaders that pick a buffer by an index they compute
+ /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of
+ /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping.
+ strides: Option<(ID3D12Resource, u64, usize)>,
+ /// Title slots holding buffer views. Such a view gets its host slot
+ /// (and its memory a host copy) only when something reads it: a draw
+ /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
+ /// buffers from the whole heap.
+ buffers: Mutex>,
+ /// Of those and of the slots that left the set: the ones written since
+ /// [`HostHeap::buffer_changes`] last took them.
+ changed: Mutex>,
+ /// Title slots holding a view of a texture the title may fill itself (a
+ /// placed texture, a texture object), with the frame from which they
+ /// are due: such a texture is uploaded when a draw reads it through a
+ /// table; one a shader picks by a computed index is brought up to date
+ /// from here ([`HostHeap::texture_slots_due`]).
+ textures: Mutex,
+ /// Per title slot, the frame (plus one; 0: never) in which a draw last
+ /// read it through a table, or made a table it lies in (with
+ /// [`TABLED_READ`] set if the draw read it). The draw that
+ /// reads such a slot brings its texture up to date itself and the slot
+ /// then leaves `textures`; a write of a slot that was a table's within
+ /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`]
+ /// frames later, by when its draw has read it. A title that builds a
+ /// table per draw writes thousands of texture views a frame into slots
+ /// only tables read (the title: some 2,500 a frame in its
+ /// opening cutscene, a few hundred textures over and over), and every
+ /// one of them stood in the queue of textures picked by index, ahead
+ /// of or behind the ones shaders do pick by index.
+ tabled: Vec,
+ /// The title memory each placed texture view of this heap describes,
+ /// by slot and by address ([`Spans`]): which slots a newer view of
+ /// other memory there makes stale, and which to look at again when the
+ /// runtime maps, unmaps or writes memory ([`remapped`]).
+ placed: Mutex,
+}
+
+/// Title memory by the placed texture views that describe it: per span of
+/// memory (its start, its end) the title slots holding a view of a
+/// texture that takes exactly that span. Spans never overlap: a console
+/// title need not clear a descriptor when it streams a texture out, so a
+/// view written over memory that older views describe otherwise (another
+/// start or another length: another texture) is all that says the older
+/// ones are stale. Views of one span with different descriptions (the
+/// formats of one family, say) are one texture's.
+/// No host heap is needed, so it is tested without one.
+#[derive(Default)]
+pub(crate) struct Spans {
+ by_start: std::collections::BTreeMap)>,
+ by_slot: std::collections::HashMap,
+ /// The bytes a placed texture takes, by resource description: worked
+ /// out once for each (a title writes the views of a few thousand
+ /// descriptions, thousands of times a frame).
+ sizes: std::collections::HashMap<[u32; 14], Option>,
+}
+
+impl Spans {
+ /// The bytes of title memory a placed texture with the resource
+ /// description `desc` takes (`crate::resource::placed_bytes`).
+ fn bytes(&mut self, desc: &[u32; 14]) -> Option {
+ if let Some(&known) = self.sizes.get(desc) {
+ return known;
+ }
+ let bytes = crate::resource::placed_bytes(desc);
+ self.sizes.insert(*desc, bytes);
+ bytes
+ }
+
+ /// The starts of the spans that overlap `[start, end)`.
+ fn overlapping(&self, start: u64, end: u64) -> Vec {
+ let before = self
+ .by_start
+ .range(..start)
+ .next_back()
+ .filter(|(_, span)| span.0 > start)
+ .map(|(at, _)| *at);
+ before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect()
+ }
+
+ /// Slot `index` holds a view of a texture in `[start, end)`. `newer`:
+ /// the title wrote it now, so the slots whose views describe that
+ /// memory otherwise are stale: they are returned, and forgotten.
+ /// Otherwise (a draw made the slot from what it held) a view that
+ /// overlaps other spans is left out.
+ fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec {
+ let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end);
+ if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) {
+ return Vec::new();
+ }
+ self.forget(index);
+ if end <= start {
+ return Vec::new();
+ }
+ let mut stale = Vec::new();
+ for at in self.overlapping(start, end) {
+ if at == start && same(self.by_start.get(&at)) {
+ continue;
+ }
+ if !newer {
+ return stale;
+ }
+ if let Some((_, slots)) = self.by_start.remove(&at) {
+ for slot in slots {
+ self.by_slot.remove(&slot);
+ stale.push(slot);
+ }
+ }
+ }
+ self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index);
+ self.by_slot.insert(index, start);
+ stale
+ }
+
+ /// Slot `index` holds no placed texture view any more.
+ fn forget(&mut self, index: u32) {
+ let Some(start) = self.by_slot.remove(&index) else {
+ return;
+ };
+ if let Some(span) = self.by_start.get_mut(&start) {
+ span.1.remove(&index);
+ if span.1.is_empty() {
+ self.by_start.remove(&start);
+ }
+ }
+ }
+
+ /// The slots whose texture's memory overlaps `[start, end)`.
+ fn slots_in(&self, start: u64, end: u64) -> Vec {
+ self.overlapping(start, end)
+ .iter()
+ .filter_map(|at| self.by_start.get(at))
+ .flat_map(|span| span.1.iter().copied())
+ .collect()
+ }
+}
+
+/// Title memory the runtime mapped, unmapped or is about to write since a
+/// texture pass last took the ranges ([`remapped`]).
+static REMAPPED: Mutex> = Mutex::new(Vec::new());
+
+/// The lowest start and the highest end of any span of [`Spans`] so far
+/// (the start is `u64::MAX` until there is one): what the runtime does to
+/// memory outside is none of the texture pass's business.
+static SPANNED: [std::sync::atomic::AtomicU64; 2] = [
+ std::sync::atomic::AtomicU64::new(u64::MAX),
+ std::sync::atomic::AtomicU64::new(0),
+];
+
+/// Since the start: slots whose view a newer view of other memory there
+/// made stale; ranges of memory noted as mapped, unmapped or written;
+/// ranges dropped because no pass took them; slots made due by such
+/// ranges; and made slots whose memory was found unmapped (made null).
+pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] =
+ [const { std::sync::atomic::AtomicU64::new(0) }; 5];
+
+/// Whether a view written over memory that older views describe otherwise
+/// makes those stale; `VICTORY_STALE_TEXTURES=0` leaves them as they are.
+fn stale_out() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_STALE_TEXTURES").is_none_or(|v| v != "0"))
+}
+
+/// The runtime mapped or unmapped title memory `[at, at + len)`, or is
+/// about to write it through the kernel (`crate::watch`): the placed
+/// textures there may have arrived, gone, or changed with no descriptor
+/// written. The range is kept for the next texture pass
+/// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own
+/// locks held: this locks one mutex of its own and calls nothing.
+pub(crate) fn remapped(at: usize, len: usize) {
+ use std::sync::atomic::Ordering::Relaxed;
+ /// Ranges kept until a pass takes them.
+ const MOST: usize = 1 << 15;
+ let (start, end) = (at as u64, at.saturating_add(len) as u64);
+ if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
+ return;
+ }
+ let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner());
+ STALE[1].fetch_add(1, Relaxed);
+ // Pages are mapped one after the other.
+ if let Some(last) = ranges.last_mut()
+ && last.1 == start
+ {
+ last.1 = end;
+ return;
+ }
+ if ranges.len() >= MOST {
+ // No pass runs (no shader that picks textures by index is bound):
+ // the slots there are looked at when they are due, as before.
+ STALE[2].fetch_add(ranges.len() as u64, Relaxed);
+ ranges.clear();
+ }
+ ranges.push((start, end));
+}
+
+/// Frames for which a slot a draw read through a table counts as a table's
+/// slot ([`HostHeap::tabled`]).
+const TABLED_FRAMES: u64 = 240;
+
+/// Frames a write of a table's slot waits in the queue for the draw that
+/// reads it, before the slot is taken for one shaders pick by index.
+/// Frames as `crate::frame::current` counts them: in its opening cutscene
+/// The title begins two or three of them per frame it presents
+/// (435 begun in the 353 s of run 52's, for some 140 presented).
+const TABLED_GRACE: u64 = 8;
+
+/// In [`HostHeap::tabled`]: a draw read the slot in that frame.
+const TABLED_READ: u32 = 1 << 31;
+
+/// Since the start: writes of texture views into slots that count as a
+/// table's (due later), and slots that left the queue because a draw read
+/// them through a table.
+pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] =
+ [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// Whether slots draws read through tables leave the queue of textures
+/// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as
+/// before.
+fn tabled_out() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1"))
+}
+
+/// What the queue of textures picked by index knows of a title slot.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct Waiting {
+ /// The frame from which the slot is due.
+ due: u64,
+ /// The frame it was written in.
+ written: u64,
+ /// Which write of the queue put it here: the pass hands it back with
+ /// what it did, so a slot written again meanwhile stays as written.
+ write: u64,
+ /// Looks in a row that found nothing to upload (its memory not mapped,
+ /// or no more of it than at the last upload).
+ looks: u8,
+ /// Bytes of its memory that were mapped when it was last uploaded
+ /// without all of it there; 0: not uploaded yet.
+ mapped: u64,
+ /// For a slot uploaded whole and looked at again
+ /// ([`TextureQueue::recheck`]): where its memory is (address, bytes),
+ /// the fingerprint it had at the upload, how many looks found it
+ /// unchanged, and the frame of the upload. A fingerprint of 0: none.
+ checked: (u64, u64, u64, u8, u64),
+}
+
+/// The queue of title slots whose texture view waits to be brought up to
+/// date for shaders that pick textures by index: which are due, and in
+/// which order (no host heap needed, so it is tested without one).
+#[derive(Default)]
+pub(crate) struct TextureQueue {
+ slots: std::collections::BTreeMap,
+ writes: u64,
+}
+
+impl TextureQueue {
+ /// A texture view was written into slot `index` in `frame`, due from
+ /// frame `due`. `seen`: it was not written, a draw or the pass made
+ /// the host slot from a view the queue may hold already, which then
+ /// stays as it is.
+ fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) {
+ if seen && self.slots.contains_key(&index) {
+ return;
+ }
+ self.writes += 1;
+ let write = self.writes;
+ self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
+ }
+
+ fn remove(&mut self, index: u32) {
+ self.slots.remove(&index);
+ }
+
+ /// Up to `max` slots due at `frame`, each with its write number, in
+ /// the order to serve them:
+ /// - first the ones looked at before (their memory was not mapped, or
+ /// only part of it): the look is a query, and memory that has
+ /// arrived since is what the title streamed in last;
+ /// - then the others, the newest write first and the oldest next, in
+ /// turns: slot order served the low slots of a backlog of
+ /// 25,000-40,000 while the textures of the shot on screen waited
+ /// (run 52: 98% of the drawn pixels had no colour texture in the
+ /// first 3D frames).
+ fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> {
+ let mut again: Vec<(u64, u32, u64)> = Vec::new();
+ let mut fresh: Vec<(u64, u32, u64)> = Vec::new();
+ for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) {
+ let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh };
+ class.push((w.written, index, w.write));
+ }
+ // By the number of the write, counted over the run.
+ let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2);
+ again.sort_unstable_by(newest_first);
+ fresh.sort_unstable_by(newest_first);
+ let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect();
+ let (mut new, mut old) = (0, fresh.len());
+ while new < old && order.len() < max {
+ order.push((fresh[new].1, fresh[new].2));
+ new += 1;
+ if new < old && order.len() < max {
+ old -= 1;
+ order.push((fresh[old].1, fresh[old].2));
+ }
+ }
+ order.truncate(max);
+ order
+ }
+
+ /// The entry of `index` if it is still the write the pass was handed.
+ fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> {
+ self.slots.get_mut(&index).filter(|w| w.write == write)
+ }
+
+ /// Slot `index` is up to date: out of the queue until written again.
+ fn done(&mut self, index: u32, write: u64) {
+ if self.same(index, write).is_some() {
+ self.slots.remove(&index);
+ }
+ }
+
+ /// Nothing to upload at slot `index` now: looked at again after 1, 2,
+ /// 4, ... frames, at most `most`.
+ fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) {
+ if let Some(w) = self.same(index, write) {
+ w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1));
+ w.looks = w.looks.saturating_add(1);
+ }
+ }
+
+ /// Slot `index` was uploaded with `mapped` bytes of its memory there,
+ /// not all of it: looked at again from frame `due`.
+ fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) {
+ if let Some(w) = self.same(index, write) {
+ (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1));
+ }
+ }
+
+ /// Slot `index` was uploaded whole from memory `at` (address, bytes)
+ /// with fingerprint `print`: looked at again from frame `due`, for a
+ /// title that fills a texture's memory after it wrote the view (the
+ /// `looks`-th such look; `uploaded` is the upload's frame).
+ #[allow(clippy::too_many_arguments)]
+ fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) {
+ if let Some(w) = self.same(index, write) {
+ (w.due, w.looks, w.mapped) = (due, 1, 0);
+ w.checked = (at.0, at.1, print, looks, uploaded);
+ }
+ }
+
+ /// What [`TextureQueue::recheck`] noted of slot `index`, if it is
+ /// waiting for such a look.
+ fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
+ self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0)
+ }
+
+ /// The memory slot `index`'s texture lies in was mapped, unmapped or
+ /// written in `frame`: the slot is looked at from frame `due` as one
+ /// written now, whatever was known of it (a pass at work on it does
+ /// not take it out).
+ fn changed(&mut self, index: u32, frame: u64, due: u64) {
+ self.writes += 1;
+ let write = self.writes;
+ let due = self.slots.get(&index).map_or(due, |w| w.due.min(due));
+ self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
+ }
+
+ /// Bytes of slot `index`'s memory that were mapped at its last upload
+ /// (0: not uploaded, or all of it was).
+ fn mapped(&self, index: u32) -> u64 {
+ self.slots.get(&index).map_or(0, |w| w.mapped)
+ }
+
+ /// For the frame line: slots in the queue; of them due at `frame`;
+ /// waiting for their memory (looked at, never uploaded); uploaded in
+ /// part; and the frames the oldest due one has waited since its write.
+ fn census(&self, frame: u64) -> [u64; 5] {
+ let mut c = [self.slots.len() as u64, 0, 0, 0, 0];
+ for w in self.slots.values() {
+ if w.mapped > 0 {
+ c[3] += 1;
+ } else if w.looks > 0 {
+ c[2] += 1;
+ }
+ if w.due <= frame {
+ c[1] += 1;
+ c[4] = c[4].max(frame.saturating_sub(w.written));
+ }
+ }
+ c
+ }
+}
+
+/// Whether `view` is of a texture the title may fill itself: a texture it
+/// placed in memory, or a texture object.
+pub(crate) fn is_texture_view(view: &View) -> bool {
+ match view {
+ View::Placed(false, resource, _) => resource[0] != 1,
+ View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(),
+ _ => false,
+ }
+}
+
+/// Buffer views left null because the host would refuse them
+/// ([`buffer_view_ok`]), since the start.
+pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Whether the host device is gone, and why (the first time it is asked
+/// after that): for passes that make many views, to name the one that did
+/// it.
+pub(crate) fn device_removed() -> Option {
+ let host = host()?;
+ // SAFETY: a plain query.
+ let reason = unsafe { host.device.GetDeviceRemovedReason() };
+ reason.err().map(|e| e.to_string())
+}
+
+/// Writes of title view-heap slots with a placed texture view and with a
+/// view of a texture object, since the start (diagnostic counts).
+pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Bytes per element of a buffer view, as the console's descriptor holds
+/// them for indexed reads (structured: the stride; raw: 1, the index is the
+/// byte; typed: the format's); `None` if `view` is not a buffer view.
+fn view_stride(view: &View) -> Option {
+ const BUFFER: u32 = 1;
+ let (words, unordered): (&[u32; 10], bool) = match view {
+ View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false),
+ View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true),
+ View::Placed(unordered, resource, d) if resource[0] == BUFFER => {
+ (d[..10].try_into().ok()?, *unordered)
+ }
+ _ => return None,
+ };
+ // SAFETY: buffer views' union members.
+ let (stride, raw, format) = unsafe {
+ if unordered {
+ let d = uav_desc(words);
+ let b = d.Anonymous.Buffer;
+ (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format)
+ } else {
+ let d = srv_desc(words);
+ let b = d.Anonymous.Buffer;
+ (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format)
+ }
+ };
+ Some(if stride > 0 {
+ stride
+ } else if raw {
+ 1
+ } else {
+ crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32)
+ })
}
/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
@@ -59,10 +532,67 @@ pub(crate) fn near_heaps(va: u64) -> String {
/// tiers 1 and 2; tier 3 hardware may take more.
const PORTABLE_VIEWS: u32 = 1_000_000;
+/// The size of every host view heap on a host that takes more than
+/// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000
+/// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and
+/// the last slot is the null slot every view index at or past it reads.
+const UNCAPPED_VIEWS: u32 = 1 << 21;
+
+/// Picks, once, the null slot at the end of every host view heap and tells
+/// the translator now (`set_view_heap_limit`) instead of when the title's
+/// heap is made: a shader keeps the limit it was translated with, and the
+/// title makes 25 pipelines (their shaders translated at once) before it
+/// makes its view heap. Called before a shader is translated and before a
+/// view heap is made.
+///
+/// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`]
+/// (NVIDIA) hung on a view index past the heap; one that does not (AMD
+/// RDNA3, RX 7900 XT) took a page fault and removed the device on entering
+/// the world: a compute program read view slot 16,777,088 (0xffff80) of a
+/// heap of 1,507,328, past its end. Unclamped, that index is undefined on
+/// any host.
+pub(crate) fn probe_view_limit() {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(|| {
+ let Some(host) = host() else { return };
+ let fits = |count: u32| {
+ // SAFETY: plain heap creation; the heap is released at once.
+ let made: windows::core::Result = unsafe {
+ host.device
+ .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
+ Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
+ NumDescriptors: count,
+ Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
+ NodeMask: 0,
+ })
+ };
+ made.is_ok()
+ };
+ let views = if fits(UNCAPPED_VIEWS) {
+ UNCAPPED_VIEWS
+ } else {
+ PORTABLE_VIEWS
+ };
+ tracing::info!(
+ views,
+ "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on"
+ );
+ victory_shader::emit::set_view_heap_limit(views - 1);
+ });
+}
+
/// Slots past the title's in a view heap, for tables a draw needs made
/// afresh (constant buffers copied per draw). A list holds the slots it
/// took until it is reset (its submissions have run) or released.
-const DYNAMIC: u32 = 1 << 16;
+/// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11;
+/// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views
+/// (NVIDIA) these come out of the title's slots, whose highest seen is
+/// about 720,000: 2^17 left 868,000 of them, and ran out in the opening
+/// cutscene (a frame asks for up to 16,000 tables while the frame before
+/// still holds its own; a draw refused its table read slots never made
+/// for it, and the card stopped within frames). 2^18 leaves 737,000; a
+/// table past them is made afresh in these slots like any other.
+pub(crate) const DYNAMIC: u32 = 1 << 18;
impl HostHeap {
pub(crate) fn new(sampler: bool, count: u32) -> Option {
@@ -85,17 +615,41 @@ impl HostHeap {
}
};
let extra = if sampler { 0 } else { DYNAMIC };
- let (heap, count) = match make(count + extra) {
- Ok(heap) => (heap, count),
- Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
- // shortcut: descriptors past the host's limit are left out;
- // a title that reaches them needs remapping.
- tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
- (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra)
- }
- Err(e) => {
- tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
- return None;
+ // A view heap ends at the null slot shaders clamp view indices to
+ // (`probe_view_limit`), whatever the title's own count: the title's
+ // slots, then the dynamic ones, then null up to and with that slot.
+ if !sampler {
+ probe_view_limit();
+ }
+ let null = if sampler {
+ 0
+ } else {
+ victory_shader::emit::view_heap_limit()
+ };
+ let (heap, count, size) = if null == 0 {
+ match make(count + extra) {
+ Ok(heap) => (heap, count, count + extra),
+ Err(e) => {
+ tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
+ return None;
+ }
+ }
+ } else {
+ let size = null + 1;
+ let fitted = if count + extra <= null {
+ count
+ } else {
+ // shortcut: descriptors past the host's limit are left out; a title that reaches
+ // them needs remapping. They read the null slot instead.
+ tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot");
+ null - extra
+ };
+ match make(size) {
+ Ok(heap) => (heap, fitted, size),
+ Err(e) => {
+ tracing::warn!(error = %e, count, size, "no host view heap");
+ return None;
+ }
}
};
// SAFETY: a live heap.
@@ -110,26 +664,50 @@ impl HostHeap {
let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
gpu,
- u64::from(count + extra) * u64::from(step),
+ u64::from(size) * u64::from(step),
u64::from(step),
sampler,
));
+ let strides = (!sampler)
+ .then(|| {
+ let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4;
+ let (buffer, data) = host.upload_buffer(bytes)?;
+ // SAFETY: the buffer's whole mapping; a live buffer.
+ let gpu = unsafe {
+ std::ptr::write_bytes(data, 0, bytes as usize);
+ buffer.GetGPUVirtualAddress()
+ };
+ crate::host::name(&buffer, || "element strides by view heap slot".to_owned());
+ Some((buffer, gpu, data as usize))
+ })
+ .flatten();
let h = HostHeap {
heap,
cpu,
step,
count,
+ dynamic: extra,
sampler,
made: Mutex::new(vec![0; count as usize]),
kept: Mutex::new(vec![None; (count + extra) as usize]),
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
+ free: std::sync::atomic::AtomicU32::new(DYNAMIC),
+ too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
+ strides,
+ buffers: Mutex::default(),
+ changed: Mutex::default(),
+ textures: Mutex::default(),
+ tabled: (0..if sampler { 0 } else { count })
+ .map(|_| std::sync::atomic::AtomicU32::new(0))
+ .collect(),
+ placed: Mutex::default(),
};
// A slot never written is undefined: shaders reading one (a slot
// the title wrote in a way we do not know, or a table entry no
// used-resource entry names) read a wild address. Every slot starts
// null instead.
let started = std::time::Instant::now();
- if let Err(e) = h.fill_null(kind, count + extra) {
+ if let Err(e) = h.fill_null(kind, size) {
tracing::warn!(error = %e, "host descriptor heap not made null");
}
tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
@@ -201,18 +779,24 @@ impl HostHeap {
/// `n` consecutive free dynamic slots (view heaps only), taken until
/// [`HostHeap::release`]: the first's index.
pub(crate) fn dynamic(&self, n: u32) -> Option {
- if self.sampler || n == 0 || n > DYNAMIC {
+ if self.sampler || n == 0 || n > self.dynamic {
return None;
}
+ #[cfg(feature = "diagnostics")]
+ let started = std::time::Instant::now();
+ #[cfg(feature = "diagnostics")]
+ crate::copystat::add(crate::copystat::C::DynamicAsked, 1);
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
let (next, taken) = &mut *guard;
+ let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
+ && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
let n = n as usize;
// Search from `next` on, then from the start.
- let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize);
+ let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize);
let mut run = 0;
let mut found = None;
let mut last = usize::MAX;
- for at in starts {
+ for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) {
// A run cannot wrap past the end.
if at != last.wrapping_add(1) {
run = 0;
@@ -225,15 +809,339 @@ impl HostHeap {
}
}
let Some(first) = found else {
+ if enough {
+ self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed);
+ }
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
+ #[cfg(feature = "diagnostics")]
+ {
+ use crate::copystat::{C, add};
+ add(C::DynamicRefused, 1);
+ add(C::DynamicNs, started.elapsed().as_nanos() as u64);
+ }
return None;
};
+ #[cfg(feature = "diagnostics")]
+ crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
taken[first..first + n].fill(true);
+ self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
*next = ((first + n) % DYNAMIC as usize) as u32;
Some(self.count + first as u32)
}
+ /// The title slots this heap has host slots for; fewer than the title's
+ /// when the host caps its size.
+ pub(crate) fn count(&self) -> u32 {
+ self.count
+ }
+
+ /// The GPU address of the table of element strides by title slot (view
+ /// heaps).
+ pub(crate) fn strides_gpu(&self) -> Option {
+ self.strides.as_ref().map(|s| s.1)
+ }
+
+ /// The table's buffer, for a list to hold.
+ pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> {
+ self.strides.as_ref().map(|s| &s.0)
+ }
+
+ /// Up to `max` title slots whose texture view is due at `frame`, each
+ /// with its write number, in the order to serve them
+ /// ([`TextureQueue::due`]), and the queue's counts
+ /// ([`TextureQueue::census`]).
+ pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) {
+ let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame))
+ }
+
+ /// The texture view of title slot `index` (as handed out with `write`)
+ /// was brought up to date: due again from frame `again` (uploaded with
+ /// that many bytes of its memory there, not all), or not until the
+ /// slot is written again.
+ pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) {
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ match again {
+ Some((frame, mapped)) => textures.partly(index, write, frame, mapped),
+ None => textures.done(index, write),
+ }
+ }
+
+ /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`].
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn texture_slot_recheck(
+ &self,
+ index: u32,
+ write: u64,
+ due: u64,
+ at: (u64, u64),
+ print: u64,
+ looks: u8,
+ uploaded: u64,
+ ) {
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ textures.recheck(index, write, due, at, print, looks, uploaded);
+ }
+
+ /// See [`TextureQueue::checked`].
+ pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
+ self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index)
+ }
+
+ /// Nothing to upload at title slot `index` now (its memory is not
+ /// mapped, or no more of it than before): looked at again after 1, 2,
+ /// 4, ... frames, at most `most`.
+ pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) {
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ textures.later(index, write, frame, most);
+ }
+
+ /// Bytes of title slot `index`'s memory that were mapped when it was
+ /// last uploaded in part (0: not uploaded, or whole).
+ pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
+ self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index)
+ }
+
+ /// Takes the ranges of title memory the runtime mapped, unmapped or
+ /// wrote since the last call ([`remapped`]) and makes the slots whose
+ /// placed texture lies there due from the next frame (by when a write
+ /// under way has landed): memory that arrived is uploaded, memory that
+ /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a
+ /// texture streamed into the place of another of the same description
+ /// is uploaded although no descriptor says so. Slots tables read are
+ /// left to their draws. Returns how many slots it made due.
+ /// shortcut: the ranges are kept in one place for all heaps; the heap
+ /// whose pass runs first takes them (a title has one view heap).
+ pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
+ use std::sync::atomic::Ordering::Relaxed;
+ let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
+ if ranges.is_empty() {
+ return 0;
+ }
+ let mut slots: Vec = {
+ let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
+ ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
+ };
+ slots.sort_unstable();
+ slots.dedup();
+ slots.retain(|&slot| !self.tabled_lately(slot, frame));
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ for &slot in &slots {
+ textures.changed(slot, frame, frame + 1);
+ }
+ STALE[3].fetch_add(slots.len() as u64, Relaxed);
+ slots.len()
+ }
+
+ /// The memory of the texture title slot `index` views is not mapped
+ /// (any more): a host slot made from it becomes null again, so that
+ /// the host copy can be let go (`crate::resource::let_go_idle`; a slot
+ /// keeps what it views). True if the slot was made.
+ pub(crate) fn texture_slot_gone(&self, index: u32) -> bool {
+ let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
+ if made.get(index as usize).is_none_or(|&key| key == 0) {
+ return false;
+ }
+ self.unmake(&mut made, index);
+ STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ true
+ }
+
+ /// Makes host slot `index` null again, as it is before its view is
+ /// made: a null view of the kind it held.
+ fn unmake(&self, made: &mut [u64], index: u32) {
+ let Some(key) = made.get_mut(index as usize).map(std::mem::take) else {
+ return;
+ };
+ if key == 0 {
+ return;
+ }
+ match view_at(key as u32, (key >> 32) as u32) {
+ Some(view) => null_for(&view, self.cpu(index)),
+ None => null_view(self.cpu(index)),
+ }
+ self.keep(index, None);
+ }
+
+ /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a
+ /// draw read it through the table and brought what it views up to
+ /// date, so the slot leaves the queue of textures picked by index; the
+ /// caller makes the host slot in place ([`HostHeap::mirror`]), as the
+ /// pass would have, for a shader that picks it by index all the same.
+ pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) {
+ self.tabled_in(index, read, crate::frame::current());
+ }
+
+ /// [`HostHeap::texture_slot_tabled`] in frame `frame`.
+ fn tabled_in(&self, index: u32, read: bool, frame: u64) {
+ use std::sync::atomic::Ordering::Relaxed;
+ let Some(stamp) = self.tabled.get(index as usize) else {
+ return;
+ };
+ let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
+ let old = stamp.load(Relaxed);
+ if !read {
+ if old & !TABLED_READ != now {
+ stamp.store(now, Relaxed);
+ }
+ return;
+ }
+ // Once per slot and frame: tables are read by every draw.
+ if old != now | TABLED_READ {
+ stamp.store(now | TABLED_READ, Relaxed);
+ if tabled_out() {
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ if textures.slots.remove(&index).is_some() {
+ TABLED_WRITES[1].fetch_add(1, Relaxed);
+ }
+ }
+ }
+ }
+
+ /// Whether title slot `index` was a table's within the last
+ /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are
+ /// to be queued as any other).
+ fn tabled_lately(&self, index: u32, frame: u64) -> bool {
+ let stamp = self.tabled_stamp(index) & !TABLED_READ;
+ let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
+ tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES
+ }
+
+ /// What `tabled` holds for title slot `index`; 0: never a table's.
+ fn tabled_stamp(&self, index: u32) -> u32 {
+ self.tabled
+ .get(index as usize)
+ .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed))
+ }
+
+ /// The queue's part of a write of title slot `index` in `frame`:
+ /// `texture`, whether it now holds a view of a texture the title may
+ /// fill; `seen` as for [`HostHeap::note_buffer`].
+ fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) {
+ let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 };
+ let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
+ // A table's slot lately: the draw that reads it uploads its
+ // texture, so its write waits for that draw.
+ let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES;
+ // Made now by a draw of this frame that read it through a table:
+ // up to date.
+ let read_now = seen && stamp == now | TABLED_READ;
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ if texture && !read_now {
+ let due = if lately && !seen {
+ TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ frame + TABLED_GRACE
+ } else {
+ 0
+ };
+ textures.written(index, frame, due, seen);
+ } else {
+ textures.remove(index);
+ }
+ }
+
+ /// The title slots that hold buffer views.
+ pub(crate) fn buffer_slots(&self) -> Vec {
+ let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
+ buffers.iter().copied().collect()
+ }
+
+ /// The title slots whose buffer view was written, or went, since the
+ /// last call.
+ pub(crate) fn buffer_changes(&self) -> Vec {
+ let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
+ std::mem::take(&mut *changed).into_iter().collect()
+ }
+
+ /// Records what title slot `index` now holds for shaders that pick
+ /// buffers from the heap: its element stride in the table, and whether
+ /// it is a buffer view at all.
+ /// `seen`: the slot was not written now, a draw or a pass made its
+ /// host slot from what it held.
+ /// Returns the title slots whose placed texture view the write made
+ /// stale ([`Spans`]): out of the queue of textures already, their host
+ /// slots are the caller's to make null (it holds `made`).
+ fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec {
+ if self.sampler {
+ return Vec::new();
+ }
+ // Measured for the texture side of the same gap (textures a shader
+ // picks by a computed index are neither made, if placed, nor
+ // uploaded): slots written with a placed texture view, and with a
+ // view of a texture object.
+ let texture = match view {
+ Some(View::Placed(false, resource, _)) if resource[0] != 1 => {
+ PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ true
+ }
+ Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => {
+ OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ true
+ }
+ _ => false,
+ };
+ self.queue_texture(index, texture, seen, crate::frame::current());
+ // The memory a placed texture view describes. Not for a slot
+ // tables read (thousands of writes a frame, each read by its
+ // draw): no pass looks at it, and the same texture's view in a
+ // slot shaders pick by index says what it says.
+ let placed_view = match view {
+ Some(View::Placed(false, resource, desc))
+ if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
+ {
+ Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32))
+ }
+ _ => None,
+ };
+ let stale = {
+ use std::sync::atomic::Ordering::Relaxed;
+ let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
+ let span = placed_view
+ .and_then(|(resource, start)| Some((start, start.saturating_add(placed.bytes(resource)?))));
+ match span {
+ Some((start, end)) => {
+ SPANNED[0].fetch_min(start, Relaxed);
+ SPANNED[1].fetch_max(end, Relaxed);
+ placed.note(index, start, end, !seen && stale_out())
+ }
+ None => {
+ placed.forget(index);
+ Vec::new()
+ }
+ }
+ };
+ if !stale.is_empty() {
+ STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed);
+ let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
+ for &slot in &stale {
+ textures.remove(slot);
+ }
+ }
+ let stride = view.and_then(view_stride);
+ if let Some((_, _, data)) = &self.strides
+ && index < victory_shader::emit::SLOT_STRIDES_COUNT
+ {
+ // SAFETY: inside the mapping; shaders read it while we write (a
+ // dword, either value is one the slot had).
+ unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
+ }
+ let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
+ let was = if stride.is_some() {
+ buffers.insert(index);
+ true
+ } else {
+ buffers.remove(&index)
+ };
+ if was {
+ self.changed
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .insert(index);
+ }
+ stale
+ }
+
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
/// returned).
///
@@ -243,8 +1151,11 @@ impl HostHeap {
return;
};
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
- let end = (at + n).min(DYNAMIC) as usize;
+ let end = (at + n).min(self.dynamic) as usize;
if let Some(slots) = guard.1.get_mut(at as usize..end) {
+ let given = slots.iter().filter(|taken| **taken).count() as u32;
+ self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
+ self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
slots.fill(false);
}
}
@@ -273,7 +1184,114 @@ impl HostHeap {
fn keep(&self, index: u32, resource: Option) {
let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
if let Some(slot) = kept.get_mut(index as usize) {
- *slot = resource;
+ // A running submission may still read the old resource through
+ // this slot.
+ if let Some(old) = std::mem::replace(slot, resource) {
+ crate::host::retire(old);
+ }
+ }
+ }
+
+ /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes
+ /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a
+ /// size, whose reads past it return zeros instead of reaching whatever
+ /// the host placed after the buffer.
+ pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
+ let Some(host) = host() else { return };
+ let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
+ let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
+ Format: DXGI_FORMAT_R32_TYPELESS,
+ ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
+ Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
+ Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
+ Buffer: D3D12_BUFFER_SRV {
+ FirstElement: offset / 4,
+ NumElements: elements,
+ StructureByteStride: 0,
+ Flags: D3D12_BUFFER_SRV_FLAG_RAW,
+ },
+ },
+ };
+ // SAFETY: a slot of our heap and a live buffer covering the range.
+ unsafe {
+ host.device
+ .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index))
+ };
+ self.keep(index, Some(buffer.clone()));
+ }
+
+ /// Makes slot `index` (a dynamic one) a raw buffer view that reads
+ /// zeros.
+ pub(crate) fn null_raw_at(&self, index: u32) {
+ null_buffer_view(self.cpu(index));
+ self.keep(index, None);
+ }
+
+ /// Makes slot `index` (a dynamic one) a raw unordered access view of
+ /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a
+ /// root UAV with a size, whose accesses past it do nothing instead of
+ /// reaching whatever the host placed after the buffer.
+ pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
+ let Some(host) = host() else { return };
+ let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
+ let desc = 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 {
+ FirstElement: offset / 4,
+ NumElements: elements,
+ StructureByteStride: 0,
+ CounterOffsetInBytes: 0,
+ Flags: D3D12_BUFFER_UAV_FLAG_RAW,
+ },
+ },
+ };
+ // SAFETY: a slot of our heap and a live buffer covering the range.
+ unsafe {
+ host.device.CreateUnorderedAccessView(
+ buffer,
+ None::<&ID3D12Resource>,
+ Some(&desc),
+ self.cpu(index),
+ )
+ };
+ self.keep(index, Some(buffer.clone()));
+ }
+
+ /// Makes slot `index` (a dynamic one) a raw unordered access view of
+ /// nothing: reads give zeros, writes are dropped.
+ pub(crate) fn null_raw_uav_at(&self, index: u32) {
+ self.keep(index, None);
+ let Some(host) = host() else { return };
+ let desc = 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: 1,
+ Flags: D3D12_BUFFER_UAV_FLAG_RAW,
+ ..Default::default()
+ },
+ },
+ };
+ // SAFETY: a slot of our heap; a null resource is allowed with a desc.
+ unsafe {
+ host.device.CreateUnorderedAccessView(
+ None::<&ID3D12Resource>,
+ None::<&ID3D12Resource>,
+ Some(&desc),
+ self.cpu(index),
+ )
+ };
+ }
+
+ /// The shader-visible handle of slot `index`.
+ pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE {
+ // SAFETY: a live shader-visible heap.
+ let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr };
+ D3D12_GPU_DESCRIPTOR_HANDLE {
+ ptr: start + u64::from(index) * u64::from(self.step),
}
}
@@ -305,6 +1323,17 @@ impl HostHeap {
/// data: a host copy of a buffer is made on first use.
pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option {
if index >= self.count {
+ // Diagnostic (NVIDIA heap cap): the highest title slot past the
+ // host heap seen so far.
+ static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
+ tracing::warn!(
+ index,
+ count = self.count,
+ for_draw,
+ "title slot past the host heap"
+ );
+ }
return None;
}
// SAFETY: the handle is a descriptor slot in title memory.
@@ -319,11 +1348,46 @@ impl HostHeap {
if made[index as usize] != 0 {
made[index as usize] = 0;
self.make_null(index);
+ let _ = self.note_buffer(index, None, false);
+ } else if for_draw {
+ // Left for later and stale since: out of the sets and the stride table.
+ let _ = self.note_buffer(index, None, false);
}
return None;
};
if made[index as usize] != key {
- let later = !for_draw && view.is_buffer();
+ // Views of other textures in the memory this one describes
+ // are stale: their host slots read nothing from here on, and
+ // let go of the host copies they held.
+ for stale in self.note_buffer(index, Some(&view), for_draw) {
+ if stale != index {
+ self.unmake(&mut made, stale);
+ }
+ }
+ // A view of a texture object that has no host copy yet waits
+ // for it, as buffer views wait for a draw: the slot is made
+ // when the texture is first used (`super::make_waiting`), or
+ // here when a draw reads the slot through a table.
+ let waiting = if for_draw { None } else { view.waiting_texture() };
+ if let Some(texture) = waiting {
+ super::wait_for(texture, handle);
+ }
+ let later = !for_draw && (view.is_buffer() || waiting.is_some());
+ // Another view of the placed texture the slot shows already (a
+ // title that streams a texture in writes its view again with
+ // more mips each time some arrive): the slot goes on showing
+ // the old view until a draw or the texture pass makes the new
+ // one and uploads what it shows. Made null here, the texture
+ // read as nothing for as long as it waited in the queue, every
+ // time it got sharper.
+ if later
+ && keep_views()
+ && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
+ .is_some_and(|old| same_placed_texture(&old, &view))
+ {
+ KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ return Some(view);
+ }
made[index as usize] = if later { 0 } else { key };
let kept = if later {
None
@@ -338,6 +1402,16 @@ impl HostHeap {
Some(view)
}
+ /// Whether host slot `index` shows `buffer`; `None` if it shows no
+ /// resource (diagnostics: a buffer view's slot must show the host copy
+ /// that is brought up to date for it).
+ #[cfg(feature = "diagnostics")]
+ pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option {
+ let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
+ let shown = kept.get(index as usize)?.as_ref()?;
+ Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer))
+ }
+
/// The view host slot `index` was made from, in a few words, with the
/// title and host addresses of a buffer view (diagnostics). "null" for
/// a slot never made or left null.
@@ -435,6 +1509,60 @@ pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
))
}
+/// The title memory the host slot of buffer view `view` is made on
+/// (address, bytes): the whole buffer the view is of, which is what
+/// [`make`] finds the host copy by. [`buffer_range`] is the part of it the
+/// view reads.
+pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> {
+ match view {
+ View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => {
+ let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?;
+ Some((data as u64, len))
+ }
+ View::Placed(_, resource, desc) if resource[0] == 1 => Some((
+ u64::from(desc[10]) | u64::from(desc[11]) << 32,
+ u64::from(resource[4]) | u64::from(resource[5]) << 32,
+ )),
+ _ => None,
+ }
+}
+
+/// Whether a buffer view is brought up to date in the host copy its slot
+/// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the
+/// copy up by the view's range alone, as before.
+fn view_extent() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0"))
+}
+
+/// The host copy buffer view `view` reads, and the title range (address,
+/// bytes) it reads there; `None` for other views and empty ranges.
+///
+/// The copy is the one the view's slot shows: [`make`] finds it by the
+/// whole buffer the view is of ([`buffer_extent`]). Looked up by the range
+/// the view reads, as it was, the copy is another one wherever the two
+/// lookups differ: for memory outside buffer objects, a view of a part of a
+/// buffer that crosses a window line (the buffer's window is two cells, the
+/// part's one), and for buffer objects, a part that also lies in a smaller
+/// buffer object. The slot then showed a copy nothing brought up to date,
+/// and what shaders wrote through it was looked for in the other copy.
+pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> {
+ let (address, len) = buffer_range(view)?;
+ if len == 0 {
+ return None;
+ }
+ if view_extent()
+ && let Some((base, width)) = buffer_extent(view)
+ // (The console is lax: a view may begin past its buffer's end.)
+ && address >= base
+ && address - base < width.max(1)
+ && let Some(shadow) = crate::shadow::find(base, width)
+ {
+ return Some((shadow, address, len));
+ }
+ crate::shadow::find(address, len).map(|shadow| (shadow, address, len))
+}
+
/// [`buffer_range`] of an unordered access view of memory at `base`.
fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
let desc = uav_desc(words);
@@ -456,6 +1584,64 @@ fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
/// The host resource a slot made by [`make`] views, if any.
type Kept = Option;
+/// A structured buffer view (`first`, `count` elements of `stride` bytes,
+/// `offset` bytes into its host copy) as a raw view of the same bytes:
+/// its first dword and its dwords. Translated shaders read untyped buffers
+/// as raw bytes at `element * stride + offset` (the stride from the
+/// used-resource entry, or from the table by heap slot for a buffer picked
+/// by index), and a raw read through a structured view gives zeros on
+/// NVIDIA (reported upstream with PR #193; structured reads through raw
+/// views were right there). So the host's view is raw whenever it can be:
+/// the bytes must start on 16 (the host's raw view alignment) and be whole
+/// dwords. A view that cannot stays structured.
+fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> {
+ if stride == 0 {
+ return None;
+ }
+ let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?;
+ let bytes = u64::from(count) * u64::from(stride);
+ (start % 16 == 0 && bytes % 4 == 0)
+ .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords)))
+ .flatten()
+}
+
+/// Whether the host accepts a buffer view with these fields of a buffer of
+/// `width` bytes. It removes the device for one it does not (view creation
+/// returns nothing), and the console is laxer: the title's heap holds
+/// views past their memory's end, of no elements, of typeless formats
+/// without the raw flag, with strides the host has no structured buffers
+/// for. Since every buffer view of the heap is made for shaders that pick
+/// them by index, one such view ended the run (2026-11-24, run 10).
+fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool {
+ use crate::resource::family;
+ let f = format.0 as u32;
+ let element = if raw {
+ // raw: R32 typeless, counted in dwords, starting on 16 bytes
+ if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) {
+ return false;
+ }
+ 4
+ } else if stride > 0 {
+ // structured: no format, a stride the host takes
+ if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) {
+ return false;
+ }
+ u64::from(stride)
+ } else {
+ // typed: a format with a size that is not typeless
+ let typeless = family(f) == f && family(f + 1) == f;
+ match crate::resource::element(f) {
+ Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes,
+ _ => return false,
+ }
+ };
+ count > 0
+ && first
+ .checked_add(u64::from(count))
+ .and_then(|end| end.checked_mul(element))
+ .is_some_and(|end| end <= width)
+}
+
fn buffer_srv(
address: u64,
len: u64,
@@ -463,19 +1649,57 @@ fn buffer_srv(
at: D3D12_CPU_DESCRIPTOR_HANDLE,
) -> Option {
let shadow = crate::shadow::find(address, len)?;
+ let offset = shadow.offset(address);
+ // A structured view as a raw view of the same bytes (see `raw_window`).
+ // SAFETY: a buffer view's union member.
+ let structured = unsafe { desc.Anonymous.Buffer };
+ let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
+ .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride))
+ .flatten();
+ if let Some((first, count)) = window {
+ desc.Format = DXGI_FORMAT_R32_TYPELESS;
+ desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
+ FirstElement: first,
+ NumElements: count,
+ StructureByteStride: 0,
+ Flags: D3D12_BUFFER_SRV_FLAG_RAW,
+ };
+ }
let element = element_size(&desc);
// SAFETY: a buffer view's union member.
let buffer = unsafe { &mut desc.Anonymous.Buffer };
- let offset = shadow.offset(address);
- if element == 0 || offset % element != 0 {
+ if window.is_none() {
+ if element == 0 || offset % element != 0 {
+ once!(
+ offset,
+ element,
+ "buffer view not on an element of its host copy"
+ );
+ return None;
+ }
+ buffer.FirstElement += offset / element;
+ }
+ let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
+ let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0;
+ // SAFETY: a live buffer.
+ let width = unsafe { shadow.buffer.GetDesc() }.Width;
+ if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
+ REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
once!(
- offset,
- element,
- "buffer view not on an element of its host copy"
+ format = desc.Format.0,
+ first,
+ count,
+ stride,
+ raw,
+ width,
+ "buffer view the host would refuse left null"
);
return None;
}
- buffer.FirstElement += offset / element;
+ // The console has no component mapping; one the host does not know is the default's.
+ if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING {
+ desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ }
let host = host()?;
// SAFETY: a live buffer and a slot of our heap.
unsafe {
@@ -513,12 +1737,45 @@ fn buffer_uav(
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
};
let offset = shadow.offset(address);
- if element == 0 || offset % element != 0 {
- once!(offset, element, "unordered buffer view not on an element of its host copy");
- return None;
+ // A structured view as a raw view of the same bytes (see `raw_window`).
+ let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
+ .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride))
+ .flatten();
+ if let Some((first, count)) = window {
+ buffer.FirstElement = first;
+ buffer.NumElements = count;
+ buffer.StructureByteStride = 0;
+ buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
+ } else {
+ if element == 0 || offset % element != 0 {
+ once!(offset, element, "unordered buffer view not on an element of its host copy");
+ return None;
+ }
+ buffer.FirstElement += offset / element;
}
- buffer.FirstElement += offset / element;
buffer.CounterOffsetInBytes = 0;
+ let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
+ let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0;
+ if window.is_some() {
+ // (Left out at first: every structured unordered access view was then
+ // refused by `buffer_view_ok` and left null, runs 15 and 16.)
+ desc.Format = DXGI_FORMAT_R32_TYPELESS;
+ }
+ // SAFETY: a live buffer.
+ let width = unsafe { shadow.buffer.GetDesc() }.Width;
+ if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
+ REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ once!(
+ format = desc.Format.0,
+ first,
+ count,
+ stride,
+ raw,
+ width,
+ "unordered buffer view the host would refuse left null"
+ );
+ return None;
+ }
let host = host()?;
// SAFETY: a live buffer and a slot of our heap.
unsafe {
@@ -547,6 +1804,9 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere
};
let own = d.Format.0 as u32;
if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
+ if unordered {
+ crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
once!(
unordered,
format = own,
@@ -569,6 +1829,14 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere
if view == 0 {
return !typeless;
}
+ // A view of a target whose format the host refuses, in the title's
+ // format: in the stand-in the host copy has.
+ if view != own && crate::resource::target_format(view) == own {
+ if let Some(format) = format {
+ *format = d.Format;
+ }
+ return true;
+ }
if family(view) != family(own) {
once!(view, own, "view format of another family");
return false;
@@ -581,6 +1849,73 @@ fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordere
true
}
+/// The title's unordered access view of a depth texture, as a view of the
+/// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip
+/// and slices, in the colour format of the twin's family for a depth or
+/// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the
+/// bits are the same). Without a description: mip 0 of every slice.
+/// The twin of a stencil plane (R8) stands for the views of that plane
+/// only, which become R8_UINT views of its one plane; `None` for a view of
+/// the depth plane, which the twin does not stand for. The depth plane has
+/// a twin of its own, viewed as a depth texture's without stencil: a view
+/// in the format of the depth plane of a depth-stencil format (21, 46)
+/// takes the twin's colour format too.
+fn twin_uav(
+ twin: &ID3D12Resource,
+ desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>,
+) -> Option {
+ // SAFETY: a live resource.
+ let d = unsafe { twin.GetDesc() };
+ let mut desc = desc.cloned().unwrap_or_else(|| {
+ let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC {
+ ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
+ ..Default::default()
+ };
+ if d.DepthOrArraySize > 1 {
+ all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
+ all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
+ ArraySize: u32::from(d.DepthOrArraySize),
+ ..Default::default()
+ };
+ }
+ all
+ });
+ // A stencil plane's twin (R8 typeless, 60): the title's view is of the
+ // stencil plane if it names plane 1 or a stencil view format (22, 47).
+ if d.Format.0 == 60 {
+ let mut plane = 0;
+ match desc.ViewDimension {
+ D3D12_UAV_DIMENSION_TEXTURE2D => {
+ // SAFETY: the member the dimension names.
+ let mut view = unsafe { desc.Anonymous.Texture2D };
+ plane = std::mem::take(&mut view.PlaneSlice);
+ desc.Anonymous.Texture2D = view;
+ }
+ D3D12_UAV_DIMENSION_TEXTURE2DARRAY => {
+ // SAFETY: the member the dimension names.
+ let mut view = unsafe { desc.Anonymous.Texture2DArray };
+ plane = std::mem::take(&mut view.PlaneSlice);
+ desc.Anonymous.Texture2DArray = view;
+ }
+ _ => {}
+ }
+ if plane != 1 && !matches!(desc.Format.0, 22 | 47) {
+ return None;
+ }
+ desc.Format.0 = 62;
+ return Some(desc);
+ }
+ // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40),
+ // and those of a depth-stencil format's depth plane (19 to 21, 44 to
+ // 46), for the twin of such a plane.
+ desc.Format.0 = match (desc.Format.0, d.Format.0) {
+ (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56,
+ (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41,
+ (other, _) => other,
+ };
+ Some(desc)
+}
+
/// Makes the host descriptor for `view` at `at`: the host resource it
/// views, or `None` if it cannot.
fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option {
@@ -608,6 +1943,30 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option {
View::Shader(resource, desc) => {
let resource = *resource as crate::object::This;
if let Some(texture) = crate::resource::host_resource(resource) {
+ // The title's views of textures with a stencil plane, as it
+ // describes them (format, dimension, component mapping, a
+ // pad, then first level, levels, plane): each distinct one
+ // once. They say how its shaders read the stencil plane
+ // (the lighting takes each pixel's material class and its
+ // "inside a room" bit from it).
+ #[cfg(feature = "diagnostics")]
+ {
+ // SAFETY: a live resource.
+ let own = unsafe { texture.GetDesc() }.Format.0;
+ if matches!(own, 19..=22 | 44..=47) {
+ static SEEN: Mutex)>> = Mutex::new(Vec::new());
+ let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
+ if seen.len() < 64 && !seen.contains(&(own, *desc)) {
+ seen.push((own, *desc));
+ tracing::info!(
+ ?resource,
+ texture_format = own,
+ view = ?desc,
+ "shader view of a depth-stencil texture"
+ );
+ }
+ }
+ }
let mut desc = desc.as_ref().map(srv_desc);
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
return None;
@@ -639,7 +1998,37 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option {
_ => None,
};
};
+ // The first such views of depth textures are logged as the
+ // title describes them (format, dimension, then mip, slices and
+ // plane): they say which planes shaders write, and as what.
+ if crate::resource::depth_and_unordered(resource) {
+ static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 {
+ tracing::info!(
+ ?resource,
+ view = ?desc,
+ "unordered access view of a depth texture"
+ );
+ }
+ }
let mut desc = desc.as_ref().map(uav_desc);
+ // A depth texture's unordered access is its colour twin's: the
+ // host gives a depth texture none.
+ let twin = crate::resource::twin_resource(resource)
+ .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?)))
+ // A view of the depth plane of a texture with a stencil
+ // plane: of that plane's own twin.
+ .or_else(|| {
+ let twin = crate::resource::twin_plane_resource(resource)?;
+ Some((twin, twin_uav(twin, desc.as_ref())?))
+ });
+ let texture = match twin {
+ Some((twin, view)) => {
+ desc = Some(view);
+ twin
+ }
+ None => texture,
+ };
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
return None;
}
@@ -696,6 +2085,30 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option {
}
}
+/// Writes of a slot with another view of the placed texture it showed,
+/// since the start: the slot kept showing the old view.
+pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Whether a slot written with another view of the placed texture it
+/// shows keeps showing the old one until the new is made;
+/// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before.
+fn keep_views() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
+}
+
+/// Whether both are shader views of one texture the title placed in
+/// memory: the same address and the same resource description, whatever
+/// part of it each shows.
+fn same_placed_texture(a: &View, b: &View) -> bool {
+ match (a, b) {
+ (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => {
+ resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12]
+ }
+ _ => false,
+ }
+}
+
/// A shader view of a texture the title placed in memory itself, as a view
/// of the resource made for that memory (on first use).
pub(crate) fn placed_texture(view: &View) -> Option {
@@ -717,14 +2130,20 @@ pub(crate) fn placed_texture(view: &View) -> Option {
fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let Some(host) = host() else { return };
let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
- let buffer = match view {
- View::Unordered(r, _, _) => is_buffer(r),
- View::Placed(true, resource, _) => resource[0] == 1,
+ // Unordered views: whether a buffer, and the title's view dimension.
+ let (buffer, dimension) = match view {
+ View::Unordered(r, _, desc) => (
+ is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
+ desc.map(|d| d[1]),
+ ),
+ View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])),
// Shader views of buffers read nothing through a null buffer view:
// a null 2D view where the shader expects a buffer is a mismatch
// the hardware does not survive in general (GPU-based validation
// reports it).
- View::Shader(r, _) if is_buffer(r) => return null_buffer_view(at),
+ View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => {
+ return null_buffer_view(at);
+ }
View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
// Textures: a null view of the title's dimension (1D, arrays, 3D,
// cubes), not always 2D.
@@ -739,14 +2158,14 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
}
_ => return null_view(at),
};
- let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
- Format: DXGI_FORMAT_R32_UINT,
- ViewDimension: if buffer {
- D3D12_UAV_DIMENSION_BUFFER
- } else {
- D3D12_UAV_DIMENSION_TEXTURE2D
- },
- ..Default::default()
+ let desc = if buffer {
+ D3D12_UNORDERED_ACCESS_VIEW_DESC {
+ Format: DXGI_FORMAT_R32_UINT,
+ ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
+ ..Default::default()
+ }
+ } else {
+ null_uav_desc(dimension)
};
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
unsafe {
@@ -759,6 +2178,46 @@ fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
};
}
+/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays,
+/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D
+/// texture is a mismatch GPU-based validation reports (the world's wind
+/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24).
+fn null_uav_desc(dimension: Option) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
+ let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
+ Format: DXGI_FORMAT_R32_UINT,
+ ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
+ ..Default::default()
+ };
+ match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) {
+ Some(D3D12_UAV_DIMENSION_TEXTURE1D) => {
+ desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
+ }
+ Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => {
+ desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
+ desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV {
+ ArraySize: 1,
+ ..Default::default()
+ };
+ }
+ Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => {
+ desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
+ desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
+ ArraySize: 1,
+ ..Default::default()
+ };
+ }
+ Some(D3D12_UAV_DIMENSION_TEXTURE3D) => {
+ desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
+ desc.Anonymous.Texture3D = D3D12_TEX3D_UAV {
+ WSize: u32::MAX,
+ ..Default::default()
+ };
+ }
+ _ => {}
+ }
+ desc
+}
+
/// A buffer view that reads zeros (raw, as translated shaders mostly read
/// buffers).
fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
@@ -810,6 +2269,9 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
}
/// A view that reads zeros, for slots whose view the host cannot make.
+/// shortcut: slots with no view at all (kind unknown) get this null 2D
+/// view; null buffer views there did not stop the world's low-address
+/// page faults (2026-11-24, run w10), so they are not the cause.
fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
let Some(host) = host() else { return };
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
@@ -834,19 +2296,261 @@ fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
mod tests {
use super::*;
+ /// A null texture UAV keeps the title's dimension (3D for the world's
+ /// wind field), and is 2D when the title names none.
+ #[test]
+ fn null_uavs_keep_the_titles_dimension() {
+ let d = null_uav_desc(Some(8));
+ assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D);
+ // SAFETY: the member the dimension names.
+ assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX);
+ let d = null_uav_desc(Some(5));
+ assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
+ // SAFETY: the member the dimension names.
+ assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1);
+ let dimension = |d| null_uav_desc(d).ViewDimension;
+ assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D);
+ assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D);
+ assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D);
+ // Multisampled UAVs need a cap; they stay 2D.
+ assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
+ }
+
+ /// Views of one placed texture are told from views of others by the
+ /// address and the resource description, not by what they show.
+ #[test]
+ fn views_of_one_placed_texture_are_told_by_address_and_description() {
+ let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
+ let view = |resource: [u32; 14], first_mip: u32, address: u32| {
+ let mut desc = [0u32; 16];
+ (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb);
+ View::Placed(false, resource, desc)
+ };
+ let low = view(texture, 3, 0x1000_0000);
+ // more mips of the same texture
+ assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000)));
+ // another address, another description, a buffer, an unordered view
+ assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000)));
+ let mut wider = texture;
+ wider[4] = 1024;
+ assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000)));
+ let mut buffer = texture;
+ buffer[0] = 1;
+ assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000)));
+ let View::Placed(_, resource, desc) = low.clone() else { unreachable!() };
+ assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc)));
+ assert!(!same_placed_texture(&low, &View::Shader(0, None)));
+ }
+
+ /// A null 3D UAV made on the real device leaves it alive.
+ #[test]
+ fn null_3d_uav_is_accepted_by_the_device() {
+ let Some(host) = host() else {
+ return; // no host GPU
+ };
+ let Some(heap) = HostHeap::new(false, 4) else {
+ return;
+ };
+ let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0]));
+ null_for(&view, heap.cpu(0));
+ // SAFETY: a plain device query.
+ assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
+ }
+
/// Dynamic slots stay taken until given back, and runs do not wrap.
+ #[test]
+ fn a_structured_view_made_raw_passes_the_host_check() {
+ // 100 elements of 20 bytes from element 8, in a copy that starts 32
+ // bytes before the view's memory: bytes 192..2192.
+ let (first, count) = raw_window(32, 8, 100, 20).unwrap();
+ assert_eq!((first, count), (48, 500));
+ assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096));
+ // the format a raw view must name; the structured one's is refused
+ assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096));
+ // past the buffer, not on 16 bytes, no elements
+ assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000));
+ assert!(raw_window(4, 0, 100, 20).is_none());
+ assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096));
+ // a structured view the host takes as it is
+ assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096));
+ }
+
+ /// The queue of textures picked by index serves the slots looked at
+ /// before first, then the newest write and the oldest in turns; a
+ /// slot whose memory is not there is looked at again after
+ /// 1, 2, 4 frames up to the limit; and what the pass reports about a
+ /// slot written again meanwhile is dropped.
+ #[test]
+ fn the_texture_queue_serves_the_newest_writes_first() {
+ let mut q = TextureQueue::default();
+ // Slots 10..18 written in frames 1..9, slot 5 last.
+ for i in 0..8u32 {
+ q.written(10 + i, u64::from(i) + 1, 0, false);
+ }
+ q.written(5, 9, 0, false);
+ let order: Vec = q.due(9, 100).into_iter().map(|d| d.0).collect();
+ // newest, oldest, newest, oldest, and so on
+ assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]);
+ assert_eq!(q.due(9, 2).len(), 2);
+ assert_eq!(q.census(9), [9, 9, 0, 0, 8]);
+ // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4.
+ let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1;
+ let w17 = write(&q, 17);
+ let mut frame = 9;
+ for wait in [1, 2, 4, 4] {
+ q.later(17, w17, frame, 4);
+ assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17));
+ frame += wait;
+ // Due again, and ahead of every slot never looked at.
+ assert_eq!(q.due(frame, 100)[0].0, 17);
+ }
+ assert_eq!(q.census(9)[2], 1);
+ q.done(17, w17);
+ assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17));
+ // Uploaded with part of its memory there: kept, with what was there.
+ let w16 = write(&q, 16);
+ q.partly(16, w16, 12, 4096);
+ assert_eq!(q.mapped(16), 4096);
+ assert_eq!(q.due(12, 100)[0].0, 16);
+ // The title writes slot 16 again while the pass works on it: what
+ // the pass then says about the old write changes nothing.
+ q.written(16, 13, 0, false);
+ q.done(16, w16);
+ q.later(16, w16, 13, 4);
+ assert_eq!(q.mapped(16), 0);
+ assert_eq!(q.due(13, 100)[0].0, 16);
+ // A draw that makes the host slot (`seen`) keeps what the queue knows,
+ let w15 = write(&q, 15);
+ q.partly(15, w15, 20, 8192);
+ q.written(15, 14, 0, true);
+ assert_eq!(q.mapped(15), 8192);
+ // and queues a slot the queue did not hold.
+ q.written(99, 14, 0, true);
+ assert!(q.due(14, 100).iter().any(|d| d.0 == 99));
+ // A write due later (a table's slot) is not handed out before.
+ q.written(98, 14, 16, false);
+ assert!(!q.due(15, 100).iter().any(|d| d.0 == 98));
+ assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
+ }
+
+ /// A view written over memory that older views describe otherwise
+ /// makes those stale; views of the same span are one texture's.
+ #[test]
+ fn a_newer_view_of_other_memory_makes_the_older_stale() {
+ let mut spans = Spans::default();
+ // Three textures side by side, the first in two slots.
+ assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
+ assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
+ assert!(spans.note(3, 0x3000, 0x4000, true).is_empty());
+ assert!(spans.note(4, 0x8000, 0x9000, true).is_empty());
+ // The same slot written with the same span again: nothing changes.
+ assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
+ assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
+ assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]);
+ // A draw makes a slot whose view overlaps them: left out, nothing stale.
+ assert!(spans.note(9, 0x2000, 0x3800, false).is_empty());
+ assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
+ // The title writes a texture over the end of the first and all of
+ // the second: their three slots are stale.
+ let mut stale = spans.note(5, 0x2000, 0x4000, true);
+ stale.sort_unstable();
+ assert_eq!(stale, [1, 2, 3]);
+ assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]);
+ // Another start in the same memory: stale in turn. Another length
+ // from the same start too.
+ assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]);
+ assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]);
+ // A slot that moves to another texture leaves its span behind.
+ assert!(spans.note(7, 0x8000, 0x9000, true).is_empty());
+ assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]);
+ assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]);
+ spans.forget(4);
+ spans.forget(7);
+ assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
+ }
+
+ /// Memory the runtime maps under a slot's texture makes the slot due
+ /// again from the next frame; a stale slot leaves the queue.
+ #[test]
+ fn remapped_memory_makes_its_texture_slots_due() {
+ let Some(heap) = HostHeap::new(false, 8) else {
+ return; // no host GPU
+ };
+ let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
+ // 64x64 BC7, one mip, at an address no test and no title uses.
+ let at = 0x7fee_0000_0000u64;
+ let view = |address: u64, width: u32| {
+ let mut desc = [0u32; 16];
+ (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
+ View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc)
+ };
+ let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap();
+ assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty());
+ let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
+ assert_eq!(queued, 1);
+ heap.texture_slot_done(1, write, None);
+ assert_eq!(slots(u64::MAX), []);
+ // Memory elsewhere: nothing. Under the texture: due from the next frame.
+ remapped((at + 2 * len) as usize, 0x1000);
+ remapped(at as usize, 0x1000);
+ assert_eq!(heap.texture_slots_remapped(50), 1);
+ assert_eq!(slots(50), []);
+ assert_eq!(slots(51), [1]);
+ // A wider texture written at the same address: slot 1 is stale.
+ assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]);
+ assert_eq!(slots(u64::MAX), [2]);
+ }
+
+ /// A slot a draw read through a table leaves the queue; the title's
+ /// next write of it waits for its draw, and is due after the grace
+ /// frames if none reads it.
+ #[test]
+ fn slots_read_through_tables_leave_the_texture_queue() {
+ let Some(heap) = HostHeap::new(false, 8) else {
+ return; // no host GPU
+ };
+ let frame = 100;
+ let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
+ let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]);
+ assert!(is_texture_view(&texture));
+ heap.queue_texture(2, true, false, frame);
+ heap.queue_texture(3, true, false, frame);
+ assert_eq!(slots(frame), [3, 2]);
+ heap.tabled_in(3, true, frame);
+ assert_eq!(slots(frame), [2]);
+ // Made in place by the draw that read it: still out.
+ heap.queue_texture(3, true, true, frame);
+ assert_eq!(slots(frame), [2]);
+ // Written again in the next frame: due once the grace frames have
+ // passed without a draw that reads it.
+ heap.queue_texture(3, true, false, frame + 1);
+ assert_eq!(slots(frame + TABLED_GRACE), [2]);
+ assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]);
+ // The draw comes after all: out again.
+ heap.tabled_in(3, true, frame + 1);
+ assert_eq!(slots(u64::MAX), [2]);
+ // A slot of a table no draw read stays queued; its next write waits.
+ heap.tabled_in(2, false, frame + 1);
+ assert_eq!(slots(frame + 1), [2]);
+ heap.queue_texture(2, true, false, frame + 2);
+ assert_eq!(slots(frame + 2), []);
+ // Long after the last table, a write is due at once.
+ heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES);
+ assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]);
+ }
+
#[test]
fn dynamic_slots_are_held_until_released() {
let Some(heap) = HostHeap::new(false, 4) else {
return; // no host GPU
};
- let a = heap.dynamic(DYNAMIC - 100).unwrap();
+ let a = heap.dynamic(heap.dynamic - 100).unwrap();
let b = heap.dynamic(60).unwrap();
- assert_eq!((a, b), (4, 4 + DYNAMIC - 100));
+ assert_eq!((a, b), (4, 4 + heap.dynamic - 100));
// 40 left at the end: 50 do not fit until something is given back.
assert_eq!(heap.dynamic(50), None);
heap.release(a, 50);
assert_eq!(heap.dynamic(50), Some(4));
- assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40));
+ assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
}
}
diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs
index 39a38a034b..dfbf2b2253 100644
--- a/crates/victory-gpu/src/device.rs
+++ b/crates/victory-gpu/src/device.rs
@@ -29,7 +29,7 @@ pub static IID: Iid = guid(
);
/// The levels the device answers to, as on PC: `ID3D12Device1` to
-/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates
+/// `ID3D12Device8`, and `ID3D12Device11`, which the title creates
/// its device as. Each level's table is the one before plus its methods.
const LEVEL_IIDS: [Iid; 9] = [
guid(
@@ -88,12 +88,13 @@ const LEVEL_IIDS: [Iid; 9] = [
),
];
-fn is_device(iid: *const Iid) -> bool {
+/// Whether `iid` names the device: its first interface or a newer level.
+pub(crate) fn is_device(iid: *const Iid) -> bool {
object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS)
}
/// The interface version these layouts were checked against (2.4). Both
-/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it.
+/// Minecraft (March 2022) and the title (April 2026) pass it.
pub const CHECKED_VERSION: u32 = 0x0002_0004;
/// Feature level 12_2, what the console hardware supports.
@@ -159,7 +160,7 @@ pub extern "system" fn create(
/// queues then have the newer layouts (two more methods each; see
/// `list` and `queue`), although the interface version stays 2.4.
/// shortcut: the creation interface is the only sign of the newer layouts
-/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022);
+/// we have (the title, April 2026, versus Minecraft, March 2022);
/// look for a better one if a title breaks the rule.
static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
@@ -345,6 +346,59 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
}
}
+/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both
+/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface
+/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the
+/// object `out` names and draws with it; on failure it goes without that
+/// pipeline, silently. What the descriptions hold is not known: the calls
+/// fail as they always did, with `out` null, and the first ones log the
+/// description's words and what its first word points at, so that the two
+/// methods can be written.
+/// shortcut: not implemented. Answering `S_OK` here without making the
+/// pipeline would hand the title whatever its stack held as an object.
+extern "system" fn unknown_pipeline(
+ _: This,
+ desc: *const u8,
+ _iid: *const Iid,
+ out: *mut This,
+) -> HRESULT {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2];
+ let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1;
+ if !out.is_null() {
+ // SAFETY: the title's out pointer (a local of its own).
+ unsafe { *out = std::ptr::null() };
+ }
+ if calls <= 4 || calls.is_power_of_two() {
+ // Sixteen 64-bit words at `at`, read through the kernel: neither
+ // pointer is known to be mapped.
+ #[cfg(windows)]
+ let words = |at: usize| -> Option> {
+ let mut bytes = [0u8; 128];
+ (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| {
+ bytes
+ .as_chunks::<8>().0.iter()
+ .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b)))
+ .collect()
+ })
+ };
+ #[cfg(not(windows))]
+ let words = |_: usize| None::>;
+ let description = words(desc as usize);
+ let first = description
+ .as_ref()
+ .and_then(|w| words(w[0] as usize));
+ tracing::warn!(
+ slot = format_args!("{:#x}", SLOT),
+ calls,
+ description = format_args!("{description:x?}"),
+ first_points_at = format_args!("{first:x?}"),
+ "a pipeline creation method that is not implemented: the title goes without this pipeline"
+ );
+ }
+ E_NOTIMPL
+}
+
/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
@@ -381,8 +435,10 @@ static FUNCTIONS: Table<160> = {
f[39] = query::create as *const (); // 0x138
f[41] = signature::create as *const (); // 0x148
f[48] = queue::create_x as *const (); // 0x180
+ f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
+ f[67] = unknown_pipeline::<0x218> as *const (); // 0x218
f[69] = object::ignore as *const (); // 0x228 debug error filter
f[70] = descriptor::create_placed_srv as *const (); // 0x230
f[71] = descriptor::create_placed_uav as *const (); // 0x238
@@ -434,7 +490,7 @@ mod tests {
#[test]
fn newer_device_levels_are_the_same_device() {
- // ID3D12Device11, as Grand Theft Auto VI asks for it.
+ // ID3D12Device11, as the title asks for it.
let (hr, device) = create_as(&LEVEL_IIDS[8]);
assert_eq!((hr, device), (S_OK, super::device()));
let mut same = std::ptr::null();
@@ -445,6 +501,54 @@ mod tests {
assert_eq!(missing(), E_NOTIMPL);
}
+ /// A device child, and the DXGI device, hand out the device as any
+ /// interface the device itself answers to.
+ #[test]
+ fn the_device_is_found_at_every_level_through_others() {
+ type Get = extern "system" fn(This, *const Iid, *mut This) -> HRESULT;
+ let fence_iid = &crate::fence::FENCE_IIDS[0];
+ let mut fence = std::ptr::null();
+ assert_eq!(
+ crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence),
+ S_OK
+ );
+ let get_device = slot::(fence, 0x38);
+ let dxgi = dxgi::device();
+ let query = slot::(dxgi, 0);
+ for iid in std::iter::once(&IID).chain(&LEVEL_IIDS) {
+ let mut found = std::ptr::null();
+ assert_eq!(get_device(fence, iid, &mut found), S_OK, "{iid:02x?}");
+ assert_eq!(found, device());
+ let mut found = std::ptr::null();
+ assert_eq!(query(dxgi, iid, &mut found), S_OK, "{iid:02x?}");
+ assert_eq!(found, device());
+ }
+ // What the device is not, it is not through them either.
+ let mut found = device();
+ assert_eq!(get_device(fence, fence_iid, &mut found), E_NOINTERFACE);
+ assert!(found.is_null());
+ slot:: u32>(fence, 0x10)(fence);
+ }
+
+ /// The host's: a fence's `GetDevice` for `ID3D12Device5`.
+ #[cfg(windows)]
+ #[test]
+ fn the_hosts_children_hand_out_newer_device_levels() {
+ use windows::Win32::Graphics::Direct3D12::{
+ D3D12_FENCE_FLAG_NONE, ID3D12Device5, ID3D12Fence,
+ };
+ let Some(host) = crate::host::host() else {
+ return; // no host GPU here
+ };
+ // SAFETY: plain calls on the host device and its fence.
+ unsafe {
+ let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
+ let mut device: Option = None;
+ assert!(fence.GetDevice(&mut device).is_ok());
+ assert!(device.is_some());
+ }
+ }
+
#[test]
fn virtual_memory_configuration_reports_user_space() {
let mut config = VirtualMemory {
diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs
index 8762d33e14..e13542220b 100644
--- a/crates/victory-gpu/src/draw.rs
+++ b/crates/victory-gpu/src/draw.rs
@@ -10,6 +10,7 @@
use std::sync::atomic::{AtomicU64, Ordering};
+use victory_shader::resource::RootIndexedView;
use victory_shader::{ResourceType, RootType, UsedResource};
use crate::descriptor::View;
@@ -51,6 +52,100 @@ pub(crate) struct IndexView {
format: u32,
}
+/// Host states of a depth target, and of a texture shaders read.
+const DEPTH_WRITE: u32 = 0x10;
+const DEPTH_READ: u32 = 0x20;
+const SHADER_RESOURCE: u32 = 0x40 | 0x80;
+
+thread_local! {
+ /// While a draw is prepared (`State::bind`, then its targets' states):
+ /// the depth target the draw only tests (0: none, or one it writes),
+ /// and whether a view its shaders read is of that same texture.
+ static TESTED_DEPTH: std::cell::Cell<(usize, bool)> =
+ const { std::cell::Cell::new((0, false)) };
+ /// While a stage's tables are walked (`State::tables`): whether that
+ /// stage's shader can store to buffers (`Translated::stores`).
+ static STORES: std::cell::Cell = const { std::cell::Cell::new(true) };
+}
+
+/// Whether a buffer range a shader names through an unordered access view
+/// is given to shaders as written (snapshot before the submission, compare
+/// and write back after) only if that shader's code can store to buffers.
+/// The title binds buffers its shaders only read through such views, and
+/// every range declared costs a snapshot and a compare of its bytes: 3.97
+/// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of
+/// comparing (run 28). On by default; `VICTORY_WRITE_SKIP=0` declares
+/// every such range, as before.
+fn write_skip() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_WRITE_SKIP").is_none_or(|v| v != "0"))
+}
+
+/// A run of indirect records clamped in one pass ([`windows`]): the host
+/// copy they came from (its number), their kind and stride, the offset of
+/// the first in that copy, how many, and the list's scratch buffer that
+/// holds them clamped, record `i` at `i * step`.
+#[derive(Clone)]
+struct Window {
+ copy: u64,
+ kind: u32,
+ stride: u32,
+ /// How far apart the records are in the copy, and in the scratch
+ /// buffer: what the title walks them by ([`windows`]).
+ step: u32,
+ base: u64,
+ records: u32,
+ scratch: ID3D12Resource,
+}
+
+/// The most records clamped in one pass ([`windows`]).
+const WINDOW_MOST: u64 = 64;
+
+/// Whether indirect draws that read record after record of one argument
+/// buffer are clamped a window at a time (`VICTORY_INDIRECT_WINDOW=1`; off
+/// by default).
+///
+/// The title issues its mesh draws one record per call, each from the next
+/// slot of the same argument buffer: 3,460 a frame in gameplay, and before
+/// each our clamp ran as a compute dispatch of its own between two waits,
+/// so the card went from drawing to compute and back for every record. In
+/// the timing run of the lit scene (run 79) a shadow draw of next to
+/// nothing cost 14-16 microseconds, 4,126 records a frame.
+///
+/// With the switch, when a draw asks for a record a short step after the
+/// one drawn before, the clamp takes that record and the ones that step
+/// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at
+/// most, never past the buffer) into
+/// the list's scratch buffer in one pass, and the draws that follow read
+/// their record there with no pass of ours, until one of these: a compute
+/// dispatch, a direct draw, an indirect call with a count buffer or more
+/// than one record, a draw whose shaders can store to buffers, a record
+/// outside the window, another host list.
+///
+/// The step is the one the title is seen to take, not the stride its
+/// command signature names: it draws one record a call, for which the
+/// stride means nothing, and the title names 12 bytes (the three
+/// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of
+/// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16
+/// apart, which ends a window). Walked by the named stride the window
+/// never opened: run 87, with the switch, still clamped 5,068 records a
+/// frame one at a time.
+///
+/// What it costs the guard against garbage records: nothing against a
+/// hang (every record is bounded as before and charged to the list's
+/// budget as before), but the budget is charged when a window is clamped,
+/// so also for records of the window's tail that are never drawn. Those
+/// hold garbage in this title (slots of all ones: run 93 spent lists'
+/// budgets on them and emptied the draws after), so in a window a record
+/// that asks for more than can run is left empty and charges nothing
+/// (`crate::indirect::bound_ahead`); a tail record that looks real is
+/// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as
+/// before, at the next submission.
+fn windows() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1"))
+}
+
/// What one title list has set, and what its host list was last given.
#[derive(Default)]
pub(crate) struct State {
@@ -64,19 +159,45 @@ pub(crate) struct State {
/// Bound render target and depth resources, for their host states.
targets: Vec,
depth: usize,
+ /// The host state the bound depth view needs ([`depth_state`]).
+ depth_state: u32,
/// The title's primitive topology (the host's may differ).
topology: u32,
+ /// What the title set that goes straight onto the host list, kept for
+ /// the host list that continues this one after a cut ([`State::replay`]):
+ /// whether a topology was set, the render target and depth handles, the
+ /// viewports, the scissors, the blend factor and the stencil reference.
+ topology_set: bool,
+ target_handles: Vec,
+ depth_handle: u64,
+ targets_set: bool,
+ viewports: Vec,
+ scissors: Vec,
+ blend: Option<[f32; 4]>,
+ stencil: Option,
+ /// The indirect records clamped last, if later draws may still read
+ /// them ([`windows`]).
+ window: Option,
/// What the host list has: pipeline, root signature, heaps.
host_pipeline: usize,
/// Graphics, compute.
host_roots: [usize; 2],
host_heaps: [usize; 2],
- /// Tables made afresh in this list: (table, what it holds) → first
+ /// Tables made afresh in this list: (table, slot count, contents) → first
/// dynamic slot.
- fresh_tables: std::collections::HashMap<(u64, u64), u32>,
+ fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>,
/// The dynamic slots the list holds: title heap, first, count; given
- /// back when the list is reset or released.
+ /// back when the list has run, is reset or released.
dynamic: Vec<(usize, u32, u32)>,
+ /// Root SRVs bound as one-view tables in this list: (title heap, title
+ /// address; 0 for none) → dynamic slot, and the host copy the slot
+ /// shows: later draws of the list bring that one up to date, whatever
+ /// copy the address would find by then (`shadow.rs` `tails`).
+ root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>,
+ /// Root UAVs bound as one-view tables in this list, likewise.
+ root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>,
+ /// The list ran and its dynamic slots were given back.
+ tables_gone: bool,
}
impl Drop for State {
@@ -87,6 +208,84 @@ impl Drop for State {
}
}
+impl State {
+ /// The list's submission has run (submissions are waited for): the
+ /// dynamic slots its tables were made in are given back, not kept
+ /// until the title resets the list. A frame of the opening cutscene
+ /// asks for 12,500 tables; held until the resets they ran the 131,072
+ /// slots out, and up to 4,900 draws a frame went without their tables.
+ /// shortcut: a list the title runs a second time without a reset then
+ /// reads slots others may have taken (logged once).
+ pub(crate) fn tables_done(&mut self) {
+ if self.tables_gone && self.dynamic.is_empty() {
+ return;
+ }
+ if self.tables_gone {
+ static ONCE: std::sync::Once = std::sync::Once::new();
+ ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back"));
+ }
+ for (heap, first, n) in self.dynamic.drain(..) {
+ crate::descriptor::release_dynamic(heap, first, n);
+ }
+ self.fresh_tables.clear();
+ self.root_srv_slots.clear();
+ self.root_uav_slots.clear();
+ self.tables_gone = true;
+ }
+}
+
+/// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`):
+/// they are all widened to the whole target. The title's room at
+/// the start of the prologue lost its walls in five runs of seven, and in
+/// those runs the player's body and the world outside were cut by one
+/// rectangle around the window (run 85, frame 2046): one run with this on
+/// says whether the walls are drawn and cut away by such a rectangle, or
+/// not drawn at all. Off by default: a rectangle the title sets is part of
+/// its picture.
+fn scissor_test() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full"))
+}
+
+/// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none
+/// is issued), 2 for `scissor` (each runs its shaders but rasterises one
+/// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung
+/// by what the shader's triangles cover.
+fn mesh_test() -> u8 {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() {
+ Ok("skip") => 1,
+ Ok("scissor") => 2,
+ _ => 0,
+ })
+}
+
+/// `VICTORY_MESH_TEST=keep:[:]`: only the mesh
+/// draws whose mesh shader's hash ends in one of the first digits (and
+/// whose digit before it is one of the second, if given) are issued: a
+/// search for the shaders that stop the card.
+fn mesh_kept(pipeline: usize) -> bool {
+ static KEEP: std::sync::OnceLock> = std::sync::OnceLock::new();
+ let Some((last, before)) = KEEP.get_or_init(|| {
+ let value = std::env::var("VICTORY_MESH_TEST").ok()?;
+ let mut parts = value.strip_prefix("keep:")?.split(':');
+ Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned()))
+ }) else {
+ return true;
+ };
+ let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else {
+ return true;
+ };
+ let Some(at) = p.name.find("mesh ") else {
+ return true;
+ };
+ let hash = p.name[at + 5..].as_bytes();
+ if hash.len() < 16 {
+ return true;
+ }
+ last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14]))
+}
+
/// Draws recorded on the host GPU since the last frame line.
static DRAWN: AtomicU64 = AtomicU64::new(0);
@@ -111,11 +310,65 @@ pub(crate) fn take_frame() -> Vec {
pub(crate) fn take_dropped() -> u64 {
DROPPED.swap(0, Ordering::Relaxed)
}
+/// A root SRV's dynamic slot in a list, and the host copy it shows.
+type RootSlot = (u32, Option>);
+
+/// Buffer views of the heap whose slot showed another host buffer than
+/// the copy the pass brought up to date for them, since the start
+/// (diagnostics; for the memory line). It stays 0 while the pass and the
+/// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were
+/// read stale.
+#[cfg(feature = "diagnostics")]
+pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0);
+/// Passes over the view heap's buffer views for shaders that pick them by
+/// index ([`State::heap_buffers`]), and the microseconds they took.
+pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
+pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
+/// Textures brought up to date for shaders that pick them by index
+/// ([`State::heap_textures`]), the bytes of their memory, and the slots
+/// still waiting.
+pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0);
+pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0);
+pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0);
+/// Passes that made no texture because the card had no room
+/// (`crate::resource::room`), for the memory line.
+pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0);
+
+/// Frames after a whole upload of a texture picked by index at which its
+/// memory is looked at again, each counted from the look before.
+const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400];
+
+/// Looks at uploaded textures picked by index that found the memory as it
+/// was, and that found it changed (uploaded again), since the start.
+pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
+
+/// Whether textures picked by index are looked at again after their upload
+/// (`VICTORY_HEAP_RECHECK=0`: no).
+fn heap_recheck() -> bool {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0"))
+}
+/// Times a placed texture's slot was passed over because its memory is not
+/// mapped.
+pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0);
+/// Slots the pass found up to date already: their texture is uploaded by
+/// the draws that read it through a table (it has a staging buffer).
+pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0);
+/// The queue of textures picked by index at the last pass
+/// (`TextureQueue::census`): slots in it, due, waiting for their memory,
+/// uploaded in part, and the frames the oldest due one has waited.
+pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
+/// Since the start: looks at a slot uploaded in part that found no more of
+/// its memory mapped; uploads of textures not all mapped; and of those,
+/// the ones whose first page was not there (asked by the first page alone,
+/// as before, they counted as not there at all).
+pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
static DROPPED: AtomicU64 = AtomicU64::new(0);
/// Marks the last traced draw as not run on the host.
#[cfg(feature = "diagnostics")]
-fn dropped() {
+fn dropped(pipeline: usize) {
+ crate::pipeline::note_drop(pipeline as This);
if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
last.push_str(" DROPPED");
}
@@ -131,13 +384,24 @@ pub(crate) fn dispatched() -> u64 {
/// The host address of a root view: its buffer's host copy, or for a
/// constant buffer not 256-byte aligned there (the console needs 16) a
/// copy in upload memory.
-/// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
-/// other views as 1 MiB (both cut at their buffer's end).
+/// shortcut: a root view has no size; constant buffers are taken as 64 KiB
+/// (cut at their buffer's end), other views as all that is left of their
+/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex
+/// streams of a cutscene frame reach further, and what lay past the first
+/// megabyte was never brought up to date - meshes without bodies, exploded
+/// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.)
fn root_view(list: &HostList, address: u64, srv: bool) -> Option {
+ static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new();
+ let limit = *LIMIT.get_or_init(|| {
+ std::env::var("VICTORY_ROOT_VIEW_MB")
+ .ok()
+ .and_then(|v| v.parse::().ok())
+ .map_or(u64::MAX, |mb| mb << 20)
+ });
let shadow = crate::shadow::find(address, 1)?;
let len = shadow
.left(address)
- .min(if srv { 1 << 20 } else { 1 << 16 });
+ .min(if srv { limit } else { 1 << 16 });
let gpu = shadow.gpu(address);
if srv || gpu % 256 == 0 {
shadow.refresh(list, address, len);
@@ -173,6 +437,7 @@ impl State {
/// [`crate::primitive`]).
pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
self.topology = topology;
+ self.topology_set = true;
let host = match topology {
RECTANGLES => 4,
TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
@@ -241,6 +506,12 @@ impl State {
}
}
+ pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
+ for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
+ *slot = VertexView::default();
+ }
+ }
+
pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
self.index = view.copied().unwrap_or_default();
}
@@ -250,6 +521,10 @@ impl State {
let Some(host) = crate::host::host() else {
return;
};
+ self.target_handles.clear();
+ self.target_handles.extend_from_slice(handles);
+ self.depth_handle = depth;
+ self.targets_set = true;
self.targets.clear();
let mut rtvs = Vec::new();
for &h in handles {
@@ -261,17 +536,34 @@ impl State {
continue;
};
let Some(texture) = crate::resource::host_resource(record.resource) else {
+ // A typed null view (or a target without a host copy) still
+ // takes its slot: left out, the next live target would move
+ // into it and the pixel shader's outputs reach the wrong
+ // targets.
+ // shortcut: a view without a description or a format has no
+ // null view to stand for it and is left out, as before.
+ let null = record
+ .desc()
+ .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0);
+ if let Some(desc) = null {
+ rtvs.push(host.rtv(None, Some(&desc)));
+ }
continue;
};
self.targets.push(record.resource as usize);
#[cfg(feature = "diagnostics")]
crate::capture::note_target(record.resource);
- rtvs.push(host.rtv(texture, record.desc().as_ref()));
+ rtvs.push(host.rtv(Some(texture), record.desc().as_ref()));
}
self.depth = 0;
+ self.depth_state = DEPTH_WRITE;
let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
let texture = crate::resource::host_resource(record.resource)?;
self.depth = record.resource as usize;
+ self.depth_state = depth_state(texture, record.depth_desc().as_ref());
+ if crate::resource::depth_and_unordered(record.resource) {
+ crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed);
+ }
#[cfg(feature = "diagnostics")]
crate::capture::note_target(record.resource);
Some(host.dsv(texture, record.depth_desc().as_ref()))
@@ -287,6 +579,81 @@ impl State {
};
}
+ /// Viewports, scissors, the blend factor and the stencil reference: set
+ /// on the host list at once, and kept for [`State::replay`].
+ pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) {
+ self.viewports.clear();
+ self.viewports.extend_from_slice(viewports);
+ crate::draw::viewports(list, viewports);
+ }
+
+ pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) {
+ self.scissors.clear();
+ self.scissors.extend_from_slice(rects);
+ if scissor_test() {
+ // The experiment: every rectangle the title sets is widened to
+ // the largest target there is, so nothing is cut by one. What
+ // the listing shows (`op_text`) stays the title's own.
+ let full = RECT {
+ left: 0,
+ top: 0,
+ right: 16384,
+ bottom: 16384,
+ };
+ crate::draw::scissors(list, &vec![full; rects.len()]);
+ return;
+ }
+ crate::draw::scissors(list, rects);
+ }
+
+ pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) {
+ self.blend = factor.copied();
+ crate::draw::blend_factor(list, factor);
+ }
+
+ pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) {
+ self.stencil = Some(reference);
+ crate::draw::stencil_ref(list, reference);
+ }
+
+ /// `list` is a new host list that continues the title's list (it was
+ /// cut at a wait for a memory value, `crate::list::cut`): a new host
+ /// list has nothing set, so what the title set so far is set again.
+ /// The pipeline, the root signatures and the heaps are set by the next
+ /// draw or dispatch (`bind`, which is told here that the host list has
+ /// none); root arguments, vertex and index buffers are set by every
+ /// draw anyway. The dynamic descriptor slots and the tables made in
+ /// them stay: the parts before the cut have not run yet, and they are
+ /// given back when the title's list is reset.
+ /// shortcut: the render target views are made again from the handles'
+ /// descriptors as they are now, not as they were when the title set
+ /// the targets (a descriptor rewritten in between names another view).
+ pub(crate) fn replay(&mut self, list: &HostList) {
+ self.host_pipeline = 0;
+ self.host_roots = [0; 2];
+ self.host_heaps = [0; 2];
+ if self.topology_set {
+ self.set_topology(list, self.topology);
+ }
+ if self.targets_set {
+ let handles = std::mem::take(&mut self.target_handles);
+ self.set_targets(list, &handles, self.depth_handle);
+ }
+ if !self.viewports.is_empty() {
+ crate::draw::viewports(list, &self.viewports);
+ }
+ if !self.scissors.is_empty() {
+ let rects = std::mem::take(&mut self.scissors);
+ self.set_scissors(list, &rects);
+ }
+ if let Some(factor) = self.blend {
+ crate::draw::blend_factor(list, Some(&factor));
+ }
+ if let Some(reference) = self.stencil {
+ crate::draw::stencil_ref(list, reference);
+ }
+ }
+
/// The user-data value of a root argument, as translated shaders read
/// it: a table's byte offset in its heap, a constant's value.
fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
@@ -304,6 +671,8 @@ impl State {
(Some(Root::Constants(c)), RootType::Constants) => {
c.get(dword as usize).copied().unwrap_or(0)
}
+ // The host's own ([`Self::host_word`]): no root argument.
+ (_, RootType::Other(_)) => 0,
_ => {
once!(
slot,
@@ -315,6 +684,73 @@ impl State {
}
}
+ /// A user-data dword the host computes for a translated shader
+ /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`).
+ fn host_word(
+ &self,
+ compute: bool,
+ kind: u32,
+ slot: u8,
+ dword: u32,
+ memory: Option<&crate::memory::Ready>,
+ ) -> u32 {
+ use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
+ if kind == USER_MEMORY_BASE {
+ return memory.map_or(0, |m| m.base);
+ }
+ if kind == USER_VIEW_BIAS {
+ // The view begins on 16 bytes of the copy the address finds
+ // (`root_uav`, `root_srv_table`).
+ // shortcut: found again here, not taken from the list's slot.
+ return match self.roots_ref(compute).get(usize::from(slot)) {
+ Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| {
+ // SAFETY: a live buffer.
+ let base = unsafe { s.buffer.GetGPUVirtualAddress() };
+ ((s.gpu(address) - base) & 15) as u32
+ }),
+ _ => 0,
+ };
+ }
+ if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 {
+ once!(kind, "a shader reads a host value this build does not know");
+ return 0;
+ }
+ // The title address of the buffer view at that dword of the table.
+ let address = match self.roots_ref(compute).get(usize::from(slot)) {
+ Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
+ .and_then(|view| crate::descriptor::host::buffer_range(&view))
+ .map_or(0, |range| range.0),
+ _ => 0,
+ };
+ if address == 0 {
+ once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0");
+ }
+ if kind == USER_VIEW_ADDRESS {
+ address as u32
+ } else {
+ (address >> 32) as u32
+ }
+ }
+
+ /// For a shader that reads title memory by address
+ /// ([`crate::memory`]): its directory, fault notes and view slots,
+ /// with the pages of the root views the list has set made ready.
+ fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option {
+ let heap = match self.heaps[0] {
+ 0 => None,
+ h => crate::descriptor::heap(h as This).host(),
+ }?;
+ let (mut addresses, mut constants) = (Vec::new(), Vec::new());
+ for root in self.roots_ref(compute) {
+ match root {
+ Root::View(address) => addresses.push(*address),
+ Root::Constants(values) => constants.extend_from_slice(values),
+ _ => {}
+ }
+ }
+ crate::memory::ready(list, heap, &addresses, &constants, writes)
+ }
+
/// The bound heap holding `handle`.
fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
self.heaps
@@ -332,6 +768,10 @@ impl State {
/// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
+ #[cfg(feature = "diagnostics")]
+ if crate::pipeline::is_skipped(self.pipeline as This) {
+ return false;
+ }
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
return false;
};
@@ -339,7 +779,13 @@ impl State {
once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
return false;
}
- self.bind(list, p, false);
+ if p.rects && self.topology != RECTANGLES {
+ // Its geometry stage would turn each triangle into a rectangle.
+ once!("a rectangle pipeline drawn with another topology");
+ }
+ if !self.bind(list, p, false) {
+ return false;
+ }
let l = &list.list;
// Vertex buffers the input layout reads.
let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
@@ -352,7 +798,7 @@ impl State {
if v.address == 0 || v.size == 0 {
continue;
}
- let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
+ let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
continue;
};
shadow.refresh(list, v.address, u64::from(v.size));
@@ -370,7 +816,7 @@ impl State {
}
if indexed {
let v = self.index;
- let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
+ let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
return false;
};
shadow.refresh(list, v.address, u64::from(v.size));
@@ -383,12 +829,28 @@ impl State {
unsafe { l.IASetIndexBuffer(Some(&view)) };
}
const RENDER_TARGET: u32 = 0x4;
- const DEPTH_WRITE: u32 = 0x10;
for &t in &self.targets {
crate::list::ensure_state(list, t as This, RENDER_TARGET);
}
if self.depth != 0 {
- crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
+ // A depth texture shaders also write: what they wrote, first.
+ list.twin_use(self.depth as This, false, true);
+ // A view that writes neither plane keeps the texture readable:
+ // the depth read state, together with the shader read states
+ // if this draw's shaders read the same texture (the write state
+ // put it out of the state those views need, and a move to it
+ // and back for every such draw).
+ let state = if self.depth_state == DEPTH_READ {
+ let (tested, read) = TESTED_DEPTH.get();
+ if read && tested == self.depth {
+ DEPTH_READ | SHADER_RESOURCE
+ } else {
+ DEPTH_READ
+ }
+ } else {
+ DEPTH_WRITE
+ };
+ crate::list::ensure_state(list, self.depth as This, state);
}
true
}
@@ -398,7 +860,9 @@ impl State {
/// What draws and dispatches share: heaps, our root signature, the
/// pipeline, and per stage the user data, root views and the
/// descriptors its tables hold.
- fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
+ /// False if the draw or dispatch must not run: a root SRV it reads
+ /// could not be given a view.
+ pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
let l = &list.list;
// Heaps first: a root signature with directly indexed heaps must be
// set after them.
@@ -416,6 +880,14 @@ impl State {
self.host_heaps = self.heaps;
self.host_roots = [0; 2];
}
+ // The depth target a draw only tests, for the views of it that the
+ // draw's shaders read (`readable`).
+ let tested = if !compute && self.depth_state == DEPTH_READ {
+ self.depth
+ } else {
+ 0
+ };
+ TESTED_DEPTH.set((tested, false));
let root = p.root.as_raw() as usize;
if self.host_roots[usize::from(compute)] != root {
// SAFETY: an open list and a live root signature.
@@ -441,10 +913,35 @@ impl State {
}
for stage in &p.stages {
let t = stage.translated();
- let made = self.tables(list, &t.used, compute);
+ STORES.set(t.stores);
+ let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
+ STORES.set(true);
+ if made.iter().any(|m| m.1 == u32::MAX) {
+ once!("a draw whose descriptor table found no free slots is dropped");
+ return false;
+ }
+ // What the shader stores through root views and raw addresses is
+ // copied back into title memory afterwards.
+ let writes = (t.stores || !write_skip())
+ && !crate::pipeline::builder_quarantined(self.pipeline as This);
+ // Title memory by address: what the shader finds it by.
+ let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
+ let Some(ready) = self.memory_ready(list, compute, writes) else {
+ once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
+ return false;
+ };
+ Some(ready)
+ } else {
+ None
+ };
if let Some((param, dwords)) = stage.user_data {
let mut values = vec![0u32; dwords as usize];
for u in &t.host.user_data {
+ if let RootType::Other(kind) = u.root {
+ values[u.index as usize] =
+ self.host_word(compute, kind, u.slot, u.dword, memory.as_ref());
+ continue;
+ }
let fresh = made
.iter()
.find(|m| m.0 == u.slot && u.root == RootType::Table);
@@ -464,14 +961,72 @@ impl State {
}
for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
for &(slot, param) in views {
- let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
+ if srv && slot == victory_shader::emit::SLOT_MEMORY {
+ // Ours: the directory of title memory by address.
+ if let Some(m) = &memory {
+ // SAFETY: an open list; the directory lives as
+ // long as the process and the list holds it.
+ unsafe {
+ if compute {
+ l.SetComputeRootShaderResourceView(param, m.directory);
+ } else {
+ l.SetGraphicsRootShaderResourceView(param, m.directory);
+ }
+ }
+ }
+ continue;
+ }
+ if srv && slot == victory_shader::emit::SLOT_STRIDES {
+ // Ours, not the title's: the shader picks buffers
+ // from the view heap by an index it computes.
+ match self.heap_buffers(list) {
+ // SAFETY: an open list; the table lives as long
+ // as the heap the list holds.
+ Some(gpu) => unsafe {
+ if compute {
+ l.SetComputeRootShaderResourceView(param, gpu);
+ } else {
+ l.SetGraphicsRootShaderResourceView(param, gpu);
+ }
+ },
+ None => once!("a shader picks buffers from a view heap that is not set"),
+ }
+ continue;
+ }
+ let tabled = srv && crate::pipeline::host::bounded_root_srvs();
+ let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
else {
once!(slot, "a shader reads a root view the title did not set");
+ // A table left unset is undefined: a null view.
+ if tabled && !self.root_srv_table(list, None, param, compute, false) {
+ return false;
+ }
continue;
};
- let Some(gpu) = root_view(list, *address, srv) else {
+ // The shader adds the bytes a raw view begins early by.
+ let biased = srv
+ && t.host.user_data.iter().any(|u| {
+ u.slot == slot
+ && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS)
+ });
+ if tabled {
+ if !self.root_srv_table(list, Some(address), param, compute, biased) {
+ return false;
+ }
+ continue;
+ }
+ let Some(mut gpu) = root_view(list, address, srv) else {
continue;
};
+ if biased {
+ gpu -= u64::from(self.host_word(
+ compute,
+ victory_shader::emit::USER_VIEW_BIAS,
+ slot,
+ 0,
+ None,
+ ));
+ }
// SAFETY: an open list; the address is in live memory.
unsafe {
match (compute, srv) {
@@ -483,24 +1038,750 @@ impl State {
}
}
}
+ for &(slot, param) in &stage.root_uavs {
+ if slot == victory_shader::emit::SLOT_FAULTS {
+ // Ours: where shaders note the pages they found empty.
+ if let Some(m) = &memory {
+ // SAFETY: an open list; the buffer lives as long as
+ // the process and the list holds it.
+ unsafe {
+ if compute {
+ l.SetComputeRootUnorderedAccessView(param, m.faults);
+ } else {
+ l.SetGraphicsRootUnorderedAccessView(param, m.faults);
+ }
+ }
+ }
+ continue;
+ }
+ let address = match self.roots_ref(compute).get(usize::from(slot)) {
+ Some(&Root::View(address)) => Some(address),
+ _ => {
+ once!(slot, "a shader writes through a root view the title did not set");
+ None
+ }
+ };
+ if !self.root_uav(list, address, param, compute, writes) {
+ return false;
+ }
+ }
+ }
+ // Depth textures it writes through unordered access: their colour
+ // twins hold what they lack from here on.
+ list.twins_written();
+ true
+ }
+
+ /// Binds a root UAV: a raw unordered access view of the title buffer's
+ /// host copy from `address` on, as a one-view table (a null view
+ /// without an address, without a host copy shaders can write, or at an
+ /// address not on 16 bytes), or as a root descriptor with
+ /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there
+ /// is nothing to bind). With `writes`, what the shader stored is copied
+ /// back into title memory when the list has run. False if the draw
+ /// must be dropped.
+ /// shortcut: a root view has no size: the view, the refresh and the
+ /// copy back cover all that is left of the title's buffer
+ /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three).
+ fn root_uav(
+ &mut self,
+ list: &HostList,
+ address: Option,
+ param: u32,
+ compute: bool,
+ writes: bool,
+ ) -> bool {
+ const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0;
+ static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new();
+ let limit = *LIMIT.get_or_init(|| {
+ std::env::var("VICTORY_ROOT_UAV_MB")
+ .ok()
+ .and_then(|v| v.parse::().ok())
+ .map_or(u64::MAX, |mb| mb << 20)
+ });
+ let find = |a: u64| {
+ let s = crate::shadow::find(a, 1)?;
+ // SAFETY: a live buffer.
+ let flags = unsafe { s.buffer.GetDesc() }.Flags;
+ if flags.0 & UNORDERED == 0 {
+ once!("a root UAV of a buffer whose host copy shaders cannot write");
+ return None;
+ }
+ Some(s)
+ };
+ let ready = |a: u64, s: &std::sync::Arc| {
+ let len = s.left(a).min(limit);
+ s.refresh(list, a, len);
+ if writes {
+ s.gpu_writes(list, a, len);
+ }
+ };
+ if !crate::pipeline::host::bounded_root_srvs() {
+ let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else {
+ once!("a root UAV with nothing to bind: the draw is dropped");
+ return false;
+ };
+ ready(a, &s);
+ // From the 16 bytes below: the shader adds the rest.
+ // SAFETY: a live buffer.
+ let base = unsafe { s.buffer.GetGPUVirtualAddress() };
+ let gpu = base + ((s.gpu(a) - base) & !15);
+ // SAFETY: an open list; the address is in a live buffer.
+ unsafe {
+ if compute {
+ list.list.SetComputeRootUnorderedAccessView(param, gpu);
+ } else {
+ list.list.SetGraphicsRootUnorderedAccessView(param, gpu);
+ }
+ }
+ return true;
+ }
+ let heap = match self.heaps[0] {
+ 0 => None,
+ h => Some(crate::descriptor::heap(h as This)),
+ };
+ let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
+ once!("a root UAV without a bound view heap: the draw is dropped");
+ return false;
+ };
+ let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0));
+ let (index, shadow) = match self.root_uav_slots.get(&key) {
+ Some((index, shadow)) => (*index, address.zip(shadow.clone())),
+ None => {
+ let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
+ let Some(index) = host.dynamic(1) else {
+ return false;
+ };
+ self.dynamic.push((key.0, index, 1));
+ if let Some((a, s)) = &shadow {
+ // SAFETY: a live buffer.
+ let base = unsafe { s.buffer.GetGPUVirtualAddress() };
+ let offset = s.gpu(*a) - base;
+ // Raw views start on 16 bytes: from the 16 bytes
+ // below, and the shader adds the rest to its offsets
+ // (`victory_shader::emit::USER_VIEW_BIAS`). (An address
+ // not on 16 bytes got a null view at first: the
+ // builder's counters are at such addresses.)
+ let bias = offset & 15;
+ host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias);
+ }
+ if shadow.is_none() {
+ host.null_raw_uav_at(index);
+ }
+ self.root_uav_slots
+ .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
+ (index, shadow)
+ }
+ };
+ if let Some((a, s)) = &shadow {
+ ready(*a, s);
+ }
+ let handle = host.gpu_handle(index);
+ // SAFETY: an open list; the slot is in the bound view heap.
+ unsafe {
+ if compute {
+ list.list.SetComputeRootDescriptorTable(param, handle);
+ } else {
+ list.list.SetGraphicsRootDescriptorTable(param, handle);
+ }
+ }
+ true
+ }
+
+ /// Binds a root SRV as a one-view table
+ /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the
+ /// title buffer's host copy from `address` to the copy's end, or a null
+ /// view (no address, no host copy, or an address not on 16 bytes). One
+ /// dynamic slot per address per list, given back with the list's
+ /// others. False if no slot could be had or no view heap is bound.
+ fn root_srv_table(
+ &mut self,
+ list: &HostList,
+ address: Option,
+ param: u32,
+ compute: bool,
+ biased: bool,
+ ) -> bool {
+ let heap = match self.heaps[0] {
+ 0 => None,
+ h => Some(crate::descriptor::heap(h as This)),
+ };
+ let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
+ once!("a root SRV without a bound view heap: the draw is dropped");
+ return false;
+ };
+ // A view that begins early is another view than one that does not
+ // (title addresses stay below bit 63).
+ let key = (
+ std::ptr::from_ref(heap) as usize,
+ address.unwrap_or(0) | u64::from(biased) << 63,
+ );
+ let (index, shadow) = match self.root_srv_slots.get(&key) {
+ Some((index, shadow)) => (*index, address.zip(shadow.clone())),
+ None => {
+ let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
+ let Some(index) = host.dynamic(1) else {
+ return false;
+ };
+ self.dynamic.push((key.0, index, 1));
+ self.root_srv_slots
+ .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
+ match &shadow {
+ Some((a, s)) => {
+ // SAFETY: a live buffer.
+ let base = unsafe { s.buffer.GetGPUVirtualAddress() };
+ let offset = s.gpu(*a) - base;
+ if biased {
+ // From the 16 bytes below; the shader adds the
+ // rest (`victory_shader::emit::USER_VIEW_BIAS`).
+ let bias = offset & 15;
+ host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias);
+ } else if offset.is_multiple_of(16) {
+ host.raw_at(index, &s.buffer, offset, s.left(*a));
+ } else {
+ // Raw views start on 16 bytes; one from the
+ // aligned start would shift every read.
+ once!(
+ address = format_args!("{a:#x}"),
+ "a root SRV not on 16 bytes reads zeros"
+ );
+ host.null_raw_at(index);
+ }
+ }
+ None => host.null_raw_at(index),
+ }
+ (index, shadow)
+ }
+ };
+ // As for root descriptors (`root_view`): all that is left of the
+ // buffer is brought up to date. The first 1 MiB only left what lay
+ // past it stale (most mesh vertex streams reach further).
+ if let Some((a, s)) = &shadow {
+ s.refresh(list, *a, s.left(*a));
}
+ let handle = host.gpu_handle(index);
+ // SAFETY: an open list; the slot is in the bound view heap.
+ unsafe {
+ if compute {
+ list.list.SetComputeRootDescriptorTable(param, handle);
+ } else {
+ list.list.SetGraphicsRootDescriptorTable(param, handle);
+ }
+ }
+ true
+ }
+
+ /// For a shader that picks buffers from the view heap by an index it
+ /// computes (SM 6.6 dynamic resources): the GPU address of the heap's
+ /// table of element strides, with every buffer view of the heap given
+ /// its host slot and its memory brought up to date when `list` is
+ /// submitted. Tables tell us which views a draw reads; nothing tells
+ /// us which of the heap's a computed index names, so all of them are
+ /// made ready, once per list.
+ /// shortcut: the buffers are read, not written: what such a shader
+ /// writes through a picked unordered access view stays in the host
+ /// copy. A list refreshes them where it first runs such a shader;
+ /// title writes recorded later in the same list are not seen.
+ fn heap_buffers(&self, list: &HostList) -> Option {
+ let heap = self
+ .heaps
+ .iter()
+ .filter(|&&h| h != 0)
+ .map(|&h| crate::descriptor::heap(h as This))
+ .find(|h| !h.samplers())?;
+ let host = heap.host()?;
+ let gpu = host.strides_gpu()?;
+ // One key per list, as textures have: no title resource is there.
+ const ONCE: usize = usize::MAX - 0x5e;
+ if !list.first_use(ONCE) {
+ return Some(gpu);
+ }
+ // The list may outlive the title's heap object, which owns the table.
+ if let Some(buffer) = host.strides_buffer() {
+ list.keep(buffer);
+ }
+ // The pass itself once per frame: per list it ran up to 51 times a
+ // frame over 81,000 views and 4,100 host copies, 18 s of every
+ // frame (2026-11-24, run 11).
+ // shortcut: what the title writes into such buffers between lists
+ // of one frame is seen a frame late.
+ static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
+ let frame = crate::frame::current();
+ if FRAME.swap(frame, Ordering::Relaxed) == frame {
+ return Some(gpu);
+ }
+ let started = std::time::Instant::now();
+ // Per host heap: the host copy and range each slot's buffer view
+ // reads, kept from pass to pass. Only the slots written since the
+ // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s
+ // at best); all of them every 16 passes, because a view of a
+ // released resource goes stale without a write, and a slot written
+ // before its memory had a host copy is only made then.
+ type Ranges = std::collections::HashMap, u64, u64)>;
+ static RANGES: std::sync::Mutex>> =
+ std::sync::Mutex::new(None);
+ let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
+ let (passes, ranges) = kept
+ .get_or_insert_with(Default::default)
+ .entry(std::ptr::from_ref(host) as usize)
+ .or_insert_with(|| (0, Ranges::new()));
+ let changed = host.buffer_changes();
+ let slots = if *passes % 16 == 0 {
+ ranges.clear();
+ host.buffer_slots()
+ } else {
+ changed
+ };
+ *passes += 1;
+ // Whether the device was there before the pass: a view that removes
+ // it is named below.
+ static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+ let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
+ for (n, &index) in slots.iter().enumerate() {
+ ranges.remove(&index);
+ let Some(handle) = heap.handle(index) else {
+ continue;
+ };
+ let Some(view) = host.mirror(index, handle, true) else {
+ continue;
+ };
+ // Every 64 views while the device lives (a cheap query).
+ if alive
+ && n % 64 == 63
+ && let Some(why) = crate::descriptor::host::device_removed()
+ {
+ alive = false;
+ GONE.store(true, Ordering::Relaxed);
+ let last: Vec = slots[n - 63..=n]
+ .iter()
+ .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
+ .map(|s| s.chars().take(200).collect())
+ .collect();
+ tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}");
+ crate::host::log_removal_context();
+ }
+ // The copy the slot shows (`buffer_copy`), not the one the
+ // view's range alone would find.
+ let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else {
+ continue;
+ };
+ #[cfg(feature = "diagnostics")]
+ if host.shows(index, &shadow.buffer) == Some(false) {
+ HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
+ }
+ ranges.insert(index, (shadow, address, address + len));
+ }
+ let views = ranges.len() as u32;
+ // Per host copy, the span its picked views cover.
+ let mut spans: std::collections::HashMap, u64, u64)> =
+ std::collections::HashMap::new();
+ for (shadow, from, to) in ranges.values() {
+ let key = std::sync::Arc::as_ptr(shadow) as usize;
+ let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
+ span.1 = span.1.min(*from);
+ span.2 = span.2.max(*to);
+ }
+ drop(kept);
+ let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
+ // Memory that is not write-watched is copied whole by every refresh.
+ // It was once refreshed only every 120 frames (unmapped pages read
+ // one by one cost 14 GB a frame in run 11, before they were
+ // remembered): streamed geometry then drew from stale buffers, and
+ // the garbage ended runs (the card stopped answering 14-90 frames
+ // into the opening cutscene; with every frame it ran on). The pass
+ // costs some 30 ms a frame this way.
+ static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None);
+ let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
+ let whole = whole.get_or_insert_with(Default::default);
+ for (shadow, from, to) in spans.values() {
+ if shadow.unwatched() {
+ // By the copy's number: a copy made where one let go was
+ // (`shadow::let_go_idle`) has never been refreshed.
+ let key = shadow.id() as usize;
+ // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame).
+ static EVERY: std::sync::OnceLock = std::sync::OnceLock::new();
+ let every = *EVERY.get_or_init(|| {
+ std::env::var("VICTORY_UNWATCHED_FRAMES")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(1)
+ });
+ match whole.get(&key) {
+ Some(&last) if frame < last + every => continue,
+ _ => {
+ whole.insert(key, frame);
+ }
+ }
+ }
+ shadow.refresh(list, *from, to - from);
+ }
+ self.heap_textures(list, heap, host);
+ HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
+ HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
+ static LOGGED: AtomicU64 = AtomicU64::new(0);
+ // The first pass and every growth of the set by half.
+ let seen = LOGGED.load(Ordering::Relaxed);
+ if u64::from(views) > seen + seen / 2 {
+ LOGGED.store(u64::from(views), Ordering::Relaxed);
+ tracing::info!(
+ slots = slots.len(),
+ views,
+ copies = spans.len(),
+ mb = bytes >> 20,
+ ms = started.elapsed().as_millis(),
+ "buffer views of the heap made ready for shaders that pick them by index"
+ );
+ }
+ Some(gpu)
+ }
+
+ /// The texture side of [`State::heap_buffers`]: textures the title fills
+ /// itself (streamed pages, layout-library copies) whose views sit in the
+ /// view heap are created (placed textures have no host texture until
+ /// something reads them) and uploaded, as a table read would do, for
+ /// shaders that pick them by a computed index. Within a budget of bytes
+ /// per frame and in all; the rest waits for later lists and frames.
+ /// The most recently written slots first (`TextureQueue::due`); slots
+ /// draws read through tables are not in the queue.
+ /// shortcut: uploaded once, and again only when the title rewrites the
+ /// slot. A placed texture not all mapped yet is uploaded with what is
+ /// there and looked at again (1, 2, 4, ... frames later, at most about
+ /// a second): uploaded again when more of it is mapped. Pages mapped
+ /// in place of others, and contents changed with no descriptor write,
+ /// are missed (hook the page-mapping events for those).
+ /// `VICTORY_HEAP_TEXTURES=0` turns it off.
+ fn heap_textures(
+ &self,
+ list: &HostList,
+ heap: &crate::descriptor::Heap,
+ host: &crate::descriptor::host::HostHeap,
+ ) {
+ static ON: std::sync::OnceLock = std::sync::OnceLock::new();
+ if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
+ return;
+ }
+ /// Bytes of texture memory staged per frame.
+ // `VICTORY_TEXTURE_STAGE_MB` raises it: a backlog of tens of thousands of
+ // textures (a scene's first minutes) then drains in fewer frames.
+ static PER_FRAME_MB: std::sync::OnceLock = std::sync::OnceLock::new();
+ let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| {
+ std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192)
+ }) << 20;
+ static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
+ static SPENT: AtomicU64 = AtomicU64::new(0);
+ let frame = crate::frame::current();
+ if FRAME.swap(frame, Ordering::Relaxed) != frame {
+ SPENT.store(0, Ordering::Relaxed);
+ }
+ // No more of them are made while the card has no room
+ // (`resource::room`): by what is alive now, not by what was ever
+ // staged (4 GB in all, after which later textures stayed empty for
+ // the run). The ones nothing names any more are let go, which
+ // makes room again: so the slots are still looked at (the pass
+ // returned here, and a slot whose texture had been streamed out
+ // kept its host copy for as long as the card was full).
+ let room = crate::resource::room();
+ if !room {
+ HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
+ once!("textures picked by index: the card has no room for more; they wait");
+ }
+ let mut refused = 0;
+ // Slots whose texture's memory the runtime mapped, unmapped or
+ // wrote since the last pass are due again.
+ host.texture_slots_remapped(frame);
+ let (due, census) = host.texture_slots_due(frame, 4096);
+ HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
+ for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
+ count.store(now, Ordering::Relaxed);
+ }
+ // The frames in about four seconds, between 16 and 256: how long a
+ // slot with nothing to upload waits at most for its next look. In
+ // frames alone it was 120: four minutes at the opening cutscene's
+ // half a frame per second, while the title streams by the clock.
+ // (About a second before the runtime told of the memory it maps:
+ // the looks are now only for what that does not tell.)
+ static PASSED: AtomicU64 = AtomicU64::new(0);
+ let now = crate::host::now_ms();
+ let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
+ let most = (4000 / took).clamp(16, 256);
+ // What a table entry of a texture a shader samples says.
+ let sampled = UsedResource {
+ kind: ResourceType::Srv,
+ root: RootType::Table,
+ table_offset_dwords: 0,
+ lower_bound: 0,
+ stride: 0,
+ dwords: 8,
+ user_data: 0,
+ slot: 0,
+ };
+ // Also within a time per pass: the pass runs on a thread that
+ // records the frame, and making and staging 192 MB of textures took
+ // 1.6-2.2 s of each of the world's first twenty frames (run 20).
+ // The rest waits for the next frames, as it does past the bytes.
+ static SPAN_MS: std::sync::OnceLock = std::sync::OnceLock::new();
+ let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| {
+ std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250)
+ }));
+ // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black
+ // surfaces at 192 MB a frame) gets three times the bytes and the time until it
+ // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
+ static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new();
+ let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
+ let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
+ let began = std::time::Instant::now();
+ for (index, write) in due {
+ if SPENT.load(Ordering::Relaxed) >= per_frame || began.elapsed() > span {
+ break;
+ }
+ // A placed texture whose memory is not mapped (not streamed in
+ // yet, or streamed out again: the heap keeps tens of thousands
+ // of such views) gets no host texture; looked at again soon (a
+ // title writes a texture's view before its pages are mapped,
+ // and the pass runs early in a frame). One of which some is
+ // mapped (a texture streaming in: its smaller mips lie at the
+ // start of its memory and arrive first) is uploaded with what
+ // is there, and again when more is. (It was uploaded again
+ // every 120 frames, changed or not; and asked by its first
+ // page alone, one whose first page is the one missing counted
+ // as not there.)
+ // A slot uploaded whole is looked at again a few times
+ // (`RECHECK_FRAMES`): the title writes a texture's view, and
+ // may fill the texture's memory itself only afterwards, with
+ // no descriptor write and nothing from the runtime to tell of
+ // it. The host copy then kept what the memory held at the
+ // first look for the rest of the run. The look reads 48 KiB;
+ // only a changed texture is uploaded again.
+ // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
+ if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
+ if crate::texture::fingerprint(at, len) == print {
+ HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
+ match RECHECK_FRAMES.get(usize::from(looks) + 1) {
+ Some(wait) => {
+ host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded)
+ }
+ None => host.texture_slot_done(index, write, None),
+ }
+ continue;
+ }
+ let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
+ if n < 200 || n.is_multiple_of(1000) {
+ tracing::warn!(
+ slot = index,
+ address = format_args!("{at:#x}"),
+ bytes = len,
+ frames_after_upload = frame.saturating_sub(uploaded),
+ looks,
+ changed = n + 1,
+ "a texture picked by index changed after its upload with nothing to tell of it: uploaded again"
+ );
+ }
+ }
+ let mut partly = None;
+ if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
+ let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
+ let len = crate::resource::placed_bytes(&resource).unwrap_or(1);
+ let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
+ if mapped == 0 {
+ HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
+ // Streamed out: what the slot showed is let go.
+ host.texture_slot_gone(index);
+ host.texture_slot_later(index, write, frame, most);
+ continue;
+ }
+ if mapped < len {
+ if mapped <= host.texture_slot_mapped(index) {
+ HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
+ host.texture_slot_later(index, write, frame, most);
+ continue;
+ }
+ if !crate::texture::committed(address as *const u8, 1) {
+ HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed);
+ }
+ partly = Some(mapped);
+ }
+ }
+ // A texture object the host renders to or writes holds the
+ // host's own contents: nothing to bring up to date, and this
+ // pass is no use of it (its host copy is made when something
+ // uses it, and its slots then: `descriptor::make_waiting`).
+ if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view)
+ && crate::resource::buffer_bytes(object as This).is_none()
+ && !crate::resource::title_fills(object as This)
+ {
+ host.texture_slot_done(index, write, None);
+ continue;
+ }
+ // From here on a host texture is made: not without room. The
+ // slot stays due.
+ if !room {
+ refused += 1;
+ if refused > 256 {
+ break;
+ }
+ continue;
+ }
+ let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true));
+ let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
+ let resource = match placed.as_ref().or(view.as_ref()) {
+ Some(&View::Shader(resource, _)) => resource as This,
+ _ => {
+ host.texture_slot_done(index, write, None);
+ continue;
+ }
+ };
+ let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written);
+ if !title_fills {
+ // a render target, a depth or unordered access texture: the host's own
+ host.texture_slot_done(index, write, None);
+ continue;
+ }
+ // A texture that has a staging buffer now is one draws read
+ // through a table: they upload it, and check it at every
+ // submission that samples it.
+ let tabled = crate::texture::is_staged(resource);
+ if let Some(view) = &view {
+ readable(list, sampled.kind, view);
+ }
+ // A texture view the host refuses removes the device: name it.
+ static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+ if !GONE.load(Ordering::Relaxed)
+ && let Some(why) = crate::descriptor::host::device_removed()
+ {
+ GONE.store(true, Ordering::Relaxed);
+ let text: String = format!("{view:?}").chars().take(300).collect();
+ tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
+ crate::host::log_removal_context();
+ return;
+ }
+ let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true));
+ // Not all of it there: looked at again next frame, and from
+ // then on as a slot with nothing new (a placed texture: until
+ // more of it is mapped; a texture object at an address the
+ // title mapped: again in 120 frames, as before).
+ let again = match partly {
+ Some(mapped) => Some((frame + 1, mapped)),
+ None => (!whole).then_some((frame + 120, 0)),
+ };
+ if again.is_some() {
+ HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed);
+ }
+ if tabled {
+ // Nothing was staged here, so nothing is counted or spent,
+ // and the staging buffer stays: taking it away made the
+ // next draw that reads the texture through a table stage,
+ // detile and upload all of it once more.
+ HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed);
+ host.texture_slot_done(index, write, again);
+ continue;
+ }
+ // Uploaded: the list holds the staging buffer until it has run;
+ // a table read, or the next look at a texture not all mapped
+ // yet, makes it anew. (Kept for those until now: every partly
+ // streamed texture of the heap held a staging buffer of its full
+ // size for good.)
+ let memory = if again.is_none() && heap_recheck() {
+ crate::texture::staged_memory(resource)
+ } else {
+ None
+ };
+ crate::texture::unstage(resource);
+ SPENT.fetch_add(bytes, Ordering::Relaxed);
+ HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
+ HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
+ match memory {
+ // Whole and uploaded: looked at again (see above).
+ Some((at, len)) => {
+ let print = crate::texture::fingerprint(at, len);
+ host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame);
+ }
+ None => host.texture_slot_done(index, write, again),
+ }
+ }
+ }
+
+ /// For the frame listing, after a dropped dispatch's line: its group
+ /// counts and the compute root arguments it was recorded with (root
+ /// constants as hex dwords, root views with the title buffer they
+ /// point into). A program that does not translate has no bindings to
+ /// list; these say which memory it would have read and written (the
+ /// ray-tracing structure builder passes its buffers this way).
+ #[cfg(feature = "diagnostics")]
+ fn list_dropped_roots(&self, groups: [u32; 3]) {
+ crate::capture::op(0, || {
+ use std::fmt::Write;
+ let [x, y, z] = groups;
+ let mut text = format!(" its roots ({x}x{y}x{z}):");
+ for (slot, root) in self.compute.iter().enumerate() {
+ match root {
+ Root::None => {}
+ Root::Table(a) => {
+ let _ = write!(text, " {slot}=table {a:#x}");
+ }
+ Root::Constants(v) => {
+ let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]);
+ }
+ Root::View(a) => {
+ let _ = write!(text, " {slot}=view {a:#x}");
+ match crate::shadow::extent(*a) {
+ Some((start, len)) => {
+ let _ = write!(text, " in buffer {start:#x}+{len:#x}");
+ }
+ None => text.push_str(" in no buffer"),
+ }
+ }
+ }
+ }
+ text
+ });
}
/// Runs a dispatch on the host.
pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
+ // It may write the arguments a window holds clamped.
+ self.window = None;
+ #[cfg(feature = "diagnostics")]
+ if crate::pipeline::is_skipped(self.pipeline as This) {
+ DROPPED.fetch_add(1, Ordering::Relaxed);
+ crate::pipeline::note_drop(self.pipeline as This);
+ return;
+ }
+ // The ray-tracing structure builder's stages run all or none.
+ if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
+ DROPPED.fetch_add(1, Ordering::Relaxed);
+ #[cfg(feature = "diagnostics")]
+ {
+ crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
+ self.list_dropped_roots([x, y, z]);
+ }
+ return;
+ }
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
once!(
pipeline = format_args!("{:#x}", self.pipeline),
"a dispatch without a host pipeline dropped"
);
DROPPED.fetch_add(1, Ordering::Relaxed);
+ #[cfg(feature = "diagnostics")]
+ {
+ crate::pipeline::note_drop(self.pipeline as This);
+ self.list_dropped_roots([x, y, z]);
+ }
return;
};
if !p.compute {
once!("a dispatch with a graphics pipeline");
return;
}
- self.bind(list, p, true);
+ if !self.bind(list, p, true) {
+ DROPPED.fetch_add(1, Ordering::Relaxed);
+ // A stage of the structure builder that cannot be bound is a
+ // dropped stage: the others stop too.
+ if crate::pipeline::is_builder(self.pipeline as This) {
+ crate::pipeline::builder_off("one of its dispatches could not be bound");
+ }
+ return;
+ }
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
// SAFETY: an open list with everything set.
@@ -519,6 +1800,32 @@ impl State {
return kind;
};
let mut text = format!("{kind} {}", p.name);
+ // What it draws into (a dispatch writes through its views below).
+ if !compute {
+ let described = |t: usize| {
+ crate::resource::host_made(t as This).map(|r| {
+ // SAFETY: a live resource.
+ let d = unsafe { r.GetDesc() };
+ format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)
+ })
+ };
+ let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect();
+ let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state);
+ // The title's scissor and viewport at this draw (the first of
+ // each): the title draws what it sees through a
+ // portal (a window, from inside a room) under the portal's
+ // rectangle, and the listing did not say which draws those are.
+ if let Some(r) = self.scissors.first() {
+ let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom);
+ }
+ if let Some(v) = self.viewports.first() {
+ let _ = write!(
+ text,
+ " viewport [{} {} {} {} depth {}..{}]",
+ v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth
+ );
+ }
+ }
let views = (self.heaps[0] != 0)
.then(|| crate::descriptor::heap(self.heaps[0] as This).host())
.flatten();
@@ -526,14 +1833,17 @@ impl State {
let t = stage.translated();
let _ = write!(text, " | {}:", stage.shader.hash);
for u in &t.host.user_data {
- let v = self.user_value(compute, u.slot, u.root, u.dword);
+ let v = match u.root {
+ RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None),
+ _ => self.user_value(compute, u.slot, u.root, u.dword),
+ };
let _ = write!(text, " u{}={v:#x}", u.index);
let index = if u.root == RootType::Table { v / 32 } else { v };
if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
let _ = write!(text, " [heap {index}: {slot}]");
}
}
- for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
+ for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) {
if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
let host = crate::shadow::find(*address, 1)
.map(|s| (s.gpu(*address), s.left(*address)));
@@ -545,18 +1855,37 @@ impl State {
text
}
+ /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
+ /// the scissors before it (`on`), the title's after it.
+ fn mesh_scissor(&self, list: &HostList, on: bool) {
+ if mesh_test() != 2 {
+ return;
+ }
+ if on {
+ let one = RECT { left: 0, top: 0, right: 1, bottom: 1 };
+ crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]);
+ } else if !self.scissors.is_empty() {
+ crate::draw::scissors(list, &self.scissors);
+ }
+ }
+
/// Runs a mesh dispatch of `x` groups on the host (the title's mesh
/// programs are one-dimensional).
pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
+ self.window = None;
#[cfg(feature = "diagnostics")]
self.trace("mesh", x, 0);
- let ran = self.prepare_for(list, false, true)
+ let ran = mesh_test() != 1
+ && mesh_kept(self.pipeline)
+ && self.prepare_for(list, false, true)
&& match list.list.cast::() {
Ok(l6) => {
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("mesh {x}"), false));
+ self.mesh_scissor(list, true);
// SAFETY: an open list with everything set.
unsafe { l6.DispatchMesh(x, 1, 1) };
+ self.mesh_scissor(list, false);
DRAWN.fetch_add(1, Ordering::Relaxed);
true
}
@@ -565,7 +1894,7 @@ impl State {
if !ran {
DROPPED.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
- dropped();
+ dropped(self.pipeline);
}
}
@@ -589,7 +1918,11 @@ impl State {
return;
};
if let Some(view) = host.mirror(index, handle, true) {
- readable(list, u, &view);
+ readable(list, u.kind, &view);
+ // Up to date by this draw: not the texture pass's to make.
+ if crate::descriptor::host::is_texture_view(&view) {
+ host.texture_slot_tabled(index, true);
+ }
}
}
@@ -604,7 +1937,13 @@ impl State {
/// once: its constant data is copied at submission either way, and the
/// big tables the world binds would otherwise take hundreds of slots per
/// draw, wrapping the dynamic slots onto lists not yet submitted.
- fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
+ pub(crate) fn tables(
+ &mut self,
+ list: &HostList,
+ used: &[UsedResource],
+ indexed: &[RootIndexedView],
+ compute: bool,
+ ) -> Vec<(u8, u32)> {
let tables = |u: &&UsedResource| u.root == RootType::Table;
let mut fresh: Vec = used
.iter()
@@ -612,6 +1951,27 @@ impl State {
.filter(|u| u.kind == ResourceType::Cbv)
.map(|u| u.slot)
.collect();
+ // Tables reaching past a host heap smaller than the title's (the
+ // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
+ // title's slots there have no host slot of their own.
+ for u in used.iter().filter(tables) {
+ if fresh.contains(&u.slot) {
+ continue;
+ }
+ let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
+ continue;
+ };
+ let end = table + u64::from(u.table_offset_dwords) * 4;
+ let Some(heap) = self.heap_of(table) else {
+ continue;
+ };
+ let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
+ continue;
+ };
+ if index >= host.count() {
+ fresh.push(u.slot);
+ }
+ }
fresh.sort_unstable();
fresh.dedup();
for u in used.iter().filter(tables) {
@@ -632,14 +1992,42 @@ impl State {
let Some(heap) = self.heap_of(table) else {
continue;
};
+ if heap.samplers() || (table - heap.start) % 32 != 0 {
+ continue;
+ }
let Some(host) = heap.host() else {
continue;
};
+ let mut selected: Vec = indexed
+ .iter()
+ .filter(|index| index.table_slot == slot)
+ .map(|index| {
+ let constant = self.user_value(
+ compute,
+ index.constant_slot,
+ RootType::Constants,
+ index.constant_dword,
+ );
+ // The shader adds i32 byte offsets and shifts by 5.
+ index.byte_offset.wrapping_add(constant << index.shift) / 32
+ })
+ .collect();
+ selected.sort_unstable();
+ selected.dedup();
let n = entries
.iter()
- .map(|u| u.table_offset_dwords / 8 + 1)
+ .map(|u| u.table_offset_dwords / 8)
+ .chain(selected.last().copied())
.max()
- .unwrap_or(1);
+ .unwrap_or(0)
+ + 1;
+ let last = table.checked_add(u64::from(n - 1) * 32);
+ if n > crate::descriptor::host::DYNAMIC
+ || last.and_then(|handle| heap.index(handle)).is_none()
+ {
+ once!(slot, n, "fresh descriptor table exceeds the available span");
+ continue;
+ }
// The table and what its entries hold (record words).
let key = {
use std::hash::{Hash, Hasher};
@@ -649,24 +2037,41 @@ impl State {
// SAFETY: a descriptor slot in title memory.
unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
}
- (table, h.finish())
+ (table, n, h.finish())
};
if let Some(&first) = self.fresh_tables.get(&key) {
for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
let handle = table + u64::from(u.table_offset_dwords) * 4;
if let Some(view) = crate::descriptor::view(handle) {
- readable(list, u, &view);
+ readable(list, u.kind, &view);
+ }
+ }
+ for k in selected {
+ if entries.iter().any(|u| u.table_offset_dwords / 8 == k) {
+ continue;
+ }
+ let handle = table + u64::from(k) * 32;
+ if let Some(view) = crate::descriptor::view(handle)
+ && let Some(kind) = view_kind(&view)
+ {
+ readable(list, kind, &view);
}
}
made.push((slot, first * 32));
continue;
}
let Some(first) = host.dynamic(n) else {
+ // No room: the draw must not run with the title's own
+ // offsets (slots never made for it); `bind` drops it.
+ made.push((slot, u32::MAX));
continue;
};
self.fresh_tables.insert(key, first);
self.dynamic
.push((std::ptr::from_ref(heap) as usize, first, n));
+ // The title's own slots of this table: what the draw reads of
+ // them it brings up to date here, in the dynamic slots.
+ let title_first = heap.index(table).filter(|first| first + n <= host.count());
// The whole range: a shader may index past the entries its
// used-resource list names (descriptor arrays).
for k in 0..n {
@@ -683,8 +2088,24 @@ impl State {
}
Some(view) => {
host.make_at(index, &view);
- if let Some(u) = used {
- readable(list, u, &view);
+ let kind = used.map(|u| u.kind).or_else(|| {
+ selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
+ });
+ if let Some(kind) = kind {
+ readable(list, kind, &view);
+ }
+ // The title's slot is a table's: out of the queue
+ // of textures picked by index if the draw read it
+ // (its texture is up to date now), and made in
+ // place as the texture pass would have made it,
+ // for a shader that picks it by index all the same.
+ if let Some(title) = title_first
+ && crate::descriptor::host::is_texture_view(&view)
+ {
+ host.texture_slot_tabled(title + k, kind.is_some());
+ if kind.is_some() {
+ host.mirror(title + k, table + u64::from(k) * 32, true);
+ }
}
}
None => {
@@ -713,7 +2134,7 @@ impl State {
let targets: Vec = self
.targets
.iter()
- .filter_map(|&t| crate::resource::host_resource(t as This))
+ .filter_map(|&t| crate::resource::host_made(t as This))
.map(|t| {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
@@ -774,10 +2195,14 @@ impl State {
first: u32,
first_instance: u32,
) {
+ self.window = None;
#[cfg(feature = "diagnostics")]
self.trace("draw", vertices, first);
- let rects = self.topology == RECTANGLES;
- let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
+ let ready = self.prepare(list, false);
+ // A pipeline with the rectangle geometry stage draws the title's
+ // vertices as they are; any other gets its rectangles expanded.
+ let rects = self.topology == RECTANGLES && !self.completes_rects();
+ let ran = ready && (!rects || self.rectangles(list, vertices, first));
if ran {
// Rectangles were expanded into their own vertex buffers.
let (count, from) = if rects {
@@ -797,10 +2222,16 @@ impl State {
if !ran {
DROPPED.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
- dropped();
+ dropped(self.pipeline);
}
}
+ /// Whether the bound pipeline completes rectangles itself, in the
+ /// geometry stage rectangle pipelines get (`HostPipeline::rects`).
+ fn completes_rects(&self) -> bool {
+ crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects)
+ }
+
/// Binds vertex buffers holding the rectangles of vertices `first..first
/// + count` as triangles, made when the list is submitted.
fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
@@ -835,6 +2266,10 @@ impl State {
let (from, to, stride) = (from as usize, to as usize, stride as usize);
let n = rects as usize;
list.defer_host(move || {
+ // The vertices are read in place, at submission: no change
+ // of mapping under the read (see
+ // `crate::watch::title_memory_reading`).
+ let _mapped = crate::watch::title_memory_reading();
// SAFETY: the vertices lie in a title buffer (checked when
// recorded) and the scratch memory is the list's.
let (src, dst) = unsafe {
@@ -865,12 +2300,16 @@ impl State {
base: i32,
first_instance: u32,
) {
+ self.window = None;
#[cfg(feature = "diagnostics")]
self.trace("indexed", indices, first);
- if self.topology == RECTANGLES {
+ // Indexed rectangles are drawn by the rectangle geometry stage
+ // alone (nothing expands them on the CPU).
+ let lost = self.topology == RECTANGLES && !self.completes_rects();
+ if lost {
once!("indexed rectangles not drawn");
}
- let ran = self.topology != RECTANGLES && self.prepare(list, true);
+ let ran = !lost && self.prepare(list, true);
if ran {
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
@@ -884,7 +2323,7 @@ impl State {
if !ran {
DROPPED.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
- dropped();
+ dropped(self.pipeline);
}
}
}
@@ -903,18 +2342,70 @@ impl State {
arguments: u64,
count: Option,
) -> bool {
+ // Skip before the argument clamp can mutate the indirect buffer.
+ #[cfg(feature = "diagnostics")]
+ if crate::pipeline::is_skipped(self.pipeline as This) {
+ crate::pipeline::note_drop(self.pipeline as This);
+ return false;
+ }
+ if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
+ return false;
+ }
const DRAW: u32 = 0;
const INDEXED: u32 = 1;
const DISPATCH: u32 = 2;
const MESH: u32 = 10;
+ #[cfg(feature = "diagnostics")]
+ let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
+ #[cfg(not(feature = "diagnostics"))]
+ let why = |_: &str| {};
+ let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
+ #[cfg(feature = "diagnostics")]
+ crate::pipeline::note_drop(self.pipeline as This);
+ return false;
+ };
+ // Indirect rectangles (the title's tiled lighting, 256
+ // indirect draws a frame, makes their corners from the vertex
+ // number) are completed by the pipeline's geometry stage: the
+ // arguments stay the title's, three vertices a rectangle. They
+ // cannot be expanded on the CPU, which does not know their count.
+ // shortcut: in a pipeline without that stage, a rectangle with no
+ // per-vertex inputs is drawn as its first triangle (three vertices,
+ // half of it), and one with vertex buffers is not drawn.
+ let made_rects = !p.rects
+ && kind == DRAW
+ && self.topology == RECTANGLES
+ && !p.inputs.iter().any(|e| !e.per_instance);
+ if made_rects {
+ once!("indirect rectangles without vertex inputs drawn as their first triangle");
+ }
+ let matches_kind = match kind {
+ DRAW | INDEXED => {
+ (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh
+ }
+ MESH => !p.compute && p.mesh,
+ DISPATCH => p.compute,
+ _ => false,
+ };
+ if !matches_kind {
+ why(&format!(
+ "pipeline mismatch (compute {}, mesh {}, topology {})",
+ p.compute, p.mesh, self.topology
+ ));
+ return false;
+ }
let len = u64::from(stride) * u64::from(max.max(1));
- let Some(args) = crate::shadow::find(arguments, len) else {
+ let Some(args) = crate::shadow::find_any(arguments, len) else {
+ why("arguments outside title buffers");
return false;
};
let counter = match count {
- Some(at) => match crate::shadow::find(at, 4) {
+ Some(at) => match crate::shadow::find_any(at, 4) {
Some(s) => Some((s, at)),
- None => return false,
+ None => {
+ why("count outside title buffers");
+ return false;
+ }
},
None => None,
};
@@ -922,51 +2413,128 @@ impl State {
.then(|| host_signature(kind, stride))
.flatten()
else {
+ why("no host signature");
return false;
};
- args.refresh(list, arguments, len);
- if let Some((s, at)) = &counter {
- s.refresh(list, *at, 4);
- }
- // Bounded first: the clamp binds a compute pipeline of its own.
- if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) {
+ if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) {
+ why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
return false;
}
- self.host_pipeline = 0;
- self.host_roots[1] = 0;
+ // A window of records clamped in one pass (`windows`): for single
+ // records without a count buffer, drawn by shaders that store to no
+ // buffer. Anything else ends the window: it uses the scratch buffer
+ // or may write the arguments.
+ const WINDOW_USE: usize = usize::MAX - 0x77;
+ let offset = args.offset(arguments);
+ let windowed = windows()
+ && kind != DISPATCH
+ && max == 1
+ && count.is_none()
+ && !p.stages.iter().any(|stage| stage.translated().stores);
+ // Another host list (a new one after a cut, or this one after its
+ // reset) has another scratch buffer, or this one's with old bytes.
+ if !windowed || list.first_use(WINDOW_USE) {
+ self.window = None;
+ }
+ let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride;
+ let hit = self
+ .window
+ .as_ref()
+ .filter(|w| same(w) && offset >= w.base)
+ .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
+ .map(|w| (w.scratch.clone(), offset - w.base));
+ let (bounded, at) = match hit {
+ Some(hit) => hit,
+ None => {
+ // A record a short step after the last window's last one
+ // (the same step as that window's, if it had one): the
+ // title walks the buffer, so the ones that step apart
+ // after it are clamped with it.
+ let (step, records) = match &self.window {
+ Some(w) if windowed && same(w) => {
+ let last = w.base + u64::from(w.records - 1) * u64::from(w.step);
+ let step = offset.saturating_sub(last);
+ let walks = step >= u64::from(stride)
+ && step <= 256
+ && step % 4 == 0
+ && (w.records == 1 || step == u64::from(w.step));
+ if walks {
+ let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32;
+ (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1))
+ } else {
+ (stride, max)
+ }
+ }
+ _ => (stride, max),
+ };
+ args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records)));
+ if let Some((s, at)) = &counter {
+ s.refresh(list, *at, 4);
+ }
+ // Bounded first: the clamp binds a compute pipeline of its
+ // own and copies clamped active records into a scratch
+ // buffer at offset 0.
+ let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
+ // More than the record asked for: a window clamped ahead,
+ // whose unfilled slots must not spend the list's budget.
+ let bounded = if windowed && records > 1 {
+ crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records))
+ } else {
+ crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records))
+ };
+ let Some(bounded) = bounded else {
+ self.window = None;
+ why("not bounded (no clamp, or arguments not 4-byte aligned)");
+ return false;
+ };
+ self.host_pipeline = 0;
+ self.host_roots[1] = 0;
+ self.window = windowed.then(|| Window {
+ copy: args.id(),
+ kind,
+ stride,
+ step,
+ base: offset,
+ records,
+ scratch: bounded.clone(),
+ });
+ (bounded, 0)
+ }
+ };
let ran = match kind {
- DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED),
+ DRAW | INDEXED => self.prepare(list, kind == INDEXED),
MESH => self.prepare_for(list, false, true),
- DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) {
- Some(p) if p.compute => {
- self.bind(list, p, true);
- true
- }
- _ => false,
- },
+ DISPATCH => self.bind(list, p, true),
_ => false,
};
if !ran {
- crate::indirect::done(list, &args.buffer);
+ crate::indirect::done(list, &bounded);
+ why("prepare failed");
return false;
}
#[cfg(feature = "diagnostics")]
list.note_op(|| {
self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
});
- // SAFETY: an open list with everything set; the buffers are host
- // copies the list keeps alive (refresh), the signature is cached.
+ if kind == MESH {
+ self.mesh_scissor(list, true);
+ }
+ // SAFETY: an open list with everything set; the scratch buffer and
+ // host copies are kept alive by the list, and the signature is cached.
unsafe {
list.list.ExecuteIndirect(
&signature,
max,
- &args.buffer,
- args.offset(arguments),
+ &bounded,
+ at,
counter.as_ref().map(|(s, _)| &s.buffer),
counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
)
};
- crate::indirect::done(list, &args.buffer);
+ if kind == MESH {
+ self.mesh_scissor(list, false);
+ }
+ crate::indirect::done(list, &bounded);
if kind == DISPATCH {
DISPATCHED.fetch_add(1, Ordering::Relaxed);
} else {
@@ -1016,30 +2584,89 @@ fn host_signature(kind: u32, stride: u32) -> Option {
/// Gets what a shader reads or writes through a view ready: buffer data
/// copied, textures moved to the state they need.
-fn readable(list: &HostList, u: &UsedResource, view: &View) {
- const SHADER_RESOURCE: u32 = 0x40 | 0x80;
+fn view_kind(view: &View) -> Option {
+ match view {
+ View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv),
+ View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav),
+ _ => None,
+ }
+}
+
+/// The host state a depth view needs of its texture: the read state if the
+/// view writes no plane the format has (the title's read-only flags), else
+/// the write state.
+/// shortcut: whole textures have one state, so a view that writes one of
+/// two planes counts as writing.
+fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 {
+ // D16_UNORM and D32_FLOAT: depth formats without a stencil plane.
+ const ONE_PLANE: [i32; 2] = [55, 40];
+ let Some(desc) = desc else {
+ return DEPTH_WRITE;
+ };
+ let format = if desc.Format.0 == 0 {
+ // SAFETY: a live texture; a view without a format has its own.
+ unsafe { texture.GetDesc() }.Format.0
+ } else {
+ desc.Format.0
+ };
+ let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0;
+ if !ONE_PLANE.contains(&format) {
+ needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0;
+ }
+ if desc.Flags.0 & needed == needed {
+ DEPTH_READ
+ } else {
+ DEPTH_WRITE
+ }
+}
+
+fn readable(list: &HostList, kind: ResourceType, view: &View) {
const UNORDERED_ACCESS: u32 = 0x8;
let placed = crate::descriptor::host::placed_texture(view);
let view = placed.as_ref().unwrap_or(view);
// Buffer views read title memory: their range is copied at submission;
// what shaders write through unordered access goes back to it after.
- if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
- && len > 0
- && let Some(shadow) = crate::shadow::find(address, len)
- {
+ if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) {
shadow.refresh(list, address, len);
- if u.kind == ResourceType::Uav {
- shadow.gpu_writes(list, address, len);
+ if kind == ResourceType::Uav {
+ // A shader that cannot store to buffers leaves the range as
+ // the title has it: nothing to find afterwards.
+ if STORES.get() || !write_skip() {
+ shadow.gpu_writes(list, address, len);
+ } else {
+ #[cfg(feature = "diagnostics")]
+ {
+ crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1);
+ crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len);
+ }
+ }
}
}
- match (view, u.kind) {
+ match (view, kind) {
(View::Shader(resource, _), ResourceType::Srv) => {
- if let Some(t) = crate::resource::host_resource(*resource as This)
+ // A view the title placed, in another format, in the memory of
+ // a texture the host writes: that texture's texels, copied on
+ // the host (title memory does not have them).
+ let aliased = crate::resource::alias_of(*resource as This)
+ .is_some_and(|source| crate::texture::alias(list, *resource as This, source));
+ if !aliased
+ && let Some(t) = crate::resource::host_resource(*resource as This)
&& crate::texture::title_written(t)
{
crate::texture::upload(list, *resource as This, t);
}
- crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
+ // A depth texture shaders also write: what they wrote, first.
+ list.twin_use(*resource as This, false, false);
+ // The depth target the draw only tests is read in both ways at
+ // once: both read states, which its preparation asks for too.
+ let (tested, _) = TESTED_DEPTH.get();
+ let state = if tested != 0 && tested == *resource {
+ TESTED_DEPTH.set((tested, true));
+ DEPTH_READ | SHADER_RESOURCE
+ } else {
+ SHADER_RESOURCE
+ };
+ crate::list::ensure_state(list, *resource as This, state);
#[cfg(feature = "diagnostics")]
if let Some(t) = crate::resource::host_resource(*resource as This) {
// SAFETY: a live resource.
@@ -1056,7 +2683,10 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) {
(View::Unordered(resource, _, _), ResourceType::Uav) => {
#[cfg(feature = "diagnostics")]
crate::capture::note_target(*resource as This);
- crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
+ // Unordered access to a depth texture is its colour twin's.
+ if !list.twin_use(*resource as This, true, true) {
+ crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
+ }
}
_ => {}
}
@@ -1066,17 +2696,23 @@ fn readable(list: &HostList, u: &UsedResource, view: &View) {
#[cfg(feature = "diagnostics")]
fn describe(view: Option<&View>) -> String {
let texture = |r: This| {
- crate::resource::host_resource(r).map(|t| {
+ crate::resource::host_made(r).map(|t| {
// SAFETY: a live resource.
let d = unsafe { t.GetDesc() };
- format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
+ format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0)
})
};
match view {
None => "no view".into(),
Some(v @ View::Shader(r, _)) => texture(*r as This)
.unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
- Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
+ Some(v @ View::Unordered(r, ..)) => match texture(*r as This) {
+ Some(t) => format!("uav texture {t}"),
+ None => format!(
+ "uav resource {r:#x} buffer {:?}",
+ crate::descriptor::host::buffer_range(v)
+ ),
+ },
Some(View::Placed(u, r, d)) => format!(
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
r[0],
@@ -1122,6 +2758,8 @@ pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
}
pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
+ #[cfg(feature = "diagnostics")]
+ crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}"));
// SAFETY: an open list.
unsafe { list.list.OMSetStencilRef(reference) };
}
diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs
index 1ce11c7c3b..af1022705f 100644
--- a/crates/victory-gpu/src/dxgi.rs
+++ b/crates/victory-gpu/src/dxgi.rs
@@ -92,7 +92,7 @@ fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut Thi
/// The DXGI device also answers for the D3D12 device.
extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
- if object::is(iid, &[crate::device::IID]) {
+ if crate::device::is_device(iid) {
return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out);
}
query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out)
@@ -219,7 +219,28 @@ struct Mode {
}
const _: () = assert!(size_of::() == 32);
-/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks
+/// The size of the display the console reports: `VICTORY_DISPLAY_MODE=WxH`
+/// if set (as a console reports the television it is plugged into: a
+/// Series X on a 1080p set lists a 1080p mode), else 3840x2160.
+/// shortcut: not yet the host display's own size by default; make it so
+/// once a title is seen to render for the mode it is given.
+fn display_size() -> (u32, u32) {
+ static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new();
+ *SIZE.get_or_init(|| {
+ let asked = std::env::var("VICTORY_DISPLAY_MODE").ok().and_then(|v| {
+ let (w, h) = v.trim().split_once(['x', 'X'])?;
+ Some((w.trim().parse::().ok()?, h.trim().parse::().ok()?))
+ });
+ let size = match asked {
+ Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h),
+ _ => (3840, 2160),
+ };
+ tracing::info!(width = size.0, height = size.1, "display mode reported to the title");
+ size
+ })
+}
+
+/// The console's mode list: one 4K mode at 60 Hz (the title looks
/// for a 120 Hz one to allow 120 Hz frame intervals).
/// shortcut: fixed mode, not the host display's; report the host's rates if
/// a title paces by them.
@@ -242,9 +263,10 @@ extern "system" fn modes(
return MORE_DATA;
}
*count = 1;
+ let (width, height) = display_size();
let mode = Mode {
- width: 3840,
- height: 2160,
+ width,
+ height,
refresh: [60, 1],
format: 0,
scanlines: 1, // progressive
diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs
index 285e7bddfa..98daa899ba 100644
--- a/crates/victory-gpu/src/fence.rs
+++ b/crates/victory-gpu/src/fence.rs
@@ -75,7 +75,7 @@ extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT
extern "system" fn release(this: This) -> u32 {
object::release_boxed::(this)
}
-extern "system" fn completed(this: This) -> u64 {
+pub(crate) extern "system" fn completed(this: This) -> u64 {
fence(this).value.load(Ordering::Acquire)
}
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
@@ -88,6 +88,19 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
return S_OK;
}
if event.is_null() {
+ // With submissions sent to the card and not waited for
+ // (`crate::host::late`) the signal may be behind them: they are
+ // settled, which sets it.
+ #[cfg(windows)]
+ if crate::host::late() {
+ drop(waiters);
+ crate::host::settle_for_fence();
+ if fence.value.load(Ordering::Acquire) >= value {
+ return S_OK;
+ }
+ tracing::warn!(value, "blocking fence wait not implemented");
+ return E_NOTIMPL;
+ }
// shortcut: a null event means "block until reached"; nothing can
// reach it while no GPU work runs, so fail instead of hanging.
tracing::warn!(value, "blocking fence wait not implemented");
@@ -96,7 +109,8 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c
waiters.push((value, event as usize));
S_OK
}
-pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
+/// Moves the fence to `value` and sets the events that waited for it.
+pub(crate) fn set(this: This, value: u64) {
let fence = fence(this);
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
fence.value.store(value, Ordering::Release);
@@ -107,6 +121,12 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
}
!reached
});
+}
+pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
+ set(this, value);
+ // A queue may have waited for it: what it held runs now.
+ #[cfg(windows)]
+ crate::queue::release_held(false);
S_OK
}
@@ -162,7 +182,7 @@ mod tests {
// SAFETY: as above.
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
- // Grand Theft Auto VI reads the value at the fence's address.
+ // The title reads the value at the fence's address.
let at = slot:: u64>(f, 0x60)(f);
// SAFETY: the fence's value.
assert_eq!(unsafe { *(at as *const u64) }, 5);
diff --git a/crates/victory-gpu/src/frame.rs b/crates/victory-gpu/src/frame.rs
index 837dfbce18..798b760690 100644
--- a/crates/victory-gpu/src/frame.rs
+++ b/crates/victory-gpu/src/frame.rs
@@ -2,7 +2,7 @@
//! to begin. Ours is a clock started by the first interval set, ticking
//! once per interval; the token is the frame number. Each event kind
//! (origin, vblank, flip) happens once per tick, so two waits for the same
-//! kind never end on the same tick: Grand Theft Auto VI polls the origin
+//! kind never end on the same tick: the title polls the origin
//! with "token on time-out" (starting its next frame at once) and is paced
//! by a blocking wait for the flip before each present.
//!
@@ -126,8 +126,22 @@ pub(crate) extern "system" fn wait(
token: *mut u64,
) -> HRESULT {
let origin = kind == ORIGIN;
- let (tick, wait) = next_tick(kind);
+ let (mut tick, mut wait) = next_tick(kind);
let limit = Duration::from_millis(u64::from(timeout_ms));
+ // A blocking wait for an event that has happened since the last wait
+ // for it ended (a frame took longer than a tick) ends at once, on the
+ // tick that passed: sleeping on to the next one cost 17 ms of every
+ // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a
+ // time-out shorter than a tick) answer as before.
+ // `VICTORY_LATE_WAITS=1` sleeps to the next tick, as before.
+ static SLEEP: std::sync::OnceLock = std::sync::OnceLock::new();
+ if !*SLEEP.get_or_init(|| std::env::var_os("VICTORY_LATE_WAITS").is_some_and(|v| v == "1"))
+ && limit >= wait
+ && tick > last(kind).load(Ordering::Relaxed) + 1
+ {
+ tick -= 1;
+ wait = Duration::ZERO;
+ }
let hr = if wait > limit {
std::thread::sleep(limit);
TIMEOUT
@@ -136,6 +150,12 @@ pub(crate) extern "system" fn wait(
last(kind).fetch_max(tick, Ordering::Relaxed);
S_OK
};
+ #[cfg(all(windows, feature = "diagnostics"))]
+ {
+ use crate::copystat::{C, add};
+ add(C::PaceWaits, 1);
+ add(C::PaceUs, wait.min(limit).as_micros() as u64);
+ }
// A frame begun on a time-out takes no tick: its flip still does.
if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
// Tokens count frames (consecutive), not ticks.
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 51c7b47726..e073616b54 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -1,7 +1,8 @@
//! The host GPU: one D3D12 device and direct queue (decision 0007), and a
//! window to present on.
//!
-//! shortcut: every submission is waited for, so CPU and GPU never overlap;
+//! shortcut: every submission is waited for, so CPU and GPU never overlap
+//! (unless `VICTORY_LATE_WAIT=1`, see [`late`]);
//! overlap them with per-submission fences once more than clears run.
use std::sync::atomic::{AtomicU32, Ordering};
@@ -53,6 +54,9 @@ pub(crate) struct Host {
messages: Option,
next_rtv: AtomicU32,
presenter: Mutex>,
+ /// The adapter the device is on, for its memory budget
+ /// ([`Host::video_memory`]); `None` if the system does not name it.
+ adapter: Option,
}
// SAFETY: D3D12 devices, queues, fences and descriptor heaps are
@@ -61,6 +65,277 @@ unsafe impl Send for Host {}
// SAFETY: as above.
unsafe impl Sync for Host {}
+/// Host objects the title let go of while a submission may still use them
+/// (a texture its descriptors name, a descriptor slot's old resource), by
+/// the submission count they wait for. The title's descriptor writes and
+/// releases reach the host at once, from its own threads, while the host
+/// runs a submission: freeing there is a GPU page fault on the freed
+/// texture (a device hang).
+static RETIRED: Mutex> = Mutex::new(Vec::new());
+/// Submissions started and finished (waited for).
+static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// A retired object, dropped on whatever thread finishes the submission.
+struct Retired(#[allow(dead_code)] Box);
+// SAFETY: what is retired is D3D12 objects (free-threaded) and the
+// reference-counted wrappers holding them, dropped once.
+unsafe impl Send for Retired {}
+
+/// Milliseconds since the first call.
+pub(crate) fn now_ms() -> u64 {
+ static EPOCH: OnceLock = OnceLock::new();
+ EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
+}
+
+/// This moment, for telling later how long ago it was ([`long_ago`]): the
+/// frames begun so far (high half, `crate::frame::current`) and tenths of a
+/// second since the start. Host copies of title memory, staging buffers and
+/// host textures note when they were last used with it.
+pub(crate) fn moment() -> u64 {
+ (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff)
+}
+
+/// Whether `moment` lies at least `ms` milliseconds and `frames` frames
+/// back. Both: at seconds per frame, what every frame uses is not touched
+/// for seconds, and at many frames per second not for many frames. (A title
+/// that never waits for frames has no frame count: nothing is then idle.)
+pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool {
+ let now = self::moment();
+ let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff);
+ (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms
+}
+
+/// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`.
+pub(crate) fn available_physical_ram() -> Option {
+ use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
+ // SAFETY: plain data the call fills in.
+ let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
+ m.dwLength = std::mem::size_of::() as u32;
+ // SAFETY: a sized structure.
+ let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0;
+ ok.then_some(m.ullAvailPhys)
+}
+
+/// Effective idle timeout (in milliseconds) for VRAM-backed host textures,
+/// scaled down under VRAM pressure. Never returns less than 1,000 ms so
+/// handles not yet recorded into a list or slot remain protected.
+pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 {
+ const NORMAL_MS: u64 = 5_000;
+ const MODERATE_MS: u64 = 2_500;
+ const HIGH_MS: u64 = 1_000;
+ let Some([budget, used, ..]) = video_memory else {
+ return NORMAL_MS;
+ };
+ if budget == 0 {
+ return NORMAL_MS;
+ }
+ let used_pct = (u128::from(used) * 100) / u128::from(budget);
+ if used_pct >= 85 {
+ HIGH_MS
+ } else if used_pct >= 75 {
+ MODERATE_MS
+ } else {
+ NORMAL_MS
+ }
+}
+
+/// Effective idle timeout (in milliseconds) for system-RAM caches (staging
+/// buffers, loose shadows, and the mapped pipeline library), scaled down
+/// when free physical RAM is low. Never returns less than 2,000 ms.
+pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 {
+ const GIB: u64 = 1024 * 1024 * 1024;
+ const NORMAL_MS: u64 = 10_000;
+ const MODERATE_MS: u64 = 5_000;
+ const HIGH_MS: u64 = 2_000;
+ let Some(avail) = avail_phys else {
+ return NORMAL_MS;
+ };
+ if avail < 2 * GIB {
+ HIGH_MS
+ } else if avail < 4 * GIB {
+ MODERATE_MS
+ } else {
+ NORMAL_MS
+ }
+}
+
+/// How many references are held on a host object (its COM count): ours
+/// all, since the host's views and commands hold none. A buffer or texture
+/// with one is held by its owner alone: no descriptor slot keeps it
+/// (`HostHeap::kept`) and no list (`HostList::keep`).
+pub(crate) fn references(object: &impl Interface) -> u32 {
+ type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32;
+ let raw = object.as_raw();
+ // SAFETY: a live COM object, whose first three methods are those of
+ // `IUnknown` (query, add a reference, release one); the pair leaves the
+ // count as it was, and the release returns it. The first is not called.
+ unsafe {
+ let methods = *raw.cast::<*const [Method; 3]>();
+ ((*methods)[1])(raw);
+ ((*methods)[2])(raw)
+ }
+}
+
+/// Once a second, before a submission starts: lets go of what nothing
+/// names any more (copies of windows of title memory, staging buffers,
+/// host copies of textures the title fills).
+/// `VICTORY_SWEEP=0` keeps everything, as before.
+fn sweep() {
+ // The in-place probe and census, if asked for (`VICTORY_INPLACE_PROBE`).
+ crate::inplace::tick();
+ static ON: OnceLock = OnceLock::new();
+ if !*ON.get_or_init(|| std::env::var_os("VICTORY_SWEEP").is_none_or(|v| v != "0")) {
+ return;
+ }
+ static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+ let now = now_ms();
+ let last = LAST.load(Ordering::Relaxed);
+ if now < last + 1000
+ || LAST
+ .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed)
+ .is_err()
+ {
+ return;
+ }
+ crate::pipeline::trim_library();
+ crate::shadow::let_go_idle();
+ crate::texture::let_go_idle();
+ crate::resource::let_go_idle();
+}
+
+/// Drops `object` once every submission running now has finished: at once
+/// if none is.
+pub(crate) fn retire(object: T) {
+ let started = STARTED.load(Ordering::Acquire);
+ if started <= FINISHED.load(Ordering::Acquire) {
+ RETIREMENTS[0].fetch_add(1, Ordering::Relaxed);
+ drop(object);
+ return;
+ }
+ RETIREMENTS[1].fetch_add(1, Ordering::Relaxed);
+ RETIRED
+ .lock()
+ .unwrap_or_else(|e| e.into_inner())
+ .push((started, Retired(Box::new(object))));
+}
+
+/// Drops what waited for submissions up to `finished`.
+fn bury(finished: u64) {
+ let done: Vec<(u64, Retired)> = {
+ let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
+ if retired.is_empty() {
+ return;
+ }
+ let (done, keep) = std::mem::take(&mut *retired)
+ .into_iter()
+ .partition(|(at, _)| *at <= finished);
+ *retired = keep;
+ done
+ };
+ drop(done);
+}
+
+/// Objects [`retire`] dropped at once (no submission was running) and
+/// kept until a running submission finished, since the start.
+static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// What the layer did to the host's objects lately, newest last (sweeps
+/// that let host copies go, pipeline library calls, saves and trims): said
+/// once when the host device is removed ([`log_removal_context`]), with
+/// what the submitting thread and the pipeline workers were doing at that
+/// moment. A device the driver removes "internally" names no command, and
+/// the pass that happens to notice first names only the view it was at:
+/// the three such losses of runs 72, 73 and 82 each came within 5 ms of a
+/// pipeline library call that no line of the log tied to them.
+/// `VICTORY_TRAIL=0`: nothing is kept and nothing is said.
+static TRAIL: Mutex> = Mutex::new(std::collections::VecDeque::new());
+/// The entries kept.
+const TRAIL_MOST: usize = 96;
+
+fn trail_on() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_TRAIL").is_none_or(|v| v != "0"))
+}
+
+/// Microseconds since the first call.
+pub(crate) fn now_us() -> u64 {
+ static EPOCH: OnceLock = OnceLock::new();
+ EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64
+}
+
+/// The calling thread, as the log's other lines name threads.
+pub(crate) fn thread_id() -> u32 {
+ // SAFETY: a plain query.
+ unsafe { windows::Win32::System::Threading::GetCurrentThreadId() }
+}
+
+/// Notes something done to the host's objects ([`TRAIL`]); `what` is only
+/// run when the trail is kept.
+pub(crate) fn trail(what: impl FnOnce() -> String) {
+ if !trail_on() {
+ return;
+ }
+ let entry = (now_us(), thread_id(), what());
+ let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
+ if trail.len() >= TRAIL_MOST {
+ trail.pop_front();
+ }
+ trail.push_back(entry);
+}
+
+/// What the submitting thread is doing (0 nothing: between submissions,
+/// 1 preparing one, 2 waiting for the card to run it, 3 copying back what
+/// it wrote), the lists of that submission, and since when ([`now_us`]).
+static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+fn submitting(phase: u64, lists: usize) {
+ SUBMITTING[1].store(lists as u64, Ordering::Relaxed);
+ SUBMITTING[2].store(now_us(), Ordering::Relaxed);
+ SUBMITTING[0].store(phase, Ordering::Relaxed);
+}
+
+/// What was going on when the host device went: whether a submission was
+/// on the card, the pipeline library's state and the calls running in it,
+/// and the trail.
+pub(crate) fn removal_context() -> String {
+ use std::fmt::Write;
+ let now = now_us();
+ let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0;
+ let phase = match SUBMITTING[0].load(Ordering::Relaxed) {
+ 0 => "between submissions (nothing of ours was running on the card)",
+ 1 => "preparing a submission (nothing of ours was running on the card)",
+ 2 => "waiting for the card to run a submission",
+ _ => "copying back what a submission wrote (nothing of ours was running on the card)",
+ };
+ let mut text = format!(
+ "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}",
+ SUBMITTING[1].load(Ordering::Relaxed),
+ ms(SUBMITTING[2].load(Ordering::Relaxed)),
+ crate::pipeline::library_removal_note(),
+ RETIREMENTS[0].load(Ordering::Relaxed),
+ RETIREMENTS[1].load(Ordering::Relaxed),
+ STARTED.load(Ordering::Relaxed),
+ FINISHED.load(Ordering::Relaxed),
+ );
+ let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner());
+ let _ = write!(text, "; the last {} things done, newest last:", trail.len());
+ for (at, thread, what) in trail.iter() {
+ let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at));
+ }
+ text
+}
+
+/// Says [`removal_context`] in the log, once: called by whoever finds the
+/// host device removed.
+pub(crate) fn log_removal_context() {
+ static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+ if !trail_on() || SAID.swap(true, Ordering::Relaxed) {
+ return;
+ }
+ tracing::error!("when the host device went: {}", removal_context());
+}
+
/// Time spent in submissions since the last frame-rate line, in
/// microseconds: preparing them on the CPU (title memory copies, texture
/// detiling), then waiting for the GPU.
@@ -73,6 +348,103 @@ static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
[std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
+/// The card's clock, for the frame line of every run, in microseconds since
+/// the last one: how long the card had nothing of ours queued; how much of
+/// that while the thread that holds the submission lock was working (the
+/// card idle behind us: preparing and copying back are done with the card
+/// standing); and how long that thread stood waiting for the card.
+///
+/// Every send of lists to the queue is followed by a signal on a fence of
+/// the clock's own ([`Host::card_sent`]). A thread of the clock waits for
+/// the newest signal and notes the moment the card reached it with nothing
+/// newer sent; the next send ends that idle stretch.
+static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+/// Of the thread that holds the submission lock: the microseconds it has
+/// worked so far (preparing, copying back; not its waits for the card), and
+/// since when it works now ([`now_us`] plus one; 0: it does not).
+static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// The thread that holds the submission lock starts (`on`) or stops
+/// working; whether it worked until now.
+fn working(on: bool) -> bool {
+ let now = now_us() + 1;
+ let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed);
+ if since != 0 {
+ WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed);
+ }
+ since != 0
+}
+
+/// [`WORKING`] as of now: microseconds worked so far.
+fn worked() -> u64 {
+ let since = WORKING[1].load(Ordering::Relaxed);
+ let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 };
+ WORKING[0].load(Ordering::Relaxed) + now
+}
+
+/// The thread that holds the submission lock stood waiting for the card
+/// from `since` until now ([`CARD_CLOCK_US`]).
+fn stood(since: std::time::Instant) {
+ CARD_CLOCK_US[2].fetch_add(since.elapsed().as_micros() as u64, Ordering::Relaxed);
+}
+
+/// What [`CARD_CLOCK_US`] is measured with.
+struct CardClock {
+ fence: ID3D12Fence,
+ /// Signals sent so far; and, while the card has reached the last of
+ /// them, since when and what [`worked`] said then.
+ state: Mutex<(u64, Option<(std::time::Instant, u64)>)>,
+ sent: std::sync::Condvar,
+}
+
+// SAFETY: a fence (free-threaded) behind a lock.
+unsafe impl Send for CardClock {}
+// SAFETY: as above.
+unsafe impl Sync for CardClock {}
+
+/// The clock's thread: waits for the newest signal sent and notes when the
+/// card got there with nothing newer behind it.
+fn card_clock_watch(clock: &'static CardClock) {
+ // SAFETY: a plain event of our own.
+ let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else {
+ return;
+ };
+ let mut seen = 0;
+ loop {
+ let target = {
+ let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
+ while state.0 == seen {
+ state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner());
+ }
+ state.0
+ };
+ // SAFETY: the clock's fence and this thread's event.
+ unsafe {
+ if clock.fence.SetEventOnCompletion(target, event).is_ok() {
+ WaitForSingleObject(event, INFINITE);
+ }
+ }
+ seen = target;
+ let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner());
+ if state.0 == target && state.1.is_none() {
+ state.1 = Some((std::time::Instant::now(), worked()));
+ }
+ }
+}
+
+/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the
+/// frame's time.
+fn card_clock_line(frames: f64, ms: f64) {
+ let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames);
+ tracing::info!(
+ "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \
+ {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \
+ had not submitted; the submitting thread stood waiting for the card {stood:.1} ms",
+ if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 }
+ );
+}
+
/// Of the preparing: title memory copies (microseconds, bytes) and texture
/// refreshes (microseconds, bytes hashed), since the last frame-rate line.
pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
@@ -82,6 +454,48 @@ pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
std::sync::atomic::AtomicU64::new(0),
];
+/// Host buffers made since the start, as (count, bytes): in the upload heap
+/// (staging, list scratch), shared with the processor (host copies of title
+/// memory) and the graphics card's own (indirect arguments, twins' copies).
+/// For the memory line: against what is alive, they show what was let go.
+pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
+
+/// What of that is alive now, for the memory line (`MADE` counts what was
+/// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60,
+/// and nothing said how many were alive): host lists; the lists' scratch
+/// chunks and their bytes; of those, the chunks no list holds (kept for the
+/// next list, [`Spare`]) and their bytes; chunks taken from those kept
+/// instead of made, since the start; and the lists' other upload buffers
+/// (texture data copied from buffers, scratch too big for a chunk) and
+/// their bytes.
+pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8];
+
+/// About host lists, for the memory line: lists made by the host since the
+/// start; preludes made (a list's second allocator and list, made when it
+/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the
+/// bytes the process's private memory grew by while lists were being made
+/// (what a list costs: host objects with the driver's command memory; 631
+/// lists were alive in run 65, each with a prelude it may never use).
+/// Then the lists alive that were never reset since they were made: the
+/// host sides of title lists the title made and has not used (a host list
+/// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title
+/// makes at its start).
+pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
+
+/// The process's private bytes (diagnostics: around the making of lists).
+#[cfg(feature = "diagnostics")]
+fn private_bytes() -> u64 {
+ use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
+ use windows_sys::Win32::System::Threading::GetCurrentProcess;
+ let mut c = PROCESS_MEMORY_COUNTERS {
+ cb: size_of::() as u32,
+ ..Default::default()
+ };
+ // SAFETY: our own process and a sized structure.
+ unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
+ c.PagefileUsage as u64
+}
+
/// What the runtime does when the host GPU fails for good: report it like a
/// crash and end the run. The console has no such state, and carrying on
/// draws nothing at seconds per frame.
@@ -101,6 +515,7 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
// SAFETY: a plain query.
if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
text.push_str(&format!("; device removed: {e}"));
+ log_removal_context();
}
match host.log_messages() {
Some(first) => text.push_str(&format!("; debug layer: {first}")),
@@ -111,6 +526,9 @@ pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
}
}
tracing::error!("{text}");
+ // Tests have no log: the reason goes to their output.
+ #[cfg(test)]
+ eprintln!("host GPU failure: {text}");
match ON_FAILURE.get() {
Some(report) => report(&text),
None => std::process::abort(),
@@ -177,14 +595,42 @@ fn create() -> windows::core::Result {
// is an access violation in this process (a crash report with the
// address and instruction) instead of a GPU fault and driver reset.
if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
- let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
- let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
+ let adapter = warp_adapter()?;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
tracing::info!("host device on the software adapter (WARP)");
} else {
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
}
let device = device.ok_or_else(windows::core::Error::empty)?;
+ // `VICTORY_D3D12_BACKGROUND=0`: the runtime's background work (the
+ // driver compiling shaders again on the "D3D Background Thread"s,
+ // for minutes after pipelines were made or loaded) is switched off.
+ // An experiment: while those threads ran, the same shot took
+ // 1,000-1,200 ms a frame, and 830-950 ms from the moment they
+ // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default:
+ // whether the card is slower with the shaders it then keeps is not
+ // known.
+ if std::env::var_os("VICTORY_D3D12_BACKGROUND").is_some_and(|v| v == "0")
+ && let Ok(device6) = device.cast::()
+ {
+ let set = device6.SetBackgroundProcessingMode(
+ D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK,
+ D3D12_MEASUREMENTS_ACTION_KEEP_ALL,
+ None,
+ None,
+ );
+ tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (VICTORY_D3D12_BACKGROUND=0)");
+ }
+ // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose
+ // cross-lane code stays in 32-lane halves translated for waves of 32
+ let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
+ if device
+ .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32)
+ .is_ok()
+ {
+ tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
+ victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
+ }
let messages = debug
.then(|| device.cast::().ok())
.flatten();
@@ -208,6 +654,9 @@ fn create() -> windows::core::Result {
..Default::default()
})?;
let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
+ let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0))
+ .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid()))
+ .ok();
tracing::info!("host D3D12 device ready");
Ok(Host {
device,
@@ -223,10 +672,98 @@ fn create() -> windows::core::Result {
messages,
next_rtv: AtomicU32::new(0),
presenter: Mutex::new(None),
+ adapter,
})
}
}
+/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
+/// Reject it before creating a device in diagnostics' software-only mode.
+fn warp_adapter() -> windows::core::Result {
+ // SAFETY: plain DXGI adapter queries.
+ unsafe {
+ let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
+ let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
+ let desc = adapter.cast::()?.GetDesc1()?;
+ if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
+ tracing::warn!(
+ vendor = format_args!("{:#x}", desc.VendorId),
+ flags = format_args!("{:#x}", desc.Flags),
+ "DXGI did not identify the WARP adapter as software; refusing device"
+ );
+ return Err(windows::core::Error::from_hresult(
+ windows::Win32::Foundation::E_FAIL,
+ ));
+ }
+ Ok(adapter)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn sparse_copies_preserve_islands_and_observe_remaps() {
+ use windows_sys::Win32::System::Memory::*;
+ const N: usize = 5 << 16;
+ // SAFETY: we reserve a private region, commit selected pages inside it,
+ // and only directly access the pages while they are writable.
+ unsafe {
+ let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::();
+ assert!(!base.is_null());
+ let mut expected = vec![0; N];
+ for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] {
+ let at = base.add(offset);
+ assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
+ at.write_bytes(value, 4096);
+ expected[offset..offset + 4096].fill(value);
+ }
+ for remap in [false, true] {
+ if remap {
+ let mut old = 0;
+ assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0);
+ expected[..4096].fill(0);
+ let at = base.add(1 << 16);
+ assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast());
+ at.write_bytes(0xc7, 4096);
+ expected[1 << 16..(1 << 16) + 4096].fill(0xc7);
+ }
+ let mut out = vec![0xee; N];
+ super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false);
+ assert_eq!(out[27..N - 27], expected[27..N - 27]);
+ assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee));
+ }
+ assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
+ }
+ }
+
+ use super::*;
+
+ #[test]
+ fn warp_adapter_accepts_only_software() {
+ // This probes DXGI without creating a D3D12 device or running a title.
+ // SAFETY: plain DXGI adapter queries.
+ let raw = unsafe {
+ let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0))
+ else {
+ return;
+ };
+ factory.EnumWarpAdapter::()
+ };
+ let Ok(raw) = raw else { return };
+ // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements
+ // IDXGIAdapter1; `raw` owns that interface.
+ let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() };
+ eprintln!(
+ "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
+ desc.VendorId, desc.Flags
+ );
+ assert_eq!(
+ warp_adapter().is_ok(),
+ desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
+ );
+ }
+}
+
/// A host command list and its allocator, always used together.
pub(crate) struct HostList {
allocator: ID3D12CommandAllocator,
@@ -243,19 +780,50 @@ pub(crate) struct HostList {
/// list names alive until it is reset, even if the title releases the
/// resource first.
states: Mutex,
- /// The list that runs those transitions just before this one.
- prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
+ /// What the list does with depth textures that have a colour twin, by
+ /// twin ([`TwinUse`]).
+ twins: Mutex>,
+ /// The list that runs those transitions just before this one, made
+ /// when the list first has such transitions ([`lazy_prelude`]).
+ prelude: OnceLock>,
/// The pipelines the list binds, for reports of slow submissions.
pipelines: Mutex>,
/// The work its indirect executions may still do (`indirect`): a
/// shader-writable word, zeroed when the list is submitted.
budget: OnceLock>,
+ /// Device-local scratch buffer for clamped indirect arguments (`indirect`),
+ /// grown to the largest indirect execution recorded on the list.
+ indirect_args: Mutex >,
+ /// Counts the list in [`ALIVE`] while it lives.
+ _alive: Counted,
/// The texts of the markers `note_op` set, in order (for device-removed
/// data without marker texts), with the host GPU range a copy reads.
#[cfg(feature = "diagnostics")]
notes: Mutex>,
+ /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
+ /// and at the end, and where they are read back.
+ #[cfg(feature = "diagnostics")]
+ stamps: OnceLock>,
+}
+
+/// A list's prelude: an allocator and a closed list.
+type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList);
+
+/// Whether a host list's prelude is made when the list first needs one. A
+/// prelude runs the texture transitions and twin copies a list needs before
+/// it; lists that name no texture never have one, and every host list was
+/// made with one all the same: twice the host objects per list, for the
+/// title's 630 lists and for every list made anew.
+/// `VICTORY_LAZY_PRELUDE=0`: made with the list, as before.
+fn lazy_prelude() -> bool {
+ static ON: OnceLock = OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_PRELUDE").is_none_or(|v| v != "0"))
}
+/// Timestamps per list (diagnostics); commands past them are not timed.
+#[cfg(feature = "diagnostics")]
+const STAMPS: u32 = 4096;
+
/// A marker's text and the host range its command reads (diagnostics).
#[cfg(feature = "diagnostics")]
type Note = (String, Option<(u64, u64)>);
@@ -265,6 +833,429 @@ type States = std::collections::HashMap<
(u32, u32, std::sync::Arc),
>;
+/// What a list does with a depth texture that has a colour twin
+/// ([`crate::resource::Twin`]). Lists are recorded on many threads and run
+/// in submission order, so a list cannot know which side an earlier list
+/// leaves behind: it notes which sides it uses as it finds them, and its
+/// prelude copies one side into the other at submission if that side is
+/// behind then. From its first use of a side on, the list knows.
+struct TwinUse {
+ /// The depth texture (the title resource's host copy) and its twin.
+ depth: std::sync::Arc,
+ twin: std::sync::Arc,
+ /// The sides (depth texture, twin) the list uses as it finds them.
+ needs: [bool; 2],
+ /// Whether each side lacks what the other was written last, where the
+ /// list is now; `None`: as the list found it.
+ behind: [Option; 2],
+ /// The draw or dispatch being prepared writes the twin.
+ writing: bool,
+ /// The depth plane's twin holds what the plane lacks although the list
+ /// copied the twins since: the plane's pass waits for the list's close.
+ late: bool,
+}
+
+/// The pass that draws the twin of a depth plane into the plane: one
+/// triangle over each mip of each slice, its pixel shader writing the
+/// twin's texel as the depth, with the depth test "always" and no stencil
+/// (the stencil plane is copied through a buffer and not touched here).
+///
+/// A 16-bit twin holds whole steps of 1/65535, and the depth written is
+/// the step times the float nearest 1/65535 (0x37800080). That is how
+/// The title's tiled lighting computes the depth of the
+/// rectangles it then draws with the test "equal", one class of materials
+/// a draw (all six of its vertex shaders multiply the class number by that
+/// constant), so the pass and the draw give the host the same float, and
+/// the host turns the same float into the same 24 bits. The step divided
+/// by 65535 is another float for 512 of the 65,536 steps (none under 257),
+/// and lands in another 24-bit step for 127 of them (none under 385).
+const PLANE_CORNERS: &str = r#"
+float4 corner(uint i : SV_VertexID) : SV_Position {
+ return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0);
+}
+"#;
+const PLANE_STEPS: &str = r#"
+#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
+Texture2DArray twin : register(t0);
+[RootSignature(RS)]
+float plane(float4 p : SV_Position) : SV_Depth {
+ return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080);
+}
+"#;
+const PLANE_FLOATS: &str = r#"
+#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)"
+Texture2DArray twin : register(t0);
+[RootSignature(RS)]
+float plane(float4 p : SV_Position) : SV_Depth {
+ return twin.Load(int4(int2(p.xy), 0, 0));
+}
+"#;
+
+/// Views of twins the pass reads, in a heap of ours used as a ring.
+/// shortcut: a view must last until its list has run; with one or two
+/// passes a frame the ring is far from coming round.
+const PLANE_VIEWS: u32 = 256;
+
+/// What the pass draws with: the heap of its views of twins, and per kind
+/// of twin (16-bit steps or floats) and depth format the root signature
+/// and pipeline, made when first needed (`None`: the host refused).
+struct PlanePass {
+ views: ID3D12DescriptorHeap,
+ cpu: usize,
+ gpu: u64,
+ step: u32,
+ next: AtomicU32,
+ made: Mutex)>>,
+}
+
+/// The pass's root signature and pipeline for one kind of twin and one
+/// depth format.
+type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState);
+
+// SAFETY: D3D12 objects are free-threaded.
+unsafe impl Send for PlanePass {}
+// SAFETY: as above.
+unsafe impl Sync for PlanePass {}
+
+fn plane_pass() -> Option<&'static PlanePass> {
+ static PASS: OnceLock> = OnceLock::new();
+ PASS.get_or_init(|| {
+ let host = host()?;
+ let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ // SAFETY: plain heap creation and queries.
+ unsafe {
+ let views: ID3D12DescriptorHeap = host
+ .device
+ .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
+ Type: kind,
+ NumDescriptors: PLANE_VIEWS,
+ Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
+ NodeMask: 0,
+ })
+ .ok()?;
+ Some(PlanePass {
+ cpu: views.GetCPUDescriptorHandleForHeapStart().ptr,
+ gpu: views.GetGPUDescriptorHandleForHeapStart().ptr,
+ step: host.device.GetDescriptorHandleIncrementSize(kind),
+ views,
+ next: AtomicU32::new(0),
+ made: Mutex::default(),
+ })
+ }
+ })
+ .as_ref()
+}
+
+/// Compiles function `entry` of `source` for `target` with the system's
+/// compiler, as the indirect-argument clamp is (`crate::indirect`).
+pub(crate) fn compile(
+ source: &str,
+ entry: windows::core::PCSTR,
+ target: windows::core::PCSTR,
+) -> windows::core::Result> {
+ use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
+ use windows::Win32::Graphics::Direct3D::ID3DBlob;
+ let mut code: Option = None;
+ let mut errors: Option = None;
+ // SAFETY: the source and names live through the call; out pointers ours.
+ let compiled = unsafe {
+ D3DCompile(
+ source.as_ptr().cast(),
+ source.len(),
+ windows::core::s!("victory"),
+ None,
+ None,
+ entry,
+ target,
+ 0,
+ 0,
+ &mut code,
+ Some(&mut errors),
+ )
+ };
+ if let Err(e) = compiled {
+ if let Some(errors) = errors {
+ // SAFETY: the blob's own bytes.
+ let text = unsafe {
+ std::slice::from_raw_parts(
+ errors.GetBufferPointer().cast::(),
+ errors.GetBufferSize(),
+ )
+ };
+ tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text));
+ }
+ return Err(e);
+ }
+ let code = code.ok_or_else(windows::core::Error::empty)?;
+ // SAFETY: the blob's own bytes.
+ let bytes = unsafe {
+ std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize())
+ };
+ Ok(bytes.to_vec())
+}
+
+impl PlanePass {
+ /// The root signature and pipeline for a twin of 16-bit steps (`steps`)
+ /// or of floats and the depth format `format`.
+ fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option {
+ let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) {
+ return pipeline.clone();
+ }
+ let pipeline = match Self::make(steps, format) {
+ Ok(pipeline) => Some(pipeline),
+ Err(e) => {
+ tracing::warn!(
+ error = %e,
+ steps,
+ format = format.0,
+ "no pipeline to draw a depth plane from its twin: such planes stay as they are"
+ );
+ None
+ }
+ };
+ made.push((steps, format.0, pipeline.clone()));
+ pipeline
+ }
+
+ fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result