draw.rs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. //! Draws on the host GPU (decision 0007, step 3). A list keeps the state
  2. //! the title sets for its draws (pipeline, descriptor heaps, root
  3. //! arguments, vertex and index buffers, targets); each draw then brings the
  4. //! host list up to date: the host pipeline and our root signature, the
  5. //! user data the translated shaders read, the host copies of the buffers
  6. //! and descriptors they read, and the states of the textures involved.
  7. //! State the host keeps across draws (viewports, scissors, blend factor,
  8. //! stencil reference, topology, targets) is set on the host list as the
  9. //! title sets it.
  10. use std::sync::atomic::{AtomicU64, Ordering};
  11. use victory_shader::{ResourceType, RootType, UsedResource};
  12. use crate::descriptor::View;
  13. use windows::Win32::Foundation::RECT;
  14. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  15. use windows::Win32::Graphics::Direct3D12::*;
  16. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  17. use windows::core::Interface;
  18. use crate::host::HostList;
  19. use crate::object::This;
  20. use crate::pipeline::host::HostPipeline;
  21. /// A root argument as the title set it.
  22. #[derive(Debug, Clone, Default)]
  23. enum Root {
  24. #[default]
  25. None,
  26. /// A descriptor table's first descriptor (an address in a heap).
  27. Table(u64),
  28. Constants(Vec<u32>),
  29. /// A root view's GPU address.
  30. View(u64),
  31. }
  32. #[repr(C)]
  33. #[derive(Debug, Clone, Copy, Default)]
  34. pub(crate) struct VertexView {
  35. address: u64,
  36. size: u32,
  37. stride: u32,
  38. }
  39. #[repr(C)]
  40. #[derive(Debug, Clone, Copy, Default)]
  41. pub(crate) struct IndexView {
  42. address: u64,
  43. size: u32,
  44. format: u32,
  45. }
  46. /// What one title list has set, and what its host list was last given.
  47. #[derive(Default)]
  48. pub(crate) struct State {
  49. pipeline: usize,
  50. /// View heap, sampler heap.
  51. heaps: [usize; 2],
  52. graphics: Vec<Root>,
  53. compute: Vec<Root>,
  54. vertex: [VertexView; 32],
  55. index: IndexView,
  56. /// Bound render target and depth resources, for their host states.
  57. targets: Vec<usize>,
  58. depth: usize,
  59. /// The title's primitive topology (the host's may differ).
  60. topology: u32,
  61. /// What the host list has: pipeline, root signature, heaps.
  62. host_pipeline: usize,
  63. /// Graphics, compute.
  64. host_roots: [usize; 2],
  65. host_heaps: [usize; 2],
  66. /// Tables made afresh in this list: (table, what it holds) → first
  67. /// dynamic slot.
  68. fresh_tables: std::collections::HashMap<(u64, u64), u32>,
  69. /// The dynamic slots the list holds: title heap, first, count; given
  70. /// back when the list is reset or released.
  71. dynamic: Vec<(usize, u32, u32)>,
  72. /// A fresh table of the stage being bound could not be made.
  73. table_failed: bool,
  74. }
  75. impl Drop for State {
  76. fn drop(&mut self) {
  77. for &(heap, first, n) in &self.dynamic {
  78. crate::descriptor::release_dynamic(heap, first, n);
  79. }
  80. }
  81. }
  82. /// Draws recorded on the host GPU since the last frame line.
  83. static DRAWN: AtomicU64 = AtomicU64::new(0);
  84. /// Draws run on the host so far.
  85. pub(crate) fn drawn() -> u64 {
  86. DRAWN.load(Ordering::Relaxed)
  87. }
  88. /// The draws traced since the last present (diagnostics builds, with
  89. /// debug logging for this module): logged when the frame comes out black.
  90. #[cfg(feature = "diagnostics")]
  91. static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  92. /// The draws traced since the last call.
  93. #[cfg(feature = "diagnostics")]
  94. pub(crate) fn take_frame() -> Vec<String> {
  95. std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
  96. }
  97. /// Draws, mesh dispatches and dispatches recorded but not run on the host
  98. /// (no host pipeline) since the last call.
  99. pub(crate) fn take_dropped() -> u64 {
  100. DROPPED.swap(0, Ordering::Relaxed)
  101. }
  102. static DROPPED: AtomicU64 = AtomicU64::new(0);
  103. /// Marks the last traced draw as not run on the host.
  104. #[cfg(feature = "diagnostics")]
  105. fn dropped(pipeline: usize) {
  106. crate::pipeline::note_drop(pipeline as This);
  107. if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
  108. last.push_str(" DROPPED");
  109. }
  110. }
  111. /// Dispatches run on the host so far.
  112. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  113. pub(crate) fn dispatched() -> u64 {
  114. DISPATCHED.load(Ordering::Relaxed)
  115. }
  116. /// The host address of a root view: its buffer's host copy, or for a
  117. /// constant buffer not 256-byte aligned there (the console needs 16) a
  118. /// copy in upload memory.
  119. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
  120. /// other views as 1 MiB (both cut at their buffer's end).
  121. fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
  122. let shadow = crate::shadow::find(address, 1)?;
  123. let len = shadow
  124. .left(address)
  125. .min(if srv { 1 << 20 } else { 1 << 16 });
  126. let gpu = shadow.gpu(address);
  127. if srv || gpu % 256 == 0 {
  128. shadow.refresh(list, address, len);
  129. return Some(gpu);
  130. }
  131. let (gpu, to) = list.scratch(len)?;
  132. list.defer_fill(to, address as *const u8, len as usize);
  133. Some(gpu)
  134. }
  135. macro_rules! once {
  136. ($($arg:tt)*) => {{
  137. static ONCE: std::sync::Once = std::sync::Once::new();
  138. ONCE.call_once(|| tracing::warn!($($arg)*));
  139. }};
  140. }
  141. fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
  142. let slot = slot as usize;
  143. if roots.len() <= slot {
  144. roots.resize(slot + 1, Root::None);
  145. }
  146. roots[slot] = root;
  147. }
  148. impl State {
  149. pub(crate) fn reset(&mut self, pipeline: This) {
  150. *self = State::default();
  151. self.pipeline = pipeline as usize;
  152. }
  153. /// The title's topology; console-only ones become host lists (see
  154. /// [`crate::primitive`]).
  155. pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
  156. self.topology = topology;
  157. let host = match topology {
  158. RECTANGLES => 4,
  159. TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
  160. once!(topology, "console topology drawn as a triangle list");
  161. 4
  162. }
  163. t => t,
  164. };
  165. // SAFETY: an open list.
  166. unsafe {
  167. list.list
  168. .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
  169. };
  170. }
  171. pub(crate) fn set_pipeline(&mut self, pipeline: This) {
  172. self.pipeline = pipeline as usize;
  173. }
  174. pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
  175. self.heaps = [0; 2];
  176. for &h in heaps {
  177. if !h.is_null() {
  178. let samplers = crate::descriptor::heap(h).samplers();
  179. self.heaps[usize::from(samplers)] = h as usize;
  180. }
  181. }
  182. }
  183. fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
  184. if compute {
  185. &mut self.compute
  186. } else {
  187. &mut self.graphics
  188. }
  189. }
  190. pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
  191. set(self.roots(compute), slot, Root::Table(handle));
  192. }
  193. pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
  194. set(self.roots(compute), slot, Root::View(address));
  195. }
  196. pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
  197. let roots = self.roots(compute);
  198. let s = slot as usize;
  199. if !matches!(roots.get(s), Some(Root::Constants(_))) {
  200. set(roots, slot, Root::Constants(Vec::new()));
  201. }
  202. if let Root::Constants(c) = &mut roots[s] {
  203. let end = offset as usize + values.len();
  204. if c.len() < end {
  205. c.resize(end, 0);
  206. }
  207. c[offset as usize..end].copy_from_slice(values);
  208. }
  209. }
  210. pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
  211. for (i, v) in views.iter().enumerate() {
  212. if let Some(slot) = self.vertex.get_mut(start as usize + i) {
  213. *slot = *v;
  214. }
  215. }
  216. }
  217. pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
  218. for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
  219. *slot = VertexView::default();
  220. }
  221. }
  222. pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
  223. self.index = view.copied().unwrap_or_default();
  224. }
  225. /// Render targets and depth, set on the host list at once.
  226. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
  227. let Some(host) = crate::host::host() else {
  228. return;
  229. };
  230. self.targets.clear();
  231. let mut rtvs = Vec::new();
  232. for &h in handles {
  233. let Some(record) = crate::descriptor::rtv_record(h) else {
  234. once!(
  235. handle = format_args!("{h:#x}"),
  236. "render target without a recorded view"
  237. );
  238. continue;
  239. };
  240. let Some(texture) = crate::resource::host_resource(record.resource) else {
  241. continue;
  242. };
  243. self.targets.push(record.resource as usize);
  244. #[cfg(feature = "diagnostics")]
  245. crate::capture::note_target(record.resource);
  246. rtvs.push(host.rtv(texture, record.desc().as_ref()));
  247. }
  248. self.depth = 0;
  249. let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
  250. let texture = crate::resource::host_resource(record.resource)?;
  251. self.depth = record.resource as usize;
  252. #[cfg(feature = "diagnostics")]
  253. crate::capture::note_target(record.resource);
  254. Some(host.dsv(texture, record.depth_desc().as_ref()))
  255. });
  256. // SAFETY: an open list; the views were just made.
  257. unsafe {
  258. list.list.OMSetRenderTargets(
  259. rtvs.len() as u32,
  260. (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
  261. false,
  262. dsv.as_ref().map(std::ptr::from_ref),
  263. )
  264. };
  265. }
  266. /// The user-data value of a root argument, as translated shaders read
  267. /// it: a table's byte offset in its heap, a constant's value.
  268. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
  269. match (self.roots_ref(compute).get(usize::from(slot)), root) {
  270. (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
  271. Some(heap) => (handle - heap.start) as u32,
  272. None => {
  273. once!(
  274. handle = format_args!("{handle:#x}"),
  275. "descriptor table outside the bound heaps"
  276. );
  277. 0
  278. }
  279. },
  280. (Some(Root::Constants(c)), RootType::Constants) => {
  281. c.get(dword as usize).copied().unwrap_or(0)
  282. }
  283. _ => {
  284. once!(
  285. slot,
  286. ?root,
  287. "a shader reads a root argument the title did not set"
  288. );
  289. 0
  290. }
  291. }
  292. }
  293. /// The bound heap holding `handle`.
  294. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  295. self.heaps
  296. .iter()
  297. .filter(|&&h| h != 0)
  298. .map(|&h| crate::descriptor::heap(h as This))
  299. .find(|h| h.index(handle).is_some())
  300. }
  301. /// Brings the host list up to date for a draw; false if the draw cannot
  302. /// run on the host.
  303. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  304. self.prepare_for(list, indexed, false)
  305. }
  306. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  307. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  308. #[cfg(feature = "diagnostics")]
  309. if crate::pipeline::is_skipped(self.pipeline as This) {
  310. return false;
  311. }
  312. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  313. return false;
  314. };
  315. if p.compute || p.mesh != mesh {
  316. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  317. return false;
  318. }
  319. if !self.bind(list, p, false) {
  320. return false;
  321. }
  322. let l = &list.list;
  323. // Vertex buffers the input layout reads.
  324. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  325. let mut count = 0;
  326. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  327. if p.slots & 1 << slot == 0 {
  328. continue;
  329. }
  330. count = slot + 1;
  331. if v.address == 0 || v.size == 0 {
  332. continue;
  333. }
  334. let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
  335. continue;
  336. };
  337. shadow.refresh(list, v.address, u64::from(v.size));
  338. *view = D3D12_VERTEX_BUFFER_VIEW {
  339. BufferLocation: shadow.gpu(v.address),
  340. SizeInBytes: v.size,
  341. StrideInBytes: v.stride,
  342. };
  343. }
  344. // SAFETY: an open list; the views name live host buffers.
  345. unsafe {
  346. if count > 0 {
  347. l.IASetVertexBuffers(0, Some(&views[..count]));
  348. }
  349. }
  350. if indexed {
  351. let v = self.index;
  352. let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
  353. return false;
  354. };
  355. shadow.refresh(list, v.address, u64::from(v.size));
  356. let view = D3D12_INDEX_BUFFER_VIEW {
  357. BufferLocation: shadow.gpu(v.address),
  358. SizeInBytes: v.size,
  359. Format: DXGI_FORMAT(v.format as i32),
  360. };
  361. // SAFETY: an open list; the view names a live host buffer.
  362. unsafe { l.IASetIndexBuffer(Some(&view)) };
  363. }
  364. const RENDER_TARGET: u32 = 0x4;
  365. const DEPTH_WRITE: u32 = 0x10;
  366. for &t in &self.targets {
  367. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  368. }
  369. if self.depth != 0 {
  370. crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
  371. }
  372. true
  373. }
  374. /// A descriptor a shader reads through a table: its host slot made if
  375. /// it changed, constant data copied, textures made readable.
  376. /// What draws and dispatches share: heaps, our root signature, the
  377. /// pipeline, and per stage the user data, root views and the
  378. /// descriptors its tables hold.
  379. /// False if the draw or dispatch must not run: a table it reads could
  380. /// not be made.
  381. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
  382. let l = &list.list;
  383. // Heaps first: a root signature with directly indexed heaps must be
  384. // set after them.
  385. if self.host_heaps != self.heaps {
  386. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  387. .heaps
  388. .iter()
  389. .filter(|&&h| h != 0)
  390. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  391. .map(|h| Some(h.heap.clone()))
  392. .collect();
  393. heaps.iter().flatten().for_each(|h| list.keep(h));
  394. // SAFETY: an open list and shader-visible heaps.
  395. unsafe { l.SetDescriptorHeaps(&heaps) };
  396. self.host_heaps = self.heaps;
  397. self.host_roots = [0; 2];
  398. }
  399. let root = p.root.as_raw() as usize;
  400. if self.host_roots[usize::from(compute)] != root {
  401. // SAFETY: an open list and a live root signature.
  402. unsafe {
  403. if compute {
  404. l.SetComputeRootSignature(&p.root);
  405. } else {
  406. l.SetGraphicsRootSignature(&p.root);
  407. }
  408. }
  409. self.host_roots[usize::from(compute)] = root;
  410. }
  411. // By host object: a title pipeline released and another made at its
  412. // address is another host pipeline (the list keeps the old one).
  413. if self.host_pipeline != p.pso.as_raw() as usize {
  414. // SAFETY: an open list and a live pipeline.
  415. unsafe { l.SetPipelineState(&p.pso) };
  416. self.host_pipeline = p.pso.as_raw() as usize;
  417. list.used_pipeline(&p.name);
  418. // The title may release the pipeline before it submits the list.
  419. list.keep(&p.pso);
  420. list.keep(&p.root);
  421. }
  422. for stage in &p.stages {
  423. let t = stage.translated();
  424. self.table_failed = false;
  425. let made = self.tables(list, &t.used, compute);
  426. if self.table_failed {
  427. static DROPPED_TABLES: AtomicU64 = AtomicU64::new(0);
  428. let n = DROPPED_TABLES.fetch_add(1, Ordering::Relaxed) + 1;
  429. if n.is_power_of_two() {
  430. tracing::warn!(
  431. dropped = n,
  432. "a draw or dispatch dropped: no dynamic slots for its tables"
  433. );
  434. }
  435. return false;
  436. }
  437. if let Some((param, dwords)) = stage.user_data {
  438. let mut values = vec![0u32; dwords as usize];
  439. for u in &t.host.user_data {
  440. let fresh = made
  441. .iter()
  442. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  443. values[u.index as usize] = match fresh {
  444. Some(&(_, offset)) => offset,
  445. None => self.user_value(compute, u.slot, u.root, u.dword),
  446. };
  447. }
  448. // SAFETY: an open list; `values` covers the parameter.
  449. unsafe {
  450. if compute {
  451. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  452. } else {
  453. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  454. }
  455. }
  456. }
  457. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  458. for &(slot, param) in views {
  459. let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  460. else {
  461. once!(slot, "a shader reads a root view the title did not set");
  462. continue;
  463. };
  464. let Some(gpu) = root_view(list, *address, srv) else {
  465. continue;
  466. };
  467. // SAFETY: an open list; the address is in live memory.
  468. unsafe {
  469. match (compute, srv) {
  470. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  471. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  472. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  473. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  474. }
  475. }
  476. }
  477. }
  478. }
  479. true
  480. }
  481. /// Runs a dispatch on the host.
  482. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
  483. #[cfg(feature = "diagnostics")]
  484. if crate::pipeline::is_skipped(self.pipeline as This) {
  485. DROPPED.fetch_add(1, Ordering::Relaxed);
  486. crate::pipeline::note_drop(self.pipeline as This);
  487. return;
  488. }
  489. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  490. once!(
  491. pipeline = format_args!("{:#x}", self.pipeline),
  492. "a dispatch without a host pipeline dropped"
  493. );
  494. DROPPED.fetch_add(1, Ordering::Relaxed);
  495. #[cfg(feature = "diagnostics")]
  496. crate::pipeline::note_drop(self.pipeline as This);
  497. return;
  498. };
  499. if !p.compute {
  500. once!("a dispatch with a graphics pipeline");
  501. return;
  502. }
  503. if !self.bind(list, p, true) {
  504. DROPPED.fetch_add(1, Ordering::Relaxed);
  505. return;
  506. }
  507. #[cfg(feature = "diagnostics")]
  508. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  509. // SAFETY: an open list with everything set.
  510. unsafe { list.list.Dispatch(x, y, z) };
  511. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  512. }
  513. /// What a draw or dispatch runs, for the device-removed report
  514. /// (diagnostics): the pipeline, then per stage the user data it gets
  515. /// (with the view at that heap index, if one is), the host addresses
  516. /// of its root views and the views its tables name.
  517. #[cfg(feature = "diagnostics")]
  518. fn op_text(&self, kind: String, compute: bool) -> String {
  519. use std::fmt::Write;
  520. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  521. return kind;
  522. };
  523. let mut text = format!("{kind} {}", p.name);
  524. let views = (self.heaps[0] != 0)
  525. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  526. .flatten();
  527. for stage in &p.stages {
  528. let t = stage.translated();
  529. let _ = write!(text, " | {}:", stage.shader.hash);
  530. for u in &t.host.user_data {
  531. let v = self.user_value(compute, u.slot, u.root, u.dword);
  532. let _ = write!(text, " u{}={v:#x}", u.index);
  533. let index = if u.root == RootType::Table { v / 32 } else { v };
  534. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  535. let _ = write!(text, " [heap {index}: {slot}]");
  536. }
  537. }
  538. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
  539. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  540. let host = crate::shadow::find(*address, 1)
  541. .map(|s| (s.gpu(*address), s.left(*address)));
  542. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  543. }
  544. }
  545. }
  546. let _ = write!(text, " tables {:?}", self.reads(compute));
  547. text
  548. }
  549. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  550. /// programs are one-dimensional).
  551. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  552. #[cfg(feature = "diagnostics")]
  553. self.trace("mesh", x, 0);
  554. let ran = self.prepare_for(list, false, true)
  555. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  556. Ok(l6) => {
  557. #[cfg(feature = "diagnostics")]
  558. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  559. // SAFETY: an open list with everything set.
  560. unsafe { l6.DispatchMesh(x, 1, 1) };
  561. DRAWN.fetch_add(1, Ordering::Relaxed);
  562. true
  563. }
  564. Err(_) => false,
  565. };
  566. if !ran {
  567. DROPPED.fetch_add(1, Ordering::Relaxed);
  568. #[cfg(feature = "diagnostics")]
  569. dropped(self.pipeline);
  570. }
  571. }
  572. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  573. if compute {
  574. &self.compute
  575. } else {
  576. &self.graphics
  577. }
  578. }
  579. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  580. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  581. return;
  582. };
  583. let handle = table + u64::from(u.table_offset_dwords) * 4;
  584. let Some(heap) = self.heap_of(handle) else {
  585. return;
  586. };
  587. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  588. return;
  589. };
  590. if let Some(view) = host.mirror(index, handle, true) {
  591. readable(list, u, &view);
  592. }
  593. }
  594. /// The descriptors a shader reads through tables. Tables holding a
  595. /// constant buffer are made afresh for the draw in dynamic slots, with
  596. /// the constant data copied to upload memory when the list is
  597. /// submitted: the host wants constant buffers 256-byte aligned, the
  598. /// console only 16. Returns those tables' new byte offsets by root
  599. /// parameter; the other tables' slots are made from the title's.
  600. ///
  601. /// Within a list, the same table holding the same descriptors is made
  602. /// once: its constant data is copied at submission either way, and the
  603. /// big tables the world binds would otherwise take hundreds of slots per
  604. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  605. fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
  606. let tables = |u: &&UsedResource| u.root == RootType::Table;
  607. let mut fresh: Vec<u8> = used
  608. .iter()
  609. .filter(tables)
  610. .filter(|u| u.kind == ResourceType::Cbv)
  611. .map(|u| u.slot)
  612. .collect();
  613. // Tables reaching past a host heap smaller than the title's (the
  614. // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
  615. // title's slots there have no host slot of their own.
  616. for u in used.iter().filter(tables) {
  617. if fresh.contains(&u.slot) {
  618. continue;
  619. }
  620. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  621. continue;
  622. };
  623. let end = table + u64::from(u.table_offset_dwords) * 4;
  624. let Some(heap) = self.heap_of(table) else {
  625. continue;
  626. };
  627. let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
  628. continue;
  629. };
  630. if index >= host.count() {
  631. fresh.push(u.slot);
  632. }
  633. }
  634. fresh.sort_unstable();
  635. fresh.dedup();
  636. for u in used.iter().filter(tables) {
  637. if !fresh.contains(&u.slot) {
  638. self.table_entry(list, u, compute);
  639. }
  640. }
  641. let mut made = Vec::new();
  642. for slot in fresh {
  643. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  644. continue;
  645. };
  646. let entries: Vec<&UsedResource> = used
  647. .iter()
  648. .filter(tables)
  649. .filter(|u| u.slot == slot)
  650. .collect();
  651. let Some(heap) = self.heap_of(table) else {
  652. continue;
  653. };
  654. let Some(host) = heap.host() else {
  655. continue;
  656. };
  657. let n = entries
  658. .iter()
  659. .map(|u| u.table_offset_dwords / 8 + 1)
  660. .max()
  661. .unwrap_or(1);
  662. // The table and what its entries hold (record words).
  663. let key = {
  664. use std::hash::{Hash, Hasher};
  665. let mut h = std::collections::hash_map::DefaultHasher::new();
  666. for k in 0..n {
  667. let at = table + u64::from(k) * 32;
  668. // SAFETY: a descriptor slot in title memory.
  669. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
  670. }
  671. (table, h.finish())
  672. };
  673. if let Some(&first) = self.fresh_tables.get(&key) {
  674. for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
  675. let handle = table + u64::from(u.table_offset_dwords) * 4;
  676. if let Some(view) = crate::descriptor::view(handle) {
  677. readable(list, u, &view);
  678. }
  679. }
  680. made.push((slot, first * 32));
  681. continue;
  682. }
  683. let Some(first) = host.dynamic(n) else {
  684. // Without its fresh table the shader would read the title's
  685. // slots, which for constant buffer tables hold no constant
  686. // view: a texture or null descriptor read as a buffer gives
  687. // a wild address on AMD and the device is removed (#59).
  688. // The draw or dispatch is dropped instead.
  689. self.table_failed = true;
  690. continue;
  691. };
  692. self.fresh_tables.insert(key, first);
  693. self.dynamic
  694. .push((std::ptr::from_ref(heap) as usize, first, n));
  695. // The whole range: a shader may index past the entries its
  696. // used-resource list names (descriptor arrays).
  697. for k in 0..n {
  698. let index = first + k;
  699. let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
  700. match crate::descriptor::view(table + u64::from(k) * 32) {
  701. Some(View::Constant(address, size)) => {
  702. let Some((gpu, to)) = list.scratch(u64::from(size)) else {
  703. host.make_null(index);
  704. continue;
  705. };
  706. list.defer_fill(to, address as *const u8, size as usize);
  707. host.constant_at(index, gpu, size);
  708. }
  709. Some(view) => {
  710. host.make_at(index, &view);
  711. if let Some(u) = used {
  712. readable(list, u, &view);
  713. }
  714. }
  715. None => {
  716. host.make_null(index);
  717. if used.is_some() {
  718. once!(slot, "a table entry without a view");
  719. }
  720. }
  721. }
  722. }
  723. made.push((slot, first * 32));
  724. }
  725. made
  726. }
  727. /// The first draws, at debug level: what they bind and read
  728. /// (diagnostics builds).
  729. #[cfg(feature = "diagnostics")]
  730. fn trace(&self, kind: &str, count: u32, first: u32) {
  731. static TRACED: AtomicU64 = AtomicU64::new(0);
  732. if !tracing::enabled!(tracing::Level::DEBUG) {
  733. return;
  734. }
  735. let listed = crate::capture::listed(crate::queue::presented() + 1);
  736. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  737. let targets: Vec<String> = self
  738. .targets
  739. .iter()
  740. .filter_map(|&t| crate::resource::host_resource(t as This))
  741. .map(|t| {
  742. // SAFETY: a live resource.
  743. let d = unsafe { t.GetDesc() };
  744. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  745. })
  746. .collect();
  747. let v = self.vertex[0];
  748. let line = format!(
  749. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  750. self.topology,
  751. self.pipeline,
  752. v.address,
  753. v.size,
  754. v.stride,
  755. self.reads(false)
  756. );
  757. if logged {
  758. tracing::debug!("draw {line}");
  759. }
  760. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  761. if frame.len() < 256 {
  762. frame.push(line);
  763. }
  764. }
  765. /// What a draw's shaders read, one line per used resource (diagnostics
  766. /// builds).
  767. #[cfg(feature = "diagnostics")]
  768. fn reads(&self, compute: bool) -> Vec<String> {
  769. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  770. return vec!["no host pipeline".into()];
  771. };
  772. let mut out = Vec::new();
  773. for stage in &p.stages {
  774. let t = stage.translated();
  775. for u in &t.used {
  776. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  777. (RootType::Table, Some(Root::Table(table))) => {
  778. let handle = table + u64::from(u.table_offset_dwords) * 4;
  779. describe(crate::descriptor::view(handle).as_ref())
  780. }
  781. (root, _) => format!("{root:?}"),
  782. };
  783. out.push(format!(
  784. "{} {:?} s{}+{}: {what}",
  785. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  786. ));
  787. }
  788. }
  789. out
  790. }
  791. pub(crate) fn draw(
  792. &mut self,
  793. list: &HostList,
  794. vertices: u32,
  795. instances: u32,
  796. first: u32,
  797. first_instance: u32,
  798. ) {
  799. #[cfg(feature = "diagnostics")]
  800. self.trace("draw", vertices, first);
  801. let rects = self.topology == RECTANGLES;
  802. let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
  803. if ran {
  804. // Rectangles were expanded into their own vertex buffers.
  805. let (count, from) = if rects {
  806. (vertices / 3 * 6, 0)
  807. } else {
  808. (vertices, first)
  809. };
  810. #[cfg(feature = "diagnostics")]
  811. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  812. // SAFETY: an open list with everything set.
  813. unsafe {
  814. list.list
  815. .DrawInstanced(count, instances, from, first_instance)
  816. };
  817. DRAWN.fetch_add(1, Ordering::Relaxed);
  818. }
  819. if !ran {
  820. DROPPED.fetch_add(1, Ordering::Relaxed);
  821. #[cfg(feature = "diagnostics")]
  822. dropped(self.pipeline);
  823. }
  824. }
  825. /// Binds vertex buffers holding the rectangles of vertices `first..first
  826. /// + count` as triangles, made when the list is submitted.
  827. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  828. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  829. return false;
  830. };
  831. let rects = u64::from(count / 3);
  832. for slot in 0..32 {
  833. let elements: Vec<(u32, u32)> = p
  834. .inputs
  835. .iter()
  836. .filter(|e| e.slot == slot && !e.per_instance)
  837. .map(|e| (e.offset, e.format))
  838. .collect();
  839. if elements.is_empty() {
  840. continue;
  841. }
  842. let v = self.vertex[slot as usize];
  843. let stride = u64::from(v.stride);
  844. let from = v.address + u64::from(first) * stride;
  845. if v.address == 0
  846. || stride == 0
  847. || u64::from(first + count) * stride > u64::from(v.size)
  848. || crate::shadow::find(from, rects * 3 * stride).is_none()
  849. {
  850. once!(slot, "rectangle vertices outside their buffer");
  851. return false;
  852. }
  853. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  854. return false;
  855. };
  856. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  857. let n = rects as usize;
  858. list.defer_host(move || {
  859. // SAFETY: the vertices lie in a title buffer (checked when
  860. // recorded) and the scratch memory is the list's.
  861. let (src, dst) = unsafe {
  862. (
  863. std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
  864. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  865. )
  866. };
  867. crate::primitive::expand_rects(src, dst, stride, &elements);
  868. });
  869. let view = D3D12_VERTEX_BUFFER_VIEW {
  870. BufferLocation: gpu,
  871. SizeInBytes: (rects * 6 * stride as u64) as u32,
  872. StrideInBytes: v.stride,
  873. };
  874. // SAFETY: an open list; the view names live scratch memory.
  875. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  876. }
  877. true
  878. }
  879. pub(crate) fn draw_indexed(
  880. &mut self,
  881. list: &HostList,
  882. indices: u32,
  883. instances: u32,
  884. first: u32,
  885. base: i32,
  886. first_instance: u32,
  887. ) {
  888. #[cfg(feature = "diagnostics")]
  889. self.trace("indexed", indices, first);
  890. if self.topology == RECTANGLES {
  891. once!("indexed rectangles not drawn");
  892. }
  893. let ran = self.topology != RECTANGLES && self.prepare(list, true);
  894. if ran {
  895. #[cfg(feature = "diagnostics")]
  896. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  897. // SAFETY: an open list with everything set.
  898. unsafe {
  899. list.list
  900. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  901. };
  902. DRAWN.fetch_add(1, Ordering::Relaxed);
  903. }
  904. if !ran {
  905. DROPPED.fetch_add(1, Ordering::Relaxed);
  906. #[cfg(feature = "diagnostics")]
  907. dropped(self.pipeline);
  908. }
  909. }
  910. }
  911. impl State {
  912. /// Indirect execution of a one-argument signature of `kind` (PC
  913. /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
  914. /// records `stride` bytes apart at title address `arguments`, and the
  915. /// record count at `count` if the title gives one: the GPU reads them
  916. /// from the buffer's host copy, where earlier dispatches may have
  917. /// written them. False if it cannot run on the host.
  918. pub(crate) fn execute_indirect(
  919. &mut self,
  920. list: &HostList,
  921. (kind, stride, max): (u32, u32, u32),
  922. arguments: u64,
  923. count: Option<u64>,
  924. ) -> bool {
  925. // Skip before the argument clamp can mutate the indirect buffer.
  926. #[cfg(feature = "diagnostics")]
  927. if crate::pipeline::is_skipped(self.pipeline as This) {
  928. crate::pipeline::note_drop(self.pipeline as This);
  929. return false;
  930. }
  931. const DRAW: u32 = 0;
  932. const INDEXED: u32 = 1;
  933. const DISPATCH: u32 = 2;
  934. const MESH: u32 = 10;
  935. #[cfg(feature = "diagnostics")]
  936. let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
  937. #[cfg(not(feature = "diagnostics"))]
  938. let why = |_: &str| {};
  939. let len = u64::from(stride) * u64::from(max.max(1));
  940. let Some(args) = crate::shadow::find(arguments, len) else {
  941. why("arguments outside title buffers");
  942. return false;
  943. };
  944. let counter = match count {
  945. Some(at) => match crate::shadow::find(at, 4) {
  946. Some(s) => Some((s, at)),
  947. None => {
  948. why("count outside title buffers");
  949. return false;
  950. }
  951. },
  952. None => None,
  953. };
  954. let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
  955. .then(|| host_signature(kind, stride))
  956. .flatten()
  957. else {
  958. why("no host signature");
  959. return false;
  960. };
  961. args.refresh(list, arguments, len);
  962. if let Some((s, at)) = &counter {
  963. s.refresh(list, *at, 4);
  964. }
  965. // Bounded first: the clamp binds a compute pipeline of its own.
  966. if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) {
  967. why("not bounded (no clamp, or arguments not 4-byte aligned)");
  968. return false;
  969. }
  970. self.host_pipeline = 0;
  971. self.host_roots[1] = 0;
  972. let ran = match kind {
  973. DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED),
  974. MESH => self.prepare_for(list, false, true),
  975. DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) {
  976. Some(p) if p.compute => self.bind(list, p, true),
  977. _ => false,
  978. },
  979. _ => false,
  980. };
  981. if !ran {
  982. crate::indirect::done(list, &args.buffer);
  983. #[cfg(feature = "diagnostics")]
  984. match crate::pipeline::host_pipeline(self.pipeline as This) {
  985. None => crate::pipeline::note_drop(self.pipeline as This),
  986. Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)),
  987. }
  988. return false;
  989. }
  990. #[cfg(feature = "diagnostics")]
  991. list.note_op(|| {
  992. self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
  993. });
  994. // SAFETY: an open list with everything set; the buffers are host
  995. // copies the list keeps alive (refresh), the signature is cached.
  996. unsafe {
  997. list.list.ExecuteIndirect(
  998. &signature,
  999. max,
  1000. &args.buffer,
  1001. args.offset(arguments),
  1002. counter.as_ref().map(|(s, _)| &s.buffer),
  1003. counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
  1004. )
  1005. };
  1006. crate::indirect::done(list, &args.buffer);
  1007. if kind == DISPATCH {
  1008. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  1009. } else {
  1010. DRAWN.fetch_add(1, Ordering::Relaxed);
  1011. }
  1012. true
  1013. }
  1014. }
  1015. /// The host command signature for one argument of `kind` with records
  1016. /// `stride` bytes apart (no root arguments, so no root signature), made
  1017. /// once.
  1018. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
  1019. static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
  1020. std::sync::Mutex::new(Vec::new());
  1021. let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
  1022. if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
  1023. return Some(s.clone());
  1024. }
  1025. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  1026. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  1027. ..Default::default()
  1028. };
  1029. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  1030. ByteStride: stride,
  1031. NumArgumentDescs: 1,
  1032. pArgumentDescs: &argument,
  1033. NodeMask: 0,
  1034. };
  1035. let mut signature: Option<ID3D12CommandSignature> = None;
  1036. // SAFETY: a description of one argument; no root arguments.
  1037. let result = unsafe {
  1038. crate::host::host()?.device.CreateCommandSignature(
  1039. &desc,
  1040. None::<&ID3D12RootSignature>,
  1041. &mut signature,
  1042. )
  1043. };
  1044. if let Err(e) = result {
  1045. once!(error = %e, kind, stride, "host command signature refused");
  1046. return None;
  1047. }
  1048. let signature = signature?;
  1049. made.push(((kind, stride), signature.clone()));
  1050. Some(signature)
  1051. }
  1052. /// Gets what a shader reads or writes through a view ready: buffer data
  1053. /// copied, textures moved to the state they need.
  1054. fn readable(list: &HostList, u: &UsedResource, view: &View) {
  1055. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  1056. const UNORDERED_ACCESS: u32 = 0x8;
  1057. let placed = crate::descriptor::host::placed_texture(view);
  1058. let view = placed.as_ref().unwrap_or(view);
  1059. // Buffer views read title memory: their range is copied at submission;
  1060. // what shaders write through unordered access goes back to it after.
  1061. if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
  1062. && len > 0
  1063. && let Some(shadow) = crate::shadow::find(address, len)
  1064. {
  1065. shadow.refresh(list, address, len);
  1066. if u.kind == ResourceType::Uav {
  1067. shadow.gpu_writes(list, address, len);
  1068. }
  1069. }
  1070. match (view, u.kind) {
  1071. (View::Shader(resource, _), ResourceType::Srv) => {
  1072. if let Some(t) = crate::resource::host_resource(*resource as This)
  1073. && crate::texture::title_written(t)
  1074. {
  1075. crate::texture::upload(list, *resource as This, t);
  1076. }
  1077. crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
  1078. #[cfg(feature = "diagnostics")]
  1079. if let Some(t) = crate::resource::host_resource(*resource as This) {
  1080. // SAFETY: a live resource.
  1081. let d = unsafe { t.GetDesc() };
  1082. if d.Flags.0 & 7 == 0 {
  1083. tracing::debug!(
  1084. resource = format_args!("{resource:#x}"),
  1085. ?d,
  1086. "a shader reads a texture the title fills"
  1087. );
  1088. }
  1089. }
  1090. }
  1091. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  1092. #[cfg(feature = "diagnostics")]
  1093. crate::capture::note_target(*resource as This);
  1094. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  1095. }
  1096. _ => {}
  1097. }
  1098. }
  1099. /// A view in a few words (diagnostics builds).
  1100. #[cfg(feature = "diagnostics")]
  1101. fn describe(view: Option<&View>) -> String {
  1102. let texture = |r: This| {
  1103. crate::resource::host_resource(r).map(|t| {
  1104. // SAFETY: a live resource.
  1105. let d = unsafe { t.GetDesc() };
  1106. format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
  1107. })
  1108. };
  1109. match view {
  1110. None => "no view".into(),
  1111. Some(v @ View::Shader(r, _)) => texture(*r as This)
  1112. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  1113. // A buffer has no host texture: its title range, as for a shader view.
  1114. Some(v @ View::Unordered(r, ..)) => texture(*r as This).map_or_else(
  1115. || format!("uav buffer {:?}", crate::descriptor::host::buffer_range(v)),
  1116. |t| format!("uav {t}"),
  1117. ),
  1118. Some(View::Placed(u, r, d)) => format!(
  1119. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  1120. r[0],
  1121. u64::from(r[4]) | u64::from(r[5]) << 32,
  1122. r[6],
  1123. r[8],
  1124. r[11],
  1125. u64::from(d[10]) | u64::from(d[11]) << 32
  1126. ),
  1127. // The first four values, as a colour rectangle's constants are.
  1128. Some(View::Constant(address, size))
  1129. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  1130. {
  1131. // SAFETY: 16 committed bytes of title memory.
  1132. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  1133. format!("Constant({address:#x}, {size}) {v:?}")
  1134. }
  1135. Some(v) => format!("{v:?}").chars().take(60).collect(),
  1136. }
  1137. }
  1138. /// The console's own primitive topologies.
  1139. const TRIANGLE_FAN: u32 = 6;
  1140. const RECTANGLES: u32 = 17;
  1141. const LINE_LOOP: u32 = 18;
  1142. const QUADS: u32 = 19;
  1143. const QUAD_STRIP: u32 = 20;
  1144. /// Fixed-function state, straight onto the host list.
  1145. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  1146. // SAFETY: an open list.
  1147. unsafe { list.list.RSSetViewports(viewports) };
  1148. }
  1149. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  1150. // SAFETY: an open list.
  1151. unsafe { list.list.RSSetScissorRects(rects) };
  1152. }
  1153. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  1154. // SAFETY: an open list.
  1155. unsafe { list.list.OMSetBlendFactor(factor) };
  1156. }
  1157. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  1158. // SAFETY: an open list.
  1159. unsafe { list.list.OMSetStencilRef(reference) };
  1160. }