known.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. //! Every pipeline the title has ever created, kept on disk
  2. //! (`VICTORY_PIPELINE_BOOK=1`), and their host pipelines made ahead of a run
  3. //! (`victory warm`), so that the driver's own cache on disk has them before
  4. //! a draw asks for one.
  5. //!
  6. //! The title creates 84,000 pipelines while it loads and draws with some
  7. //! 2,000 of them; which ones is known from earlier runs (`library`), and
  8. //! those are made during loading. One met for the first time (a place never
  9. //! seen, or everything after a change of the translator or of the driver) is
  10. //! compiled when a draw wants it. Making all of them in the running title
  11. //! (`VICTORY_EARLY_ALL=1`) ended it inside the driver's compiler; made here,
  12. //! a compiler that crashes or hangs ends a child process, costs that pipeline
  13. //! alone and is named in `warm-bad.txt`.
  14. //!
  15. //! Two files beside the library, both only ever added to (a torn end is cut
  16. //! off): `known-shaders.bin` (stage, hash, length, container) and
  17. //! `known-pipelines.bin` (length, then the key, the shaders' stages and
  18. //! hashes, and the graphics state). They hold the title's own code: they stay
  19. //! in the cache folder.
  20. use std::collections::{HashMap, HashSet};
  21. use std::ffi::CString;
  22. use std::io::{Read, Seek, SeekFrom, Write};
  23. use std::path::{Path, PathBuf};
  24. use std::sync::{Arc, Mutex, OnceLock};
  25. use windows::Win32::Graphics::Direct3D12::*;
  26. use windows::Win32::Graphics::Dxgi::Common::*;
  27. use windows::core::PCSTR;
  28. use super::Shader;
  29. use super::host::{GraphicsState, HostPipeline};
  30. const SHADERS: &str = "known-shaders.bin";
  31. const PIPELINES: &str = "known-pipelines.bin";
  32. /// Stages by their number in the files.
  33. const STAGES: [&str; 8] =
  34. ["vertex", "pixel", "domain", "hull", "geometry", "compute", "amplification", "mesh"];
  35. /// `VICTORY_PIPELINE_BOOK=1`: the pipelines the title creates are kept.
  36. fn on() -> bool {
  37. static ON: OnceLock<bool> = OnceLock::new();
  38. *ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_BOOK").is_some_and(|v| v == "1"))
  39. }
  40. struct Book {
  41. dir: PathBuf,
  42. keys: HashSet<[u8; 16]>,
  43. shaders: HashSet<[u8; 32]>,
  44. /// Not yet written: shaders, then pipelines.
  45. new: [Vec<u8>; 2],
  46. added: usize,
  47. }
  48. static BOOK: OnceLock<Option<Mutex<Book>>> = OnceLock::new();
  49. fn book() -> Option<&'static Mutex<Book>> {
  50. BOOK.get_or_init(|| {
  51. let dir = super::library::folder().filter(|_| on())?;
  52. std::fs::create_dir_all(&dir).ok()?;
  53. let mut keys = HashSet::new();
  54. let mut shaders = HashSet::new();
  55. let ends = [
  56. walk_shaders(&dir, |_, hash, _, _| drop(shaders.insert(hash))),
  57. walk_pipelines(&dir, |_, bytes| {
  58. keys.extend(bytes.first_chunk::<16>().copied());
  59. }),
  60. ];
  61. for (file, end) in [SHADERS, PIPELINES].iter().zip(ends) {
  62. let path = dir.join(file);
  63. if std::fs::metadata(&path).is_ok_and(|m| m.len() > end)
  64. && let Ok(f) = std::fs::OpenOptions::new().write(true).open(&path)
  65. {
  66. let _ = f.set_len(end);
  67. }
  68. }
  69. tracing::info!(pipelines = keys.len(), shaders = shaders.len(), "title pipelines known from earlier runs");
  70. let spawned = std::thread::Builder::new().name("victory-known".into()).spawn(|| {
  71. loop {
  72. std::thread::sleep(std::time::Duration::from_secs(2));
  73. flush();
  74. }
  75. });
  76. spawned.ok()?;
  77. Some(Mutex::new(Book { dir, keys, shaders, new: Default::default(), added: 0 }))
  78. })
  79. .as_ref()
  80. }
  81. /// The title created a pipeline.
  82. pub(super) fn note(key: &str, shaders: &[Arc<Shader>], graphics: Option<&GraphicsState>) {
  83. let Some(book) = book() else { return };
  84. let mut id = [0u8; 16];
  85. for (at, b) in id.iter_mut().enumerate() {
  86. *b = key.get(2 * at..2 * at + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).unwrap_or(0);
  87. }
  88. let mut book = book.lock().unwrap_or_else(|e| e.into_inner());
  89. if shaders.is_empty() || !book.keys.insert(id) {
  90. return;
  91. }
  92. let mut entry = id.to_vec();
  93. entry.push(shaders.len() as u8);
  94. for s in shaders {
  95. let hash = *blake3::hash(&s.container).as_bytes();
  96. let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u8;
  97. entry.push(stage);
  98. entry.extend(hash);
  99. if book.shaders.insert(hash) {
  100. let new = &mut book.new[0];
  101. new.push(stage);
  102. new.extend(hash);
  103. new.extend((s.container.len() as u32).to_le_bytes());
  104. new.extend(&s.container);
  105. }
  106. }
  107. entry.push(u8::from(graphics.is_some()));
  108. if let Some(g) = graphics {
  109. g.put(&mut entry);
  110. }
  111. book.new[1].extend((entry.len() as u32).to_le_bytes());
  112. book.new[1].extend(entry);
  113. book.added += 1;
  114. }
  115. /// Writes what was noted.
  116. fn flush() {
  117. let Some(Some(book)) = BOOK.get() else { return };
  118. let (dir, new, added) = {
  119. let mut book = book.lock().unwrap_or_else(|e| e.into_inner());
  120. if book.added == 0 {
  121. return;
  122. }
  123. (book.dir.clone(), std::mem::take(&mut book.new), std::mem::take(&mut book.added))
  124. };
  125. for (file, bytes) in [SHADERS, PIPELINES].iter().zip(&new) {
  126. let written = std::fs::OpenOptions::new()
  127. .create(true)
  128. .append(true)
  129. .open(dir.join(file))
  130. .and_then(|mut f| f.write_all(bytes));
  131. if let Err(e) = written {
  132. tracing::warn!(error = %e, file, "title pipelines not written down");
  133. return;
  134. }
  135. }
  136. tracing::info!(pipelines = added, "title pipelines written down");
  137. }
  138. /// Calls `f` with each container's stage, hash, place and length; where the
  139. /// last whole one ends.
  140. fn walk_shaders(dir: &Path, mut f: impl FnMut(u8, [u8; 32], u64, u32)) -> u64 {
  141. let Ok(file) = std::fs::File::open(dir.join(SHADERS)) else { return 0 };
  142. let len = file.metadata().map_or(0, |m| m.len());
  143. let mut file = std::io::BufReader::new(file);
  144. let mut at = 0;
  145. let mut head = [0u8; 37];
  146. while file.read_exact(&mut head).is_ok() {
  147. let size = u32::from_le_bytes([head[33], head[34], head[35], head[36]]);
  148. if at + 37 + u64::from(size) > len || file.seek_relative(i64::from(size)).is_err() {
  149. break;
  150. }
  151. let mut hash = [0; 32];
  152. hash.copy_from_slice(&head[1..33]);
  153. f(head[0], hash, at + 37, size);
  154. at += 37 + u64::from(size);
  155. }
  156. at
  157. }
  158. /// Calls `f` with each pipeline's number and entry; where the last whole one
  159. /// ends.
  160. fn walk_pipelines(dir: &Path, mut f: impl FnMut(usize, &[u8])) -> u64 {
  161. let bytes = std::fs::read(dir.join(PIPELINES)).unwrap_or_default();
  162. let (mut at, mut n) = (0, 0);
  163. while let Some(head) = bytes.get(at..at + 4) {
  164. let size = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
  165. let Some(entry) = bytes.get(at + 4..at + 4 + size) else { break };
  166. f(n, entry);
  167. (at, n) = (at + 4 + size, n + 1);
  168. }
  169. at as u64
  170. }
  171. /// How many pipelines are known in `dir`.
  172. pub fn count(dir: &Path) -> usize {
  173. let mut n = 0;
  174. walk_pipelines(dir, |_, _| n += 1);
  175. n
  176. }
  177. /// The key of each pipeline known in `dir`, as the early list has it.
  178. pub fn keys(dir: &Path) -> Vec<String> {
  179. let mut all = Vec::new();
  180. walk_pipelines(dir, |_, e| {
  181. all.push(e.get(..16).unwrap_or_default().iter().map(|b| format!("{b:02x}")).collect());
  182. });
  183. all
  184. }
  185. /// What a driver's cached pipelines depend on besides the title's: the
  186. /// translator with its settings, and the driver.
  187. pub fn fingerprint() -> String {
  188. let mut h = blake3::Hasher::new();
  189. h.update(&crate::shader_cache::translation());
  190. if let Some(host) = crate::host::host() {
  191. h.update(&host.driver().to_le_bytes());
  192. }
  193. h.finalize().to_hex()[..16].to_owned()
  194. }
  195. /// The translations of earlier runs are in `dir` (the pipeline library is
  196. /// not used: what is made here is the driver's to keep).
  197. pub fn use_translations(dir: PathBuf) {
  198. crate::shader_cache::use_shader_cache(dir);
  199. }
  200. /// Makes the host pipelines of those of `which` (numbers in the file) and
  201. /// lets each go again: the driver's cache on disk keeps them. `each` is told
  202. /// the number before, and what came of it after: milliseconds and whether
  203. /// there is one.
  204. pub fn make(dir: &Path, which: &[usize], mut each: impl FnMut(usize, Option<(f64, bool)>)) {
  205. let mut places = HashMap::new();
  206. walk_shaders(dir, |stage, hash, at, len| drop(places.insert(hash, (stage, at, len))));
  207. let Ok(mut file) = std::fs::File::open(dir.join(SHADERS)) else { return };
  208. let wanted: HashSet<usize> = which.iter().copied().collect();
  209. let mut entries = HashMap::new();
  210. walk_pipelines(dir, |n, bytes| {
  211. if wanted.contains(&n) {
  212. entries.insert(n, bytes.to_vec());
  213. }
  214. });
  215. let mut read = |hash: &[u8; 32]| {
  216. let &(_, at, len) = places.get(hash)?;
  217. let mut bytes = vec![0; len as usize];
  218. file.seek(SeekFrom::Start(at)).ok()?;
  219. file.read_exact(&mut bytes).ok()?;
  220. Some(bytes)
  221. };
  222. for n in which {
  223. let Some(entry) = entries.get(n) else { continue };
  224. each(*n, None);
  225. let began = std::time::Instant::now();
  226. let made = parse(entry, &mut read)
  227. .and_then(|(shaders, g)| HostPipeline::new(&shaders, g.as_deref()))
  228. .is_some();
  229. each(*n, Some((began.elapsed().as_secs_f64() * 1e3, made)));
  230. }
  231. }
  232. #[allow(clippy::type_complexity)]
  233. fn parse(
  234. entry: &[u8],
  235. read: &mut impl FnMut(&[u8; 32]) -> Option<Vec<u8>>,
  236. ) -> Option<(Vec<Arc<Shader>>, Option<Box<GraphicsState>>)> {
  237. let mut rest = entry.get(16..)?;
  238. let (&count, after) = rest.split_first()?;
  239. rest = after;
  240. let mut shaders = Vec::new();
  241. for _ in 0..count {
  242. let (head, after) = rest.split_first_chunk::<33>()?;
  243. rest = after;
  244. let mut hash = [0; 32];
  245. hash.copy_from_slice(&head[1..]);
  246. shaders.push(super::shader(STAGES.get(usize::from(head[0]))?, &read(&hash)?));
  247. }
  248. let (&graphics, rest) = rest.split_first()?;
  249. let g = match graphics {
  250. 0 => None,
  251. _ => Some(Box::new(GraphicsState::get(rest)?)),
  252. };
  253. Some((shaders, g))
  254. }
  255. /// Calls `$f` with each number of a graphics state but its input elements',
  256. /// as a place of 32 bits, in one order.
  257. macro_rules! numbers {
  258. ($g:expr, $f:ident) => {{
  259. $f!($g.blend.AlphaToCoverageEnable.0);
  260. $f!($g.blend.IndependentBlendEnable.0);
  261. for t in &mut $g.blend.RenderTarget {
  262. $f!(t.BlendEnable.0);
  263. $f!(t.LogicOpEnable.0);
  264. $f!(t.SrcBlend.0);
  265. $f!(t.DestBlend.0);
  266. $f!(t.BlendOp.0);
  267. $f!(t.SrcBlendAlpha.0);
  268. $f!(t.DestBlendAlpha.0);
  269. $f!(t.BlendOpAlpha.0);
  270. $f!(t.LogicOp.0);
  271. $f!(t.RenderTargetWriteMask);
  272. }
  273. $f!($g.sample_mask);
  274. $f!($g.rasterizer.FillMode.0);
  275. $f!($g.rasterizer.CullMode.0);
  276. $f!($g.rasterizer.FrontCounterClockwise.0);
  277. $f!($g.rasterizer.DepthBias);
  278. $f!($g.rasterizer.DepthClipEnable.0);
  279. $f!($g.rasterizer.MultisampleEnable.0);
  280. $f!($g.rasterizer.AntialiasedLineEnable.0);
  281. $f!($g.rasterizer.ForcedSampleCount);
  282. $f!($g.rasterizer.ConservativeRaster.0);
  283. $f!($g.depth.DepthEnable.0);
  284. $f!($g.depth.DepthWriteMask.0);
  285. $f!($g.depth.DepthFunc.0);
  286. $f!($g.depth.StencilEnable.0);
  287. $f!($g.depth.StencilReadMask);
  288. $f!($g.depth.StencilWriteMask);
  289. for face in [&mut $g.depth.FrontFace, &mut $g.depth.BackFace] {
  290. $f!(face.StencilFailOp.0);
  291. $f!(face.StencilDepthFailOp.0);
  292. $f!(face.StencilPassOp.0);
  293. $f!(face.StencilFunc.0);
  294. }
  295. $f!($g.strip_cut.0);
  296. $f!($g.topology.0);
  297. $f!($g.targets.NumRenderTargets);
  298. for format in &mut $g.targets.RTFormats {
  299. $f!(format.0);
  300. }
  301. $f!($g.depth_format.0);
  302. $f!($g.samples.Count);
  303. $f!($g.samples.Quality);
  304. }};
  305. }
  306. impl GraphicsState {
  307. /// The state as bytes.
  308. fn put(&self, out: &mut Vec<u8>) {
  309. out.push(u8::from(self.depth_bounds));
  310. for f in [self.rasterizer.DepthBiasClamp, self.rasterizer.SlopeScaledDepthBias] {
  311. out.extend(f.to_le_bytes());
  312. }
  313. let mut plain = GraphicsState {
  314. blend: self.blend,
  315. sample_mask: self.sample_mask,
  316. rasterizer: self.rasterizer,
  317. depth: self.depth,
  318. strip_cut: self.strip_cut,
  319. topology: self.topology,
  320. targets: self.targets,
  321. depth_format: self.depth_format,
  322. samples: self.samples,
  323. ..Default::default()
  324. };
  325. macro_rules! write {
  326. ($x:expr) => {
  327. out.extend(($x as u32).to_le_bytes())
  328. };
  329. }
  330. numbers!(plain, write);
  331. out.push(self.inputs.len() as u8);
  332. for (e, name) in self.inputs.iter().zip(&self.names) {
  333. let name = name.as_bytes();
  334. out.push(name.len() as u8);
  335. out.extend(name);
  336. for v in [
  337. e.SemanticIndex,
  338. e.Format.0 as u32,
  339. e.InputSlot,
  340. e.AlignedByteOffset,
  341. e.InputSlotClass.0 as u32,
  342. e.InstanceDataStepRate,
  343. ] {
  344. out.extend(v.to_le_bytes());
  345. }
  346. }
  347. }
  348. fn get(bytes: &[u8]) -> Option<GraphicsState> {
  349. let mut g = GraphicsState::default();
  350. let (&bounds, mut rest) = bytes.split_first()?;
  351. g.depth_bounds = bounds != 0;
  352. let mut next = || {
  353. let (head, after) = rest.split_first_chunk::<4>()?;
  354. rest = after;
  355. Some(u32::from_le_bytes(*head))
  356. };
  357. g.rasterizer.DepthBiasClamp = f32::from_bits(next()?);
  358. g.rasterizer.SlopeScaledDepthBias = f32::from_bits(next()?);
  359. macro_rules! read {
  360. ($x:expr) => {
  361. $x = next()? as _
  362. };
  363. }
  364. numbers!(g, read);
  365. let (&count, mut rest) = rest.split_first()?;
  366. let mut elements = Vec::new();
  367. for _ in 0..count {
  368. let (&len, after) = rest.split_first()?;
  369. let (name, after) = after.split_at_checked(usize::from(len))?;
  370. let (numbers, after) = after.split_first_chunk::<24>()?;
  371. rest = after;
  372. let mut v = [0u32; 6];
  373. for (v, b) in v.iter_mut().zip(numbers.chunks_exact(4)) {
  374. *v = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
  375. }
  376. elements.push((CString::new(name).ok()?, v));
  377. }
  378. g.names = elements.iter().map(|e| e.0.clone()).collect();
  379. g.inputs = g
  380. .names
  381. .iter()
  382. .zip(&elements)
  383. .map(|(name, (_, v))| D3D12_INPUT_ELEMENT_DESC {
  384. SemanticName: PCSTR(name.as_ptr().cast()),
  385. SemanticIndex: v[0],
  386. Format: DXGI_FORMAT(v[1] as i32),
  387. InputSlot: v[2],
  388. AlignedByteOffset: v[3],
  389. InputSlotClass: D3D12_INPUT_CLASSIFICATION(v[4] as i32),
  390. InstanceDataStepRate: v[5],
  391. })
  392. .collect();
  393. Some(g)
  394. }
  395. }
  396. #[cfg(test)]
  397. mod tests {
  398. use super::*;
  399. #[test]
  400. fn a_state_comes_back_as_it_was() {
  401. let mut g = GraphicsState { sample_mask: 7, depth_bounds: true, ..Default::default() };
  402. g.rasterizer.DepthBias = -3;
  403. g.rasterizer.SlopeScaledDepthBias = 1.25;
  404. g.blend.RenderTarget[3].RenderTargetWriteMask = 5;
  405. g.depth.StencilReadMask = 9;
  406. g.targets.NumRenderTargets = 2;
  407. g.targets.RTFormats[1] = DXGI_FORMAT_R8_UNORM;
  408. g.depth_format = DXGI_FORMAT_D32_FLOAT;
  409. g.names = vec![CString::new("POSITION").unwrap(), CString::new("T").unwrap()];
  410. g.inputs = g
  411. .names
  412. .iter()
  413. .enumerate()
  414. .map(|(n, name)| D3D12_INPUT_ELEMENT_DESC {
  415. SemanticName: PCSTR(name.as_ptr().cast()),
  416. SemanticIndex: n as u32,
  417. Format: DXGI_FORMAT_R32G32_FLOAT,
  418. InputSlot: 2,
  419. AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT,
  420. InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA,
  421. InstanceDataStepRate: 4,
  422. })
  423. .collect();
  424. let mut bytes = Vec::new();
  425. g.put(&mut bytes);
  426. let back = GraphicsState::get(&bytes).expect("whole");
  427. assert_eq!(back.describe(), g.describe());
  428. assert!(GraphicsState::get(&bytes[..bytes.len() - 1]).is_none());
  429. assert!(GraphicsState::get(&bytes[..9]).is_none());
  430. }
  431. #[test]
  432. fn a_torn_end_is_not_read() {
  433. let dir = std::env::temp_dir().join(format!("victory-known-{}", std::process::id()));
  434. std::fs::create_dir_all(&dir).unwrap();
  435. let mut bytes = Vec::new();
  436. for n in 0..3u8 {
  437. bytes.extend(20u32.to_le_bytes());
  438. bytes.extend([n; 20]);
  439. }
  440. std::fs::write(dir.join(PIPELINES), &bytes[..bytes.len() - 5]).unwrap();
  441. assert_eq!(count(&dir), 2);
  442. assert_eq!(keys(&dir)[1], "01".repeat(16));
  443. assert_eq!(walk_pipelines(&dir, |_, _| ()), 48);
  444. let mut shader = vec![5u8];
  445. shader.extend([9; 32]);
  446. shader.extend(4u32.to_le_bytes());
  447. shader.extend([1, 2, 3, 4]);
  448. let one = shader.len() as u64;
  449. shader.extend_from_slice(&shader.clone()[..20]);
  450. std::fs::write(dir.join(SHADERS), &shader).unwrap();
  451. let mut seen = Vec::new();
  452. assert_eq!(walk_shaders(&dir, |stage, hash, at, len| seen.push((stage, hash[0], at, len))), one);
  453. assert_eq!(seen, [(5, 9, 37, 4)]);
  454. let _ = std::fs::remove_dir_all(&dir);
  455. }
  456. }