diff --git a/CHANGELOG.md b/CHANGELOG.md index e6cc5807..fac08aca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ - **Breaking:** Removed `DamageOutOfRange` error case. If the damage value is greater than the backend supports, it is instead clamped to an appropriate value. - **Breaking:** Removed `SurfaceExtWeb` and the associated `NoDisplayHandle` and `NoWindowHandle` helpers. Use `RawWindowHandle::WebCanvas` or `RawWindowHandle::WebOffscreenCanvas` instead. - Fixed `present_with_damage` with bounds out of range on Windows, Web and X11. +- Fixed tearing on Windows by presenting through a DXGI flip model swap chain where available. # 0.4.8 diff --git a/Cargo.toml b/Cargo.toml index 92412ee5..5c90601a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,7 @@ drm = { version = "0.15.0", default-features = false, optional = true } [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.61.2", features = [ "Win32_Graphics_Gdi", + "Win32_System_LibraryLoader", "Win32_UI_ColorSystem", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", @@ -189,6 +190,10 @@ criterion = { version = "0.8.1", default-features = false, features = [ "cargo_bench_support", ] } +[target.'cfg(target_os = "windows")'.dev-dependencies] +# Read back what a window shows in tests. +windows-sys = { version = "0.61.2", features = ["Win32_Storage_Xps"] } + [target.'cfg(target_os = "android")'.dev-dependencies] # Use NativeActivity on Android. winit = { version = "0.30.0", features = ["android-native-activity"] } diff --git a/src/backends/win32.rs b/src/backends/win32.rs index 566fbff9..9ed1ba11 100644 --- a/src/backends/win32.rs +++ b/src/backends/win32.rs @@ -1,6 +1,9 @@ //! Implementation of software buffering for Windows. //! -//! This module converts the input buffer into a bitmap and then stretches it to the window. +//! Frames are presented through a DXGI swap chain. Where that isn't available, the buffer is a +//! bitmap that GDI blits to the window. + +mod dxgi; use crate::backend_interface::*; use crate::{util, AlphaMode, Pixel, Rect, SoftBufferError}; @@ -158,11 +161,8 @@ pub struct Win32Impl { /// The window handle. window: OnlyUsedFromOrigin, - /// The device context for the window. - dc: OnlyUsedFromOrigin, - - /// The buffer used to hold the image. - buffer: Option, + /// What presents the frames. + presenter: Presenter, /// The handle for the window. /// @@ -175,7 +175,50 @@ pub struct Win32Impl { _display: PhantomData, } -impl Drop for Win32Impl { +#[derive(Debug)] +enum Presenter { + /// A DXGI flip model swap chain, which hands DWM whole frames. + Dxgi(dxgi::Presenter), + + /// GDI, where DXGI isn't available. + Gdi(GdiPresenter), +} + +#[derive(Debug)] +struct GdiPresenter { + /// The window that the device context belongs to. + window: OnlyUsedFromOrigin, + + /// The device context for the window. + dc: OnlyUsedFromOrigin, + + /// The buffer used to hold the image. + buffer: Option, +} + +impl GdiPresenter { + fn new(window: HWND) -> Result { + // Get the handle to the device context. + // SAFETY: We have confirmed that the window handle is valid. + let dc = Allocator::get().get_dc(window); + + // GetDC returns null if there is a platform error. + if dc.is_null() { + return Err(SoftBufferError::PlatformError( + Some("Device Context is null".into()), + Some(Box::new(io::Error::last_os_error())), + )); + } + + Ok(Self { + window: window.into(), + dc: dc.into(), + buffer: None, + }) + } +} + +impl Drop for GdiPresenter { fn drop(&mut self) { // Release our resources. Allocator::get().release(self.window.0, self.dc.0); @@ -203,24 +246,18 @@ impl SurfaceInterface for Win32Im return Err(crate::InitError::Unsupported(window)); }; - // Get the handle to the device context. - // SAFETY: We have confirmed that the window handle is valid. let hwnd = handle.hwnd.get() as HWND; - let dc = Allocator::get().get_dc(hwnd); - - // GetDC returns null if there is a platform error. - if dc.is_null() { - return Err(SoftBufferError::PlatformError( - Some("Device Context is null".into()), - Some(Box::new(io::Error::last_os_error())), - ) - .into()); - } + let presenter = match dxgi::Presenter::new(hwnd) { + Ok(presenter) => Presenter::Dxgi(presenter), + Err(error) => { + tracing::warn!("DXGI is not available, presenting with GDI: {error}"); + Presenter::Gdi(GdiPresenter::new(hwnd)?) + } + }; Ok(Self { - dc: dc.into(), window: hwnd.into(), - buffer: None, + presenter, handle: window, _display: PhantomData, }) @@ -250,7 +287,22 @@ impl SurfaceInterface for Win32Im })() .ok_or(SoftBufferError::SizeOutOfRange { width, height })?; - if let Some(buffer) = self.buffer.as_ref() { + if let Presenter::Dxgi(presenter) = &mut self.presenter { + match presenter.configure(width.try_into().unwrap(), height.try_into().unwrap()) { + Ok(()) => return Ok(()), + // GDI no longer draws into a window that a flip model swap chain presented to. + Err(error) if presenter.presented() => return Err(error), + Err(error) => { + tracing::warn!("DXGI failed, presenting with GDI: {error}"); + self.presenter = Presenter::Gdi(GdiPresenter::new(self.window.0)?); + } + } + } + let Presenter::Gdi(gdi) = &mut self.presenter else { + unreachable!("the presenter is GDI") + }; + + if let Some(buffer) = gdi.buffer.as_ref() { if buffer.width == width && buffer.height == height { return Ok(()); } @@ -261,21 +313,29 @@ impl SurfaceInterface for Win32Im AlphaMode::Premultiplied => true, AlphaMode::Postmultiplied => unreachable!("unsupported alpha format"), }; - self.buffer = Some(Buffer::new(self.dc.0, width, height, alpha)); + gdi.buffer = Some(Buffer::new(gdi.dc.0, width, height, alpha)); Ok(()) } fn next_buffer(&mut self, _alpha_mode: AlphaMode) -> Result, SoftBufferError> { - let buffer = self - .buffer - .as_mut() - .expect("Must set size of surface before calling `next_buffer()`"); + let target = match &mut self.presenter { + Presenter::Dxgi(presenter) => { + presenter.map()?; + Target::Dxgi(presenter) + } + Presenter::Gdi(gdi) => Target::Gdi { + dc: &gdi.dc, + buffer: gdi + .buffer + .as_mut() + .expect("Must set size of surface before calling `next_buffer()`"), + }, + }; Ok(BufferImpl { window: &self.window, - dc: &self.dc, - buffer, + target, }) } @@ -288,68 +348,90 @@ impl SurfaceInterface for Win32Im #[derive(Debug)] pub struct BufferImpl<'surface> { window: &'surface OnlyUsedFromOrigin, - dc: &'surface OnlyUsedFromOrigin, - buffer: &'surface mut Buffer, + target: Target<'surface>, +} + +#[derive(Debug)] +enum Target<'surface> { + Dxgi(&'surface mut dxgi::Presenter), + Gdi { + dc: &'surface OnlyUsedFromOrigin, + buffer: &'surface mut Buffer, + }, } impl BufferInterface for BufferImpl<'_> { fn byte_stride(&self) -> NonZeroU32 { - let width = self.buffer.width.get() as u32; - NonZeroU32::new(byte_stride(width, 32)).unwrap() + match &self.target { + Target::Dxgi(presenter) => presenter.byte_stride(), + Target::Gdi { buffer, .. } => { + let width = buffer.width.get() as u32; + NonZeroU32::new(byte_stride(width, 32)).unwrap() + } + } } fn width(&self) -> NonZeroU32 { - self.buffer.width.try_into().unwrap() + match &self.target { + Target::Dxgi(presenter) => presenter.width(), + Target::Gdi { buffer, .. } => buffer.width.try_into().unwrap(), + } } fn height(&self) -> NonZeroU32 { - self.buffer.height.try_into().unwrap() + match &self.target { + Target::Dxgi(presenter) => presenter.height(), + Target::Gdi { buffer, .. } => buffer.height.try_into().unwrap(), + } } #[inline] fn pixels_mut(&mut self) -> &mut [Pixel] { - self.buffer.pixels_mut() + match &mut self.target { + Target::Dxgi(presenter) => presenter.pixels_mut(), + Target::Gdi { buffer, .. } => buffer.pixels_mut(), + } } fn age(&self) -> u8 { - if self.buffer.presented { - 1 - } else { - 0 + match &self.target { + Target::Dxgi(presenter) => presenter.age(), + Target::Gdi { buffer, .. } => { + if buffer.presented { + 1 + } else { + 0 + } + } } } fn present_with_damage(self, damage: &[Rect]) -> Result<(), SoftBufferError> { - unsafe { - for rect in damage { - let rect = util::clamp_rect( - *rect, - self.buffer.width.try_into().unwrap(), - self.buffer.height.try_into().unwrap(), - ); - let x = util::to_i32_saturating(rect.x); - let y = util::to_i32_saturating(rect.y); - let width = util::to_i32_saturating(rect.width.get()); - let height = util::to_i32_saturating(rect.height.get()); - - // TODO: Draw with something else to make transparency work. - Gdi::BitBlt( - self.dc.0, - x, - y, - width, - height, - self.buffer.dc, - x, - y, - Gdi::SRCCOPY, - ); + match self.target { + Target::Dxgi(presenter) => presenter.present(damage)?, + Target::Gdi { dc, buffer } => { + for rect in damage { + let rect = util::clamp_rect( + *rect, + buffer.width.try_into().unwrap(), + buffer.height.try_into().unwrap(), + ); + let x = util::to_i32_saturating(rect.x); + let y = util::to_i32_saturating(rect.y); + let width = util::to_i32_saturating(rect.width.get()); + let height = util::to_i32_saturating(rect.height.get()); + + // TODO: Draw with something else to make transparency work. + unsafe { + Gdi::BitBlt(dc.0, x, y, width, height, buffer.dc, x, y, Gdi::SRCCOPY) + }; + } + buffer.presented = true; } - - // Validate the window. - Gdi::ValidateRect(self.window.0, ptr::null_mut()); } - self.buffer.presented = true; + + // Validate the window. + unsafe { Gdi::ValidateRect(self.window.0, ptr::null_mut()) }; Ok(()) } @@ -496,6 +578,9 @@ impl Command { } } +#[cfg(test)] +mod tests; + #[derive(Debug)] struct OnlyUsedFromOrigin(T); unsafe impl Send for OnlyUsedFromOrigin {} diff --git a/src/backends/win32/dxgi.rs b/src/backends/win32/dxgi.rs new file mode 100644 index 00000000..5dd45e1a --- /dev/null +++ b/src/backends/win32/dxgi.rs @@ -0,0 +1,752 @@ +//! Presentation through a DXGI flip model swap chain. +//! +//! GDI blits into the surface that DWM composes from, and nothing marks where a frame ends, so a +//! composition during a blit shows the top of one frame over the bottom of the previous one. A +//! flip model swap chain hands DWM whole frames instead. +//! +//! The buffer is a staging texture of a WARP device, which renders on the CPU and needs no graphics +//! driver. Presenting copies the damage into the swap chain's back buffer, and DXGI copies the rest +//! of the previous frame. + +use std::ffi::c_void; +use std::fmt; +use std::io; +use std::marker::PhantomData; +use std::mem; +use std::num::NonZeroU32; +use std::ptr::{self, NonNull}; +use std::slice; +use std::sync::OnceLock; + +use windows_sys::core::HRESULT; +use windows_sys::Win32::Foundation::{HWND, RECT}; +use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32, +}; + +use self::ffi::*; +use crate::{Pixel, Rect, SoftBufferError}; + +/// A window's swap chain, with the device that copies frames into it. +#[derive(Debug)] +pub struct Presenter { + window: HWND, + /// Made by `configure`. + frame: Option, + /// Made by the first `configure`. + swap_chain: Option>, + factory: Com, + context: Com, + device: Com, + /// A frame was presented, after which GDI no longer draws into the window. + presented: bool, +} + +// SAFETY: Direct3D 11 and DXGI objects aren't tied to a thread. The device context must not be +// used by two threads at once, which can't happen, as the surface isn't `Sync`. +unsafe impl Send for Presenter {} + +#[derive(Debug)] +struct Frame { + /// The texture that holds the frame. The CPU draws into it while it's mapped. + staging: Com, + width: NonZeroU32, + height: NonZeroU32, + mapping: Option, + /// The texture holds the frame that was presented last. + presented: bool, + /// The swap chain's buffers may not hold the last frame, so the next present copies all of it. + present_whole_frame: bool, +} + +#[derive(Debug)] +struct Mapping { + pixels: NonNull, + byte_stride: NonZeroU32, +} + +impl Presenter { + /// Creates a WARP device for presenting to `window`. + pub fn new(window: HWND) -> Result { + let create_device = d3d11_create_device().ok_or_else(|| { + SoftBufferError::PlatformError(Some("Direct3D 11 is not available".into()), None) + })?; + let mut device = ptr::null_mut(); + let mut context = ptr::null_mut(); + let result = unsafe { + create_device( + ptr::null_mut(), + D3D_DRIVER_TYPE_WARP, + ptr::null_mut(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + ptr::null(), + 0, + D3D11_SDK_VERSION, + &mut device, + ptr::null_mut(), + &mut context, + ) + }; + check(result, "failed to create a WARP device")?; + let device = unsafe { Com::::new(device) }?; + let context = unsafe { Com::::new(context) }?; + + // Swap chains must come from the factory that made the device's adapter. + let mut dxgi_device = ptr::null_mut(); + let result = unsafe { + (device.vtable().base.QueryInterface)( + device.as_ptr(), + &IID_IDXGI_DEVICE, + &mut dxgi_device, + ) + }; + check(result, "failed to get the DXGI device")?; + let dxgi_device = unsafe { Com::::new(dxgi_device) }?; + let mut adapter = ptr::null_mut(); + let result = + unsafe { (dxgi_device.vtable().GetAdapter)(dxgi_device.as_ptr(), &mut adapter) }; + check(result, "failed to get the device's adapter")?; + let adapter = unsafe { Com::::new(adapter) }?; + let mut factory = ptr::null_mut(); + let result = unsafe { + (adapter.vtable().GetParent)(adapter.as_ptr(), &IID_IDXGI_FACTORY2, &mut factory) + }; + check(result, "failed to get the adapter's factory")?; + let factory = unsafe { Com::::new(factory) }?; + + Ok(Self { + window, + frame: None, + swap_chain: None, + factory, + context, + device, + presented: false, + }) + } + + /// Whether a frame was presented, after which GDI no longer draws into the window. + pub fn presented(&self) -> bool { + self.presented + } + + /// Sizes the frame and the swap chain, which the first call creates. + pub fn configure( + &mut self, + width: NonZeroU32, + height: NonZeroU32, + ) -> Result<(), SoftBufferError> { + if let Some(frame) = &self.frame { + if frame.width == width && frame.height == height { + return Ok(()); + } + } + + let staging = self.create_staging(width, height)?; + match &self.swap_chain { + Some(swap_chain) => { + let result = unsafe { + (swap_chain.vtable().ResizeBuffers)( + swap_chain.as_ptr(), + 0, + width.get(), + height.get(), + DXGI_FORMAT_UNKNOWN, + 0, + ) + }; + check(result, "failed to resize the swap chain")?; + } + None => self.swap_chain = Some(self.create_swap_chain(width, height)?), + } + + self.unmap(); + self.frame = Some(Frame { + staging, + width, + height, + mapping: None, + presented: false, + present_whole_frame: true, + }); + Ok(()) + } + + fn create_staging( + &self, + width: NonZeroU32, + height: NonZeroU32, + ) -> Result, SoftBufferError> { + let desc = D3D11_TEXTURE2D_DESC { + Width: width.get(), + Height: height.get(), + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_B8G8R8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_STAGING, + BindFlags: 0, + CPUAccessFlags: D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE, + MiscFlags: 0, + }; + let mut texture = ptr::null_mut(); + let result = unsafe { + (self.device.vtable().CreateTexture2D)( + self.device.as_ptr(), + &desc, + ptr::null(), + &mut texture, + ) + }; + check(result, "failed to create a staging texture")?; + unsafe { Com::new(texture) } + } + + fn create_swap_chain( + &self, + width: NonZeroU32, + height: NonZeroU32, + ) -> Result, SoftBufferError> { + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: width.get(), + Height: height.get(), + Format: DXGI_FORMAT_B8G8R8A8_UNORM, + Stereo: 0, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: 2, + // Like GDI, draw a frame of another size than the window in its top left corner. + Scaling: DXGI_SCALING_NONE, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, + AlphaMode: DXGI_ALPHA_MODE_IGNORE, + Flags: 0, + }; + let mut swap_chain = ptr::null_mut(); + let result = unsafe { + (self.factory.vtable().CreateSwapChainForHwnd)( + self.factory.as_ptr(), + self.device.as_ptr(), + self.window, + &desc, + ptr::null(), + ptr::null_mut(), + &mut swap_chain, + ) + }; + check(result, "failed to create a swap chain for the window")?; + let swap_chain = unsafe { Com::new(swap_chain) }?; + + // Keep DXGI from watching the window's messages and turning Alt+Enter into full screen. + let result = unsafe { + (self.factory.vtable().MakeWindowAssociation)( + self.factory.as_ptr(), + self.window, + DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER, + ) + }; + check(result, "failed to associate the window")?; + Ok(swap_chain) + } + + /// Maps the frame for the CPU to draw into. + pub fn map(&mut self) -> Result<(), SoftBufferError> { + let frame = self + .frame + .as_mut() + .expect("Must set size of surface before calling `next_buffer()`"); + if frame.mapping.is_some() { + return Ok(()); + } + + let mut mapped = D3D11_MAPPED_SUBRESOURCE { + pData: ptr::null_mut(), + RowPitch: 0, + DepthPitch: 0, + }; + let result = unsafe { + (self.context.vtable().Map)( + self.context.as_ptr(), + frame.staging.as_ptr(), + 0, + D3D11_MAP_READ_WRITE, + 0, + &mut mapped, + ) + }; + check(result, "failed to map the staging texture")?; + + // A 2D texture's depth pitch spans all of its rows. + let byte_stride = mapped.RowPitch as usize; + let fits = byte_stride >= frame.width.get() as usize * 4 + && byte_stride % 4 == 0 + && mapped.DepthPitch as usize >= byte_stride * frame.height.get() as usize + && mapped.pData as usize % mem::align_of::() == 0; + match ( + NonNull::new(mapped.pData.cast()), + NonZeroU32::new(mapped.RowPitch), + ) { + (Some(pixels), Some(byte_stride)) if fits => { + frame.mapping = Some(Mapping { + pixels, + byte_stride, + }); + Ok(()) + } + _ => { + unsafe { + (self.context.vtable().Unmap)(self.context.as_ptr(), frame.staging.as_ptr(), 0) + }; + Err(SoftBufferError::PlatformError( + Some("the staging texture was mapped with an unexpected layout".into()), + None, + )) + } + } + } + + fn unmap(&mut self) { + if let Some(frame) = &mut self.frame { + if frame.mapping.take().is_some() { + unsafe { + (self.context.vtable().Unmap)(self.context.as_ptr(), frame.staging.as_ptr(), 0) + }; + } + } + } + + fn mapped(&self) -> (&Frame, &Mapping) { + let frame = self.frame.as_ref().unwrap(); + (frame, frame.mapping.as_ref().unwrap()) + } + + pub fn byte_stride(&self) -> NonZeroU32 { + self.mapped().1.byte_stride + } + + pub fn width(&self) -> NonZeroU32 { + self.mapped().0.width + } + + pub fn height(&self) -> NonZeroU32 { + self.mapped().0.height + } + + pub fn pixels_mut(&mut self) -> &mut [Pixel] { + let (frame, mapping) = self.mapped(); + let len = mapping.byte_stride.get() as usize / 4 * frame.height.get() as usize; + // SAFETY: The mapping holds this many pixels, checked in `map`. It stays valid until the + // texture is unmapped, which needs `&mut self`. + unsafe { slice::from_raw_parts_mut(mapping.pixels.as_ptr(), len) } + } + + pub fn age(&self) -> u8 { + u8::from(self.mapped().0.presented) + } + + /// Copies the damage into the swap chain and presents it. + pub fn present(&mut self, damage: &[Rect]) -> Result<(), SoftBufferError> { + self.unmap(); + let frame = self.frame.as_mut().unwrap(); + let swap_chain = self.swap_chain.as_ref().unwrap(); + let (width, height) = (frame.width.get(), frame.height.get()); + + let mut dirty: Vec = if frame.present_whole_frame { + vec![RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }] + } else { + damage + .iter() + .filter_map(|rect| clip(rect, width, height)) + .collect() + }; + if dirty.is_empty() { + return Ok(()); + } + + let mut back_buffer = ptr::null_mut(); + let result = unsafe { + (swap_chain.vtable().GetBuffer)( + swap_chain.as_ptr(), + 0, + &IID_ID3D11_TEXTURE2D, + &mut back_buffer, + ) + }; + check(result, "failed to get the swap chain's back buffer")?; + let back_buffer = unsafe { Com::::new(back_buffer) }?; + for rect in &dirty { + let source = D3D11_BOX { + left: rect.left as u32, + top: rect.top as u32, + front: 0, + right: rect.right as u32, + bottom: rect.bottom as u32, + back: 1, + }; + unsafe { + (self.context.vtable().CopySubresourceRegion)( + self.context.as_ptr(), + back_buffer.as_ptr(), + 0, + source.left, + source.top, + 0, + frame.staging.as_ptr(), + 0, + &source, + ) + }; + } + drop(back_buffer); + + // DXGI copies what the previous frame changed outside of the dirty rectangles, so the + // back buffer ends up with the whole frame. A whole frame needs no rectangles. + let parameters = DXGI_PRESENT_PARAMETERS { + DirtyRectsCount: if frame.present_whole_frame { + 0 + } else { + dirty.len() as u32 + }, + pDirtyRects: if frame.present_whole_frame { + ptr::null_mut() + } else { + dirty.as_mut_ptr() + }, + pScrollRect: ptr::null_mut(), + pScrollOffset: ptr::null_mut(), + }; + let result = + unsafe { (swap_chain.vtable().Present1)(swap_chain.as_ptr(), 0, 0, ¶meters) }; + // `DXGI_STATUS_OCCLUDED` means that the window isn't visible, not that the present failed. + check(result, "failed to present")?; + frame.present_whole_frame = false; + frame.presented = true; + self.presented = true; + Ok(()) + } +} + +impl Drop for Presenter { + fn drop(&mut self) { + self.unmap(); + } +} + +/// The part of `rect` inside the frame, if any. +fn clip(rect: &Rect, width: u32, height: u32) -> Option { + let left = rect.x.min(width); + let top = rect.y.min(height); + let right = rect.x.saturating_add(rect.width.get()).min(width); + let bottom = rect.y.saturating_add(rect.height.get()).min(height); + // Direct3D textures are at most 16384 pixels wide, so these fit in an `i32`. + (left < right && top < bottom).then_some(RECT { + left: left as i32, + top: top as i32, + right: right as i32, + bottom: bottom as i32, + }) +} + +fn check(result: HRESULT, message: &str) -> Result<(), SoftBufferError> { + if result < 0 { + Err(SoftBufferError::PlatformError( + Some(message.into()), + Some(Box::new(io::Error::from_raw_os_error(result))), + )) + } else { + Ok(()) + } +} + +/// `D3D11CreateDevice`, loaded at run time so that a system without `d3d11.dll` still runs. +fn d3d11_create_device() -> Option { + static FUNCTION: OnceLock> = OnceLock::new(); + *FUNCTION.get_or_init(|| { + // The library stays loaded, as the objects it creates run its code. + let module = unsafe { + LoadLibraryExW( + windows_sys::w!("d3d11.dll"), + ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return None; + } + let function = unsafe { GetProcAddress(module, b"D3D11CreateDevice\0".as_ptr()) }?; + // SAFETY: This is the function's signature. + Some(unsafe { + mem::transmute:: isize, D3D11CreateDevice>(function) + }) + }) +} + +/// An owned COM interface pointer, whose methods are the vtable `V`. +struct Com(NonNull, PhantomData); + +impl Com { + /// Takes ownership of an interface pointer that a call returned. + /// + /// # Safety + /// + /// The pointer must be null, or point to an interface whose vtable starts with `V`, with a + /// reference that the caller owns. + unsafe fn new(pointer: *mut c_void) -> Result { + match NonNull::new(pointer) { + Some(pointer) => Ok(Self(pointer, PhantomData)), + None => Err(SoftBufferError::PlatformError( + Some("a call returned no interface".into()), + None, + )), + } + } + + fn as_ptr(&self) -> *mut c_void { + self.0.as_ptr() + } + + fn vtable(&self) -> &V { + // SAFETY: An interface pointer points to a pointer to its vtable, which starts with `V`. + unsafe { &**self.as_ptr().cast::<*const V>() } + } +} + +impl Drop for Com { + fn drop(&mut self) { + // SAFETY: Every vtable starts with the methods of `IUnknown`. + unsafe { + let vtable = &**self.as_ptr().cast::<*const IUnknownVtbl>(); + (vtable.Release)(self.as_ptr()); + } + } +} + +impl fmt::Debug for Com { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Com").field(&self.0).finish() + } +} + +/// The Direct3D 11 and DXGI definitions used here, from the Windows SDK's `d3d11.h`, `dxgi.h`, +/// `dxgi1_2.h` and `dxgiformat.h`. `windows-sys` doesn't include them. +#[allow(non_camel_case_types, non_snake_case)] +mod ffi { + use std::ffi::c_void; + + use windows_sys::core::{GUID, HRESULT}; + use windows_sys::Win32::Foundation::{HMODULE, HWND, POINT, RECT}; + + pub type D3D11CreateDevice = unsafe extern "system" fn( + adapter: *mut c_void, + driver_type: i32, + software: HMODULE, + flags: u32, + feature_levels: *const i32, + feature_level_count: u32, + sdk_version: u32, + device: *mut *mut c_void, + feature_level: *mut i32, + immediate_context: *mut *mut c_void, + ) -> HRESULT; + + pub const D3D_DRIVER_TYPE_WARP: i32 = 5; + pub const D3D11_SDK_VERSION: u32 = 7; + pub const D3D11_CREATE_DEVICE_BGRA_SUPPORT: u32 = 0x20; + pub const D3D11_USAGE_STAGING: i32 = 3; + pub const D3D11_CPU_ACCESS_WRITE: u32 = 0x10000; + pub const D3D11_CPU_ACCESS_READ: u32 = 0x20000; + pub const D3D11_MAP_READ_WRITE: i32 = 3; + pub const DXGI_FORMAT_UNKNOWN: i32 = 0; + pub const DXGI_FORMAT_B8G8R8A8_UNORM: i32 = 87; + pub const DXGI_USAGE_RENDER_TARGET_OUTPUT: u32 = 0x20; + pub const DXGI_SCALING_NONE: i32 = 1; + pub const DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL: i32 = 3; + pub const DXGI_ALPHA_MODE_IGNORE: i32 = 3; + pub const DXGI_MWA_NO_WINDOW_CHANGES: u32 = 1; + pub const DXGI_MWA_NO_ALT_ENTER: u32 = 2; + + pub const IID_IDXGI_DEVICE: GUID = GUID::from_u128(0x54ec77fa_1377_44e6_8c32_88fd5f44c84c); + pub const IID_IDXGI_FACTORY2: GUID = GUID::from_u128(0x50c83a1c_e072_4c48_87b0_3630fa36a6d0); + pub const IID_ID3D11_TEXTURE2D: GUID = GUID::from_u128(0x6f15aaf2_d208_4e89_9ab4_489535d34f9c); + + #[repr(C)] + pub struct DXGI_SAMPLE_DESC { + pub Count: u32, + pub Quality: u32, + } + + #[repr(C)] + pub struct D3D11_TEXTURE2D_DESC { + pub Width: u32, + pub Height: u32, + pub MipLevels: u32, + pub ArraySize: u32, + pub Format: i32, + pub SampleDesc: DXGI_SAMPLE_DESC, + pub Usage: i32, + pub BindFlags: u32, + pub CPUAccessFlags: u32, + pub MiscFlags: u32, + } + + #[repr(C)] + pub struct D3D11_MAPPED_SUBRESOURCE { + pub pData: *mut c_void, + pub RowPitch: u32, + pub DepthPitch: u32, + } + + #[repr(C)] + pub struct D3D11_BOX { + pub left: u32, + pub top: u32, + pub front: u32, + pub right: u32, + pub bottom: u32, + pub back: u32, + } + + #[repr(C)] + pub struct DXGI_SWAP_CHAIN_DESC1 { + pub Width: u32, + pub Height: u32, + pub Format: i32, + pub Stereo: i32, + pub SampleDesc: DXGI_SAMPLE_DESC, + pub BufferUsage: u32, + pub BufferCount: u32, + pub Scaling: i32, + pub SwapEffect: i32, + pub AlphaMode: i32, + pub Flags: u32, + } + + #[repr(C)] + pub struct DXGI_PRESENT_PARAMETERS { + pub DirtyRectsCount: u32, + pub pDirtyRects: *mut RECT, + pub pScrollRect: *mut RECT, + pub pScrollOffset: *mut POINT, + } + + // Each vtable lists the methods in the order of the headers, up to the last one used here. + // Methods that aren't called are placeholders. + + type Method = usize; + + #[repr(C)] + pub struct IUnknownVtbl { + pub QueryInterface: + unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT, + _AddRef: Method, + pub Release: unsafe extern "system" fn(*mut c_void) -> u32, + } + + #[repr(C)] + pub struct ID3D11DeviceVtbl { + pub base: IUnknownVtbl, + /// `CreateBuffer` and `CreateTexture1D`. + _before_CreateTexture2D: [Method; 2], + pub CreateTexture2D: unsafe extern "system" fn( + *mut c_void, + *const D3D11_TEXTURE2D_DESC, + *const c_void, + *mut *mut c_void, + ) -> HRESULT, + } + + #[repr(C)] + pub struct ID3D11DeviceContextVtbl { + pub base: IUnknownVtbl, + /// The 4 methods of `ID3D11DeviceChild`, then `VSSetConstantBuffers` to `Draw`. + _before_Map: [Method; 11], + pub Map: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + u32, + i32, + u32, + *mut D3D11_MAPPED_SUBRESOURCE, + ) -> HRESULT, + pub Unmap: unsafe extern "system" fn(*mut c_void, *mut c_void, u32), + /// `PSSetConstantBuffers` to `RSSetScissorRects`. + _before_CopySubresourceRegion: [Method; 30], + pub CopySubresourceRegion: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + u32, + u32, + u32, + u32, + *mut c_void, + u32, + *const D3D11_BOX, + ), + } + + /// `IDXGIObject`, which `IDXGIAdapter` inherits without adding methods used here. + #[repr(C)] + pub struct IDXGIObjectVtbl { + pub base: IUnknownVtbl, + /// `SetPrivateData`, `SetPrivateDataInterface` and `GetPrivateData`. + _before_GetParent: [Method; 3], + pub GetParent: + unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT, + } + + #[repr(C)] + pub struct IDXGIDeviceVtbl { + pub base: IDXGIObjectVtbl, + pub GetAdapter: unsafe extern "system" fn(*mut c_void, *mut *mut c_void) -> HRESULT, + } + + #[repr(C)] + pub struct IDXGIFactory2Vtbl { + pub base: IDXGIObjectVtbl, + /// `IDXGIFactory::EnumAdapters`. + _before_MakeWindowAssociation: [Method; 1], + pub MakeWindowAssociation: unsafe extern "system" fn(*mut c_void, HWND, u32) -> HRESULT, + /// `GetWindowAssociation` to `IDXGIFactory2::IsWindowedStereoEnabled`. + _before_CreateSwapChainForHwnd: [Method; 6], + pub CreateSwapChainForHwnd: unsafe extern "system" fn( + *mut c_void, + *mut c_void, + HWND, + *const DXGI_SWAP_CHAIN_DESC1, + *const c_void, + *mut c_void, + *mut *mut c_void, + ) -> HRESULT, + } + + #[repr(C)] + pub struct IDXGISwapChain1Vtbl { + pub base: IDXGIObjectVtbl, + /// `IDXGIDeviceSubObject::GetDevice` and `IDXGISwapChain::Present`. + _before_GetBuffer: [Method; 2], + pub GetBuffer: + unsafe extern "system" fn(*mut c_void, u32, *const GUID, *mut *mut c_void) -> HRESULT, + /// `SetFullscreenState` to `GetDesc`. + _before_ResizeBuffers: [Method; 3], + pub ResizeBuffers: + unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32) -> HRESULT, + /// `ResizeTarget` to `IDXGISwapChain1::GetCoreWindow`. + _before_Present1: [Method; 8], + pub Present1: unsafe extern "system" fn( + *mut c_void, + u32, + u32, + *const DXGI_PRESENT_PARAMETERS, + ) -> HRESULT, + } +} diff --git a/src/backends/win32/tests.rs b/src/backends/win32/tests.rs new file mode 100644 index 00000000..d24341d5 --- /dev/null +++ b/src/backends/win32/tests.rs @@ -0,0 +1,408 @@ +//! Presents into real windows and reads back what DWM shows. + +use std::mem; +use std::num::{NonZeroIsize, NonZeroU32}; +use std::ptr; +use std::slice; +use std::sync::atomic::{AtomicI32, Ordering}; +use std::sync::{mpsc, Arc, Once}; +use std::thread; +use std::time::{Duration, Instant}; + +use raw_window_handle::{ + DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawWindowHandle, + Win32WindowHandle, WindowHandle, +}; +use windows_sys::Win32::Foundation::{HWND, RECT}; +use windows_sys::Win32::Graphics::Gdi; +use windows_sys::Win32::Storage::Xps::{PrintWindow, PW_CLIENTONLY}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::WindowsAndMessaging as wm; + +use super::{GdiPresenter, Presenter}; +use crate::backend_dispatch::SurfaceDispatch; +use crate::{Context, Pixel, Rect, Surface}; + +/// Asks DWM for the window as it composes it, swap chains included. +const PW_RENDERFULLCONTENT: u32 = 2; + +const WIDTH: u32 = 200; +const HEIGHT: u32 = 150; + +const RED: u32 = 0xff0000; +const GREEN: u32 = 0x00ff00; +const BLUE: u32 = 0x0000ff; +const YELLOW: u32 = 0xffff00; +const CYAN: u32 = 0x00ffff; + +#[test] +fn dxgi_presents_damage() { + let window = Window::new(); + let context = Context::new(&window).unwrap(); + let mut surface = Surface::new(&context, &window).unwrap(); + assert!(matches!(presenter(&mut surface), Presenter::Dxgi(_))); + + presents_damage(&window, &mut surface); +} + +#[test] +fn gdi_presents_damage() { + let window = Window::new(); + let context = Context::new(&window).unwrap(); + let mut surface = Surface::new(&context, &window).unwrap(); + // GDI still draws into the window, as nothing was presented through DXGI. + *presenter(&mut surface) = Presenter::Gdi(GdiPresenter::new(window.0).unwrap()); + + presents_damage(&window, &mut surface); +} + +/// Presents a whole frame, rectangles that cover each other, and a smaller frame. +/// +/// With two buffers, each partial present lands on the buffer before the previous one, so the +/// window only shows the right frame if the previous frame's damage reached it too. +fn presents_damage(window: &Window, surface: &mut Surface<&Window, &Window>) { + let mut expected = Frame::new(WIDTH, HEIGHT, RED); + surface + .resize( + NonZeroU32::new(WIDTH).unwrap(), + NonZeroU32::new(HEIGHT).unwrap(), + ) + .unwrap(); + let mut buffer = surface.next_buffer().unwrap(); + assert_eq!(buffer.age(), 0); + expected.draw_into(&mut buffer); + buffer.present().unwrap(); + window.assert_shows(&expected); + + let frames: [&[(Rect, u32)]; 6] = [ + &[(rect(20, 20, 50, 40), BLUE)], + &[(rect(110, 70, 60, 50), GREEN)], + &[(rect(40, 40, 90, 60), YELLOW)], + &[(rect(20, 20, 50, 40), RED)], + // Damage that reaches past the frame is cut to it. + &[(rect(150, 100, 100, 100), CYAN)], + // Rectangles that overlap. + &[(rect(30, 90, 50, 40), BLUE), (rect(60, 110, 50, 30), GREEN)], + ]; + for damage in frames { + let mut buffer = surface.next_buffer().unwrap(); + assert_eq!(buffer.age(), 1); + for &(rect, color) in damage { + expected.fill(rect, color); + } + expected.draw_into(&mut buffer); + let damage: Vec = damage.iter().map(|&(rect, _)| rect).collect(); + buffer.present_with_damage(&damage).unwrap(); + window.assert_shows(&expected); + } + + // A frame smaller than the window is drawn in its top left corner. + let expected = Frame::new(WIDTH / 2, HEIGHT / 2, CYAN); + surface + .resize( + NonZeroU32::new(WIDTH / 2).unwrap(), + NonZeroU32::new(HEIGHT / 2).unwrap(), + ) + .unwrap(); + let mut buffer = surface.next_buffer().unwrap(); + assert_eq!(buffer.age(), 0); + expected.draw_into(&mut buffer); + buffer.present().unwrap(); + window.assert_shows(&expected); +} + +/// Like the `winit_multithread` example, presents from another thread while the window's thread +/// waits for it. +#[test] +fn dxgi_presents_from_another_thread() { + let window = Arc::new(Window::new()); + let context = Context::new(window.clone()).unwrap(); + let mut surface = Surface::new(&context, window.clone()).unwrap(); + assert!(matches!(presenter(&mut surface), Presenter::Dxgi(_))); + + let expected = Arc::new(Frame::new(WIDTH, HEIGHT, GREEN)); + let (done, finished) = mpsc::channel(); + let frame = expected.clone(); + thread::spawn(move || { + surface + .resize( + NonZeroU32::new(WIDTH).unwrap(), + NonZeroU32::new(HEIGHT).unwrap(), + ) + .unwrap(); + for _ in 0..3 { + let mut buffer = surface.next_buffer().unwrap(); + frame.draw_into(&mut buffer); + buffer.present().unwrap(); + } + done.send(surface).unwrap(); + }); + let surface = finished + .recv_timeout(Duration::from_secs(10)) + .expect("presenting from another thread blocked"); + window.assert_shows(&expected); + // The window shows the swap chain only while it exists. + drop(surface); +} + +/// Presents while the window is minimized, then shows the last frame once it's restored. +#[test] +fn dxgi_presents_to_a_minimized_window() { + let window = Arc::new(Window::new()); + let context = Context::new(window.clone()).unwrap(); + let mut surface = Surface::new(&context, window.clone()).unwrap(); + assert!(matches!(presenter(&mut surface), Presenter::Dxgi(_))); + + let mut expected = Frame::new(WIDTH, HEIGHT, RED); + surface + .resize( + NonZeroU32::new(WIDTH).unwrap(), + NonZeroU32::new(HEIGHT).unwrap(), + ) + .unwrap(); + let mut buffer = surface.next_buffer().unwrap(); + expected.draw_into(&mut buffer); + buffer.present().unwrap(); + window.assert_shows(&expected); + + unsafe { wm::ShowWindow(window.0, wm::SW_MINIMIZE) }; + pump(); + // On another thread, so that a present that waits for the window fails the test. + let (done, finished) = mpsc::channel(); + thread::spawn(move || { + for (index, color) in [BLUE, GREEN, YELLOW].into_iter().enumerate() { + let damage = rect(20 + 40 * index as u32, 20, 30, 30); + let mut buffer = surface.next_buffer().unwrap(); + expected.fill(damage, color); + expected.draw_into(&mut buffer); + buffer.present_with_damage(&[damage]).unwrap(); + } + done.send((surface, expected)).unwrap(); + }); + let deadline = Instant::now() + Duration::from_secs(10); + let (mut surface, expected) = loop { + pump(); + match finished.recv_timeout(Duration::from_millis(10)) { + Ok(result) => break result, + Err(_) if Instant::now() < deadline => {} + Err(_) => panic!("presenting to a minimized window blocked"), + } + }; + + unsafe { wm::ShowWindow(window.0, wm::SW_RESTORE) }; + let buffer = surface.next_buffer().unwrap(); + buffer.present_with_damage(&[]).unwrap(); + window.assert_shows(&expected); +} + +fn presenter(surface: &mut Surface) -> &mut Presenter { + let SurfaceDispatch::Win32(surface) = &mut *surface.surface_impl; + &mut surface.presenter +} + +fn rect(x: u32, y: u32, width: u32, height: u32) -> Rect { + Rect { + x, + y, + width: NonZeroU32::new(width).unwrap(), + height: NonZeroU32::new(height).unwrap(), + } +} + +/// The frame that the window should show, as `0xRRGGBB` values. +struct Frame { + width: u32, + height: u32, + pixels: Vec, +} + +impl Frame { + fn new(width: u32, height: u32, color: u32) -> Self { + Self { + width, + height, + pixels: vec![color; (width * height) as usize], + } + } + + fn fill(&mut self, rect: Rect, color: u32) { + let right = (rect.x + rect.width.get()).min(self.width); + let bottom = (rect.y + rect.height.get()).min(self.height); + for y in rect.y..bottom { + for x in rect.x..right { + self.pixels[(y * self.width + x) as usize] = color; + } + } + } + + fn draw_into(&self, buffer: &mut crate::Buffer<'_>) { + assert_eq!(buffer.width().get(), self.width); + assert_eq!(buffer.height().get(), self.height); + for (row, pixels) in buffer + .pixel_rows() + .zip(self.pixels.chunks(self.width as usize)) + { + for (pixel, &color) in row.iter_mut().zip(pixels) { + let [b, g, r, _] = color.to_le_bytes(); + *pixel = Pixel::new_rgb(r, g, b); + } + } + } +} + +/// A top-level window with a client area of `WIDTH` by `HEIGHT` pixels. +struct Window(HWND); + +// SAFETY: A window handle can be used from any thread. +unsafe impl Send for Window {} +unsafe impl Sync for Window {} + +impl Window { + fn new() -> Self { + static REGISTER: Once = Once::new(); + static NEXT_POSITION: AtomicI32 = AtomicI32::new(0); + + let class = windows_sys::w!("softbuffer test window"); + let instance = unsafe { GetModuleHandleW(ptr::null()) }; + REGISTER.call_once(|| { + // Read back pixels instead of scaled ones on displays with a scale factor. + unsafe { wm::SetProcessDPIAware() }; + let class = wm::WNDCLASSW { + lpfnWndProc: Some(wm::DefWindowProcW), + hInstance: instance, + lpszClassName: class, + ..unsafe { mem::zeroed() } + }; + assert_ne!(unsafe { wm::RegisterClassW(&class) }, 0); + }); + + let style = wm::WS_OVERLAPPEDWINDOW | wm::WS_VISIBLE; + let mut frame = RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }; + unsafe { wm::AdjustWindowRectEx(&mut frame, style, 0, 0) }; + // Side by side, so that windows of tests that run at the same time don't cover each other. + let position = 50 + 250 * (NEXT_POSITION.fetch_add(1, Ordering::Relaxed) % 4); + let hwnd = unsafe { + wm::CreateWindowExW( + 0, + class, + windows_sys::w!("softbuffer"), + style, + position, + 50, + frame.right - frame.left, + frame.bottom - frame.top, + ptr::null_mut(), + ptr::null_mut(), + instance, + ptr::null(), + ) + }; + assert!(!hwnd.is_null(), "failed to create a window"); + pump(); + Self(hwnd) + } + + /// Waits until DWM shows the frame in the top left corner of the client area. + fn assert_shows(&self, expected: &Frame) { + // Leave out the corners, which Windows 11 rounds. + let inside = |x: u32, y: u32| { + (8..expected.width.min(WIDTH) - 8).contains(&x) + && (8..expected.height.min(HEIGHT) - 8).contains(&y) + }; + let deadline = Instant::now() + Duration::from_secs(5); + loop { + pump(); + let shown = self.capture(); + let wrong = (0..expected.height) + .flat_map(|y| (0..expected.width).map(move |x| (x, y))) + .filter(|&(x, y)| inside(x, y)) + .find(|&(x, y)| { + shown[(y * WIDTH + x) as usize] + != expected.pixels[(y * expected.width + x) as usize] + }); + match wrong { + None => return, + Some((x, y)) if Instant::now() > deadline => panic!( + "the window shows {:06x} at ({x}, {y}) instead of {:06x}", + shown[(y * WIDTH + x) as usize], + expected.pixels[(y * expected.width + x) as usize], + ), + Some(_) => thread::sleep(Duration::from_millis(20)), + } + } + } + + /// The client area as DWM shows it, as `0xRRGGBB` values. + fn capture(&self) -> Vec { + unsafe { + let dc = Gdi::CreateCompatibleDC(ptr::null_mut()); + let mut info: Gdi::BITMAPINFO = mem::zeroed(); + info.bmiHeader = Gdi::BITMAPINFOHEADER { + biSize: mem::size_of::() as u32, + biWidth: WIDTH as i32, + biHeight: -(HEIGHT as i32), + biPlanes: 1, + biBitCount: 32, + biCompression: Gdi::BI_RGB, + ..mem::zeroed() + }; + let mut bits = ptr::null_mut(); + let bitmap = Gdi::CreateDIBSection( + dc, + &info, + Gdi::DIB_RGB_COLORS, + &mut bits, + ptr::null_mut(), + 0, + ); + assert!(!bitmap.is_null(), "failed to create a bitmap"); + let previous = Gdi::SelectObject(dc, bitmap); + let printed = PrintWindow(self.0, dc, PW_CLIENTONLY | PW_RENDERFULLCONTENT); + let pixels = slice::from_raw_parts(bits.cast::(), (WIDTH * HEIGHT) as usize) + .iter() + .map(|pixel| pixel & 0xffffff) + .collect(); + Gdi::SelectObject(dc, previous); + Gdi::DeleteObject(bitmap); + Gdi::DeleteDC(dc); + assert_ne!(printed, 0, "failed to print the window"); + pixels + } + } +} + +impl Drop for Window { + fn drop(&mut self) { + unsafe { wm::DestroyWindow(self.0) }; + } +} + +impl HasWindowHandle for Window { + fn window_handle(&self) -> Result, HandleError> { + let handle = Win32WindowHandle::new(NonZeroIsize::new(self.0 as isize).unwrap()); + // SAFETY: The window lives as long as `self`. + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Win32(handle)) }) + } +} + +impl HasDisplayHandle for Window { + fn display_handle(&self) -> Result, HandleError> { + Ok(DisplayHandle::windows()) + } +} + +/// Handles the messages of the windows that this thread created. +fn pump() { + unsafe { + let mut message = mem::zeroed(); + while wm::PeekMessageW(&mut message, ptr::null_mut(), 0, 0, wm::PM_REMOVE) != 0 { + wm::TranslateMessage(&message); + wm::DispatchMessageW(&message); + } + } +}