From 6d6a3e36eea397eb1efb3c27c26fea6208f28ab0 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:32:11 -0300 Subject: [PATCH 1/3] Memory: detect a macOS host under Wine (mac_host) util::mac_host(): the process runs under Wine on a Mac (CrossOver or the Game Porting Toolkit), where D3D12 is Apple's D3DMetal and the title's code runs through Rosetta 2. ntdll's wine_get_host_version names the host's system; "Darwin" is a Mac. XCL_MAC_HOST=1 / 0 overrides it. Nothing calls it yet. The Mac changes that need to know they run there (the barrier default, title textures on shared pages) build on it; until now only Ahmet-Dedeler's mac7 branch had it. Part of #258. --- crates/xcl/src/util.rs | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/xcl/src/util.rs b/crates/xcl/src/util.rs index a7609fe3ff..37b05d9354 100644 --- a/crates/xcl/src/util.rs +++ b/crates/xcl/src/util.rs @@ -132,6 +132,36 @@ pub fn under_wine() -> bool { }) } +/// The process runs under Wine on a Mac (ntdll's `wine_get_host_version` says Darwin): CrossOver +/// or the Game Porting Toolkit, where D3D12 is Apple's D3DMetal and, on Apple Silicon, the +/// title's code runs through Rosetta 2. Known from the start of the run, before there is a +/// device. `XCL_MAC_HOST=1` / `0` overrides the detection. +pub fn mac_host() -> bool { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + static MAC: std::sync::OnceLock = std::sync::OnceLock::new(); + *MAC.get_or_init(|| { + let forced = std::env::var("XCL_MAC_HOST").ok(); + // SAFETY: ntdll is always loaded; Wine's export fills two pointers to static strings. + let sysname = unsafe { + GetProcAddress(GetModuleHandleA(c"ntdll.dll".as_ptr() as *const u8), c"wine_get_host_version".as_ptr() as *const u8).and_then(|f| { + let f: unsafe extern "C" fn(*mut *const u8, *mut *const u8) = std::mem::transmute(f); + let (mut sysname, mut release) = (std::ptr::null(), std::ptr::null()); + f(&mut sysname, &mut release); + from_cstr_ptr(sysname) + }) + }; + mac_host_from(forced.as_deref(), sysname.as_deref()) + }) +} + +/// `mac_host`'s answer from `XCL_MAC_HOST` (`forced`) and the host's system name, if Wine gave one. +fn mac_host_from(forced: Option<&str>, sysname: Option<&str>) -> bool { + match forced { + Some(v) => v.trim() != "0", + None => sysname.is_some_and(|s| s.eq_ignore_ascii_case("Darwin")), + } +} + /// Normalised DLL key: lower-case file name, ".dll" appended when no extension. pub fn dll_key(name: &str) -> String { let base = name.rsplit(['\\', '/']).next().unwrap_or(name); @@ -321,6 +351,20 @@ unsafe impl Sync for SendPtr {} mod tests { use super::*; + /// Darwin from Wine's host version is a Mac (in any case); Linux, Windows and no answer are + /// not; `XCL_MAC_HOST` decides when it is set, "0" for no and anything else for yes. + #[test] + fn a_mac_host_is_darwin_under_wine_unless_forced() { + assert!(mac_host_from(None, Some("Darwin"))); + assert!(mac_host_from(None, Some("darwin"))); + assert!(!mac_host_from(None, Some("Linux"))); + assert!(!mac_host_from(None, None)); + assert!(!mac_host_from(Some("0"), Some("Darwin"))); + assert!(!mac_host_from(Some(" 0 "), Some("Darwin"))); + assert!(mac_host_from(Some("1"), None)); + assert!(mac_host_from(Some("1"), Some("Linux"))); + } + #[test] fn dll_keys() { assert_eq!(dll_key("KERNELX"), "kernelx.dll"); From 861903ffb478c7d0a02b9aacf59c18f8ba7a7e3a Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:32:25 -0300 Subject: [PATCH 2/3] D3D12.X: title textures share video-memory pages on a macOS host too #288's shared pages never run on D3DMetal: it reports D3D12_FORMAT_SUPPORT2_TILED for no format, so `reservable` refuses every texture and each title texture keeps a copy of its own in video memory (about 16 GB more wired memory while a title loads on a Mac). D3DMetal does make the reserved textures. Measured with copies and shader reads on CrossOver 26.3: a texture written by a copy and read through another reserved texture on the same tiles reads scrambled bytes, whatever the barrier, format or layout. Block-compressed textures, and textures made with ALLOW_UNORDERED_ACCESS, share correctly. The likely reason is compression state that D3DMetal keeps per texture, not per tile. On a macOS host (util::mac_host): - `reservable` skips the TILED bit and accepts block-compressed formats and formats with typed unordered access (single-sample only); - `place_on_pages` gives the reserved texture ALLOW_UNORDERED_ACCESS unless it is block-compressed. Render and depth targets, and the GPU-owned `place`, stay in arenas: their sharing was not probed. Windows is unchanged. sampled_textures_at_one_address_share_their_pages_in_every_slice places two 256x256, 4-slice, 9-level textures (RGBA8 and BC7) at one address, writes all 36 subresources through one and reads them through the other. On the Mac it needs the native-host vtable fix of #1904 and a deferred release for D3DMetal's own threads: without the first, placing the texture faults in GetResourceTiling; without the second, a list that touches it never completes. With both, it fails without this change (not placed on the pages), passes with it, and fails again if RGBA8 gets no unordered-access flag (every subresource reads back wrong). Part of #258. --- crates/xcl/src/hle/d3d12x/vram.rs | 155 +++++++++++++++++++++++++++++- 1 file changed, 154 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 35fc67d205..53c8befb3d 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -924,6 +924,23 @@ fn can_reserve(support2: i32, samples: u32, tiled_msaa_levels: u32) -> bool { support2 & D3D12_FORMAT_SUPPORT2_TILED.0 != 0 && (samples <= 1 || tiled_msaa_levels > 0) } +/// On D3DMetal, a texture written by a copy and read through another reserved texture on the same +/// tiles reads scrambled bytes unless it is block-compressed or allows unordered access (measured +/// with copies and shader reads; the texture's own compression state, kept per texture and not +/// per tile, is the likely reason). The flags a shared-page texture of `format` needs there, or +/// None when it can have neither (`support1`: the format's D3D12_FORMAT_SUPPORT1). +fn native_page_flags(format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, support1: i32) -> Option { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC5_SNORM, DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC7_UNORM_SRGB}; + let block_compressed = (DXGI_FORMAT_BC1_TYPELESS.0..=DXGI_FORMAT_BC5_SNORM.0).contains(&format.0) || (DXGI_FORMAT_BC6H_TYPELESS.0..=DXGI_FORMAT_BC7_UNORM_SRGB.0).contains(&format.0); + if block_compressed { + Some(D3D12_RESOURCE_FLAG_NONE) + } else if support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0 { + Some(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) + } else { + None + } +} + /// Whether the device can make `desc` a reserved texture, asked before CreateReservedResource: /// refused, it is an error in the debug layer (#940: R32G8X24_TYPELESS depth, 1 and 4 samples). /// A query that fails says yes, and creation decides. @@ -932,6 +949,11 @@ unsafe fn reservable(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC) -> bool { if dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut f as *mut _ as *mut c_void, std::mem::size_of_val(&f) as u32).is_err() { return true; } + // D3DMetal reports TILED for no format but makes reserved textures of them; they share + // pages only as block-compressed formats or with unordered access (`native_page_flags`) + if crate::util::mac_host() { + return desc.SampleDesc.Count <= 1 && native_page_flags(desc.Format, f.Support1.0).is_some(); + } // a format without TILED is not reservable whatever the sample count's query says if !can_reserve(f.Support2.0, 1, 0) { return false; @@ -985,7 +1007,16 @@ unsafe fn place_on_pages( return None; } // reserved textures have the PC's 64 KiB tiles - let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; + let mut tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; + if crate::util::mac_host() { + // render and depth targets: their sharing was not probed on D3DMetal, they keep arenas + if require_aligned || desc.Flags.0 & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0) != 0 { + return None; + } + let mut f = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: desc.Format, ..Default::default() }; + let support1 = if dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut f as *mut _ as *mut c_void, std::mem::size_of_val(&f) as u32).is_ok() { f.Support1.0 } else { 0 }; + tiled.Flags.0 |= native_page_flags(desc.Format, support1)?.0; + } static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let log = |why: &str| { if require_aligned && N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { @@ -1745,6 +1776,128 @@ mod tests { } } + /// Two sampled textures placed at one address are on its shared pages, and what a copy writes + /// through one the other reads back in every slice and level (packed ones too), RGBA8 and BC7. + /// On a Mac neither was placed (D3DMetal reports TILED for no format), and there an RGBA8 + /// texture without unordered access reads another's writes scrambled. Needs a hardware adapter + /// (skips on WARP). + #[test] + fn sampled_textures_at_one_address_share_their_pages_in_every_slice() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return skip_test("no GPU") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return skip_test("no GPU"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { return skip_test("no GPU") }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let buffer = |bytes: u64| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: sample, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + let barrier = |r: &ID3D12Resource, from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }; + D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() } + }; + let run = |record: &dyn Fn(&ID3D12GraphicsCommandList)| { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + record(&list); + list.Close().unwrap(); + before_execute(&queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + }; + + // 256x256, 4 slices, 9 levels: standard and packed levels in each slice + for (k, format) in [DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_BC7_UNORM].into_iter().enumerate() { + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 256, Height: 256, DepthOrArraySize: 4, MipLevels: 9, Format: format, SampleDesc: sample, ..Default::default() }; + // (an adapter that makes no reserved array with packed levels does not run the path) + let mut r: Option = None; + if dev.CreateReservedResource(&D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..desc }, D3D12_RESOURCE_STATE_COMMON, None, &mut r).is_err() || r.is_none() { + return skip_test("no reserved array with packed levels"); + } + let va = 0x60_0000_0000 + k * 64 * MIB; + let place_at = || { + let mut p = std::ptr::null_mut(); + let hr = place_pages(dev.as_raw(), va, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut p); + assert!(hr.is_some_and(|hr| hr >= 0) && !p.is_null(), "format {}: not placed on the pages at {va:#x}", format.0); + assert!(is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + let (a, b) = (place_at(), place_at()); + let subs = 9 * 4; + let placed = a.GetDesc(); + let mut layouts = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); subs]; + let (mut rows, mut row_bytes, mut total) = (vec![0u32; subs], vec![0u64; subs], 0u64); + dev.GetCopyableFootprints(&placed, 0, subs as u32, 0, Some(layouts.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + let row = |s: usize, y: usize| layouts[s].Offset as usize + y * layouts[s].Footprint.RowPitch as usize; + let want = |s: usize, y: usize, x: usize| (s * 37 + y * 11 + x * 13 + k) as u8; + + let (mut upload, mut readback): (Option, Option) = (None, None); + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer(total), D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut upload).unwrap(); + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer(total), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let (upload, readback) = (upload.unwrap(), readback.unwrap()); + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).unwrap(); + let bytes = std::slice::from_raw_parts_mut(p as *mut u8, total as usize); + for s in 0..subs { + for y in 0..rows[s] as usize { + for x in 0..row_bytes[s] as usize { + bytes[row(s, y) + x] = want(s, y, x); + } + } + } + upload.Unmap(0, None); + let copy = |list: &ID3D12GraphicsCommandList, buf: &ID3D12Resource, tex: &ID3D12Resource, to_texture: bool| { + for (s, layout) in layouts.iter().enumerate() { + let footprint = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(buf), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *layout } }; + let sub = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(tex), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s as u32 } }; + if to_texture { + list.CopyTextureRegion(&sub, 0, 0, 0, &footprint, None); + } else { + list.CopyTextureRegion(&footprint, 0, 0, 0, &sub, None); + } + } + }; + // written through `a` ... + run(&|list| { + list.ResourceBarrier(&[barrier(&a, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + copy(list, &upload, &a, true); + list.ResourceBarrier(&[barrier(&a, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]); + }); + // ... read through `b` + run(&|list| { + let alias = D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::ManuallyDrop::new(None), pResourceAfter: std::mem::ManuallyDrop::new(None) }; + let alias = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(alias) }, ..Default::default() }; + list.ResourceBarrier(&[alias, barrier(&b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + copy(list, &readback, &b, false); + list.ResourceBarrier(&[barrier(&b, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + }); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let bytes = std::slice::from_raw_parts(p as *const u8, total as usize); + let mut wrong = Vec::new(); + for s in 0..subs { + let bad = (0..rows[s] as usize).flat_map(|y| (0..row_bytes[s] as usize).map(move |x| (y, x))).filter(|&(y, x)| bytes[row(s, y) + x] != want(s, y, x)).count(); + if bad > 0 { + wrong.push(format!("slice {} level {}: {bad} bytes", s / 9, s % 9)); + } + } + readback.Unmap(0, None); + assert!(wrong.is_empty(), "format {}: read through the other texture: {}", format.0, wrong.join(", ")); + drop((a, b)); + } + } + } + /// A placement's arena id, with heaps numbered as they are made. fn take(a: &mut Arenas, va: usize, bytes: usize, align: usize, now: Instant) -> u64 { let n = a.list.len() as u32; From 4c97142153a3d14076e9252e24853ed389218f63 Mon Sep 17 00:00:00 2001 From: vakaobr <15154330+vakaobr@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:13:18 -0300 Subject: [PATCH 3/3] D3D12.X: render targets share video-memory pages on a macOS host too A title's GPU-owned textures (render targets, depth targets, UAVs) are placed through vram::place, which asks place_on_pages with require_aligned. On a Mac, #2402 returned there for all of them, so a render target never reached the shared pages; its own RT/DS flag check was never reached by a title's texture. Render targets share correctly on D3DMetal: with two reserved textures on the same tiles, an R8G8B8A8_UNORM render target (RT + UAV) cleared through one reads back through the other with 0 of 4096 texels wrong. A D32_FLOAT depth target reads back with 3968 of 4096 wrong (D3DMetal's compression state, kept per texture). Both measured with raw CreateReservedResource / UpdateTileMappings probes on an M5 Pro under CrossOver 26.3. On a macOS host, place_on_pages now lets render targets through the require_aligned return; they get ALLOW_UNORDERED_ACCESS from native_page_flags, and one whose format has no typed UAV still stays in its arena (native_page_flags is None). Depth targets and the other GPU-owned textures keep their arenas. Windows is unchanged. render_targets_at_one_address_share_their_pages places two render targets at one address through vram::place: it fails without this (not on the shared pages) and passes with it, 0 of 65536 pixels wrong. --- crates/xcl/src/hle/d3d12x/vram.rs | 92 ++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 53c8befb3d..026b171953 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1009,8 +1009,11 @@ unsafe fn place_on_pages( // reserved textures have the PC's 64 KiB tiles let mut tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; if crate::util::mac_host() { - // render and depth targets: their sharing was not probed on D3DMetal, they keep arenas - if require_aligned || desc.Flags.0 & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0) != 0 { + // depth targets keep arenas: one cleared through a reserved texture reads back scrambled + // through another on the same tiles (D32_FLOAT: 3968 of 4096 texels); of the other + // GPU-owned textures (`place`) only render targets were probed + let render_target = desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 != 0; + if (require_aligned && !render_target) || desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0 { return None; } let mut f = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: desc.Format, ..Default::default() }; @@ -1898,6 +1901,91 @@ mod tests { } } + /// Two render targets placed at one address (`place`, as a title's render target is) are on + /// its shared pages, and what a clear writes through one the other reads back. On a Mac they + /// kept arenas. Needs a hardware adapter (skips on WARP). + #[test] + fn render_targets_at_one_address_share_their_pages() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use crate::gpu::recomp::runner::skip_test; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return skip_test("no GPU") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return skip_test("no GPU"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev.filter(|d| tier2(d)) else { return skip_test("no GPU") }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let sample = DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 256, Height: 256, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: sample, Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, ..Default::default() }; + let va = 0x62_0000_0000; + let place_at = || { + let mut p = std::ptr::null_mut(); + let hr = place(dev.as_raw(), va, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut p); + assert!(hr.is_some_and(|hr| hr >= 0) && !p.is_null(), "not placed at {va:#x}"); + let on_pages = PAGES.lock().unwrap().values().flatten().any(|pages| pages.targets.contains_key(&(p as usize))); + assert!(on_pages, "render target not placed on the pages at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let (a, b) = (place_at(), place_at()); + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&a, None, rtv); + let mut layout = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0u64; + dev.GetCopyableFootprints(&a.GetDesc(), 0, 1, 0, Some(&mut layout), None, None, Some(&mut total)); + let buffer = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: sample, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + let mut readback: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback).unwrap(); + let readback = readback.unwrap(); + let barrier = |r: &ID3D12Resource, from: D3D12_RESOURCE_STATES, to: D3D12_RESOURCE_STATES| { + let t = D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(r), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: from, StateAfter: to }; + D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(t) }, ..Default::default() } + }; + let run = |record: &dyn Fn(&ID3D12GraphicsCommandList)| { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + record(&list); + list.Close().unwrap(); + before_execute(&queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + }; + // cleared through `a` (values a UNORM8 holds exactly) ... + let want = [51u8, 102, 153, 255]; + run(&|list| { + list.ResourceBarrier(&[barrier(&a, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + list.ClearRenderTargetView(rtv, &want.map(|c| c as f32 / 255.0), None); + list.ResourceBarrier(&[barrier(&a, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COMMON)]); + }); + // ... read through `b` + run(&|list| { + let alias = D3D12_RESOURCE_ALIASING_BARRIER { pResourceBefore: std::mem::ManuallyDrop::new(None), pResourceAfter: std::mem::ManuallyDrop::new(None) }; + let alias = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: std::mem::ManuallyDrop::new(alias) }, ..Default::default() }; + list.ResourceBarrier(&[alias, barrier(&b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let footprint = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: layout } }; + let sub = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&b), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&footprint, 0, 0, 0, &sub, None); + list.ResourceBarrier(&[barrier(&b, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + }); + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).unwrap(); + let bytes = std::slice::from_raw_parts(p as *const u8, total as usize); + let pitch = layout.Footprint.RowPitch as usize; + let wrong = (0..256usize).flat_map(|y| (0..256usize).map(move |x| y * pitch + x * 4)).filter(|&o| bytes[o..o + 4] != want).count(); + readback.Unmap(0, None); + assert_eq!(wrong, 0, "{wrong} of 65536 pixels read through the other render target differ"); + drop((a, b)); + } + } + /// A placement's arena id, with heaps numbered as they are made. fn take(a: &mut Arenas, va: usize, bytes: usize, align: usize, now: Instant) -> u64 { let n = a.list.len() as u32;