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:
MarvisandClaude Fable 5.2 committed 2026-11-23 23:10:01 +01:00
1 parent bc3070991a
commit 2849477415
107 files changed
+42526 -868

No files matched your search

+363
View File
@@ -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
}