diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index 2312cde537..72c935367c 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") }; @@ -1212,8 +1213,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); @@ -1267,19 +1282,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 c4c538e510..3f3c4bb7cf 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -1339,6 +1339,55 @@ 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 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)> { @@ -1385,14 +1434,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 @@ -2483,6 +2539,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. @@ -2495,10 +2557,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() { @@ -2524,6 +2590,8 @@ impl HostHeap { let _ = self.note_buffer(index, None, false); } self.update_sparse(index, None, None, false); + #[cfg(feature = "diagnostics")] + trace("invalid_title_view"); return Ok(None); }; if queued_write.is_some() && let View::Placed(false, resource, desc) = &view { @@ -2536,6 +2604,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); } } @@ -2552,6 +2622,8 @@ impl HostHeap { }); let current = (made[index as usize] == key && !changed_owner) || pending; if !allow(&view, current) { + #[cfg(feature = "diagnostics")] + trace("vram_budget"); return Err(()); } if !current { @@ -2621,6 +2693,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 2900faa5d2..432dbf4655 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -1269,7 +1269,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) @@ -1280,9 +1284,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 { @@ -1983,7 +1994,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); @@ -2054,7 +2066,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 @@ -2075,11 +2091,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); @@ -2088,6 +2110,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; @@ -2123,10 +2147,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 750f2285a5..ddb3c48b12 100644 --- a/crates/victory-gpu/src/material_demand.rs +++ b/crates/victory-gpu/src/material_demand.rs @@ -26,8 +26,63 @@ 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 + // 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]), @@ -56,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, @@ -65,6 +164,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]); @@ -174,7 +287,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); } @@ -183,13 +296,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; }; @@ -221,6 +338,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; }; @@ -228,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. @@ -239,7 +360,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; @@ -261,12 +384,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; @@ -279,6 +413,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(), @@ -286,6 +422,7 @@ pub(crate) fn record( stamp, frame, slots, + capture: captured, }); } } @@ -293,21 +430,43 @@ pub(crate) fn record( } impl Mailbox { + #[cfg(all(test, feature = "diagnostics"))] + pub(crate) fn captured_fields(&self) -> Vec<(u32, u32)> { + let observations = self.observations.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() + } + + #[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 { - 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 { @@ -321,11 +480,45 @@ 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 } } +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 { @@ -393,6 +586,41 @@ 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))); + } + + #[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();