diff --git a/wgpu-hal/src/auxil/dxgi/exception.rs b/wgpu-hal/src/auxil/dxgi/exception.rs index 31d5e6933a8..fceac7db5fc 100644 --- a/wgpu-hal/src/auxil/dxgi/exception.rs +++ b/wgpu-hal/src/auxil/dxgi/exception.rs @@ -46,21 +46,23 @@ unsafe extern "system" fn output_debug_string_handler( exception_info: *mut winnt::EXCEPTION_POINTERS, ) -> i32 { // See https://stackoverflow.com/a/41480827 - let record = &*(*exception_info).ExceptionRecord; + let record = unsafe { &*(*exception_info).ExceptionRecord }; if record.NumberParameters != 2 { return excpt::EXCEPTION_CONTINUE_SEARCH; } let message = match record.ExceptionCode { - winnt::DBG_PRINTEXCEPTION_C => String::from_utf8_lossy(slice::from_raw_parts( - record.ExceptionInformation[1] as *const u8, - record.ExceptionInformation[0], - )), - winnt::DBG_PRINTEXCEPTION_WIDE_C => { - Cow::Owned(String::from_utf16_lossy(slice::from_raw_parts( + winnt::DBG_PRINTEXCEPTION_C => String::from_utf8_lossy(unsafe { + slice::from_raw_parts( + record.ExceptionInformation[1] as *const u8, + record.ExceptionInformation[0], + ) + }), + winnt::DBG_PRINTEXCEPTION_WIDE_C => Cow::Owned(String::from_utf16_lossy(unsafe { + slice::from_raw_parts( record.ExceptionInformation[1] as *const u16, record.ExceptionInformation[0], - ))) - } + ) + })), _ => return excpt::EXCEPTION_CONTINUE_SEARCH, }; diff --git a/wgpu-hal/src/auxil/renderdoc.rs b/wgpu-hal/src/auxil/renderdoc.rs index 712eac4180c..8b994550d61 100644 --- a/wgpu-hal/src/auxil/renderdoc.rs +++ b/wgpu-hal/src/auxil/renderdoc.rs @@ -68,22 +68,23 @@ impl RenderDoc { } }; - let get_api: libloading::Symbol = match renderdoc_lib.get(b"RENDERDOC_GetAPI\0") { - Ok(api) => api, - Err(e) => { - return RenderDoc::NotAvailable { - reason: format!( - "Unable to get RENDERDOC_GetAPI from renderdoc library '{}': {:?}", - renderdoc_filename, e - ), + let get_api: libloading::Symbol = + match unsafe { renderdoc_lib.get(b"RENDERDOC_GetAPI\0") } { + Ok(api) => api, + Err(e) => { + return RenderDoc::NotAvailable { + reason: format!( + "Unable to get RENDERDOC_GetAPI from renderdoc library '{}': {:?}", + renderdoc_filename, e + ), + } } - } - }; + }; let mut obj = ptr::null_mut(); - match get_api(10401, &mut obj) { + match unsafe { get_api(10401, &mut obj) } { 1 => RenderDoc::Available { api: RenderDocApi { - api: *(obj as *mut renderdoc_sys::RENDERDOC_API_1_4_1), + api: unsafe { *(obj as *mut renderdoc_sys::RENDERDOC_API_1_4_1) }, lib: renderdoc_lib, }, }, @@ -115,7 +116,7 @@ impl RenderDoc { pub unsafe fn start_frame_capture(&self, device_handle: Handle, window_handle: Handle) -> bool { match *self { Self::Available { api: ref entry } => { - entry.api.StartFrameCapture.unwrap()(device_handle, window_handle); + unsafe { entry.api.StartFrameCapture.unwrap()(device_handle, window_handle) }; true } Self::NotAvailable { ref reason } => { @@ -129,7 +130,7 @@ impl RenderDoc { pub unsafe fn end_frame_capture(&self, device_handle: Handle, window_handle: Handle) { match *self { Self::Available { api: ref entry } => { - entry.api.EndFrameCapture.unwrap()(device_handle, window_handle); + unsafe { entry.api.EndFrameCapture.unwrap()(device_handle, window_handle) }; } Self::NotAvailable { ref reason } => { log::warn!("Could not end RenderDoc frame capture: {}", reason) diff --git a/wgpu-hal/src/dx11/device.rs b/wgpu-hal/src/dx11/device.rs index 7b095ba1df3..9300f382079 100644 --- a/wgpu-hal/src/dx11/device.rs +++ b/wgpu-hal/src/dx11/device.rs @@ -227,12 +227,14 @@ impl crate::Queue for super::Queue { impl super::D3D11Device { #[allow(trivial_casts)] // come on pub unsafe fn check_feature_support(&self, feature: d3d11::D3D11_FEATURE) -> T { - let mut value = mem::zeroed::(); - let ret = self.CheckFeatureSupport( - feature, - &mut value as *mut T as *mut c_void, - mem::size_of::() as u32, - ); + let mut value = unsafe { mem::zeroed::() }; + let ret = unsafe { + self.CheckFeatureSupport( + feature, + &mut value as *mut T as *mut c_void, + mem::size_of::() as u32, + ) + }; assert_eq!(ret.into_result(), Ok(())); value diff --git a/wgpu-hal/src/dx12/adapter.rs b/wgpu-hal/src/dx12/adapter.rs index b7d70e77fe3..7371b1ad173 100644 --- a/wgpu-hal/src/dx12/adapter.rs +++ b/wgpu-hal/src/dx12/adapter.rs @@ -29,15 +29,17 @@ impl Drop for super::Adapter { impl super::Adapter { pub unsafe fn report_live_objects(&self) { - if let Ok(debug_device) = self - .raw - .cast::() - .into_result() - { - debug_device.ReportLiveDeviceObjects( - d3d12sdklayers::D3D12_RLDO_SUMMARY | d3d12sdklayers::D3D12_RLDO_IGNORE_INTERNAL, - ); - debug_device.destroy(); + if let Ok(debug_device) = unsafe { + self.raw + .cast::() + .into_result() + } { + unsafe { + debug_device.ReportLiveDeviceObjects( + d3d12sdklayers::D3D12_RLDO_SUMMARY | d3d12sdklayers::D3D12_RLDO_IGNORE_INTERNAL, + ) + }; + unsafe { debug_device.destroy() }; } } @@ -365,35 +367,33 @@ impl crate::Adapter for super::Adapter { let mut data = d3d12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: raw_format, - Support1: mem::zeroed(), - Support2: mem::zeroed(), + Support1: unsafe { mem::zeroed() }, + Support2: unsafe { mem::zeroed() }, }; - assert_eq!( - winerror::S_OK, + assert_eq!(winerror::S_OK, unsafe { self.device.CheckFeatureSupport( d3d12::D3D12_FEATURE_FORMAT_SUPPORT, &mut data as *mut _ as *mut _, mem::size_of::() as _, ) - ); + }); // Because we use a different format for SRV and UAV views of depth textures, we need to check // the features that use SRV/UAVs using the no-depth format. let mut data_no_depth = d3d12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: no_depth_format, - Support1: mem::zeroed(), - Support2: mem::zeroed(), + Support1: unsafe { mem::zeroed() }, + Support2: unsafe { mem::zeroed() }, }; if raw_format != no_depth_format { // Only-recheck if we're using a different format - assert_eq!( - winerror::S_OK, + assert_eq!(winerror::S_OK, unsafe { self.device.CheckFeatureSupport( d3d12::D3D12_FEATURE_FORMAT_SUPPORT, &mut data_no_depth as *mut _ as *mut _, mem::size_of::() as _, ) - ); + }); } else { // Same format, just copy over. data_no_depth = data; @@ -462,8 +462,8 @@ impl crate::Adapter for super::Adapter { let current_extent = { match surface.target { SurfaceTarget::WndHandle(wnd_handle) => { - let mut rect: windef::RECT = mem::zeroed(); - if winuser::GetClientRect(wnd_handle, &mut rect) != 0 { + let mut rect: windef::RECT = unsafe { mem::zeroed() }; + if unsafe { winuser::GetClientRect(wnd_handle, &mut rect) } != 0 { Some(wgt::Extent3d { width: (rect.right - rect.left) as u32, height: (rect.bottom - rect.top) as u32, diff --git a/wgpu-hal/src/dx12/command.rs b/wgpu-hal/src/dx12/command.rs index daeaa96e118..9f879e8b636 100644 --- a/wgpu-hal/src/dx12/command.rs +++ b/wgpu-hal/src/dx12/command.rs @@ -64,7 +64,7 @@ impl super::CommandEncoder { self.pass.kind = kind; if let Some(label) = label { let (wide_label, size) = self.temp.prepare_marker(label); - list.BeginEvent(0, wide_label.as_ptr() as *const _, size); + unsafe { list.BeginEvent(0, wide_label.as_ptr() as *const _, size) }; self.pass.has_label = true; } self.pass.dirty_root_elements = 0; @@ -76,7 +76,7 @@ impl super::CommandEncoder { let list = self.list.unwrap(); list.set_descriptor_heaps(&[]); if self.pass.has_label { - list.EndEvent(); + unsafe { list.EndEvent() }; } self.pass.clear(); } @@ -86,11 +86,13 @@ impl super::CommandEncoder { let list = self.list.unwrap(); let index = self.pass.dirty_vertex_buffers.trailing_zeros(); self.pass.dirty_vertex_buffers ^= 1 << index; - list.IASetVertexBuffers( - index, - 1, - self.pass.vertex_buffers.as_ptr().offset(index as isize), - ); + unsafe { + list.IASetVertexBuffers( + index, + 1, + self.pass.vertex_buffers.as_ptr().offset(index as isize), + ); + } } if let Some(root_index) = self.pass.layout.special_constants_root_index { let needs_update = match self.pass.root_elements[root_index as usize] { @@ -244,7 +246,7 @@ impl crate::CommandEncoder for super::CommandEncoder { if let Some(label) = label { let cwstr = conv::map_label(label); - list.SetName(cwstr.as_ptr()); + unsafe { list.SetName(cwstr.as_ptr()) }; } self.list = Some(list); @@ -290,32 +292,38 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut raw = d3d12::D3D12_RESOURCE_BARRIER { Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; - *raw.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: barrier.buffer.resource.as_mut_ptr(), - Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: s0, - StateAfter: s1, + unsafe { + *raw.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: barrier.buffer.resource.as_mut_ptr(), + Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: s0, + StateAfter: s1, + } }; self.temp.barriers.push(raw); } else if barrier.usage.start == crate::BufferUses::STORAGE_READ_WRITE { let mut raw = d3d12::D3D12_RESOURCE_BARRIER { Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; - *raw.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER { - pResource: barrier.buffer.resource.as_mut_ptr(), + unsafe { + *raw.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER { + pResource: barrier.buffer.resource.as_mut_ptr(), + } }; self.temp.barriers.push(raw); } } if !self.temp.barriers.is_empty() { - self.list - .unwrap() - .ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()); + unsafe { + self.list + .unwrap() + .ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()) + }; } } @@ -340,13 +348,15 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut raw = d3d12::D3D12_RESOURCE_BARRIER { Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; - *raw.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: barrier.texture.resource.as_mut_ptr(), - Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: s0, - StateAfter: s1, + unsafe { + *raw.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: barrier.texture.resource.as_mut_ptr(), + Subresource: d3d12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: s0, + StateAfter: s1, + } }; let mip_level_count = match barrier.range.mip_level_count { @@ -383,12 +393,14 @@ impl crate::CommandEncoder for super::CommandEncoder { for rel_mip_level in 0..mip_level_count { for rel_array_layer in 0..array_layer_count { for plane in planes.clone() { - raw.u.Transition_mut().Subresource = - barrier.texture.calc_subresource( - barrier.range.base_mip_level + rel_mip_level, - barrier.range.base_array_layer + rel_array_layer, - plane, - ); + unsafe { + raw.u.Transition_mut().Subresource = + barrier.texture.calc_subresource( + barrier.range.base_mip_level + rel_mip_level, + barrier.range.base_array_layer + rel_array_layer, + plane, + ); + }; self.temp.barriers.push(raw); } } @@ -398,19 +410,23 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut raw = d3d12::D3D12_RESOURCE_BARRIER { Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; - *raw.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER { - pResource: barrier.texture.resource.as_mut_ptr(), + unsafe { + *raw.u.UAV_mut() = d3d12::D3D12_RESOURCE_UAV_BARRIER { + pResource: barrier.texture.resource.as_mut_ptr(), + } }; self.temp.barriers.push(raw); } } if !self.temp.barriers.is_empty() { - self.list - .unwrap() - .ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()); + unsafe { + self.list + .unwrap() + .ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()) + }; } } @@ -419,13 +435,15 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut offset = range.start; while offset < range.end { let size = super::ZERO_BUFFER_SIZE.min(range.end - offset); - list.CopyBufferRegion( - buffer.resource.as_mut_ptr(), - offset, - self.shared.zero_buffer.as_mut_ptr(), - 0, - size, - ); + unsafe { + list.CopyBufferRegion( + buffer.resource.as_mut_ptr(), + offset, + self.shared.zero_buffer.as_mut_ptr(), + 0, + size, + ) + }; offset += size; } } @@ -440,13 +458,15 @@ impl crate::CommandEncoder for super::CommandEncoder { { let list = self.list.unwrap(); for r in regions { - list.CopyBufferRegion( - dst.resource.as_mut_ptr(), - r.dst_offset, - src.resource.as_mut_ptr(), - r.src_offset, - r.size.get(), - ); + unsafe { + list.CopyBufferRegion( + dst.resource.as_mut_ptr(), + r.dst_offset, + src.resource.as_mut_ptr(), + r.src_offset, + r.size.get(), + ) + }; } } @@ -463,27 +483,33 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut src_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: src.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; let mut dst_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: dst.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; for r in regions { let src_box = make_box(&r.src_base.origin, &r.size); - *src_location.u.SubresourceIndex_mut() = src.calc_subresource_for_copy(&r.src_base); - *dst_location.u.SubresourceIndex_mut() = dst.calc_subresource_for_copy(&r.dst_base); - - list.CopyTextureRegion( - &dst_location, - r.dst_base.origin.x, - r.dst_base.origin.y, - r.dst_base.origin.z, - &src_location, - &src_box, - ); + unsafe { + *src_location.u.SubresourceIndex_mut() = src.calc_subresource_for_copy(&r.src_base) + }; + unsafe { + *dst_location.u.SubresourceIndex_mut() = dst.calc_subresource_for_copy(&r.dst_base) + }; + + unsafe { + list.CopyTextureRegion( + &dst_location, + r.dst_base.origin.x, + r.dst_base.origin.y, + r.dst_base.origin.z, + &src_location, + &src_box, + ) + }; } } @@ -499,25 +525,32 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut src_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: src.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; let mut dst_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: dst.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; for r in regions { let src_box = make_box(&wgt::Origin3d::ZERO, &r.size); - *src_location.u.PlacedFootprint_mut() = r.to_subresource_footprint(dst.format); - *dst_location.u.SubresourceIndex_mut() = dst.calc_subresource_for_copy(&r.texture_base); - list.CopyTextureRegion( - &dst_location, - r.texture_base.origin.x, - r.texture_base.origin.y, - r.texture_base.origin.z, - &src_location, - &src_box, - ); + unsafe { + *src_location.u.PlacedFootprint_mut() = r.to_subresource_footprint(dst.format) + }; + unsafe { + *dst_location.u.SubresourceIndex_mut() = + dst.calc_subresource_for_copy(&r.texture_base) + }; + unsafe { + list.CopyTextureRegion( + &dst_location, + r.texture_base.origin.x, + r.texture_base.origin.y, + r.texture_base.origin.z, + &src_location, + &src_box, + ) + }; } } @@ -534,37 +567,48 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut src_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: src.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; let mut dst_location = d3d12::D3D12_TEXTURE_COPY_LOCATION { pResource: dst.resource.as_mut_ptr(), Type: d3d12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; for r in regions { let src_box = make_box(&r.texture_base.origin, &r.size); - *src_location.u.SubresourceIndex_mut() = src.calc_subresource_for_copy(&r.texture_base); - *dst_location.u.PlacedFootprint_mut() = r.to_subresource_footprint(src.format); - list.CopyTextureRegion(&dst_location, 0, 0, 0, &src_location, &src_box); + unsafe { + *src_location.u.SubresourceIndex_mut() = + src.calc_subresource_for_copy(&r.texture_base) + }; + unsafe { + *dst_location.u.PlacedFootprint_mut() = r.to_subresource_footprint(src.format) + }; + unsafe { list.CopyTextureRegion(&dst_location, 0, 0, 0, &src_location, &src_box) }; } } unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { - self.list - .unwrap() - .BeginQuery(set.raw.as_mut_ptr(), set.raw_ty, index); + unsafe { + self.list + .unwrap() + .BeginQuery(set.raw.as_mut_ptr(), set.raw_ty, index) + }; } unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) { - self.list - .unwrap() - .EndQuery(set.raw.as_mut_ptr(), set.raw_ty, index); + unsafe { + self.list + .unwrap() + .EndQuery(set.raw.as_mut_ptr(), set.raw_ty, index) + }; } unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { - self.list.unwrap().EndQuery( - set.raw.as_mut_ptr(), - d3d12::D3D12_QUERY_TYPE_TIMESTAMP, - index, - ); + unsafe { + self.list.unwrap().EndQuery( + set.raw.as_mut_ptr(), + d3d12::D3D12_QUERY_TYPE_TIMESTAMP, + index, + ) + }; } unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range) { // nothing to do here @@ -577,20 +621,22 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, _stride: wgt::BufferSize, ) { - self.list.unwrap().ResolveQueryData( - set.raw.as_mut_ptr(), - set.raw_ty, - range.start, - range.end - range.start, - buffer.resource.as_mut_ptr(), - offset, - ); + unsafe { + self.list.unwrap().ResolveQueryData( + set.raw.as_mut_ptr(), + set.raw_ty, + range.start, + range.end - range.start, + buffer.resource.as_mut_ptr(), + offset, + ) + }; } // render unsafe fn begin_render_pass(&mut self, desc: &crate::RenderPassDescriptor) { - self.begin_pass(super::PassKind::Render, desc.label); + unsafe { self.begin_pass(super::PassKind::Render, desc.label) }; let mut color_views = [native::CpuDescriptor { ptr: 0 }; crate::MAX_COLOR_ATTACHMENTS]; for (rtv, cat) in color_views.iter_mut().zip(desc.color_attachments.iter()) { if let Some(cat) = cat.as_ref() { @@ -612,12 +658,14 @@ impl crate::CommandEncoder for super::CommandEncoder { }; let list = self.list.unwrap(); - list.OMSetRenderTargets( - desc.color_attachments.len() as u32, - color_views.as_ptr(), - 0, - ds_view, - ); + unsafe { + list.OMSetRenderTargets( + desc.color_attachments.len() as u32, + color_views.as_ptr(), + 0, + ds_view, + ) + }; self.pass.resolves.clear(); for (rtv, cat) in color_views.iter().zip(desc.color_attachments.iter()) { @@ -657,7 +705,7 @@ impl crate::CommandEncoder for super::CommandEncoder { if !ds_view.is_null() && !flags.is_empty() { list.clear_depth_stencil_view( - *ds_view, + unsafe { *ds_view }, flags, ds.clear_value.0, ds.clear_value.1 as u8, @@ -680,8 +728,8 @@ impl crate::CommandEncoder for super::CommandEncoder { right: desc.extent.width as i32, bottom: desc.extent.height as i32, }; - list.RSSetViewports(1, &raw_vp); - list.RSSetScissorRects(1, &raw_rect); + unsafe { list.RSSetViewports(1, &raw_vp) }; + unsafe { list.RSSetScissorRects(1, &raw_rect) }; } unsafe fn end_render_pass(&mut self) { @@ -695,54 +743,70 @@ impl crate::CommandEncoder for super::CommandEncoder { let mut barrier = d3d12::D3D12_RESOURCE_BARRIER { Type: d3d12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: d3d12::D3D12_RESOURCE_BARRIER_FLAG_NONE, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; //Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`. // If it's not the case, we can include the `TextureUses` in `PassResove`. - *barrier.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: resolve.src.0.as_mut_ptr(), - Subresource: resolve.src.1, - StateBefore: d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET, - StateAfter: d3d12::D3D12_RESOURCE_STATE_RESOLVE_SOURCE, + unsafe { + *barrier.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: resolve.src.0.as_mut_ptr(), + Subresource: resolve.src.1, + StateBefore: d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: d3d12::D3D12_RESOURCE_STATE_RESOLVE_SOURCE, + } }; self.temp.barriers.push(barrier); - *barrier.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: resolve.dst.0.as_mut_ptr(), - Subresource: resolve.dst.1, - StateBefore: d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET, - StateAfter: d3d12::D3D12_RESOURCE_STATE_RESOLVE_DEST, + unsafe { + *barrier.u.Transition_mut() = d3d12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: resolve.dst.0.as_mut_ptr(), + Subresource: resolve.dst.1, + StateBefore: d3d12::D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: d3d12::D3D12_RESOURCE_STATE_RESOLVE_DEST, + } }; self.temp.barriers.push(barrier); } if !self.temp.barriers.is_empty() { profiling::scope!("ID3D12GraphicsCommandList::ResourceBarrier"); - list.ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()); + unsafe { + list.ResourceBarrier( + self.temp.barriers.len() as u32, + self.temp.barriers.as_ptr(), + ) + }; } for resolve in self.pass.resolves.iter() { profiling::scope!("ID3D12GraphicsCommandList::ResolveSubresource"); - list.ResolveSubresource( - resolve.dst.0.as_mut_ptr(), - resolve.dst.1, - resolve.src.0.as_mut_ptr(), - resolve.src.1, - resolve.format, - ); + unsafe { + list.ResolveSubresource( + resolve.dst.0.as_mut_ptr(), + resolve.dst.1, + resolve.src.0.as_mut_ptr(), + resolve.src.1, + resolve.format, + ) + }; } // Flip all the barriers to reverse, back into `COLOR_TARGET`. for barrier in self.temp.barriers.iter_mut() { - let transition = barrier.u.Transition_mut(); + let transition = unsafe { barrier.u.Transition_mut() }; mem::swap(&mut transition.StateBefore, &mut transition.StateAfter); } if !self.temp.barriers.is_empty() { profiling::scope!("ID3D12GraphicsCommandList::ResourceBarrier"); - list.ResourceBarrier(self.temp.barriers.len() as u32, self.temp.barriers.as_ptr()); + unsafe { + list.ResourceBarrier( + self.temp.barriers.len() as u32, + self.temp.barriers.as_ptr(), + ) + }; } } - self.end_pass(); + unsafe { self.end_pass() }; } unsafe fn set_bind_group( @@ -818,18 +882,22 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn insert_debug_marker(&mut self, label: &str) { let (wide_label, size) = self.temp.prepare_marker(label); - self.list - .unwrap() - .SetMarker(0, wide_label.as_ptr() as *const _, size); + unsafe { + self.list + .unwrap() + .SetMarker(0, wide_label.as_ptr() as *const _, size) + }; } unsafe fn begin_debug_marker(&mut self, group_label: &str) { let (wide_label, size) = self.temp.prepare_marker(group_label); - self.list - .unwrap() - .BeginEvent(0, wide_label.as_ptr() as *const _, size); + unsafe { + self.list + .unwrap() + .BeginEvent(0, wide_label.as_ptr() as *const _, size) + }; } unsafe fn end_debug_marker(&mut self) { - self.list.unwrap().EndEvent() + unsafe { self.list.unwrap().EndEvent() } } unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { @@ -842,7 +910,7 @@ impl crate::CommandEncoder for super::CommandEncoder { }; list.set_pipeline_state(pipeline.raw); - list.IASetPrimitiveTopology(pipeline.topology); + unsafe { list.IASetPrimitiveTopology(pipeline.topology) }; for (index, (vb, &stride)) in self .pass @@ -891,7 +959,7 @@ impl crate::CommandEncoder for super::CommandEncoder { MinDepth: depth_range.start, MaxDepth: depth_range.end, }; - self.list.unwrap().RSSetViewports(1, &raw_vp); + unsafe { self.list.unwrap().RSSetViewports(1, &raw_vp) }; } unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect) { let raw_rect = d3d12::D3D12_RECT { @@ -900,7 +968,7 @@ impl crate::CommandEncoder for super::CommandEncoder { right: (rect.x + rect.w) as i32, bottom: (rect.y + rect.h) as i32, }; - self.list.unwrap().RSSetScissorRects(1, &raw_rect); + unsafe { self.list.unwrap().RSSetScissorRects(1, &raw_rect) }; } unsafe fn set_stencil_reference(&mut self, value: u32) { self.list.unwrap().set_stencil_reference(value); @@ -916,7 +984,7 @@ impl crate::CommandEncoder for super::CommandEncoder { start_instance: u32, instance_count: u32, ) { - self.prepare_draw(start_vertex as i32, start_instance); + unsafe { self.prepare_draw(start_vertex as i32, start_instance) }; self.list .unwrap() .draw(vertex_count, instance_count, start_vertex, start_instance); @@ -929,7 +997,7 @@ impl crate::CommandEncoder for super::CommandEncoder { start_instance: u32, instance_count: u32, ) { - self.prepare_draw(base_vertex, start_instance); + unsafe { self.prepare_draw(base_vertex, start_instance) }; self.list.unwrap().draw_indexed( index_count, instance_count, @@ -944,15 +1012,17 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, draw_count: u32, ) { - self.prepare_draw(0, 0); - self.list.unwrap().ExecuteIndirect( - self.shared.cmd_signatures.draw.as_mut_ptr(), - draw_count, - buffer.resource.as_mut_ptr(), - offset, - ptr::null_mut(), - 0, - ); + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.unwrap().ExecuteIndirect( + self.shared.cmd_signatures.draw.as_mut_ptr(), + draw_count, + buffer.resource.as_mut_ptr(), + offset, + ptr::null_mut(), + 0, + ) + }; } unsafe fn draw_indexed_indirect( &mut self, @@ -960,15 +1030,17 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, draw_count: u32, ) { - self.prepare_draw(0, 0); - self.list.unwrap().ExecuteIndirect( - self.shared.cmd_signatures.draw_indexed.as_mut_ptr(), - draw_count, - buffer.resource.as_mut_ptr(), - offset, - ptr::null_mut(), - 0, - ); + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.unwrap().ExecuteIndirect( + self.shared.cmd_signatures.draw_indexed.as_mut_ptr(), + draw_count, + buffer.resource.as_mut_ptr(), + offset, + ptr::null_mut(), + 0, + ) + }; } unsafe fn draw_indirect_count( &mut self, @@ -978,15 +1050,17 @@ impl crate::CommandEncoder for super::CommandEncoder { count_offset: wgt::BufferAddress, max_count: u32, ) { - self.prepare_draw(0, 0); - self.list.unwrap().ExecuteIndirect( - self.shared.cmd_signatures.draw.as_mut_ptr(), - max_count, - buffer.resource.as_mut_ptr(), - offset, - count_buffer.resource.as_mut_ptr(), - count_offset, - ); + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.unwrap().ExecuteIndirect( + self.shared.cmd_signatures.draw.as_mut_ptr(), + max_count, + buffer.resource.as_mut_ptr(), + offset, + count_buffer.resource.as_mut_ptr(), + count_offset, + ) + }; } unsafe fn draw_indexed_indirect_count( &mut self, @@ -996,24 +1070,26 @@ impl crate::CommandEncoder for super::CommandEncoder { count_offset: wgt::BufferAddress, max_count: u32, ) { - self.prepare_draw(0, 0); - self.list.unwrap().ExecuteIndirect( - self.shared.cmd_signatures.draw_indexed.as_mut_ptr(), - max_count, - buffer.resource.as_mut_ptr(), - offset, - count_buffer.resource.as_mut_ptr(), - count_offset, - ); + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.unwrap().ExecuteIndirect( + self.shared.cmd_signatures.draw_indexed.as_mut_ptr(), + max_count, + buffer.resource.as_mut_ptr(), + offset, + count_buffer.resource.as_mut_ptr(), + count_offset, + ) + }; } // compute unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor) { - self.begin_pass(super::PassKind::Compute, desc.label); + unsafe { self.begin_pass(super::PassKind::Compute, desc.label) }; } unsafe fn end_compute_pass(&mut self) { - self.end_pass(); + unsafe { self.end_pass() }; } unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { @@ -1035,13 +1111,15 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn dispatch_indirect(&mut self, buffer: &super::Buffer, offset: wgt::BufferAddress) { self.prepare_dispatch([0; 3]); //TODO: update special constants indirectly - self.list.unwrap().ExecuteIndirect( - self.shared.cmd_signatures.dispatch.as_mut_ptr(), - 1, - buffer.resource.as_mut_ptr(), - offset, - ptr::null_mut(), - 0, - ); + unsafe { + self.list.unwrap().ExecuteIndirect( + self.shared.cmd_signatures.dispatch.as_mut_ptr(), + 1, + buffer.resource.as_mut_ptr(), + offset, + ptr::null_mut(), + 0, + ) + }; } } diff --git a/wgpu-hal/src/dx12/descriptor.rs b/wgpu-hal/src/dx12/descriptor.rs index 67c8eca4fee..46fdd3eecd6 100644 --- a/wgpu-hal/src/dx12/descriptor.rs +++ b/wgpu-hal/src/dx12/descriptor.rs @@ -157,7 +157,7 @@ impl FixedSizeHeap { } unsafe fn destroy(&self) { - self.raw.destroy(); + unsafe { self.raw.destroy() }; } } @@ -225,7 +225,7 @@ impl CpuPool { pub(super) unsafe fn destroy(&self) { for heap in &self.heaps { - heap.destroy(); + unsafe { heap.destroy() }; } } } @@ -274,7 +274,7 @@ impl CpuHeap { } pub(super) unsafe fn destroy(self) { - self.inner.into_inner().raw.destroy(); + unsafe { self.inner.into_inner().raw.destroy() }; } } @@ -296,14 +296,16 @@ pub(super) unsafe fn upload( ) -> Result { let count = src.stage.len() as u32; let index = dst.allocate_slice(count as u64)?; - device.CopyDescriptors( - 1, - &dst.cpu_descriptor_at(index), - &count, - count, - src.stage.as_ptr(), - dummy_copy_counts.as_ptr(), - dst.ty as u32, - ); + unsafe { + device.CopyDescriptors( + 1, + &dst.cpu_descriptor_at(index), + &count, + count, + src.stage.as_ptr(), + dummy_copy_counts.as_ptr(), + dst.ty as u32, + ) + }; Ok(dst.at(index, count as u64)) } diff --git a/wgpu-hal/src/dx12/device.rs b/wgpu-hal/src/dx12/device.rs index 42bb343fa4f..7971e6140d7 100644 --- a/wgpu-hal/src/dx12/device.rs +++ b/wgpu-hal/src/dx12/device.rs @@ -182,7 +182,7 @@ impl super::Device { .fence .set_event_on_completion(self.idler.event, value); hr.into_device_result("Set event")?; - synchapi::WaitForSingleObject(self.idler.event.0, winbase::INFINITE); + unsafe { synchapi::WaitForSingleObject(self.idler.event.0, winbase::INFINITE) }; Ok(()) } @@ -319,13 +319,13 @@ impl super::Device { impl crate::Device for super::Device { unsafe fn exit(self, queue: super::Queue) { self.rtv_pool.lock().free_handle(self.null_rtv_handle); - self.rtv_pool.into_inner().destroy(); - self.dsv_pool.into_inner().destroy(); - self.srv_uav_pool.into_inner().destroy(); - self.sampler_pool.into_inner().destroy(); - self.shared.destroy(); - self.idler.destroy(); - queue.raw.destroy(); + unsafe { self.rtv_pool.into_inner().destroy() }; + unsafe { self.dsv_pool.into_inner().destroy() }; + unsafe { self.srv_uav_pool.into_inner().destroy() }; + unsafe { self.sampler_pool.into_inner().destroy() }; + unsafe { self.shared.destroy() }; + unsafe { self.idler.destroy() }; + unsafe { queue.raw.destroy() }; } unsafe fn create_buffer( @@ -377,30 +377,32 @@ impl crate::Device for super::Device { VisibleNodeMask: 0, }; - let hr = self.raw.CreateCommittedResource( - &heap_properties, - if self.private_caps.heap_create_not_zeroed { - D3D12_HEAP_FLAG_CREATE_NOT_ZEROED - } else { - d3d12::D3D12_HEAP_FLAG_NONE - }, - &raw_desc, - d3d12::D3D12_RESOURCE_STATE_COMMON, - ptr::null(), - &d3d12::ID3D12Resource::uuidof(), - resource.mut_void(), - ); + let hr = unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.private_caps.heap_create_not_zeroed { + D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + d3d12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + d3d12::D3D12_RESOURCE_STATE_COMMON, + ptr::null(), + &d3d12::ID3D12Resource::uuidof(), + resource.mut_void(), + ) + }; hr.into_device_result("Buffer creation")?; if let Some(label) = desc.label { let cwstr = conv::map_label(label); - resource.SetName(cwstr.as_ptr()); + unsafe { resource.SetName(cwstr.as_ptr()) }; } Ok(super::Buffer { resource, size }) } unsafe fn destroy_buffer(&self, buffer: super::Buffer) { - buffer.resource.destroy(); + unsafe { buffer.resource.destroy() }; } unsafe fn map_buffer( &self, @@ -408,17 +410,17 @@ impl crate::Device for super::Device { range: crate::MemoryRange, ) -> Result { let mut ptr = ptr::null_mut(); - let hr = (*buffer.resource).Map(0, ptr::null(), &mut ptr); + let hr = unsafe { (*buffer.resource).Map(0, ptr::null(), &mut ptr) }; hr.into_device_result("Map buffer")?; Ok(crate::BufferMapping { - ptr: ptr::NonNull::new(ptr.offset(range.start as isize) as *mut _).unwrap(), + ptr: ptr::NonNull::new(unsafe { ptr.offset(range.start as isize) } as *mut _).unwrap(), //TODO: double-check this. Documentation is a bit misleading - // it implies that Map/Unmap is needed to invalidate/flush memory. is_coherent: true, }) } unsafe fn unmap_buffer(&self, buffer: &super::Buffer) -> Result<(), crate::DeviceError> { - (*buffer.resource).Unmap(0, ptr::null()); + unsafe { (*buffer.resource).Unmap(0, ptr::null()) }; Ok(()) } unsafe fn flush_mapped_ranges(&self, _buffer: &super::Buffer, _ranges: I) {} @@ -470,24 +472,26 @@ impl crate::Device for super::Device { VisibleNodeMask: 0, }; - let hr = self.raw.CreateCommittedResource( - &heap_properties, - if self.private_caps.heap_create_not_zeroed { - D3D12_HEAP_FLAG_CREATE_NOT_ZEROED - } else { - d3d12::D3D12_HEAP_FLAG_NONE - }, - &raw_desc, - d3d12::D3D12_RESOURCE_STATE_COMMON, - ptr::null(), // clear value - &d3d12::ID3D12Resource::uuidof(), - resource.mut_void(), - ); + let hr = unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.private_caps.heap_create_not_zeroed { + D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + d3d12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + d3d12::D3D12_RESOURCE_STATE_COMMON, + ptr::null(), // clear value + &d3d12::ID3D12Resource::uuidof(), + resource.mut_void(), + ) + }; hr.into_device_result("Texture creation")?; if let Some(label) = desc.label { let cwstr = conv::map_label(label); - resource.SetName(cwstr.as_ptr()); + unsafe { resource.SetName(cwstr.as_ptr()) }; } Ok(super::Texture { @@ -500,7 +504,7 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_texture(&self, texture: super::Texture) { - texture.resource.destroy(); + unsafe { texture.resource.destroy() }; } unsafe fn create_texture_view( @@ -518,13 +522,15 @@ impl crate::Device for super::Device { texture.calc_subresource(desc.range.base_mip_level, desc.range.base_array_layer, 0), ), handle_srv: if desc.usage.intersects(crate::TextureUses::RESOURCE) { - let raw_desc = view_desc.to_srv(); + let raw_desc = unsafe { view_desc.to_srv() }; let handle = self.srv_uav_pool.lock().alloc_handle(); - self.raw.CreateShaderResourceView( - texture.resource.as_mut_ptr(), - &raw_desc, - handle.raw, - ); + unsafe { + self.raw.CreateShaderResourceView( + texture.resource.as_mut_ptr(), + &raw_desc, + handle.raw, + ) + }; Some(handle) } else { None @@ -532,26 +538,30 @@ impl crate::Device for super::Device { handle_uav: if desc.usage.intersects( crate::TextureUses::STORAGE_READ | crate::TextureUses::STORAGE_READ_WRITE, ) { - let raw_desc = view_desc.to_uav(); + let raw_desc = unsafe { view_desc.to_uav() }; let handle = self.srv_uav_pool.lock().alloc_handle(); - self.raw.CreateUnorderedAccessView( - texture.resource.as_mut_ptr(), - ptr::null_mut(), - &raw_desc, - handle.raw, - ); + unsafe { + self.raw.CreateUnorderedAccessView( + texture.resource.as_mut_ptr(), + ptr::null_mut(), + &raw_desc, + handle.raw, + ) + }; Some(handle) } else { None }, handle_rtv: if desc.usage.intersects(crate::TextureUses::COLOR_TARGET) { - let raw_desc = view_desc.to_rtv(); + let raw_desc = unsafe { view_desc.to_rtv() }; let handle = self.rtv_pool.lock().alloc_handle(); - self.raw.CreateRenderTargetView( - texture.resource.as_mut_ptr(), - &raw_desc, - handle.raw, - ); + unsafe { + self.raw.CreateRenderTargetView( + texture.resource.as_mut_ptr(), + &raw_desc, + handle.raw, + ) + }; Some(handle) } else { None @@ -560,13 +570,15 @@ impl crate::Device for super::Device { .usage .intersects(crate::TextureUses::DEPTH_STENCIL_READ) { - let raw_desc = view_desc.to_dsv(desc.format.into()); + let raw_desc = unsafe { view_desc.to_dsv(desc.format.into()) }; let handle = self.dsv_pool.lock().alloc_handle(); - self.raw.CreateDepthStencilView( - texture.resource.as_mut_ptr(), - &raw_desc, - handle.raw, - ); + unsafe { + self.raw.CreateDepthStencilView( + texture.resource.as_mut_ptr(), + &raw_desc, + handle.raw, + ) + }; Some(handle) } else { None @@ -575,13 +587,15 @@ impl crate::Device for super::Device { .usage .intersects(crate::TextureUses::DEPTH_STENCIL_WRITE) { - let raw_desc = view_desc.to_dsv(FormatAspects::empty()); + let raw_desc = unsafe { view_desc.to_dsv(FormatAspects::empty()) }; let handle = self.dsv_pool.lock().alloc_handle(); - self.raw.CreateDepthStencilView( - texture.resource.as_mut_ptr(), - &raw_desc, - handle.raw, - ); + unsafe { + self.raw.CreateDepthStencilView( + texture.resource.as_mut_ptr(), + &raw_desc, + handle.raw, + ) + }; Some(handle) } else { None @@ -664,7 +678,7 @@ impl crate::Device for super::Device { if let Some(label) = desc.label { let cwstr = conv::map_label(label); - allocator.SetName(cwstr.as_ptr()); + unsafe { allocator.SetName(cwstr.as_ptr()) }; } Ok(super::CommandEncoder { @@ -681,12 +695,12 @@ impl crate::Device for super::Device { unsafe fn destroy_command_encoder(&self, encoder: super::CommandEncoder) { if let Some(list) = encoder.list { list.close(); - list.destroy(); + unsafe { list.destroy() }; } for list in encoder.free_lists { - list.destroy(); + unsafe { list.destroy() }; } - encoder.allocator.destroy(); + unsafe { encoder.allocator.destroy() }; } unsafe fn create_bind_group_layout( @@ -737,10 +751,10 @@ impl crate::Device for super::Device { } unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) { if let Some(cpu_heap) = bg_layout.cpu_heap_views { - cpu_heap.destroy(); + unsafe { cpu_heap.destroy() }; } if let Some(cpu_heap) = bg_layout.cpu_heap_samplers { - cpu_heap.destroy(); + unsafe { cpu_heap.destroy() }; } } @@ -1064,9 +1078,9 @@ impl crate::Device for super::Device { if !error.is_null() { log::error!( "Root signature serialization error: {:?}", - error.as_c_str().to_str().unwrap() + unsafe { error.as_c_str() }.to_str().unwrap() ); - error.destroy(); + unsafe { error.destroy() }; return Err(crate::DeviceError::Lost); } @@ -1074,13 +1088,13 @@ impl crate::Device for super::Device { .raw .create_root_signature(blob, 0) .into_device_result("Root signature creation")?; - blob.destroy(); + unsafe { blob.destroy() }; log::debug!("\traw = {:?}", raw); if let Some(label) = desc.label { let cwstr = conv::map_label(label); - raw.SetName(cwstr.as_ptr()); + unsafe { raw.SetName(cwstr.as_ptr()) }; } Ok(super::PipelineLayout { @@ -1101,7 +1115,7 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_pipeline_layout(&self, pipeline_layout: super::PipelineLayout) { - pipeline_layout.shared.signature.destroy(); + unsafe { pipeline_layout.shared.signature.destroy() }; } unsafe fn create_bind_group( @@ -1155,7 +1169,7 @@ impl crate::Device for super::Device { BufferLocation: gpu_address, SizeInBytes: ((size - 1) | size_mask) + 1, }; - self.raw.CreateConstantBufferView(&raw_desc, handle); + unsafe { self.raw.CreateConstantBufferView(&raw_desc, handle) }; } wgt::BufferBindingType::Storage { read_only: true } => { let mut raw_desc = d3d12::D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -1163,39 +1177,47 @@ impl crate::Device for super::Device { Shader4ComponentMapping: view::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ViewDimension: d3d12::D3D12_SRV_DIMENSION_BUFFER, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; - *raw_desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_SRV { - FirstElement: data.offset / 4, - NumElements: size / 4, - StructureByteStride: 0, - Flags: d3d12::D3D12_BUFFER_SRV_FLAG_RAW, + unsafe { + *raw_desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_SRV { + FirstElement: data.offset / 4, + NumElements: size / 4, + StructureByteStride: 0, + Flags: d3d12::D3D12_BUFFER_SRV_FLAG_RAW, + } + }; + unsafe { + self.raw.CreateShaderResourceView( + data.buffer.resource.as_mut_ptr(), + &raw_desc, + handle, + ) }; - self.raw.CreateShaderResourceView( - data.buffer.resource.as_mut_ptr(), - &raw_desc, - handle, - ); } wgt::BufferBindingType::Storage { read_only: false } => { let mut raw_desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: dxgiformat::DXGI_FORMAT_R32_TYPELESS, ViewDimension: d3d12::D3D12_UAV_DIMENSION_BUFFER, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, + }; + unsafe { + *raw_desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_UAV { + FirstElement: data.offset / 4, + NumElements: size / 4, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: d3d12::D3D12_BUFFER_UAV_FLAG_RAW, + } }; - *raw_desc.u.Buffer_mut() = d3d12::D3D12_BUFFER_UAV { - FirstElement: data.offset / 4, - NumElements: size / 4, - StructureByteStride: 0, - CounterOffsetInBytes: 0, - Flags: d3d12::D3D12_BUFFER_UAV_FLAG_RAW, + unsafe { + self.raw.CreateUnorderedAccessView( + data.buffer.resource.as_mut_ptr(), + ptr::null_mut(), + &raw_desc, + handle, + ) }; - self.raw.CreateUnorderedAccessView( - data.buffer.resource.as_mut_ptr(), - ptr::null_mut(), - &raw_desc, - handle, - ); } } inner.stage.push(handle); @@ -1229,24 +1251,28 @@ impl crate::Device for super::Device { let handle_views = match cpu_views { Some(inner) => { - let dual = descriptor::upload( - self.raw, - &*inner, - &self.shared.heap_views, - &desc.layout.copy_counts, - )?; + let dual = unsafe { + descriptor::upload( + self.raw, + &*inner, + &self.shared.heap_views, + &desc.layout.copy_counts, + ) + }?; Some(dual) } None => None, }; let handle_samplers = match cpu_samplers { Some(inner) => { - let dual = descriptor::upload( - self.raw, - &*inner, - &self.shared.heap_samplers, - &desc.layout.copy_counts, - )?; + let dual = unsafe { + descriptor::upload( + self.raw, + &*inner, + &self.shared.heap_samplers, + &desc.layout.copy_counts, + ) + }?; Some(dual) } None => None, @@ -1400,7 +1426,7 @@ impl crate::Device for super::Device { RasterizerState: raw_rasterizer, DepthStencilState: match desc.depth_stencil { Some(ref ds) => conv::map_depth_stencil(ds), - None => mem::zeroed(), + None => unsafe { mem::zeroed() }, }, InputLayout: d3d12::D3D12_INPUT_LAYOUT_DESC { pInputElementDescs: if input_element_descs.is_empty() { @@ -1441,16 +1467,18 @@ impl crate::Device for super::Device { let mut raw = native::PipelineState::null(); let hr = { profiling::scope!("ID3D12Device::CreateGraphicsPipelineState"); - self.raw.CreateGraphicsPipelineState( - &raw_desc, - &d3d12::ID3D12PipelineState::uuidof(), - raw.mut_void(), - ) + unsafe { + self.raw.CreateGraphicsPipelineState( + &raw_desc, + &d3d12::ID3D12PipelineState::uuidof(), + raw.mut_void(), + ) + } }; - blob_vs.destroy(); + unsafe { blob_vs.destroy() }; if !blob_fs.is_null() { - blob_fs.destroy(); + unsafe { blob_fs.destroy() }; } hr.into_result() @@ -1458,7 +1486,7 @@ impl crate::Device for super::Device { if let Some(name) = desc.label { let cwstr = conv::map_label(name); - raw.SetName(cwstr.as_ptr()); + unsafe { raw.SetName(cwstr.as_ptr()) }; } Ok(super::RenderPipeline { @@ -1469,7 +1497,7 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { - pipeline.raw.destroy(); + unsafe { pipeline.raw.destroy() }; } unsafe fn create_compute_pipeline( @@ -1489,7 +1517,7 @@ impl crate::Device for super::Device { ) }; - blob_cs.destroy(); + unsafe { blob_cs.destroy() }; let raw = pair.into_result().map_err(|err| { crate::PipelineError::Linkage(wgt::ShaderStages::COMPUTE, err.into_owned()) @@ -1497,7 +1525,7 @@ impl crate::Device for super::Device { if let Some(name) = desc.label { let cwstr = conv::map_label(name); - raw.SetName(cwstr.as_ptr()); + unsafe { raw.SetName(cwstr.as_ptr()) }; } Ok(super::ComputePipeline { @@ -1506,7 +1534,7 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) { - pipeline.raw.destroy(); + unsafe { pipeline.raw.destroy() }; } unsafe fn create_query_set( @@ -1535,34 +1563,36 @@ impl crate::Device for super::Device { if let Some(label) = desc.label { let cwstr = conv::map_label(label); - raw.SetName(cwstr.as_ptr()); + unsafe { raw.SetName(cwstr.as_ptr()) }; } Ok(super::QuerySet { raw, raw_ty }) } unsafe fn destroy_query_set(&self, set: super::QuerySet) { - set.raw.destroy(); + unsafe { set.raw.destroy() }; } unsafe fn create_fence(&self) -> Result { let mut raw = native::Fence::null(); - let hr = self.raw.CreateFence( - 0, - d3d12::D3D12_FENCE_FLAG_NONE, - &d3d12::ID3D12Fence::uuidof(), - raw.mut_void(), - ); + let hr = unsafe { + self.raw.CreateFence( + 0, + d3d12::D3D12_FENCE_FLAG_NONE, + &d3d12::ID3D12Fence::uuidof(), + raw.mut_void(), + ) + }; hr.into_device_result("Fence creation")?; Ok(super::Fence { raw }) } unsafe fn destroy_fence(&self, fence: super::Fence) { - fence.raw.destroy(); + unsafe { fence.raw.destroy() }; } unsafe fn get_fence_value( &self, fence: &super::Fence, ) -> Result { - Ok(fence.raw.GetCompletedValue()) + Ok(unsafe { fence.raw.GetCompletedValue() }) } unsafe fn wait( &self, @@ -1570,13 +1600,13 @@ impl crate::Device for super::Device { value: crate::FenceValue, timeout_ms: u32, ) -> Result { - if fence.raw.GetCompletedValue() >= value { + if unsafe { fence.raw.GetCompletedValue() } >= value { return Ok(true); } let hr = fence.raw.set_event_on_completion(self.idler.event, value); hr.into_device_result("Set event")?; - match synchapi::WaitForSingleObject(self.idler.event.0, timeout_ms) { + match unsafe { synchapi::WaitForSingleObject(self.idler.event.0, timeout_ms) } { winbase::WAIT_ABANDONED | winbase::WAIT_FAILED => Err(crate::DeviceError::Lost), winbase::WAIT_OBJECT_0 => Ok(true), winerror::WAIT_TIMEOUT => Ok(false), @@ -1590,8 +1620,10 @@ impl crate::Device for super::Device { unsafe fn start_capture(&self) -> bool { #[cfg(feature = "renderdoc")] { - self.render_doc - .start_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut()) + unsafe { + self.render_doc + .start_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut()) + } } #[cfg(not(feature = "renderdoc"))] false @@ -1599,7 +1631,9 @@ impl crate::Device for super::Device { unsafe fn stop_capture(&self) { #[cfg(feature = "renderdoc")] - self.render_doc - .end_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut()) + unsafe { + self.render_doc + .end_frame_capture(self.raw.as_mut_ptr() as *mut _, ptr::null_mut()) + } } } diff --git a/wgpu-hal/src/dx12/instance.rs b/wgpu-hal/src/dx12/instance.rs index b300c39857f..71f53e140ef 100644 --- a/wgpu-hal/src/dx12/instance.rs +++ b/wgpu-hal/src/dx12/instance.rs @@ -21,7 +21,7 @@ impl crate::Instance for super::Instance { Ok(pair) => match pair.into_result() { Ok(debug_controller) => { debug_controller.enable_layer(); - debug_controller.Release(); + unsafe { debug_controller.Release() }; } Err(err) => { log::warn!("Unable to enable D3D12 debug interface: {}", err); @@ -43,11 +43,13 @@ impl crate::Instance for super::Instance { #[allow(trivial_casts)] if let Some(factory5) = factory.as_factory5() { let mut allow_tearing: minwindef::BOOL = minwindef::FALSE; - let hr = factory5.CheckFeatureSupport( - dxgi1_5::DXGI_FEATURE_PRESENT_ALLOW_TEARING, - &mut allow_tearing as *mut _ as *mut _, - mem::size_of::() as _, - ); + let hr = unsafe { + factory5.CheckFeatureSupport( + dxgi1_5::DXGI_FEATURE_PRESENT_ALLOW_TEARING, + &mut allow_tearing as *mut _ as *mut _, + mem::size_of::() as _, + ) + }; match hr.into_result() { Err(err) => log::warn!("Unable to check for tearing support: {}", err), diff --git a/wgpu-hal/src/dx12/mod.rs b/wgpu-hal/src/dx12/mod.rs index 009a01d42d4..39858fd41d1 100644 --- a/wgpu-hal/src/dx12/mod.rs +++ b/wgpu-hal/src/dx12/mod.rs @@ -100,7 +100,7 @@ impl Instance { ) -> Surface { Surface { factory: self.factory, - target: SurfaceTarget::Visual(native::WeakPtr::from_raw(visual)), + target: SurfaceTarget::Visual(unsafe { native::WeakPtr::from_raw(visual) }), supports_allow_tearing: self.supports_allow_tearing, swap_chain: None, } @@ -183,7 +183,7 @@ struct Idler { impl Idler { unsafe fn destroy(self) { - self.fence.destroy(); + unsafe { self.fence.destroy() }; } } @@ -195,9 +195,9 @@ struct CommandSignatures { impl CommandSignatures { unsafe fn destroy(&self) { - self.draw.destroy(); - self.draw_indexed.destroy(); - self.dispatch.destroy(); + unsafe { self.draw.destroy() }; + unsafe { self.draw_indexed.destroy() }; + unsafe { self.dispatch.destroy() }; } } @@ -210,10 +210,10 @@ struct DeviceShared { impl DeviceShared { unsafe fn destroy(&self) { - self.zero_buffer.destroy(); - self.cmd_signatures.destroy(); - self.heap_views.raw.destroy(); - self.heap_samplers.raw.destroy(); + unsafe { self.zero_buffer.destroy() }; + unsafe { self.cmd_signatures.destroy() }; + unsafe { self.heap_views.raw.destroy() }; + unsafe { self.heap_samplers.raw.destroy() }; } } @@ -538,7 +538,7 @@ unsafe impl Sync for ComputePipeline {} impl SwapChain { unsafe fn release_resources(self) -> native::WeakPtr { for resource in self.resources { - resource.destroy(); + unsafe { resource.destroy() }; } self.raw } @@ -551,7 +551,7 @@ impl SwapChain { Some(duration) => duration.as_millis() as u32, None => winbase::INFINITE, }; - match synchapi::WaitForSingleObject(self.waitable, timeout_ms) { + match unsafe { synchapi::WaitForSingleObject(self.waitable, timeout_ms) } { winbase::WAIT_ABANDONED | winbase::WAIT_FAILED => Err(crate::SurfaceError::Lost), winbase::WAIT_OBJECT_0 => Ok(true), winerror::WAIT_TIMEOUT => Ok(false), @@ -583,16 +583,18 @@ impl crate::Surface for Surface { //Note: this path doesn't properly re-initialize all of the things Some(sc) => { // can't have image resources in flight used by GPU - let _ = device.wait_idle(); - - let raw = sc.release_resources(); - let result = raw.ResizeBuffers( - config.swap_chain_size, - config.extent.width, - config.extent.height, - non_srgb_format, - flags, - ); + let _ = unsafe { device.wait_idle() }; + + let raw = unsafe { sc.release_resources() }; + let result = unsafe { + raw.ResizeBuffers( + config.swap_chain_size, + config.extent.width, + config.extent.height, + non_srgb_format, + flags, + ) + }; if let Err(err) = result.into_result() { log::error!("ResizeBuffers failed: {}", err); return Err(crate::SurfaceError::Other("window is in use")); @@ -654,7 +656,8 @@ impl crate::Surface for Surface { match self.target { SurfaceTarget::WndHandle(_) => {} SurfaceTarget::Visual(visual) => { - if let Err(err) = visual.SetContent(swap_chain1.as_unknown()).into_result() + if let Err(err) = + unsafe { visual.SetContent(swap_chain1.as_unknown()) }.into_result() { log::error!("Unable to SetContent: {}", err); return Err(crate::SurfaceError::Other( @@ -664,9 +667,9 @@ impl crate::Surface for Surface { } } - match swap_chain1.cast::().into_result() { + match unsafe { swap_chain1.cast::() }.into_result() { Ok(swap_chain3) => { - swap_chain1.destroy(); + unsafe { swap_chain1.destroy() }; swap_chain3 } Err(err) => { @@ -682,20 +685,24 @@ impl crate::Surface for Surface { // Disable automatic Alt+Enter handling by DXGI. const DXGI_MWA_NO_WINDOW_CHANGES: u32 = 1; const DXGI_MWA_NO_ALT_ENTER: u32 = 2; - self.factory.MakeWindowAssociation( - wnd_handle, - DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER, - ); + unsafe { + self.factory.MakeWindowAssociation( + wnd_handle, + DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER, + ) + }; } SurfaceTarget::Visual(_) => {} } - swap_chain.SetMaximumFrameLatency(config.swap_chain_size); - let waitable = swap_chain.GetFrameLatencyWaitableObject(); + unsafe { swap_chain.SetMaximumFrameLatency(config.swap_chain_size) }; + let waitable = unsafe { swap_chain.GetFrameLatencyWaitableObject() }; let mut resources = vec![native::Resource::null(); config.swap_chain_size as usize]; for (i, res) in resources.iter_mut().enumerate() { - swap_chain.GetBuffer(i as _, &d3d12::ID3D12Resource::uuidof(), res.mut_void()); + unsafe { + swap_chain.GetBuffer(i as _, &d3d12::ID3D12Resource::uuidof(), res.mut_void()) + }; } self.swap_chain = Some(SwapChain { @@ -713,12 +720,12 @@ impl crate::Surface for Surface { unsafe fn unconfigure(&mut self, device: &Device) { if let Some(mut sc) = self.swap_chain.take() { - let _ = sc.wait(None); + let _ = unsafe { sc.wait(None) }; //TODO: this shouldn't be needed, // but it complains that the queue is still used otherwise - let _ = device.wait_idle(); - let raw = sc.release_resources(); - raw.destroy(); + let _ = unsafe { device.wait_idle() }; + let raw = unsafe { sc.release_resources() }; + unsafe { raw.destroy() }; } } @@ -728,9 +735,9 @@ impl crate::Surface for Surface { ) -> Result>, crate::SurfaceError> { let sc = self.swap_chain.as_mut().unwrap(); - sc.wait(timeout)?; + unsafe { sc.wait(timeout) }?; - let base_index = sc.raw.GetCurrentBackBufferIndex() as usize; + let base_index = unsafe { sc.raw.GetCurrentBackBufferIndex() } as usize; let index = (base_index + sc.acquired_count) % sc.resources.len(); sc.acquired_count += 1; @@ -793,14 +800,14 @@ impl crate::Queue for Queue { }; profiling::scope!("IDXGISwapchain3::Present"); - sc.raw.Present(interval, flags); + unsafe { sc.raw.Present(interval, flags) }; Ok(()) } unsafe fn get_timestamp_period(&self) -> f32 { let mut frequency = 0u64; - self.raw.GetTimestampFrequency(&mut frequency); + unsafe { self.raw.GetTimestampFrequency(&mut frequency) }; (1_000_000_000.0 / frequency as f64) as f32 } } diff --git a/wgpu-hal/src/dx12/view.rs b/wgpu-hal/src/dx12/view.rs index 81e187aaf15..39d97073128 100644 --- a/wgpu-hal/src/dx12/view.rs +++ b/wgpu-hal/src/dx12/view.rs @@ -42,16 +42,18 @@ impl ViewDescriptor { Format: self.format_nodepth, ViewDimension: 0, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; match self.dimension { wgt::TextureViewDimension::D1 => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE1D; - *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } } } /* @@ -67,67 +69,81 @@ impl ViewDescriptor { }*/ wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DMS; - *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_SRV { - UnusedField_NothingToDefine: 0, + unsafe { + *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_SRV { + UnusedField_NothingToDefine: 0, + } } } wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2D; - *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - PlaneSlice: 0, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array if self.multisampled => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; - *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_SRV { - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, + unsafe { + *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_SRV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE2DARRAY; - *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, - PlaneSlice: 0, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + } } } wgt::TextureViewDimension::D3 => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURE3D; - *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } } } wgt::TextureViewDimension::Cube if self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURECUBE; - *desc.u.TextureCube_mut() = d3d12::D3D12_TEXCUBE_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.TextureCube_mut() = d3d12::D3D12_TEXCUBE_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } } } wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { desc.ViewDimension = d3d12::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; - *desc.u.TextureCubeArray_mut() = d3d12::D3D12_TEXCUBE_ARRAY_SRV { - MostDetailedMip: self.mip_level_base, - MipLevels: self.mip_level_count, - First2DArrayFace: self.array_layer_base, - NumCubes: if self.array_layer_count == !0 { - !0 - } else { - self.array_layer_count / 6 - }, - ResourceMinLODClamp: 0.0, + unsafe { + *desc.u.TextureCubeArray_mut() = d3d12::D3D12_TEXCUBE_ARRAY_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + First2DArrayFace: self.array_layer_base, + NumCubes: if self.array_layer_count == !0 { + !0 + } else { + self.array_layer_count / 6 + }, + ResourceMinLODClamp: 0.0, + } } } } @@ -139,14 +155,16 @@ impl ViewDescriptor { let mut desc = d3d12::D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: self.format_nodepth, ViewDimension: 0, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; match self.dimension { wgt::TextureViewDimension::D1 => { desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE1D; - *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_UAV { - MipSlice: self.mip_level_base, + unsafe { + *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_UAV { + MipSlice: self.mip_level_base, + } } } /* @@ -160,26 +178,32 @@ impl ViewDescriptor { }*/ wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE2D; - *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_UAV { - MipSlice: self.mip_level_base, - PlaneSlice: 0, + unsafe { + *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_UAV { + MipSlice: self.mip_level_base, + PlaneSlice: 0, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE2DARRAY; - *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_UAV { - MipSlice: self.mip_level_base, - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, - PlaneSlice: 0, + unsafe { + *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_UAV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: 0, + } } } wgt::TextureViewDimension::D3 => { desc.ViewDimension = d3d12::D3D12_UAV_DIMENSION_TEXTURE3D; - *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_UAV { - MipSlice: self.mip_level_base, - FirstWSlice: self.array_layer_base, - WSize: self.array_layer_count, + unsafe { + *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_UAV { + MipSlice: self.mip_level_base, + FirstWSlice: self.array_layer_base, + WSize: self.array_layer_count, + } } } wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { @@ -194,14 +218,16 @@ impl ViewDescriptor { let mut desc = d3d12::D3D12_RENDER_TARGET_VIEW_DESC { Format: self.format, ViewDimension: 0, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; match self.dimension { wgt::TextureViewDimension::D1 => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE1D; - *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_RTV { - MipSlice: self.mip_level_base, + unsafe { + *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_RTV { + MipSlice: self.mip_level_base, + } } } /* @@ -215,41 +241,51 @@ impl ViewDescriptor { }*/ wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DMS; - *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_RTV { - UnusedField_NothingToDefine: 0, + unsafe { + *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_RTV { + UnusedField_NothingToDefine: 0, + } } } wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2D; - *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_RTV { - MipSlice: self.mip_level_base, - PlaneSlice: 0, + unsafe { + *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_RTV { + MipSlice: self.mip_level_base, + PlaneSlice: 0, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array if self.multisampled => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; - *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_RTV { - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, + unsafe { + *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_RTV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY; - *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_RTV { - MipSlice: self.mip_level_base, - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, - PlaneSlice: 0, + unsafe { + *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_RTV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: 0, + } } } wgt::TextureViewDimension::D3 => { desc.ViewDimension = d3d12::D3D12_RTV_DIMENSION_TEXTURE3D; - *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_RTV { - MipSlice: self.mip_level_base, - FirstWSlice: self.array_layer_base, - WSize: self.array_layer_count, + unsafe { + *desc.u.Texture3D_mut() = d3d12::D3D12_TEX3D_RTV { + MipSlice: self.mip_level_base, + FirstWSlice: self.array_layer_base, + WSize: self.array_layer_count, + } } } wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { @@ -277,14 +313,16 @@ impl ViewDescriptor { } flags }, - u: mem::zeroed(), + u: unsafe { mem::zeroed() }, }; match self.dimension { wgt::TextureViewDimension::D1 => { desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE1D; - *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_DSV { - MipSlice: self.mip_level_base, + unsafe { + *desc.u.Texture1D_mut() = d3d12::D3D12_TEX1D_DSV { + MipSlice: self.mip_level_base, + } } } /* @@ -298,31 +336,39 @@ impl ViewDescriptor { }*/ wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DMS; - *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_DSV { - UnusedField_NothingToDefine: 0, + unsafe { + *desc.u.Texture2DMS_mut() = d3d12::D3D12_TEX2DMS_DSV { + UnusedField_NothingToDefine: 0, + } } } wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2D; - *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_DSV { - MipSlice: self.mip_level_base, + unsafe { + *desc.u.Texture2D_mut() = d3d12::D3D12_TEX2D_DSV { + MipSlice: self.mip_level_base, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array if self.multisampled => { desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; - *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_DSV { - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, + unsafe { + *desc.u.Texture2DMSArray_mut() = d3d12::D3D12_TEX2DMS_ARRAY_DSV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } } } wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { desc.ViewDimension = d3d12::D3D12_DSV_DIMENSION_TEXTURE2DARRAY; - *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_DSV { - MipSlice: self.mip_level_base, - FirstArraySlice: self.array_layer_base, - ArraySize: self.array_layer_count, + unsafe { + *desc.u.Texture2DArray_mut() = d3d12::D3D12_TEX2D_ARRAY_DSV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } } } wgt::TextureViewDimension::D3 diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 3f09101c2e3..189bd3d9511 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -41,6 +41,7 @@ #![warn( trivial_casts, trivial_numeric_casts, + unsafe_op_in_unsafe_fn, unused_extern_crates, unused_qualifications, // We don't match on a reference, unless required. diff --git a/wgpu-hal/src/vulkan/adapter.rs b/wgpu-hal/src/vulkan/adapter.rs index 86e0893b27b..dac87d717f0 100644 --- a/wgpu-hal/src/vulkan/adapter.rs +++ b/wgpu-hal/src/vulkan/adapter.rs @@ -1118,9 +1118,11 @@ impl super::Adapter { ) -> Result, crate::DeviceError> { let mem_properties = { profiling::scope!("vkGetPhysicalDeviceMemoryProperties"); - self.instance - .raw - .get_physical_device_memory_properties(self.raw) + unsafe { + self.instance + .raw + .get_physical_device_memory_properties(self.raw) + } }; let memory_types = &mem_properties.memory_types[..mem_properties.memory_type_count as usize]; @@ -1227,7 +1229,7 @@ impl super::Adapter { let raw_queue = { profiling::scope!("vkGetDeviceQueue"); - raw_device.get_device_queue(family_index, queue_index) + unsafe { raw_device.get_device_queue(family_index, queue_index) } }; let shared = Arc::new(super::DeviceShared { @@ -1254,9 +1256,11 @@ impl super::Adapter { }); let mut relay_semaphores = [vk::Semaphore::null(); 2]; for sem in relay_semaphores.iter_mut() { - *sem = shared - .raw - .create_semaphore(&vk::SemaphoreCreateInfo::builder(), None)?; + unsafe { + *sem = shared + .raw + .create_semaphore(&vk::SemaphoreCreateInfo::builder(), None)? + }; } let queue = super::Queue { raw: raw_queue, @@ -1352,18 +1356,20 @@ impl crate::Adapter for super::Adapter { .build(); let raw_device = { profiling::scope!("vkCreateDevice"); - self.instance.raw.create_device(self.raw, &info, None)? + unsafe { self.instance.raw.create_device(self.raw, &info, None)? } }; - self.device_from_raw( - raw_device, - true, - &enabled_extensions, - features, - uab_types, - family_info.queue_family_index, - 0, - ) + unsafe { + self.device_from_raw( + raw_device, + true, + &enabled_extensions, + features, + uab_types, + family_info.queue_family_index, + 0, + ) + } } unsafe fn texture_format_capabilities( @@ -1373,10 +1379,11 @@ impl crate::Adapter for super::Adapter { use crate::TextureFormatCapabilities as Tfc; let vk_format = self.private_caps.map_texture_format(format); - let properties = self - .instance - .raw - .get_physical_device_format_properties(self.raw, vk_format); + let properties = unsafe { + self.instance + .raw + .get_physical_device_format_properties(self.raw, vk_format) + }; let features = properties.optimal_tiling_features; let mut flags = Tfc::empty(); @@ -1442,11 +1449,13 @@ impl crate::Adapter for super::Adapter { let queue_family_index = 0; //TODO { profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR"); - match surface.functor.get_physical_device_surface_support( - self.raw, - queue_family_index, - surface.raw, - ) { + match unsafe { + surface.functor.get_physical_device_surface_support( + self.raw, + queue_family_index, + surface.raw, + ) + } { Ok(true) => (), Ok(false) => return None, Err(e) => { @@ -1458,10 +1467,11 @@ impl crate::Adapter for super::Adapter { let caps = { profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); - match surface - .functor - .get_physical_device_surface_capabilities(self.raw, surface.raw) - { + match unsafe { + surface + .functor + .get_physical_device_surface_capabilities(self.raw, surface.raw) + } { Ok(caps) => caps, Err(e) => { log::error!("get_physical_device_surface_capabilities: {}", e); @@ -1503,10 +1513,11 @@ impl crate::Adapter for super::Adapter { let raw_present_modes = { profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR"); - match surface - .functor - .get_physical_device_surface_present_modes(self.raw, surface.raw) - { + match unsafe { + surface + .functor + .get_physical_device_surface_present_modes(self.raw, surface.raw) + } { Ok(present_modes) => present_modes, Err(e) => { log::error!("get_physical_device_surface_present_modes: {}", e); @@ -1517,10 +1528,11 @@ impl crate::Adapter for super::Adapter { let raw_surface_formats = { profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR"); - match surface - .functor - .get_physical_device_surface_formats(self.raw, surface.raw) - { + match unsafe { + surface + .functor + .get_physical_device_surface_formats(self.raw, surface.raw) + } { Ok(formats) => formats, Err(e) => { log::error!("get_physical_device_surface_formats: {}", e); diff --git a/wgpu-hal/src/vulkan/command.rs b/wgpu-hal/src/vulkan/command.rs index e225ca83569..aa3d409ce13 100644 --- a/wgpu-hal/src/vulkan/command.rs +++ b/wgpu-hal/src/vulkan/command.rs @@ -50,18 +50,20 @@ impl crate::CommandEncoder for super::CommandEncoder { .command_pool(self.raw) .command_buffer_count(ALLOCATION_GRANULARITY) .build(); - let cmd_buf_vec = self.device.raw.allocate_command_buffers(&vk_info)?; + let cmd_buf_vec = unsafe { self.device.raw.allocate_command_buffers(&vk_info)? }; self.free.extend(cmd_buf_vec); } let raw = self.free.pop().unwrap(); // Set the name unconditionally, since there might be a // previous name assigned to this. - self.device.set_object_name( - vk::ObjectType::COMMAND_BUFFER, - raw, - label.unwrap_or_default(), - ); + unsafe { + self.device.set_object_name( + vk::ObjectType::COMMAND_BUFFER, + raw, + label.unwrap_or_default(), + ) + }; // Reset this in case the last renderpass was never ended. self.rpass_debug_marker_active = false; @@ -69,7 +71,7 @@ impl crate::CommandEncoder for super::CommandEncoder { let vk_info = vk::CommandBufferBeginInfo::builder() .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT) .build(); - self.device.raw.begin_command_buffer(raw, &vk_info)?; + unsafe { self.device.raw.begin_command_buffer(raw, &vk_info) }?; self.active = raw; Ok(()) @@ -78,7 +80,7 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn end_encoding(&mut self) -> Result { let raw = self.active; self.active = vk::CommandBuffer::null(); - self.device.raw.end_command_buffer(raw)?; + unsafe { self.device.raw.end_command_buffer(raw) }?; Ok(super::CommandBuffer { raw }) } @@ -95,10 +97,11 @@ impl crate::CommandEncoder for super::CommandEncoder { self.free .extend(cmd_bufs.into_iter().map(|cmd_buf| cmd_buf.raw)); self.free.append(&mut self.discarded); - let _ = self - .device - .raw - .reset_command_pool(self.raw, vk::CommandPoolResetFlags::RELEASE_RESOURCES); + let _ = unsafe { + self.device + .raw + .reset_command_pool(self.raw, vk::CommandPoolResetFlags::RELEASE_RESOURCES) + }; } unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) @@ -128,15 +131,17 @@ impl crate::CommandEncoder for super::CommandEncoder { } if !vk_barriers.is_empty() { - self.device.raw.cmd_pipeline_barrier( - self.active, - src_stages, - dst_stages, - vk::DependencyFlags::empty(), - &[], - vk_barriers, - &[], - ); + unsafe { + self.device.raw.cmd_pipeline_barrier( + self.active, + src_stages, + dst_stages, + vk::DependencyFlags::empty(), + &[], + vk_barriers, + &[], + ) + }; } } @@ -171,26 +176,30 @@ impl crate::CommandEncoder for super::CommandEncoder { } if !vk_barriers.is_empty() { - self.device.raw.cmd_pipeline_barrier( - self.active, - src_stages, - dst_stages, - vk::DependencyFlags::empty(), - &[], - &[], - vk_barriers, - ); + unsafe { + self.device.raw.cmd_pipeline_barrier( + self.active, + src_stages, + dst_stages, + vk::DependencyFlags::empty(), + &[], + &[], + vk_barriers, + ) + }; } } unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) { - self.device.raw.cmd_fill_buffer( - self.active, - buffer.raw, - range.start, - range.end - range.start, - 0, - ); + unsafe { + self.device.raw.cmd_fill_buffer( + self.active, + buffer.raw, + range.start, + range.end - range.start, + 0, + ) + }; } unsafe fn copy_buffer_to_buffer( @@ -207,12 +216,14 @@ impl crate::CommandEncoder for super::CommandEncoder { size: r.size.get(), }); - self.device.raw.cmd_copy_buffer( - self.active, - src.raw, - dst.raw, - &smallvec::SmallVec::<[vk::BufferCopy; 32]>::from_iter(vk_regions_iter), - ); + unsafe { + self.device.raw.cmd_copy_buffer( + self.active, + src.raw, + dst.raw, + &smallvec::SmallVec::<[vk::BufferCopy; 32]>::from_iter(vk_regions_iter), + ) + }; } unsafe fn copy_texture_to_texture( @@ -244,14 +255,16 @@ impl crate::CommandEncoder for super::CommandEncoder { } }); - self.device.raw.cmd_copy_image( - self.active, - src.raw, - src_layout, - dst.raw, - DST_IMAGE_LAYOUT, - &smallvec::SmallVec::<[vk::ImageCopy; 32]>::from_iter(vk_regions_iter), - ); + unsafe { + self.device.raw.cmd_copy_image( + self.active, + src.raw, + src_layout, + dst.raw, + DST_IMAGE_LAYOUT, + &smallvec::SmallVec::<[vk::ImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; } unsafe fn copy_buffer_to_texture( @@ -264,13 +277,15 @@ impl crate::CommandEncoder for super::CommandEncoder { { let vk_regions_iter = dst.map_buffer_copies(regions); - self.device.raw.cmd_copy_buffer_to_image( - self.active, - src.raw, - dst.raw, - DST_IMAGE_LAYOUT, - &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), - ); + unsafe { + self.device.raw.cmd_copy_buffer_to_image( + self.active, + src.raw, + dst.raw, + DST_IMAGE_LAYOUT, + &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; } unsafe fn copy_texture_to_buffer( @@ -285,41 +300,49 @@ impl crate::CommandEncoder for super::CommandEncoder { let src_layout = conv::derive_image_layout(src_usage, src.aspects); let vk_regions_iter = src.map_buffer_copies(regions); - self.device.raw.cmd_copy_image_to_buffer( - self.active, - src.raw, - src_layout, - dst.raw, - &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), - ); + unsafe { + self.device.raw.cmd_copy_image_to_buffer( + self.active, + src.raw, + src_layout, + dst.raw, + &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; } unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { - self.device.raw.cmd_begin_query( - self.active, - set.raw, - index, - vk::QueryControlFlags::empty(), - ); + unsafe { + self.device.raw.cmd_begin_query( + self.active, + set.raw, + index, + vk::QueryControlFlags::empty(), + ) + }; } unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) { - self.device.raw.cmd_end_query(self.active, set.raw, index); + unsafe { self.device.raw.cmd_end_query(self.active, set.raw, index) }; } unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { - self.device.raw.cmd_write_timestamp( - self.active, - vk::PipelineStageFlags::BOTTOM_OF_PIPE, - set.raw, - index, - ); + unsafe { + self.device.raw.cmd_write_timestamp( + self.active, + vk::PipelineStageFlags::BOTTOM_OF_PIPE, + set.raw, + index, + ) + }; } unsafe fn reset_queries(&mut self, set: &super::QuerySet, range: Range) { - self.device.raw.cmd_reset_query_pool( - self.active, - set.raw, - range.start, - range.end - range.start, - ); + unsafe { + self.device.raw.cmd_reset_query_pool( + self.active, + set.raw, + range.start, + range.end - range.start, + ) + }; } unsafe fn copy_query_results( &mut self, @@ -329,16 +352,18 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, stride: wgt::BufferSize, ) { - self.device.raw.cmd_copy_query_pool_results( - self.active, - set.raw, - range.start, - range.end - range.start, - buffer.raw, - offset, - stride.get(), - vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, - ); + unsafe { + self.device.raw.cmd_copy_query_pool_results( + self.active, + set.raw, + range.start, + range.end - range.start, + buffer.raw, + offset, + stride.get(), + vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, + ) + }; } // render @@ -358,7 +383,7 @@ impl crate::CommandEncoder for super::CommandEncoder { for cat in desc.color_attachments { if let Some(cat) = cat.as_ref() { vk_clear_values.push(vk::ClearValue { - color: cat.make_vk_clear_color(), + color: unsafe { cat.make_vk_clear_color() }, }); vk_image_views.push(cat.target.view.raw); let color = super::ColorAttachmentKey { @@ -371,7 +396,7 @@ impl crate::CommandEncoder for super::CommandEncoder { rp_key.colors.push(Some(color)); fb_key.attachments.push(cat.target.view.attachment.clone()); if let Some(ref at) = cat.resolve_target { - vk_clear_values.push(mem::zeroed()); + vk_clear_values.push(unsafe { mem::zeroed() }); vk_image_views.push(at.view.raw); fb_key.attachments.push(at.view.attachment.clone()); } @@ -456,26 +481,34 @@ impl crate::CommandEncoder for super::CommandEncoder { } if let Some(label) = desc.label { - self.begin_debug_marker(label); + unsafe { self.begin_debug_marker(label) }; self.rpass_debug_marker_active = true; } - self.device - .raw - .cmd_set_viewport(self.active, 0, &vk_viewports); - self.device - .raw - .cmd_set_scissor(self.active, 0, &[render_area]); - self.device - .raw - .cmd_begin_render_pass(self.active, &vk_info, vk::SubpassContents::INLINE); + unsafe { + self.device + .raw + .cmd_set_viewport(self.active, 0, &vk_viewports) + }; + unsafe { + self.device + .raw + .cmd_set_scissor(self.active, 0, &[render_area]) + }; + unsafe { + self.device.raw.cmd_begin_render_pass( + self.active, + &vk_info, + vk::SubpassContents::INLINE, + ) + }; self.bind_point = vk::PipelineBindPoint::GRAPHICS; } unsafe fn end_render_pass(&mut self) { - self.device.raw.cmd_end_render_pass(self.active); + unsafe { self.device.raw.cmd_end_render_pass(self.active) }; if self.rpass_debug_marker_active { - self.end_debug_marker(); + unsafe { self.end_debug_marker() }; self.rpass_debug_marker_active = false; } } @@ -488,14 +521,16 @@ impl crate::CommandEncoder for super::CommandEncoder { dynamic_offsets: &[wgt::DynamicOffset], ) { let sets = [*group.set.raw()]; - self.device.raw.cmd_bind_descriptor_sets( - self.active, - self.bind_point, - layout.raw, - index, - &sets, - dynamic_offsets, - ); + unsafe { + self.device.raw.cmd_bind_descriptor_sets( + self.active, + self.bind_point, + layout.raw, + index, + &sets, + dynamic_offsets, + ) + }; } unsafe fn set_push_constants( &mut self, @@ -504,41 +539,45 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: u32, data: &[u32], ) { - self.device.raw.cmd_push_constants( - self.active, - layout.raw, - conv::map_shader_stage(stages), - offset, - slice::from_raw_parts(data.as_ptr() as _, data.len() * 4), - ); + unsafe { + self.device.raw.cmd_push_constants( + self.active, + layout.raw, + conv::map_shader_stage(stages), + offset, + slice::from_raw_parts(data.as_ptr() as _, data.len() * 4), + ) + }; } unsafe fn insert_debug_marker(&mut self, label: &str) { if let Some(ext) = self.device.debug_messenger() { let cstr = self.temp.make_c_str(label); let vk_label = vk::DebugUtilsLabelEXT::builder().label_name(cstr).build(); - ext.cmd_insert_debug_utils_label(self.active, &vk_label); + unsafe { ext.cmd_insert_debug_utils_label(self.active, &vk_label) }; } } unsafe fn begin_debug_marker(&mut self, group_label: &str) { if let Some(ext) = self.device.debug_messenger() { let cstr = self.temp.make_c_str(group_label); let vk_label = vk::DebugUtilsLabelEXT::builder().label_name(cstr).build(); - ext.cmd_begin_debug_utils_label(self.active, &vk_label); + unsafe { ext.cmd_begin_debug_utils_label(self.active, &vk_label) }; } } unsafe fn end_debug_marker(&mut self) { if let Some(ext) = self.device.debug_messenger() { - ext.cmd_end_debug_utils_label(self.active); + unsafe { ext.cmd_end_debug_utils_label(self.active) }; } } unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { - self.device.raw.cmd_bind_pipeline( - self.active, - vk::PipelineBindPoint::GRAPHICS, - pipeline.raw, - ); + unsafe { + self.device.raw.cmd_bind_pipeline( + self.active, + vk::PipelineBindPoint::GRAPHICS, + pipeline.raw, + ) + }; } unsafe fn set_index_buffer<'a>( @@ -546,12 +585,14 @@ impl crate::CommandEncoder for super::CommandEncoder { binding: crate::BufferBinding<'a, super::Api>, format: wgt::IndexFormat, ) { - self.device.raw.cmd_bind_index_buffer( - self.active, - binding.buffer.raw, - binding.offset, - conv::map_index_format(format), - ); + unsafe { + self.device.raw.cmd_bind_index_buffer( + self.active, + binding.buffer.raw, + binding.offset, + conv::map_index_format(format), + ) + }; } unsafe fn set_vertex_buffer<'a>( &mut self, @@ -560,9 +601,11 @@ impl crate::CommandEncoder for super::CommandEncoder { ) { let vk_buffers = [binding.buffer.raw]; let vk_offsets = [binding.offset]; - self.device - .raw - .cmd_bind_vertex_buffers(self.active, index, &vk_buffers, &vk_offsets); + unsafe { + self.device + .raw + .cmd_bind_vertex_buffers(self.active, index, &vk_buffers, &vk_offsets) + }; } unsafe fn set_viewport(&mut self, rect: &crate::Rect, depth_range: Range) { let vk_viewports = [vk::Viewport { @@ -577,9 +620,11 @@ impl crate::CommandEncoder for super::CommandEncoder { min_depth: depth_range.start, max_depth: depth_range.end, }]; - self.device - .raw - .cmd_set_viewport(self.active, 0, &vk_viewports); + unsafe { + self.device + .raw + .cmd_set_viewport(self.active, 0, &vk_viewports) + }; } unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect) { let vk_scissors = [vk::Rect2D { @@ -592,19 +637,23 @@ impl crate::CommandEncoder for super::CommandEncoder { height: rect.h, }, }]; - self.device - .raw - .cmd_set_scissor(self.active, 0, &vk_scissors); + unsafe { + self.device + .raw + .cmd_set_scissor(self.active, 0, &vk_scissors) + }; } unsafe fn set_stencil_reference(&mut self, value: u32) { - self.device.raw.cmd_set_stencil_reference( - self.active, - vk::StencilFaceFlags::FRONT_AND_BACK, - value, - ); + unsafe { + self.device.raw.cmd_set_stencil_reference( + self.active, + vk::StencilFaceFlags::FRONT_AND_BACK, + value, + ) + }; } unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { - self.device.raw.cmd_set_blend_constants(self.active, color); + unsafe { self.device.raw.cmd_set_blend_constants(self.active, color) }; } unsafe fn draw( @@ -614,13 +663,15 @@ impl crate::CommandEncoder for super::CommandEncoder { start_instance: u32, instance_count: u32, ) { - self.device.raw.cmd_draw( - self.active, - vertex_count, - instance_count, - start_vertex, - start_instance, - ); + unsafe { + self.device.raw.cmd_draw( + self.active, + vertex_count, + instance_count, + start_vertex, + start_instance, + ) + }; } unsafe fn draw_indexed( &mut self, @@ -630,14 +681,16 @@ impl crate::CommandEncoder for super::CommandEncoder { start_instance: u32, instance_count: u32, ) { - self.device.raw.cmd_draw_indexed( - self.active, - index_count, - instance_count, - start_index, - base_vertex, - start_instance, - ); + unsafe { + self.device.raw.cmd_draw_indexed( + self.active, + index_count, + instance_count, + start_index, + base_vertex, + start_instance, + ) + }; } unsafe fn draw_indirect( &mut self, @@ -645,13 +698,15 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, draw_count: u32, ) { - self.device.raw.cmd_draw_indirect( - self.active, - buffer.raw, - offset, - draw_count, - mem::size_of::() as u32, - ); + unsafe { + self.device.raw.cmd_draw_indirect( + self.active, + buffer.raw, + offset, + draw_count, + mem::size_of::() as u32, + ) + }; } unsafe fn draw_indexed_indirect( &mut self, @@ -659,13 +714,15 @@ impl crate::CommandEncoder for super::CommandEncoder { offset: wgt::BufferAddress, draw_count: u32, ) { - self.device.raw.cmd_draw_indexed_indirect( - self.active, - buffer.raw, - offset, - draw_count, - mem::size_of::() as u32, - ); + unsafe { + self.device.raw.cmd_draw_indexed_indirect( + self.active, + buffer.raw, + offset, + draw_count, + mem::size_of::() as u32, + ) + }; } unsafe fn draw_indirect_count( &mut self, @@ -678,15 +735,17 @@ impl crate::CommandEncoder for super::CommandEncoder { let stride = mem::size_of::() as u32; match self.device.extension_fns.draw_indirect_count { Some(ref t) => { - t.cmd_draw_indirect_count( - self.active, - buffer.raw, - offset, - count_buffer.raw, - count_offset, - max_count, - stride, - ); + unsafe { + t.cmd_draw_indirect_count( + self.active, + buffer.raw, + offset, + count_buffer.raw, + count_offset, + max_count, + stride, + ) + }; } None => panic!("Feature `DRAW_INDIRECT_COUNT` not enabled"), } @@ -702,15 +761,17 @@ impl crate::CommandEncoder for super::CommandEncoder { let stride = mem::size_of::() as u32; match self.device.extension_fns.draw_indirect_count { Some(ref t) => { - t.cmd_draw_indexed_indirect_count( - self.active, - buffer.raw, - offset, - count_buffer.raw, - count_offset, - max_count, - stride, - ); + unsafe { + t.cmd_draw_indexed_indirect_count( + self.active, + buffer.raw, + offset, + count_buffer.raw, + count_offset, + max_count, + stride, + ) + }; } None => panic!("Feature `DRAW_INDIRECT_COUNT` not enabled"), } @@ -721,34 +782,40 @@ impl crate::CommandEncoder for super::CommandEncoder { unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor) { self.bind_point = vk::PipelineBindPoint::COMPUTE; if let Some(label) = desc.label { - self.begin_debug_marker(label); + unsafe { self.begin_debug_marker(label) }; self.rpass_debug_marker_active = true; } } unsafe fn end_compute_pass(&mut self) { if self.rpass_debug_marker_active { - self.end_debug_marker(); + unsafe { self.end_debug_marker() }; self.rpass_debug_marker_active = false } } unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { - self.device.raw.cmd_bind_pipeline( - self.active, - vk::PipelineBindPoint::COMPUTE, - pipeline.raw, - ); + unsafe { + self.device.raw.cmd_bind_pipeline( + self.active, + vk::PipelineBindPoint::COMPUTE, + pipeline.raw, + ) + }; } unsafe fn dispatch(&mut self, count: [u32; 3]) { - self.device - .raw - .cmd_dispatch(self.active, count[0], count[1], count[2]); + unsafe { + self.device + .raw + .cmd_dispatch(self.active, count[0], count[1], count[2]) + }; } unsafe fn dispatch_indirect(&mut self, buffer: &super::Buffer, offset: wgt::BufferAddress) { - self.device - .raw - .cmd_dispatch_indirect(self.active, buffer.raw, offset) + unsafe { + self.device + .raw + .cmd_dispatch_indirect(self.active, buffer.raw, offset) + } } } diff --git a/wgpu-hal/src/vulkan/device.rs b/wgpu-hal/src/vulkan/device.rs index b9d74e36e35..af22f8e0391 100644 --- a/wgpu-hal/src/vulkan/device.rs +++ b/wgpu-hal/src/vulkan/device.rs @@ -48,14 +48,15 @@ impl super::DeviceShared { .collect(); &buffer_vec }; - - let _result = extension.debug_utils_set_object_name( - self.raw.handle(), - &vk::DebugUtilsObjectNameInfoEXT::builder() - .object_type(object_type) - .object_handle(object.as_raw()) - .object_name(CStr::from_bytes_with_nul_unchecked(name_bytes)), - ); + let _result = unsafe { + extension.debug_utils_set_object_name( + self.raw.handle(), + &vk::DebugUtilsObjectNameInfoEXT::builder() + .object_type(object_type) + .object_handle(object.as_raw()) + .object_name(CStr::from_bytes_with_nul_unchecked(name_bytes)), + ) + }; } pub fn make_render_pass( @@ -278,13 +279,13 @@ impl super::DeviceShared { unsafe fn free_resources(&self) { for &raw in self.render_passes.lock().values() { - self.raw.destroy_render_pass(raw, None); + unsafe { self.raw.destroy_render_pass(raw, None) }; } for &raw in self.framebuffers.lock().values() { - self.raw.destroy_framebuffer(raw, None); + unsafe { self.raw.destroy_framebuffer(raw, None) }; } if self.handle_is_owned { - self.raw.destroy_device(None); + unsafe { self.raw.destroy_device(None) }; } } } @@ -308,7 +309,7 @@ impl gpu_alloc::MemoryDevice for super::DeviceShared { info = info.push_next(&mut info_flags); } - match self.raw.allocate_memory(&info, None) { + match unsafe { self.raw.allocate_memory(&info, None) } { Ok(memory) => Ok(memory), Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { Err(gpu_alloc::OutOfMemory::OutOfDeviceMemory) @@ -322,7 +323,7 @@ impl gpu_alloc::MemoryDevice for super::DeviceShared { } unsafe fn deallocate_memory(&self, memory: vk::DeviceMemory) { - self.raw.free_memory(memory, None); + unsafe { self.raw.free_memory(memory, None) }; } unsafe fn map_memory( @@ -331,10 +332,10 @@ impl gpu_alloc::MemoryDevice for super::DeviceShared { offset: u64, size: u64, ) -> Result, gpu_alloc::DeviceMapError> { - match self - .raw - .map_memory(*memory, offset, size, vk::MemoryMapFlags::empty()) - { + match unsafe { + self.raw + .map_memory(*memory, offset, size, vk::MemoryMapFlags::empty()) + } { Ok(ptr) => Ok(ptr::NonNull::new(ptr as *mut u8) .expect("Pointer to memory mapping must not be null")), Err(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY) => { @@ -349,7 +350,7 @@ impl gpu_alloc::MemoryDevice for super::DeviceShared { } unsafe fn unmap_memory(&self, memory: &mut vk::DeviceMemory) { - self.raw.unmap_memory(*memory); + unsafe { self.raw.unmap_memory(*memory) }; } unsafe fn invalidate_memory_ranges( @@ -433,7 +434,7 @@ impl .pool_sizes(&filtered_counts) .build(); - match self.raw.create_descriptor_pool(&vk_info, None) { + match unsafe { self.raw.create_descriptor_pool(&vk_info, None) } { Ok(pool) => Ok(pool), Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY) => { Err(gpu_descriptor::CreatePoolError::OutOfHostMemory) @@ -452,7 +453,7 @@ impl } unsafe fn destroy_descriptor_pool(&self, pool: vk::DescriptorPool) { - self.raw.destroy_descriptor_pool(pool, None) + unsafe { self.raw.destroy_descriptor_pool(pool, None) } } unsafe fn alloc_descriptor_sets<'a>( @@ -461,16 +462,18 @@ impl layouts: impl ExactSizeIterator, sets: &mut impl Extend, ) -> Result<(), gpu_descriptor::DeviceAllocationError> { - let result = self.raw.allocate_descriptor_sets( - &vk::DescriptorSetAllocateInfo::builder() - .descriptor_pool(*pool) - .set_layouts( - &smallvec::SmallVec::<[vk::DescriptorSetLayout; 32]>::from_iter( - layouts.cloned(), - ), - ) - .build(), - ); + let result = unsafe { + self.raw.allocate_descriptor_sets( + &vk::DescriptorSetAllocateInfo::builder() + .descriptor_pool(*pool) + .set_layouts( + &smallvec::SmallVec::<[vk::DescriptorSetLayout; 32]>::from_iter( + layouts.cloned(), + ), + ) + .build(), + ) + }; match result { Ok(vk_sets) => { @@ -499,10 +502,12 @@ impl pool: &mut vk::DescriptorPool, sets: impl Iterator, ) { - let result = self.raw.free_descriptor_sets( - *pool, - &smallvec::SmallVec::<[vk::DescriptorSet; 32]>::from_iter(sets), - ); + let result = unsafe { + self.raw.free_descriptor_sets( + *pool, + &smallvec::SmallVec::<[vk::DescriptorSet; 32]>::from_iter(sets), + ) + }; match result { Ok(()) => {} Err(err) => log::error!("free_descriptor_sets: {:?}", err), @@ -559,12 +564,12 @@ impl super::Device { let result = { profiling::scope!("vkCreateSwapchainKHR"); - functor.create_swapchain(&info, None) + unsafe { functor.create_swapchain(&info, None) } }; // doing this before bailing out with error if old_swapchain != vk::SwapchainKHR::null() { - functor.destroy_swapchain(old_swapchain, None) + unsafe { functor.destroy_swapchain(old_swapchain, None) } } let raw = match result { @@ -580,15 +585,11 @@ impl super::Device { } }; - let images = functor - .get_swapchain_images(raw) - .map_err(crate::DeviceError::from)?; + let images = + unsafe { functor.get_swapchain_images(raw) }.map_err(crate::DeviceError::from)?; let vk_info = vk::FenceCreateInfo::builder().build(); - let fence = self - .shared - .raw - .create_fence(&vk_info, None) + let fence = unsafe { self.shared.raw.create_fence(&vk_info, None) } .map_err(crate::DeviceError::from)?; Ok(super::Swapchain { @@ -741,12 +742,12 @@ impl super::Device { impl crate::Device for super::Device { unsafe fn exit(self, queue: super::Queue) { - self.mem_allocator.into_inner().cleanup(&*self.shared); - self.desc_allocator.into_inner().cleanup(&*self.shared); + unsafe { self.mem_allocator.into_inner().cleanup(&*self.shared) }; + unsafe { self.desc_allocator.into_inner().cleanup(&*self.shared) }; for &sem in queue.relay_semaphores.iter() { - self.shared.raw.destroy_semaphore(sem, None); + unsafe { self.shared.raw.destroy_semaphore(sem, None) }; } - self.shared.free_resources(); + unsafe { self.shared.free_resources() }; } unsafe fn create_buffer( @@ -758,8 +759,8 @@ impl crate::Device for super::Device { .usage(conv::map_buffer_usage(desc.usage)) .sharing_mode(vk::SharingMode::EXCLUSIVE); - let raw = self.shared.raw.create_buffer(&vk_info, None)?; - let req = self.shared.raw.get_buffer_memory_requirements(raw); + let raw = unsafe { self.shared.raw.create_buffer(&vk_info, None)? }; + let req = unsafe { self.shared.raw.get_buffer_memory_requirements(raw) }; let mut alloc_usage = if desc .usage @@ -784,23 +785,29 @@ impl crate::Device for super::Device { desc.memory_flags.contains(crate::MemoryFlags::TRANSIENT), ); - let block = self.mem_allocator.lock().alloc( - &*self.shared, - gpu_alloc::Request { - size: req.size, - align_mask: req.alignment - 1, - usage: alloc_usage, - memory_types: req.memory_type_bits & self.valid_ash_memory_types, - }, - )?; + let block = unsafe { + self.mem_allocator.lock().alloc( + &*self.shared, + gpu_alloc::Request { + size: req.size, + align_mask: req.alignment - 1, + usage: alloc_usage, + memory_types: req.memory_type_bits & self.valid_ash_memory_types, + }, + )? + }; - self.shared - .raw - .bind_buffer_memory(raw, *block.memory(), block.offset())?; + unsafe { + self.shared + .raw + .bind_buffer_memory(raw, *block.memory(), block.offset())? + }; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::BUFFER, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::BUFFER, raw, label) + }; } Ok(super::Buffer { @@ -809,10 +816,12 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_buffer(&self, buffer: super::Buffer) { - self.shared.raw.destroy_buffer(buffer.raw, None); - self.mem_allocator - .lock() - .dealloc(&*self.shared, buffer.block.into_inner()); + unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) }; + unsafe { + self.mem_allocator + .lock() + .dealloc(&*self.shared, buffer.block.into_inner()) + }; } unsafe fn map_buffer( @@ -822,14 +831,14 @@ impl crate::Device for super::Device { ) -> Result { let size = range.end - range.start; let mut block = buffer.block.lock(); - let ptr = block.map(&*self.shared, range.start, size as usize)?; + let ptr = unsafe { block.map(&*self.shared, range.start, size as usize)? }; let is_coherent = block .props() .contains(gpu_alloc::MemoryPropertyFlags::HOST_COHERENT); Ok(crate::BufferMapping { ptr, is_coherent }) } unsafe fn unmap_buffer(&self, buffer: &super::Buffer) -> Result<(), crate::DeviceError> { - buffer.block.lock().unmap(&*self.shared); + unsafe { buffer.block.lock().unmap(&*self.shared) }; Ok(()) } @@ -839,12 +848,14 @@ impl crate::Device for super::Device { { let vk_ranges = self.shared.make_memory_ranges(buffer, ranges); - self.shared - .raw - .flush_mapped_memory_ranges( - &smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), - ) - .unwrap(); + unsafe { + self.shared + .raw + .flush_mapped_memory_ranges( + &smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), + ) + } + .unwrap(); } unsafe fn invalidate_mapped_ranges(&self, buffer: &super::Buffer, ranges: I) where @@ -852,12 +863,14 @@ impl crate::Device for super::Device { { let vk_ranges = self.shared.make_memory_ranges(buffer, ranges); - self.shared - .raw - .invalidate_mapped_memory_ranges( - &smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), - ) - .unwrap(); + unsafe { + self.shared + .raw + .invalidate_mapped_memory_ranges( + &smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), + ) + } + .unwrap(); } unsafe fn create_texture( @@ -896,26 +909,32 @@ impl crate::Device for super::Device { .sharing_mode(vk::SharingMode::EXCLUSIVE) .initial_layout(vk::ImageLayout::UNDEFINED); - let raw = self.shared.raw.create_image(&vk_info, None)?; - let req = self.shared.raw.get_image_memory_requirements(raw); - - let block = self.mem_allocator.lock().alloc( - &*self.shared, - gpu_alloc::Request { - size: req.size, - align_mask: req.alignment - 1, - usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, - memory_types: req.memory_type_bits & self.valid_ash_memory_types, - }, - )?; + let raw = unsafe { self.shared.raw.create_image(&vk_info, None)? }; + let req = unsafe { self.shared.raw.get_image_memory_requirements(raw) }; + + let block = unsafe { + self.mem_allocator.lock().alloc( + &*self.shared, + gpu_alloc::Request { + size: req.size, + align_mask: req.alignment - 1, + usage: gpu_alloc::UsageFlags::FAST_DEVICE_ACCESS, + memory_types: req.memory_type_bits & self.valid_ash_memory_types, + }, + )? + }; - self.shared - .raw - .bind_image_memory(raw, *block.memory(), block.offset())?; + unsafe { + self.shared + .raw + .bind_image_memory(raw, *block.memory(), block.offset())? + }; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::IMAGE, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::IMAGE, raw, label) + }; } Ok(super::Texture { @@ -931,10 +950,10 @@ impl crate::Device for super::Device { } unsafe fn destroy_texture(&self, texture: super::Texture) { if texture.drop_guard.is_none() { - self.shared.raw.destroy_image(texture.raw, None); + unsafe { self.shared.raw.destroy_image(texture.raw, None) }; } if let Some(block) = texture.block { - self.mem_allocator.lock().dealloc(&*self.shared, block); + unsafe { self.mem_allocator.lock().dealloc(&*self.shared, block) }; } } @@ -964,11 +983,13 @@ impl crate::Device for super::Device { texture.usage }; - let raw = self.shared.raw.create_image_view(&vk_info, None)?; + let raw = unsafe { self.shared.raw.create_image_view(&vk_info, None) }?; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::IMAGE_VIEW, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::IMAGE_VIEW, raw, label) + }; } let attachment = super::FramebufferAttachment { @@ -993,12 +1014,12 @@ impl crate::Device for super::Device { let mut fbuf_lock = self.shared.framebuffers.lock(); for (key, &raw_fbuf) in fbuf_lock.iter() { if key.attachments.iter().any(|at| at.raw == view.raw) { - self.shared.raw.destroy_framebuffer(raw_fbuf, None); + unsafe { self.shared.raw.destroy_framebuffer(raw_fbuf, None) }; } } fbuf_lock.retain(|key, _| !key.attachments.iter().any(|at| at.raw == view.raw)); } - self.shared.raw.destroy_image_view(view.raw, None); + unsafe { self.shared.raw.destroy_image_view(view.raw, None) }; } unsafe fn create_sampler( @@ -1040,17 +1061,19 @@ impl crate::Device for super::Device { vk_info = vk_info.border_color(conv::map_border_color(color)); } - let raw = self.shared.raw.create_sampler(&vk_info, None)?; + let raw = unsafe { self.shared.raw.create_sampler(&vk_info, None)? }; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::SAMPLER, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::SAMPLER, raw, label) + }; } Ok(super::Sampler { raw }) } unsafe fn destroy_sampler(&self, sampler: super::Sampler) { - self.shared.raw.destroy_sampler(sampler.raw, None); + unsafe { self.shared.raw.destroy_sampler(sampler.raw, None) }; } unsafe fn create_command_encoder( @@ -1060,7 +1083,7 @@ impl crate::Device for super::Device { let vk_info = vk::CommandPoolCreateInfo::builder() .queue_family_index(desc.queue.family_index) .build(); - let raw = self.shared.raw.create_command_pool(&vk_info, None)?; + let raw = unsafe { self.shared.raw.create_command_pool(&vk_info, None)? }; Ok(super::CommandEncoder { raw, @@ -1075,16 +1098,20 @@ impl crate::Device for super::Device { } unsafe fn destroy_command_encoder(&self, cmd_encoder: super::CommandEncoder) { if !cmd_encoder.free.is_empty() { - self.shared - .raw - .free_command_buffers(cmd_encoder.raw, &cmd_encoder.free); + unsafe { + self.shared + .raw + .free_command_buffers(cmd_encoder.raw, &cmd_encoder.free) + }; } if !cmd_encoder.discarded.is_empty() { - self.shared - .raw - .free_command_buffers(cmd_encoder.raw, &cmd_encoder.discarded); + unsafe { + self.shared + .raw + .free_command_buffers(cmd_encoder.raw, &cmd_encoder.discarded) + }; } - self.shared.raw.destroy_command_pool(cmd_encoder.raw, None); + unsafe { self.shared.raw.destroy_command_pool(cmd_encoder.raw, None) }; } unsafe fn create_bind_group_layout( @@ -1223,14 +1250,17 @@ impl crate::Device for super::Device { let vk_info = vk_info.flags(dsl_create_flags); - let raw = self - .shared - .raw - .create_descriptor_set_layout(&vk_info, None)?; + let raw = unsafe { + self.shared + .raw + .create_descriptor_set_layout(&vk_info, None)? + }; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::DESCRIPTOR_SET_LAYOUT, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::DESCRIPTOR_SET_LAYOUT, raw, label) + }; } Ok(super::BindGroupLayout { @@ -1242,9 +1272,11 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) { - self.shared - .raw - .destroy_descriptor_set_layout(bg_layout.raw, None); + unsafe { + self.shared + .raw + .destroy_descriptor_set_layout(bg_layout.raw, None) + }; } unsafe fn create_pipeline_layout( @@ -1274,12 +1306,14 @@ impl crate::Device for super::Device { let raw = { profiling::scope!("vkCreatePipelineLayout"); - self.shared.raw.create_pipeline_layout(&vk_info, None)? + unsafe { self.shared.raw.create_pipeline_layout(&vk_info, None)? } }; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::PIPELINE_LAYOUT, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::PIPELINE_LAYOUT, raw, label) + }; } let mut binding_arrays = BTreeMap::new(); @@ -1303,31 +1337,37 @@ impl crate::Device for super::Device { }) } unsafe fn destroy_pipeline_layout(&self, pipeline_layout: super::PipelineLayout) { - self.shared - .raw - .destroy_pipeline_layout(pipeline_layout.raw, None); + unsafe { + self.shared + .raw + .destroy_pipeline_layout(pipeline_layout.raw, None) + }; } unsafe fn create_bind_group( &self, desc: &crate::BindGroupDescriptor, ) -> Result { - let mut vk_sets = self.desc_allocator.lock().allocate( - &*self.shared, - &desc.layout.raw, - if desc.layout.requires_update_after_bind { - gpu_descriptor::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND - } else { - gpu_descriptor::DescriptorSetLayoutCreateFlags::empty() - }, - &desc.layout.desc_count, - 1, - )?; + let mut vk_sets = unsafe { + self.desc_allocator.lock().allocate( + &*self.shared, + &desc.layout.raw, + if desc.layout.requires_update_after_bind { + gpu_descriptor::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND + } else { + gpu_descriptor::DescriptorSetLayoutCreateFlags::empty() + }, + &desc.layout.desc_count, + 1, + )? + }; let set = vk_sets.pop().unwrap(); if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::DESCRIPTOR_SET, *set.raw(), label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::DESCRIPTOR_SET, *set.raw(), label) + }; } let mut writes = Vec::with_capacity(desc.entries.len()); @@ -1396,13 +1436,15 @@ impl crate::Device for super::Device { writes.push(write.build()); } - self.shared.raw.update_descriptor_sets(&writes, &[]); + unsafe { self.shared.raw.update_descriptor_sets(&writes, &[]) }; Ok(super::BindGroup { set }) } unsafe fn destroy_bind_group(&self, group: super::BindGroup) { - self.desc_allocator - .lock() - .free(&*self.shared, Some(group.set)); + unsafe { + self.desc_allocator + .lock() + .free(&*self.shared, Some(group.set)) + }; } unsafe fn create_shader_module( @@ -1447,8 +1489,10 @@ impl crate::Device for super::Device { let raw = self.create_shader_module_impl(&*spv)?; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::SHADER_MODULE, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::SHADER_MODULE, raw, label) + }; } Ok(super::ShaderModule::Raw(raw)) @@ -1456,7 +1500,7 @@ impl crate::Device for super::Device { unsafe fn destroy_shader_module(&self, module: super::ShaderModule) { match module { super::ShaderModule::Raw(raw) => { - self.shared.raw.destroy_shader_module(raw, None); + unsafe { self.shared.raw.destroy_shader_module(raw, None) }; } super::ShaderModule::Intermediate { .. } => {} } @@ -1673,33 +1717,37 @@ impl crate::Device for super::Device { let mut raw_vec = { profiling::scope!("vkCreateGraphicsPipelines"); - self.shared - .raw - .create_graphics_pipelines(vk::PipelineCache::null(), &vk_infos, None) - .map_err(|(_, e)| crate::DeviceError::from(e))? + unsafe { + self.shared + .raw + .create_graphics_pipelines(vk::PipelineCache::null(), &vk_infos, None) + .map_err(|(_, e)| crate::DeviceError::from(e)) + }? }; let raw = raw_vec.pop().unwrap(); if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::PIPELINE, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::PIPELINE, raw, label) + }; } if let Some(raw_module) = compiled_vs.temp_raw_module { - self.shared.raw.destroy_shader_module(raw_module, None); + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } if let Some(CompiledStage { temp_raw_module: Some(raw_module), .. }) = compiled_fs { - self.shared.raw.destroy_shader_module(raw_module, None); + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } Ok(super::RenderPipeline { raw }) } unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { - self.shared.raw.destroy_pipeline(pipeline.raw, None); + unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; } unsafe fn create_compute_pipeline( @@ -1721,26 +1769,30 @@ impl crate::Device for super::Device { let mut raw_vec = { profiling::scope!("vkCreateComputePipelines"); - self.shared - .raw - .create_compute_pipelines(vk::PipelineCache::null(), &vk_infos, None) - .map_err(|(_, e)| crate::DeviceError::from(e))? + unsafe { + self.shared + .raw + .create_compute_pipelines(vk::PipelineCache::null(), &vk_infos, None) + .map_err(|(_, e)| crate::DeviceError::from(e)) + }? }; let raw = raw_vec.pop().unwrap(); if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::PIPELINE, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::PIPELINE, raw, label) + }; } if let Some(raw_module) = compiled.temp_raw_module { - self.shared.raw.destroy_shader_module(raw_module, None); + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; } Ok(super::ComputePipeline { raw }) } unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) { - self.shared.raw.destroy_pipeline(pipeline.raw, None); + unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; } unsafe fn create_query_set( @@ -1768,16 +1820,18 @@ impl crate::Device for super::Device { .pipeline_statistics(pipeline_statistics) .build(); - let raw = self.shared.raw.create_query_pool(&vk_info, None)?; + let raw = unsafe { self.shared.raw.create_query_pool(&vk_info, None) }?; if let Some(label) = desc.label { - self.shared - .set_object_name(vk::ObjectType::QUERY_POOL, raw, label); + unsafe { + self.shared + .set_object_name(vk::ObjectType::QUERY_POOL, raw, label) + }; } Ok(super::QuerySet { raw }) } unsafe fn destroy_query_set(&self, set: super::QuerySet) { - self.shared.raw.destroy_query_pool(set.raw, None); + unsafe { self.shared.raw.destroy_query_pool(set.raw, None) }; } unsafe fn create_fence(&self) -> Result { @@ -1785,7 +1839,7 @@ impl crate::Device for super::Device { let mut sem_type_info = vk::SemaphoreTypeCreateInfo::builder().semaphore_type(vk::SemaphoreType::TIMELINE); let vk_info = vk::SemaphoreCreateInfo::builder().push_next(&mut sem_type_info); - let raw = self.shared.raw.create_semaphore(&vk_info, None)?; + let raw = unsafe { self.shared.raw.create_semaphore(&vk_info, None) }?; super::Fence::TimelineSemaphore(raw) } else { super::Fence::FencePool { @@ -1798,7 +1852,7 @@ impl crate::Device for super::Device { unsafe fn destroy_fence(&self, fence: super::Fence) { match fence { super::Fence::TimelineSemaphore(raw) => { - self.shared.raw.destroy_semaphore(raw, None); + unsafe { self.shared.raw.destroy_semaphore(raw, None) }; } super::Fence::FencePool { active, @@ -1806,10 +1860,10 @@ impl crate::Device for super::Device { last_completed: _, } => { for (_, raw) in active { - self.shared.raw.destroy_fence(raw, None); + unsafe { self.shared.raw.destroy_fence(raw, None) }; } for raw in free { - self.shared.raw.destroy_fence(raw, None); + unsafe { self.shared.raw.destroy_fence(raw, None) }; } } } @@ -1838,12 +1892,12 @@ impl crate::Device for super::Device { .semaphores(&semaphores) .values(&values); let result = match self.shared.extension_fns.timeline_semaphore { - Some(super::ExtensionFn::Extension(ref ext)) => { + Some(super::ExtensionFn::Extension(ref ext)) => unsafe { ext.wait_semaphores(&vk_info, timeout_ns) - } - Some(super::ExtensionFn::Promoted) => { + }, + Some(super::ExtensionFn::Promoted) => unsafe { self.shared.raw.wait_semaphores(&vk_info, timeout_ns) - } + }, None => unreachable!(), }; match result { @@ -1862,7 +1916,9 @@ impl crate::Device for super::Device { } else { match active.iter().find(|&&(value, _)| value >= wait_value) { Some(&(_, raw)) => { - match self.shared.raw.wait_for_fences(&[raw], true, timeout_ns) { + match unsafe { + self.shared.raw.wait_for_fences(&[raw], true, timeout_ns) + } { Ok(()) => Ok(true), Err(vk::Result::TIMEOUT) => Ok(false), Err(other) => Err(other.into()), @@ -1884,9 +1940,11 @@ impl crate::Device for super::Device { // Renderdoc requires us to give us the pointer that vkInstance _points to_. let raw_vk_instance = ash::vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; - let raw_vk_instance_dispatch_table = *raw_vk_instance; - self.render_doc - .start_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; + unsafe { + self.render_doc + .start_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + } } #[cfg(not(feature = "renderdoc"))] false @@ -1897,10 +1955,12 @@ impl crate::Device for super::Device { // Renderdoc requires us to give us the pointer that vkInstance _points to_. let raw_vk_instance = ash::vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; - let raw_vk_instance_dispatch_table = *raw_vk_instance; + let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; - self.render_doc - .end_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + unsafe { + self.render_doc + .end_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + } } } } diff --git a/wgpu-hal/src/vulkan/instance.rs b/wgpu-hal/src/vulkan/instance.rs index 79045ff061a..5b01e97c3a6 100644 --- a/wgpu-hal/src/vulkan/instance.rs +++ b/wgpu-hal/src/vulkan/instance.rs @@ -31,17 +31,17 @@ unsafe extern "system" fn debug_utils_messenger_callback( _ => log::Level::Warn, }; - let cd = &*callback_data_ptr; + let cd = unsafe { &*callback_data_ptr }; let message_id_name = if cd.p_message_id_name.is_null() { Cow::from("") } else { - CStr::from_ptr(cd.p_message_id_name).to_string_lossy() + unsafe { CStr::from_ptr(cd.p_message_id_name) }.to_string_lossy() }; let message = if cd.p_message.is_null() { Cow::from("") } else { - CStr::from_ptr(cd.p_message).to_string_lossy() + unsafe { CStr::from_ptr(cd.p_message) }.to_string_lossy() }; let _ = std::panic::catch_unwind(|| { @@ -56,14 +56,13 @@ unsafe extern "system" fn debug_utils_messenger_callback( }); if cd.queue_label_count != 0 { - let labels = slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize); + let labels = + unsafe { slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize) }; let names = labels .iter() .flat_map(|dul_obj| { - dul_obj - .p_label_name - .as_ref() - .map(|lbl| CStr::from_ptr(lbl).to_string_lossy()) + unsafe { dul_obj.p_label_name.as_ref() } + .map(|lbl| unsafe { CStr::from_ptr(lbl) }.to_string_lossy()) }) .collect::>(); @@ -73,14 +72,13 @@ unsafe extern "system" fn debug_utils_messenger_callback( } if cd.cmd_buf_label_count != 0 { - let labels = slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize); + let labels = + unsafe { slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize) }; let names = labels .iter() .flat_map(|dul_obj| { - dul_obj - .p_label_name - .as_ref() - .map(|lbl| CStr::from_ptr(lbl).to_string_lossy()) + unsafe { dul_obj.p_label_name.as_ref() } + .map(|lbl| unsafe { CStr::from_ptr(lbl) }.to_string_lossy()) }) .collect::>(); @@ -90,15 +88,13 @@ unsafe extern "system" fn debug_utils_messenger_callback( } if cd.object_count != 0 { - let labels = slice::from_raw_parts(cd.p_objects, cd.object_count as usize); + let labels = unsafe { slice::from_raw_parts(cd.p_objects, cd.object_count as usize) }; //TODO: use color fields of `vk::DebugUtilsLabelExt`? let names = labels .iter() .map(|obj_info| { - let name = obj_info - .p_object_name - .as_ref() - .map(|name| CStr::from_ptr(name).to_string_lossy()) + let name = unsafe { obj_info.p_object_name.as_ref() } + .map(|name| unsafe { CStr::from_ptr(name) }.to_string_lossy()) .unwrap_or(Cow::Borrowed("?")); format!( @@ -125,9 +121,9 @@ impl super::Swapchain { profiling::scope!("Swapchain::release_resources"); { profiling::scope!("vkDeviceWaitIdle"); - let _ = device.device_wait_idle(); + let _ = unsafe { device.device_wait_idle() }; }; - device.destroy_fence(self.fence, None); + unsafe { device.destroy_fence(self.fence, None) }; self } } @@ -257,9 +253,8 @@ impl super::Instance { | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE, ) .pfn_user_callback(Some(debug_utils_messenger_callback)); - let messenger = extension - .create_debug_utils_messenger(&vk_info, None) - .unwrap(); + let messenger = + unsafe { extension.create_debug_utils_messenger(&vk_info, None) }.unwrap(); Some(super::DebugUtils { extension, messenger, @@ -459,7 +454,7 @@ impl Drop for super::InstanceShared { impl crate::Instance for super::Instance { unsafe fn init(desc: &crate::InstanceDescriptor) -> Result { - let entry = match ash::Entry::load() { + let entry = match unsafe { ash::Entry::load() } { Ok(entry) => entry, Err(err) => { log::info!("Missing Vulkan entry points: {:?}", err); @@ -509,7 +504,7 @@ impl crate::Instance for super::Instance { let nv_optimus_layer = CStr::from_bytes_with_nul(b"VK_LAYER_NV_optimus\0").unwrap(); let has_nv_optimus = instance_layers .iter() - .any(|inst_layer| CStr::from_ptr(inst_layer.layer_name.as_ptr()) == nv_optimus_layer); + .any(|inst_layer| unsafe { CStr::from_ptr(inst_layer.layer_name.as_ptr()) } == nv_optimus_layer); // Check requested layers against the available layers let layers = { @@ -520,10 +515,9 @@ impl crate::Instance for super::Instance { // Only keep available layers. layers.retain(|&layer| { - if instance_layers - .iter() - .any(|inst_layer| CStr::from_ptr(inst_layer.layer_name.as_ptr()) == layer) - { + if instance_layers.iter().any( + |inst_layer| unsafe { CStr::from_ptr(inst_layer.layer_name.as_ptr()) } == layer, + ) { true } else { log::warn!("Unable to find layer: {}", layer.to_string_lossy()); @@ -571,22 +565,24 @@ impl crate::Instance for super::Instance { .enabled_layer_names(&str_pointers[..layers.len()]) .enabled_extension_names(&str_pointers[layers.len()..]); - entry.create_instance(&create_info, None).map_err(|e| { + unsafe { entry.create_instance(&create_info, None) }.map_err(|e| { log::warn!("create_instance: {:?}", e); crate::InstanceError })? }; - Self::from_raw( - entry, - vk_instance, - driver_api_version, - android_sdk_version, - extensions, - desc.flags, - has_nv_optimus, - Some(Box::new(())), // `Some` signals that wgpu-hal is in charge of destroying vk_instance - ) + unsafe { + Self::from_raw( + entry, + vk_instance, + driver_api_version, + android_sdk_version, + extensions, + desc.flags, + has_nv_optimus, + Some(Box::new(())), // `Some` signals that wgpu-hal is in charge of destroying vk_instance + ) + } } unsafe fn create_surface( @@ -615,7 +611,7 @@ impl crate::Instance for super::Instance { (Rwh::Win32(handle), _) => { use winapi::um::libloaderapi::GetModuleHandleW; - let hinstance = GetModuleHandleW(std::ptr::null()); + let hinstance = unsafe { GetModuleHandleW(std::ptr::null()) }; Ok(self.create_surface_from_hwnd(hinstance as *mut _, handle.hwnd)) } #[cfg(target_os = "macos")] @@ -635,13 +631,13 @@ impl crate::Instance for super::Instance { } unsafe fn destroy_surface(&self, surface: super::Surface) { - surface.functor.destroy_surface(surface.raw, None); + unsafe { surface.functor.destroy_surface(surface.raw, None) }; } unsafe fn enumerate_adapters(&self) -> Vec> { use crate::auxil::db; - let raw_devices = match self.shared.raw.enumerate_physical_devices() { + let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } { Ok(devices) => devices, Err(err) => { log::error!("enumerate_adapters: {}", err); @@ -688,9 +684,9 @@ impl crate::Surface for super::Surface { let old = self .swapchain .take() - .map(|sc| sc.release_resources(&device.shared.raw)); + .map(|sc| unsafe { sc.release_resources(&device.shared.raw) }); - let swapchain = device.create_swapchain(self, config, old)?; + let swapchain = unsafe { device.create_swapchain(self, config, old)? }; self.swapchain = Some(swapchain); Ok(()) @@ -698,8 +694,8 @@ impl crate::Surface for super::Surface { unsafe fn unconfigure(&mut self, device: &super::Device) { if let Some(sc) = self.swapchain.take() { - let swapchain = sc.release_resources(&device.shared.raw); - swapchain.functor.destroy_swapchain(swapchain.raw, None); + let swapchain = unsafe { sc.release_resources(&device.shared.raw) }; + unsafe { swapchain.functor.destroy_swapchain(swapchain.raw, None) }; } } @@ -728,23 +724,22 @@ impl crate::Surface for super::Surface { } // will block if no image is available - let (index, suboptimal) = - match sc - .functor + let (index, suboptimal) = match unsafe { + sc.functor .acquire_next_image(sc.raw, timeout_ns, vk::Semaphore::null(), sc.fence) - { - Ok(pair) => pair, - Err(error) => { - return match error { - vk::Result::TIMEOUT => Ok(None), - vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => { - Err(crate::SurfaceError::Outdated) - } - vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost), - other => Err(crate::DeviceError::from(other).into()), + } { + Ok(pair) => pair, + Err(error) => { + return match error { + vk::Result::TIMEOUT => Ok(None), + vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => { + Err(crate::SurfaceError::Outdated) } + vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost), + other => Err(crate::DeviceError::from(other).into()), } - }; + } + }; // special case for Intel Vulkan returning bizzare values (ugh) if sc.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 { @@ -753,14 +748,9 @@ impl crate::Surface for super::Surface { let fences = &[sc.fence]; - sc.device - .raw - .wait_for_fences(fences, true, !0) - .map_err(crate::DeviceError::from)?; - sc.device - .raw - .reset_fences(fences) + unsafe { sc.device.raw.wait_for_fences(fences, true, !0) } .map_err(crate::DeviceError::from)?; + unsafe { sc.device.raw.reset_fences(fences) }.map_err(crate::DeviceError::from)?; let texture = super::SurfaceTexture { index, diff --git a/wgpu-hal/src/vulkan/mod.rs b/wgpu-hal/src/vulkan/mod.rs index d3416a50ed9..6fc7450be01 100644 --- a/wgpu-hal/src/vulkan/mod.rs +++ b/wgpu-hal/src/vulkan/mod.rs @@ -582,10 +582,11 @@ impl crate::Queue for Queue { } => { fence_raw = match free.pop() { Some(raw) => raw, - None => self - .device - .raw - .create_fence(&vk::FenceCreateInfo::builder(), None)?, + None => unsafe { + self.device + .raw + .create_fence(&vk::FenceCreateInfo::builder(), None)? + }, }; active.push((value, fence_raw)); } @@ -613,9 +614,11 @@ impl crate::Queue for Queue { vk_info = vk_info.signal_semaphores(&signal_semaphores[..signal_count]); profiling::scope!("vkQueueSubmit"); - self.device - .raw - .queue_submit(self.raw, &[vk_info.build()], fence_raw)?; + unsafe { + self.device + .raw + .queue_submit(self.raw, &[vk_info.build()], fence_raw)? + }; Ok(()) } @@ -638,13 +641,13 @@ impl crate::Queue for Queue { let suboptimal = { profiling::scope!("vkQueuePresentKHR"); - self.swapchain_fn - .queue_present(self.raw, &vk_info) - .map_err(|error| match error { + unsafe { self.swapchain_fn.queue_present(self.raw, &vk_info) }.map_err(|error| { + match error { vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated, vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost, _ => crate::DeviceError::from(error).into(), - })? + } + })? }; if suboptimal { log::warn!("Suboptimal present of frame {}", texture.index);