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
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user