play.rs 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546
  1. //! The replayer: makes a captured frame's objects again, puts their
  2. //! contents back, and runs the frame as often as asked, with its time on
  3. //! the card and experiments on it (`super::edit`).
  4. use std::collections::{BTreeMap, HashMap, HashSet};
  5. use std::fmt::Write as _;
  6. use std::fs::File;
  7. use std::os::windows::fs::FileExt;
  8. use std::path::{Path, PathBuf};
  9. use std::sync::atomic::{AtomicUsize, Ordering};
  10. use std::time::Instant;
  11. use anyhow::{Context, Result, anyhow, bail};
  12. use windows::Win32::Foundation::RECT;
  13. use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY};
  14. use windows::Win32::Graphics::Direct3D12::*;
  15. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  16. use windows::Win32::Graphics::Dxgi::*;
  17. use windows::core::Interface;
  18. use super::edit::{self, Clamp, RESULTS};
  19. use super::gpu::{self, Seen, Worker};
  20. use super::snap::read_sub;
  21. use super::states::{
  22. self, COMMON, COPY_DEST, COPY_SOURCE, DEPTH_WRITE, RENDER_TARGET, RESOLVE_DEST, States,
  23. UNORDERED_ACCESS,
  24. };
  25. use super::wire::{
  26. self, ALL, Barrier, Cmd, Content, Delta, Frame, Loc, MISSING, NONE, Place, Slot, Va, ZERO, slot,
  27. };
  28. pub mod diverge;
  29. pub mod look;
  30. mod merge;
  31. pub mod pixel;
  32. mod upcopies;
  33. /// The name of the argument clamp's pipeline, by which its passes are
  34. /// recognised.
  35. pub const CLAMP: &str = "victory: argument clamp";
  36. /// The name of the pipeline that compares and hashes card buffers.
  37. pub const COMPARE: &str = "victory: card compare";
  38. /// An upload buffer contents come back through.
  39. const STAGING: u64 = 256 << 20;
  40. /// Where buffers the CPU saw lie in a replay.
  41. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  42. pub enum Buffers {
  43. /// Where they lay.
  44. #[default]
  45. AsRecorded,
  46. /// All in the card's memory.
  47. Card,
  48. /// All in the PC's memory, the card's own buffers too.
  49. Pc,
  50. }
  51. #[derive(Clone, Debug)]
  52. pub struct Options {
  53. pub loops: u32,
  54. /// Put back, before each run, what the run before changed.
  55. pub restore: bool,
  56. /// Time every command, not only lists.
  57. pub detailed: bool,
  58. /// Shaders listed.
  59. pub top: usize,
  60. /// Where the picture goes (default: `replay.png` in the capture).
  61. pub image: Option<PathBuf>,
  62. pub buffers: Buffers,
  63. /// Of those, only the ones all of these match ([`chosen`]).
  64. pub only_buffers: Vec<String>,
  65. pub no_barriers: bool,
  66. pub merge_barriers: bool,
  67. pub skip_clamps: bool,
  68. /// The clamps in batches (`edit::batch_clamps`); 2: carefully.
  69. pub batch_clamps: u32,
  70. pub skip_hash_passes: bool,
  71. pub one_submit: bool,
  72. /// Copies of what the CPU wrote leave alone what the card wrote in this
  73. /// run (`merge`).
  74. pub merge: bool,
  75. /// A full wait after every command that works.
  76. pub wait_all: bool,
  77. /// Each list sent on its own, and waited for.
  78. pub wait_lists: bool,
  79. /// Milliseconds the sender waits after each submission, as a title does
  80. /// that prepares the next one meanwhile: the card stands idle.
  81. pub pace: f64,
  82. /// The card kept awake meanwhile (`crate::host::awake`).
  83. pub awake: bool,
  84. /// Run only these lists (by their place in the frame).
  85. pub only: Option<(u32, u32)>,
  86. /// The last command that runs (list, command); after it only barriers.
  87. pub until: Option<(u32, usize)>,
  88. /// Skip what runs a pipeline whose name or shader hash has one of
  89. /// these in it.
  90. pub skip_shaders: Vec<String>,
  91. /// Shaders taken from this folder where it has them: `<hash>.dxil`, by
  92. /// the hash the runtime names the title's shader by (ours: by their own).
  93. pub shaders: Option<PathBuf>,
  94. /// With `compare`: the folder the shaders of the second are from.
  95. pub shaders_b: Option<PathBuf>,
  96. /// Run the frame unchanged first, and compare.
  97. pub compare: bool,
  98. /// The debug layer, if it is installed.
  99. pub debug: bool,
  100. /// The system's breadcrumbs after every command, as
  101. /// `VICTORY_D3D12_DRED=light` has them.
  102. pub breadcrumbs: bool,
  103. }
  104. impl Default for Options {
  105. fn default() -> Self {
  106. Options {
  107. loops: 5,
  108. restore: true,
  109. detailed: false,
  110. top: 20,
  111. image: None,
  112. buffers: Buffers::AsRecorded,
  113. only_buffers: Vec::new(),
  114. no_barriers: false,
  115. merge_barriers: false,
  116. skip_clamps: false,
  117. batch_clamps: 0,
  118. skip_hash_passes: false,
  119. one_submit: false,
  120. merge: true,
  121. wait_all: false,
  122. wait_lists: false,
  123. pace: 0.0,
  124. awake: false,
  125. only: None,
  126. until: None,
  127. skip_shaders: Vec::new(),
  128. shaders: None,
  129. shaders_b: None,
  130. compare: false,
  131. debug: false,
  132. breadcrumbs: false,
  133. }
  134. }
  135. }
  136. impl Options {
  137. fn edited(&self) -> bool {
  138. self.no_barriers
  139. || self.merge_barriers
  140. || self.skip_clamps
  141. || self.batch_clamps > 0
  142. || self.skip_hash_passes
  143. || self.one_submit
  144. || self.wait_all
  145. || self.wait_lists
  146. || self.only.is_some()
  147. || !self.skip_shaders.is_empty()
  148. }
  149. /// The same without the experiments.
  150. fn plain(&self) -> Options {
  151. Options {
  152. no_barriers: false,
  153. merge_barriers: false,
  154. skip_clamps: false,
  155. batch_clamps: 0,
  156. skip_hash_passes: false,
  157. one_submit: false,
  158. wait_all: false,
  159. wait_lists: false,
  160. awake: false,
  161. only: None,
  162. skip_shaders: Vec::new(),
  163. ..self.clone()
  164. }
  165. }
  166. }
  167. /// How a run went.
  168. #[derive(Clone, Debug, Default)]
  169. pub struct Report {
  170. /// Per loop: from the first list's start to the last one's end, in ms.
  171. pub frame_ms: Vec<f64>,
  172. /// Per loop: how long the lists of submissions ran.
  173. pub busy_ms: Vec<f64>,
  174. /// Per loop: copies of ours that stand for what the CPU wrote.
  175. pub delta_ms: Vec<f64>,
  176. /// Of the last loop, by submission: lists, ms.
  177. pub submits: Vec<(usize, f64)>,
  178. /// With detailed timing: ms (median of the loops) and count by category.
  179. pub categories: Vec<(String, f64, u32)>,
  180. /// With detailed timing: ms, count and name of the costliest pipelines.
  181. pub shaders: Vec<(f64, u32, String)>,
  182. /// Against the presented picture: dB (infinite: the same), and whether
  183. /// its bytes are the same.
  184. pub picture: Option<(f64, bool)>,
  185. /// Of each loop's picture: dB against the presented one, and its hash.
  186. pub pictures: Vec<(f64, String)>,
  187. /// Things to know: from the capture and the replay.
  188. pub notes: Vec<String>,
  189. }
  190. impl Report {
  191. pub fn median_ms(&self) -> f64 {
  192. median(&self.frame_ms)
  193. }
  194. /// The report as text.
  195. pub fn text(&self, what: &str) -> String {
  196. let mut t = String::new();
  197. let ms = |v: &[f64]| {
  198. v.iter()
  199. .map(|x| format!("{x:.2}"))
  200. .collect::<Vec<_>>()
  201. .join(" ")
  202. };
  203. let _ = writeln!(
  204. t,
  205. "{what}: {:.2} ms on the card (median of {})",
  206. self.median_ms(),
  207. self.frame_ms.len()
  208. );
  209. let _ = writeln!(t, " loops, ms: {}", ms(&self.frame_ms));
  210. let (busy, delta) = (median(&self.busy_ms), median(&self.delta_ms));
  211. let idle = (self.median_ms() - busy - delta).max(0.0);
  212. let _ = writeln!(
  213. t,
  214. " submissions busy {busy:.2} ms, copies standing for CPU writes {delta:.2} ms, between submissions {idle:.2} ms"
  215. );
  216. let _ = writeln!(t, " by submission (lists: ms): {}", {
  217. self.submits
  218. .iter()
  219. .enumerate()
  220. .map(|(i, (n, ms))| format!("{i} ({n}): {ms:.2}"))
  221. .collect::<Vec<_>>()
  222. .join(", ")
  223. });
  224. if !self.categories.is_empty() {
  225. let _ = writeln!(t, " by kind of command, ms (commands):");
  226. for (name, ms, n) in &self.categories {
  227. let _ = writeln!(t, " {ms:8.2} {n:6} {name}");
  228. }
  229. }
  230. if !self.shaders.is_empty() {
  231. let _ = writeln!(t, " costliest pipelines, ms (commands):");
  232. for (ms, n, name) in &self.shaders {
  233. let _ = writeln!(t, " {ms:8.2} {n:6} {name}");
  234. }
  235. }
  236. match self.picture {
  237. Some((_, true)) => _ = writeln!(t, " picture: the same bytes as presented"),
  238. Some((db, false)) => {
  239. _ = writeln!(
  240. t,
  241. " picture: differs from the presented one, PSNR {db:.1} dB"
  242. )
  243. }
  244. None => {}
  245. }
  246. if self.pictures.len() > 1 {
  247. let all: Vec<String> = self
  248. .pictures
  249. .iter()
  250. .map(|(db, hash)| format!("{db:.1} dB {}", &hash[..8]))
  251. .collect();
  252. let kinds: HashSet<&String> = self.pictures.iter().map(|p| &p.1).collect();
  253. let _ = writeln!(
  254. t,
  255. " pictures of the loops: {} different: {}",
  256. kinds.len(),
  257. all.join(", ")
  258. );
  259. }
  260. for n in &self.notes {
  261. let _ = writeln!(t, " note: {n}");
  262. }
  263. t
  264. }
  265. }
  266. /// Whether `--only-buffers` means a buffer: all of `only` match it.
  267. /// `name=<text in its name>`, `min=<bytes>`, `max=<bytes>`,
  268. /// `seen=<how the CPU saw it>`, `id=<a>..<b>`; with `!` in front: that does not.
  269. fn chosen(r: &wire::Resource, only: &[String]) -> bool {
  270. only.iter().all(|f| {
  271. let (no, f) = match f.strip_prefix('!') {
  272. Some(f) => (true, f),
  273. None => (false, f.as_str()),
  274. };
  275. let (key, value) = f.split_once('=').unwrap_or(("name", f));
  276. let number = value.parse().unwrap_or(0u64);
  277. let is = match key {
  278. "min" => r.desc.width >= number,
  279. "max" => r.desc.width <= number,
  280. "seen" => {
  281. matches!(&r.place, Place::Committed { props, .. } if format!("{:?}", gpu::seen(props)).eq_ignore_ascii_case(value))
  282. }
  283. "id" => value.split_once("..").is_some_and(|(a, b)| {
  284. (a.parse().unwrap_or(0)..b.parse().unwrap_or(u32::MAX)).contains(&r.id)
  285. }),
  286. _ => r.name.contains(value),
  287. };
  288. is != no
  289. })
  290. }
  291. fn median(v: &[f64]) -> f64 {
  292. let mut v = v.to_vec();
  293. v.sort_by(f64::total_cmp);
  294. v.get(v.len() / 2).copied().unwrap_or(0.0)
  295. }
  296. /// The folder of a capture: `folder`, or the last `capture-<n>` in it that
  297. /// is complete.
  298. pub fn find(folder: &Path) -> Result<PathBuf> {
  299. if folder.join("frame.bin").exists() {
  300. return Ok(folder.to_owned());
  301. }
  302. let mut best: Option<(u32, PathBuf)> = None;
  303. for entry in std::fs::read_dir(folder)
  304. .with_context(|| format!("{}", folder.display()))?
  305. .flatten()
  306. {
  307. let name = entry.file_name().to_string_lossy().into_owned();
  308. let Some(n) = name.strip_prefix("capture-").and_then(|n| n.parse().ok()) else {
  309. continue;
  310. };
  311. if entry.path().join("frame.bin").exists() && best.as_ref().is_none_or(|b| b.0 < n) {
  312. best = Some((n, entry.path()));
  313. }
  314. }
  315. best.map(|b| b.1)
  316. .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display()))
  317. }
  318. /// The stage and hash by which the runtime names each of the title's shaders
  319. /// in a capture.
  320. pub fn title_shaders(folder: &Path) -> Result<std::collections::BTreeSet<(String, String)>> {
  321. let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
  322. let mut all = std::collections::BTreeSet::new();
  323. for p in &frame.pipelines {
  324. for part in &p.parts {
  325. if let wire::Part::Code { blob, .. } = part
  326. && let Some(hash) = title_hash(p, *blob)
  327. {
  328. let at = p.name.find(hash).unwrap_or(0);
  329. let stage = p.name[..at].trim_end().rsplit(['[', ' ']).next().unwrap_or("");
  330. all.insert((stage.to_owned(), hash.to_owned()));
  331. }
  332. }
  333. }
  334. Ok(all)
  335. }
  336. /// The hash by which the runtime names the title's shader that code blob
  337. /// `blob` of pipeline `p` is the translation of.
  338. fn title_hash(p: &wire::Pipeline, blob: u32) -> Option<&str> {
  339. let kind = p.parts.iter().find_map(|part| match part {
  340. wire::Part::Code { kind, blob: b } if *b == blob => Some(*kind),
  341. _ => None,
  342. })?;
  343. let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(kind) {
  344. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS => "vertex ",
  345. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "pixel ",
  346. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "mesh ",
  347. D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS => "compute ",
  348. _ => return None,
  349. };
  350. let at = p.name.find(stage)? + stage.len();
  351. p.name.get(at..at + 16)
  352. }
  353. /// Writes the DXIL of the pipelines whose name has `text` in it to `shaders`
  354. /// in the capture, and the pipelines' descriptions; what was written.
  355. pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
  356. let folder = find(folder)?;
  357. let frame = Frame::read(&folder.join("frame.bin"))?;
  358. let file = File::open(folder.join("shaders.bin"))?;
  359. let to = folder.join("shaders");
  360. std::fs::create_dir_all(&to)?;
  361. let mut out = Vec::new();
  362. for p in frame.pipelines.iter().filter(|p| p.name.contains(text)) {
  363. let mut line = format!("pipeline {} {}:", p.id, p.name);
  364. for part in &p.parts {
  365. match part {
  366. wire::Part::Code { kind, blob } => {
  367. let c = &frame.codes[*blob as usize];
  368. let mut bytes = vec![0; c.len as usize];
  369. read_at(&file, &mut bytes, c.at)?;
  370. let name: String = c.hash[..8].iter().map(|b| format!("{b:02x}")).collect();
  371. std::fs::write(to.join(format!("{name}.dxil")), bytes)?;
  372. let _ = write!(line, " {kind}={name}.dxil");
  373. }
  374. wire::Part::Root { root } => {
  375. if let Some((_, blob)) = frame.roots.iter().find(|r| r.0 == *root) {
  376. std::fs::write(to.join(format!("root-{root}.bin")), &blob.0)?;
  377. }
  378. let _ = write!(line, " root-{root}.bin");
  379. }
  380. other => {
  381. let _ = write!(line, " {other:?}");
  382. }
  383. }
  384. }
  385. out.push(line);
  386. }
  387. Ok(out)
  388. }
  389. /// Writes, one line each, the commands of lists (by their place in the
  390. /// frame), and before them the frame's buffers: `--listing`.
  391. pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) -> Result<()> {
  392. let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
  393. let pipelines: HashMap<u32, &str> =
  394. frame.pipelines.iter().map(|p| (p.id, p.name.as_str())).collect();
  395. for r in &frame.resources {
  396. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  397. let place = match &r.place {
  398. Place::Committed { props, .. } => format!("{:?}", gpu::seen(props)),
  399. other => format!("{other:?}"),
  400. };
  401. line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
  402. } else {
  403. let d = &r.desc;
  404. line(&format!(
  405. "texture {} {}x{}x{} mips {} f{}: {}",
  406. r.id, d.width, d.height, d.depth, d.mips, d.format, r.name
  407. ));
  408. }
  409. }
  410. let mut place = 0;
  411. for (i, s) in frame.submits.iter().enumerate() {
  412. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  413. let here = place;
  414. place += 1;
  415. if here < lists.0 || here > lists.1 {
  416. continue;
  417. }
  418. line(&format!("list {here} of submission {i}"));
  419. for (n, c) in Cmd::all(&frame.lists[l as usize].commands.0)?.iter().enumerate() {
  420. match c {
  421. Cmd::Pipeline { pso } => {
  422. line(&format!("{n} Pipeline {pso} {}", pipelines.get(pso).copied().unwrap_or_default()));
  423. }
  424. c => line(&format!("{n} {c:?}")),
  425. }
  426. }
  427. }
  428. }
  429. Ok(())
  430. }
  431. /// Loads a capture and runs it: the whole of `victory replay`. The reports,
  432. /// with what each is of.
  433. pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
  434. let mut player = Player::load(folder, options)?;
  435. let mut out = Vec::new();
  436. if options.compare && (options.edited() || options.shaders_b.is_some()) {
  437. // Turn by turn: what else the machine does falls on both.
  438. let image = Some(player.folder.join("replay-unchanged.png"));
  439. let plain = Options {
  440. image,
  441. ..options.plain()
  442. };
  443. let mut a = player.prepare(&plain)?;
  444. // The lists of the first hold its pipelines by name alone: kept.
  445. let _pipelines = match &options.shaders_b {
  446. Some(folder) => {
  447. let kept = std::mem::take(&mut player.pipelines);
  448. player.make_pipelines(Some(folder))?;
  449. kept
  450. }
  451. None => HashMap::new(),
  452. };
  453. let mut b = player.prepare(options)?;
  454. let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new());
  455. for _ in 0..options.loops.max(1) {
  456. stamps_a.push(player.once(&plain, &mut a)?);
  457. stamps_b.push(player.once(options, &mut b)?);
  458. }
  459. out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?));
  460. out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?));
  461. return Ok(out);
  462. }
  463. let what = if options.edited() {
  464. "with the experiments"
  465. } else {
  466. "unchanged"
  467. };
  468. out.push((what.into(), player.run(options)?));
  469. Ok(out)
  470. }
  471. struct Object {
  472. res: ID3D12Resource,
  473. va: u64,
  474. /// In the capture's `resources`.
  475. index: usize,
  476. subs: u32,
  477. }
  478. /// One version of a shader-visible descriptor heap.
  479. struct Version {
  480. heap: ID3D12DescriptorHeap,
  481. gpu: u64,
  482. }
  483. pub struct Player {
  484. pub folder: PathBuf,
  485. frame: Frame,
  486. device: ID3D12Device,
  487. worker: Worker,
  488. info: Option<ID3D12InfoQueue>,
  489. frequency: f64,
  490. objects: HashMap<u32, Object>,
  491. _heaps: HashMap<u32, ID3D12Heap>,
  492. roots: HashMap<u32, ID3D12RootSignature>,
  493. pipelines: HashMap<u32, ID3D12PipelineState>,
  494. signatures: HashMap<u32, ID3D12CommandSignature>,
  495. queries: HashMap<u32, ID3D12QueryHeap>,
  496. /// Descriptor heaps by id, in their versions; each submission's version.
  497. descriptors: HashMap<u32, (Vec<Version>, u64)>,
  498. version_of: Vec<usize>,
  499. /// Render target and depth views by what they are of.
  500. targets: HashMap<Slot, D3D12_CPU_DESCRIPTOR_HANDLE>,
  501. _target_heaps: Vec<ID3D12DescriptorHeap>,
  502. /// Copies of what the frame changes, as at its start.
  503. masters: Vec<(u32, ID3D12Resource)>,
  504. /// What the CPU wrote between submissions, and for each submission
  505. /// where in it.
  506. deltas: Option<ID3D12Resource>,
  507. delta_parts: Vec<Vec<(Delta, u64)>>,
  508. /// States at the start of the frame and after it.
  509. start: HashMap<u32, Vec<u32>>,
  510. end: HashMap<u32, Vec<u32>>,
  511. /// For `Options::merge`.
  512. merger: Option<merge::Merger>,
  513. merging: bool,
  514. /// Resources the card may write in the frame.
  515. card_writes: HashSet<u32>,
  516. /// The results of clamp passes ([`RESULTS`]).
  517. results: Option<ID3D12Resource>,
  518. /// Other buffers of ours that commands name.
  519. extra: HashMap<u32, ID3D12Resource>,
  520. commands: Vec<Vec<Cmd>>,
  521. /// Resources in the states of the start (not those of the end).
  522. fresh: bool,
  523. /// States as the last run left them (`diverge`).
  524. at: States,
  525. notes: Vec<String>,
  526. }
  527. /// What a command of a list is timed as.
  528. type Stamp = (usize, &'static str, u32);
  529. /// With a stamp of a copy to a texture: this bit and the texture's number
  530. /// stand for the pipeline's.
  531. const COPY_TO: u32 = 1 << 31;
  532. /// A list made from commands, with what its timestamps are of.
  533. struct Built {
  534. _allocator: ID3D12CommandAllocator,
  535. list: ID3D12GraphicsCommandList,
  536. /// The query of its start; its end is the one before the next list's.
  537. first: u32,
  538. last: u32,
  539. stamps: Vec<Stamp>,
  540. }
  541. impl Player {
  542. pub fn load(folder: &Path, options: &Options) -> Result<Player> {
  543. let folder = find(folder)?;
  544. let began = Instant::now();
  545. let frame = Frame::read(&folder.join("frame.bin"))?;
  546. let (device, info) = make_device(&frame, options.debug, options.breadcrumbs)?;
  547. // SAFETY: plain creation and queries.
  548. let (queue, frequency) = unsafe {
  549. let queue: ID3D12CommandQueue =
  550. device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  551. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  552. ..Default::default()
  553. })?;
  554. let frequency = queue.GetTimestampFrequency()? as f64;
  555. (queue, frequency)
  556. };
  557. let commands: Vec<Vec<Cmd>> = frame
  558. .lists
  559. .iter()
  560. .map(|l| Cmd::all(&l.commands.0))
  561. .collect::<std::result::Result<_, _>>()?;
  562. let mut player = Player {
  563. folder,
  564. worker: Worker::new(&device, &queue)?,
  565. device,
  566. info,
  567. frequency,
  568. objects: HashMap::new(),
  569. _heaps: HashMap::new(),
  570. roots: HashMap::new(),
  571. pipelines: HashMap::new(),
  572. signatures: HashMap::new(),
  573. queries: HashMap::new(),
  574. descriptors: HashMap::new(),
  575. version_of: Vec::new(),
  576. targets: HashMap::new(),
  577. _target_heaps: Vec::new(),
  578. masters: Vec::new(),
  579. deltas: None,
  580. delta_parts: Vec::new(),
  581. start: HashMap::new(),
  582. end: HashMap::new(),
  583. merger: None,
  584. merging: false,
  585. card_writes: HashSet::new(),
  586. results: None,
  587. extra: HashMap::new(),
  588. commands,
  589. fresh: true,
  590. at: States::default(),
  591. notes: frame
  592. .notes
  593. .iter()
  594. .map(|n| format!("recorder: {n}"))
  595. .collect(),
  596. frame,
  597. };
  598. player.check()?;
  599. let mut steps: Vec<(&str, std::time::Duration)> = Vec::new();
  600. let mut step = |what: &'static str, at: &mut Instant| {
  601. steps.push((what, at.elapsed()));
  602. *at = Instant::now();
  603. };
  604. let mut at = Instant::now();
  605. player.make_resources(options.buffers, &options.only_buffers)?;
  606. step("resources", &mut at);
  607. player.make_pipelines(options.shaders.as_deref())?;
  608. step("pipelines", &mut at);
  609. player.make_descriptors()?;
  610. step("descriptors", &mut at);
  611. player.load_contents()?;
  612. step("contents", &mut at);
  613. player.make_masters(options.buffers, options.restore)?;
  614. step("copies to restore from", &mut at);
  615. let steps: Vec<String> = steps
  616. .iter()
  617. .map(|(w, d)| format!("{w} {:.1} s", d.as_secs_f64()))
  618. .collect();
  619. if let Some([budget, used, pc]) = player.memory() {
  620. let over = if used + 256 > budget {
  621. ": over the budget, so the system moves memory to the PC's and the times are not the card's"
  622. } else {
  623. ""
  624. };
  625. player.notes.push(format!(
  626. "{used} MB of the card's memory used, budget {budget} MB; {pc} MB of the PC's{over}"
  627. ));
  628. }
  629. player.notes.push(format!(
  630. "loaded in {:.1} s: {}",
  631. began.elapsed().as_secs_f64(),
  632. steps.join(", ")
  633. ));
  634. Ok(player)
  635. }
  636. fn note(&mut self, n: String) {
  637. tracing::warn!("{n}");
  638. self.notes.push(n);
  639. }
  640. /// Says what of the frame is not there.
  641. fn check(&mut self) -> Result<()> {
  642. let missing = self
  643. .frame
  644. .submits
  645. .iter()
  646. .flat_map(|s| &s.lists)
  647. .filter(|&&l| l == MISSING)
  648. .count();
  649. if missing > 0 {
  650. self.note(format!(
  651. "{missing} lists of the frame were not recorded: the frame is incomplete"
  652. ));
  653. }
  654. if self.frame.submits.is_empty() {
  655. bail!("the capture has no submission");
  656. }
  657. let unknown = self
  658. .commands
  659. .iter()
  660. .flatten()
  661. .filter(|c| {
  662. matches!(
  663. c,
  664. Cmd::RootView {
  665. va: Va::Unknown { .. },
  666. ..
  667. }
  668. )
  669. })
  670. .count();
  671. if unknown > 0 {
  672. self.note(format!(
  673. "{unknown} root views name memory in no known buffer: they are null in the replay"
  674. ));
  675. }
  676. Ok(())
  677. }
  678. fn resource(&self, id: u32) -> Option<&ID3D12Resource> {
  679. if id == RESULTS {
  680. return self.results.as_ref();
  681. }
  682. self.objects
  683. .get(&id)
  684. .map(|o| &o.res)
  685. .or_else(|| self.extra.get(&id))
  686. }
  687. fn va(&self, va: &Va) -> u64 {
  688. match va {
  689. Va::At { res, offset } => self.objects.get(res).map_or(0, |o| o.va + offset),
  690. _ => 0,
  691. }
  692. }
  693. fn make_resources(&mut self, buffers: Buffers, only: &[String]) -> Result<()> {
  694. // A heap of memory the CPU sees becomes one the card may write too:
  695. // what the CPU wrote is put back by the card.
  696. let props = |p: &wire::HeapProps, buffer: bool| -> D3D12_HEAP_PROPERTIES {
  697. let pc = |page| D3D12_HEAP_PROPERTIES {
  698. Type: D3D12_HEAP_TYPE_CUSTOM,
  699. CPUPageProperty: page,
  700. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  701. ..Default::default()
  702. };
  703. let card = D3D12_HEAP_PROPERTIES {
  704. Type: D3D12_HEAP_TYPE_DEFAULT,
  705. ..Default::default()
  706. };
  707. match (gpu::seen(p), buffers) {
  708. (Seen::ReadBack, _) => gpu::to_props(p),
  709. (_, Buffers::Card) if buffer => card,
  710. (Seen::No, Buffers::Pc) if buffer => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_BACK),
  711. (Seen::Combined, _) if p.kind > D3D12_HEAP_TYPE_CUSTOM.0 => card,
  712. (Seen::Combined, _) => pc(D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE),
  713. _ => gpu::to_props(p),
  714. }
  715. };
  716. // Flags a replay has no use for: sharing, display, not zeroed.
  717. const DROP: i32 = 0x1 | 0x8 | 0x20 | 0x1000;
  718. let used_by_buffers_only: HashSet<u32> = {
  719. let mut textures = HashSet::new();
  720. for r in &self.frame.resources {
  721. if let Place::Placed { heap, .. } = r.place
  722. && r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0
  723. {
  724. textures.insert(heap);
  725. }
  726. }
  727. self.frame
  728. .heaps
  729. .iter()
  730. .map(|h| h.id)
  731. .filter(|id| !textures.contains(id))
  732. .collect()
  733. };
  734. for h in &self.frame.heaps {
  735. let desc = D3D12_HEAP_DESC {
  736. SizeInBytes: h.size,
  737. Properties: props(&h.props, only.is_empty() && used_by_buffers_only.contains(&h.id)),
  738. Alignment: h.alignment,
  739. Flags: D3D12_HEAP_FLAGS(h.flags & !DROP),
  740. };
  741. let mut heap: Option<ID3D12Heap> = None;
  742. // SAFETY: plain creation.
  743. unsafe { self.device.CreateHeap(&desc, &mut heap) }
  744. .with_context(|| format!("heap {}", h.id))?;
  745. self._heaps.extend(heap.map(|heap| (h.id, heap)));
  746. }
  747. let mut failed = 0;
  748. let mut moves: BTreeMap<String, (u32, u64)> = BTreeMap::new();
  749. for (index, r) in self.frame.resources.iter().enumerate() {
  750. let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  751. let moved = is_buffer && chosen(r, only);
  752. if moved && let Place::Committed { props, .. } = &r.place {
  753. let seen = gpu::seen(props);
  754. let m = moves.entry(format!("{seen:?}")).or_insert((0u32, 0u64));
  755. *m = (m.0 + 1, m.1 + r.desc.width);
  756. }
  757. let desc = gpu::to_desc(&r.desc);
  758. let mut made: Option<ID3D12Resource> = None;
  759. let clear: Option<D3D12_CLEAR_VALUE> = r.clear.map(|c| {
  760. // SAFETY: 20 bytes that were a clear value.
  761. unsafe { std::mem::transmute::<[u32; 5], D3D12_CLEAR_VALUE>(c) }
  762. });
  763. let clear = clear.as_ref().map(|c| c as *const _);
  764. // SAFETY: plain creation from a description the host took.
  765. let result = unsafe {
  766. match &r.place {
  767. Place::Placed { heap, offset } => match self._heaps.get(heap) {
  768. Some(h) => self.device.CreatePlacedResource(
  769. h,
  770. *offset,
  771. &desc,
  772. D3D12_RESOURCE_STATE_COMMON,
  773. clear,
  774. &mut made,
  775. ),
  776. None => Err(windows::core::Error::empty()),
  777. },
  778. Place::Committed { props: p, flags } => {
  779. let p = props(p, moved);
  780. let state = if p.Type == D3D12_HEAP_TYPE_READBACK {
  781. D3D12_RESOURCE_STATE_COPY_DEST
  782. } else {
  783. D3D12_RESOURCE_STATE_COMMON
  784. };
  785. self.device.CreateCommittedResource(
  786. &p,
  787. D3D12_HEAP_FLAGS(flags & !DROP),
  788. &desc,
  789. state,
  790. clear,
  791. &mut made,
  792. )
  793. }
  794. Place::BackBuffer {} => {
  795. let p = D3D12_HEAP_PROPERTIES {
  796. Type: D3D12_HEAP_TYPE_DEFAULT,
  797. ..Default::default()
  798. };
  799. self.device.CreateCommittedResource(
  800. &p,
  801. D3D12_HEAP_FLAG_NONE,
  802. &desc,
  803. D3D12_RESOURCE_STATE_COMMON,
  804. None,
  805. &mut made,
  806. )
  807. }
  808. }
  809. };
  810. match (result, made) {
  811. (Ok(()), Some(res)) => {
  812. // SAFETY: a live resource.
  813. let va = if is_buffer {
  814. unsafe { res.GetGPUVirtualAddress() }
  815. } else {
  816. 0
  817. };
  818. self.objects.insert(
  819. r.id,
  820. Object {
  821. res,
  822. va,
  823. index,
  824. subs: gpu::subresources(&r.desc),
  825. },
  826. );
  827. }
  828. (e, _) => {
  829. if failed == 0 {
  830. tracing::warn!("resource {} not made: {e:?}: {r:?}", r.id);
  831. }
  832. failed += 1;
  833. }
  834. }
  835. if !is_buffer {
  836. self.start.insert(r.id, r.state.clone());
  837. }
  838. }
  839. if failed > 0 {
  840. self.note(format!("{failed} resources could not be made again"));
  841. }
  842. if buffers != Buffers::AsRecorded {
  843. self.notes.push(format!(
  844. "--buffers is of, by how the CPU saw them (buffers, bytes): {moves:?}"
  845. ));
  846. }
  847. Ok(())
  848. }
  849. fn make_pipelines(&mut self, shaders: Option<&Path>) -> Result<()> {
  850. for (id, blob) in &self.frame.roots {
  851. if self.roots.contains_key(id) {
  852. // (Made for another set of shaders: the root signatures are the same.)
  853. continue;
  854. }
  855. // SAFETY: a blob the host took.
  856. let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }
  857. .with_context(|| format!("root signature {id}"))?;
  858. self.roots.insert(*id, root);
  859. }
  860. for s in &self.frame.signatures {
  861. if self.signatures.contains_key(&s.id) {
  862. continue;
  863. }
  864. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  865. ByteStride: s.stride,
  866. NumArgumentDescs: s.args.len() as u32,
  867. pArgumentDescs: s.args.as_ptr().cast(),
  868. NodeMask: 0,
  869. };
  870. let mut made: Option<ID3D12CommandSignature> = None;
  871. // SAFETY: a description the host took.
  872. unsafe {
  873. self.device
  874. .CreateCommandSignature(&desc, self.roots.get(&s.root), &mut made)?
  875. };
  876. self.signatures.extend(made.map(|m| (s.id, m)));
  877. }
  878. for q in &self.frame.query_heaps {
  879. if self.queries.contains_key(&q.id) {
  880. continue;
  881. }
  882. let desc = D3D12_QUERY_HEAP_DESC {
  883. Type: D3D12_QUERY_HEAP_TYPE(q.kind),
  884. Count: q.count,
  885. NodeMask: 0,
  886. };
  887. let mut made: Option<ID3D12QueryHeap> = None;
  888. // SAFETY: plain creation.
  889. unsafe { self.device.CreateQueryHeap(&desc, &mut made)? };
  890. self.queries.extend(made.map(|m| (q.id, m)));
  891. }
  892. let file = File::open(self.folder.join("shaders.bin"))?;
  893. let device: ID3D12Device2 = self.device.cast()?;
  894. let next = AtomicUsize::new(0);
  895. type Made = std::result::Result<ID3D12PipelineState, String>;
  896. let made: std::sync::Mutex<Vec<(u32, Made)>> = std::sync::Mutex::default();
  897. let threads = std::thread::available_parallelism()
  898. .map_or(4, |n| n.get() / 2)
  899. .max(1);
  900. let (frame, roots) = (&self.frame, &self.roots);
  901. let (swapped, kept) = (AtomicUsize::new(0), AtomicUsize::new(0));
  902. std::thread::scope(|scope| {
  903. for _ in 0..threads {
  904. scope.spawn(|| {
  905. while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) {
  906. let recorded = |i: u32| {
  907. let c = frame.codes.get(i as usize)?;
  908. let mut bytes = vec![0; c.len as usize];
  909. read_at(&file, &mut bytes, c.at).ok()?;
  910. Some(bytes)
  911. };
  912. let root = |id: u32| roots.get(&id).cloned();
  913. let taken = std::cell::Cell::new(false);
  914. let mut m = super::pso::make(&device, &p.parts, root, |i| {
  915. let other = shaders.and_then(|dir| {
  916. let own = || frame.codes.get(i as usize).map(|c| c.hash[..8].iter().map(|b| format!("{b:02x}")).collect());
  917. let hash = title_hash(p, i).map(str::to_owned).or_else(own)?;
  918. std::fs::read(dir.join(format!("{hash}.dxil"))).ok()
  919. });
  920. taken.set(taken.get() || other.is_some());
  921. other.or_else(|| recorded(i))
  922. });
  923. if taken.get() && m.is_err() {
  924. // Not for the root signature or the other stage recorded.
  925. kept.fetch_add(1, Ordering::Relaxed);
  926. m = super::pso::make(&device, &p.parts, root, recorded);
  927. } else if taken.get() {
  928. swapped.fetch_add(1, Ordering::Relaxed);
  929. }
  930. made.lock()
  931. .unwrap_or_else(|e| e.into_inner())
  932. .push((p.id, m));
  933. }
  934. });
  935. }
  936. });
  937. let mut refused = Vec::new();
  938. for (id, m) in made.into_inner().unwrap_or_else(|e| e.into_inner()) {
  939. match m {
  940. Ok(p) => drop(self.pipelines.insert(id, p)),
  941. Err(e) => refused.push((id, e)),
  942. }
  943. }
  944. if shaders.is_some() {
  945. let n = format!(
  946. "{} of {} pipelines made with shaders of the folder given, {} refused with them (as recorded)",
  947. swapped.into_inner(),
  948. self.frame.pipelines.len(),
  949. kept.into_inner()
  950. );
  951. self.note(n);
  952. }
  953. if let Some((id, e)) = refused.first() {
  954. let n = format!(
  955. "{} pipelines could not be made again, first {}: {e}",
  956. refused.len(),
  957. self.pipeline_name(*id)
  958. );
  959. self.note(n);
  960. }
  961. Ok(())
  962. }
  963. /// A pipeline's name for reports: what the host layer called it and the
  964. /// hashes of its shaders.
  965. fn pipeline_name(&self, id: u32) -> String {
  966. let Some(p) = self.frame.pipelines.iter().find(|p| p.id == id) else {
  967. return format!("pipeline {id}");
  968. };
  969. let code: Vec<String> = self.hashes(p);
  970. format!(
  971. "{} (DXIL {})",
  972. if p.name.is_empty() {
  973. "unnamed"
  974. } else {
  975. &p.name
  976. },
  977. code.join(" ")
  978. )
  979. }
  980. fn hashes(&self, p: &wire::Pipeline) -> Vec<String> {
  981. p.parts
  982. .iter()
  983. .filter_map(|part| match part {
  984. wire::Part::Code { blob, .. } => {
  985. let c = self.frame.codes.get(*blob as usize)?;
  986. Some(c.hash[..8].iter().map(|b| format!("{b:02x}")).collect())
  987. }
  988. _ => None,
  989. })
  990. .collect()
  991. }
  992. /// Makes a view; one of a resource that is not there is null.
  993. ///
  994. /// # Safety
  995. /// `at` is a slot of a heap of the view's type.
  996. unsafe fn view(&self, s: &Slot, at: D3D12_CPU_DESCRIPTOR_HANDLE, sampler: bool) {
  997. let gone = s.res != NONE && !self.objects.contains_key(&s.res);
  998. let res = self.objects.get(&s.res).map(|o| &o.res);
  999. let counter = self.objects.get(&s.counter).map(|o| &o.res);
  1000. // The descriptions lie in the slot unaligned.
  1001. // SAFETY: the slot's description is of its kind; the resources live.
  1002. unsafe {
  1003. match (s.kind, s.described != 0 && !gone) {
  1004. (slot::CBV, described) => {
  1005. let mut d: D3D12_CONSTANT_BUFFER_VIEW_DESC = Default::default();
  1006. if described && let Some(o) = self.objects.get(&s.res) {
  1007. d = s
  1008. .desc
  1009. .as_ptr()
  1010. .cast::<D3D12_CONSTANT_BUFFER_VIEW_DESC>()
  1011. .read_unaligned();
  1012. d.BufferLocation = o.va + s.address();
  1013. }
  1014. self.device.CreateConstantBufferView(Some(&d), at);
  1015. }
  1016. (slot::SRV, true) => {
  1017. let d = s
  1018. .desc
  1019. .as_ptr()
  1020. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  1021. .read_unaligned();
  1022. self.device.CreateShaderResourceView(res, Some(&d), at);
  1023. }
  1024. (slot::SRV, false) if res.is_some() => {
  1025. self.device.CreateShaderResourceView(res, None, at)
  1026. }
  1027. (slot::UAV, true) => {
  1028. let d = s
  1029. .desc
  1030. .as_ptr()
  1031. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  1032. .read_unaligned();
  1033. self.device
  1034. .CreateUnorderedAccessView(res, counter, Some(&d), at);
  1035. }
  1036. (slot::UAV, false) if res.is_some() => {
  1037. self.device
  1038. .CreateUnorderedAccessView(res, None::<&ID3D12Resource>, None, at)
  1039. }
  1040. (slot::SAMPLER, true) => {
  1041. let d = s
  1042. .desc
  1043. .as_ptr()
  1044. .cast::<D3D12_SAMPLER_DESC>()
  1045. .read_unaligned();
  1046. self.device.CreateSampler(&d, at);
  1047. }
  1048. _ if sampler => {
  1049. let d = D3D12_SAMPLER_DESC {
  1050. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  1051. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1052. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1053. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1054. ..Default::default()
  1055. };
  1056. self.device.CreateSampler(&d, at);
  1057. }
  1058. (slot::UAV, _) => {
  1059. let d = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  1060. Format: DXGI_FORMAT(41),
  1061. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  1062. ..Default::default()
  1063. };
  1064. self.device.CreateUnorderedAccessView(
  1065. None::<&ID3D12Resource>,
  1066. None::<&ID3D12Resource>,
  1067. Some(&d),
  1068. at,
  1069. );
  1070. }
  1071. _ => {
  1072. let d = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1073. Format: DXGI_FORMAT(41),
  1074. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  1075. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1076. ..Default::default()
  1077. };
  1078. self.device
  1079. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&d), at);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. fn make_descriptors(&mut self) -> Result<()> {
  1085. // A submission whose views replace ones that were in use gets a
  1086. // version of the heaps of its own: lists are sent without waiting,
  1087. // so a heap cannot be written between them.
  1088. let mut now: HashMap<(u32, u32), Slot> = HashMap::new();
  1089. let replaced: HashSet<(u32, u32)> = self
  1090. .frame
  1091. .submits
  1092. .iter()
  1093. .flat_map(|s| s.views.iter().map(|v| (v.0, v.1)))
  1094. .collect();
  1095. for h in &self.frame.descriptor_heaps {
  1096. for (id, i) in replaced.iter().filter(|k| k.0 == h.id) {
  1097. let k = h.runs.partition_point(|run| run.0 <= *i);
  1098. if let Some((first, n, s)) = k.checked_sub(1).and_then(|k| h.runs.get(k))
  1099. && i - first < *n
  1100. {
  1101. now.insert((*id, *i), *s);
  1102. }
  1103. }
  1104. }
  1105. // What each version changes against the one before.
  1106. let mut versions: Vec<Vec<(u32, u32, Slot)>> = vec![Vec::new()];
  1107. let mut touched: HashSet<(u32, u32)> = HashSet::new();
  1108. for s in &self.frame.submits {
  1109. let live =
  1110. |old: Option<&Slot>| old.is_some_and(|o| o.kind == slot::SAMPLER || o.res != NONE);
  1111. let news: Vec<&(u32, u32, Slot)> = s
  1112. .views
  1113. .iter()
  1114. .filter(|(h, i, v)| now.get(&(*h, *i)) != Some(v))
  1115. .collect();
  1116. if news
  1117. .iter()
  1118. .any(|(h, i, _)| live(now.get(&(*h, *i))) || touched.contains(&(*h, *i)))
  1119. {
  1120. versions.push(Vec::new());
  1121. touched.clear();
  1122. }
  1123. for (h, i, v) in news {
  1124. now.insert((*h, *i), *v);
  1125. touched.insert((*h, *i));
  1126. if let Some(last) = versions.last_mut() {
  1127. last.push((*h, *i, *v));
  1128. }
  1129. }
  1130. self.version_of.push(versions.len() - 1);
  1131. }
  1132. let mut made = HashMap::new();
  1133. let mut full = 0;
  1134. for h in &self.frame.descriptor_heaps {
  1135. let sampler = h.kind == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0;
  1136. let kind = D3D12_DESCRIPTOR_HEAP_TYPE(h.kind);
  1137. let make = |flags| -> windows::core::Result<ID3D12DescriptorHeap> {
  1138. let d = D3D12_DESCRIPTOR_HEAP_DESC {
  1139. Type: kind,
  1140. NumDescriptors: h.count,
  1141. Flags: flags,
  1142. NodeMask: 0,
  1143. };
  1144. // SAFETY: plain creation.
  1145. unsafe { self.device.CreateDescriptorHeap(&d) }
  1146. };
  1147. let cpu = make(D3D12_DESCRIPTOR_HEAP_FLAG_NONE)?;
  1148. // SAFETY: slots of the heap just made; threads write other ones.
  1149. unsafe {
  1150. let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize;
  1151. let start = cpu.GetCPUDescriptorHandleForHeapStart();
  1152. let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
  1153. ptr: start.ptr + i as usize * step,
  1154. };
  1155. self.view(&Slot::EMPTY, start, sampler);
  1156. let mut filled = 1;
  1157. while filled < h.count {
  1158. let n = filled.min(h.count - filled).min(1 << 16);
  1159. // Sources and destinations do not overlap.
  1160. self.device
  1161. .CopyDescriptorsSimple(n, at(filled), start, kind);
  1162. filled += n;
  1163. }
  1164. for (first, n, s) in &h.runs {
  1165. self.view(s, at(*first), sampler);
  1166. for i in 1..*n {
  1167. self.device
  1168. .CopyDescriptorsSimple(1, at(first + i), at(*first), kind);
  1169. }
  1170. }
  1171. let mut all = Vec::new();
  1172. for changes in &versions {
  1173. let mine: Vec<&(u32, u32, Slot)> =
  1174. changes.iter().filter(|(id, _, _)| *id == h.id).collect();
  1175. for (_, i, s) in &mine {
  1176. if *i < h.count {
  1177. self.view(s, at(*i), sampler);
  1178. }
  1179. }
  1180. if mine.is_empty()
  1181. && let Some(Version { heap, gpu }) = all.last()
  1182. {
  1183. let same = Version {
  1184. heap: ID3D12DescriptorHeap::clone(heap),
  1185. gpu: *gpu,
  1186. };
  1187. all.push(same);
  1188. continue;
  1189. }
  1190. let heap = match make(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) {
  1191. Ok(heap) => heap,
  1192. // Room for no more of them: the changes go into the
  1193. // last one, and lists before see them too.
  1194. Err(_) if !all.is_empty() => {
  1195. full += 1;
  1196. let Some(Version { heap, gpu }) = all.last() else {
  1197. break;
  1198. };
  1199. let same = Version {
  1200. heap: ID3D12DescriptorHeap::clone(heap),
  1201. gpu: *gpu,
  1202. };
  1203. self.device.CopyDescriptorsSimple(
  1204. h.count,
  1205. same.heap.GetCPUDescriptorHandleForHeapStart(),
  1206. start,
  1207. kind,
  1208. );
  1209. all.push(same);
  1210. continue;
  1211. }
  1212. Err(e) => return Err(e.into()),
  1213. };
  1214. self.device.CopyDescriptorsSimple(
  1215. h.count,
  1216. heap.GetCPUDescriptorHandleForHeapStart(),
  1217. start,
  1218. kind,
  1219. );
  1220. let gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr;
  1221. all.push(Version { heap, gpu });
  1222. }
  1223. made.insert(h.id, (all, step as u64));
  1224. }
  1225. }
  1226. self.descriptors = made;
  1227. if versions.len() > 1 {
  1228. self.notes.push(format!(
  1229. "{} versions of the descriptor heaps (views replaced during the frame)",
  1230. versions.len()
  1231. ));
  1232. }
  1233. if full > 0 {
  1234. self.note(format!(
  1235. "{full} versions of descriptor heaps had no room: earlier lists see later views"
  1236. ));
  1237. }
  1238. // Render target and depth views.
  1239. let mut views: [HashSet<Slot>; 2] = Default::default();
  1240. for c in self.commands.iter().flatten() {
  1241. match c {
  1242. Cmd::Targets { colors, depth } => {
  1243. views[0].extend(colors);
  1244. views[1].extend(depth);
  1245. }
  1246. Cmd::ClearTarget { view, .. } => _ = views[0].insert(*view),
  1247. Cmd::ClearDepth { view, .. } => _ = views[1].insert(*view),
  1248. _ => {}
  1249. }
  1250. }
  1251. for (i, all) in views.iter().enumerate() {
  1252. if all.is_empty() {
  1253. continue;
  1254. }
  1255. let kind = [
  1256. D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  1257. D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  1258. ][i];
  1259. let d = D3D12_DESCRIPTOR_HEAP_DESC {
  1260. Type: kind,
  1261. NumDescriptors: all.len() as u32,
  1262. ..Default::default()
  1263. };
  1264. // SAFETY: plain creation; slots of the heap just made.
  1265. unsafe {
  1266. let heap: ID3D12DescriptorHeap = self.device.CreateDescriptorHeap(&d)?;
  1267. let step = self.device.GetDescriptorHandleIncrementSize(kind) as usize;
  1268. let mut at = heap.GetCPUDescriptorHandleForHeapStart();
  1269. for s in all {
  1270. let res = self.objects.get(&s.res).map(|o| &o.res);
  1271. if i == 0 {
  1272. let d = s
  1273. .desc
  1274. .as_ptr()
  1275. .cast::<D3D12_RENDER_TARGET_VIEW_DESC>()
  1276. .read_unaligned();
  1277. // Without either there is nothing to make a view of.
  1278. let null = D3D12_RENDER_TARGET_VIEW_DESC {
  1279. Format: DXGI_FORMAT(28),
  1280. ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D,
  1281. ..Default::default()
  1282. };
  1283. let d = if s.described != 0 {
  1284. Some(&d as *const _)
  1285. } else if res.is_none() {
  1286. Some(&null as *const _)
  1287. } else {
  1288. None
  1289. };
  1290. self.device.CreateRenderTargetView(res, d, at);
  1291. } else {
  1292. let d = s
  1293. .desc
  1294. .as_ptr()
  1295. .cast::<D3D12_DEPTH_STENCIL_VIEW_DESC>()
  1296. .read_unaligned();
  1297. let null = D3D12_DEPTH_STENCIL_VIEW_DESC {
  1298. Format: DXGI_FORMAT(40),
  1299. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  1300. ..Default::default()
  1301. };
  1302. let d = if s.described != 0 {
  1303. Some(&d as *const _)
  1304. } else if res.is_none() {
  1305. Some(&null as *const _)
  1306. } else {
  1307. None
  1308. };
  1309. self.device.CreateDepthStencilView(res, d, at);
  1310. }
  1311. self.targets.insert(*s, at);
  1312. at.ptr += step;
  1313. }
  1314. self._target_heaps.push(heap);
  1315. }
  1316. }
  1317. Ok(())
  1318. }
  1319. /// Reads parts of files into upload memory and has `copy` record what
  1320. /// is done with each.
  1321. fn upload<T: Sync>(
  1322. &mut self,
  1323. parts: &[(T, u64, u64)],
  1324. file: &File,
  1325. mut copy: impl FnMut(&Player, &ID3D12GraphicsCommandList, &[(&T, u64, u64)], &ID3D12Resource),
  1326. ) -> Result<()> {
  1327. // Batches of parts with their place in the buffer.
  1328. let mut batches: Vec<Vec<(usize, u64)>> = vec![Vec::new()];
  1329. let (mut at, mut most) = (0u64, 0u64);
  1330. for (i, (_, len, _)) in parts.iter().enumerate() {
  1331. at = at.next_multiple_of(512);
  1332. if at + len > STAGING && at > 0 {
  1333. batches.push(Vec::new());
  1334. at = 0;
  1335. }
  1336. if let Some(b) = batches.last_mut() {
  1337. b.push((i, at));
  1338. }
  1339. at += len;
  1340. most = most.max(at);
  1341. }
  1342. if parts.is_empty() {
  1343. return Ok(());
  1344. }
  1345. let mut stagings: Vec<(ID3D12Resource, usize, u64)> = Vec::new();
  1346. for _ in 0..batches.len().min(2) {
  1347. let (b, data) = gpu::buffer(
  1348. &self.device,
  1349. D3D12_HEAP_TYPE_UPLOAD,
  1350. most,
  1351. D3D12_RESOURCE_FLAG_NONE,
  1352. )?;
  1353. stagings.push((b, data as usize, 0));
  1354. }
  1355. for (n, batch) in batches.iter().enumerate() {
  1356. let k = n % stagings.len();
  1357. self.worker.wait(stagings[k].2)?;
  1358. let map = stagings[k].1;
  1359. let next = AtomicUsize::new(0);
  1360. let failed: std::sync::Mutex<Option<std::io::Error>> = std::sync::Mutex::default();
  1361. std::thread::scope(|scope| {
  1362. for _ in 0..8.min(batch.len()) {
  1363. scope.spawn(|| {
  1364. while let Some(&(i, at)) = batch.get(next.fetch_add(1, Ordering::Relaxed)) {
  1365. let (_, len, from) = &parts[i];
  1366. // SAFETY: this part's own bytes of the mapping.
  1367. let to = unsafe {
  1368. std::slice::from_raw_parts_mut(
  1369. (map + at as usize) as *mut u8,
  1370. *len as usize,
  1371. )
  1372. };
  1373. if *from == ZERO {
  1374. to.fill(0);
  1375. } else if let Err(e) = read_at(file, to, *from) {
  1376. failed
  1377. .lock()
  1378. .unwrap_or_else(|e| e.into_inner())
  1379. .get_or_insert(e);
  1380. }
  1381. }
  1382. });
  1383. }
  1384. });
  1385. if let Some(e) = failed.into_inner().unwrap_or_else(|e| e.into_inner()) {
  1386. return Err(e).context("the capture's contents");
  1387. }
  1388. let list: Vec<(&T, u64, u64)> = batch
  1389. .iter()
  1390. .map(|&(i, at)| (&parts[i].0, parts[i].1, at))
  1391. .collect();
  1392. let buffer = stagings[k].0.clone();
  1393. // The worker is another part of the player than `copy` uses.
  1394. let other = Worker::new(&self.device, &self.worker.queue)?;
  1395. let mut worker = std::mem::replace(&mut self.worker, other);
  1396. let sent = worker.send(|l| copy(self, l, &list, &buffer));
  1397. self.worker = worker;
  1398. stagings[k].2 = sent?;
  1399. }
  1400. self.worker.idle()?;
  1401. Ok(())
  1402. }
  1403. fn load_contents(&mut self) -> Result<()> {
  1404. // Idle aliases first: a change of their state may write memory the
  1405. // one in use holds.
  1406. let known: HashSet<u32> = self.frame.contents.iter().map(|c| c.res).collect();
  1407. let mut early = Vec::new();
  1408. let mut into = Vec::new();
  1409. for r in &self.frame.resources {
  1410. let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else {
  1411. continue;
  1412. };
  1413. let loaded = !r.idle && known.contains(&r.id);
  1414. gpu::moves(
  1415. &o.res,
  1416. &[COMMON],
  1417. if loaded { &[COPY_DEST] } else { state },
  1418. if loaded { &mut into } else { &mut early },
  1419. );
  1420. }
  1421. let textures: Vec<(Content, u64, u64)> = self
  1422. .frame
  1423. .contents
  1424. .iter()
  1425. .filter(|c| self.objects.contains_key(&c.res))
  1426. .map(|c| (c.clone(), c.len, c.file))
  1427. .collect();
  1428. let missing = self.frame.contents.len() - textures.len();
  1429. self.worker.run(|list| {
  1430. // SAFETY: an open list; live resources.
  1431. unsafe {
  1432. for all in early.chunks(1000) {
  1433. list.ResourceBarrier(all);
  1434. }
  1435. list.ResourceBarrier(&[alias()]);
  1436. for all in into.chunks(1000) {
  1437. list.ResourceBarrier(all);
  1438. }
  1439. }
  1440. })?;
  1441. let file = File::open(self.folder.join("contents.bin"))?;
  1442. self.upload(&textures, &file, |player, list, parts, staging| {
  1443. for (c, len, at) in parts {
  1444. let Some(o) = player.objects.get(&c.res) else {
  1445. continue;
  1446. };
  1447. let r = &player.frame.resources[o.index];
  1448. // SAFETY: an open list; live resources.
  1449. unsafe {
  1450. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1451. list.CopyBufferRegion(&o.res, c.first, staging, *at, *len);
  1452. continue;
  1453. }
  1454. let (all, _) = gpu::footprints(
  1455. &player.device,
  1456. &gpu::to_desc(&r.desc),
  1457. c.first as u32,
  1458. c.count,
  1459. );
  1460. for (i, mut f) in all.into_iter().enumerate() {
  1461. f.Offset += at;
  1462. let to = gpu::sub_location(&o.res, c.first as u32 + i as u32);
  1463. list.CopyTextureRegion(
  1464. &to,
  1465. 0,
  1466. 0,
  1467. 0,
  1468. &gpu::placed_location(staging, f),
  1469. None,
  1470. );
  1471. }
  1472. }
  1473. }
  1474. })?;
  1475. // To the states of the frame's start.
  1476. let mut back = Vec::new();
  1477. for r in &self.frame.resources {
  1478. let (Some(o), Some(state)) = (self.objects.get(&r.id), self.start.get(&r.id)) else {
  1479. continue;
  1480. };
  1481. if !r.idle && known.contains(&r.id) {
  1482. gpu::moves(&o.res, &[COPY_DEST], state, &mut back);
  1483. }
  1484. }
  1485. self.worker.run(|list| {
  1486. for all in back.chunks(1000) {
  1487. // SAFETY: an open list; live resources.
  1488. unsafe { list.ResourceBarrier(all) };
  1489. }
  1490. })?;
  1491. if missing > 0 {
  1492. self.note(format!(
  1493. "contents of {missing} parts of resources that could not be made are left out"
  1494. ));
  1495. }
  1496. // What the CPU had put into the memory both see by the first
  1497. // submission: part of the start of the frame.
  1498. let file = File::open(self.folder.join("deltas.bin"))?;
  1499. let named = self.named_buffers();
  1500. let of = |s: &wire::Submit| {
  1501. s.deltas
  1502. .iter()
  1503. .filter(|d| named.contains(&d.res))
  1504. .cloned()
  1505. .collect::<Vec<Delta>>()
  1506. };
  1507. // In memory the card cannot write, bytes looked at first when a
  1508. // later submission read them can stand there from the start.
  1509. let upload: HashSet<u32> = self
  1510. .frame
  1511. .resources
  1512. .iter()
  1513. .filter(|r| matches!(&r.place, Place::Committed { props, .. } if props.kind == D3D12_HEAP_TYPE_UPLOAD.0))
  1514. .map(|r| r.id)
  1515. .collect();
  1516. let mut first = of(&self.frame.submits[0]);
  1517. let mut seen: HashSet<(u32, u64)> = HashSet::new();
  1518. let pages = |d: &Delta| {
  1519. (d.at / 4096..(d.at + d.len).div_ceil(4096))
  1520. .map(|p| (d.res, p))
  1521. .collect::<Vec<_>>()
  1522. };
  1523. first.iter().for_each(|d| seen.extend(pages(d)));
  1524. let mut rest: Vec<Vec<Delta>> = vec![Vec::new()];
  1525. for s in self.frame.submits.iter().skip(1) {
  1526. let (early, late): (Vec<Delta>, Vec<Delta>) = of(s).into_iter().partition(|d| {
  1527. upload.contains(&d.res) && pages(d).iter().all(|p| !seen.contains(p))
  1528. });
  1529. early.iter().for_each(|d| seen.extend(pages(d)));
  1530. first.extend(early);
  1531. rest.push(late);
  1532. }
  1533. let first: Vec<(Delta, u64, u64)> = first
  1534. .into_iter()
  1535. .map(|d| (d.clone(), d.len, d.file))
  1536. .collect();
  1537. self.upload(&first, &file, |player, list, parts, staging| {
  1538. for (d, len, at) in parts {
  1539. if let Some(o) = player.objects.get(&d.res) {
  1540. // SAFETY: an open list; live buffers.
  1541. unsafe { list.CopyBufferRegion(&o.res, d.at, staging, *at, *len) };
  1542. }
  1543. }
  1544. })?;
  1545. // The later ones wait in a buffer of their own.
  1546. let mut later: Vec<((u64, Delta), u64, u64)> = Vec::new();
  1547. let mut total = 0u64;
  1548. self.delta_parts = vec![Vec::new(); self.frame.submits.len()];
  1549. for (i, all) in rest.into_iter().enumerate() {
  1550. for d in all {
  1551. later.push(((total, d.clone()), d.len, d.file));
  1552. total += d.len;
  1553. self.delta_parts[i].push((d, total - later.last().map_or(0, |l| l.1)));
  1554. }
  1555. }
  1556. if total > 0 {
  1557. let (buffer, _) = gpu::buffer(
  1558. &self.device,
  1559. D3D12_HEAP_TYPE_DEFAULT,
  1560. total,
  1561. D3D12_RESOURCE_FLAG_NONE,
  1562. )?;
  1563. self.deltas = Some(buffer.clone());
  1564. self.upload(&later, &file, |_, list, parts, staging| {
  1565. for ((to, _), len, at) in parts {
  1566. // SAFETY: an open list; live buffers.
  1567. unsafe { list.CopyBufferRegion(&buffer, *to, staging, *at, *len) };
  1568. }
  1569. })?;
  1570. }
  1571. Ok(())
  1572. }
  1573. /// The buffers the frame names, in commands or descriptors: what the CPU
  1574. /// writes to others (buffers it has results fetched to) is of no use.
  1575. fn named_buffers(&self) -> HashSet<u32> {
  1576. let mut named = HashSet::new();
  1577. let mut va = |va: &Va| {
  1578. if let Va::At { res, .. } = va {
  1579. named.insert(*res);
  1580. }
  1581. };
  1582. for c in self.commands.iter().flatten() {
  1583. match c {
  1584. Cmd::RootView { va: v, .. } => va(v),
  1585. Cmd::IndexBuffer {
  1586. view: Some((v, _, _)),
  1587. } => va(v),
  1588. Cmd::VertexBuffers {
  1589. views: Some(all), ..
  1590. } => all.iter().for_each(|(v, _, _)| va(v)),
  1591. Cmd::WriteImmediate { all } => all.iter().for_each(|(v, _, _)| va(v)),
  1592. _ => {}
  1593. }
  1594. }
  1595. for c in self.commands.iter().flatten() {
  1596. match c {
  1597. Cmd::CopyBuffer { dst, src, .. } | Cmd::CopyResource { dst, src } => {
  1598. named.extend([*dst, *src])
  1599. }
  1600. Cmd::CopyTexture { dst, src, .. } => {
  1601. for Loc::Sub { res, .. } | Loc::Placed { res, .. } in [dst, src] {
  1602. named.insert(*res);
  1603. }
  1604. }
  1605. Cmd::Indirect { args, count, .. } => named.extend([*args, *count]),
  1606. Cmd::ResolveQuery { dst, .. } => _ = named.insert(*dst),
  1607. _ => {}
  1608. }
  1609. }
  1610. for h in &self.frame.descriptor_heaps {
  1611. named.extend(h.runs.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
  1612. }
  1613. for s in &self.frame.submits {
  1614. named.extend(s.views.iter().flat_map(|(_, _, s)| [s.res, s.counter]));
  1615. }
  1616. named
  1617. }
  1618. /// Copies of what the frame changes; and the states it leaves.
  1619. fn make_masters(&mut self, buffers: Buffers, wanted: bool) -> Result<()> {
  1620. let mut states = States::default();
  1621. for r in &self.frame.resources {
  1622. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1623. continue;
  1624. }
  1625. let subs = gpu::subresources(&r.desc);
  1626. let decays = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0;
  1627. states.add(r.id, subs, r.state[0], decays);
  1628. if r.state.len() > 1 {
  1629. for (i, s) in r.state.iter().enumerate() {
  1630. states.change(&states::Change {
  1631. res: r.id,
  1632. sub: i as u32,
  1633. after: *s,
  1634. promoted: false,
  1635. alias: false,
  1636. });
  1637. }
  1638. }
  1639. }
  1640. // Resources in a state they are written in at some time, or written
  1641. // some other way.
  1642. const WRITE: u32 =
  1643. RENDER_TARGET | UNORDERED_ACCESS | DEPTH_WRITE | COPY_DEST | RESOLVE_DEST;
  1644. let mut written: HashSet<u32> = self
  1645. .frame
  1646. .resources
  1647. .iter()
  1648. .filter(|r| r.state.iter().any(|s| s & WRITE != 0))
  1649. .map(|r| r.id)
  1650. .collect();
  1651. let mut by_cpu: HashSet<u32> = HashSet::new();
  1652. for (i, s) in self.frame.submits.iter().enumerate() {
  1653. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1654. for c in &self.commands[l as usize] {
  1655. let mut changes = Vec::new();
  1656. states::changes(c, &mut changes);
  1657. for ch in &changes {
  1658. states.change(ch);
  1659. }
  1660. match c {
  1661. Cmd::Barriers { all } => {
  1662. for b in all {
  1663. if let Barrier::Transition {
  1664. res, before, after, ..
  1665. } = b
  1666. && (*before | *after) as u32 & WRITE != 0
  1667. {
  1668. written.insert(*res);
  1669. }
  1670. }
  1671. }
  1672. Cmd::CopyBuffer { dst, .. }
  1673. | Cmd::CopyResource { dst, .. }
  1674. | Cmd::ResolveQuery { dst, .. } => _ = written.insert(*dst),
  1675. Cmd::CopyTexture {
  1676. dst: Loc::Sub { res, .. } | Loc::Placed { res, .. },
  1677. ..
  1678. } => _ = written.insert(*res),
  1679. Cmd::Resolve { dst, .. } | Cmd::ResolveRegion { dst, .. } => {
  1680. _ = written.insert(*dst)
  1681. }
  1682. Cmd::RootView {
  1683. kind: slot::UAV,
  1684. va: Va::At { res, .. },
  1685. ..
  1686. } => _ = written.insert(*res),
  1687. Cmd::WriteImmediate { all } => {
  1688. written.extend(all.iter().filter_map(|(va, _, _)| {
  1689. if let Va::At { res, .. } = va {
  1690. Some(*res)
  1691. } else {
  1692. None
  1693. }
  1694. }));
  1695. }
  1696. _ => {}
  1697. }
  1698. }
  1699. }
  1700. states.decay();
  1701. if i > 0 {
  1702. by_cpu.extend(self.delta_parts[i].iter().map(|(d, _)| d.res));
  1703. }
  1704. }
  1705. // Buffers any unordered-access view names.
  1706. let is_buffer = |id: u32| {
  1707. self.objects.get(&id).is_some_and(|o| {
  1708. self.frame.resources[o.index].desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0
  1709. })
  1710. };
  1711. let simultaneous = |id: u32| {
  1712. self.objects.get(&id).is_some_and(|o| {
  1713. self.frame.resources[o.index].desc.flags
  1714. & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0
  1715. != 0
  1716. })
  1717. };
  1718. let views = self
  1719. .frame
  1720. .descriptor_heaps
  1721. .iter()
  1722. .flat_map(|h| h.runs.iter().map(|(_, _, s)| s));
  1723. let late = self
  1724. .frame
  1725. .submits
  1726. .iter()
  1727. .flat_map(|s| s.views.iter().map(|(_, _, s)| s));
  1728. for s in views.chain(late).filter(|s| s.kind == slot::UAV) {
  1729. for id in [s.res, s.counter] {
  1730. if is_buffer(id) || simultaneous(id) {
  1731. written.insert(id);
  1732. }
  1733. }
  1734. }
  1735. self.card_writes = written.clone();
  1736. written.extend(by_cpu);
  1737. for id in self.start.keys() {
  1738. self.end
  1739. .insert(*id, states.get(*id).unwrap_or(vec![COMMON]));
  1740. }
  1741. let mut ids: Vec<u32> = written
  1742. .into_iter()
  1743. .filter(|id| {
  1744. self.objects.get(id).is_some_and(|o| {
  1745. let r = &self.frame.resources[o.index];
  1746. let back = matches!(&r.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::ReadBack);
  1747. !r.idle && !back && !matches!(r.place, Place::BackBuffer {})
  1748. })
  1749. })
  1750. .collect();
  1751. ids.sort_unstable();
  1752. // Without restoring they are of no use, and their room may be what
  1753. // the frame itself lacks.
  1754. if !wanted {
  1755. ids.clear();
  1756. }
  1757. let mut total = 0u64;
  1758. let mut in_pc = 0u64;
  1759. for id in ids {
  1760. let o = &self.objects[&id];
  1761. let r = &self.frame.resources[o.index];
  1762. let mut desc = gpu::to_desc(&r.desc);
  1763. desc.Alignment = 0;
  1764. // Copies are only copied to and from; a depth format needs its
  1765. // flag.
  1766. if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
  1767. desc.Flags = D3D12_RESOURCE_FLAG_NONE;
  1768. }
  1769. // SAFETY: a plain query.
  1770. let size = unsafe { self.device.GetResourceAllocationInfo(0, &[desc]) }.SizeInBytes;
  1771. let room = self.room();
  1772. let buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  1773. // With all buffers in the card's memory there is no room for
  1774. // their copies as well.
  1775. let pc = buffer
  1776. && (buffers == Buffers::Card || room.is_some_and(|room| room < size + (1 << 30)));
  1777. let props = if pc {
  1778. D3D12_HEAP_PROPERTIES {
  1779. Type: D3D12_HEAP_TYPE_CUSTOM,
  1780. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
  1781. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  1782. ..Default::default()
  1783. }
  1784. } else {
  1785. D3D12_HEAP_PROPERTIES {
  1786. Type: D3D12_HEAP_TYPE_DEFAULT,
  1787. ..Default::default()
  1788. }
  1789. };
  1790. let mut made: Option<ID3D12Resource> = None;
  1791. // SAFETY: plain creation.
  1792. let result = unsafe {
  1793. self.device.CreateCommittedResource(
  1794. &props,
  1795. D3D12_HEAP_FLAG_NONE,
  1796. &desc,
  1797. D3D12_RESOURCE_STATE_COMMON,
  1798. None,
  1799. &mut made,
  1800. )
  1801. };
  1802. match (result, made) {
  1803. (Ok(()), Some(m)) => {
  1804. total += size;
  1805. in_pc += if pc { size } else { 0 };
  1806. self.masters.push((id, m));
  1807. }
  1808. (e, _) => self.note(format!(
  1809. "no copy of resource {id} to restore it from ({e:?})"
  1810. )),
  1811. }
  1812. }
  1813. tracing::info!(
  1814. resources = self.masters.len(),
  1815. mb = total >> 20,
  1816. in_pc_memory_mb = in_pc >> 20,
  1817. "copies of what the frame changes"
  1818. );
  1819. // Filled now: the resources are as at the frame's start. Masters
  1820. // stay in the copy-source state (buffers decay).
  1821. let (masters, objects, start) = (&self.masters, &self.objects, &self.start);
  1822. for some in masters.chunks(256) {
  1823. let (mut before, mut after) = (Vec::new(), Vec::new());
  1824. for (id, m) in some {
  1825. let Some(state) = start.get(id) else { continue };
  1826. let o = &objects[id];
  1827. let to: Vec<u32> = state
  1828. .iter()
  1829. .map(|&s| if s & COPY_SOURCE != 0 { s } else { COPY_SOURCE })
  1830. .collect();
  1831. gpu::moves(&o.res, state, &to, &mut before);
  1832. gpu::moves(&o.res, &to, state, &mut after);
  1833. before.push(gpu::transition(m, ALL, COMMON, COPY_DEST));
  1834. after.push(gpu::transition(m, ALL, COPY_DEST, COPY_SOURCE));
  1835. }
  1836. self.worker.run(|list| {
  1837. // SAFETY: an open list; live resources of one size.
  1838. unsafe {
  1839. barriers(list, &before);
  1840. for (id, m) in some {
  1841. list.CopyResource(m, &objects[id].res);
  1842. }
  1843. barriers(list, &after);
  1844. }
  1845. })?;
  1846. }
  1847. Ok(())
  1848. }
  1849. /// The card's memory budget and use, and the use of the PC's memory, in
  1850. /// MB.
  1851. fn memory(&self) -> Option<[u64; 3]> {
  1852. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  1853. let mut pc = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  1854. // SAFETY: plain queries.
  1855. unsafe {
  1856. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  1857. let adapter: IDXGIAdapter3 = factory
  1858. .EnumAdapterByLuid(self.device.GetAdapterLuid())
  1859. .ok()?;
  1860. adapter
  1861. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  1862. .ok()?;
  1863. adapter
  1864. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut pc)
  1865. .ok()?;
  1866. }
  1867. Some([
  1868. own.Budget >> 20,
  1869. own.CurrentUsage >> 20,
  1870. pc.CurrentUsage >> 20,
  1871. ])
  1872. }
  1873. /// What is free of the card's memory budget.
  1874. fn room(&self) -> Option<u64> {
  1875. let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
  1876. // SAFETY: plain queries.
  1877. unsafe {
  1878. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
  1879. let adapter: IDXGIAdapter3 = factory
  1880. .EnumAdapterByLuid(self.device.GetAdapterLuid())
  1881. .ok()?;
  1882. adapter
  1883. .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own)
  1884. .ok()?;
  1885. }
  1886. Some(own.Budget.saturating_sub(own.CurrentUsage))
  1887. }
  1888. /// Puts back what a run changed.
  1889. fn restore(&mut self, contents: bool) -> Result<()> {
  1890. if self.fresh {
  1891. return Ok(());
  1892. }
  1893. let restored: HashMap<u32, &ID3D12Resource> = if contents {
  1894. self.masters.iter().map(|(id, m)| (*id, m)).collect()
  1895. } else {
  1896. HashMap::new()
  1897. };
  1898. let (mut idle, mut into, mut back, mut plain) =
  1899. (Vec::new(), Vec::new(), Vec::new(), Vec::new());
  1900. for (id, start) in &self.start {
  1901. let Some(o) = self.objects.get(id) else {
  1902. continue;
  1903. };
  1904. let end = self.end.get(id).unwrap_or(start);
  1905. if restored.contains_key(id) {
  1906. gpu::moves(&o.res, end, &[COPY_DEST], &mut into);
  1907. gpu::moves(&o.res, &[COPY_DEST], start, &mut back);
  1908. } else if self.frame.resources[o.index].idle {
  1909. gpu::moves(&o.res, end, start, &mut idle);
  1910. } else {
  1911. gpu::moves(&o.res, end, start, &mut plain);
  1912. }
  1913. }
  1914. let objects = &self.objects;
  1915. self.worker.run(|list| {
  1916. // SAFETY: an open list; live resources, each copied from one of
  1917. // its own description.
  1918. unsafe {
  1919. barriers(list, &idle);
  1920. barriers(list, &[alias()]);
  1921. barriers(list, &plain);
  1922. barriers(list, &into);
  1923. for (id, m) in &restored {
  1924. list.CopyResource(&objects[id].res, *m);
  1925. }
  1926. if let Some(merger) = &self.merger {
  1927. for (id, base) in &merger.bases {
  1928. if let Some((_, m)) = self.masters.iter().find(|m| m.0 == *id) {
  1929. list.CopyResource(base, m);
  1930. }
  1931. }
  1932. }
  1933. barriers(list, &back);
  1934. }
  1935. })?;
  1936. self.fresh = true;
  1937. Ok(())
  1938. }
  1939. fn pipelines_named(&self, name: &str) -> HashSet<u32> {
  1940. self.frame
  1941. .pipelines
  1942. .iter()
  1943. .filter(|p| p.name == name)
  1944. .map(|p| p.id)
  1945. .collect()
  1946. }
  1947. /// The frame's lists, edited: for each submission, its lists' commands.
  1948. fn edited(
  1949. &mut self,
  1950. o: &Options,
  1951. report: &mut Report,
  1952. clamps: &[Vec<Clamp>],
  1953. ) -> Vec<Vec<Vec<Cmd>>> {
  1954. let skip: HashSet<u32> = self
  1955. .frame
  1956. .pipelines
  1957. .iter()
  1958. .filter(|p| {
  1959. let hashes = self.hashes(p);
  1960. o.skip_shaders.iter().any(|s| {
  1961. !s.is_empty()
  1962. && (p.name.contains(s.as_str())
  1963. || hashes.iter().any(|h| h.contains(s.as_str())))
  1964. })
  1965. })
  1966. .map(|p| p.id)
  1967. .collect();
  1968. if !o.skip_shaders.is_empty() {
  1969. report
  1970. .notes
  1971. .push(format!("{} pipelines match --skip-shader", skip.len()));
  1972. }
  1973. let hash = self.pipelines_named(COMPARE);
  1974. let clamp = self.pipelines_named(CLAMP);
  1975. let compute: HashSet<u32> = self
  1976. .frame
  1977. .pipelines
  1978. .iter()
  1979. .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS.0)))
  1980. .map(|p| p.id)
  1981. .collect();
  1982. let mut batched = edit::Batched::default();
  1983. let mut jobs = Vec::new();
  1984. let mut scratches = Vec::new();
  1985. let (mut skipped, mut hashed, mut uavs, mut merged) = (0, 0, 0, 0);
  1986. let mut place = 0;
  1987. let mut out = Vec::new();
  1988. for s in &self.frame.submits {
  1989. let mut lists = Vec::new();
  1990. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  1991. let mut cmds = self.commands[l as usize].clone();
  1992. let here = place;
  1993. place += 1;
  1994. if o.only.is_some_and(|(from, to)| here < from || here > to) {
  1995. lists.push(edit::barriers_only(cmds));
  1996. continue;
  1997. }
  1998. if let Some((list, command)) = o.until
  1999. && here >= list
  2000. {
  2001. let from = if here > list { 0 } else { (command + 1).min(cmds.len()) };
  2002. let rest = cmds.split_off(from);
  2003. cmds.extend(edit::barriers_only(rest));
  2004. }
  2005. if o.skip_clamps
  2006. && let Some(c) = clamps.get(here as usize)
  2007. {
  2008. cmds = edit::skip_clamps(cmds, c);
  2009. }
  2010. if o.batch_clamps > 0 {
  2011. let scratch = edit::BATCH_SCRATCH - here;
  2012. let done;
  2013. (cmds, done) = edit::batch_clamps(
  2014. cmds,
  2015. &clamp,
  2016. &compute,
  2017. scratch,
  2018. o.batch_clamps > 1,
  2019. &mut jobs,
  2020. );
  2021. batched.clamps += done.clamps;
  2022. batched.batches += done.batches;
  2023. batched.jobs += done.jobs;
  2024. if done.scratch > 0 {
  2025. scratches.push((scratch, done.scratch));
  2026. }
  2027. }
  2028. let mut n;
  2029. if !skip.is_empty() {
  2030. (cmds, n) = edit::skip_pipelines(cmds, &skip);
  2031. skipped += n;
  2032. }
  2033. if o.skip_hash_passes {
  2034. (cmds, n) = edit::skip_pipelines(cmds, &hash);
  2035. hashed += n;
  2036. }
  2037. if o.no_barriers {
  2038. (cmds, n) = edit::no_uav_barriers(cmds);
  2039. uavs += n;
  2040. }
  2041. if o.merge_barriers {
  2042. (cmds, n) = edit::merge_barriers(cmds);
  2043. merged += n;
  2044. }
  2045. lists.push(cmds);
  2046. }
  2047. out.push(lists);
  2048. }
  2049. if o.batch_clamps > 0 {
  2050. report.notes.push(format!(
  2051. "--batch-clamps: {} clamp passes became {}, of {} records",
  2052. batched.clamps, batched.batches, batched.jobs
  2053. ));
  2054. if let Err(e) = self.make_batches(&jobs, &scratches) {
  2055. report.notes.push(format!("--batch-clamps failed: {e:#}"));
  2056. }
  2057. }
  2058. if !skip.is_empty() {
  2059. report
  2060. .notes
  2061. .push(format!("--skip-shader left out {skipped} commands"));
  2062. }
  2063. if o.skip_hash_passes {
  2064. report
  2065. .notes
  2066. .push(format!("--skip-hash-passes left out {hashed} dispatches"));
  2067. }
  2068. if o.no_barriers {
  2069. report.notes.push(format!(
  2070. "--no-barriers left out {uavs} unordered-access barriers"
  2071. ));
  2072. }
  2073. if o.merge_barriers {
  2074. report.notes.push(format!(
  2075. "--merge-barriers joined {merged} barrier calls to ones before them"
  2076. ));
  2077. }
  2078. out
  2079. }
  2080. /// What lists edited by [`edit::batch_clamps`] name: the pass, its
  2081. /// tables and scratch buffers.
  2082. fn make_batches(&mut self, jobs: &[u8], scratches: &[(u32, u64)]) -> Result<()> {
  2083. let (root, pso) = crate::indirect::batch_for(&self.device)?;
  2084. self.roots.insert(edit::BATCH_ROOT, root);
  2085. self.pipelines.insert(edit::BATCH, pso);
  2086. let (table, data) = gpu::buffer(
  2087. &self.device,
  2088. D3D12_HEAP_TYPE_UPLOAD,
  2089. jobs.len().max(4) as u64,
  2090. D3D12_RESOURCE_FLAG_NONE,
  2091. )?;
  2092. // SAFETY: a mapping of as many bytes.
  2093. unsafe { std::ptr::copy_nonoverlapping(jobs.as_ptr(), data.cast(), jobs.len()) };
  2094. let mut all = vec![(edit::BATCH_JOBS, table)];
  2095. for &(id, bytes) in scratches {
  2096. let (scratch, _) = gpu::buffer(
  2097. &self.device,
  2098. D3D12_HEAP_TYPE_DEFAULT,
  2099. bytes.next_multiple_of(64 << 10),
  2100. D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  2101. )?;
  2102. all.push((id, scratch));
  2103. }
  2104. for (id, res) in all {
  2105. // SAFETY: a live buffer.
  2106. let va = unsafe { res.GetGPUVirtualAddress() };
  2107. let object = Object {
  2108. res,
  2109. va,
  2110. index: 0,
  2111. subs: 1,
  2112. };
  2113. self.objects.insert(id, object);
  2114. }
  2115. Ok(())
  2116. }
  2117. /// The clamp passes of each list of the frame, in order, and their
  2118. /// results in [`RESULTS`] (by a run that keeps them).
  2119. fn clamp_results(&mut self, report: &mut Report) -> Result<Vec<Vec<Clamp>>> {
  2120. let psos = self.pipelines_named(CLAMP);
  2121. let mut next = 0;
  2122. let mut clamps = Vec::new();
  2123. let mut submits = Vec::new();
  2124. for s in &self.frame.submits {
  2125. let mut lists = Vec::new();
  2126. for &l in s.lists.iter().filter(|&&l| l != MISSING) {
  2127. let cmds = self.commands[l as usize].clone();
  2128. let found = edit::find_clamps(&cmds, &psos, &mut next);
  2129. lists.push(edit::keep_clamped(cmds, &found));
  2130. clamps.push(found);
  2131. }
  2132. submits.push(lists);
  2133. }
  2134. let n: usize = clamps.iter().map(Vec::len).sum();
  2135. report.notes.push(format!(
  2136. "--skip-clamps: {n} clamp passes, {} KB of arguments kept from a first run",
  2137. next >> 10
  2138. ));
  2139. if n == 0 {
  2140. return Ok(clamps);
  2141. }
  2142. self.results = Some(
  2143. gpu::buffer(
  2144. &self.device,
  2145. D3D12_HEAP_TYPE_DEFAULT,
  2146. next,
  2147. D3D12_RESOURCE_FLAG_NONE,
  2148. )?
  2149. .0,
  2150. );
  2151. let built = self.build(&submits, &Options::default())?;
  2152. self.restore(true)?;
  2153. self.send(&built, &Options::default())?;
  2154. self.fresh = false;
  2155. Ok(clamps)
  2156. }
  2157. /// Makes the lists of all submissions, and before each one's the copies
  2158. /// of what the CPU wrote.
  2159. fn build(&self, submits: &[Vec<Vec<Cmd>>], o: &Options) -> Result<Sends> {
  2160. // Room for the timestamps of every command that has one.
  2161. let count: usize = submits
  2162. .iter()
  2163. .flatten()
  2164. .map(|c| {
  2165. 2 + if o.detailed {
  2166. c.iter()
  2167. .filter(|c| c.works() || matches!(c, Cmd::Barriers { .. }))
  2168. .count()
  2169. } else {
  2170. 0
  2171. }
  2172. })
  2173. .sum::<usize>()
  2174. + 2 * submits.len();
  2175. let mut heap: Option<ID3D12QueryHeap> = None;
  2176. let desc = D3D12_QUERY_HEAP_DESC {
  2177. Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
  2178. Count: count.max(1) as u32,
  2179. NodeMask: 0,
  2180. };
  2181. // SAFETY: plain creation.
  2182. unsafe { self.device.CreateQueryHeap(&desc, &mut heap)? };
  2183. let heap = heap.context("no timestamps")?;
  2184. let (back, data) = gpu::buffer(
  2185. &self.device,
  2186. D3D12_HEAP_TYPE_READBACK,
  2187. count.max(1) as u64 * 8,
  2188. D3D12_RESOURCE_FLAG_NONE,
  2189. )?;
  2190. let mut next = 0u32;
  2191. let mut steps = Vec::new();
  2192. for (i, lists) in submits.iter().enumerate() {
  2193. let parts = self.delta_parts.get(i).filter(|p| !p.is_empty());
  2194. let delta = match (parts, &self.deltas) {
  2195. (Some(parts), Some(from)) => {
  2196. let open = self.open(&heap, &mut next)?;
  2197. // SAFETY: an open list; live buffers.
  2198. unsafe {
  2199. let mut seen = HashSet::new();
  2200. let mut after = Vec::new();
  2201. let mut merges = Vec::new();
  2202. for (d, at) in parts {
  2203. let Some(ob) = self.objects.get(&d.res) else {
  2204. continue;
  2205. };
  2206. if self.merging && self.card_writes.contains(&d.res) {
  2207. merges.push((d.res, d.at, *at, d.len));
  2208. continue;
  2209. }
  2210. open.1.CopyBufferRegion(&ob.res, d.at, from, *at, d.len);
  2211. if seen.insert(d.res) {
  2212. // Back to the common state by itself, for
  2213. // lists in the same submission.
  2214. after.push(gpu::transition(&ob.res, ALL, COPY_DEST, COMMON));
  2215. }
  2216. }
  2217. barriers(&open.1, &after);
  2218. if !merges.is_empty() {
  2219. self.wait_for_all(&open.1);
  2220. self.merge_all(&open.1, from.GetGPUVirtualAddress(), &merges);
  2221. self.wait_for_all(&open.1);
  2222. }
  2223. }
  2224. Some(self.close(open, &heap, &mut next, Vec::new())?)
  2225. }
  2226. _ => None,
  2227. };
  2228. let mut built = Vec::new();
  2229. for cmds in lists {
  2230. let open = self.open(&heap, &mut next)?;
  2231. let stamps = self.translate(
  2232. &open.1,
  2233. cmds,
  2234. i,
  2235. o.detailed.then_some((&heap, &mut next)),
  2236. o.wait_all,
  2237. );
  2238. built.push(self.close(open, &heap, &mut next, stamps)?);
  2239. }
  2240. steps.push((delta, built));
  2241. }
  2242. // Between submissions that are sent as one: everything waits. A list
  2243. // each: one cannot stand twice in a submission.
  2244. let mut joints = Vec::new();
  2245. if o.one_submit {
  2246. for _ in 0..2 * submits.len() {
  2247. let open = self.plain_list()?;
  2248. // SAFETY: an open list.
  2249. unsafe {
  2250. self.wait_for_all(&open.1);
  2251. open.1.Close()?;
  2252. }
  2253. joints.push(open);
  2254. }
  2255. }
  2256. let resolve = {
  2257. let open = self.plain_list()?;
  2258. // SAFETY: an open list; `next` queries were written.
  2259. unsafe {
  2260. open.1.ResolveQueryData(
  2261. &heap,
  2262. D3D12_QUERY_TYPE_TIMESTAMP,
  2263. 0,
  2264. next.max(1),
  2265. &back,
  2266. 0,
  2267. );
  2268. open.1.Close()?;
  2269. }
  2270. open
  2271. };
  2272. Ok(Sends {
  2273. steps,
  2274. joints,
  2275. resolve,
  2276. _heap: heap,
  2277. _back: back,
  2278. data: data as usize,
  2279. count: next,
  2280. })
  2281. }
  2282. /// Records a wait for everything before, with all caches written out.
  2283. ///
  2284. /// # Safety
  2285. /// An open list.
  2286. unsafe fn wait_for_all(&self, list: &ID3D12GraphicsCommandList) {
  2287. // SAFETY: the caller's; a feature structure of its size.
  2288. unsafe {
  2289. let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default();
  2290. let size = size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS12>() as u32;
  2291. let known = self
  2292. .device
  2293. .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, (&raw mut o).cast(), size)
  2294. .is_ok();
  2295. if known
  2296. && o.EnhancedBarriersSupported.as_bool()
  2297. && let Ok(list) = list.cast::<ID3D12GraphicsCommandList7>()
  2298. {
  2299. let all = [D3D12_GLOBAL_BARRIER {
  2300. SyncBefore: D3D12_BARRIER_SYNC_ALL,
  2301. SyncAfter: D3D12_BARRIER_SYNC_ALL,
  2302. AccessBefore: D3D12_BARRIER_ACCESS_COMMON,
  2303. AccessAfter: D3D12_BARRIER_ACCESS_COMMON,
  2304. }];
  2305. list.Barrier(&[D3D12_BARRIER_GROUP {
  2306. Type: D3D12_BARRIER_TYPE_GLOBAL,
  2307. NumBarriers: 1,
  2308. Anonymous: D3D12_BARRIER_GROUP_0 {
  2309. pGlobalBarriers: all.as_ptr(),
  2310. },
  2311. }]);
  2312. } else {
  2313. list.ResourceBarrier(&[alias(), uav_barrier(None)]);
  2314. }
  2315. }
  2316. }
  2317. fn plain_list(&self) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> {
  2318. // SAFETY: plain creation.
  2319. unsafe {
  2320. let allocator: ID3D12CommandAllocator = self
  2321. .device
  2322. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  2323. let list = self.device.CreateCommandList(
  2324. 0,
  2325. D3D12_COMMAND_LIST_TYPE_DIRECT,
  2326. &allocator,
  2327. None,
  2328. )?;
  2329. Ok((allocator, list))
  2330. }
  2331. }
  2332. fn open(
  2333. &self,
  2334. heap: &ID3D12QueryHeap,
  2335. next: &mut u32,
  2336. ) -> Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32)> {
  2337. let (allocator, list) = self.plain_list()?;
  2338. // SAFETY: an open list; a query of the heap.
  2339. unsafe { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next) };
  2340. *next += 1;
  2341. Ok((allocator, list, *next - 1))
  2342. }
  2343. fn close(
  2344. &self,
  2345. (allocator, list, first): (ID3D12CommandAllocator, ID3D12GraphicsCommandList, u32),
  2346. heap: &ID3D12QueryHeap,
  2347. next: &mut u32,
  2348. stamps: Vec<Stamp>,
  2349. ) -> Result<Built> {
  2350. // SAFETY: as above.
  2351. unsafe {
  2352. list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, *next);
  2353. list.Close()
  2354. .context("a list of the frame could not be recorded again")?;
  2355. }
  2356. *next += 1;
  2357. Ok(Built {
  2358. _allocator: allocator,
  2359. list,
  2360. first,
  2361. last: *next - 1,
  2362. stamps,
  2363. })
  2364. }
  2365. /// Records commands into a list, in submission `submit`.
  2366. fn translate(
  2367. &self,
  2368. list: &ID3D12GraphicsCommandList,
  2369. cmds: &[Cmd],
  2370. submit: usize,
  2371. mut stamp: Option<(&ID3D12QueryHeap, &mut u32)>,
  2372. wait: bool,
  2373. ) -> Vec<Stamp> {
  2374. let version = self.version_of.get(submit).copied().unwrap_or(0);
  2375. let mut clamps = self.pipelines_named(CLAMP);
  2376. clamps.insert(edit::BATCH);
  2377. let compares = self.pipelines_named(COMPARE);
  2378. let mesh: HashSet<u32> = self
  2379. .frame
  2380. .pipelines
  2381. .iter()
  2382. .filter(|p| p.parts.iter().any(|part| matches!(part, wire::Part::Code { kind, .. } if *kind == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS.0)))
  2383. .map(|p| p.id)
  2384. .collect();
  2385. let dispatches: HashSet<u32> = self
  2386. .frame
  2387. .signatures
  2388. .iter()
  2389. .filter(|s| {
  2390. s.args
  2391. .iter()
  2392. .any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)
  2393. })
  2394. .map(|s| s.id)
  2395. .collect();
  2396. let mut stamps = Vec::new();
  2397. let mut bound = NONE;
  2398. // What the compute side has bound.
  2399. let mut compute: Vec<Cmd> = Vec::new();
  2400. for c in cmds {
  2401. if let Cmd::Pipeline { pso } = c {
  2402. bound = *pso;
  2403. }
  2404. let merged = self.merged_copy(c);
  2405. if let Some((from, what)) = merged {
  2406. // SAFETY: an open list; live buffers; what the compute side
  2407. // of it had bound is bound again.
  2408. unsafe {
  2409. self.wait_for_all(list);
  2410. self.merge_all(list, from, &[what]);
  2411. self.wait_for_all(list);
  2412. for c in &compute {
  2413. self.command(list, c, version);
  2414. }
  2415. }
  2416. } else {
  2417. // SAFETY: an open list; the objects are the frame's, alive
  2418. // with the player; commands the host recorded the same way.
  2419. unsafe { self.command(list, c, version) };
  2420. }
  2421. match c {
  2422. Cmd::RootSignature {
  2423. graphics: false, ..
  2424. } => {
  2425. compute.retain(|c| matches!(c, Cmd::Pipeline { .. }));
  2426. compute.push(c.clone());
  2427. }
  2428. Cmd::Pipeline { .. } => {
  2429. compute.retain(|c| !matches!(c, Cmd::Pipeline { .. }));
  2430. compute.push(c.clone());
  2431. }
  2432. Cmd::Table {
  2433. graphics: false, ..
  2434. }
  2435. | Cmd::Constants {
  2436. graphics: false, ..
  2437. }
  2438. | Cmd::RootView {
  2439. graphics: false, ..
  2440. } => compute.push(c.clone()),
  2441. _ => {}
  2442. }
  2443. if wait && c.works() {
  2444. // SAFETY: an open list.
  2445. unsafe { self.wait_for_all(list) };
  2446. }
  2447. let timed = c.works() || matches!(c, Cmd::Barriers { .. });
  2448. if timed && let Some((heap, next)) = &mut stamp {
  2449. // SAFETY: as above.
  2450. unsafe { list.EndQuery(*heap, D3D12_QUERY_TYPE_TIMESTAMP, **next) };
  2451. let category = match c {
  2452. Cmd::Barriers { .. } => "barriers",
  2453. Cmd::Dispatch { .. } if clamps.contains(&bound) => "argument clamps (ours)",
  2454. Cmd::Dispatch { .. } if compares.contains(&bound) => {
  2455. "hash and compare passes (ours)"
  2456. }
  2457. Cmd::Dispatch { .. } => "dispatches",
  2458. Cmd::Indirect { signature, .. } if dispatches.contains(signature) => {
  2459. "indirect dispatches"
  2460. }
  2461. Cmd::Indirect { .. } if mesh.contains(&bound) => "indirect mesh draws",
  2462. Cmd::Indirect { .. } => "indirect draws",
  2463. Cmd::Draw { .. } | Cmd::DrawIndexed { .. } | Cmd::DispatchMesh { .. } => {
  2464. "draws"
  2465. }
  2466. Cmd::ClearDepth { .. } | Cmd::ClearTarget { .. } | Cmd::Discard { .. } => {
  2467. "clears"
  2468. }
  2469. Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves",
  2470. _ => self.copy_kind(c),
  2471. };
  2472. let runs = match c {
  2473. c if c.runs_shaders() => bound,
  2474. // Copies to textures by what they go to.
  2475. Cmd::CopyResource { dst, .. }
  2476. | Cmd::CopyTexture {
  2477. dst: Loc::Sub { res: dst, .. },
  2478. ..
  2479. } => COPY_TO | dst,
  2480. _ => NONE,
  2481. };
  2482. stamps.push((**next as usize, category, runs));
  2483. **next += 1;
  2484. }
  2485. }
  2486. stamps
  2487. }
  2488. /// Which copies a copy is counted with: by the memory it crosses.
  2489. fn copy_kind(&self, c: &Cmd) -> &'static str {
  2490. let pc = |id: u32| {
  2491. self.objects.get(&id).is_some_and(|o| {
  2492. matches!(&self.frame.resources[o.index].place,
  2493. Place::Committed { props, .. } if gpu::seen(props) != Seen::No)
  2494. })
  2495. };
  2496. let res = |l: &Loc| match l {
  2497. Loc::Sub { res, .. } | Loc::Placed { res, .. } => *res,
  2498. };
  2499. match c {
  2500. Cmd::CopyBuffer { dst, src, .. } => match (pc(*dst), pc(*src)) {
  2501. (false, true) => "copies of buffers, PC to card",
  2502. (true, false) => "copies of buffers, card to PC",
  2503. (true, true) => "copies of buffers, PC to PC",
  2504. (false, false) => "copies of buffers, card to card",
  2505. },
  2506. Cmd::CopyTexture { dst, src, .. } => match (pc(res(dst)), pc(res(src))) {
  2507. (false, true) => "copies of textures, PC to card",
  2508. (true, _) => "copies of textures, to the PC",
  2509. (false, false) => "copies of textures, card to card",
  2510. },
  2511. Cmd::CopyResource { .. } => "copies of whole resources",
  2512. _ => "copies",
  2513. }
  2514. }
  2515. unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) {
  2516. let res = |id: u32| self.resource(id);
  2517. let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default();
  2518. // SAFETY: the caller's.
  2519. unsafe {
  2520. match c {
  2521. Cmd::Draw {
  2522. vertices,
  2523. instances,
  2524. first,
  2525. first_instance,
  2526. } => l.DrawInstanced(*vertices, *instances, *first, *first_instance),
  2527. Cmd::DrawIndexed {
  2528. indices,
  2529. instances,
  2530. first,
  2531. base,
  2532. first_instance,
  2533. } => {
  2534. l.DrawIndexedInstanced(*indices, *instances, *first, *base, *first_instance);
  2535. }
  2536. Cmd::Dispatch { groups } => l.Dispatch(groups[0], groups[1], groups[2]),
  2537. Cmd::DispatchMesh { groups } => {
  2538. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList6>() {
  2539. l.DispatchMesh(groups[0], groups[1], groups[2]);
  2540. }
  2541. }
  2542. Cmd::CopyBuffer {
  2543. dst,
  2544. dst_at,
  2545. src,
  2546. src_at,
  2547. len,
  2548. } => {
  2549. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2550. l.CopyBufferRegion(dst, *dst_at, src, *src_at, *len);
  2551. }
  2552. }
  2553. Cmd::CopyTexture { dst, at, src, part } => {
  2554. let side = |loc: &Loc| match loc {
  2555. Loc::Sub { res: id, sub } => Some(gpu::sub_location(res(*id)?, *sub)),
  2556. Loc::Placed {
  2557. res: id,
  2558. offset,
  2559. format,
  2560. size,
  2561. pitch,
  2562. } => {
  2563. let f = D3D12_SUBRESOURCE_FOOTPRINT {
  2564. Format: DXGI_FORMAT(*format),
  2565. Width: size[0],
  2566. Height: size[1],
  2567. Depth: size[2],
  2568. RowPitch: *pitch,
  2569. };
  2570. Some(gpu::placed_location(
  2571. res(*id)?,
  2572. D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  2573. Offset: *offset,
  2574. Footprint: f,
  2575. },
  2576. ))
  2577. }
  2578. };
  2579. if let (Some(dst), Some(src)) = (side(dst), side(src)) {
  2580. let part = part.map(|p| D3D12_BOX {
  2581. left: p[0],
  2582. top: p[1],
  2583. front: p[2],
  2584. right: p[3],
  2585. bottom: p[4],
  2586. back: p[5],
  2587. });
  2588. l.CopyTextureRegion(
  2589. &dst,
  2590. at[0],
  2591. at[1],
  2592. at[2],
  2593. &src,
  2594. part.as_ref().map(|p| p as *const _),
  2595. );
  2596. }
  2597. }
  2598. Cmd::CopyResource { dst, src } => {
  2599. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2600. l.CopyResource(dst, src);
  2601. }
  2602. }
  2603. Cmd::Resolve {
  2604. dst,
  2605. dst_sub,
  2606. src,
  2607. src_sub,
  2608. format,
  2609. } => {
  2610. if let (Some(dst), Some(src)) = (res(*dst), res(*src)) {
  2611. l.ResolveSubresource(dst, *dst_sub, src, *src_sub, DXGI_FORMAT(*format));
  2612. }
  2613. }
  2614. Cmd::ResolveRegion {
  2615. dst,
  2616. dst_sub,
  2617. at,
  2618. src,
  2619. src_sub,
  2620. part,
  2621. format,
  2622. mode,
  2623. } => {
  2624. if let (Some(dst), Some(src), Ok(l)) =
  2625. (res(*dst), res(*src), l.cast::<ID3D12GraphicsCommandList1>())
  2626. {
  2627. let part = part.map(to_rect);
  2628. let part = part.as_ref().map(|r| r as *const _);
  2629. l.ResolveSubresourceRegion(
  2630. dst,
  2631. *dst_sub,
  2632. at[0],
  2633. at[1],
  2634. src,
  2635. *src_sub,
  2636. part,
  2637. DXGI_FORMAT(*format),
  2638. D3D12_RESOLVE_MODE(*mode),
  2639. );
  2640. }
  2641. }
  2642. Cmd::Topology { kind } => l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(*kind)),
  2643. Cmd::Viewports { all } => {
  2644. let all: Vec<D3D12_VIEWPORT> = all
  2645. .iter()
  2646. .map(|v| D3D12_VIEWPORT {
  2647. TopLeftX: v[0],
  2648. TopLeftY: v[1],
  2649. Width: v[2],
  2650. Height: v[3],
  2651. MinDepth: v[4],
  2652. MaxDepth: v[5],
  2653. })
  2654. .collect();
  2655. l.RSSetViewports(&all);
  2656. }
  2657. Cmd::Scissors { all } => {
  2658. l.RSSetScissorRects(&all.iter().map(|r| to_rect(*r)).collect::<Vec<_>>())
  2659. }
  2660. Cmd::BlendFactor { factor } => l.OMSetBlendFactor(factor.as_ref()),
  2661. Cmd::StencilRef { value } => l.OMSetStencilRef(*value),
  2662. Cmd::DepthBounds { min, max } => {
  2663. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList1>() {
  2664. l.OMSetDepthBounds(*min, *max);
  2665. }
  2666. }
  2667. Cmd::Pipeline { pso } => {
  2668. if let Some(p) = self.pipelines.get(pso) {
  2669. l.SetPipelineState(p);
  2670. }
  2671. }
  2672. Cmd::Barriers { all } => {
  2673. let all: Vec<D3D12_RESOURCE_BARRIER> =
  2674. all.iter().filter_map(|b| self.barrier(b)).collect();
  2675. barriers(l, &all);
  2676. }
  2677. Cmd::Heaps { heaps } => {
  2678. let all: Vec<Option<ID3D12DescriptorHeap>> = heaps
  2679. .iter()
  2680. .filter_map(|id| {
  2681. Some(Some(self.descriptors.get(id)?.0.get(version)?.heap.clone()))
  2682. })
  2683. .collect();
  2684. l.SetDescriptorHeaps(&all);
  2685. }
  2686. Cmd::RootSignature { graphics, root } => {
  2687. let root = self.roots.get(root);
  2688. if *graphics {
  2689. l.SetGraphicsRootSignature(root)
  2690. } else {
  2691. l.SetComputeRootSignature(root)
  2692. }
  2693. }
  2694. Cmd::Table {
  2695. graphics,
  2696. param,
  2697. heap,
  2698. slot,
  2699. } => {
  2700. if let Some((versions, step)) = self.descriptors.get(heap)
  2701. && let Some(v) = versions.get(version)
  2702. {
  2703. let at = D3D12_GPU_DESCRIPTOR_HANDLE {
  2704. ptr: v.gpu + u64::from(*slot) * step,
  2705. };
  2706. if *graphics {
  2707. l.SetGraphicsRootDescriptorTable(*param, at)
  2708. } else {
  2709. l.SetComputeRootDescriptorTable(*param, at)
  2710. }
  2711. }
  2712. }
  2713. Cmd::Constants {
  2714. graphics,
  2715. param,
  2716. offset,
  2717. values,
  2718. } => {
  2719. let (n, data) = (values.len() as u32, values.as_ptr().cast());
  2720. if *graphics {
  2721. l.SetGraphicsRoot32BitConstants(*param, n, data, *offset);
  2722. } else {
  2723. l.SetComputeRoot32BitConstants(*param, n, data, *offset);
  2724. }
  2725. }
  2726. Cmd::RootView {
  2727. graphics,
  2728. kind,
  2729. param,
  2730. va,
  2731. } => {
  2732. let va = self.va(va);
  2733. match (*kind, *graphics) {
  2734. (slot::CBV, true) => l.SetGraphicsRootConstantBufferView(*param, va),
  2735. (slot::CBV, false) => l.SetComputeRootConstantBufferView(*param, va),
  2736. (slot::SRV, true) => l.SetGraphicsRootShaderResourceView(*param, va),
  2737. (slot::SRV, false) => l.SetComputeRootShaderResourceView(*param, va),
  2738. (_, true) => l.SetGraphicsRootUnorderedAccessView(*param, va),
  2739. (_, false) => l.SetComputeRootUnorderedAccessView(*param, va),
  2740. }
  2741. }
  2742. Cmd::IndexBuffer { view } => {
  2743. let v = view
  2744. .as_ref()
  2745. .map(|(va, size, format)| D3D12_INDEX_BUFFER_VIEW {
  2746. BufferLocation: self.va(va),
  2747. SizeInBytes: *size,
  2748. Format: DXGI_FORMAT(*format),
  2749. });
  2750. l.IASetIndexBuffer(v.as_ref().map(|v| v as *const _));
  2751. }
  2752. Cmd::VertexBuffers {
  2753. start,
  2754. views,
  2755. count,
  2756. } => match views {
  2757. Some(views) => {
  2758. let all: Vec<D3D12_VERTEX_BUFFER_VIEW> = views
  2759. .iter()
  2760. .map(|(va, size, stride)| D3D12_VERTEX_BUFFER_VIEW {
  2761. BufferLocation: self.va(va),
  2762. SizeInBytes: *size,
  2763. StrideInBytes: *stride,
  2764. })
  2765. .collect();
  2766. l.IASetVertexBuffers(*start, Some(&all));
  2767. }
  2768. None => l.IASetVertexBuffers(
  2769. *start,
  2770. Some(&vec![D3D12_VERTEX_BUFFER_VIEW::default(); *count as usize]),
  2771. ),
  2772. },
  2773. Cmd::Targets { colors, depth } => {
  2774. let colors: Vec<D3D12_CPU_DESCRIPTOR_HANDLE> =
  2775. colors.iter().map(view).collect();
  2776. let depth = depth.as_ref().map(view);
  2777. l.OMSetRenderTargets(
  2778. colors.len() as u32,
  2779. (!colors.is_empty()).then_some(colors.as_ptr()),
  2780. false,
  2781. depth.as_ref().map(|d| d as *const _),
  2782. );
  2783. }
  2784. Cmd::ClearDepth {
  2785. view: v,
  2786. flags,
  2787. depth,
  2788. stencil,
  2789. rects,
  2790. } => {
  2791. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2792. let rects = (!rects.is_empty()).then_some(&rects[..]);
  2793. if self.objects.contains_key(&v.res) {
  2794. l.ClearDepthStencilView(
  2795. view(v),
  2796. D3D12_CLEAR_FLAGS(*flags),
  2797. *depth,
  2798. *stencil,
  2799. rects,
  2800. );
  2801. }
  2802. }
  2803. Cmd::ClearTarget {
  2804. view: v,
  2805. color,
  2806. rects,
  2807. } => {
  2808. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2809. let rects = (!rects.is_empty()).then_some(&rects[..]);
  2810. if self.objects.contains_key(&v.res) {
  2811. l.ClearRenderTargetView(view(v), color, rects);
  2812. }
  2813. }
  2814. Cmd::Discard {
  2815. res: id,
  2816. rects,
  2817. subs,
  2818. } => {
  2819. if let Some(r) = res(*id) {
  2820. let rects: Vec<RECT> = rects.iter().map(|r| to_rect(*r)).collect();
  2821. let region = subs.map(|s| D3D12_DISCARD_REGION {
  2822. NumRects: rects.len() as u32,
  2823. pRects: if rects.is_empty() {
  2824. std::ptr::null()
  2825. } else {
  2826. rects.as_ptr()
  2827. },
  2828. FirstSubresource: s[0],
  2829. NumSubresources: s[1],
  2830. });
  2831. l.DiscardResource(r, region.as_ref().map(|r| r as *const _));
  2832. }
  2833. }
  2834. Cmd::BeginQuery { heap, kind, index } => {
  2835. if let Some(h) = self.queries.get(heap) {
  2836. l.BeginQuery(h, D3D12_QUERY_TYPE(*kind), *index);
  2837. }
  2838. }
  2839. Cmd::EndQuery { heap, kind, index } => {
  2840. if let Some(h) = self.queries.get(heap) {
  2841. l.EndQuery(h, D3D12_QUERY_TYPE(*kind), *index);
  2842. }
  2843. }
  2844. Cmd::ResolveQuery {
  2845. heap,
  2846. kind,
  2847. first,
  2848. count,
  2849. dst,
  2850. at,
  2851. } => {
  2852. if let (Some(h), Some(dst)) = (self.queries.get(heap), res(*dst)) {
  2853. l.ResolveQueryData(h, D3D12_QUERY_TYPE(*kind), *first, *count, dst, *at);
  2854. }
  2855. }
  2856. Cmd::Indirect {
  2857. signature,
  2858. most,
  2859. args,
  2860. at,
  2861. count,
  2862. count_at,
  2863. } => {
  2864. if let (Some(s), Some(a)) = (self.signatures.get(signature), res(*args)) {
  2865. l.ExecuteIndirect(s, *most, a, *at, res(*count), *count_at);
  2866. }
  2867. }
  2868. Cmd::WriteImmediate { all } => {
  2869. if let Ok(l) = l.cast::<ID3D12GraphicsCommandList2>() {
  2870. let all: Vec<&(Va, u32, i32)> =
  2871. all.iter().filter(|(va, _, _)| self.va(va) != 0).collect();
  2872. let params: Vec<D3D12_WRITEBUFFERIMMEDIATE_PARAMETER> = all
  2873. .iter()
  2874. .map(|(va, v, _)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER {
  2875. Dest: self.va(va),
  2876. Value: *v,
  2877. })
  2878. .collect();
  2879. let modes: Vec<D3D12_WRITEBUFFERIMMEDIATE_MODE> = all
  2880. .iter()
  2881. .map(|(_, _, m)| D3D12_WRITEBUFFERIMMEDIATE_MODE(*m))
  2882. .collect();
  2883. if !params.is_empty() {
  2884. l.WriteBufferImmediate(
  2885. params.len() as u32,
  2886. params.as_ptr(),
  2887. Some(modes.as_ptr()),
  2888. );
  2889. }
  2890. }
  2891. }
  2892. }
  2893. }
  2894. }
  2895. fn barrier(&self, b: &Barrier) -> Option<D3D12_RESOURCE_BARRIER> {
  2896. Some(match b {
  2897. Barrier::Transition {
  2898. flags,
  2899. res,
  2900. sub,
  2901. before,
  2902. after,
  2903. } => {
  2904. let mut t =
  2905. gpu::transition(self.resource(*res)?, *sub, *before as u32, *after as u32);
  2906. t.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags);
  2907. t
  2908. }
  2909. Barrier::Uav { flags, res } => {
  2910. let mut u = uav_barrier(if *res == NONE {
  2911. None
  2912. } else {
  2913. Some(self.resource(*res)?)
  2914. });
  2915. u.Flags = D3D12_RESOURCE_BARRIER_FLAGS(*flags);
  2916. u
  2917. }
  2918. Barrier::Alias {
  2919. flags,
  2920. before,
  2921. after,
  2922. } => {
  2923. let side = |id: &u32| -> std::mem::ManuallyDrop<Option<ID3D12Resource>> {
  2924. // SAFETY: a borrowed pointer (or none) never released.
  2925. self.resource(*id)
  2926. .map_or(std::mem::ManuallyDrop::new(None), |r| unsafe {
  2927. std::mem::transmute_copy(r)
  2928. })
  2929. };
  2930. D3D12_RESOURCE_BARRIER {
  2931. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  2932. Flags: D3D12_RESOURCE_BARRIER_FLAGS(*flags),
  2933. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  2934. Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  2935. pResourceBefore: side(before),
  2936. pResourceAfter: side(after),
  2937. }),
  2938. },
  2939. }
  2940. }
  2941. })
  2942. }
  2943. /// Sends the frame, waits for it, and reads the timestamps.
  2944. fn send(&mut self, s: &Sends, o: &Options) -> Result<Vec<u64>> {
  2945. let cast = |l: &ID3D12GraphicsCommandList| l.cast::<ID3D12CommandList>().map(Some);
  2946. let mut submissions: Vec<Vec<Option<ID3D12CommandList>>> = Vec::new();
  2947. for (delta, lists) in &s.steps {
  2948. if let Some(d) = delta {
  2949. submissions.push(vec![cast(&d.list)?]);
  2950. }
  2951. let mut all = Vec::new();
  2952. for l in lists {
  2953. all.push(cast(&l.list)?);
  2954. }
  2955. if !all.is_empty() {
  2956. submissions.push(all);
  2957. }
  2958. }
  2959. if o.one_submit {
  2960. let mut all = Vec::new();
  2961. for (i, lists) in submissions.into_iter().enumerate() {
  2962. if i > 0
  2963. && let Some(joint) = s.joints.get(i)
  2964. {
  2965. all.push(cast(&joint.1)?);
  2966. }
  2967. all.extend(lists);
  2968. }
  2969. submissions = vec![all];
  2970. }
  2971. // SAFETY: closed lists whose last run has finished.
  2972. unsafe {
  2973. for all in &submissions {
  2974. if !o.wait_lists {
  2975. self.worker.queue.ExecuteCommandLists(all);
  2976. if o.pace > 0.0 {
  2977. let until = Instant::now() + std::time::Duration::from_secs_f64(o.pace / 1e3);
  2978. while Instant::now() < until {
  2979. std::thread::yield_now();
  2980. }
  2981. }
  2982. continue;
  2983. }
  2984. for l in all {
  2985. self.worker.queue.ExecuteCommandLists(&[l.clone()]);
  2986. self.worker.idle()?;
  2987. }
  2988. }
  2989. self.worker
  2990. .queue
  2991. .ExecuteCommandLists(&[cast(&s.resolve.1)?]);
  2992. }
  2993. self.worker
  2994. .idle()
  2995. .context("the card was lost running the frame")?;
  2996. // SAFETY: the mapping of `count` resolved timestamps.
  2997. Ok(unsafe { std::slice::from_raw_parts(s.data as *const u64, s.count as usize) }.to_vec())
  2998. }
  2999. /// Runs the frame as the options say.
  3000. pub fn run(&mut self, o: &Options) -> Result<Report> {
  3001. let mut made = self.prepare(o)?;
  3002. let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None };
  3003. let mut stamps = Vec::new();
  3004. for _ in 0..o.loops.max(1) {
  3005. stamps.push(self.once(o, &mut made)?);
  3006. }
  3007. self.finish(o, made, &stamps)
  3008. }
  3009. /// The lists for a run as the options say.
  3010. fn prepare(&mut self, o: &Options) -> Result<(Sends, Report)> {
  3011. let mut report = Report {
  3012. notes: self.notes.clone(),
  3013. ..Default::default()
  3014. };
  3015. self.set_merging(o.merge)?;
  3016. let clamps = if o.skip_clamps {
  3017. self.clamp_results(&mut report)?
  3018. } else {
  3019. Vec::new()
  3020. };
  3021. let submits = self.edited(o, &mut report, &clamps);
  3022. Ok((self.build(&submits, o)?, report))
  3023. }
  3024. /// One run of the frame, noted in the report; its timestamps.
  3025. fn once(&mut self, o: &Options, (built, report): &mut (Sends, Report)) -> Result<Vec<u64>> {
  3026. self.restore(o.restore)?;
  3027. self.fresh = false;
  3028. let stamps = self.send(built, o)?;
  3029. if let Some((db, _, hash, _)) = self.picture_now()? {
  3030. report.pictures.push((db, hash));
  3031. }
  3032. let ms = |a: u32, b: u32| {
  3033. stamps[b as usize].saturating_sub(stamps[a as usize]) as f64 * 1e3 / self.frequency
  3034. };
  3035. let lists: Vec<&Built> = built.steps.iter().flat_map(|(_, l)| l).collect();
  3036. let (Some(first), Some(last)) = (lists.first(), lists.last()) else {
  3037. bail!("no lists to run");
  3038. };
  3039. let delta = built.steps.iter().filter_map(|(d, _)| d.as_ref());
  3040. report.delta_ms.push(
  3041. delta
  3042. .filter(|d| d.first > first.first)
  3043. .map(|d| ms(d.first, d.last))
  3044. .sum(),
  3045. );
  3046. report.frame_ms.push(ms(first.first, last.last));
  3047. let each = |l: &[Built]| match (l.first(), l.last()) {
  3048. (Some(a), Some(b)) => ms(a.first, b.last),
  3049. _ => 0.0,
  3050. };
  3051. report.submits = built
  3052. .steps
  3053. .iter()
  3054. .map(|(_, l)| (l.len(), each(l)))
  3055. .collect();
  3056. report
  3057. .busy_ms
  3058. .push(report.submits.iter().map(|s| s.1).sum());
  3059. Ok(stamps)
  3060. }
  3061. /// The report after the last run.
  3062. fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[Vec<u64>]) -> Result<Report> {
  3063. if o.detailed {
  3064. self.detail(&built, stamps, o, &mut report);
  3065. }
  3066. if self.merging {
  3067. let notes = self.merge_notes(o.loops)?;
  3068. report.notes.extend(notes);
  3069. }
  3070. self.picture(o, &mut report)?;
  3071. if let Some(q) = &self.info {
  3072. report.notes.extend(debug_messages(q));
  3073. }
  3074. Ok(report)
  3075. }
  3076. /// The time by command: the median of the loops, without the first (which
  3077. /// is slower) where there are others.
  3078. fn detail(&self, built: &Sends, stamps: &[Vec<u64>], o: &Options, report: &mut Report) {
  3079. let mut kinds: BTreeMap<&str, (Vec<f64>, u32)> = BTreeMap::new();
  3080. let mut shaders: HashMap<u32, (Vec<f64>, u32)> = HashMap::new();
  3081. let loops = if stamps.len() > 2 { &stamps[1..] } else { stamps };
  3082. for stamps in loops {
  3083. let mut of_kind: BTreeMap<&str, (f64, u32)> = BTreeMap::new();
  3084. let mut of_shader: HashMap<u32, (f64, u32)> = HashMap::new();
  3085. for l in built.steps.iter().flat_map(|(_, l)| l) {
  3086. let mut before = stamps[l.first as usize];
  3087. for &(at, kind, pso) in &l.stamps {
  3088. let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency;
  3089. before = before.max(stamps[at]);
  3090. let k = of_kind.entry(kind).or_default();
  3091. *k = (k.0 + ms, k.1 + 1);
  3092. if pso != NONE {
  3093. let s = of_shader.entry(pso).or_default();
  3094. *s = (s.0 + ms, s.1 + 1);
  3095. }
  3096. }
  3097. }
  3098. for (k, (ms, n)) in of_kind {
  3099. let all = kinds.entry(k).or_default();
  3100. all.0.push(ms);
  3101. all.1 = n;
  3102. }
  3103. for (k, (ms, n)) in of_shader {
  3104. let all = shaders.entry(k).or_default();
  3105. all.0.push(ms);
  3106. all.1 = n;
  3107. }
  3108. }
  3109. let kinds = kinds.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n)));
  3110. let shaders = shaders.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n)));
  3111. report.categories = kinds
  3112. .into_iter()
  3113. .map(|(k, (ms, n))| (k.to_owned(), ms, n))
  3114. .collect();
  3115. report.categories.sort_by(|a, b| b.1.total_cmp(&a.1));
  3116. let mut all: Vec<(f64, u32, u32)> = shaders
  3117. .into_iter()
  3118. .map(|(pso, (ms, n))| (ms, n, pso))
  3119. .collect();
  3120. all.sort_by(|a, b| b.0.total_cmp(&a.0));
  3121. all.truncate(o.top);
  3122. report.shaders = all
  3123. .into_iter()
  3124. .map(|(ms, n, pso)| {
  3125. let name = match self.objects.get(&(pso & !COPY_TO)).filter(|_| pso & COPY_TO != 0) {
  3126. Some(o) => {
  3127. let r = &self.frame.resources[o.index];
  3128. format!("copies to #{} {}", pso & !COPY_TO, r.name)
  3129. }
  3130. None => self.pipeline_name(pso),
  3131. };
  3132. (ms, n, name)
  3133. })
  3134. .collect();
  3135. }
  3136. /// The presented picture as it is now: dB against the recorded one,
  3137. /// whether its bytes are the same, its hash, and its pixels.
  3138. fn picture_now(&mut self) -> Result<Option<(f64, bool, String, Vec<u8>)>> {
  3139. let Some(p) = self.frame.presents.last().cloned() else {
  3140. return Ok(None);
  3141. };
  3142. let Some(bytes) = self.contents(p.res)? else {
  3143. return Ok(None);
  3144. };
  3145. let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
  3146. return Ok(None);
  3147. };
  3148. let mut recorded = vec![0; bytes.len()];
  3149. read_at(
  3150. &File::open(self.folder.join("present.bin"))?,
  3151. &mut recorded,
  3152. p.file,
  3153. )?;
  3154. let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
  3155. let hash = blake3::hash(&rgb).to_hex().to_string();
  3156. Ok(Some((
  3157. gpu::psnr(&rgb, &was),
  3158. rows_equal(&p, &bytes, &recorded),
  3159. hash,
  3160. rgb,
  3161. )))
  3162. }
  3163. /// Saves the presented picture and compares it with the recorded one.
  3164. fn picture(&mut self, o: &Options, report: &mut Report) -> Result<()> {
  3165. let Some(p) = self.frame.presents.last().cloned() else {
  3166. report.notes.push("no picture was presented".into());
  3167. return Ok(());
  3168. };
  3169. let Some(bytes) = self.contents(p.res)? else {
  3170. report
  3171. .notes
  3172. .push("the presented texture is not there".into());
  3173. return Ok(());
  3174. };
  3175. let Some(rgb) = gpu::rgb(p.width, p.height, p.pitch, p.format, &bytes) else {
  3176. report
  3177. .notes
  3178. .push("the presented format is not shown".into());
  3179. return Ok(());
  3180. };
  3181. let path = o
  3182. .image
  3183. .clone()
  3184. .unwrap_or_else(|| self.folder.join("replay.png"));
  3185. std::fs::write(&path, crate::capture::png(p.width, p.height, &rgb))?;
  3186. let mut recorded = vec![0; bytes.len()];
  3187. read_at(
  3188. &File::open(self.folder.join("present.bin"))?,
  3189. &mut recorded,
  3190. p.file,
  3191. )?;
  3192. let was = gpu::rgb(p.width, p.height, p.pitch, p.format, &recorded).unwrap_or_default();
  3193. report.picture = Some((gpu::psnr(&rgb, &was), rows_equal(&p, &bytes, &recorded)));
  3194. report.notes.push(format!(
  3195. "picture {} (blake3 {}; recorded {})",
  3196. path.display(),
  3197. &blake3::hash(&rgb).to_hex()[..16],
  3198. &blake3::hash(&was).to_hex()[..16]
  3199. ));
  3200. Ok(())
  3201. }
  3202. /// What a resource holds now (after a run): a buffer's bytes, or a
  3203. /// texture's first subresource in its copyable layout.
  3204. pub fn contents(&mut self, id: u32) -> Result<Option<Vec<u8>>> {
  3205. self.contents_of(id, 0)
  3206. }
  3207. /// As [`Player::contents`], of a texture's subresource `sub`.
  3208. pub fn contents_of(&mut self, id: u32, sub: u32) -> Result<Option<Vec<u8>>> {
  3209. let Some(o) = self.objects.get(&id) else {
  3210. return Ok(None);
  3211. };
  3212. let (res, r, subs) = (o.res.clone(), &self.frame.resources[o.index], o.subs);
  3213. let desc = gpu::to_desc(&r.desc);
  3214. let is_buffer = r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  3215. let states = if self.fresh { &self.start } else { &self.end };
  3216. let state = states.get(&id).cloned().unwrap_or(vec![COMMON]);
  3217. let (f, total) = if is_buffer {
  3218. (Vec::new(), r.desc.width)
  3219. } else {
  3220. gpu::footprints(&self.device, &desc, sub, 1)
  3221. };
  3222. let (back, data) = gpu::buffer(
  3223. &self.device,
  3224. D3D12_HEAP_TYPE_READBACK,
  3225. total,
  3226. D3D12_RESOURCE_FLAG_NONE,
  3227. )?;
  3228. self.worker.run(|list| {
  3229. if is_buffer {
  3230. // SAFETY: an open list; live buffers.
  3231. unsafe { list.CopyBufferRegion(&back, 0, &res, 0, total) };
  3232. } else if state.len() == 1 || subs == 1 {
  3233. read_sub(list, &res, sub, state[0], &back, f[0]);
  3234. } else {
  3235. let (mut before, mut after) = (Vec::new(), Vec::new());
  3236. gpu::moves(&res, &state, &[COPY_SOURCE], &mut before);
  3237. gpu::moves(&res, &[COPY_SOURCE], &state, &mut after);
  3238. // SAFETY: an open list; live resources.
  3239. unsafe { barriers(list, &before) };
  3240. read_sub(list, &res, sub, COPY_SOURCE, &back, f[0]);
  3241. // SAFETY: as above.
  3242. unsafe { barriers(list, &after) };
  3243. }
  3244. })?;
  3245. // SAFETY: the buffer's mapping; the copy into it has run.
  3246. Ok(Some(
  3247. unsafe { std::slice::from_raw_parts(data, total as usize) }.to_vec(),
  3248. ))
  3249. }
  3250. /// The id of the resource of a name (tests).
  3251. pub fn named(&self, name: &str) -> Option<u32> {
  3252. self.frame
  3253. .resources
  3254. .iter()
  3255. .find(|r| r.name == name)
  3256. .map(|r| r.id)
  3257. }
  3258. }
  3259. /// Everything to send for a frame.
  3260. struct Sends {
  3261. /// For each submission: the copies of what the CPU wrote, its lists.
  3262. steps: Vec<(Option<Built>, Vec<Built>)>,
  3263. joints: Vec<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
  3264. resolve: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
  3265. _heap: ID3D12QueryHeap,
  3266. _back: ID3D12Resource,
  3267. data: usize,
  3268. count: u32,
  3269. }
  3270. fn rows_equal(p: &wire::Present, a: &[u8], b: &[u8]) -> bool {
  3271. let texel = match p.format {
  3272. 9..=14 => 8,
  3273. _ => 4,
  3274. };
  3275. (0..p.height as usize).all(|y| {
  3276. let from = y * p.pitch as usize;
  3277. let to = from + p.width as usize * texel;
  3278. a.get(from..to) == b.get(from..to)
  3279. })
  3280. }
  3281. fn to_rect(r: [i32; 4]) -> RECT {
  3282. RECT {
  3283. left: r[0],
  3284. top: r[1],
  3285. right: r[2],
  3286. bottom: r[3],
  3287. }
  3288. }
  3289. /// # Safety
  3290. /// An open list; barriers of live resources.
  3291. unsafe fn barriers(list: &ID3D12GraphicsCommandList, all: &[D3D12_RESOURCE_BARRIER]) {
  3292. for some in all.chunks(1000) {
  3293. // SAFETY: the caller's.
  3294. unsafe { list.ResourceBarrier(some) };
  3295. }
  3296. }
  3297. fn uav_barrier(res: Option<&ID3D12Resource>) -> D3D12_RESOURCE_BARRIER {
  3298. D3D12_RESOURCE_BARRIER {
  3299. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  3300. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3301. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3302. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  3303. // SAFETY: a borrowed pointer (or none) never released.
  3304. pResource: res.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe {
  3305. std::mem::transmute_copy(r)
  3306. }),
  3307. }),
  3308. },
  3309. }
  3310. }
  3311. /// Any placed resource to any other: waits for all writes.
  3312. fn alias() -> D3D12_RESOURCE_BARRIER {
  3313. D3D12_RESOURCE_BARRIER {
  3314. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  3315. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  3316. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  3317. Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  3318. pResourceBefore: std::mem::ManuallyDrop::new(None),
  3319. pResourceAfter: std::mem::ManuallyDrop::new(None),
  3320. }),
  3321. },
  3322. }
  3323. }
  3324. fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> {
  3325. while !to.is_empty() {
  3326. let n = file.seek_read(to, at)?;
  3327. if n == 0 {
  3328. return Err(std::io::ErrorKind::UnexpectedEof.into());
  3329. }
  3330. to = &mut to[n..];
  3331. at += n as u64;
  3332. }
  3333. Ok(())
  3334. }
  3335. fn make_device(frame: &Frame, debug: bool, breadcrumbs: bool) -> Result<(ID3D12Device, Option<ID3D12InfoQueue>)> {
  3336. // SAFETY: plain creation and queries.
  3337. unsafe {
  3338. if debug {
  3339. let mut layer: Option<ID3D12Debug> = None;
  3340. match D3D12GetDebugInterface(&mut layer) {
  3341. Ok(()) => layer.iter().for_each(|l| {
  3342. l.EnableDebugLayer();
  3343. // Every shader access checked on the card: very slow.
  3344. if std::env::var_os("VICTORY_REPLAY_GBV").is_some()
  3345. && let Ok(l) = l.cast::<ID3D12Debug1>()
  3346. {
  3347. l.SetEnableGPUBasedValidation(true);
  3348. }
  3349. }),
  3350. Err(e) => tracing::warn!("no debug layer: {e}"),
  3351. }
  3352. }
  3353. if breadcrumbs {
  3354. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  3355. D3D12GetDebugInterface(&mut dred)?;
  3356. if let Some(dred) = dred {
  3357. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  3358. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  3359. }
  3360. }
  3361. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  3362. let mut adapter = None;
  3363. for i in 0.. {
  3364. let Ok(a) = factory.EnumAdapters1(i) else {
  3365. break;
  3366. };
  3367. let d = a.GetDesc1()?;
  3368. if (d.VendorId, d.DeviceId) == (frame.vendor, frame.device) {
  3369. adapter = Some(a);
  3370. break;
  3371. }
  3372. }
  3373. if adapter.is_none() {
  3374. tracing::warn!(
  3375. "the adapter recorded on ({}) is not here: the default one is used",
  3376. frame.adapter
  3377. );
  3378. }
  3379. let mut device: Option<ID3D12Device> = None;
  3380. match &adapter {
  3381. Some(a) => D3D12CreateDevice(a, D3D_FEATURE_LEVEL_12_0, &mut device)?,
  3382. None => D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?,
  3383. }
  3384. let device = device.context("no device")?;
  3385. let info = device.cast::<ID3D12InfoQueue>().ok();
  3386. Ok((device, info))
  3387. }
  3388. }
  3389. /// The debug layer's errors: how many of each kind, and its first text.
  3390. fn debug_messages(q: &ID3D12InfoQueue) -> Vec<String> {
  3391. let mut seen: BTreeMap<i32, (u32, String)> = BTreeMap::new();
  3392. // SAFETY: messages read into buffers of the size asked for.
  3393. unsafe {
  3394. for i in 0..q.GetNumStoredMessages() {
  3395. let mut size = 0;
  3396. if q.GetMessage(i, None, &mut size).is_err() {
  3397. continue;
  3398. }
  3399. let mut buffer = vec![0u64; size.div_ceil(8)];
  3400. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  3401. if q.GetMessage(i, Some(message), &mut size).is_err() {
  3402. continue;
  3403. }
  3404. let m = &*message;
  3405. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 {
  3406. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  3407. let text = || {
  3408. String::from_utf8_lossy(text)
  3409. .trim_end_matches('\0')
  3410. .to_owned()
  3411. };
  3412. seen.entry(m.ID.0).or_insert_with(|| (0, text())).0 += 1;
  3413. }
  3414. }
  3415. q.ClearStoredMessages();
  3416. }
  3417. seen.into_iter()
  3418. .map(|(id, (n, text))| format!("debug layer: {n} errors {id}, first: {text}"))
  3419. .collect()
  3420. }
  3421. #[cfg(test)]
  3422. mod tests {
  3423. use super::*;
  3424. #[test]
  3425. fn captures_are_found() {
  3426. let dir = tempfile::tempdir().unwrap();
  3427. assert!(find(dir.path()).is_err());
  3428. for n in [1, 2, 10, 11] {
  3429. std::fs::create_dir(dir.path().join(format!("capture-{n}"))).unwrap();
  3430. }
  3431. for n in [1, 2, 10] {
  3432. std::fs::write(dir.path().join(format!("capture-{n}/frame.bin")), "").unwrap();
  3433. }
  3434. // The last complete one; itself when named.
  3435. assert_eq!(find(dir.path()).unwrap(), dir.path().join("capture-10"));
  3436. assert_eq!(
  3437. find(&dir.path().join("capture-2")).unwrap(),
  3438. dir.path().join("capture-2")
  3439. );
  3440. }
  3441. #[test]
  3442. fn reports() {
  3443. assert_eq!(median(&[]), 0.0);
  3444. assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0);
  3445. let r = Report {
  3446. frame_ms: vec![10.0, 12.0, 11.0],
  3447. busy_ms: vec![9.0; 3],
  3448. delta_ms: vec![0.5; 3],
  3449. submits: vec![(2, 9.0)],
  3450. picture: Some((40.0, false)),
  3451. ..Default::default()
  3452. };
  3453. let t = r.text("a frame");
  3454. assert!(t.contains("a frame: 11.00 ms"), "{t}");
  3455. assert!(t.contains("between submissions 1.50 ms"), "{t}");
  3456. assert!(t.contains("PSNR 40.0 dB"), "{t}");
  3457. let o = Options {
  3458. skip_clamps: true,
  3459. buffers: Buffers::Card,
  3460. ..Default::default()
  3461. };
  3462. assert!(o.edited() && !o.plain().edited() && o.plain().buffers == Buffers::Card);
  3463. }
  3464. }