Run Grand Theft Auto VI from first boot into the world
The title now boots through every first-boot and menu screen at its own 30 fps, drawing with translated shaders, with input, sound, saves and loading served; it reaches the world, where the host GPU path still fails (see "Not working yet"). Loader and runtime - Crash reports unwind properly, name C++ throws and host GPU failures, carry the title's last debug lines and are appended to crashes.log. - Thread notices on our own threads, reentrant late DLL loading, exit in the console's order, relaunch on a launch-new-game request. - Offline guard: the title cannot reach the network (sockets, name lookups, WinHTTP, the media source resolver); by-name lookups and loads follow the import rules. - Every runtime area the title calls is served (networking hint, packages, store, saves, display, UI, speech stubs, user, async pool). Saves persist; an update is one rename and survives a kill at any step. - DirectStorage reads for real: shared worker pool, priorities, zlib and BCPack. BCPack is our own decoder; the format's constant tables ship in crates/victory-formats/src/bcpack-tables.bin (the asset policy's one exception, see docs/asset-policy.md). - GameInput from XInput pads and the keyboard, with a keyboard stand-in pad; console timers (1 ms) for the whole process. - Audio: XMA2 decoding on the emulated contexts, Opus on the decoder queues, the DSP interface as a stub; title memory placed below 2^40. - Console texture layouts (sizes, tiling, detiling) and the layout library's imports. GPU - Draws, mesh dispatches and compute dispatches run on the host with shaders translated at first use and cached on disk; descriptor heaps, views, root signatures, barriers and host texture states; rectangle lists; comparison samplers. - Title memory reaches the host through persistent mirrors that copy only pages written since the last copy; shader-written buffers are copied back. - Presentation with frame pacing per event kind; framerate in the window caption. Shaders - DXIL emission for vertex, pixel, compute and mesh programs from the console's native code, with a differential test suite against the PC compile. World set: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539; utility set complete. Build - Debugging aids (debug logs, frame capture, stack dumps, scripted keys, the host debug layer, the software adapter) exist only with the `diagnostics` feature; `[profile.diag]` keeps that build apart. Not working yet - In the world the host device is removed within seconds (descriptor handling fixes are in, unproven by a surviving run) and frames present black. - 64-bit image atomics, merged geometry stages and the BVH builder's own shaders do not translate; reverb is silent. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
bc3070991a
commit
2849477415
107 files changed
+42526
-868
No files matched your search
@@ -8,13 +8,26 @@ license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
blake3.workspace = true
|
||||
miniz_oxide.workspace = true
|
||||
tracing.workspace = true
|
||||
anyhow.workspace = true
|
||||
victory-formats.workspace = true
|
||||
victory-pipeline.workspace = true
|
||||
victory-shader.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[features]
|
||||
# Debugging switches (frame capture, the host debug layer, per-draw data).
|
||||
diagnostics = []
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] }
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
//! Presented frames written to PNG files, to see what reaches the screen:
|
||||
//! with `VICTORY_CAPTURE=<folder>`, every frame whose number is a power of
|
||||
//! two (the frames the log reports) is saved as `frame-<n>.png`, at half
|
||||
//! size. Only in builds with diagnostics.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
|
||||
/// The folder frames go to, if capturing.
|
||||
pub(crate) fn folder() -> Option<&'static PathBuf> {
|
||||
static FOLDER: std::sync::OnceLock<Option<PathBuf>> = std::sync::OnceLock::new();
|
||||
FOLDER
|
||||
.get_or_init(|| std::env::var_os("VICTORY_CAPTURE").map(PathBuf::from))
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// Frames listed in `VICTORY_CAPTURE_FRAMES` (comma-separated): saved
|
||||
/// too, and their draws traced at debug level.
|
||||
pub(crate) fn listed(n: u64) -> bool {
|
||||
static LIST: std::sync::OnceLock<Vec<u64>> = std::sync::OnceLock::new();
|
||||
LIST.get_or_init(|| {
|
||||
let list = std::env::var("VICTORY_CAPTURE_FRAMES").unwrap_or_default();
|
||||
list.split(',')
|
||||
.filter_map(|f| f.trim().parse().ok())
|
||||
.collect()
|
||||
})
|
||||
.contains(&n)
|
||||
}
|
||||
|
||||
/// Whether frame `n` is saved.
|
||||
pub(crate) fn wanted(n: u64) -> bool {
|
||||
folder().is_some() && (n.is_power_of_two() || listed(n))
|
||||
}
|
||||
|
||||
/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`.
|
||||
pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
|
||||
save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows);
|
||||
}
|
||||
|
||||
/// Saves 8-bit RGBA or BGRA rows as `<name>.png`, at half size.
|
||||
fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) {
|
||||
let Some(folder) = folder() else { return };
|
||||
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
|
||||
// Filter byte 0 per row, then RGB of every other pixel of every other row.
|
||||
let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize);
|
||||
for y in 0..h as usize {
|
||||
raw.push(0);
|
||||
let row = &rows[(2 * y).min(height as usize - 1) * pitch..];
|
||||
for x in 0..w as usize {
|
||||
let p = &row[(2 * x).min(width as usize - 1) * 4..][..3];
|
||||
if bgra {
|
||||
raw.extend([p[2], p[1], p[0]]);
|
||||
} else {
|
||||
raw.extend_from_slice(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let mut header = Vec::new();
|
||||
header.extend(w.to_be_bytes());
|
||||
header.extend(h.to_be_bytes());
|
||||
header.extend([8, 2, 0, 0, 0]); // 8-bit RGB
|
||||
chunk(&mut png, b"IHDR", &header);
|
||||
chunk(
|
||||
&mut png,
|
||||
b"IDAT",
|
||||
&miniz_oxide::deflate::compress_to_vec_zlib(&raw, 3),
|
||||
);
|
||||
chunk(&mut png, b"IEND", &[]);
|
||||
let path = folder.join(format!("{name}.png"));
|
||||
match std::fs::write(&path, png) {
|
||||
Ok(()) => tracing::info!(path = %path.display(), "frame saved"),
|
||||
Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"),
|
||||
}
|
||||
}
|
||||
|
||||
fn chunk(png: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
png.extend((data.len() as u32).to_be_bytes());
|
||||
let start = png.len();
|
||||
png.extend(kind);
|
||||
png.extend(data);
|
||||
let crc = crc32(&png[start..]);
|
||||
png.extend(crc.to_be_bytes());
|
||||
}
|
||||
|
||||
fn crc32(bytes: &[u8]) -> u32 {
|
||||
let mut crc = !0u32;
|
||||
for &b in bytes {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg());
|
||||
}
|
||||
}
|
||||
!crc
|
||||
}
|
||||
|
||||
/// Records a copy of `texture` (in the copy-source state) into a
|
||||
/// readback buffer.
|
||||
pub(crate) fn read_back(
|
||||
device: &ID3D12Device,
|
||||
list: &ID3D12GraphicsCommandList,
|
||||
texture: &ID3D12Resource,
|
||||
) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> {
|
||||
let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
|
||||
let mut total = 0;
|
||||
// SAFETY: a live texture; outputs for one subresource.
|
||||
unsafe {
|
||||
let desc = texture.GetDesc();
|
||||
device.GetCopyableFootprints(
|
||||
&desc,
|
||||
0,
|
||||
1,
|
||||
0,
|
||||
Some(&mut footprint),
|
||||
None,
|
||||
None,
|
||||
Some(&mut total),
|
||||
);
|
||||
}
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_READBACK,
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: total,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
..Default::default()
|
||||
};
|
||||
let mut buffer: Option<ID3D12Resource> = None;
|
||||
// SAFETY: plain creation; an open list; locations naming live resources.
|
||||
unsafe {
|
||||
device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
None,
|
||||
&mut buffer,
|
||||
)
|
||||
.ok()?;
|
||||
let buffer = buffer?;
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(&buffer),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: footprint,
|
||||
},
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(texture),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
SubresourceIndex: 0,
|
||||
},
|
||||
};
|
||||
list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
|
||||
Some((buffer, footprint))
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves a frame read back by [`read_back`] (8-bit color only).
|
||||
pub(crate) fn save_read_back(
|
||||
frame: u64,
|
||||
buffer: &ID3D12Resource,
|
||||
footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
|
||||
) {
|
||||
let f = footprint.Footprint;
|
||||
let bgra = match f.Format {
|
||||
DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false,
|
||||
DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true,
|
||||
other => {
|
||||
tracing::warn!(format = other.0, "frame not saved: not 8-bit color");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: the copy finished (every submission is waited for); the
|
||||
// mapping spans the footprint's rows.
|
||||
unsafe {
|
||||
if buffer.Map(0, None, Some(&mut data)).is_err() {
|
||||
return;
|
||||
}
|
||||
let len = f.RowPitch as usize * f.Height as usize;
|
||||
let rows = std::slice::from_raw_parts(data.cast::<u8>(), len);
|
||||
save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows);
|
||||
buffer.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// With `VICTORY_DUMP_TARGETS` set: title textures the frames listed in
|
||||
/// `VICTORY_CAPTURE_FRAMES` render to or write, in first-use order, saved
|
||||
/// at that frame's present as `frame-<n>-<i>-<resource>-<w>x<h>-f<format>.png`
|
||||
/// (what each holds at the end of the frame; formats normalized to show
|
||||
/// structure: floats scaled by their largest value, depth by its range).
|
||||
static TARGETS: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
fn dump_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| folder().is_some() && std::env::var_os("VICTORY_DUMP_TARGETS").is_some())
|
||||
}
|
||||
|
||||
/// Notes a title texture the frame being built renders to or writes.
|
||||
pub(crate) fn note_target(resource: crate::object::This) {
|
||||
if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) {
|
||||
return;
|
||||
}
|
||||
let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !targets.contains(&(resource as usize)) {
|
||||
targets.push(resource as usize);
|
||||
}
|
||||
}
|
||||
|
||||
/// At the present of frame `frame`: saves the noted targets.
|
||||
pub(crate) fn dump_targets(frame: u64) {
|
||||
let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
for (i, &resource) in targets.iter().enumerate() {
|
||||
let resource = resource as crate::object::This;
|
||||
let Some(texture) = crate::resource::host_resource(resource) else {
|
||||
continue;
|
||||
};
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D {
|
||||
continue;
|
||||
}
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
let Some(before) = crate::resource::host_transition(resource, COPY_SOURCE).map(|(_, b)| b)
|
||||
else {
|
||||
dump_one(host, texture, COPY_SOURCE, frame, i, resource, &d);
|
||||
continue;
|
||||
};
|
||||
dump_one(host, texture, before, frame, i, resource, &d);
|
||||
crate::resource::host_transition(resource, before);
|
||||
}
|
||||
}
|
||||
|
||||
fn dump_one(
|
||||
host: &crate::host::Host,
|
||||
texture: &ID3D12Resource,
|
||||
state: u32,
|
||||
frame: u64,
|
||||
i: usize,
|
||||
resource: crate::object::This,
|
||||
d: &D3D12_RESOURCE_DESC,
|
||||
) {
|
||||
let Ok(list) = host.new_list() else { return };
|
||||
let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32);
|
||||
let copy = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
// SAFETY: an open list of ours and a live texture.
|
||||
let read = unsafe {
|
||||
if state != copy {
|
||||
list.list
|
||||
.ResourceBarrier(&[crate::host::transition(texture, state, copy)]);
|
||||
}
|
||||
let read = read_back(&host.device, &list.list, texture);
|
||||
if state != copy {
|
||||
list.list
|
||||
.ResourceBarrier(&[crate::host::transition(texture, copy, state)]);
|
||||
}
|
||||
read
|
||||
};
|
||||
list.close();
|
||||
host.execute(&[&list]);
|
||||
let Some((buffer, footprint)) = read else { return };
|
||||
let f = footprint.Footprint;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: the copy finished; the mapping spans the footprint's rows.
|
||||
unsafe {
|
||||
if buffer.Map(0, None, Some(&mut data)).is_err() {
|
||||
return;
|
||||
}
|
||||
let pitch = f.RowPitch as usize;
|
||||
let rows = std::slice::from_raw_parts(data.cast::<u8>(), pitch * f.Height as usize);
|
||||
if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) {
|
||||
let name = format!(
|
||||
"frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}",
|
||||
d.Width, d.Height, d.Format.0
|
||||
);
|
||||
save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba);
|
||||
} else {
|
||||
tracing::info!(format = f.Format.0, ?resource, "target not dumped: format");
|
||||
}
|
||||
buffer.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
|
||||
fn half(h: u16) -> f32 {
|
||||
let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
|
||||
let v = match exp {
|
||||
0 => man * 2f32.powi(-24),
|
||||
31 => f32::INFINITY,
|
||||
e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
|
||||
};
|
||||
if sign == 1 { -v } else { v }
|
||||
}
|
||||
|
||||
/// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits
|
||||
/// (the 11- and 10-bit floats of R11G11B10).
|
||||
fn small_float(bits: u32, man: u32) -> f32 {
|
||||
let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32);
|
||||
match exp {
|
||||
0 => m / (1 << man) as f32 * 2f32.powi(-14),
|
||||
31 => f32::INFINITY,
|
||||
e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else
|
||||
/// as channel values scaled so the largest finite one is white (single
|
||||
/// channels: lowest black, highest white, as grey). `None` for formats not
|
||||
/// handled.
|
||||
fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(w * h * 4);
|
||||
let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n];
|
||||
let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]);
|
||||
let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4]));
|
||||
// Channel values as floats, then scaled.
|
||||
type Decode = Box<dyn Fn(&[u8]) -> [f32; 3]>;
|
||||
let (n, decode): (usize, Decode) = match format {
|
||||
27..=32 => {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = px(x, y, 4);
|
||||
out.extend([p[0], p[1], p[2], 255]);
|
||||
}
|
||||
}
|
||||
return Some(out);
|
||||
}
|
||||
87..=93 => {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = px(x, y, 4);
|
||||
out.extend([p[2], p[1], p[0], 255]);
|
||||
}
|
||||
}
|
||||
return Some(out);
|
||||
}
|
||||
23..=25 => (4, Box::new(move |b| {
|
||||
let v = u32_at(b, 0);
|
||||
[(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32]
|
||||
})),
|
||||
26 => (4, Box::new(move |b| {
|
||||
let v = u32_at(b, 0);
|
||||
[small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)]
|
||||
})),
|
||||
9..=11 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])),
|
||||
33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])),
|
||||
1..=2 => (16, Box::new(move |b| {
|
||||
[0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))
|
||||
})),
|
||||
15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])),
|
||||
35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])),
|
||||
48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])),
|
||||
// Single channels: shown as grey.
|
||||
39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])),
|
||||
53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])),
|
||||
55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])),
|
||||
60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])),
|
||||
_ => return None,
|
||||
};
|
||||
let values: Vec<[f32; 3]> = (0..h)
|
||||
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
||||
.map(|(x, y)| decode(px(x, y, n)))
|
||||
.collect();
|
||||
let grey = matches!(format, 39..=43 | 53..=65);
|
||||
let finite = values.iter().flatten().copied().filter(|v| v.is_finite());
|
||||
let (low, high) = if grey {
|
||||
finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v)))
|
||||
} else {
|
||||
(0.0, finite.fold(0.0f32, f32::max))
|
||||
};
|
||||
let range = (high - low).max(1e-20);
|
||||
tracing::info!(format, low, high, "target values");
|
||||
for v in values {
|
||||
let c = v.map(|c| (((c - low) / range).clamp(0.0, 1.0) * 255.0) as u8);
|
||||
out.extend([c[0], c[1], c[2], 255]);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Pixels per side of the grid [`probe`] reads.
|
||||
const GRID: u32 = 4;
|
||||
/// Bytes between the grid's pixels in the readback buffer (placement
|
||||
/// alignment).
|
||||
const SLOT: u64 = 512;
|
||||
|
||||
/// Records copies of a grid of pixels of `texture` (8-bit color, in the
|
||||
/// copy-source state) into a readback buffer, to tell black frames.
|
||||
pub(crate) fn probe(
|
||||
device: &ID3D12Device,
|
||||
list: &ID3D12GraphicsCommandList,
|
||||
texture: &ID3D12Resource,
|
||||
) -> Option<ID3D12Resource> {
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) {
|
||||
return None;
|
||||
}
|
||||
let desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: SLOT * u64::from(GRID * GRID),
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
..Default::default()
|
||||
};
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_READBACK,
|
||||
..Default::default()
|
||||
};
|
||||
let mut buffer: Option<ID3D12Resource> = None;
|
||||
// SAFETY: plain creation; an open list; locations naming live resources.
|
||||
unsafe {
|
||||
device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
None,
|
||||
&mut buffer,
|
||||
)
|
||||
.ok()?;
|
||||
let buffer = buffer?;
|
||||
for i in 0..GRID * GRID {
|
||||
let (x, y) = (
|
||||
(2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID),
|
||||
(2 * (i / GRID) + 1) * d.Height / (2 * GRID),
|
||||
);
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(&buffer),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
Offset: SLOT * u64::from(i),
|
||||
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
|
||||
Format: d.Format,
|
||||
Width: 1,
|
||||
Height: 1,
|
||||
Depth: 1,
|
||||
RowPitch: 256,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
pResource: std::mem::transmute_copy(texture),
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
SubresourceIndex: 0,
|
||||
},
|
||||
};
|
||||
let pixel = D3D12_BOX {
|
||||
left: x,
|
||||
top: y,
|
||||
front: 0,
|
||||
right: x + 1,
|
||||
bottom: y + 1,
|
||||
back: 1,
|
||||
};
|
||||
list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel));
|
||||
}
|
||||
Some(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every pixel [`probe`] read is (near) black.
|
||||
pub(crate) fn black(buffer: &ID3D12Resource) -> bool {
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: the copies finished (every submission is waited for).
|
||||
unsafe {
|
||||
if buffer.Map(0, None, Some(&mut data)).is_err() {
|
||||
return false;
|
||||
}
|
||||
let bytes =
|
||||
std::slice::from_raw_parts(data.cast::<u8>(), (SLOT * u64::from(GRID * GRID)) as usize);
|
||||
let level = bytes
|
||||
.chunks(SLOT as usize)
|
||||
.flat_map(|pixel| pixel[..3].iter().copied())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
buffer.Unmap(0, None);
|
||||
let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if levels.len() == 12 {
|
||||
levels.pop_front();
|
||||
}
|
||||
levels.push_back(level);
|
||||
level < 8
|
||||
}
|
||||
}
|
||||
|
||||
/// The brightest probed channel of the last frames, oldest first: a fade
|
||||
/// darkens over several, a glitch drops at once.
|
||||
static LEVELS: std::sync::Mutex<std::collections::VecDeque<u8>> =
|
||||
std::sync::Mutex::new(std::collections::VecDeque::new());
|
||||
|
||||
pub(crate) fn recent_levels() -> Vec<u8> {
|
||||
let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
levels.iter().copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn crc_matches_the_png_check_value() {
|
||||
assert_eq!(super::crc32(b"IEND"), 0xae42_6082);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Which console the title runs on. Titles pick settings (resolution,
|
||||
//! memory budgets) by it, so the user chooses; Series X unless told.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
const GIB: usize = 1 << 30;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Console {
|
||||
#[default]
|
||||
SeriesX,
|
||||
SeriesS,
|
||||
}
|
||||
|
||||
impl Console {
|
||||
/// Title memory in bytes: (GPU-optimal, standard). Series X in the
|
||||
/// advanced configuration; Series S has one range, counted as standard
|
||||
/// (7,776 MiB, the published console-mode figure).
|
||||
// shortcut: later system updates gave Series S titles more (amount not
|
||||
// published here); Grand Theft Auto VI sizes nothing from this figure
|
||||
// (it goes by the device type), so update it if a title does.
|
||||
pub const fn title_memory(self) -> (usize, usize) {
|
||||
match self {
|
||||
Console::SeriesX => (10 * GIB, 7 * GIB / 2),
|
||||
Console::SeriesS => (0, 7_776 << 20),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn name(self) -> &'static str {
|
||||
match self {
|
||||
Console::SeriesX => "Xbox Series X",
|
||||
Console::SeriesS => "Xbox Series S",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static SERIES_S: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// Set before the title starts.
|
||||
pub fn set(console: Console) {
|
||||
SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn current() -> Console {
|
||||
if SERIES_S.load(Ordering::Relaxed) {
|
||||
Console::SeriesS
|
||||
} else {
|
||||
Console::SeriesX
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Diagnostics: where the submission copies of title memory go (which
|
||||
//! ranges, how often, of what memory) and what limits their rate, logged
|
||||
//! with the frame-rate line. `VICTORY_COPY_MODE=plain` copies without the
|
||||
//! mapped-page guard, `none` skips the copies (both for timing only).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
|
||||
/// Counters since the last line.
|
||||
pub(crate) enum C {
|
||||
Submissions,
|
||||
Copies,
|
||||
CopyBytes,
|
||||
Refreshes,
|
||||
RefreshBytes,
|
||||
Skipped,
|
||||
SkippedBytes,
|
||||
Runs,
|
||||
RunUs,
|
||||
Queries,
|
||||
QueryUs,
|
||||
MoveUs,
|
||||
Unmapped,
|
||||
/// Write-watch askings and their time.
|
||||
Watches,
|
||||
WatchUs,
|
||||
/// Bytes of watched ranges checked, and of those found unchanged.
|
||||
Checked,
|
||||
Unchanged,
|
||||
/// Copies that met an unmapped page.
|
||||
Fallbacks,
|
||||
/// Writes taken by the guard on view memory.
|
||||
GuardFaults,
|
||||
/// Texture bytes detiled after a watched write; hashed; detiled after a
|
||||
/// hash change.
|
||||
TexWatched,
|
||||
TexHashed,
|
||||
TexChanged,
|
||||
}
|
||||
const COUNTERS: usize = 22;
|
||||
static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS];
|
||||
|
||||
pub(crate) fn add(c: C, n: u64) {
|
||||
COUNT[c as usize].fetch_add(n, Relaxed);
|
||||
}
|
||||
|
||||
/// How copies run: 0 guarded (as always), 1 plain, 2 not at all.
|
||||
pub(crate) fn mode() -> u8 {
|
||||
static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*MODE.get_or_init(|| match std::env::var("VICTORY_COPY_MODE").as_deref() {
|
||||
Ok("plain") => 1,
|
||||
Ok("none") => 2,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Per source range (start, length): copies, bytes, microseconds, memory type.
|
||||
type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>;
|
||||
static RANGES: Mutex<Option<Ranges>> = Mutex::new(None);
|
||||
|
||||
/// A copy of `len` bytes from `src` (memory type `kind`) took `us`.
|
||||
pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) {
|
||||
let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let e = map
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.entry((src, len))
|
||||
.or_insert((0, 0, 0, kind));
|
||||
e.0 += 1;
|
||||
e.1 += len as u64;
|
||||
e.2 += us;
|
||||
}
|
||||
|
||||
fn page_faults() -> u64 {
|
||||
use windows_sys::Win32::System::ProcessStatus::{
|
||||
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
let mut c = PROCESS_MEMORY_COUNTERS {
|
||||
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: our own process and a sized structure.
|
||||
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) };
|
||||
u64::from(c.PageFaultCount)
|
||||
}
|
||||
|
||||
/// Logs the counters per frame over `frames` frames, and the ranges that
|
||||
/// took most bytes.
|
||||
pub(crate) fn log(frames: f64) {
|
||||
static FAULTS: AtomicU64 = AtomicU64::new(0);
|
||||
let faults = page_faults();
|
||||
let faults = faults - FAULTS.swap(faults, Relaxed).min(faults);
|
||||
let c: Vec<f64> = COUNT
|
||||
.iter()
|
||||
.map(|a| a.swap(0, Relaxed) as f64 / frames)
|
||||
.collect();
|
||||
let mb = |v: f64| v / 1e6;
|
||||
let ms = |v: f64| v / 1e3;
|
||||
tracing::info!(
|
||||
"copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \
|
||||
{:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \
|
||||
{:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \
|
||||
unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \
|
||||
changed, {:.1} MB hashed, {:.1} MB of them changed",
|
||||
c[C::Submissions as usize],
|
||||
c[C::Copies as usize],
|
||||
mb(c[C::CopyBytes as usize]),
|
||||
c[C::Refreshes as usize],
|
||||
mb(c[C::RefreshBytes as usize]),
|
||||
c[C::Skipped as usize],
|
||||
mb(c[C::SkippedBytes as usize]),
|
||||
c[C::Runs as usize],
|
||||
ms(c[C::RunUs as usize]),
|
||||
c[C::Queries as usize],
|
||||
ms(c[C::QueryUs as usize]),
|
||||
ms(c[C::MoveUs as usize]),
|
||||
mb(c[C::Unmapped as usize]),
|
||||
faults as f64 / frames,
|
||||
c[C::Watches as usize],
|
||||
ms(c[C::WatchUs as usize]),
|
||||
mb(c[C::Checked as usize]),
|
||||
mb(c[C::Unchanged as usize]),
|
||||
c[C::Fallbacks as usize],
|
||||
c[C::GuardFaults as usize],
|
||||
mb(c[C::TexWatched as usize]),
|
||||
mb(c[C::TexHashed as usize]),
|
||||
mb(c[C::TexChanged as usize]),
|
||||
);
|
||||
let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
let mut ranges: Vec<_> = ranges.into_iter().flatten().collect();
|
||||
ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes));
|
||||
for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) {
|
||||
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) };
|
||||
let kind = info.Type;
|
||||
tracing::info!(
|
||||
" copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame",
|
||||
n as f64 / frames,
|
||||
bytes as f64 / 1e6 / frames,
|
||||
us as f64 / 1e3 / frames
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@
|
||||
use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
|
||||
use crate::resource::{Memory, PAGEABLE_IIDS};
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod host;
|
||||
|
||||
const HEAP_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x8efb471d,
|
||||
@@ -31,18 +34,139 @@ pub(crate) struct HeapDesc {
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
/// Newer titles (Grand Theft Auto VI) pass the description followed by
|
||||
/// memory of their own for the descriptors: an address and its size in
|
||||
/// bytes, or a null address to have the heap allocate (inferred from the
|
||||
/// title's call sites; older titles pass the plain description).
|
||||
#[repr(C)]
|
||||
struct Heap {
|
||||
object: Object,
|
||||
desc: HeapDesc,
|
||||
memory: Memory,
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct Placement {
|
||||
address: u64,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
fn heap<'a>(this: This) -> &'a Heap {
|
||||
#[repr(C)]
|
||||
pub(crate) struct Heap {
|
||||
object: Object,
|
||||
desc: HeapDesc,
|
||||
/// The first descriptor: in `memory`, or in the title's own memory.
|
||||
pub(crate) start: u64,
|
||||
memory: Option<Memory>,
|
||||
/// Shader-visible view and sampler heaps get a host heap with the same
|
||||
/// descriptor order when a draw first uses them (decision 0007, step
|
||||
/// 3); slots written before wait in `pending`.
|
||||
#[cfg(windows)]
|
||||
host: std::sync::OnceLock<Option<host::HostHeap>>,
|
||||
#[cfg(windows)]
|
||||
pending: std::sync::Mutex<Vec<u32>>,
|
||||
}
|
||||
|
||||
pub(crate) fn heap<'a>(this: This) -> &'a Heap {
|
||||
// SAFETY: called from descriptor heap methods only.
|
||||
unsafe { &*this.cast::<Heap>() }
|
||||
}
|
||||
|
||||
impl Heap {
|
||||
/// Whether this is a sampler heap.
|
||||
pub(crate) fn samplers(&self) -> bool {
|
||||
self.desc.kind == SAMPLERS
|
||||
}
|
||||
|
||||
/// The host heap, made on first use from what the title wrote so far.
|
||||
/// Made late because a host view heap the size of Grand Theft Auto VI's
|
||||
/// costs over 100 MB of commit, which its boot needs for its page pool.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host(&self) -> Option<&host::HostHeap> {
|
||||
if let Some(h) = self.host.get() {
|
||||
return h.as_ref();
|
||||
}
|
||||
if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let h = self
|
||||
.host
|
||||
.get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count))
|
||||
.as_ref()?;
|
||||
let step = u64::from(increment(self.desc.kind)?);
|
||||
for i in pending.drain(..) {
|
||||
h.mirror(i, self.start + u64::from(i) * step, false);
|
||||
}
|
||||
Some(h)
|
||||
}
|
||||
|
||||
/// The descriptor index of `handle` in this heap, if it lies in it.
|
||||
pub(crate) fn index(&self, handle: u64) -> Option<u32> {
|
||||
let step = u64::from(increment(self.desc.kind)?);
|
||||
let at = handle.checked_sub(self.start)?;
|
||||
let index = at / step;
|
||||
(index < u64::from(self.desc.count)).then_some(index as u32)
|
||||
}
|
||||
}
|
||||
|
||||
const VIEWS_KIND: u32 = 0;
|
||||
const SAMPLERS: u32 = 1;
|
||||
const SHADER_VISIBLE: u32 = 1;
|
||||
|
||||
/// Shader-visible heaps by address range, for mirroring descriptor writes:
|
||||
/// start, end, heap.
|
||||
#[cfg(windows)]
|
||||
static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// The shader-visible heap holding `handle`, and the descriptor's index.
|
||||
#[cfg(windows)]
|
||||
fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> {
|
||||
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let &(_, _, at) = heaps
|
||||
.iter()
|
||||
.find(|&&(start, end, _)| (start..end).contains(&handle))?;
|
||||
// SAFETY: registered heaps are live (removed when dropped).
|
||||
let heap = unsafe { &*(at as *const Heap) };
|
||||
Some((heap, heap.index(handle)?))
|
||||
}
|
||||
|
||||
/// Makes the host descriptor for what the title wrote at `handle`, if it
|
||||
/// is in a shader-visible heap.
|
||||
#[cfg(windows)]
|
||||
fn mirror(handle: u64) {
|
||||
let Some((heap, index)) = shader_slot(handle) else {
|
||||
return;
|
||||
};
|
||||
let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match heap.host.get() {
|
||||
None => pending.push(index),
|
||||
Some(host) => {
|
||||
drop(pending);
|
||||
if let Some(host) = host {
|
||||
host.mirror(index, handle, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives back dynamic slots of the host heap behind the title heap at
|
||||
/// `heap`, if that heap still exists.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
|
||||
let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if heaps.iter().any(|&(_, _, h)| h == heap)
|
||||
// SAFETY: registered heaps are live (removed when dropped).
|
||||
&& let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
|
||||
{
|
||||
host.release(first, n);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for Heap {
|
||||
fn drop(&mut self) {
|
||||
let at = std::ptr::from_ref::<Heap>(self) as usize;
|
||||
let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
heaps.retain(|&(_, _, h)| h != at);
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes per descriptor, by heap type (views, samplers, render targets,
|
||||
/// depth).
|
||||
fn increment(kind: u32) -> Option<u32> {
|
||||
@@ -73,12 +197,40 @@ impl RtvRecord {
|
||||
pub(crate) fn desc(
|
||||
&self,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
|
||||
// SAFETY: 24 bytes in the host's layout.
|
||||
(self.described != 0).then(|| unsafe {
|
||||
(&raw const self.desc)
|
||||
.cast::<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC>()
|
||||
.read_unaligned()
|
||||
})
|
||||
const TEXTURE_2D: u32 = 4;
|
||||
self.host_desc(TEXTURE_2D)
|
||||
}
|
||||
|
||||
/// The depth view description in the host's type (the same layout).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn depth_desc(
|
||||
&self,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> {
|
||||
const TEXTURE_2D: u32 = 3;
|
||||
self.host_desc(TEXTURE_2D)
|
||||
}
|
||||
|
||||
/// The description words as a host type, the format as the host has it.
|
||||
/// Without one, a typeless host copy gets a 2D view (`dimension`) in
|
||||
/// the title's format, which the host needs spelled out.
|
||||
#[cfg(windows)]
|
||||
fn host_desc<T>(&self, dimension: u32) -> Option<T> {
|
||||
assert!(size_of::<T>() <= size_of::<[u32; 6]>());
|
||||
let mut words = if self.described != 0 {
|
||||
self.desc
|
||||
} else {
|
||||
[
|
||||
crate::resource::view_format(self.resource)?,
|
||||
dimension,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
]
|
||||
};
|
||||
words[0] = crate::resource::pc_format(words[0]);
|
||||
// SAFETY: both host view descriptions are 24 bytes in this layout.
|
||||
Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,41 +256,380 @@ pub(crate) extern "system" fn create_rtv(
|
||||
unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
|
||||
}
|
||||
|
||||
/// Device method: a depth view, recorded as render target views are.
|
||||
pub(crate) extern "system" fn create_dsv(
|
||||
this: This,
|
||||
resource: This,
|
||||
desc: *const [u32; 6],
|
||||
handle: u64,
|
||||
) {
|
||||
create_rtv(this, resource, desc, handle);
|
||||
if handle != 0 {
|
||||
// SAFETY: just written by `create_rtv`.
|
||||
unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) };
|
||||
}
|
||||
}
|
||||
const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV");
|
||||
|
||||
/// A shader view or sampler as the title described it (descriptions in the
|
||||
/// host's layout, kept as words), for the host to build its own from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) enum View {
|
||||
/// Constant buffer: GPU address and size.
|
||||
Constant(u64, u32),
|
||||
/// Shader resource: resource, description (none: the resource's own).
|
||||
Shader(usize, Option<[u32; 10]>),
|
||||
/// Unordered access: resource, counter resource, description.
|
||||
Unordered(usize, usize, Option<[u32; 10]>),
|
||||
Sampler([u32; 13]),
|
||||
/// The console's own sampler description: flags, filters per axis,
|
||||
/// addressing, LOD and anisotropy settings, border color, then
|
||||
/// console-only tuning words.
|
||||
ConsoleSampler([u32; 27]),
|
||||
/// A view of memory without a resource object: whether it is unordered
|
||||
/// access, the resource description, then the view's (the plain one
|
||||
/// followed by the memory address and console fields).
|
||||
Placed(bool, [u32; 14], [u32; 16]),
|
||||
}
|
||||
|
||||
impl View {
|
||||
/// Whether the view reads buffer memory (constant buffers, buffer views
|
||||
/// of resources or of memory) or memory the title placed a texture in:
|
||||
/// such views get host slots only for draws.
|
||||
#[cfg(windows)]
|
||||
fn is_buffer(&self) -> bool {
|
||||
match self {
|
||||
View::Constant(..) | View::Placed(..) => true,
|
||||
View::Shader(r, _) | View::Unordered(r, _, _) => {
|
||||
crate::resource::buffer_bytes(*r as This).is_some()
|
||||
}
|
||||
View::Sampler(_) | View::ConsoleSampler(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every distinct view in use; a descriptor holds a tag, an index into it
|
||||
/// and the entry's generation, which survive titles copying descriptors as
|
||||
/// bytes. A view of a resource lives as long as the resource: when the
|
||||
/// title releases it, its entries are freed for reuse under a new
|
||||
/// generation, so descriptors (and host slots made from them) naming the
|
||||
/// old one go stale instead of naming whatever is made at the same address
|
||||
/// next.
|
||||
/// shortcut: views without a resource object (constant buffers, memory
|
||||
/// views, samplers) are kept for the run; they are bounded by the title's
|
||||
/// memory and sampler states.
|
||||
struct Views {
|
||||
/// Each entry's view and generation.
|
||||
list: Vec<(View, u32)>,
|
||||
index: std::collections::BTreeMap<View, u32>,
|
||||
/// Entries naming each resource.
|
||||
by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
|
||||
free: Vec<u32>,
|
||||
}
|
||||
|
||||
static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
|
||||
list: Vec::new(),
|
||||
index: std::collections::BTreeMap::new(),
|
||||
by_resource: std::collections::BTreeMap::new(),
|
||||
free: Vec::new(),
|
||||
});
|
||||
const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
|
||||
|
||||
impl View {
|
||||
/// The resource objects the view names.
|
||||
fn resources(&self) -> [usize; 2] {
|
||||
match *self {
|
||||
View::Shader(r, _) => [r, 0],
|
||||
View::Unordered(r, counter, _) => [r, counter],
|
||||
_ => [0, 0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record(handle: u64, view: View) {
|
||||
if handle == 0 {
|
||||
return;
|
||||
}
|
||||
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let i = match views.index.get(&view) {
|
||||
Some(&i) => i,
|
||||
None => {
|
||||
let i = match views.free.pop() {
|
||||
Some(i) => {
|
||||
views.list[i as usize].0 = view.clone();
|
||||
i
|
||||
}
|
||||
None => {
|
||||
views.list.push((view.clone(), 1));
|
||||
views.list.len() as u32 - 1
|
||||
}
|
||||
};
|
||||
for r in view.resources().into_iter().filter(|&r| r != 0) {
|
||||
views.by_resource.entry(r).or_default().push(i);
|
||||
}
|
||||
views.index.insert(view, i);
|
||||
i
|
||||
}
|
||||
};
|
||||
let generation = views.list[i as usize].1;
|
||||
// SAFETY: the handle is a descriptor slot, at least 16 bytes.
|
||||
unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
|
||||
drop(views);
|
||||
#[cfg(windows)]
|
||||
mirror(handle);
|
||||
}
|
||||
|
||||
/// The title released `resource`: the views naming it go stale.
|
||||
pub(crate) fn forget(resource: usize) {
|
||||
let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(entries) = views.by_resource.remove(&resource) else {
|
||||
return;
|
||||
};
|
||||
for i in entries {
|
||||
let (view, generation) = views.list[i as usize].clone();
|
||||
// Entries freed through a view's other resource may hold another
|
||||
// view by now.
|
||||
if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) {
|
||||
continue;
|
||||
}
|
||||
views.index.remove(&view);
|
||||
views.list[i as usize].1 = generation.wrapping_add(1).max(1);
|
||||
// The view's other resource (a counter) keeps a stale entry, which
|
||||
// `forget` of that resource skips.
|
||||
views.free.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// The view of entry `i` if `generation` is still its own.
|
||||
#[cfg(windows)]
|
||||
fn view_at(i: u32, generation: u32) -> Option<View> {
|
||||
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (view, current) = views.list.get(i as usize)?;
|
||||
(*current == generation).then(|| view.clone())
|
||||
}
|
||||
|
||||
/// The view recorded at `handle`, if one is (and its resource is alive).
|
||||
pub(crate) fn view(handle: u64) -> Option<View> {
|
||||
if handle == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the handle is a descriptor slot the title passes back.
|
||||
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
|
||||
let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (view, current) = views.list.get(i as usize)?;
|
||||
(tag == VIEW_TAG && *current == generation).then(|| view.clone())
|
||||
}
|
||||
|
||||
/// A description of `N` words, if the title passes one.
|
||||
fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> {
|
||||
// SAFETY: the title passes a description or null.
|
||||
(!desc.is_null()).then(|| unsafe { desc.read_unaligned() })
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) {
|
||||
if let Some([lo, hi, size, _]) = words(desc) {
|
||||
let address = u64::from(lo) | u64::from(hi) << 32;
|
||||
record(handle, View::Constant(address, size));
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_srv(
|
||||
_: This,
|
||||
resource: This,
|
||||
desc: *const [u32; 10],
|
||||
handle: u64,
|
||||
) {
|
||||
record(handle, View::Shader(resource as usize, words(desc)));
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_uav(
|
||||
_: This,
|
||||
resource: This,
|
||||
counter: This,
|
||||
desc: *const [u32; 10],
|
||||
handle: u64,
|
||||
) {
|
||||
let view = View::Unordered(resource as usize, counter as usize, words(desc));
|
||||
record(handle, view);
|
||||
}
|
||||
|
||||
/// Device methods 0x230 and 0x238: shader resource and unordered access
|
||||
/// views of memory the title placed itself, `(resource desc, view desc,
|
||||
/// handle)`.
|
||||
pub(crate) extern "system" fn create_placed_srv(
|
||||
_: This,
|
||||
resource: *const [u32; 14],
|
||||
desc: *const [u32; 16],
|
||||
handle: u64,
|
||||
) {
|
||||
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
|
||||
record(handle, View::Placed(false, resource, desc));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_placed_uav(
|
||||
_: This,
|
||||
resource: *const [u32; 14],
|
||||
desc: *const [u32; 16],
|
||||
handle: u64,
|
||||
) {
|
||||
if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
|
||||
record(handle, View::Placed(true, resource, desc));
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) {
|
||||
if let Some(desc) = words(desc) {
|
||||
record(handle, View::Sampler(desc));
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method 0x1e8.
|
||||
pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) {
|
||||
if let Some(desc) = words(desc) {
|
||||
record(handle, View::ConsoleSampler(desc));
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: `count` descriptors of `kind` from `src` to `dst`.
|
||||
pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) {
|
||||
let step = u64::from(increment(kind).unwrap_or(0));
|
||||
let len = u64::from(count) * step;
|
||||
if dst != 0 && src != 0 {
|
||||
// SAFETY: both ranges are descriptor slots the title owns.
|
||||
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) };
|
||||
#[cfg(windows)]
|
||||
for i in 0..u64::from(count) {
|
||||
mirror(dst + i * step);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: ranges of descriptors (start and count each) gathered
|
||||
/// from the sources and scattered to the destinations, in order.
|
||||
#[allow(clippy::too_many_arguments)] // the method's own arguments
|
||||
pub(crate) extern "system" fn copy(
|
||||
_: This,
|
||||
dst_ranges: u32,
|
||||
dst_starts: *const u64,
|
||||
dst_sizes: *const u32,
|
||||
src_ranges: u32,
|
||||
src_starts: *const u64,
|
||||
src_sizes: *const u32,
|
||||
kind: u32,
|
||||
) {
|
||||
let Some(step) = increment(kind) else {
|
||||
return;
|
||||
};
|
||||
// Each range as (start, count); a null size array means one descriptor
|
||||
// per range.
|
||||
let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> {
|
||||
(0..n as usize)
|
||||
.map(|i| {
|
||||
// SAFETY: the title passes `n` starts and sizes (or null sizes).
|
||||
unsafe {
|
||||
(
|
||||
*starts.add(i),
|
||||
if sizes.is_null() { 1 } else { *sizes.add(i) },
|
||||
)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
if dst_starts.is_null() || src_starts.is_null() {
|
||||
return;
|
||||
}
|
||||
let src = ranges(src_ranges, src_starts, src_sizes);
|
||||
let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter();
|
||||
let (mut to, mut room) = dst.next().unwrap_or((0, 0));
|
||||
for (mut from, mut left) in src {
|
||||
while left > 0 {
|
||||
while room == 0 {
|
||||
let Some(next) = dst.next() else { return };
|
||||
(to, room) = next;
|
||||
}
|
||||
let n = left.min(room);
|
||||
copy_simple(std::ptr::null(), n, to, from, kind);
|
||||
let bytes = u64::from(n) * u64::from(step);
|
||||
(to, from, room, left) = (to + bytes, from + bytes, room - n, left - n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The view recorded at `handle`, if one is.
|
||||
pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
|
||||
tagged_record(handle, RTV_TAG)
|
||||
}
|
||||
|
||||
/// The depth view recorded at `handle`, if one is.
|
||||
pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> {
|
||||
tagged_record(handle, DSV_TAG)
|
||||
}
|
||||
|
||||
fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> {
|
||||
if handle == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the handle is a descriptor slot the title passes back.
|
||||
let record = unsafe { (handle as *const RtvRecord).read_unaligned() };
|
||||
(record.tag == RTV_TAG).then_some(record)
|
||||
(record.tag == tag).then_some(record)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_heap(
|
||||
_: This,
|
||||
desc: *const HeapDesc,
|
||||
desc_ptr: *const HeapDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1)))
|
||||
else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "descriptor heap");
|
||||
let memory = match Memory::zeroed(size, 64) {
|
||||
Ok(memory) => memory,
|
||||
Err(hr) => return hr,
|
||||
// SAFETY: read only as a hint: a title that passes the plain
|
||||
// description has its own stack or data after it.
|
||||
let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() };
|
||||
// shortcut: a placement is recognised by its size matching the count,
|
||||
// since the plain and extended descriptions share the slot and the
|
||||
// interface version; find the flag that tells them apart if a title
|
||||
// trips over this.
|
||||
let placed = placement.address != 0 && placement.size == size;
|
||||
tracing::debug!(?desc, placed, "descriptor heap");
|
||||
let (start, memory) = if placed {
|
||||
(placement.address, None)
|
||||
} else {
|
||||
match Memory::zeroed(size, 64) {
|
||||
Ok(memory) => (memory.address(), Some(memory)),
|
||||
Err(hr) => return hr,
|
||||
}
|
||||
};
|
||||
let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS);
|
||||
let heap = Box::new(Heap {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
desc,
|
||||
start,
|
||||
memory,
|
||||
#[cfg(windows)]
|
||||
host: std::sync::OnceLock::new(),
|
||||
#[cfg(windows)]
|
||||
pending: Default::default(),
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if visible {
|
||||
let at = std::ptr::from_ref::<Heap>(&heap) as usize;
|
||||
let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
heaps.push((start, start + size, at));
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = visible;
|
||||
object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
|
||||
}
|
||||
|
||||
@@ -157,12 +648,12 @@ extern "system" fn desc(this: This, out: *mut HeapDesc) {
|
||||
}
|
||||
/// The same address for the CPU and the GPU start.
|
||||
extern "system" fn start(this: This) -> u64 {
|
||||
heap(this).memory.address()
|
||||
heap(this).start
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, heap 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 11>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
@@ -177,6 +668,16 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
/// What newer titles pass; tests use it throughout, so that reading the
|
||||
/// placement stays inside the value.
|
||||
#[repr(C)]
|
||||
struct Extended(HeapDesc, Placement);
|
||||
|
||||
fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT {
|
||||
let extended = Extended(desc, placement);
|
||||
create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heaps_hold_count_descriptors_from_their_start() {
|
||||
let null = std::ptr::null();
|
||||
@@ -186,8 +687,12 @@ mod tests {
|
||||
flags: 1,
|
||||
nodes: 0,
|
||||
};
|
||||
let none = Placement {
|
||||
address: 0,
|
||||
size: 0,
|
||||
};
|
||||
let mut h = null;
|
||||
assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK);
|
||||
assert_eq!(create(desc, none, &mut h), S_OK);
|
||||
let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
|
||||
assert_eq!(cpu % 64, 0);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
|
||||
@@ -196,6 +701,90 @@ mod tests {
|
||||
unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) };
|
||||
assert_eq!(increment_size(null, 9), 0);
|
||||
let bad = HeapDesc { kind: 9, ..desc };
|
||||
assert_eq!(create_heap(null, &bad, &HEAP_IIDS[0], &mut h), E_INVALIDARG);
|
||||
assert_eq!(create(bad, none, &mut h), E_INVALIDARG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_survive_copies() {
|
||||
let null = std::ptr::null();
|
||||
let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots
|
||||
let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64;
|
||||
let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3));
|
||||
create_cbv(null, &[0x1000, 1, 256, 0], s0);
|
||||
assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256)));
|
||||
create_srv(null, null, std::ptr::null(), s1);
|
||||
assert_eq!(view(s1), Some(View::Shader(0, None)));
|
||||
// The same view twice is one entry.
|
||||
create_srv(null, null, std::ptr::null(), s2);
|
||||
// SAFETY: both slots are in `heap`.
|
||||
assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe {
|
||||
*(s2 as *const [u32; 3])
|
||||
});
|
||||
// Two ranges of one into one range of two.
|
||||
let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]);
|
||||
copy(
|
||||
null,
|
||||
1,
|
||||
dst.as_ptr(),
|
||||
dst_n.as_ptr(),
|
||||
2,
|
||||
src.as_ptr(),
|
||||
src_n.as_ptr(),
|
||||
0,
|
||||
);
|
||||
assert_eq!(view(s2), view(s0));
|
||||
assert_eq!(view(s3), view(s1));
|
||||
assert_eq!(view(at(0) + 8), None);
|
||||
heap[0] = 0;
|
||||
}
|
||||
|
||||
/// A released resource's views go stale; the same view of a new
|
||||
/// resource at the same address is a new record.
|
||||
#[test]
|
||||
fn views_die_with_their_resource() {
|
||||
let null = std::ptr::null();
|
||||
let slots = [0u64; 2 * 4];
|
||||
let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32);
|
||||
let resource = 0x7777_0000usize as This;
|
||||
create_srv(null, resource, std::ptr::null(), a);
|
||||
assert_eq!(view(a), Some(View::Shader(0x7777_0000, None)));
|
||||
forget(0x7777_0000);
|
||||
assert_eq!(view(a), None, "stale after release");
|
||||
create_srv(null, resource, std::ptr::null(), b);
|
||||
assert_eq!(view(b), Some(View::Shader(0x7777_0000, None)));
|
||||
// SAFETY: both slots are in `slots`.
|
||||
let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) };
|
||||
assert_ne!(old, new, "a new generation");
|
||||
}
|
||||
|
||||
/// Grand Theft Auto VI places its shader-visible heap in its own memory
|
||||
/// and checks that the heap starts there.
|
||||
#[test]
|
||||
fn placed_heaps_start_at_the_title_memory() {
|
||||
let mut memory = vec![0u8; 64 * 32];
|
||||
let address = memory.as_mut_ptr() as u64;
|
||||
let desc = HeapDesc {
|
||||
kind: 0,
|
||||
count: 64,
|
||||
flags: 1,
|
||||
nodes: 1,
|
||||
};
|
||||
let mut h = std::ptr::null();
|
||||
assert_eq!(
|
||||
create(
|
||||
desc,
|
||||
Placement {
|
||||
address,
|
||||
size: 64 * 32
|
||||
},
|
||||
&mut h
|
||||
),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address);
|
||||
// A size that does not match the count is not a placement.
|
||||
assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK);
|
||||
assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
//! Host descriptor heaps behind the title's shader-visible heaps (decision
|
||||
//! 0007, step 3). Translated shaders index the heaps directly at the
|
||||
//! title's descriptor positions, so each host heap keeps the title heap's
|
||||
//! order: slot `i` is made from what the title wrote at slot `i`, when it
|
||||
//! writes it (view creation and descriptor copies) and again when a draw
|
||||
//! reads it through a table and finds the slot changed.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
|
||||
use super::{VIEW_TAG, View, view_at};
|
||||
use crate::host::host;
|
||||
|
||||
pub(crate) struct HostHeap {
|
||||
pub(crate) heap: ID3D12DescriptorHeap,
|
||||
cpu: usize,
|
||||
step: u32,
|
||||
/// Slots mirroring the title's; view heaps have [`DYNAMIC`] more.
|
||||
count: u32,
|
||||
sampler: bool,
|
||||
/// The record (view index and generation) each slot was last made from.
|
||||
made: Mutex<Vec<u64>>,
|
||||
/// Where the search for free dynamic slots starts, and which are taken
|
||||
/// (by lists not yet reset).
|
||||
next: Mutex<(u32, Vec<bool>)>,
|
||||
}
|
||||
|
||||
/// The host's limit for shader-visible view heaps on resource binding
|
||||
/// tiers 1 and 2; tier 3 hardware may take more.
|
||||
const PORTABLE_VIEWS: u32 = 1_000_000;
|
||||
|
||||
/// Slots past the title's in a view heap, for tables a draw needs made
|
||||
/// afresh (constant buffers copied per draw). A list holds the slots it
|
||||
/// took until it is reset (its submissions have run) or released.
|
||||
const DYNAMIC: u32 = 1 << 16;
|
||||
|
||||
impl HostHeap {
|
||||
pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
|
||||
let host = host()?;
|
||||
let kind = if sampler {
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
|
||||
} else {
|
||||
D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
|
||||
};
|
||||
let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> {
|
||||
// SAFETY: plain heap creation.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: kind,
|
||||
NumDescriptors: count,
|
||||
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
})
|
||||
}
|
||||
};
|
||||
let extra = if sampler { 0 } else { DYNAMIC };
|
||||
let (heap, count) = match make(count + extra) {
|
||||
Ok(heap) => (heap, count),
|
||||
Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
|
||||
// shortcut: descriptors past the host's limit are left out;
|
||||
// a title that reaches them needs remapping.
|
||||
tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
|
||||
(make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// SAFETY: a live heap.
|
||||
let (cpu, step) = unsafe {
|
||||
(
|
||||
heap.GetCPUDescriptorHandleForHeapStart().ptr,
|
||||
host.device.GetDescriptorHandleIncrementSize(kind),
|
||||
)
|
||||
};
|
||||
tracing::debug!(count, sampler, "host descriptor heap");
|
||||
let h = HostHeap {
|
||||
heap,
|
||||
cpu,
|
||||
step,
|
||||
count,
|
||||
sampler,
|
||||
made: Mutex::new(vec![0; count as usize]),
|
||||
next: Mutex::new((0, vec![false; DYNAMIC as usize])),
|
||||
};
|
||||
// A slot never written is undefined: shaders reading one (a slot
|
||||
// the title wrote in a way we do not know, or a table entry no
|
||||
// used-resource entry names) read a wild address. Every slot starts
|
||||
// null instead.
|
||||
let started = std::time::Instant::now();
|
||||
if let Err(e) = h.fill_null(kind, count + extra) {
|
||||
tracing::warn!(error = %e, "host descriptor heap not made null");
|
||||
}
|
||||
tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
|
||||
Some(h)
|
||||
}
|
||||
|
||||
/// Makes the first `total` slots null: one null slot in a CPU-side heap,
|
||||
/// doubled by copies to a block, the block copied over the heap.
|
||||
fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> {
|
||||
const BLOCK: u32 = 1 << 16;
|
||||
let Some(host) = host() else { return Ok(()) };
|
||||
// SAFETY: plain heap creation and copies inside live heaps.
|
||||
unsafe {
|
||||
let block: ID3D12DescriptorHeap =
|
||||
host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: kind,
|
||||
NumDescriptors: BLOCK,
|
||||
..Default::default()
|
||||
})?;
|
||||
let start = block.GetCPUDescriptorHandleForHeapStart();
|
||||
let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: start.ptr + (i * self.step) as usize,
|
||||
};
|
||||
if self.sampler {
|
||||
null_sampler(start);
|
||||
} else {
|
||||
null_view(start);
|
||||
}
|
||||
let mut filled = 1;
|
||||
while filled < BLOCK {
|
||||
let n = filled.min(BLOCK - filled);
|
||||
host.device.CopyDescriptorsSimple(n, at(filled), start, kind);
|
||||
filled += n;
|
||||
}
|
||||
let mut done = 0;
|
||||
while done < total {
|
||||
let n = BLOCK.min(total - done);
|
||||
host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind);
|
||||
done += n;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A plain point sampler at slot `index`, for sampler slots without a
|
||||
/// view.
|
||||
fn null_sampler(&self, index: u32) {
|
||||
null_sampler(self.cpu(index));
|
||||
}
|
||||
}
|
||||
|
||||
/// A plain point sampler at `at`.
|
||||
fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
MaxAnisotropy: 1,
|
||||
ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: a slot of a sampler heap of ours.
|
||||
unsafe { host.device.CreateSampler(&desc, at) };
|
||||
}
|
||||
|
||||
impl HostHeap {
|
||||
/// `n` consecutive free dynamic slots (view heaps only), taken until
|
||||
/// [`HostHeap::release`]: the first's index.
|
||||
pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
|
||||
if self.sampler || n == 0 || n > DYNAMIC {
|
||||
return None;
|
||||
}
|
||||
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (next, taken) = &mut *guard;
|
||||
let n = n as usize;
|
||||
// Search from `next` on, then from the start.
|
||||
let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize);
|
||||
let mut run = 0;
|
||||
let mut found = None;
|
||||
let mut last = usize::MAX;
|
||||
for at in starts {
|
||||
// A run cannot wrap past the end.
|
||||
if at != last.wrapping_add(1) {
|
||||
run = 0;
|
||||
}
|
||||
last = at;
|
||||
run = if taken[at] { 0 } else { run + 1 };
|
||||
if run == n {
|
||||
found = Some(at + 1 - n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(first) = found else {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
|
||||
return None;
|
||||
};
|
||||
taken[first..first + n].fill(true);
|
||||
*next = ((first + n) % DYNAMIC as usize) as u32;
|
||||
Some(self.count + first as u32)
|
||||
}
|
||||
|
||||
/// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
|
||||
/// returned).
|
||||
///
|
||||
/// [`dynamic`]: HostHeap::dynamic
|
||||
pub(crate) fn release(&self, first: u32, n: u32) {
|
||||
let Some(at) = first.checked_sub(self.count) else {
|
||||
return;
|
||||
};
|
||||
let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let end = (at + n).min(DYNAMIC) as usize;
|
||||
if let Some(slots) = guard.1.get_mut(at as usize..end) {
|
||||
slots.fill(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes slot `index` (a dynamic one) from `view`; a null view if the
|
||||
/// host cannot.
|
||||
pub(crate) fn make_at(&self, index: u32, view: &View) {
|
||||
if !make(view, self.cpu(index)) {
|
||||
null_for(view, self.cpu(index));
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes slot `index` read nothing: a null view, or a plain sampler.
|
||||
pub(crate) fn make_null(&self, index: u32) {
|
||||
if self.sampler {
|
||||
self.null_sampler(index);
|
||||
} else {
|
||||
null_view(self.cpu(index));
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes slot `index` (a dynamic one) a constant buffer view of host
|
||||
/// memory.
|
||||
pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
|
||||
BufferLocation: gpu,
|
||||
SizeInBytes: size.next_multiple_of(256),
|
||||
};
|
||||
// SAFETY: a slot of our heap; the memory is the caller's.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateConstantBufferView(Some(&desc), self.cpu(index))
|
||||
};
|
||||
}
|
||||
|
||||
fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.cpu + index as usize * self.step as usize,
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes host slot `index` from the record the title has at `handle`
|
||||
/// if it changed since, and returns the view recorded there. Buffer
|
||||
/// views are made only for draws (`for_draw`), which also copy their
|
||||
/// data: a host copy of a buffer is made on first use.
|
||||
pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
|
||||
if index >= self.count {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the handle is a descriptor slot in title memory.
|
||||
let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
|
||||
// Generations start at 1, so a made slot's key is never 0.
|
||||
let key = u64::from(generation) << 32 | u64::from(i);
|
||||
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
|
||||
let Some(view) = view else {
|
||||
// Not a view of ours (never written, or of a resource the
|
||||
// title released): nothing to read.
|
||||
if made[index as usize] != 0 {
|
||||
made[index as usize] = 0;
|
||||
self.make_null(index);
|
||||
}
|
||||
return None;
|
||||
};
|
||||
if made[index as usize] != key {
|
||||
let later = !for_draw && view.is_buffer();
|
||||
made[index as usize] = if later { 0 } else { key };
|
||||
if (later || !make(&view, self.cpu(index))) && !self.sampler {
|
||||
null_for(&view, self.cpu(index));
|
||||
}
|
||||
}
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The view host slot `index` was made from, in a few words, with the
|
||||
/// title and host addresses of a buffer view (diagnostics). "null" for
|
||||
/// a slot never made or left null.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
|
||||
let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
|
||||
if key == 0 {
|
||||
return Some("null".into());
|
||||
}
|
||||
let view = view_at(key as u32, (key >> 32) as u32)?;
|
||||
let mut text: String = format!("{view:?}").chars().take(120).collect();
|
||||
if let Some((address, len)) = buffer_range(&view) {
|
||||
let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
|
||||
text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs `what` the first time it happens.
|
||||
macro_rules! once {
|
||||
($($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
/// A view description from its words, with the format as the host has it.
|
||||
fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
let mut words = *words;
|
||||
words[0] = crate::resource::pc_format(words[0]);
|
||||
// SAFETY: 40 bytes in the host's layout.
|
||||
unsafe {
|
||||
std::ptr::from_ref(&words)
|
||||
.cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
|
||||
.read_unaligned()
|
||||
}
|
||||
}
|
||||
|
||||
fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
let mut words = *words;
|
||||
words[0] = crate::resource::pc_format(words[0]);
|
||||
// SAFETY: 40 bytes in the host's layout.
|
||||
unsafe {
|
||||
std::ptr::from_ref(&words)
|
||||
.cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
|
||||
.read_unaligned()
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer view of title memory at `address` on its host copy: the first
|
||||
/// element moves by the copy's offset.
|
||||
/// Bytes per element of a buffer view.
|
||||
fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { desc.Anonymous.Buffer };
|
||||
if buffer.StructureByteStride > 0 {
|
||||
u64::from(buffer.StructureByteStride)
|
||||
} else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// The title memory a buffer shader or unordered access view reads: its
|
||||
/// address and length.
|
||||
pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
|
||||
let (base, words): (u64, &[u32; 10]) = match view {
|
||||
View::Shader(r, Some(desc)) => (
|
||||
crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
|
||||
desc,
|
||||
),
|
||||
View::Placed(false, resource, desc) if resource[0] == 1 => (
|
||||
u64::from(desc[10]) | u64::from(desc[11]) << 32,
|
||||
desc[..10].try_into().ok()?,
|
||||
),
|
||||
View::Unordered(r, _, Some(desc)) => {
|
||||
let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
|
||||
return unordered_range(base, desc);
|
||||
}
|
||||
View::Placed(true, resource, desc) if resource[0] == 1 => {
|
||||
let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
return unordered_range(base, desc[..10].try_into().ok()?);
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let desc = srv_desc(words);
|
||||
let element = element_size(&desc);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { desc.Anonymous.Buffer };
|
||||
Some((
|
||||
base + buffer.FirstElement * element,
|
||||
u64::from(buffer.NumElements) * element,
|
||||
))
|
||||
}
|
||||
|
||||
/// [`buffer_range`] of an unordered access view of memory at `base`.
|
||||
fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
|
||||
let desc = uav_desc(words);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { desc.Anonymous.Buffer };
|
||||
let element = if buffer.StructureByteStride > 0 {
|
||||
u64::from(buffer.StructureByteStride)
|
||||
} else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32)?.0
|
||||
};
|
||||
Some((
|
||||
base + buffer.FirstElement * element,
|
||||
u64::from(buffer.NumElements) * element,
|
||||
))
|
||||
}
|
||||
|
||||
fn buffer_srv(
|
||||
address: u64,
|
||||
len: u64,
|
||||
mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> bool {
|
||||
let Some(shadow) = crate::shadow::find(address, len) else {
|
||||
return false;
|
||||
};
|
||||
let element = element_size(&desc);
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
let offset = shadow.offset(address);
|
||||
if element == 0 || offset % element != 0 {
|
||||
once!(
|
||||
offset,
|
||||
element,
|
||||
"buffer view not on an element of its host copy"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
let Some(host) = host() else { return false };
|
||||
// SAFETY: a live buffer and a slot of our heap.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
|
||||
};
|
||||
true
|
||||
}
|
||||
|
||||
/// An unordered access view of title buffer memory at `address` (`len`
|
||||
/// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
|
||||
/// written by shaders (upload memory).
|
||||
/// shortcut: what shaders write stays in the host copy; title memory (and
|
||||
/// so the CPU, and copies run on the CPU) does not see it.
|
||||
fn buffer_uav(
|
||||
address: u64,
|
||||
len: u64,
|
||||
mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
|
||||
at: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
) -> bool {
|
||||
let Some(shadow) = crate::shadow::find(address, len) else {
|
||||
return false;
|
||||
};
|
||||
// SAFETY: a live buffer.
|
||||
let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
|
||||
if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
|
||||
once!("unordered access to a buffer whose host copy shaders cannot write");
|
||||
return false;
|
||||
}
|
||||
// SAFETY: a buffer view's union member.
|
||||
let buffer = unsafe { &mut desc.Anonymous.Buffer };
|
||||
let element = if buffer.StructureByteStride > 0 {
|
||||
u64::from(buffer.StructureByteStride)
|
||||
} else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
|
||||
4
|
||||
} else {
|
||||
crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
|
||||
};
|
||||
let offset = shadow.offset(address);
|
||||
if element == 0 || offset % element != 0 {
|
||||
once!(offset, element, "unordered buffer view not on an element of its host copy");
|
||||
return false;
|
||||
}
|
||||
buffer.FirstElement += offset / element;
|
||||
buffer.CounterOffsetInBytes = 0;
|
||||
let Some(host) = host() else { return false };
|
||||
// SAFETY: a live buffer and a slot of our heap.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
|
||||
};
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the host can make a shader (or unordered access) view of
|
||||
/// `texture` in `format` (none: the texture's own). The console allows any
|
||||
/// view; the host refuses (and removes the device for) views without the
|
||||
/// resource's permission, of typed depth, and in another format than a
|
||||
/// typed resource's. A view of a typed texture in another format of its
|
||||
/// family takes the texture's format.
|
||||
/// shortcut: such a view (sRGB of UNORM, say) reads without its
|
||||
/// conversion; cast with castable formats if colors come out wrong.
|
||||
fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
|
||||
use crate::resource::{DEPTH_FORMATS, family};
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
let allowed = if unordered {
|
||||
d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
|
||||
} else {
|
||||
d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
|
||||
};
|
||||
let own = d.Format.0 as u32;
|
||||
if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
|
||||
once!(
|
||||
unordered,
|
||||
format = own,
|
||||
flags = d.Flags.0,
|
||||
"view the host does not allow"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Every family has more than one format, its typeless one first.
|
||||
let typeless = family(own) == own && family(own + 1) == own;
|
||||
if let Some(format) = format.as_deref_mut()
|
||||
&& unordered
|
||||
&& let Some(&(_, linear)) = crate::resource::SRGB
|
||||
.iter()
|
||||
.find(|&&(s, _)| s == format.0 as u32)
|
||||
{
|
||||
format.0 = linear as i32;
|
||||
}
|
||||
let view = format.as_ref().map_or(0, |f| f.0 as u32);
|
||||
if view == 0 {
|
||||
return !typeless;
|
||||
}
|
||||
if family(view) != family(own) {
|
||||
once!(view, own, "view format of another family");
|
||||
return false;
|
||||
}
|
||||
if let Some(format) = format
|
||||
&& !typeless
|
||||
{
|
||||
*format = d.Format;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Makes the host descriptor for `view` at `at`; false if it cannot.
|
||||
fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> bool {
|
||||
let Some(host) = host() else { return false };
|
||||
let device = &host.device;
|
||||
match view {
|
||||
&View::Constant(address, size) => {
|
||||
let Some(shadow) = crate::shadow::find(address, u64::from(size)) else {
|
||||
return false;
|
||||
};
|
||||
let gpu = shadow.gpu(address);
|
||||
if gpu % 256 != 0 {
|
||||
once!(
|
||||
address = format_args!("{address:#x}"),
|
||||
"constant buffer not 256-byte aligned on the host"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
|
||||
BufferLocation: gpu,
|
||||
SizeInBytes: size.next_multiple_of(256),
|
||||
};
|
||||
// SAFETY: a slot of our heap; the range lies in the host copy.
|
||||
unsafe { device.CreateConstantBufferView(Some(&desc), at) };
|
||||
true
|
||||
}
|
||||
View::Shader(resource, desc) => {
|
||||
let resource = *resource as crate::object::This;
|
||||
if let Some(texture) = crate::resource::host_resource(resource) {
|
||||
let mut desc = desc.as_ref().map(srv_desc);
|
||||
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: a live texture and a slot of our heap.
|
||||
unsafe {
|
||||
device.CreateShaderResourceView(
|
||||
texture,
|
||||
desc.as_ref().map(std::ptr::from_ref),
|
||||
at,
|
||||
)
|
||||
};
|
||||
true
|
||||
} else if let (Some((data, len)), Some(desc)) =
|
||||
(crate::resource::buffer_bytes(resource), desc)
|
||||
{
|
||||
buffer_srv(data as u64, len, srv_desc(desc), at)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
View::Unordered(resource, _counter, desc) => {
|
||||
let resource = *resource as crate::object::This;
|
||||
let Some(texture) = crate::resource::host_resource(resource) else {
|
||||
return match (crate::resource::buffer_bytes(resource), desc) {
|
||||
(Some((data, len)), Some(desc)) => {
|
||||
buffer_uav(data as u64, len, uav_desc(desc), at)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
};
|
||||
let mut desc = desc.as_ref().map(uav_desc);
|
||||
if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: a live texture and a slot of our heap.
|
||||
unsafe {
|
||||
device.CreateUnorderedAccessView(
|
||||
texture,
|
||||
None::<&ID3D12Resource>,
|
||||
desc.as_ref().map(std::ptr::from_ref),
|
||||
at,
|
||||
)
|
||||
};
|
||||
true
|
||||
}
|
||||
View::Sampler(words) => {
|
||||
// SAFETY: 13 words in the host's layout.
|
||||
let desc = unsafe {
|
||||
std::ptr::from_ref(words)
|
||||
.cast::<D3D12_SAMPLER_DESC>()
|
||||
.read_unaligned()
|
||||
};
|
||||
// SAFETY: a slot of our sampler heap.
|
||||
unsafe { device.CreateSampler(&desc, at) };
|
||||
true
|
||||
}
|
||||
View::ConsoleSampler(words) => {
|
||||
let desc = crate::sampler::console(words);
|
||||
// SAFETY: a slot of our sampler heap.
|
||||
unsafe { device.CreateSampler(&desc, at) };
|
||||
true
|
||||
}
|
||||
View::Placed(unordered, resource, desc) => {
|
||||
if let Some(view) = placed_texture(view) {
|
||||
return make(&view, at);
|
||||
}
|
||||
const BUFFER: u32 = 1;
|
||||
if resource[0] != BUFFER {
|
||||
// shortcut: unordered access to a texture the title placed
|
||||
// itself is not mirrored; give it a resource as shader
|
||||
// views of such textures get when a dispatch writes one.
|
||||
once!(dimension = resource[0], "placed unordered texture view not mirrored");
|
||||
return false;
|
||||
}
|
||||
// The resource description's width, after the alignment.
|
||||
let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
|
||||
if *unordered {
|
||||
buffer_uav(address, len, uav_desc(words), at)
|
||||
} else {
|
||||
buffer_srv(address, len, srv_desc(words), at)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shader view of a texture the title placed in memory itself, as a view
|
||||
/// of the resource made for that memory (on first use).
|
||||
pub(crate) fn placed_texture(view: &View) -> Option<View> {
|
||||
const BUFFER: u32 = 1;
|
||||
let View::Placed(false, resource, desc) = view else {
|
||||
return None;
|
||||
};
|
||||
if resource[0] == BUFFER {
|
||||
return None;
|
||||
}
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
let texture = crate::resource::texture_at(address, resource)?;
|
||||
Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
|
||||
}
|
||||
|
||||
/// A null view of the kind `view` is, for a slot whose view the host
|
||||
/// cannot make: unordered access (to a buffer or a 2D texture) or a shader
|
||||
/// view. Writes to it are dropped, reads give zeros.
|
||||
fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let buffer = match view {
|
||||
View::Unordered(r, _, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_some(),
|
||||
View::Placed(true, resource, _) => resource[0] == 1,
|
||||
_ => return null_view(at),
|
||||
};
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_UINT,
|
||||
ViewDimension: if buffer {
|
||||
D3D12_UAV_DIMENSION_BUFFER
|
||||
} else {
|
||||
D3D12_UAV_DIMENSION_TEXTURE2D
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
|
||||
unsafe {
|
||||
host.device.CreateUnorderedAccessView(
|
||||
None::<&ID3D12Resource>,
|
||||
None::<&ID3D12Resource>,
|
||||
Some(&desc),
|
||||
at,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// A view that reads zeros, for slots whose view the host cannot make.
|
||||
fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let Some(host) = host() else { return };
|
||||
let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
|
||||
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Texture2D: D3D12_TEX2D_SRV {
|
||||
MipLevels: 1,
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: a slot of our heap; a null resource is allowed with a desc.
|
||||
unsafe {
|
||||
host.device
|
||||
.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Dynamic slots stay taken until given back, and runs do not wrap.
|
||||
#[test]
|
||||
fn dynamic_slots_are_held_until_released() {
|
||||
let Some(heap) = HostHeap::new(false, 4) else {
|
||||
return; // no host GPU
|
||||
};
|
||||
let a = heap.dynamic(DYNAMIC - 100).unwrap();
|
||||
let b = heap.dynamic(60).unwrap();
|
||||
assert_eq!((a, b), (4, 4 + DYNAMIC - 100));
|
||||
// 40 left at the end: 50 do not fit until something is given back.
|
||||
assert_eq!(heap.dynamic(50), None);
|
||||
heap.release(a, 50);
|
||||
assert_eq!(heap.dynamic(50), Some(4));
|
||||
assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40));
|
||||
}
|
||||
}
|
||||
@@ -28,8 +28,72 @@ pub static IID: Iid = guid(
|
||||
[0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
|
||||
);
|
||||
|
||||
/// The interface version these layouts were checked against (2.4, what
|
||||
/// Minecraft passes). Newer titles may lay objects out differently.
|
||||
/// The levels the device answers to, as on PC: `ID3D12Device1` to
|
||||
/// `ID3D12Device8`, and `ID3D12Device11`, which Grand Theft Auto VI creates
|
||||
/// its device as. Each level's table is the one before plus its methods.
|
||||
const LEVEL_IIDS: [Iid; 9] = [
|
||||
guid(
|
||||
0x77acce80,
|
||||
0x638e,
|
||||
0x4e65,
|
||||
[0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e],
|
||||
),
|
||||
guid(
|
||||
0x30baa41e,
|
||||
0xb15b,
|
||||
0x475c,
|
||||
[0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28],
|
||||
),
|
||||
guid(
|
||||
0x81dadc15,
|
||||
0x2bad,
|
||||
0x4392,
|
||||
[0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98],
|
||||
),
|
||||
guid(
|
||||
0xe865df17,
|
||||
0xa9ee,
|
||||
0x46f9,
|
||||
[0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5],
|
||||
),
|
||||
guid(
|
||||
0x8b4f173b,
|
||||
0x2fea,
|
||||
0x4b80,
|
||||
[0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d],
|
||||
),
|
||||
guid(
|
||||
0xc70b221b,
|
||||
0x40e4,
|
||||
0x4a17,
|
||||
[0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc],
|
||||
),
|
||||
guid(
|
||||
0x5c014b53,
|
||||
0x68a1,
|
||||
0x4b9b,
|
||||
[0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b],
|
||||
),
|
||||
guid(
|
||||
0x728f1fa2,
|
||||
0xea11,
|
||||
0x4a9f,
|
||||
[0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9],
|
||||
),
|
||||
guid(
|
||||
0x5405c344,
|
||||
0xd457,
|
||||
0x444e,
|
||||
[0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39],
|
||||
),
|
||||
];
|
||||
|
||||
fn is_device(iid: *const Iid) -> bool {
|
||||
object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS)
|
||||
}
|
||||
|
||||
/// The interface version these layouts were checked against (2.4). Both
|
||||
/// Minecraft (March 2022) and Grand Theft Auto VI (April 2026) pass it.
|
||||
pub const CHECKED_VERSION: u32 = 0x0002_0004;
|
||||
|
||||
/// Feature level 12_2, what the console hardware supports.
|
||||
@@ -78,19 +142,34 @@ pub extern "system" fn create(
|
||||
"device layouts were checked against {CHECKED_VERSION:#x} only"
|
||||
);
|
||||
}
|
||||
if *iid != IID {
|
||||
if !is_device(iid) {
|
||||
tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface");
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
if out.is_null() {
|
||||
return S_FALSE;
|
||||
}
|
||||
if *iid == LEVEL_IIDS[8] {
|
||||
NEWER.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
object::answer(object::DEVICE, iid, Some(device()), out)
|
||||
}
|
||||
|
||||
/// Set when the title creates the device as `ID3D12Device11`. Its lists and
|
||||
/// queues then have the newer layouts (two more methods each; see
|
||||
/// `list` and `queue`), although the interface version stays 2.4.
|
||||
/// shortcut: the creation interface is the only sign of the newer layouts
|
||||
/// we have (Grand Theft Auto VI, April 2026, versus Minecraft, March 2022);
|
||||
/// look for a better one if a title breaks the rule.
|
||||
static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
pub(crate) fn newer() -> bool {
|
||||
NEWER.load(std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The device, or its DXGI side.
|
||||
extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = if object::is(iid, &[IID]) {
|
||||
let found = if is_device(iid) {
|
||||
Some(this)
|
||||
} else if object::is(iid, &dxgi::DEVICE_IIDS) {
|
||||
Some(dxgi::device())
|
||||
@@ -100,6 +179,55 @@ extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This)
|
||||
object::answer(object::DEVICE, iid, found, out)
|
||||
}
|
||||
|
||||
/// What `D3D12ConfigureVirtualMemoryX` takes and fills in.
|
||||
#[repr(C)]
|
||||
pub struct VirtualMemory {
|
||||
flags: u32,
|
||||
/// GPU page table size in 4 MiB pages.
|
||||
page_table_pages: u32,
|
||||
/// Memory kept across title processes for the frame buffer.
|
||||
preserved_bytes: u32,
|
||||
/// Out: the range graphics addresses fall in.
|
||||
lowest: u64,
|
||||
highest: u64,
|
||||
}
|
||||
const _: () = assert!(size_of::<VirtualMemory>() == 0x20);
|
||||
|
||||
/// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics
|
||||
/// allocation. The inputs size console structures we do not have; the
|
||||
/// range out is all of user space, since GPU addresses are CPU addresses.
|
||||
pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT {
|
||||
// SAFETY: the title passes its configuration (null is tolerated).
|
||||
let Some(config) = (unsafe { config.as_mut() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::info!(
|
||||
flags = config.flags,
|
||||
page_table_pages = config.page_table_pages,
|
||||
preserved_bytes = config.preserved_bytes,
|
||||
"graphics virtual memory"
|
||||
);
|
||||
(config.lowest, config.highest) = user_space();
|
||||
S_OK
|
||||
}
|
||||
|
||||
fn user_space() -> (u64, u64) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO};
|
||||
// SAFETY: plain data, filled in by the call.
|
||||
let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer.
|
||||
unsafe { GetSystemInfo(&mut info) };
|
||||
(
|
||||
info.lpMinimumApplicationAddress as u64,
|
||||
info.lpMaximumApplicationAddress as u64,
|
||||
)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
(0x1_0000, 0x7fff_fffe_ffff)
|
||||
}
|
||||
|
||||
extern "system" fn node_count(_: This) -> u32 {
|
||||
1
|
||||
}
|
||||
@@ -217,9 +345,13 @@ fn feature_levels(data: *mut c_void) -> HRESULT {
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object methods 4, device methods 76.
|
||||
static FUNCTIONS: Table<83> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>());
|
||||
/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the
|
||||
/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9,
|
||||
/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of
|
||||
/// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown.
|
||||
/// Every slot exists so that a call to one we have not written logs it.
|
||||
static FUNCTIONS: Table<160> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>());
|
||||
f[0] = query_interface as *const (); // 0x00
|
||||
f[7] = node_count as *const (); // 0x38
|
||||
f[8] = queue::create as *const (); // 0x40
|
||||
@@ -231,8 +363,16 @@ static FUNCTIONS: Table<83> = {
|
||||
f[14] = descriptor::create_heap as *const (); // 0x70
|
||||
f[15] = descriptor::increment_size as *const (); // 0x78
|
||||
f[16] = root::create as *const (); // 0x80
|
||||
f[17] = descriptor::create_cbv as *const (); // 0x88
|
||||
f[18] = descriptor::create_srv as *const (); // 0x90
|
||||
f[19] = descriptor::create_uav as *const (); // 0x98
|
||||
f[20] = descriptor::create_rtv as *const (); // 0xa0
|
||||
f[21] = descriptor::create_dsv as *const (); // 0xa8
|
||||
f[22] = descriptor::create_sampler as *const (); // 0xb0
|
||||
f[23] = descriptor::copy as *const (); // 0xb8
|
||||
f[24] = descriptor::copy_simple as *const (); // 0xc0
|
||||
f[25] = resource::allocation_info as *const (); // 0xc8
|
||||
f[26] = resource::custom_heap_properties as *const (); // 0xd0
|
||||
f[27] = resource::create_committed as *const (); // 0xd8
|
||||
f[28] = resource::create_heap as *const (); // 0xe0
|
||||
f[29] = resource::create_placed as *const (); // 0xe8
|
||||
@@ -240,12 +380,26 @@ static FUNCTIONS: Table<83> = {
|
||||
f[38] = resource::copyable_footprints as *const (); // 0x130
|
||||
f[39] = query::create as *const (); // 0x138
|
||||
f[41] = signature::create as *const (); // 0x148
|
||||
f[48] = queue::create_x as *const (); // 0x180
|
||||
f[61] = descriptor::create_sampler_x as *const (); // 0x1e8
|
||||
f[62] = pipeline::create_compute_x as *const (); // 0x1f0
|
||||
f[69] = object::ignore as *const (); // 0x228 debug error filter
|
||||
f[70] = descriptor::create_placed_srv as *const (); // 0x230
|
||||
f[71] = descriptor::create_placed_uav as *const (); // 0x238
|
||||
f[73] = list::create_list_x as *const (); // 0x248
|
||||
f[74] = resource::register_page_pool as *const (); // 0x250
|
||||
f[75] = resource::unregister_page_pool as *const (); // 0x258
|
||||
// CreateCommittedResourceX: its description is PC's plus DCC options,
|
||||
// which we have no use for (the AMD upscaler's, on Series S).
|
||||
f[76] = resource::create_committed as *const (); // 0x260
|
||||
f[78] = frame::set_interval as *const (); // 0x270
|
||||
f[79] = frame::schedule as *const (); // 0x278
|
||||
f[80] = frame::wait as *const (); // 0x280
|
||||
f[81] = frame::statistics as *const (); // 0x288
|
||||
f[86] = pipeline::create_stream as *const (); // 0x2b0
|
||||
f[108] = resource::allocation_info2 as *const (); // 0x360
|
||||
f[127] = resource::create_committed3 as *const (); // 0x3f8
|
||||
f[133] = resource::create_at_address as *const (); // 0x428
|
||||
Table(f)
|
||||
};
|
||||
|
||||
@@ -274,10 +428,39 @@ mod tests {
|
||||
slot::<extern "system" fn(This) -> u32>(device, 0x38)(device),
|
||||
1
|
||||
);
|
||||
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x88);
|
||||
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0xf0);
|
||||
assert_eq!(missing(), E_NOTIMPL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_device_levels_are_the_same_device() {
|
||||
// ID3D12Device11, as Grand Theft Auto VI asks for it.
|
||||
let (hr, device) = create_as(&LEVEL_IIDS[8]);
|
||||
assert_eq!((hr, device), (S_OK, super::device()));
|
||||
let mut same = std::ptr::null();
|
||||
assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK);
|
||||
assert_eq!(same, device);
|
||||
// A Device8 method we have not written fails without crashing.
|
||||
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x3a0);
|
||||
assert_eq!(missing(), E_NOTIMPL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_memory_configuration_reports_user_space() {
|
||||
let mut config = VirtualMemory {
|
||||
flags: 0,
|
||||
page_table_pages: 7,
|
||||
preserved_bytes: 0,
|
||||
lowest: 0,
|
||||
highest: 0,
|
||||
};
|
||||
assert_eq!(configure_virtual_memory(&mut config), S_OK);
|
||||
assert!(0 < config.lowest && config.lowest < config.highest);
|
||||
let heap = Box::new(0u8);
|
||||
assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64)));
|
||||
assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_levels_pick_the_highest_supported() {
|
||||
type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT;
|
||||
|
||||
@@ -0,0 +1,987 @@
|
||||
//! Draws on the host GPU (decision 0007, step 3). A list keeps the state
|
||||
//! the title sets for its draws (pipeline, descriptor heaps, root
|
||||
//! arguments, vertex and index buffers, targets); each draw then brings the
|
||||
//! host list up to date: the host pipeline and our root signature, the
|
||||
//! user data the translated shaders read, the host copies of the buffers
|
||||
//! and descriptors they read, and the states of the textures involved.
|
||||
//! State the host keeps across draws (viewports, scissors, blend factor,
|
||||
//! stencil reference, topology, targets) is set on the host list as the
|
||||
//! title sets it.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use victory_shader::{ResourceType, RootType, UsedResource};
|
||||
|
||||
use crate::descriptor::View;
|
||||
use windows::Win32::Foundation::RECT;
|
||||
use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
|
||||
use windows::core::Interface;
|
||||
|
||||
use crate::host::HostList;
|
||||
use crate::object::This;
|
||||
use crate::pipeline::host::HostPipeline;
|
||||
|
||||
/// A root argument as the title set it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
enum Root {
|
||||
#[default]
|
||||
None,
|
||||
/// A descriptor table's first descriptor (an address in a heap).
|
||||
Table(u64),
|
||||
Constants(Vec<u32>),
|
||||
/// A root view's GPU address.
|
||||
View(u64),
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct VertexView {
|
||||
address: u64,
|
||||
size: u32,
|
||||
stride: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct IndexView {
|
||||
address: u64,
|
||||
size: u32,
|
||||
format: u32,
|
||||
}
|
||||
|
||||
/// What one title list has set, and what its host list was last given.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct State {
|
||||
pipeline: usize,
|
||||
/// View heap, sampler heap.
|
||||
heaps: [usize; 2],
|
||||
graphics: Vec<Root>,
|
||||
compute: Vec<Root>,
|
||||
vertex: [VertexView; 32],
|
||||
index: IndexView,
|
||||
/// Bound render target and depth resources, for their host states.
|
||||
targets: Vec<usize>,
|
||||
depth: usize,
|
||||
/// The title's primitive topology (the host's may differ).
|
||||
topology: u32,
|
||||
/// What the host list has: pipeline, root signature, heaps.
|
||||
host_pipeline: usize,
|
||||
/// Graphics, compute.
|
||||
host_roots: [usize; 2],
|
||||
host_heaps: [usize; 2],
|
||||
/// Tables made afresh in this list: (table, what it holds) → first
|
||||
/// dynamic slot.
|
||||
fresh_tables: std::collections::HashMap<(u64, u64), u32>,
|
||||
/// The dynamic slots the list holds: title heap, first, count; given
|
||||
/// back when the list is reset or released.
|
||||
dynamic: Vec<(usize, u32, u32)>,
|
||||
}
|
||||
|
||||
impl Drop for State {
|
||||
fn drop(&mut self) {
|
||||
for &(heap, first, n) in &self.dynamic {
|
||||
crate::descriptor::release_dynamic(heap, first, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws recorded on the host GPU since the last frame line.
|
||||
static DRAWN: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Draws run on the host so far.
|
||||
pub(crate) fn drawn() -> u64 {
|
||||
DRAWN.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The draws traced since the last present (diagnostics builds, with
|
||||
/// debug logging for this module): logged when the frame comes out black.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// The draws traced since the last call.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn take_frame() -> Vec<String> {
|
||||
std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
/// Marks the last traced draw as not run on the host.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn dropped() {
|
||||
if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
|
||||
last.push_str(" DROPPED");
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatches run on the host so far.
|
||||
static DISPATCHED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub(crate) fn dispatched() -> u64 {
|
||||
DISPATCHED.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The host address of a root view: its buffer's host copy, or for a
|
||||
/// constant buffer not 256-byte aligned there (the console needs 16) a
|
||||
/// copy in upload memory.
|
||||
/// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
|
||||
/// other views as 1 MiB (both cut at their buffer's end).
|
||||
fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
|
||||
let shadow = crate::shadow::find(address, 1)?;
|
||||
let len = shadow
|
||||
.left(address)
|
||||
.min(if srv { 1 << 20 } else { 1 << 16 });
|
||||
let gpu = shadow.gpu(address);
|
||||
if srv || gpu % 256 == 0 {
|
||||
shadow.refresh(list, address, len);
|
||||
return Some(gpu);
|
||||
}
|
||||
let (gpu, to) = list.scratch(len)?;
|
||||
list.defer_fill(to, address as *const u8, len as usize);
|
||||
Some(gpu)
|
||||
}
|
||||
|
||||
macro_rules! once {
|
||||
($($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
|
||||
let slot = slot as usize;
|
||||
if roots.len() <= slot {
|
||||
roots.resize(slot + 1, Root::None);
|
||||
}
|
||||
roots[slot] = root;
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub(crate) fn reset(&mut self, pipeline: This) {
|
||||
*self = State::default();
|
||||
self.pipeline = pipeline as usize;
|
||||
}
|
||||
|
||||
/// The title's topology; console-only ones become host lists (see
|
||||
/// [`crate::primitive`]).
|
||||
pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
|
||||
self.topology = topology;
|
||||
let host = match topology {
|
||||
RECTANGLES => 4,
|
||||
TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
|
||||
once!(topology, "console topology drawn as a triangle list");
|
||||
4
|
||||
}
|
||||
t => t,
|
||||
};
|
||||
// SAFETY: an open list.
|
||||
unsafe {
|
||||
list.list
|
||||
.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn set_pipeline(&mut self, pipeline: This) {
|
||||
self.pipeline = pipeline as usize;
|
||||
}
|
||||
|
||||
pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
|
||||
self.heaps = [0; 2];
|
||||
for &h in heaps {
|
||||
if !h.is_null() {
|
||||
let samplers = crate::descriptor::heap(h).samplers();
|
||||
self.heaps[usize::from(samplers)] = h as usize;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
|
||||
if compute {
|
||||
&mut self.compute
|
||||
} else {
|
||||
&mut self.graphics
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
|
||||
set(self.roots(compute), slot, Root::Table(handle));
|
||||
}
|
||||
|
||||
pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
|
||||
set(self.roots(compute), slot, Root::View(address));
|
||||
}
|
||||
|
||||
pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
|
||||
let roots = self.roots(compute);
|
||||
let s = slot as usize;
|
||||
if !matches!(roots.get(s), Some(Root::Constants(_))) {
|
||||
set(roots, slot, Root::Constants(Vec::new()));
|
||||
}
|
||||
if let Root::Constants(c) = &mut roots[s] {
|
||||
let end = offset as usize + values.len();
|
||||
if c.len() < end {
|
||||
c.resize(end, 0);
|
||||
}
|
||||
c[offset as usize..end].copy_from_slice(values);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
|
||||
for (i, v) in views.iter().enumerate() {
|
||||
if let Some(slot) = self.vertex.get_mut(start as usize + i) {
|
||||
*slot = *v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
|
||||
self.index = view.copied().unwrap_or_default();
|
||||
}
|
||||
|
||||
/// Render targets and depth, set on the host list at once.
|
||||
pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
|
||||
let Some(host) = crate::host::host() else {
|
||||
return;
|
||||
};
|
||||
self.targets.clear();
|
||||
let mut rtvs = Vec::new();
|
||||
for &h in handles {
|
||||
let Some(record) = crate::descriptor::rtv_record(h) else {
|
||||
once!(
|
||||
handle = format_args!("{h:#x}"),
|
||||
"render target without a recorded view"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let Some(texture) = crate::resource::host_resource(record.resource) else {
|
||||
continue;
|
||||
};
|
||||
self.targets.push(record.resource as usize);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::capture::note_target(record.resource);
|
||||
rtvs.push(host.rtv(texture, record.desc().as_ref()));
|
||||
}
|
||||
self.depth = 0;
|
||||
let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
|
||||
let texture = crate::resource::host_resource(record.resource)?;
|
||||
self.depth = record.resource as usize;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::capture::note_target(record.resource);
|
||||
Some(host.dsv(texture, record.depth_desc().as_ref()))
|
||||
});
|
||||
// SAFETY: an open list; the views were just made.
|
||||
unsafe {
|
||||
list.list.OMSetRenderTargets(
|
||||
rtvs.len() as u32,
|
||||
(!rtvs.is_empty()).then_some(rtvs.as_ptr()),
|
||||
false,
|
||||
dsv.as_ref().map(std::ptr::from_ref),
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// The user-data value of a root argument, as translated shaders read
|
||||
/// it: a table's byte offset in its heap, a constant's value.
|
||||
fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
|
||||
match (self.roots_ref(compute).get(usize::from(slot)), root) {
|
||||
(Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
|
||||
Some(heap) => (handle - heap.start) as u32,
|
||||
None => {
|
||||
once!(
|
||||
handle = format_args!("{handle:#x}"),
|
||||
"descriptor table outside the bound heaps"
|
||||
);
|
||||
0
|
||||
}
|
||||
},
|
||||
(Some(Root::Constants(c)), RootType::Constants) => {
|
||||
c.get(dword as usize).copied().unwrap_or(0)
|
||||
}
|
||||
_ => {
|
||||
once!(
|
||||
slot,
|
||||
?root,
|
||||
"a shader reads a root argument the title did not set"
|
||||
);
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bound heap holding `handle`.
|
||||
fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
|
||||
self.heaps
|
||||
.iter()
|
||||
.filter(|&&h| h != 0)
|
||||
.map(|&h| crate::descriptor::heap(h as This))
|
||||
.find(|h| h.index(handle).is_some())
|
||||
}
|
||||
|
||||
/// Brings the host list up to date for a draw; false if the draw cannot
|
||||
/// run on the host.
|
||||
fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
|
||||
self.prepare_for(list, indexed, false)
|
||||
}
|
||||
|
||||
/// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
|
||||
fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
|
||||
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
|
||||
return false;
|
||||
};
|
||||
if p.compute || p.mesh != mesh {
|
||||
once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
|
||||
return false;
|
||||
}
|
||||
self.bind(list, p, false);
|
||||
let l = &list.list;
|
||||
// Vertex buffers the input layout reads.
|
||||
let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
|
||||
let mut count = 0;
|
||||
for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
|
||||
if p.slots & 1 << slot == 0 {
|
||||
continue;
|
||||
}
|
||||
count = slot + 1;
|
||||
if v.address == 0 || v.size == 0 {
|
||||
continue;
|
||||
}
|
||||
let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
|
||||
continue;
|
||||
};
|
||||
shadow.refresh(list, v.address, u64::from(v.size));
|
||||
*view = D3D12_VERTEX_BUFFER_VIEW {
|
||||
BufferLocation: shadow.gpu(v.address),
|
||||
SizeInBytes: v.size,
|
||||
StrideInBytes: v.stride,
|
||||
};
|
||||
}
|
||||
// SAFETY: an open list; the views name live host buffers.
|
||||
unsafe {
|
||||
if count > 0 {
|
||||
l.IASetVertexBuffers(0, Some(&views[..count]));
|
||||
}
|
||||
}
|
||||
if indexed {
|
||||
let v = self.index;
|
||||
let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
|
||||
return false;
|
||||
};
|
||||
shadow.refresh(list, v.address, u64::from(v.size));
|
||||
let view = D3D12_INDEX_BUFFER_VIEW {
|
||||
BufferLocation: shadow.gpu(v.address),
|
||||
SizeInBytes: v.size,
|
||||
Format: DXGI_FORMAT(v.format as i32),
|
||||
};
|
||||
// SAFETY: an open list; the view names a live host buffer.
|
||||
unsafe { l.IASetIndexBuffer(Some(&view)) };
|
||||
}
|
||||
const RENDER_TARGET: u32 = 0x4;
|
||||
const DEPTH_WRITE: u32 = 0x10;
|
||||
for &t in &self.targets {
|
||||
crate::list::ensure_state(list, t as This, RENDER_TARGET);
|
||||
}
|
||||
if self.depth != 0 {
|
||||
crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A descriptor a shader reads through a table: its host slot made if
|
||||
/// it changed, constant data copied, textures made readable.
|
||||
/// What draws and dispatches share: heaps, our root signature, the
|
||||
/// pipeline, and per stage the user data, root views and the
|
||||
/// descriptors its tables hold.
|
||||
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
|
||||
let l = &list.list;
|
||||
// Heaps first: a root signature with directly indexed heaps must be
|
||||
// set after them.
|
||||
if self.host_heaps != self.heaps {
|
||||
let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
|
||||
.heaps
|
||||
.iter()
|
||||
.filter(|&&h| h != 0)
|
||||
.filter_map(|&h| crate::descriptor::heap(h as This).host())
|
||||
.map(|h| Some(h.heap.clone()))
|
||||
.collect();
|
||||
// SAFETY: an open list and shader-visible heaps.
|
||||
unsafe { l.SetDescriptorHeaps(&heaps) };
|
||||
self.host_heaps = self.heaps;
|
||||
self.host_roots = [0; 2];
|
||||
}
|
||||
let root = p.root.as_raw() as usize;
|
||||
if self.host_roots[usize::from(compute)] != root {
|
||||
// SAFETY: an open list and a live root signature.
|
||||
unsafe {
|
||||
if compute {
|
||||
l.SetComputeRootSignature(&p.root);
|
||||
} else {
|
||||
l.SetGraphicsRootSignature(&p.root);
|
||||
}
|
||||
}
|
||||
self.host_roots[usize::from(compute)] = root;
|
||||
}
|
||||
if self.host_pipeline != self.pipeline {
|
||||
// SAFETY: an open list and a live pipeline.
|
||||
unsafe { l.SetPipelineState(&p.pso) };
|
||||
self.host_pipeline = self.pipeline;
|
||||
list.used_pipeline(&p.name);
|
||||
}
|
||||
for stage in &p.stages {
|
||||
let t = stage.translated();
|
||||
let made = self.tables(list, &t.used, compute);
|
||||
if let Some((param, dwords)) = stage.user_data {
|
||||
let mut values = vec![0u32; dwords as usize];
|
||||
for u in &t.host.user_data {
|
||||
let fresh = made
|
||||
.iter()
|
||||
.find(|m| m.0 == u.slot && u.root == RootType::Table);
|
||||
values[u.index as usize] = match fresh {
|
||||
Some(&(_, offset)) => offset,
|
||||
None => self.user_value(compute, u.slot, u.root, u.dword),
|
||||
};
|
||||
}
|
||||
// SAFETY: an open list; `values` covers the parameter.
|
||||
unsafe {
|
||||
if compute {
|
||||
l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
|
||||
} else {
|
||||
l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
|
||||
for &(slot, param) in views {
|
||||
let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
|
||||
else {
|
||||
once!(slot, "a shader reads a root view the title did not set");
|
||||
continue;
|
||||
};
|
||||
let Some(gpu) = root_view(list, *address, srv) else {
|
||||
continue;
|
||||
};
|
||||
// SAFETY: an open list; the address is in live memory.
|
||||
unsafe {
|
||||
match (compute, srv) {
|
||||
(false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
|
||||
(false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
|
||||
(true, false) => l.SetComputeRootConstantBufferView(param, gpu),
|
||||
(true, true) => l.SetComputeRootShaderResourceView(param, gpu),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a dispatch on the host.
|
||||
pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
|
||||
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
|
||||
once!(
|
||||
pipeline = format_args!("{:#x}", self.pipeline),
|
||||
"a dispatch without a host pipeline dropped"
|
||||
);
|
||||
return;
|
||||
};
|
||||
if !p.compute {
|
||||
once!("a dispatch with a graphics pipeline");
|
||||
return;
|
||||
}
|
||||
self.bind(list, p, true);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { list.list.Dispatch(x, y, z) };
|
||||
DISPATCHED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// What a draw or dispatch runs, for the device-removed report
|
||||
/// (diagnostics): the pipeline, then per stage the user data it gets
|
||||
/// (with the view at that heap index, if one is), the host addresses
|
||||
/// of its root views and the views its tables name.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn op_text(&self, kind: String, compute: bool) -> String {
|
||||
use std::fmt::Write;
|
||||
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
|
||||
return kind;
|
||||
};
|
||||
let mut text = format!("{kind} {}", p.name);
|
||||
let views = (self.heaps[0] != 0)
|
||||
.then(|| crate::descriptor::heap(self.heaps[0] as This).host())
|
||||
.flatten();
|
||||
for stage in &p.stages {
|
||||
let t = stage.translated();
|
||||
let _ = write!(text, " | {}:", stage.shader.hash);
|
||||
for u in &t.host.user_data {
|
||||
let v = self.user_value(compute, u.slot, u.root, u.dword);
|
||||
let _ = write!(text, " u{}={v:#x}", u.index);
|
||||
let index = if u.root == RootType::Table { v / 32 } else { v };
|
||||
if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
|
||||
let _ = write!(text, " [heap {index}: {slot}]");
|
||||
}
|
||||
}
|
||||
for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
|
||||
if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
|
||||
let host = crate::shadow::find(*address, 1)
|
||||
.map(|s| (s.gpu(*address), s.left(*address)));
|
||||
let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = write!(text, " tables {:?}", self.reads(compute));
|
||||
text
|
||||
}
|
||||
|
||||
/// Runs a mesh dispatch of `x` groups on the host (the title's mesh
|
||||
/// programs are one-dimensional).
|
||||
pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
self.trace("mesh", x, 0);
|
||||
let ran = self.prepare_for(list, false, true)
|
||||
&& match list.list.cast::<ID3D12GraphicsCommandList6>() {
|
||||
Ok(l6) => {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("mesh {x}"), false));
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { l6.DispatchMesh(x, 1, 1) };
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
dropped();
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = ran;
|
||||
}
|
||||
|
||||
fn roots_ref(&self, compute: bool) -> &Vec<Root> {
|
||||
if compute {
|
||||
&self.compute
|
||||
} else {
|
||||
&self.graphics
|
||||
}
|
||||
}
|
||||
|
||||
fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
|
||||
let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
|
||||
return;
|
||||
};
|
||||
let handle = table + u64::from(u.table_offset_dwords) * 4;
|
||||
let Some(heap) = self.heap_of(handle) else {
|
||||
return;
|
||||
};
|
||||
let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
|
||||
return;
|
||||
};
|
||||
if let Some(view) = host.mirror(index, handle, true) {
|
||||
readable(list, u, &view);
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptors a shader reads through tables. Tables holding a
|
||||
/// constant buffer are made afresh for the draw in dynamic slots, with
|
||||
/// the constant data copied to upload memory when the list is
|
||||
/// submitted: the host wants constant buffers 256-byte aligned, the
|
||||
/// console only 16. Returns those tables' new byte offsets by root
|
||||
/// parameter; the other tables' slots are made from the title's.
|
||||
///
|
||||
/// Within a list, the same table holding the same descriptors is made
|
||||
/// once: its constant data is copied at submission either way, and the
|
||||
/// big tables the world binds would otherwise take hundreds of slots per
|
||||
/// draw, wrapping the dynamic slots onto lists not yet submitted.
|
||||
fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
|
||||
let tables = |u: &&UsedResource| u.root == RootType::Table;
|
||||
let mut fresh: Vec<u8> = used
|
||||
.iter()
|
||||
.filter(tables)
|
||||
.filter(|u| u.kind == ResourceType::Cbv)
|
||||
.map(|u| u.slot)
|
||||
.collect();
|
||||
fresh.sort_unstable();
|
||||
fresh.dedup();
|
||||
for u in used.iter().filter(tables) {
|
||||
if !fresh.contains(&u.slot) {
|
||||
self.table_entry(list, u, compute);
|
||||
}
|
||||
}
|
||||
let mut made = Vec::new();
|
||||
for slot in fresh {
|
||||
let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
|
||||
continue;
|
||||
};
|
||||
let entries: Vec<&UsedResource> = used
|
||||
.iter()
|
||||
.filter(tables)
|
||||
.filter(|u| u.slot == slot)
|
||||
.collect();
|
||||
let Some(heap) = self.heap_of(table) else {
|
||||
continue;
|
||||
};
|
||||
let Some(host) = heap.host() else {
|
||||
continue;
|
||||
};
|
||||
let n = entries
|
||||
.iter()
|
||||
.map(|u| u.table_offset_dwords / 8 + 1)
|
||||
.max()
|
||||
.unwrap_or(1);
|
||||
// The table and what its entries hold (record words).
|
||||
let key = {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
for k in 0..n {
|
||||
let at = table + u64::from(k) * 32;
|
||||
// SAFETY: a descriptor slot in title memory.
|
||||
unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
|
||||
}
|
||||
(table, h.finish())
|
||||
};
|
||||
if let Some(&first) = self.fresh_tables.get(&key) {
|
||||
for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
|
||||
let handle = table + u64::from(u.table_offset_dwords) * 4;
|
||||
if let Some(view) = crate::descriptor::view(handle) {
|
||||
readable(list, u, &view);
|
||||
}
|
||||
}
|
||||
made.push((slot, first * 32));
|
||||
continue;
|
||||
}
|
||||
let Some(first) = host.dynamic(n) else {
|
||||
continue;
|
||||
};
|
||||
self.fresh_tables.insert(key, first);
|
||||
self.dynamic
|
||||
.push((std::ptr::from_ref(heap) as usize, first, n));
|
||||
// The whole range: a shader may index past the entries its
|
||||
// used-resource list names (descriptor arrays).
|
||||
for k in 0..n {
|
||||
let index = first + k;
|
||||
let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
|
||||
match crate::descriptor::view(table + u64::from(k) * 32) {
|
||||
Some(View::Constant(address, size)) => {
|
||||
let Some((gpu, to)) = list.scratch(u64::from(size)) else {
|
||||
host.make_null(index);
|
||||
continue;
|
||||
};
|
||||
list.defer_fill(to, address as *const u8, size as usize);
|
||||
host.constant_at(index, gpu, size);
|
||||
}
|
||||
Some(view) => {
|
||||
host.make_at(index, &view);
|
||||
if let Some(u) = used {
|
||||
readable(list, u, &view);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
host.make_null(index);
|
||||
if used.is_some() {
|
||||
once!(slot, "a table entry without a view");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
made.push((slot, first * 32));
|
||||
}
|
||||
made
|
||||
}
|
||||
|
||||
/// The first draws, at debug level: what they bind and read
|
||||
/// (diagnostics builds).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn trace(&self, kind: &str, count: u32, first: u32) {
|
||||
static TRACED: AtomicU64 = AtomicU64::new(0);
|
||||
if !tracing::enabled!(tracing::Level::DEBUG) {
|
||||
return;
|
||||
}
|
||||
let listed = crate::capture::listed(crate::queue::presented() + 1);
|
||||
let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
|
||||
let targets: Vec<String> = self
|
||||
.targets
|
||||
.iter()
|
||||
.filter_map(|&t| crate::resource::host_resource(t as This))
|
||||
.map(|t| {
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { t.GetDesc() };
|
||||
format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
|
||||
})
|
||||
.collect();
|
||||
let v = self.vertex[0];
|
||||
let line = format!(
|
||||
"{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
|
||||
self.topology,
|
||||
self.pipeline,
|
||||
v.address,
|
||||
v.size,
|
||||
v.stride,
|
||||
self.reads(false)
|
||||
);
|
||||
if logged {
|
||||
tracing::debug!("draw {line}");
|
||||
}
|
||||
let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if frame.len() < 256 {
|
||||
frame.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a draw's shaders read, one line per used resource (diagnostics
|
||||
/// builds).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn reads(&self, compute: bool) -> Vec<String> {
|
||||
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
|
||||
return vec!["no host pipeline".into()];
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for stage in &p.stages {
|
||||
let t = stage.translated();
|
||||
for u in &t.used {
|
||||
let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
|
||||
(RootType::Table, Some(Root::Table(table))) => {
|
||||
let handle = table + u64::from(u.table_offset_dwords) * 4;
|
||||
describe(crate::descriptor::view(handle).as_ref())
|
||||
}
|
||||
(root, _) => format!("{root:?}"),
|
||||
};
|
||||
out.push(format!(
|
||||
"{} {:?} s{}+{}: {what}",
|
||||
stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn draw(
|
||||
&mut self,
|
||||
list: &HostList,
|
||||
vertices: u32,
|
||||
instances: u32,
|
||||
first: u32,
|
||||
first_instance: u32,
|
||||
) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
self.trace("draw", vertices, first);
|
||||
let rects = self.topology == RECTANGLES;
|
||||
let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
|
||||
if ran {
|
||||
// Rectangles were expanded into their own vertex buffers.
|
||||
let (count, from) = if rects {
|
||||
(vertices / 3 * 6, 0)
|
||||
} else {
|
||||
(vertices, first)
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe {
|
||||
list.list
|
||||
.DrawInstanced(count, instances, from, first_instance)
|
||||
};
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
dropped();
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds vertex buffers holding the rectangles of vertices `first..first
|
||||
/// + count` as triangles, made when the list is submitted.
|
||||
fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
|
||||
let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
|
||||
return false;
|
||||
};
|
||||
let rects = u64::from(count / 3);
|
||||
for slot in 0..32 {
|
||||
let elements: Vec<(u32, u32)> = p
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|e| e.slot == slot && !e.per_instance)
|
||||
.map(|e| (e.offset, e.format))
|
||||
.collect();
|
||||
if elements.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let v = self.vertex[slot as usize];
|
||||
let stride = u64::from(v.stride);
|
||||
let from = v.address + u64::from(first) * stride;
|
||||
if v.address == 0
|
||||
|| stride == 0
|
||||
|| u64::from(first + count) * stride > u64::from(v.size)
|
||||
|| crate::shadow::find(from, rects * 3 * stride).is_none()
|
||||
{
|
||||
once!(slot, "rectangle vertices outside their buffer");
|
||||
return false;
|
||||
}
|
||||
let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
|
||||
return false;
|
||||
};
|
||||
let (from, to, stride) = (from as usize, to as usize, stride as usize);
|
||||
let n = rects as usize;
|
||||
list.defer_host(move || {
|
||||
// SAFETY: the vertices lie in a title buffer (checked when
|
||||
// recorded) and the scratch memory is the list's.
|
||||
let (src, dst) = unsafe {
|
||||
(
|
||||
std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
|
||||
std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
|
||||
)
|
||||
};
|
||||
crate::primitive::expand_rects(src, dst, stride, &elements);
|
||||
});
|
||||
let view = D3D12_VERTEX_BUFFER_VIEW {
|
||||
BufferLocation: gpu,
|
||||
SizeInBytes: (rects * 6 * stride as u64) as u32,
|
||||
StrideInBytes: v.stride,
|
||||
};
|
||||
// SAFETY: an open list; the view names live scratch memory.
|
||||
unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn draw_indexed(
|
||||
&mut self,
|
||||
list: &HostList,
|
||||
indices: u32,
|
||||
instances: u32,
|
||||
first: u32,
|
||||
base: i32,
|
||||
first_instance: u32,
|
||||
) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
self.trace("indexed", indices, first);
|
||||
if self.topology == RECTANGLES {
|
||||
once!("indexed rectangles not drawn");
|
||||
}
|
||||
let ran = self.topology != RECTANGLES && self.prepare(list, true);
|
||||
if ran {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe {
|
||||
list.list
|
||||
.DrawIndexedInstanced(indices, instances, first, base, first_instance)
|
||||
};
|
||||
DRAWN.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !ran {
|
||||
dropped();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets what a shader reads or writes through a view ready: buffer data
|
||||
/// copied, textures moved to the state they need.
|
||||
fn readable(list: &HostList, u: &UsedResource, view: &View) {
|
||||
const SHADER_RESOURCE: u32 = 0x40 | 0x80;
|
||||
const UNORDERED_ACCESS: u32 = 0x8;
|
||||
let placed = crate::descriptor::host::placed_texture(view);
|
||||
let view = placed.as_ref().unwrap_or(view);
|
||||
// Buffer views read title memory: their range is copied at submission;
|
||||
// what shaders write through unordered access goes back to it after.
|
||||
if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
|
||||
&& len > 0
|
||||
&& let Some(shadow) = crate::shadow::find(address, len)
|
||||
{
|
||||
shadow.refresh(list, address, len);
|
||||
if u.kind == ResourceType::Uav {
|
||||
shadow.gpu_writes(list, address, len);
|
||||
}
|
||||
}
|
||||
match (view, u.kind) {
|
||||
(View::Shader(resource, _), ResourceType::Srv) => {
|
||||
if let Some(t) = crate::resource::host_resource(*resource as This)
|
||||
&& crate::texture::title_written(t)
|
||||
{
|
||||
crate::texture::upload(list, *resource as This, t);
|
||||
}
|
||||
crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(t) = crate::resource::host_resource(*resource as This) {
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { t.GetDesc() };
|
||||
if d.Flags.0 & 7 == 0 {
|
||||
tracing::debug!(
|
||||
resource = format_args!("{resource:#x}"),
|
||||
?d,
|
||||
"a shader reads a texture the title fills"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
(View::Unordered(resource, _, _), ResourceType::Uav) => {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::capture::note_target(*resource as This);
|
||||
crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A view in a few words (diagnostics builds).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn describe(view: Option<&View>) -> String {
|
||||
let texture = |r: This| {
|
||||
crate::resource::host_resource(r).map(|t| {
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { t.GetDesc() };
|
||||
format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
|
||||
})
|
||||
};
|
||||
match view {
|
||||
None => "no view".into(),
|
||||
Some(v @ View::Shader(r, _)) => texture(*r as This)
|
||||
.unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
|
||||
Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
|
||||
Some(View::Placed(u, r, d)) => format!(
|
||||
"placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
|
||||
r[0],
|
||||
u64::from(r[4]) | u64::from(r[5]) << 32,
|
||||
r[6],
|
||||
r[8],
|
||||
r[11],
|
||||
u64::from(d[10]) | u64::from(d[11]) << 32
|
||||
),
|
||||
// The first four values, as a colour rectangle's constants are.
|
||||
Some(View::Constant(address, size))
|
||||
if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
|
||||
{
|
||||
// SAFETY: 16 committed bytes of title memory.
|
||||
let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
|
||||
format!("Constant({address:#x}, {size}) {v:?}")
|
||||
}
|
||||
Some(v) => format!("{v:?}").chars().take(60).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The console's own primitive topologies.
|
||||
const TRIANGLE_FAN: u32 = 6;
|
||||
const RECTANGLES: u32 = 17;
|
||||
const LINE_LOOP: u32 = 18;
|
||||
const QUADS: u32 = 19;
|
||||
const QUAD_STRIP: u32 = 20;
|
||||
|
||||
/// Fixed-function state, straight onto the host list.
|
||||
pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
|
||||
// SAFETY: an open list.
|
||||
unsafe { list.list.RSSetViewports(viewports) };
|
||||
}
|
||||
|
||||
pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
|
||||
// SAFETY: an open list.
|
||||
unsafe { list.list.RSSetScissorRects(rects) };
|
||||
}
|
||||
|
||||
pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
|
||||
// SAFETY: an open list.
|
||||
unsafe { list.list.OMSetBlendFactor(factor) };
|
||||
}
|
||||
|
||||
pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
|
||||
// SAFETY: an open list.
|
||||
unsafe { list.list.OMSetStencilRef(reference) };
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{
|
||||
self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, NOT_FOUND, OUTPUT, Object,
|
||||
S_OK, Table, This, guid,
|
||||
self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, MORE_DATA, NOT_FOUND, OUTPUT,
|
||||
Object, S_OK, Table, This, guid,
|
||||
};
|
||||
|
||||
/// The DXGI device interfaces, base first (as on PC).
|
||||
@@ -132,7 +132,6 @@ struct AdapterDescription {
|
||||
const _: () = assert!(size_of::<AdapterDescription>() == 0x130);
|
||||
|
||||
const AMD: u32 = 0x1002;
|
||||
const GIB: usize = 1 << 30;
|
||||
|
||||
extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT {
|
||||
if out.is_null() {
|
||||
@@ -142,17 +141,18 @@ extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) ->
|
||||
for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) {
|
||||
*slot = unit;
|
||||
}
|
||||
// shortcut: memory sizes are the Series X game split (10 GiB fast,
|
||||
// 3.5 GiB standard), not measured; revisit once memory is emulated.
|
||||
// shortcut: memory sizes are the title's split (GPU-optimal, standard),
|
||||
// not measured; revisit once memory is emulated.
|
||||
let (gpu_optimal, standard) = crate::console::current().title_memory();
|
||||
let description = AdapterDescription {
|
||||
name,
|
||||
vendor: AMD,
|
||||
device: 0,
|
||||
subsystem: 0,
|
||||
revision: 0,
|
||||
dedicated_video_memory: 10 * GIB,
|
||||
dedicated_video_memory: gpu_optimal,
|
||||
dedicated_system_memory: 0,
|
||||
shared_system_memory: 7 * GIB / 2,
|
||||
shared_system_memory: standard,
|
||||
luid: [1, 0],
|
||||
};
|
||||
// SAFETY: checked non-null; the title passes room for the description.
|
||||
@@ -178,8 +178,8 @@ extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HR
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device 5 + 2 + 3.
|
||||
static DEVICE_FUNCTIONS: Table<17> = {
|
||||
let mut f = object::missing_table::<DXGI_DEVICE, 17>();
|
||||
static DEVICE_FUNCTIONS: Table<32> = {
|
||||
let mut f = object::missing_table::<DXGI_DEVICE, 32>();
|
||||
f[0] = device_query as *const ();
|
||||
f[6] = device_parent as *const (); // 0x30
|
||||
f[7] = device_adapter as *const (); // 0x38
|
||||
@@ -187,8 +187,8 @@ static DEVICE_FUNCTIONS: Table<17> = {
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, adapter 3 + 1 + 1.
|
||||
static ADAPTER_FUNCTIONS: Table<12> = {
|
||||
let mut f = object::missing_table::<ADAPTER, 12>();
|
||||
static ADAPTER_FUNCTIONS: Table<24> = {
|
||||
let mut f = object::missing_table::<ADAPTER, 24>();
|
||||
f[0] = adapter_query as *const ();
|
||||
f[6] = adapter_parent as *const (); // 0x30
|
||||
f[7] = adapter_outputs as *const (); // 0x38
|
||||
@@ -197,19 +197,71 @@ static ADAPTER_FUNCTIONS: Table<12> = {
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, factory 5 + 2 + 11.
|
||||
static FACTORY_FUNCTIONS: Table<25> = {
|
||||
let mut f = object::missing_table::<FACTORY, 25>();
|
||||
static FACTORY_FUNCTIONS: Table<32> = {
|
||||
let mut f = object::missing_table::<FACTORY, 32>();
|
||||
f[0] = factory_query as *const ();
|
||||
f[7] = factory_adapters as *const (); // 0x38
|
||||
f[12] = factory_adapters as *const (); // 0x60, the same for version 1
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// A display mode as the console lists it: size, refresh rate (numerator,
|
||||
/// denominator), format, scanline order, scaling, flags.
|
||||
#[repr(C)]
|
||||
struct Mode {
|
||||
width: u32,
|
||||
height: u32,
|
||||
refresh: [u32; 2],
|
||||
format: u32,
|
||||
scanlines: u32,
|
||||
scaling: u32,
|
||||
flags: u32,
|
||||
}
|
||||
const _: () = assert!(size_of::<Mode>() == 32);
|
||||
|
||||
/// The console's mode list: one 4K mode at 60 Hz (Grand Theft Auto VI looks
|
||||
/// for a 120 Hz one to allow 120 Hz frame intervals).
|
||||
/// shortcut: fixed mode, not the host display's; report the host's rates if
|
||||
/// a title paces by them.
|
||||
extern "system" fn modes(
|
||||
_: This,
|
||||
_format: u32,
|
||||
_flags: u32,
|
||||
count: *mut u32,
|
||||
out: *mut Mode,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes its count (null is tolerated).
|
||||
let Some(count) = (unsafe { count.as_mut() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if out.is_null() {
|
||||
*count = 1;
|
||||
return S_OK;
|
||||
}
|
||||
if *count < 1 {
|
||||
return MORE_DATA;
|
||||
}
|
||||
*count = 1;
|
||||
let mode = Mode {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
refresh: [60, 1],
|
||||
format: 0,
|
||||
scanlines: 1, // progressive
|
||||
scaling: 0,
|
||||
flags: 0,
|
||||
};
|
||||
// SAFETY: checked non-null; room for `count` >= 1 modes.
|
||||
unsafe { out.write(mode) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones).
|
||||
static OUTPUT_FUNCTIONS: Table<22> = {
|
||||
let mut f = object::missing_table::<OUTPUT, 22>();
|
||||
static OUTPUT_FUNCTIONS: Table<32> = {
|
||||
let mut f = object::missing_table::<OUTPUT, 32>();
|
||||
f[0] = output_query as *const ();
|
||||
f[6] = output_parent as *const (); // 0x30
|
||||
f[21] = modes as *const (); // 0xa8
|
||||
Table(f)
|
||||
};
|
||||
|
||||
|
||||
@@ -24,7 +24,10 @@ pub(crate) const FENCE_IIDS: [Iid; 4] = [
|
||||
#[repr(C)]
|
||||
struct Fence {
|
||||
object: Object,
|
||||
/// Titles also read it straight from memory, at the fence's GPU
|
||||
/// address.
|
||||
value: AtomicU64,
|
||||
flags: u32,
|
||||
/// Events to set once the value reaches theirs (handles as integers).
|
||||
waiters: Mutex<Vec<(u64, usize)>>,
|
||||
}
|
||||
@@ -45,6 +48,7 @@ pub(crate) extern "system" fn create(
|
||||
let fence = Box::new(Fence {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
value: AtomicU64::new(initial),
|
||||
flags,
|
||||
waiters: Mutex::new(Vec::new()),
|
||||
});
|
||||
object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
|
||||
@@ -106,15 +110,26 @@ pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, fence 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<FENCE, 11>());
|
||||
extern "system" fn creation_flags(this: This) -> u32 {
|
||||
fence(this).flags
|
||||
}
|
||||
/// Where the value lives (GPU addresses are CPU addresses).
|
||||
extern "system" fn gpu_address(this: This) -> u64 {
|
||||
(&raw const fence(this).value) as u64
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console
|
||||
/// one among them).
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<FENCE, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = completed as *const (); // 0x40
|
||||
f[9] = set_event_on_completion as *const (); // 0x48
|
||||
f[10] = signal as *const (); // 0x50
|
||||
f[11] = creation_flags as *const (); // 0x58
|
||||
f[12] = gpu_address as *const (); // 0x60
|
||||
Table(f)
|
||||
};
|
||||
|
||||
@@ -147,6 +162,10 @@ mod tests {
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
|
||||
// Grand Theft Auto VI reads the value at the fence's address.
|
||||
let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f);
|
||||
// SAFETY: the fence's value.
|
||||
assert_eq!(unsafe { *(at as *const u64) }, 5);
|
||||
// SAFETY: ours.
|
||||
unsafe { CloseHandle(event) };
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);
|
||||
|
||||
+126
-39
@@ -1,25 +1,35 @@
|
||||
//! Frame pacing: the title sets a frame interval and waits for each frame
|
||||
//! to begin. Ours is a clock started by the first interval set, ticking
|
||||
//! once per interval; the token is the frame number.
|
||||
//! once per interval; the token is the frame number. Each event kind
|
||||
//! (origin, vblank, flip) happens once per tick, so two waits for the same
|
||||
//! kind never end on the same tick: Grand Theft Auto VI polls the origin
|
||||
//! with "token on time-out" (starting its next frame at once) and is paced
|
||||
//! by a blocking wait for the flip before each present.
|
||||
//!
|
||||
//! shortcut: event offsets and display events are not told apart (all
|
||||
//! waits end on the next tick); tie the clock to presentation once frames
|
||||
//! reach the screen.
|
||||
//! shortcut: event offsets are ignored (every event is at the tick); tie
|
||||
//! the clock to presentation if a title paces by them.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::object::{HRESULT, S_OK, This};
|
||||
use crate::object::{HRESULT, S_FALSE, S_OK, This};
|
||||
|
||||
/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`.
|
||||
const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32;
|
||||
/// What a wait returns when its time is up first.
|
||||
const TIMEOUT: HRESULT = S_FALSE;
|
||||
/// The frame-origin event: the one that starts frames and makes tokens.
|
||||
const ORIGIN: u32 = 0;
|
||||
/// Make the frame's token even if the wait times out (the title starts the
|
||||
/// frame early).
|
||||
const TOKEN_ON_TIMEOUT: u32 = 2;
|
||||
const SIXTIETH: Duration = Duration::from_micros(16_667);
|
||||
|
||||
struct Clock {
|
||||
start: Instant,
|
||||
interval: Duration,
|
||||
/// The tick number at `start` (ticks go on across interval changes).
|
||||
first: u64,
|
||||
}
|
||||
|
||||
static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
|
||||
@@ -29,29 +39,32 @@ fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> {
|
||||
CLOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Device method: `periods` intervals of `length` microseconds per frame.
|
||||
/// Device method: a frame every `length` microseconds. The period is how
|
||||
/// many intervals a frame may take to reach the display (pipeline depth),
|
||||
/// not part of the rate.
|
||||
pub(crate) extern "system" fn set_interval(
|
||||
_: This,
|
||||
_output: This,
|
||||
length: u32,
|
||||
periods: u32,
|
||||
_period: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
let interval = match u64::from(length) * u64::from(periods.max(1)) {
|
||||
let interval = match length {
|
||||
0 => SIXTIETH,
|
||||
us => Duration::from_micros(us),
|
||||
us => Duration::from_micros(u64::from(us)),
|
||||
};
|
||||
tracing::info!(?interval, "frame interval");
|
||||
let mut clock = clock();
|
||||
match clock.as_mut() {
|
||||
Some(c) => c.interval = interval,
|
||||
None => {
|
||||
*clock = Some(Clock {
|
||||
start: Instant::now(),
|
||||
interval,
|
||||
})
|
||||
}
|
||||
}
|
||||
// A new interval starts from now, after the last tick handed out.
|
||||
let first = LAST
|
||||
.iter()
|
||||
.map(|t| t.load(Ordering::Relaxed))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
*clock() = Some(Clock {
|
||||
start: Instant::now(),
|
||||
interval,
|
||||
first,
|
||||
});
|
||||
S_OK
|
||||
}
|
||||
|
||||
@@ -66,42 +79,84 @@ pub(crate) extern "system" fn schedule(
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// How long until the next tick.
|
||||
fn until_next_tick() -> Duration {
|
||||
/// Frames begun so far (frame waits that ended).
|
||||
pub(crate) fn current() -> u64 {
|
||||
FRAME.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Per event kind (origin, vblank, flip and later kinds): the last tick a
|
||||
/// wait for it ended on.
|
||||
static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
|
||||
|
||||
fn last(kind: u32) -> &'static AtomicU64 {
|
||||
&LAST[(kind as usize).min(LAST.len() - 1)]
|
||||
}
|
||||
|
||||
/// The next tick after now and after the last one a wait for `kind` ended
|
||||
/// on (an event happens once per tick: a wait woken a little early must not
|
||||
/// let the next one end on the same tick), and how long until it.
|
||||
fn next_tick(kind: u32) -> (u64, Duration) {
|
||||
let mut clock = clock();
|
||||
let c = clock.get_or_insert_with(|| Clock {
|
||||
start: Instant::now(),
|
||||
interval: SIXTIETH,
|
||||
first: 0,
|
||||
});
|
||||
let elapsed = c.start.elapsed().as_nanos();
|
||||
let interval = c.interval.as_nanos().max(1);
|
||||
let next = (elapsed / interval + 1) * interval;
|
||||
Duration::from_nanos((next - elapsed) as u64)
|
||||
let tick =
|
||||
(c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1);
|
||||
let at = u128::from(tick - c.first) * interval;
|
||||
(
|
||||
tick,
|
||||
Duration::from_nanos(at.saturating_sub(elapsed) as u64),
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method: blocks until the next tick, then hands out the frame's
|
||||
/// token.
|
||||
/// Device method: blocks until the next tick (or the time-out); an origin
|
||||
/// wait then hands out the new frame's token. Other events keep the token
|
||||
/// the title passes. Ticks are absolute (start plus whole intervals), so
|
||||
/// lateness never accumulates.
|
||||
pub(crate) extern "system" fn wait(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
kind: u32,
|
||||
timeout_ms: u32,
|
||||
_list: *const u8,
|
||||
_flags: u32,
|
||||
flags: u32,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
let wait = until_next_tick();
|
||||
let origin = kind == ORIGIN;
|
||||
let (tick, wait) = next_tick(kind);
|
||||
let limit = Duration::from_millis(u64::from(timeout_ms));
|
||||
if wait > limit {
|
||||
let hr = if wait > limit {
|
||||
std::thread::sleep(limit);
|
||||
return TIMEOUT;
|
||||
TIMEOUT
|
||||
} else {
|
||||
std::thread::sleep(wait);
|
||||
last(kind).fetch_max(tick, Ordering::Relaxed);
|
||||
S_OK
|
||||
};
|
||||
// A frame begun on a time-out takes no tick: its flip still does.
|
||||
if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) {
|
||||
// Tokens count frames (consecutive), not ticks.
|
||||
let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if !token.is_null() {
|
||||
// SAFETY: checked non-null; the title passes its token.
|
||||
unsafe { token.write(frame) };
|
||||
}
|
||||
}
|
||||
std::thread::sleep(wait);
|
||||
let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if !token.is_null() {
|
||||
// SAFETY: checked non-null; the title passes its token.
|
||||
unsafe { token.write(frame) };
|
||||
}
|
||||
S_OK
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tracing::debug!(
|
||||
kind,
|
||||
timeout_ms,
|
||||
flags,
|
||||
hr,
|
||||
tick,
|
||||
wait_us = wait.as_micros() as u64,
|
||||
frame = current(),
|
||||
"frame wait"
|
||||
);
|
||||
hr
|
||||
}
|
||||
|
||||
/// Device method: no statistics are kept, so none are returned.
|
||||
@@ -135,5 +190,37 @@ mod tests {
|
||||
assert!(second > first);
|
||||
assert!(before.elapsed() <= Duration::from_millis(50));
|
||||
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
|
||||
// Tokens count frames, a frame started early on a time-out too.
|
||||
let mut early = 0;
|
||||
let flags = TOKEN_ON_TIMEOUT;
|
||||
assert_eq!(
|
||||
wait(null, 0, 0, std::ptr::null(), flags, &mut early),
|
||||
TIMEOUT
|
||||
);
|
||||
let mut next = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK);
|
||||
assert!(early == second + 1 && next == early + 1);
|
||||
assert!(LAST[0].load(Ordering::Relaxed) >= 2);
|
||||
|
||||
// The title's loop (the clock is global, so in the same test): an
|
||||
// origin poll that times out (and starts the frame), then a
|
||||
// blocking flip wait. Each flip takes its own tick.
|
||||
const FLIP: u32 = 2;
|
||||
assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK);
|
||||
let mut token = 0;
|
||||
let flips: Vec<u64> = (0..4)
|
||||
.map(|_| {
|
||||
let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token);
|
||||
assert_eq!(
|
||||
wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token),
|
||||
S_OK
|
||||
);
|
||||
LAST[2].load(Ordering::Relaxed)
|
||||
})
|
||||
.collect();
|
||||
assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}");
|
||||
// Even when a flip wait begins on the tick another just ended on.
|
||||
let (tick, _) = next_tick(FLIP);
|
||||
assert!(tick > flips[3]);
|
||||
}
|
||||
}
|
||||
+1022
-53
File diff suppressed because it is too large.
Load diff
@@ -12,10 +12,18 @@
|
||||
//! descriptor heaps, [`root`] root signatures, [`query`] query heaps,
|
||||
//! [`signature`] command signatures, [`pipeline`] pipeline states,
|
||||
//! [`frame`] frame pacing, [`object`] what all console graphics objects
|
||||
//! share. Planned: `present` (swap chain).
|
||||
//! share, [`console`] which console model the title sees. Planned:
|
||||
//! `present` (swap chain).
|
||||
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod capture;
|
||||
pub mod console;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod copystat;
|
||||
pub mod descriptor;
|
||||
pub mod device;
|
||||
#[cfg(windows)]
|
||||
mod draw;
|
||||
pub mod dxgi;
|
||||
pub mod fence;
|
||||
pub mod frame;
|
||||
@@ -24,8 +32,25 @@ mod host;
|
||||
pub mod list;
|
||||
pub mod object;
|
||||
pub mod pipeline;
|
||||
#[cfg(windows)]
|
||||
mod primitive;
|
||||
pub mod query;
|
||||
pub mod queue;
|
||||
pub mod resource;
|
||||
pub mod root;
|
||||
#[cfg(windows)]
|
||||
mod sampler;
|
||||
#[cfg(windows)]
|
||||
pub mod shader_cache;
|
||||
#[cfg(windows)]
|
||||
mod shadow;
|
||||
pub mod signature;
|
||||
#[cfg(windows)]
|
||||
mod texture;
|
||||
#[cfg(windows)]
|
||||
mod watch;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use host::on_failure;
|
||||
#[cfg(windows)]
|
||||
pub use watch::{title_memory_remapped, writing as kernel_will_write};
|
||||
+725
-48
@@ -5,9 +5,9 @@
|
||||
//! lists keep the pointer and every limit at zero, so every command reaches
|
||||
//! the table as a call.
|
||||
//!
|
||||
//! shortcut: the methods record nothing yet; unwritten ones log once, so a
|
||||
//! run lists what to translate. Translate them onto host command lists
|
||||
//! (TODO.md, GPU).
|
||||
//! Each list records onto a host command list as its methods are called
|
||||
//! (decision 0007); draw state lives in [`crate::draw`]. Methods not
|
||||
//! written yet log once with their caller, so a run lists what to do next.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::mem::offset_of;
|
||||
@@ -15,6 +15,7 @@ use std::mem::offset_of;
|
||||
use crate::object::{
|
||||
self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
|
||||
};
|
||||
use crate::queue::Written;
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const ALLOCATOR_IIDS: [Iid; 4] = [
|
||||
@@ -29,9 +30,11 @@ const ALLOCATOR_IIDS: [Iid; 4] = [
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
/// The list interfaces whose ids are the same as on PC, then the device
|
||||
/// child's.
|
||||
const LIST_IIDS: [Iid; 8] = [
|
||||
/// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has
|
||||
/// all their slots): those whose ids are the same as on PC, the console's
|
||||
/// own List5 and List6 (Grand Theft Auto VI asks for List6), then the
|
||||
/// device child's.
|
||||
const LIST_IIDS: [Iid; 10] = [
|
||||
guid(
|
||||
0x7116d91c,
|
||||
0xe7e4,
|
||||
@@ -68,6 +71,18 @@ const LIST_IIDS: [Iid; 8] = [
|
||||
0x4541,
|
||||
[0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
|
||||
),
|
||||
guid(
|
||||
0x55050859,
|
||||
0x4024,
|
||||
0x474c,
|
||||
[0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
|
||||
),
|
||||
guid(
|
||||
0xc3827890,
|
||||
0x4024,
|
||||
0x474c,
|
||||
[0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
|
||||
),
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
@@ -91,14 +106,33 @@ struct List {
|
||||
graphics_root_headers: [u32; 128],
|
||||
compute_root_headers: [u32; 128],
|
||||
pipeline_shadow: [u32; 8],
|
||||
/// Ours, after the console layout: the host list the calls record
|
||||
/// into (decision 0007).
|
||||
/// Newer titles' lists are larger: Grand Theft Auto VI's state flush
|
||||
/// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and
|
||||
/// tests +0x548, so its layout runs past 0x560. Its size is unknown;
|
||||
/// this keeps our fields clear of whatever the title writes there.
|
||||
newer: [u32; 256],
|
||||
/// Ours, after the console layout: memory handed out by
|
||||
/// [`allocate_upload`], kept until the list is reset; the host list the
|
||||
/// calls record into (decision 0007), and the draw state the title set.
|
||||
uploads: std::sync::Mutex<Vec<Vec<u8>>>,
|
||||
#[cfg(windows)]
|
||||
host: Option<crate::host::HostList>,
|
||||
#[cfg(windows)]
|
||||
state: std::sync::Mutex<crate::draw::State>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(List, put) == 0x18);
|
||||
const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
|
||||
|
||||
/// Runs `f` with the host list and draw state of a title list, if there
|
||||
/// is a host GPU.
|
||||
#[cfg(windows)]
|
||||
fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) {
|
||||
let Some(list) = host_list(this) else { return };
|
||||
// SAFETY: the title passes one of our lists.
|
||||
let state = unsafe { &(*this.cast::<List>()).state };
|
||||
f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
}
|
||||
|
||||
/// The host list behind a title list, if there is a host GPU.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
|
||||
@@ -168,13 +202,19 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES
|
||||
}
|
||||
tracing::debug!(kind, "command list");
|
||||
let list = Box::new(List {
|
||||
object: Object::new(&LIST_FUNCTIONS),
|
||||
object: if crate::device::newer() {
|
||||
Object::new(&NEWER_LIST_FUNCTIONS)
|
||||
} else {
|
||||
Object::new(&LIST_FUNCTIONS)
|
||||
},
|
||||
kind,
|
||||
put: [0; 5],
|
||||
reserved: [0; 64],
|
||||
graphics_root_headers: [0; 128],
|
||||
compute_root_headers: [0; 128],
|
||||
pipeline_shadow: [0; 8],
|
||||
newer: [0; 256],
|
||||
uploads: Default::default(),
|
||||
#[cfg(windows)]
|
||||
host: crate::host::host().and_then(|h| match h.new_list() {
|
||||
Ok(list) => Some(list),
|
||||
@@ -183,6 +223,8 @@ fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRES
|
||||
None
|
||||
}
|
||||
}),
|
||||
#[cfg(windows)]
|
||||
state: Default::default(),
|
||||
});
|
||||
object::hand_out(LIST, list, iid, &LIST_IIDS, out)
|
||||
}
|
||||
@@ -216,14 +258,21 @@ extern "system" fn close(this: This) -> HRESULT {
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT {
|
||||
extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT {
|
||||
if allocator.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// Every submission of the list has run (submissions are waited for).
|
||||
// SAFETY: the title passes one of our lists.
|
||||
let uploads = unsafe { &(*this.cast::<List>()).uploads };
|
||||
uploads.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = host_list(this) {
|
||||
with_state(this, |host, state| {
|
||||
host.reset();
|
||||
}
|
||||
state.reset(pipeline);
|
||||
});
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, pipeline);
|
||||
S_OK
|
||||
}
|
||||
|
||||
@@ -243,7 +292,7 @@ pub(crate) struct Barrier {
|
||||
/// The barrier on host resources, or `None` if it names a resource the host
|
||||
/// GPU does not have (buffers so far).
|
||||
#[cfg(windows)]
|
||||
fn host_barrier(b: &Barrier) -> Option<Barrier> {
|
||||
fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
|
||||
use windows::core::Interface;
|
||||
let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
|
||||
match b.kind {
|
||||
@@ -253,16 +302,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> {
|
||||
if b.flags & BEGIN_ONLY != 0 {
|
||||
return None;
|
||||
}
|
||||
// shortcut: whole resources, from the state we tracked (see
|
||||
// `host_transition`); subresources are not told apart.
|
||||
// shortcut: whole resources, from the state the list tracked
|
||||
// (`HostList::transition`); subresources are not told apart.
|
||||
let wanted = crate::host::texture_state(b.last as u32);
|
||||
let (resource, before) = crate::resource::host_transition(b.first, wanted)?;
|
||||
let (texture, before) = list.transition(b.first, wanted)?;
|
||||
Some(Barrier {
|
||||
kind: 0,
|
||||
flags: 0,
|
||||
first: resource.cast_const().cast(),
|
||||
first: texture.as_raw().cast_const().cast(),
|
||||
second: 0xffff_ffff | (u64::from(before) << 32),
|
||||
last: u64::from(wanted),
|
||||
last: u64::from(crate::host::legal_state(texture, wanted)),
|
||||
})
|
||||
}
|
||||
1 => Some(Barrier {
|
||||
@@ -290,6 +339,16 @@ fn host_barrier(b: &Barrier) -> Option<Barrier> {
|
||||
}
|
||||
}
|
||||
|
||||
/// An unordered access barrier on every resource: earlier shader writes
|
||||
/// finish before later work reads or writes.
|
||||
const UAV_BARRIER: Barrier = Barrier {
|
||||
kind: 2,
|
||||
flags: 0,
|
||||
first: std::ptr::null(),
|
||||
second: 0,
|
||||
last: 0,
|
||||
};
|
||||
|
||||
/// Returns the console's barrier "actions" (none).
|
||||
extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
|
||||
#[cfg(windows)]
|
||||
@@ -298,7 +357,17 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
|
||||
{
|
||||
// SAFETY: the title passes `count` barriers.
|
||||
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
|
||||
let host: Vec<Barrier> = barriers.iter().filter_map(host_barrier).collect();
|
||||
let mut host: Vec<Barrier> = barriers
|
||||
.iter()
|
||||
.filter_map(|b| host_barrier(list, b))
|
||||
.collect();
|
||||
// Buffers have host copies, not resources the barrier can name:
|
||||
// a barrier on one waits for every shader write before it.
|
||||
if barriers.iter().any(|b| {
|
||||
b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
|
||||
}) {
|
||||
host.push(UAV_BARRIER);
|
||||
}
|
||||
if !host.is_empty() {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
|
||||
const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
|
||||
@@ -319,11 +388,10 @@ extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) ->
|
||||
|
||||
/// Moves a title texture's host copy to `state` in the list, if needed.
|
||||
#[cfg(windows)]
|
||||
fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
|
||||
pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
if let Some(texture) = crate::resource::host_resource(resource)
|
||||
&& let Some((_, before)) = crate::resource::host_transition(resource, state)
|
||||
{
|
||||
if let Some((texture, before)) = list.transition(resource, state) {
|
||||
let state = crate::host::legal_state(texture, state);
|
||||
let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
|
||||
// SAFETY: an open list and a live texture.
|
||||
unsafe { list.list.ResourceBarrier(&[barrier]) };
|
||||
@@ -380,6 +448,9 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
|
||||
) {
|
||||
ensure_state(list, dst, COPY_DEST);
|
||||
ensure_state(list, src, COPY_SOURCE);
|
||||
crate::texture::host_written(dst);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
|
||||
// SAFETY: an open list and live textures.
|
||||
unsafe { list.list.CopyResource(to, from) };
|
||||
} else if let (Some((to, a)), Some((from, b))) = (
|
||||
@@ -461,9 +532,26 @@ extern "system" fn copy_texture_region(
|
||||
from.resource = texture.as_raw().cast_const().cast();
|
||||
}
|
||||
ensure_state(list, dst.resource, COPY_DEST);
|
||||
crate::texture::host_written(dst.resource);
|
||||
let mut to_location = dst;
|
||||
to_location.resource = to.as_raw().cast_const().cast();
|
||||
let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| {
|
||||
// SAFETY: a live texture; the box is the title's or null.
|
||||
let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
|
||||
format!(
|
||||
"copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
|
||||
dst.resource,
|
||||
d.Width,
|
||||
d.Height,
|
||||
d.Format.0,
|
||||
dst.kind,
|
||||
src.resource,
|
||||
src.kind,
|
||||
(src.kind == FOOTPRINT).then_some(src.footprint)
|
||||
)
|
||||
});
|
||||
const _: () =
|
||||
assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
|
||||
// SAFETY: an open list; both locations in the host's layout, naming
|
||||
@@ -522,6 +610,9 @@ extern "system" fn resolve(
|
||||
const RESOLVE_SOURCE: u32 = 0x2000;
|
||||
ensure_state(list, dst, RESOLVE_DEST);
|
||||
ensure_state(list, src, RESOLVE_SOURCE);
|
||||
crate::texture::host_written(dst);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
|
||||
// SAFETY: an open list and live textures; the region is inside both.
|
||||
unsafe {
|
||||
let (a, b) = (to.GetDesc(), from.GetDesc());
|
||||
@@ -594,9 +685,7 @@ extern "system" fn clear_rtv(
|
||||
let rtv = host.rtv(texture, record.desc().as_ref());
|
||||
// SAFETY: an open list, a fresh view of a live texture.
|
||||
unsafe {
|
||||
if let Some((_, before)) =
|
||||
crate::resource::host_transition(record.resource, RENDER_TARGET)
|
||||
{
|
||||
if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
list.list.ResourceBarrier(&[crate::host::transition(
|
||||
texture,
|
||||
@@ -611,9 +700,137 @@ extern "system" fn clear_rtv(
|
||||
let _ = (this, handle, color, count, rects);
|
||||
}
|
||||
|
||||
/// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
|
||||
/// flags: 1 depth, 2 stencil.
|
||||
extern "system" fn clear_dsv(
|
||||
this: This,
|
||||
handle: u64,
|
||||
flags: u32,
|
||||
depth: f32,
|
||||
stencil: u8,
|
||||
count: u32,
|
||||
rects: *const Rect,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
|
||||
let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (Some(texture), Some(host)) = (
|
||||
crate::resource::host_resource(record.resource),
|
||||
crate::host::host(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let rects = (count > 0 && !rects.is_null()).then(|| {
|
||||
// SAFETY: the title passes `count` rectangles, laid out as the host's.
|
||||
unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
|
||||
});
|
||||
const DEPTH_WRITE: u32 = 0x10;
|
||||
ensure_state(list, record.resource, DEPTH_WRITE);
|
||||
let dsv = host.dsv(texture, record.depth_desc().as_ref());
|
||||
// SAFETY: an open list, a fresh view of a live texture.
|
||||
unsafe {
|
||||
list.list
|
||||
.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
|
||||
};
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, handle, flags, depth, stencil, count, rects);
|
||||
}
|
||||
|
||||
/// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
|
||||
/// are title memory, copied at submission like buffer copies (if mapped).
|
||||
extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& dst != 0
|
||||
&& src != 0
|
||||
{
|
||||
let len = len as usize;
|
||||
list.defer(move || {
|
||||
if crate::texture::committed(src as *const u8, len)
|
||||
&& crate::texture::committed(dst as *const u8, len)
|
||||
{
|
||||
// SAFETY: both ranges are committed title memory.
|
||||
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, src, len);
|
||||
}
|
||||
|
||||
/// `DriverHintX(feature, value)`: no hints for the host.
|
||||
extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
|
||||
0
|
||||
}
|
||||
|
||||
/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
|
||||
/// host has no use for (the ray-tracing builder dispatches this way).
|
||||
extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
|
||||
#[cfg(windows)]
|
||||
state::dispatch(this, x, y, z);
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (this, x, y, z);
|
||||
count_dispatch();
|
||||
}
|
||||
}
|
||||
|
||||
/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
|
||||
/// resolved.
|
||||
extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
|
||||
|
||||
/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
|
||||
/// each query's result into the buffer once the list has run. Timestamps
|
||||
/// (type 2) are the GPU clock then; occlusion counts (0) say a million
|
||||
/// samples passed and binary occlusion (1) visible, so nothing is culled
|
||||
/// by a query.
|
||||
/// shortcut: no query runs on the host GPU; results are plausible values,
|
||||
/// not measured ones (time spans come out as the submission's length).
|
||||
extern "system" fn resolve_queries(
|
||||
this: This,
|
||||
_heap: This,
|
||||
kind: u32,
|
||||
_first: u32,
|
||||
count: u32,
|
||||
buffer: This,
|
||||
offset: u64,
|
||||
) {
|
||||
const OCCLUSION: u32 = 0;
|
||||
const BINARY: u32 = 1;
|
||||
const TIMESTAMP: u32 = 2;
|
||||
const PIPELINE_STATISTICS: u32 = 3;
|
||||
let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
|
||||
return;
|
||||
};
|
||||
let (what, bytes) = match kind {
|
||||
OCCLUSION => (Written::Value(1 << 20), 8),
|
||||
BINARY => (Written::Value(1), 8),
|
||||
TIMESTAMP => (Written::GpuTimestamp, 8),
|
||||
PIPELINE_STATISTICS => (Written::Value(0), 88),
|
||||
_ => (Written::Value(0), 16),
|
||||
};
|
||||
if offset + u64::from(count) * bytes > size {
|
||||
return;
|
||||
}
|
||||
for i in 0..u64::from(count) {
|
||||
// Wider results are written as 8-byte pieces.
|
||||
for piece in 0..bytes / 8 {
|
||||
// SAFETY: inside the buffer, checked above.
|
||||
let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
|
||||
let what = if piece == 0 { what } else { Written::Value(0) };
|
||||
defer_write(this, at as u64, what, 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, allocator 2.
|
||||
static ALLOCATOR_FUNCTIONS: Table<10> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 10>());
|
||||
static ALLOCATOR_FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
|
||||
f[0] = allocator_query as *const ();
|
||||
f[2] = allocator_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
@@ -622,26 +839,472 @@ static ALLOCATOR_FUNCTIONS: Table<10> = {
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, list 1, graphics list 96 (59 as
|
||||
/// on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 + 13).
|
||||
static LIST_FUNCTIONS: Table<140> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<LIST, 140>());
|
||||
f[0] = list_query as *const ();
|
||||
f[2] = list_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = list_type as *const (); // 0x40
|
||||
f[9] = close as *const (); // 0x48
|
||||
f[10] = reset as *const (); // 0x50
|
||||
f[15] = copy_buffer_region as *const (); // 0x78
|
||||
f[16] = copy_texture_region as *const (); // 0x80
|
||||
f[17] = copy_resource as *const (); // 0x88
|
||||
f[19] = resolve as *const (); // 0x98
|
||||
f[26] = barrier as *const (); // 0xd0
|
||||
f[83] = copy_texture_region_x as *const (); // 0x298
|
||||
f[84] = copy_resource_x as *const (); // 0x2a0
|
||||
f[52] = clear_rtv as *const (); // 0x1a0
|
||||
Table(f)
|
||||
};
|
||||
extern "system" fn set_pipeline(this: This, pipeline: This) {
|
||||
crate::pipeline::bound(pipeline);
|
||||
#[cfg(windows)]
|
||||
with_state(this, |_, state| state.set_pipeline(pipeline));
|
||||
#[cfg(not(windows))]
|
||||
let _ = this;
|
||||
}
|
||||
|
||||
/// Pipeline syncs: waits for earlier work and cache flushes, at the top or
|
||||
/// bottom of the pipe `(flags, control, address, size)`. Host lists order
|
||||
/// their own work and every submission is waited for, so there is nothing
|
||||
/// to do.
|
||||
extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {}
|
||||
|
||||
/// Reset with console flags `(allocator, pipeline, flags)`; the flags only
|
||||
/// tune the console's command memory.
|
||||
extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
|
||||
reset(this, allocator, pipeline)
|
||||
}
|
||||
|
||||
/// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
|
||||
/// owns until it is reset, which the CPU writes and the GPU reads at the
|
||||
/// same address; null on failure. Grand Theft Auto VI's BVH builder puts
|
||||
/// its instance descriptions there (and wrote through our old
|
||||
/// `E_NOTIMPL` as a pointer).
|
||||
extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
|
||||
let align = usize::try_from(alignment).unwrap_or(0).max(16);
|
||||
let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
if this.is_null() || !align.is_power_of_two() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let mut block = vec![0u8; len];
|
||||
let start = block.as_mut_ptr();
|
||||
// SAFETY: the offset is below `align`, so `size` bytes fit after it.
|
||||
let at = unsafe { start.add(start.align_offset(align)) };
|
||||
// SAFETY: the title passes one of our lists.
|
||||
let uploads = unsafe { &(*this.cast::<List>()).uploads };
|
||||
// Moving the vector keeps its heap block where it is.
|
||||
uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
|
||||
at
|
||||
}
|
||||
|
||||
/// Draw state the host has no use for (root signatures: ours come with
|
||||
/// the pipeline; depth bounds, depth order and shading rate hints): any
|
||||
/// arguments, nothing returned.
|
||||
extern "system" fn ignored_state(_: This) {}
|
||||
|
||||
/// The title's draw state (decision 0007, step 3), kept for its draws or
|
||||
/// set on the host list at once. Without a host GPU these do nothing.
|
||||
#[cfg(windows)]
|
||||
mod state {
|
||||
use super::{This, host_list, with_state};
|
||||
use crate::draw::{IndexView, VertexView};
|
||||
use windows::Win32::Foundation::RECT;
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
|
||||
|
||||
/// `count` items at `items`, or none.
|
||||
fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
|
||||
if items.is_null() || count == 0 {
|
||||
return &[];
|
||||
}
|
||||
// SAFETY: the title passes `count` items.
|
||||
unsafe { std::slice::from_raw_parts(items, count as usize) }
|
||||
}
|
||||
|
||||
pub(super) extern "system" fn topology(this: This, topology: u32) {
|
||||
with_state(this, |list, s| s.set_topology(list, topology));
|
||||
}
|
||||
pub(super) extern "system" fn viewports(
|
||||
this: This,
|
||||
count: u32,
|
||||
viewports: *const D3D12_VIEWPORT,
|
||||
) {
|
||||
if let Some(list) = host_list(this) {
|
||||
crate::draw::viewports(list, items(viewports, count));
|
||||
}
|
||||
}
|
||||
pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
|
||||
if let Some(list) = host_list(this) {
|
||||
crate::draw::scissors(list, items(rects, count));
|
||||
}
|
||||
}
|
||||
pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
|
||||
if let Some(list) = host_list(this) {
|
||||
// SAFETY: the title passes four floats or null.
|
||||
crate::draw::blend_factor(list, unsafe { factor.as_ref() });
|
||||
}
|
||||
}
|
||||
pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
|
||||
if let Some(list) = host_list(this) {
|
||||
crate::draw::stencil_ref(list, reference);
|
||||
}
|
||||
}
|
||||
pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
|
||||
with_state(this, |_, s| s.set_heaps(items(heaps, count)));
|
||||
}
|
||||
pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
|
||||
with_state(this, |_, s| s.set_table(true, slot, handle));
|
||||
}
|
||||
pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
|
||||
with_state(this, |_, s| s.set_table(false, slot, handle));
|
||||
}
|
||||
pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
|
||||
with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
|
||||
}
|
||||
pub(super) extern "system" fn graphics_constant(
|
||||
this: This,
|
||||
slot: u32,
|
||||
value: u32,
|
||||
offset: u32,
|
||||
) {
|
||||
with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
|
||||
}
|
||||
pub(super) extern "system" fn compute_constants(
|
||||
this: This,
|
||||
slot: u32,
|
||||
count: u32,
|
||||
values: *const u32,
|
||||
offset: u32,
|
||||
) {
|
||||
with_state(this, |_, s| {
|
||||
s.set_constants(true, slot, items(values, count), offset)
|
||||
});
|
||||
}
|
||||
pub(super) extern "system" fn graphics_constants(
|
||||
this: This,
|
||||
slot: u32,
|
||||
count: u32,
|
||||
values: *const u32,
|
||||
offset: u32,
|
||||
) {
|
||||
with_state(this, |_, s| {
|
||||
s.set_constants(false, slot, items(values, count), offset)
|
||||
});
|
||||
}
|
||||
/// Root constant buffer, shader resource and unordered access views.
|
||||
pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
|
||||
with_state(this, |_, s| s.set_view(true, slot, address));
|
||||
}
|
||||
pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
|
||||
with_state(this, |_, s| s.set_view(false, slot, address));
|
||||
}
|
||||
pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
|
||||
// SAFETY: the title passes a view or null.
|
||||
with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
|
||||
}
|
||||
pub(super) extern "system" fn vertex_buffers(
|
||||
this: This,
|
||||
start: u32,
|
||||
count: u32,
|
||||
views: *const VertexView,
|
||||
) {
|
||||
with_state(this, |_, s| {
|
||||
s.set_vertex_buffers(start, items(views, count))
|
||||
});
|
||||
}
|
||||
/// `(count, handles, one range, depth)`: with one range, the handles
|
||||
/// follow the first at the render target view size (128 bytes).
|
||||
pub(super) extern "system" fn targets(
|
||||
this: This,
|
||||
count: u32,
|
||||
handles: *const u64,
|
||||
one_range: i32,
|
||||
depth: *const u64,
|
||||
) {
|
||||
let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
|
||||
// SAFETY: the title passes the first handle.
|
||||
let first = unsafe { *handles };
|
||||
(0..u64::from(count)).map(|i| first + 128 * i).collect()
|
||||
} else {
|
||||
items(handles, count).to_vec()
|
||||
};
|
||||
// SAFETY: the title passes a handle or null.
|
||||
let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
|
||||
with_state(this, |list, s| s.set_targets(list, &handles, depth));
|
||||
}
|
||||
pub(super) extern "system" fn draw(
|
||||
this: This,
|
||||
vertices: u32,
|
||||
instances: u32,
|
||||
first: u32,
|
||||
first_instance: u32,
|
||||
) {
|
||||
super::count_draw();
|
||||
with_state(this, |list, s| {
|
||||
s.draw(list, vertices, instances, first, first_instance)
|
||||
});
|
||||
}
|
||||
pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
|
||||
super::count_dispatch();
|
||||
with_state(this, |list, s| s.dispatch(list, x, y, z));
|
||||
}
|
||||
/// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
|
||||
/// programs take `x` groups only.
|
||||
pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
|
||||
super::count_draw();
|
||||
if y * z != 1 {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
|
||||
}
|
||||
with_state(this, |list, s| s.dispatch_mesh(list, x));
|
||||
}
|
||||
/// `DispatchMeshX(x, flags, indirect arguments, payload)`.
|
||||
/// shortcut: dispatches whose group count is in GPU memory (indirect)
|
||||
/// are dropped; make them ExecuteIndirect when the title uses them.
|
||||
pub(super) extern "system" fn dispatch_mesh_x(
|
||||
this: This,
|
||||
x: u32,
|
||||
_flags: u64,
|
||||
indirect: u64,
|
||||
_payload: u64,
|
||||
) {
|
||||
super::count_draw();
|
||||
if indirect != 0 {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
|
||||
return;
|
||||
}
|
||||
with_state(this, |list, s| s.dispatch_mesh(list, x));
|
||||
}
|
||||
pub(super) extern "system" fn draw_indexed(
|
||||
this: This,
|
||||
indices: u32,
|
||||
instances: u32,
|
||||
first: u32,
|
||||
base: i32,
|
||||
first_instance: u32,
|
||||
) {
|
||||
super::count_draw();
|
||||
with_state(this, |list, s| {
|
||||
s.draw_indexed(list, indices, instances, first, base, first_instance)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a host GPU every draw state call is ignored.
|
||||
#[cfg(not(windows))]
|
||||
mod state {
|
||||
pub(super) use super::dispatch;
|
||||
pub(super) use super::draw;
|
||||
pub(super) use super::draw as draw_indexed;
|
||||
pub(super) use super::draw as dispatch_mesh;
|
||||
pub(super) use super::draw as dispatch_mesh_x;
|
||||
pub(super) use super::ignored_state as blend_factor;
|
||||
pub(super) use super::ignored_state as compute_constant;
|
||||
pub(super) use super::ignored_state as compute_constants;
|
||||
pub(super) use super::ignored_state as compute_table;
|
||||
pub(super) use super::ignored_state as compute_view;
|
||||
pub(super) use super::ignored_state as graphics_constant;
|
||||
pub(super) use super::ignored_state as graphics_constants;
|
||||
pub(super) use super::ignored_state as graphics_table;
|
||||
pub(super) use super::ignored_state as graphics_view;
|
||||
pub(super) use super::ignored_state as heaps;
|
||||
pub(super) use super::ignored_state as index_buffer;
|
||||
pub(super) use super::ignored_state as scissors;
|
||||
pub(super) use super::ignored_state as stencil_ref;
|
||||
pub(super) use super::ignored_state as targets;
|
||||
pub(super) use super::ignored_state as topology;
|
||||
pub(super) use super::ignored_state as vertex_buffers;
|
||||
pub(super) use super::ignored_state as viewports;
|
||||
}
|
||||
|
||||
fn count_draw() {
|
||||
DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Draws of the kinds the host does not run yet (indirect, mesh), and
|
||||
/// dispatches, counted per frame for the log.
|
||||
/// shortcut: dropped until their shaders translate (decision 0007).
|
||||
extern "system" fn draw(_: This) {
|
||||
count_draw();
|
||||
}
|
||||
fn count_dispatch() {
|
||||
DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
extern "system" fn dispatch(_: This) {
|
||||
count_dispatch();
|
||||
}
|
||||
static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Draws (any kind, mesh and indirect included) and compute dispatches
|
||||
/// recorded since the last call.
|
||||
pub(crate) fn take_counts() -> (u64, u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
(DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
|
||||
}
|
||||
|
||||
/// A GPU wait for a memory value `(address, comparison, reference, ...)`.
|
||||
/// Lists run one after another and to completion, so a value another queue
|
||||
/// or the CPU has to write first cannot be waited for; nothing to do.
|
||||
extern "system" fn wait_value(_: This, _address: u64, _comparison: u32, _reference: u64) {}
|
||||
|
||||
/// The enhanced barriers `(group count, groups)`: buffer, texture and
|
||||
/// global barriers with layouts instead of states. Every host use of a
|
||||
/// title texture (clears, copies) moves its host copy to the state it needs
|
||||
/// first, so only their ordering matters: one barrier on every shader
|
||||
/// write (the title's buffer barriers order compute passes).
|
||||
extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
|
||||
#[cfg(windows)]
|
||||
if count > 0
|
||||
&& let Some(list) = host_list(this)
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
|
||||
// SAFETY: the same layout; no resource named.
|
||||
let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
|
||||
// SAFETY: an open list.
|
||||
unsafe { list.list.ResourceBarrier(&[barrier]) };
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, count);
|
||||
}
|
||||
|
||||
/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
|
||||
/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
|
||||
/// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
|
||||
extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
|
||||
defer_write(this, address, Written::Value(u64::from(value)), 4);
|
||||
}
|
||||
extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
|
||||
const GPU_TIMESTAMP: u32 = 1;
|
||||
const SYSTEM_TIMESTAMP: u32 = 2;
|
||||
let what = match flags {
|
||||
GPU_TIMESTAMP => Written::GpuTimestamp,
|
||||
SYSTEM_TIMESTAMP => Written::SystemTimestamp,
|
||||
_ => Written::Value(value),
|
||||
};
|
||||
defer_write(this, address, what, 8);
|
||||
}
|
||||
|
||||
fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
|
||||
if address == 0 {
|
||||
return;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this) {
|
||||
list.defer_write(address as *mut u8, what, bytes);
|
||||
return;
|
||||
}
|
||||
let _ = this;
|
||||
// Without a host GPU nothing runs later: write now.
|
||||
what.write(address as *mut u8, bytes);
|
||||
}
|
||||
|
||||
/// The list methods by their slot in older titles' lists (the 2020-era
|
||||
/// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
|
||||
/// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
|
||||
/// + 13): 140 slots.
|
||||
const METHODS: [(usize, *const ()); 52] = [
|
||||
(0, list_query as *const ()),
|
||||
(2, list_release as *const ()),
|
||||
(7, object::parent_device as *const ()), // 0x38
|
||||
(8, list_type as *const ()), // 0x40
|
||||
(9, close as *const ()), // 0x48
|
||||
(10, reset as *const ()), // 0x50
|
||||
(12, state::draw as *const ()), // 0x60 instanced
|
||||
(13, state::draw_indexed as *const ()), // 0x68 indexed
|
||||
(14, state::dispatch as *const ()), // 0x70
|
||||
(15, copy_buffer_region as *const ()), // 0x78
|
||||
(16, copy_texture_region as *const ()), // 0x80
|
||||
(17, copy_resource as *const ()), // 0x88
|
||||
(19, resolve as *const ()), // 0x98
|
||||
(20, state::topology as *const ()), // 0xa0
|
||||
(21, state::viewports as *const ()), // 0xa8
|
||||
(22, state::scissors as *const ()), // 0xb0
|
||||
(23, state::blend_factor as *const ()), // 0xb8
|
||||
(24, state::stencil_ref as *const ()), // 0xc0
|
||||
(25, set_pipeline as *const ()), // 0xc8
|
||||
(26, barrier as *const ()), // 0xd0
|
||||
(32, state::heaps as *const ()), // 0x100
|
||||
(33, ignored_state as *const ()), // 0x108 compute root signature
|
||||
(34, ignored_state as *const ()), // 0x110 graphics root signature
|
||||
(35, state::compute_table as *const ()), // 0x118
|
||||
(36, state::graphics_table as *const ()), // 0x120
|
||||
(37, state::compute_constant as *const ()), // 0x128
|
||||
(38, state::graphics_constant as *const ()), // 0x130
|
||||
(39, state::compute_constants as *const ()), // 0x138
|
||||
(40, state::graphics_constants as *const ()), // 0x140
|
||||
(41, state::compute_view as *const ()), // 0x148 CBV
|
||||
(42, state::graphics_view as *const ()), // 0x150 CBV
|
||||
(43, state::compute_view as *const ()), // 0x158 SRV
|
||||
(44, state::graphics_view as *const ()), // 0x160 SRV
|
||||
(45, state::compute_view as *const ()), // 0x168 UAV
|
||||
(46, state::graphics_view as *const ()), // 0x170 UAV
|
||||
(47, state::index_buffer as *const ()), // 0x178
|
||||
(48, state::vertex_buffers as *const ()), // 0x180
|
||||
(50, state::targets as *const ()), // 0x190
|
||||
(51, clear_dsv as *const ()), // 0x198
|
||||
(52, clear_rtv as *const ()), // 0x1a0
|
||||
(59, draw as *const ()), // 0x1d8 indirect
|
||||
(60, copy_memory as *const ()), // 0x1e0
|
||||
(68, ignored_state as *const ()), // 0x220 depth bounds
|
||||
(69, write32 as *const ()), // 0x228
|
||||
(70, write64 as *const ()), // 0x230
|
||||
(71, wait_value as *const ()), // 0x238, 32 bits
|
||||
(72, wait_value as *const ()), // 0x240, 64 bits
|
||||
(73, ignored_state as *const ()), // 0x248 pixel shader depth order
|
||||
(83, copy_texture_region_x as *const ()), // 0x298
|
||||
(84, copy_resource_x as *const ()), // 0x2a0
|
||||
(124, ignored_state as *const ()), // 0x3e0 shading rate
|
||||
(127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
|
||||
];
|
||||
/// The rest of [`METHODS`], kept apart only to stay readable.
|
||||
const MORE_METHODS: [(usize, *const ()); 9] = [
|
||||
(28, query_mark as *const ()), // 0xe0 BeginQuery
|
||||
(29, query_mark as *const ()), // 0xe8 EndQuery
|
||||
(30, resolve_queries as *const ()), // 0xf0
|
||||
(78, dispatch_x as *const ()), // 0x270
|
||||
(98, state::dispatch_mesh_x as *const ()), // 0x310
|
||||
(99, driver_hint as *const ()), // 0x318
|
||||
// Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
|
||||
(129, sync as *const ()),
|
||||
(130, sync as *const ()),
|
||||
(137, reset_x as *const ()), // 0x448
|
||||
];
|
||||
|
||||
/// Newer titles' lists have two more methods in the console part of the
|
||||
/// base list, after the clears (0x198/0x1a0 as before) and before
|
||||
/// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
|
||||
/// on is two later (taken here as starting exactly at 0x1d8). Inferred from
|
||||
/// Grand Theft Auto VI's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
|
||||
/// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
|
||||
/// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
|
||||
const fn newer_slot(slot: usize) -> usize {
|
||||
if slot >= 59 { slot + 2 } else { slot }
|
||||
}
|
||||
|
||||
/// Methods only newer titles' lists have. 0x490: the enhanced barrier
|
||||
/// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
|
||||
/// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
|
||||
/// called from Grand Theft Auto VI's state flush with its result unused.
|
||||
/// shortcut: 0x470's purpose is unknown; ignored until a title shows it
|
||||
/// matters.
|
||||
const NEWER_METHODS: [(usize, *const ()); 3] = [
|
||||
(142, ignored_state as *const ()),
|
||||
(146, barrier_groups as *const ()),
|
||||
(148, allocate_upload as *const ()),
|
||||
];
|
||||
|
||||
const fn list_table(newer: bool) -> [*const (); 160] {
|
||||
let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
|
||||
let mut i = 0;
|
||||
while i < METHODS.len() + MORE_METHODS.len() {
|
||||
let (slot, method) = if i < METHODS.len() {
|
||||
METHODS[i]
|
||||
} else {
|
||||
MORE_METHODS[i - METHODS.len()]
|
||||
};
|
||||
f[if newer { newer_slot(slot) } else { slot }] = method;
|
||||
i += 1;
|
||||
}
|
||||
let mut i = 0;
|
||||
while newer && i < NEWER_METHODS.len() {
|
||||
f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
|
||||
i += 1;
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// Every slot up to the limit exists and logs, for the methods newer
|
||||
/// titles add.
|
||||
static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
|
||||
static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -666,11 +1329,25 @@ mod tests {
|
||||
(at(0x18), at(0x28), at(0x30))
|
||||
};
|
||||
assert!(put >= draw_limit && put >= api_limit);
|
||||
// The console's ID3D12GraphicsCommandList6, as Grand Theft Auto VI asks.
|
||||
let mut same = null;
|
||||
assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
|
||||
assert_eq!(same, list);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
|
||||
S_OK
|
||||
);
|
||||
// List-owned upload memory: aligned, writable, gone at reset.
|
||||
let p = allocate_upload(list, 40, 0x100);
|
||||
assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
|
||||
// SAFETY: 40 bytes were handed out.
|
||||
unsafe { p.write_bytes(0xab, 40) };
|
||||
assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
|
||||
assert_eq!(reset(list, allocator, null), S_OK);
|
||||
// SAFETY: the list is ours.
|
||||
assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
|
||||
let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
|
||||
assert_eq!(release(list), 0);
|
||||
assert_eq!(release(allocator), 0);
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
/// What D3D and DXGI return for a missing item (adapter, output, private
|
||||
/// data).
|
||||
pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32;
|
||||
const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32;
|
||||
pub(crate) const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32;
|
||||
|
||||
pub type Iid = [u8; 16];
|
||||
|
||||
@@ -275,19 +275,54 @@ const MAX_SLOTS: usize = 160;
|
||||
static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] =
|
||||
[const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()];
|
||||
|
||||
/// Logged once per slot. Wrong for a slot that returns a value instead of
|
||||
/// Logged once per slot, with the caller's offset in its module (the title
|
||||
/// image for title calls). Wrong for a slot that returns a value instead of
|
||||
/// an `HRESULT`.
|
||||
extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT {
|
||||
if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!(
|
||||
object = KINDS[KIND],
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
caller = caller(),
|
||||
"method not implemented"
|
||||
);
|
||||
}
|
||||
E_NOTIMPL
|
||||
}
|
||||
|
||||
/// The return address of whoever called our caller, as `+offset` into its
|
||||
/// module.
|
||||
#[inline(never)]
|
||||
fn caller() -> String {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
GetModuleHandleExW,
|
||||
};
|
||||
let mut frame = std::ptr::null_mut();
|
||||
// SAFETY: room for one frame; skips this function and its caller.
|
||||
if unsafe { RtlCaptureStackBackTrace(2, 1, &mut frame, std::ptr::null_mut()) } == 1 {
|
||||
let mut module = std::ptr::null_mut();
|
||||
// SAFETY: looks up the module holding the address, no reference.
|
||||
let found = unsafe {
|
||||
GetModuleHandleExW(
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
|
||||
| GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
frame as *const u16,
|
||||
&mut module,
|
||||
)
|
||||
};
|
||||
if found != 0 {
|
||||
return format!("+{:#x}", frame as usize - module as usize);
|
||||
}
|
||||
return format!("{frame:?}");
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Accepts and ignores (debug-only settings).
|
||||
pub(crate) extern "system" fn ignore() -> HRESULT {
|
||||
S_OK
|
||||
@@ -298,6 +333,8 @@ macro_rules! missing {
|
||||
}
|
||||
|
||||
/// A table of `N` slots that log and fail; callers fill in what they have.
|
||||
/// Tables are made longer than the interfaces we know, so that a method a
|
||||
/// newer title adds logs instead of jumping into whatever follows the table.
|
||||
pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*const (); N] {
|
||||
let all = missing!(KIND;
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
//! Pipeline states. Both descriptions start as on PC: the root signature,
|
||||
//! then the shader stages (five for graphics, one for compute); only those
|
||||
//! are read so far.
|
||||
//! then the shader stages (five for graphics, one for compute); streams
|
||||
//! carry the rest of the graphics state as subobjects of the standard
|
||||
//! types.
|
||||
//!
|
||||
//! shortcut: the console shader containers are kept, not translated, and
|
||||
//! the rest of the description is ignored. Translate through the cache
|
||||
//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte
|
||||
//! Host pipelines are made on a pipeline's first draw, not at creation:
|
||||
//! Grand Theft Auto VI creates some 60,000 pipelines in its first 20
|
||||
//! seconds and draws with a few dozen (decision 0007, step 3). Shader
|
||||
//! containers are shared by content hash and translated once, on first
|
||||
//! use (decision 0003).
|
||||
//!
|
||||
//! shortcut: only vertex plus pixel pipelines from streams and compute
|
||||
//! pipelines get host pipelines; mesh, tessellation and geometry stages,
|
||||
//! and the plain graphics description, keep their containers only. The 32-byte
|
||||
//! packet after the header stays zero: titles only copy it inline, which
|
||||
//! our null command-list limits keep from running.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::mem::offset_of;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
@@ -45,30 +54,183 @@ pub(crate) struct ComputeHead {
|
||||
stage: Bytecode,
|
||||
}
|
||||
|
||||
/// A shader container a title passed, shared by every pipeline with the
|
||||
/// same bytes.
|
||||
pub(crate) struct Shader {
|
||||
pub(crate) stage: &'static str,
|
||||
/// The first 8 bytes of its BLAKE3, as logged.
|
||||
pub(crate) hash: String,
|
||||
container: Vec<u8>,
|
||||
#[cfg(windows)]
|
||||
translated: OnceLock<Option<Translated>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Shader {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{} {}", self.stage, self.hash)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every container seen, by full content hash.
|
||||
static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
|
||||
|
||||
/// The shared container for `bytes`.
|
||||
fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
|
||||
let full = blake3::hash(bytes);
|
||||
let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
shaders
|
||||
.get_or_insert_with(HashMap::new)
|
||||
.entry(*full.as_bytes())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(Shader {
|
||||
stage,
|
||||
hash: full.to_hex()[..16].to_owned(),
|
||||
container: bytes.to_vec(),
|
||||
#[cfg(windows)]
|
||||
translated: OnceLock::new(),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// A translated shader and the console resources its code reads.
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct Translated {
|
||||
pub(crate) host: victory_shader::emit::HostShader,
|
||||
pub(crate) used: Vec<victory_shader::UsedResource>,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Shader {
|
||||
/// The translation, made on first use; a shader that does not
|
||||
/// translate is logged once.
|
||||
pub(crate) fn translated(&self) -> Option<&Translated> {
|
||||
self.translated
|
||||
.get_or_init(|| {
|
||||
let done = translate(&self.container);
|
||||
match &done {
|
||||
Ok(t) => tracing::info!(
|
||||
stage = self.stage,
|
||||
hash = %self.hash,
|
||||
user_data = t.host.user_data.len(),
|
||||
samplers = t.host.samplers.len(),
|
||||
"shader translated"
|
||||
),
|
||||
Err(e) => tracing::warn!(
|
||||
stage = self.stage,
|
||||
hash = %self.hash,
|
||||
error = %e,
|
||||
"shader does not translate; its pipelines' draws are dropped"
|
||||
),
|
||||
}
|
||||
done.ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn translate(container: &[u8]) -> Result<Translated, String> {
|
||||
use victory_shader::{Container, FourCC, HwStage};
|
||||
let host = crate::shader_cache::host_shader(container)?;
|
||||
let c = Container::parse(container).map_err(|e| e.to_string())?;
|
||||
let used = match c.part(FourCC::DXIL) {
|
||||
Some(part) => victory_shader::native_programs(part.data)
|
||||
.map_err(|e| e.to_string())?
|
||||
.into_iter()
|
||||
.find(|p| {
|
||||
matches!(
|
||||
p.stage,
|
||||
HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
|
||||
)
|
||||
})
|
||||
.map(|p| p.used)
|
||||
.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(Translated { host, used })
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Pipeline {
|
||||
object: Object,
|
||||
packet: [u32; 8],
|
||||
/// Each stage's container, empty when the stage is unused.
|
||||
shaders: Vec<Vec<u8>>,
|
||||
/// Each used stage's container.
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
/// Whether a list has bound it yet (its shaders are logged then).
|
||||
bound: std::sync::atomic::AtomicBool,
|
||||
/// The rest of a stream's graphics state, for the host pipeline.
|
||||
#[cfg(windows)]
|
||||
graphics: Option<Box<host::GraphicsState>>,
|
||||
#[cfg(windows)]
|
||||
host: OnceLock<Option<host::HostPipeline>>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
|
||||
|
||||
fn copy(stage: &Bytecode) -> Vec<u8> {
|
||||
if stage.code.is_null() || stage.size == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec()
|
||||
/// Stage names, in description order.
|
||||
const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"];
|
||||
|
||||
fn pipeline<'a>(this: This) -> &'a Pipeline {
|
||||
// SAFETY: the title passes one of our pipelines.
|
||||
unsafe { &*this.cast::<Pipeline>() }
|
||||
}
|
||||
|
||||
fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect();
|
||||
tracing::debug!(?sizes, "pipeline state");
|
||||
/// List method: logs each pipeline's shaders the first time a list binds
|
||||
/// it, so a run lists the shaders its frames need first.
|
||||
pub(crate) fn bound(this: This) {
|
||||
if this.is_null() {
|
||||
return;
|
||||
}
|
||||
let p = pipeline(this);
|
||||
if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let frame = crate::frame::current();
|
||||
for shader in &p.shaders {
|
||||
tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind");
|
||||
}
|
||||
}
|
||||
|
||||
/// The host pipeline of a title pipeline, made on first use; `None` if one
|
||||
/// of its shaders does not translate or the host refuses it.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
let p = pipeline(this);
|
||||
p.host
|
||||
.get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref()))
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The stage's container, if it has one.
|
||||
fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> {
|
||||
if code.code.is_null() || code.size == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
Some(shader(stage, unsafe {
|
||||
std::slice::from_raw_parts(code.code, code.size)
|
||||
}))
|
||||
}
|
||||
|
||||
fn hand_out(
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
#[cfg(windows)] graphics: Option<Box<host::GraphicsState>>,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
tracing::trace!(?shaders, "pipeline state");
|
||||
let pipeline = Box::new(Pipeline {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
packet: [0; 8],
|
||||
shaders,
|
||||
bound: std::sync::atomic::AtomicBool::new(false),
|
||||
#[cfg(windows)]
|
||||
graphics,
|
||||
#[cfg(windows)]
|
||||
host: OnceLock::new(),
|
||||
});
|
||||
object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
|
||||
}
|
||||
@@ -84,7 +246,15 @@ pub(crate) extern "system" fn create_graphics(
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(desc.stages.iter().map(copy).collect(), iid, out)
|
||||
let stages = GRAPHICS_STAGES.iter().zip(&desc.stages);
|
||||
let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect();
|
||||
hand_out(
|
||||
shaders,
|
||||
#[cfg(windows)]
|
||||
None,
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
@@ -98,7 +268,115 @@ pub(crate) extern "system" fn create_compute(
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(vec![copy(&desc.stage)], iid, out)
|
||||
hand_out(
|
||||
copy("compute", &desc.stage).into_iter().collect(),
|
||||
#[cfg(windows)]
|
||||
None,
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method 0x1f0: the plain compute description plus console
|
||||
/// extensions `(desc, extension count, extensions, iid, out)`.
|
||||
/// shortcut: the extensions (console shader settings) are ignored, as is
|
||||
/// the rest of the description.
|
||||
pub(crate) extern "system" fn create_compute_x(
|
||||
this: This,
|
||||
desc: *const ComputeHead,
|
||||
_extensions: u32,
|
||||
_extended: *const u8,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
create_compute(this, desc, iid, out)
|
||||
}
|
||||
|
||||
/// A pipeline described as a stream: its size and the subobjects, each a
|
||||
/// type then its data, padded to 8 bytes.
|
||||
#[repr(C)]
|
||||
pub(crate) struct StreamDesc {
|
||||
size: usize,
|
||||
stream: *const u8,
|
||||
}
|
||||
|
||||
/// A subobject type's size (type included), and the stage it is if it is a
|
||||
/// shader. The console numbers amplification and mesh shaders 23 and 24
|
||||
/// (PC: 24 and 25); its own types from 25 on are not sized yet.
|
||||
fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> {
|
||||
let stage = |name| Some((24, Some(name)));
|
||||
match kind {
|
||||
1 => stage("vertex"),
|
||||
2 => stage("pixel"),
|
||||
3 => stage("domain"),
|
||||
4 => stage("hull"),
|
||||
5 => stage("geometry"),
|
||||
6 => stage("compute"),
|
||||
23 => stage("amplification"),
|
||||
24 => stage("mesh"),
|
||||
0 => Some((16, None)),
|
||||
12 | 19 => Some((24, None)),
|
||||
7 | 15 => Some((40, None)),
|
||||
8 => Some((336, None)),
|
||||
10 => Some((48, None)),
|
||||
11 => Some((56, None)),
|
||||
17 => Some((16, None)),
|
||||
21 => Some((64, None)),
|
||||
22 => Some((32, None)),
|
||||
9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: a pipeline from a stream; the shaders are kept, and the
|
||||
/// graphics state for the host pipeline.
|
||||
pub(crate) extern "system" fn create_stream(
|
||||
_: This,
|
||||
desc: *const StreamDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.stream.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut shaders = Vec::new();
|
||||
#[cfg(windows)]
|
||||
let mut graphics = host::GraphicsState::default();
|
||||
let mut at = 0;
|
||||
while at + 8 <= desc.size {
|
||||
// SAFETY: inside the stream the title passes.
|
||||
let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() };
|
||||
let Some((size, stage)) = subobject(kind) else {
|
||||
tracing::warn!(
|
||||
kind,
|
||||
at,
|
||||
"pipeline subobject of unknown size; the rest is ignored"
|
||||
);
|
||||
break;
|
||||
};
|
||||
if let Some(stage) = stage {
|
||||
// SAFETY: a shader subobject has its bytecode at +8.
|
||||
let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() };
|
||||
shaders.extend(copy(stage, code));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
// SAFETY: a whole subobject of this kind lies at `at`.
|
||||
unsafe {
|
||||
graphics.read(kind, desc.stream.add(at))
|
||||
};
|
||||
at += size;
|
||||
}
|
||||
hand_out(
|
||||
shaders,
|
||||
#[cfg(windows)]
|
||||
Some(Box::new(graphics)),
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
@@ -110,19 +388,30 @@ extern "system" fn release(this: This) -> u32 {
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, pipeline 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) mod host;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> {
|
||||
pipeline(p)
|
||||
.shaders
|
||||
.iter()
|
||||
.map(|s| (s.stage, s.container.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipelines_keep_their_shaders() {
|
||||
let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
|
||||
@@ -151,11 +440,71 @@ mod tests {
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: one of our pipelines.
|
||||
let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders };
|
||||
assert_eq!(shaders[0], vs);
|
||||
assert_eq!(shaders[1], ps);
|
||||
assert!(shaders[2].is_empty());
|
||||
assert_eq!(
|
||||
shaders(p),
|
||||
[("vertex", vs.to_vec()), ("pixel", ps.to_vec())]
|
||||
);
|
||||
// A second pipeline with the same pixel shader shares its container.
|
||||
let mut q = std::ptr::null();
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q);
|
||||
assert!(Arc::ptr_eq(
|
||||
&pipeline(p).shaders[1],
|
||||
&pipeline(q).shaders[1]
|
||||
));
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
|
||||
}
|
||||
|
||||
/// The stream layout Grand Theft Auto VI builds (title+0x86f090): root
|
||||
/// signature, five shader slots (the first a mesh shader), blend, sample
|
||||
/// mask, rasterizer, depth-stencil 1, sample description, input layout,
|
||||
/// topology, render target and depth formats: 0x2b0 bytes.
|
||||
#[test]
|
||||
fn streams_yield_their_shaders() {
|
||||
let (ms, ps) = ([9u8; 7], [4u8; 5]);
|
||||
let mut stream = vec![0u8; 0x2b0];
|
||||
let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes());
|
||||
for (at, kind) in [
|
||||
(0x10, 24),
|
||||
(0x28, 2),
|
||||
(0x40, 3),
|
||||
(0x58, 4),
|
||||
(0x70, 5),
|
||||
(0x88, 8),
|
||||
(0x1d8, 9),
|
||||
(0x1e0, 10),
|
||||
(0x210, 21),
|
||||
(0x250, 17),
|
||||
(0x260, 12),
|
||||
(0x278, 14),
|
||||
(0x280, 15),
|
||||
(0x2a8, 16),
|
||||
] {
|
||||
put(at, kind);
|
||||
}
|
||||
put(0x18, ms.as_ptr() as u64);
|
||||
put(0x20, ms.len() as u64);
|
||||
put(0x30, ps.as_ptr() as u64);
|
||||
put(0x38, ps.len() as u64);
|
||||
// Topology type 3 (triangles), one render target of format 28.
|
||||
put(0x278, 14 | 3 << 32);
|
||||
put(0x280, 15 | 28 << 32);
|
||||
put(0x2a0, 1 << 32);
|
||||
let desc = StreamDesc {
|
||||
size: stream.len(),
|
||||
stream: stream.as_ptr(),
|
||||
};
|
||||
let mut p = std::ptr::null();
|
||||
let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p);
|
||||
assert_eq!(hr, S_OK);
|
||||
assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let g = pipeline(p).graphics.as_deref().unwrap();
|
||||
assert_eq!(g.topology.0, 3);
|
||||
assert_eq!(
|
||||
(g.targets.NumRenderTargets, g.targets.RTFormats[0].0),
|
||||
(1, 28)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
//! Host pipelines for title pipelines (decision 0007, step 3): the
|
||||
//! title's graphics state with the translated shaders, under a root
|
||||
//! signature of our own that the translated shaders' bindings define
|
||||
//! (`victory_shader::emit`): per stage one block of root constants for the
|
||||
//! user data, root views for the title's root views, static samplers for
|
||||
//! the immediate samplers, and directly indexed heaps.
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::sync::Arc;
|
||||
|
||||
use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
|
||||
use windows::Win32::Graphics::Direct3D::ID3DBlob;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::core::PCSTR;
|
||||
|
||||
use super::{Shader, Translated};
|
||||
use crate::host::host;
|
||||
|
||||
/// A stream's graphics state, owned (the title's stream lives only for the
|
||||
/// creation call). Subobjects the stream leaves out keep D3D12's defaults.
|
||||
pub(crate) struct GraphicsState {
|
||||
blend: D3D12_BLEND_DESC,
|
||||
sample_mask: u32,
|
||||
rasterizer: D3D12_RASTERIZER_DESC,
|
||||
depth: D3D12_DEPTH_STENCIL_DESC,
|
||||
/// Input elements, their names pointing into `names`.
|
||||
inputs: Vec<D3D12_INPUT_ELEMENT_DESC>,
|
||||
names: Vec<CString>,
|
||||
strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
|
||||
pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
pub(crate) targets: D3D12_RT_FORMAT_ARRAY,
|
||||
depth_format: DXGI_FORMAT,
|
||||
samples: DXGI_SAMPLE_DESC,
|
||||
}
|
||||
|
||||
impl Default for GraphicsState {
|
||||
fn default() -> Self {
|
||||
let target = D3D12_RENDER_TARGET_BLEND_DESC {
|
||||
SrcBlend: D3D12_BLEND_ONE,
|
||||
DestBlend: D3D12_BLEND_ZERO,
|
||||
BlendOp: D3D12_BLEND_OP_ADD,
|
||||
SrcBlendAlpha: D3D12_BLEND_ONE,
|
||||
DestBlendAlpha: D3D12_BLEND_ZERO,
|
||||
BlendOpAlpha: D3D12_BLEND_OP_ADD,
|
||||
LogicOp: D3D12_LOGIC_OP_NOOP,
|
||||
RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8,
|
||||
..Default::default()
|
||||
};
|
||||
let keep = D3D12_DEPTH_STENCILOP_DESC {
|
||||
StencilFailOp: D3D12_STENCIL_OP_KEEP,
|
||||
StencilDepthFailOp: D3D12_STENCIL_OP_KEEP,
|
||||
StencilPassOp: D3D12_STENCIL_OP_KEEP,
|
||||
StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS,
|
||||
};
|
||||
GraphicsState {
|
||||
blend: D3D12_BLEND_DESC {
|
||||
RenderTarget: [target; 8],
|
||||
..Default::default()
|
||||
},
|
||||
sample_mask: u32::MAX,
|
||||
rasterizer: D3D12_RASTERIZER_DESC {
|
||||
FillMode: D3D12_FILL_MODE_SOLID,
|
||||
CullMode: D3D12_CULL_MODE_BACK,
|
||||
DepthClipEnable: true.into(),
|
||||
..Default::default()
|
||||
},
|
||||
depth: D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: true.into(),
|
||||
DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL,
|
||||
DepthFunc: D3D12_COMPARISON_FUNC_LESS,
|
||||
StencilReadMask: 0xff,
|
||||
StencilWriteMask: 0xff,
|
||||
FrontFace: keep,
|
||||
BackFace: keep,
|
||||
..Default::default()
|
||||
},
|
||||
inputs: Vec::new(),
|
||||
names: Vec::new(),
|
||||
strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED,
|
||||
topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED,
|
||||
targets: D3D12_RT_FORMAT_ARRAY::default(),
|
||||
depth_format: DXGI_FORMAT_UNKNOWN,
|
||||
samples: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphicsState {
|
||||
/// Takes in one subobject of a stream: its type, then its data at +4
|
||||
/// (+8 for those holding pointers).
|
||||
///
|
||||
/// # Safety
|
||||
/// `at` points at a whole subobject of type `kind`.
|
||||
pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) {
|
||||
// SAFETY: the caller passes a whole subobject.
|
||||
unsafe {
|
||||
let data = at.add(4);
|
||||
match kind {
|
||||
8 => self.blend = data.cast::<D3D12_BLEND_DESC>().read_unaligned(),
|
||||
9 => self.sample_mask = data.cast::<u32>().read_unaligned(),
|
||||
10 => self.rasterizer = data.cast::<D3D12_RASTERIZER_DESC>().read_unaligned(),
|
||||
11 => self.depth = data.cast::<D3D12_DEPTH_STENCIL_DESC>().read_unaligned(),
|
||||
21 => {
|
||||
// shortcut: the depth bounds test is dropped (the host
|
||||
// pipeline uses the plain description); bring it back
|
||||
// with a stream if a title enables it.
|
||||
let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
|
||||
self.depth = D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: d.DepthEnable,
|
||||
DepthWriteMask: d.DepthWriteMask,
|
||||
DepthFunc: d.DepthFunc,
|
||||
StencilEnable: d.StencilEnable,
|
||||
StencilReadMask: d.StencilReadMask,
|
||||
StencilWriteMask: d.StencilWriteMask,
|
||||
FrontFace: d.FrontFace,
|
||||
BackFace: d.BackFace,
|
||||
};
|
||||
}
|
||||
12 => {
|
||||
let layout = at.add(8).cast::<D3D12_INPUT_LAYOUT_DESC>().read_unaligned();
|
||||
if layout.pInputElementDescs.is_null() {
|
||||
return;
|
||||
}
|
||||
let elements = std::slice::from_raw_parts(
|
||||
layout.pInputElementDescs,
|
||||
layout.NumElements as usize,
|
||||
);
|
||||
self.names = elements
|
||||
.iter()
|
||||
.map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned())
|
||||
.collect();
|
||||
self.inputs = elements
|
||||
.iter()
|
||||
.zip(&self.names)
|
||||
.map(|(e, name)| D3D12_INPUT_ELEMENT_DESC {
|
||||
SemanticName: PCSTR(name.as_ptr().cast()),
|
||||
Format: DXGI_FORMAT(
|
||||
crate::resource::pc_format(e.Format.0 as u32) as i32
|
||||
),
|
||||
..*e
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
13 => {
|
||||
self.strip_cut =
|
||||
D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::<i32>().read_unaligned())
|
||||
}
|
||||
14 => {
|
||||
self.topology =
|
||||
D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::<i32>().read_unaligned())
|
||||
}
|
||||
15 => {
|
||||
self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
|
||||
for f in &mut self.targets.RTFormats {
|
||||
f.0 = crate::resource::pc_format(f.0 as u32) as i32;
|
||||
}
|
||||
}
|
||||
16 => {
|
||||
let f = data.cast::<u32>().read_unaligned();
|
||||
self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32);
|
||||
}
|
||||
17 => self.samples = data.cast::<DXGI_SAMPLE_DESC>().read_unaligned(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The vertex buffer slots the input layout reads.
|
||||
fn slots(&self) -> u32 {
|
||||
self.inputs
|
||||
.iter()
|
||||
.fold(0, |m, e| m | 1 << e.InputSlot.min(31))
|
||||
}
|
||||
|
||||
/// The input elements with their byte offsets worked out.
|
||||
fn elements(&self) -> Vec<Input> {
|
||||
let mut next = [0u32; 32];
|
||||
self.inputs
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let slot = e.InputSlot.min(31) as usize;
|
||||
let format = e.Format.0 as u32;
|
||||
let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT {
|
||||
next[slot]
|
||||
} else {
|
||||
e.AlignedByteOffset
|
||||
};
|
||||
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
|
||||
next[slot] = offset + bytes;
|
||||
Input {
|
||||
slot: slot as u32,
|
||||
offset,
|
||||
format,
|
||||
per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// One input element: vertex buffer slot, byte offset, format.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Input {
|
||||
pub(crate) slot: u32,
|
||||
pub(crate) offset: u32,
|
||||
pub(crate) format: u32,
|
||||
pub(crate) per_instance: bool,
|
||||
}
|
||||
|
||||
/// The console's own primitive topology types.
|
||||
const RECTANGLES: i32 = 19;
|
||||
const QUADS: i32 = 32;
|
||||
|
||||
/// One stage of a host pipeline and where its bindings go.
|
||||
pub(crate) struct Stage {
|
||||
pub(crate) shader: Arc<Shader>,
|
||||
/// The root parameter of its user data, and its size in dwords.
|
||||
pub(crate) user_data: Option<(u32, u32)>,
|
||||
/// Root parameters of its root views: (title root parameter, ours).
|
||||
pub(crate) root_cbvs: Vec<(u8, u32)>,
|
||||
pub(crate) root_srvs: Vec<(u8, u32)>,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
pub(crate) fn translated(&self) -> &Translated {
|
||||
self.shader
|
||||
.translated()
|
||||
.expect("host pipelines are made from translated shaders")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct HostPipeline {
|
||||
/// A compute pipeline (else graphics).
|
||||
pub(crate) compute: bool,
|
||||
/// A mesh pipeline (graphics without vertex input).
|
||||
pub(crate) mesh: bool,
|
||||
pub(crate) pso: ID3D12PipelineState,
|
||||
pub(crate) root: ID3D12RootSignature,
|
||||
/// Vertex, then pixel stage, or the compute stage.
|
||||
pub(crate) stages: Vec<Stage>,
|
||||
/// The vertex buffer slots it reads (bit per slot).
|
||||
pub(crate) slots: u32,
|
||||
pub(crate) inputs: Vec<Input>,
|
||||
/// Its shaders, for reports of slow submissions.
|
||||
pub(crate) name: String,
|
||||
}
|
||||
|
||||
/// Logs a pipeline that gets no host pipeline, once per reason.
|
||||
fn refuse(reason: &'static str, shaders: &[Arc<Shader>]) -> Option<HostPipeline> {
|
||||
static SEEN: std::sync::Mutex<Vec<&str>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !seen.contains(&reason) {
|
||||
seen.push(reason);
|
||||
tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl HostPipeline {
|
||||
/// A host pipeline for vertex and pixel shaders with the graphics
|
||||
/// state `g`, or for one compute shader.
|
||||
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
|
||||
let find = |stage| shaders.iter().find(|s| s.stage == stage);
|
||||
let compute = match shaders {
|
||||
[cs] if cs.stage == "compute" => Some(cs),
|
||||
_ => None,
|
||||
};
|
||||
if compute.is_none()
|
||||
&& shaders
|
||||
.iter()
|
||||
.any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh"))
|
||||
{
|
||||
return refuse(
|
||||
"only vertex, mesh, pixel and compute stages are translated",
|
||||
shaders,
|
||||
);
|
||||
}
|
||||
let mesh = find("mesh");
|
||||
let stages = if let Some(cs) = compute {
|
||||
vec![(cs, D3D12_SHADER_VISIBILITY_ALL)]
|
||||
} else {
|
||||
let first = match (mesh, find("vertex")) {
|
||||
(Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH),
|
||||
(None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX),
|
||||
(None, None) => return refuse("no vertex or mesh shader", shaders),
|
||||
};
|
||||
let mut stages = vec![first];
|
||||
stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL)));
|
||||
stages
|
||||
};
|
||||
if mesh.is_some() && !host()?.mesh_shaders() {
|
||||
return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders);
|
||||
}
|
||||
for (s, _) in &stages {
|
||||
s.translated()?;
|
||||
}
|
||||
let host = host()?;
|
||||
|
||||
// The root signature the translated shaders' bindings define.
|
||||
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
|
||||
let mut samplers = Vec::new();
|
||||
let mut bound = Vec::new();
|
||||
for &(shader, visibility) in &stages {
|
||||
let t = &shader.translated()?.host;
|
||||
let mut stage = Stage {
|
||||
shader: shader.clone(),
|
||||
user_data: None,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
};
|
||||
let dwords = t.user_data_dwords();
|
||||
if dwords > 0 {
|
||||
stage.user_data = Some((params.len() as u32, dwords));
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
|
||||
Anonymous: D3D12_ROOT_PARAMETER1_0 {
|
||||
Constants: D3D12_ROOT_CONSTANTS {
|
||||
ShaderRegister: 0,
|
||||
RegisterSpace: USER_DATA_SPACE,
|
||||
Num32BitValues: dwords,
|
||||
},
|
||||
},
|
||||
ShaderVisibility: visibility,
|
||||
});
|
||||
}
|
||||
for (slots, kind, out) in [
|
||||
(
|
||||
&t.root_cbvs,
|
||||
D3D12_ROOT_PARAMETER_TYPE_CBV,
|
||||
&mut stage.root_cbvs,
|
||||
),
|
||||
(
|
||||
&t.root_srvs,
|
||||
D3D12_ROOT_PARAMETER_TYPE_SRV,
|
||||
&mut stage.root_srvs,
|
||||
),
|
||||
] {
|
||||
for &slot in slots {
|
||||
out.push((slot, params.len() as u32));
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: kind,
|
||||
Anonymous: D3D12_ROOT_PARAMETER1_0 {
|
||||
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
|
||||
ShaderRegister: u32::from(slot),
|
||||
RegisterSpace: ROOT_CBV_SPACE,
|
||||
Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
|
||||
},
|
||||
},
|
||||
ShaderVisibility: visibility,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (n, s) in t.static_samplers.iter().enumerate() {
|
||||
samplers.push(D3D12_STATIC_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER(s.filter as i32),
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32),
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32),
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32),
|
||||
MipLODBias: s.mip_lod_bias,
|
||||
MaxAnisotropy: s.max_anisotropy,
|
||||
ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32),
|
||||
BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32),
|
||||
MinLOD: s.min_lod,
|
||||
MaxLOD: s.max_lod,
|
||||
ShaderRegister: n as u32,
|
||||
RegisterSpace: SAMPLER_SPACE,
|
||||
ShaderVisibility: visibility,
|
||||
});
|
||||
}
|
||||
bound.push(stage);
|
||||
}
|
||||
let root = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) {
|
||||
Ok(root) => root,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, ?shaders, "host root signature refused");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let code = |i: usize| {
|
||||
stages.get(i).and_then(|(s, _)| s.translated()).map_or(
|
||||
D3D12_SHADER_BYTECODE::default(),
|
||||
|t| D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: t.host.dxil.as_ptr().cast(),
|
||||
BytecodeLength: t.host.dxil.len(),
|
||||
},
|
||||
)
|
||||
};
|
||||
if compute.is_some() {
|
||||
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
|
||||
// SAFETY: a borrowed pointer the description never releases.
|
||||
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
|
||||
CS: code(0),
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the description points at live data.
|
||||
let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } {
|
||||
Ok(pso) => pso,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
|
||||
host.log_messages();
|
||||
return None;
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host pipeline");
|
||||
return Some(HostPipeline {
|
||||
compute: true,
|
||||
mesh: false,
|
||||
pso,
|
||||
root,
|
||||
stages: bound,
|
||||
name: format!("{shaders:?}"),
|
||||
slots: 0,
|
||||
inputs: Vec::new(),
|
||||
});
|
||||
}
|
||||
let Some(g) = g else {
|
||||
return refuse("graphics state not kept (plain description)", shaders);
|
||||
};
|
||||
if mesh.is_some() {
|
||||
let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) {
|
||||
Ok(pso) => pso,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused");
|
||||
host.log_messages();
|
||||
return None;
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host mesh pipeline");
|
||||
return Some(HostPipeline {
|
||||
compute: false,
|
||||
mesh: true,
|
||||
pso,
|
||||
root,
|
||||
stages: bound,
|
||||
name: format!("{shaders:?}"),
|
||||
slots: 0,
|
||||
inputs: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
// SAFETY: a borrowed pointer the description never releases.
|
||||
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
|
||||
VS: code(0),
|
||||
PS: code(1),
|
||||
BlendState: g.blend,
|
||||
SampleMask: g.sample_mask,
|
||||
RasterizerState: g.rasterizer,
|
||||
DepthStencilState: g.depth,
|
||||
InputLayout: D3D12_INPUT_LAYOUT_DESC {
|
||||
pInputElementDescs: g.inputs.as_ptr(),
|
||||
NumElements: g.inputs.len() as u32,
|
||||
},
|
||||
IBStripCutValue: g.strip_cut,
|
||||
// The console's rectangle and quad types draw as triangles on
|
||||
// the host (see `draw`).
|
||||
PrimitiveTopologyType: match g.topology.0 {
|
||||
RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
_ => g.topology,
|
||||
},
|
||||
NumRenderTargets: g.targets.NumRenderTargets,
|
||||
RTVFormats: g.targets.RTFormats,
|
||||
DSVFormat: g.depth_format,
|
||||
SampleDesc: g.samples,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the description points at live data.
|
||||
let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } {
|
||||
Ok(pso) => pso,
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, ?shaders, "host pipeline refused");
|
||||
host.log_messages();
|
||||
return None;
|
||||
}
|
||||
};
|
||||
tracing::info!(?shaders, "host pipeline");
|
||||
tracing::debug!(
|
||||
?shaders,
|
||||
depth = ?g.depth,
|
||||
dsv = g.depth_format.0,
|
||||
targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize],
|
||||
blend = ?g.blend.RenderTarget[0],
|
||||
cull = g.rasterizer.CullMode.0,
|
||||
"host graphics state"
|
||||
);
|
||||
Some(HostPipeline {
|
||||
compute: false,
|
||||
mesh: false,
|
||||
pso,
|
||||
root,
|
||||
stages: bound,
|
||||
name: format!("{shaders:?}"),
|
||||
slots: g.slots(),
|
||||
inputs: g.elements(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A mesh pipeline from the title's graphics state: the pipeline-state
|
||||
/// stream form (no input layout or topology).
|
||||
fn mesh_pipeline(
|
||||
device: &ID3D12Device,
|
||||
root: &ID3D12RootSignature,
|
||||
ms: D3D12_SHADER_BYTECODE,
|
||||
ps: D3D12_SHADER_BYTECODE,
|
||||
g: &GraphicsState,
|
||||
) -> windows::core::Result<ID3D12PipelineState> {
|
||||
use windows::core::Interface;
|
||||
/// A stream subobject: its type, then its description, pointer-aligned.
|
||||
#[repr(C, align(8))]
|
||||
struct Sub<T>(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T);
|
||||
#[repr(C)]
|
||||
struct Stream {
|
||||
root: Sub<*mut std::ffi::c_void>,
|
||||
ms: Sub<D3D12_SHADER_BYTECODE>,
|
||||
ps: Sub<D3D12_SHADER_BYTECODE>,
|
||||
blend: Sub<D3D12_BLEND_DESC>,
|
||||
mask: Sub<u32>,
|
||||
raster: Sub<D3D12_RASTERIZER_DESC>,
|
||||
depth: Sub<D3D12_DEPTH_STENCIL_DESC>,
|
||||
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
|
||||
dsv: Sub<DXGI_FORMAT>,
|
||||
samples: Sub<DXGI_SAMPLE_DESC>,
|
||||
}
|
||||
let mut stream = Stream {
|
||||
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
|
||||
ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms),
|
||||
ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps),
|
||||
blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend),
|
||||
mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask),
|
||||
raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer),
|
||||
depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth),
|
||||
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
|
||||
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
|
||||
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
|
||||
};
|
||||
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
|
||||
SizeInBytes: size_of::<Stream>(),
|
||||
pPipelineStateSubobjectStream: (&raw mut stream).cast(),
|
||||
};
|
||||
// SAFETY: the stream holds whole subobjects pointing at live data.
|
||||
unsafe { device.cast::<ID3D12Device2>()?.CreatePipelineState(&desc) }
|
||||
}
|
||||
|
||||
fn root_signature(
|
||||
device: &ID3D12Device,
|
||||
params: &[D3D12_ROOT_PARAMETER1],
|
||||
samplers: &[D3D12_STATIC_SAMPLER_DESC],
|
||||
compute: bool,
|
||||
) -> windows::core::Result<ID3D12RootSignature> {
|
||||
let input = if compute {
|
||||
D3D12_ROOT_SIGNATURE_FLAG_NONE
|
||||
} else {
|
||||
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT
|
||||
};
|
||||
let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC {
|
||||
Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1,
|
||||
Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 {
|
||||
Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 {
|
||||
NumParameters: params.len() as u32,
|
||||
pParameters: params.as_ptr(),
|
||||
NumStaticSamplers: samplers.len() as u32,
|
||||
pStaticSamplers: samplers.as_ptr(),
|
||||
Flags: input
|
||||
| D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED
|
||||
| D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED,
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: the description points at live arrays; the blob is read in
|
||||
// full before it is released.
|
||||
unsafe {
|
||||
let mut blob: Option<ID3DBlob> = None;
|
||||
let mut error: Option<ID3DBlob> = None;
|
||||
if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) {
|
||||
if let Some(error) = error {
|
||||
let text = std::slice::from_raw_parts(
|
||||
error.GetBufferPointer().cast::<u8>(),
|
||||
error.GetBufferSize(),
|
||||
);
|
||||
tracing::warn!("root signature: {}", String::from_utf8_lossy(text));
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
let blob = blob.ok_or_else(windows::core::Error::empty)?;
|
||||
let bytes =
|
||||
std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
|
||||
device.CreateRootSignature(0, bytes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Console primitive types the host lacks. A rectangle list gives three
|
||||
//! corners per rectangle, the second the one between the other two, and
|
||||
//! the hardware adds the fourth at `v0 + v2 - v1` (Grand Theft Auto VI's
|
||||
//! full-screen rectangles come as top left, bottom left, bottom right); on
|
||||
//! the host each rectangle becomes two triangles, with the fourth vertex
|
||||
//! made from the other three on the CPU.
|
||||
//!
|
||||
//! shortcut: the fourth vertex is computed from vertex inputs, not from
|
||||
//! vertex shader outputs as the hardware does; that is the same for vertex
|
||||
//! shaders linear in their inputs (blits, 2D quads). Inputs in formats
|
||||
//! [`components`] does not know keep the first vertex's value.
|
||||
|
||||
/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six
|
||||
/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both
|
||||
/// triangles turn the same way. `elements` are (byte offset, format).
|
||||
pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) {
|
||||
for (rect, out) in src
|
||||
.chunks_exact(3 * stride)
|
||||
.zip(dst.chunks_exact_mut(6 * stride))
|
||||
{
|
||||
let v = |i: usize| &rect[i * stride..(i + 1) * stride];
|
||||
for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() {
|
||||
out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i));
|
||||
}
|
||||
let fourth = &mut out[5 * stride..];
|
||||
fourth.copy_from_slice(v(0));
|
||||
for &(offset, format) in elements {
|
||||
let at = offset as usize;
|
||||
let Some((n, kind)) = components(format) else {
|
||||
continue;
|
||||
};
|
||||
for c in 0..n {
|
||||
let get = |i: usize| kind.read(&v(i)[at..], c);
|
||||
let value = get(0) + get(2) - get(1);
|
||||
kind.write(&mut fourth[at..], c, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
F32,
|
||||
F16,
|
||||
Unorm8,
|
||||
Unorm16,
|
||||
}
|
||||
|
||||
/// Component count and kind of the vertex formats rectangles use.
|
||||
fn components(format: u32) -> Option<(usize, Kind)> {
|
||||
Some(match format {
|
||||
2 => (4, Kind::F32),
|
||||
6 => (3, Kind::F32),
|
||||
16 => (2, Kind::F32),
|
||||
41 => (1, Kind::F32),
|
||||
10 => (4, Kind::F16),
|
||||
34 => (2, Kind::F16),
|
||||
54 => (1, Kind::F16),
|
||||
11 => (4, Kind::Unorm16),
|
||||
35 => (2, Kind::Unorm16),
|
||||
28 | 29 | 87 | 91 => (4, Kind::Unorm8),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
fn bytes(self) -> usize {
|
||||
match self {
|
||||
Kind::F32 => 4,
|
||||
Kind::F16 | Kind::Unorm16 => 2,
|
||||
Kind::Unorm8 => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn read(self, at: &[u8], c: usize) -> f32 {
|
||||
let b = &at[c * self.bytes()..];
|
||||
match self {
|
||||
Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
|
||||
Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
|
||||
Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
|
||||
Kind::Unorm8 => f32::from(b[0]) / 255.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn write(self, at: &mut [u8], c: usize, v: f32) {
|
||||
let n = self.bytes();
|
||||
let b = &mut at[c * n..(c + 1) * n];
|
||||
match self {
|
||||
Kind::F32 => b.copy_from_slice(&v.to_le_bytes()),
|
||||
Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()),
|
||||
Kind::Unorm16 => {
|
||||
b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
|
||||
}
|
||||
Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn half_to_f32(h: u16) -> f32 {
|
||||
let sign = u32::from(h >> 15) << 31;
|
||||
let exp = u32::from((h >> 10) & 0x1f);
|
||||
let man = u32::from(h & 0x3ff);
|
||||
let bits = match (exp, man) {
|
||||
(0, 0) => sign,
|
||||
// Subnormal: scale the mantissa.
|
||||
(0, m) => {
|
||||
let v = m as f32 * 2f32.powi(-24);
|
||||
return if sign != 0 { -v } else { v };
|
||||
}
|
||||
(31, m) => sign | 0x7f80_0000 | m << 13,
|
||||
(e, m) => sign | (e + 112) << 23 | m << 13,
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
fn f32_to_half(v: f32) -> u16 {
|
||||
let bits = v.to_bits();
|
||||
let sign = ((bits >> 16) & 0x8000) as u16;
|
||||
let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
|
||||
let man = bits & 0x7f_ffff;
|
||||
if exp >= 31 {
|
||||
return sign | 0x7c00; // too large: infinity
|
||||
}
|
||||
if exp <= 0 {
|
||||
return sign; // too small: zero
|
||||
}
|
||||
sign | (exp as u16) << 10 | ((man + 0x1000) >> 13) as u16
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A rectangle of float2 positions and RGBA8 colors, given as top
|
||||
/// left, bottom left, bottom right: the fourth corner completes the
|
||||
/// parallelogram at the top right.
|
||||
#[test]
|
||||
fn rectangles_get_their_fourth_corner() {
|
||||
let vertex = |x: f32, y: f32, r: u8| {
|
||||
let mut v = Vec::new();
|
||||
v.extend(x.to_le_bytes());
|
||||
v.extend(y.to_le_bytes());
|
||||
v.extend([r, 0, 0, 255]);
|
||||
v
|
||||
};
|
||||
let src: Vec<u8> = [
|
||||
vertex(-1.0, 1.0, 0),
|
||||
vertex(-1.0, -1.0, 100),
|
||||
vertex(1.0, -1.0, 150),
|
||||
]
|
||||
.concat();
|
||||
let mut dst = vec![0u8; 6 * 12];
|
||||
expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]);
|
||||
assert_eq!(dst[..36], src[..]);
|
||||
assert_eq!(dst[36..48], src[..12]);
|
||||
assert_eq!(dst[48..60], src[24..36]);
|
||||
assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]);
|
||||
assert_eq!(f32_to_half(1.5), 0x3e00);
|
||||
assert_eq!(half_to_f32(0x3e00), 1.5);
|
||||
assert_eq!(half_to_f32(0xc000), -2.0);
|
||||
}
|
||||
}
|
||||
@@ -63,8 +63,8 @@ extern "system" fn release(this: This) -> u32 {
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 8>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
|
||||
+354
-27
@@ -1,5 +1,5 @@
|
||||
//! Command queues. Nothing is executed yet: submitted lists are dropped and
|
||||
//! fence signals complete at once, as if the GPU were infinitely fast.
|
||||
//! Command queues. Submitted lists run on the host GPU and are waited for,
|
||||
//! so fence signals complete at once.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
@@ -54,13 +54,50 @@ pub(crate) extern "system" fn create(
|
||||
};
|
||||
tracing::debug!(?desc, "command queue");
|
||||
let queue = Box::new(Queue {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
object: if crate::device::newer() {
|
||||
Object::new(&NEWER_FUNCTIONS)
|
||||
} else {
|
||||
Object::new(&FUNCTIONS)
|
||||
},
|
||||
kind: desc.kind,
|
||||
desc,
|
||||
});
|
||||
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
|
||||
}
|
||||
|
||||
/// The console's queue description: an engine or pipe and a queue on it
|
||||
/// in place of PC's priority and node mask.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct QueueDescX {
|
||||
kind: u32,
|
||||
flags: u32,
|
||||
engine_or_pipe: u32,
|
||||
queue: u32,
|
||||
}
|
||||
|
||||
/// Device method `CreateCommandQueueX`. The host picks engines itself, so
|
||||
/// the queue is created as on PC.
|
||||
pub(crate) extern "system" fn create_x(
|
||||
this: This,
|
||||
desc: *const QueueDescX,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&x) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(desc = ?x, "console command queue");
|
||||
let desc = QueueDesc {
|
||||
kind: x.kind,
|
||||
priority: 0,
|
||||
flags: x.flags,
|
||||
nodes: 1,
|
||||
};
|
||||
create(this, &desc, iid, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
QUEUE,
|
||||
@@ -102,6 +139,22 @@ pub(crate) struct Plane {
|
||||
count: u32,
|
||||
resources: *const This,
|
||||
}
|
||||
/// Submission tagged with the frame it belongs to `(count, lists, frame
|
||||
/// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
|
||||
extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
|
||||
execute(this, count, lists);
|
||||
}
|
||||
/// Signal with sync settings for the top and bottom of the pipe; our
|
||||
/// submissions are complete when they return, so it signals at once.
|
||||
extern "system" fn signal2_x(
|
||||
this: This,
|
||||
fence: This,
|
||||
value: u64,
|
||||
_bottom: *const u8,
|
||||
_top: *const u8,
|
||||
) -> HRESULT {
|
||||
signal(this, fence, value)
|
||||
}
|
||||
/// Markers and events only matter to profilers.
|
||||
extern "system" fn marker(_: This) {}
|
||||
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
|
||||
@@ -114,15 +167,71 @@ extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
|
||||
extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
|
||||
if fence.is_null() { E_INVALIDARG } else { S_OK }
|
||||
}
|
||||
/// Ticks per second of GPU timestamps; none are written yet.
|
||||
/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
|
||||
extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(100_000_000) };
|
||||
unsafe { out.write(TIMESTAMP_FREQUENCY) };
|
||||
S_OK
|
||||
}
|
||||
const TIMESTAMP_FREQUENCY: u64 = 100_000_000;
|
||||
|
||||
/// What a list's bottom-of-pipe write stores when the list has run.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum Written {
|
||||
Value(u64),
|
||||
/// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the
|
||||
/// process started (our GPU work is done on the CPU's timeline).
|
||||
GpuTimestamp,
|
||||
/// The CPU's performance counter.
|
||||
SystemTimestamp,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
/// Stores the low `bytes` (4 or 8) of the value at `at`.
|
||||
pub(crate) fn write(self, at: *mut u8, bytes: usize) {
|
||||
let value = match self {
|
||||
Written::Value(v) => v,
|
||||
Written::GpuTimestamp => {
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
|
||||
(elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64
|
||||
}
|
||||
Written::SystemTimestamp => system_timestamp(),
|
||||
};
|
||||
// SAFETY: the title names writable GPU memory (unified with ours).
|
||||
unsafe {
|
||||
if bytes == 4 {
|
||||
at.cast::<u32>().write_unaligned(value as u32);
|
||||
} else {
|
||||
at.cast::<u64>().write_unaligned(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn system_timestamp() -> u64 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut count = 0;
|
||||
// SAFETY: a valid out pointer.
|
||||
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) };
|
||||
count as u64
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
0
|
||||
}
|
||||
|
||||
/// Frames presented so far.
|
||||
static FRAMES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn presented() -> u64 {
|
||||
FRAMES.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Shows the first plane's first resource in our window.
|
||||
///
|
||||
/// shortcut: one plane, no scaling or placement, the source expected in
|
||||
@@ -133,10 +242,38 @@ extern "system" fn present(
|
||||
plane_parameters: *const Plane,
|
||||
_parameters: *const u8,
|
||||
) -> HRESULT {
|
||||
static FRAMES: AtomicU64 = AtomicU64::new(0);
|
||||
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if frame.is_power_of_two() {
|
||||
tracing::info!(frame, "frame presented");
|
||||
let (draws, dispatches) = crate::list::take_counts();
|
||||
#[cfg(windows)]
|
||||
let (drawn, dispatched) = {
|
||||
static DRAWN: AtomicU64 = AtomicU64::new(0);
|
||||
static DISPATCHED: AtomicU64 = AtomicU64::new(0);
|
||||
let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed);
|
||||
(
|
||||
since(&DRAWN, crate::draw::drawn()),
|
||||
since(&DISPATCHED, crate::draw::dispatched()),
|
||||
)
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let (drawn, dispatched) = (0, 0);
|
||||
tracing::info!(
|
||||
frame,
|
||||
draws,
|
||||
drawn,
|
||||
dispatches,
|
||||
dispatched,
|
||||
"frame presented (since the last line: draws and dispatches, and those run on the host)"
|
||||
);
|
||||
#[cfg(windows)]
|
||||
if frame >= 256 {
|
||||
let (hits, misses) = crate::shader_cache::counts();
|
||||
tracing::info!(hits, misses, "shaders from the cache and translated so far");
|
||||
}
|
||||
}
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
if crate::capture::listed(frame) {
|
||||
crate::capture::dump_targets(frame);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if planes > 0
|
||||
@@ -152,13 +289,125 @@ extern "system" fn present(
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
let state = crate::resource::host_transition(resource, COPY_SOURCE)
|
||||
.map_or(COPY_SOURCE, |(_, before)| before);
|
||||
host.present(texture, state);
|
||||
let shown = host.present(texture, state, frame);
|
||||
crate::resource::host_transition(resource, state);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
blinks(frame, resource, state, shown);
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = shown;
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (planes, plane_parameters);
|
||||
S_OK
|
||||
}
|
||||
/// Diagnostics: logs a presented frame that is black after one that was
|
||||
/// not, with what was presented and how many draws ran since.
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
|
||||
static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0));
|
||||
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let drawn = crate::draw::drawn();
|
||||
let black = shown.unwrap_or(false);
|
||||
let draws = crate::draw::take_frame();
|
||||
if black && !last.0 {
|
||||
last.2 += 1;
|
||||
tracing::warn!(
|
||||
frame,
|
||||
resource = ?resource,
|
||||
state = format_args!("{state:#x}"),
|
||||
draws = drawn - last.1,
|
||||
copied = shown.is_some(),
|
||||
black_frames = last.2,
|
||||
levels = ?crate::capture::recent_levels(),
|
||||
"a black frame after a frame that was not"
|
||||
);
|
||||
for d in draws {
|
||||
tracing::warn!("black frame {frame}: {d}");
|
||||
}
|
||||
AFTER.store(frame + 6, Ordering::Relaxed);
|
||||
}
|
||||
// Six frames on: the levels around it (a fade or a single drop).
|
||||
static AFTER: AtomicU64 = AtomicU64::new(0);
|
||||
if AFTER.load(Ordering::Relaxed) == frame {
|
||||
tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame");
|
||||
}
|
||||
*last = (black, drawn, last.2);
|
||||
}
|
||||
|
||||
/// A run of destination pages: how they are mapped (0 pool pages from
|
||||
/// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
|
||||
/// and how many.
|
||||
#[repr(C)]
|
||||
pub(crate) struct PageRange {
|
||||
kind: u32,
|
||||
start: u32,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// The ranges mapped from a destination address on.
|
||||
#[repr(C)]
|
||||
pub(crate) struct PageBatch {
|
||||
destination: u64,
|
||||
count: u32,
|
||||
ranges: *const PageRange,
|
||||
}
|
||||
|
||||
/// Bytes per mapped page.
|
||||
const PAGE: u64 = 64 << 10;
|
||||
|
||||
/// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
|
||||
/// pages of a pool (memory the title mapped physical pages into) at the
|
||||
/// batches' addresses. Grand Theft Auto VI streams textures into pool pages
|
||||
/// and maps them into its tiled heap this way (title+0xf2c470, ranges of
|
||||
/// one constant page or of unmapped pages). Done at once: every earlier
|
||||
/// submission has run.
|
||||
extern "system" fn copy_page_mappings(
|
||||
_: This,
|
||||
count: u32,
|
||||
batches: *const PageBatch,
|
||||
pool: u64,
|
||||
pool_pages: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
let Some(map) = crate::resource::page_mapper() else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if batches.is_null() && count > 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let batches = (count > 0).then(|| {
|
||||
// SAFETY: the title passes `count` batches.
|
||||
unsafe { std::slice::from_raw_parts(batches, count as usize) }
|
||||
});
|
||||
let mut ok = true;
|
||||
for b in batches.into_iter().flatten() {
|
||||
if b.ranges.is_null() {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: each batch holds `count` ranges.
|
||||
let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
|
||||
let mut at = b.destination;
|
||||
for r in ranges {
|
||||
let len = u64::from(r.count) * PAGE;
|
||||
let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
|
||||
let source = pool + u64::from(r.start) * PAGE;
|
||||
ok &= match r.kind {
|
||||
0 if inside(r.count) => map(at, source, len),
|
||||
1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
|
||||
2 => map(at, 0, len),
|
||||
3 => true,
|
||||
_ => false,
|
||||
};
|
||||
at += len;
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn desc(this: This, out: *mut QueueDesc) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a description.
|
||||
@@ -166,30 +415,70 @@ extern "system" fn desc(this: This, out: *mut QueueDesc) {
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, then
|
||||
/// console ones).
|
||||
static FUNCTIONS: Table<34> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUEUE, 34>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[10] = execute as *const (); // 0x50
|
||||
f[11] = marker as *const (); // 0x58 set marker
|
||||
f[12] = marker as *const (); // 0x60 begin event
|
||||
f[13] = marker as *const (); // 0x68 end event
|
||||
f[14] = signal as *const (); // 0x70
|
||||
f[15] = wait as *const (); // 0x78
|
||||
f[16] = timestamp_frequency as *const (); // 0x80
|
||||
f[26] = desc as *const (); // 0xd0
|
||||
f[30] = present as *const (); // 0xf0
|
||||
Table(f)
|
||||
};
|
||||
/// The queue methods by their slot in older titles' queues (the 2020-era
|
||||
/// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC,
|
||||
/// then console ones).
|
||||
const METHODS: [(usize, *const ()); 15] = [
|
||||
(0, query as *const ()),
|
||||
(2, release as *const ()),
|
||||
(7, object::parent_device as *const ()), // 0x38
|
||||
(10, execute as *const ()), // 0x50
|
||||
(11, marker as *const ()), // 0x58 set marker
|
||||
(12, marker as *const ()), // 0x60 begin event
|
||||
(13, marker as *const ()), // 0x68 end event
|
||||
(14, signal as *const ()), // 0x70
|
||||
(15, wait as *const ()), // 0x78
|
||||
(16, timestamp_frequency as *const ()), // 0x80
|
||||
(26, desc as *const ()), // 0xd0
|
||||
(29, copy_page_mappings as *const ()), // 0xe8 page mapping batch
|
||||
(30, present as *const ()), // 0xf0
|
||||
(33, execute_x as *const ()), // 0x108
|
||||
(32, signal2_x as *const ()), // 0x100
|
||||
];
|
||||
|
||||
/// Newer titles' queues have two more methods before Signal, which moved
|
||||
/// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as
|
||||
/// starting exactly at 0x70, the methods before it kept in place).
|
||||
/// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence,
|
||||
/// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume
|
||||
/// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count,
|
||||
/// lists, token, flags)` (title+0x24821dd).
|
||||
const fn newer_slot(slot: usize) -> usize {
|
||||
if slot >= 14 { slot + 2 } else { slot }
|
||||
}
|
||||
|
||||
const fn queue_table(newer: bool) -> [*const (); 36] {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>());
|
||||
let mut i = 0;
|
||||
while i < METHODS.len() {
|
||||
let (slot, method) = METHODS[i];
|
||||
f[if newer { newer_slot(slot) } else { slot }] = method;
|
||||
i += 1;
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
static FUNCTIONS: Table<36> = Table(queue_table(false));
|
||||
static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
/// Where a queue's signal is: newer layouts have it two slots later.
|
||||
/// Another test may switch layouts while this one runs, so the queue's
|
||||
/// own table decides.
|
||||
fn signal_slot(q: This) -> usize {
|
||||
// SAFETY: one of our queues; its first field is the table.
|
||||
let table = unsafe { *q.cast::<*const *const ()>() };
|
||||
if table == NEWER_FUNCTIONS.0.as_ptr() {
|
||||
0x80
|
||||
} else {
|
||||
0x70
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_signals_complete_at_once() {
|
||||
let null = std::ptr::null();
|
||||
@@ -209,7 +498,7 @@ mod tests {
|
||||
crate::fence::create(null, 0, 0, fence_iid, &mut fence),
|
||||
S_OK
|
||||
);
|
||||
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, 0x70);
|
||||
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q));
|
||||
assert_eq!(signal(q, fence, 7), S_OK);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
|
||||
@@ -217,4 +506,42 @@ mod tests {
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
|
||||
}
|
||||
|
||||
/// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`.
|
||||
#[test]
|
||||
fn console_queues_are_created_as_on_pc() {
|
||||
let null = std::ptr::null();
|
||||
let desc = QueueDescX {
|
||||
kind: 2,
|
||||
flags: 0,
|
||||
engine_or_pipe: 1,
|
||||
queue: 0,
|
||||
};
|
||||
let mut q = null;
|
||||
assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
|
||||
assert_eq!(queue(q).desc.kind, 2);
|
||||
let none = std::ptr::null();
|
||||
assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newer_queues_have_their_methods_two_slots_later() {
|
||||
let (old, new) = (queue_table(false), queue_table(true));
|
||||
assert_eq!(old[10], new[10]); // submission stays at 0x50
|
||||
assert_eq!(old[14], new[16]); // signal 0x70 → 0x80
|
||||
assert_eq!(old[30], new[32]); // present 0xf0 → 0x100
|
||||
assert_eq!(new[35], execute_x as *const ()); // 0x118
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_and_values_are_written() {
|
||||
let mut at = [0u64; 2];
|
||||
Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4);
|
||||
assert_eq!(at[0], 2);
|
||||
Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
|
||||
let first = at[1];
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
|
||||
assert!(at[1] > first);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
//! Heaps, committed and placed resources, and resource sizes.
|
||||
//!
|
||||
//! shortcut: heaps and resources are plain host memory and a resource's
|
||||
//! GPU address is its CPU address, as on the console. Rewrite them on host
|
||||
//! D3D12 heaps and resources once the command-stream decoder needs the host
|
||||
//! GPU to see them (TODO.md, GPU).
|
||||
//! Heaps and resources are host memory and a resource's GPU address is its
|
||||
//! CPU address, as on the console; textures also get a host copy, and
|
||||
//! buffers a host copy when a draw reads them (`shadow`).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::alloc::{Layout, alloc_zeroed, dealloc};
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use victory_formats::texture;
|
||||
|
||||
use crate::object::{
|
||||
self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
|
||||
guid,
|
||||
@@ -112,29 +113,83 @@ const BUFFER: u32 = 1;
|
||||
const TEXTURE_3D: u32 = 4;
|
||||
|
||||
/// Bytes per element and the element's width in texels (4 for block
|
||||
/// compression), by DXGI format number. `None` for 1-bit, video and
|
||||
/// console-only formats.
|
||||
fn element(format: u32) -> Option<(u64, u64)> {
|
||||
/// compression), by DXGI format number. `None` for 1-bit and video
|
||||
/// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit
|
||||
/// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed
|
||||
/// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color).
|
||||
pub(crate) fn element(format: u32) -> Option<(u64, u64)> {
|
||||
Some(match format {
|
||||
1..=4 => (16, 1),
|
||||
5..=8 => (12, 1),
|
||||
9..=22 => (8, 1),
|
||||
23..=47 | 67 | 87..=93 => (4, 1),
|
||||
23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1),
|
||||
118..=120 => (3, 1),
|
||||
48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
|
||||
60..=65 => (1, 1),
|
||||
60..=65 | 190 => (1, 1),
|
||||
70..=72 | 79..=81 => (8, 4),
|
||||
73..=78 | 82..=84 | 94..=99 => (16, 4),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes and alignment a resource takes in our layout: every mip of every
|
||||
/// array slice and sample, packed, rounded up to 64 KiB.
|
||||
///
|
||||
/// shortcut: an unpadded bound, not the console's tiled layout. Titles that
|
||||
/// write console-tiled data straight into memory may need more; revisit with
|
||||
/// the texture layouts (TODO.md, formats).
|
||||
/// A texture's layout in console memory, as the console's layout library
|
||||
/// gives it (`victory-hle`'s `xg` serves the same): the description's
|
||||
/// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick.
|
||||
pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> {
|
||||
use texture::{Dimension, Swizzle, TextureDesc};
|
||||
const TEXTURE_1D: u32 = 2;
|
||||
const TEXTURE_2D: u32 = 3;
|
||||
const RENDER_TARGET: u32 = 1;
|
||||
const DEPTH: u32 = 2;
|
||||
let dimension = match desc.dimension {
|
||||
TEXTURE_1D => Dimension::Tex1d,
|
||||
TEXTURE_2D => Dimension::Tex2d,
|
||||
TEXTURE_3D => Dimension::Tex3d,
|
||||
_ => return None,
|
||||
};
|
||||
let swizzle = match desc.layout {
|
||||
0 if dimension == Dimension::Tex1d => Swizzle::LINEAR,
|
||||
0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X,
|
||||
0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X,
|
||||
0 => Swizzle::SW_4KB_S,
|
||||
1 => Swizzle::LINEAR,
|
||||
l if l & !0xff == 0x100 => Swizzle(l & 0xff),
|
||||
_ => return None,
|
||||
};
|
||||
texture::Texture::new(&TextureDesc {
|
||||
dimension,
|
||||
width: u32::try_from(desc.width).ok()?,
|
||||
height: desc.height,
|
||||
depth_or_array: u32::from(desc.depth_or_array_size),
|
||||
mips: u32::from(desc.mip_levels),
|
||||
format: desc.format,
|
||||
samples: desc.sample_count.max(1),
|
||||
swizzle,
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Bytes and alignment a resource takes: buffers their width (64 KiB
|
||||
/// aligned), textures their console layout (formats it does not know:
|
||||
/// every mip of every array slice and sample, packed, 64 KiB aligned),
|
||||
/// rounded up to the alignment.
|
||||
fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
|
||||
if desc.dimension != BUFFER
|
||||
&& let Some(t) = texture_layout(desc)
|
||||
{
|
||||
// As the console: the layout's own alignment unless more is asked
|
||||
// (4 KiB for 4 KiB modes, where PC says 64 KiB). Grand Theft Auto
|
||||
// VI keeps these sizes in its texture tables, and its streaming
|
||||
// asserts when they disagree with the streamed layout.
|
||||
let alignment = desc.alignment.max(t.alignment);
|
||||
if !alignment.is_power_of_two() {
|
||||
return None;
|
||||
}
|
||||
return Some(AllocationInfo {
|
||||
size: t.size.checked_next_multiple_of(alignment)?,
|
||||
alignment,
|
||||
});
|
||||
}
|
||||
let bytes = if desc.dimension == BUFFER {
|
||||
desc.width
|
||||
} else {
|
||||
@@ -171,6 +226,72 @@ fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A format as the host has it. The console's 16-bit depth with stencil
|
||||
/// (and its typeless views) has no PC format: the 24-bit ones stand in.
|
||||
pub(crate) fn pc_format(format: u32) -> u32 {
|
||||
match format {
|
||||
118 => 45,
|
||||
119 => 46,
|
||||
120 => 47,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The typeless format of a format's family (itself if it has none).
|
||||
pub(crate) fn family(format: u32) -> u32 {
|
||||
const FAMILIES: [(u32, u32); 22] = [
|
||||
(1, 4),
|
||||
(5, 8),
|
||||
(9, 14),
|
||||
(15, 18),
|
||||
(19, 22),
|
||||
(23, 25),
|
||||
(27, 32),
|
||||
(33, 38),
|
||||
(39, 43),
|
||||
(44, 47),
|
||||
(48, 52),
|
||||
(53, 59),
|
||||
(60, 65),
|
||||
(70, 72),
|
||||
(73, 75),
|
||||
(76, 78),
|
||||
(79, 81),
|
||||
(82, 84),
|
||||
(90, 91),
|
||||
(92, 93),
|
||||
(94, 96),
|
||||
(97, 99),
|
||||
];
|
||||
match format {
|
||||
87 => 90,
|
||||
88 => 92,
|
||||
f => FAMILIES
|
||||
.iter()
|
||||
.find(|&&(first, last)| (first..=last).contains(&f))
|
||||
.map_or(f, |&(first, _)| first),
|
||||
}
|
||||
}
|
||||
|
||||
/// sRGB formats and their linear twins.
|
||||
pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)];
|
||||
|
||||
/// The format a view of a title texture must name when its host copy is
|
||||
/// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if
|
||||
/// the host copy is typed.
|
||||
pub(crate) fn view_format(this: This) -> Option<u32> {
|
||||
let own = pc_format(resource(this).desc.format);
|
||||
let host = host_resource(this)?;
|
||||
// SAFETY: a live resource.
|
||||
let format = unsafe { host.GetDesc() }.Format.0 as u32;
|
||||
(format != own).then_some(own)
|
||||
}
|
||||
|
||||
/// Depth formats with their typeless family: depth textures that shaders
|
||||
/// read are made typeless on the host, which only allows views of
|
||||
/// typeless depth resources.
|
||||
pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)];
|
||||
|
||||
/// Mip levels, the full chain for 0.
|
||||
fn mip_count(desc: &ResourceDesc) -> u32 {
|
||||
let depth = if desc.dimension == TEXTURE_3D {
|
||||
@@ -342,34 +463,170 @@ pub(crate) extern "system" fn allocation_info(
|
||||
// SAFETY: the title passes `count` descriptions.
|
||||
unsafe { std::slice::from_raw_parts(descs, count as usize) }
|
||||
};
|
||||
// SAFETY: the caller passes room for the value.
|
||||
unsafe { out.write(place(descs.iter(), |_, _| ())) };
|
||||
out
|
||||
}
|
||||
|
||||
/// The newer description: the plain one, then a sampler feedback mip
|
||||
/// region (width, height, depth).
|
||||
#[repr(C)]
|
||||
pub(crate) struct ResourceDesc1 {
|
||||
desc: ResourceDesc,
|
||||
mip_region: [u32; 3],
|
||||
}
|
||||
const _: () = assert!(size_of::<ResourceDesc1>() == 72);
|
||||
|
||||
/// Where one resource goes in [`allocation_info2`]'s placement.
|
||||
#[repr(C)]
|
||||
pub(crate) struct AllocationInfo1 {
|
||||
offset: u64,
|
||||
alignment: u64,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
/// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer
|
||||
/// descriptions, also telling where each resource goes.
|
||||
pub(crate) extern "system" fn allocation_info2(
|
||||
out: *mut AllocationInfo,
|
||||
_: This,
|
||||
_visible: u32,
|
||||
count: u32,
|
||||
descs: *const ResourceDesc1,
|
||||
each: *mut AllocationInfo1,
|
||||
) -> *mut AllocationInfo {
|
||||
let descs = if descs.is_null() {
|
||||
&[][..]
|
||||
} else {
|
||||
// SAFETY: the title passes `count` descriptions.
|
||||
unsafe { std::slice::from_raw_parts(descs, count as usize) }
|
||||
};
|
||||
let total = place(descs.iter().map(|d| &d.desc), |i, info| {
|
||||
if !each.is_null() {
|
||||
// SAFETY: the title passes room for `count` entries.
|
||||
unsafe { each.add(i).write(info) };
|
||||
}
|
||||
});
|
||||
// SAFETY: the caller passes room for the value.
|
||||
unsafe { out.write(total) };
|
||||
out
|
||||
}
|
||||
|
||||
/// Resources placed one after another: the whole footprint, telling `each`
|
||||
/// where every resource goes. Unknown sizes give the documented `u64::MAX`.
|
||||
fn place<'a>(
|
||||
descs: impl Iterator<Item = &'a ResourceDesc>,
|
||||
mut each: impl FnMut(usize, AllocationInfo1),
|
||||
) -> AllocationInfo {
|
||||
let mut total = AllocationInfo {
|
||||
size: 0,
|
||||
alignment: KIB_64,
|
||||
};
|
||||
for desc in descs {
|
||||
for (i, desc) in descs.enumerate() {
|
||||
let Some(one) = footprint(desc) else {
|
||||
tracing::warn!(?desc, "no size for this resource");
|
||||
total = AllocationInfo {
|
||||
each(
|
||||
i,
|
||||
AllocationInfo1 {
|
||||
offset: u64::MAX,
|
||||
alignment: 0,
|
||||
size: u64::MAX,
|
||||
},
|
||||
);
|
||||
return AllocationInfo {
|
||||
size: u64::MAX,
|
||||
alignment: 0,
|
||||
};
|
||||
break;
|
||||
};
|
||||
total.size = total.size.next_multiple_of(one.alignment) + one.size;
|
||||
tracing::debug!(?desc, ?one, "allocation info");
|
||||
let offset = total.size.next_multiple_of(one.alignment);
|
||||
each(
|
||||
i,
|
||||
AllocationInfo1 {
|
||||
offset,
|
||||
alignment: one.alignment,
|
||||
size: one.size,
|
||||
},
|
||||
);
|
||||
total.size = offset + one.size;
|
||||
total.alignment = total.alignment.max(one.alignment);
|
||||
}
|
||||
// SAFETY: the caller passes room for the value.
|
||||
unsafe { out.write(total) };
|
||||
out
|
||||
total
|
||||
}
|
||||
|
||||
/// Zeroed host memory standing in for GPU memory.
|
||||
pub(crate) struct Memory {
|
||||
ptr: NonNull<u8>,
|
||||
layout: Layout,
|
||||
/// Set when the memory came from the title's allocator, with these
|
||||
/// allocation attributes (it goes back there).
|
||||
attributes: Option<u64>,
|
||||
}
|
||||
|
||||
pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
|
||||
pub type FreeRoutine = extern "system" fn(*mut c_void, u64);
|
||||
static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new();
|
||||
|
||||
/// Committed resources get their memory from the title's general
|
||||
/// allocator, as on the console, where titles hook it to place graphics
|
||||
/// memory themselves (Grand Theft Auto VI places its back buffers in a
|
||||
/// block of its own and checks they fill it). The runtime names it before
|
||||
/// the device exists.
|
||||
pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) {
|
||||
let _ = ALLOCATOR.set((alloc, free));
|
||||
}
|
||||
|
||||
/// Maps the physical pages behind one range of title memory at another,
|
||||
/// `(to, from, len)` (`from` 0 unmaps); false on failure.
|
||||
pub type PageMapper = fn(u64, u64, u64) -> bool;
|
||||
static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new();
|
||||
|
||||
/// The runtime's page mapper, for the queues' page-mapping copies (memory
|
||||
/// is the runtime's, as on the console).
|
||||
pub fn use_page_mapper(mapper: PageMapper) {
|
||||
let _ = PAGE_MAPPER.set(mapper);
|
||||
}
|
||||
|
||||
pub(crate) fn page_mapper() -> Option<PageMapper> {
|
||||
PAGE_MAPPER.get().copied()
|
||||
}
|
||||
|
||||
/// Allocation attributes for resource memory: allocator id, page size
|
||||
/// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2
|
||||
/// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only
|
||||
/// heaps, cacheable for the CPU-visible ones).
|
||||
/// shortcut: the console runtime's own choice of page size and memory type
|
||||
/// is not known; this is the plausible one.
|
||||
fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 {
|
||||
const GRAPHICS_ALLOCATOR: u64 = 128 << 16;
|
||||
const DEFAULT_HEAP: u32 = 1;
|
||||
let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 };
|
||||
let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 };
|
||||
let alignment = u64::from(info.alignment.max(1).trailing_zeros());
|
||||
GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
/// A committed resource's memory: from the title's allocator if the
|
||||
/// runtime named one, else our own; zeroed either way.
|
||||
fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> {
|
||||
let Some(&(alloc, _)) = ALLOCATOR.get() else {
|
||||
return Memory::new(info);
|
||||
};
|
||||
let layout = Layout::from_size_align(info.size as usize, info.alignment as usize)
|
||||
.map_err(|_| E_INVALIDARG)?;
|
||||
let attributes = resource_attributes(info, heap_kind);
|
||||
let ptr =
|
||||
NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?;
|
||||
// SAFETY: the allocator handed out `size` bytes.
|
||||
unsafe { ptr.as_ptr().write_bytes(0, layout.size()) };
|
||||
Ok(Memory {
|
||||
ptr,
|
||||
layout,
|
||||
attributes: Some(attributes),
|
||||
})
|
||||
}
|
||||
|
||||
/// `size` zeroed bytes aligned to `alignment` (a power of two).
|
||||
pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
|
||||
Memory::new(AllocationInfo { size, alignment })
|
||||
@@ -388,14 +645,21 @@ impl Memory {
|
||||
.ok_or(E_INVALIDARG)?;
|
||||
// SAFETY: the size is non-zero.
|
||||
let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?;
|
||||
Ok(Memory { ptr, layout })
|
||||
Ok(Memory {
|
||||
ptr,
|
||||
layout,
|
||||
attributes: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Memory {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: allocated in `new` with this layout.
|
||||
unsafe { dealloc(self.ptr.as_ptr(), self.layout) };
|
||||
match (self.attributes, ALLOCATOR.get()) {
|
||||
(Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
|
||||
// SAFETY: allocated in `new` with this layout.
|
||||
_ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,7 +722,12 @@ extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
|
||||
/// to.
|
||||
enum Backing {
|
||||
Committed(Memory),
|
||||
Placed { heap: This, offset: u64 },
|
||||
Placed {
|
||||
heap: This,
|
||||
offset: u64,
|
||||
},
|
||||
/// Memory the title mapped itself, at this address.
|
||||
Address(*mut u8),
|
||||
}
|
||||
|
||||
impl Drop for Backing {
|
||||
@@ -499,6 +768,15 @@ pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u
|
||||
(before != wanted).then(|| (host.as_raw(), before))
|
||||
}
|
||||
|
||||
/// Sets the state the host texture is in after a submission; returns the
|
||||
/// one it was in.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn swap_host_state(this: This, state: u32) -> u32 {
|
||||
resource(this)
|
||||
.host_state
|
||||
.swap(state, std::sync::atomic::Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The host GPU's copy of a title resource, if it has one.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_resource<'a>(
|
||||
@@ -528,6 +806,35 @@ fn host_texture(
|
||||
d.layout = 0;
|
||||
d.alignment = 0;
|
||||
d.flags &= PC_FLAGS;
|
||||
// PC refuses depth targets that are also unordered-access (the console
|
||||
// allows both; Grand Theft Auto VI's shadow maps ask for it).
|
||||
// shortcut: the host copy loses UAV use; give it a second view-only
|
||||
// copy if draws write it as a UAV.
|
||||
const DEPTH: u32 = 2;
|
||||
const UNORDERED: u32 = 4;
|
||||
if d.flags & DEPTH != 0 {
|
||||
d.flags &= !UNORDERED;
|
||||
}
|
||||
d.format = pc_format(d.format);
|
||||
const DENY_SHADER_RESOURCE: u32 = 8;
|
||||
if d.flags & DENY_SHADER_RESOURCE == 0
|
||||
&& let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format)
|
||||
{
|
||||
d.format = typeless;
|
||||
}
|
||||
// The host has no sRGB unordered access: such textures are typeless,
|
||||
// their unordered access views plain UNORM.
|
||||
if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) {
|
||||
d.format = family(d.format);
|
||||
}
|
||||
// The clear value names the format too: format, then color or depth
|
||||
// and stencil (5 words).
|
||||
let clear_value = (!clear.is_null()).then(|| {
|
||||
// SAFETY: the title passes a whole clear value.
|
||||
let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() };
|
||||
value[0] = pc_format(value[0]);
|
||||
value
|
||||
});
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_DEFAULT,
|
||||
..Default::default()
|
||||
@@ -540,18 +847,34 @@ fn host_texture(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
(&raw const d).cast(),
|
||||
D3D12_RESOURCE_STATES(crate::host::texture_state(state) as i32),
|
||||
D3D12_RESOURCE_STATES(
|
||||
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
|
||||
),
|
||||
// The same layout: format, then color or depth and stencil.
|
||||
(!clear.is_null()).then_some(clear.cast()),
|
||||
clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
|
||||
&mut texture,
|
||||
)
|
||||
};
|
||||
if let Err(e) = made {
|
||||
tracing::warn!(error = %e, desc = ?d, "no host texture");
|
||||
}
|
||||
if let Some(t) = &texture {
|
||||
crate::host::name(t, || {
|
||||
format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
|
||||
});
|
||||
}
|
||||
texture
|
||||
}
|
||||
|
||||
/// A texture's console memory and description; `None` for buffers.
|
||||
pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
let r = resource(this);
|
||||
(r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc))
|
||||
}
|
||||
|
||||
/// A buffer's host memory and size; `None` for textures.
|
||||
pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> {
|
||||
if this.is_null() {
|
||||
@@ -573,6 +896,7 @@ impl Resource {
|
||||
.as_ptr()
|
||||
.add(offset as usize)
|
||||
},
|
||||
Backing::Address(at) => at,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -596,6 +920,8 @@ fn hand_out_resource(
|
||||
) -> HRESULT {
|
||||
#[cfg(not(windows))]
|
||||
let _ = (state, clear);
|
||||
#[cfg(windows)]
|
||||
let host = host_texture(&desc, state, clear);
|
||||
let resource = Box::new(Resource {
|
||||
object: Object::new(&RESOURCE_FUNCTIONS),
|
||||
desc,
|
||||
@@ -603,13 +929,35 @@ fn hand_out_resource(
|
||||
heap_flags,
|
||||
backing,
|
||||
#[cfg(windows)]
|
||||
host: host_texture(&desc, state, clear),
|
||||
host_state: host
|
||||
.as_ref()
|
||||
.map_or(0, |t| crate::host::legal_state(t, crate::host::texture_state(state)))
|
||||
.into(),
|
||||
#[cfg(windows)]
|
||||
host_state: crate::host::texture_state(state).into(),
|
||||
host,
|
||||
});
|
||||
#[cfg(windows)]
|
||||
if desc.dimension == BUFFER {
|
||||
let at = std::ptr::from_ref::<Resource>(&resource) as usize;
|
||||
crate::shadow::register(at, resource.data() as u64, desc.width);
|
||||
}
|
||||
object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl Drop for Resource {
|
||||
fn drop(&mut self) {
|
||||
crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
|
||||
crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
|
||||
if self.desc.dimension == BUFFER {
|
||||
crate::shadow::unregister(
|
||||
std::ptr::from_ref::<Resource>(self) as usize,
|
||||
self.data() as u64,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_committed(
|
||||
_: This,
|
||||
heap: *const HeapProperties,
|
||||
@@ -634,7 +982,7 @@ pub(crate) extern "system" fn create_committed(
|
||||
heap = heap.kind,
|
||||
"committed resource"
|
||||
);
|
||||
let memory = match Memory::new(info) {
|
||||
let memory = match Memory::for_resource(info, heap.kind) {
|
||||
Ok(memory) => memory,
|
||||
Err(hr) => return hr,
|
||||
};
|
||||
@@ -650,6 +998,159 @@ pub(crate) extern "system" fn create_committed(
|
||||
)
|
||||
}
|
||||
|
||||
/// Device method 0x3f8, inferred from Grand Theft Auto VI's calls
|
||||
/// (title+0x193e1b4: its back buffers, heap flag "allow display"): the
|
||||
/// committed resource creation of the enhanced-barrier interfaces,
|
||||
/// `(heap, heap flags, desc1, initial layout, clear value, protected
|
||||
/// session, castable format count, castable formats, iid, out)`. The host
|
||||
/// copy starts in the common state, as layouts are not tracked.
|
||||
#[allow(clippy::too_many_arguments)] // the method's own arguments
|
||||
pub(crate) extern "system" fn create_committed3(
|
||||
this: This,
|
||||
heap: *const HeapProperties,
|
||||
heap_flags: u32,
|
||||
desc: *const ResourceDesc,
|
||||
_layout: u32,
|
||||
clear: *const c_void,
|
||||
_protected: This,
|
||||
_castable_count: u32,
|
||||
_castable: *const u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
const COMMON: u32 = 0;
|
||||
create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out)
|
||||
}
|
||||
|
||||
/// Registered page pools (64 KiB pages the title maps into tiled
|
||||
/// resources by page index): first address and page count; a handle is an
|
||||
/// index plus one, a removed pool leaves `None`.
|
||||
static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new());
|
||||
|
||||
fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> {
|
||||
PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Device method 0x250: `(address, page count, handle out)`.
|
||||
pub(crate) extern "system" fn register_page_pool(
|
||||
_: This,
|
||||
address: u64,
|
||||
pages: u32,
|
||||
out: *mut usize,
|
||||
) -> HRESULT {
|
||||
if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool");
|
||||
let mut pools = page_pools();
|
||||
pools.push(Some((address, pages)));
|
||||
// SAFETY: checked non-null; the title passes room for a handle.
|
||||
unsafe { out.write(pools.len()) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Device method 0x258.
|
||||
pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT {
|
||||
match page_pools().get_mut(handle.wrapping_sub(1)) {
|
||||
Some(pool @ Some(_)) => {
|
||||
*pool = None;
|
||||
S_OK
|
||||
}
|
||||
_ => E_INVALIDARG,
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11`
|
||||
/// additions. From Grand Theft Auto VI's call: a resource at a virtual
|
||||
/// address the title mapped itself, `(address, desc1, initial barrier
|
||||
/// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with
|
||||
/// enhanced barriers. GPU addresses are CPU addresses, so the resource is
|
||||
/// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain
|
||||
/// description; its sampler feedback region is not needed.
|
||||
pub(crate) extern "system" fn create_at_address(
|
||||
_: This,
|
||||
address: u64,
|
||||
desc: *const ResourceDesc,
|
||||
layout: u32,
|
||||
clear: *const c_void,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if address == 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
tracing::debug!(
|
||||
address = format_args!("{address:#x}"),
|
||||
dimension = desc.dimension,
|
||||
width = desc.width,
|
||||
layout,
|
||||
"resource at an address"
|
||||
);
|
||||
const COMMON: u32 = 0;
|
||||
const DEFAULT: HeapProperties = HeapProperties {
|
||||
kind: 1,
|
||||
cpu_pages: 0,
|
||||
pool: 0,
|
||||
creation_nodes: 1,
|
||||
visible_nodes: 1,
|
||||
};
|
||||
hand_out_resource(
|
||||
desc,
|
||||
DEFAULT,
|
||||
0,
|
||||
Backing::Address(address as *mut u8),
|
||||
COMMON,
|
||||
clear,
|
||||
iid,
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
/// Textures the title placed in its own memory and views without a
|
||||
/// resource object (device 0x230, Grand Theft Auto VI's streamed and
|
||||
/// interface textures), by address and description: a resource at that
|
||||
/// address, made the first time a draw reads one.
|
||||
/// shortcut: never released (one host texture per distinct address and
|
||||
/// description viewed); release them when the title unmaps or reuses the
|
||||
/// memory once streaming grows VRAM use.
|
||||
#[cfg(windows)]
|
||||
static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
|
||||
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// The resource for a texture placed at `address` with the resource
|
||||
/// description `desc` (as words), made on first use.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(&r) = map.get(&(address, *desc)) {
|
||||
return Some(r as This);
|
||||
}
|
||||
// SAFETY: 56 bytes in the description's layout.
|
||||
let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
|
||||
if d.dimension == BUFFER {
|
||||
return None;
|
||||
}
|
||||
let mut out = std::ptr::null();
|
||||
let made = create_at_address(
|
||||
std::ptr::null(),
|
||||
address,
|
||||
&d,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
&RESOURCE_IIDS[0],
|
||||
&mut out,
|
||||
);
|
||||
if made != S_OK {
|
||||
return None;
|
||||
}
|
||||
map.insert((address, *desc), out as usize);
|
||||
resource(out).host.is_some().then_some(out)
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_placed(
|
||||
_: This,
|
||||
heap: This,
|
||||
@@ -725,8 +1226,59 @@ extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
|
||||
unsafe { out.write(resource(this).desc) };
|
||||
}
|
||||
}
|
||||
/// Device method `GetCustomHeapProperties`, returning its struct through a
|
||||
/// hidden first argument: what a standard heap type is as a custom heap.
|
||||
/// Memory is unified and cache-coherent (as the architecture query says),
|
||||
/// so every type is in pool L0, default heaps are not CPU-visible and the
|
||||
/// others are write-back.
|
||||
pub(crate) extern "system" fn custom_heap_properties(
|
||||
out: *mut HeapProperties,
|
||||
_: This,
|
||||
nodes: u32,
|
||||
kind: u32,
|
||||
) -> *mut HeapProperties {
|
||||
const CUSTOM: u32 = 4;
|
||||
const NOT_AVAILABLE: u32 = 1;
|
||||
const WRITE_BACK: u32 = 3;
|
||||
const L0: u32 = 1;
|
||||
let nodes = nodes.max(1);
|
||||
let cpu_pages = match kind {
|
||||
1 => NOT_AVAILABLE,
|
||||
2 | 3 => WRITE_BACK,
|
||||
_ => 0,
|
||||
};
|
||||
let properties = HeapProperties {
|
||||
kind: CUSTOM,
|
||||
cpu_pages,
|
||||
pool: if cpu_pages == 0 { 0 } else { L0 },
|
||||
creation_nodes: nodes,
|
||||
visible_nodes: nodes,
|
||||
};
|
||||
// SAFETY: the title passes room for the result (null is tolerated).
|
||||
if let Some(out) = unsafe { out.as_mut() } {
|
||||
*out = properties;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
extern "system" fn gpu_address(this: This) -> u64 {
|
||||
resource(this).data() as u64
|
||||
let r = resource(this);
|
||||
let at = r.data() as u64;
|
||||
// The console's GPU addresses fit in 40 bits; its ray-tracing builder
|
||||
// refuses others (diagnostics: which memory breaks that).
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if at >> 40 != 0 {
|
||||
static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()];
|
||||
let backing = match r.backing {
|
||||
Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes),
|
||||
Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"),
|
||||
Backing::Address(_) => "at a title address".into(),
|
||||
};
|
||||
ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| {
|
||||
tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits")
|
||||
});
|
||||
}
|
||||
at
|
||||
}
|
||||
extern "system" fn heap_properties(
|
||||
this: This,
|
||||
@@ -747,8 +1299,8 @@ extern "system" fn heap_properties(
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, heap 1.
|
||||
static HEAP_FUNCTIONS: Table<9> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<HEAP, 9>());
|
||||
static HEAP_FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>());
|
||||
f[0] = heap_query as *const ();
|
||||
f[2] = heap_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
@@ -758,8 +1310,8 @@ static HEAP_FUNCTIONS: Table<9> = {
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3
|
||||
/// console ones).
|
||||
static RESOURCE_FUNCTIONS: Table<18> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 18>());
|
||||
static RESOURCE_FUNCTIONS: Table<32> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>());
|
||||
f[0] = resource_query as *const ();
|
||||
f[2] = resource_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
@@ -856,15 +1408,114 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_setup_heap_properties_and_resources_at_addresses() {
|
||||
let device = crate::device::device();
|
||||
// GetCustomHeapProperties (0xd0): the struct comes back through the
|
||||
// hidden first argument, which is also returned.
|
||||
type Custom =
|
||||
extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties;
|
||||
let mut p = PROPERTIES;
|
||||
let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2);
|
||||
assert_eq!(back, &raw mut p);
|
||||
assert_eq!(
|
||||
(
|
||||
p.kind,
|
||||
p.cpu_pages,
|
||||
p.pool,
|
||||
p.creation_nodes,
|
||||
p.visible_nodes
|
||||
),
|
||||
(4, 3, 1, 1, 1),
|
||||
"upload: custom, write-back, L0"
|
||||
);
|
||||
slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1);
|
||||
assert_eq!(p.cpu_pages, 1, "default: not CPU-visible");
|
||||
|
||||
// 0x428: a buffer over memory the title owns, as GTA VI asks.
|
||||
type At = extern "system" fn(
|
||||
This,
|
||||
u64,
|
||||
*const ResourceDesc,
|
||||
u32,
|
||||
*const c_void,
|
||||
*const Iid,
|
||||
*mut This,
|
||||
) -> HRESULT;
|
||||
let memory = vec![0u8; 0x1_0000];
|
||||
let address = memory.as_ptr() as u64;
|
||||
let mut r = std::ptr::null();
|
||||
let create = slot::<At>(device, 0x428);
|
||||
let desc = buffer(0x1_0000);
|
||||
let null = std::ptr::null();
|
||||
assert_eq!(
|
||||
create(
|
||||
device,
|
||||
address,
|
||||
&desc,
|
||||
u32::MAX,
|
||||
null,
|
||||
&RESOURCE_IIDS[0],
|
||||
&mut r
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(slot::<Address>(r, 0x58)(r), address);
|
||||
assert_eq!(slot::<Release>(r, 0x10)(r), 0);
|
||||
// The title's memory is still there after the release.
|
||||
assert_eq!(memory[0xffff], 0);
|
||||
assert_ne!(
|
||||
create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_cover_every_mip() {
|
||||
let size = |d: &ResourceDesc| footprint(d).map(|i| i.size);
|
||||
assert_eq!(size(&buffer(256)), Some(KIB_64));
|
||||
// 256x256 RGBA8, full chain: 4/3 of 256 KiB, rounded up.
|
||||
assert_eq!(size(&texture(256, 256, 28, 0)), Some(384 << 10));
|
||||
// Textures take their console layout and its alignment (4 KiB
|
||||
// standard swizzle when the description leaves it to the library):
|
||||
// 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on
|
||||
// the console.
|
||||
let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size;
|
||||
let rgba = texture(256, 256, 28, 0);
|
||||
assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096)));
|
||||
let bc7 = footprint(&texture(512, 512, 98, 10));
|
||||
let console = AllocationInfo {
|
||||
size: 0x56000,
|
||||
alignment: 0x1000,
|
||||
};
|
||||
assert_eq!(bc7, Some(console));
|
||||
assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip");
|
||||
// BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB.
|
||||
assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10));
|
||||
assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format");
|
||||
// Linear layout (1) and an explicit mode (64 KiB display, 0x10a).
|
||||
let linear = ResourceDesc {
|
||||
layout: 1,
|
||||
..texture(100, 60, 28, 1)
|
||||
};
|
||||
assert_eq!(
|
||||
texture_layout(&linear).unwrap().planes[0]
|
||||
.layout
|
||||
.desc
|
||||
.swizzle
|
||||
.0,
|
||||
0
|
||||
);
|
||||
let display = ResourceDesc {
|
||||
layout: 0x10a,
|
||||
..texture(100, 60, 28, 1)
|
||||
};
|
||||
assert_eq!(
|
||||
texture_layout(&display).unwrap().planes[0]
|
||||
.layout
|
||||
.desc
|
||||
.swizzle
|
||||
.0,
|
||||
10
|
||||
);
|
||||
|
||||
let mut info = AllocationInfo {
|
||||
size: 0,
|
||||
@@ -875,7 +1526,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
info,
|
||||
AllocationInfo {
|
||||
size: (64 + 384) << 10,
|
||||
size: KIB_64 + size(&descs[1]).unwrap(),
|
||||
alignment: KIB_64
|
||||
}
|
||||
);
|
||||
|
||||
+159
-31
@@ -1,12 +1,12 @@
|
||||
//! Root signatures.
|
||||
//!
|
||||
//! Serializing goes to the host's `D3D12SerializeRootSignature`: the
|
||||
//! description is laid out as on PC, and the blob it returns works as the
|
||||
//! console's, whose two methods sit in the same slots. The console's own
|
||||
//! flags (bit 24 and up) are dropped first.
|
||||
//! Serializing goes to the host's `D3D12SerializeRootSignature` (or its
|
||||
//! versioned form): the description is laid out as on PC, and the blob it
|
||||
//! returns works as the console's, whose two methods sit in the same slots.
|
||||
//! The console's own flags (bit 24 and up) are dropped first.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ffi::{CStr, c_void};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::object::{
|
||||
@@ -37,23 +37,32 @@ pub struct Desc {
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
/// Every version's description starts with the fields of [`Desc`].
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct VersionedDesc {
|
||||
version: u32,
|
||||
desc: Desc,
|
||||
}
|
||||
|
||||
type Serialize =
|
||||
unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
|
||||
type SerializeVersioned =
|
||||
unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
|
||||
|
||||
/// The host's serializer, from `d3d12.dll` in System32.
|
||||
fn host_serializer() -> Option<Serialize> {
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let address = *FUNCTION.get_or_init(|| {
|
||||
/// An export of the host's `d3d12.dll` in System32, looked up once.
|
||||
fn host_export(cache: &OnceLock<Option<usize>>, name: &CStr) -> Option<usize> {
|
||||
*cache.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
|
||||
let dll: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
|
||||
// SAFETY: a NUL-terminated name; System32 only.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
name.as_ptr(),
|
||||
dll.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
@@ -62,14 +71,24 @@ fn host_serializer() -> Option<Serialize> {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a loaded module and a NUL-terminated name.
|
||||
unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) }
|
||||
.map(|f| f as usize)
|
||||
unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
});
|
||||
// SAFETY: the export has this signature.
|
||||
address.map(|a| unsafe { std::mem::transmute::<usize, Serialize>(a) })
|
||||
})
|
||||
}
|
||||
|
||||
fn without_console_flags(desc: Desc) -> Desc {
|
||||
if desc.flags & CONSOLE_FLAGS != 0 {
|
||||
tracing::debug!(
|
||||
flags = format_args!("{:#x}", desc.flags),
|
||||
"console root signature flags dropped"
|
||||
);
|
||||
}
|
||||
Desc {
|
||||
flags: desc.flags & !CONSOLE_FLAGS,
|
||||
..desc
|
||||
}
|
||||
}
|
||||
|
||||
/// `d3d12_xs!D3D12SerializeRootSignature`.
|
||||
@@ -83,22 +102,68 @@ pub extern "system" fn serialize(
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.flags & CONSOLE_FLAGS != 0 {
|
||||
tracing::debug!(
|
||||
flags = format_args!("{:#x}", desc.flags),
|
||||
"console root signature flags dropped"
|
||||
);
|
||||
}
|
||||
let desc = Desc {
|
||||
flags: desc.flags & !CONSOLE_FLAGS,
|
||||
..desc
|
||||
};
|
||||
let Some(serialize) = host_serializer() else {
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") else {
|
||||
tracing::warn!("no host d3d12.dll to serialize root signatures");
|
||||
return E_NOTIMPL;
|
||||
};
|
||||
// SAFETY: the host function takes the same arguments the title passed.
|
||||
unsafe { serialize(&desc, version, blob, error) }
|
||||
// SAFETY: the export has this signature; it takes what the title passed.
|
||||
unsafe {
|
||||
std::mem::transmute::<usize, Serialize>(address)(
|
||||
&without_console_flags(desc),
|
||||
version,
|
||||
blob,
|
||||
error,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `d3d12_xs!D3D12SerializeVersionedRootSignature`.
|
||||
pub extern "system" fn serialize_versioned(
|
||||
desc: *const VersionedDesc,
|
||||
blob: *mut *mut c_void,
|
||||
error: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else {
|
||||
tracing::warn!("no host d3d12.dll to serialize root signatures");
|
||||
return E_NOTIMPL;
|
||||
};
|
||||
let desc = VersionedDesc {
|
||||
desc: without_console_flags(desc.desc),
|
||||
..desc
|
||||
};
|
||||
// SAFETY: the export has this signature; it takes what the title passed.
|
||||
unsafe { std::mem::transmute::<usize, SerializeVersioned>(address)(&desc, blob, error) }
|
||||
}
|
||||
|
||||
type Deserialize =
|
||||
unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT;
|
||||
|
||||
/// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the
|
||||
/// host's serialization, so the host's deserializer reads them, and its
|
||||
/// object (IUnknown, then the description getter) is laid out as the
|
||||
/// console's. Grand Theft Auto VI's upscaler asks with the PC interface id.
|
||||
pub extern "system" fn create_deserializer(
|
||||
blob: *const u8,
|
||||
size: usize,
|
||||
iid: *const Iid,
|
||||
out: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
if blob.is_null() || out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else {
|
||||
tracing::warn!("no host d3d12.dll to deserialize root signatures");
|
||||
return E_NOTIMPL;
|
||||
};
|
||||
// SAFETY: the export has this signature; it takes what the title passed.
|
||||
unsafe { std::mem::transmute::<usize, Deserialize>(address)(blob, size, iid, out) }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
@@ -139,8 +204,8 @@ extern "system" fn release(this: This) -> u32 {
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 8>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
@@ -193,4 +258,67 @@ mod tests {
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0);
|
||||
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
|
||||
}
|
||||
|
||||
/// The host's deserializer reads our blobs back (the upscaler's call).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn our_blobs_deserialize_on_the_host() {
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer;
|
||||
use windows::core::Interface;
|
||||
let desc = VersionedDesc {
|
||||
version: 1,
|
||||
desc: Desc {
|
||||
parameter_count: 0,
|
||||
parameters: std::ptr::null(),
|
||||
sampler_count: 0,
|
||||
samplers: std::ptr::null(),
|
||||
flags: 1,
|
||||
},
|
||||
};
|
||||
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
|
||||
assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
|
||||
let blob = blob.cast_const().cast::<Object>();
|
||||
let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
|
||||
let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
|
||||
let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes();
|
||||
let iid = guid(
|
||||
u32::from_be_bytes(iid[0..4].try_into().unwrap()),
|
||||
u16::from_be_bytes(iid[4..6].try_into().unwrap()),
|
||||
u16::from_be_bytes(iid[6..8].try_into().unwrap()),
|
||||
iid[8..16].try_into().unwrap(),
|
||||
);
|
||||
let mut out = std::ptr::null_mut();
|
||||
assert_eq!(create_deserializer(data, size, &iid, &mut out), S_OK);
|
||||
// SAFETY: the host handed out this interface.
|
||||
let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) };
|
||||
// SAFETY: valid while the deserializer lives.
|
||||
let read = unsafe { &*deserializer.GetRootSignatureDesc() };
|
||||
assert_eq!((read.NumParameters, read.Flags.0), (0, 1));
|
||||
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
|
||||
}
|
||||
|
||||
/// Version 1.0 through the versioned entry point, with a console flag.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn versioned_descriptions_serialize_on_the_host() {
|
||||
let desc = VersionedDesc {
|
||||
version: 1,
|
||||
desc: Desc {
|
||||
parameter_count: 0,
|
||||
parameters: std::ptr::null(),
|
||||
sampler_count: 0,
|
||||
samplers: std::ptr::null(),
|
||||
flags: 0x0200_0001,
|
||||
},
|
||||
};
|
||||
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
|
||||
assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
|
||||
let blob = blob.cast_const().cast::<Object>();
|
||||
assert!(slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob) > 0);
|
||||
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
|
||||
assert_eq!(
|
||||
serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error),
|
||||
E_INVALIDARG
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Samplers as the host describes them, from the console's sampler
|
||||
//! description (`CreateSamplerX`), which names the hardware's sampler
|
||||
//! fields. (Immediate samplers in shader code come decoded with the
|
||||
//! translation.)
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// The fields both forms share.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct Fields {
|
||||
/// Point 0, bilinear 1, anisotropic point 2, anisotropic bilinear 3.
|
||||
mag: u32,
|
||||
min: u32,
|
||||
/// None 0, point 1, linear 2.
|
||||
mip: u32,
|
||||
/// Plain 0, minimum 1, maximum 2.
|
||||
mode: u32,
|
||||
/// Host address modes.
|
||||
address: [u32; 3],
|
||||
anisotropy: u32,
|
||||
/// Host comparison function.
|
||||
compare: u32,
|
||||
min_lod: f32,
|
||||
max_lod: f32,
|
||||
bias: f32,
|
||||
border: [f32; 4],
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn host(&self) -> D3D12_SAMPLER_DESC {
|
||||
let linear = |f: u32| u32::from(f == 1 || f == 3);
|
||||
let aniso = self.mag >= 2 || self.min >= 2;
|
||||
// The console compares when the instruction says so, with the
|
||||
// sampler's function; the host needs a comparison sampler for that.
|
||||
// A sampler given a real test (less ... greater-or-equal) is one;
|
||||
// never, always and none are plain samplers.
|
||||
const LESS: u32 = 2;
|
||||
const GREATER_EQUAL: u32 = 7;
|
||||
let compares = (LESS..=GREATER_EQUAL).contains(&self.compare);
|
||||
let reduction = match self.mode {
|
||||
1 => 2,
|
||||
2 => 3,
|
||||
_ => u32::from(compares),
|
||||
};
|
||||
let filter = if aniso {
|
||||
0x55
|
||||
} else {
|
||||
linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2)
|
||||
};
|
||||
D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER((reduction << 7 | filter) as i32),
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32),
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32),
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32),
|
||||
MipLODBias: self.bias,
|
||||
MaxAnisotropy: if aniso {
|
||||
self.anisotropy.clamp(1, 16)
|
||||
} else {
|
||||
1
|
||||
},
|
||||
ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32),
|
||||
BorderColor: self.border,
|
||||
MinLOD: self.min_lod,
|
||||
// Without a mip filter the console samples mip 0 only.
|
||||
MaxLOD: if self.mip == 0 {
|
||||
self.min_lod
|
||||
} else {
|
||||
self.max_lod
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The console's sampler description (27 words): flags, magnification,
|
||||
/// minification, mip and depth filters, filter mode, three address modes,
|
||||
/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias
|
||||
/// and threshold, comparison, border color, then tuning words.
|
||||
pub(crate) fn console(words: &[u32; 27]) -> D3D12_SAMPLER_DESC {
|
||||
let f = |i: usize| f32::from_bits(words[i]);
|
||||
Fields {
|
||||
mag: words[1],
|
||||
min: words[2],
|
||||
mip: words[3],
|
||||
mode: words[5],
|
||||
address: [words[6], words[7], words[8]],
|
||||
min_lod: f(9),
|
||||
max_lod: f(10),
|
||||
bias: f(11),
|
||||
anisotropy: words[13],
|
||||
compare: words[16],
|
||||
border: [f(17), f(18), f(19), f(20)],
|
||||
}
|
||||
.host()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn console_descriptions_decode() {
|
||||
let mut w = [0u32; 27];
|
||||
w[1] = 1; // bilinear magnification
|
||||
w[2] = 0; // point minification
|
||||
w[3] = 2; // linear mips
|
||||
w[6..9].copy_from_slice(&[3, 3, 3]);
|
||||
w[10] = 1000.0f32.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!(d.Filter.0, 0x5, "min point, mag and mip linear");
|
||||
assert_eq!(d.AddressW, D3D12_TEXTURE_ADDRESS_MODE_CLAMP);
|
||||
assert_eq!(d.MaxLOD, 1000.0);
|
||||
// A less-or-equal test makes a comparison sampler; never does not.
|
||||
w[16] = 4;
|
||||
assert_eq!(console(&w).Filter.0, 0x85);
|
||||
assert_eq!(console(&w).ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL);
|
||||
w[16] = 1;
|
||||
assert_eq!(console(&w).Filter.0, 0x5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! Translated shaders kept on disk (decision 0003): under the configured
|
||||
//! cache folder, keyed by the container's content and by the VIctory build
|
||||
//! that translated it (the BLAKE3 of our executable), so a rebuilt
|
||||
//! translator never serves an old translation. Entries go through
|
||||
//! `victory-pipeline`'s content-addressed cache, which writes them
|
||||
//! atomically; an entry that does not read back is translated again.
|
||||
//!
|
||||
//! The entry is our own encoding of [`HostShader`]: a field added to it
|
||||
//! must be added to [`encode`] and [`decode`] too (entries of older builds
|
||||
//! are ignored anyway).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use victory_pipeline::{Cache, Converter};
|
||||
use victory_shader::emit::{HostShader, StaticSampler, UserData};
|
||||
use victory_shader::{HwStage, RootType};
|
||||
|
||||
static CACHE: OnceLock<Cache> = OnceLock::new();
|
||||
static HITS: AtomicU64 = AtomicU64::new(0);
|
||||
static MISSES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Keeps translated shaders in `dir` from now on.
|
||||
pub fn use_shader_cache(dir: PathBuf) {
|
||||
match Cache::open(dir) {
|
||||
Ok(cache) => {
|
||||
let _ = CACHE.set(cache);
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "no shader cache"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shaders found in the cache and translated since the start.
|
||||
pub(crate) fn counts() -> (u64, u64) {
|
||||
(HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// What identifies this build: the BLAKE3 of our executable file.
|
||||
fn build() -> &'static [u8; 32] {
|
||||
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
|
||||
BUILD.get_or_init(|| {
|
||||
let exe = std::env::current_exe().and_then(std::fs::read);
|
||||
match exe {
|
||||
Ok(bytes) => *blake3::hash(&bytes).as_bytes(),
|
||||
Err(e) => {
|
||||
// Without it no entry can be trusted: a fresh key per run.
|
||||
tracing::warn!(error = %e, "cannot read our executable; shader cache unused");
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
*blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The translation of a console shader container, from the cache when
|
||||
/// there is one.
|
||||
pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
|
||||
let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
|
||||
match CACHE.get() {
|
||||
Some(cache) => cached(cache, build(), container, translate),
|
||||
None => translate(container),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache entry's converter: the build and the container in, the
|
||||
/// encoded translation out. `ran` tells a miss from a hit.
|
||||
struct Translate<F> {
|
||||
translate: F,
|
||||
ran: AtomicBool,
|
||||
}
|
||||
|
||||
impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
|
||||
fn id(&self) -> &'static str {
|
||||
"shader.dxil"
|
||||
}
|
||||
fn version(&self) -> u32 {
|
||||
// The build fingerprint in the input does the versioning.
|
||||
1
|
||||
}
|
||||
fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
|
||||
self.ran.store(true, Ordering::Relaxed);
|
||||
let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?;
|
||||
Ok(encode(&shader))
|
||||
}
|
||||
}
|
||||
|
||||
fn cached(
|
||||
cache: &Cache,
|
||||
build: &[u8; 32],
|
||||
container: &[u8],
|
||||
translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
|
||||
) -> Result<HostShader, String> {
|
||||
let input = [&build[..], container].concat();
|
||||
let converter = Translate {
|
||||
translate,
|
||||
ran: AtomicBool::new(false),
|
||||
};
|
||||
for _ in 0..2 {
|
||||
let path = cache
|
||||
.get_or_convert(&converter, &input)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) {
|
||||
let (counter, what) = if converter.ran.load(Ordering::Relaxed) {
|
||||
(&MISSES, "translated and cached")
|
||||
} else {
|
||||
(&HITS, "from the cache")
|
||||
};
|
||||
counter.fetch_add(1, Ordering::Relaxed);
|
||||
tracing::debug!(path = %path.display(), "shader {what}");
|
||||
return Ok(shader);
|
||||
}
|
||||
tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
MISSES.fetch_add(1, Ordering::Relaxed);
|
||||
(converter.translate)(container)
|
||||
}
|
||||
|
||||
const MAGIC: &[u8; 4] = b"VSH1";
|
||||
const STAGES: [HwStage; 8] = [
|
||||
HwStage::Ls,
|
||||
HwStage::Hs,
|
||||
HwStage::Es,
|
||||
HwStage::Gs,
|
||||
HwStage::Vs,
|
||||
HwStage::Ps,
|
||||
HwStage::Ms,
|
||||
HwStage::Cs,
|
||||
];
|
||||
|
||||
fn root_code(r: RootType) -> u32 {
|
||||
match r {
|
||||
RootType::Constants => 0,
|
||||
RootType::Descriptor => 1,
|
||||
RootType::Table => 2,
|
||||
RootType::ImmediateSampler => 3,
|
||||
RootType::ResourceHeap => 4,
|
||||
RootType::SamplerHeap => 5,
|
||||
RootType::Other(x) => 6 + x,
|
||||
}
|
||||
}
|
||||
|
||||
fn root_type(code: u32) -> RootType {
|
||||
match code {
|
||||
0 => RootType::Constants,
|
||||
1 => RootType::Descriptor,
|
||||
2 => RootType::Table,
|
||||
3 => RootType::ImmediateSampler,
|
||||
4 => RootType::ResourceHeap,
|
||||
5 => RootType::SamplerHeap,
|
||||
x => RootType::Other(x - 6),
|
||||
}
|
||||
}
|
||||
|
||||
/// Little-endian words and length-prefixed lists.
|
||||
fn encode(s: &HostShader) -> Vec<u8> {
|
||||
let mut out = MAGIC.to_vec();
|
||||
let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes());
|
||||
let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32;
|
||||
word(&mut out, stage);
|
||||
word(&mut out, s.dxil.len() as u32);
|
||||
out.extend(&s.dxil);
|
||||
word(&mut out, s.user_data.len() as u32);
|
||||
for u in &s.user_data {
|
||||
for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] {
|
||||
word(&mut out, v);
|
||||
}
|
||||
}
|
||||
word(&mut out, s.samplers.len() as u32);
|
||||
for sampler in &s.samplers {
|
||||
for &v in sampler {
|
||||
word(&mut out, v);
|
||||
}
|
||||
}
|
||||
word(&mut out, s.static_samplers.len() as u32);
|
||||
for t in &s.static_samplers {
|
||||
let [u, v, w] = t.address;
|
||||
let words = [
|
||||
t.filter,
|
||||
u,
|
||||
v,
|
||||
w,
|
||||
t.mip_lod_bias.to_bits(),
|
||||
t.max_anisotropy,
|
||||
t.comparison,
|
||||
t.border,
|
||||
t.min_lod.to_bits(),
|
||||
t.max_lod.to_bits(),
|
||||
];
|
||||
for v in words {
|
||||
word(&mut out, v);
|
||||
}
|
||||
}
|
||||
for slots in [&s.root_cbvs, &s.root_srvs] {
|
||||
word(&mut out, slots.len() as u32);
|
||||
out.extend(slots);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn decode(bytes: &[u8]) -> Option<HostShader> {
|
||||
struct Reader<'a>(&'a [u8]);
|
||||
impl<'a> Reader<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let (head, rest) = self.0.split_at_checked(n)?;
|
||||
self.0 = rest;
|
||||
Some(head)
|
||||
}
|
||||
fn word(&mut self) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
|
||||
}
|
||||
fn list(&mut self) -> Option<Vec<u8>> {
|
||||
let n = self.word()? as usize;
|
||||
Some(self.take(n)?.to_vec())
|
||||
}
|
||||
}
|
||||
let mut r = Reader(bytes);
|
||||
if r.take(4)? != MAGIC {
|
||||
return None;
|
||||
}
|
||||
let stage = *STAGES.get(r.word()? as usize)?;
|
||||
let dxil = r.list()?;
|
||||
let n = r.word()? as usize;
|
||||
let mut user_data = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
user_data.push(UserData {
|
||||
index: r.word()?,
|
||||
slot: u8::try_from(r.word()?).ok()?,
|
||||
root: root_type(r.word()?),
|
||||
dword: r.word()?,
|
||||
});
|
||||
}
|
||||
let n = r.word()? as usize;
|
||||
let mut samplers = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]);
|
||||
}
|
||||
let n = r.word()? as usize;
|
||||
let mut static_samplers = Vec::with_capacity(n.min(256));
|
||||
for _ in 0..n {
|
||||
static_samplers.push(StaticSampler {
|
||||
filter: r.word()?,
|
||||
address: [r.word()?, r.word()?, r.word()?],
|
||||
mip_lod_bias: f32::from_bits(r.word()?),
|
||||
max_anisotropy: r.word()?,
|
||||
comparison: r.word()?,
|
||||
border: r.word()?,
|
||||
min_lod: f32::from_bits(r.word()?),
|
||||
max_lod: f32::from_bits(r.word()?),
|
||||
});
|
||||
}
|
||||
let root_cbvs = r.list()?;
|
||||
let root_srvs = r.list()?;
|
||||
r.0.is_empty().then_some(HostShader {
|
||||
stage,
|
||||
dxil,
|
||||
user_data,
|
||||
samplers,
|
||||
static_samplers,
|
||||
root_cbvs,
|
||||
root_srvs,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn shader() -> HostShader {
|
||||
HostShader {
|
||||
stage: HwStage::Ps,
|
||||
dxil: b"DXBC and the rest".to_vec(),
|
||||
user_data: vec![UserData {
|
||||
index: 8,
|
||||
slot: 1,
|
||||
root: RootType::Table,
|
||||
dword: 0,
|
||||
}],
|
||||
samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]],
|
||||
static_samplers: vec![StaticSampler::from_words([
|
||||
0x400,
|
||||
0xc0_0000,
|
||||
0x18f0_0000,
|
||||
0,
|
||||
])],
|
||||
root_cbvs: vec![2],
|
||||
root_srvs: vec![0, 3],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translations_come_back_from_the_cache() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = Cache::open(dir.path()).unwrap();
|
||||
let build = [7u8; 32];
|
||||
let container = b"a console container".as_slice();
|
||||
let runs = AtomicU64::new(0);
|
||||
let translate = |_: &[u8]| {
|
||||
runs.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(shader())
|
||||
};
|
||||
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
|
||||
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
|
||||
assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");
|
||||
|
||||
// Another build translates again.
|
||||
assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader()));
|
||||
assert_eq!(runs.load(Ordering::Relaxed), 2);
|
||||
|
||||
// A damaged entry is a miss, translated and stored again.
|
||||
for e in walk(dir.path()) {
|
||||
std::fs::write(e, b"VSH1 broken").unwrap();
|
||||
}
|
||||
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
|
||||
assert_eq!(runs.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
|
||||
assert_eq!(runs.load(Ordering::Relaxed), 3);
|
||||
|
||||
// Failures are not stored.
|
||||
let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned());
|
||||
assert!(cached(&cache, &build, b"other", fail).is_err());
|
||||
}
|
||||
|
||||
fn walk(dir: &std::path::Path) -> Vec<PathBuf> {
|
||||
let mut files = Vec::new();
|
||||
for e in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
if e.path().is_dir() {
|
||||
files.extend(walk(&e.path()));
|
||||
} else {
|
||||
files.push(e.path());
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_round_trip_and_reject_damage() {
|
||||
let bytes = encode(&shader());
|
||||
assert_eq!(decode(&bytes), Some(shader()));
|
||||
assert_eq!(decode(&bytes[..bytes.len() - 1]), None);
|
||||
assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None);
|
||||
assert_eq!(decode(b"VSH0"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! Host copies of title buffers (decision 0007, step 3 and "Copies of title
|
||||
//! memory"). Title buffers are title memory, which the host GPU cannot
|
||||
//! read, so a buffer a draw uses gets a persistent host buffer of its size
|
||||
//! on first use (system memory shaders may also write), and the ranges each
|
||||
//! submission reads (vertex, index and constant data, buffer views) are
|
||||
//! brought up to date from title memory before it runs: the 64 KiB pages
|
||||
//! the title wrote since they were last copied ([`crate::watch`]: write
|
||||
//! watching, or read-only guards on physical-page views), all of it where
|
||||
//! neither works. A title GPU address inside the buffer is the same offset
|
||||
//! in its copy. Ranges shaders write go back to title memory after the
|
||||
//! submission ([`Shadow::gpu_writes`]).
|
||||
//!
|
||||
//! shortcut: only the ranges draws are known to read are brought up to
|
||||
//! date (vertex and index buffer views, constant buffers in tables, root
|
||||
//! descriptors, buffer views in tables); buffers read through directly
|
||||
//! indexed heaps keep what their first use copied.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
|
||||
|
||||
use crate::host::{HostList, host};
|
||||
use crate::watch::PAGE;
|
||||
|
||||
/// A title buffer's host copy.
|
||||
pub(crate) struct Shadow {
|
||||
pub(crate) buffer: ID3D12Resource,
|
||||
data: *mut u8,
|
||||
gpu: u64,
|
||||
/// Where the title buffer starts and how long it is.
|
||||
start: u64,
|
||||
len: u64,
|
||||
/// Per page of title memory from `start`'s on: the write-watch asking
|
||||
/// after which it was last copied (0: never).
|
||||
copied: Mutex<Vec<u64>>,
|
||||
/// Whether the memory is write-watched: unknown, yes, no.
|
||||
watched: AtomicU8,
|
||||
/// Ranges shaders of a submission not yet copied back may be writing:
|
||||
/// title memory there is older than the copy.
|
||||
pending: Mutex<Vec<(usize, usize)>>,
|
||||
}
|
||||
|
||||
const NOT_WATCHED: u8 = 2;
|
||||
|
||||
// SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping
|
||||
// written only on the submitting thread.
|
||||
unsafe impl Send for Shadow {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Shadow {}
|
||||
|
||||
impl Shadow {
|
||||
/// The host GPU address of a title address inside the buffer.
|
||||
pub(crate) fn gpu(&self, address: u64) -> u64 {
|
||||
self.gpu + (address - self.start)
|
||||
}
|
||||
|
||||
/// Bytes from a title address to the buffer's end.
|
||||
pub(crate) fn left(&self, address: u64) -> u64 {
|
||||
(self.start + self.len).saturating_sub(address)
|
||||
}
|
||||
|
||||
/// Offset of a title address from the buffer's start.
|
||||
pub(crate) fn offset(&self, address: u64) -> u64 {
|
||||
address - self.start
|
||||
}
|
||||
|
||||
/// Brings `len` bytes at `address` up to date when `list` is submitted,
|
||||
/// and keeps the copy alive until the list is reset.
|
||||
pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
|
||||
let len = len.min(self.start + self.len - address);
|
||||
list.defer_refresh(self, address as usize, len as usize);
|
||||
}
|
||||
|
||||
fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow {
|
||||
let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64;
|
||||
Shadow {
|
||||
buffer,
|
||||
data,
|
||||
gpu,
|
||||
start,
|
||||
len,
|
||||
copied: Mutex::new(vec![0; pages as usize]),
|
||||
watched: AtomicU8::new(0),
|
||||
pending: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shaders of `list` may write `[address, address + len)` of the copy
|
||||
/// (unordered access): after the list's submission has run, the range
|
||||
/// is copied back into title memory, where the title reads it; until
|
||||
/// then no refresh copies title memory over it. Call after the
|
||||
/// [`Shadow::refresh`] that gives the shaders the title's data.
|
||||
///
|
||||
/// shortcut: the whole range goes back after every submission that
|
||||
/// declares it; copy back only what shaders wrote (a GPU-side dirty
|
||||
/// mask) if big unordered-access buffers make it slow.
|
||||
pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
|
||||
let len = len.min(self.left(address));
|
||||
list.defer_gpu_write(self, address as usize, len as usize);
|
||||
}
|
||||
|
||||
/// At submission: a submitted list's shaders write this range.
|
||||
pub(crate) fn writing(&self, address: usize, len: usize) {
|
||||
self.pending
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push((address, address + len));
|
||||
}
|
||||
|
||||
/// After the submission ran: copies what its shaders may have written
|
||||
/// back into title memory (unmapped pages left alone). Pages wholly
|
||||
/// written are current in this copy, so our own write is not taken for
|
||||
/// the title's.
|
||||
pub(crate) fn copy_back(&self, address: usize, len: usize) {
|
||||
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
|
||||
let (from, to) = (address.max(start), (address + len).min(end));
|
||||
if from < to {
|
||||
// SAFETY: inside the mapping.
|
||||
let at = unsafe { self.data.add(from - start) };
|
||||
crate::watch::writing(from, to - from);
|
||||
crate::host::write_mapped(from as *mut u8, at, to - from);
|
||||
let (first, last) = (from.div_ceil(PAGE), to / PAGE);
|
||||
if first < last
|
||||
&& self.watched.load(Ordering::Relaxed) != NOT_WATCHED
|
||||
&& let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true)
|
||||
{
|
||||
let base = start / PAGE;
|
||||
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
copied[first - base..last - base].fill(now);
|
||||
}
|
||||
}
|
||||
let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(i) = pending.iter().position(|&r| r == (address, address + len)) {
|
||||
pending.swap_remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// At submission: copies what changed of `[address, address + len)`
|
||||
/// since it was last copied (all of it if the memory is not
|
||||
/// write-watched). Returns the bytes copied.
|
||||
pub(crate) fn update(&self, address: usize, len: usize) -> usize {
|
||||
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
|
||||
let (from, to) = (address.max(start), (address + len).min(end));
|
||||
if from >= to {
|
||||
return 0;
|
||||
}
|
||||
let mut busy: Vec<(usize, usize)> = self
|
||||
.pending
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&(a, e)| a < to && e > from)
|
||||
.collect();
|
||||
if !busy.is_empty() {
|
||||
// Rare: around ranges shaders are writing, everything is copied.
|
||||
busy.sort_unstable();
|
||||
let (mut at, mut bytes) = (from, 0);
|
||||
for (a, e) in busy {
|
||||
if a > at {
|
||||
bytes += self.copy(at, a);
|
||||
}
|
||||
at = at.max(e);
|
||||
}
|
||||
if at < to {
|
||||
bytes += self.copy(at, to);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
|
||||
if let Some((now, written)) = crate::watch::writes(from, to, true) {
|
||||
self.watched.store(1, Ordering::Relaxed);
|
||||
let copied = self.copy_stale(from, to, now, &written);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
use crate::copystat::{C, add};
|
||||
add(C::Checked, (to - from) as u64);
|
||||
add(C::Unchanged, (to - from).saturating_sub(copied) as u64);
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
self.watched.store(NOT_WATCHED, Ordering::Relaxed);
|
||||
}
|
||||
self.copy(from, to);
|
||||
to - from
|
||||
}
|
||||
|
||||
/// Copies the pages of `[from, to)` written after their last copy
|
||||
/// (`written`: last writes by page, in page order; `now`: this
|
||||
/// asking), whole pages within the buffer.
|
||||
fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize {
|
||||
let base = self.start as usize / PAGE;
|
||||
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut writes = written.iter().peekable();
|
||||
let (mut bytes, mut run) = (0, None);
|
||||
let last = (to - 1) / PAGE;
|
||||
for page in from / PAGE..=last {
|
||||
let write = match writes.peek() {
|
||||
Some(&&(p, w)) if p == page => {
|
||||
writes.next();
|
||||
w
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let at = &mut copied[page - base];
|
||||
if *at == 0 || write > *at {
|
||||
*at = now;
|
||||
run.get_or_insert(page);
|
||||
} else if let Some(first) = run.take() {
|
||||
bytes += self.copy(first * PAGE, page * PAGE);
|
||||
}
|
||||
}
|
||||
if let Some(first) = run {
|
||||
bytes += self.copy(first * PAGE, (last + 1) * PAGE);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Copies title memory `[from, to)`, cut to the buffer, into the copy.
|
||||
fn copy(&self, from: usize, to: usize) -> usize {
|
||||
let (start, end) = (self.start as usize, (self.start + self.len) as usize);
|
||||
let (from, to) = (from.max(start), to.min(end));
|
||||
// SAFETY: inside the mapping (`from` and `to` are within the buffer).
|
||||
let at = unsafe { self.data.add(from - start) };
|
||||
crate::host::copy_mapped(at, from as *const u8, to - from, false);
|
||||
to - from
|
||||
}
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
end: u64,
|
||||
shadow: Option<Arc<Shadow>>,
|
||||
}
|
||||
|
||||
/// Title buffers by (start address, resource), with their copy once made.
|
||||
static BUFFERS: Mutex<BTreeMap<(u64, usize), Entry>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> {
|
||||
BUFFERS.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// A title buffer exists at `start` (`len` bytes).
|
||||
pub(crate) fn register(resource: usize, start: u64, len: u64) {
|
||||
buffers().insert(
|
||||
(start, resource),
|
||||
Entry {
|
||||
end: start + len,
|
||||
shadow: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The title released it; lists that still hold its copy keep it alive.
|
||||
pub(crate) fn unregister(resource: usize, start: u64) {
|
||||
buffers().remove(&(start, resource));
|
||||
}
|
||||
|
||||
/// The copy of the innermost title buffer holding `[address, address +
|
||||
/// len)`, made on first use.
|
||||
pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
|
||||
let end = address.checked_add(len.max(1))?;
|
||||
let mut map = buffers();
|
||||
let key = map
|
||||
.range(..=(address, usize::MAX))
|
||||
.rev()
|
||||
.take(64)
|
||||
.find(|(_, e)| e.end >= end)
|
||||
.map(|(k, _)| *k);
|
||||
let Some(key) = key else {
|
||||
drop(map);
|
||||
return loose(address, end);
|
||||
};
|
||||
let entry = map.get_mut(&key)?;
|
||||
if entry.shadow.is_none() {
|
||||
let len = entry.end - key.0;
|
||||
// Rounded up so that views ending in the buffer's last 256 bytes fit.
|
||||
// Shaders write some buffers (unordered access), so not upload memory.
|
||||
let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?;
|
||||
crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
if len >= 16 << 20 {
|
||||
tracing::info!(
|
||||
start = format_args!("{:#x}", key.0),
|
||||
len,
|
||||
"large buffer copied to the host"
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
start = format_args!("{:#x}", key.0),
|
||||
len,
|
||||
"buffer copied to the host"
|
||||
);
|
||||
}
|
||||
entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len)));
|
||||
}
|
||||
entry.shadow.clone()
|
||||
}
|
||||
|
||||
/// Titles also use memory outside any buffer object as GPU memory (Grand
|
||||
/// Theft Auto VI's interface vertices, from its own allocator). Such memory
|
||||
/// gets copies of the aligned windows it touches.
|
||||
/// shortcut: copies of windows are never freed; key them to the title's
|
||||
/// allocations if memory use grows.
|
||||
const WINDOW: u64 = 4 << 20;
|
||||
|
||||
/// Copies of title memory outside buffers, by (start, length).
|
||||
static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
|
||||
let start = address & !(WINDOW - 1);
|
||||
let len = end.next_multiple_of(WINDOW) - start;
|
||||
let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(shadow) = map.get(&(start, len)) {
|
||||
return Some(shadow.clone());
|
||||
}
|
||||
let (buffer, data) = host()?.shared_buffer(len)?;
|
||||
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
tracing::debug!(
|
||||
start = format_args!("{start:#x}"),
|
||||
len,
|
||||
"loose memory copied to the host"
|
||||
);
|
||||
let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len));
|
||||
map.insert((start, len), shadow.clone());
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// For device-removed reports: the copy of title memory whose host range
|
||||
/// starts closest below host GPU address `va`, and where `va` is in it.
|
||||
pub(crate) fn near(va: u64) -> String {
|
||||
let mut all: Vec<(u64, u64, u64)> = buffers()
|
||||
.values()
|
||||
.filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len)))
|
||||
.collect();
|
||||
all.extend(
|
||||
LOOSE
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.values()
|
||||
.map(|s| (s.gpu, s.start, s.len)),
|
||||
);
|
||||
let below = all.iter().filter(|c| c.0 <= va).max();
|
||||
let above = all.iter().filter(|c| c.0 > va).min();
|
||||
let mut text = match below {
|
||||
Some(&(gpu, start, len)) => format!(
|
||||
"; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}",
|
||||
va - gpu
|
||||
),
|
||||
None => "; no title memory copy below it".into(),
|
||||
};
|
||||
if let Some(&(gpu, start, len)) = above {
|
||||
text.push_str(&format!(
|
||||
"; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)",
|
||||
all.len()
|
||||
));
|
||||
}
|
||||
text
|
||||
}
|
||||
@@ -74,8 +74,8 @@ extern "system" fn release(this: This) -> u32 {
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 8>());
|
||||
static FUNCTIONS: Table<24> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 24>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Texture contents the title writes itself (decision 0007, "Texture
|
||||
//! memory"): streamed pages, layout-library copies, movie frames, glyph
|
||||
//! atlases. Such a texture lives in console memory in its tiled layout;
|
||||
//! before a submission samples its host copy, the memory is detiled into a
|
||||
//! staging buffer when its content changed, and the staging buffer is
|
||||
//! copied into the host texture.
|
||||
//!
|
||||
//! "Changed" means a page of the memory was written since the last detiling
|
||||
//! ([`crate::watch`]), in write-watched memory; in physical-page views,
|
||||
//! which cannot be watched, a content hash of the whole memory at every
|
||||
//! submission that samples it.
|
||||
//!
|
||||
//! shortcut: a change detiles the whole texture, not the pages written.
|
||||
//! Only textures read through descriptor tables are brought up to date
|
||||
//! (directly indexed views are not known per draw); plane 0 is uploaded
|
||||
//! (every mip and array slice), depth and stencil planes are not.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use crate::host::{HostList, host};
|
||||
use crate::object::This;
|
||||
|
||||
macro_rules! once {
|
||||
($($arg:tt)*) => {{
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!($($arg)*));
|
||||
}};
|
||||
}
|
||||
|
||||
/// A texture's upload state: the staging buffer laid out as the host
|
||||
/// texture's subresources, and what was last detiled.
|
||||
struct Staging {
|
||||
buffer: ID3D12Resource,
|
||||
data: *mut u8,
|
||||
footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
|
||||
rows: Vec<u32>,
|
||||
layout: victory_formats::texture::Layout,
|
||||
/// Mips per array slice.
|
||||
mips: u32,
|
||||
memory: *const u8,
|
||||
last: Mutex<Last>,
|
||||
}
|
||||
|
||||
/// What a texture's staging buffer holds: the hash of the memory detiled
|
||||
/// (memory not watched), or the write-watch asking it was detiled after,
|
||||
/// with room to read the memory into.
|
||||
#[derive(Default)]
|
||||
struct Last {
|
||||
hash: Option<blake3::Hash>,
|
||||
asked: u64,
|
||||
read: Vec<u8>,
|
||||
}
|
||||
|
||||
// SAFETY: the staging mapping is written only at submission, under
|
||||
// `last`'s lock; the title memory is only read.
|
||||
unsafe impl Send for Staging {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Staging {}
|
||||
|
||||
static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
|
||||
|
||||
/// Textures the host GPU wrote by a copy or resolve: their contents are on
|
||||
/// the host, not in title memory, which stays as it was.
|
||||
static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
|
||||
|
||||
/// A host copy or resolve writes `resource`.
|
||||
pub(crate) fn host_written(resource: This) {
|
||||
let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
set.get_or_insert_with(Default::default)
|
||||
.insert(resource as usize);
|
||||
}
|
||||
|
||||
/// The title released a resource.
|
||||
pub(crate) fn forget(resource: usize) {
|
||||
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(map) = map.as_mut() {
|
||||
map.remove(&resource);
|
||||
}
|
||||
let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(set) = set.as_mut() {
|
||||
set.remove(&resource);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `resource`'s host copy takes its contents from title memory:
|
||||
/// a texture the host GPU does not render to or write.
|
||||
pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
|
||||
const TARGET_DEPTH_UNORDERED: i32 = 0x7;
|
||||
// SAFETY: a live resource.
|
||||
unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0
|
||||
}
|
||||
|
||||
/// Records, once per list, the copy of `resource`'s staging buffer into
|
||||
/// its host copy, and the detiling that refreshes the staging buffer at
|
||||
/// submission if the memory changed. Leaves the texture in the copy
|
||||
/// destination state.
|
||||
pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
|
||||
let host_written = HOST_WRITTEN
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.as_ref()
|
||||
.is_some_and(|set| set.contains(&(resource as usize)));
|
||||
// shortcut: a texture the host copied into keeps the host's contents
|
||||
// even if the title later writes its memory too.
|
||||
if host_written || !list.first_use(resource as usize) {
|
||||
return;
|
||||
}
|
||||
let Some(staging) = staging(resource, texture) else {
|
||||
return;
|
||||
};
|
||||
const COPY_DEST: u32 = 0x400;
|
||||
crate::list::ensure_state(list, resource, COPY_DEST);
|
||||
for (i, footprint) in staging.footprints.iter().enumerate() {
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
SubresourceIndex: i as u32,
|
||||
},
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: *footprint,
|
||||
},
|
||||
};
|
||||
// SAFETY: an open list; both locations name live resources.
|
||||
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
list.defer_host(move || staging.refresh());
|
||||
}
|
||||
|
||||
impl Staging {
|
||||
/// Detiles the texture memory into the staging buffer if it changed
|
||||
/// since the last time (and is mapped at all).
|
||||
fn refresh(&self) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let started = std::time::Instant::now();
|
||||
let read = self.refresh_now();
|
||||
let preparing = &crate::host::PREPARING;
|
||||
preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
|
||||
preparing[3].fetch_add(read as u64, Relaxed);
|
||||
}
|
||||
|
||||
/// Returns the bytes of title memory read.
|
||||
fn refresh_now(&self) -> usize {
|
||||
let size = self.layout.size as usize;
|
||||
let start = self.memory as usize;
|
||||
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let last = &mut *last;
|
||||
if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
|
||||
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
|
||||
return 0;
|
||||
}
|
||||
last.asked = now;
|
||||
// Read through the copy, which stands unmapped pages: memory of
|
||||
// big pools is too slow to ask page by page.
|
||||
last.read.resize(size, 0);
|
||||
crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
|
||||
self.detile(&last.read);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
|
||||
return size;
|
||||
}
|
||||
if !committed(self.memory, size) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tracing::debug!(
|
||||
memory = ?self.memory,
|
||||
size,
|
||||
desc = ?self.layout.desc,
|
||||
"a sampled texture's memory is not committed"
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
// SAFETY: committed memory of the texture's layout size.
|
||||
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
|
||||
let hash = blake3::hash(tiled);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
|
||||
if last.hash == Some(hash) {
|
||||
return size;
|
||||
}
|
||||
last.hash = Some(hash);
|
||||
self.detile(tiled);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
|
||||
size
|
||||
}
|
||||
|
||||
/// Detiles `tiled` (the texture's memory) into the staging buffer.
|
||||
fn detile(&self, tiled: &[u8]) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if tiled.iter().all(|&b| b == 0) {
|
||||
tracing::debug!(
|
||||
memory = ?self.memory,
|
||||
desc = ?self.layout.desc,
|
||||
"a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
|
||||
);
|
||||
}
|
||||
for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() {
|
||||
let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips);
|
||||
let f = footprint.Footprint;
|
||||
let pitch = f.RowPitch as usize;
|
||||
let len = pitch * rows as usize * f.Depth as usize;
|
||||
// SAFETY: the subresource's part of the mapped staging buffer.
|
||||
let linear = unsafe {
|
||||
std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
|
||||
};
|
||||
if let Err(e) =
|
||||
self.layout
|
||||
.detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
|
||||
{
|
||||
tracing::warn!(?e, mip, slice, "texture not detiled");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `[at, at + len)` is committed memory (streamed textures may be
|
||||
/// unmapped until their pages arrive).
|
||||
pub(crate) fn committed(at: *const u8, len: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
let mut p = at as usize;
|
||||
let end = p + len;
|
||||
while p < end {
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
|
||||
if n == 0 || info.State != MEM_COMMIT {
|
||||
return false;
|
||||
}
|
||||
p = info.BaseAddress as usize + info.RegionSize;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The staging state of a title texture, made on first use.
|
||||
fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
||||
let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = map.get_or_insert_with(HashMap::new);
|
||||
if let Some(s) = map.get(&(resource as usize)) {
|
||||
return Some(s.clone());
|
||||
}
|
||||
let (memory, desc) = crate::resource::texture_memory(resource)?;
|
||||
let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone())
|
||||
else {
|
||||
once!(
|
||||
?desc,
|
||||
"texture contents without a console layout not uploaded"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
if layout.desc.swizzle.xor() {
|
||||
once!(?desc, "texture contents in an XOR mode not uploaded");
|
||||
return None;
|
||||
}
|
||||
let host = host()?;
|
||||
// SAFETY: a live resource.
|
||||
let d = unsafe { texture.GetDesc() };
|
||||
let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
|
||||
u32::from(d.MipLevels)
|
||||
} else {
|
||||
u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize)
|
||||
};
|
||||
let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
|
||||
let mut rows = vec![0u32; count as usize];
|
||||
let mut total = 0;
|
||||
// SAFETY: outputs for `count` subresources.
|
||||
unsafe {
|
||||
host.device.GetCopyableFootprints(
|
||||
&d,
|
||||
0,
|
||||
count,
|
||||
0,
|
||||
Some(footprints.as_mut_ptr()),
|
||||
Some(rows.as_mut_ptr()),
|
||||
None,
|
||||
Some(&mut total),
|
||||
);
|
||||
}
|
||||
let (buffer, data) = host.upload_buffer(total)?;
|
||||
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
|
||||
let s = Arc::new(Staging {
|
||||
buffer,
|
||||
data,
|
||||
footprints,
|
||||
rows,
|
||||
layout,
|
||||
mips: u32::from(d.MipLevels),
|
||||
memory,
|
||||
last: Mutex::default(),
|
||||
});
|
||||
map.insert(resource as usize, s.clone());
|
||||
Some(s)
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
//! Which title memory the title wrote since a host copy took it (decision
|
||||
//! 0007, "Copies of title memory"). The runtime reserves title GPU memory
|
||||
//! with write watching (`victory-hle` xmem), so the kernel keeps a dirty bit
|
||||
//! per 4 KiB page; asking for a range's written pages also clears them. Host
|
||||
//! copies of the same memory can overlap (nested buffers, textures in
|
||||
//! buffers), so what one asks is kept here for the others: a journal of
|
||||
//! each page's last write, numbered by the asking.
|
||||
//!
|
||||
//! Physical-page views (xmem's sections) cannot be write-watched. There a
|
||||
//! copy leaves each 64 KiB block it took read-only, and our vectored handler
|
||||
//! takes the first write to it: it notes the block as written and gives the
|
||||
//! write access back. The runtime tells us when it maps or unmaps views
|
||||
//! ([`title_memory_remapped`]), which resets their protection.
|
||||
//!
|
||||
//! shortcut: writes into physical pages through another view (xmem's
|
||||
//! `write_physical`, DirectStorage's page destinations) are not seen at
|
||||
//! the guarded addresses; they go to the texture pool, whose textures are
|
||||
//! hashed, not guarded. A system call writing into a guarded block fails
|
||||
//! (none is known to).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// The unit tracked and copied: 64 KiB, the console's page (the kernel's
|
||||
/// 4 KiB pages fold into it). Finer units made the checks of the world's
|
||||
/// big buffers cost more than the copies they saved.
|
||||
pub(crate) const PAGE: usize = 64 << 10;
|
||||
/// The kernel's page, the unit of its answers.
|
||||
const KERNEL_PAGE: usize = 4096;
|
||||
|
||||
struct Journal {
|
||||
/// Numbers the askings; 0 is "never".
|
||||
asked: u64,
|
||||
/// Page number → the asking that last found it written.
|
||||
written: BTreeMap<usize, u64>,
|
||||
/// Room for the kernel's answer.
|
||||
found: Vec<usize>,
|
||||
}
|
||||
|
||||
static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
|
||||
asked: 0,
|
||||
written: BTreeMap::new(),
|
||||
found: Vec::new(),
|
||||
});
|
||||
|
||||
/// The pages of `[start, end)` (whole pages) as last written, for pages
|
||||
/// written since tracking began: `(page number, asking)` in page order, and
|
||||
/// this asking's number, which is higher than any in the list but those the
|
||||
/// kernel just reported. `None` if the memory is not write-watched (nor,
|
||||
/// with `guarded`, view memory, which is then guarded).
|
||||
pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
|
||||
use windows_sys::Win32::System::Memory::GetWriteWatch;
|
||||
const WRITE_WATCH_FLAG_RESET: u32 = 1;
|
||||
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
|
||||
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let j = &mut *j;
|
||||
let mut count = (last - first) * PAGE / KERNEL_PAGE;
|
||||
j.found.resize(count.max(j.found.len()), 0);
|
||||
let mut granularity = 0;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let started = std::time::Instant::now();
|
||||
// SAFETY: the answer buffer holds `count` entries.
|
||||
let failed = unsafe {
|
||||
GetWriteWatch(
|
||||
WRITE_WATCH_FLAG_RESET,
|
||||
(first * PAGE) as *const _,
|
||||
(last - first) * PAGE,
|
||||
j.found.as_mut_ptr().cast(),
|
||||
&mut count,
|
||||
&mut granularity,
|
||||
)
|
||||
} != 0;
|
||||
let guarded = if failed {
|
||||
count = 0;
|
||||
if !guarded {
|
||||
return None;
|
||||
}
|
||||
guard(first * PAGE, last * PAGE)?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
use crate::copystat::{C, add};
|
||||
add(C::Watches, 1);
|
||||
add(C::WatchUs, started.elapsed().as_micros() as u64);
|
||||
}
|
||||
j.asked += 1;
|
||||
let now = j.asked;
|
||||
let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
|
||||
for page in pages.collect::<Vec<_>>() {
|
||||
j.written.insert(page, now);
|
||||
}
|
||||
Some((
|
||||
now,
|
||||
j.written
|
||||
.range(first..last)
|
||||
.map(|(&p, &w)| (p, w))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Guarded blocks of view memory.
|
||||
const BLOCK: usize = PAGE;
|
||||
|
||||
struct Guards {
|
||||
/// Blocks we made read-only.
|
||||
protected: BTreeSet<usize>,
|
||||
/// Of those, the ones not written since a copy took them.
|
||||
clean: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
|
||||
protected: BTreeSet::new(),
|
||||
clean: BTreeSet::new(),
|
||||
});
|
||||
|
||||
fn guards() -> std::sync::MutexGuard<'static, Guards> {
|
||||
GUARDS.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// For view memory: the pages of `[start, end)`'s blocks written since
|
||||
/// they were last guarded (all of a block's pages), guarding them again
|
||||
/// before the caller copies them. `None` if the memory is not a view.
|
||||
fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
|
||||
use windows_sys::Win32::System::Memory::{MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) };
|
||||
if n == 0 || info.Type != MEM_MAPPED {
|
||||
return None;
|
||||
}
|
||||
install();
|
||||
let mut g = guards();
|
||||
let mut written = Vec::new();
|
||||
let mut run: Option<usize> = None;
|
||||
let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
|
||||
for block in first..=last {
|
||||
let open = block < last && !g.clean.contains(&block);
|
||||
if open {
|
||||
written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE);
|
||||
if g.protected.contains(&block) {
|
||||
// Written through the runtime, still read-only.
|
||||
g.clean.insert(block);
|
||||
} else {
|
||||
run.get_or_insert(block);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(from) = run.take() {
|
||||
protect(&mut g, from, block);
|
||||
}
|
||||
}
|
||||
Some(written)
|
||||
}
|
||||
|
||||
/// Makes blocks `[from, to)` read-only and notes them guarded and clean;
|
||||
/// block by block if they span views, leaving out any that fail (unmapped).
|
||||
fn protect(g: &mut Guards, from: usize, to: usize) {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
|
||||
let set = |from: usize, to: usize| {
|
||||
let mut old = 0;
|
||||
// SAFETY: title view memory; only its protection changes.
|
||||
unsafe {
|
||||
VirtualProtect(
|
||||
(from * BLOCK) as *const _,
|
||||
(to - from) * BLOCK,
|
||||
PAGE_READONLY,
|
||||
&mut old,
|
||||
) != 0
|
||||
}
|
||||
};
|
||||
let note = |g: &mut Guards, from: usize, to: usize| {
|
||||
g.protected.extend(from..to);
|
||||
g.clean.extend(from..to);
|
||||
};
|
||||
if set(from, to) {
|
||||
note(g, from, to);
|
||||
return;
|
||||
}
|
||||
for block in from..to {
|
||||
if set(block, block + 1) {
|
||||
note(g, block, block + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives write access back to the guarded blocks of `[start, end)` and
|
||||
/// notes them written; true if any was guarded.
|
||||
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
.range(start / BLOCK..end.div_ceil(BLOCK))
|
||||
.copied()
|
||||
.collect();
|
||||
for &block in &blocks {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
let mut old = 0;
|
||||
// SAFETY: a block we made read-only.
|
||||
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
|
||||
}
|
||||
!blocks.is_empty()
|
||||
}
|
||||
|
||||
/// Before our own write into title memory `[at, at + len)` through the
|
||||
/// kernel (which does not fault into our handler): opens its guarded blocks.
|
||||
/// The runtime calls it (as `kernel_will_write`) before the title's kernel
|
||||
/// reads into its own memory.
|
||||
pub fn writing(at: usize, len: usize) {
|
||||
open(&mut guards(), at, at + len);
|
||||
}
|
||||
|
||||
/// The runtime mapped or unmapped title memory `[at, at + len)`: what it
|
||||
/// shows is new and read-write, so it is no longer guarded.
|
||||
pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
let mut g = guards();
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
.range(at / BLOCK..(at + len).div_ceil(BLOCK))
|
||||
.copied()
|
||||
.collect();
|
||||
for block in blocks {
|
||||
g.protected.remove(&block);
|
||||
g.clean.remove(&block);
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the handler that takes writes to guarded blocks, once, ahead
|
||||
/// of the crash reporter's.
|
||||
fn install() {
|
||||
use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::{
|
||||
AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
|
||||
EXCEPTION_POINTERS,
|
||||
};
|
||||
unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
|
||||
// SAFETY: the system passes the exception being dispatched.
|
||||
let r = unsafe { &*(*info).ExceptionRecord };
|
||||
const WRITE: usize = 1;
|
||||
if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|
||||
|| r.NumberParameters < 2
|
||||
|| r.ExceptionInformation[0] != WRITE
|
||||
{
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
let at = r.ExceptionInformation[1];
|
||||
if open(&mut guards(), at, at + 1) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::GuardFaults, 1);
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
// Another thread may have opened the block since this one faulted.
|
||||
if writable(at) {
|
||||
EXCEPTION_CONTINUE_EXECUTION
|
||||
} else {
|
||||
EXCEPTION_CONTINUE_SEARCH
|
||||
}
|
||||
}
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
// SAFETY: the handler only touches our guard state and protections.
|
||||
ONCE.call_once(|| unsafe {
|
||||
AddVectoredExceptionHandler(1, Some(on_write));
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether `at` is committed read-write memory now.
|
||||
fn writable(at: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery,
|
||||
};
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
|
||||
n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
|
||||
};
|
||||
const MEM_WRITE_WATCH: u32 = 0x20_0000;
|
||||
|
||||
#[test]
|
||||
fn written_pages_are_reported_to_every_asker() {
|
||||
// SAFETY: a fresh write-watched allocation, freed at the end.
|
||||
let p = unsafe {
|
||||
VirtualAlloc(
|
||||
std::ptr::null(),
|
||||
4 * PAGE,
|
||||
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
|
||||
PAGE_READWRITE,
|
||||
)
|
||||
} as usize;
|
||||
assert_ne!(p, 0);
|
||||
let (start, end) = (p, p + 4 * PAGE);
|
||||
let (_, before) = writes(start, end, false).expect("watched");
|
||||
assert!(before.is_empty());
|
||||
// SAFETY: committed pages of ours.
|
||||
unsafe { ((p + PAGE + 8) as *mut u8).write(1) };
|
||||
let (now, after) = writes(start, end, false).expect("watched");
|
||||
assert_eq!(after, [(p / PAGE + 1, now)]);
|
||||
// Another asker after the kernel's bit was cleared still sees it.
|
||||
let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched");
|
||||
assert!(later > now);
|
||||
assert_eq!(again, [(p / PAGE + 1, now)]);
|
||||
let mut plain = vec![0u8; PAGE];
|
||||
assert!(
|
||||
writes(
|
||||
plain.as_mut_ptr() as usize,
|
||||
plain.as_ptr() as usize + PAGE,
|
||||
true
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
// SAFETY: our allocation.
|
||||
unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
/// A kernel read into a guarded view block fails; opened first, it
|
||||
/// lands and the block counts as written.
|
||||
#[test]
|
||||
fn kernel_reads_into_guarded_blocks_after_opening() {
|
||||
use std::io::{Read, Seek, Write};
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
|
||||
};
|
||||
// SAFETY: a pagefile section of two blocks, mapped read-write.
|
||||
let view = unsafe {
|
||||
let section = CreateFileMappingW(
|
||||
-1isize as _,
|
||||
std::ptr::null(),
|
||||
PAGE_READWRITE,
|
||||
0,
|
||||
(2 * BLOCK) as u32,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!section.is_null());
|
||||
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
|
||||
};
|
||||
assert_ne!(view, 0);
|
||||
assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
file.write_all(b"from the disk").unwrap();
|
||||
// `ReadFile` inside: the kernel writes the view.
|
||||
let read = |file: &mut std::fs::File| {
|
||||
file.rewind().unwrap();
|
||||
// SAFETY: 13 bytes of our view, nothing else refers to them.
|
||||
let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
|
||||
file.read(into).is_ok_and(|n| n == 13)
|
||||
};
|
||||
assert!(!read(&mut file), "the kernel does not fault into our handler");
|
||||
writing(view + 100, 13);
|
||||
assert!(read(&mut file));
|
||||
// SAFETY: the bytes just read.
|
||||
assert_eq!(unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }, b"from the disk");
|
||||
assert_eq!(guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()));
|
||||
// SAFETY: our view.
|
||||
unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
|
||||
title_memory_remapped(view, 2 * BLOCK);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user