Merge day/textures
This commit is contained in:
commit
f6e2b31ceb
20 files changed
+1887
-84
No files matched your search
@@ -514,8 +514,8 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
|
||||
}
|
||||
|
||||
/// Runs `f` with the host heap of the title's largest view heap, if there is
|
||||
/// one (reports: nothing is waited for).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
/// one (nothing is waited for).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn with_view_heap<T>(f: impl FnOnce(&host::HostHeap) -> T) -> Option<T> {
|
||||
let heaps = SHADER_HEAPS.try_read().ok()?;
|
||||
let host = heaps
|
||||
|
||||
@@ -365,6 +365,13 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
|
||||
|
||||
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Makes the slots whose new texture's upload has run
|
||||
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
|
||||
/// something else: the next texture pass does.
|
||||
pub(crate) fn flip_now() {
|
||||
let _ = super::with_view_heap(HostHeap::texture_slots_flip);
|
||||
}
|
||||
|
||||
/// Since the start: slots made from their new view after its upload had run,
|
||||
/// and those the title had written again by then.
|
||||
pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
|
||||
@@ -754,6 +761,20 @@ pub(crate) fn remapped(at: usize, len: usize) {
|
||||
ranges.push((start, end));
|
||||
}
|
||||
|
||||
/// Ranges of memory, those that touch made one (DexNom/VIctory 921d8d3b:
|
||||
/// several threads map and write, some 5,000 ranges a frame, the same
|
||||
/// textures' over and over, and each was looked up).
|
||||
fn join(ranges: &mut Vec<(u64, u64)>) {
|
||||
ranges.sort_unstable();
|
||||
ranges.dedup_by(|next, last| {
|
||||
if next.0 > last.1 {
|
||||
return false;
|
||||
}
|
||||
last.1 = last.1.max(next.1);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Frames for which a slot a draw read through a table counts as a table's
|
||||
/// slot ([`HostHeap::tabled`]).
|
||||
const TABLED_FRAMES: u64 = 240;
|
||||
@@ -1037,6 +1058,17 @@ fn view_stride(view: &View) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// What else the table of strides says of a typed buffer view of an integer
|
||||
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view.
|
||||
fn view_kind(view: &View) -> u32 {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
match view_elements(view) {
|
||||
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
|
||||
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A buffer view's structure stride, whether it is raw, and its format;
|
||||
/// `None` if `view` is not a buffer view.
|
||||
fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
|
||||
@@ -1732,10 +1764,11 @@ impl HostHeap {
|
||||
pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
self.texture_slots_page_written(frame);
|
||||
let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let mut ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if ranges.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
join(&mut ranges);
|
||||
let mut slots: Vec<u32> = {
|
||||
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
|
||||
ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
|
||||
@@ -2022,24 +2055,36 @@ impl HostHeap {
|
||||
/// `handle` views, or something else: until then it shows the neutral
|
||||
/// texture ([`show_after`]).
|
||||
pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
|
||||
if self.show_later(index, handle) {
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
}
|
||||
}
|
||||
|
||||
/// What slot `index` shows until the texture the record at `handle` views
|
||||
/// is shown. False: it shows it, or there is none.
|
||||
fn show_later(&self, index: u32, handle: u64) -> bool {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let key = record_key(handle);
|
||||
let view = view_at(key as u32, (key >> 32) as u32);
|
||||
let (true, Some(view)) = (key != 0, view) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
let stale = {
|
||||
let _made = self.made.lock(index);
|
||||
let Some(shown) = self.made.get(index) else {
|
||||
return;
|
||||
return false;
|
||||
};
|
||||
if shown == key {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
// (As `mirror`.)
|
||||
let stale = self.note_buffer(index, Some(&view), true);
|
||||
let old = view_at(shown as u32, (shown >> 32) as u32);
|
||||
if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) {
|
||||
let kept = old.is_some_and(|old| match kin(&old, &view) {
|
||||
Kin::Same => true,
|
||||
kin => kin.kept(keep_shown()),
|
||||
});
|
||||
if shown == 0 || !kept {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
note_before(index, shown, "neutral");
|
||||
self.quick_is(index, 0);
|
||||
@@ -2053,7 +2098,21 @@ impl HostHeap {
|
||||
stale
|
||||
};
|
||||
self.unmake_stale(index, stale);
|
||||
self.flip(list, index, handle, Some(crate::frame::current()));
|
||||
true
|
||||
}
|
||||
|
||||
/// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job`
|
||||
/// makes: shown when that has run.
|
||||
pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) {
|
||||
if !self.show_later(index, handle) {
|
||||
return;
|
||||
}
|
||||
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
|
||||
let late = Some(crate::frame::current());
|
||||
job.then(move || {
|
||||
let flip = Flip { after: 0, heap, index, handle, key, late };
|
||||
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
|
||||
});
|
||||
}
|
||||
|
||||
/// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made
|
||||
@@ -2067,6 +2126,7 @@ impl HostHeap {
|
||||
&& let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view))
|
||||
&& crate::resource::buffer_bytes(resource as crate::object::This).is_none()
|
||||
&& crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh)
|
||||
&& !crate::texture::ahead::there(resource as crate::object::This)
|
||||
{
|
||||
return self.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
@@ -2131,8 +2191,14 @@ impl HostHeap {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
note_before(f.index, shown, if f.late.is_some() { "shown after its upload" } else { "flip" });
|
||||
self.put(f.index);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let was = shown;
|
||||
self.made.set(f.index, f.key);
|
||||
self.keep(f.index, kept);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if f.late.is_some() && was != 0 {
|
||||
same_bytes(was, f.key);
|
||||
}
|
||||
if let Some(since) = f.late {
|
||||
let frames = crate::frame::current().saturating_sub(since);
|
||||
let n = LATE[0].fetch_add(1, Relaxed) + 1;
|
||||
@@ -2380,12 +2446,13 @@ impl HostHeap {
|
||||
}
|
||||
}
|
||||
let stride = view.and_then(view_stride);
|
||||
let kind = view.map_or(0, view_kind);
|
||||
if let Some((_, _, data)) = &self.strides
|
||||
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
|
||||
{
|
||||
// SAFETY: inside the mapping; shaders read it while we write (a
|
||||
// dword, either value is one the slot had).
|
||||
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
|
||||
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
|
||||
}
|
||||
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let was = if stride.is_some() {
|
||||
@@ -2916,13 +2983,27 @@ impl HostHeap {
|
||||
// time it got sharper.
|
||||
if later
|
||||
&& keep_views()
|
||||
&& view_at(shown as u32, (shown >> 32) as u32)
|
||||
.is_some_and(|old| same_placed_texture(&old, &view))
|
||||
&& let Some(old) = view_at(shown as u32, (shown >> 32) as u32)
|
||||
{
|
||||
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
let kin = kin(&old, &view);
|
||||
if kin == Kin::Same {
|
||||
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
}
|
||||
// And of another texture that can stand for it
|
||||
// ([`keep_shown`]): black, then grey for a frame or two is
|
||||
// what popped.
|
||||
if is_texture_view(&old) {
|
||||
let kept = kin.kept(keep_shown());
|
||||
rewritten(kin, kept);
|
||||
if kept {
|
||||
drop(held);
|
||||
self.unmake_stale(index, stale);
|
||||
return Some(view);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if !self.sampler && is_texture_view(&view) {
|
||||
@@ -4016,6 +4097,160 @@ fn keep_views() -> bool {
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// What the texture view a slot is written with has to do with the one it
|
||||
/// shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Kin {
|
||||
/// A view of the same placed texture ([`same_placed_texture`]).
|
||||
Same,
|
||||
/// A texture of the same description placed elsewhere (moved, or one of
|
||||
/// its kind).
|
||||
Moved,
|
||||
/// One of the same format and shape in another size: the same texture
|
||||
/// with more or fewer levels, as a title streams it.
|
||||
Sized,
|
||||
/// A view of the same dimension, of another texture.
|
||||
Other,
|
||||
/// A view no shader that reads the one can read.
|
||||
None,
|
||||
}
|
||||
|
||||
impl Kin {
|
||||
/// Whether the slot goes on showing what it shows, by [`keep_shown`].
|
||||
fn kept(self, keep: u8) -> bool {
|
||||
match self {
|
||||
Kin::Same => true,
|
||||
Kin::Moved | Kin::Sized => keep >= 1,
|
||||
Kin::Other => keep >= 2,
|
||||
Kin::None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Kin`] of the view `old`, which a slot shows, and `new`.
|
||||
fn kin(old: &View, new: &View) -> Kin {
|
||||
if same_placed_texture(old, new) {
|
||||
return Kin::Same;
|
||||
}
|
||||
if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) {
|
||||
if a[0] == 1 || b[0] == 1 || from[1] != to[1] {
|
||||
return Kin::None;
|
||||
}
|
||||
// (Width, 64 bits, height, depth and levels, format: words 4 to 8.)
|
||||
if a[0] == b[0] && a[2..13] == b[2..13] {
|
||||
return Kin::Moved;
|
||||
}
|
||||
let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from));
|
||||
return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] {
|
||||
Kin::Sized
|
||||
} else {
|
||||
Kin::Other
|
||||
};
|
||||
}
|
||||
let dimension = |view: &View| match view {
|
||||
View::Placed(false, resource, desc) if resource[0] != 1 => desc[1],
|
||||
View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1],
|
||||
_ => 0,
|
||||
};
|
||||
match (dimension(old), dimension(new)) {
|
||||
(0, _) | (_, 0) => Kin::None,
|
||||
(a, b) if a == b => Kin::Other,
|
||||
_ => Kin::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a slot that is written with a view of another texture goes on
|
||||
/// showing the one it shows until the new one is made and its upload has run
|
||||
/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral
|
||||
/// texture; 1: one of the same kind in another place or size; 2: any of the
|
||||
/// same dimension.
|
||||
fn keep_shown() -> u8 {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") {
|
||||
return if on { 2 } else { 0 };
|
||||
}
|
||||
static KEEP: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
|
||||
*KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1))
|
||||
}
|
||||
|
||||
/// Slots that showed a texture and were written with a view of another,
|
||||
/// since the start, by [`Kin`] (moved, sized, other, none), and those of
|
||||
/// them that kept what they showed.
|
||||
static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
|
||||
|
||||
fn rewritten(kin: Kin, kept: bool) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let class = match kin {
|
||||
Kin::Moved | Kin::Same => 0,
|
||||
Kin::Sized => 1,
|
||||
Kin::Other => 2,
|
||||
Kin::None => 3,
|
||||
};
|
||||
REWRITTEN[class].fetch_add(1, Relaxed);
|
||||
REWRITTEN[4].fetch_add(u64::from(kept), Relaxed);
|
||||
let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
|
||||
if n.is_multiple_of(5000) {
|
||||
tracing::info!(
|
||||
"slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)",
|
||||
REWRITTEN[0].load(Relaxed),
|
||||
REWRITTEN[1].load(Relaxed),
|
||||
REWRITTEN[2].load(Relaxed),
|
||||
REWRITTEN[3].load(Relaxed),
|
||||
REWRITTEN[4].load(Relaxed)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Diagnostics: whether a texture that a slot showed until its new one came
|
||||
/// holds the new one's bytes (the title moved it), by the bytes their host
|
||||
/// copies were filled from: equal, different, not known.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
fn same_bytes(old: u64, new: u64) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
static SEEN: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
|
||||
let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
|
||||
let (Some(old), Some(new)) = (view(old), view(new)) else {
|
||||
return;
|
||||
};
|
||||
let held = |view: &View| {
|
||||
let View::Placed(false, resource, desc) = view else {
|
||||
return None;
|
||||
};
|
||||
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
|
||||
crate::resource::texture_held(crate::resource::texture_at_made(address, resource)?)
|
||||
};
|
||||
let class = match kin(&old, &new) {
|
||||
Kin::Moved => 0,
|
||||
Kin::Same | Kin::None => return,
|
||||
_ => 3,
|
||||
};
|
||||
let which = match (held(&old), held(&new)) {
|
||||
(Some(a), Some(b)) if a == b => 0,
|
||||
(Some(a), Some(b)) if a.0 == b.0 => 1,
|
||||
_ => 2,
|
||||
};
|
||||
SEEN[class + which].fetch_add(1, Relaxed);
|
||||
let n: u64 = SEEN.iter().map(|n| n.load(Relaxed)).sum();
|
||||
if n.is_multiple_of(1000) {
|
||||
let seen: Vec<u64> = SEEN.iter().map(|n| n.load(Relaxed)).collect();
|
||||
tracing::info!(
|
||||
"slots that went on showing another texture until the new one came, since the start: of one of the same kind elsewhere {} had the new one's bytes, {} others, {} not known; of others {}, {}, {}",
|
||||
seen[0], seen[1], seen[2], seen[3], seen[4], seen[5]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// For `crate::popwatch`, since the start: slots made null as they were
|
||||
/// written with another texture, such that kept the old one, slots given the
|
||||
/// neutral texture, slots made null as their memory was another's.
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) fn pop_causes() -> [u64; 4] {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let all: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
|
||||
let kept = REWRITTEN[4].load(Relaxed);
|
||||
[all.saturating_sub(kept), kept, LATE[3].load(Relaxed), STALE[0].load(Relaxed)]
|
||||
}
|
||||
|
||||
/// Whether a slot already made from its record is told so without the lock
|
||||
/// (`VICTORY_QUICK_MIRROR=0`: with it, as before).
|
||||
fn quick_mirror() -> bool {
|
||||
@@ -4425,6 +4660,61 @@ mod tests {
|
||||
assert!(!same_placed_texture(&low, &View::Shader(0, None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_that_touch_are_one() {
|
||||
let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)];
|
||||
join(&mut ranges);
|
||||
assert_eq!(ranges, [(1, 1), (10, 20), (30, 61)]);
|
||||
join(&mut ranges);
|
||||
assert_eq!(ranges.len(), 3);
|
||||
}
|
||||
|
||||
/// Typed buffer views of integer formats are marked in the table of
|
||||
/// strides; float, normalized, raw and structured ones are not.
|
||||
#[test]
|
||||
fn integer_typed_buffer_views_are_marked_in_the_table_of_strides() {
|
||||
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
|
||||
// Format, dimension (buffer), first element, count, stride, counter, flags.
|
||||
let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0]));
|
||||
assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT");
|
||||
assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT");
|
||||
assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT");
|
||||
assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM");
|
||||
assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw");
|
||||
assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured");
|
||||
assert_eq!(view_stride(&uav(12, 0, 0)), Some(8));
|
||||
}
|
||||
|
||||
/// What may stand for a texture that is not there yet: one of its kind in
|
||||
/// another place or size; another one only if asked; nothing a shader
|
||||
/// cannot read in its place.
|
||||
#[test]
|
||||
fn a_slot_shows_on_what_can_stand_for_its_new_texture() {
|
||||
let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| {
|
||||
let mut desc = [0u32; 16];
|
||||
(desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb);
|
||||
View::Placed(false, resource, desc)
|
||||
};
|
||||
let old = view(texture, 98, 4, 0x1000_0000);
|
||||
let mut twice = texture;
|
||||
(twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001);
|
||||
let mut square = texture;
|
||||
square[6] = 512;
|
||||
let mut buffer = texture;
|
||||
buffer[0] = 1;
|
||||
assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same);
|
||||
assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved);
|
||||
assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized);
|
||||
assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other);
|
||||
assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other);
|
||||
assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None);
|
||||
assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None);
|
||||
for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] {
|
||||
assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A constant buffer view larger than the host takes is cut to what it
|
||||
/// takes: the device, which such a view removes, stays.
|
||||
#[test]
|
||||
|
||||
@@ -2404,7 +2404,7 @@ impl State {
|
||||
let _ = host.mirror(index, handle, true);
|
||||
}
|
||||
// Its bytes are in, or on the way there in a list before.
|
||||
if late && texture.is_some_and(crate::pool::fresh) {
|
||||
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_after(list, index, handle);
|
||||
}
|
||||
@@ -2422,7 +2422,27 @@ impl State {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(view) = &view {
|
||||
// The first upload of a texture no list has used: on a queue of
|
||||
// its own, and the slot shows it as soon as that has run.
|
||||
let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) {
|
||||
crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(ahead) = &ahead {
|
||||
use crate::texture::ahead::Taken;
|
||||
let (Taken::New(job) | Taken::Known(job)) = ahead;
|
||||
if let Some(handle) = heap.handle(index) {
|
||||
host.texture_slot_show_ahead(job, index, handle);
|
||||
}
|
||||
if let Taken::New(job) = ahead {
|
||||
crate::texture::ahead::send(job);
|
||||
}
|
||||
}
|
||||
let late = late && ahead.is_none();
|
||||
if let Some(view) = &view
|
||||
&& ahead.is_none()
|
||||
{
|
||||
// (What was found mapped of it a moment ago is not asked
|
||||
// again, unless the host copy may need more.)
|
||||
crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
|
||||
|
||||
@@ -8702,6 +8702,7 @@ impl Host {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let watched = crate::popwatch::take(&self.device, list, texture);
|
||||
p.panel.draw(self, copy, &back, (width, height), format);
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = frame;
|
||||
@@ -8714,13 +8715,23 @@ impl Host {
|
||||
),
|
||||
]);
|
||||
copy.close();
|
||||
match slot {
|
||||
let flown = match slot {
|
||||
Some(i) => {
|
||||
let flown = self.execute_own(copy);
|
||||
p.ahead[i].1 = flown;
|
||||
flown
|
||||
}
|
||||
None => self.execute(&[copy]),
|
||||
None => {
|
||||
self.execute(&[copy]);
|
||||
0
|
||||
}
|
||||
};
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(taken) = watched {
|
||||
crate::popwatch::sent(taken, flown, frame);
|
||||
}
|
||||
#[cfg(not(feature = "diagnostics"))]
|
||||
let _ = flown;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some((buffer, footprint)) = capture {
|
||||
crate::capture::save_read_back(frame, &buffer, &footprint);
|
||||
|
||||
@@ -46,6 +46,8 @@ pub mod pipeline;
|
||||
mod picked;
|
||||
#[cfg(windows)]
|
||||
mod pool;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
mod popwatch;
|
||||
#[cfg(windows)]
|
||||
mod primitive;
|
||||
pub mod query;
|
||||
|
||||
@@ -151,6 +151,17 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1
|
||||
}
|
||||
|
||||
impl GraphicsState {
|
||||
/// Whether the draws are a pass over the screen: no vertex input, no
|
||||
/// depth or stencil, a target. Such passes fill tables once; their shaders
|
||||
/// are few. (After Belobug/VIctory-Belobug-AMD 18e57db8.)
|
||||
pub(crate) fn screen_pass(&self) -> bool {
|
||||
self.inputs.is_empty()
|
||||
&& (self.depth_format == DXGI_FORMAT_UNKNOWN
|
||||
|| !self.depth.DepthEnable.as_bool() && !self.depth.StencilEnable.as_bool())
|
||||
&& self.targets.NumRenderTargets > 0
|
||||
&& self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE
|
||||
}
|
||||
|
||||
/// Takes in one subobject of a stream: its type, then its data at +4
|
||||
/// (+8 for those holding pointers).
|
||||
///
|
||||
|
||||
@@ -13,7 +13,13 @@
|
||||
//! whose pipeline is not ready is dropped, as an untranslated one is.
|
||||
//!
|
||||
//! The default budget is half a second per title frame. A pass the title
|
||||
//! runs only once and whose pipeline takes longer is lost.
|
||||
//! runs only once and whose pipeline takes longer is lost. Passes over the
|
||||
//! screen (no vertex input, no depth) have workers and a longer budget of
|
||||
//! their own ([`screen_budget`]): the title fills its lighting tables with
|
||||
//! such draws once, at the world's first frame, and behind a world's worth of
|
||||
//! pipelines they were dropped; that run had no lamps and no diffuse light to
|
||||
//! its end (run textures-d2, the first after a new translation; Belobug
|
||||
//! 18e57db8 found the same).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
|
||||
@@ -33,6 +39,8 @@ pub(crate) struct Pending {
|
||||
/// whether a draw or dispatch has requested it yet.
|
||||
key: String,
|
||||
used: AtomicBool,
|
||||
/// A pass over the screen ([`GraphicsState::screen_pass`]).
|
||||
screen: bool,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
|
||||
@@ -50,6 +58,7 @@ impl Pending {
|
||||
}
|
||||
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
|
||||
Pending {
|
||||
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
|
||||
shaders,
|
||||
graphics,
|
||||
queue_state: AtomicU8::new(NOT_QUEUED),
|
||||
@@ -113,6 +122,21 @@ fn wait_budget() -> Duration {
|
||||
})
|
||||
}
|
||||
|
||||
/// As [`wait_budget`], for passes over the screen (`VICTORY_SCREEN_WAIT_MS`,
|
||||
/// 10 s; 0: like the others). Below the title's 30 s watchdog.
|
||||
fn screen_budget() -> Duration {
|
||||
static BUDGET: OnceLock<Duration> = OnceLock::new();
|
||||
*BUDGET.get_or_init(|| {
|
||||
let millis = std::env::var("VICTORY_SCREEN_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(10_000);
|
||||
Duration::from_millis(millis)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether passes over the screen go before the others.
|
||||
fn screens_first() -> bool {
|
||||
!screen_budget().is_zero()
|
||||
}
|
||||
|
||||
/// Pipelines queued and not made yet.
|
||||
static WAITING: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
@@ -167,16 +191,18 @@ fn shared_budget() -> bool {
|
||||
|
||||
/// Waits for `p` while frame `frame` has budget left.
|
||||
fn wait(p: &Pending, frame: u64) {
|
||||
let budget = wait_budget();
|
||||
let screen = p.screen && screens_first();
|
||||
let budget = if screen { screen_budget() } else { wait_budget() };
|
||||
if budget.is_zero() {
|
||||
return;
|
||||
}
|
||||
// The frame the budget belongs to, and what was waited of it (or is
|
||||
// taken by a thread waiting now).
|
||||
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
|
||||
// taken by a thread waiting now); of the passes over the screen too.
|
||||
static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2];
|
||||
let spent_of = &SPENT[usize::from(screen)];
|
||||
let shared = shared_budget();
|
||||
let left = {
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if spent.0 != frame {
|
||||
*spent = (frame, Duration::ZERO);
|
||||
}
|
||||
@@ -201,8 +227,16 @@ fn wait(p: &Pending, frame: u64) {
|
||||
}
|
||||
drop(held);
|
||||
let waited = started.elapsed().min(left);
|
||||
if screen && waited > Duration::from_millis(500) {
|
||||
tracing::info!(
|
||||
ms = waited.as_millis() as u64,
|
||||
made = p.made.get().is_some(),
|
||||
shaders = ?p.shaders,
|
||||
"a pass over the screen was waited for (VICTORY_SCREEN_WAIT_MS=0: dropped past half a second a frame)"
|
||||
);
|
||||
}
|
||||
{
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A frame that began meanwhile has its own budget.
|
||||
if spent.0 == frame {
|
||||
if shared {
|
||||
@@ -225,6 +259,9 @@ const REQUESTED: u8 = 2;
|
||||
const MAKING: u8 = 3;
|
||||
|
||||
struct Queue {
|
||||
/// Requested passes over the screen: before all others, and the only ones
|
||||
/// [`SCREEN_WORKERS`] take.
|
||||
screen: VecDeque<Arc<Pending>>,
|
||||
early: VecDeque<Arc<Pending>>,
|
||||
requested: VecDeque<Arc<Pending>>,
|
||||
}
|
||||
@@ -232,6 +269,7 @@ struct Queue {
|
||||
impl Queue {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
screen: VecDeque::new(),
|
||||
early: VecDeque::new(),
|
||||
requested: VecDeque::new(),
|
||||
}
|
||||
@@ -245,7 +283,9 @@ impl Queue {
|
||||
return None;
|
||||
}
|
||||
p.queue_state.store(priority, Ordering::Relaxed);
|
||||
if priority == REQUESTED {
|
||||
if priority == REQUESTED && p.screen && screens_first() {
|
||||
self.screen.push_back(p.clone());
|
||||
} else if priority == REQUESTED {
|
||||
self.requested.push_back(p.clone());
|
||||
} else {
|
||||
self.early.push_back(p.clone());
|
||||
@@ -253,12 +293,16 @@ impl Queue {
|
||||
Some(prev == NOT_QUEUED)
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<Arc<Pending>> {
|
||||
let p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
})?;
|
||||
fn pop(&mut self, screens_only: bool) -> Option<Arc<Pending>> {
|
||||
let mut p = self.screen.pop_front();
|
||||
if p.is_none() && !screens_only {
|
||||
p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
});
|
||||
}
|
||||
let p = p?;
|
||||
p.queue_state.store(MAKING, Ordering::Relaxed);
|
||||
Some(p)
|
||||
}
|
||||
@@ -284,14 +328,21 @@ fn start(p: &Arc<Pending>, priority: u8) {
|
||||
if new {
|
||||
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
AVAILABLE.notify_one();
|
||||
if p.screen {
|
||||
AVAILABLE.notify_all();
|
||||
} else {
|
||||
AVAILABLE.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next() -> Arc<Pending> {
|
||||
/// Workers that make passes over the screen alone, besides the others.
|
||||
const SCREEN_WORKERS: usize = 2;
|
||||
|
||||
fn next(screens_only: bool) -> Arc<Pending> {
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if let Some(p) = queue.pop() {
|
||||
if let Some(p) = queue.pop(screens_only) {
|
||||
return p;
|
||||
}
|
||||
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
@@ -320,14 +371,16 @@ fn workers() -> bool {
|
||||
std::thread::available_parallelism().map_or(2, |n| n.get()),
|
||||
);
|
||||
tracing::info!(workers, "pipeline workers");
|
||||
for i in 0..workers {
|
||||
let screens = if screens_first() { SCREEN_WORKERS } else { 0 };
|
||||
for i in 0..workers + screens {
|
||||
let screens_only = i >= workers;
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(format!("victory-pipelines-{i}"))
|
||||
.spawn(|| {
|
||||
.spawn(move || {
|
||||
// Below the title's own threads (loading, recording),
|
||||
// and the streaming one, which is below normal itself
|
||||
// (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before).
|
||||
let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
|
||||
let lowest = !screens_only && std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
|
||||
// SAFETY: a plain call on our own thread.
|
||||
unsafe {
|
||||
use windows::Win32::System::Threading::*;
|
||||
@@ -335,7 +388,7 @@ fn workers() -> bool {
|
||||
let _ = SetThreadPriority(GetCurrentThread(), priority);
|
||||
}
|
||||
loop {
|
||||
next().make();
|
||||
next(screens_only).make();
|
||||
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
drained();
|
||||
} else {
|
||||
@@ -425,10 +478,28 @@ mod tests {
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &promoted));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier));
|
||||
assert!(queue.pop().is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &earlier));
|
||||
assert!(queue.pop(false).is_none());
|
||||
}
|
||||
|
||||
/// Passes over the screen go before all others, and workers of their own
|
||||
/// take nothing else.
|
||||
#[test]
|
||||
fn passes_over_the_screen_go_first() {
|
||||
let of = |screen| {
|
||||
let mut p = Pending::new(Vec::new(), None);
|
||||
p.screen = screen;
|
||||
Arc::new(p)
|
||||
};
|
||||
let (world, screen) = (of(false), of(true));
|
||||
let mut queue = Queue::new();
|
||||
assert_eq!(queue.push(&world, REQUESTED), Some(true));
|
||||
assert_eq!(queue.push(&screen, REQUESTED), Some(true));
|
||||
assert!(Arc::ptr_eq(&queue.pop(true).unwrap(), &screen));
|
||||
assert!(queue.pop(true).is_none());
|
||||
assert!(Arc::ptr_eq(&queue.pop(false).unwrap(), &world));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Diagnostics: textures that pop. `VICTORY_POP_WATCH=<from>-<to>[,<from>-<to>..]`
|
||||
//! (seconds since the start): every presented frame in those times is read
|
||||
//! back, made small on a thread of its own and compared with its neighbours,
|
||||
//! block by block. Counted and logged:
|
||||
//! - blips: blocks that one frame shows otherwise than the frames before and
|
||||
//! after it, which agree (a texture black, grey or another one for a frame);
|
||||
//! - steps: blocks that change from one frame to the next and stay so, while
|
||||
//! most of the picture does not move;
|
||||
//! - lone blocks: blocks found in neither neighbour, wherever the camera may
|
||||
//! have moved them, while the neighbours' blocks there are found in each
|
||||
//! other (a blip while the camera moves).
|
||||
//!
|
||||
//! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
|
||||
//! blips (at most 200 times) are saved there, 640 wide; with
|
||||
//! `VICTORY_POP_ALL=1` every frame's is.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Mutex, OnceLock, mpsc};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// A small picture: so many pixels wide and high.
|
||||
const WIDE: usize = 640;
|
||||
const HIGH: usize = 360;
|
||||
/// Pixels per side of a block.
|
||||
const BLOCK: usize = 16;
|
||||
/// A block changed: so much in the mean of its pixels' largest channel change.
|
||||
const CHANGED: f32 = 10.0;
|
||||
/// A block stayed.
|
||||
const STAYED: f32 = 4.0;
|
||||
|
||||
/// `10-20,30-40` as seconds.
|
||||
fn parse(text: &str) -> Vec<(f64, f64)> {
|
||||
text.split(',')
|
||||
.filter_map(|part| {
|
||||
let (from, to) = part.trim().split_once('-')?;
|
||||
Some((from.trim().parse().ok()?, to.trim().parse().ok()?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn asked() -> &'static [(f64, f64)] {
|
||||
static ASKED: OnceLock<Vec<(f64, f64)>> = OnceLock::new();
|
||||
ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Whether frames are watched now.
|
||||
pub(crate) fn on() -> bool {
|
||||
let asked = asked();
|
||||
if asked.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let now = crate::host::now_ms() as f64 / 1e3;
|
||||
asked.iter().any(|&(from, to)| now >= from && now < to)
|
||||
}
|
||||
|
||||
/// A frame on its way back.
|
||||
pub(crate) struct Taken {
|
||||
buffer: ID3D12Resource,
|
||||
footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
frame: u64,
|
||||
taken: Taken,
|
||||
/// The submission that copies it.
|
||||
flown: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: usize,
|
||||
}
|
||||
|
||||
/// Read-back buffers not in use.
|
||||
static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
|
||||
/// How far a block is looked for in a neighbour's picture, in pixels of half
|
||||
/// the small picture's size, and the side of a block there.
|
||||
const REACH: i32 = 14;
|
||||
const HALF_BLOCK: usize = BLOCK / 2;
|
||||
|
||||
/// A small picture at half its size, as brightness and two colour differences.
|
||||
fn half(rgb: &[u8]) -> Vec<[i16; 3]> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let mut out = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut s = [0i16; 3];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let at = ((y * 2 + dy) * WIDE + x * 2 + dx) * 3;
|
||||
for (s, v) in s.iter_mut().zip(&rgb[at..at + 3]) {
|
||||
*s += i16::from(*v);
|
||||
}
|
||||
}
|
||||
out.push(s.map(|s| s / 4));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Per block of `a`: how much it differs from the place in `b` that is most
|
||||
/// like it, as [`differ`] says it.
|
||||
fn moved(a: &[[i16; 3]], b: &[[i16; 3]]) -> Vec<f32> {
|
||||
let (w, h) = (WIDE / 2, HIGH / 2);
|
||||
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
|
||||
let mut out = vec![f32::MAX; across * down];
|
||||
for (n, best) in out.iter_mut().enumerate() {
|
||||
let (bx, by) = (n % across * HALF_BLOCK, n / across * HALF_BLOCK);
|
||||
let mut least = u32::MAX;
|
||||
for dy in -REACH..=REACH {
|
||||
let y0 = by as i32 + dy;
|
||||
if y0 < 0 || y0 as usize + HALF_BLOCK > h {
|
||||
continue;
|
||||
}
|
||||
for dx in -REACH..=REACH {
|
||||
let x0 = bx as i32 + dx;
|
||||
if x0 < 0 || x0 as usize + HALF_BLOCK > w {
|
||||
continue;
|
||||
}
|
||||
let mut sum = 0u32;
|
||||
for row in 0..HALF_BLOCK {
|
||||
let ra = &a[(by + row) * w + bx..][..HALF_BLOCK];
|
||||
let rb = &b[(y0 as usize + row) * w + x0 as usize..][..HALF_BLOCK];
|
||||
sum += ra
|
||||
.iter()
|
||||
.zip(rb)
|
||||
.map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0) as u32)
|
||||
.sum::<u32>();
|
||||
if sum >= least {
|
||||
break;
|
||||
}
|
||||
}
|
||||
least = least.min(sum);
|
||||
}
|
||||
}
|
||||
*best = least as f32 / (HALF_BLOCK * HALF_BLOCK) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Blocks of `now` found in neither neighbour, where `before` is found in
|
||||
/// `after`.
|
||||
fn lone(before: &[[i16; 3]], now: &[[i16; 3]], after: &[[i16; 3]]) -> Vec<usize> {
|
||||
let (one, two) = (moved(now, before), moved(now, after));
|
||||
let both = moved(before, after);
|
||||
// A cut on either side is none.
|
||||
if one.iter().filter(|&&d| d > CHANGED).count() * 4 > one.len()
|
||||
|| two.iter().filter(|&&d| d > CHANGED).count() * 4 > two.len()
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] > CHANGED && both[n] < CHANGED / 2.0).collect()
|
||||
}
|
||||
|
||||
/// Frames on their way.
|
||||
static WAITING: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Records the read-back of `texture` (in the copy-source state).
|
||||
pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option<Taken> {
|
||||
if !on() || WAITING.load(Relaxed) > 8 {
|
||||
return None;
|
||||
}
|
||||
let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop();
|
||||
let Some(taken) = free else {
|
||||
let (buffer, footprint) = crate::capture::read_back(device, list, texture)?;
|
||||
return Some(Taken { buffer, footprint });
|
||||
};
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(&taken.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
// SAFETY: an open list, live resources.
|
||||
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
Some(taken)
|
||||
}
|
||||
|
||||
/// The list with `taken` went to the card as submission `flown` (0: it has
|
||||
/// run). `frame`: the frame it shows.
|
||||
pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
|
||||
static THREAD: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
|
||||
let Some(to) = THREAD.get_or_init(|| {
|
||||
let (to, from) = mpsc::channel::<Job>();
|
||||
std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
WAITING.fetch_add(1, Relaxed);
|
||||
let job = Job {
|
||||
frame,
|
||||
taken,
|
||||
flown,
|
||||
ms: crate::host::now_ms(),
|
||||
causes: crate::descriptor::host::pop_causes(),
|
||||
phase: usize::from(crate::ab::pick("VICTORY_KEEP_SHOWN").unwrap_or(false))
|
||||
+ 2 * usize::from(crate::ab::pick("VICTORY_UPLOAD_AHEAD").unwrap_or(false)),
|
||||
};
|
||||
let _ = to.send(job);
|
||||
}
|
||||
|
||||
/// What was seen of the frames so far.
|
||||
#[derive(Default)]
|
||||
struct Seen {
|
||||
frames: u64,
|
||||
blips: u64,
|
||||
blip_frames: u64,
|
||||
steps: u64,
|
||||
still: u64,
|
||||
lone: u64,
|
||||
lone_frames: u64,
|
||||
}
|
||||
|
||||
struct Picture {
|
||||
frame: u64,
|
||||
ms: u64,
|
||||
causes: [u64; 4],
|
||||
phase: usize,
|
||||
rgb: Vec<u8>,
|
||||
half: Vec<[i16; 3]>,
|
||||
/// Per block: how much it differs from the frame before.
|
||||
changed: Vec<f32>,
|
||||
saved: bool,
|
||||
}
|
||||
|
||||
/// Per block, the mean of the pixels' largest channel change.
|
||||
fn differ(a: &[u8], b: &[u8]) -> Vec<f32> {
|
||||
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
|
||||
let mut out = vec![0.0; across * down];
|
||||
for (n, sum) in out.iter_mut().enumerate() {
|
||||
let (bx, by) = (n % across * BLOCK, n / across * BLOCK);
|
||||
let mut total = 0u32;
|
||||
for y in by..by + BLOCK {
|
||||
let at = (y * WIDE + bx) * 3;
|
||||
let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]);
|
||||
total += ra
|
||||
.chunks_exact(3)
|
||||
.zip(rb.chunks_exact(3))
|
||||
.map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0))
|
||||
.sum::<u32>();
|
||||
}
|
||||
*sum = total as f32 / (BLOCK * BLOCK) as f32;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The blips of `now` between `before` and `after`, and its steps (the frame
|
||||
/// before `before` had `quiet` changes): numbers of blocks. `None` for the
|
||||
/// steps if the picture moves.
|
||||
fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option<usize>) {
|
||||
let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after));
|
||||
let blips = (0..one.len())
|
||||
.filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n])
|
||||
.count();
|
||||
let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7;
|
||||
let steps = still.then(|| {
|
||||
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count()
|
||||
});
|
||||
(blips, steps)
|
||||
}
|
||||
|
||||
/// `width * height` 8-bit RGBA (or BGRA) pixels made small.
|
||||
fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(WIDE * HIGH * 3);
|
||||
for y in 0..HIGH {
|
||||
for x in 0..WIDE {
|
||||
let mut sum = [0u32; 3];
|
||||
for sy in 0..3 {
|
||||
for sx in 0..3 {
|
||||
let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6);
|
||||
let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6);
|
||||
let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3];
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += u32::from(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let c = sum.map(|s| (s / 9) as u8);
|
||||
out.extend(if bgra { [c[2], c[1], c[0]] } else { c });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn folder() -> Option<&'static PathBuf> {
|
||||
static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
FOLDER
|
||||
.get_or_init(|| {
|
||||
let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?);
|
||||
std::fs::create_dir_all(&folder).ok()?;
|
||||
Some(folder)
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn save(p: &mut Picture) {
|
||||
if p.saved {
|
||||
return;
|
||||
}
|
||||
p.saved = true;
|
||||
if let Some(folder) = folder() {
|
||||
let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb);
|
||||
let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png);
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(from: &mpsc::Receiver<Job>) {
|
||||
let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
|
||||
let mut last: VecDeque<Picture> = VecDeque::new();
|
||||
let mut seen: [Seen; 4] = Default::default();
|
||||
let mut told = crate::host::now_ms();
|
||||
let mut sets = 0;
|
||||
while let Ok(job) = from.recv() {
|
||||
while crate::host::submissions().1 < job.flown {
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
let f = job.taken.footprint.Footprint;
|
||||
let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91));
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: the copy has run; the mapping spans the footprint's rows.
|
||||
let rgb = unsafe {
|
||||
if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() {
|
||||
WAITING.fetch_sub(1, Relaxed);
|
||||
continue;
|
||||
}
|
||||
let rows = std::slice::from_raw_parts(data.cast::<u8>(), f.RowPitch as usize * f.Height as usize);
|
||||
let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra);
|
||||
job.taken.buffer.Unmap(0, None);
|
||||
rgb
|
||||
};
|
||||
FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken);
|
||||
WAITING.fetch_sub(1, Relaxed);
|
||||
// Frames that follow each other only.
|
||||
if last.back().is_some_and(|p| p.frame + 1 != job.frame) {
|
||||
last.clear();
|
||||
}
|
||||
let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
|
||||
let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
|
||||
let half = half(&rgb);
|
||||
last.push_back(Picture { frame, ms, causes, phase, rgb, half, changed, saved: false });
|
||||
if all && let Some(p) = last.back_mut() {
|
||||
save(p);
|
||||
}
|
||||
if last.len() > 4 {
|
||||
last.pop_front();
|
||||
}
|
||||
if let [first, before, now, after] = last.make_contiguous() {
|
||||
let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
|
||||
let side = &mut seen[now.phase];
|
||||
side.frames += 1;
|
||||
side.blips += blips as u64;
|
||||
side.blip_frames += u64::from(blips > 0);
|
||||
side.still += u64::from(steps.is_some());
|
||||
side.steps += steps.unwrap_or(0) as u64;
|
||||
let lone = lone(&before.half, &now.half, &after.half);
|
||||
side.lone += lone.len() as u64;
|
||||
side.lone_frames += u64::from(!lone.is_empty());
|
||||
if blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 0) {
|
||||
let since: Vec<u64> = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect();
|
||||
tracing::info!(
|
||||
"pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps, lone blocks {lone:?}; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
|
||||
now.frame,
|
||||
now.ms as f64 / 1e3
|
||||
);
|
||||
}
|
||||
if (blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 2)) && sets < 200 {
|
||||
sets += 1;
|
||||
save(before);
|
||||
save(now);
|
||||
save(after);
|
||||
}
|
||||
}
|
||||
if crate::host::now_ms().saturating_sub(told) > 5000 {
|
||||
told = crate::host::now_ms();
|
||||
for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
|
||||
tracing::info!(
|
||||
"pop watch, since the start, A/B VICTORY_KEEP_SHOWN {} VICTORY_UPLOAD_AHEAD {}: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped, lone blocks in {} frames ({} blocks)",
|
||||
n & 1,
|
||||
n >> 1,
|
||||
s.frames,
|
||||
s.blip_frames,
|
||||
s.blips,
|
||||
s.still,
|
||||
s.steps,
|
||||
s.lone_frames,
|
||||
s.lone
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn picture(color: u8) -> Vec<u8> {
|
||||
vec![color; WIDE * HIGH * 3]
|
||||
}
|
||||
|
||||
fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) {
|
||||
for y in by * BLOCK..(by + 1) * BLOCK {
|
||||
let at = (y * WIDE + bx * BLOCK) * 3;
|
||||
p[at..at + BLOCK * 3].fill(color);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() {
|
||||
let (a, mut b) = (picture(100), picture(100));
|
||||
patch(&mut b, 3, 4, 0);
|
||||
let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)];
|
||||
assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0)));
|
||||
assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1)));
|
||||
assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0)));
|
||||
// All of it changes: a cut, no step.
|
||||
assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None));
|
||||
// What moved just before is no step either.
|
||||
assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_one_frame_alone_shows_is_found_while_the_camera_moves() {
|
||||
// A picture of noise, moved by 6 pixels a frame.
|
||||
let at = |shift: usize| -> Vec<u8> {
|
||||
(0..HIGH)
|
||||
.flat_map(|y| (0..WIDE).map(move |x| ((x + shift) / 8 * 37 + y / 8 * 91) as u8))
|
||||
.flat_map(|v| [v, v.wrapping_mul(3), 255 - v])
|
||||
.collect()
|
||||
};
|
||||
let (a, mut b, c) = (at(0), at(8), at(16));
|
||||
assert!(lone(&half(&a), &half(&b), &half(&c)).is_empty());
|
||||
patch(&mut b, 20, 10, 128);
|
||||
assert_eq!(lone(&half(&a), &half(&b), &half(&c)), vec![10 * (WIDE / BLOCK) + 20]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn times_are_read_and_pictures_made_small() {
|
||||
assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
|
||||
assert!(parse("x").is_empty());
|
||||
let rows: Vec<u8> = [1u8, 2, 3, 255].repeat(1280 * 720);
|
||||
let out = small(&rows, 1280, 720, 1280 * 4, true);
|
||||
assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..]));
|
||||
}
|
||||
}
|
||||
@@ -1177,6 +1177,8 @@ pub(crate) struct HostTexture {
|
||||
pub(crate) grown: std::sync::atomic::AtomicBool,
|
||||
/// What the last submitted upload put in it.
|
||||
pub(crate) holds: std::sync::Arc<Holds>,
|
||||
/// Who makes its first upload (`crate::texture::ahead`).
|
||||
pub(crate) ahead: std::sync::atomic::AtomicU8,
|
||||
/// The texture's flags (asked once: the runtime takes 100 ns to say, and
|
||||
/// every texture of every draw is asked about).
|
||||
flags: u32,
|
||||
@@ -2295,6 +2297,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2319,6 +2322,7 @@ impl HostTexture {
|
||||
serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
|
||||
grown: Default::default(),
|
||||
holds: Default::default(),
|
||||
ahead: crate::texture::ahead::fresh(),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
@@ -2968,6 +2972,13 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
|
||||
Some(*found as This)
|
||||
}
|
||||
|
||||
/// From which level on the title texture's host copy was filled, and from
|
||||
/// which bytes (diagnostics).
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> {
|
||||
*made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// The resource for a texture placed at `address` with the resource
|
||||
/// description `desc` (as words), made on first use.
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
//! (directly indexed views are not known per draw); plane 0 is uploaded
|
||||
//! (every mip and array slice), depth and stencil planes are not.
|
||||
|
||||
pub(crate) mod ahead;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -745,6 +747,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
|
||||
return;
|
||||
};
|
||||
let texture = ©.texture;
|
||||
ahead::listed(©);
|
||||
let Some(staging) = staging(resource, ©, first) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
//! First uploads of textures picked by index on a copy queue of their own
|
||||
//! (`VICTORY_UPLOAD_AHEAD`): read, detiled and copied by threads of ours as
|
||||
//! soon as the texture pass has made them, and the slots that wait for them
|
||||
//! shown when the copy has run. Recorded into the pass's list, as every other
|
||||
//! upload is, the copy ran with the frame that needs it, so a slot that shows
|
||||
//! its texture only after its upload ([`crate::descriptor::host::show_after`])
|
||||
//! was black or grey in that frame, and in the next.
|
||||
//!
|
||||
//! Only a texture that no list has used is taken: made in the last second,
|
||||
//! in the common state, and never asked for an upload before
|
||||
//! ([`crate::resource::HostTexture::ahead`]). It stays in the common state
|
||||
//! (a copy queue's copies leave it there), from which the card's shaders read
|
||||
//! it as any texture.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::Interface;
|
||||
|
||||
use super::Staging;
|
||||
use crate::object::This;
|
||||
use crate::resource::HostTexture;
|
||||
|
||||
/// [`HostTexture::ahead`]: no upload was asked for yet; one is on its way
|
||||
/// here; it has run; one was recorded into a list.
|
||||
pub(crate) const NONE: u8 = 0;
|
||||
const PENDING: u8 = 1;
|
||||
const DONE: u8 = 2;
|
||||
pub(crate) const LISTED: u8 = 3;
|
||||
|
||||
/// Bytes of title memory on their way at most: past it uploads go into the
|
||||
/// lists, as before.
|
||||
const MOST: u64 = 96 << 20;
|
||||
/// Bytes and textures of one submission at most.
|
||||
const BATCH: (u64, usize) = (16 << 20, 64);
|
||||
|
||||
/// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off).
|
||||
pub(crate) fn on() -> bool {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(on) = crate::ab::pick("VICTORY_UPLOAD_AHEAD") {
|
||||
return on;
|
||||
}
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_AHEAD").is_some_and(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// An upload on its way.
|
||||
pub(crate) struct Job {
|
||||
staging: Arc<Staging>,
|
||||
copy: Arc<HostTexture>,
|
||||
asked: std::time::Instant,
|
||||
/// What to do when it has run; `None`: it has.
|
||||
then: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// Calls `f` when the copy has run: now if it has.
|
||||
pub(crate) fn then(&self, f: impl FnOnce() + Send + 'static) {
|
||||
let mut then = self.then.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match then.as_mut() {
|
||||
Some(then) => then.push(Box::new(f)),
|
||||
None => {
|
||||
drop(then);
|
||||
f();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a texture asked for here gets.
|
||||
pub(crate) enum Taken {
|
||||
/// A job of its own, to be [`send`] once what follows it is added.
|
||||
New(Arc<Job>),
|
||||
/// One already on its way, or that has run.
|
||||
Known(Arc<Job>),
|
||||
}
|
||||
|
||||
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
|
||||
/// Those on their way, by host copy ([`HostTexture::serial`]).
|
||||
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
|
||||
static LANDED: Condvar = Condvar::new();
|
||||
static BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// Since the start: uploads, bytes, microseconds from the asking until the
|
||||
/// copy had run, the longest; askings turned down; waits of lists.
|
||||
static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
|
||||
|
||||
/// Takes the first upload of `resource`'s levels from `first` on, `there` of
|
||||
/// whose bytes are mapped (`u64::MAX`: not known). `None`: the list's.
|
||||
pub(crate) fn take(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
if on() { claim(resource, first, there) } else { None }
|
||||
}
|
||||
|
||||
fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
|
||||
workers()?;
|
||||
let turned_down = || {
|
||||
STATS[4].fetch_add(1, Relaxed);
|
||||
None
|
||||
};
|
||||
let copy = crate::resource::host_copy(resource)?;
|
||||
if copy.ahead.load(Relaxed) == PENDING {
|
||||
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
|
||||
}
|
||||
if BYTES.load(Relaxed) >= MOST
|
||||
|| copy.flags() & 0x7 != 0
|
||||
|| copy.state.load(Relaxed) != 0
|
||||
|| copy.grown.load(Relaxed)
|
||||
|| copy.tiled.is_some()
|
||||
|| copy.holds.lock().unwrap_or_else(|e| e.into_inner()).is_some()
|
||||
|| !crate::pool::fresh(©.texture)
|
||||
|| super::host_wrote(resource as usize)
|
||||
|| crate::resource::alias_of(resource).is_some()
|
||||
{
|
||||
return turned_down();
|
||||
}
|
||||
if copy.ahead.compare_exchange(NONE, PENDING, Relaxed, Relaxed).is_err() {
|
||||
return turned_down();
|
||||
}
|
||||
super::PICKING.set(Some(there));
|
||||
let staging = super::staging(resource, ©, first);
|
||||
super::PICKING.set(None);
|
||||
let Some(staging) = staging.filter(|s| {
|
||||
!s.on_demand && s.first == s.level0 && !s.uploaded.load(Relaxed) && s.once.load(Relaxed)
|
||||
}) else {
|
||||
copy.ahead.store(LISTED, Relaxed);
|
||||
return turned_down();
|
||||
};
|
||||
if super::no_wait() && super::fill_unlocked() {
|
||||
staging.expected.store(if there == u64::MAX { super::mapped_bytes(staging.memory, staging.read) } else { there }, Relaxed);
|
||||
}
|
||||
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
|
||||
BYTES.fetch_add(job.staging.read as u64, Relaxed);
|
||||
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
|
||||
Some(Taken::New(job))
|
||||
}
|
||||
|
||||
/// Sends a job of [`take`] on its way.
|
||||
pub(crate) fn send(job: &Arc<Job>) {
|
||||
QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()).push_back(job.clone());
|
||||
QUEUE.1.notify_one();
|
||||
}
|
||||
|
||||
/// A list is about to record an upload into `copy`: one on its way here runs
|
||||
/// first, and no other is taken after it.
|
||||
pub(crate) fn listed(copy: &HostTexture) {
|
||||
if copy.ahead.compare_exchange(NONE, LISTED, Relaxed, Relaxed) != Err(PENDING) {
|
||||
return;
|
||||
}
|
||||
STATS[5].fetch_add(1, Relaxed);
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let started = std::time::Instant::now();
|
||||
while way.iter().any(|(serial, _)| *serial == copy.serial) && started.elapsed().as_millis() < 1000 {
|
||||
way = LANDED.wait_timeout(way, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy queue and its threads, made on first use.
|
||||
fn workers() -> Option<&'static ID3D12CommandQueue> {
|
||||
/// Free-threaded.
|
||||
struct Queue(ID3D12CommandQueue);
|
||||
// SAFETY: a command queue is free-threaded.
|
||||
unsafe impl Send for Queue {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Queue {}
|
||||
static WORKERS: OnceLock<Option<Queue>> = OnceLock::new();
|
||||
WORKERS
|
||||
.get_or_init(|| {
|
||||
let host = crate::host::host()?;
|
||||
// SAFETY: plain object creation.
|
||||
let queue: ID3D12CommandQueue = unsafe {
|
||||
host.device
|
||||
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
||||
Type: D3D12_COMMAND_LIST_TYPE_COPY,
|
||||
..Default::default()
|
||||
})
|
||||
.ok()?
|
||||
};
|
||||
for n in 0..2 {
|
||||
let worker = Worker::new(&host.device, queue.clone()).ok()?;
|
||||
std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?;
|
||||
}
|
||||
Some(Queue(queue))
|
||||
})
|
||||
.as_ref()
|
||||
.map(|q| &q.0)
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
queue: ID3D12CommandQueue,
|
||||
allocator: ID3D12CommandAllocator,
|
||||
list: ID3D12GraphicsCommandList,
|
||||
fence: ID3D12Fence,
|
||||
}
|
||||
|
||||
// SAFETY: a worker's objects are its thread's own; the queue is free-threaded.
|
||||
unsafe impl Send for Worker {}
|
||||
|
||||
impl Worker {
|
||||
fn new(device: &ID3D12Device, queue: ID3D12CommandQueue) -> windows::core::Result<Worker> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
|
||||
let list: ID3D12GraphicsCommandList =
|
||||
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
|
||||
list.Close()?;
|
||||
Ok(Worker { queue, allocator, list, fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? })
|
||||
}
|
||||
}
|
||||
|
||||
fn work(self) {
|
||||
let mut value = 0;
|
||||
loop {
|
||||
let mut jobs = Vec::new();
|
||||
{
|
||||
let mut queue = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while queue.is_empty() {
|
||||
queue = QUEUE.1.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
let mut bytes = 0;
|
||||
while bytes < BATCH.0 && jobs.len() < BATCH.1
|
||||
&& let Some(job) = queue.pop_front()
|
||||
{
|
||||
bytes += job.staging.read as u64;
|
||||
jobs.push(job);
|
||||
}
|
||||
}
|
||||
value += 1;
|
||||
if let Err(e) = self.copy(&jobs, value) {
|
||||
tracing::warn!(error = %e, "uploads ahead did not run");
|
||||
}
|
||||
finish(jobs);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy(&self, jobs: &[Arc<Job>], value: u64) -> windows::core::Result<()> {
|
||||
for job in jobs {
|
||||
job.staging.refresh();
|
||||
}
|
||||
// SAFETY: this worker's allocator and list, whose last submission has
|
||||
// run; the jobs hold what the list names until after the wait.
|
||||
unsafe {
|
||||
self.allocator.Reset()?;
|
||||
self.list.Reset(&self.allocator, None)?;
|
||||
for job in jobs {
|
||||
job.record(&self.list);
|
||||
}
|
||||
self.list.Close()?;
|
||||
self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
|
||||
self.queue.Signal(&self.fence, value)?;
|
||||
// (Without an event: this waits.)
|
||||
self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// # Safety
|
||||
/// `list` is an open copy list, and the job lives until it has run.
|
||||
unsafe fn record(&self, list: &ID3D12GraphicsCommandList) {
|
||||
let (s, texture) = (&self.staging, &self.copy.texture);
|
||||
for (i, footprint) in s.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: s.first - s.level0 + i as u32 },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(&s.buffer) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
||||
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint },
|
||||
},
|
||||
};
|
||||
// SAFETY: the caller's.
|
||||
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The jobs' copies have run.
|
||||
fn finish(jobs: Vec<Arc<Job>>) {
|
||||
for job in &jobs {
|
||||
job.staging.uploaded.store(true, Relaxed);
|
||||
job.staging.dirty.store(false, Relaxed);
|
||||
job.staging.note_held();
|
||||
job.copy.ahead.store(DONE, Relaxed);
|
||||
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
|
||||
}
|
||||
{
|
||||
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
|
||||
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
|
||||
LANDED.notify_all();
|
||||
}
|
||||
for job in &jobs {
|
||||
let us = job.asked.elapsed().as_micros() as u64;
|
||||
let n = STATS[0].fetch_add(1, Relaxed) + 1;
|
||||
let bytes = STATS[1].fetch_add(job.staging.read as u64, Relaxed) + job.staging.read as u64;
|
||||
let all = STATS[2].fetch_add(us, Relaxed) + us;
|
||||
let most = STATS[3].fetch_max(us, Relaxed).max(us);
|
||||
if n == 1 || n.is_multiple_of(5000) {
|
||||
tracing::info!(
|
||||
"textures uploaded ahead of the lists (VICTORY_UPLOAD_AHEAD=1), since the start: {n}, {} MB, {:.1} ms from the asking until they were there, the longest {:.0}; {} turned down, {} waited for by lists",
|
||||
bytes >> 20,
|
||||
all as f64 / n as f64 / 1e3,
|
||||
most as f64 / 1e3,
|
||||
STATS[4].load(Relaxed),
|
||||
STATS[5].load(Relaxed)
|
||||
);
|
||||
}
|
||||
let then = job.then.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
for f in then.into_iter().flatten() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
crate::descriptor::host::flip_now();
|
||||
}
|
||||
|
||||
/// Whether `resource`'s host copy was filled here: no list still brings what
|
||||
/// it shows.
|
||||
pub(crate) fn there(resource: This) -> bool {
|
||||
crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE)
|
||||
}
|
||||
|
||||
/// The state of [`HostTexture::ahead`] of a new host copy.
|
||||
pub(crate) fn fresh() -> AtomicU8 {
|
||||
AtomicU8::new(NONE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The texels of a placed texture arrive by the copy queue, all levels of
|
||||
/// them, and what waits for them is called then; a second asking finds the
|
||||
/// first on its way, and a later one is the list's.
|
||||
#[test]
|
||||
fn a_placed_texture_is_filled_ahead_of_the_lists() {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
// 256x256 BC7, nine levels.
|
||||
let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
|
||||
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
|
||||
// SAFETY: memory of our own that stays.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
|
||||
// SAFETY: as above.
|
||||
unsafe { (0..whole).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8)) };
|
||||
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
|
||||
crate::resource::want_level(texture, 0);
|
||||
let copy = crate::resource::host_copy(texture).unwrap();
|
||||
if !crate::pool::fresh(©.texture) {
|
||||
return;
|
||||
}
|
||||
assert!(!there(texture));
|
||||
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
|
||||
let (told, heard) = std::sync::mpsc::channel();
|
||||
let also = told.clone();
|
||||
let Some(Taken::Known(same)) = claim(texture, 0, u64::MAX) else { panic!("not known") };
|
||||
assert!(Arc::ptr_eq(&job, &same));
|
||||
job.then(move || told.send(1).unwrap());
|
||||
same.then(move || also.send(2).unwrap());
|
||||
send(&job);
|
||||
let wait = std::time::Duration::from_secs(20);
|
||||
assert_eq!((heard.recv_timeout(wait), heard.recv_timeout(wait)), (Ok(1), Ok(2)));
|
||||
assert!(there(texture) && claim(texture, 0, u64::MAX).is_none());
|
||||
// Level 0 as the card has it, and as the layout says.
|
||||
let layout = crate::resource::texture_memory(texture)
|
||||
.and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone()))
|
||||
.unwrap();
|
||||
let (pitch, rows) = (1024usize, 64usize);
|
||||
let mut expected = vec![0u8; pitch * rows];
|
||||
// SAFETY: the memory above.
|
||||
let tiled = unsafe { std::slice::from_raw_parts(at, whole) };
|
||||
layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap();
|
||||
let back = host.read_back_buffer((pitch * rows) as u64).unwrap();
|
||||
let list = host.new_list().unwrap();
|
||||
list.close();
|
||||
list.reset();
|
||||
let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
|
||||
Offset: 0,
|
||||
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
|
||||
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98),
|
||||
Width: 256,
|
||||
Height: 256,
|
||||
Depth: 1,
|
||||
RowPitch: pitch as u32,
|
||||
},
|
||||
};
|
||||
let to = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: a borrowed pointer the location never releases.
|
||||
pResource: unsafe { std::mem::transmute_copy(&back) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
|
||||
};
|
||||
let from = D3D12_TEXTURE_COPY_LOCATION {
|
||||
// SAFETY: as above.
|
||||
pResource: unsafe { std::mem::transmute_copy(©.texture) },
|
||||
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
||||
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
|
||||
};
|
||||
// SAFETY: an open list, live resources; the mapping spans the buffer.
|
||||
unsafe {
|
||||
list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
|
||||
list.close();
|
||||
host.execute(&[&list]);
|
||||
let mut data = std::ptr::null_mut();
|
||||
back.Map(0, None, Some(&mut data)).unwrap();
|
||||
let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows);
|
||||
assert!(seen == expected.as_slice(), "level 0's blocks");
|
||||
back.Unmap(0, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user