VICTORY_PRELUDE_UPLOADS=1: title textures uploaded on the list's prelude, decided at submission after the check (off)

Ported from Belobug/VIctory-Belobug-AMD 5d6bd84 ("Upload title textures in
submission prelude to fix frame-order & flickering"), where it is the only
way. A list records the upload of a title texture it samples only if the
staging buffer was changed when the list was recorded; the check at
submission may then find the memory changed and detile it, and only the
next list that samples the texture uploads that: a frame late when every
list of the frame was recorded before the check (a video's ring of buffers
shows an older picture, a texture streamed in its last one). A candidate of
the flicker at scene loads (analysis 6.12).

With the switch, `texture::upload_from` records nothing in the list: it
leaves a `PreludeUpload` (staging buffer, host copy, levels on demand) with
the list, and its `Step::Texture` as before, so the checks run where they
ran. At submission, after the list's steps, the staging buffers left pending
are refreshed (`Batch::refresh_textures`), and each texture whose host copy
was never uploaded or whose staging buffer was detiled since its last upload
is claimed (`claim_upload`; once per change, whichever lists of the
submission sample it) and copied on the list's prelude (`HostList::prelude`):
aliasing barrier for a pooled texture's first upload, to the copy
destination state and from there to the state the list starts with. What
the list's own upload did after the copy (a host copy grown, levels on
demand given memory, what the host copy holds) is done at the claim.

Kept as before: bakes (they record their copies whatever the check finds)
and movie planes. Left out of the port: the texture store's prefill (this
tree has none), the fork's refreshes before every copy and run step (here
`title_written` flushes the textures due already), the fork's change of
`Step::Texture`'s payload (the upload is held beside it instead, so the steps'
other readers, `card_steps` and `place`, are untouched), and its panel
change (unrelated).

Off by default (not behaviour-neutral: when textures are uploaded changes).
Tests (from the fork): a claim per change, in the same submission; a ring of
three buffers never shows an older picture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
readmet3xt-labandClaude Opus 5.5 committed 2026-11-27 01:08:54 +05:30
1 parent ee3fb5201a
commit 91df493ead
3 files changed
+272 -4

No files matched your search

+77 -4
View File
@@ -2333,6 +2333,9 @@ struct Deferred {
uploads: Vec<ID3D12Resource>,
/// Standalone upload footprints kept through this list's fence (movie planes).
plane_uploads: Vec<(Chunk, u64)>,
/// Title textures whose upload the list's prelude records if the check at
/// submission finds it due (`crate::texture::prelude_uploads`).
prelude_uploads: Vec<crate::texture::PreludeUpload>,
/// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
upload_bytes: u64,
/// Host objects the list's commands name (pipelines, root signatures,
@@ -5757,7 +5760,9 @@ impl Host {
for list in runs {
list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
firsts.push(lists.len());
if let Some(prelude) = list.prelude() {
// (None unless `VICTORY_PRELUDE_UPLOADS=1`.)
let uploads = list.prelude_uploads(&mut batch);
if let Some(prelude) = list.prelude(&uploads) {
lists.push(Some(prelude));
}
lists.push(list.list.cast().ok());
@@ -6819,8 +6824,12 @@ impl HostList {
/// its real state to the one the list starts with; the textures' real
/// states become those the list ends with. For depth textures with a
/// colour twin it first copies the side the list uses as it finds it
/// from the other, if a list submitted earlier left it behind.
fn prelude(&self) -> Option<ID3D12CommandList> {
/// from the other, if a list submitted earlier left it behind. Title
/// textures whose upload is decided at submission (`uploads`,
/// `crate::texture::prelude_uploads`) are copied into their host copies
/// here, right before the list runs (Belobug/VIctory-Belobug-AMD
/// 5d6bd84).
fn prelude(&self, uploads: &[(crate::texture::PreludeUpload, bool)]) -> Option<ID3D12CommandList> {
const COPY_DEST: u32 = 0x400;
const COPY_SOURCE: u32 = 0x800;
let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32);
@@ -6875,13 +6884,45 @@ impl HostList {
}
}
}
// The uploads decided at submission: each host copy to the copy
// destination state, and from there to the state the list starts
// with (back to its real state if the list does not use it).
let mut aliasing = Vec::new();
for (upload, first_upload) in uploads {
let copy = &upload.copy;
let key = std::sync::Arc::as_ptr(copy) as usize;
// A texture cut from a block may lie where another did: what the
// card holds of that one is done with before the first upload
// into this one.
if crate::pool::on() && *first_upload {
aliasing.push(D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(&copy.texture) },
}),
},
});
}
let real = copying.get(&key).copied().unwrap_or_else(|| copy.state.load(Ordering::Relaxed));
if real != COPY_DEST {
to_copy.push(transition(&copy.texture, host_state(real), host_state(COPY_DEST)));
if !states.contains_key(&key) {
barriers.push(transition(&copy.texture, host_state(COPY_DEST), host_state(real)));
}
}
copying.insert(key, COPY_DEST);
}
barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| {
let real = copy.state.swap(*last, Ordering::Relaxed);
let real = copying.get(key).copied().unwrap_or(real);
(real != *first)
.then(|| transition(&copy.texture, host_state(real), host_state(*first)))
}));
if barriers.is_empty() && syncs.is_empty() {
if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() {
return None;
}
let Some((allocator, list)) = self
@@ -6896,12 +6937,18 @@ impl HostList {
let recorded = unsafe {
allocator.Reset().and_then(|()| {
list.Reset(allocator, None)?;
if !aliasing.is_empty() {
list.ResourceBarrier(&aliasing);
}
if !to_copy.is_empty() {
list.ResourceBarrier(&to_copy);
}
for (depth, twin, colour) in &syncs {
record_twin_copy(list, &depth.texture, twin, *colour);
}
for (upload, _) in uploads {
upload.record(list);
}
if !barriers.is_empty() {
list.ResourceBarrier(&barriers);
}
@@ -7476,6 +7523,32 @@ impl HostList {
self.deferred().copies.push(Step::Texture(staging));
}
/// [`HostList::defer_texture`] of a texture whose upload the list's
/// prelude records if the check finds it due
/// (`crate::texture::prelude_uploads`; [`HostList::prelude_uploads`]).
pub(crate) fn defer_prelude_upload(&self, upload: crate::texture::PreludeUpload) {
let mut deferred = self.deferred();
deferred.copies.push(Step::Texture(upload.staging()));
deferred.prelude_uploads.push(upload);
}
/// At submission, after the list's steps: the textures whose upload its
/// prelude records, each with whether it is the first upload into its
/// host copy. Their staging buffers are refreshed first (those the
/// submission's steps left pending). Ported from
/// Belobug/VIctory-Belobug-AMD 5d6bd84.
fn prelude_uploads(&self, batch: &mut Batch) -> Vec<(crate::texture::PreludeUpload, bool)> {
let waiting = self.deferred().prelude_uploads.clone();
if waiting.is_empty() {
return Vec::new();
}
batch.refresh_textures();
waiting
.into_iter()
.filter_map(|upload| upload.finish_refresh().map(|first| (upload, first)))
.collect()
}
/// A copy source owned exclusively by this list until reset after its
/// last execution. A different list can prepare its movie plane concurrently.
pub(crate) fn plane_upload(
+1
View File
@@ -2804,6 +2804,7 @@ pub(crate) fn first_shown(this: This) -> Option<u32> {
/// A host copy made without memory of its own (`crate::tiles`), as a
/// submission-time step of a list holds it.
#[cfg(windows)]
#[derive(Clone)]
pub(crate) struct OnDemand(std::sync::Arc<HostTexture>);
// SAFETY: the host texture is named only in queue calls, which any thread
+194
View File
@@ -857,6 +857,21 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
staging.uploaded.store(true, Relaxed);
return;
}
// With `VICTORY_PRELUDE_UPLOADS=1`: whether to upload is decided when
// the list is submitted, after the check that refreshes the staging
// buffer, and the copy goes on the list's prelude ([`PreludeUpload`]).
if prelude_uploads() && !baking {
if no_wait() && fill_unlocked() {
let there = match picking {
Some(there) if there != u64::MAX => there,
_ => mapped_bytes(staging.memory, staging.read),
};
staging.expected.store(there, Relaxed);
}
let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None };
list.defer_prelude_upload(PreludeUpload { staging, copy, on_demand });
return;
}
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
@@ -922,6 +937,129 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
});
}
/// Whether title textures that lists sample are uploaded on each list's
/// prelude at submission, when the check that refreshes the staging buffer
/// has run, if it changed or was never uploaded (`VICTORY_PRELUDE_UPLOADS=1`;
/// off: the list records the upload when it samples the texture, if the
/// staging buffer was changed then, as before; bakes and movie planes keep
/// that either way).
///
/// Ported from Belobug/VIctory-Belobug-AMD 5d6bd84 ("Upload title textures
/// in submission prelude to fix frame-order & flickering"), where it is the
/// only way. Recorded when the list samples a texture, an upload is left out
/// if the staging buffer held what the host copy holds at that moment; the
/// check at submission may then find the memory changed and detile it, and
/// only the next list that samples the texture uploads that: a frame late
/// when every list of the frame was recorded before the check (a ring of
/// video buffers then shows an old picture, a texture streamed in shows the
/// last one for a frame). Decided at submission, the copy takes what the
/// check found, in the submission that samples it. A candidate of the
/// flicker at scene loads (analysis 6.12).
pub(crate) fn prelude_uploads() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PRELUDE_UPLOADS").is_some_and(|v| v == "1"))
}
/// Whether the prelude of the list being submitted records the upload into
/// a host texture ([`PreludeUpload::finish_refresh`]): `Some(first upload)`
/// when it was never uploaded or its staging buffer was detiled since the
/// last upload; `None` when the host texture holds what the staging buffer
/// holds. (Ported from Belobug/VIctory-Belobug-AMD 5d6bd84.)
fn claim_upload(uploaded: &std::sync::atomic::AtomicBool, dirty: &std::sync::atomic::AtomicBool) -> Option<bool> {
use std::sync::atomic::Ordering::AcqRel;
let was_uploaded = uploaded.swap(true, AcqRel);
let was_dirty = dirty.swap(false, AcqRel);
(!was_uploaded || was_dirty).then_some(!was_uploaded)
}
/// A title texture a list samples, its upload decided at the list's
/// submission ([`prelude_uploads`]): its staging buffer, its host copy (both
/// held by the list until it is reset), and its levels on demand. (Ported
/// from Belobug/VIctory-Belobug-AMD 5d6bd84, without its texture store's
/// prefill, which this tree does not have.)
#[derive(Clone)]
pub(crate) struct PreludeUpload {
staging: Arc<Staging>,
pub(crate) copy: Arc<crate::resource::HostTexture>,
on_demand: Option<crate::resource::OnDemand>,
}
impl PreludeUpload {
/// The staging buffer, for the submission's check (`Step::Texture`).
pub(crate) fn staging(&self) -> Arc<Staging> {
self.staging.clone()
}
/// On the submitting thread, once the check that refreshes the staging
/// buffer has run for this submission: `Some(first upload)` if the
/// list's prelude records the copy into the host texture, with what the
/// list's own upload noted when it was recorded (a host copy grown, the
/// levels on demand given memory, what the host copy holds).
pub(crate) fn finish_refresh(&self) -> Option<bool> {
use std::sync::atomic::Ordering::Relaxed;
let Some(first_upload) = claim_upload(&self.staging.uploaded, &self.staging.dirty) else {
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexSkipped, 1);
return None;
};
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexUploads, 1);
// A host copy that took the place of one with fewer levels: the slots
// that show that one are made again once this upload has run.
if self.staging.first == self.staging.level0 && self.copy.grown.swap(false, Relaxed) {
crate::descriptor::host::levels_changed_after(self.staging.memory as u64);
}
// Levels on demand (`crate::tiles`): the held levels the staging
// buffer holds as the title's are given the card's memory before the
// prelude copies into them; else what the host copy now holds is
// noted.
match &self.on_demand {
Some(on_demand) => {
let waiting = on_demand.uploaded(self.staging.detiled.load(Relaxed), self.staging.memory as u64);
self.staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed);
// A texture picked by index has no staging buffer after this
// upload: its slots are made due again by the texture pass.
if waiting {
crate::descriptor::host::levels_waiting(self.staging.memory as u64);
}
}
None => self.staging.note_held(),
}
Some(first_upload)
}
/// Records the copy of the staging buffer into the host texture on
/// `list` (the prelude), the host texture in the copy destination state.
pub(crate) fn record(&self, list: &ID3D12GraphicsCommandList) {
let texture = &self.copy.texture;
// The staging buffer lives as long as `self.staging`, which the
// list's steps hold until it is reset.
for (i, footprint) in self.staging.footprints.iter().enumerate() {
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: self.staging.first - self.staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&self.staging.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: self.staging.base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
}
fn record_upload(
list: &HostList,
resource: This,
@@ -2226,6 +2364,62 @@ mod title_memory_tests {
}
}
/// [`claim_upload`] (ported from Belobug/VIctory-Belobug-AMD 5d6bd84).
#[cfg(test)]
mod prelude_upload_tests {
use super::claim_upload;
use std::sync::atomic::{AtomicBool, Ordering::Release};
/// The first upload is claimed, a second list of the submission skips,
/// an unchanged texture skips, a changed one is claimed in the same
/// submission, every time it changes.
#[test]
fn first_upload_clean_skip_and_immediate_same_frame_reupload() {
let uploaded = AtomicBool::new(false);
let dirty = AtomicBool::new(true);
assert_eq!(claim_upload(&uploaded, &dirty), Some(true));
assert_eq!(claim_upload(&uploaded, &dirty), None);
assert_eq!(claim_upload(&uploaded, &dirty), None);
dirty.store(true, Release);
assert_eq!(claim_upload(&uploaded, &dirty), Some(false));
dirty.store(true, Release);
assert_eq!(claim_upload(&uploaded, &dirty), Some(false));
}
/// A ring of three buffers written in turn (a video's) never shows a
/// picture older than the one its buffer holds, a held picture
/// included.
#[test]
fn three_buffer_ring_never_displays_stale_frame() {
let ring: [(AtomicBool, AtomicBool); 3] = std::array::from_fn(|_| (AtomicBool::new(false), AtomicBool::new(true)));
let mut shown = [0u32; 3];
let schedule = [
(0, 1, true),
(1, 2, true),
(2, 3, true),
(0, 4, true),
(1, 5, true),
(1, 5, false),
(2, 6, true),
(0, 7, true),
(1, 8, true),
(2, 9, true),
(0, 10, true),
(1, 11, true),
];
for (slot, picture, changed) in schedule {
let (uploaded, dirty) = &ring[slot];
if changed {
dirty.store(true, Release);
}
if claim_upload(uploaded, dirty).is_some() {
shown[slot] = picture;
}
assert_eq!(shown[slot], picture, "slot {slot} shows picture {} instead of {picture}", shown[slot]);
}
}
}
/// How long this PC's card takes to make the allocations a staged texture needs, for
/// `cargo test -p victory-gpu allocation_costs -- --ignored --nocapture`.
#[cfg(test)]