upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNotRexed <therealnothingfn@gmail.com>2026-11-30 13:18:51 -0500
committerNotRexed <therealnothingfn@gmail.com>2026-11-30 13:18:51 -0500
commit6cdc0a0d13e33daeae13f7fcfdde0907c46bc73d (patch)
tree5803652915939addf7962b933ba4ffa30420fbcb
parentf7857c4d6f3314d5325daae7651a85a333c3afab (diff)
parentad36782c6d54af6af343def1a86861d760de9e96 (diff)
Merge remote-tracking branch 'origin/main' into push/main-1130
-rw-r--r--d3d12/crates/leonida-gpu/src/host.rs16
-rw-r--r--d3d12/crates/leonida-gpu/src/host/frametime.rs284
-rw-r--r--d3d12/crates/leonida-gpu/src/host/panel.rs15
-rw-r--r--d3d12/crates/leonida-gpu/src/pipeline.rs7
-rw-r--r--d3d12/crates/leonida-gpu/src/pipeline/make.rs121
-rw-r--r--docs/boot.md4
-rw-r--r--docs/d3d12_vulkan.md10
-rw-r--r--runtime/CMakeLists.txt7
-rw-r--r--runtime/shims/d3d12_backend.h23
-rw-r--r--runtime/shims/d3d12_com.h4
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp48
-rw-r--r--runtime/shims/d3d12_xs.cpp17
-rw-r--r--runtime/src/pipeline_cache_store.h38
-rw-r--r--runtime/src/pipeline_profile.h16
-rw-r--r--runtime/test/d3d12_backend_test.cpp41
-rw-r--r--runtime/test/d3d12_descriptor_test.cpp19
-rw-r--r--runtime/test/pipeline_cache_store_test.cpp43
-rw-r--r--runtime/test/vk_test_device.h8
18 files changed, 701 insertions, 20 deletions
diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs
index 0baea5109..b380d0c33 100644
--- a/d3d12/crates/leonida-gpu/src/host.rs
+++ b/d3d12/crates/leonida-gpu/src/host.rs
@@ -5337,6 +5337,8 @@ pub(crate) mod indirects;
5337mod font; 5337mod font;
5338#[cfg(feature = "diagnostics")] 5338#[cfg(feature = "diagnostics")]
5339mod panel; 5339mod panel;
5340// Frame-time percentiles and what stalls frames, with the frame-rate line.
5341mod frametime;
5340// Leonida: the F1 settings menu and the frame-rate line, in every build. 5342// Leonida: the F1 settings menu and the frame-rate line, in every build.
5341mod menu; 5343mod menu;
5342// Leonida: the trainer menu laid over the picture (`leonida-menu`, F4). 5344// Leonida: the trainer menu laid over the picture (`leonida-menu`, F4).
@@ -12361,6 +12363,8 @@ struct Meter {
12361 logged: std::time::Instant, 12363 logged: std::time::Instant,
12362 /// The caption the window had, once read. 12364 /// The caption the window had, once read.
12363 caption: Option<Vec<u16>>, 12365 caption: Option<Vec<u16>>,
12366 /// Frame times and stalls, logged with the line.
12367 stalls: frametime::Meter,
12364} 12368}
12365 12369
12366impl Meter { 12370impl Meter {
@@ -12374,6 +12378,10 @@ impl Meter {
12374 drawn: crate::draw::drawn(), 12378 drawn: crate::draw::drawn(),
12375 logged: now, 12379 logged: now,
12376 caption: None, 12380 caption: None,
12381 stalls: frametime::Meter::new(
12382 crate::pipeline::made(),
12383 RESIDENT[1].load(Ordering::Relaxed),
12384 ),
12377 } 12385 }
12378 } 12386 }
12379 12387
@@ -12389,6 +12397,7 @@ impl Meter {
12389 tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present"); 12397 tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present");
12390 #[cfg(feature = "diagnostics")] 12398 #[cfg(feature = "diagnostics")]
12391 crate::copystat::presented(); 12399 crate::copystat::presented();
12400 self.stalls.presented(std::time::Instant::now());
12392 self.frames += 1; 12401 self.frames += 1;
12393 #[cfg(feature = "diagnostics")] 12402 #[cfg(feature = "diagnostics")]
12394 { 12403 {
@@ -12409,6 +12418,13 @@ impl Meter {
12409 let five = self.logged.elapsed() >= std::time::Duration::from_secs(5); 12418 let five = self.logged.elapsed() >= std::time::Duration::from_secs(5);
12410 if five { 12419 if five {
12411 self.logged = std::time::Instant::now(); 12420 self.logged = std::time::Instant::now();
12421 // (Here: the frame times are this meter's.)
12422 self.stalls.line(
12423 crate::pipeline::making(),
12424 crate::pipeline::made(),
12425 RESIDENT[1].load(Ordering::Relaxed),
12426 crate::residency::available_commit(),
12427 );
12412 } 12428 }
12413 // (The copy counters run from one five-second line to the next.) 12429 // (The copy counters run from one five-second line to the next.)
12414 #[cfg(feature = "diagnostics")] 12430 #[cfg(feature = "diagnostics")]
diff --git a/d3d12/crates/leonida-gpu/src/host/frametime.rs b/d3d12/crates/leonida-gpu/src/host/frametime.rs
new file mode 100644
index 000000000..75e6e0d40
--- /dev/null
+++ b/d3d12/crates/leonida-gpu/src/host/frametime.rs
@@ -0,0 +1,284 @@
1//! Frame times as a distribution, not only a mean, so that stalls show: every
2//! presented frame's time goes in, and with the frame-rate line, every five
3//! seconds, one line gives the median, the 95th and 99th percentiles, the
4//! longest frame and how many took over 100 ms and over a second, beside what
5//! stalls frames: host pipelines queued and made a second, waits for new
6//! memory to be resident, and the commit the system has left. The panel (F3)
7//! shows the last one.
8
9use std::time::Instant;
10
11/// Frame times kept for the percentiles of one line (about 13 s at 300 fps);
12/// past it the counts and the longest frame stay exact.
13const KEPT: usize = 4096;
14
15/// The times of the frames since the last [`FrameTimes::take`], in ms.
16#[derive(Default)]
17pub(super) struct FrameTimes {
18 ms: Vec<f32>,
19 frames: u32,
20 longest: f32,
21 over_100: u32,
22 over_1s: u32,
23}
24
25/// What [`FrameTimes::take`] gives back, in ms. The percentiles are nearest
26/// rank: a value some frame took, such that that share of frames took as
27/// long or less.
28#[derive(Clone, Copy, Debug, Default, PartialEq)]
29pub(super) struct Summary {
30 pub(super) frames: u32,
31 pub(super) p50: f32,
32 pub(super) p95: f32,
33 pub(super) p99: f32,
34 pub(super) longest: f32,
35 pub(super) over_100: u32,
36 pub(super) over_1s: u32,
37}
38
39impl FrameTimes {
40 pub(super) fn push(&mut self, ms: f32) {
41 self.frames += 1;
42 self.longest = self.longest.max(ms);
43 self.over_100 += u32::from(ms > 100.0);
44 self.over_1s += u32::from(ms > 1000.0);
45 if self.ms.len() < KEPT {
46 self.ms.push(ms);
47 }
48 }
49
50 /// The frames since the last call (none: `None`), and a fresh start.
51 pub(super) fn take(&mut self) -> Option<Summary> {
52 if self.frames == 0 {
53 return None;
54 }
55 self.ms.sort_unstable_by(f32::total_cmp);
56 let n = self.ms.len();
57 // Nearest rank, in whole numbers: the ceil(p * n / 100)-th time.
58 let at = |percent: usize| self.ms[(percent * n).div_ceil(100).clamp(1, n) - 1];
59 let summary = Summary {
60 frames: self.frames,
61 p50: at(50),
62 p95: at(95),
63 p99: at(99),
64 longest: self.longest,
65 over_100: self.over_100,
66 over_1s: self.over_1s,
67 };
68 self.ms.clear();
69 (self.frames, self.longest, self.over_100, self.over_1s) = (0, 0.0, 0, 0);
70 Some(summary)
71 }
72}
73
74/// One line's numbers.
75#[derive(Clone, Copy, Debug, Default, PartialEq)]
76pub(super) struct Stalls {
77 pub(super) times: Summary,
78 /// Host pipelines queued or being made.
79 pub(super) queued: u64,
80 pub(super) made_per_s: f64,
81 /// Waits for new memory to be resident, ms a frame.
82 pub(super) resident_ms: f64,
83 pub(super) commit_left_gb: f64,
84}
85
86/// The last line's numbers, for the panel.
87#[cfg(feature = "diagnostics")]
88pub(super) static LAST: std::sync::Mutex<Option<Stalls>> = std::sync::Mutex::new(None);
89
90/// The frame-rate meter's part: frame times, and the totals the next line
91/// counts from.
92pub(super) struct Meter {
93 times: FrameTimes,
94 last: Option<Instant>,
95 since: Instant,
96 made: u64,
97 resident_us: u64,
98}
99
100impl Meter {
101 /// From the totals so far (`made` host pipelines, `resident_us` waited for
102 /// new memory), so that the first line counts only what came after.
103 pub(super) fn new(made: u64, resident_us: u64) -> Meter {
104 Meter {
105 times: FrameTimes::default(),
106 last: None,
107 since: Instant::now(),
108 made,
109 resident_us,
110 }
111 }
112
113 /// A frame was presented at `now`.
114 pub(super) fn presented(&mut self, now: Instant) {
115 if let Some(last) = self.last.replace(now) {
116 self.times.push((now - last).as_secs_f32() * 1000.0);
117 }
118 }
119
120 /// Logs the line, from the totals since the start: `made` host pipelines,
121 /// `resident_us` waited for new memory; `queued` and `commit` (bytes) now.
122 pub(super) fn line(&mut self, queued: u64, made: u64, resident_us: u64, commit: u64) {
123 let Some(times) = self.times.take() else {
124 return;
125 };
126 let now = Instant::now();
127 let seconds = (now - self.since).as_secs_f64().max(1e-3);
128 let stalls = Stalls {
129 times,
130 queued,
131 made_per_s: made.saturating_sub(self.made) as f64 / seconds,
132 resident_ms: resident_us.saturating_sub(self.resident_us) as f64
133 / 1e3
134 / f64::from(times.frames),
135 commit_left_gb: commit as f64 / f64::from(1u32 << 30),
136 };
137 (self.since, self.made, self.resident_us) = (now, made, resident_us);
138 tracing::info!(
139 "frame times over {seconds:.1} s, {} frames: median {:.1} ms, 95th percentile {:.1}, 99th {:.1}, longest {:.1}; \
140 {} over 100 ms, {} over 1 s; host pipelines {queued} queued or being made, {:.1} made a second; waits for new memory to be \
141 resident {:.2} ms a frame; commit left {:.1} GB",
142 times.frames,
143 times.p50,
144 times.p95,
145 times.p99,
146 times.longest,
147 times.over_100,
148 times.over_1s,
149 stalls.made_per_s,
150 stalls.resident_ms,
151 stalls.commit_left_gb
152 );
153 #[cfg(feature = "diagnostics")]
154 if let Ok(mut last) = LAST.lock() {
155 *last = Some(stalls);
156 }
157 }
158}
159
160/// A frame time for the panel in at most four or five characters: ms up to
161/// 9999, then whole seconds with an S.
162#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
163fn short(ms: f32) -> String {
164 if ms < 9999.5 {
165 format!("{ms:.0}")
166 } else {
167 format!("{:.0}S", ms / 1000.0)
168 }
169}
170
171/// The panel's lines for `s`, with `pipeline_wait_ms` a frame (summed over
172/// threads, over the panel's half second; the rest over the five-second
173/// line), each at most 40 characters of the panel's font.
174#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
175pub(super) fn panel_lines(s: &Stalls, pipeline_wait_ms: f64) -> [String; 5] {
176 let t = &s.times;
177 let (p50, p95, p99, max) = (short(t.p50), short(t.p95), short(t.p99), short(t.longest));
178 [
179 format!("P50 {p50} P95 {p95} P99 {p99} MAX {max}"),
180 format!("OVER 100 MS {} OVER 1 S {}", t.over_100, t.over_1s),
181 format!("PIPES PENDING {} MADE/S {:.1}", s.queued, s.made_per_s),
182 format!(
183 "WAITS PIPES {pipeline_wait_ms:.1} RESIDENT {:.1} MS",
184 s.resident_ms
185 ),
186 format!("COMMIT LEFT {:.1} GB", s.commit_left_gb),
187 ]
188}
189
190#[cfg(test)]
191mod tests {
192 use super::{FrameTimes, Stalls, Summary, panel_lines};
193
194 #[test]
195 fn frame_times_give_percentiles_counts_and_the_longest() {
196 let mut t = FrameTimes::default();
197 assert_eq!(t.take(), None, "no frame, no line");
198 // 98 smooth frames, one hitch and one stall.
199 for _ in 0..98 {
200 t.push(10.0);
201 }
202 t.push(150.0);
203 t.push(2000.0);
204 let s = t.take().unwrap();
205 assert_eq!(
206 (s.frames, s.p50, s.p95, s.longest),
207 (100, 10.0, 10.0, 2000.0)
208 );
209 assert_eq!(s.p99, 150.0, "the 99th of 100 frames is the second longest");
210 assert_eq!((s.over_100, s.over_1s), (2, 1));
211 assert_eq!(t.take(), None, "taking starts afresh");
212 }
213
214 #[test]
215 fn percentiles_are_nearest_rank_without_float_rounding() {
216 let mut t = FrameTimes::default();
217 for ms in 1..=20 {
218 t.push(ms as f32);
219 }
220 let s = t.take().unwrap();
221 // ceil(0.95 * 20) = 19, ceil(0.99 * 20) = 20, ceil(0.5 * 20) = 10.
222 assert_eq!((s.p50, s.p95, s.p99), (10.0, 19.0, 20.0));
223 // Ranks are whole numbers, (percent * n).div_ceil(100), so no float
224 // can move one. For 50, 95 and 99 a float rank, ceil(p / 100 * n),
225 // happens to agree for every n up to 4096: this case pins the
226 // direction (up, not down) at 100 frames.
227 for ms in 1..=100 {
228 t.push(ms as f32);
229 }
230 let s = t.take().unwrap();
231 assert_eq!((s.p50, s.p95, s.p99), (50.0, 95.0, 99.0));
232 }
233
234 #[test]
235 fn past_the_kept_times_the_counts_stay_exact() {
236 let mut t = FrameTimes::default();
237 for _ in 0..super::KEPT {
238 t.push(16.0);
239 }
240 for _ in 0..10 {
241 t.push(1500.0);
242 }
243 let s = t.take().unwrap();
244 assert_eq!(s.frames as usize, super::KEPT + 10);
245 assert_eq!((s.over_100, s.over_1s, s.longest), (10, 10, 1500.0));
246 }
247
248 #[test]
249 fn the_panel_lines_fit_its_box_and_font() {
250 // Long stalls too: 10 s and more (the launcher's pipeline budget),
251 // up to a minute without a present.
252 for ms in [9999.0, 10_000.0, 99_999.0, 600_000.0] {
253 let s = Stalls {
254 times: Summary {
255 frames: 9999,
256 p50: ms,
257 p95: ms,
258 p99: ms,
259 longest: ms,
260 over_100: 9999,
261 over_1s: 9999,
262 },
263 queued: 99999,
264 made_per_s: 999.9,
265 resident_ms: 999.9,
266 commit_left_gb: 99.9,
267 };
268 for line in panel_lines(&s, 9999.9) {
269 assert!(
270 line.len() <= 40,
271 "{line:?} is longer than the panel's 40 columns"
272 );
273 assert!(
274 line.bytes().all(|c| c == b' '
275 || crate::host::font::glyph(c) != crate::host::font::glyph(b'#')),
276 "{line:?} has a character the panel cannot draw"
277 );
278 }
279 }
280 assert_eq!(super::short(9999.0), "9999");
281 assert_eq!(super::short(10_000.0), "10S");
282 assert_eq!(super::short(600_000.0), "600S");
283 }
284}
diff --git a/d3d12/crates/leonida-gpu/src/host/panel.rs b/d3d12/crates/leonida-gpu/src/host/panel.rs
index a722f20aa..6ba7daf7b 100644
--- a/d3d12/crates/leonida-gpu/src/host/panel.rs
+++ b/d3d12/crates/leonida-gpu/src/host/panel.rs
@@ -28,7 +28,7 @@ const GLYPH: (u32, u32) = (5, 7);
28const CELL: (u32, u32) = (6, 9); 28const CELL: (u32, u32) = (6, 9);
29/// Characters in a line, lines, and the box's rim in dots. 29/// Characters in a line, lines, and the box's rim in dots.
30const COLUMNS: u32 = 40; 30const COLUMNS: u32 = 40;
31const LINES: u32 = 9; 31const LINES: u32 = 14;
32const RIM: u32 = 3; 32const RIM: u32 = 3;
33 33
34/// The texts are put into one of these in turn: the card reads the others, 34/// The texts are put into one of these in turn: the card reads the others,
@@ -118,7 +118,7 @@ fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> V
118#[derive(Clone, Copy, Default)] 118#[derive(Clone, Copy, Default)]
119struct Counters([u64; COUNTERS]); 119struct Counters([u64; COUNTERS]);
120 120
121const COUNTERS: usize = 11; 121const COUNTERS: usize = 12;
122 122
123impl Counters { 123impl Counters {
124 fn now() -> Counters { 124 fn now() -> Counters {
@@ -138,6 +138,7 @@ impl Counters {
138 crate::drops::totals().1, 138 crate::drops::totals().1,
139 peek(C::RecordNs), 139 peek(C::RecordNs),
140 crate::draw::drawn(), 140 crate::draw::drawn(),
141 peek(C::PipelineWaitUs),
141 ]) 142 ])
142 } 143 }
143 144
@@ -159,7 +160,9 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
159 let (working, private) = crate::copystat::process_memory(); 160 let (working, private) = crate::copystat::process_memory();
160 let [budget, used, _, shared] = host.video_memory().unwrap_or_default(); 161 let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
161 let idle = (c[1] / 1e3).min(ms); 162 let idle = (c[1] / 1e3).min(ms);
162 vec![ 163 // The frame-time line's last numbers (every five seconds), once there is one.
164 let stalls = super::frametime::LAST.lock().ok().and_then(|last| *last);
165 let mut lines = vec![
163 // LOCAL (11/26): with frame generation, the frames shown beside those rendered. 166 // LOCAL (11/26): with frame generation, the frames shown beside those rendered.
164 match crate::fg::shown_per_frame() { 167 match crate::fg::shown_per_frame() {
165 1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)), 168 1 => format!("FPS {:.1} FRAME {ms:.1} MS", 1e3 / ms.max(0.001)),
@@ -173,7 +176,11 @@ fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec
173 format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)), 176 format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)),
174 format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)), 177 format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)),
175 format!("THIS PANEL {:.0} US A FRAME", cost), 178 format!("THIS PANEL {:.0} US A FRAME", cost),
176 ] 179 ];
180 if let Some(s) = stalls {
181 lines.extend(super::frametime::panel_lines(&s, c[11] / 1e3));
182 }
183 lines
177} 184}
178 185
179/// The buffers of a box that size and format. 186/// The buffers of a box that size and format.
diff --git a/d3d12/crates/leonida-gpu/src/pipeline.rs b/d3d12/crates/leonida-gpu/src/pipeline.rs
index 808cd87c4..f8a7652f6 100644
--- a/d3d12/crates/leonida-gpu/src/pipeline.rs
+++ b/d3d12/crates/leonida-gpu/src/pipeline.rs
@@ -839,6 +839,13 @@ pub(crate) fn making() -> u64 {
839 make::waiting() 839 make::waiting()
840} 840}
841 841
842/// Host pipelines created or loaded from the library since the start.
843#[cfg(windows)]
844pub(crate) fn made() -> u64 {
845 use std::sync::atomic::Ordering::Relaxed;
846 library::MADE.load(Relaxed) + library::LOADED.load(Relaxed)
847}
848
842/// Draws and dispatches dropped since the last [`take_drops`], by reason 849/// Draws and dispatches dropped since the last [`take_drops`], by reason
843/// (diagnostics). 850/// (diagnostics).
844#[cfg(all(windows, feature = "diagnostics"))] 851#[cfg(all(windows, feature = "diagnostics"))]
diff --git a/d3d12/crates/leonida-gpu/src/pipeline/make.rs b/d3d12/crates/leonida-gpu/src/pipeline/make.rs
index 42189790a..66e4e82ae 100644
--- a/d3d12/crates/leonida-gpu/src/pipeline/make.rs
+++ b/d3d12/crates/leonida-gpu/src/pipeline/make.rs
@@ -519,7 +519,12 @@ fn wait(p: &Pending, frame: u64) {
519 if left.is_zero() { 519 if left.is_zero() {
520 return; 520 return;
521 } 521 }
522 // Before the promotion: the queue's lock it may wait for is part of this
523 // frame's wait, not on top of it.
522 let started = Instant::now(); 524 let started = Instant::now();
525 if await_first() {
526 promote(p);
527 }
523 let (lock, done) = &DONE; 528 let (lock, done) = &DONE;
524 let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); 529 let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
525 while p.made.get().is_none() { 530 while p.made.get().is_none() {
@@ -567,10 +572,35 @@ fn wait(p: &Pending, frame: u64) {
567 ); 572 );
568} 573}
569 574
575/// Whether a pipeline a frame waits for goes before the others asked for
576/// ([`AWAITED`]). A draw's pipeline went to the back of the queue: on the
577/// first visit to the world about 1,700 were queued at once (562 of them took
578/// over a second each), and with the launcher's 10 s budget every frame waited
579/// its whole budget for one that a thousand others stood before, then dropped
580/// its draws anyway: 0.35 fps for three and a half minutes (RTX 3080, 8
581/// workers). On by default; `LEONIDA_PIPELINE_AWAIT_FIRST=0`: in the order
582/// asked, as before.
583fn await_first() -> bool {
584 static ON: OnceLock<bool> = OnceLock::new();
585 *ON.get_or_init(|| std::env::var_os("LEONIDA_PIPELINE_AWAIT_FIRST").is_none_or(|v| v != "0"))
586}
587
588/// Moves `p`, asked for and not taken by a worker yet, to the front of its
589/// list as a frame begins to wait for it. (A frame waiting again for one
590/// already moved or being made does not take the lock.)
591fn promote(p: &Pending) {
592 if p.queue_state.load(Ordering::Relaxed) == REQUESTED {
593 QUEUE.lock().unwrap_or_else(|e| e.into_inner()).promote(p);
594 }
595}
596
570const NOT_QUEUED: u8 = 0; 597const NOT_QUEUED: u8 = 0;
571const EARLY: u8 = 1; 598const EARLY: u8 = 1;
572const REQUESTED: u8 = 2; 599const REQUESTED: u8 = 2;
573const MAKING: u8 = 3; 600/// Requested, and a frame waits for it: at the front of its list, after
601/// those awaited before it ([`Queue::promote`]).
602const AWAITED: u8 = 3;
603const MAKING: u8 = 4;
574 604
575/// How many workers may make pipelines at once that are known to take long 605/// How many workers may make pipelines at once that are known to take long
576/// and that no draw has asked for: a quarter of them. On a fresh cache (a 606/// and that no draw has asked for: a quarter of them. On a fresh cache (a
@@ -638,6 +668,36 @@ impl Queue {
638 Some(prev == NOT_QUEUED) 668 Some(prev == NOT_QUEUED)
639 } 669 }
640 670
671 /// Moves `p` from its place among those asked for to the front, after
672 /// those awaited before it; whether it moved (not if a worker has it, it
673 /// is not asked for, or it was moved already). Behind the earlier ones,
674 /// not before them: with the shared budget their frames' waits have run
675 /// out, but taking them in turn keeps any from waiting forever. It does
676 /// not stop a make a worker has begun: the next free worker takes it.
677 fn promote(&mut self, p: &Pending) -> bool {
678 if p.queue_state.load(Ordering::Relaxed) != REQUESTED {
679 return false;
680 }
681 let list = if p.screen && screens_first() {
682 &mut self.screen
683 } else {
684 &mut self.requested
685 };
686 let Some(at) = list.iter().position(|q| std::ptr::eq(Arc::as_ptr(q), p)) else {
687 return false;
688 };
689 let Some(q) = list.remove(at) else {
690 return false;
691 };
692 q.queue_state.store(AWAITED, Ordering::Relaxed);
693 let front = list
694 .iter()
695 .position(|q| q.queue_state.load(Ordering::Relaxed) != AWAITED)
696 .unwrap_or(list.len());
697 list.insert(front, q);
698 true
699 }
700
641 fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> { 701 fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> {
642 // An early entry can have been promoted and claimed already. 702 // An early entry can have been promoted and claimed already.
643 let unclaimed = |list: &mut VecDeque<Arc<Pending>>| { 703 let unclaimed = |list: &mut VecDeque<Arc<Pending>>| {
@@ -930,4 +990,63 @@ mod tests {
930 assert!(queue.pop(true, 1).is_none()); 990 assert!(queue.pop(true, 1).is_none());
931 assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &world)); 991 assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &world));
932 } 992 }
993
994 fn in_order(queue: &mut Queue, screens_only: bool, expected: &[&Arc<Pending>]) {
995 let made: Vec<_> = std::iter::from_fn(|| queue.pop(screens_only, 1)).collect();
996 assert_eq!(made.len(), expected.len());
997 for (i, (got, want)) in made.iter().zip(expected).enumerate() {
998 assert!(Arc::ptr_eq(got, want), "pipeline {i} out of order");
999 }
1000 }
1001
1002 /// A pipeline a frame waits for is made next, before those asked for
1003 /// earlier; those awaited keep their order among themselves.
1004 #[test]
1005 fn an_awaited_pipeline_is_made_before_those_asked_earlier() {
1006 let new = || Arc::new(Pending::new(Vec::new(), None));
1007 let (a, b, c, d, e) = (new(), new(), new(), new(), new());
1008 let mut queue = Queue::new();
1009 for p in [&a, &b, &c, &d] {
1010 assert_eq!(queue.push_as(p, REQUESTED, false), Some(true));
1011 }
1012 // c, then a, are waited for: they go first, c before a, once each.
1013 assert!(queue.promote(&c));
1014 assert!(queue.promote(&a));
1015 assert!(!queue.promote(&a));
1016 // One a draw has not asked for, or that a worker has, stays where it is.
1017 assert!(!queue.promote(&e));
1018 assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &c));
1019 assert!(!queue.promote(&c));
1020 in_order(&mut queue, false, &[&a, &b, &d]);
1021 }
1022
1023 #[test]
1024 fn an_awaited_early_pipeline_is_claimed_once() {
1025 let new = || Arc::new(Pending::new(Vec::new(), None));
1026 let (early, asked) = (new(), new());
1027 let mut queue = Queue::new();
1028 assert_eq!(queue.push_as(&early, EARLY, false), Some(true));
1029 assert_eq!(queue.push_as(&asked, REQUESTED, false), Some(true));
1030 assert_eq!(queue.push_as(&early, REQUESTED, false), Some(false));
1031 assert!(queue.promote(&early));
1032 // Already past asked for: a draw asking again changes nothing.
1033 assert_eq!(queue.push_as(&early, REQUESTED, false), None);
1034 // (The early list's stale entry is passed over.)
1035 in_order(&mut queue, false, &[&early, &asked]);
1036 }
1037
1038 #[test]
1039 fn an_awaited_pass_over_the_screen_goes_first_among_them() {
1040 let pass = || {
1041 let mut p = Pending::new(Vec::new(), None);
1042 p.screen = true;
1043 Arc::new(p)
1044 };
1045 let (first, second) = (pass(), pass());
1046 let mut queue = Queue::new();
1047 assert_eq!(queue.push(&first, REQUESTED), Some(true));
1048 assert_eq!(queue.push(&second, REQUESTED), Some(true));
1049 assert!(queue.promote(&second));
1050 in_order(&mut queue, true, &[&second, &first]);
1051 }
933} 1052}
diff --git a/docs/boot.md b/docs/boot.md
index 688d91dd1..e6fbea587 100644
--- a/docs/boot.md
+++ b/docs/boot.md
@@ -90,8 +90,8 @@ fresh name or delete the old one. `LEONIDA_D3D12=vulkan` selects the Vulkan-back
90traces command lists, resources and pipelines; without it the layer uses the Windows D3D12 device, and the 90traces command lists, resources and pipelines; without it the layer uses the Windows D3D12 device, and the
91`[d3d12-trace]` lines are only what the Xbox-ABI proxy forwards (device creation, queue, fence and allocator 91`[d3d12-trace]` lines are only what the Xbox-ABI proxy forwards (device creation, queue, fence and allocator
92calls), which `boot_trace.py` summarizes without complaint. A run on the Vulkan device prints 92calls), which `boot_trace.py` summarizes without complaint. A run on the Vulkan device prints
93`[rt] d3d12: Vulkan device: <name>`; check the log for it (a runtime built without the Vulkan headers accepts the 93`[rt] d3d12: Vulkan device: <name>`; check the log for it (a runtime built without the Vulkan headers stays on the Windows
94variable and stays on the Windows device). Keep the traces out of the repository: they can quote whatever the game prints. 94device and says so in one `[rt] d3d12_xs: LEONIDA_D3D12=vulkan is set, but ...` line). Keep the traces out of the repository: they can quote whatever the game prints.
95 95
96Useful switches: 96Useful switches:
97 97
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 5bd6182ea..083c91e0d 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -2918,6 +2918,16 @@ Pipeline creation:
2918 so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the 2918 so they no longer reach `pipeline_cache.session.bin`. `LEONIDA_HEAVY_PIPELINE_CACHE_MS=0` turns the heavy cache off, and with it the
2919 `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create 2919 `pipelineCreationCacheControl` feature unless `LEONIDA_PIPELINE_COMPILE=cache-only` asks for it. A cache-only create
2920 (`cache-only`) is left as it is. 2920 (`cache-only`) is left as it is.
2921 A driver can stop keeping new pipelines once its cache is large, with no error. On NVIDIA 610.88 (RTX 5060 Ti),
2922 a 1.23 GB or 1.35 GB cache came back from `vkGetPipelineCacheData` the same size to the byte after a 2 s compile
2923 (with the 1.35 GB one the next process compiled the pipeline again; a hit then comes only from the driver's own
2924 disk cache), where an empty cache grew ~210 KiB and served the next process in 0.01 s. In the game, seeded with
2925 the 1.23 GB file, 68 of ~110 builds over 200 ms were slow again in the next run; started with no seed, 5 of 164
2926 were. An older cache of other pipelines stopped growing at 4.9 GB, so the point is not a fixed size. The runtime
2927 takes the cache's size when it creates it and at each session save, counts the title's builds that took at least
2928 200 ms (a hit takes a few milliseconds), and says once when 16 or more of them compiled while the cache grew by
2929 less than 64 KiB. The remedy is a smaller seed: without `pipeline_cache.bin`, the session file holds only what the
2930 title builds.
2921 `LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]` (`all`: every compute program) never builds the matching 2931 `LEONIDA_SKIP_COMPUTE=<part of a name>[,<part>...]` (`all`: every compute program) never builds the matching
2922 compute programs at play and drops their dispatches, direct and indirect; the first dropped dispatch of each is 2932 compute programs at play and drops their dispatches, direct and indirect; the first dropped dispatch of each is
2923 logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix. 2933 logged. It is a way past a program that hangs the GPU while the program or its input is fixed, not a fix.
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 4bed82a4f..765b2611a 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -2223,6 +2223,13 @@ if(NOT TARGET Vulkan::Headers)
2223 FetchContent_MakeAvailable(VulkanHeaders) 2223 FetchContent_MakeAvailable(VulkanHeaders)
2224 endif() 2224 endif()
2225endif() 2225endif()
2226# LEONIDA_D3D12=vulkan asked of a runtime with no Vulkan-backed device (shims/d3d12_backend.h). Outside the block
2227# below on purpose: a configure without the Vulkan headers is the case it is about.
2228add_executable(d3d12_backend_test test/d3d12_backend_test.cpp)
2229if(WIN32 AND MSVC)
2230 target_compile_options(d3d12_backend_test PRIVATE /W4 /permissive- /utf-8)
2231endif()
2232add_test(NAME d3d12_backend COMMAND d3d12_backend_test)
2226# The Windows runtime's D3D12 layer needs newer headers than the portable Vulkan tools, so only its builds check. 2233# The Windows runtime's D3D12 layer needs newer headers than the portable Vulkan tools, so only its builds check.
2227if(TARGET Vulkan::Headers AND WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) 2234if(TARGET Vulkan::Headers AND WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
2228 include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_version.cmake") 2235 include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/vulkan_headers_version.cmake")
diff --git a/runtime/shims/d3d12_backend.h b/runtime/shims/d3d12_backend.h
new file mode 100644
index 000000000..7bba99dc5
--- /dev/null
+++ b/runtime/shims/d3d12_backend.h
@@ -0,0 +1,23 @@
1// Which device D3D12XboxCreateDevice puts behind the Xbox-ABI proxy, as LEONIDA_D3D12 asks (RT-VULKAN-REQUESTED-NOT-BUILT).
2// Header only, so the test needs neither a device nor the Vulkan headers.
3#pragma once
4
5#include <cstring>
6
7namespace rt::d3d12_xs::backend {
8
9// LEONIDA_D3D12=vulkan, exactly: the one value that selects the Vulkan-backed device.
10inline bool vulkan_requested(const char* value) { return value && std::strcmp(value, "vulkan") == 0; }
11
12// What to tell the user when the variable asks for the Vulkan-backed device and this runtime has none, else null.
13// A runtime configured without the Vulkan headers is built without LEONIDA_VULKAN_DEVICE: it used to take the variable
14// without a word and run the title on the host's D3D12 device, which stops somewhere else and looks like a boot result.
15inline const char* vulkan_not_built_note(const char* value, bool vulkan_built) {
16 if (vulkan_built || !vulkan_requested(value)) return nullptr;
17 return "LEONIDA_D3D12=vulkan is set, but this runtime was built without the Vulkan-backed device (its configure "
18 "found no Vulkan headers), so the title gets the host's D3D12 device instead. Configure again with "
19 "VULKAN_SDK set or -DLEONIDA_VULKAN_HEADERS_FETCH=ON; -DLEONIDA_REQUIRE_VULKAN=ON makes a configure "
20 "without the headers fail";
21}
22
23} // namespace rt::d3d12_xs::backend
diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h
index 79752e514..e627a29db 100644
--- a/runtime/shims/d3d12_com.h
+++ b/runtime/shims/d3d12_com.h
@@ -148,6 +148,10 @@ struct VulkanDeviceInfo {
148 bool sampler_anisotropy = false; 148 bool sampler_anisotropy = false;
149 bool sampler_mirror_clamp_to_edge = false; 149 bool sampler_mirror_clamp_to_edge = false;
150 bool sampler_filter_minmax = false; 150 bool sampler_filter_minmax = false;
151 // VkPhysicalDeviceSamplerFilterMinmaxProperties::filterMinmaxImageComponentMapping. Without it a minimum/maximum
152 // reduction defines only the R component of a sample, and only through an identity-swizzled view (Vulkan
153 // specification, Texel Filtering); G, B and A are undefined (D3D-994: Polaris on the AMD Windows driver).
154 bool sampler_filter_minmax_component_mapping = false;
151 // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock). 155 // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock).
152 bool calibrated_timestamps = false; 156 bool calibrated_timestamps = false;
153 // VK_EXT_conditional_rendering (with its conditionalRendering feature) is enabled: SetPredication works, and 157 // VK_EXT_conditional_rendering (with its conditionalRendering feature) is enabled: SetPredication works, and
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 54805bf63..1c97dad48 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -2924,6 +2924,41 @@ bool startup_cache_checkpoints_enabled() {
2924} 2924}
2925 2925
2926// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. 2926// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write.
2927// RT-PIPELINE-CACHE-GROWTH-STALL: says once when the title's builds keep compiling but the driver's cache stops
2928// growing, so the next run would compile them again (pipeline_cache_store::GrowthWatch). The size is taken when the
2929// cache is created and at every session save, also one over the write limit.
2930std::mutex& pipeline_cache_growth_mutex() {
2931 static std::mutex mutex;
2932 return mutex;
2933}
2934
2935leonida::pipeline_cache_store::GrowthWatch& pipeline_cache_growth() {
2936 static leonida::pipeline_cache_store::GrowthWatch watch;
2937 return watch;
2938}
2939
2940void note_pipeline_cache_size(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) {
2941 std::size_t size = 0;
2942 if (!cache || !vk.vkGetPipelineCacheData || vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS)
2943 return;
2944 std::lock_guard lock(pipeline_cache_growth_mutex());
2945 pipeline_cache_growth().observe(size, leonida::pipeline_profile::compiled_builds().load());
2946}
2947
2948void report_pipeline_cache_growth(std::size_t size) {
2949 const auto compiled = leonida::pipeline_profile::compiled_builds().load();
2950 std::lock_guard lock(pipeline_cache_growth_mutex());
2951 auto& watch = pipeline_cache_growth();
2952 const std::size_t before = watch.bytes();
2953 const unsigned long long builds = compiled - watch.compiled();
2954 if (watch.stalled(size, compiled))
2955 std::fprintf(stderr, "[rt] d3d12: the Vulkan pipeline cache grew %zu bytes (to %zu) over %llu pipeline builds "
2956 "that compiled: the driver no longer keeps new pipelines, so the next run compiles them "
2957 "again. A large pipeline_cache.bin or pipeline_cache.session.bin can cause it "
2958 "(docs/d3d12_vulkan.md, pipeline caches)\n",
2959 size > before ? size - before : 0, size, builds);
2960}
2961
2927void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, 2962void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
2928 bool checkpoint = false, const char* op = nullptr) { 2963 bool checkpoint = false, const char* op = nullptr) {
2929 if (!cache || !vk.vkGetPipelineCacheData) return; 2964 if (!cache || !vk.vkGetPipelineCacheData) return;
@@ -2934,6 +2969,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev
2934 std::size_t size = 0; 2969 std::size_t size = 0;
2935 if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || 2970 if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS ||
2936 size <= sizeof(VkPipelineCacheHeaderVersionOne)) return; 2971 size <= sizeof(VkPipelineCacheHeaderVersionOne)) return;
2972 report_pipeline_cache_growth(size);
2937 const std::size_t seed = g_offline_seed_bytes.load(std::memory_order_relaxed); 2973 const std::size_t seed = g_offline_seed_bytes.load(std::memory_order_relaxed);
2938 if (leonida::pipeline_cache_store::over_save_limit(size, seed, limit)) { 2974 if (leonida::pipeline_cache_store::over_save_limit(size, seed, limit)) {
2939 std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes (%zu of them the offline seed), over the " 2975 std::fprintf(stderr, "[rt] d3d12: pipeline cache is %zu bytes (%zu of them the offline seed), over the "
@@ -3788,6 +3824,7 @@ struct DeviceState {
3788 else if (!direct_session_cache() && !compile_helper::build_host) 3824 else if (!direct_session_cache() && !compile_helper::build_host)
3789 pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); 3825 pipeline_cache_seeded = merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity);
3790 } 3826 }
3827 note_pipeline_cache_size(vk, info.device, pipeline_cache_handle);
3791 if (!pipeline_journal_dir().empty()) { 3828 if (!pipeline_journal_dir().empty()) {
3792 char text[32] = {}; 3829 char text[32] = {};
3793 size_t length = 0; 3830 size_t length = 0;
@@ -13739,6 +13776,10 @@ struct DeviceState {
13739 reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode); 13776 reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode);
13740 reduction.pNext = sampler_info.pNext; 13777 reduction.pNext = sampler_info.pNext;
13741 sampler_info.pNext = &reduction; 13778 sampler_info.pNext = &reduction;
13779 if (!info.sampler_filter_minmax_component_mapping)
13780 log_once("minimum/maximum filter sampler without filterMinmaxImageComponentMapping; only R is "
13781 "defined, mode",
13782 int(sampler.filter_mode));
13742 } else { 13783 } else {
13743 log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode", 13784 log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode",
13744 int(sampler.filter_mode)); 13785 int(sampler.filter_mode));
@@ -31734,6 +31775,13 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin
31734 info.sampler_anisotropy = chosen_features.samplerAnisotropy; 31775 info.sampler_anisotropy = chosen_features.samplerAnisotropy;
31735 info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; 31776 info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge;
31736 info.sampler_filter_minmax = chosen12.samplerFilterMinmax; 31777 info.sampler_filter_minmax = chosen12.samplerFilterMinmax;
31778 if (info.sampler_filter_minmax) {
31779 VkPhysicalDeviceSamplerFilterMinmaxProperties minmax{
31780 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES};
31781 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmax};
31782 vkGetPhysicalDeviceProperties2(info.physical, &properties);
31783 info.sampler_filter_minmax_component_mapping = minmax.filterMinmaxImageComponentMapping == VK_TRUE;
31784 }
31737 enable12.runtimeDescriptorArray = info.bindless; 31785 enable12.runtimeDescriptorArray = info.bindless;
31738 enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless; 31786 enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless;
31739 enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless; 31787 enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless;
diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp
index a6c7934e4..b584b0407 100644
--- a/runtime/shims/d3d12_xs.cpp
+++ b/runtime/shims/d3d12_xs.cpp
@@ -20,6 +20,7 @@
20#ifdef LEONIDA_VULKAN_DEVICE 20#ifdef LEONIDA_VULKAN_DEVICE
21#include "d3d12_com.h" 21#include "d3d12_com.h"
22#endif 22#endif
23#include "d3d12_backend.h"
23#include "d3d12_trace.h" 24#include "d3d12_trace.h"
24#include "d3d12_xs_device.h" 25#include "d3d12_xs_device.h"
25#include "d3d12_xs_rootsig.h" 26#include "d3d12_xs_rootsig.h"
@@ -198,12 +199,24 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons
198 const bool pc_lists = getenv_s(&lists_length, lists_mode, "LEONIDA_D3D12_LISTS") == 0 && 199 const bool pc_lists = getenv_s(&lists_length, lists_mode, "LEONIDA_D3D12_LISTS") == 0 &&
199 std::strcmp(lists_mode, "pc") == 0; 200 std::strcmp(lists_mode, "pc") == 0;
200 201
201#ifdef LEONIDA_VULKAN_DEVICE
202 // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device 202 // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device
203 // behind the same proxy instead of the host's D3D12 device. 203 // behind the same proxy instead of the host's D3D12 device.
204 char backend[16] = {}; 204 char backend[16] = {};
205 size_t backend_length = 0; 205 size_t backend_length = 0;
206 if (getenv_s(&backend_length, backend, "LEONIDA_D3D12") == 0 && std::strcmp(backend, "vulkan") == 0) { 206 const bool backend_read = getenv_s(&backend_length, backend, "LEONIDA_D3D12") == 0;
207#ifdef LEONIDA_VULKAN_DEVICE
208 constexpr bool vulkan_built = true;
209#else
210 constexpr bool vulkan_built = false;
211#endif
212 // A runtime configured without the Vulkan headers has no such device: say so once instead of running the title on
213 // the host's device as if nothing had been asked.
214 if (const char* note = rt::d3d12_xs::backend::vulkan_not_built_note(backend_read ? backend : nullptr, vulkan_built)) {
215 static std::atomic<bool> noted{false};
216 if (!noted.exchange(true, std::memory_order_relaxed)) std::fprintf(stderr, "[rt] d3d12_xs: %s\n", note);
217 }
218#ifdef LEONIDA_VULKAN_DEVICE
219 if (backend_read && rt::d3d12_xs::backend::vulkan_requested(backend)) {
207 ID3D12Device* vulkan = nullptr; 220 ID3D12Device* vulkan = nullptr;
208 HRESULT vhr = rt::d3d12::create_vulkan_device_standalone( 221 HRESULT vhr = rt::d3d12::create_vulkan_device_standalone(
209 __uuidof(ID3D12Device), reinterpret_cast<void**>(&vulkan), rt::d3d12::QueueTestSettings::ignore); 222 __uuidof(ID3D12Device), reinterpret_cast<void**>(&vulkan), rt::d3d12::QueueTestSettings::ignore);
diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h
index 5b93d93f0..151ada16e 100644
--- a/runtime/src/pipeline_cache_store.h
+++ b/runtime/src/pipeline_cache_store.h
@@ -73,4 +73,42 @@ inline bool header_matches(const void* data, std::size_t size, const cached_pso:
73 std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; 73 std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0;
74} 74}
75 75
76// Whether the driver still keeps the pipelines the title compiles (RT-PIPELINE-CACHE-GROWTH-STALL). A driver can stop
77// adding to a large cache without any error. Measured on NVIDIA 610.88 (RTX 5060 Ti): after a 2 s compile, a 1.23 GB
78// or 1.35 GB cache came back from vkGetPipelineCacheData the same size to the byte, where an empty cache grew ~210 KiB
79// for the same module; an older cache of other pipelines stopped at 4.9 GB, so there is no fixed size to test.
80// Instead two sizes of the live cache are compared with the builds that compiled in between (pipeline_profile::
81// compiled_builds): each one adds tens to hundreds of KiB when the driver keeps it.
82inline constexpr unsigned long long stalled_after_builds = 16;
83inline constexpr std::size_t stalled_below_bytes = std::size_t{64} << 10; // 64 KiB
84
85class GrowthWatch {
86public:
87 // The cache's size and the compiled-build count when it is created, or at a save.
88 void observe(std::size_t bytes, unsigned long long compiled) {
89 bytes_ = bytes;
90 compiled_ = compiled;
91 known_ = true;
92 }
93
94 // At a later size: true once, the first time at least stalled_after_builds builds compiled since the last
95 // observation while the cache grew by less than stalled_below_bytes. The new size is recorded either way.
96 bool stalled(std::size_t bytes, unsigned long long compiled) {
97 const bool stall = known_ && !reported_ && compiled >= compiled_ && compiled - compiled_ >= stalled_after_builds &&
98 bytes < bytes_ + stalled_below_bytes;
99 if (stall) reported_ = true;
100 observe(bytes, compiled);
101 return stall;
102 }
103
104 std::size_t bytes() const { return bytes_; }
105 unsigned long long compiled() const { return compiled_; }
106
107private:
108 std::size_t bytes_ = 0;
109 unsigned long long compiled_ = 0;
110 bool known_ = false;
111 bool reported_ = false;
112};
113
76} // namespace leonida::pipeline_cache_store 114} // namespace leonida::pipeline_cache_store
diff --git a/runtime/src/pipeline_profile.h b/runtime/src/pipeline_profile.h
index f81c00c7d..965d8f525 100644
--- a/runtime/src/pipeline_profile.h
+++ b/runtime/src/pipeline_profile.h
@@ -39,23 +39,33 @@ inline long long thread_cpu_us() {
39 return -1; 39 return -1;
40} 40}
41 41
42// Title pipeline builds that took long enough to have compiled rather than come from the pipeline cache: a cache hit
43// takes a few milliseconds, also while the title keeps every core busy. Counted whether or not profiling is on; the
44// session cache save compares the count with how much the cache grew (pipeline_cache_store::GrowthWatch).
45inline constexpr long long compiled_build_us = 200000; // 200 ms
46inline std::atomic<unsigned long long>& compiled_builds() {
47 static std::atomic<unsigned long long> count{0};
48 return count;
49}
50
42class DriverCall { 51class DriverCall {
43public: 52public:
44 DriverCall(const char* stage, const char* origin, const char* program, const char* fragment = "-", 53 DriverCall(const char* stage, const char* origin, const char* program, const char* fragment = "-",
45 unsigned unbound = 0) { 54 unsigned unbound = 0)
55 : start_(std::chrono::steady_clock::now()) {
46 if (!enabled()) return; 56 if (!enabled()) return;
47 static std::atomic<unsigned long long> sequence{0}; 57 static std::atomic<unsigned long long> sequence{0};
48 id_ = sequence.fetch_add(1, std::memory_order_relaxed) + 1; 58 id_ = sequence.fetch_add(1, std::memory_order_relaxed) + 1;
49 start_ = std::chrono::steady_clock::now();
50 cpu_start_ = thread_cpu_us(); 59 cpu_start_ = thread_cpu_us();
51 std::fprintf(stderr, "[rt] pso-driver begin id=%llu unix_ms=%lld stage=%s origin=%s program=%s ps=%s mask=%u\n", 60 std::fprintf(stderr, "[rt] pso-driver begin id=%llu unix_ms=%lld stage=%s origin=%s program=%s ps=%s mask=%u\n",
52 id_, unix_ms(), stage, origin, program, fragment, unbound); 61 id_, unix_ms(), stage, origin, program, fragment, unbound);
53 } 62 }
54 63
55 void finish(int result) const { 64 void finish(int result) const {
56 if (!id_) return;
57 const auto us = std::chrono::duration_cast<std::chrono::microseconds>( 65 const auto us = std::chrono::duration_cast<std::chrono::microseconds>(
58 std::chrono::steady_clock::now() - start_).count(); 66 std::chrono::steady_clock::now() - start_).count();
67 if (result == 0 && us >= compiled_build_us) compiled_builds().fetch_add(1, std::memory_order_relaxed);
68 if (!id_) return;
59 const long long cpu = thread_cpu_us(); 69 const long long cpu = thread_cpu_us();
60 std::fprintf(stderr, "[rt] pso-driver end id=%llu unix_ms=%lld us=%lld cpu_us=%lld result=%d\n", 70 std::fprintf(stderr, "[rt] pso-driver end id=%llu unix_ms=%lld us=%lld cpu_us=%lld result=%d\n",
61 id_, unix_ms(), static_cast<long long>(us), cpu >= 0 && cpu_start_ >= 0 ? cpu - cpu_start_ : -1, 71 id_, unix_ms(), static_cast<long long>(us), cpu >= 0 && cpu_start_ >= 0 ? cpu - cpu_start_ : -1,
diff --git a/runtime/test/d3d12_backend_test.cpp b/runtime/test/d3d12_backend_test.cpp
new file mode 100644
index 000000000..51c9a1e51
--- /dev/null
+++ b/runtime/test/d3d12_backend_test.cpp
@@ -0,0 +1,41 @@
1// d3d12_backend.h (RT-VULKAN-REQUESTED-NOT-BUILT): LEONIDA_D3D12=vulkan in a runtime that has no Vulkan-backed device
2// gets a note; every other case gets none. CPU only: no device, no Vulkan headers, no game file.
3#include "../shims/d3d12_backend.h"
4
5#include <cstdio>
6#include <cstring>
7
8namespace backend = rt::d3d12_xs::backend;
9
10static int failures = 0;
11static void check(bool condition, const char* what) {
12 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
13 if (!condition) ++failures;
14}
15
16int main() {
17 check(backend::vulkan_requested("vulkan"), "requested: vulkan");
18 check(!backend::vulkan_requested(nullptr), "requested: the variable is not set");
19 check(!backend::vulkan_requested(""), "requested: an empty value");
20 check(!backend::vulkan_requested("Vulkan"), "requested: another case is another value, as the device branch reads it");
21 check(!backend::vulkan_requested("vulkan "), "requested: a trailing space is another value");
22 check(!backend::vulkan_requested("host"), "requested: another backend name");
23
24 const char* note = backend::vulkan_not_built_note("vulkan", false);
25 check(note != nullptr, "note: vulkan asked of a runtime without the device");
26 check(note && std::strstr(note, "LEONIDA_D3D12=vulkan") && std::strstr(note, "host's D3D12 device"),
27 "note: names the variable and the device the title gets");
28 check(note && std::strstr(note, "LEONIDA_VULKAN_HEADERS_FETCH") && std::strstr(note, "LEONIDA_REQUIRE_VULKAN") &&
29 std::strstr(note, "VULKAN_SDK"),
30 "note: names the ways to get the headers and the option that fails the configure");
31
32 check(backend::vulkan_not_built_note("vulkan", true) == nullptr, "note: none when the device is built in");
33 check(backend::vulkan_not_built_note(nullptr, false) == nullptr, "note: none when the variable is not set");
34 check(backend::vulkan_not_built_note("", false) == nullptr, "note: none for an empty value");
35 check(backend::vulkan_not_built_note("Vulkan", false) == nullptr,
36 "note: none for a value the Vulkan build would not take either");
37 check(backend::vulkan_not_built_note(nullptr, true) == nullptr, "note: none, device built in and nothing asked");
38
39 std::printf("%d failures\n", failures);
40 return failures ? 1 : 0;
41}
diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp
index 63e473570..d8e8dbc68 100644
--- a/runtime/test/d3d12_descriptor_test.cpp
+++ b/runtime/test/d3d12_descriptor_test.cpp
@@ -340,6 +340,7 @@ int main() {
340 info.bindless_partially_bound = d.partially_bound; 340 info.bindless_partially_bound = d.partially_bound;
341 info.image_view_min_lod = d.image_view_min_lod; 341 info.image_view_min_lod = d.image_view_min_lod;
342 info.sampler_filter_minmax = d.sampler_filter_minmax; 342 info.sampler_filter_minmax = d.sampler_filter_minmax;
343 info.sampler_filter_minmax_component_mapping = d.sampler_filter_minmax_component_mapping;
343 info.custom_border_color = d.custom_border_color; 344 info.custom_border_color = d.custom_border_color;
344 info.custom_border_color_without_format = d.custom_border_color_without_format; 345 info.custom_border_color_without_format = d.custom_border_color_without_format;
345 ID3D12Device* inner = nullptr; 346 ID3D12Device* inner = nullptr;
@@ -2607,24 +2608,28 @@ int main() {
2607 (bc1_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT) != 0; 2608 (bc1_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT) != 0;
2608 constexpr std::array<std::uint8_t, 4> want_min{16, 16, 16, 255}; 2609 constexpr std::array<std::uint8_t, 4> want_min{16, 16, 16, 255};
2609 constexpr std::array<std::uint8_t, 4> want_max{240, 240, 240, 255}; 2610 constexpr std::array<std::uint8_t, 4> want_max{240, 240, 240, 255};
2611 // Without filterMinmaxImageComponentMapping only R of a reduced sample is defined (D3D-994): compare R
2612 // there, all four channels where the device maps every component.
2613 const std::size_t mm_compared = d.sampler_filter_minmax_component_mapping ? 4 : 1;
2610 UINT min_matches = 0, max_matches = 0, blend_diff_min = 0, blend_diff_max = 0; 2614 UINT min_matches = 0, max_matches = 0, blend_diff_min = 0, blend_diff_max = 0;
2611 for (UINT i = 0; i < texels; ++i) { 2615 for (UINT i = 0; i < texels; ++i) {
2612 const auto* got_min = &mm_pixels[0 * bytes + i * 4]; 2616 const auto* got_min = &mm_pixels[0 * bytes + i * 4];
2613 const auto* got_max = &mm_pixels[1 * bytes + i * 4]; 2617 const auto* got_max = &mm_pixels[1 * bytes + i * 4];
2614 const auto* got_blend = &mm_pixels[2 * bytes + i * 4]; 2618 const auto* got_blend = &mm_pixels[2 * bytes + i * 4];
2615 if (rgba8_minmax) { 2619 if (rgba8_minmax) {
2616 min_matches += std::memcmp(got_min, want_min.data(), 4) == 0; 2620 min_matches += std::memcmp(got_min, want_min.data(), mm_compared) == 0;
2617 max_matches += std::memcmp(got_max, want_max.data(), 4) == 0; 2621 max_matches += std::memcmp(got_max, want_max.data(), mm_compared) == 0;
2618 blend_diff_min += std::memcmp(got_blend, want_min.data(), 4) != 0; 2622 blend_diff_min += std::memcmp(got_blend, want_min.data(), mm_compared) != 0;
2619 blend_diff_max += std::memcmp(got_blend, want_max.data(), 4) != 0; 2623 blend_diff_max += std::memcmp(got_blend, want_max.data(), mm_compared) != 0;
2620 } else { 2624 } else {
2621 min_matches += std::memcmp(got_min, got_blend, 4) == 0; 2625 min_matches += std::memcmp(got_min, got_blend, 4) == 0;
2622 max_matches += std::memcmp(got_max, got_blend, 4) == 0; 2626 max_matches += std::memcmp(got_max, got_blend, 4) == 0;
2623 } 2627 }
2624 } 2628 }
2625 std::printf("sampler reduction min/max (RGBA8=%s, BC1=%s): min %u/%u, max %u/%u (blend differed: %u/%u vs " 2629 std::printf("sampler reduction min/max (RGBA8=%s, BC1=%s, compared %s): min %u/%u, max %u/%u (blend "
2626 "min, %u/%u vs max)\n", 2630 "differed: %u/%u vs min, %u/%u vs max)\n",
2627 rgba8_minmax ? "yes" : "no", bc1_minmax ? "yes" : "no", min_matches, texels, max_matches, 2631 rgba8_minmax ? "yes" : "no", bc1_minmax ? "yes" : "no", mm_compared == 4 ? "RGBA" : "R only",
2632 min_matches, texels, max_matches,
2628 texels, blend_diff_min, texels, blend_diff_max, texels); 2633 texels, blend_diff_min, texels, blend_diff_max, texels);
2629 EXPECT(min_matches == texels && max_matches == texels); 2634 EXPECT(min_matches == texels && max_matches == texels);
2630 if (rgba8_minmax) EXPECT(blend_diff_min == texels && blend_diff_max == texels); 2635 if (rgba8_minmax) EXPECT(blend_diff_min == texels && blend_diff_max == texels);
diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp
index 7af94bca6..a1b093191 100644
--- a/runtime/test/pipeline_cache_store_test.cpp
+++ b/runtime/test/pipeline_cache_store_test.cpp
@@ -95,7 +95,48 @@ static int test_header() {
95 return 0; 95 return 0;
96} 96}
97 97
98static int test_growth() {
99 using store::GrowthWatch;
100 constexpr auto builds = store::stalled_after_builds;
101 constexpr auto kept = store::stalled_below_bytes;
102 // No size at creation: nothing to compare with yet, and the first save becomes the reference.
103 GrowthWatch fresh;
104 CHECK(!fresh.stalled(1000, builds * 4));
105 CHECK(fresh.stalled(1000, builds * 5));
106 // A cache that grows with its builds is fine at any size.
107 GrowthWatch growing;
108 growing.observe(std::size_t{1} << 30, 10);
109 CHECK(!growing.stalled((std::size_t{1} << 30) + kept, 10 + builds));
110 CHECK(growing.bytes() == (std::size_t{1} << 30) + kept);
111 CHECK(growing.compiled() == 10 + builds);
112 // Too few builds compiled to tell: a few cache-sized misses can be refused for other reasons.
113 GrowthWatch few;
114 few.observe(5000, 0);
115 CHECK(!few.stalled(5000, builds - 1));
116 // Enough compiled builds and less than stalled_below_bytes of growth: said once, then never again.
117 GrowthWatch stuck;
118 stuck.observe(1346482377, 100);
119 CHECK(stuck.stalled(1346482377 + kept - 1, 100 + builds));
120 CHECK(!stuck.stalled(1346482377 + kept - 1, 100 + builds * 3));
121 // Builds and growth are counted from the previous save: growth then, none now.
122 GrowthWatch interval;
123 interval.observe(2000, 0);
124 CHECK(!interval.stalled(2000 + kept * 8, builds * 3));
125 CHECK(interval.stalled(2000 + kept * 8, builds * 4));
126 // Too few builds at one save still moves the reference to that save.
127 GrowthWatch moved;
128 moved.observe(2000, 0);
129 CHECK(!moved.stalled(2000, builds - 1));
130 CHECK(moved.stalled(2000, builds * 2 - 1));
131 // A count that went backwards (a second device's counter view) is not read as a huge number of builds.
132 GrowthWatch backwards;
133 backwards.observe(3000, 50);
134 CHECK(!backwards.stalled(3000, 10));
135 return 0;
136}
137
98int main() { 138int main() {
99 if (const int failed = test_limit()) return failed; 139 if (const int failed = test_limit()) return failed;
100 return test_header(); 140 if (const int failed = test_header()) return failed;
141 return test_growth();
101} 142}
diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h
index 96357d325..ef75b7622 100644
--- a/runtime/test/vk_test_device.h
+++ b/runtime/test/vk_test_device.h
@@ -103,6 +103,7 @@ public:
103 bool partially_bound = false; // and its slots can stay empty 103 bool partially_bound = false; // and its slots can stay empty
104 bool image_view_min_lod = false; 104 bool image_view_min_lod = false;
105 bool sampler_filter_minmax = false; 105 bool sampler_filter_minmax = false;
106 bool sampler_filter_minmax_component_mapping = false; // filterMinmaxImageComponentMapping (D3D-994)
106 bool vertex_attribute_divisor = false; 107 bool vertex_attribute_divisor = false;
107 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled 108 bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled
108 bool storage_image_extended_formats = false; // typed r8ui storage images 109 bool storage_image_extended_formats = false; // typed r8ui storage images
@@ -460,6 +461,13 @@ private:
460 enable12.descriptorBindingPartiallyBound = partially_bound; 461 enable12.descriptorBindingPartiallyBound = partially_bound;
461 sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE; 462 sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE;
462 enable12.samplerFilterMinmax = sampler_filter_minmax; 463 enable12.samplerFilterMinmax = sampler_filter_minmax;
464 if (sampler_filter_minmax) {
465 VkPhysicalDeviceSamplerFilterMinmaxProperties minmax{
466 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES};
467 VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &minmax};
468 instance_fn<PFN_vkGetPhysicalDeviceProperties2>("vkGetPhysicalDeviceProperties2")(physical, &properties);
469 sampler_filter_minmax_component_mapping = minmax.filterMinmaxImageComponentMapping == VK_TRUE;
470 }
463 shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE; 471 shader_output_viewport_index = features12.shaderOutputViewportIndex == VK_TRUE;
464 enable12.shaderOutputViewportIndex = shader_output_viewport_index; 472 enable12.shaderOutputViewportIndex = shader_output_viewport_index;
465 vulkan_memory_model = features12.vulkanMemoryModel == VK_TRUE; 473 vulkan_memory_model = features12.vulkanMemoryModel == VK_TRUE;