Skip to content

Commit be2ec15

Browse files
committed
[wgpu-hal] gfx-rs#5956 windows-rs migration followups and cleanups
PR gfx-rs#5956 wasn't fully complete and still had some outstanding minor issues and cleanups to be done, as well as hidden semantic changes. This addresses a bunch of them: - Remove unnecessary `Error` mapping to `String` as `windows-rs`'s `Error` has a more complete `Display` representation by itself. - Remove `into_result()` as every call could have formatted the `windows-rs` `Error` in a log call directly. - Pass `None` instead of a pointer to an empty slice wherever possible (waiting for microsoft/win32metadata#1971 to trickle down into `windows-rs`). - Remove `.clone()` on COM objects (temporarily increasing the refcount) when it can be avoided by inverting the order of operations on `raw` variables.
1 parent bbdbafd commit be2ec15

File tree

7 files changed

+59
-71
lines changed

7 files changed

+59
-71
lines changed

wgpu-hal/src/auxil/dxgi/result.rs

+6-29
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,33 @@
1-
use std::borrow::Cow;
2-
31
use windows::Win32::{Foundation, Graphics::Dxgi};
42

53
pub(crate) trait HResult<O> {
6-
fn into_result(self) -> Result<O, Cow<'static, str>>;
74
fn into_device_result(self, description: &str) -> Result<O, crate::DeviceError>;
85
}
96
impl<T> HResult<T> for windows::core::Result<T> {
10-
fn into_result(self) -> Result<T, Cow<'static, str>> {
11-
// TODO: use windows-rs built-in error formatting?
12-
let description = match self {
13-
Ok(t) => return Ok(t),
14-
Err(e) if e.code() == Foundation::E_UNEXPECTED => "unexpected",
15-
Err(e) if e.code() == Foundation::E_NOTIMPL => "not implemented",
16-
Err(e) if e.code() == Foundation::E_OUTOFMEMORY => "out of memory",
17-
Err(e) if e.code() == Foundation::E_INVALIDARG => "invalid argument",
18-
Err(e) => return Err(Cow::Owned(format!("{e:?}"))),
19-
};
20-
Err(Cow::Borrowed(description))
21-
}
227
fn into_device_result(self, description: &str) -> Result<T, crate::DeviceError> {
238
#![allow(unreachable_code)]
249

25-
let err_code = if let Err(err) = &self {
26-
Some(err.code())
27-
} else {
28-
None
29-
};
30-
self.into_result().map_err(|err| {
10+
self.map_err(|err| {
3111
log::error!("{} failed: {}", description, err);
3212

33-
let Some(err_code) = err_code else {
34-
unreachable!()
35-
};
36-
37-
match err_code {
13+
match err.code() {
3814
Foundation::E_OUTOFMEMORY => {
3915
#[cfg(feature = "oom_panic")]
4016
panic!("{description} failed: Out of memory");
41-
return crate::DeviceError::OutOfMemory;
17+
crate::DeviceError::OutOfMemory
4218
}
4319
Dxgi::DXGI_ERROR_DEVICE_RESET | Dxgi::DXGI_ERROR_DEVICE_REMOVED => {
4420
#[cfg(feature = "device_lost_panic")]
4521
panic!("{description} failed: Device lost ({err})");
22+
23+
crate::DeviceError::Lost
4624
}
4725
_ => {
4826
#[cfg(feature = "internal_error_panic")]
4927
panic!("{description} failed: {err}");
28+
crate::DeviceError::Unexpected
5029
}
5130
}
52-
53-
crate::DeviceError::Lost
5431
})
5532
}
5633
}

wgpu-hal/src/dx12/command.rs

+23-10
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ impl crate::BufferTextureCopy {
5353

5454
impl super::Temp {
5555
fn prepare_marker(&mut self, marker: &str) -> (&[u16], u32) {
56-
// TODO: Store in HSTRING
5756
self.marker.clear();
5857
self.marker.extend(marker.encode_utf16());
5958
self.marker.push(0);
@@ -153,7 +152,7 @@ impl super::CommandEncoder {
153152
self.update_root_elements();
154153
}
155154

156-
//Note: we have to call this lazily before draw calls. Otherwise, D3D complains
155+
// Note: we have to call this lazily before draw calls. Otherwise, D3D complains
157156
// about the root parameters being incompatible with root signature.
158157
fn update_root_elements(&mut self) {
159158
use super::{BufferViewKind as Bvk, PassKind as Pk};
@@ -265,7 +264,8 @@ impl crate::CommandEncoder for super::CommandEncoder {
265264
unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
266265
let list = loop {
267266
if let Some(list) = self.free_lists.pop() {
268-
let reset_result = unsafe { list.Reset(&self.allocator, None) }.into_result();
267+
// TODO: Is an error expected here and should we print it?
268+
let reset_result = unsafe { list.Reset(&self.allocator, None) };
269269
if reset_result.is_ok() {
270270
break Some(list);
271271
}
@@ -314,7 +314,9 @@ impl crate::CommandEncoder for super::CommandEncoder {
314314
for cmd_buf in command_buffers {
315315
self.free_lists.push(cmd_buf.raw);
316316
}
317-
let _todo_handle_error = unsafe { self.allocator.Reset() };
317+
if let Err(e) = unsafe { self.allocator.Reset() } {
318+
log::error!("ID3D12CommandAllocator::Reset() failed with {e}");
319+
}
318320
}
319321

320322
unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
@@ -725,7 +727,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
725727
cat.clear_value.a as f32,
726728
];
727729
// TODO: Empty slice vs None?
728-
unsafe { list.ClearRenderTargetView(*rtv, &value, Some(&[])) };
730+
unsafe { list.ClearRenderTargetView(*rtv, &value, None) };
729731
}
730732
if let Some(ref target) = cat.resolve_target {
731733
self.pass.resolves.push(super::PassResolve {
@@ -754,12 +756,23 @@ impl crate::CommandEncoder for super::CommandEncoder {
754756
if let Some(ds_view) = ds_view {
755757
if flags != Direct3D12::D3D12_CLEAR_FLAGS::default() {
756758
unsafe {
757-
list.ClearDepthStencilView(
758-
ds_view,
759+
// list.ClearDepthStencilView(
760+
// ds_view,
761+
// flags,
762+
// ds.clear_value.0,
763+
// ds.clear_value.1 as u8,
764+
// None,
765+
// )
766+
// TODO: Replace with the above in the next breaking windows-rs release,
767+
// when https://github.com/microsoft/win32metadata/pull/1971 is in.
768+
(windows_core::Interface::vtable(list).ClearDepthStencilView)(
769+
windows_core::Interface::as_raw(list),
770+
mem::transmute(ds_view),
759771
flags,
760772
ds.clear_value.0,
761773
ds.clear_value.1 as u8,
762-
&[],
774+
0,
775+
std::ptr::null(),
763776
)
764777
}
765778
}
@@ -796,7 +809,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
796809
Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
797810
Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
798811
Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 {
799-
//Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`.
812+
// Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`.
800813
// If it's not the case, we can include the `TextureUses` in `PassResove`.
801814
Transition: mem::ManuallyDrop::new(
802815
Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER {
@@ -813,7 +826,7 @@ impl crate::CommandEncoder for super::CommandEncoder {
813826
Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
814827
Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE,
815828
Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 {
816-
//Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`.
829+
// Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`.
817830
// If it's not the case, we can include the `TextureUses` in `PassResolve`.
818831
Transition: mem::ManuallyDrop::new(
819832
Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER {

wgpu-hal/src/dx12/descriptor.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,18 @@ impl GeneralHeap {
5656
.into_device_result("Descriptor heap creation")?
5757
};
5858

59+
let start = DualHandle {
60+
cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
61+
gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
62+
count: 0,
63+
};
64+
5965
Ok(Self {
60-
raw: raw.clone(),
66+
raw,
6167
ty,
6268
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64,
6369
total_handles,
64-
start: DualHandle {
65-
cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
66-
gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
67-
count: 0,
68-
},
70+
start,
6971
ranges: Mutex::new(RangeAllocator::new(0..total_handles)),
7072
})
7173
}
@@ -268,12 +270,14 @@ impl CpuHeap {
268270
let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
269271
.into_device_result("CPU descriptor heap creation")?;
270272

273+
let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() };
274+
271275
Ok(Self {
272276
inner: Mutex::new(CpuHeapInner {
273-
_raw: raw.clone(),
277+
_raw: raw,
274278
stage: Vec::new(),
275279
}),
276-
start: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
280+
start,
277281
handle_size,
278282
total,
279283
})
@@ -297,7 +301,7 @@ impl fmt::Debug for CpuHeap {
297301
}
298302

299303
pub(super) unsafe fn upload(
300-
device: Direct3D12::ID3D12Device,
304+
device: &Direct3D12::ID3D12Device,
301305
src: &CpuHeapInner,
302306
dst: &GeneralHeap,
303307
dummy_copy_counts: &[u32],

wgpu-hal/src/dx12/device.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1295,7 +1295,7 @@ impl crate::Device for super::Device {
12951295
Some(inner) => {
12961296
let dual = unsafe {
12971297
descriptor::upload(
1298-
self.raw.clone(),
1298+
&self.raw,
12991299
&inner,
13001300
&self.shared.heap_views,
13011301
&desc.layout.copy_counts,
@@ -1309,7 +1309,7 @@ impl crate::Device for super::Device {
13091309
Some(inner) => {
13101310
let dual = unsafe {
13111311
descriptor::upload(
1312-
self.raw.clone(),
1312+
&self.raw,
13131313
&inner,
13141314
&self.shared.heap_samplers,
13151315
&desc.layout.copy_counts,

wgpu-hal/src/dx12/instance.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@ impl crate::Instance for super::Instance {
9898
)
9999
};
100100

101-
match hr.into_result() {
102-
Err(err) => log::warn!("Unable to check for tearing support: {}", err),
101+
match hr {
102+
Err(err) => log::warn!("Unable to check for tearing support: {err}"),
103103
Ok(()) => supports_allow_tearing = true,
104104
}
105105
}

wgpu-hal/src/dx12/mod.rs

+12-18
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,13 @@ use std::{ffi, fmt, mem, num::NonZeroU32, ops::Deref, sync::Arc};
4949
use arrayvec::ArrayVec;
5050
use parking_lot::{Mutex, RwLock};
5151
use windows::{
52-
core::{Interface, Param as _},
52+
core::{Free, Interface, Param as _},
5353
Win32::{
5454
Foundation,
5555
Graphics::{Direct3D, Direct3D12, DirectComposition, Dxgi},
5656
System::Threading,
5757
},
5858
};
59-
use windows_core::Free;
6059

6160
use crate::auxil::{
6261
self,
@@ -1026,8 +1025,8 @@ impl crate::Surface for Surface {
10261025
flags,
10271026
)
10281027
};
1029-
if let Err(err) = result.into_result() {
1030-
log::error!("ResizeBuffers failed: {}", err);
1028+
if let Err(err) = result {
1029+
log::error!("ResizeBuffers failed: {err}");
10311030
return Err(crate::SurfaceError::Other("window is in use"));
10321031
}
10331032
raw
@@ -1092,38 +1091,33 @@ impl crate::Surface for Surface {
10921091

10931092
let swap_chain1 = swap_chain1.map_err(|err| {
10941093
log::error!("SwapChain creation error: {}", err);
1095-
crate::SurfaceError::Other("swap chain creation")
1094+
crate::SurfaceError::Other("swapchain creation")
10961095
})?;
10971096

10981097
match &self.target {
10991098
SurfaceTarget::WndHandle(_) | SurfaceTarget::SurfaceHandle(_) => {}
11001099
SurfaceTarget::Visual(visual) => {
1101-
if let Err(err) = unsafe { visual.SetContent(&swap_chain1) }.into_result() {
1102-
log::error!("Unable to SetContent: {}", err);
1100+
if let Err(err) = unsafe { visual.SetContent(&swap_chain1) } {
1101+
log::error!("Unable to SetContent: {err}");
11031102
return Err(crate::SurfaceError::Other(
11041103
"IDCompositionVisual::SetContent",
11051104
));
11061105
}
11071106
}
11081107
SurfaceTarget::SwapChainPanel(swap_chain_panel) => {
1109-
if let Err(err) =
1110-
unsafe { swap_chain_panel.SetSwapChain(&swap_chain1) }.into_result()
1111-
{
1112-
log::error!("Unable to SetSwapChain: {}", err);
1108+
if let Err(err) = unsafe { swap_chain_panel.SetSwapChain(&swap_chain1) } {
1109+
log::error!("Unable to SetSwapChain: {err}");
11131110
return Err(crate::SurfaceError::Other(
11141111
"ISwapChainPanelNative::SetSwapChain",
11151112
));
11161113
}
11171114
}
11181115
}
11191116

1120-
match swap_chain1.cast::<Dxgi::IDXGISwapChain3>() {
1121-
Ok(swap_chain3) => swap_chain3,
1122-
Err(err) => {
1123-
log::error!("Unable to cast swap chain: {}", err);
1124-
return Err(crate::SurfaceError::Other("swap chain cast to 3"));
1125-
}
1126-
}
1117+
swap_chain1.cast::<Dxgi::IDXGISwapChain3>().map_err(|err| {
1118+
log::error!("Unable to cast swapchain: {}", err);
1119+
crate::SurfaceError::Other("swapchain cast to version 3")
1120+
})?
11271121
}
11281122
};
11291123

wgpu-hal/src/dx12/shader_compilation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ pub(super) fn compile_fxc(
5757
)
5858
};
5959

60-
match hr.into_result() {
60+
match hr {
6161
Ok(()) => {
6262
let shader_data = shader_data.unwrap();
6363
(

0 commit comments

Comments
 (0)