play.rs 132 KB

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