Skip to content

Commit

Permalink
rt(d3d11): avoid QueryInterface in GetSize
Browse files Browse the repository at this point in the history
  • Loading branch information
chyyran committed Sep 28, 2024
1 parent a5c8fcf commit 2fe7702
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions librashader-common/src/d3d11.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{FilterMode, GetSize, Size, WrapMode};
use windows::core::Interface;
use windows::Win32::Foundation::E_NOINTERFACE;
use windows::Win32::Graphics::Direct3D11;
use windows::Win32::Graphics::Direct3D11::{ID3D11Texture2D, D3D11_RESOURCE_DIMENSION_TEXTURE2D};

impl From<WrapMode> for Direct3D11::D3D11_TEXTURE_ADDRESS_MODE {
fn from(value: WrapMode) -> Self {
Expand All @@ -26,7 +27,21 @@ impl GetSize<u32> for Direct3D11::ID3D11RenderTargetView {
type Error = windows::core::Error;

fn size(&self) -> Result<Size<u32>, Self::Error> {
let parent = unsafe { self.GetResource()?.cast::<Direct3D11::ID3D11Texture2D>()? };
let parent: ID3D11Texture2D = unsafe {
let resource = self.GetResource()?;
if resource.GetType() != D3D11_RESOURCE_DIMENSION_TEXTURE2D {
return Err(windows::core::Error::new(
E_NOINTERFACE,
"expected ID3D11Texture2D as the resource for the view.",
));
}
// SAFETY: We know tha the resource is an `ID3D11Texture2D`.
// This downcast is safe because ID3D11Texture2D has ID3D11Resource in its
// inheritance chain.
//
// This check + transmute is cheaper than doing `.cast` (i.e. `QueryInterface`).
std::mem::transmute(resource)
};

let mut desc = Default::default();
unsafe {
Expand All @@ -44,8 +59,21 @@ impl GetSize<u32> for Direct3D11::ID3D11ShaderResourceView {
type Error = windows::core::Error;

fn size(&self) -> Result<Size<u32>, Self::Error> {
let parent = unsafe { self.GetResource()?.cast::<Direct3D11::ID3D11Texture2D>()? };

let parent: ID3D11Texture2D = unsafe {
let resource = self.GetResource()?;
if resource.GetType() != D3D11_RESOURCE_DIMENSION_TEXTURE2D {
return Err(windows::core::Error::new(
E_NOINTERFACE,
"expected ID3D11Texture2D as the resource for the view.",
));
}
// SAFETY: We know tha the resource is an `ID3D11Texture2D`.
// This downcast is safe because ID3D11Texture2D has ID3D11Resource in its
// inheritance chain.
//
// This check + transmute is cheaper than doing `.cast` (i.e. `QueryInterface`).
std::mem::transmute(resource)
};
let mut desc = Default::default();
unsafe {
parent.GetDesc(&mut desc);
Expand Down

0 comments on commit 2fe7702

Please sign in to comment.