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
142 changes: 130 additions & 12 deletions d3d12/crates/leonida-gpu/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,21 +566,43 @@ fn record_ahead_split() -> std::thread::Result<Vec<crate::list::Detached>> {
// (as `Ahead` hands it on).
unsafe impl Send for Sent {}
let began = std::time::Instant::now();
let (buffers, textures) = std::thread::scope(|scope| {
let beside = std::thread::Builder::new().name("leonida-ahead-textures".into()).stack_size(8 << 20).spawn_scoped(scope, || {
crate::cores::keep_on_fast_cores("leonida-ahead-textures");
// As the thread it helps: the line waits for it, so it does not wait for the line.
behind::no_drain_here();
catch_unwind(AssertUnwindSafe(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures))))
});
let (buffers, textures) = if ahead_kept_thread() {
// Leonida: the textures' half on the thread kept for it ([`AHEAD_BESIDE`]).
let pending = AHEAD_BESIDE
.get_or_init(|| {
beside::Kept::new("leonida-ahead-textures", || {
crate::cores::keep_on_fast_cores("leonida-ahead-textures");
// As the thread it helps: the line waits for it, so it does not wait for the line.
behind::no_drain_here();
})
.ok()
})
.as_ref()
.and_then(|kept| kept.start(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures))));
let buffers = catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Buffers)));
let textures = match beside {
Ok(thread) => thread.join().and_then(|r| r).map(|sent| sent.0),
// No thread: here, after the buffers.
Err(_) => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))),
let textures = match pending.and_then(|done| done.recv().ok()) {
Some(result) => result.map(|sent| sent.0),
// No kept thread: here, after the buffers.
None => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))),
};
(buffers, textures)
});
} else {
std::thread::scope(|scope| {
let beside = std::thread::Builder::new().name("leonida-ahead-textures".into()).stack_size(8 << 20).spawn_scoped(scope, || {
crate::cores::keep_on_fast_cores("leonida-ahead-textures");
// As the thread it helps: the line waits for it, so it does not wait for the line.
behind::no_drain_here();
catch_unwind(AssertUnwindSafe(|| Sent(crate::list::ahead_of_frame_part(AheadPart::Textures))))
});
let buffers = catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Buffers)));
let textures = match beside {
Ok(thread) => thread.join().and_then(|r| r).map(|sent| sent.0),
// No thread: here, after the buffers.
Err(_) => catch_unwind(AssertUnwindSafe(|| crate::list::ahead_of_frame_part(AheadPart::Textures))),
};
(buffers, textures)
})
};
let lists: Vec<_> = buffers?.into_iter().chain(textures?).collect();
if !lists.is_empty() {
crate::draw::AHEAD_STATS[0].fetch_add(1, Ordering::Relaxed);
Expand All @@ -589,6 +611,102 @@ fn record_ahead_split() -> std::thread::Result<Vec<crate::list::Detached>> {
Ok(lists)
}

/// Leonida: the thread kept for the textures' half of a split list ahead ([`record_ahead_split`]),
/// made at the first split; `None` if it could not be made (each split then records both halves
/// here, one after the other).
#[cfg(windows)]
static AHEAD_BESIDE: std::sync::OnceLock<Option<beside::Kept>> = std::sync::OnceLock::new();

/// Leonida: `LEONIDA_AHEAD_KEPT_THREAD` (on; `0`: off, `LEONIDA_AB` can switch it): the textures'
/// half of a split list ahead ([`crate::draw::ahead_split`]) is recorded by one thread kept for the
/// run ([`AHEAD_BESIDE`]), instead of by a thread made for it each frame. Each of those was a new
/// OS thread with an 8 MiB stack, a choice of the fast cores for it and a line in the log, on the
/// path of the line's thread, which waits for that half: 14,271 such lines in some 2.5 minutes of
/// play on an RTX 4070 Laptop with a Core Ultra 7 155H (2026-12-01). There, with `LEONIDA_AB`
/// turning it every 10 s (18 steady phases a side), the line's thread stood 2.5 ms a frame for the
/// list ahead with it, 5.2 ms without.
#[cfg(windows)]
fn ahead_kept_thread() -> bool {
crate::toggled!("LEONIDA_AHEAD_KEPT_THREAD")
}

/// Leonida: a thread kept for work handed to it one piece at a time, each waited for by the one
/// that handed it ([`Kept::start`]).
#[cfg(windows)]
mod beside {
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Mutex, mpsc};

type Job = Box<dyn FnOnce() + Send>;

pub(super) struct Kept {
jobs: Mutex<mpsc::Sender<Job>>,
}

impl Kept {
/// Makes the thread, named `name`, with an 8 MiB stack (as the threads made for each piece
/// had); `start` runs on it once, before any piece.
pub(super) fn new(name: &str, start: fn()) -> std::io::Result<Self> {
let (jobs, taken) = mpsc::channel::<Job>();
std::thread::Builder::new().name(name.into()).stack_size(8 << 20).spawn(move || {
start();
for job in taken {
job();
}
})?;
Ok(Kept { jobs: Mutex::new(jobs) })
}

/// Hands `piece` to the thread and returns at once; what it returns (or how it panicked)
/// comes back on the receiver. `None` if the thread is gone, and then `piece` has not run.
pub(super) fn start<R: Send + 'static>(
&self,
piece: impl FnOnce() -> R + Send + 'static,
) -> Option<mpsc::Receiver<std::thread::Result<R>>> {
let (done, wait) = mpsc::sync_channel(1);
let job: Job = Box::new(move || {
// A panic stays in the piece: the thread goes on for the next one.
let _ = done.send(catch_unwind(AssertUnwindSafe(piece)));
});
self.jobs.lock().unwrap_or_else(|e| e.into_inner()).send(job).ok()?;
Some(wait)
}
}

#[cfg(test)]
mod tests {
use super::Kept;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};

static STARTED: AtomicUsize = AtomicUsize::new(0);

/// Every piece runs on the one thread kept, made once (its start runs once), and a piece
/// that panics leaves the thread there for the next.
#[test]
fn pieces_run_on_one_thread_made_once_and_a_panic_stays_in_its_piece() {
let kept = Kept::new("test-beside", || {
STARTED.fetch_add(1, Relaxed);
})
.expect("the thread");
let ids: Vec<_> = (0..200)
.map(|i| {
let wait = kept.start(move || (std::thread::current().id(), i)).expect("handed");
let (id, got) = wait.recv().expect("an answer").expect("no panic");
assert_eq!(got, i);
id
})
.collect();
assert_ne!(ids[0], std::thread::current().id(), "not on the caller's thread");
assert!(ids.iter().all(|id| *id == ids[0]), "one thread for all the pieces");
assert_eq!(STARTED.load(Relaxed), 1, "made once");
let panicked = kept.start(|| -> u32 { panic!("a piece that panics") }).expect("handed").recv().expect("an answer");
assert!(panicked.is_err(), "the panic comes back to the one that waits");
let after = kept.start(|| std::thread::current().id()).expect("handed").recv().expect("an answer").expect("no panic");
assert_eq!(after, ids[0], "the same thread after a panicking piece");
}
}
}

/// The line's thread is at a present, with everything of that frame sent: the
/// list ahead of the next one is recorded from now on, by a thread of its own,
/// beside the present and whatever comes before the next frame's first
Expand Down
5 changes: 3 additions & 2 deletions d3d12/docs/switches.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ It says which names exist and what the code's own comments say of them. It is **
settings and says nothing of what a switch gains: for that read [findings.md](findings.md) first,
and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.

669 names; 628 have a sentence of a comment below, the others no comment or only a bare list.
670 names; 629 have a sentence of a comment below, the others no comment or only a bare list.

- **Kind**: how the code reads it, where that can be told. "see the code" is a number, a path, a list or a
switch read some other way; its default is not given here.
Expand All @@ -21,7 +21,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.

| Name | Kind | A/B | L | F | Named in | In the code's words |
|---|---|---|---|---|---|---|
| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +38 | `LEONIDA_AB=&lt;seconds&gt;,&lt;switch&gt;[,&lt;switch&gt;..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... |
| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +39 | `LEONIDA_AB=&lt;seconds&gt;,&lt;switch&gt;[,&lt;switch&gt;..]`: every so many seconds, at a present, the next phase begins; switch number n is on in the phases whose number has bit n, so that all combinations come one after another, again... |
| `LEONIDA_AUDIO_CAPTURE` | see the code | | | | `leonida/main.rs` +1 | `LEONIDA_AUDIO_CAPTURE=&lt;file.wav&gt;` records what the title plays, 48 kHz stereo 16-bit, through process loopback: our own process tree only, never the rest of the host's mix. |
| `LEONIDA_CAPTURE` | see the code | | yes | | `leonida/leonida.rs` +4 | Presented frames written to PNG files, to see what reaches the screen: with `LEONIDA_CAPTURE=&lt;folder&gt;`, every frame whose number is a power of two (the frames the log reports) is saved as `frame-&lt;n&gt;.png`, at half size. |
| `LEONIDA_CARD_AWAKE` | see the code | yes | yes | yes | `leonida/replay.rs` +4 | Keeps the card's clocks up between submissions (`LEONIDA_CARD_AWAKE=1`; off by default). |
Expand Down Expand Up @@ -113,6 +113,7 @@ and [how to measure frame rates](../../docs/measuring_fps.md) before trying one.
| `LEONIDA_ACTIVATE_RAYS` | see the code | | yes | | `leonida-gpu/pipeline/make.rs` +1 | |
| `LEONIDA_ADAPTER` | see the code | | yes | | `leonida-gpu/host.rs` +3 | LOCAL: the card `LEONIDA_ADAPTER` names, for a PC with more than one. |
| `LEONIDA_AHEAD_INDEX` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | Whether the page ranges asked ahead ([`Journal::ahead`]) are kept in order, so that the one that holds a range is found in a few steps (`LEONIDA_AHEAD_INDEX=0`: a list looked through from its start, as before). |
| `LEONIDA_AHEAD_KEPT_THREAD` | on, `0` turns it off | yes | | | `leonida-gpu/queue.rs` | `LEONIDA_AHEAD_KEPT_THREAD` (on; `0`: off, `LEONIDA_AB` can switch it): the textures' half of a split list ahead ([`crate::draw::ahead_split`]) is recorded by one thread kept for the run ([`AHEAD_BESIDE`]), instead of by... |
| `LEONIDA_AHEAD_SPLIT` | off unless set and not `0` | yes | yes | yes | `leonida-gpu/draw.rs` +1 | `LEONIDA_AHEAD_SPLIT=1`: the list ahead of a frame is recorded as two lists by two threads at once, the buffer views' pass and the textures' pass (sent in that order), instead of one after the other into one list. |
| `LEONIDA_ALIAS_CAST` | on, `0` turns it off | yes | | yes | `leonida-gpu/descriptor/host.rs` +2 | ..., with no copy on the card and no host texture of its own (`LEONIDA_ALIAS_CAST=0`: copied as before; `LEONIDA_AB` can name it).... |
| `LEONIDA_ALIAS_COPY` | see the code | | | | `leonida-gpu/resource.rs` | `LEONIDA_ALIAS_COPY=0`: none is found, as before; `=1`: only textures of one level and one layer, as at first. |
Expand Down
Loading