Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ loader that maps the game's executable and resolves its imports to shims. Nothin
- The format or behaviour may already be measured in `docs/design.md`. Quote the file and offset a claim comes from,
or call it a hypothesis.
- Count over the whole corpus, not a sample: a rule that holds for 400 shaders can fail on the other 26 000.
- Frame rates of the D3D12 runtime (`d3d12/`): search [d3d12/docs/findings.md](d3d12/docs/findings.md) for the switch or
function before measuring it, and measure as [docs/measuring_fps.md](docs/measuring_fps.md) says (a switch by turns
inside one run). The variables are listed in [d3d12/docs/switches.md](d3d12/docs/switches.md).

## Test without the game first

Expand Down
182 changes: 170 additions & 12 deletions d3d12/crates/leonida-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1621,11 +1621,153 @@ impl<T> SweepRanges<T> {
}
}

mod heap_sweep;
#[cfg(test)]
mod heap_sweep_tests;

/// The selected backend owns the observed slots for a descriptor heap.
enum SweepState<T> {
Legacy(SweepRanges<T>),
Indexed(heap_sweep::IndexedSweep<T>),
}

impl<T> SweepState<T> {
fn new(indexed: bool) -> Self {
if indexed {
Self::Indexed(Default::default())
} else {
Self::Legacy(Default::default())
}
}

fn clear(&mut self) {
match self {
Self::Legacy(sweep) => sweep.clear(),
Self::Indexed(sweep) => sweep.clear(),
}
}

fn forget_part(&mut self, part: u32) {
match self {
Self::Legacy(sweep) => sweep.forget_part(part),
Self::Indexed(sweep) => sweep.forget_part(part),
}
}

fn set(&mut self, slot: u32, range: Option<Span<T>>) {
match self {
Self::Legacy(sweep) => sweep.set(slot, range),
Self::Indexed(sweep) => sweep.set(slot, range),
}
}

/// At a phase transition, transfer the ranges already observed while the
/// heap's sweep lock is held. The next pass consumes only its usual
/// changed slots. No descriptor is reread and the round stays in step.
#[cfg(any(test, feature = "diagnostics"))]
fn change_backend(&mut self, indexed: bool) {
if matches!(self, Self::Indexed(_)) == indexed {
return;
}
#[cfg(feature = "diagnostics")]
let began = std::time::Instant::now();
let mut next = Self::new(indexed);
match self {
Self::Legacy(sweep) => {
for (slot, range) in sweep.ranges.0.iter_mut().enumerate() {
if let Some(range) = range.take() {
next.set(slot as u32, Some(range));
}
}
}
Self::Indexed(sweep) => sweep.take_slots(|slot, range| next.set(slot, Some(range))),
}
*self = next;
#[cfg(feature = "diagnostics")]
tracing::info!(indexed, ms = began.elapsed().as_secs_f64() * 1000.0, "heap span backend changed for a timing turn");
}

fn snapshot(&mut self) -> SweepSnapshot<'_, T> {
match self {
Self::Legacy(sweep) => {
let (spans, views) = sweep.spans();
SweepSnapshot::Legacy { spans, views }
}
Self::Indexed(sweep) => {
sweep.finish();
SweepSnapshot::Indexed(sweep)
}
}
}
}

/// The older sweep experiment needs the legacy backend in both of its phases.
fn indexed_sweep_allowed(
requested: bool,
legacy_in_ab: impl FnOnce() -> bool,
legacy_enabled: impl FnOnce() -> bool,
) -> bool {
requested && !legacy_in_ab() && legacy_enabled()
}

fn sweep_spans_in_ab() -> bool {
#[cfg(feature = "diagnostics")]
{
crate::ab::bit("LEONIDA_SWEEP_SPANS").is_some()
}
#[cfg(not(feature = "diagnostics"))]
{
false
}
}

impl<T> Default for SweepState<T> {
fn default() -> Self {
static INDEXED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
Self::new(*INDEXED.get_or_init(|| {
let requested = crate::switch::on("LEONIDA_INDEX_HEAP_SPANS");
let indexed = indexed_sweep_allowed(requested, sweep_spans_in_ab, sweep_spans);
if requested {
let backend = if indexed { "indexed" } else { "legacy" };
tracing::info!(backend, "heap buffer span sweep backend selected");
}
indexed
}))
}
}

/// Both paths emit the same span per live copy at the same point in the
/// deferred list. Ordering within this group is unspecified: the legacy
/// snapshot is a hash table and a refresh reads source bytes into its own copy.
enum SweepSnapshot<'a, T> {
Legacy {
spans: crate::host::ByCopy<Span<T>>,
views: u32,
},
Indexed(&'a heap_sweep::IndexedSweep<T>),
}

impl<T> SweepSnapshot<'_, T> {
fn counts(&self) -> (usize, u32) {
match self {
Self::Legacy { spans, views } => (spans.len(), *views),
Self::Indexed(sweep) => (sweep.len(), sweep.views()),
}
}

fn for_each(&self, visit: impl FnMut(&Span<T>)) {
match self {
Self::Legacy { spans, .. } => spans.values().for_each(visit),
Self::Indexed(sweep) => sweep.values().for_each(visit),
}
}
}

/// Descriptor-derived references belong to the heap that produced them.
#[derive(Default)]
pub(crate) struct BufferSweep {
passes: u64,
ranges: SweepRanges<crate::shadow::Shadow>,
ranges: SweepState<crate::shadow::Shadow>,
// Last refresh frame and covered interval for throttled, unwatched copies.
unwatched: std::collections::HashMap<u64, (u64, u64, u64)>,
}
Expand Down Expand Up @@ -2079,6 +2221,10 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
// released resource goes stale without a write, and a slot written
// before its memory had a host copy is only made then.
let mut kept = host.buffer_sweep.lock().unwrap_or_else(|e| e.into_inner());
#[cfg(feature = "diagnostics")]
if let Some(indexed) = crate::ab::pick("LEONIDA_INDEX_HEAP_SPANS") {
kept.ranges.change_backend(indexed_sweep_allowed(indexed, sweep_spans_in_ab, sweep_spans));
}
let changed = host.buffer_changes();
let all = kept.passes == 0 || (kept.passes % HEAP_ROUND == 0 && !heap_spread());
let slots = if all {
Expand Down Expand Up @@ -2172,8 +2318,11 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
#[cfg(feature = "diagnostics")]
let looked = std::time::Instant::now();
// Per host copy, the span its picked views cover ([`sweep_spans`]).
let (spans, views) = kept.ranges.spans();
let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
let BufferSweep {
ranges, unwatched, ..
} = &mut *kept;
let spans = ranges.snapshot();
let (copies, views) = spans.counts();
// Memory that is not write-watched is copied whole by every refresh.
// It was once refreshed only every 120 frames (unmapped pages read
// one by one cost 14 GB a frame in run 11, before they were
Expand All @@ -2183,24 +2332,33 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
// costs some 30 ms a frame this way.
static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let every = *EVERY.get_or_init(|| {
std::env::var("LEONIDA_UNWATCHED_FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(1)
std::env::var("LEONIDA_UNWATCHED_FRAMES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1)
});
let mut found = Vec::with_capacity(spans.len());
let mut found = Vec::with_capacity(copies);
let mut bytes = 0;
let mut next_unwatched = std::collections::HashMap::new();
for (shadow, from, to) in spans.values() {
spans.for_each(|(shadow, from, to)| {
bytes += to - from;
if every > 1 && shadow.unwatched() {
let id = shadow.id();
if let Some(&(last, low, high)) = kept.unwatched.get(&id)
&& frame >= last && frame - last < every && low <= *from && *to <= high
if let Some(&(last, low, high)) = unwatched.get(&id)
&& frame >= last
&& frame - last < every
&& low <= *from
&& *to <= high
{
next_unwatched.insert(id, (last, low, high));
continue;
return;
}
next_unwatched.insert(id, (frame, *from, *to));
}
found.push((shadow.clone(), *from, (*to).min(*from + shadow.left(*from))));
}
kept.unwatched = next_unwatched;
});
drop(spans);
*unwatched = next_unwatched;
drop(kept);
#[cfg(feature = "diagnostics")]
let refreshed = std::time::Instant::now();
Expand All @@ -2217,7 +2375,7 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
tracing::info!(
slots = slots.len(),
views,
copies = spans.len(),
copies,
mb = bytes >> 20,
ms = started.elapsed().as_millis(),
"buffer views of the heap made ready for shaders that pick them by index"
Expand Down
Loading