Debian Codegraph @

third_party/rust/wgpu-hal/src/dx12/mod.rs

raw
1 /*!
2 # DirectX12 API internals.
3
4 Generally the mapping is straightforward.
5
6 ## Resource transitions
7
8 D3D12 API matches WebGPU internal states very well. The only
9 caveat here is issuing a special UAV barrier whenever both source
10 and destination states match, and they are for storage sync.
11
12 ## Memory
13
14 For now, all resources are created with "committed" memory.
15
16 ## Sampler Descriptor Management
17
18 At most one descriptor heap of each type can be bound at once. This
19 means that the descriptors from all bind groups need to be present
20 in the same heap, and they need to be contiguous within that heap.
21 This is not a problem for the SRV/CBV/UAV heap as it can be sized into
22 the millions of entries. However the sampler heap is limited to 2048 entries.
23
24 In order to work around this limitation, we refer to samplers indirectly by index.
25 The entire sampler heap is bound at once and a buffer containing all sampler indexes
26 for that bind group is bound. The shader then uses the index to look up the sampler
27 in the heap. To help visualize this, the generated HLSL looks like this:
28
29 ```wgsl
30 @group(0) @binding(2) var myLinearSampler: sampler;
31 @group(1) @binding(1) var myAnisoSampler: sampler;
32 @group(1) @binding(4) var myCompSampler: sampler;
33 ```
34
35 ```cpp
36 // These bindings alias the same descriptors. Depending on the type, the shader will use the correct one.
37 SamplerState nagaSamplerHeap[2048]: register(s0, space0);
38 SamplerComparisonState nagaComparisonSamplerHeap[2048]: register(s2048, space1);
39
40 StructuredBuffer<uint> nagaGroup0SamplerIndexArray : register(t0, space0);
41 StructuredBuffer<uint> nagaGroup1SamplerIndexArray : register(t1, space0);
42
43 // Indexes into group 0 index array
44 static const SamplerState myLinearSampler = nagaSamplerHeap[nagaGroup0SamplerIndexArray[0]];
45
46 // Indexes into group 1 index array
47 static const SamplerState myAnisoSampler = nagaSamplerHeap[nagaGroup1SamplerIndexArray[0]];
48 static const SamplerComparisonState myCompSampler = nagaComparisonSamplerHeap[nagaGroup1SamplerIndexArray[1]];
49 ```
50
51 Without this transform we would need separate set of sampler descriptors for each unique combination of samplers
52 in a bind group. This results in a lot of duplication and makes it easy to hit the 2048 limit. With the transform
53 the limit is merely 2048 unique samplers in existence, which is much more reasonable.
54
55 ## Resource binding
56
57 See ['Device::create_pipeline_layout`] documentation for the structure
58 of the root signature corresponding to WebGPU pipeline layout.
59
60 Binding groups is mostly straightforward, with one big caveat:
61 all bindings have to be reset whenever the root signature changes.
62 This is the rule of D3D12, and we can do nothing to help it.
63
64 We detect this change at both [`crate::CommandEncoder::set_bind_group`]
65 and [`crate::CommandEncoder::set_render_pipeline`] with
66 [`crate::CommandEncoder::set_compute_pipeline`].
67
68 For this reason, in order avoid repeating the binding code,
69 we are binding everything in `CommandEncoder::update_root_elements`.
70 When the pipeline layout is changed, we reset all bindings.
71 Otherwise, we pass a range corresponding only to the current bind group.
72
73 !*/
74
75 mod adapter;
76 mod command;
77 mod conv;
78 mod descriptor;
79 mod device;
80 mod instance;
81 mod sampler;
82 mod shader_compilation;
83 mod suballocation;
84 mod types;
85 mod view;
86
87 use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec};
88 use core::{ffi, fmt, mem, num::NonZeroU32, ops::Deref};
89
90 use arrayvec::ArrayVec;
91 use parking_lot::{Mutex, RwLock};
92 use suballocation::Allocator;
93 use windows::{
94 core::{Free, Interface},
95 Win32::{
96 Foundation,
97 Graphics::{Direct3D, Direct3D12, DirectComposition, Dxgi},
98 System::Threading,
99 },
100 };
101
102 use crate::auxil::{
103 self,
104 dxgi::{
105 factory::{DxgiAdapter, DxgiFactory},
106 result::HResult,
107 },
108 };
109
110 #[derive(Debug)]
111 struct DynLib {
112 inner: libloading::Library,
113 }
114
115 impl DynLib {
116 unsafe fn new<P>(filename: P) -> Result<Self, libloading::Error>
117 where
118 P: AsRef<std::ffi::OsStr>,
119 {
120 unsafe { libloading::Library::new(filename) }.map(|inner| Self { inner })
121 }
122
123 unsafe fn get<T>(
124 &self,
125 symbol: &[u8],
126 ) -> Result<libloading::Symbol<'_, T>, crate::DeviceError> {
127 unsafe { self.inner.get(symbol) }.map_err(|e| match e {
128 libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown => {
129 crate::DeviceError::Unexpected
130 }
131 libloading::Error::IncompatibleSize
132 | libloading::Error::CreateCString { .. }
133 | libloading::Error::CreateCStringWithTrailing { .. } => crate::hal_internal_error(e),
134 _ => crate::DeviceError::Unexpected, // could be unreachable!() but we prefer to be more robust
135 })
136 }
137 }
138
139 #[derive(Debug)]
140 struct D3D12Lib {
141 lib: DynLib,
142 }
143
144 impl D3D12Lib {
145 fn new() -> Result<Self, libloading::Error> {
146 unsafe { DynLib::new("d3d12.dll").map(|lib| Self { lib }) }
147 }
148
149 fn create_device(
150 &self,
151 adapter: &DxgiAdapter,
152 feature_level: Direct3D::D3D_FEATURE_LEVEL,
153 ) -> Result<Option<Direct3D12::ID3D12Device>, crate::DeviceError> {
154 // Calls windows::Win32::Graphics::Direct3D12::D3D12CreateDevice on d3d12.dll
155 type Fun = extern "system" fn(
156 padapter: *mut ffi::c_void,
157 minimumfeaturelevel: Direct3D::D3D_FEATURE_LEVEL,
158 riid: *const windows_core::GUID,
159 ppdevice: *mut *mut ffi::c_void,
160 ) -> windows_core::HRESULT;
161 let func: libloading::Symbol<Fun> =
162 unsafe { self.lib.get(c"D3D12CreateDevice".to_bytes()) }?;
163
164 let mut result__: Option<Direct3D12::ID3D12Device> = None;
165
166 let res = (func)(
167 adapter.as_raw(),
168 feature_level,
169 // TODO: Generic?
170 &Direct3D12::ID3D12Device::IID,
171 <*mut _>::cast(&mut result__),
172 )
173 .ok();
174
175 if let Err(ref err) = res {
176 match err.code() {
177 Dxgi::DXGI_ERROR_UNSUPPORTED => return Ok(None),
178 Dxgi::DXGI_ERROR_DRIVER_INTERNAL_ERROR => return Err(crate::DeviceError::Lost),
179 _ => {}
180 }
181 }
182
183 res.into_device_result("Device creation")?;
184
185 result__.ok_or(crate::DeviceError::Unexpected).map(Some)
186 }
187
188 fn serialize_root_signature(
189 &self,
190 version: Direct3D12::D3D_ROOT_SIGNATURE_VERSION,
191 parameters: &[Direct3D12::D3D12_ROOT_PARAMETER],
192 static_samplers: &[Direct3D12::D3D12_STATIC_SAMPLER_DESC],
193 flags: Direct3D12::D3D12_ROOT_SIGNATURE_FLAGS,
194 ) -> Result<D3DBlob, crate::DeviceError> {
195 // Calls windows::Win32::Graphics::Direct3D12::D3D12SerializeRootSignature on d3d12.dll
196 type Fun = extern "system" fn(
197 prootsignature: *const Direct3D12::D3D12_ROOT_SIGNATURE_DESC,
198 version: Direct3D12::D3D_ROOT_SIGNATURE_VERSION,
199 ppblob: *mut *mut ffi::c_void,
200 pperrorblob: *mut *mut ffi::c_void,
201 ) -> windows_core::HRESULT;
202 let func: libloading::Symbol<Fun> =
203 unsafe { self.lib.get(c"D3D12SerializeRootSignature".to_bytes()) }?;
204
205 let desc = Direct3D12::D3D12_ROOT_SIGNATURE_DESC {
206 NumParameters: parameters.len() as _,
207 pParameters: parameters.as_ptr(),
208 NumStaticSamplers: static_samplers.len() as _,
209 pStaticSamplers: static_samplers.as_ptr(),
210 Flags: flags,
211 };
212
213 let mut blob = None;
214 let mut error = None::<Direct3D::ID3DBlob>;
215 (func)(
216 &desc,
217 version,
218 <*mut _>::cast(&mut blob),
219 <*mut _>::cast(&mut error),
220 )
221 .ok()
222 .into_device_result("Root signature serialization")?;
223
224 if let Some(error) = error {
225 let error = D3DBlob(error);
226 log::error!(
227 "Root signature serialization error: {:?}",
228 unsafe { error.as_c_str() }.unwrap().to_str().unwrap()
229 );
230 return Err(crate::DeviceError::Unexpected); // could be hal_usage_error or hal_internal_error
231 }
232
233 blob.ok_or(crate::DeviceError::Unexpected)
234 }
235
236 fn debug_interface(&self) -> Result<Option<Direct3D12::ID3D12Debug>, crate::DeviceError> {
237 // Calls windows::Win32::Graphics::Direct3D12::D3D12GetDebugInterface on d3d12.dll
238 type Fun = extern "system" fn(
239 riid: *const windows_core::GUID,
240 ppvdebug: *mut *mut ffi::c_void,
241 ) -> windows_core::HRESULT;
242 let func: libloading::Symbol<Fun> =
243 unsafe { self.lib.get(c"D3D12GetDebugInterface".to_bytes()) }?;
244
245 let mut result__ = None;
246
247 let res = (func)(&Direct3D12::ID3D12Debug::IID, <*mut _>::cast(&mut result__)).ok();
248
249 if let Err(ref err) = res {
250 match err.code() {
251 Dxgi::DXGI_ERROR_SDK_COMPONENT_MISSING => return Ok(None),
252 _ => {}
253 }
254 }
255
256 res.into_device_result("GetDebugInterface")?;
257
258 result__.ok_or(crate::DeviceError::Unexpected).map(Some)
259 }
260 }
261
262 #[derive(Debug)]
263 pub(super) struct DxgiLib {
264 lib: DynLib,
265 }
266
267 impl DxgiLib {
268 pub fn new() -> Result<Self, libloading::Error> {
269 unsafe { DynLib::new("dxgi.dll").map(|lib| Self { lib }) }
270 }
271
272 /// Will error with crate::DeviceError::Unexpected if DXGI 1.3 is not available.
273 pub fn debug_interface1(&self) -> Result<Option<Dxgi::IDXGIInfoQueue>, crate::DeviceError> {
274 // Calls windows::Win32::Graphics::Dxgi::DXGIGetDebugInterface1 on dxgi.dll
275 type Fun = extern "system" fn(
276 flags: u32,
277 riid: *const windows_core::GUID,
278 pdebug: *mut *mut ffi::c_void,
279 ) -> windows_core::HRESULT;
280 let func: libloading::Symbol<Fun> =
281 unsafe { self.lib.get(c"DXGIGetDebugInterface1".to_bytes()) }?;
282
283 let mut result__ = None;
284
285 let res = (func)(0, &Dxgi::IDXGIInfoQueue::IID, <*mut _>::cast(&mut result__)).ok();
286
287 if let Err(ref err) = res {
288 match err.code() {
289 Dxgi::DXGI_ERROR_SDK_COMPONENT_MISSING => return Ok(None),
290 _ => {}
291 }
292 }
293
294 res.into_device_result("debug_interface1")?;
295
296 result__.ok_or(crate::DeviceError::Unexpected).map(Some)
297 }
298
299 /// Will error with crate::DeviceError::Unexpected if DXGI 1.4 is not available.
300 pub fn create_factory4(
301 &self,
302 factory_flags: Dxgi::DXGI_CREATE_FACTORY_FLAGS,
303 ) -> Result<Dxgi::IDXGIFactory4, crate::DeviceError> {
304 // Calls windows::Win32::Graphics::Dxgi::CreateDXGIFactory2 on dxgi.dll
305 type Fun = extern "system" fn(
306 flags: Dxgi::DXGI_CREATE_FACTORY_FLAGS,
307 riid: *const windows_core::GUID,
308 ppfactory: *mut *mut ffi::c_void,
309 ) -> windows_core::HRESULT;
310 let func: libloading::Symbol<Fun> =
311 unsafe { self.lib.get(c"CreateDXGIFactory2".to_bytes()) }?;
312
313 let mut result__ = None;
314
315 (func)(
316 factory_flags,
317 &Dxgi::IDXGIFactory4::IID,
318 <*mut _>::cast(&mut result__),
319 )
320 .ok()
321 .into_device_result("create_factory4")?;
322
323 result__.ok_or(crate::DeviceError::Unexpected)
324 }
325
326 /// Will error with crate::DeviceError::Unexpected if DXGI 1.3 is not available.
327 pub fn create_factory_media(&self) -> Result<Dxgi::IDXGIFactoryMedia, crate::DeviceError> {
328 // Calls windows::Win32::Graphics::Dxgi::CreateDXGIFactory1 on dxgi.dll
329 type Fun = extern "system" fn(
330 riid: *const windows_core::GUID,
331 ppfactory: *mut *mut ffi::c_void,
332 ) -> windows_core::HRESULT;
333 let func: libloading::Symbol<Fun> =
334 unsafe { self.lib.get(c"CreateDXGIFactory1".to_bytes()) }?;
335
336 let mut result__ = None;
337
338 // https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nn-dxgi1_3-idxgifactorymedia
339 (func)(&Dxgi::IDXGIFactoryMedia::IID, <*mut _>::cast(&mut result__))
340 .ok()
341 .into_device_result("create_factory_media")?;
342
343 result__.ok_or(crate::DeviceError::Unexpected)
344 }
345 }
346
347 /// Create a temporary "owned" copy inside a [`mem::ManuallyDrop`] without increasing the refcount or
348 /// moving away the source variable.
349 ///
350 /// This is a common pattern when needing to pass interface pointers ("borrows") into Windows
351 /// structs. Moving/cloning ownership is impossible/inconvenient because:
352 ///
353 /// - The caller does _not_ assume ownership (and decrement the refcount at a later time);
354 /// - Unnecessarily increasing and decrementing the refcount;
355 /// - [`Drop`] destructors cannot run inside `union` structures (when the created structure is
356 /// implicitly dropped after a call).
357 ///
358 /// See also <https://github.com/microsoft/windows-rs/pull/2361#discussion_r1150799401> and
359 /// <https://github.com/microsoft/windows-rs/issues/2386>.
360 ///
361 /// # Safety
362 /// Performs a [`mem::transmute_copy()`] on a refcounted [`Interface`] type. The returned
363 /// [`mem::ManuallyDrop`] should _not_ be dropped.
364 pub unsafe fn borrow_interface_temporarily<I: Interface>(src: &I) -> mem::ManuallyDrop<Option<I>> {
365 unsafe { mem::transmute_copy(src) }
366 }
367
368 /// See [`borrow_interface_temporarily()`]
369 pub unsafe fn borrow_optional_interface_temporarily<I: Interface>(
370 src: &Option<I>,
371 ) -> mem::ManuallyDrop<Option<I>> {
372 unsafe { mem::transmute_copy(src) }
373 }
374
375 struct D3DBlob(Direct3D::ID3DBlob);
376
377 impl Deref for D3DBlob {
378 type Target = Direct3D::ID3DBlob;
379
380 fn deref(&self) -> &Self::Target {
381 &self.0
382 }
383 }
384
385 impl D3DBlob {
386 unsafe fn as_slice(&self) -> &[u8] {
387 unsafe { core::slice::from_raw_parts(self.GetBufferPointer().cast(), self.GetBufferSize()) }
388 }
389
390 unsafe fn as_c_str(&self) -> Result<&ffi::CStr, ffi::FromBytesUntilNulError> {
391 ffi::CStr::from_bytes_until_nul(unsafe { self.as_slice() })
392 }
393 }
394
395 #[derive(Clone, Debug)]
396 pub struct Api;
397
398 impl crate::Api for Api {
399 type Instance = Instance;
400 type Surface = Surface;
401 type Adapter = Adapter;
402 type Device = Device;
403
404 type Queue = Queue;
405 type CommandEncoder = CommandEncoder;
406 type CommandBuffer = CommandBuffer;
407
408 type Buffer = Buffer;
409 type Texture = Texture;
410 type SurfaceTexture = Texture;
411 type TextureView = TextureView;
412 type Sampler = Sampler;
413 type QuerySet = QuerySet;
414 type Fence = Fence;
415
416 type BindGroupLayout = BindGroupLayout;
417 type BindGroup = BindGroup;
418 type PipelineLayout = PipelineLayout;
419 type ShaderModule = ShaderModule;
420 type RenderPipeline = RenderPipeline;
421 type ComputePipeline = ComputePipeline;
422 type PipelineCache = PipelineCache;
423
424 type AccelerationStructure = AccelerationStructure;
425 }
426
427 crate::impl_dyn_resource!(
428 Adapter,
429 AccelerationStructure,
430 BindGroup,
431 BindGroupLayout,
432 Buffer,
433 CommandBuffer,
434 CommandEncoder,
435 ComputePipeline,
436 Device,
437 Fence,
438 Instance,
439 PipelineCache,
440 PipelineLayout,
441 QuerySet,
442 Queue,
443 RenderPipeline,
444 Sampler,
445 ShaderModule,
446 Surface,
447 Texture,
448 TextureView
449 );
450
451 // Limited by D3D12's root signature size of 64. Each element takes 1 or 2 entries.
452 const MAX_ROOT_ELEMENTS: usize = 64;
453 const ZERO_BUFFER_SIZE: wgt::BufferAddress = 256 << 10;
454
455 pub struct Instance {
456 factory: DxgiFactory,
457 factory_media: Option<Dxgi::IDXGIFactoryMedia>,
458 library: Arc<D3D12Lib>,
459 supports_allow_tearing: bool,
460 _lib_dxgi: DxgiLib,
461 flags: wgt::InstanceFlags,
462 memory_budget_thresholds: wgt::MemoryBudgetThresholds,
463 dxc_container: Option<Arc<shader_compilation::DxcContainer>>,
464 }
465
466 impl Instance {
467 pub unsafe fn create_surface_from_visual(&self, visual: *mut ffi::c_void) -> Surface {
468 let visual = unsafe { DirectComposition::IDCompositionVisual::from_raw_borrowed(&visual) }
469 .expect("COM pointer should not be NULL");
470 Surface {
471 factory: self.factory.clone(),
472 factory_media: self.factory_media.clone(),
473 target: SurfaceTarget::Visual(visual.to_owned()),
474 supports_allow_tearing: self.supports_allow_tearing,
475 swap_chain: RwLock::new(None),
476 }
477 }
478
479 pub unsafe fn create_surface_from_surface_handle(
480 &self,
481 surface_handle: *mut ffi::c_void,
482 ) -> Surface {
483 // TODO: We're not given ownership, so we shouldn't call HANDLE::free(). This puts an extra burden on the caller to keep it alive.
484 // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-duplicatehandle could help us, even though DirectComposition is not in the list?
485 // Or we make all these types owned, require an ownership transition, and replace SurfaceTargetUnsafe with SurfaceTarget.
486 let surface_handle = Foundation::HANDLE(surface_handle);
487 Surface {
488 factory: self.factory.clone(),
489 factory_media: self.factory_media.clone(),
490 target: SurfaceTarget::SurfaceHandle(surface_handle),
491 supports_allow_tearing: self.supports_allow_tearing,
492 swap_chain: RwLock::new(None),
493 }
494 }
495
496 pub unsafe fn create_surface_from_swap_chain_panel(
497 &self,
498 swap_chain_panel: *mut ffi::c_void,
499 ) -> Surface {
500 let swap_chain_panel =
501 unsafe { types::ISwapChainPanelNative::from_raw_borrowed(&swap_chain_panel) }
502 .expect("COM pointer should not be NULL");
503 Surface {
504 factory: self.factory.clone(),
505 factory_media: self.factory_media.clone(),
506 target: SurfaceTarget::SwapChainPanel(swap_chain_panel.to_owned()),
507 supports_allow_tearing: self.supports_allow_tearing,
508 swap_chain: RwLock::new(None),
509 }
510 }
511 }
512
513 unsafe impl Send for Instance {}
514 unsafe impl Sync for Instance {}
515
516 struct SwapChain {
517 // TODO: Drop order frees the SWC before the raw image pointers...?
518 raw: Dxgi::IDXGISwapChain3,
519 // need to associate raw image pointers with the swapchain so they can be properly released
520 // when the swapchain is destroyed
521 resources: Vec<Direct3D12::ID3D12Resource>,
522 /// Handle is freed in [`Self::release_resources()`]
523 waitable: Foundation::HANDLE,
524 acquired_count: usize,
525 present_mode: wgt::PresentMode,
526 format: wgt::TextureFormat,
527 size: wgt::Extent3d,
528 }
529
530 enum SurfaceTarget {
531 /// Borrowed, lifetime externally managed
532 WndHandle(Foundation::HWND),
533 Visual(DirectComposition::IDCompositionVisual),
534 /// Borrowed, lifetime externally managed
535 SurfaceHandle(Foundation::HANDLE),
536 SwapChainPanel(types::ISwapChainPanelNative),
537 }
538
539 pub struct Surface {
540 factory: DxgiFactory,
541 factory_media: Option<Dxgi::IDXGIFactoryMedia>,
542 target: SurfaceTarget,
543 supports_allow_tearing: bool,
544 swap_chain: RwLock<Option<SwapChain>>,
545 }
546
547 unsafe impl Send for Surface {}
548 unsafe impl Sync for Surface {}
549
550 impl Surface {
551 pub fn swap_chain(&self) -> Option<Dxgi::IDXGISwapChain3> {
552 Some(self.swap_chain.read().as_ref()?.raw.clone())
553 }
554 }
555
556 #[derive(Debug, Clone, Copy)]
557 enum MemoryArchitecture {
558 Unified {
559 #[allow(unused)]
560 cache_coherent: bool,
561 },
562 NonUnified,
563 }
564
565 #[derive(Debug, Clone, Copy)]
566 struct PrivateCapabilities {
567 instance_flags: wgt::InstanceFlags,
568 #[allow(unused)]
569 heterogeneous_resource_heaps: bool,
570 memory_architecture: MemoryArchitecture,
571 heap_create_not_zeroed: bool,
572 casting_fully_typed_format_supported: bool,
573 suballocation_supported: bool,
574 shader_model: naga::back::hlsl::ShaderModel,
575 max_sampler_descriptor_heap_size: u32,
576 }
577
578 #[derive(Default)]
579 struct Workarounds {
580 // On WARP, temporary CPU descriptors are still used by the runtime
581 // after we call `CopyDescriptors`.
582 avoid_cpu_descriptor_overwrites: bool,
583 }
584
585 pub struct Adapter {
586 raw: DxgiAdapter,
587 device: Direct3D12::ID3D12Device,
588 library: Arc<D3D12Lib>,
589 private_caps: PrivateCapabilities,
590 presentation_timer: auxil::dxgi::time::PresentationTimer,
591 // Note: this isn't used right now, but we'll need it later.
592 #[allow(unused)]
593 workarounds: Workarounds,
594 memory_budget_thresholds: wgt::MemoryBudgetThresholds,
595 dxc_container: Option<Arc<shader_compilation::DxcContainer>>,
596 }
597
598 unsafe impl Send for Adapter {}
599 unsafe impl Sync for Adapter {}
600
601 struct Event(pub Foundation::HANDLE);
602 impl Event {
603 pub fn create(manual_reset: bool, initial_state: bool) -> Result<Self, crate::DeviceError> {
604 Ok(Self(
605 unsafe { Threading::CreateEventA(None, manual_reset, initial_state, None) }
606 .into_device_result("CreateEventA")?,
607 ))
608 }
609 }
610
611 impl Drop for Event {
612 fn drop(&mut self) {
613 unsafe { Foundation::HANDLE::free(&mut self.0) }
614 }
615 }
616
617 /// Helper structure for waiting for GPU.
618 struct Idler {
619 fence: Direct3D12::ID3D12Fence,
620 event: Event,
621 }
622
623 #[derive(Debug, Clone)]
624 struct CommandSignatures {
625 draw: Direct3D12::ID3D12CommandSignature,
626 draw_indexed: Direct3D12::ID3D12CommandSignature,
627 dispatch: Direct3D12::ID3D12CommandSignature,
628 }
629
630 struct DeviceShared {
631 adapter: DxgiAdapter,
632 zero_buffer: Direct3D12::ID3D12Resource,
633 cmd_signatures: CommandSignatures,
634 heap_views: descriptor::GeneralHeap,
635 sampler_heap: sampler::SamplerHeap,
636 private_caps: PrivateCapabilities,
637 }
638
639 unsafe impl Send for DeviceShared {}
640 unsafe impl Sync for DeviceShared {}
641
642 pub struct Device {
643 raw: Direct3D12::ID3D12Device,
644 present_queue: Direct3D12::ID3D12CommandQueue,
645 idler: Idler,
646 features: wgt::Features,
647 shared: Arc<DeviceShared>,
648 // CPU only pools
649 rtv_pool: Arc<Mutex<descriptor::CpuPool>>,
650 dsv_pool: Mutex<descriptor::CpuPool>,
651 srv_uav_pool: Mutex<descriptor::CpuPool>,
652 // library
653 library: Arc<D3D12Lib>,
654 #[cfg(feature = "renderdoc")]
655 render_doc: auxil::renderdoc::RenderDoc,
656 null_rtv_handle: descriptor::Handle,
657 mem_allocator: Allocator,
658 dxc_container: Option<Arc<shader_compilation::DxcContainer>>,
659 counters: Arc<wgt::HalCounters>,
660 }
661
662 impl Drop for Device {
663 fn drop(&mut self) {
664 self.rtv_pool.lock().free_handle(self.null_rtv_handle);
665 if self
666 .shared
667 .private_caps
668 .instance_flags
669 .contains(wgt::InstanceFlags::VALIDATION)
670 {
671 auxil::dxgi::exception::unregister_exception_handler();
672 }
673 }
674 }
675
676 unsafe impl Send for Device {}
677 unsafe impl Sync for Device {}
678
679 pub struct Queue {
680 raw: Direct3D12::ID3D12CommandQueue,
681 temp_lists: Mutex<Vec<Option<Direct3D12::ID3D12CommandList>>>,
682 }
683
684 impl Queue {
685 pub fn as_raw(&self) -> &Direct3D12::ID3D12CommandQueue {
686 &self.raw
687 }
688 }
689
690 unsafe impl Send for Queue {}
691 unsafe impl Sync for Queue {}
692
693 #[derive(Default)]
694 struct Temp {
695 marker: Vec<u16>,
696 barriers: Vec<Direct3D12::D3D12_RESOURCE_BARRIER>,
697 }
698
699 impl Temp {
700 fn clear(&mut self) {
701 self.marker.clear();
702 self.barriers.clear();
703 }
704 }
705
706 struct PassResolve {
707 src: (Direct3D12::ID3D12Resource, u32),
708 dst: (Direct3D12::ID3D12Resource, u32),
709 format: Dxgi::Common::DXGI_FORMAT,
710 }
711
712 #[derive(Clone, Copy, Debug)]
713 enum RootElement {
714 Empty,
715 Constant,
716 SpecialConstantBuffer {
717 /// The first vertex in an indirect draw call, _or_ the `x` of a compute dispatch.
718 first_vertex: i32,
719 /// The first instance in an indirect draw call, _or_ the `y` of a compute dispatch.
720 first_instance: u32,
721 /// Unused in an indirect draw call, _or_ the `z` of a compute dispatch.
722 other: u32,
723 },
724 /// Descriptor table.
725 Table(Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE),
726 /// Descriptor for an uniform buffer that has dynamic offset.
727 DynamicUniformBuffer {
728 address: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE,
729 },
730 /// Descriptor table referring to the entire sampler heap.
731 SamplerHeap,
732 /// Root constants for dynamic offsets.
733 ///
734 /// start..end is the range of values in [`PassState::dynamic_storage_buffer_offsets`]
735 /// that will be used to update the root constants.
736 DynamicOffsetsBuffer {
737 start: usize,
738 end: usize,
739 },
740 }
741
742 #[derive(Clone, Copy)]
743 enum PassKind {
744 Render,
745 Compute,
746 Transfer,
747 }
748
749 struct PassState {
750 has_label: bool,
751 resolves: ArrayVec<PassResolve, { crate::MAX_COLOR_ATTACHMENTS }>,
752 layout: PipelineLayoutShared,
753 root_elements: [RootElement; MAX_ROOT_ELEMENTS],
754 constant_data: [u32; MAX_ROOT_ELEMENTS],
755 dynamic_storage_buffer_offsets: Vec<u32>,
756 dirty_root_elements: u64,
757 vertex_buffers: [Direct3D12::D3D12_VERTEX_BUFFER_VIEW; crate::MAX_VERTEX_BUFFERS],
758 dirty_vertex_buffers: usize,
759 kind: PassKind,
760 }
761
762 #[test]
763 fn test_dirty_mask() {
764 assert_eq!(MAX_ROOT_ELEMENTS, u64::BITS as usize);
765 }
766
767 impl PassState {
768 fn new() -> Self {
769 PassState {
770 has_label: false,
771 resolves: ArrayVec::new(),
772 layout: PipelineLayoutShared {
773 signature: None,
774 total_root_elements: 0,
775 special_constants: None,
776 root_constant_info: None,
777 sampler_heap_root_index: None,
778 },
779 root_elements: [RootElement::Empty; MAX_ROOT_ELEMENTS],
780 constant_data: [0; MAX_ROOT_ELEMENTS],
781 dynamic_storage_buffer_offsets: Vec::new(),
782 dirty_root_elements: 0,
783 vertex_buffers: [Default::default(); crate::MAX_VERTEX_BUFFERS],
784 dirty_vertex_buffers: 0,
785 kind: PassKind::Transfer,
786 }
787 }
788
789 fn clear(&mut self) {
790 // careful about heap allocations!
791 *self = Self::new();
792 }
793 }
794
795 pub struct CommandEncoder {
796 allocator: Direct3D12::ID3D12CommandAllocator,
797 device: Direct3D12::ID3D12Device,
798 shared: Arc<DeviceShared>,
799 mem_allocator: Allocator,
800
801 rtv_pool: Arc<Mutex<descriptor::CpuPool>>,
802 temp_rtv_handles: Vec<descriptor::Handle>,
803
804 null_rtv_handle: descriptor::Handle,
805 list: Option<Direct3D12::ID3D12GraphicsCommandList>,
806 free_lists: Vec<Direct3D12::ID3D12GraphicsCommandList>,
807 pass: PassState,
808 temp: Temp,
809
810 /// If set, the end of the next render/compute pass will write a timestamp at
811 /// the given pool & location.
812 end_of_pass_timer_query: Option<(Direct3D12::ID3D12QueryHeap, u32)>,
813
814 counters: Arc<wgt::HalCounters>,
815 }
816
817 unsafe impl Send for CommandEncoder {}
818 unsafe impl Sync for CommandEncoder {}
819
820 impl fmt::Debug for CommandEncoder {
821 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822 f.debug_struct("CommandEncoder")
823 .field("allocator", &self.allocator)
824 .field("device", &self.allocator)
825 .finish()
826 }
827 }
828
829 #[derive(Debug)]
830 pub struct CommandBuffer {
831 raw: Direct3D12::ID3D12GraphicsCommandList,
832 }
833
834 impl crate::DynCommandBuffer for CommandBuffer {}
835
836 unsafe impl Send for CommandBuffer {}
837 unsafe impl Sync for CommandBuffer {}
838
839 #[derive(Debug)]
840 pub struct Buffer {
841 resource: Direct3D12::ID3D12Resource,
842 // While the allocation also has _a_ size, it may not
843 // be the same as the original size of the buffer,
844 // as the allocation size varies for assorted reasons.
845 size: wgt::BufferAddress,
846 allocation: suballocation::Allocation,
847 }
848
849 unsafe impl Send for Buffer {}
850 unsafe impl Sync for Buffer {}
851
852 impl crate::DynBuffer for Buffer {}
853
854 impl crate::BufferBinding<'_, Buffer> {
855 fn resolve_size(&self) -> wgt::BufferAddress {
856 match self.size {
857 Some(size) => size.get(),
858 None => self.buffer.size - self.offset,
859 }
860 }
861
862 // TODO: Return GPU handle directly?
863 fn resolve_address(&self) -> wgt::BufferAddress {
864 (unsafe { self.buffer.resource.GetGPUVirtualAddress() }) + self.offset
865 }
866 }
867
868 #[derive(Debug)]
869 pub struct Texture {
870 resource: Direct3D12::ID3D12Resource,
871 format: wgt::TextureFormat,
872 dimension: wgt::TextureDimension,
873 size: wgt::Extent3d,
874 mip_level_count: u32,
875 sample_count: u32,
876 allocation: suballocation::Allocation,
877 }
878
879 impl Texture {
880 pub unsafe fn raw_resource(&self) -> &Direct3D12::ID3D12Resource {
881 &self.resource
882 }
883 }
884
885 impl crate::DynTexture for Texture {}
886 impl crate::DynSurfaceTexture for Texture {}
887
888 impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
889 fn borrow(&self) -> &dyn crate::DynTexture {
890 self
891 }
892 }
893
894 unsafe impl Send for Texture {}
895 unsafe impl Sync for Texture {}
896
897 impl Texture {
898 fn array_layer_count(&self) -> u32 {
899 match self.dimension {
900 wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1,
901 wgt::TextureDimension::D2 => self.size.depth_or_array_layers,
902 }
903 }
904
905 /// see <https://learn.microsoft.com/en-us/windows/win32/direct3d12/subresources#plane-slice>
906 fn calc_subresource(&self, mip_level: u32, array_layer: u32, plane: u32) -> u32 {
907 mip_level + (array_layer + plane * self.array_layer_count()) * self.mip_level_count
908 }
909
910 fn calc_subresource_for_copy(&self, base: &crate::TextureCopyBase) -> u32 {
911 let plane = match base.aspect {
912 crate::FormatAspects::COLOR | crate::FormatAspects::DEPTH => 0,
913 crate::FormatAspects::STENCIL => 1,
914 _ => unreachable!(),
915 };
916 self.calc_subresource(base.mip_level, base.array_layer, plane)
917 }
918 }
919
920 #[derive(Debug)]
921 pub struct TextureView {
922 raw_format: Dxgi::Common::DXGI_FORMAT,
923 aspects: crate::FormatAspects,
924 dimension: wgt::TextureViewDimension,
925 texture: Direct3D12::ID3D12Resource,
926 subresource_index: u32,
927 mip_slice: u32,
928 handle_srv: Option<descriptor::Handle>,
929 handle_uav: Option<descriptor::Handle>,
930 handle_rtv: Option<descriptor::Handle>,
931 handle_dsv_ro: Option<descriptor::Handle>,
932 handle_dsv_rw: Option<descriptor::Handle>,
933 }
934
935 impl crate::DynTextureView for TextureView {}
936
937 unsafe impl Send for TextureView {}
938 unsafe impl Sync for TextureView {}
939
940 #[derive(Debug)]
941 pub struct Sampler {
942 index: sampler::SamplerIndex,
943 desc: Direct3D12::D3D12_SAMPLER_DESC,
944 }
945
946 impl crate::DynSampler for Sampler {}
947
948 unsafe impl Send for Sampler {}
949 unsafe impl Sync for Sampler {}
950
951 #[derive(Debug)]
952 pub struct QuerySet {
953 raw: Direct3D12::ID3D12QueryHeap,
954 raw_ty: Direct3D12::D3D12_QUERY_TYPE,
955 }
956
957 impl crate::DynQuerySet for QuerySet {}
958
959 unsafe impl Send for QuerySet {}
960 unsafe impl Sync for QuerySet {}
961
962 #[derive(Debug)]
963 pub struct Fence {
964 raw: Direct3D12::ID3D12Fence,
965 }
966
967 impl crate::DynFence for Fence {}
968
969 unsafe impl Send for Fence {}
970 unsafe impl Sync for Fence {}
971
972 impl Fence {
973 pub fn raw_fence(&self) -> &Direct3D12::ID3D12Fence {
974 &self.raw
975 }
976 }
977
978 #[derive(Debug)]
979 pub struct BindGroupLayout {
980 /// Sorted list of entries.
981 entries: Vec<wgt::BindGroupLayoutEntry>,
982 cpu_heap_views: Option<descriptor::CpuHeap>,
983 copy_counts: Vec<u32>, // all 1's
984 }
985
986 impl crate::DynBindGroupLayout for BindGroupLayout {}
987
988 #[derive(Debug, Clone, Copy)]
989 enum DynamicBuffer {
990 Uniform(Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE),
991 Storage,
992 }
993
994 #[derive(Debug)]
995 struct SamplerIndexBuffer {
996 buffer: Direct3D12::ID3D12Resource,
997 allocation: suballocation::Allocation,
998 }
999
1000 #[derive(Debug)]
1001 pub struct BindGroup {
1002 handle_views: Option<descriptor::DualHandle>,
1003 sampler_index_buffer: Option<SamplerIndexBuffer>,
1004 dynamic_buffers: Vec<DynamicBuffer>,
1005 }
1006
1007 impl crate::DynBindGroup for BindGroup {}
1008
1009 bitflags::bitflags! {
1010 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1011 struct TableTypes: u8 {
1012 const SRV_CBV_UAV = 1 << 0;
1013 const SAMPLERS = 1 << 1;
1014 }
1015 }
1016
1017 // Element (also known as parameter) index into the root signature.
1018 type RootIndex = u32;
1019
1020 #[derive(Debug)]
1021 struct BindGroupInfo {
1022 base_root_index: RootIndex,
1023 tables: TableTypes,
1024 dynamic_storage_buffer_offsets: Option<DynamicStorageBufferOffsets>,
1025 }
1026
1027 #[derive(Debug, Clone)]
1028 struct RootConstantInfo {
1029 root_index: RootIndex,
1030 range: core::ops::Range<u32>,
1031 }
1032
1033 #[derive(Debug, Clone)]
1034 struct DynamicStorageBufferOffsets {
1035 root_index: RootIndex,
1036 range: core::ops::Range<usize>,
1037 }
1038
1039 #[derive(Debug, Clone)]
1040 struct PipelineLayoutShared {
1041 signature: Option<Direct3D12::ID3D12RootSignature>,
1042 total_root_elements: RootIndex,
1043 special_constants: Option<PipelineLayoutSpecialConstants>,
1044 root_constant_info: Option<RootConstantInfo>,
1045 sampler_heap_root_index: Option<RootIndex>,
1046 }
1047
1048 unsafe impl Send for PipelineLayoutShared {}
1049 unsafe impl Sync for PipelineLayoutShared {}
1050
1051 #[derive(Debug, Clone)]
1052 struct PipelineLayoutSpecialConstants {
1053 root_index: RootIndex,
1054 indirect_cmd_signatures: Option<CommandSignatures>,
1055 }
1056
1057 unsafe impl Send for PipelineLayoutSpecialConstants {}
1058 unsafe impl Sync for PipelineLayoutSpecialConstants {}
1059
1060 #[derive(Debug)]
1061 pub struct PipelineLayout {
1062 shared: PipelineLayoutShared,
1063 // Storing for each associated bind group, which tables we created
1064 // in the root signature. This is required for binding descriptor sets.
1065 bind_group_infos: ArrayVec<BindGroupInfo, { crate::MAX_BIND_GROUPS }>,
1066 naga_options: naga::back::hlsl::Options,
1067 }
1068
1069 impl crate::DynPipelineLayout for PipelineLayout {}
1070
1071 #[derive(Debug)]
1072 pub struct ShaderModule {
1073 naga: crate::NagaShader,
1074 raw_name: Option<alloc::ffi::CString>,
1075 runtime_checks: wgt::ShaderRuntimeChecks,
1076 }
1077
1078 impl crate::DynShaderModule for ShaderModule {}
1079
1080 pub(super) enum CompiledShader {
1081 Dxc(Direct3D::Dxc::IDxcBlob),
1082 Fxc(Direct3D::ID3DBlob),
1083 }
1084
1085 impl CompiledShader {
1086 fn create_native_shader(&self) -> Direct3D12::D3D12_SHADER_BYTECODE {
1087 match self {
1088 CompiledShader::Dxc(shader) => Direct3D12::D3D12_SHADER_BYTECODE {
1089 pShaderBytecode: unsafe { shader.GetBufferPointer() },
1090 BytecodeLength: unsafe { shader.GetBufferSize() },
1091 },
1092 CompiledShader::Fxc(shader) => Direct3D12::D3D12_SHADER_BYTECODE {
1093 pShaderBytecode: unsafe { shader.GetBufferPointer() },
1094 BytecodeLength: unsafe { shader.GetBufferSize() },
1095 },
1096 }
1097 }
1098
1099 unsafe fn destroy(self) {}
1100 }
1101
1102 #[derive(Debug)]
1103 pub struct RenderPipeline {
1104 raw: Direct3D12::ID3D12PipelineState,
1105 layout: PipelineLayoutShared,
1106 topology: Direct3D::D3D_PRIMITIVE_TOPOLOGY,
1107 vertex_strides: [Option<NonZeroU32>; crate::MAX_VERTEX_BUFFERS],
1108 }
1109
1110 impl crate::DynRenderPipeline for RenderPipeline {}
1111
1112 unsafe impl Send for RenderPipeline {}
1113 unsafe impl Sync for RenderPipeline {}
1114
1115 #[derive(Debug)]
1116 pub struct ComputePipeline {
1117 raw: Direct3D12::ID3D12PipelineState,
1118 layout: PipelineLayoutShared,
1119 }
1120
1121 impl crate::DynComputePipeline for ComputePipeline {}
1122
1123 unsafe impl Send for ComputePipeline {}
1124 unsafe impl Sync for ComputePipeline {}
1125
1126 #[derive(Debug)]
1127 pub struct PipelineCache;
1128
1129 impl crate::DynPipelineCache for PipelineCache {}
1130
1131 #[derive(Debug)]
1132 pub struct AccelerationStructure {
1133 resource: Direct3D12::ID3D12Resource,
1134 allocation: suballocation::Allocation,
1135 }
1136
1137 impl crate::DynAccelerationStructure for AccelerationStructure {}
1138
1139 impl SwapChain {
1140 unsafe fn release_resources(mut self) -> Dxgi::IDXGISwapChain3 {
1141 unsafe { Foundation::HANDLE::free(&mut self.waitable) };
1142 self.raw
1143 }
1144
1145 unsafe fn wait(
1146 &mut self,
1147 timeout: Option<core::time::Duration>,
1148 ) -> Result<bool, crate::SurfaceError> {
1149 let timeout_ms = match timeout {
1150 Some(duration) => duration.as_millis() as u32,
1151 None => Threading::INFINITE,
1152 };
1153 match unsafe { Threading::WaitForSingleObject(self.waitable, timeout_ms) } {
1154 Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => Err(crate::SurfaceError::Lost),
1155 Foundation::WAIT_OBJECT_0 => Ok(true),
1156 Foundation::WAIT_TIMEOUT => Ok(false),
1157 other => {
1158 log::error!("Unexpected wait status: 0x{:x?}", other);
1159 Err(crate::SurfaceError::Lost)
1160 }
1161 }
1162 }
1163 }
1164
1165 impl crate::Surface for Surface {
1166 type A = Api;
1167
1168 unsafe fn configure(
1169 &self,
1170 device: &Device,
1171 config: &crate::SurfaceConfiguration,
1172 ) -> Result<(), crate::SurfaceError> {
1173 let mut flags = Dxgi::DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
1174 // We always set ALLOW_TEARING on the swapchain no matter
1175 // what kind of swapchain we want because ResizeBuffers
1176 // cannot change the swapchain's ALLOW_TEARING flag.
1177 //
1178 // This does not change the behavior of the swapchain, just
1179 // allow present calls to use tearing.
1180 if self.supports_allow_tearing {
1181 flags |= Dxgi::DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
1182 }
1183
1184 // While `configure`s contract ensures that no work on the GPU's main queues
1185 // are in flight, we still need to wait for the present queue to be idle.
1186 unsafe { device.wait_for_present_queue_idle() }?;
1187
1188 let non_srgb_format = auxil::dxgi::conv::map_texture_format_nosrgb(config.format);
1189
1190 // The range for `SetMaximumFrameLatency` is 1-16 so the maximum latency requested should be 15 because we add 1.
1191 // https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgidevice1-setmaximumframelatency
1192 debug_assert!(config.maximum_frame_latency <= 15);
1193
1194 // Nvidia recommends to use 1-2 more buffers than the maximum latency
1195 // https://developer.nvidia.com/blog/advanced-api-performance-swap-chains/
1196 // For high latency extra buffers seems excessive, so go with a minimum of 3 and beyond that add 1.
1197 let swap_chain_buffer = (config.maximum_frame_latency + 1).min(16);
1198
1199 let swap_chain = match self.swap_chain.write().take() {
1200 //Note: this path doesn't properly re-initialize all of the things
1201 Some(sc) => {
1202 let raw = unsafe { sc.release_resources() };
1203 let result = unsafe {
1204 raw.ResizeBuffers(
1205 swap_chain_buffer,
1206 config.extent.width,
1207 config.extent.height,
1208 non_srgb_format,
1209 flags,
1210 )
1211 };
1212 if let Err(err) = result {
1213 log::error!("ResizeBuffers failed: {err}");
1214 return Err(crate::SurfaceError::Other("window is in use"));
1215 }
1216 raw
1217 }
1218 None => {
1219 let desc = Dxgi::DXGI_SWAP_CHAIN_DESC1 {
1220 AlphaMode: auxil::dxgi::conv::map_acomposite_alpha_mode(
1221 config.composite_alpha_mode,
1222 ),
1223 Width: config.extent.width,
1224 Height: config.extent.height,
1225 Format: non_srgb_format,
1226 Stereo: false.into(),
1227 SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
1228 Count: 1,
1229 Quality: 0,
1230 },
1231 BufferUsage: Dxgi::DXGI_USAGE_RENDER_TARGET_OUTPUT,
1232 BufferCount: swap_chain_buffer,
1233 Scaling: Dxgi::DXGI_SCALING_STRETCH,
1234 SwapEffect: Dxgi::DXGI_SWAP_EFFECT_FLIP_DISCARD,
1235 Flags: flags.0 as u32,
1236 };
1237 let swap_chain1 = match self.target {
1238 SurfaceTarget::Visual(_) | SurfaceTarget::SwapChainPanel(_) => {
1239 profiling::scope!("IDXGIFactory2::CreateSwapChainForComposition");
1240 unsafe {
1241 self.factory.CreateSwapChainForComposition(
1242 &device.present_queue,
1243 &desc,
1244 None,
1245 )
1246 }
1247 }
1248 SurfaceTarget::SurfaceHandle(handle) => {
1249 profiling::scope!(
1250 "IDXGIFactoryMedia::CreateSwapChainForCompositionSurfaceHandle"
1251 );
1252 unsafe {
1253 self.factory_media
1254 .as_ref()
1255 .ok_or(crate::SurfaceError::Other("IDXGIFactoryMedia not found"))?
1256 .CreateSwapChainForCompositionSurfaceHandle(
1257 &device.present_queue,
1258 handle,
1259 &desc,
1260 None,
1261 )
1262 }
1263 }
1264 SurfaceTarget::WndHandle(hwnd) => {
1265 profiling::scope!("IDXGIFactory2::CreateSwapChainForHwnd");
1266 unsafe {
1267 self.factory.CreateSwapChainForHwnd(
1268 &device.present_queue,
1269 hwnd,
1270 &desc,
1271 None,
1272 None,
1273 )
1274 }
1275 }
1276 };
1277
1278 let swap_chain1 = swap_chain1.map_err(|err| {
1279 log::error!("SwapChain creation error: {}", err);
1280 crate::SurfaceError::Other("swapchain creation")
1281 })?;
1282
1283 match &self.target {
1284 SurfaceTarget::WndHandle(_) | SurfaceTarget::SurfaceHandle(_) => {}
1285 SurfaceTarget::Visual(visual) => {
1286 if let Err(err) = unsafe { visual.SetContent(&swap_chain1) } {
1287 log::error!("Unable to SetContent: {err}");
1288 return Err(crate::SurfaceError::Other(
1289 "IDCompositionVisual::SetContent",
1290 ));
1291 }
1292 }
1293 SurfaceTarget::SwapChainPanel(swap_chain_panel) => {
1294 if let Err(err) = unsafe { swap_chain_panel.SetSwapChain(&swap_chain1) } {
1295 log::error!("Unable to SetSwapChain: {err}");
1296 return Err(crate::SurfaceError::Other(
1297 "ISwapChainPanelNative::SetSwapChain",
1298 ));
1299 }
1300 }
1301 }
1302
1303 swap_chain1.cast::<Dxgi::IDXGISwapChain3>().map_err(|err| {
1304 log::error!("Unable to cast swapchain: {err}");
1305 crate::SurfaceError::Other("swapchain cast to version 3")
1306 })?
1307 }
1308 };
1309
1310 match self.target {
1311 SurfaceTarget::WndHandle(wnd_handle) => {
1312 // Disable automatic Alt+Enter handling by DXGI.
1313 unsafe {
1314 self.factory.MakeWindowAssociation(
1315 wnd_handle,
1316 Dxgi::DXGI_MWA_NO_WINDOW_CHANGES | Dxgi::DXGI_MWA_NO_ALT_ENTER,
1317 )
1318 }
1319 .into_device_result("MakeWindowAssociation")?;
1320 }
1321 SurfaceTarget::Visual(_)
1322 | SurfaceTarget::SurfaceHandle(_)
1323 | SurfaceTarget::SwapChainPanel(_) => {}
1324 }
1325
1326 unsafe { swap_chain.SetMaximumFrameLatency(config.maximum_frame_latency) }
1327 .into_device_result("SetMaximumFrameLatency")?;
1328 let waitable = unsafe { swap_chain.GetFrameLatencyWaitableObject() };
1329
1330 let mut resources = Vec::with_capacity(swap_chain_buffer as usize);
1331 for i in 0..swap_chain_buffer {
1332 let resource = unsafe { swap_chain.GetBuffer(i) }
1333 .into_device_result("Failed to get swapchain buffer")?;
1334 resources.push(resource);
1335 }
1336
1337 let mut swapchain = self.swap_chain.write();
1338 *swapchain = Some(SwapChain {
1339 raw: swap_chain,
1340 resources,
1341 waitable,
1342 acquired_count: 0,
1343 present_mode: config.present_mode,
1344 format: config.format,
1345 size: config.extent,
1346 });
1347
1348 Ok(())
1349 }
1350
1351 unsafe fn unconfigure(&self, device: &Device) {
1352 if let Some(sc) = self.swap_chain.write().take() {
1353 unsafe {
1354 // While `unconfigure`s contract ensures that no work on the GPU's main queues
1355 // are in flight, we still need to wait for the present queue to be idle.
1356
1357 // The major failure mode of this function is device loss,
1358 // which if we have lost the device, we should just continue
1359 // cleaning up, without error.
1360 let _ = device.wait_for_present_queue_idle();
1361
1362 let _raw = sc.release_resources();
1363 }
1364 }
1365 }
1366
1367 unsafe fn acquire_texture(
1368 &self,
1369 timeout: Option<core::time::Duration>,
1370 _fence: &Fence,
1371 ) -> Result<Option<crate::AcquiredSurfaceTexture<Api>>, crate::SurfaceError> {
1372 let mut swapchain = self.swap_chain.write();
1373 let sc = swapchain.as_mut().unwrap();
1374
1375 unsafe { sc.wait(timeout) }?;
1376
1377 let base_index = unsafe { sc.raw.GetCurrentBackBufferIndex() } as usize;
1378 let index = (base_index + sc.acquired_count) % sc.resources.len();
1379 sc.acquired_count += 1;
1380
1381 let texture = Texture {
1382 resource: sc.resources[index].clone(),
1383 format: sc.format,
1384 dimension: wgt::TextureDimension::D2,
1385 size: sc.size,
1386 mip_level_count: 1,
1387 sample_count: 1,
1388 allocation: suballocation::Allocation::none(
1389 suballocation::AllocationType::Texture,
1390 sc.format.theoretical_memory_footprint(sc.size),
1391 ),
1392 };
1393 Ok(Some(crate::AcquiredSurfaceTexture {
1394 texture,
1395 suboptimal: false,
1396 }))
1397 }
1398 unsafe fn discard_texture(&self, _texture: Texture) {
1399 let mut swapchain = self.swap_chain.write();
1400 let sc = swapchain.as_mut().unwrap();
1401 sc.acquired_count -= 1;
1402 }
1403 }
1404
1405 impl crate::Queue for Queue {
1406 type A = Api;
1407
1408 unsafe fn submit(
1409 &self,
1410 command_buffers: &[&CommandBuffer],
1411 _surface_textures: &[&Texture],
1412 (signal_fence, signal_value): (&mut Fence, crate::FenceValue),
1413 ) -> Result<(), crate::DeviceError> {
1414 let mut temp_lists = self.temp_lists.lock();
1415 temp_lists.clear();
1416 for cmd_buf in command_buffers {
1417 temp_lists.push(Some(cmd_buf.raw.clone().into()));
1418 }
1419
1420 {
1421 profiling::scope!("ID3D12CommandQueue::ExecuteCommandLists");
1422 unsafe { self.raw.ExecuteCommandLists(&temp_lists) }
1423 }
1424
1425 unsafe { self.raw.Signal(&signal_fence.raw, signal_value) }
1426 .into_device_result("Signal fence")?;
1427
1428 // Note the lack of synchronization here between the main Direct queue
1429 // and the dedicated presentation queue. This is automatically handled
1430 // by the D3D runtime by detecting uses of resources derived from the
1431 // swapchain. This automatic detection is why you cannot use a swapchain
1432 // as an UAV in D3D12.
1433
1434 Ok(())
1435 }
1436 unsafe fn present(
1437 &self,
1438 surface: &Surface,
1439 _texture: Texture,
1440 ) -> Result<(), crate::SurfaceError> {
1441 let mut swapchain = surface.swap_chain.write();
1442 let sc = swapchain.as_mut().unwrap();
1443 sc.acquired_count -= 1;
1444
1445 let (interval, flags) = match sc.present_mode {
1446 // We only allow immediate if ALLOW_TEARING is valid.
1447 wgt::PresentMode::Immediate => (0, Dxgi::DXGI_PRESENT_ALLOW_TEARING),
1448 wgt::PresentMode::Mailbox => (0, Dxgi::DXGI_PRESENT::default()),
1449 wgt::PresentMode::Fifo => (1, Dxgi::DXGI_PRESENT::default()),
1450 m => unreachable!("Cannot make surface with present mode {m:?}"),
1451 };
1452
1453 profiling::scope!("IDXGISwapchain3::Present");
1454 unsafe { sc.raw.Present(interval, flags) }
1455 .ok()
1456 .into_device_result("Present")?;
1457
1458 Ok(())
1459 }
1460
1461 unsafe fn get_timestamp_period(&self) -> f32 {
1462 let frequency = unsafe { self.raw.GetTimestampFrequency() }.expect("GetTimestampFrequency");
1463 (1_000_000_000.0 / frequency as f64) as f32
1464 }
1465 }