record.rs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774
  1. //! The recorder: what the host layer makes and records with D3D12, seen at
  2. //! the D3D12 boundary (`super::hook`), and one frame of it written down
  3. //! (`super::snap`). On with `VICTORY_RECORD=<folder>` only; without it
  4. //! nothing is hooked.
  5. //!
  6. //! From the device's creation on it keeps what objects were made from and
  7. //! what each descriptor slot holds, and follows the states of textures.
  8. //! Lists are recorded only while it is armed: a few frames ahead of the one
  9. //! captured, since the title records lists before they run.
  10. use std::cell::Cell;
  11. use std::collections::{BTreeMap, HashMap};
  12. use std::ffi::c_void;
  13. use std::mem::ManuallyDrop;
  14. use std::path::PathBuf;
  15. use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
  16. use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock};
  17. use windows::Win32::Foundation::RECT;
  18. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  19. use windows::Win32::Graphics::Direct3D12::*;
  20. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  21. use windows::core::{BOOL, GUID, HRESULT, IUnknown, Interface, PCWSTR};
  22. use super::hook::{self, method, noted_entry, orig};
  23. use super::states::{self, Change, States};
  24. use super::wire::{self, ALL, Barrier, Cmd, Loc, NONE, Part, Place, Slot, Va, Wire, slot};
  25. use super::{gpu, pso, snap};
  26. type Ptr = *mut c_void;
  27. type Out = *mut *mut c_void;
  28. /// What to record.
  29. #[derive(Clone, Debug)]
  30. pub struct Settings {
  31. /// Captures go to `capture-<n>` in it.
  32. pub folder: PathBuf,
  33. pub at: At,
  34. /// Frames to capture.
  35. pub frames: u32,
  36. /// Record lists from the start on, not only once a capture is near: for
  37. /// a title that submits lists it recorded long before.
  38. pub always: bool,
  39. }
  40. #[derive(Clone, Copy, Debug, PartialEq)]
  41. pub enum At {
  42. /// Seconds after the device was made.
  43. Seconds(f64),
  44. /// A number of presents.
  45. Frame(u64),
  46. /// When a file named `go` appears in the folder (this works in the
  47. /// other cases too).
  48. Trigger,
  49. }
  50. impl Settings {
  51. /// From `VICTORY_RECORD`, `VICTORY_RECORD_AT` (seconds, or `f<frame>`),
  52. /// `VICTORY_RECORD_FRAMES` and `VICTORY_RECORD_ALWAYS=1`.
  53. pub fn from_env() -> Option<Settings> {
  54. let folder = PathBuf::from(std::env::var_os("VICTORY_RECORD").filter(|v| !v.is_empty())?);
  55. let at = parse_at(&std::env::var("VICTORY_RECORD_AT").unwrap_or_default());
  56. let frames = std::env::var("VICTORY_RECORD_FRAMES")
  57. .ok()
  58. .and_then(|v| v.trim().parse().ok())
  59. .unwrap_or(1);
  60. let always = std::env::var_os("VICTORY_RECORD_ALWAYS").is_some_and(|v| v == "1");
  61. Some(Settings {
  62. folder,
  63. at,
  64. frames: std::cmp::max(frames, 1),
  65. always,
  66. })
  67. }
  68. }
  69. fn parse_at(text: &str) -> At {
  70. let text = text.trim();
  71. if let Some(frame) = text.strip_prefix('f').and_then(|n| n.parse().ok()) {
  72. return At::Frame(frame);
  73. }
  74. match text.parse::<f64>() {
  75. Ok(s) => At::Seconds(s),
  76. Err(_) => At::Trigger,
  77. }
  78. }
  79. pub(super) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
  80. m.lock().unwrap_or_else(|e| e.into_inner())
  81. }
  82. pub(super) fn read<T>(m: &RwLock<T>) -> std::sync::RwLockReadGuard<'_, T> {
  83. m.read().unwrap_or_else(|e| e.into_inner())
  84. }
  85. fn write<T>(m: &RwLock<T>) -> std::sync::RwLockWriteGuard<'_, T> {
  86. m.write().unwrap_or_else(|e| e.into_inner())
  87. }
  88. /// A resource that lives.
  89. pub(super) struct Res {
  90. pub(super) id: u32,
  91. pub(super) ptr: usize,
  92. pub(super) place: Place,
  93. pub(super) desc: wire::Desc,
  94. pub(super) made_in: i32,
  95. pub(super) clear: Option<[u32; 5]>,
  96. pub(super) subs: u32,
  97. pub(super) seen: gpu::Seen,
  98. /// Made while a frame was being captured.
  99. pub(super) late: bool,
  100. }
  101. impl Res {
  102. pub(super) fn is_buffer(&self) -> bool {
  103. self.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0
  104. }
  105. /// The object, without a reference of its own.
  106. pub(super) fn object(&self) -> ManuallyDrop<ID3D12Resource> {
  107. borrow(self.ptr as Ptr)
  108. }
  109. }
  110. /// A COM object named by its address, without a reference.
  111. pub(super) fn borrow<T: Interface>(p: Ptr) -> ManuallyDrop<T> {
  112. // SAFETY: the caller's live object; never released here.
  113. ManuallyDrop::new(unsafe { T::from_raw(p) })
  114. }
  115. /// A descriptor heap: where it lies and what its slots hold.
  116. pub(super) struct Heap {
  117. pub(super) id: u32,
  118. pub(super) kind: i32,
  119. pub(super) count: u32,
  120. pub(super) flags: i32,
  121. cpu: usize,
  122. gpu: u64,
  123. step: usize,
  124. slots: *mut Slot,
  125. }
  126. // SAFETY: slots are written by the thread that writes the descriptor (the
  127. // same rule as the descriptors': one writer at a time) and read as plain
  128. // data.
  129. unsafe impl Send for Heap {}
  130. // SAFETY: as above.
  131. unsafe impl Sync for Heap {}
  132. impl Heap {
  133. fn new(id: u32, desc: &D3D12_DESCRIPTOR_HEAP_DESC, cpu: usize, gpu: u64, step: usize) -> Heap {
  134. let layout = Self::layout(desc.NumDescriptors);
  135. // SAFETY: a layout of at least one slot; a zeroed slot is an empty
  136. // one.
  137. let slots = unsafe { std::alloc::alloc_zeroed(layout) }.cast::<Slot>();
  138. if slots.is_null() {
  139. std::alloc::handle_alloc_error(layout);
  140. }
  141. Heap {
  142. id,
  143. kind: desc.Type.0,
  144. count: desc.NumDescriptors,
  145. flags: desc.Flags.0,
  146. cpu,
  147. gpu,
  148. step,
  149. slots,
  150. }
  151. }
  152. fn layout(count: u32) -> std::alloc::Layout {
  153. std::alloc::Layout::array::<Slot>(count.max(1) as usize)
  154. .unwrap_or(std::alloc::Layout::new::<Slot>())
  155. }
  156. pub(super) fn visible(&self) -> bool {
  157. self.flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0
  158. }
  159. pub(super) fn get(&self, i: u32) -> Slot {
  160. if i >= self.count {
  161. return Slot::EMPTY;
  162. }
  163. // SAFETY: a slot of ours.
  164. unsafe { self.slots.add(i as usize).read_volatile() }
  165. }
  166. fn set(&self, i: u32, s: &Slot) {
  167. if i < self.count {
  168. // SAFETY: a slot of ours.
  169. unsafe { self.slots.add(i as usize).write_volatile(*s) };
  170. }
  171. }
  172. /// All slots, as they are now.
  173. pub(super) fn all(&self) -> Vec<Slot> {
  174. let mut out = Vec::with_capacity(self.count as usize);
  175. // SAFETY: `count` slots of ours.
  176. unsafe {
  177. std::ptr::copy_nonoverlapping(self.slots, out.as_mut_ptr(), self.count as usize);
  178. out.set_len(self.count as usize);
  179. }
  180. out
  181. }
  182. }
  183. impl Drop for Heap {
  184. fn drop(&mut self) {
  185. // SAFETY: as allocated.
  186. unsafe { std::alloc::dealloc(self.slots.cast(), Self::layout(self.count)) };
  187. }
  188. }
  189. #[derive(Default)]
  190. pub(super) struct Heaps {
  191. by_cpu: BTreeMap<usize, Arc<Heap>>,
  192. by_gpu: BTreeMap<u64, Arc<Heap>>,
  193. }
  194. impl Heaps {
  195. fn add(&mut self, heap: Arc<Heap>) {
  196. let end = heap.cpu + heap.count as usize * heap.step;
  197. let gone: Vec<usize> = self
  198. .by_cpu
  199. .range(..end)
  200. .rev()
  201. .take_while(|(_, h)| h.cpu + h.count as usize * h.step > heap.cpu)
  202. .map(|(&k, _)| k)
  203. .collect();
  204. for k in gone {
  205. self.by_cpu.remove(&k);
  206. }
  207. if heap.visible() {
  208. self.by_gpu.insert(heap.gpu, heap.clone());
  209. }
  210. self.by_cpu.insert(heap.cpu, heap);
  211. }
  212. fn remove(&mut self, id: u32) {
  213. self.by_cpu.retain(|_, h| h.id != id);
  214. self.by_gpu.retain(|_, h| h.id != id);
  215. }
  216. fn cpu(&self, at: usize) -> Option<(&Arc<Heap>, u32)> {
  217. let (_, h) = self.by_cpu.range(..=at).next_back()?;
  218. let i = (at - h.cpu) / h.step;
  219. (i < h.count as usize).then_some((h, i as u32))
  220. }
  221. fn gpu(&self, at: u64) -> Option<(&Arc<Heap>, u32)> {
  222. let (_, h) = self.by_gpu.range(..=at).next_back()?;
  223. let i = (at - h.gpu) / h.step as u64;
  224. (i < u64::from(h.count)).then_some((h, i as u32))
  225. }
  226. pub(super) fn visible(&self) -> impl Iterator<Item = &Arc<Heap>> {
  227. self.by_gpu.values()
  228. }
  229. }
  230. /// A command list's recording.
  231. pub(super) struct ListState {
  232. pub(super) kind: i32,
  233. inner: Mutex<ListInner>,
  234. }
  235. #[derive(Default)]
  236. struct ListInner {
  237. /// Recorded from its reset on.
  238. whole: bool,
  239. bytes: Vec<u8>,
  240. changes: Vec<Change>,
  241. closed: Option<(Option<Arc<Vec<u8>>>, Arc<Vec<Change>>)>,
  242. }
  243. impl ListState {
  244. fn push(&self, cmd: &Cmd) {
  245. let mut inner = lock(&self.inner);
  246. if inner.whole {
  247. cmd.put(&mut inner.bytes);
  248. }
  249. }
  250. /// The recording closed last: its commands if it was recorded whole,
  251. /// and the states it changes. None if it was not seen closed since its
  252. /// reset.
  253. pub(super) fn closed(&self) -> Option<(Option<Arc<Vec<u8>>>, Arc<Vec<Change>>)> {
  254. lock(&self.inner).closed.clone()
  255. }
  256. }
  257. struct QueueState {
  258. kind: i32,
  259. }
  260. /// Shader code, written to `shaders.bin` as it is met, once each.
  261. pub(super) struct Codes {
  262. file: Option<std::fs::File>,
  263. at: u64,
  264. index: HashMap<[u8; 32], u32>,
  265. pub(super) all: Vec<wire::Code>,
  266. }
  267. /// Objects by their address: ids.
  268. #[derive(Default)]
  269. struct Ids([RwLock<HashMap<usize, u32>>; 32]);
  270. impl Ids {
  271. fn shard(&self, p: usize) -> &RwLock<HashMap<usize, u32>> {
  272. &self.0[(p >> 5 ^ p >> 12) % 32]
  273. }
  274. fn get(&self, p: usize) -> Option<u32> {
  275. read(self.shard(p)).get(&p).copied()
  276. }
  277. fn set(&self, p: usize, id: u32) {
  278. write(self.shard(p)).insert(p, id);
  279. }
  280. fn remove(&self, p: usize, id: u32) {
  281. let mut map = write(self.shard(p));
  282. if map.get(&p) == Some(&id) {
  283. map.remove(&p);
  284. }
  285. }
  286. }
  287. pub(super) struct Recorder {
  288. pub(super) settings: Settings,
  289. /// Where this process' capture goes.
  290. pub(super) folder: PathBuf,
  291. pub(super) began: std::time::Instant,
  292. next: AtomicU32,
  293. ids: Ids,
  294. pub(super) resources: RwLock<HashMap<u32, Arc<Res>>>,
  295. /// Buffers by their GPU address: size and id.
  296. addresses: RwLock<BTreeMap<u64, (u64, u32)>>,
  297. pub(super) descriptors: RwLock<Heaps>,
  298. lists: RwLock<HashMap<usize, Arc<ListState>>>,
  299. pub(super) heaps: Mutex<HashMap<u32, wire::Heap>>,
  300. pub(super) roots: Mutex<HashMap<u32, Arc<Vec<u8>>>>,
  301. pub(super) pipelines: Mutex<HashMap<u32, Arc<Vec<Part>>>>,
  302. pub(super) signatures: Mutex<HashMap<u32, wire::Signature>>,
  303. pub(super) queries: Mutex<HashMap<u32, wire::QueryHeap>>,
  304. pub(super) names: Mutex<HashMap<u32, String>>,
  305. pub(super) codes: Mutex<Codes>,
  306. pub(super) states: Mutex<States>,
  307. pub(super) queues: Mutex<Vec<(ID3D12CommandQueue, i32)>>,
  308. device: Mutex<Option<ID3D12Device>>,
  309. /// Lists are recorded.
  310. armed: AtomicBool,
  311. /// A frame is being captured: descriptor writes are noted, resources
  312. /// made are kept alive.
  313. pub(super) watching: AtomicBool,
  314. pub(super) writes: Mutex<Vec<(u32, u32, u32)>>,
  315. /// Resources kept alive for a capture, by id. One that dies all the same
  316. /// (its last reference was going when ours was taken) is taken out: see
  317. /// `Recorder::gone`.
  318. pub(super) held: Mutex<HashMap<u32, ID3D12Resource>>,
  319. /// What could not be recorded, with how often.
  320. problems: Mutex<BTreeMap<String, u64>>,
  321. /// Submissions and presents, one at a time.
  322. pub(super) submits: Mutex<snap::Phase>,
  323. }
  324. static RECORDER: OnceLock<Recorder> = OnceLock::new();
  325. /// The recorder, if it is on.
  326. pub(super) fn recorder() -> Option<&'static Recorder> {
  327. RECORDER.get()
  328. }
  329. /// Whether the recorder is on.
  330. pub fn on() -> bool {
  331. RECORDER.get().is_some()
  332. }
  333. thread_local! {
  334. static OURS: Cell<u32> = const { Cell::new(0) };
  335. }
  336. /// While it lives, this thread's D3D12 calls are our own: not recorded.
  337. pub(super) struct Ours;
  338. impl Ours {
  339. pub(super) fn new() -> Ours {
  340. OURS.with(|o| o.set(o.get() + 1));
  341. Ours
  342. }
  343. }
  344. impl Drop for Ours {
  345. fn drop(&mut self) {
  346. OURS.with(|o| o.set(o.get() - 1));
  347. }
  348. }
  349. fn ours() -> bool {
  350. OURS.with(|o| o.get() > 0)
  351. }
  352. impl Recorder {
  353. fn new(settings: Settings) -> std::io::Result<Recorder> {
  354. std::fs::create_dir_all(&settings.folder)?;
  355. let mut n = 1;
  356. let folder = loop {
  357. let folder = settings.folder.join(format!("capture-{n}"));
  358. match std::fs::create_dir(&folder) {
  359. Ok(()) => break folder,
  360. Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
  361. Err(e) => return Err(e),
  362. }
  363. };
  364. let file = std::fs::File::create(folder.join("shaders.bin"))?;
  365. Ok(Recorder {
  366. settings,
  367. folder,
  368. began: std::time::Instant::now(),
  369. next: AtomicU32::new(1),
  370. ids: Ids::default(),
  371. resources: RwLock::default(),
  372. addresses: RwLock::default(),
  373. descriptors: RwLock::default(),
  374. lists: RwLock::default(),
  375. heaps: Mutex::default(),
  376. roots: Mutex::default(),
  377. pipelines: Mutex::default(),
  378. signatures: Mutex::default(),
  379. queries: Mutex::default(),
  380. names: Mutex::default(),
  381. codes: Mutex::new(Codes {
  382. file: Some(file),
  383. at: 0,
  384. index: HashMap::new(),
  385. all: Vec::new(),
  386. }),
  387. states: Mutex::default(),
  388. queues: Mutex::default(),
  389. device: Mutex::default(),
  390. armed: AtomicBool::new(false),
  391. watching: AtomicBool::new(false),
  392. writes: Mutex::default(),
  393. held: Mutex::default(),
  394. problems: Mutex::default(),
  395. submits: Mutex::new(snap::Phase::default()),
  396. })
  397. }
  398. fn id(&self) -> u32 {
  399. self.next.fetch_add(1, Ordering::Relaxed)
  400. }
  401. /// Notes something that is not in the capture.
  402. pub(super) fn problem(&self, what: &str) {
  403. self.problem_times(what, 1);
  404. }
  405. pub(super) fn problem_times(&self, what: &str, n: u64) {
  406. let mut problems = lock(&self.problems);
  407. let seen = problems.entry(what.to_owned()).or_insert(0);
  408. if *seen == 0 {
  409. tracing::warn!("frame recorder: {what}");
  410. }
  411. *seen += n;
  412. }
  413. /// The problems so far.
  414. pub(super) fn problems(&self) -> Vec<String> {
  415. lock(&self.problems)
  416. .iter()
  417. .map(|(what, n)| {
  418. if *n == 1 {
  419. what.clone()
  420. } else {
  421. format!("{what} ({n} times)")
  422. }
  423. })
  424. .collect()
  425. }
  426. pub(super) fn arm(&self, on: bool) {
  427. self.armed.store(on, Ordering::SeqCst);
  428. }
  429. pub(super) fn device(&self) -> Option<ID3D12Device> {
  430. lock(&self.device).clone()
  431. }
  432. /// Whether a list was made through the hooked device (the swap chain may
  433. /// have others).
  434. pub(super) fn knows(&self, p: Ptr) -> bool {
  435. read(&self.lists).contains_key(&(p as usize))
  436. }
  437. /// The state of a list, if its methods are still ours.
  438. pub(super) fn list(&self, p: Ptr) -> Option<Arc<ListState>> {
  439. let state = read(&self.lists).get(&(p as usize)).cloned()?;
  440. // SAFETY: a live list: it is being submitted.
  441. if !unsafe { hook::ours(p) } {
  442. self.problem("a list lost its hooks");
  443. return None;
  444. }
  445. Some(state)
  446. }
  447. /// The buffer an address lies in.
  448. pub(super) fn va(&self, address: u64) -> Va {
  449. if address == 0 {
  450. return Va::Null {};
  451. }
  452. match read(&self.addresses).range(..=address).next_back() {
  453. Some((&start, &(size, res))) if address - start < size => Va::At {
  454. res,
  455. offset: address - start,
  456. },
  457. _ => Va::Unknown { address },
  458. }
  459. }
  460. /// The id of an object, [`NONE`] for null; an unknown one is a problem.
  461. fn object(&self, p: Ptr, what: &str) -> u32 {
  462. if p.is_null() {
  463. return NONE;
  464. }
  465. self.ids.get(p as usize).unwrap_or_else(|| {
  466. self.problem(&format!("{what} was used that was not seen made"));
  467. NONE
  468. })
  469. }
  470. /// The id of a resource; one not seen made (a swap chain's buffer) is
  471. /// taken in now.
  472. pub(super) fn resource(&self, p: Ptr) -> u32 {
  473. if p.is_null() {
  474. return NONE;
  475. }
  476. if let Some(id) = self.ids.get(p as usize) {
  477. return id;
  478. }
  479. self.add(p, Place::BackBuffer {}, 0, None)
  480. }
  481. /// Takes a new resource in.
  482. fn add(&self, p: Ptr, place: Place, made_in: i32, clear: Option<[u32; 5]>) -> u32 {
  483. let object = borrow::<ID3D12Resource>(p);
  484. // SAFETY: a live resource.
  485. let d = unsafe { object.GetDesc() };
  486. let desc = gpu::from_desc(&d);
  487. let id = self.id();
  488. let seen = match &place {
  489. Place::Committed { props, .. } => gpu::seen(props),
  490. Place::Placed { heap, .. } => lock(&self.heaps)
  491. .get(heap)
  492. .map_or(gpu::Seen::No, |h| gpu::seen(&h.props)),
  493. Place::BackBuffer {} => gpu::Seen::No,
  494. };
  495. let subs = gpu::subresources(&desc);
  496. let is_buffer = desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0;
  497. // SAFETY: a live buffer.
  498. let va = if is_buffer {
  499. unsafe { object.GetGPUVirtualAddress() }
  500. } else {
  501. 0
  502. };
  503. let placed = matches!(place, Place::Placed { .. });
  504. let late = self.watching.load(Ordering::SeqCst);
  505. {
  506. let mut states = lock(&self.states);
  507. if !is_buffer {
  508. let decays = d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS.0 != 0;
  509. states.add(id, subs, made_in as u32, decays);
  510. }
  511. if placed {
  512. states.in_use(id);
  513. }
  514. }
  515. if va != 0 {
  516. write(&self.addresses).insert(va, (desc.width, id));
  517. }
  518. let res = Arc::new(Res {
  519. id,
  520. ptr: p as usize,
  521. place,
  522. desc,
  523. made_in,
  524. clear,
  525. subs,
  526. seen,
  527. late,
  528. });
  529. write(&self.resources).insert(id, res);
  530. self.ids.set(p as usize, id);
  531. if late {
  532. lock(&self.held).insert(id, ID3D12Resource::clone(&object));
  533. }
  534. self.tell_gone(
  535. &*object,
  536. Gone::Resource {
  537. id,
  538. ptr: p as usize,
  539. va,
  540. },
  541. );
  542. id
  543. }
  544. fn gone(&self, what: &Gone) {
  545. match *what {
  546. Gone::Resource { id, ptr, va } => {
  547. // The memory goes whatever we hold: letting go of it later
  548. // would be a call into what is there then.
  549. if let Some(dead) = lock(&self.held).remove(&id) {
  550. std::mem::forget(dead);
  551. self.problem("a resource died as the frame started: its contents may be missing");
  552. }
  553. self.ids.remove(ptr, id);
  554. write(&self.resources).remove(&id);
  555. if va != 0 {
  556. let mut all = write(&self.addresses);
  557. if all.get(&va).is_some_and(|&(_, i)| i == id) {
  558. all.remove(&va);
  559. }
  560. }
  561. lock(&self.states).remove(id);
  562. lock(&self.names).remove(&id);
  563. }
  564. Gone::List { ptr } => {
  565. write(&self.lists).remove(&ptr);
  566. }
  567. Gone::Heap { id, ptr } => {
  568. self.ids.remove(ptr, id);
  569. write(&self.descriptors).remove(id);
  570. }
  571. }
  572. }
  573. /// Has us told when an object dies.
  574. fn tell_gone(&self, object: &impl Interface, what: Gone) {
  575. const KEY: GUID = GUID::from_u128(0x3d0d5c1e_7a1b_4a53_9a3e_5f2b1e6b9c41);
  576. let notice = Box::into_raw(Box::new(Notice {
  577. methods: &NOTICE,
  578. references: AtomicU32::new(1),
  579. what,
  580. }));
  581. // SAFETY: a COM object of ours with one reference, which this drops
  582. // at the end; the object takes its own.
  583. unsafe {
  584. let notice = IUnknown::from_raw(notice.cast());
  585. let set = object
  586. .cast::<ID3D12Object>()
  587. .and_then(|o| o.SetPrivateDataInterface(&KEY, &notice));
  588. if set.is_err() {
  589. self.problem("an object's end cannot be followed");
  590. std::mem::forget(notice);
  591. }
  592. }
  593. }
  594. fn view(&self, at: usize) -> Slot {
  595. match read(&self.descriptors).cpu(at) {
  596. Some((h, i)) => h.get(i),
  597. None => {
  598. self.problem("a descriptor handle in no heap seen made");
  599. Slot::EMPTY
  600. }
  601. }
  602. }
  603. fn set_view(&self, at: usize, s: &Slot) {
  604. let all = read(&self.descriptors);
  605. let Some((h, i)) = all.cpu(at) else {
  606. drop(all);
  607. self.problem("a view was made in no descriptor heap seen made");
  608. return;
  609. };
  610. h.set(i, s);
  611. self.wrote(h, i, 1);
  612. }
  613. /// After slots were written: noted if a frame is being captured.
  614. fn wrote(&self, h: &Heap, first: u32, n: u32) {
  615. if h.visible() && self.watching.load(Ordering::SeqCst) {
  616. lock(&self.writes).push((h.id, first, n));
  617. }
  618. }
  619. fn copy_views(&self, to: usize, from: usize, n: u32) {
  620. let all = read(&self.descriptors);
  621. let (Some((a, i)), Some((b, j))) = (all.cpu(to), all.cpu(from)) else {
  622. drop(all);
  623. self.problem("descriptors were copied in no heap seen made");
  624. return;
  625. };
  626. for k in 0..n {
  627. a.set(i + k, &b.get(j + k));
  628. }
  629. self.wrote(a, i, n);
  630. }
  631. fn code(&self, bytes: &[u8]) -> u32 {
  632. use std::io::Write;
  633. let hash = *blake3::hash(bytes).as_bytes();
  634. let mut codes = lock(&self.codes);
  635. if let Some(&i) = codes.index.get(&hash) {
  636. return i;
  637. }
  638. let i = codes.all.len() as u32;
  639. let at = codes.at;
  640. let wrote = codes
  641. .file
  642. .as_mut()
  643. .is_some_and(|f| f.write_all(bytes).is_ok());
  644. if !wrote {
  645. drop(codes);
  646. self.problem("shader code could not be written");
  647. return u32::MAX;
  648. }
  649. codes.at += bytes.len() as u64;
  650. codes.all.push(wire::Code {
  651. at,
  652. len: bytes.len() as u64,
  653. hash,
  654. });
  655. codes.index.insert(hash, i);
  656. i
  657. }
  658. fn pipeline(&self, p: Ptr, parts: Vec<Part>) {
  659. let id = self.id();
  660. lock(&self.pipelines).insert(id, Arc::new(parts));
  661. self.ids.set(p as usize, id);
  662. }
  663. /// `name` is an object's, for reports.
  664. fn name(&self, p: Ptr, name: &str) {
  665. if let Some(id) = self.ids.get(p as usize) {
  666. lock(&self.names).insert(id, name.to_owned());
  667. }
  668. }
  669. }
  670. struct Keeper<'a>(&'a Recorder);
  671. impl pso::Keep for Keeper<'_> {
  672. fn root(&mut self, root: Ptr) -> u32 {
  673. self.0.object(root, "a root signature")
  674. }
  675. fn code(&mut self, code: &[u8]) -> u32 {
  676. self.0.code(code)
  677. }
  678. fn lost(&mut self, what: &str) {
  679. self.0.problem(what);
  680. }
  681. }
  682. /// Which object died.
  683. enum Gone {
  684. Resource { id: u32, ptr: usize, va: u64 },
  685. List { ptr: usize },
  686. Heap { id: u32, ptr: usize },
  687. }
  688. /// A COM object an object of D3D12's holds and lets go of when it dies.
  689. #[repr(C)]
  690. struct Notice {
  691. methods: *const NoticeTable,
  692. references: AtomicU32,
  693. what: Gone,
  694. }
  695. #[repr(C)]
  696. struct NoticeTable {
  697. query: unsafe extern "system" fn(Ptr, *const GUID, Out) -> HRESULT,
  698. add: unsafe extern "system" fn(Ptr) -> u32,
  699. release: unsafe extern "system" fn(Ptr) -> u32,
  700. }
  701. static NOTICE: NoticeTable = NoticeTable {
  702. query: notice_query,
  703. add: notice_add,
  704. release: notice_release,
  705. };
  706. unsafe extern "system" fn notice_query(this: Ptr, iid: *const GUID, out: Out) -> HRESULT {
  707. // SAFETY: COM's rules: a valid id and place for the answer.
  708. unsafe {
  709. if *iid == IUnknown::IID {
  710. notice_add(this);
  711. *out = this;
  712. return HRESULT(0);
  713. }
  714. *out = std::ptr::null_mut();
  715. }
  716. HRESULT(0x8000_4002_u32 as i32)
  717. }
  718. unsafe extern "system" fn notice_add(this: Ptr) -> u32 {
  719. // SAFETY: one of ours, alive while a reference is.
  720. unsafe {
  721. (*this.cast::<Notice>())
  722. .references
  723. .fetch_add(1, Ordering::Relaxed)
  724. + 1
  725. }
  726. }
  727. unsafe extern "system" fn notice_release(this: Ptr) -> u32 {
  728. // SAFETY: as above; the last reference frees the box it was made as.
  729. unsafe {
  730. let left = (*this.cast::<Notice>())
  731. .references
  732. .fetch_sub(1, Ordering::AcqRel)
  733. - 1;
  734. if left == 0 {
  735. let notice = Box::from_raw(this.cast::<Notice>());
  736. if let Some(r) = recorder() {
  737. r.gone(&notice.what);
  738. }
  739. }
  740. left
  741. }
  742. }
  743. /// Starts the recorder if the environment asks for it, and hooks `device`.
  744. /// Called right after the device was made.
  745. pub(crate) fn from_env(device: &ID3D12Device) {
  746. let Some(settings) = Settings::from_env() else {
  747. return;
  748. };
  749. match start(settings, device) {
  750. Ok(folder) => tracing::info!(folder = %folder.display(), "frame recorder on"),
  751. Err(e) => tracing::warn!(error = %e, "frame recorder not started"),
  752. }
  753. }
  754. /// Starts the recorder (once a process) and hooks `device`, which must have
  755. /// made nothing the frame will use. Where the capture will be.
  756. pub fn start(settings: Settings, device: &ID3D12Device) -> std::io::Result<PathBuf> {
  757. let r = Recorder::new(settings)?;
  758. let folder = r.folder.clone();
  759. if RECORDER.set(r).is_err() {
  760. return Err(std::io::Error::other("the recorder is already on"));
  761. }
  762. let r = recorder().ok_or_else(|| std::io::Error::other("no recorder"))?;
  763. *lock(&r.device) = Some(device.clone());
  764. r.arm(r.settings.always);
  765. // The newer interfaces may be other pointers (they are the same one
  766. // without the debug layer).
  767. let mut all = vec![device.as_raw()];
  768. let mut more: Vec<IUnknown> = Vec::new();
  769. for iid in [
  770. ID3D12Device1::IID,
  771. ID3D12Device2::IID,
  772. ID3D12Device3::IID,
  773. ID3D12Device4::IID,
  774. ID3D12Device5::IID,
  775. ID3D12Device8::IID,
  776. ID3D12Device10::IID,
  777. ID3D12Device11::IID,
  778. ID3D12Device13::IID,
  779. ] {
  780. if let Some(p) = query(device.as_raw(), &iid) {
  781. all.push(p.as_raw());
  782. more.push(p);
  783. }
  784. }
  785. for p in all {
  786. // SAFETY: a live device; the entries below are of their methods'
  787. // types (the compiler checks them).
  788. unsafe { hook::install(p, std::ptr::null(), device_table) };
  789. }
  790. Ok(folder)
  791. }
  792. /// Unhooks `device` (tests).
  793. pub fn unhook(device: &ID3D12Device) {
  794. // SAFETY: a live device, used by no other thread (the caller's word).
  795. unsafe { hook::remove(device.as_raw()) };
  796. }
  797. /// The object's interface `iid`.
  798. fn query(p: Ptr, iid: &GUID) -> Option<IUnknown> {
  799. let object = borrow::<IUnknown>(p);
  800. let mut out = std::ptr::null_mut();
  801. // SAFETY: a live COM object.
  802. unsafe {
  803. object.query(iid, &mut out).ok().ok()?;
  804. (!out.is_null()).then(|| IUnknown::from_raw(out))
  805. }
  806. }
  807. /// Names an object for reports.
  808. pub fn name(object: &impl Interface, text: &str) {
  809. if let Some(r) = recorder() {
  810. r.name(object.as_raw(), text);
  811. }
  812. }
  813. /// At the end of a frame, before the swap chain's present: `texture`, in
  814. /// `state`, is shown.
  815. pub fn present(texture: &ID3D12Resource, state: D3D12_RESOURCE_STATES) {
  816. if let Some(r) = recorder() {
  817. snap::present(r, texture, state.0 as u32);
  818. }
  819. }
  820. /// Where the capture is, once it is done.
  821. pub fn finished() -> Option<PathBuf> {
  822. let r = recorder()?;
  823. lock(&r.submits).done().then(|| r.folder.clone())
  824. }
  825. /// Sets a method of a table to a function of its type.
  826. macro_rules! set {
  827. ($t:ident, $vtbl:ident . $name:ident = $f:expr) => {{
  828. // The compiler checks the function's type here.
  829. let _ = |v: &mut $vtbl| v.$name = $f;
  830. $t[method!($vtbl.$name)] = $f as *const () as usize;
  831. }};
  832. }
  833. /// The object's own method.
  834. macro_rules! own {
  835. ($this:ident, $vtbl:ident . $name:ident) => {
  836. orig::<$vtbl>($this).$name
  837. };
  838. }
  839. /// Entries for methods that are not recorded: counted, and named in the
  840. /// capture's notes if they were called.
  841. macro_rules! not_recorded {
  842. ($t:ident, $class:ident, $names:ident: $($vtbl:ident . $name:ident),* $(,)?) => {
  843. const $names: &[(usize, &str)] = &[$((method!($vtbl.$name), stringify!($name))),*];
  844. $($t[method!($vtbl.$name)] = noted_entry::<{ hook::$class * hook::SLOTS + method!($vtbl.$name) }>();)*
  845. };
  846. }
  847. fn device_table(t: &mut [usize; hook::SLOTS]) {
  848. set!(t, ID3D12Device_Vtbl.CreateCommandQueue = create_queue);
  849. set!(
  850. t,
  851. ID3D12Device_Vtbl.CreateGraphicsPipelineState = create_graphics
  852. );
  853. set!(
  854. t,
  855. ID3D12Device_Vtbl.CreateComputePipelineState = create_compute
  856. );
  857. set!(t, ID3D12Device_Vtbl.CreateCommandList = create_list);
  858. set!(
  859. t,
  860. ID3D12Device_Vtbl.CreateDescriptorHeap = create_descriptors
  861. );
  862. set!(t, ID3D12Device_Vtbl.CreateRootSignature = create_root);
  863. set!(t, ID3D12Device_Vtbl.CreateConstantBufferView = create_cbv);
  864. set!(t, ID3D12Device_Vtbl.CreateShaderResourceView = create_srv);
  865. set!(t, ID3D12Device_Vtbl.CreateUnorderedAccessView = create_uav);
  866. set!(t, ID3D12Device_Vtbl.CreateRenderTargetView = create_rtv);
  867. set!(t, ID3D12Device_Vtbl.CreateDepthStencilView = create_dsv);
  868. set!(t, ID3D12Device_Vtbl.CreateSampler = create_sampler);
  869. set!(t, ID3D12Device_Vtbl.CopyDescriptors = copy_descriptors);
  870. set!(
  871. t,
  872. ID3D12Device_Vtbl.CopyDescriptorsSimple = copy_descriptors_simple
  873. );
  874. set!(
  875. t,
  876. ID3D12Device_Vtbl.CreateCommittedResource = create_committed
  877. );
  878. set!(t, ID3D12Device_Vtbl.CreateHeap = create_heap);
  879. set!(t, ID3D12Device_Vtbl.CreatePlacedResource = create_placed);
  880. set!(t, ID3D12Device_Vtbl.CreateQueryHeap = create_queries);
  881. set!(
  882. t,
  883. ID3D12Device_Vtbl.CreateCommandSignature = create_signature
  884. );
  885. set!(t, ID3D12Device1_Vtbl.CreatePipelineLibrary = create_library);
  886. set!(t, ID3D12Device2_Vtbl.CreatePipelineState = create_stream);
  887. let _ = device_rest(t);
  888. }
  889. fn device_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] {
  890. not_recorded!(t, DEVICE, NAMES:
  891. ID3D12Device_Vtbl.CreateReservedResource,
  892. ID3D12Device_Vtbl.OpenSharedHandle,
  893. ID3D12Device4_Vtbl.CreateCommandList1,
  894. ID3D12Device4_Vtbl.CreateCommittedResource1,
  895. ID3D12Device4_Vtbl.CreateHeap1,
  896. ID3D12Device4_Vtbl.CreateReservedResource1,
  897. ID3D12Device5_Vtbl.CreateStateObject,
  898. ID3D12Device8_Vtbl.CreateCommittedResource2,
  899. ID3D12Device8_Vtbl.CreatePlacedResource1,
  900. ID3D12Device8_Vtbl.CreateSamplerFeedbackUnorderedAccessView,
  901. ID3D12Device10_Vtbl.CreateCommittedResource3,
  902. ID3D12Device10_Vtbl.CreatePlacedResource2,
  903. ID3D12Device10_Vtbl.CreateReservedResource2,
  904. ID3D12Device11_Vtbl.CreateSampler2,
  905. );
  906. NAMES
  907. }
  908. fn queue_table(t: &mut [usize; hook::SLOTS]) {
  909. set!(t, ID3D12CommandQueue_Vtbl.ExecuteCommandLists = execute);
  910. let _ = queue_rest(t);
  911. }
  912. fn queue_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] {
  913. not_recorded!(t, QUEUE, NAMES:
  914. ID3D12CommandQueue_Vtbl.UpdateTileMappings,
  915. ID3D12CommandQueue_Vtbl.CopyTileMappings,
  916. ID3D12CommandQueue_Vtbl.Wait,
  917. );
  918. NAMES
  919. }
  920. fn library_table(t: &mut [usize; hook::SLOTS]) {
  921. set!(
  922. t,
  923. ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline = load_graphics
  924. );
  925. set!(
  926. t,
  927. ID3D12PipelineLibrary_Vtbl.LoadComputePipeline = load_compute
  928. );
  929. set!(t, ID3D12PipelineLibrary1_Vtbl.LoadPipeline = load_stream);
  930. }
  931. fn list_table(t: &mut [usize; hook::SLOTS]) {
  932. set!(t, ID3D12GraphicsCommandList_Vtbl.Close = list_close);
  933. set!(t, ID3D12GraphicsCommandList_Vtbl.Reset = list_reset);
  934. set!(t, ID3D12GraphicsCommandList_Vtbl.DrawInstanced = draw);
  935. set!(
  936. t,
  937. ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced = draw_indexed
  938. );
  939. set!(t, ID3D12GraphicsCommandList_Vtbl.Dispatch = dispatch);
  940. set!(
  941. t,
  942. ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion = copy_buffer
  943. );
  944. set!(
  945. t,
  946. ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion = copy_texture
  947. );
  948. set!(
  949. t,
  950. ID3D12GraphicsCommandList_Vtbl.CopyResource = copy_resource
  951. );
  952. set!(
  953. t,
  954. ID3D12GraphicsCommandList_Vtbl.ResolveSubresource = resolve
  955. );
  956. set!(
  957. t,
  958. ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology = topology
  959. );
  960. set!(t, ID3D12GraphicsCommandList_Vtbl.RSSetViewports = viewports);
  961. set!(
  962. t,
  963. ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects = scissors
  964. );
  965. set!(
  966. t,
  967. ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor = blend_factor
  968. );
  969. set!(
  970. t,
  971. ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef = stencil_ref
  972. );
  973. set!(
  974. t,
  975. ID3D12GraphicsCommandList_Vtbl.SetPipelineState = set_pipeline
  976. );
  977. set!(t, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier = barrier);
  978. set!(
  979. t,
  980. ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps = set_heaps
  981. );
  982. set!(
  983. t,
  984. ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature = root_compute
  985. );
  986. set!(
  987. t,
  988. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature = root_graphics
  989. );
  990. set!(
  991. t,
  992. ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable = table_compute
  993. );
  994. set!(
  995. t,
  996. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable = table_graphics
  997. );
  998. set!(
  999. t,
  1000. ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant = constant_compute
  1001. );
  1002. set!(
  1003. t,
  1004. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant = constant_graphics
  1005. );
  1006. set!(
  1007. t,
  1008. ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants = constants_compute
  1009. );
  1010. set!(
  1011. t,
  1012. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants = constants_graphics
  1013. );
  1014. set!(
  1015. t,
  1016. ID3D12GraphicsCommandList_Vtbl.SetComputeRootConstantBufferView = cbv_compute
  1017. );
  1018. set!(
  1019. t,
  1020. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootConstantBufferView = cbv_graphics
  1021. );
  1022. set!(
  1023. t,
  1024. ID3D12GraphicsCommandList_Vtbl.SetComputeRootShaderResourceView = srv_compute
  1025. );
  1026. set!(
  1027. t,
  1028. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootShaderResourceView = srv_graphics
  1029. );
  1030. set!(
  1031. t,
  1032. ID3D12GraphicsCommandList_Vtbl.SetComputeRootUnorderedAccessView = uav_compute
  1033. );
  1034. set!(
  1035. t,
  1036. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootUnorderedAccessView = uav_graphics
  1037. );
  1038. set!(
  1039. t,
  1040. ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer = index_buffer
  1041. );
  1042. set!(
  1043. t,
  1044. ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers = vertex_buffers
  1045. );
  1046. set!(
  1047. t,
  1048. ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets = targets
  1049. );
  1050. set!(
  1051. t,
  1052. ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView = clear_depth
  1053. );
  1054. set!(
  1055. t,
  1056. ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView = clear_target
  1057. );
  1058. set!(t, ID3D12GraphicsCommandList_Vtbl.DiscardResource = discard);
  1059. set!(t, ID3D12GraphicsCommandList_Vtbl.BeginQuery = begin_query);
  1060. set!(t, ID3D12GraphicsCommandList_Vtbl.EndQuery = end_query);
  1061. set!(
  1062. t,
  1063. ID3D12GraphicsCommandList_Vtbl.ResolveQueryData = resolve_query
  1064. );
  1065. set!(t, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect = indirect);
  1066. set!(
  1067. t,
  1068. ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion = resolve_region
  1069. );
  1070. set!(
  1071. t,
  1072. ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds = depth_bounds
  1073. );
  1074. set!(
  1075. t,
  1076. ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate = write_immediate
  1077. );
  1078. set!(
  1079. t,
  1080. ID3D12GraphicsCommandList6_Vtbl.DispatchMesh = dispatch_mesh
  1081. );
  1082. let _ = list_rest(t);
  1083. }
  1084. fn list_rest(t: &mut [usize; hook::SLOTS]) -> &'static [(usize, &'static str)] {
  1085. not_recorded!(t, LIST, NAMES:
  1086. ID3D12GraphicsCommandList_Vtbl.ClearState,
  1087. ID3D12GraphicsCommandList_Vtbl.CopyTiles,
  1088. ID3D12GraphicsCommandList_Vtbl.ExecuteBundle,
  1089. ID3D12GraphicsCommandList_Vtbl.SOSetTargets,
  1090. ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewUint,
  1091. ID3D12GraphicsCommandList_Vtbl.ClearUnorderedAccessViewFloat,
  1092. ID3D12GraphicsCommandList_Vtbl.SetPredication,
  1093. ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT,
  1094. ID3D12GraphicsCommandList1_Vtbl.AtomicCopyBufferUINT64,
  1095. ID3D12GraphicsCommandList1_Vtbl.SetSamplePositions,
  1096. ID3D12GraphicsCommandList1_Vtbl.SetViewInstanceMask,
  1097. ID3D12GraphicsCommandList3_Vtbl.SetProtectedResourceSession,
  1098. ID3D12GraphicsCommandList4_Vtbl.BeginRenderPass,
  1099. ID3D12GraphicsCommandList4_Vtbl.EndRenderPass,
  1100. ID3D12GraphicsCommandList4_Vtbl.InitializeMetaCommand,
  1101. ID3D12GraphicsCommandList4_Vtbl.ExecuteMetaCommand,
  1102. ID3D12GraphicsCommandList4_Vtbl.BuildRaytracingAccelerationStructure,
  1103. ID3D12GraphicsCommandList4_Vtbl.EmitRaytracingAccelerationStructurePostbuildInfo,
  1104. ID3D12GraphicsCommandList4_Vtbl.CopyRaytracingAccelerationStructure,
  1105. ID3D12GraphicsCommandList4_Vtbl.SetPipelineState1,
  1106. ID3D12GraphicsCommandList4_Vtbl.DispatchRays,
  1107. ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRate,
  1108. ID3D12GraphicsCommandList5_Vtbl.RSSetShadingRateImage,
  1109. ID3D12GraphicsCommandList7_Vtbl.Barrier,
  1110. ID3D12GraphicsCommandList8_Vtbl.OMSetFrontAndBackStencilRef,
  1111. ID3D12GraphicsCommandList9_Vtbl.RSSetDepthBias,
  1112. ID3D12GraphicsCommandList9_Vtbl.IASetIndexBufferStripCutValue,
  1113. ID3D12GraphicsCommandList10_Vtbl.SetProgram,
  1114. ID3D12GraphicsCommandList10_Vtbl.DispatchGraph,
  1115. );
  1116. NAMES
  1117. }
  1118. /// How often each method that is not recorded was called so far.
  1119. pub(super) fn not_recorded_calls() -> Vec<(String, u64)> {
  1120. let mut t = [0; hook::SLOTS];
  1121. let mut all = Vec::new();
  1122. for (class, of, names) in [
  1123. (hook::LIST, "command list", list_rest(&mut t)),
  1124. (hook::DEVICE, "device", device_rest(&mut t)),
  1125. (hook::QUEUE, "queue", queue_rest(&mut t)),
  1126. ] {
  1127. for &(slot, name) in names {
  1128. let what = match (class, name) {
  1129. // Submissions are in order anyway: the replay has one queue.
  1130. (hook::QUEUE, "Wait") => {
  1131. "waits of the drawing queue (the swap chain makes some) are not replayed"
  1132. .to_owned()
  1133. }
  1134. _ => format!("{of} method {name} is not recorded, and was called"),
  1135. };
  1136. all.push((what, hook::count(class, slot)));
  1137. }
  1138. }
  1139. all
  1140. }
  1141. /// The recorder, for a call that is the host layer's and not our own, which
  1142. /// succeeded.
  1143. fn made(hr: HRESULT, out: Out) -> Option<(&'static Recorder, Ptr)> {
  1144. if hr.is_err() || out.is_null() || ours() {
  1145. return None;
  1146. }
  1147. // SAFETY: the call's answer.
  1148. let p = unsafe { *out };
  1149. (!p.is_null()).then_some(())?;
  1150. Some((recorder()?, p))
  1151. }
  1152. unsafe extern "system" fn create_queue(
  1153. this: Ptr,
  1154. desc: *const D3D12_COMMAND_QUEUE_DESC,
  1155. iid: *const GUID,
  1156. out: Out,
  1157. ) -> HRESULT {
  1158. // SAFETY: the caller's arguments, passed on; then a new queue no other
  1159. // thread knows.
  1160. unsafe {
  1161. let hr = own!(this, ID3D12Device_Vtbl.CreateCommandQueue)(this, desc, iid, out);
  1162. if let Some((r, p)) = made(hr, out) {
  1163. let kind = (*desc).Type.0;
  1164. let state = Box::leak(Box::new(QueueState { kind }));
  1165. hook::install(p, (&raw const *state).cast(), queue_table);
  1166. lock(&r.queues).push((ID3D12CommandQueue::clone(&borrow(p)), kind));
  1167. }
  1168. hr
  1169. }
  1170. }
  1171. unsafe extern "system" fn create_list(
  1172. this: Ptr,
  1173. nodes: u32,
  1174. kind: D3D12_COMMAND_LIST_TYPE,
  1175. allocator: Ptr,
  1176. pso: Ptr,
  1177. iid: *const GUID,
  1178. out: Out,
  1179. ) -> HRESULT {
  1180. // SAFETY: as above.
  1181. unsafe {
  1182. let hr = own!(this, ID3D12Device_Vtbl.CreateCommandList)(
  1183. this, nodes, kind, allocator, pso, iid, out,
  1184. );
  1185. if let Some((r, p)) = made(hr, out) {
  1186. let state = Arc::new(ListState {
  1187. kind: kind.0,
  1188. inner: Mutex::default(),
  1189. });
  1190. // Every interface of it we hook, and the one it is submitted as.
  1191. static ONE: OnceLock<bool> = OnceLock::new();
  1192. let iids = [
  1193. ID3D12CommandList::IID,
  1194. ID3D12GraphicsCommandList1::IID,
  1195. ID3D12GraphicsCommandList2::IID,
  1196. ID3D12GraphicsCommandList4::IID,
  1197. ID3D12GraphicsCommandList6::IID,
  1198. ];
  1199. let same = *ONE.get_or_init(|| {
  1200. iids.iter()
  1201. .all(|iid| query(p, iid).is_none_or(|q| q.as_raw() == p))
  1202. });
  1203. let mut all = vec![p];
  1204. if !same {
  1205. all.extend(
  1206. iids.iter()
  1207. .filter_map(|iid| query(p, iid))
  1208. .map(|q| q.as_raw()),
  1209. );
  1210. }
  1211. {
  1212. let mut inner = lock(&state.inner);
  1213. inner.whole =
  1214. r.armed.load(Ordering::SeqCst) && kind == D3D12_COMMAND_LIST_TYPE_DIRECT;
  1215. begin(&mut inner, r, pso);
  1216. }
  1217. for q in all {
  1218. // The state's address is kept for good, as the table is.
  1219. hook::install(q, Arc::into_raw(state.clone()).cast(), list_table);
  1220. write(&r.lists).insert(q as usize, state.clone());
  1221. r.tell_gone(
  1222. &*borrow::<ID3D12CommandList>(q),
  1223. Gone::List { ptr: q as usize },
  1224. );
  1225. }
  1226. }
  1227. hr
  1228. }
  1229. }
  1230. /// A list is open again, with pipeline `pso`.
  1231. fn begin(inner: &mut ListInner, r: &Recorder, pso: Ptr) {
  1232. inner.bytes = Vec::new();
  1233. inner.changes.clear();
  1234. if inner.whole && !pso.is_null() {
  1235. Cmd::Pipeline {
  1236. pso: r.object(pso, "a pipeline"),
  1237. }
  1238. .put(&mut inner.bytes);
  1239. }
  1240. }
  1241. unsafe extern "system" fn create_library(
  1242. this: Ptr,
  1243. blob: *const c_void,
  1244. size: usize,
  1245. iid: *const GUID,
  1246. out: Out,
  1247. ) -> HRESULT {
  1248. // SAFETY: as above.
  1249. unsafe {
  1250. let hr = own!(this, ID3D12Device1_Vtbl.CreatePipelineLibrary)(this, blob, size, iid, out);
  1251. if let Some((_, p)) = made(hr, out) {
  1252. let mut all = vec![p];
  1253. let newer = query(p, &ID3D12PipelineLibrary1::IID);
  1254. all.extend(newer.as_ref().map(|q| q.as_raw()));
  1255. for q in all {
  1256. hook::install(q, std::ptr::null(), library_table);
  1257. }
  1258. }
  1259. hr
  1260. }
  1261. }
  1262. unsafe extern "system" fn create_graphics(
  1263. this: Ptr,
  1264. desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC,
  1265. iid: *const GUID,
  1266. out: Out,
  1267. ) -> HRESULT {
  1268. // SAFETY: as above; the description is valid, as it was accepted.
  1269. unsafe {
  1270. let hr = own!(this, ID3D12Device_Vtbl.CreateGraphicsPipelineState)(this, desc, iid, out);
  1271. if let Some((r, p)) = made(hr, out) {
  1272. r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r)));
  1273. }
  1274. hr
  1275. }
  1276. }
  1277. unsafe extern "system" fn create_compute(
  1278. this: Ptr,
  1279. desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC,
  1280. iid: *const GUID,
  1281. out: Out,
  1282. ) -> HRESULT {
  1283. // SAFETY: as above.
  1284. unsafe {
  1285. let hr = own!(this, ID3D12Device_Vtbl.CreateComputePipelineState)(this, desc, iid, out);
  1286. if let Some((r, p)) = made(hr, out) {
  1287. r.pipeline(p, pso::compute(&*desc, &mut Keeper(r)));
  1288. }
  1289. hr
  1290. }
  1291. }
  1292. unsafe extern "system" fn create_stream(
  1293. this: Ptr,
  1294. desc: *const D3D12_PIPELINE_STATE_STREAM_DESC,
  1295. iid: *const GUID,
  1296. out: Out,
  1297. ) -> HRESULT {
  1298. // SAFETY: as above.
  1299. unsafe {
  1300. let hr = own!(this, ID3D12Device2_Vtbl.CreatePipelineState)(this, desc, iid, out);
  1301. if let Some((r, p)) = made(hr, out) {
  1302. r.pipeline(p, pso::stream(&*desc, &mut Keeper(r)));
  1303. }
  1304. hr
  1305. }
  1306. }
  1307. unsafe extern "system" fn load_graphics(
  1308. this: Ptr,
  1309. name: PCWSTR,
  1310. desc: *const D3D12_GRAPHICS_PIPELINE_STATE_DESC,
  1311. iid: *const GUID,
  1312. out: Out,
  1313. ) -> HRESULT {
  1314. // SAFETY: as above.
  1315. unsafe {
  1316. let hr =
  1317. own!(this, ID3D12PipelineLibrary_Vtbl.LoadGraphicsPipeline)(this, name, desc, iid, out);
  1318. if let Some((r, p)) = made(hr, out) {
  1319. r.pipeline(p, pso::graphics(&*desc, &mut Keeper(r)));
  1320. }
  1321. hr
  1322. }
  1323. }
  1324. unsafe extern "system" fn load_compute(
  1325. this: Ptr,
  1326. name: PCWSTR,
  1327. desc: *const D3D12_COMPUTE_PIPELINE_STATE_DESC,
  1328. iid: *const GUID,
  1329. out: Out,
  1330. ) -> HRESULT {
  1331. // SAFETY: as above.
  1332. unsafe {
  1333. let hr =
  1334. own!(this, ID3D12PipelineLibrary_Vtbl.LoadComputePipeline)(this, name, desc, iid, out);
  1335. if let Some((r, p)) = made(hr, out) {
  1336. r.pipeline(p, pso::compute(&*desc, &mut Keeper(r)));
  1337. }
  1338. hr
  1339. }
  1340. }
  1341. unsafe extern "system" fn load_stream(
  1342. this: Ptr,
  1343. name: PCWSTR,
  1344. desc: *const D3D12_PIPELINE_STATE_STREAM_DESC,
  1345. iid: *const GUID,
  1346. out: Out,
  1347. ) -> HRESULT {
  1348. // SAFETY: as above.
  1349. unsafe {
  1350. let hr = own!(this, ID3D12PipelineLibrary1_Vtbl.LoadPipeline)(this, name, desc, iid, out);
  1351. if let Some((r, p)) = made(hr, out) {
  1352. r.pipeline(p, pso::stream(&*desc, &mut Keeper(r)));
  1353. }
  1354. hr
  1355. }
  1356. }
  1357. unsafe extern "system" fn create_root(
  1358. this: Ptr,
  1359. nodes: u32,
  1360. blob: *const c_void,
  1361. size: usize,
  1362. iid: *const GUID,
  1363. out: Out,
  1364. ) -> HRESULT {
  1365. // SAFETY: as above.
  1366. unsafe {
  1367. let hr =
  1368. own!(this, ID3D12Device_Vtbl.CreateRootSignature)(this, nodes, blob, size, iid, out);
  1369. if let Some((r, p)) = made(hr, out) {
  1370. // D3D12 may answer with an object it made before.
  1371. let known = r
  1372. .ids
  1373. .get(p as usize)
  1374. .filter(|id| lock(&r.roots).contains_key(id));
  1375. let bytes = std::slice::from_raw_parts(blob.cast::<u8>(), size).to_vec();
  1376. let id = known.unwrap_or_else(|| r.id());
  1377. lock(&r.roots).insert(id, Arc::new(bytes));
  1378. r.ids.set(p as usize, id);
  1379. }
  1380. hr
  1381. }
  1382. }
  1383. unsafe extern "system" fn create_signature(
  1384. this: Ptr,
  1385. desc: *const D3D12_COMMAND_SIGNATURE_DESC,
  1386. root: Ptr,
  1387. iid: *const GUID,
  1388. out: Out,
  1389. ) -> HRESULT {
  1390. // SAFETY: as above.
  1391. unsafe {
  1392. let hr = own!(this, ID3D12Device_Vtbl.CreateCommandSignature)(this, desc, root, iid, out);
  1393. if let Some((r, p)) = made(hr, out) {
  1394. let id = r.id();
  1395. let d = &*desc;
  1396. let args: Vec<[u32; 4]> = std::slice::from_raw_parts(
  1397. d.pArgumentDescs.cast::<[u32; 4]>(),
  1398. d.NumArgumentDescs as usize,
  1399. )
  1400. .to_vec();
  1401. // Arguments that are GPU addresses lie in buffers; they are not
  1402. // rewritten for a replay.
  1403. let addresses = [
  1404. D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW,
  1405. D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW,
  1406. D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW,
  1407. D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW,
  1408. D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW,
  1409. ];
  1410. if args
  1411. .iter()
  1412. .any(|a| addresses.iter().any(|t| t.0 as u32 == a[0]))
  1413. {
  1414. r.problem("a command signature with GPU addresses among its arguments: a replay reads the recorded addresses");
  1415. }
  1416. let root = if root.is_null() {
  1417. NONE
  1418. } else {
  1419. r.object(root, "a root signature")
  1420. };
  1421. lock(&r.signatures).insert(
  1422. id,
  1423. wire::Signature {
  1424. id,
  1425. stride: d.ByteStride,
  1426. args,
  1427. root,
  1428. },
  1429. );
  1430. r.ids.set(p as usize, id);
  1431. }
  1432. hr
  1433. }
  1434. }
  1435. unsafe extern "system" fn create_queries(
  1436. this: Ptr,
  1437. desc: *const D3D12_QUERY_HEAP_DESC,
  1438. iid: *const GUID,
  1439. out: Out,
  1440. ) -> HRESULT {
  1441. // SAFETY: as above.
  1442. unsafe {
  1443. let hr = own!(this, ID3D12Device_Vtbl.CreateQueryHeap)(this, desc, iid, out);
  1444. if let Some((r, p)) = made(hr, out) {
  1445. let id = r.id();
  1446. lock(&r.queries).insert(
  1447. id,
  1448. wire::QueryHeap {
  1449. id,
  1450. kind: (*desc).Type.0,
  1451. count: (*desc).Count,
  1452. },
  1453. );
  1454. r.ids.set(p as usize, id);
  1455. }
  1456. hr
  1457. }
  1458. }
  1459. unsafe extern "system" fn create_descriptors(
  1460. this: Ptr,
  1461. desc: *const D3D12_DESCRIPTOR_HEAP_DESC,
  1462. iid: *const GUID,
  1463. out: Out,
  1464. ) -> HRESULT {
  1465. // SAFETY: as above.
  1466. unsafe {
  1467. let hr = own!(this, ID3D12Device_Vtbl.CreateDescriptorHeap)(this, desc, iid, out);
  1468. if let Some((r, p)) = made(hr, out) {
  1469. let heap = borrow::<ID3D12DescriptorHeap>(p);
  1470. let d = &*desc;
  1471. let visible = d.Flags.0 & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 != 0;
  1472. let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr;
  1473. let gpu = if visible {
  1474. heap.GetGPUDescriptorHandleForHeapStart().ptr
  1475. } else {
  1476. 0
  1477. };
  1478. let step = own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, d.Type)
  1479. as usize;
  1480. let id = r.id();
  1481. write(&r.descriptors).add(Arc::new(Heap::new(id, d, cpu, gpu, step.max(1))));
  1482. r.ids.set(p as usize, id);
  1483. r.tell_gone(
  1484. &*heap,
  1485. Gone::Heap {
  1486. id,
  1487. ptr: p as usize,
  1488. },
  1489. );
  1490. }
  1491. hr
  1492. }
  1493. }
  1494. unsafe extern "system" fn create_heap(
  1495. this: Ptr,
  1496. desc: *const D3D12_HEAP_DESC,
  1497. iid: *const GUID,
  1498. out: Out,
  1499. ) -> HRESULT {
  1500. // SAFETY: as above.
  1501. unsafe {
  1502. let hr = own!(this, ID3D12Device_Vtbl.CreateHeap)(this, desc, iid, out);
  1503. if let Some((r, p)) = made(hr, out) {
  1504. let id = r.id();
  1505. lock(&r.heaps).insert(id, heap_of(id, &*desc));
  1506. r.ids.set(p as usize, id);
  1507. }
  1508. hr
  1509. }
  1510. }
  1511. fn heap_of(id: u32, d: &D3D12_HEAP_DESC) -> wire::Heap {
  1512. wire::Heap {
  1513. id,
  1514. size: d.SizeInBytes,
  1515. props: gpu::from_props(&d.Properties),
  1516. alignment: d.Alignment,
  1517. flags: d.Flags.0,
  1518. }
  1519. }
  1520. unsafe fn clear_of(clear: *const D3D12_CLEAR_VALUE) -> Option<[u32; 5]> {
  1521. const _: () = assert!(size_of::<D3D12_CLEAR_VALUE>() == 20);
  1522. // SAFETY: null or a clear value, of 20 bytes.
  1523. (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read() })
  1524. }
  1525. #[allow(clippy::too_many_arguments)]
  1526. unsafe extern "system" fn create_committed(
  1527. this: Ptr,
  1528. props: *const D3D12_HEAP_PROPERTIES,
  1529. flags: D3D12_HEAP_FLAGS,
  1530. desc: *const D3D12_RESOURCE_DESC,
  1531. state: D3D12_RESOURCE_STATES,
  1532. clear: *const D3D12_CLEAR_VALUE,
  1533. iid: *const GUID,
  1534. out: Out,
  1535. ) -> HRESULT {
  1536. // SAFETY: as above.
  1537. unsafe {
  1538. let hr = own!(this, ID3D12Device_Vtbl.CreateCommittedResource)(
  1539. this, props, flags, desc, state, clear, iid, out,
  1540. );
  1541. if let Some((r, p)) = made(hr, out) {
  1542. let place = Place::Committed {
  1543. props: gpu::from_props(&*props),
  1544. flags: flags.0,
  1545. };
  1546. r.add(p, place, state.0, clear_of(clear));
  1547. }
  1548. hr
  1549. }
  1550. }
  1551. #[allow(clippy::too_many_arguments)]
  1552. unsafe extern "system" fn create_placed(
  1553. this: Ptr,
  1554. heap: Ptr,
  1555. offset: u64,
  1556. desc: *const D3D12_RESOURCE_DESC,
  1557. state: D3D12_RESOURCE_STATES,
  1558. clear: *const D3D12_CLEAR_VALUE,
  1559. iid: *const GUID,
  1560. out: Out,
  1561. ) -> HRESULT {
  1562. // SAFETY: as above.
  1563. unsafe {
  1564. let hr = own!(this, ID3D12Device_Vtbl.CreatePlacedResource)(
  1565. this, heap, offset, desc, state, clear, iid, out,
  1566. );
  1567. if let Some((r, p)) = made(hr, out) {
  1568. // One opened from memory was not seen made.
  1569. let heap = r.ids.get(heap as usize).unwrap_or_else(|| {
  1570. let id = r.id();
  1571. let d = borrow::<ID3D12Heap>(heap).GetDesc();
  1572. r.problem("a heap opened from existing memory: a replay makes one like it");
  1573. lock(&r.heaps).insert(id, heap_of(id, &d));
  1574. r.ids.set(heap as usize, id);
  1575. id
  1576. });
  1577. r.add(p, Place::Placed { heap, offset }, state.0, clear_of(clear));
  1578. }
  1579. hr
  1580. }
  1581. }
  1582. unsafe extern "system" fn create_cbv(
  1583. this: Ptr,
  1584. desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC,
  1585. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1586. ) {
  1587. // SAFETY: as above.
  1588. unsafe {
  1589. own!(this, ID3D12Device_Vtbl.CreateConstantBufferView)(this, desc, at);
  1590. if let Some(r) = recorder().filter(|_| !ours()) {
  1591. r.set_view(
  1592. at.ptr,
  1593. &Slot::new(
  1594. slot::CBV,
  1595. NONE,
  1596. NONE,
  1597. desc.cast(),
  1598. size_of::<D3D12_CONSTANT_BUFFER_VIEW_DESC>(),
  1599. ),
  1600. );
  1601. }
  1602. }
  1603. }
  1604. unsafe extern "system" fn create_srv(
  1605. this: Ptr,
  1606. res: Ptr,
  1607. desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC,
  1608. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1609. ) {
  1610. // SAFETY: as above.
  1611. unsafe {
  1612. own!(this, ID3D12Device_Vtbl.CreateShaderResourceView)(this, res, desc, at);
  1613. if let Some(r) = recorder().filter(|_| !ours()) {
  1614. let id = r.resource(res);
  1615. r.set_view(
  1616. at.ptr,
  1617. &Slot::new(
  1618. slot::SRV,
  1619. id,
  1620. NONE,
  1621. desc.cast(),
  1622. size_of::<D3D12_SHADER_RESOURCE_VIEW_DESC>(),
  1623. ),
  1624. );
  1625. }
  1626. }
  1627. }
  1628. unsafe extern "system" fn create_uav(
  1629. this: Ptr,
  1630. res: Ptr,
  1631. counter: Ptr,
  1632. desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC,
  1633. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1634. ) {
  1635. // SAFETY: as above.
  1636. unsafe {
  1637. own!(this, ID3D12Device_Vtbl.CreateUnorderedAccessView)(this, res, counter, desc, at);
  1638. if let Some(r) = recorder().filter(|_| !ours()) {
  1639. let (id, counter) = (r.resource(res), r.resource(counter));
  1640. r.set_view(
  1641. at.ptr,
  1642. &Slot::new(
  1643. slot::UAV,
  1644. id,
  1645. counter,
  1646. desc.cast(),
  1647. size_of::<D3D12_UNORDERED_ACCESS_VIEW_DESC>(),
  1648. ),
  1649. );
  1650. }
  1651. }
  1652. }
  1653. unsafe extern "system" fn create_rtv(
  1654. this: Ptr,
  1655. res: Ptr,
  1656. desc: *const D3D12_RENDER_TARGET_VIEW_DESC,
  1657. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1658. ) {
  1659. // SAFETY: as above.
  1660. unsafe {
  1661. own!(this, ID3D12Device_Vtbl.CreateRenderTargetView)(this, res, desc, at);
  1662. if let Some(r) = recorder().filter(|_| !ours()) {
  1663. let id = r.resource(res);
  1664. r.set_view(
  1665. at.ptr,
  1666. &Slot::new(
  1667. slot::RTV,
  1668. id,
  1669. NONE,
  1670. desc.cast(),
  1671. size_of::<D3D12_RENDER_TARGET_VIEW_DESC>(),
  1672. ),
  1673. );
  1674. }
  1675. }
  1676. }
  1677. unsafe extern "system" fn create_dsv(
  1678. this: Ptr,
  1679. res: Ptr,
  1680. desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC,
  1681. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1682. ) {
  1683. // SAFETY: as above.
  1684. unsafe {
  1685. own!(this, ID3D12Device_Vtbl.CreateDepthStencilView)(this, res, desc, at);
  1686. if let Some(r) = recorder().filter(|_| !ours()) {
  1687. let id = r.resource(res);
  1688. r.set_view(
  1689. at.ptr,
  1690. &Slot::new(
  1691. slot::DSV,
  1692. id,
  1693. NONE,
  1694. desc.cast(),
  1695. size_of::<D3D12_DEPTH_STENCIL_VIEW_DESC>(),
  1696. ),
  1697. );
  1698. }
  1699. }
  1700. }
  1701. unsafe extern "system" fn create_sampler(
  1702. this: Ptr,
  1703. desc: *const D3D12_SAMPLER_DESC,
  1704. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  1705. ) {
  1706. const _: () = assert!(size_of::<D3D12_SAMPLER_DESC>() == 52);
  1707. // SAFETY: as above.
  1708. unsafe {
  1709. own!(this, ID3D12Device_Vtbl.CreateSampler)(this, desc, at);
  1710. if let Some(r) = recorder().filter(|_| !ours()) {
  1711. r.set_view(
  1712. at.ptr,
  1713. &Slot::new(slot::SAMPLER, NONE, NONE, desc.cast(), 52),
  1714. );
  1715. }
  1716. }
  1717. }
  1718. unsafe extern "system" fn copy_descriptors_simple(
  1719. this: Ptr,
  1720. n: u32,
  1721. to: D3D12_CPU_DESCRIPTOR_HANDLE,
  1722. from: D3D12_CPU_DESCRIPTOR_HANDLE,
  1723. kind: D3D12_DESCRIPTOR_HEAP_TYPE,
  1724. ) {
  1725. // SAFETY: as above.
  1726. unsafe {
  1727. own!(this, ID3D12Device_Vtbl.CopyDescriptorsSimple)(this, n, to, from, kind);
  1728. if let Some(r) = recorder().filter(|_| !ours()) {
  1729. r.copy_views(to.ptr, from.ptr, n);
  1730. }
  1731. }
  1732. }
  1733. #[allow(clippy::too_many_arguments)]
  1734. unsafe extern "system" fn copy_descriptors(
  1735. this: Ptr,
  1736. n_to: u32,
  1737. to: *const D3D12_CPU_DESCRIPTOR_HANDLE,
  1738. to_sizes: *const u32,
  1739. n_from: u32,
  1740. from: *const D3D12_CPU_DESCRIPTOR_HANDLE,
  1741. from_sizes: *const u32,
  1742. kind: D3D12_DESCRIPTOR_HEAP_TYPE,
  1743. ) {
  1744. // SAFETY: as above; the arrays have as many entries as the counts say,
  1745. // and null sizes mean one descriptor each.
  1746. unsafe {
  1747. own!(this, ID3D12Device_Vtbl.CopyDescriptors)(
  1748. this, n_to, to, to_sizes, n_from, from, from_sizes, kind,
  1749. );
  1750. let Some(r) = recorder().filter(|_| !ours()) else {
  1751. return;
  1752. };
  1753. let step =
  1754. own!(this, ID3D12Device_Vtbl.GetDescriptorHandleIncrementSize)(this, kind) as usize;
  1755. let size = |sizes: *const u32, i: u32| {
  1756. if sizes.is_null() {
  1757. 1
  1758. } else {
  1759. *sizes.add(i as usize)
  1760. }
  1761. };
  1762. let (mut i, mut j, mut done_to, mut done_from) = (0, 0, 0, 0);
  1763. while i < n_to && j < n_from {
  1764. let n = (size(to_sizes, i) - done_to).min(size(from_sizes, j) - done_from);
  1765. if n > 0 {
  1766. let a = (*to.add(i as usize)).ptr + done_to as usize * step;
  1767. let b = (*from.add(j as usize)).ptr + done_from as usize * step;
  1768. r.copy_views(a, b, n);
  1769. }
  1770. done_to += n;
  1771. done_from += n;
  1772. if done_to >= size(to_sizes, i) {
  1773. (i, done_to) = (i + 1, 0);
  1774. }
  1775. if done_from >= size(from_sizes, j) {
  1776. (j, done_from) = (j + 1, 0);
  1777. }
  1778. }
  1779. }
  1780. }
  1781. unsafe extern "system" fn execute(this: Ptr, n: u32, lists: *const Ptr) {
  1782. // SAFETY: `n` closed lists, as D3D12 asks; the state is the queue's.
  1783. unsafe {
  1784. let go = || own!(this, ID3D12CommandQueue_Vtbl.ExecuteCommandLists)(this, n, lists);
  1785. let Some(r) = recorder().filter(|_| !ours()) else {
  1786. return go();
  1787. };
  1788. let kind = hook::state::<QueueState>(this).kind;
  1789. if kind != D3D12_COMMAND_LIST_TYPE_DIRECT.0 {
  1790. snap::other_queue(r, n);
  1791. return go();
  1792. }
  1793. let all = std::slice::from_raw_parts(lists, n as usize);
  1794. snap::submit(r, &borrow::<ID3D12CommandQueue>(this), all, go);
  1795. }
  1796. }
  1797. /// A list's recorder and state, for a call of the host layer's.
  1798. unsafe fn of(this: Ptr) -> Option<(&'static Recorder, &'static ListState)> {
  1799. let r = recorder()?;
  1800. if ours() {
  1801. return None;
  1802. }
  1803. // SAFETY: a list with a shim; its state is a list's.
  1804. Some((r, unsafe { hook::state::<ListState>(this) }))
  1805. }
  1806. /// Records a command, if lists are recorded now.
  1807. unsafe fn note(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) {
  1808. // SAFETY: a list with a shim.
  1809. if let Some((r, state)) = unsafe { of(this) }
  1810. && r.armed.load(Ordering::Relaxed)
  1811. {
  1812. state.push(&cmd(r));
  1813. }
  1814. }
  1815. unsafe extern "system" fn list_close(this: Ptr) -> HRESULT {
  1816. // SAFETY: as above.
  1817. unsafe {
  1818. let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Close)(this);
  1819. if let Some((_, state)) = of(this) {
  1820. let mut inner = lock(&state.inner);
  1821. let bytes = std::mem::take(&mut inner.bytes);
  1822. let changes = Arc::new(std::mem::take(&mut inner.changes));
  1823. inner.closed = Some((inner.whole.then(|| Arc::new(bytes)), changes));
  1824. }
  1825. hr
  1826. }
  1827. }
  1828. unsafe extern "system" fn list_reset(this: Ptr, allocator: Ptr, pso: Ptr) -> HRESULT {
  1829. // SAFETY: as above.
  1830. unsafe {
  1831. let table = hook::table(this);
  1832. let hr = own!(this, ID3D12GraphicsCommandList_Vtbl.Reset)(this, allocator, pso);
  1833. // A reset sets the list's table pointer anew.
  1834. hook::again(this, table, list_table);
  1835. if let Some((r, state)) = of(this)
  1836. && hr.is_ok()
  1837. {
  1838. let mut inner = lock(&state.inner);
  1839. inner.closed = None;
  1840. inner.whole =
  1841. r.armed.load(Ordering::SeqCst) && state.kind == D3D12_COMMAND_LIST_TYPE_DIRECT.0;
  1842. begin(&mut inner, r, pso);
  1843. }
  1844. hr
  1845. }
  1846. }
  1847. unsafe extern "system" fn draw(
  1848. this: Ptr,
  1849. vertices: u32,
  1850. instances: u32,
  1851. first: u32,
  1852. first_instance: u32,
  1853. ) {
  1854. // SAFETY: as above.
  1855. unsafe {
  1856. own!(this, ID3D12GraphicsCommandList_Vtbl.DrawInstanced)(
  1857. this,
  1858. vertices,
  1859. instances,
  1860. first,
  1861. first_instance,
  1862. );
  1863. note(this, |_| Cmd::Draw {
  1864. vertices,
  1865. instances,
  1866. first,
  1867. first_instance,
  1868. });
  1869. }
  1870. }
  1871. unsafe extern "system" fn draw_indexed(
  1872. this: Ptr,
  1873. indices: u32,
  1874. instances: u32,
  1875. first: u32,
  1876. base: i32,
  1877. first_instance: u32,
  1878. ) {
  1879. // SAFETY: as above.
  1880. unsafe {
  1881. own!(this, ID3D12GraphicsCommandList_Vtbl.DrawIndexedInstanced)(
  1882. this,
  1883. indices,
  1884. instances,
  1885. first,
  1886. base,
  1887. first_instance,
  1888. );
  1889. note(this, |_| Cmd::DrawIndexed {
  1890. indices,
  1891. instances,
  1892. first,
  1893. base,
  1894. first_instance,
  1895. });
  1896. }
  1897. }
  1898. unsafe extern "system" fn dispatch(this: Ptr, x: u32, y: u32, z: u32) {
  1899. // SAFETY: as above.
  1900. unsafe {
  1901. own!(this, ID3D12GraphicsCommandList_Vtbl.Dispatch)(this, x, y, z);
  1902. note(this, |_| Cmd::Dispatch { groups: [x, y, z] });
  1903. }
  1904. }
  1905. unsafe extern "system" fn dispatch_mesh(this: Ptr, x: u32, y: u32, z: u32) {
  1906. // SAFETY: as above.
  1907. unsafe {
  1908. own!(this, ID3D12GraphicsCommandList6_Vtbl.DispatchMesh)(this, x, y, z);
  1909. note(this, |_| Cmd::DispatchMesh { groups: [x, y, z] });
  1910. }
  1911. }
  1912. unsafe extern "system" fn copy_buffer(
  1913. this: Ptr,
  1914. dst: Ptr,
  1915. dst_at: u64,
  1916. src: Ptr,
  1917. src_at: u64,
  1918. len: u64,
  1919. ) {
  1920. // SAFETY: as above.
  1921. unsafe {
  1922. own!(this, ID3D12GraphicsCommandList_Vtbl.CopyBufferRegion)(
  1923. this, dst, dst_at, src, src_at, len,
  1924. );
  1925. note(this, |r| Cmd::CopyBuffer {
  1926. dst: r.resource(dst),
  1927. dst_at,
  1928. src: r.resource(src),
  1929. src_at,
  1930. len,
  1931. });
  1932. }
  1933. }
  1934. unsafe fn location(r: &Recorder, l: &D3D12_TEXTURE_COPY_LOCATION) -> Loc {
  1935. // SAFETY: a copy's valid location.
  1936. unsafe {
  1937. let res = r.resource(std::mem::transmute_copy::<_, Ptr>(&l.pResource));
  1938. if l.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX {
  1939. return Loc::Sub {
  1940. res,
  1941. sub: l.Anonymous.SubresourceIndex,
  1942. };
  1943. }
  1944. let p = l.Anonymous.PlacedFootprint;
  1945. let f = p.Footprint;
  1946. Loc::Placed {
  1947. res,
  1948. offset: p.Offset,
  1949. format: f.Format.0,
  1950. size: [f.Width, f.Height, f.Depth],
  1951. pitch: f.RowPitch,
  1952. }
  1953. }
  1954. }
  1955. /// A command that changes states whether lists are recorded or not.
  1956. unsafe fn note_change(this: Ptr, cmd: impl FnOnce(&Recorder) -> Cmd) {
  1957. // SAFETY: a list with a shim.
  1958. if let Some((r, state)) = unsafe { of(this) } {
  1959. let cmd = cmd(r);
  1960. let mut inner = lock(&state.inner);
  1961. states::changes(&cmd, &mut inner.changes);
  1962. if inner.whole {
  1963. cmd.put(&mut inner.bytes);
  1964. }
  1965. }
  1966. }
  1967. unsafe extern "system" fn copy_texture(
  1968. this: Ptr,
  1969. dst: *const D3D12_TEXTURE_COPY_LOCATION,
  1970. x: u32,
  1971. y: u32,
  1972. z: u32,
  1973. src: *const D3D12_TEXTURE_COPY_LOCATION,
  1974. part: *const D3D12_BOX,
  1975. ) {
  1976. // SAFETY: as above.
  1977. unsafe {
  1978. own!(this, ID3D12GraphicsCommandList_Vtbl.CopyTextureRegion)(this, dst, x, y, z, src, part);
  1979. note_change(this, |r| Cmd::CopyTexture {
  1980. dst: location(r, &*dst),
  1981. at: [x, y, z],
  1982. src: location(r, &*src),
  1983. part: part
  1984. .as_ref()
  1985. .map(|b| [b.left, b.top, b.front, b.right, b.bottom, b.back]),
  1986. });
  1987. }
  1988. }
  1989. unsafe extern "system" fn copy_resource(this: Ptr, dst: Ptr, src: Ptr) {
  1990. // SAFETY: as above.
  1991. unsafe {
  1992. own!(this, ID3D12GraphicsCommandList_Vtbl.CopyResource)(this, dst, src);
  1993. note_change(this, |r| Cmd::CopyResource {
  1994. dst: r.resource(dst),
  1995. src: r.resource(src),
  1996. });
  1997. }
  1998. }
  1999. unsafe extern "system" fn resolve(
  2000. this: Ptr,
  2001. dst: Ptr,
  2002. dst_sub: u32,
  2003. src: Ptr,
  2004. src_sub: u32,
  2005. format: DXGI_FORMAT,
  2006. ) {
  2007. // SAFETY: as above.
  2008. unsafe {
  2009. own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveSubresource)(
  2010. this, dst, dst_sub, src, src_sub, format,
  2011. );
  2012. note(this, |r| Cmd::Resolve {
  2013. dst: r.resource(dst),
  2014. dst_sub,
  2015. src: r.resource(src),
  2016. src_sub,
  2017. format: format.0,
  2018. });
  2019. }
  2020. }
  2021. #[allow(clippy::too_many_arguments)]
  2022. unsafe extern "system" fn resolve_region(
  2023. this: Ptr,
  2024. dst: Ptr,
  2025. dst_sub: u32,
  2026. x: u32,
  2027. y: u32,
  2028. src: Ptr,
  2029. src_sub: u32,
  2030. part: *const RECT,
  2031. format: DXGI_FORMAT,
  2032. mode: D3D12_RESOLVE_MODE,
  2033. ) {
  2034. // SAFETY: as above.
  2035. unsafe {
  2036. own!(
  2037. this,
  2038. ID3D12GraphicsCommandList1_Vtbl.ResolveSubresourceRegion
  2039. )(this, dst, dst_sub, x, y, src, src_sub, part, format, mode);
  2040. note(this, |r| Cmd::ResolveRegion {
  2041. dst: r.resource(dst),
  2042. dst_sub,
  2043. at: [x, y],
  2044. src: r.resource(src),
  2045. src_sub,
  2046. part: part.as_ref().map(rect),
  2047. format: format.0,
  2048. mode: mode.0,
  2049. });
  2050. }
  2051. }
  2052. fn rect(r: &RECT) -> [i32; 4] {
  2053. [r.left, r.top, r.right, r.bottom]
  2054. }
  2055. unsafe fn rects(n: u32, all: *const RECT) -> Vec<[i32; 4]> {
  2056. if all.is_null() || n == 0 {
  2057. return Vec::new();
  2058. }
  2059. // SAFETY: `n` rectangles.
  2060. unsafe { std::slice::from_raw_parts(all, n as usize) }
  2061. .iter()
  2062. .map(rect)
  2063. .collect()
  2064. }
  2065. unsafe extern "system" fn topology(this: Ptr, kind: D3D_PRIMITIVE_TOPOLOGY) {
  2066. // SAFETY: as above.
  2067. unsafe {
  2068. own!(this, ID3D12GraphicsCommandList_Vtbl.IASetPrimitiveTopology)(this, kind);
  2069. note(this, |_| Cmd::Topology { kind: kind.0 });
  2070. }
  2071. }
  2072. unsafe extern "system" fn viewports(this: Ptr, n: u32, all: *const D3D12_VIEWPORT) {
  2073. // SAFETY: as above.
  2074. unsafe {
  2075. own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetViewports)(this, n, all);
  2076. note(this, |_| Cmd::Viewports {
  2077. all: (0..n as usize)
  2078. .map(|i| all.add(i).cast::<[f32; 6]>().read())
  2079. .collect(),
  2080. });
  2081. }
  2082. }
  2083. unsafe extern "system" fn scissors(this: Ptr, n: u32, all: *const RECT) {
  2084. // SAFETY: as above.
  2085. unsafe {
  2086. own!(this, ID3D12GraphicsCommandList_Vtbl.RSSetScissorRects)(this, n, all);
  2087. note(this, |_| Cmd::Scissors { all: rects(n, all) });
  2088. }
  2089. }
  2090. unsafe extern "system" fn blend_factor(this: Ptr, factor: *const f32) {
  2091. // SAFETY: as above.
  2092. unsafe {
  2093. own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetBlendFactor)(this, factor);
  2094. note(this, |_| Cmd::BlendFactor {
  2095. factor: factor.cast::<[f32; 4]>().as_ref().copied(),
  2096. });
  2097. }
  2098. }
  2099. unsafe extern "system" fn stencil_ref(this: Ptr, value: u32) {
  2100. // SAFETY: as above.
  2101. unsafe {
  2102. own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetStencilRef)(this, value);
  2103. note(this, |_| Cmd::StencilRef { value });
  2104. }
  2105. }
  2106. unsafe extern "system" fn depth_bounds(this: Ptr, min: f32, max: f32) {
  2107. // SAFETY: as above.
  2108. unsafe {
  2109. own!(this, ID3D12GraphicsCommandList1_Vtbl.OMSetDepthBounds)(this, min, max);
  2110. note(this, |_| Cmd::DepthBounds { min, max });
  2111. }
  2112. }
  2113. unsafe extern "system" fn set_pipeline(this: Ptr, pso: Ptr) {
  2114. // SAFETY: as above.
  2115. unsafe {
  2116. own!(this, ID3D12GraphicsCommandList_Vtbl.SetPipelineState)(this, pso);
  2117. note(this, |r| Cmd::Pipeline {
  2118. pso: r.object(pso, "a pipeline"),
  2119. });
  2120. }
  2121. }
  2122. unsafe extern "system" fn barrier(this: Ptr, n: u32, all: *const D3D12_RESOURCE_BARRIER) {
  2123. // SAFETY: as above; a barrier's type says which of its parts holds.
  2124. unsafe {
  2125. own!(this, ID3D12GraphicsCommandList_Vtbl.ResourceBarrier)(this, n, all);
  2126. note_change(this, |r| {
  2127. let all = std::slice::from_raw_parts(all, n as usize)
  2128. .iter()
  2129. .map(|b| match b.Type {
  2130. D3D12_RESOURCE_BARRIER_TYPE_ALIASING => {
  2131. let a = &b.Anonymous.Aliasing;
  2132. Barrier::Alias {
  2133. flags: b.Flags.0,
  2134. before: r
  2135. .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceBefore)),
  2136. after: r
  2137. .resource(std::mem::transmute_copy::<_, Ptr>(&a.pResourceAfter)),
  2138. }
  2139. }
  2140. D3D12_RESOURCE_BARRIER_TYPE_UAV => Barrier::Uav {
  2141. flags: b.Flags.0,
  2142. res: r.resource(std::mem::transmute_copy::<_, Ptr>(
  2143. &b.Anonymous.UAV.pResource,
  2144. )),
  2145. },
  2146. _ => {
  2147. let t = &b.Anonymous.Transition;
  2148. Barrier::Transition {
  2149. flags: b.Flags.0,
  2150. res: r.resource(std::mem::transmute_copy::<_, Ptr>(&t.pResource)),
  2151. sub: t.Subresource,
  2152. before: t.StateBefore.0,
  2153. after: t.StateAfter.0,
  2154. }
  2155. }
  2156. })
  2157. .collect();
  2158. Cmd::Barriers { all }
  2159. });
  2160. }
  2161. }
  2162. unsafe extern "system" fn set_heaps(this: Ptr, n: u32, all: *const Ptr) {
  2163. // SAFETY: as above.
  2164. unsafe {
  2165. own!(this, ID3D12GraphicsCommandList_Vtbl.SetDescriptorHeaps)(this, n, all);
  2166. note(this, |r| Cmd::Heaps {
  2167. heaps: (0..n as usize)
  2168. .map(|i| r.object(*all.add(i), "a descriptor heap"))
  2169. .collect(),
  2170. });
  2171. }
  2172. }
  2173. unsafe extern "system" fn root_compute(this: Ptr, root: Ptr) {
  2174. // SAFETY: as above.
  2175. unsafe {
  2176. own!(this, ID3D12GraphicsCommandList_Vtbl.SetComputeRootSignature)(this, root);
  2177. note(this, |r| Cmd::RootSignature {
  2178. graphics: false,
  2179. root: r.object(root, "a root signature"),
  2180. });
  2181. }
  2182. }
  2183. unsafe extern "system" fn root_graphics(this: Ptr, root: Ptr) {
  2184. // SAFETY: as above.
  2185. unsafe {
  2186. own!(
  2187. this,
  2188. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootSignature
  2189. )(this, root);
  2190. note(this, |r| Cmd::RootSignature {
  2191. graphics: true,
  2192. root: r.object(root, "a root signature"),
  2193. });
  2194. }
  2195. }
  2196. fn table(r: &Recorder, graphics: bool, param: u32, at: u64) -> Cmd {
  2197. let (heap, slot) = match read(&r.descriptors).gpu(at) {
  2198. Some((h, i)) => (h.id, i),
  2199. None => (NONE, 0),
  2200. };
  2201. if heap == NONE {
  2202. r.problem("a descriptor table in no heap seen made");
  2203. }
  2204. Cmd::Table {
  2205. graphics,
  2206. param,
  2207. heap,
  2208. slot,
  2209. }
  2210. }
  2211. unsafe extern "system" fn table_compute(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) {
  2212. // SAFETY: as above.
  2213. unsafe {
  2214. own!(
  2215. this,
  2216. ID3D12GraphicsCommandList_Vtbl.SetComputeRootDescriptorTable
  2217. )(this, param, at);
  2218. note(this, |r| table(r, false, param, at.ptr));
  2219. }
  2220. }
  2221. unsafe extern "system" fn table_graphics(this: Ptr, param: u32, at: D3D12_GPU_DESCRIPTOR_HANDLE) {
  2222. // SAFETY: as above.
  2223. unsafe {
  2224. own!(
  2225. this,
  2226. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRootDescriptorTable
  2227. )(this, param, at);
  2228. note(this, |r| table(r, true, param, at.ptr));
  2229. }
  2230. }
  2231. unsafe extern "system" fn constant_compute(this: Ptr, param: u32, value: u32, offset: u32) {
  2232. // SAFETY: as above.
  2233. unsafe {
  2234. own!(
  2235. this,
  2236. ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstant
  2237. )(this, param, value, offset);
  2238. note(this, |_| Cmd::Constants {
  2239. graphics: false,
  2240. param,
  2241. offset,
  2242. values: vec![value],
  2243. });
  2244. }
  2245. }
  2246. unsafe extern "system" fn constant_graphics(this: Ptr, param: u32, value: u32, offset: u32) {
  2247. // SAFETY: as above.
  2248. unsafe {
  2249. own!(
  2250. this,
  2251. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstant
  2252. )(this, param, value, offset);
  2253. note(this, |_| Cmd::Constants {
  2254. graphics: true,
  2255. param,
  2256. offset,
  2257. values: vec![value],
  2258. });
  2259. }
  2260. }
  2261. unsafe fn values(n: u32, data: *const c_void) -> Vec<u32> {
  2262. // SAFETY: `n` values, of any alignment.
  2263. (0..n as usize)
  2264. .map(|i| unsafe { data.cast::<u32>().add(i).read_unaligned() })
  2265. .collect()
  2266. }
  2267. unsafe extern "system" fn constants_compute(
  2268. this: Ptr,
  2269. param: u32,
  2270. n: u32,
  2271. data: *const c_void,
  2272. offset: u32,
  2273. ) {
  2274. // SAFETY: as above.
  2275. unsafe {
  2276. own!(
  2277. this,
  2278. ID3D12GraphicsCommandList_Vtbl.SetComputeRoot32BitConstants
  2279. )(this, param, n, data, offset);
  2280. note(this, |_| Cmd::Constants {
  2281. graphics: false,
  2282. param,
  2283. offset,
  2284. values: values(n, data),
  2285. });
  2286. }
  2287. }
  2288. unsafe extern "system" fn constants_graphics(
  2289. this: Ptr,
  2290. param: u32,
  2291. n: u32,
  2292. data: *const c_void,
  2293. offset: u32,
  2294. ) {
  2295. // SAFETY: as above.
  2296. unsafe {
  2297. own!(
  2298. this,
  2299. ID3D12GraphicsCommandList_Vtbl.SetGraphicsRoot32BitConstants
  2300. )(this, param, n, data, offset);
  2301. note(this, |_| Cmd::Constants {
  2302. graphics: true,
  2303. param,
  2304. offset,
  2305. values: values(n, data),
  2306. });
  2307. }
  2308. }
  2309. /// A root view's address, reported if it lies in no buffer.
  2310. fn address(r: &Recorder, at: u64) -> Va {
  2311. let va = r.va(at);
  2312. if matches!(va, Va::Unknown { .. }) {
  2313. r.problem("a GPU address in no buffer seen made");
  2314. }
  2315. va
  2316. }
  2317. macro_rules! root_views {
  2318. ($($name:ident, $method:ident, $graphics:literal, $kind:ident;)*) => {$(
  2319. unsafe extern "system" fn $name(this: Ptr, param: u32, at: u64) {
  2320. // SAFETY: as above.
  2321. unsafe {
  2322. own!(this, ID3D12GraphicsCommandList_Vtbl.$method)(this, param, at);
  2323. note(this, |r| Cmd::RootView { graphics: $graphics, kind: slot::$kind, param, va: address(r, at) });
  2324. }
  2325. }
  2326. )*};
  2327. }
  2328. root_views! {
  2329. cbv_compute, SetComputeRootConstantBufferView, false, CBV;
  2330. cbv_graphics, SetGraphicsRootConstantBufferView, true, CBV;
  2331. srv_compute, SetComputeRootShaderResourceView, false, SRV;
  2332. srv_graphics, SetGraphicsRootShaderResourceView, true, SRV;
  2333. uav_compute, SetComputeRootUnorderedAccessView, false, UAV;
  2334. uav_graphics, SetGraphicsRootUnorderedAccessView, true, UAV;
  2335. }
  2336. unsafe extern "system" fn index_buffer(this: Ptr, view: *const D3D12_INDEX_BUFFER_VIEW) {
  2337. // SAFETY: as above.
  2338. unsafe {
  2339. own!(this, ID3D12GraphicsCommandList_Vtbl.IASetIndexBuffer)(this, view);
  2340. note(this, |r| Cmd::IndexBuffer {
  2341. view: view
  2342. .as_ref()
  2343. .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.Format.0)),
  2344. });
  2345. }
  2346. }
  2347. unsafe extern "system" fn vertex_buffers(
  2348. this: Ptr,
  2349. start: u32,
  2350. n: u32,
  2351. views: *const D3D12_VERTEX_BUFFER_VIEW,
  2352. ) {
  2353. // SAFETY: as above.
  2354. unsafe {
  2355. own!(this, ID3D12GraphicsCommandList_Vtbl.IASetVertexBuffers)(this, start, n, views);
  2356. note(this, |r| Cmd::VertexBuffers {
  2357. start,
  2358. count: n,
  2359. views: (!views.is_null()).then(|| {
  2360. let all = std::slice::from_raw_parts(views, n as usize);
  2361. all.iter()
  2362. .map(|v| (address(r, v.BufferLocation), v.SizeInBytes, v.StrideInBytes))
  2363. .collect()
  2364. }),
  2365. });
  2366. }
  2367. }
  2368. unsafe extern "system" fn targets(
  2369. this: Ptr,
  2370. n: u32,
  2371. colors: *const D3D12_CPU_DESCRIPTOR_HANDLE,
  2372. range: BOOL,
  2373. depth: *const D3D12_CPU_DESCRIPTOR_HANDLE,
  2374. ) {
  2375. // SAFETY: as above.
  2376. unsafe {
  2377. own!(this, ID3D12GraphicsCommandList_Vtbl.OMSetRenderTargets)(
  2378. this, n, colors, range, depth,
  2379. );
  2380. note(this, |r| {
  2381. let colors = (0..n as usize)
  2382. .map(|i| {
  2383. if !range.as_bool() {
  2384. return r.view((*colors.add(i)).ptr);
  2385. }
  2386. let all = read(&r.descriptors);
  2387. all.cpu((*colors).ptr)
  2388. .map_or(Slot::EMPTY, |(h, first)| h.get(first + i as u32))
  2389. })
  2390. .collect();
  2391. Cmd::Targets {
  2392. colors,
  2393. depth: depth.as_ref().map(|d| r.view(d.ptr)),
  2394. }
  2395. });
  2396. }
  2397. }
  2398. #[allow(clippy::too_many_arguments)]
  2399. unsafe extern "system" fn clear_depth(
  2400. this: Ptr,
  2401. view: D3D12_CPU_DESCRIPTOR_HANDLE,
  2402. flags: D3D12_CLEAR_FLAGS,
  2403. depth: f32,
  2404. stencil: u8,
  2405. n: u32,
  2406. all: *const RECT,
  2407. ) {
  2408. // SAFETY: as above.
  2409. unsafe {
  2410. own!(this, ID3D12GraphicsCommandList_Vtbl.ClearDepthStencilView)(
  2411. this, view, flags, depth, stencil, n, all,
  2412. );
  2413. note(this, |r| Cmd::ClearDepth {
  2414. view: r.view(view.ptr),
  2415. flags: flags.0,
  2416. depth,
  2417. stencil,
  2418. rects: rects(n, all),
  2419. });
  2420. }
  2421. }
  2422. unsafe extern "system" fn clear_target(
  2423. this: Ptr,
  2424. view: D3D12_CPU_DESCRIPTOR_HANDLE,
  2425. color: *const f32,
  2426. n: u32,
  2427. all: *const RECT,
  2428. ) {
  2429. // SAFETY: as above.
  2430. unsafe {
  2431. own!(this, ID3D12GraphicsCommandList_Vtbl.ClearRenderTargetView)(this, view, color, n, all);
  2432. note(this, |r| Cmd::ClearTarget {
  2433. view: r.view(view.ptr),
  2434. color: color.cast::<[f32; 4]>().read(),
  2435. rects: rects(n, all),
  2436. });
  2437. }
  2438. }
  2439. unsafe extern "system" fn discard(this: Ptr, res: Ptr, region: *const D3D12_DISCARD_REGION) {
  2440. // SAFETY: as above.
  2441. unsafe {
  2442. own!(this, ID3D12GraphicsCommandList_Vtbl.DiscardResource)(this, res, region);
  2443. note(this, |r| Cmd::Discard {
  2444. res: r.resource(res),
  2445. rects: region
  2446. .as_ref()
  2447. .map_or(Vec::new(), |d| rects(d.NumRects, d.pRects)),
  2448. subs: region
  2449. .as_ref()
  2450. .map(|d| [d.FirstSubresource, d.NumSubresources]),
  2451. });
  2452. }
  2453. }
  2454. unsafe extern "system" fn begin_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) {
  2455. // SAFETY: as above.
  2456. unsafe {
  2457. own!(this, ID3D12GraphicsCommandList_Vtbl.BeginQuery)(this, heap, kind, index);
  2458. note(this, |r| Cmd::BeginQuery {
  2459. heap: r.object(heap, "a query heap"),
  2460. kind: kind.0,
  2461. index,
  2462. });
  2463. }
  2464. }
  2465. unsafe extern "system" fn end_query(this: Ptr, heap: Ptr, kind: D3D12_QUERY_TYPE, index: u32) {
  2466. // SAFETY: as above.
  2467. unsafe {
  2468. own!(this, ID3D12GraphicsCommandList_Vtbl.EndQuery)(this, heap, kind, index);
  2469. note(this, |r| Cmd::EndQuery {
  2470. heap: r.object(heap, "a query heap"),
  2471. kind: kind.0,
  2472. index,
  2473. });
  2474. }
  2475. }
  2476. unsafe extern "system" fn resolve_query(
  2477. this: Ptr,
  2478. heap: Ptr,
  2479. kind: D3D12_QUERY_TYPE,
  2480. first: u32,
  2481. count: u32,
  2482. dst: Ptr,
  2483. at: u64,
  2484. ) {
  2485. // SAFETY: as above.
  2486. unsafe {
  2487. own!(this, ID3D12GraphicsCommandList_Vtbl.ResolveQueryData)(
  2488. this, heap, kind, first, count, dst, at,
  2489. );
  2490. note(this, |r| Cmd::ResolveQuery {
  2491. heap: r.object(heap, "a query heap"),
  2492. kind: kind.0,
  2493. first,
  2494. count,
  2495. dst: r.resource(dst),
  2496. at,
  2497. });
  2498. }
  2499. }
  2500. unsafe extern "system" fn indirect(
  2501. this: Ptr,
  2502. signature: Ptr,
  2503. most: u32,
  2504. args: Ptr,
  2505. at: u64,
  2506. count: Ptr,
  2507. count_at: u64,
  2508. ) {
  2509. // SAFETY: as above.
  2510. unsafe {
  2511. own!(this, ID3D12GraphicsCommandList_Vtbl.ExecuteIndirect)(
  2512. this, signature, most, args, at, count, count_at,
  2513. );
  2514. note(this, |r| Cmd::Indirect {
  2515. signature: r.object(signature, "a command signature"),
  2516. most,
  2517. args: r.resource(args),
  2518. at,
  2519. count: r.resource(count),
  2520. count_at,
  2521. });
  2522. }
  2523. }
  2524. unsafe extern "system" fn write_immediate(
  2525. this: Ptr,
  2526. n: u32,
  2527. all: *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER,
  2528. modes: *const D3D12_WRITEBUFFERIMMEDIATE_MODE,
  2529. ) {
  2530. // SAFETY: as above.
  2531. unsafe {
  2532. own!(this, ID3D12GraphicsCommandList2_Vtbl.WriteBufferImmediate)(this, n, all, modes);
  2533. note(this, |r| Cmd::WriteImmediate {
  2534. all: (0..n as usize)
  2535. .map(|i| {
  2536. let p = all.add(i).read();
  2537. let mode = if modes.is_null() {
  2538. 0
  2539. } else {
  2540. modes.add(i).read().0
  2541. };
  2542. (address(r, p.Dest), p.Value, mode)
  2543. })
  2544. .collect(),
  2545. });
  2546. }
  2547. }
  2548. /// The first subresources of all: what [`ALL`] means in a barrier.
  2549. const _: () = assert!(ALL == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES);
  2550. #[cfg(test)]
  2551. mod tests {
  2552. use super::*;
  2553. #[test]
  2554. fn when_to_record() {
  2555. assert_eq!(parse_at("120"), At::Seconds(120.0));
  2556. assert_eq!(parse_at(" 1.5 "), At::Seconds(1.5));
  2557. assert_eq!(parse_at("f900"), At::Frame(900));
  2558. assert_eq!(parse_at(""), At::Trigger);
  2559. assert_eq!(parse_at("later"), At::Trigger);
  2560. }
  2561. #[test]
  2562. fn descriptor_heaps_are_found_by_address() {
  2563. let heap = |id, cpu, gpu, count| {
  2564. let d = D3D12_DESCRIPTOR_HEAP_DESC {
  2565. NumDescriptors: count,
  2566. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  2567. ..Default::default()
  2568. };
  2569. Arc::new(Heap::new(id, &d, cpu, gpu, 32))
  2570. };
  2571. let mut all = Heaps::default();
  2572. all.add(heap(1, 0x1000, 0x10_0000, 4));
  2573. all.add(heap(2, 0x2000, 0x20_0000, 8));
  2574. let at = |all: &Heaps, p| all.cpu(p).map(|(h, i)| (h.id, i));
  2575. assert_eq!(at(&all, 0x1000), Some((1, 0)));
  2576. assert_eq!(at(&all, 0x1060), Some((1, 3)));
  2577. assert_eq!(at(&all, 0x1080), None, "past its end");
  2578. assert_eq!(at(&all, 0xfff), None);
  2579. assert_eq!(all.gpu(0x20_0040).map(|(h, i)| (h.id, i)), Some((2, 2)));
  2580. // A heap made where a dead one was takes its place.
  2581. all.add(heap(3, 0x1020, 0x30_0000, 4));
  2582. assert_eq!(at(&all, 0x1000), None);
  2583. assert_eq!(at(&all, 0x1020), Some((3, 0)));
  2584. all.remove(2);
  2585. assert_eq!(at(&all, 0x2000), None);
  2586. let h = heap(4, 0, 0, 2);
  2587. let s = Slot {
  2588. kind: slot::SRV,
  2589. res: 5,
  2590. ..Slot::EMPTY
  2591. };
  2592. h.set(1, &s);
  2593. h.set(2, &s);
  2594. assert_eq!(h.all(), [Slot::EMPTY, s]);
  2595. assert_eq!(h.get(9), Slot::EMPTY);
  2596. }
  2597. }