Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ The on/off switches below (`...=1`) are off when unset or set to `0`.
| `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight |
| `VICTORY_SKIP_PIPELINES=<hash>,...` | 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; a device removal names the list it happened in and lists all its commands |
| `VICTORY_TRACE_SHADERS=<hash>,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500) |
| `VICTORY_TRACE_SHADERS=<hash>,...` | with `VICTORY_D3D12_DRED`, every draw and dispatch of a listed shader logged with what it binds (user data, heap slots, root views and their first dwords; the first 500, and all of them in listed capture frames); the records of its indirect executions are read back and logged in every frame (records with work, the first four, the frame) |
| `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) |
| `VICTORY_PIPELINE_LOG=<file>` | a line per title pipeline created (key, shaders, state), first used, and made or loaded (library name); `translate --cache --pipelines` writes the last kind too |
| `VICTORY_PREBUILD_KEYS=<file>` | `translate --cache --pipelines` makes nothing and lists each pack record's key, shaders and state (or why it is skipped) |
Expand Down
7 changes: 5 additions & 2 deletions apps/victory/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ pub fn run(
// Before the import registry is first used: it holds the module only
// when the host's FidelityFX serves.
victory_hle::modules::fidelityfx::use_host_dir(cfg.fidelityfx_dir.as_deref());
let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
let prepared = victory_loader::prepare(&original)?;
let prepared = victory_loader::prepare(
&std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?,
)?;
let hash = prepared.original_hash.to_hex();
let title_dir = exe.parent().unwrap_or(Path::new("."));
match victory_game::identify(&hash) {
Expand All @@ -82,6 +83,8 @@ pub fn run(
}
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
let image = victory_loader::load(&prepared, &images)?;
// Mapped: the patched bytes (the exe's size, 114 MB) are not needed.
drop(prepared);
victory_hle::runtime::set_main_image(image.base());
victory_hle::runtime::set_image_path(image.base(), exe);
println!(
Expand Down
6 changes: 4 additions & 2 deletions crates/victory-gpu/src/capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,7 @@ pub(crate) fn read_indirect(
count: Option<(&ID3D12Resource, u64)>,
(kind, stride, max): (u32, u32, u32),
name: String,
always: bool,
) {
struct Readback(ID3D12Resource);
// SAFETY: D3D12 objects are free-threaded.
Expand Down Expand Up @@ -488,7 +489,8 @@ pub(crate) fn read_indirect(
let counted = count.is_some();
list.defer_after(move || {
// Recorded ahead: logged if the frame running it is listed.
if !listed(crate::queue::presented() + 1) {
let frame = crate::queue::presented() + 1;
if !always && !listed(frame) {
return;
}
let mut data = std::ptr::null_mut();
Expand All @@ -513,7 +515,7 @@ pub(crate) fn read_indirect(
let shown: Vec<&[u32]> = (0..records.min(4)).map(first).collect();
tracing::info!(
target: "victory_gpu::trace",
"indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name}"
"indirect kind {kind} max {max} count {n:?}: {busy} of {records} records with work, {total} in all; first {shown:?} {name} frame {frame}"
);
buffer.0.Unmap(0, None);
});
Expand Down
161 changes: 148 additions & 13 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1705,12 +1705,17 @@ impl State {
counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
)
};
// A listed frame: what the records held (after the clamp).
// A listed frame, or any frame for a traced shader: what the records
// held (after the clamp).
#[cfg(feature = "diagnostics")]
if crate::capture::dump_on() {
let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
let name = crate::pipeline::shaders_of(pipeline);
crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name);
{
let always = !crate::host::traced_shaders().is_empty()
&& crate::host::is_traced(&crate::pipeline::shaders_of(pipeline));
if always || crate::capture::dump_on() {
let count = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
let name = crate::pipeline::shaders_of(pipeline);
crate::capture::read_indirect(list, (&args.buffer, args.offset(arguments)), count, (kind, stride, max), name, always);
}
}
crate::indirect::done(list, &args.buffer);
if kind == DISPATCH {
Expand Down Expand Up @@ -2022,6 +2027,128 @@ void main(uint3 id : SV_DispatchThreadID) {
}
}

/// Which pixels of a 64x64 host D32S8 `texture` (title texture `depth`)
/// pass an EQUAL depth test against a square (two triangles, as the
/// title's rectangles become) drawn over pixel `k - 1` (row by row) with
/// z = k times the title's 1/65535 (`0x37800080`), the depth
/// `VS_TiledLighting` gives draw k: entry `k - 1`.
fn equal_test_passes(depth: This, texture: &ID3D12Resource) -> Vec<bool> {
use windows::Win32::Graphics::Dxgi::Common::*;
const SOURCE: &str = r#"
#define RS "RootFlags(0)"
static const float2 CORNERS[6] = { float2(0, 0), float2(1, 0), float2(0, 1), float2(1, 0), float2(1, 1), float2(0, 1) };
[RootSignature(RS)]
float4 vs(uint v : SV_VertexID) : SV_Position {
uint i = v / 6;
float2 p = float2(i % 64, i / 64) + CORNERS[v % 6];
return float4(p.x / 32.0 - 1.0, 1.0 - p.y / 32.0, (float)(i + 1) * asfloat(0x37800080), 1.0);
}
uint ps() : SV_Target { return 1; }
"#;
let host = crate::host::host().unwrap();
let blob = |entry: windows::core::PCSTR, target: windows::core::PCSTR| {
let mut code: Option<ID3DBlob> = None;
// SAFETY: the source and names outlive the call.
unsafe { D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("equal"), None, None, entry, target, 0, 0, &mut code, None) }.unwrap();
code.unwrap()
};
let (vs, ps) = (blob(s!("vs"), s!("vs_5_1")), blob(s!("ps"), s!("ps_5_1")));
// SAFETY: the blobs' own bytes.
let bytes = |b: &ID3DBlob| unsafe { D3D12_SHADER_BYTECODE { pShaderBytecode: b.GetBufferPointer(), BytecodeLength: b.GetBufferSize() } };
// SAFETY: a compiled shader with its root signature inside.
let root: ID3D12RootSignature = unsafe {
host.device.CreateRootSignature(0, std::slice::from_raw_parts(vs.GetBufferPointer().cast::<u8>(), vs.GetBufferSize()))
}
.unwrap();
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
// SAFETY: borrowed for the call.
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
VS: bytes(&vs),
PS: bytes(&ps),
SampleMask: u32::MAX,
PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
NumRenderTargets: 1,
DSVFormat: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
desc.RTVFormats[0] = DXGI_FORMAT_R32_UINT;
desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf;
desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
desc.RasterizerState.DepthClipEnable = true.into();
desc.DepthStencilState.DepthEnable = true.into();
desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO;
desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_EQUAL;
// SAFETY: a complete description.
let pso: ID3D12PipelineState = unsafe { host.device.CreateGraphicsPipelineState(&desc) }.unwrap();
let target_desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 64,
Height: 64,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT_R32_UINT,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
..Default::default()
};
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let mut target: Option<ID3D12Resource> = None;
// SAFETY: plain creation.
unsafe {
host.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_RENDER_TARGET, None, &mut target)
}
.unwrap();
let target = target.unwrap();
let mut f = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
let mut total = 0;
// SAFETY: outputs for one subresource.
unsafe { host.device.GetCopyableFootprints(&target_desc, 0, 1, 0, Some(&mut f), None, None, Some(&mut total)) };
let (raw, data) = host.shared_buffer(total).unwrap();
let list = host.new_list().unwrap();
crate::list::ensure_state(&list, depth, 0x10);
let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
..Default::default()
};
let (rtv, dsv) = (host.rtv(&target, None), host.dsv(texture, Some(&dsv)));
// SAFETY: an open list; the target in the render target state, the
// depth texture in the depth write state; copies into our buffer.
unsafe {
let l = &list.list;
l.ClearRenderTargetView(rtv, &[0.0; 4], None);
l.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv));
l.RSSetViewports(&[D3D12_VIEWPORT { Width: 64.0, Height: 64.0, MaxDepth: 1.0, ..Default::default() }]);
l.RSSetScissorRects(&[windows::Win32::Foundation::RECT { right: 64, bottom: 64, ..Default::default() }]);
l.SetGraphicsRootSignature(&root);
l.SetPipelineState(&pso);
l.IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
l.DrawInstanced(64 * 64 * 6, 1, 0, 0);
l.ResourceBarrier(&[crate::host::transition(&target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&raw),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: f },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&target),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
l.CopyTextureRegion(&to, 0, 0, 0, &from, None);
}
list.close();
host.execute(&[&list]);
(0..64 * 64)
.map(|i| {
// SAFETY: inside the mapped buffer, by the footprint.
unsafe { (data.add(f.Offset as usize + (i / 64) * f.Footprint.RowPitch as usize + (i % 64) * 4) as *const u32).read() == 1 }
})
.collect()
}

/// A title buffer of `bytes` in memory of its own.
fn buffer(bytes: u64) -> This {
let desc: [u32; 14] = [1, 0, 0, 0, bytes as u32, (bytes >> 32) as u32, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
Expand Down Expand Up @@ -2300,11 +2427,11 @@ void main(uint3 id : SV_DispatchThreadID) {
}

/// A depth texture with stencil (the console's 16-bit depth, the
/// host's 24-bit) written through unordered views of its planes, then
/// read as depth and stencil: the 16-bit depth arrives in 24 bits as
/// the host converts the same value, the stencil as written. Rendered
/// as depth (a clear), then used through the unordered view: back in
/// 16 bits.
/// host's 32-bit float) written through unordered views of its planes,
/// then read as depth and stencil: the 16-bit depth arrives as the
/// float the title's shaders compute for it, the stencil as written,
/// and a draw at that depth passes an EQUAL test. Rendered as depth (a
/// clear), then used through the unordered view: back in 16 bits.
#[test]
fn a_depth_texture_written_through_unordered_views_reads_as_depth() {
let Some(host) = crate::host::host() else {
Expand Down Expand Up @@ -2391,7 +2518,8 @@ void main(uint3 id : SV_DispatchThreadID) {
}
list.close();
host.execute(&[&list]);
let d24 = |u: u32| u * 256 + (u * 255 + 32767) / 65535;
// The title's float for 16-bit value u (its 1/65535 is 0x37800080).
let float = |u: u32| (u as f32 * f32::from_bits(0x3780_0080)).to_bits();
for (x, y) in [(0usize, 0usize), (5, 0), (63, 2), (17, 40), (63, 63)] {
let k = (1 + x + 64 * y) as u32;
// SAFETY: inside the mapped buffers.
Expand All @@ -2406,15 +2534,22 @@ void main(uint3 id : SV_DispatchThreadID) {
raw_data.add(f[1].Offset as usize + y * f[1].Footprint.RowPitch as usize + x).read(),
)
};
assert_eq!(word & 0xff_ffff, d24(k), "24-bit depth at {x},{y}");
assert_eq!(word, float(k), "depth at {x},{y}");
assert_eq!(u32::from(byte), ((x ^ y) & 0xff) as u32);
}
// Tested EQUAL against a point at the depth the title's tiled
// lighting gives value k (k times its 1/65535), as the console's
// 16-bit depth passes it for every k. In 24-bit depth on the RX 6700
// XT only k = 258 of 1..=4096 passed.
let passed = equal_test_passes(depth, &copy.texture);
let failed: Vec<u32> = (1..=4096).filter(|&k| !passed[k as usize - 1]).collect();
assert!(failed.is_empty(), "EQUAL fails at {failed:?}");
// Rendered as depth (a clear of both planes), then used through
// the unordered view: copied to the twin, converted back.
list.reset();
crate::list::ensure_state(&list, depth, 0x10);
let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D24_UNORM_S8_UINT,
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
..Default::default()
};
Expand Down
58 changes: 52 additions & 6 deletions crates/victory-gpu/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,17 @@ fn last(kind: u32) -> &'static AtomicU64 {
&LAST[(kind as usize).min(LAST.len() - 1)]
}

/// The next tick after now and after the last one a wait for `kind` took
/// (an event happens once per tick: a wait woken a little early must not
/// let the next one end on the same tick), and how long until it. A wait
/// that comes within `limit` takes the tick here, under the clock's lock,
/// so two threads waiting for one kind never take the same tick.
/// The tick a wait for `kind` ends on, and how long until it: the first
/// one after the last a wait for `kind` took (an event happens once per
/// tick: a wait woken a little early must not let the next one end on the
/// same tick), the latest one passed if that is later. A wait begun after
/// its tick passed (a frame slower than the interval) so ends at once, as
/// an event signalled at the tick and left signalled until a wait takes it
/// would (assumed: nothing we have says what a late wait does); waiting for
/// the next tick instead cost the cutscene's frames 0-33 ms each (4 % of
/// the frame thread, run perf3). A wait that
/// comes within `limit` takes the tick here, under the clock's lock, so two
/// threads waiting for one kind never take the same tick.
fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) {
let mut clock = clock();
let fps = fps_limit();
Expand All @@ -253,7 +259,7 @@ fn next_tick(kind: u32, limit: Duration) -> (u64, Duration) {
let elapsed = c.start.elapsed().as_nanos();
let interval = interval.as_nanos().max(1);
let tick =
(c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
(c.first + (elapsed / interval) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
let at = u128::from(tick - c.first) * interval;
let wait = Duration::from_nanos(at.saturating_sub(elapsed) as u64);
if wait <= limit {
Expand Down Expand Up @@ -368,6 +374,13 @@ pub(crate) extern "system" fn wait(
if kind == FLIP && hr == S_OK {
FLIPS.fetch_add(1, Ordering::Relaxed);
}
#[cfg(feature = "diagnostics")]
{
WAITS[0].fetch_add(1, Ordering::Relaxed);
if hr == S_OK && wait.is_zero() {
WAITS[1].fetch_add(1, Ordering::Relaxed);
}
}
// 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.
Expand Down Expand Up @@ -395,6 +408,29 @@ pub(crate) extern "system" fn wait(
hr
}

/// Diagnostics: frame waits, and those that ended at once (their tick had
/// passed); presents whose flip tick was the previous present's.
#[cfg(feature = "diagnostics")]
static WAITS: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
#[cfg(feature = "diagnostics")]
static PRESENT_TICK: AtomicU64 = AtomicU64::new(0);

/// Diagnostics: a frame was presented (counts presents sharing a flip tick).
#[cfg(feature = "diagnostics")]
pub(crate) fn presented() {
let flip = LAST[2].load(Ordering::Relaxed);
if flip != 0 && PRESENT_TICK.swap(flip, Ordering::Relaxed) == flip {
WAITS[2].fetch_add(1, Ordering::Relaxed);
}
}

/// Diagnostics: logs [`WAITS`] since the last call.
#[cfg(feature = "diagnostics")]
pub(crate) fn log() {
let [waits, at_once, shared] = [0, 1, 2].map(|i| WAITS[i].swap(0, Ordering::Relaxed));
tracing::info!("frame waits: {waits}, {at_once} of them ended at once; presents sharing a flip tick: {shared}");
}

/// Device method: refreshes monotonic frame statistics and reports 0 console
/// records until the console's frame-statistics output struct layout is
/// verified (avoiding unverified writes into caller-owned `out`).
Expand Down Expand Up @@ -486,6 +522,16 @@ mod tests {
// Even when a flip wait begins on the tick another just ended on.
let (tick, _) = next_tick(FLIP, Duration::ZERO);
assert!(tick > flips[3]);
// A flip wait begun after its tick passed (two ticks missed) ends at
// once, on the latest tick passed; the next one waits for the next.
std::thread::sleep(Duration::from_millis(110));
let before = Instant::now();
assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK);
assert!(before.elapsed() < Duration::from_millis(10), "{:?}", before.elapsed());
let late = LAST[2].load(Ordering::Relaxed);
assert!(late >= flips[3] + 2, "{late} after {}", flips[3]);
assert_eq!(wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), S_OK);
assert_eq!(LAST[2].load(Ordering::Relaxed), late + 1);

// Uncapped override (Some(0)): even with a 30 FPS title interval,
// waits return immediately and still advance frames and flips.
Expand Down
Loading
Loading