Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ What each part does today and what it still needs:
| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title |
| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds |
| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves |
| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | Merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves |
| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes |
| Series S mode | Runs through the menus to the loading screen | The world, as above |

Expand Down
2 changes: 1 addition & 1 deletion crates/victory-gpu/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ diagnostics = []
workspace = true

[target.'cfg(windows)'.dependencies]
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-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "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_Direct3D_Dxc",
Expand Down
195 changes: 195 additions & 0 deletions crates/victory-gpu/src/address_map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
//! The address map translated shaders read title memory through when they
//! compute its address (a pointer they load, the BVH a ray-tracing pass
//! walks): see `victory_shader::emit::address_map` for its layout. It
//! lists the host copies of title memory made so far ([`crate::shadow`]),
//! each through raw views in dynamic slots of the view heap a list binds.
//!
//! shortcut: every copy is brought up to date (the pages the title wrote
//! since) once per list that binds the map, and what shaders write through
//! it stays in the copies (it is not copied back to title memory: the BVH
//! the title builds on the GPU is only read on the GPU). A list of copies
//! that grows into the thousands makes that refresh the cost to watch.

use std::sync::Arc;

use victory_shader::emit::address_map::{ENTRY, HEADER, Range, encode};

use crate::descriptor::host::HostHeap;
use crate::host::HostList;
use crate::shadow::Shadow;

/// The most bytes one raw view holds: D3D12 buffer views have at most 2^27
/// elements.
const VIEW_BYTES: u64 = 4 << 27;

/// Pieces of title memory the spans `(start, len)` cover, sorted and not
/// overlapping, each with the span that holds it: where spans overlap, the
/// one starting last (the innermost buffer, as [`crate::shadow::find`]
/// picks) holds the piece.
pub(crate) fn pieces(spans: &[(u64, u64)]) -> Vec<(u64, u64, usize)> {
// (address, whether a span starts there, span): ends before starts.
let mut points: Vec<(u64, bool, usize)> = Vec::with_capacity(2 * spans.len());
for (i, &(start, len)) in spans.iter().enumerate() {
if len > 0 {
points.push((start, true, i));
points.push((start.saturating_add(len), false, i));
}
}
points.sort_unstable();
let mut active = std::collections::BTreeSet::new();
let mut out: Vec<(u64, u64, usize)> = Vec::new();
let mut at = 0;
for (x, starts, i) in points {
if x > at
&& let Some(&(_, holder)) = active.iter().next_back()
{
match out.last_mut() {
Some(last) if last.2 == holder && last.0 + last.1 == at => last.1 += x - at,
_ => out.push((at, x - at, holder)),
}
}
if starts {
active.insert((spans[i].0, i));
} else {
active.remove(&(spans[i].0, i));
}
at = x;
}
out
}

/// The map's entries for `pieces` of the spans: each piece cut where its
/// span's views ([`VIEW_BYTES`] each) end, with the view (span, view number
/// within the span) and the piece's offset in that view.
fn entries(
spans: &[(u64, u64)],
pieces: &[(u64, u64, usize)],
) -> Vec<(u64, u32, (usize, u64), u32)> {
let mut out = Vec::new();
for &(start, len, span) in pieces {
let mut at = start;
let end = start + len;
while at < end {
let rel = at - spans[span].0;
let view = rel / VIEW_BYTES;
let view_end = spans[span].0 + (view + 1) * VIEW_BYTES;
let next = end.min(view_end);
out.push((
at,
(next - at) as u32,
(span, view),
(rel - view * VIEW_BYTES) as u32,
));
at = next;
}
}
out
}

/// The address map for draws of `list` while `heap` is its view heap: its
/// host GPU address, and the dynamic slots its views take (to give back
/// when the list is reset). Each copy is brought up to date when the list
/// is submitted.
pub(crate) fn make(list: &HostList, heap: &HostHeap) -> Option<(u64, (u32, u32))> {
let copies: Vec<Arc<Shadow>> = crate::shadow::all();
let spans: Vec<(u64, u64)> = copies.iter().map(|c| c.span()).collect();
let pieces = pieces(&spans);
let entries = entries(&spans, &pieces);
let mut views: Vec<(usize, u64)> = entries.iter().map(|e| e.2).collect();
views.sort_unstable();
views.dedup();
let n = views.len() as u32;
let first = if n == 0 { 0 } else { heap.dynamic(n)? };
for (k, &(span, view)) in views.iter().enumerate() {
let copy = &copies[span];
let offset = view * VIEW_BYTES;
let bytes = (copy.span().1 - offset).min(VIEW_BYTES).next_multiple_of(4);
heap.raw_uav_at(
first + k as u32,
&copy.buffer,
offset / 4,
(bytes / 4) as u32,
);
}
for c in &copies {
if list.first_use(Arc::as_ptr(c) as usize ^ MAP_KEY) {
let (start, len) = c.span();
c.refresh(list, start, len);
}
}
let ranges: Vec<Range> = entries
.iter()
.map(|&(start, len, view, view_offset)| Range {
start,
len,
view: first + views.binary_search(&view).expect("listed") as u32,
view_offset,
})
.collect();
let words = encode(&ranges);
// Room for one entry even when there is none: the shader reads it.
let bytes = u64::from(HEADER) + u64::from(ENTRY) * ranges.len().max(1) as u64;
let (gpu, to) = list.scratch(bytes)?;
// SAFETY: `bytes` of the list's upload memory, which outlives the
// list's run; the words fit.
unsafe {
std::ptr::write_bytes(to, 0, bytes as usize);
std::ptr::copy_nonoverlapping(words.as_ptr().cast::<u8>(), to, words.len() * 4);
}
Some((gpu, (first, n)))
}

/// Keeps the map's refreshes apart from other first uses the list asks
/// about (texture keys are addresses too).
const MAP_KEY: usize = 0x5;

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn inner_buffers_win_and_pieces_do_not_overlap() {
// A heap-sized buffer with two placed inside it, one past its end,
// and an empty one.
let spans = [
(0x1000, 0x1000),
(0x1200, 0x100),
(0x1800, 0x100),
(0x3000, 0x40),
(0x5000, 0),
];
assert_eq!(
pieces(&spans),
[
(0x1000, 0x200, 0),
(0x1200, 0x100, 1),
(0x1300, 0x500, 0),
(0x1800, 0x100, 2),
(0x1900, 0x700, 0),
(0x3000, 0x40, 3),
]
);
}

#[test]
fn the_same_span_twice_is_one_piece() {
assert_eq!(
pieces(&[(0x100, 0x100), (0x100, 0x100)]),
[(0x100, 0x100, 1)]
);
}

#[test]
fn pieces_are_cut_where_views_end() {
let spans = [(0x10, 2 * VIEW_BYTES + 8)];
let e = entries(&spans, &pieces(&spans));
assert_eq!(
e,
[
(0x10, VIEW_BYTES as u32, (0, 0), 0),
(0x10 + VIEW_BYTES, VIEW_BYTES as u32, (0, 1), 0),
(0x10 + 2 * VIEW_BYTES, 8, (0, 2), 0),
]
);
}
}
120 changes: 120 additions & 0 deletions crates/victory-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,58 @@ pub(crate) struct HostHeap {
/// Where the search for free dynamic slots starts, and which are taken
/// (by lists not yet reset).
next: Mutex<(u32, Vec<bool>)>,
/// View heaps: the console words of each slot's descriptor, 8 dwords
/// per slot, for shaders that read descriptors as numbers: the buffer,
/// its mapping and its host GPU address.
words: Option<(ID3D12Resource, usize, u64)>,
}

/// A GFX10 buffer descriptor's dword 3 for raw access: X Y Z W selects, a
/// 32-bit float format, raw out-of-range checking, resource level 1. The
/// address and size in dwords 0 to 2 are what programs read.
const RAW_DWORD3: u32 = 0x3101_6FAC;

/// The console words of a descriptor for `view`, as far as programs read
/// them as numbers: a buffer descriptor's address, stride and record count
/// for buffer views, constant buffers and acceleration structures (whose
/// descriptor is a buffer at the structure); zero otherwise.
pub(crate) fn console_words(view: &View) -> [u32; 8] {
let (address, len, stride) = match view {
View::Constant(address, size) => (*address, u64::from(*size), 0),
// An acceleration structure (dimension 11) names no resource: its
// location is the union's first quadword.
View::Shader(0, Some(d)) if d[1] == 11 => (
u64::from(d[4]) | u64::from(d[5]) << 32,
u64::from(u32::MAX),
0,
),
v => match buffer_range(v) {
Some((address, len)) => {
let stride = match v {
View::Shader(_, Some(d)) | View::Unordered(_, _, Some(d)) => d[7],
View::Placed(_, _, d) => d[7],
_ => 0,
};
(address, len, stride)
}
None => return [0; 8],
},
};
let records = if stride > 0 {
len / u64::from(stride)
} else {
len
};
[
address as u32,
(address >> 32) as u32 & 0xFFFF | (stride & 0x3FFF) << 16,
records.min(u64::from(u32::MAX)) as u32,
RAW_DWORD3,
0,
0,
0,
0,
]
}

/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
Expand Down Expand Up @@ -144,6 +196,20 @@ impl HostHeap {
u64::from(step),
sampler,
));
let words = if sampler {
None
} else {
let bytes = u64::from(count + extra) * 32;
host.shared_buffer(bytes).map(|(buffer, data)| {
crate::host::name(&buffer, || format!("descriptor words {count}+{extra}"));
// SAFETY: a fresh mapping of `bytes`; a live buffer.
unsafe {
std::ptr::write_bytes(data, 0, bytes as usize);
let gpu = buffer.GetGPUVirtualAddress();
(buffer, data as usize, gpu)
}
})
};
let h = HostHeap {
heap,
cpu,
Expand All @@ -154,6 +220,7 @@ impl HostHeap {
made: Mutex::new(vec![0; count as usize]),
kept: Mutex::new(vec![None; (count + extra) as usize]),
next: Mutex::new((0, vec![false; extra as usize])),
words,
};
// 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
Expand Down Expand Up @@ -302,6 +369,7 @@ impl HostHeap {
null_for(view, self.cpu(index));
}
self.keep(index, kept.flatten());
self.write_words(index, console_words(view));
}

/// Makes slot `index` read nothing: a null view, or a plain sampler.
Expand All @@ -312,6 +380,55 @@ impl HostHeap {
null_view(self.cpu(index));
}
self.keep(index, None);
self.write_words(index, [0; 8]);
}

/// The host GPU address of the heap's descriptor words (view heaps).
pub(crate) fn words(&self) -> Option<u64> {
self.words.as_ref().map(|w| w.2)
}

fn write_words(&self, index: u32, words: [u32; 8]) {
let Some((_, data, _)) = self.words else {
return;
};
if index >= self.count + self.dynamic {
return;
}
// SAFETY: slot `index` of the mapping, 32 bytes each.
unsafe {
std::ptr::copy_nonoverlapping(
words.as_ptr(),
(data as *mut u32).add(index as usize * 8),
8,
);
}
}

/// Makes slot `index` (a dynamic one) a raw unordered access view of
/// `n` dwords of `buffer` from dword `first` on, holding the buffer
/// while the slot does.
pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, first: u64, n: u32) {
let Some(host) = host() else { return };
let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_TYPELESS,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
FirstElement: first,
NumElements: n,
Flags: D3D12_BUFFER_UAV_FLAG_RAW,
..Default::default()
},
},
};
// SAFETY: a slot of our heap and a live buffer.
unsafe {
host.device
.CreateUnorderedAccessView(buffer, None, Some(&desc), self.cpu(index))
};
self.keep(index, Some(buffer.clone()));
self.write_words(index, [0; 8]);
}

/// Slot `index` now views `resource` (or nothing of the host's).
Expand Down Expand Up @@ -361,6 +478,7 @@ impl HostHeap {
/// memory (the list's own, which it holds).
pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
self.keep(index, None);
self.write_words(index, [0; 8]);
let Some(host) = host() else { return };
let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
BufferLocation: gpu,
Expand Down Expand Up @@ -413,6 +531,8 @@ impl HostHeap {
}
return None;
};
// Even buffer views made only for draws have their words now.
self.write_words(index, console_words(&view));
if made[index as usize] != key {
let later = !for_draw && view.is_buffer();
made[index as usize] = if later { 0 } else { key };
Expand Down
Loading
Loading