draw.rs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. }
  73. impl Drop for State {
  74. fn drop(&mut self) {
  75. for &(heap, first, n) in &self.dynamic {
  76. crate::descriptor::release_dynamic(heap, first, n);
  77. }
  78. }
  79. }
  80. /// Draws recorded on the host GPU since the last frame line.
  81. static DRAWN: AtomicU64 = AtomicU64::new(0);
  82. /// Draws run on the host so far.
  83. pub(crate) fn drawn() -> u64 {
  84. DRAWN.load(Ordering::Relaxed)
  85. }
  86. /// The draws traced since the last present (diagnostics builds, with
  87. /// debug logging for this module): logged when the frame comes out black.
  88. #[cfg(feature = "diagnostics")]
  89. static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  90. /// The draws traced since the last call.
  91. #[cfg(feature = "diagnostics")]
  92. pub(crate) fn take_frame() -> Vec<String> {
  93. std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
  94. }
  95. /// Marks the last traced draw as not run on the host.
  96. #[cfg(feature = "diagnostics")]
  97. fn dropped() {
  98. if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
  99. last.push_str(" DROPPED");
  100. }
  101. }
  102. /// Dispatches run on the host so far.
  103. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  104. pub(crate) fn dispatched() -> u64 {
  105. DISPATCHED.load(Ordering::Relaxed)
  106. }
  107. /// The host address of a root view: its buffer's host copy, or for a
  108. /// constant buffer not 256-byte aligned there (the console needs 16) a
  109. /// copy in upload memory.
  110. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB,
  111. /// other views as 1 MiB (both cut at their buffer's end).
  112. fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
  113. let shadow = crate::shadow::find(address, 1)?;
  114. let len = shadow
  115. .left(address)
  116. .min(if srv { 1 << 20 } else { 1 << 16 });
  117. let gpu = shadow.gpu(address);
  118. if srv || gpu % 256 == 0 {
  119. shadow.refresh(list, address, len);
  120. return Some(gpu);
  121. }
  122. let (gpu, to) = list.scratch(len)?;
  123. list.defer_fill(to, address as *const u8, len as usize);
  124. Some(gpu)
  125. }
  126. macro_rules! once {
  127. ($($arg:tt)*) => {{
  128. static ONCE: std::sync::Once = std::sync::Once::new();
  129. ONCE.call_once(|| tracing::warn!($($arg)*));
  130. }};
  131. }
  132. fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
  133. let slot = slot as usize;
  134. if roots.len() <= slot {
  135. roots.resize(slot + 1, Root::None);
  136. }
  137. roots[slot] = root;
  138. }
  139. impl State {
  140. pub(crate) fn reset(&mut self, pipeline: This) {
  141. *self = State::default();
  142. self.pipeline = pipeline as usize;
  143. }
  144. /// The title's topology; console-only ones become host lists (see
  145. /// [`crate::primitive`]).
  146. pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
  147. self.topology = topology;
  148. let host = match topology {
  149. RECTANGLES => 4,
  150. TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
  151. once!(topology, "console topology drawn as a triangle list");
  152. 4
  153. }
  154. t => t,
  155. };
  156. // SAFETY: an open list.
  157. unsafe {
  158. list.list
  159. .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
  160. };
  161. }
  162. pub(crate) fn set_pipeline(&mut self, pipeline: This) {
  163. self.pipeline = pipeline as usize;
  164. }
  165. pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
  166. self.heaps = [0; 2];
  167. for &h in heaps {
  168. if !h.is_null() {
  169. let samplers = crate::descriptor::heap(h).samplers();
  170. self.heaps[usize::from(samplers)] = h as usize;
  171. }
  172. }
  173. }
  174. fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
  175. if compute {
  176. &mut self.compute
  177. } else {
  178. &mut self.graphics
  179. }
  180. }
  181. pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
  182. set(self.roots(compute), slot, Root::Table(handle));
  183. }
  184. pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
  185. set(self.roots(compute), slot, Root::View(address));
  186. }
  187. pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
  188. let roots = self.roots(compute);
  189. let s = slot as usize;
  190. if !matches!(roots.get(s), Some(Root::Constants(_))) {
  191. set(roots, slot, Root::Constants(Vec::new()));
  192. }
  193. if let Root::Constants(c) = &mut roots[s] {
  194. let end = offset as usize + values.len();
  195. if c.len() < end {
  196. c.resize(end, 0);
  197. }
  198. c[offset as usize..end].copy_from_slice(values);
  199. }
  200. }
  201. pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
  202. for (i, v) in views.iter().enumerate() {
  203. if let Some(slot) = self.vertex.get_mut(start as usize + i) {
  204. *slot = *v;
  205. }
  206. }
  207. }
  208. pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
  209. self.index = view.copied().unwrap_or_default();
  210. }
  211. /// Render targets and depth, set on the host list at once.
  212. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
  213. let Some(host) = crate::host::host() else {
  214. return;
  215. };
  216. self.targets.clear();
  217. let mut rtvs = Vec::new();
  218. for &h in handles {
  219. let Some(record) = crate::descriptor::rtv_record(h) else {
  220. once!(
  221. handle = format_args!("{h:#x}"),
  222. "render target without a recorded view"
  223. );
  224. continue;
  225. };
  226. let Some(texture) = crate::resource::host_resource(record.resource) else {
  227. continue;
  228. };
  229. self.targets.push(record.resource as usize);
  230. #[cfg(feature = "diagnostics")]
  231. crate::capture::note_target(record.resource);
  232. rtvs.push(host.rtv(texture, record.desc().as_ref()));
  233. }
  234. self.depth = 0;
  235. let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
  236. let texture = crate::resource::host_resource(record.resource)?;
  237. self.depth = record.resource as usize;
  238. #[cfg(feature = "diagnostics")]
  239. crate::capture::note_target(record.resource);
  240. Some(host.dsv(texture, record.depth_desc().as_ref()))
  241. });
  242. // SAFETY: an open list; the views were just made.
  243. unsafe {
  244. list.list.OMSetRenderTargets(
  245. rtvs.len() as u32,
  246. (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
  247. false,
  248. dsv.as_ref().map(std::ptr::from_ref),
  249. )
  250. };
  251. }
  252. /// The user-data value of a root argument, as translated shaders read
  253. /// it: a table's byte offset in its heap, a constant's value.
  254. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
  255. match (self.roots_ref(compute).get(usize::from(slot)), root) {
  256. (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
  257. Some(heap) => (handle - heap.start) as u32,
  258. None => {
  259. once!(
  260. handle = format_args!("{handle:#x}"),
  261. "descriptor table outside the bound heaps"
  262. );
  263. 0
  264. }
  265. },
  266. (Some(Root::Constants(c)), RootType::Constants) => {
  267. c.get(dword as usize).copied().unwrap_or(0)
  268. }
  269. _ => {
  270. once!(
  271. slot,
  272. ?root,
  273. "a shader reads a root argument the title did not set"
  274. );
  275. 0
  276. }
  277. }
  278. }
  279. /// The bound heap holding `handle`.
  280. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  281. self.heaps
  282. .iter()
  283. .filter(|&&h| h != 0)
  284. .map(|&h| crate::descriptor::heap(h as This))
  285. .find(|h| h.index(handle).is_some())
  286. }
  287. /// Brings the host list up to date for a draw; false if the draw cannot
  288. /// run on the host.
  289. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  290. self.prepare_for(list, indexed, false)
  291. }
  292. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  293. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  294. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  295. return false;
  296. };
  297. if p.compute || p.mesh != mesh {
  298. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  299. return false;
  300. }
  301. self.bind(list, p, false);
  302. let l = &list.list;
  303. // Vertex buffers the input layout reads.
  304. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  305. let mut count = 0;
  306. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  307. if p.slots & 1 << slot == 0 {
  308. continue;
  309. }
  310. count = slot + 1;
  311. if v.address == 0 || v.size == 0 {
  312. continue;
  313. }
  314. let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
  315. continue;
  316. };
  317. shadow.refresh(list, v.address, u64::from(v.size));
  318. *view = D3D12_VERTEX_BUFFER_VIEW {
  319. BufferLocation: shadow.gpu(v.address),
  320. SizeInBytes: v.size,
  321. StrideInBytes: v.stride,
  322. };
  323. }
  324. // SAFETY: an open list; the views name live host buffers.
  325. unsafe {
  326. if count > 0 {
  327. l.IASetVertexBuffers(0, Some(&views[..count]));
  328. }
  329. }
  330. if indexed {
  331. let v = self.index;
  332. let Some(shadow) = crate::shadow::find(v.address, u64::from(v.size)) else {
  333. return false;
  334. };
  335. shadow.refresh(list, v.address, u64::from(v.size));
  336. let view = D3D12_INDEX_BUFFER_VIEW {
  337. BufferLocation: shadow.gpu(v.address),
  338. SizeInBytes: v.size,
  339. Format: DXGI_FORMAT(v.format as i32),
  340. };
  341. // SAFETY: an open list; the view names a live host buffer.
  342. unsafe { l.IASetIndexBuffer(Some(&view)) };
  343. }
  344. const RENDER_TARGET: u32 = 0x4;
  345. const DEPTH_WRITE: u32 = 0x10;
  346. for &t in &self.targets {
  347. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  348. }
  349. if self.depth != 0 {
  350. crate::list::ensure_state(list, self.depth as This, DEPTH_WRITE);
  351. }
  352. true
  353. }
  354. /// A descriptor a shader reads through a table: its host slot made if
  355. /// it changed, constant data copied, textures made readable.
  356. /// What draws and dispatches share: heaps, our root signature, the
  357. /// pipeline, and per stage the user data, root views and the
  358. /// descriptors its tables hold.
  359. fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
  360. let l = &list.list;
  361. // Heaps first: a root signature with directly indexed heaps must be
  362. // set after them.
  363. if self.host_heaps != self.heaps {
  364. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  365. .heaps
  366. .iter()
  367. .filter(|&&h| h != 0)
  368. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  369. .map(|h| Some(h.heap.clone()))
  370. .collect();
  371. // SAFETY: an open list and shader-visible heaps.
  372. unsafe { l.SetDescriptorHeaps(&heaps) };
  373. self.host_heaps = self.heaps;
  374. self.host_roots = [0; 2];
  375. }
  376. let root = p.root.as_raw() as usize;
  377. if self.host_roots[usize::from(compute)] != root {
  378. // SAFETY: an open list and a live root signature.
  379. unsafe {
  380. if compute {
  381. l.SetComputeRootSignature(&p.root);
  382. } else {
  383. l.SetGraphicsRootSignature(&p.root);
  384. }
  385. }
  386. self.host_roots[usize::from(compute)] = root;
  387. }
  388. if self.host_pipeline != self.pipeline {
  389. // SAFETY: an open list and a live pipeline.
  390. unsafe { l.SetPipelineState(&p.pso) };
  391. self.host_pipeline = self.pipeline;
  392. list.used_pipeline(&p.name);
  393. }
  394. for stage in &p.stages {
  395. let t = stage.translated();
  396. let made = self.tables(list, &t.used, compute);
  397. if let Some((param, dwords)) = stage.user_data {
  398. let mut values = vec![0u32; dwords as usize];
  399. for u in &t.host.user_data {
  400. let fresh = made
  401. .iter()
  402. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  403. values[u.index as usize] = match fresh {
  404. Some(&(_, offset)) => offset,
  405. None => self.user_value(compute, u.slot, u.root, u.dword),
  406. };
  407. }
  408. // SAFETY: an open list; `values` covers the parameter.
  409. unsafe {
  410. if compute {
  411. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  412. } else {
  413. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  414. }
  415. }
  416. }
  417. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  418. for &(slot, param) in views {
  419. let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  420. else {
  421. once!(slot, "a shader reads a root view the title did not set");
  422. continue;
  423. };
  424. let Some(gpu) = root_view(list, *address, srv) else {
  425. continue;
  426. };
  427. // SAFETY: an open list; the address is in live memory.
  428. unsafe {
  429. match (compute, srv) {
  430. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  431. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  432. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  433. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  434. }
  435. }
  436. }
  437. }
  438. }
  439. }
  440. /// Runs a dispatch on the host.
  441. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
  442. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  443. once!(
  444. pipeline = format_args!("{:#x}", self.pipeline),
  445. "a dispatch without a host pipeline dropped"
  446. );
  447. return;
  448. };
  449. if !p.compute {
  450. once!("a dispatch with a graphics pipeline");
  451. return;
  452. }
  453. self.bind(list, p, true);
  454. #[cfg(feature = "diagnostics")]
  455. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  456. // SAFETY: an open list with everything set.
  457. unsafe { list.list.Dispatch(x, y, z) };
  458. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  459. }
  460. /// What a draw or dispatch runs, for the device-removed report
  461. /// (diagnostics): the pipeline, then per stage the user data it gets
  462. /// (with the view at that heap index, if one is), the host addresses
  463. /// of its root views and the views its tables name.
  464. #[cfg(feature = "diagnostics")]
  465. fn op_text(&self, kind: String, compute: bool) -> String {
  466. use std::fmt::Write;
  467. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  468. return kind;
  469. };
  470. let mut text = format!("{kind} {}", p.name);
  471. let views = (self.heaps[0] != 0)
  472. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  473. .flatten();
  474. for stage in &p.stages {
  475. let t = stage.translated();
  476. let _ = write!(text, " | {}:", stage.shader.hash);
  477. for u in &t.host.user_data {
  478. let v = self.user_value(compute, u.slot, u.root, u.dword);
  479. let _ = write!(text, " u{}={v:#x}", u.index);
  480. let index = if u.root == RootType::Table { v / 32 } else { v };
  481. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  482. let _ = write!(text, " [heap {index}: {slot}]");
  483. }
  484. }
  485. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs) {
  486. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  487. let host = crate::shadow::find(*address, 1)
  488. .map(|s| (s.gpu(*address), s.left(*address)));
  489. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  490. }
  491. }
  492. }
  493. let _ = write!(text, " tables {:?}", self.reads(compute));
  494. text
  495. }
  496. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  497. /// programs are one-dimensional).
  498. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  499. #[cfg(feature = "diagnostics")]
  500. self.trace("mesh", x, 0);
  501. let ran = self.prepare_for(list, false, true)
  502. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  503. Ok(l6) => {
  504. #[cfg(feature = "diagnostics")]
  505. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  506. // SAFETY: an open list with everything set.
  507. unsafe { l6.DispatchMesh(x, 1, 1) };
  508. DRAWN.fetch_add(1, Ordering::Relaxed);
  509. true
  510. }
  511. Err(_) => false,
  512. };
  513. #[cfg(feature = "diagnostics")]
  514. if !ran {
  515. dropped();
  516. }
  517. #[cfg(not(feature = "diagnostics"))]
  518. let _ = ran;
  519. }
  520. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  521. if compute {
  522. &self.compute
  523. } else {
  524. &self.graphics
  525. }
  526. }
  527. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  528. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  529. return;
  530. };
  531. let handle = table + u64::from(u.table_offset_dwords) * 4;
  532. let Some(heap) = self.heap_of(handle) else {
  533. return;
  534. };
  535. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  536. return;
  537. };
  538. if let Some(view) = host.mirror(index, handle, true) {
  539. readable(list, u, &view);
  540. }
  541. }
  542. /// The descriptors a shader reads through tables. Tables holding a
  543. /// constant buffer are made afresh for the draw in dynamic slots, with
  544. /// the constant data copied to upload memory when the list is
  545. /// submitted: the host wants constant buffers 256-byte aligned, the
  546. /// console only 16. Returns those tables' new byte offsets by root
  547. /// parameter; the other tables' slots are made from the title's.
  548. ///
  549. /// Within a list, the same table holding the same descriptors is made
  550. /// once: its constant data is copied at submission either way, and the
  551. /// big tables the world binds would otherwise take hundreds of slots per
  552. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  553. fn tables(&mut self, list: &HostList, used: &[UsedResource], compute: bool) -> Vec<(u8, u32)> {
  554. let tables = |u: &&UsedResource| u.root == RootType::Table;
  555. let mut fresh: Vec<u8> = used
  556. .iter()
  557. .filter(tables)
  558. .filter(|u| u.kind == ResourceType::Cbv)
  559. .map(|u| u.slot)
  560. .collect();
  561. fresh.sort_unstable();
  562. fresh.dedup();
  563. for u in used.iter().filter(tables) {
  564. if !fresh.contains(&u.slot) {
  565. self.table_entry(list, u, compute);
  566. }
  567. }
  568. let mut made = Vec::new();
  569. for slot in fresh {
  570. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  571. continue;
  572. };
  573. let entries: Vec<&UsedResource> = used
  574. .iter()
  575. .filter(tables)
  576. .filter(|u| u.slot == slot)
  577. .collect();
  578. let Some(heap) = self.heap_of(table) else {
  579. continue;
  580. };
  581. let Some(host) = heap.host() else {
  582. continue;
  583. };
  584. let n = entries
  585. .iter()
  586. .map(|u| u.table_offset_dwords / 8 + 1)
  587. .max()
  588. .unwrap_or(1);
  589. // The table and what its entries hold (record words).
  590. let key = {
  591. use std::hash::{Hash, Hasher};
  592. let mut h = std::collections::hash_map::DefaultHasher::new();
  593. for k in 0..n {
  594. let at = table + u64::from(k) * 32;
  595. // SAFETY: a descriptor slot in title memory.
  596. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
  597. }
  598. (table, h.finish())
  599. };
  600. if let Some(&first) = self.fresh_tables.get(&key) {
  601. for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
  602. let handle = table + u64::from(u.table_offset_dwords) * 4;
  603. if let Some(view) = crate::descriptor::view(handle) {
  604. readable(list, u, &view);
  605. }
  606. }
  607. made.push((slot, first * 32));
  608. continue;
  609. }
  610. let Some(first) = host.dynamic(n) else {
  611. continue;
  612. };
  613. self.fresh_tables.insert(key, first);
  614. self.dynamic
  615. .push((std::ptr::from_ref(heap) as usize, first, n));
  616. // The whole range: a shader may index past the entries its
  617. // used-resource list names (descriptor arrays).
  618. for k in 0..n {
  619. let index = first + k;
  620. let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
  621. match crate::descriptor::view(table + u64::from(k) * 32) {
  622. Some(View::Constant(address, size)) => {
  623. let Some((gpu, to)) = list.scratch(u64::from(size)) else {
  624. host.make_null(index);
  625. continue;
  626. };
  627. list.defer_fill(to, address as *const u8, size as usize);
  628. host.constant_at(index, gpu, size);
  629. }
  630. Some(view) => {
  631. host.make_at(index, &view);
  632. if let Some(u) = used {
  633. readable(list, u, &view);
  634. }
  635. }
  636. None => {
  637. host.make_null(index);
  638. if used.is_some() {
  639. once!(slot, "a table entry without a view");
  640. }
  641. }
  642. }
  643. }
  644. made.push((slot, first * 32));
  645. }
  646. made
  647. }
  648. /// The first draws, at debug level: what they bind and read
  649. /// (diagnostics builds).
  650. #[cfg(feature = "diagnostics")]
  651. fn trace(&self, kind: &str, count: u32, first: u32) {
  652. static TRACED: AtomicU64 = AtomicU64::new(0);
  653. if !tracing::enabled!(tracing::Level::DEBUG) {
  654. return;
  655. }
  656. let listed = crate::capture::listed(crate::queue::presented() + 1);
  657. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  658. let targets: Vec<String> = self
  659. .targets
  660. .iter()
  661. .filter_map(|&t| crate::resource::host_resource(t as This))
  662. .map(|t| {
  663. // SAFETY: a live resource.
  664. let d = unsafe { t.GetDesc() };
  665. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  666. })
  667. .collect();
  668. let v = self.vertex[0];
  669. let line = format!(
  670. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  671. self.topology,
  672. self.pipeline,
  673. v.address,
  674. v.size,
  675. v.stride,
  676. self.reads(false)
  677. );
  678. if logged {
  679. tracing::debug!("draw {line}");
  680. }
  681. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  682. if frame.len() < 256 {
  683. frame.push(line);
  684. }
  685. }
  686. /// What a draw's shaders read, one line per used resource (diagnostics
  687. /// builds).
  688. #[cfg(feature = "diagnostics")]
  689. fn reads(&self, compute: bool) -> Vec<String> {
  690. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  691. return vec!["no host pipeline".into()];
  692. };
  693. let mut out = Vec::new();
  694. for stage in &p.stages {
  695. let t = stage.translated();
  696. for u in &t.used {
  697. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  698. (RootType::Table, Some(Root::Table(table))) => {
  699. let handle = table + u64::from(u.table_offset_dwords) * 4;
  700. describe(crate::descriptor::view(handle).as_ref())
  701. }
  702. (root, _) => format!("{root:?}"),
  703. };
  704. out.push(format!(
  705. "{} {:?} s{}+{}: {what}",
  706. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  707. ));
  708. }
  709. }
  710. out
  711. }
  712. pub(crate) fn draw(
  713. &mut self,
  714. list: &HostList,
  715. vertices: u32,
  716. instances: u32,
  717. first: u32,
  718. first_instance: u32,
  719. ) {
  720. #[cfg(feature = "diagnostics")]
  721. self.trace("draw", vertices, first);
  722. let rects = self.topology == RECTANGLES;
  723. let ran = self.prepare(list, false) && (!rects || self.rectangles(list, vertices, first));
  724. if ran {
  725. // Rectangles were expanded into their own vertex buffers.
  726. let (count, from) = if rects {
  727. (vertices / 3 * 6, 0)
  728. } else {
  729. (vertices, first)
  730. };
  731. #[cfg(feature = "diagnostics")]
  732. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  733. // SAFETY: an open list with everything set.
  734. unsafe {
  735. list.list
  736. .DrawInstanced(count, instances, from, first_instance)
  737. };
  738. DRAWN.fetch_add(1, Ordering::Relaxed);
  739. }
  740. #[cfg(feature = "diagnostics")]
  741. if !ran {
  742. dropped();
  743. }
  744. }
  745. /// Binds vertex buffers holding the rectangles of vertices `first..first
  746. /// + count` as triangles, made when the list is submitted.
  747. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  748. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  749. return false;
  750. };
  751. let rects = u64::from(count / 3);
  752. for slot in 0..32 {
  753. let elements: Vec<(u32, u32)> = p
  754. .inputs
  755. .iter()
  756. .filter(|e| e.slot == slot && !e.per_instance)
  757. .map(|e| (e.offset, e.format))
  758. .collect();
  759. if elements.is_empty() {
  760. continue;
  761. }
  762. let v = self.vertex[slot as usize];
  763. let stride = u64::from(v.stride);
  764. let from = v.address + u64::from(first) * stride;
  765. if v.address == 0
  766. || stride == 0
  767. || u64::from(first + count) * stride > u64::from(v.size)
  768. || crate::shadow::find(from, rects * 3 * stride).is_none()
  769. {
  770. once!(slot, "rectangle vertices outside their buffer");
  771. return false;
  772. }
  773. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  774. return false;
  775. };
  776. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  777. let n = rects as usize;
  778. list.defer_host(move || {
  779. // SAFETY: the vertices lie in a title buffer (checked when
  780. // recorded) and the scratch memory is the list's.
  781. let (src, dst) = unsafe {
  782. (
  783. std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
  784. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  785. )
  786. };
  787. crate::primitive::expand_rects(src, dst, stride, &elements);
  788. });
  789. let view = D3D12_VERTEX_BUFFER_VIEW {
  790. BufferLocation: gpu,
  791. SizeInBytes: (rects * 6 * stride as u64) as u32,
  792. StrideInBytes: v.stride,
  793. };
  794. // SAFETY: an open list; the view names live scratch memory.
  795. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  796. }
  797. true
  798. }
  799. pub(crate) fn draw_indexed(
  800. &mut self,
  801. list: &HostList,
  802. indices: u32,
  803. instances: u32,
  804. first: u32,
  805. base: i32,
  806. first_instance: u32,
  807. ) {
  808. #[cfg(feature = "diagnostics")]
  809. self.trace("indexed", indices, first);
  810. if self.topology == RECTANGLES {
  811. once!("indexed rectangles not drawn");
  812. }
  813. let ran = self.topology != RECTANGLES && self.prepare(list, true);
  814. if ran {
  815. #[cfg(feature = "diagnostics")]
  816. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  817. // SAFETY: an open list with everything set.
  818. unsafe {
  819. list.list
  820. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  821. };
  822. DRAWN.fetch_add(1, Ordering::Relaxed);
  823. }
  824. #[cfg(feature = "diagnostics")]
  825. if !ran {
  826. dropped();
  827. }
  828. }
  829. }
  830. /// Gets what a shader reads or writes through a view ready: buffer data
  831. /// copied, textures moved to the state they need.
  832. fn readable(list: &HostList, u: &UsedResource, view: &View) {
  833. const SHADER_RESOURCE: u32 = 0x40 | 0x80;
  834. const UNORDERED_ACCESS: u32 = 0x8;
  835. let placed = crate::descriptor::host::placed_texture(view);
  836. let view = placed.as_ref().unwrap_or(view);
  837. // Buffer views read title memory: their range is copied at submission;
  838. // what shaders write through unordered access goes back to it after.
  839. if let Some((address, len)) = crate::descriptor::host::buffer_range(view)
  840. && len > 0
  841. && let Some(shadow) = crate::shadow::find(address, len)
  842. {
  843. shadow.refresh(list, address, len);
  844. if u.kind == ResourceType::Uav {
  845. shadow.gpu_writes(list, address, len);
  846. }
  847. }
  848. match (view, u.kind) {
  849. (View::Shader(resource, _), ResourceType::Srv) => {
  850. if let Some(t) = crate::resource::host_resource(*resource as This)
  851. && crate::texture::title_written(t)
  852. {
  853. crate::texture::upload(list, *resource as This, t);
  854. }
  855. crate::list::ensure_state(list, *resource as This, SHADER_RESOURCE);
  856. #[cfg(feature = "diagnostics")]
  857. if let Some(t) = crate::resource::host_resource(*resource as This) {
  858. // SAFETY: a live resource.
  859. let d = unsafe { t.GetDesc() };
  860. if d.Flags.0 & 7 == 0 {
  861. tracing::debug!(
  862. resource = format_args!("{resource:#x}"),
  863. ?d,
  864. "a shader reads a texture the title fills"
  865. );
  866. }
  867. }
  868. }
  869. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  870. #[cfg(feature = "diagnostics")]
  871. crate::capture::note_target(*resource as This);
  872. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  873. }
  874. _ => {}
  875. }
  876. }
  877. /// A view in a few words (diagnostics builds).
  878. #[cfg(feature = "diagnostics")]
  879. fn describe(view: Option<&View>) -> String {
  880. let texture = |r: This| {
  881. crate::resource::host_resource(r).map(|t| {
  882. // SAFETY: a live resource.
  883. let d = unsafe { t.GetDesc() };
  884. format!("{}x{} f{} flags {:#x}", d.Width, d.Height, d.Format.0, d.Flags.0)
  885. })
  886. };
  887. match view {
  888. None => "no view".into(),
  889. Some(v @ View::Shader(r, _)) => texture(*r as This)
  890. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  891. Some(View::Unordered(r, ..)) => format!("uav {:?}", texture(*r as This)),
  892. Some(View::Placed(u, r, d)) => format!(
  893. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  894. r[0],
  895. u64::from(r[4]) | u64::from(r[5]) << 32,
  896. r[6],
  897. r[8],
  898. r[11],
  899. u64::from(d[10]) | u64::from(d[11]) << 32
  900. ),
  901. // The first four values, as a colour rectangle's constants are.
  902. Some(View::Constant(address, size))
  903. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  904. {
  905. // SAFETY: 16 committed bytes of title memory.
  906. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  907. format!("Constant({address:#x}, {size}) {v:?}")
  908. }
  909. Some(v) => format!("{v:?}").chars().take(60).collect(),
  910. }
  911. }
  912. /// The console's own primitive topologies.
  913. const TRIANGLE_FAN: u32 = 6;
  914. const RECTANGLES: u32 = 17;
  915. const LINE_LOOP: u32 = 18;
  916. const QUADS: u32 = 19;
  917. const QUAD_STRIP: u32 = 20;
  918. /// Fixed-function state, straight onto the host list.
  919. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  920. // SAFETY: an open list.
  921. unsafe { list.list.RSSetViewports(viewports) };
  922. }
  923. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  924. // SAFETY: an open list.
  925. unsafe { list.list.RSSetScissorRects(rects) };
  926. }
  927. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  928. // SAFETY: an open list.
  929. unsafe { list.list.OMSetBlendFactor(factor) };
  930. }
  931. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  932. // SAFETY: an open list.
  933. unsafe { list.list.OMSetStencilRef(reference) };
  934. }