diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 63ca496b0..6a87c684d 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -283,6 +283,8 @@ pub(crate) enum Metric { ExternalAcquires, /// [`Metrics::external_releases`]. ExternalReleases, + /// [`Metrics::d3d11_plane_submissions`]. + D3d11PlaneSubmissions, /// [`Metrics::surfaces_in_place`]. SurfacesInPlace, /// [`Metrics::surfaces_copied`]. @@ -352,6 +354,7 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::WaitsBehindCounter, Metric::ExternalAcquires, Metric::ExternalReleases, + Metric::D3d11PlaneSubmissions, Metric::SurfacesInPlace, Metric::SurfacesCopied, Metric::ExportedBlocksAddressed, @@ -769,6 +772,7 @@ struct Atomics { waits_behind_counter: AtomicU64, external_acquires: AtomicU64, external_releases: AtomicU64, + d3d11_plane_submissions: AtomicU64, surfaces_in_place: AtomicU64, surfaces_copied: AtomicU64, exported_blocks_addressed: AtomicU64, @@ -938,6 +942,7 @@ impl Counters { Metric::WaitsBehindCounter => &a.waits_behind_counter, Metric::ExternalAcquires => &a.external_acquires, Metric::ExternalReleases => &a.external_releases, + Metric::D3d11PlaneSubmissions => &a.d3d11_plane_submissions, Metric::SurfacesInPlace => &a.surfaces_in_place, Metric::SurfacesCopied => &a.surfaces_copied, Metric::ExportedBlocksAddressed => &a.exported_blocks_addressed, @@ -1868,6 +1873,7 @@ impl Counters { waits_behind_counter: a.waits_behind_counter.load(Relaxed), external_acquires: a.external_acquires.load(Relaxed), external_releases: a.external_releases.load(Relaxed), + d3d11_plane_submissions: a.d3d11_plane_submissions.load(Relaxed), surfaces_in_place: a.surfaces_in_place.load(Relaxed), surfaces_copied: a.surfaces_copied.load(Relaxed), exported_blocks_addressed: a.exported_blocks_addressed.load(Relaxed), @@ -2752,6 +2758,15 @@ pub struct Metrics { /// one barrier each, in the command buffer's work, also counted in /// [`barriers`](Self::barriers). pub external_releases: u64, + /// Submissions whose command buffers keep a plane of a Direct3D 11 surface + /// (`Device::import_d3d11_surface`, on Windows): each acquires those planes from + /// `VK_QUEUE_FAMILY_EXTERNAL` in a command buffer of the runtime's own at its start and + /// releases them to it in another at its end, both in the general layout, so Direct3D 11 + /// owns the planes' memory between the runtime's submissions. Each acquire and release is + /// one barrier, also counted in [`external_acquires`](Self::external_acquires), + /// [`external_releases`](Self::external_releases) and [`barriers`](Self::barriers). No + /// Metal counterpart: an IOSurface needs no hand-over between APIs. + pub d3d11_plane_submissions: u64, /// Surfaces made in place /// ([`Device::new_exported_surface`](crate::Device::new_exported_surface), /// [`SurfaceForm::InPlace`](crate::SurfaceForm::InPlace)). diff --git a/crates/metal2vulkan-runtime/src/tests/d3d11.rs b/crates/metal2vulkan-runtime/src/tests/d3d11.rs index d02a1fde9..5ac43a3c4 100644 --- a/crates/metal2vulkan-runtime/src/tests/d3d11.rs +++ b/crates/metal2vulkan-runtime/src/tests/d3d11.rs @@ -3,13 +3,15 @@ //! is not its descriptor's. Under `m2v_gpu`, on every device: a picture's two planes made as shared //! Direct3D 11 textures on the DXGI adapter of the device's LUID (luma `R8_UNORM` at 64x32, chroma //! `R16_UINT` at 32x16, which rt's texture views as `RG8Unorm`), imported by their NT handles -//! with no submission. Direct3D 11 writes picture 1 (`UpdateSubresource`, then an event query -//! waited for), rt acquires the planes (`external_writes_done`) and blits them into a Shared -//! buffer, whose bytes are picture 1's exactly. Direct3D 11 writes picture 2, each of whose bytes -//! differs from picture 1's, and rt's next read is picture 2's exactly and matches picture 1 at -//! no byte: the negative control, which a copy taken at the import, or a read of bytes the second -//! write did not reach, fails. Then rt writes picture 3 into the planes by a blit and releases -//! them, and Direct3D 11 reads picture 3 exactly through staging copies (`CopyResource`, `Map`). +//! with no submission. Direct3D 11 draws picture 1 (one triangle a plane, its pixel shader +//! computing each texel's bytes, then an event query waited for), rt acquires the planes +//! (`external_writes_done`) and blits them into a Shared buffer, whose bytes are picture 1's +//! exactly. Direct3D 11 draws picture 2, each of whose bytes differs from picture 1's, and rt's +//! next read is picture 2's exactly and matches picture 1 at no byte: the negative control, which +//! a copy taken at the import, or a read of bytes the second draw did not reach, fails. Then rt +//! writes picture 3 into the planes by a blit and releases them, and Direct3D 11 reads picture 3 +//! exactly through staging copies (`CopyResource`, `Map`). Each of rt's three submissions keeps +//! the planes, and each counts once in `Metrics::d3d11_plane_submissions`. //! While the surface lives, the surface imports gauge holds its two planes; it has no buffer and //! no export handle. The same planes made with `PixelFormatView` usage take a swizzled view in //! another format of their class (`R8Uint` of the luma, `RG8Uint` of the chroma) exactly where @@ -151,21 +153,51 @@ mod on_device { [0, PLANES[0].bytes()] } - /// The two planes' bytes, packed: picture `n`'s pattern, each picture's every byte unlike - /// the others'. + /// What picture `n`'s bytes are XORed with: each picture's every byte unlike the others'. + fn mask(n: u32) -> u8 { + [0x00, 0xff, 0x5a][n as usize - 1] + } + + /// The two planes' bytes, packed: picture `n`'s pattern, byte `b` of row `y` of plane `i` + /// being `(b * 7 + y * 13 + i * 101 + 1) mod 256`, XORed with [`mask`]. fn picture(n: u32) -> Vec { - let mask = [0x00, 0xff, 0x5a][n as usize - 1]; let mut out = Vec::with_capacity(PLANES.iter().map(Plane::bytes).sum()); for (i, plane) in PLANES.iter().enumerate() { for y in 0..plane.height { for b in 0..plane.row() { - out.push((b * 7 + y * 13 + i as u32 * 101 + 1) as u8 ^ mask); + out.push((b * 7 + y * 13 + i as u32 * 101 + 1) as u8 ^ mask(n)); } } } out } + /// The pixel shader that draws plane `i` of picture `n`, [`picture`]'s bytes: the luma's + /// one byte a texel as that byte over 255, which its `UNORM` format stores as the byte, + /// and the chroma's two bytes a texel packed into its `UINT` value, the first low. + fn pixel_shader(n: u32, i: usize) -> String { + let byte = format!( + "uint byte_at(uint b, uint y) {{ return ((b * 7 + y * 13 + {}) & 255) ^ {}; }}\n", + i * 101 + 1, + mask(n) + ); + let main = match PLANES[i].texel { + 1 => { + "float main(float4 p : SV_Position) : SV_Target { + uint2 q = uint2(p.xy); + return byte_at(q.x, q.y) / 255.0; +}" + } + _ => { + "uint main(float4 p : SV_Position) : SV_Target { + uint2 q = uint2(p.xy); + return byte_at(2 * q.x, q.y) | (byte_at(2 * q.x + 1, q.y) << 8); +}" + } + }; + byte + main + } + /// The first byte at which `got` differs from `want`, and how many bytes agree. fn compare(want: &[u8], got: &[u8]) -> (Option, usize) { assert_eq!(want.len(), got.len()); @@ -250,10 +282,11 @@ mod on_device { assert_eq!(command_buffer.error(), None, "{name}"); } - /// Direct3D 11 writes `bytes` (packed) into the textures and waits for its work. - fn d3d_write(d3d: &D3d, textures: &[SharedTexture; 2], bytes: &[u8]) { - for ((texture, plane), offset) in textures.iter().zip(&PLANES).zip(offsets()) { - d3d.write(texture, &bytes[offset..offset + plane.bytes()], plane.row()); + /// Direct3D 11 draws picture `n` into the textures, one triangle over each, and waits for + /// its work. + fn d3d_draw(d3d: &D3d, textures: &[SharedTexture; 2], n: u32) { + for (i, (texture, plane)) in textures.iter().zip(&PLANES).enumerate() { + d3d.draw(texture, (plane.width, plane.height), &pixel_shader(n, i)); } d3d.finish(); } @@ -321,13 +354,13 @@ mod on_device { "{name}: the planes' textures are in their descriptors' formats" ); - // Direct3D 11 writes, rt reads. + // Direct3D 11 draws, rt reads. let (one, two, three) = (picture(1), picture(2), picture(3)); - d3d_write(&d3d, &textures, &one); + d3d_draw(&d3d, &textures, 1); surface.external_writes_done().expect("the acquire"); let read = rt_read(name, &device, &surface); assert_eq!(compare(&one, &read).0, None, "{name}: picture 1 read by rt"); - d3d_write(&d3d, &textures, &two); + d3d_draw(&d3d, &textures, 2); surface.external_writes_done().expect("the acquire"); let read = rt_read(name, &device, &surface); assert_eq!(compare(&two, &read).0, None, "{name}: picture 2 read by rt"); @@ -352,14 +385,20 @@ mod on_device { "{name}: D3D11's read against picture 2" ); let metrics = counters.metrics(); + let kept = metrics.d3d11_plane_submissions - before.d3d11_plane_submissions; println!( "d3d11: {name}: imported two planes (R8_UNORM 64x32, R16_UINT 32x16 viewed as \ - RG8Unorm) with no submission; pictures 1 and 2 written by D3D11 read exact by \ + RG8Unorm) with no submission; pictures 1 and 2 drawn by D3D11 read exact by \ rt, the second unlike the first at every byte; picture 3 written by rt read \ - exact by D3D11; {} acquires, {} releases", + exact by D3D11; {} acquires, {} releases; {kept} of rt's 3 submissions \ + that keep the planes counted", metrics.external_acquires - before.external_acquires, metrics.external_releases - before.external_releases, ); + assert_eq!( + kept, 3, + "{name}: each of rt's submissions that keep the planes counted" + ); drop(surface); }); } @@ -623,10 +662,11 @@ mod on_device { } /// Direct3D 11 and DXGI, bound by hand: the calls the test makes, at their vtable slots in - /// the Windows SDK's `d3d11.h`, `dxgi.h` and `dxgi1_2.h`. + /// the Windows SDK's `d3d11.h`, `dxgi.h`, `dxgi1_2.h` and `d3dcommon.h` (`ID3DBlob`), and + /// `D3DCompile` (`d3dcompiler.h`), loaded from `d3dcompiler_47.dll`. #[cfg(m2v_gpu)] mod d3d { - use std::ffi::c_void; + use std::ffi::{c_char, c_void, CStr}; use std::os::windows::io::{FromRawHandle, OwnedHandle, RawHandle}; use std::time::{Duration, Instant}; @@ -643,6 +683,7 @@ mod on_device { const D3D11_CPU_ACCESS_READ: u32 = 0x20000; const D3D11_MAP_READ: u32 = 1; const D3D11_QUERY_EVENT: u32 = 0; + const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST: u32 = 4; const DXGI_SHARED_RESOURCE_READ: u32 = 0x8000_0000; const DXGI_SHARED_RESOURCE_WRITE: u32 = 0x1; const DXGI_ERROR_NOT_FOUND: i32 = 0x887a_0002_u32 as i32; @@ -729,6 +770,84 @@ mod on_device { fn CreateDXGIFactory1(riid: *const Guid, factory: *mut *mut c_void) -> i32; } + #[link(name = "kernel32")] + extern "system" { + fn LoadLibraryW(name: *const u16) -> *mut c_void; + fn GetProcAddress(module: *mut c_void, name: *const c_char) -> *mut c_void; + } + + /// The vertex shader: one triangle over the viewport, from the vertex's index alone. + const VERTEX_SHADER: &str = "float4 main(uint id : SV_VertexID) : SV_Position { + float2 t = float2((id << 1) & 2, id & 2); + return float4(t * float2(2, -2) + float2(-1, 1), 0, 1); +}"; + + /// `D3DCompile` (`d3dcompiler.h`): the source and its length, its name, defines, + /// includes, entry point, target, two flag words, and the code and errors written. + type D3dCompile = unsafe extern "system" fn( + *const c_void, + usize, + *const c_char, + *const c_void, + *mut c_void, + *const c_char, + *const c_char, + u32, + u32, + *mut *mut c_void, + *mut *mut c_void, + ) -> i32; + + /// `source`'s `main` compiled for `target` by `D3DCompile`, which `d3dcompiler_47.dll` + /// exports. + fn compile(source: &str, target: &CStr) -> Vec { + let library: Vec = "d3dcompiler_47.dll".encode_utf16().chain([0]).collect(); + // SAFETY: `library` is NUL-terminated UTF-16 naming a system library. + let module = unsafe { LoadLibraryW(library.as_ptr()) }; + assert!(!module.is_null(), "LoadLibraryW(d3dcompiler_47.dll)"); + // SAFETY: `module` is loaded and never freed; the name is NUL-terminated. + let function = unsafe { GetProcAddress(module, c"D3DCompile".as_ptr()) }; + assert!(!function.is_null(), "GetProcAddress(D3DCompile)"); + // SAFETY: the function is `D3DCompile`, of that type. + let compile = unsafe { std::mem::transmute::<*mut c_void, D3dCompile>(function) }; + let (mut code, mut errors) = (std::ptr::null_mut(), std::ptr::null_mut()); + // SAFETY: the source is `source.len()` bytes; no name, defines or includes; the entry + // point and target are NUL-terminated; the call writes the two blobs. + let hr = unsafe { + compile( + source.as_ptr().cast(), + source.len(), + std::ptr::null(), + std::ptr::null(), + std::ptr::null_mut(), + c"main".as_ptr(), + target.as_ptr(), + 0, + 0, + &mut code, + &mut errors, + ) + }; + let said = (!errors.is_null()).then(|| blob(&Com(errors))); + assert!( + hr >= 0, + "D3DCompile for {target:?}: HRESULT {hr:#x}: {}", + String::from_utf8_lossy(&said.unwrap_or_default()) + ); + blob(&Com::made("D3DCompile", hr, code)) + } + + /// A blob's bytes (`ID3DBlob`). + fn blob(blob: &Com) -> Vec { + // SAFETY: ID3DBlob's `GetBufferPointer` and `GetBufferSize`, whose bytes live as long + // as the blob. + unsafe { + let pointer = method::(blob.0, BLOB_GET_BUFFER_POINTER)(blob.0); + let size = method::(blob.0, BLOB_GET_BUFFER_SIZE)(blob.0); + std::slice::from_raw_parts(pointer, size).to_vec() + } + } + type QueryInterface = unsafe extern "system" fn(*mut c_void, *const Guid, *mut *mut c_void) -> i32; type Release = unsafe extern "system" fn(*mut c_void) -> u32; @@ -745,15 +864,28 @@ mod on_device { type End = unsafe extern "system" fn(*mut c_void, *mut c_void); type GetData = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, u32, u32) -> i32; - type UpdateSubresource = unsafe extern "system" fn( + type CreateView = unsafe extern "system" fn( *mut c_void, *mut c_void, - u32, *const c_void, + *mut *mut c_void, + ) -> i32; + type CreateShader = unsafe extern "system" fn( + *mut c_void, *const c_void, - u32, - u32, - ); + usize, + *mut c_void, + *mut *mut c_void, + ) -> i32; + type SetTopology = unsafe extern "system" fn(*mut c_void, u32); + type SetShader = + unsafe extern "system" fn(*mut c_void, *mut c_void, *const *mut c_void, u32); + type SetTargets = + unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void, *mut c_void); + type SetViewports = unsafe extern "system" fn(*mut c_void, u32, *const [f32; 6]); + type Draw = unsafe extern "system" fn(*mut c_void, u32, u32); + type BlobPointer = unsafe extern "system" fn(*mut c_void) -> *const u8; + type BlobSize = unsafe extern "system" fn(*mut c_void) -> usize; type CopyResource = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void); type Map = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, u32, u32, *mut Mapped) -> i32; @@ -772,14 +904,24 @@ mod on_device { const FACTORY1_ENUM_ADAPTERS1: usize = 12; const ADAPTER1_GET_DESC1: usize = 10; const DEVICE_CREATE_TEXTURE_2D: usize = 5; + const DEVICE_CREATE_RENDER_TARGET_VIEW: usize = 9; + const DEVICE_CREATE_VERTEX_SHADER: usize = 12; + const DEVICE_CREATE_PIXEL_SHADER: usize = 15; const DEVICE_CREATE_QUERY: usize = 24; + const CONTEXT_PS_SET_SHADER: usize = 9; + const CONTEXT_VS_SET_SHADER: usize = 11; + const CONTEXT_DRAW: usize = 13; const CONTEXT_MAP: usize = 14; const CONTEXT_UNMAP: usize = 15; + const CONTEXT_IA_SET_PRIMITIVE_TOPOLOGY: usize = 24; const CONTEXT_END: usize = 28; const CONTEXT_GET_DATA: usize = 29; + const CONTEXT_OM_SET_RENDER_TARGETS: usize = 33; + const CONTEXT_RS_SET_VIEWPORTS: usize = 44; const CONTEXT_COPY_RESOURCE: usize = 47; - const CONTEXT_UPDATE_SUBRESOURCE: usize = 48; const RESOURCE1_CREATE_SHARED_HANDLE: usize = 13; + const BLOB_GET_BUFFER_POINTER: usize = 3; + const BLOB_GET_BUFFER_SIZE: usize = 4; /// Method `index` of COM object `this`'s vtable, as `F`. /// @@ -952,22 +1094,96 @@ mod on_device { Com::made("CreateTexture2D", hr, texture) } - /// Records `bytes`, rows of `row` bytes, into `texture`'s one subresource. - pub(super) fn write(&self, texture: &SharedTexture, bytes: &[u8], row: u32) { - let context = self.context.0; - // SAFETY: ID3D11DeviceContext::UpdateSubresource of the whole subresource from - // `bytes`, which hold its rows. - unsafe { - method::(context, CONTEXT_UPDATE_SUBRESOURCE)( - context, + /// Records one triangle over the whole of `texture`, `width` by `height`, as a render + /// target, each pixel written by the pixel shader compiled from `pixel` (HLSL, its + /// entry `main`); then unbinds the target. + pub(super) fn draw( + &self, + texture: &SharedTexture, + (width, height): (u32, u32), + pixel: &str, + ) { + let vertex = self.shader( + "CreateVertexShader", + DEVICE_CREATE_VERTEX_SHADER, + &compile(VERTEX_SHADER, c"vs_5_0"), + ); + let pixel = self.shader( + "CreatePixelShader", + DEVICE_CREATE_PIXEL_SHADER, + &compile(pixel, c"ps_5_0"), + ); + let mut view = std::ptr::null_mut(); + // SAFETY: ID3D11Device::CreateRenderTargetView of a render target texture of the + // device's, in its own format, writing one pointer. + let hr = unsafe { + method::(self.device.0, DEVICE_CREATE_RENDER_TARGET_VIEW)( + self.device.0, texture.texture.0, - 0, std::ptr::null(), - bytes.as_ptr().cast(), - row, - 0, + &mut view, ) }; + let view = Com::made("CreateRenderTargetView", hr, view); + // `D3D11_VIEWPORT`: `TopLeftX`, `TopLeftY`, `Width`, `Height`, `MinDepth`, + // `MaxDepth`. A side of at most 2^24 is exact in an f32. + let viewport = [0.0, 0.0, width as f32, height as f32, 0.0, 1.0]; + let targets = [view.0]; + let context = self.context.0; + // SAFETY: each is ID3D11DeviceContext's named method, with objects of the + // device's; the vertex shader reads no input, so no input layout is bound. + unsafe { + method::(context, CONTEXT_IA_SET_PRIMITIVE_TOPOLOGY)( + context, + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + method::(context, CONTEXT_VS_SET_SHADER)( + context, + vertex.0, + std::ptr::null(), + 0, + ); + method::(context, CONTEXT_PS_SET_SHADER)( + context, + pixel.0, + std::ptr::null(), + 0, + ); + method::(context, CONTEXT_OM_SET_RENDER_TARGETS)( + context, + 1, + targets.as_ptr(), + std::ptr::null_mut(), + ); + method::(context, CONTEXT_RS_SET_VIEWPORTS)( + context, 1, &viewport, + ); + method::(context, CONTEXT_DRAW)(context, 3, 0); + method::(context, CONTEXT_OM_SET_RENDER_TARGETS)( + context, + 0, + std::ptr::null(), + std::ptr::null_mut(), + ); + } + } + + /// A shader of the device's from `code`, by its method `index` + /// (`CreateVertexShader` or `CreatePixelShader`, which take the same arguments). + fn shader(&self, what: &str, index: usize, code: &[u8]) -> Com { + let mut shader = std::ptr::null_mut(); + // SAFETY: the method is ID3D11Device's `index`, of compiled code of its stage, + // with no class linkage, writing one pointer. + let hr = unsafe { + method::(self.device.0, index)( + self.device.0, + code.as_ptr().cast(), + code.len(), + std::ptr::null_mut(), + &mut shader, + ) + }; + Com::made(what, hr, shader) } /// Waits until the work recorded so far has completed: an event query's end, then diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6fad6b8cf..e03a531d4 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1421,6 +1421,7 @@ field metal2vulkan-runtime::Metrics.consumer_allocation_max_nanos pub consumer_a field metal2vulkan-runtime::Metrics.consumer_allocation_nanos pub consumer_allocation_nanos: u64 field metal2vulkan-runtime::Metrics.consumer_allocations pub consumer_allocations: u64 field metal2vulkan-runtime::Metrics.creations_before_seed pub creations_before_seed: u64 +field metal2vulkan-runtime::Metrics.d3d11_plane_submissions pub d3d11_plane_submissions: u64 field metal2vulkan-runtime::Metrics.dispatches_without_effects pub dispatches_without_effects: u64 field metal2vulkan-runtime::Metrics.emulated_simdgroup_dispatches pub emulated_simdgroup_dispatches: u64 field metal2vulkan-runtime::Metrics.event_holds pub event_holds: [u64; STAGE_BUCKETS]