texture.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. //! Texture contents the title writes itself (decision 0007, "Texture
  2. //! memory"): streamed pages, layout-library copies, movie frames, glyph
  3. //! atlases. Such a texture lives in console memory in its tiled layout;
  4. //! before a submission samples its host copy, the memory is detiled into a
  5. //! staging buffer when its content changed, and the staging buffer is
  6. //! copied into the host texture.
  7. //!
  8. //! "Changed" means a page of the memory was written since the last detiling
  9. //! ([`crate::watch`]), in write-watched memory; in physical-page views,
  10. //! which cannot be watched, a content hash of the whole memory at every
  11. //! submission that samples it.
  12. //!
  13. //! shortcut: a change detiles the whole texture, not the pages written.
  14. //! Only textures read through descriptor tables are brought up to date
  15. //! (directly indexed views are not known per draw); plane 0 is uploaded
  16. //! (every mip and array slice), depth and stencil planes are not.
  17. use std::collections::HashMap;
  18. use std::sync::{Arc, Mutex};
  19. use windows::Win32::Graphics::Direct3D12::*;
  20. use crate::host::{HostList, host};
  21. use crate::object::This;
  22. macro_rules! once {
  23. ($($arg:tt)*) => {{
  24. static ONCE: std::sync::Once = std::sync::Once::new();
  25. ONCE.call_once(|| tracing::warn!($($arg)*));
  26. }};
  27. }
  28. /// A texture's upload state: the staging buffer laid out as the host
  29. /// texture's subresources, and what was last detiled.
  30. struct Staging {
  31. buffer: ID3D12Resource,
  32. /// Its bytes.
  33. #[cfg(feature = "diagnostics")]
  34. size: u64,
  35. data: *mut u8,
  36. footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
  37. rows: Vec<u32>,
  38. layout: victory_formats::texture::Layout,
  39. /// Mips per array slice.
  40. mips: u32,
  41. memory: *const u8,
  42. last: Mutex<Last>,
  43. }
  44. /// What a texture's staging buffer holds: the hash of the memory detiled
  45. /// (memory not watched), or the write-watch asking it was detiled after,
  46. /// with room to read the memory into.
  47. #[derive(Default)]
  48. struct Last {
  49. hash: Option<blake3::Hash>,
  50. asked: u64,
  51. read: Vec<u8>,
  52. }
  53. // SAFETY: the staging mapping is written only at submission, under
  54. // `last`'s lock; the title memory is only read.
  55. unsafe impl Send for Staging {}
  56. // SAFETY: as above.
  57. unsafe impl Sync for Staging {}
  58. static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
  59. /// Textures the host GPU wrote by a copy or resolve: their contents are on
  60. /// the host, not in title memory, which stays as it was.
  61. static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
  62. /// A host copy or resolve writes `resource`.
  63. pub(crate) fn host_written(resource: This) {
  64. let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  65. set.get_or_insert_with(Default::default)
  66. .insert(resource as usize);
  67. }
  68. /// The title released a resource.
  69. pub(crate) fn forget(resource: usize) {
  70. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  71. if let Some(map) = map.as_mut() {
  72. map.remove(&resource);
  73. }
  74. let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  75. if let Some(set) = set.as_mut() {
  76. set.remove(&resource);
  77. }
  78. }
  79. /// Whether `resource`'s host copy takes its contents from title memory:
  80. /// a texture the host GPU does not render to or write.
  81. pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
  82. const TARGET_DEPTH_UNORDERED: i32 = 0x7;
  83. // SAFETY: a live resource.
  84. unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0
  85. }
  86. /// Records, once per list, the copy of `resource`'s staging buffer into
  87. /// its host copy, and the detiling that refreshes the staging buffer at
  88. /// submission if the memory changed. Leaves the texture in the copy
  89. /// destination state.
  90. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
  91. let host_written = HOST_WRITTEN
  92. .lock()
  93. .unwrap_or_else(|e| e.into_inner())
  94. .as_ref()
  95. .is_some_and(|set| set.contains(&(resource as usize)));
  96. // shortcut: a texture the host copied into keeps the host's contents
  97. // even if the title later writes its memory too.
  98. if host_written || !list.first_use(resource as usize) {
  99. return;
  100. }
  101. let Some(staging) = staging(resource, texture) else {
  102. return;
  103. };
  104. const COPY_DEST: u32 = 0x400;
  105. crate::list::ensure_state(list, resource, COPY_DEST);
  106. // The staging buffer lives as long as `staging`, which the deferred
  107. // refresh below holds until the list is reset.
  108. for (i, footprint) in staging.footprints.iter().enumerate() {
  109. #[cfg(feature = "diagnostics")]
  110. {
  111. let f = footprint.Footprint;
  112. // SAFETY: live resources.
  113. let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
  114. let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
  115. list.note_read(
  116. || {
  117. format!(
  118. "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
  119. d.Width,
  120. d.Height,
  121. d.DepthOrArraySize,
  122. d.Format.0,
  123. d.MipLevels,
  124. staging.footprints.len(),
  125. staging.size,
  126. footprint.Offset,
  127. f.Width,
  128. f.Height,
  129. f.Depth,
  130. f.RowPitch
  131. )
  132. },
  133. (gpu + footprint.Offset, len),
  134. );
  135. }
  136. let to = D3D12_TEXTURE_COPY_LOCATION {
  137. // SAFETY: a borrowed pointer the location never releases.
  138. pResource: unsafe { std::mem::transmute_copy(texture) },
  139. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  140. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  141. SubresourceIndex: i as u32,
  142. },
  143. };
  144. let from = D3D12_TEXTURE_COPY_LOCATION {
  145. // SAFETY: as above.
  146. pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
  147. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  148. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  149. PlacedFootprint: *footprint,
  150. },
  151. };
  152. // SAFETY: an open list; both locations name live resources.
  153. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  154. }
  155. list.defer_host(move || staging.refresh());
  156. }
  157. impl Staging {
  158. /// Detiles the texture memory into the staging buffer if it changed
  159. /// since the last time (and is mapped at all).
  160. fn refresh(&self) {
  161. use std::sync::atomic::Ordering::Relaxed;
  162. let started = std::time::Instant::now();
  163. let read = self.refresh_now();
  164. let preparing = &crate::host::PREPARING;
  165. preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
  166. preparing[3].fetch_add(read as u64, Relaxed);
  167. }
  168. /// Returns the bytes of title memory read.
  169. fn refresh_now(&self) -> usize {
  170. let size = self.layout.size as usize;
  171. let start = self.memory as usize;
  172. let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
  173. let last = &mut *last;
  174. if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
  175. if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
  176. return 0;
  177. }
  178. last.asked = now;
  179. // Read through the copy, which stands unmapped pages: memory of
  180. // big pools is too slow to ask page by page.
  181. last.read.resize(size, 0);
  182. crate::host::copy_mapped(last.read.as_mut_ptr(), self.memory, size, false);
  183. self.detile(&last.read);
  184. #[cfg(feature = "diagnostics")]
  185. crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
  186. return size;
  187. }
  188. if !committed(self.memory, size) {
  189. #[cfg(feature = "diagnostics")]
  190. tracing::debug!(
  191. memory = ?self.memory,
  192. size,
  193. desc = ?self.layout.desc,
  194. "a sampled texture's memory is not committed"
  195. );
  196. return 0;
  197. }
  198. // SAFETY: committed memory of the texture's layout size.
  199. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
  200. let hash = blake3::hash(tiled);
  201. #[cfg(feature = "diagnostics")]
  202. crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
  203. if last.hash == Some(hash) {
  204. return size;
  205. }
  206. last.hash = Some(hash);
  207. self.detile(tiled);
  208. #[cfg(feature = "diagnostics")]
  209. crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
  210. size
  211. }
  212. /// Detiles `tiled` (the texture's memory) into the staging buffer.
  213. fn detile(&self, tiled: &[u8]) {
  214. #[cfg(feature = "diagnostics")]
  215. if tiled.iter().all(|&b| b == 0) {
  216. tracing::debug!(
  217. memory = ?self.memory,
  218. desc = ?self.layout.desc,
  219. "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
  220. );
  221. }
  222. for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() {
  223. let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips);
  224. let f = footprint.Footprint;
  225. let pitch = f.RowPitch as usize;
  226. let len = pitch * rows as usize * f.Depth as usize;
  227. // SAFETY: the subresource's part of the mapped staging buffer.
  228. let linear = unsafe {
  229. std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
  230. };
  231. if let Err(e) =
  232. self.layout
  233. .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
  234. {
  235. tracing::warn!(?e, mip, slice, "texture not detiled");
  236. return;
  237. }
  238. }
  239. }
  240. }
  241. /// Whether `[at, at + len)` is committed memory (streamed textures may be
  242. /// unmapped until their pages arrive).
  243. pub(crate) fn committed(at: *const u8, len: usize) -> bool {
  244. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
  245. let mut p = at as usize;
  246. let end = p + len;
  247. while p < end {
  248. // SAFETY: plain data filled in by the query.
  249. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  250. // SAFETY: a valid out pointer of the right size.
  251. let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
  252. if n == 0 || info.State != MEM_COMMIT {
  253. return false;
  254. }
  255. p = info.BaseAddress as usize + info.RegionSize;
  256. }
  257. true
  258. }
  259. /// The staging state of a title texture, made on first use.
  260. fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
  261. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  262. let map = map.get_or_insert_with(HashMap::new);
  263. if let Some(s) = map.get(&(resource as usize)) {
  264. return Some(s.clone());
  265. }
  266. let (memory, desc) = crate::resource::texture_memory(resource)?;
  267. let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone())
  268. else {
  269. once!(
  270. ?desc,
  271. "texture contents without a console layout not uploaded"
  272. );
  273. return None;
  274. };
  275. if layout.desc.swizzle.xor() {
  276. once!(?desc, "texture contents in an XOR mode not uploaded");
  277. return None;
  278. }
  279. let host = host()?;
  280. // SAFETY: a live resource.
  281. let d = unsafe { texture.GetDesc() };
  282. let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
  283. u32::from(d.MipLevels)
  284. } else {
  285. u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize)
  286. };
  287. let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
  288. let mut rows = vec![0u32; count as usize];
  289. let mut total = 0;
  290. // SAFETY: outputs for `count` subresources.
  291. unsafe {
  292. host.device.GetCopyableFootprints(
  293. &d,
  294. 0,
  295. count,
  296. 0,
  297. Some(footprints.as_mut_ptr()),
  298. Some(rows.as_mut_ptr()),
  299. None,
  300. Some(&mut total),
  301. );
  302. }
  303. let (buffer, data) = host.upload_buffer(total)?;
  304. crate::host::name(&buffer, || {
  305. format!(
  306. "staging of {resource:?} {}x{}x{} f{}",
  307. d.Width, d.Height, d.DepthOrArraySize, d.Format.0
  308. )
  309. });
  310. tracing::debug!(?desc, total, "texture contents uploaded from title memory");
  311. let s = Arc::new(Staging {
  312. buffer,
  313. #[cfg(feature = "diagnostics")]
  314. size: total,
  315. data,
  316. footprints,
  317. rows,
  318. layout,
  319. mips: u32::from(d.MipLevels),
  320. memory,
  321. last: Mutex::default(),
  322. });
  323. map.insert(resource as usize, s.clone());
  324. Some(s)
  325. }