From b8949af9e23fc673986db8d9e03c0f3f4a3d1ab5 Mon Sep 17 00:00:00 2001 From: Zhelezniak Artem Date: Wed, 25 Nov 2026 23:59:21 +0300 Subject: [PATCH 1/3] GPU: sample deferred character material textures Recognize the two deferred character shader variants that read texture indices from the material record at table 0, dword 688. The packed variant reads two extra indices. Keep this under the existing opt-in material texture demand path. --- crates/victory-gpu/src/material_demand.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/victory-gpu/src/material_demand.rs b/crates/victory-gpu/src/material_demand.rs index 750f2285a5..e2f81aa0af 100644 --- a/crates/victory-gpu/src/material_demand.rs +++ b/crates/victory-gpu/src/material_demand.rs @@ -28,6 +28,10 @@ pub(crate) fn enabled() -> bool { pub(crate) fn fields(hash: &str) -> Option<&'static [u32]> { match hash { + // The deferred character shaders read heap indices from the same + // material buffer; the packed variant also samples fields 28 and 32. + "a402e650d0acbc92" => Some(&[0, 4, 8, 12, 16, 20, 24]), + "b15ba4896d650511" => Some(&[0, 4, 8, 12, 16, 20, 24, 28, 32]), "d9fcb8a4425fc59b" | "43fc2af1f70920f1" => Some(&[0, 4, 8]), "271a87c54ac648a5" => Some(&[0, 4, 12, 16]), "d2e683031b764939" => Some(&[0, 4, 8, 16]), @@ -393,6 +397,19 @@ mod tests { assert_eq!(byte_range(3, fields, 36), None); } + #[test] + fn character_material_sampling_covers_both_record_layouts() { + let words = [11, 12, 13, 14, 15, 16, 17, 0xf8000012, 19]; + let regular = fields("a402e650d0acbc92").expect("deferred character material"); + let packed = fields("b15ba4896d650511").expect("packed deferred character material"); + + assert_eq!(indices(&words, regular, 20), [11, 12, 13, 14, 15, 16, 17]); + assert_eq!(indices(&words, packed, 20), [11, 12, 13, 14, 15, 16, 17, 18, 19]); + assert_eq!(byte_range(16, regular, 44), Some((16, 28))); + assert_eq!(byte_range(16, packed, 44), None); + assert_eq!(byte_range(16, packed, 52), Some((16, 36))); + } + #[test] fn only_current_existing_due_writes_move_ahead() { let mut due: Vec<_> = (0..10u32).map(|n| (n, u64::from(n) + 1, false)).collect(); From 92fef937e9149a320628a2dbbeb725b3eb5296f9 Mon Sep 17 00:00:00 2001 From: Zhelezniak Artem Date: Thu, 26 Nov 2026 04:15:45 +0300 Subject: [PATCH 2/3] GPU: trace material texture indices read back from the host --- crates/victory-gpu/src/descriptor.rs | 57 +++++++- crates/victory-gpu/src/descriptor/host.rs | 36 ++++++ crates/victory-gpu/src/draw.rs | 20 ++- crates/victory-gpu/src/material_demand.rs | 151 ++++++++++++++++++++-- 4 files changed, 242 insertions(+), 22 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 3eb4035876..7c4702c7f4 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1206,8 +1206,22 @@ mod tests { #[cfg(windows)] #[test] fn material_demand_follows_gpu_record_and_rejects_reused_texture_memory() { + material_record_on_gpu(false); + } + + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn material_trace_reads_packed_indices_without_scheduling_uploads() { + material_record_on_gpu(true); + } + + #[cfg(windows)] + fn material_record_on_gpu(trace: bool) { use windows::Win32::Graphics::Direct3D12::*; - let Some(device) = crate::host::host() else { return }; + let Some(device) = crate::host::host() else { + assert!(!trace, "trace fixture requires a D3D12 device"); + return; + }; let null = std::ptr::null(); let mut object = null; assert_eq!(create(HeapDesc { kind: 0, count: 128, flags: 1, nodes: 0 }, Placement { address: 0, size: 0 }, &mut object), S_OK); @@ -1261,19 +1275,54 @@ mod tests { create_placed_srv(null, &shape, &srv, heap.handle(8).unwrap()); create_cbv(null, &[0x400, 6, 256, 0], heap.handle(8).unwrap()); } - let words = [0xf800_0003u32, 0, 7, 0, 5, 6]; + let mut words = [0xf800_0003u32, 0, 7, 0, 5, 6, 0, 0, 0]; + let fields = if trace { + words[4..6].fill(0); + words[7..9].copy_from_slice(&[5, 6]); + crate::material_demand::fields("b15ba4896d650511").unwrap() + } else { + &[0, 16, 20][..] + }; let bytes = std::mem::size_of_val(&words) as u64; let (upload, mapped) = device.upload_buffer(bytes).unwrap(); // SAFETY: copy the full upload allocation into the owned material range. - // CPU memory for all six words stays zero; the selected values exist only on the GPU. + // CPU memory for these words stays zero; the selected values exist only on the GPU. unsafe { std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), mapped, bytes as usize); list.list.CopyBufferRegion(&shadow.buffer, shadow.offset(address), &upload, 0, bytes); list.list.ResourceBarrier(&[crate::host::transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); } - crate::material_demand::record(&list, heap, heap.start, 0, &[0, 16, 20]); + crate::material_demand::record(&list, heap, heap.start, crate::material_demand::Request { + record: 0, + fields, + prioritize: !trace, + capture: trace.then_some(crate::material_demand::Capture { + shader: "b15ba4896d650511", + frame: frame + 1, + list: std::ptr::from_ref(&list) as usize, + }), + }); + #[cfg(feature = "diagnostics")] + let trace_stamp = host.material_write_stamp(); list.close(); device.execute(&[&list]); + #[cfg(feature = "diagnostics")] + if trace { + let fields = host.material_demand.captured_fields(); + assert_eq!(fields, [ + (0, 3), (4, 0), (8, 7), (12, 0), (16, 0), (20, 0), (24, 0), (28, 5), (32, 6), + ]); + assert_eq!(record_bytes, [0; 8]); + assert!(host.material_slot_state(heap, 5, trace_stamp, frame) + .contains("title_texture=true native_resource=false")); + create_cbv(null, &[0x400, 6, 256, 0], heap.handle(6).unwrap()); + assert_eq!(host.material_slot_state(heap, 6, trace_stamp, frame), "title descriptor rewritten"); + let due = host.texture_slots_due(frame, 128).0; + assert!(host.material_demand.take(heap, host, frame).is_empty()); + assert_eq!(host.texture_slots_due(frame, 128).0, due); + assert_eq!(release(object), 0); + return; + } let mut due: Vec<_> = (32..48).map(|n| (n,1,false)).collect(); due.push(write); let wanted = host.material_demand.take(heap, host, frame); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index d546d20136..f7ed495128 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1168,6 +1168,42 @@ impl HostHeap { } } + /// Observe a sampled descriptor at readback time. A title rewrite + /// invalidates comparison with the command that selected the slot. + #[cfg(feature = "diagnostics")] + pub(crate) fn material_slot_state( + &self, + heap: &super::Heap, + index: u32, + stamp: crate::material_demand::Mark, + frame: u64, + ) -> String { + let Some(epoch) = self.material_epochs.get().and_then(|e| e.get(index as usize)) else { + return "outside host view heap".into(); + }; + let unchanged = || epoch.load(std::sync::atomic::Ordering::Relaxed) <= stamp.descriptor; + if !unchanged() { + return "title descriptor rewritten".into(); + } + let title = heap.handle(index).and_then(super::checked_view); + let native = self + .kept + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(Option::is_some); + let host = self.describe_slot(index).unwrap_or_else(|| "unavailable".into()); + let queue = self.texture_slot_state(index, frame, title.as_ref()); + if unchanged() { + format!( + "title_texture={} native_resource={native} host=[{host}] queue=[{queue}]", + title.as_ref().is_some_and(is_texture_view), + ) + } else { + "title descriptor rewritten".into() + } + } + /// A shader-selected material field can re-enrol its current null block-compressed SRV. /// Never supersede another allocation, or upload title bytes over a GPU writer. pub(crate) fn demand_material_texture(&self, heap: &super::Heap, index: u32, stamp: crate::material_demand::Mark, frame: u64) -> Option<(u32, u64, bool)> { diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index d6eeafa19b..6c5fb5d5f5 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1203,7 +1203,11 @@ impl State { None => self.user_value(compute, u.slot, u.root, u.dword), }; } - if !compute && crate::material_demand::enabled() + let capture = (!compute) + .then(|| crate::material_demand::capture_for(&stage.shader.hash, list)) + .flatten(); + let demand = !compute && crate::material_demand::enabled(); + if (demand || capture.is_some()) && let Some(fields) = crate::material_demand::fields(&stage.shader.hash) && t.host.user_data.iter().any(|u| u.index == 8 && u.root == RootType::Table && u.slot == 0) && let Some(u) = t.host.user_data.iter().find(|u| u.index == 14 && u.root == RootType::Constants) @@ -1214,9 +1218,16 @@ impl State { && !heap.samplers() && let Some(&bound) = values.get(8) && Some(u64::from(bound)) == table.checked_sub(heap.start) - && crate::material_demand::wants(heap, record, fields) { - crate::material_demand::record(list, heap, *table, record, fields); + let prioritize = demand && crate::material_demand::wants(heap, record, fields); + if prioritize || capture.is_some() { + crate::material_demand::record( + list, + heap, + *table, + crate::material_demand::Request { record, fields, prioritize, capture }, + ); + } } // SAFETY: an open list; `values` covers the parameter. unsafe { @@ -1915,7 +1926,8 @@ impl State { HEAP_TEXTURES_RECHECKED[1].fetch_add(changed, Ordering::Relaxed); HEAP_TEXTURES_RECHECKED[2].store(waiting, Ordering::Relaxed); } - let wanted = crate::material_demand::enabled().then(|| host.material_demand.take(heap, host, frame)); + let wanted = (crate::material_demand::enabled() || crate::material_demand::trace_enabled()) + .then(|| host.material_demand.take(heap, host, frame)); let (mut due, census) = host.texture_slots_due(frame, 4096); if let Some(wanted) = wanted { crate::material_demand::promote(&mut due, &wanted, frame); diff --git a/crates/victory-gpu/src/material_demand.rs b/crates/victory-gpu/src/material_demand.rs index e2f81aa0af..95dcc571cc 100644 --- a/crates/victory-gpu/src/material_demand.rs +++ b/crates/victory-gpu/src/material_demand.rs @@ -26,6 +26,57 @@ pub(crate) fn enabled() -> bool { }) } +pub(crate) fn trace_enabled() -> bool { + static TRACE: OnceLock = OnceLock::new(); + cfg!(feature = "diagnostics") + && *TRACE.get_or_init(|| { + std::env::var_os("VICTORY_MATERIAL_TEXTURE_TRACE").is_some_and(|v| v == "1") + }) +} + +#[derive(Clone, Copy)] +pub(crate) struct Capture { + pub(crate) shader: &'static str, + pub(crate) frame: u64, + pub(crate) list: usize, +} + +pub(crate) fn capture_for(hash: &str, list: &HostList) -> Option { + #[cfg(feature = "diagnostics")] + if trace_enabled() { + let shader = match hash { + "a402e650d0acbc92" => "a402e650d0acbc92", + "b15ba4896d650511" => "b15ba4896d650511", + _ => return None, + }; + return crate::capture::recording_listed().then(|| Capture { + shader, + frame: crate::queue::presented() + 1, + list: std::ptr::from_ref(list) as usize, + }); + } + let _ = (hash, list); + None +} + +// A listed frame can contain thousands of commands, even when the concurrent +// readbacks finish before the recorder reaches the end of that frame. +fn capture_budget(frame: u64) -> bool { + static BUDGET: Mutex<(u64, usize)> = Mutex::new((0, 0)); + let mut budget = BUDGET.lock().unwrap_or_else(|e| e.into_inner()); + if frame < budget.0 { + return false; + } + if frame != budget.0 { + *budget = (frame, 0); + } + if budget.1 == LIMIT { + return false; + } + budget.1 += 1; + true +} + pub(crate) fn fields(hash: &str) -> Option<&'static [u32]> { match hash { // The deferred character shaders read heap indices from the same @@ -69,6 +120,20 @@ struct Observation { frame: u64, stamp: Mark, slots: Vec, + capture: Option, +} + +struct CapturedMaterial { + draw: Capture, + record: u32, + fields: Vec<(u32, u32)>, +} + +pub(crate) struct Request { + pub(crate) record: u32, + pub(crate) fields: &'static [u32], + pub(crate) prioritize: bool, + pub(crate) capture: Option, } type RecordKey = (usize, u32, &'static [u32]); @@ -178,7 +243,7 @@ fn indices(words: &[u32], fields: &[u32], count: u32) -> Vec { for field in fields { if let Some(&word) = words.get((field / 4) as usize) { // The guest shifts the packed index left five bits in a 32-bit register. - let slot = word.wrapping_shl(5) >> 5; + let slot = heap_slot(word); if slot < count && !slots.contains(&slot) { slots.push(slot); } @@ -187,13 +252,17 @@ fn indices(words: &[u32], fields: &[u32], count: u32) -> Vec { slots } +fn heap_slot(word: u32) -> u32 { + word.wrapping_shl(5) >> 5 +} + pub(crate) fn record( list: &HostList, heap: &Heap, table: u64, - record: u32, - fields: &'static [u32], + request: Request, ) { + let Request { record, fields, prioritize, capture } = request; let Some(handle) = table.checked_add(TABLE_DWORDS * 4) else { return; }; @@ -225,6 +294,10 @@ pub(crate) fn record( { return; } + let capture = capture.filter(|draw| capture_budget(draw.frame)); + if !prioritize && capture.is_none() { + return; + } let Some(gpu) = crate::host::host() else { return; }; @@ -243,7 +316,9 @@ pub(crate) fn record( } list.keep(&back); list.keep(&source.buffer); - RECORDED.fetch_add(1, Ordering::Relaxed); + if prioritize { + RECORDED.fetch_add(1, Ordering::Relaxed); + } list.defer_after(move || { if !ticket.finish() || frame.abs_diff(crate::frame::current()) > MAX_AGE { return; @@ -265,12 +340,23 @@ pub(crate) fn record( if back.Map(0, Some(&read), Some(&mut data)).is_err() { return; } - let slots = if data.is_null() { - Vec::new() + let words = if data.is_null() { + &[] } else { - let words = std::slice::from_raw_parts(data.cast::(), bytes / 4); - indices(words, fields, count) + std::slice::from_raw_parts(data.cast::(), bytes / 4) }; + let slots = if prioritize { indices(words, fields, count) } else { Vec::new() }; + let captured = capture.map(|draw| CapturedMaterial { + draw, + record, + fields: fields + .iter() + .filter_map(|&offset| { + let word = *words.get((offset / 4) as usize)?; + Some((offset, heap_slot(word))) + }) + .collect(), + }); back.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); if !slots.is_empty() { let n = OBSERVED.fetch_add(1, Ordering::Relaxed) + 1; @@ -283,6 +369,8 @@ pub(crate) fn record( "GPU material records read for texture scheduling" ); } + } + if !slots.is_empty() || captured.is_some() { observations.push(Observation { source_slot: slot, view: view.clone(), @@ -290,6 +378,7 @@ pub(crate) fn record( stamp, frame, slots, + capture: captured, }); } } @@ -297,21 +386,34 @@ pub(crate) fn record( } impl Mailbox { + #[cfg(all(test, feature = "diagnostics"))] + pub(crate) fn captured_fields(&self) -> Vec<(u32, u32)> { + let observations = self.0.lock().unwrap_or_else(|e| e.into_inner()); + observations + .iter() + .find_map(|obs| obs.capture.as_ref()) + .map(|capture| capture.fields.clone()) + .unwrap_or_default() + } + pub(crate) fn take(&self, heap: &Heap, host: &HostHeap, frame: u64) -> Vec<(u32, u64, bool)> { let observations = std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner())); let mut priority = Vec::new(); for obs in observations { - if frame.abs_diff(obs.frame) > MAX_AGE - || heap + let current = frame.abs_diff(obs.frame) <= MAX_AGE + && heap .handle(obs.source_slot) .and_then(crate::descriptor::checked_view) .as_ref() - != Some(&obs.view) - || !obs + == Some(&obs.view) + && obs .shadow .upgrade() - .is_some_and(|s| host.shows(obs.source_slot, &s.buffer) == Some(true)) - { + .is_some_and(|s| host.shows(obs.source_slot, &s.buffer) == Some(true)); + if let Some(capture) = &obs.capture { + capture.report(heap, host, obs.stamp, frame, current); + } + if !current { continue; } for slot in obs.slots { @@ -330,6 +432,27 @@ impl Mailbox { } } +impl CapturedMaterial { + fn report(&self, heap: &Heap, host: &HostHeap, stamp: Mark, frame: u64, source_current: bool) { + let Capture { shader, frame: draw_frame, list } = self.draw; + tracing::info!( + shader, draw_frame, host_list = format_args!("{list:#x}"), + record = self.record, observed_frame = frame, source_current, + fields = ?self.fields, "material texture indices read back" + ); + #[cfg(feature = "diagnostics")] + if source_current { + for &(offset, slot) in &self.fields { + let state = host.material_slot_state(heap, slot, stamp, frame); + tracing::info!(shader, draw_frame, host_list = format_args!("{list:#x}"), + record = self.record, observed_frame = frame, offset, slot, %state, + "material texture descriptor observed"); + } + } + let _ = (heap, host, stamp); + } +} + // Reorder only existing due entries. Keep at least three normal slots // between each promoted write and rotate who goes first across frames. pub(crate) fn promote(due: &mut [(u32, u64, bool)], wanted: &[(u32, u64, bool)], frame: u64) -> usize { From 8929843ac738c05ebcf117bb76dcbfb7f996b36a Mon Sep 17 00:00:00 2001 From: Zhelezniak Artem Date: Thu, 26 Nov 2026 09:58:25 +0300 Subject: [PATCH 3/3] GPU: trace sampled material texture upload outcomes --- crates/victory-gpu/src/descriptor.rs | 5 +- crates/victory-gpu/src/descriptor/host.rs | 57 ++++++++++++-- crates/victory-gpu/src/draw.rs | 23 +++++- crates/victory-gpu/src/material_demand.rs | 96 ++++++++++++++++++++++- 4 files changed, 167 insertions(+), 14 deletions(-) diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 7c4702c7f4..8228eacb4b 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -1146,8 +1146,9 @@ mod tests { put(3, addr + small, 0); // touches the nominal interval, starts after the visible mips let revived = host.demand_material_texture(heap, 1, stamp, frame).unwrap(); assert!(host.texture_slots_due(frame, 8).0.contains(&revived)); - assert!(host.material_upload_allowed(1, revived.1, addr, small, small)); - assert!(!host.material_upload_allowed(1, revived.1, addr, small, small - 1)); + assert_eq!(host.material_upload_refusal(1, revived.1, addr, small, small), None); + assert_eq!(host.material_upload_refusal(1, revived.1 + 1, addr, small, small), Some("stale_write")); + assert_eq!(host.material_upload_refusal(1, revived.1, addr, small, small - 1), Some("pages_unavailable")); let srv = host.mirror(1, heap.handle(1).unwrap(), true).unwrap(); let live = host::placed_texture(&srv).unwrap(); let View::Shader(texture, _) = live.view else { panic!("no sampled texture") }; diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f7ed495128..abd10fb8a9 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1204,6 +1204,19 @@ impl HostHeap { } } + /// A sampled generation still owned by the texture upload queue. + #[cfg(feature = "diagnostics")] + pub(crate) fn material_queued_write(&self, heap: &super::Heap, index: u32, stamp: crate::material_demand::Mark) -> Option { + let epoch = self.material_epochs.get()?.get(index as usize)?; + let unchanged = || epoch.load(std::sync::atomic::Ordering::Relaxed) <= stamp.descriptor; + if !unchanged() || !heap.handle(index).and_then(super::checked_view).as_ref().is_some_and(is_texture_view) { + return None; + } + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + let queued = textures.slots.get(&index)?; + (unchanged() && (queued.write <= stamp.write || queued.recovered)).then_some(queued.write) + } + /// A shader-selected material field can re-enrol its current null block-compressed SRV. /// Never supersede another allocation, or upload title bytes over a GPU writer. pub(crate) fn demand_material_texture(&self, heap: &super::Heap, index: u32, stamp: crate::material_demand::Mark, frame: u64) -> Option<(u32, u64, bool)> { @@ -1250,14 +1263,21 @@ impl HostHeap { /// Between observation and upload the queue can be delayed by budgeting, a writable /// resource can appear over the same pages, or streaming can remove a mip. - pub(crate) fn material_upload_allowed(&self, index: u32, write: u64, start: u64, len: u64, mapped: u64) -> bool { + pub(crate) fn material_upload_refusal(&self, index: u32, write: u64, start: u64, len: u64, mapped: u64) -> Option<&'static str> { let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); - let Some(waiting) = textures.slots.get(&index).filter(|w| w.write == write) else { return false }; - if !waiting.recovered { return false; } + if !textures.slots.get(&index).is_some_and(|w| w.write == write && w.recovered) { + return Some("stale_write"); + } drop(textures); - start.checked_add(len).is_some_and(|end| mapped == len - && !crate::resource::writable_texture_overlaps(start, end) - && !crate::texture::host_written_overlaps(start, end)) + let Some(end) = start.checked_add(len) else { + return Some("invalid_texture_span"); + }; + if mapped != len { + return Some("pages_unavailable"); + } + (crate::resource::writable_texture_overlaps(start, end) + || crate::texture::host_written_overlaps(start, end)) + .then_some("recovery_conflicts_with_gpu_writes") } /// Every title slot of the queue that is due at `frame`, and whether @@ -2137,6 +2157,12 @@ impl HostHeap { queued_write: Option, allow: impl FnOnce(&View, bool) -> bool, ) -> Result, ()> { + #[cfg(feature = "diagnostics")] + let trace = |outcome| { + if let Some(write) = queued_write { + self.material_demand.upload_outcome(index, write, crate::frame::current(), outcome); + } + }; if index >= self.count { // Diagnostic (NVIDIA heap cap): the highest title slot past the // host heap seen so far. @@ -2149,10 +2175,14 @@ impl HostHeap { "title slot past the host heap" ); } + #[cfg(feature = "diagnostics")] + trace("outside_host_heap"); return Ok(None); } let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); if queued_write.is_some_and(|write| !self.queued_write_current(index, write)) { + #[cfg(feature = "diagnostics")] + trace("stale_write"); return Ok(None); } if !for_draw && let Some(epochs) = self.material_epochs.get() { @@ -2177,6 +2207,8 @@ impl HostHeap { // Left for later and stale since: out of the sets and the stride table. let _ = self.note_buffer(index, None, false); } + #[cfg(feature = "diagnostics")] + trace("invalid_title_view"); return Ok(None); }; if queued_write.is_some() && let View::Placed(false, resource, desc) = &view { @@ -2189,6 +2221,8 @@ impl HostHeap { let span = placed.bytes(resource, crate::resource::first_mip(desc)) .map(|bytes| (start, start.saturating_add(bytes))); if span.is_none() || placed.by_slot.get(&index) != span.as_ref() { + #[cfg(feature = "diagnostics")] + trace("displaced_view"); return Ok(None); } } @@ -2201,6 +2235,8 @@ impl HostHeap { }; let current = made[index as usize] == key && !changed_owner; if !allow(&view, current) { + #[cfg(feature = "diagnostics")] + trace("vram_budget"); return Err(()); } if !current { @@ -2258,6 +2294,15 @@ impl HostHeap { } self.keep(index, kept.flatten()); } + #[cfg(feature = "diagnostics")] + if queued_write.is_some() && crate::material_demand::trace_enabled() && is_texture_view(&view) { + let native = self.kept.lock().unwrap_or_else(|e| e.into_inner())[index as usize].is_some(); + trace(match (current, native) { + (false, true) => "srv_installed", + (true, true) => "srv_already_present", + (_, false) => "srv_unavailable", + }); + } Ok(Some(view)) } diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index 6c5fb5d5f5..64ca2d9944 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1998,7 +1998,11 @@ impl State { }; let began = std::time::Instant::now(); for (index, write, recovered) in due { + #[cfg(feature = "diagnostics")] + let trace = |outcome| host.material_demand.upload_outcome(index, write, frame, outcome); if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + #[cfg(feature = "diagnostics")] + trace("staging_pass_limit"); break; } // A placed texture whose memory is not mapped (not streamed in @@ -2019,11 +2023,17 @@ impl State { // another texture's. let len = crate::resource::placed_bytes_from(&resource, crate::resource::first_mip(&desc)).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); - if recovered && !host.material_upload_allowed(index, write, address, len, mapped) { + if recovered && let Some(reason) = host.material_upload_refusal(index, write, address, len, mapped) { + #[cfg(feature = "diagnostics")] + trace(reason); + #[cfg(not(feature = "diagnostics"))] + let _ = reason; host.texture_slot_done(index, write, None); continue; } if mapped == 0 { + #[cfg(feature = "diagnostics")] + trace("pages_unavailable"); HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); // Streamed out: what the slot showed is let go. host.texture_slot_gone(index, write); @@ -2032,6 +2042,8 @@ impl State { } if mapped < len { if mapped <= host.texture_slot_mapped(index) { + #[cfg(feature = "diagnostics")] + trace("no_more_pages_mapped"); HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); host.texture_slot_later(index, write, frame, most); continue; @@ -2067,10 +2079,17 @@ impl State { // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as // before. let Some(handle) = heap.handle(index) else { + #[cfg(feature = "diagnostics")] + trace("missing_title_slot"); host.texture_slot_done(index, write, None); continue; }; - let upload = (room || reupload_when_full()) + let can_mirror = room || reupload_when_full(); + #[cfg(feature = "diagnostics")] + if !can_mirror { + trace("vram_budget"); + } + let upload = can_mirror .then(|| host.mirror_queued(index, handle, write, !room)) .and_then(Result::ok); let Some((view, _residence)) = upload else { diff --git a/crates/victory-gpu/src/material_demand.rs b/crates/victory-gpu/src/material_demand.rs index 95dcc571cc..ddb3c48b12 100644 --- a/crates/victory-gpu/src/material_demand.rs +++ b/crates/victory-gpu/src/material_demand.rs @@ -111,7 +111,51 @@ pub(crate) struct Mark { } #[derive(Default)] -pub(crate) struct Mailbox(Arc>>); +pub(crate) struct Mailbox { + observations: Arc>>, + #[cfg(feature = "diagnostics")] + uploads: Mutex, +} + +#[cfg(feature = "diagnostics")] +#[derive(Default)] +struct UploadWatch(Vec); + +#[cfg(feature = "diagnostics")] +struct WatchedUpload { + slot: u32, + write: u64, + expires: u64, + remaining: u8, +} + +#[cfg(feature = "diagnostics")] +impl UploadWatch { + const SLOTS: usize = LIMIT * 9; + const FRAMES: u64 = 256; + const ATTEMPTS: u8 = 8; + + fn watch(&mut self, slot: u32, write: u64, frame: u64) { + self.0.retain(|entry| entry.expires >= frame); + let expires = frame.saturating_add(Self::FRAMES); + if let Some(entry) = self.0.iter_mut().find(|entry| (entry.slot, entry.write) == (slot, write)) { + entry.expires = expires; + } else if self.0.len() < Self::SLOTS { + self.0.push(WatchedUpload { slot, write, expires, remaining: Self::ATTEMPTS }); + } + } + + fn record(&mut self, slot: u32, write: u64, frame: u64) -> bool { + let Some(entry) = self.0.iter_mut().find(|entry| (entry.slot, entry.write) == (slot, write)) else { + return false; + }; + if frame > entry.expires || entry.remaining == 0 { + return false; + } + entry.remaining -= 1; + true + } +} struct Observation { source_slot: u32, @@ -305,7 +349,7 @@ pub(crate) fn record( return; }; let shadow = Arc::downgrade(&source); - let mailbox = Arc::downgrade(&host.material_demand.0); + let mailbox = Arc::downgrade(&host.material_demand.observations); let count = host.count(); // SAFETY: the verified range is in the title buffer in use as an SRV. // Like the title's indirect-record reads, its buffer promotes to COPY_SOURCE. @@ -388,7 +432,7 @@ pub(crate) fn record( impl Mailbox { #[cfg(all(test, feature = "diagnostics"))] pub(crate) fn captured_fields(&self) -> Vec<(u32, u32)> { - let observations = self.0.lock().unwrap_or_else(|e| e.into_inner()); + let observations = self.observations.lock().unwrap_or_else(|e| e.into_inner()); observations .iter() .find_map(|obs| obs.capture.as_ref()) @@ -396,8 +440,17 @@ impl Mailbox { .unwrap_or_default() } + #[cfg(feature = "diagnostics")] + pub(crate) fn upload_outcome(&self, slot: u32, write: u64, frame: u64, outcome: &'static str) { + if trace_enabled() + && self.uploads.lock().unwrap_or_else(|e| e.into_inner()).record(slot, write, frame) + { + tracing::info!(slot, write, frame, outcome, "material texture upload outcome"); + } + } + pub(crate) fn take(&self, heap: &Heap, host: &HostHeap, frame: u64) -> Vec<(u32, u64, bool)> { - let observations = std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner())); + let observations = std::mem::take(&mut *self.observations.lock().unwrap_or_else(|e| e.into_inner())); let mut priority = Vec::new(); for obs in observations { let current = frame.abs_diff(obs.frame) <= MAX_AGE @@ -427,6 +480,19 @@ impl Mailbox { priority.push(item); } } + // This observes the queue after demand has had its normal turn. + // Trace-only recording never enrols, promotes or reorders a slot. + #[cfg(feature = "diagnostics")] + if let Some(capture) = &obs.capture { + for &(offset, slot) in &capture.fields { + if let Some(write) = host.material_queued_write(heap, slot, obs.stamp) { + self.uploads.lock().unwrap_or_else(|e| e.into_inner()).watch(slot, write, frame); + tracing::info!(shader = capture.draw.shader, draw_frame = capture.draw.frame, + record = capture.record, offset, slot, write, frame, + "watch material texture upload"); + } + } + } } priority } @@ -533,6 +599,28 @@ mod tests { assert_eq!(byte_range(16, packed, 52), Some((16, 36))); } + #[cfg(feature = "diagnostics")] + #[test] + fn material_upload_watch_matches_the_write_and_bounds_repeated_logs() { + let mut watch = UploadWatch::default(); + watch.watch(7, 10, 4); + assert!(!watch.record(7, 11, 4)); + assert!(!watch.record(8, 10, 4)); + for _ in 0..UploadWatch::ATTEMPTS { + assert!(watch.record(7, 10, 4)); + } + watch.watch(7, 10, 5); + assert!(!watch.record(7, 10, 5)); + watch.watch(7, 11, 5); + assert!(watch.record(7, 11, 5)); + let late = 6 + UploadWatch::FRAMES; + assert!(!watch.record(7, 11, late)); + for slot in 0..=UploadWatch::SLOTS as u32 { + watch.watch(slot, 12, late); + } + assert_eq!(watch.0.len(), UploadWatch::SLOTS); + } + #[test] fn only_current_existing_due_writes_move_ahead() { let mut due: Vec<_> = (0..10u32).map(|n| (n, u64::from(n) + 1, false)).collect();