diff --git a/.gitignore b/.gitignore index a5755d01e..df8474153 100644 --- a/.gitignore +++ b/.gitignore @@ -79,3 +79,8 @@ Thumbs.db # A TypeScript sample shipped with the systematic-debugging skill; .ts is not on the policy allowlist. /.claude/skills/systematic-debugging/condition-based-waiting-example.ts + +disasm.txt +disasm-adaptive.txt +translate-results.txt +shader-dumps/ \ No newline at end of file diff --git a/TODO.md b/TODO.md index 17ad16274..1cb51d247 100644 --- a/TODO.md +++ b/TODO.md @@ -73,7 +73,6 @@ The goal: a console-like experience on PC. The game starts straight into play, h | ID | Task | Where | Needs | |----|------|-------|-------| -| C-1 | CI is red on clippy: `resource.rs:2553` (`placed_filler_twins` unused), `indirect.rs:2453` (`depth_written` never read), `fpsbox.rs:174` (`contains_key` then `insert`), `draw.rs:2577` (`sort_unstable_by_key`), `queue.rs:672`, `shadow.rs:2803` and `shadow.rs:3325` (`is_multiple_of`). All in `leonida-gpu`, all inherited from victory-gta6. | `leonida-gpu` | - | | C-2 | Failing test `indirect::tests::warp_budget_saturates_without_wraparound_and_preserves_draw_fields`, inherited from victory-gta6. Upstream VIctory `4ab20fc` ("the indirect budget is charged in record order and no longer wraps") may fix it; not checked. | `leonida-gpu` | - | | C-3 | `cargo fmt --check` reports about 1,420 differences. Run `cargo fmt` once, in a pull request of its own, at a moment when no other pull request is open (it touches almost every file), then add the check to CI. | all | - | | C-4 | 163 `shortcut:` markers where the code approximates the console (79 in `leonida-gpu`, 55 in `leonida-shader`, 23 in `leonida-hle`, 4 in `leonida-formats`, 2 in `leonida-loader`). Replace them with the console's real behaviour, one per pull request. | all | game | diff --git a/crates/leonida-gpu/src/descriptor/host.rs b/crates/leonida-gpu/src/descriptor/host.rs index 92d4e9441..9b7972d95 100644 --- a/crates/leonida-gpu/src/descriptor/host.rs +++ b/crates/leonida-gpu/src/descriptor/host.rs @@ -58,6 +58,11 @@ pub(crate) struct HostHeap { /// (`leonida_shader::emit::SLOT_STRIDES`): an upload buffer of /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. strides: Option<(ID3D12Resource, u64, usize)>, + /// View heaps: the title address of the view at each slot, for shaders + /// that take a heap-picked descriptor's address as a pointer + /// (`leonida_shader::emit::SLOT_VIEW_ADDRS`): an upload buffer of + /// 2 * `SLOT_VIEW_ADDRS_COUNT` dwords, its GPU address and its mapping. + view_addrs: Option<(ID3D12Resource, u64, usize)>, /// Title slots holding buffer views. Such a view gets its host slot /// (and its memory a host copy) only when something reads it: a draw /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick @@ -943,6 +948,19 @@ impl HostHeap { Some((buffer, gpu, data as usize)) }) .flatten(); + let view_addrs = (!sampler) + .then(|| { + let bytes = u64::from(leonida_shader::emit::SLOT_VIEW_ADDRS_COUNT) * 8; + let (buffer, data) = host.upload_buffer(bytes)?; + // SAFETY: the buffer's whole mapping; a live buffer. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress() + }; + crate::host::name(&buffer, || "view addresses by view heap slot".to_owned()); + Some((buffer, gpu, data as usize)) + }) + .flatten(); let h = HostHeap { heap, cpu, @@ -957,6 +975,7 @@ impl HostHeap { free: std::sync::atomic::AtomicU32::new(DYNAMIC), too_long: std::sync::atomic::AtomicU32::new(u32::MAX), strides, + view_addrs, buffers: Mutex::default(), changed: Mutex::default(), textures: Mutex::default(), @@ -1119,6 +1138,16 @@ impl HostHeap { self.strides.as_ref().map(|s| &s.0) } + /// The GPU address table of title view addresses by view heap slot. + pub(crate) fn view_addrs_gpu(&self) -> Option { + self.view_addrs.as_ref().map(|s| s.1) + } + + /// The table's buffer, for a list to hold. + pub(crate) fn view_addrs_buffer(&self) -> Option<&ID3D12Resource> { + self.view_addrs.as_ref().map(|s| &s.0) + } + /// Up to `max` title slots whose texture view is due at `frame`, each /// with its write number, in the order to serve them /// ([`TextureQueue::due`]), and the queue's counts @@ -1603,6 +1632,21 @@ impl HostHeap { // dword, either value is one the slot had). unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; } + if let Some((_, _, data)) = &self.view_addrs + && index < leonida_shader::emit::SLOT_VIEW_ADDRS_COUNT + { + let (lo, hi) = view + .and_then(buffer_range) + .map_or((0u32, 0u32), |(start, _)| { + (start as u32, (start >> 32) as u32) + }); + let p = *data as *mut u32; + // SAFETY: inside the mapping; shaders read it while we write. + unsafe { + p.add(index as usize * 2).write_volatile(lo); + p.add(index as usize * 2 + 1).write_volatile(hi); + } + } let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { buffers.insert(index); diff --git a/crates/leonida-gpu/src/draw.rs b/crates/leonida-gpu/src/draw.rs index ecc892098..6f1f7faf5 100644 --- a/crates/leonida-gpu/src/draw.rs +++ b/crates/leonida-gpu/src/draw.rs @@ -1225,7 +1225,7 @@ impl State { if srv && slot == leonida_shader::emit::SLOT_STRIDES { // Ours, not the title's: the shader picks buffers // from the view heap by an index it computes. - match self.heap_buffers(list) { + match self.heap_buffers(list, false) { // SAFETY: an open list; the table lives as long // as the heap the list holds. Some(gpu) => unsafe { @@ -1239,6 +1239,24 @@ impl State { } continue; } + if srv && slot == leonida_shader::emit::SLOT_VIEW_ADDRS { + // Ours: the title address of each view in the heap. + match self.heap_buffers(list, true) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!( + "a shader reads view addresses from a view heap that is not set" + ), + } + continue; + } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) else { @@ -1518,17 +1536,17 @@ impl State { } /// For a shader that picks buffers from the view heap by an index it - /// computes (SM 6.6 dynamic resources): the GPU address of the heap's - /// table of element strides, with every buffer view of the heap given - /// its host slot and its memory brought up to date when `list` is - /// submitted. Tables tell us which views a draw reads; nothing tells - /// us which of the heap's a computed index names, so all of them are - /// made ready, once per list. + /// computes (SM 6.6 dynamic resources): the GPU address of the stride or + /// title-address table selected by `view_addrs`. Every buffer view of + /// the heap gets its host slot and its memory is brought up to date when + /// `list` is submitted. Tables tell us which views a draw reads; nothing + /// tells us which of the heap's a computed index names, so all are made + /// ready, once per list. /// shortcut: the buffers are read, not written: what such a shader /// writes through a picked unordered access view stays in the host /// copy. A list refreshes them where it first runs such a shader; /// title writes recorded later in the same list are not seen. - fn heap_buffers(&self, list: &HostList) -> Option { + fn heap_buffers(&self, list: &HostList, view_addrs: bool) -> Option { let heap = self .heaps .iter() @@ -1536,7 +1554,11 @@ impl State { .map(|&h| crate::descriptor::heap(h as This)) .find(|h| !h.samplers())?; let host = heap.host()?; - let gpu = host.strides_gpu()?; + let gpu = if view_addrs { + host.view_addrs_gpu()? + } else { + host.strides_gpu()? + }; // One key per list, as textures have: no title resource is there. const ONCE: usize = usize::MAX - 0x5e; if !list.first_use(ONCE) { @@ -1546,6 +1568,9 @@ impl State { if let Some(buffer) = host.strides_buffer() { list.keep(buffer); } + if let Some(buffer) = host.view_addrs_buffer() { + list.keep(buffer); + } // The pass itself once per frame: per list it ran up to 51 times a // frame over 81,000 views and 4,100 host copies, 18 s of every // frame (2026-11-24, run 11). @@ -2574,7 +2599,7 @@ impl State { let draws: u32 = census.1.values().sum(); if draws > 0 { let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); - rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); let scissors: Vec = rects .iter() .take(5) @@ -3321,7 +3346,7 @@ impl State { // the record drawn before it. if (6..=8).contains(&why_not) { static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 256 == 0 { + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) .is_multiple_of(256) { let (last_copy, last_offset) = self.last_indirect; tracing::info!( "a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \ diff --git a/crates/leonida-gpu/src/fpsbox.rs b/crates/leonida-gpu/src/fpsbox.rs index cc2e00b47..4298055bf 100644 --- a/crates/leonida-gpu/src/fpsbox.rs +++ b/crates/leonida-gpu/src/fpsbox.rs @@ -171,7 +171,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b made.clear(); } let key = (tenths, format.0, scale); - if !made.contains_key(&key) { + if let std::collections::hash_map::Entry::Vacant(e) = made.entry(key) { let (w, h, lit) = bitmap(&text(tenths), scale); let pitch = (w as usize * bytes).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize); let Some((buffer, data)) = host.shared_buffer((pitch * h as usize) as u64) else { @@ -185,7 +185,7 @@ pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, b pixel(format, lit[y * w as usize + x], &mut out[at..at + bytes]); } } - made.insert(key, Made { buffer, width: w, height: h, pitch: pitch as u32 }); + e.insert(Made { buffer, width: w, height: h, pitch: pitch as u32 }); } let Some(m) = made.get(&key) else { return; diff --git a/crates/leonida-gpu/src/indirect.rs b/crates/leonida-gpu/src/indirect.rs index a3235334a..20b14f63c 100644 --- a/crates/leonida-gpu/src/indirect.rs +++ b/crates/leonida-gpu/src/indirect.rs @@ -2450,6 +2450,7 @@ void work() { heap_pairs: [[Option; 2]; 2], tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + #[allow(dead_code)] // TODO C-2: pending upstream VIctory 4ab20fc depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, stamps: ID3D12QueryHeap, diff --git a/crates/leonida-gpu/src/pipeline/host.rs b/crates/leonida-gpu/src/pipeline/host.rs index e2e8543b6..41fb71cdb 100644 --- a/crates/leonida-gpu/src/pipeline/host.rs +++ b/crates/leonida-gpu/src/pipeline/host.rs @@ -435,6 +435,7 @@ impl HostPipeline { slot == leonida_shader::emit::SLOT_FAULTS } else { slot == leonida_shader::emit::SLOT_STRIDES + || slot == leonida_shader::emit::SLOT_VIEW_ADDRS || slot == leonida_shader::emit::SLOT_MEMORY }; if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { diff --git a/crates/leonida-gpu/src/queue.rs b/crates/leonida-gpu/src/queue.rs index 86411ed00..fd19efb76 100644 --- a/crates/leonida-gpu/src/queue.rs +++ b/crates/leonida-gpu/src/queue.rs @@ -687,7 +687,7 @@ fn send_joined(joined: &mut Joined) { let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1; JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed); JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed); - if sent % 2048 == 0 { + if sent.is_multiple_of(2048) { let n: Vec = JOINED.iter().map(|n| n.swap(0, Ordering::Relaxed)).collect(); tracing::info!( "parts joined (LEONIDA_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet", diff --git a/crates/leonida-gpu/src/resource.rs b/crates/leonida-gpu/src/resource.rs index bebace985..7c04ed3d0 100644 --- a/crates/leonida-gpu/src/resource.rs +++ b/crates/leonida-gpu/src/resource.rs @@ -2553,10 +2553,12 @@ static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64 /// See [`PLACED_TWINS`]. #[cfg(windows)] +#[allow(dead_code)] // read by the copystat memory log (diagnostics builds) pub(crate) fn placed_filler_twins() -> u64 { PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) } + /// Width, height and format of texture `this` (`None` for a buffer), for /// `crate::texback`'s kinds. #[cfg(windows)] diff --git a/crates/leonida-gpu/src/shadow.rs b/crates/leonida-gpu/src/shadow.rs index 05e8ff837..d22904001 100644 --- a/crates/leonida-gpu/src/shadow.rs +++ b/crates/leonida-gpu/src/shadow.rs @@ -2935,7 +2935,7 @@ impl Shadow { } OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; - if n % 16384 == 0 { + if n.is_multiple_of(16384) { tracing::info!( "what shaders wrote, stored through views of our own (LEONIDA_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with LEONIDA_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean", OWN_WRITES[1].load(Ordering::Relaxed) >> 20, @@ -3457,7 +3457,7 @@ impl Shadow { COPY_CHANGED[1].fetch_add(sent as u64, Ordering::Relaxed); COPY_CHANGED[2].fetch_add(stretches.len() as u64, Ordering::Relaxed); let calls = COPY_CHANGED[3].fetch_add(1, Ordering::Relaxed) + 1; - if calls % 65536 == 0 { + if calls.is_multiple_of(65536) { tracing::info!( "copies in the card's memory, refreshed by what differs (LEONIDA_COPY_CHANGED=1), since the start: {calls} refreshes read {} MB of title memory the title had written to; {} MB of it differed from the copy and went on to the card, in {} stretches", COPY_CHANGED[0].load(Ordering::Relaxed) >> 20, diff --git a/crates/leonida-gpu/src/watch.rs b/crates/leonida-gpu/src/watch.rs index 79c449597..d4f4e4216 100644 --- a/crates/leonida-gpu/src/watch.rs +++ b/crates/leonida-gpu/src/watch.rs @@ -478,7 +478,7 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve fn failed_asking(start: usize, end: usize) { use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 2048 != 0 { + if !N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(2048) { return; } // SAFETY: plain data filled in by the query. @@ -869,7 +869,7 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) { #[cfg(feature = "diagnostics")] { static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 1024 == 0 { + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) .is_multiple_of(1024) { tracing::info!("a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", block * BLOCK); } } diff --git a/crates/leonida-shader/src/emit/lower.rs b/crates/leonida-shader/src/emit/lower.rs index 37d386a53..b7063ba2c 100644 --- a/crates/leonida-shader/src/emit/lower.rs +++ b/crates/leonida-shader/src/emit/lower.rs @@ -2743,9 +2743,66 @@ impl<'a> Lower<'a> { /// descriptor holds more in the second dword, the stride from bit 16 /// up; code that takes the address masks those away.) fn view_address(&mut self, site: Site) -> Option<(V, V)> { - use super::shader::USER_VIEW_ADDRESS; + use super::shader::{SLOT_VIEW_ADDRS, SLOT_VIEW_ADDRS_COUNT, USER_VIEW_ADDRESS}; let a = self.scalar.get(&site).copied()?; let rp = *self.x.native.layout.get(a.param)?; + let count = match self.x.p.blocks.get(site.0)?.insts.get(site.1)?.name() + .strip_prefix("s_load_dword")? + { + "" => 1, + "x2" => 2, + "x4" => 4, + "x8" => 8, + "x16" => 16, + _ => return None, + }; + if rp.root == RootType::ResourceHeap + && let Some(dynamic) = a.dynamic + && count <= 4 + { + let c = self.cur; + let mut slot = self.i32_of(dynamic).ok()?; + if a.offset != 0 { + let offset = self.s.m.i32(a.offset); + slot = self.s.m.bin(c, Bin::Add, slot, offset); + } + let five = self.s.m.i32(5); + slot = self.s.m.bin(c, Bin::LShr, slot, five); + let last = self.s.m.i32(SLOT_VIEW_ADDRS_COUNT - 1); + slot = self + .s + .op(c, "binary.i32", Attr::ReadNone, self.s.t.i32, 40, &[slot, last]); + self.s.m.tag(slot, Tag::Clamp); + let three = self.s.m.i32(3); + let at = self.s.m.bin(c, Bin::Shl, slot, three); + let h = self.s.root_srv_handle(SLOT_VIEW_ADDRS); + let u = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let low = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, at, u, mask, align], + ); + let raw_lo = self.s.m.extract(c, low, 0); + let lo = self.as_int(raw_lo); + let four = self.s.m.i32(4); + let hi_at = self.s.m.bin(c, Bin::Add, at, four); + let high = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, hi_at, u, mask, align], + ); + let raw_hi = self.s.m.extract(c, high, 0); + let hi = self.as_int(raw_hi); + return Some((lo, hi)); + } if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 { return None; } diff --git a/crates/leonida-shader/src/emit/mod.rs b/crates/leonida-shader/src/emit/mod.rs index af521b239..792ac99f3 100644 --- a/crates/leonida-shader/src/emit/mod.rs +++ b/crates/leonida-shader/src/emit/mod.rs @@ -114,7 +114,8 @@ pub use lower::set_host_max_wave; pub use rect::rect_list_gs; pub use shader::{ MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, - SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + SLOT_STRIDES_COUNT, SLOT_VIEW_ADDRS, SLOT_VIEW_ADDRS_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, + USER_VIEW_ADDRESS, USER_VIEW_BIAS, set_view_heap_limit, view_heap_limit, }; diff --git a/crates/leonida-shader/src/emit/shader.rs b/crates/leonida-shader/src/emit/shader.rs index e970e6dd6..f1e2ce250 100644 --- a/crates/leonida-shader/src/emit/shader.rs +++ b/crates/leonida-shader/src/emit/shader.rs @@ -27,6 +27,16 @@ pub const SLOT_STRIDES: u8 = 255; /// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it. pub const SLOT_STRIDES_COUNT: u32 = 1 << 21; +/// Like [`SLOT_STRIDES`], but 2 dwords per view-heap slot: the low and +/// high 32 bits of the title address of the view at heap slot `i` +/// (0, 0: unknown). For shaders that take the address out of a +/// heap-picked descriptor and use it as a pointer (the shadow-mask +/// ray programs walk title memory by raw address). A shader with this +/// root SRV also asks that every view of the heap be ready when it runs. +pub const SLOT_VIEW_ADDRS: u8 = 252; +/// Dwords of the [`SLOT_VIEW_ADDRS`] buffer: heap indices are clamped to it. +pub const SLOT_VIEW_ADDRS_COUNT: u32 = SLOT_STRIDES_COUNT; + /// Title memory by address (`resource::MEMORY`): console code reads and /// writes through raw 40-bit addresses it takes from root constants, /// descriptors and other memory (the ray-tracing structure builder and the