replay.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //! `victory replay`: a captured frame run again (docs/replay.md).
  2. use std::path::PathBuf;
  3. use anyhow::{Context, Result};
  4. use clap::{Args, ValueEnum};
  5. use victory_hle::replay::play::{self, Options};
  6. #[derive(Clone, Copy, ValueEnum)]
  7. enum Timing {
  8. /// Each list.
  9. Lists,
  10. /// Each command (adds some time of its own).
  11. Detailed,
  12. }
  13. #[derive(Clone, Copy, ValueEnum)]
  14. enum Buffers {
  15. AsRecorded,
  16. /// All in the card's memory.
  17. Vram,
  18. /// All in the PC's memory.
  19. Sysmem,
  20. }
  21. #[derive(Args)]
  22. pub(crate) struct Replay {
  23. /// The folder given as VICTORY_RECORD (its last capture) or a capture.
  24. folder: PathBuf,
  25. /// How often the frame is run.
  26. #[arg(long, default_value_t = 5)]
  27. loops: u32,
  28. /// Do not put back, between runs, what a run changed.
  29. #[arg(long)]
  30. no_restore: bool,
  31. #[arg(long, value_enum, default_value_t = Timing::Lists)]
  32. timing: Timing,
  33. /// Pipelines listed with detailed timing.
  34. #[arg(long, default_value_t = 20)]
  35. top: usize,
  36. /// Where the picture goes (default: replay.png in the capture).
  37. #[arg(long)]
  38. image: Option<PathBuf>,
  39. /// Run the frame unchanged first, and print both.
  40. #[arg(long)]
  41. compare: bool,
  42. /// Leave out unordered-access barriers.
  43. #[arg(long)]
  44. no_barriers: bool,
  45. /// Join barrier calls with no work between them.
  46. #[arg(long)]
  47. merge_barriers: bool,
  48. /// Leave out the argument clamps: what they bound is kept from a first run.
  49. #[arg(long)]
  50. skip_clamps: bool,
  51. /// The argument clamps in batches, as VICTORY_INDIRECT_BATCH does (2:
  52. /// a wait before every indirect dispatch).
  53. #[arg(long, num_args = 0..=1, default_missing_value = "1", default_value_t = 0)]
  54. batch_clamps: u32,
  55. /// Leave out the hash and compare passes over card buffers.
  56. #[arg(long)]
  57. skip_hash_passes: bool,
  58. /// Where buffers lie.
  59. #[arg(long, value_enum, default_value_t = Buffers::AsRecorded)]
  60. buffers: Buffers,
  61. /// With --buffers, only the buffers all of these match: `name=<text>`,
  62. /// `min=<bytes>`, `max=<bytes>`, `seen=<No, Cached, Combined>`,
  63. /// `id=<a>..<b>`, or `!` and one of those (may be given several times).
  64. #[arg(long)]
  65. only_buffers: Vec<String>,
  66. /// One ExecuteCommandLists for the whole frame.
  67. #[arg(long)]
  68. one_submit: bool,
  69. /// Let copies of what the CPU wrote also overwrite what the card wrote in
  70. /// the replay (as the recorded commands say).
  71. #[arg(long)]
  72. no_merge: bool,
  73. /// A full wait after every draw, dispatch, copy and clear.
  74. #[arg(long)]
  75. wait_all: bool,
  76. /// Each list sent on its own, and waited for.
  77. #[arg(long)]
  78. wait_lists: bool,
  79. /// Milliseconds to wait after sending each submission: the card stands
  80. /// idle between them, as it does while the title prepares the next.
  81. #[arg(long, default_value_t = 0.0)]
  82. pace: f64,
  83. /// Keep the card's clocks up meanwhile (VICTORY_CARD_AWAKE=1).
  84. #[arg(long)]
  85. awake: bool,
  86. /// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light).
  87. #[arg(long)]
  88. breadcrumbs: bool,
  89. /// Run only these lists, by their place in the frame (`3..7`, or `5`);
  90. /// of the others only barriers.
  91. #[arg(long)]
  92. only: Option<String>,
  93. /// Leave out what runs a pipeline whose name or DXIL hash has this in it
  94. /// (may be given several times).
  95. #[arg(long = "skip-shader")]
  96. skip_shader: Vec<String>,
  97. /// Find the commands that make identical runs differ: each list is run
  98. /// this often from the same memory.
  99. #[arg(long, num_args = 0..=1, default_missing_value = "3")]
  100. diverge: Option<u32>,
  101. /// Find where the picture's variants are decided: from each list on, the
  102. /// rest of the frame is run this often from the same memory.
  103. #[arg(long, num_args = 0..=1, default_missing_value = "5")]
  104. diverge_picture: Option<u32>,
  105. /// Run each draw of one list (--lists) whose pipeline's name has this in
  106. /// it alone, --diverge times: how many outcomes it has.
  107. #[arg(long)]
  108. draws: Option<String>,
  109. /// Say which lists (with --lists: commands) change words of buffers:
  110. /// `<resource>:<offset>:<bytes>` (hexadecimal; repeatable).
  111. #[arg(long)]
  112. watch: Vec<String>,
  113. /// With --diverge-picture and one list in --lists: its commands (`0..900`)
  114. /// and how many are stepped over at a time.
  115. #[arg(long)]
  116. commands: Option<String>,
  117. #[arg(long, default_value_t = 1)]
  118. step: usize,
  119. /// With --diverge and --diverge-picture: only these lists (`3..7`).
  120. #[arg(long)]
  121. lists: Option<String>,
  122. /// With --diverge: the most commands named of one list.
  123. #[arg(long, default_value_t = 4)]
  124. roots: u32,
  125. /// Name resources the frame changes that the replay does not put back.
  126. #[arg(long)]
  127. check_written: bool,
  128. /// Run the frame twice and say which words the copies of the CPU's sides
  129. /// of card buffers bring that the card holds another value of, and what
  130. /// shaders wrote that was not declared as written.
  131. #[arg(long)]
  132. upcopies: bool,
  133. /// Name what the heap slots hold that a command's constants name:
  134. /// `<list>:<command>`.
  135. #[arg(long)]
  136. slots: Option<String>,
  137. /// Only write the DXIL of pipelines with this in their name to the
  138. /// capture's `shaders` folder.
  139. #[arg(long)]
  140. dump: Option<String>,
  141. /// Only write the frame's buffers and the commands of these lists (`3..7`).
  142. #[arg(long)]
  143. listing: Option<String>,
  144. /// Only write what the dispatches of these lists have bound (`3..7`).
  145. #[arg(long)]
  146. flow: Option<String>,
  147. /// With --flow: draws too.
  148. #[arg(long)]
  149. flow_draws: bool,
  150. /// With --flow: heap slots shown from each place named.
  151. #[arg(long, default_value_t = 40)]
  152. flow_slots: u32,
  153. /// Run the frame once and save textures as pictures in this folder, with
  154. /// what values they hold (see --texture, --until).
  155. #[arg(long)]
  156. images: Option<PathBuf>,
  157. /// With --images: `<resource>[.<subresource>]` (repeatable); none: all
  158. /// that the frame's shaders write.
  159. #[arg(long)]
  160. texture: Vec<String>,
  161. /// With --images and no --texture: from this many texels on.
  162. #[arg(long, default_value_t = 4096)]
  163. least: u64,
  164. /// With --images: the widest picture.
  165. #[arg(long, default_value_t = 960)]
  166. width: u32,
  167. /// With --images: the values too.
  168. #[arg(long)]
  169. raw: bool,
  170. /// The last command that runs, `<list>:<command>`; after it only barriers.
  171. #[arg(long)]
  172. until: Option<String>,
  173. /// Say which commands change the pixel: `<x>,<y>` of the presented
  174. /// picture, or `<resource>[.<subresource>]:<x>,<y>` of a texture
  175. /// (repeatable). With --lists, only those are looked into.
  176. #[arg(long)]
  177. pixel: Vec<String>,
  178. /// With --pixel: the size of the picture the points are of (`1280x720`),
  179. /// if it is another than the presented one's.
  180. #[arg(long)]
  181. of: Option<String>,
  182. /// With --pixel: depth targets too.
  183. #[arg(long)]
  184. depth: bool,
  185. /// With --pixel: leave out textures that shaders may write (unordered
  186. /// access).
  187. #[arg(long)]
  188. targets_only: bool,
  189. /// With --pixel: indirect calls whose draws are run one by one:
  190. /// `<list>:<command>` (repeatable).
  191. #[arg(long)]
  192. split: Vec<String>,
  193. /// Take shaders from this folder where it has them (`<hash>.dxil`, by the
  194. /// hash the runtime names the title's shader by).
  195. #[arg(long)]
  196. shaders: Option<PathBuf>,
  197. /// With --compare: the folder the second run's shaders are from.
  198. #[arg(long)]
  199. shaders_b: Option<PathBuf>,
  200. /// Only translate the capture's shaders, into this folder (for --shaders),
  201. /// with the translator's settings of this run. Containers are looked up in
  202. /// `containers` beside the capture, and first collected there from the
  203. /// title's files.
  204. #[arg(long)]
  205. retranslate: Option<PathBuf>,
  206. /// With --retranslate: the view heap's null slot, and where raw twins of
  207. /// views start, as the capture's shaders have them (0: none).
  208. #[arg(long, default_value_t = 0)]
  209. view_limit: u32,
  210. #[arg(long, default_value_t = 0)]
  211. raw_views: u32,
  212. /// Use the D3D12 debug layer (slow).
  213. #[arg(long)]
  214. debug_layer: bool,
  215. }
  216. /// `3..7` (both included) or `5`.
  217. fn range(text: &str) -> Option<(u32, u32)> {
  218. match text.split_once("..") {
  219. Some((a, b)) => Some((a.trim().parse().ok()?, b.trim().parse().ok()?)),
  220. None => text.trim().parse().ok().map(|n| (n, n)),
  221. }
  222. }
  223. /// Two numbers with `by` between them.
  224. fn pair(text: &str, by: char) -> Option<(u32, u32)> {
  225. let (a, b) = text.split_once(by)?;
  226. Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
  227. }
  228. pub(crate) fn run(r: Replay) -> Result<()> {
  229. if let Some(text) = &r.dump {
  230. for line in play::dump(&r.folder, text)? {
  231. println!("{line}");
  232. }
  233. return Ok(());
  234. }
  235. if let Some(text) = &r.listing {
  236. let lists = range(text).with_context(|| format!("--listing {text}"))?;
  237. return play::listing(&r.folder, lists, &mut |line| println!("{line}"));
  238. }
  239. if let Some(text) = &r.flow {
  240. let lists = range(text).with_context(|| format!("--flow {text}"))?;
  241. return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}"));
  242. }
  243. if let Some(into) = &r.retranslate {
  244. return retranslate(&r.folder, into, r.view_limit, r.raw_views);
  245. }
  246. let until = match &r.until {
  247. Some(text) => Some(
  248. text.split_once(':')
  249. .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
  250. .with_context(|| format!("--until {text}: not <list>:<command>"))?,
  251. ),
  252. None => None,
  253. };
  254. let only = match &r.only {
  255. Some(text) => Some(
  256. range(text)
  257. .with_context(|| format!("--only {text}: not a list or a range of lists (3..7)"))?,
  258. ),
  259. None => None,
  260. };
  261. let options = Options {
  262. loops: r.loops.max(1),
  263. restore: !r.no_restore,
  264. detailed: matches!(r.timing, Timing::Detailed),
  265. top: r.top,
  266. image: r.image,
  267. buffers: match r.buffers {
  268. Buffers::AsRecorded => play::Buffers::AsRecorded,
  269. Buffers::Vram => play::Buffers::Card,
  270. Buffers::Sysmem => play::Buffers::Pc,
  271. },
  272. only_buffers: r.only_buffers,
  273. no_barriers: r.no_barriers,
  274. merge_barriers: r.merge_barriers,
  275. skip_clamps: r.skip_clamps,
  276. batch_clamps: r.batch_clamps,
  277. skip_hash_passes: r.skip_hash_passes,
  278. one_submit: r.one_submit,
  279. merge: !r.no_merge,
  280. wait_all: r.wait_all,
  281. wait_lists: r.wait_lists,
  282. pace: r.pace,
  283. awake: r.awake,
  284. only,
  285. until,
  286. skip_shaders: r.skip_shader,
  287. shaders: r.shaders,
  288. shaders_b: r.shaders_b,
  289. compare: r.compare,
  290. debug: r.debug_layer,
  291. breadcrumbs: r.breadcrumbs,
  292. };
  293. if let Some(text) = &r.slots {
  294. let (list, command) = text
  295. .split_once(':')
  296. .and_then(|(l, c)| Some((l.parse().ok()?, c.parse().ok()?)))
  297. .with_context(|| format!("--slots {text}: not <list>:<command>"))?;
  298. let player = play::Player::load(&r.folder, &options)?;
  299. return player.slots(list, command, &mut |line| println!("{line}"));
  300. }
  301. if let Some(folder) = &r.images {
  302. let mut which = Vec::new();
  303. for text in &r.texture {
  304. let (id, sub) = text.split_once('.').unwrap_or((text, "0"));
  305. let bad = || format!("--texture {text}");
  306. which.push((id.parse().with_context(bad)?, sub.parse().with_context(bad)?));
  307. }
  308. let images = play::look::Images {
  309. which,
  310. least: r.least,
  311. folder: folder.clone(),
  312. width: r.width,
  313. raw: r.raw,
  314. };
  315. let mut player = play::Player::load(&r.folder, &options)?;
  316. return player.images(&options, &images, &mut |line| println!("{line}"));
  317. }
  318. if !r.pixel.is_empty() {
  319. let mut player = play::Player::load(&r.folder, &options)?;
  320. let mut pixels = play::pixel::Pixels {
  321. depth: r.depth,
  322. written: !r.targets_only,
  323. ..Default::default()
  324. };
  325. if let Some(text) = &r.lists {
  326. pixels.lists = Some(range(text).with_context(|| format!("--lists {text}"))?);
  327. }
  328. let of = match &r.of {
  329. Some(text) => Some(pair(text, 'x').with_context(|| format!("--of {text}"))?),
  330. None => None,
  331. };
  332. for text in &r.pixel {
  333. let bad = || format!("--pixel {text}");
  334. match text.split_once(':') {
  335. Some((what, at)) => {
  336. let (id, sub) = what.split_once('.').unwrap_or((what, "0"));
  337. let (x, y) = pair(at, ',').with_context(bad)?;
  338. let id = id.parse().with_context(bad)?;
  339. let sub = sub.parse().with_context(bad)?;
  340. pixels.texels.push((id, sub, x, y));
  341. }
  342. None => {
  343. let (mut x, mut y) = pair(text, ',').with_context(bad)?;
  344. if let (Some((w, h)), Some((pw, ph))) = (of, player.picture_size()) {
  345. x = x * pw / w.max(1);
  346. y = y * ph / h.max(1);
  347. }
  348. pixels.points.push((x, y));
  349. }
  350. }
  351. }
  352. for text in &r.split {
  353. pixels
  354. .split
  355. .push(pair(text, ':').with_context(|| format!("--split {text}"))?);
  356. }
  357. return player.pixel(&options, &pixels, &mut |line| println!("{line}"));
  358. }
  359. if r.check_written {
  360. let mut player = play::Player::load(&r.folder, &options)?;
  361. return player.check_written(&mut |line| println!("{line}"));
  362. }
  363. if r.upcopies {
  364. let mut player = play::Player::load(&r.folder, &options)?;
  365. return player.upcopies(&options, &mut |line| println!("{line}"));
  366. }
  367. let mut watched = Vec::new();
  368. for text in &r.watch {
  369. let mut n = text
  370. .split(':')
  371. .map(|p| u64::from_str_radix(p.trim_start_matches("0x"), 16));
  372. let mut next = || {
  373. n.next()
  374. .and_then(Result::ok)
  375. .with_context(|| format!("--watch {text}"))
  376. };
  377. let id = text
  378. .split(':')
  379. .next()
  380. .and_then(|p| p.parse().ok())
  381. .with_context(|| format!("--watch {text}"))?;
  382. let _ = next();
  383. watched.push((id, next()?, next()?));
  384. }
  385. if let Some(runs) = r
  386. .diverge
  387. .or(r.diverge_picture)
  388. .or((!watched.is_empty()).then_some(2))
  389. {
  390. let lists = match &r.lists {
  391. Some(text) => Some(range(text).with_context(|| format!("--lists {text}"))?),
  392. None => None,
  393. };
  394. let search = play::diverge::Search {
  395. runs: runs.max(2),
  396. lists,
  397. roots: r.roots,
  398. wait_all: options.wait_all,
  399. options: options.clone(),
  400. };
  401. let mut player = play::Player::load(&r.folder, &options)?;
  402. if !watched.is_empty() {
  403. return player.watch(&search, &watched, &mut |line| println!("{line}"));
  404. }
  405. if let Some(text) = &r.draws {
  406. return player.diverge_draws(&search, text, &mut |line| println!("{line}"));
  407. }
  408. if r.diverge_picture.is_some() {
  409. let commands = match &r.commands {
  410. Some(text) => Some(range(text).with_context(|| format!("--commands {text}"))?),
  411. None => None,
  412. };
  413. return player
  414. .diverge_picture(&search, commands, r.step, &mut |line| println!("{line}"));
  415. }
  416. return player.diverge(&search, &mut |line| println!("{line}"));
  417. }
  418. let reports = play::replay(&r.folder, &options)?;
  419. for (what, report) in &reports {
  420. println!("{}", report.text(what));
  421. }
  422. if let [(_, before), (_, after)] = &reports[..] {
  423. println!("{:+.2} ms", after.median_ms() - before.median_ms());
  424. }
  425. Ok(())
  426. }
  427. /// Translates the capture's shaders into `into`.
  428. fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32, raw_views: u32) -> Result<()> {
  429. use std::sync::atomic::{AtomicUsize, Ordering};
  430. let wanted = play::title_shaders(folder)?;
  431. let kept = play::find(folder)?.with_file_name("containers");
  432. std::fs::create_dir_all(&kept)?;
  433. std::fs::create_dir_all(into)?;
  434. let mut missing: std::collections::HashSet<&str> = wanted
  435. .iter()
  436. .map(|w| w.1.as_str())
  437. .filter(|h| !kept.join(format!("{h}.cdxil")).exists())
  438. .collect();
  439. if !missing.is_empty() {
  440. println!("{} of {} containers are looked for in the title's files", missing.len(), wanted.len());
  441. for root in crate::default_paths(Vec::new())? {
  442. for entry in walkdir::WalkDir::new(root).into_iter().filter_map(std::result::Result::ok) {
  443. let size = entry.metadata().map_or(0, |m| m.len());
  444. if missing.is_empty() || !entry.file_type().is_file() || size > crate::shader::MAX_FILE {
  445. continue;
  446. }
  447. let Ok(data) = std::fs::read(entry.path()) else { continue };
  448. for source in crate::shader::sources(&data) {
  449. let Some(bytes) = source.bytes() else { continue };
  450. let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
  451. if missing.remove(hash.as_str()) {
  452. std::fs::write(kept.join(format!("{hash}.cdxil")), &bytes[..])?;
  453. }
  454. }
  455. }
  456. }
  457. }
  458. println!("{} containers not found", missing.len());
  459. victory_shader::emit::set_host_max_wave(64);
  460. victory_shader::emit::set_host_rdna(true);
  461. victory_shader::emit::set_view_heap_limit(view_limit);
  462. victory_shader::emit::set_raw_views(raw_views);
  463. let all: Vec<_> = wanted.iter().collect();
  464. let (next, done) = (AtomicUsize::new(0), AtomicUsize::new(0));
  465. let started = std::time::Instant::now();
  466. std::thread::scope(|s| {
  467. for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
  468. s.spawn(|| {
  469. while let Some((stage, hash)) = all.get(next.fetch_add(1, Ordering::Relaxed)) {
  470. let Ok(bytes) = std::fs::read(kept.join(format!("{hash}.cdxil"))) else { continue };
  471. match victory_shader::emit::translate(&bytes) {
  472. Ok(t) => {
  473. if std::fs::write(into.join(format!("{hash}.dxil")), &t.dxil).is_ok() {
  474. done.fetch_add(1, Ordering::Relaxed);
  475. }
  476. }
  477. Err(e) => println!("{stage} {hash}: {e}"),
  478. }
  479. }
  480. });
  481. }
  482. });
  483. println!("{} of {} shaders translated, {:.1} s", done.into_inner(), all.len(), started.elapsed().as_secs_f64());
  484. Ok(())
  485. }
  486. #[cfg(test)]
  487. mod tests {
  488. #[test]
  489. fn ranges() {
  490. assert_eq!(super::range("3..7"), Some((3, 7)));
  491. assert_eq!(super::range("5"), Some((5, 5)));
  492. assert_eq!(super::range("x"), None);
  493. assert_eq!(super::pair("12,7", ','), Some((12, 7)));
  494. assert_eq!(super::pair("12", ','), None);
  495. assert_eq!(super::range("1..x"), None);
  496. }
  497. }