Debian Codegraph @

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

raw
1 use alloc::{
2 borrow::Cow,
3 string::{String, ToString as _},
4 sync::Arc,
5 vec::Vec,
6 };
7 use core::{ffi, num::NonZeroU32, ptr, time::Duration};
8 use std::time::Instant;
9
10 use bytemuck::TransparentWrapper;
11 use parking_lot::Mutex;
12 use windows::{
13 core::Interface as _,
14 Win32::{
15 Foundation,
16 Graphics::{Direct3D12, Dxgi},
17 System::Threading,
18 },
19 };
20
21 use super::{conv, descriptor, D3D12Lib};
22 use crate::{
23 auxil::{
24 self,
25 dxgi::{name::ObjectExt, result::HResult},
26 },
27 dx12::{
28 borrow_optional_interface_temporarily, shader_compilation, suballocation,
29 DynamicStorageBufferOffsets, Event,
30 },
31 AccelerationStructureEntries, TlasInstance,
32 };
33
34 // this has to match Naga's HLSL backend, and also needs to be null-terminated
35 const NAGA_LOCATION_SEMANTIC: &[u8] = c"LOC".to_bytes();
36
37 impl super::Device {
38 #[allow(clippy::too_many_arguments)]
39 pub(super) fn new(
40 adapter: auxil::dxgi::factory::DxgiAdapter,
41 raw: Direct3D12::ID3D12Device,
42 present_queue: Direct3D12::ID3D12CommandQueue,
43 features: wgt::Features,
44 limits: &wgt::Limits,
45 memory_hints: &wgt::MemoryHints,
46 private_caps: super::PrivateCapabilities,
47 library: &Arc<D3D12Lib>,
48 memory_budget_thresholds: wgt::MemoryBudgetThresholds,
49 dxc_container: Option<Arc<shader_compilation::DxcContainer>>,
50 ) -> Result<Self, crate::DeviceError> {
51 if private_caps
52 .instance_flags
53 .contains(wgt::InstanceFlags::VALIDATION)
54 {
55 auxil::dxgi::exception::register_exception_handler();
56 }
57
58 let mem_allocator =
59 suballocation::Allocator::new(&raw, memory_hints, memory_budget_thresholds)?;
60
61 let idle_fence: Direct3D12::ID3D12Fence = unsafe {
62 profiling::scope!("ID3D12Device::CreateFence");
63 raw.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_NONE)
64 }
65 .into_device_result("Idle fence creation")?;
66
67 let raw_desc = Direct3D12::D3D12_RESOURCE_DESC {
68 Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER,
69 Alignment: 0,
70 Width: super::ZERO_BUFFER_SIZE,
71 Height: 1,
72 DepthOrArraySize: 1,
73 MipLevels: 1,
74 Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
75 SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
76 Count: 1,
77 Quality: 0,
78 },
79 Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
80 Flags: Direct3D12::D3D12_RESOURCE_FLAG_NONE,
81 };
82
83 let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
84 Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
85 CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
86 MemoryPoolPreference: match private_caps.memory_architecture {
87 super::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0,
88 super::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1,
89 },
90 CreationNodeMask: 0,
91 VisibleNodeMask: 0,
92 };
93
94 profiling::scope!("Zero Buffer Allocation");
95 let mut zero_buffer = None::<Direct3D12::ID3D12Resource>;
96 unsafe {
97 raw.CreateCommittedResource(
98 &heap_properties,
99 Direct3D12::D3D12_HEAP_FLAG_NONE,
100 &raw_desc,
101 Direct3D12::D3D12_RESOURCE_STATE_COMMON,
102 None,
103 &mut zero_buffer,
104 )
105 }
106 .into_device_result("Zero buffer creation")?;
107
108 let zero_buffer = zero_buffer.ok_or(crate::DeviceError::Unexpected)?;
109
110 // Note: without `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`
111 // this resource is zeroed by default.
112
113 // maximum number of CBV/SRV/UAV descriptors in heap for Tier 1
114 let capacity_views = limits.max_non_sampler_bindings as u64;
115
116 let shared = super::DeviceShared {
117 adapter,
118 zero_buffer,
119 cmd_signatures: super::CommandSignatures {
120 draw: Self::create_command_signature(
121 &raw,
122 None,
123 size_of::<wgt::DrawIndirectArgs>(),
124 &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
125 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW,
126 ..Default::default()
127 }],
128 0,
129 )?,
130 draw_indexed: Self::create_command_signature(
131 &raw,
132 None,
133 size_of::<wgt::DrawIndexedIndirectArgs>(),
134 &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
135 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED,
136 ..Default::default()
137 }],
138 0,
139 )?,
140 dispatch: Self::create_command_signature(
141 &raw,
142 None,
143 size_of::<wgt::DispatchIndirectArgs>(),
144 &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
145 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH,
146 ..Default::default()
147 }],
148 0,
149 )?,
150 },
151 heap_views: descriptor::GeneralHeap::new(
152 &raw,
153 Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
154 capacity_views,
155 )?,
156 sampler_heap: super::sampler::SamplerHeap::new(&raw, &private_caps)?,
157 private_caps,
158 };
159
160 let mut rtv_pool =
161 descriptor::CpuPool::new(raw.clone(), Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
162 let null_rtv_handle = rtv_pool.alloc_handle()?;
163 // A null pResource is used to initialize a null descriptor,
164 // which guarantees D3D11-like null binding behavior (reading 0s, writes are discarded)
165 unsafe {
166 raw.CreateRenderTargetView(
167 None,
168 Some(&Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC {
169 Format: Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
170 ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2D,
171 Anonymous: Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC_0 {
172 Texture2D: Direct3D12::D3D12_TEX2D_RTV {
173 MipSlice: 0,
174 PlaneSlice: 0,
175 },
176 },
177 }),
178 null_rtv_handle.raw,
179 )
180 };
181
182 Ok(super::Device {
183 raw: raw.clone(),
184 present_queue,
185 idler: super::Idler {
186 fence: idle_fence,
187 event: Event::create(false, false)?,
188 },
189 features,
190 shared: Arc::new(shared),
191 rtv_pool: Arc::new(Mutex::new(rtv_pool)),
192 dsv_pool: Mutex::new(descriptor::CpuPool::new(
193 raw.clone(),
194 Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
195 )),
196 srv_uav_pool: Mutex::new(descriptor::CpuPool::new(
197 raw.clone(),
198 Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
199 )),
200 library: Arc::clone(library),
201 #[cfg(feature = "renderdoc")]
202 render_doc: Default::default(),
203 null_rtv_handle,
204 mem_allocator,
205 dxc_container,
206 counters: Default::default(),
207 })
208 }
209
210 fn create_command_signature(
211 raw: &Direct3D12::ID3D12Device,
212 root_signature: Option<&Direct3D12::ID3D12RootSignature>,
213 byte_stride: usize,
214 arguments: &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC],
215 node_mask: u32,
216 ) -> Result<Direct3D12::ID3D12CommandSignature, crate::DeviceError> {
217 let mut signature = None;
218 unsafe {
219 raw.CreateCommandSignature(
220 &Direct3D12::D3D12_COMMAND_SIGNATURE_DESC {
221 ByteStride: byte_stride as u32,
222 NumArgumentDescs: arguments.len() as u32,
223 pArgumentDescs: arguments.as_ptr(),
224 NodeMask: node_mask,
225 },
226 root_signature,
227 &mut signature,
228 )
229 }
230 .into_device_result("Command signature creation")?;
231 signature.ok_or(crate::DeviceError::Unexpected)
232 }
233
234 // Blocks until the dedicated present queue is finished with all of its work.
235 //
236 // Once this method completes, the surface is able to be resized or deleted.
237 pub(super) unsafe fn wait_for_present_queue_idle(&self) -> Result<(), crate::DeviceError> {
238 let cur_value = unsafe { self.idler.fence.GetCompletedValue() };
239 if cur_value == !0 {
240 return Err(crate::DeviceError::Lost);
241 }
242
243 let value = cur_value + 1;
244 unsafe { self.present_queue.Signal(&self.idler.fence, value) }
245 .into_device_result("Signal")?;
246 let hr = unsafe {
247 self.idler
248 .fence
249 .SetEventOnCompletion(value, self.idler.event.0)
250 };
251 hr.into_device_result("Set event")?;
252 unsafe { Threading::WaitForSingleObject(self.idler.event.0, Threading::INFINITE) };
253 Ok(())
254 }
255
256 /// When generating the vertex shader, the fragment stage must be passed if it exists!
257 /// Otherwise, the generated HLSL may be incorrect since the fragment shader inputs are
258 /// allowed to be a subset of the vertex outputs.
259 fn load_shader(
260 &self,
261 stage: &crate::ProgrammableStage<super::ShaderModule>,
262 layout: &super::PipelineLayout,
263 naga_stage: naga::ShaderStage,
264 fragment_stage: Option<&crate::ProgrammableStage<super::ShaderModule>>,
265 ) -> Result<super::CompiledShader, crate::PipelineError> {
266 use naga::back::hlsl;
267
268 let frag_ep = fragment_stage
269 .map(|fs_stage| {
270 hlsl::FragmentEntryPoint::new(&fs_stage.module.naga.module, fs_stage.entry_point)
271 .ok_or(crate::PipelineError::EntryPoint(
272 naga::ShaderStage::Fragment,
273 ))
274 })
275 .transpose()?;
276
277 let stage_bit = auxil::map_naga_stage(naga_stage);
278
279 let (module, info) = naga::back::pipeline_constants::process_overrides(
280 &stage.module.naga.module,
281 &stage.module.naga.info,
282 stage.constants,
283 )
284 .map_err(|e| crate::PipelineError::PipelineConstants(stage_bit, format!("HLSL: {e:?}")))?;
285
286 let needs_temp_options = stage.zero_initialize_workgroup_memory
287 != layout.naga_options.zero_initialize_workgroup_memory
288 || stage.module.runtime_checks.bounds_checks != layout.naga_options.restrict_indexing
289 || stage.module.runtime_checks.force_loop_bounding
290 != layout.naga_options.force_loop_bounding;
291 let mut temp_options;
292 let naga_options = if needs_temp_options {
293 temp_options = layout.naga_options.clone();
294 temp_options.zero_initialize_workgroup_memory = stage.zero_initialize_workgroup_memory;
295 temp_options.restrict_indexing = stage.module.runtime_checks.bounds_checks;
296 temp_options.force_loop_bounding = stage.module.runtime_checks.force_loop_bounding;
297 &temp_options
298 } else {
299 &layout.naga_options
300 };
301
302 let pipeline_options = hlsl::PipelineOptions {
303 entry_point: Some((naga_stage, stage.entry_point.to_string())),
304 };
305
306 //TODO: reuse the writer
307 let mut source = String::new();
308 let mut writer = hlsl::Writer::new(&mut source, naga_options, &pipeline_options);
309 let reflection_info = {
310 profiling::scope!("naga::back::hlsl::write");
311 writer
312 .write(&module, &info, frag_ep.as_ref())
313 .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("HLSL: {e:?}")))?
314 };
315
316 let full_stage = format!(
317 "{}_{}",
318 naga_stage.to_hlsl_str(),
319 naga_options.shader_model.to_str()
320 );
321
322 let raw_ep = reflection_info.entry_point_names[0]
323 .as_ref()
324 .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{e}")))?;
325
326 let source_name = stage.module.raw_name.as_deref();
327
328 // Compile with DXC if available, otherwise fall back to FXC
329 let result = if let Some(ref dxc_container) = self.dxc_container {
330 shader_compilation::compile_dxc(
331 self,
332 &source,
333 source_name,
334 raw_ep,
335 stage_bit,
336 &full_stage,
337 dxc_container,
338 )
339 } else {
340 shader_compilation::compile_fxc(
341 self,
342 &source,
343 source_name,
344 raw_ep,
345 stage_bit,
346 &full_stage,
347 )
348 };
349
350 let log_level = if result.is_ok() {
351 log::Level::Info
352 } else {
353 log::Level::Error
354 };
355
356 log::log!(
357 log_level,
358 "Naga generated shader for {:?} at {:?}:\n{}",
359 raw_ep,
360 naga_stage,
361 source
362 );
363 result
364 }
365
366 pub fn raw_device(&self) -> &Direct3D12::ID3D12Device {
367 &self.raw
368 }
369
370 pub fn raw_queue(&self) -> &Direct3D12::ID3D12CommandQueue {
371 &self.present_queue
372 }
373
374 pub unsafe fn texture_from_raw(
375 resource: Direct3D12::ID3D12Resource,
376 format: wgt::TextureFormat,
377 dimension: wgt::TextureDimension,
378 size: wgt::Extent3d,
379 mip_level_count: u32,
380 sample_count: u32,
381 ) -> super::Texture {
382 super::Texture {
383 resource,
384 format,
385 dimension,
386 size,
387 mip_level_count,
388 sample_count,
389 allocation: suballocation::Allocation::none(
390 suballocation::AllocationType::Texture,
391 format.theoretical_memory_footprint(size),
392 ),
393 }
394 }
395
396 pub unsafe fn buffer_from_raw(
397 resource: Direct3D12::ID3D12Resource,
398 size: wgt::BufferAddress,
399 ) -> super::Buffer {
400 super::Buffer {
401 resource,
402 size,
403 allocation: suballocation::Allocation::none(
404 suballocation::AllocationType::Buffer,
405 size,
406 ),
407 }
408 }
409 }
410
411 impl crate::Device for super::Device {
412 type A = super::Api;
413
414 unsafe fn create_buffer(
415 &self,
416 desc: &crate::BufferDescriptor,
417 ) -> Result<super::Buffer, crate::DeviceError> {
418 let mut desc = desc.clone();
419
420 if desc.usage.contains(wgt::BufferUses::UNIFORM) {
421 desc.size = desc
422 .size
423 .next_multiple_of(Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT.into())
424 }
425
426 let (resource, allocation) =
427 suballocation::DeviceAllocationContext::from(self).create_buffer(&desc)?;
428
429 self.counters.buffers.add(1);
430
431 Ok(super::Buffer {
432 resource,
433 size: desc.size,
434 allocation,
435 })
436 }
437
438 unsafe fn destroy_buffer(&self, buffer: super::Buffer) {
439 suballocation::DeviceAllocationContext::from(self)
440 .free_resource(buffer.resource, buffer.allocation);
441
442 self.counters.buffers.sub(1);
443 }
444
445 unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) {
446 self.counters.buffers.add(1);
447 }
448
449 unsafe fn map_buffer(
450 &self,
451 buffer: &super::Buffer,
452 range: crate::MemoryRange,
453 ) -> Result<crate::BufferMapping, crate::DeviceError> {
454 let mut ptr = ptr::null_mut();
455 // TODO: 0 for subresource should be fine here until map and unmap buffer is subresource aware?
456 unsafe { buffer.resource.Map(0, None, Some(&mut ptr)) }.into_device_result("Map buffer")?;
457
458 Ok(crate::BufferMapping {
459 ptr: ptr::NonNull::new(unsafe { ptr.offset(range.start as isize).cast::<u8>() })
460 .unwrap(),
461 //TODO: double-check this. Documentation is a bit misleading -
462 // it implies that Map/Unmap is needed to invalidate/flush memory.
463 is_coherent: true,
464 })
465 }
466
467 unsafe fn unmap_buffer(&self, buffer: &super::Buffer) {
468 unsafe { buffer.resource.Unmap(0, None) };
469 }
470
471 unsafe fn flush_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
472 unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {}
473
474 unsafe fn create_texture(
475 &self,
476 desc: &crate::TextureDescriptor,
477 ) -> Result<super::Texture, crate::DeviceError> {
478 let raw_desc = Direct3D12::D3D12_RESOURCE_DESC {
479 Dimension: conv::map_texture_dimension(desc.dimension),
480 Alignment: 0,
481 Width: desc.size.width as u64,
482 Height: desc.size.height,
483 DepthOrArraySize: desc.size.depth_or_array_layers as u16,
484 MipLevels: desc.mip_level_count as u16,
485 Format: auxil::dxgi::conv::map_texture_format_for_resource(
486 desc.format,
487 desc.usage,
488 !desc.view_formats.is_empty(),
489 self.shared
490 .private_caps
491 .casting_fully_typed_format_supported,
492 ),
493 SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
494 Count: desc.sample_count,
495 Quality: 0,
496 },
497 Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_UNKNOWN,
498 Flags: conv::map_texture_usage_to_resource_flags(desc.usage),
499 };
500
501 let (resource, allocation) =
502 suballocation::DeviceAllocationContext::from(self).create_texture(desc, raw_desc)?;
503
504 self.counters.textures.add(1);
505
506 Ok(super::Texture {
507 resource,
508 format: desc.format,
509 dimension: desc.dimension,
510 size: desc.size,
511 mip_level_count: desc.mip_level_count,
512 sample_count: desc.sample_count,
513 allocation,
514 })
515 }
516
517 unsafe fn destroy_texture(&self, texture: super::Texture) {
518 suballocation::DeviceAllocationContext::from(self)
519 .free_resource(texture.resource, texture.allocation);
520
521 self.counters.textures.sub(1);
522 }
523
524 unsafe fn add_raw_texture(&self, _texture: &super::Texture) {
525 self.counters.textures.add(1);
526 }
527
528 unsafe fn create_texture_view(
529 &self,
530 texture: &super::Texture,
531 desc: &crate::TextureViewDescriptor,
532 ) -> Result<super::TextureView, crate::DeviceError> {
533 let view_desc = desc.to_internal(texture);
534
535 self.counters.texture_views.add(1);
536
537 Ok(super::TextureView {
538 raw_format: view_desc.rtv_dsv_format,
539 aspects: view_desc.aspects,
540 dimension: desc.dimension,
541 texture: texture.resource.clone(),
542 subresource_index: texture.calc_subresource(
543 desc.range.base_mip_level,
544 desc.range.base_array_layer,
545 0,
546 ),
547 mip_slice: desc.range.base_mip_level,
548 handle_srv: if desc.usage.intersects(wgt::TextureUses::RESOURCE) {
549 match unsafe { view_desc.to_srv() } {
550 Some(raw_desc) => {
551 let handle = self.srv_uav_pool.lock().alloc_handle()?;
552 unsafe {
553 self.raw.CreateShaderResourceView(
554 &texture.resource,
555 Some(&raw_desc),
556 handle.raw,
557 )
558 };
559 Some(handle)
560 }
561 None => None,
562 }
563 } else {
564 None
565 },
566 handle_uav: if desc.usage.intersects(
567 wgt::TextureUses::STORAGE_READ_ONLY
568 | wgt::TextureUses::STORAGE_WRITE_ONLY
569 | wgt::TextureUses::STORAGE_READ_WRITE,
570 ) {
571 match unsafe { view_desc.to_uav() } {
572 Some(raw_desc) => {
573 let handle = self.srv_uav_pool.lock().alloc_handle()?;
574 unsafe {
575 self.raw.CreateUnorderedAccessView(
576 &texture.resource,
577 None,
578 Some(&raw_desc),
579 handle.raw,
580 );
581 }
582 Some(handle)
583 }
584 None => None,
585 }
586 } else {
587 None
588 },
589 handle_rtv: if desc.usage.intersects(wgt::TextureUses::COLOR_TARGET)
590 && desc.dimension != wgt::TextureViewDimension::D3
591 // 3D RTVs must be created in the render pass
592 {
593 let raw_desc = unsafe { view_desc.to_rtv() };
594 let handle = self.rtv_pool.lock().alloc_handle()?;
595 unsafe {
596 self.raw
597 .CreateRenderTargetView(&texture.resource, Some(&raw_desc), handle.raw)
598 };
599 Some(handle)
600 } else {
601 None
602 },
603 handle_dsv_ro: if desc.usage.intersects(wgt::TextureUses::DEPTH_STENCIL_READ) {
604 let raw_desc = unsafe { view_desc.to_dsv(true) };
605 let handle = self.dsv_pool.lock().alloc_handle()?;
606 unsafe {
607 self.raw
608 .CreateDepthStencilView(&texture.resource, Some(&raw_desc), handle.raw)
609 };
610 Some(handle)
611 } else {
612 None
613 },
614 handle_dsv_rw: if desc.usage.intersects(wgt::TextureUses::DEPTH_STENCIL_WRITE) {
615 let raw_desc = unsafe { view_desc.to_dsv(false) };
616 let handle = self.dsv_pool.lock().alloc_handle()?;
617 unsafe {
618 self.raw
619 .CreateDepthStencilView(&texture.resource, Some(&raw_desc), handle.raw)
620 };
621 Some(handle)
622 } else {
623 None
624 },
625 })
626 }
627
628 unsafe fn destroy_texture_view(&self, view: super::TextureView) {
629 if view.handle_srv.is_some() || view.handle_uav.is_some() {
630 let mut pool = self.srv_uav_pool.lock();
631 if let Some(handle) = view.handle_srv {
632 pool.free_handle(handle);
633 }
634 if let Some(handle) = view.handle_uav {
635 pool.free_handle(handle);
636 }
637 }
638 if let Some(handle) = view.handle_rtv {
639 self.rtv_pool.lock().free_handle(handle);
640 }
641 if view.handle_dsv_ro.is_some() || view.handle_dsv_rw.is_some() {
642 let mut pool = self.dsv_pool.lock();
643 if let Some(handle) = view.handle_dsv_ro {
644 pool.free_handle(handle);
645 }
646 if let Some(handle) = view.handle_dsv_rw {
647 pool.free_handle(handle);
648 }
649 }
650
651 self.counters.texture_views.sub(1);
652 }
653
654 unsafe fn create_sampler(
655 &self,
656 desc: &crate::SamplerDescriptor,
657 ) -> Result<super::Sampler, crate::DeviceError> {
658 let reduction = match desc.compare {
659 Some(_) => Direct3D12::D3D12_FILTER_REDUCTION_TYPE_COMPARISON,
660 None => Direct3D12::D3D12_FILTER_REDUCTION_TYPE_STANDARD,
661 };
662 let mut filter = Direct3D12::D3D12_FILTER(
663 (conv::map_filter_mode(desc.min_filter).0 << Direct3D12::D3D12_MIN_FILTER_SHIFT)
664 | (conv::map_filter_mode(desc.mag_filter).0 << Direct3D12::D3D12_MAG_FILTER_SHIFT)
665 | (conv::map_filter_mode(desc.mipmap_filter).0
666 << Direct3D12::D3D12_MIP_FILTER_SHIFT)
667 | (reduction.0 << Direct3D12::D3D12_FILTER_REDUCTION_TYPE_SHIFT),
668 );
669
670 if desc.anisotropy_clamp != 1 {
671 filter.0 |= Direct3D12::D3D12_FILTER_ANISOTROPIC.0;
672 };
673
674 let border_color = conv::map_border_color(desc.border_color);
675
676 let raw_desc = Direct3D12::D3D12_SAMPLER_DESC {
677 Filter: filter,
678 AddressU: conv::map_address_mode(desc.address_modes[0]),
679 AddressV: conv::map_address_mode(desc.address_modes[1]),
680 AddressW: conv::map_address_mode(desc.address_modes[2]),
681 MipLODBias: 0f32,
682 MaxAnisotropy: desc.anisotropy_clamp as u32,
683
684 ComparisonFunc: conv::map_comparison(
685 desc.compare.unwrap_or(wgt::CompareFunction::Always),
686 ),
687 BorderColor: border_color,
688 MinLOD: desc.lod_clamp.start,
689 MaxLOD: desc.lod_clamp.end,
690 };
691
692 let index = self
693 .shared
694 .sampler_heap
695 .create_sampler(&self.raw, raw_desc)?;
696
697 self.counters.samplers.add(1);
698
699 Ok(super::Sampler {
700 index,
701 desc: raw_desc,
702 })
703 }
704
705 unsafe fn destroy_sampler(&self, sampler: super::Sampler) {
706 self.shared
707 .sampler_heap
708 .destroy_sampler(sampler.desc, sampler.index);
709 self.counters.samplers.sub(1);
710 }
711
712 unsafe fn create_command_encoder(
713 &self,
714 desc: &crate::CommandEncoderDescriptor<super::Queue>,
715 ) -> Result<super::CommandEncoder, crate::DeviceError> {
716 let allocator: Direct3D12::ID3D12CommandAllocator = unsafe {
717 self.raw
718 .CreateCommandAllocator(Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT)
719 }
720 .into_device_result("Command allocator creation")?;
721
722 if let Some(label) = desc.label {
723 allocator.set_name(label)?;
724 }
725
726 self.counters.command_encoders.add(1);
727
728 Ok(super::CommandEncoder {
729 allocator,
730 device: self.raw.clone(),
731 shared: Arc::clone(&self.shared),
732 mem_allocator: self.mem_allocator.clone(),
733 rtv_pool: Arc::clone(&self.rtv_pool),
734 temp_rtv_handles: Vec::new(),
735 null_rtv_handle: self.null_rtv_handle,
736 list: None,
737 free_lists: Vec::new(),
738 pass: super::PassState::new(),
739 temp: super::Temp::default(),
740 end_of_pass_timer_query: None,
741 counters: Arc::clone(&self.counters),
742 })
743 }
744
745 unsafe fn create_bind_group_layout(
746 &self,
747 desc: &crate::BindGroupLayoutDescriptor,
748 ) -> Result<super::BindGroupLayout, crate::DeviceError> {
749 let mut num_views = 0;
750 let mut has_sampler_in_group = false;
751 for entry in desc.entries.iter() {
752 let count = entry.count.map_or(1, NonZeroU32::get);
753 match entry.ty {
754 wgt::BindingType::Buffer {
755 ty: wgt::BufferBindingType::Uniform,
756 has_dynamic_offset: true,
757 ..
758 } => {}
759 wgt::BindingType::Buffer { .. }
760 | wgt::BindingType::Texture { .. }
761 | wgt::BindingType::StorageTexture { .. }
762 | wgt::BindingType::AccelerationStructure { .. } => num_views += count,
763 wgt::BindingType::Sampler { .. } => has_sampler_in_group = true,
764 }
765 }
766
767 if has_sampler_in_group {
768 num_views += 1;
769 }
770
771 self.counters.bind_group_layouts.add(1);
772
773 Ok(super::BindGroupLayout {
774 entries: desc.entries.to_vec(),
775 cpu_heap_views: if num_views != 0 {
776 let heap = descriptor::CpuHeap::new(
777 &self.raw,
778 Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
779 num_views,
780 )?;
781 Some(heap)
782 } else {
783 None
784 },
785 copy_counts: vec![1; num_views as usize],
786 })
787 }
788
789 unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {
790 self.counters.bind_group_layouts.sub(1);
791 }
792
793 unsafe fn create_pipeline_layout(
794 &self,
795 desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>,
796 ) -> Result<super::PipelineLayout, crate::DeviceError> {
797 use naga::back::hlsl;
798 // Pipeline layouts are implemented as RootSignature for D3D12.
799 //
800 // Push Constants are implemented as root constants.
801 //
802 // Each bind group layout will be one table entry of the root signature.
803 // We have the additional restriction that SRV/CBV/UAV and samplers need to be
804 // separated, so each set layout will actually occupy up to 2 entries!
805 // SRV/CBV/UAV tables are added to the signature first, then Sampler tables,
806 // and finally dynamic uniform descriptors.
807 //
808 // Uniform buffers with dynamic offsets are implemented as root descriptors.
809 // This is easier than trying to patch up the offset on the shader side.
810 //
811 // Storage buffers with dynamic offsets are part of a descriptor table and
812 // the dynamic offsets are passed via root constants.
813 //
814 // Root signature layout:
815 // Root Constants: Parameter=0, Space=0
816 // ...
817 // (bind group [0]) - Space=0
818 // View descriptor table, if any
819 // Sampler buffer descriptor table, if any
820 // Root descriptors (for dynamic offset buffers)
821 // (bind group [1]) - Space=0
822 // ...
823 // (bind group [2]) - Space=0
824 // Special constant buffer: Space=0
825 // Sampler descriptor tables: Space=0
826 // SamplerState Array: Space=0, Register=0-2047
827 // SamplerComparisonState Array: Space=0, Register=2048-4095
828
829 //TODO: put lower bind group indices further down the root signature. See:
830 // https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html#binding-model
831 // Currently impossible because wgpu-core only re-binds the descriptor sets based
832 // on Vulkan-like layout compatibility rules.
833
834 let mut binding_map = hlsl::BindingMap::default();
835 let mut sampler_buffer_binding_map = hlsl::SamplerIndexBufferBindingMap::default();
836 let mut bind_cbv = hlsl::BindTarget::default();
837 let mut bind_srv = hlsl::BindTarget::default();
838 let mut bind_uav = hlsl::BindTarget::default();
839 let mut parameters = Vec::new();
840 let mut push_constants_target = None;
841 let mut root_constant_info = None;
842
843 let mut pc_start = u32::MAX;
844 let mut pc_end = u32::MIN;
845
846 for pc in desc.push_constant_ranges.iter() {
847 pc_start = pc_start.min(pc.range.start);
848 pc_end = pc_end.max(pc.range.end);
849 }
850
851 if pc_start != u32::MAX && pc_end != u32::MIN {
852 let parameter_index = parameters.len();
853 let size = (pc_end - pc_start) / 4;
854 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
855 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
856 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
857 Constants: Direct3D12::D3D12_ROOT_CONSTANTS {
858 ShaderRegister: bind_cbv.register,
859 RegisterSpace: bind_cbv.space as u32,
860 Num32BitValues: size,
861 },
862 },
863 ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL,
864 });
865 let binding = bind_cbv;
866 bind_cbv.register += 1;
867 root_constant_info = Some(super::RootConstantInfo {
868 root_index: parameter_index as u32,
869 range: (pc_start / 4)..(pc_end / 4),
870 });
871 push_constants_target = Some(binding);
872
873 bind_cbv.space += 1;
874 }
875
876 let mut dynamic_storage_buffer_offsets_targets = alloc::collections::BTreeMap::new();
877 let mut total_dynamic_storage_buffers = 0;
878
879 // Collect the whole number of bindings we will create upfront.
880 // It allows us to preallocate enough storage to avoid reallocation,
881 // which could cause invalid pointers.
882 let mut total_non_dynamic_entries = 0_usize;
883 let mut sampler_in_any_bind_group = false;
884 for bgl in desc.bind_group_layouts {
885 let mut sampler_in_bind_group = false;
886
887 for entry in &bgl.entries {
888 match entry.ty {
889 wgt::BindingType::Buffer {
890 ty: wgt::BufferBindingType::Uniform,
891 has_dynamic_offset: true,
892 ..
893 } => {}
894 wgt::BindingType::Sampler(_) => sampler_in_bind_group = true,
895 _ => total_non_dynamic_entries += 1,
896 }
897 }
898
899 if sampler_in_bind_group {
900 // One for the sampler buffer
901 total_non_dynamic_entries += 1;
902 sampler_in_any_bind_group = true;
903 }
904 }
905
906 if sampler_in_any_bind_group {
907 // Two for the sampler arrays themselves
908 total_non_dynamic_entries += 2;
909 }
910
911 let mut ranges = Vec::with_capacity(total_non_dynamic_entries);
912
913 let mut bind_group_infos =
914 arrayvec::ArrayVec::<super::BindGroupInfo, { crate::MAX_BIND_GROUPS }>::default();
915 for (index, bgl) in desc.bind_group_layouts.iter().enumerate() {
916 let mut info = super::BindGroupInfo {
917 tables: super::TableTypes::empty(),
918 base_root_index: parameters.len() as u32,
919 dynamic_storage_buffer_offsets: None,
920 };
921
922 let mut visibility_view_static = wgt::ShaderStages::empty();
923 let mut visibility_view_dynamic_uniform = wgt::ShaderStages::empty();
924 let mut visibility_view_dynamic_storage = wgt::ShaderStages::empty();
925 for entry in bgl.entries.iter() {
926 match entry.ty {
927 wgt::BindingType::Sampler { .. } => {
928 visibility_view_static |= wgt::ShaderStages::all()
929 }
930 wgt::BindingType::Buffer {
931 ty: wgt::BufferBindingType::Uniform,
932 has_dynamic_offset: true,
933 ..
934 } => visibility_view_dynamic_uniform |= entry.visibility,
935 wgt::BindingType::Buffer {
936 ty: wgt::BufferBindingType::Storage { .. },
937 has_dynamic_offset: true,
938 ..
939 } => visibility_view_dynamic_storage |= entry.visibility,
940 _ => visibility_view_static |= entry.visibility,
941 }
942 }
943
944 let mut dynamic_storage_buffers = 0;
945
946 // SRV/CBV/UAV descriptor tables
947 let range_base = ranges.len();
948 for entry in bgl.entries.iter() {
949 let (range_ty, has_dynamic_offset) = match entry.ty {
950 wgt::BindingType::Buffer {
951 ty,
952 has_dynamic_offset: true,
953 ..
954 } => match ty {
955 wgt::BufferBindingType::Uniform => continue,
956 wgt::BufferBindingType::Storage { .. } => {
957 (conv::map_binding_type(&entry.ty), true)
958 }
959 },
960 ref other => (conv::map_binding_type(other), false),
961 };
962 let bt = match range_ty {
963 Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV => &mut bind_cbv,
964 Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV => &mut bind_srv,
965 Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV => &mut bind_uav,
966 Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER => continue,
967 _ => todo!(),
968 };
969
970 let binding_array_size = entry.count.map(NonZeroU32::get);
971
972 let dynamic_storage_buffer_offsets_index = if has_dynamic_offset {
973 debug_assert!(
974 binding_array_size.is_none(),
975 "binding arrays and dynamic buffers are mutually exclusive"
976 );
977 let ret = Some(dynamic_storage_buffers);
978 dynamic_storage_buffers += 1;
979 ret
980 } else {
981 None
982 };
983
984 binding_map.insert(
985 naga::ResourceBinding {
986 group: index as u32,
987 binding: entry.binding,
988 },
989 hlsl::BindTarget {
990 binding_array_size,
991 dynamic_storage_buffer_offsets_index,
992 ..*bt
993 },
994 );
995 ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE {
996 RangeType: range_ty,
997 NumDescriptors: entry.count.map_or(1, |count| count.get()),
998 BaseShaderRegister: bt.register,
999 RegisterSpace: bt.space as u32,
1000 OffsetInDescriptorsFromTableStart:
1001 Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
1002 });
1003 bt.register += entry.count.map(NonZeroU32::get).unwrap_or(1);
1004 }
1005
1006 let mut sampler_index_within_bind_group = 0;
1007 for entry in bgl.entries.iter() {
1008 if let wgt::BindingType::Sampler(_) = entry.ty {
1009 binding_map.insert(
1010 naga::ResourceBinding {
1011 group: index as u32,
1012 binding: entry.binding,
1013 },
1014 hlsl::BindTarget {
1015 // Naga does not use the space field for samplers
1016 space: 255,
1017 register: sampler_index_within_bind_group,
1018 binding_array_size: None,
1019 dynamic_storage_buffer_offsets_index: None,
1020 restrict_indexing: false,
1021 },
1022 );
1023 sampler_index_within_bind_group += 1;
1024 }
1025 }
1026
1027 if sampler_index_within_bind_group != 0 {
1028 sampler_buffer_binding_map.insert(
1029 hlsl::SamplerIndexBufferKey {
1030 group: index as u32,
1031 },
1032 bind_srv,
1033 );
1034 ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE {
1035 RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
1036 NumDescriptors: 1,
1037 BaseShaderRegister: bind_srv.register,
1038 RegisterSpace: bind_srv.space as u32,
1039 OffsetInDescriptorsFromTableStart:
1040 Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND,
1041 });
1042 bind_srv.register += 1;
1043 }
1044
1045 if ranges.len() > range_base {
1046 let range = &ranges[range_base..];
1047 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
1048 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
1049 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
1050 DescriptorTable: Direct3D12::D3D12_ROOT_DESCRIPTOR_TABLE {
1051 NumDescriptorRanges: range.len() as u32,
1052 pDescriptorRanges: range.as_ptr(),
1053 },
1054 },
1055 ShaderVisibility: conv::map_visibility(visibility_view_static),
1056 });
1057 info.tables |= super::TableTypes::SRV_CBV_UAV;
1058 }
1059
1060 // Root descriptors for dynamic uniform buffers
1061 let dynamic_buffers_visibility = conv::map_visibility(visibility_view_dynamic_uniform);
1062 for entry in bgl.entries.iter() {
1063 match entry.ty {
1064 wgt::BindingType::Buffer {
1065 ty: wgt::BufferBindingType::Uniform,
1066 has_dynamic_offset: true,
1067 ..
1068 } => {}
1069 _ => continue,
1070 };
1071
1072 binding_map.insert(
1073 naga::ResourceBinding {
1074 group: index as u32,
1075 binding: entry.binding,
1076 },
1077 hlsl::BindTarget {
1078 binding_array_size: entry.count.map(NonZeroU32::get),
1079 restrict_indexing: true,
1080 ..bind_cbv
1081 },
1082 );
1083
1084 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
1085 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_CBV,
1086 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
1087 Descriptor: Direct3D12::D3D12_ROOT_DESCRIPTOR {
1088 ShaderRegister: bind_cbv.register,
1089 RegisterSpace: bind_cbv.space as u32,
1090 },
1091 },
1092 ShaderVisibility: dynamic_buffers_visibility,
1093 });
1094
1095 bind_cbv.register += entry.count.map_or(1, NonZeroU32::get);
1096 }
1097
1098 // Root constants for (offsets of) dynamic storage buffers
1099 if dynamic_storage_buffers > 0 {
1100 let parameter_index = parameters.len();
1101
1102 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
1103 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
1104 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
1105 Constants: Direct3D12::D3D12_ROOT_CONSTANTS {
1106 ShaderRegister: bind_cbv.register,
1107 RegisterSpace: bind_cbv.space as u32,
1108 Num32BitValues: dynamic_storage_buffers,
1109 },
1110 },
1111 ShaderVisibility: conv::map_visibility(visibility_view_dynamic_storage),
1112 });
1113
1114 let binding = hlsl::OffsetsBindTarget {
1115 space: bind_cbv.space,
1116 register: bind_cbv.register,
1117 size: dynamic_storage_buffers,
1118 };
1119
1120 bind_cbv.register += 1;
1121
1122 dynamic_storage_buffer_offsets_targets.insert(index as u32, binding);
1123 info.dynamic_storage_buffer_offsets = Some(DynamicStorageBufferOffsets {
1124 root_index: parameter_index as u32,
1125 range: total_dynamic_storage_buffers as usize
1126 ..total_dynamic_storage_buffers as usize + dynamic_storage_buffers as usize,
1127 });
1128 total_dynamic_storage_buffers += dynamic_storage_buffers;
1129 }
1130
1131 bind_group_infos.push(info);
1132 }
1133
1134 let sampler_heap_target = hlsl::SamplerHeapBindTargets {
1135 standard_samplers: hlsl::BindTarget {
1136 space: 0,
1137 register: 0,
1138 binding_array_size: None,
1139 dynamic_storage_buffer_offsets_index: None,
1140 restrict_indexing: false,
1141 },
1142 comparison_samplers: hlsl::BindTarget {
1143 space: 0,
1144 register: 2048,
1145 binding_array_size: None,
1146 dynamic_storage_buffer_offsets_index: None,
1147 restrict_indexing: false,
1148 },
1149 };
1150
1151 let mut sampler_heap_root_index = None;
1152 if sampler_in_any_bind_group {
1153 // Sampler descriptor tables
1154 //
1155 // We bind two sampler ranges pointing to the same descriptor heap, using two different register ranges.
1156 //
1157 // We bind them as normal samplers in registers 0-2047 and comparison samplers in registers 2048-4095.
1158 // Tier 2 hardware guarantees that the type of sampler only needs to match if the sampler is actually
1159 // accessed in the shader. As such, we can bind the same array of samplers to both registers.
1160 //
1161 // We do this because HLSL does not allow you to alias registers at all.
1162 let range_base = ranges.len();
1163 // Standard samplers, registers 0-2047
1164 ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE {
1165 RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
1166 NumDescriptors: 2048,
1167 BaseShaderRegister: 0,
1168 RegisterSpace: 0,
1169 OffsetInDescriptorsFromTableStart: 0,
1170 });
1171 // Comparison samplers, registers 2048-4095
1172 ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE {
1173 RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
1174 NumDescriptors: 2048,
1175 BaseShaderRegister: 2048,
1176 RegisterSpace: 0,
1177 OffsetInDescriptorsFromTableStart: 0,
1178 });
1179
1180 let range = &ranges[range_base..];
1181 sampler_heap_root_index = Some(parameters.len() as super::RootIndex);
1182 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
1183 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
1184 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
1185 DescriptorTable: Direct3D12::D3D12_ROOT_DESCRIPTOR_TABLE {
1186 NumDescriptorRanges: range.len() as u32,
1187 pDescriptorRanges: range.as_ptr(),
1188 },
1189 },
1190 ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL,
1191 });
1192 }
1193
1194 // Ensure that we didn't reallocate!
1195 debug_assert_eq!(ranges.len(), total_non_dynamic_entries);
1196
1197 let (special_constants_root_index, special_constants_binding) = if desc.flags.intersects(
1198 crate::PipelineLayoutFlags::FIRST_VERTEX_INSTANCE
1199 | crate::PipelineLayoutFlags::NUM_WORK_GROUPS,
1200 ) {
1201 let parameter_index = parameters.len();
1202 parameters.push(Direct3D12::D3D12_ROOT_PARAMETER {
1203 ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS,
1204 Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 {
1205 Constants: Direct3D12::D3D12_ROOT_CONSTANTS {
1206 ShaderRegister: bind_cbv.register,
1207 RegisterSpace: bind_cbv.space as u32,
1208 Num32BitValues: 3, // 0 = first_vertex, 1 = first_instance, 2 = other
1209 },
1210 },
1211 ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL, // really needed for VS and CS only,
1212 });
1213 let binding = bind_cbv;
1214 bind_cbv.register += 1;
1215 (Some(parameter_index as u32), Some(binding))
1216 } else {
1217 (None, None)
1218 };
1219
1220 let blob = self.library.serialize_root_signature(
1221 Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_0,
1222 &parameters,
1223 &[],
1224 Direct3D12::D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT,
1225 )?;
1226
1227 let raw = unsafe {
1228 self.raw
1229 .CreateRootSignature::<Direct3D12::ID3D12RootSignature>(0, blob.as_slice())
1230 }
1231 .into_device_result("Root signature creation")?;
1232
1233 let special_constants = if let Some(root_index) = special_constants_root_index {
1234 let cmd_signatures = if desc
1235 .flags
1236 .contains(crate::PipelineLayoutFlags::INDIRECT_BUILTIN_UPDATE)
1237 {
1238 let constant_indirect_argument_desc = Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
1239 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT,
1240 Anonymous: Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC_0 {
1241 Constant: Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC_0_1 {
1242 RootParameterIndex: root_index,
1243 DestOffsetIn32BitValues: 0,
1244 Num32BitValuesToSet: 3,
1245 },
1246 },
1247 };
1248 let special_constant_buffer_args_len = {
1249 // Hack: construct a dummy value of the special constants buffer value we need to
1250 // fill, and calculate the size of each member.
1251 let super::RootElement::SpecialConstantBuffer {
1252 first_vertex,
1253 first_instance,
1254 other,
1255 } = (super::RootElement::SpecialConstantBuffer {
1256 first_vertex: 0,
1257 first_instance: 0,
1258 other: 0,
1259 })
1260 else {
1261 unreachable!();
1262 };
1263 size_of_val(&first_vertex) + size_of_val(&first_instance) + size_of_val(&other)
1264 };
1265 Some(super::CommandSignatures {
1266 draw: Self::create_command_signature(
1267 &self.raw,
1268 Some(&raw),
1269 special_constant_buffer_args_len + size_of::<wgt::DrawIndirectArgs>(),
1270 &[
1271 constant_indirect_argument_desc,
1272 Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
1273 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW,
1274 ..Default::default()
1275 },
1276 ],
1277 0,
1278 )?,
1279 draw_indexed: Self::create_command_signature(
1280 &self.raw,
1281 Some(&raw),
1282 special_constant_buffer_args_len
1283 + size_of::<wgt::DrawIndexedIndirectArgs>(),
1284 &[
1285 constant_indirect_argument_desc,
1286 Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
1287 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED,
1288 ..Default::default()
1289 },
1290 ],
1291 0,
1292 )?,
1293 dispatch: Self::create_command_signature(
1294 &self.raw,
1295 Some(&raw),
1296 special_constant_buffer_args_len + size_of::<wgt::DispatchIndirectArgs>(),
1297 &[
1298 constant_indirect_argument_desc,
1299 Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC {
1300 Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH,
1301 ..Default::default()
1302 },
1303 ],
1304 0,
1305 )?,
1306 })
1307 } else {
1308 None
1309 };
1310 Some(super::PipelineLayoutSpecialConstants {
1311 root_index,
1312 indirect_cmd_signatures: cmd_signatures,
1313 })
1314 } else {
1315 None
1316 };
1317
1318 if let Some(label) = desc.label {
1319 raw.set_name(label)?;
1320 }
1321
1322 self.counters.pipeline_layouts.add(1);
1323
1324 Ok(super::PipelineLayout {
1325 shared: super::PipelineLayoutShared {
1326 signature: Some(raw),
1327 total_root_elements: parameters.len() as super::RootIndex,
1328 special_constants,
1329 root_constant_info,
1330 sampler_heap_root_index,
1331 },
1332 bind_group_infos,
1333 naga_options: hlsl::Options {
1334 shader_model: self.shared.private_caps.shader_model,
1335 binding_map,
1336 fake_missing_bindings: false,
1337 special_constants_binding,
1338 push_constants_target,
1339 dynamic_storage_buffer_offsets_targets,
1340 zero_initialize_workgroup_memory: true,
1341 restrict_indexing: true,
1342 sampler_heap_target,
1343 sampler_buffer_binding_map,
1344 force_loop_bounding: true,
1345 },
1346 })
1347 }
1348
1349 unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) {
1350 self.counters.pipeline_layouts.sub(1);
1351 }
1352
1353 unsafe fn create_bind_group(
1354 &self,
1355 desc: &crate::BindGroupDescriptor<
1356 super::BindGroupLayout,
1357 super::Buffer,
1358 super::Sampler,
1359 super::TextureView,
1360 super::AccelerationStructure,
1361 >,
1362 ) -> Result<super::BindGroup, crate::DeviceError> {
1363 let mut cpu_views = desc
1364 .layout
1365 .cpu_heap_views
1366 .as_ref()
1367 .map(|cpu_heap| cpu_heap.inner.lock());
1368 if let Some(ref mut inner) = cpu_views {
1369 inner.stage.clear();
1370 }
1371 let mut dynamic_buffers = Vec::new();
1372
1373 let layout_and_entry_iter = desc.entries.iter().map(|entry| {
1374 let layout = desc
1375 .layout
1376 .entries
1377 .iter()
1378 .find(|layout_entry| layout_entry.binding == entry.binding)
1379 .expect("internal error: no layout entry found with binding slot");
1380 (layout, entry)
1381 });
1382 let mut sampler_indexes: Vec<super::sampler::SamplerIndex> = Vec::new();
1383
1384 for (layout, entry) in layout_and_entry_iter {
1385 match layout.ty {
1386 wgt::BindingType::Buffer {
1387 ty,
1388 has_dynamic_offset,
1389 ..
1390 } => {
1391 let start = entry.resource_index as usize;
1392 let end = start + entry.count as usize;
1393 for data in &desc.buffers[start..end] {
1394 let gpu_address = data.resolve_address();
1395 let mut size = data.resolve_size() as u32;
1396
1397 if has_dynamic_offset {
1398 match ty {
1399 wgt::BufferBindingType::Uniform => {
1400 dynamic_buffers.push(super::DynamicBuffer::Uniform(
1401 Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
1402 ptr: data.resolve_address(),
1403 },
1404 ));
1405 continue;
1406 }
1407 wgt::BufferBindingType::Storage { .. } => {
1408 size = (data.buffer.size - data.offset) as u32;
1409 dynamic_buffers.push(super::DynamicBuffer::Storage);
1410 }
1411 }
1412 }
1413
1414 let inner = cpu_views.as_mut().unwrap();
1415 let cpu_index = inner.stage.len() as u32;
1416 let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index);
1417 match ty {
1418 wgt::BufferBindingType::Uniform => {
1419 let size_mask =
1420 Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1;
1421 let raw_desc = Direct3D12::D3D12_CONSTANT_BUFFER_VIEW_DESC {
1422 BufferLocation: gpu_address,
1423 SizeInBytes: ((size - 1) | size_mask) + 1,
1424 };
1425 unsafe {
1426 self.raw.CreateConstantBufferView(Some(&raw_desc), handle)
1427 };
1428 }
1429 wgt::BufferBindingType::Storage { read_only: true } => {
1430 let raw_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC {
1431 Format: Dxgi::Common::DXGI_FORMAT_R32_TYPELESS,
1432 Shader4ComponentMapping:
1433 Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
1434 ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_BUFFER,
1435 Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
1436 Buffer: Direct3D12::D3D12_BUFFER_SRV {
1437 FirstElement: data.offset / 4,
1438 NumElements: size / 4,
1439 StructureByteStride: 0,
1440 Flags: Direct3D12::D3D12_BUFFER_SRV_FLAG_RAW,
1441 },
1442 },
1443 };
1444 unsafe {
1445 self.raw.CreateShaderResourceView(
1446 &data.buffer.resource,
1447 Some(&raw_desc),
1448 handle,
1449 )
1450 };
1451 }
1452 wgt::BufferBindingType::Storage { read_only: false } => {
1453 let raw_desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
1454 Format: Dxgi::Common::DXGI_FORMAT_R32_TYPELESS,
1455 ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_BUFFER,
1456 Anonymous: Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
1457 Buffer: Direct3D12::D3D12_BUFFER_UAV {
1458 FirstElement: data.offset / 4,
1459 NumElements: size / 4,
1460 StructureByteStride: 0,
1461 CounterOffsetInBytes: 0,
1462 Flags: Direct3D12::D3D12_BUFFER_UAV_FLAG_RAW,
1463 },
1464 },
1465 };
1466 unsafe {
1467 self.raw.CreateUnorderedAccessView(
1468 &data.buffer.resource,
1469 None,
1470 Some(&raw_desc),
1471 handle,
1472 )
1473 };
1474 }
1475 }
1476 inner.stage.push(handle);
1477 }
1478 }
1479 wgt::BindingType::Texture { .. } => {
1480 let start = entry.resource_index as usize;
1481 let end = start + entry.count as usize;
1482 for data in &desc.textures[start..end] {
1483 let handle = data.view.handle_srv.unwrap();
1484 cpu_views.as_mut().unwrap().stage.push(handle.raw);
1485 }
1486 }
1487 wgt::BindingType::StorageTexture { .. } => {
1488 let start = entry.resource_index as usize;
1489 let end = start + entry.count as usize;
1490 for data in &desc.textures[start..end] {
1491 let handle = data.view.handle_uav.unwrap();
1492 cpu_views.as_mut().unwrap().stage.push(handle.raw);
1493 }
1494 }
1495 wgt::BindingType::Sampler { .. } => {
1496 let start = entry.resource_index as usize;
1497 let end = start + entry.count as usize;
1498 for &data in &desc.samplers[start..end] {
1499 sampler_indexes.push(data.index);
1500 }
1501 }
1502 wgt::BindingType::AccelerationStructure { .. } => {
1503 let start = entry.resource_index as usize;
1504 let end = start + entry.count as usize;
1505 for data in &desc.acceleration_structures[start..end] {
1506 let inner = cpu_views.as_mut().unwrap();
1507 let cpu_index = inner.stage.len() as u32;
1508 let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index);
1509 let raw_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC {
1510 Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
1511 Shader4ComponentMapping:
1512 Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
1513 ViewDimension:
1514 Direct3D12::D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE,
1515 Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
1516 RaytracingAccelerationStructure:
1517 Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV {
1518 Location: unsafe { data.resource.GetGPUVirtualAddress() },
1519 },
1520 },
1521 };
1522 unsafe {
1523 self.raw
1524 .CreateShaderResourceView(None, Some(&raw_desc), handle)
1525 };
1526 inner.stage.push(handle);
1527 }
1528 }
1529 }
1530 }
1531
1532 let sampler_index_buffer = if !sampler_indexes.is_empty() {
1533 let buffer_size = (sampler_indexes.len() * size_of::<u32>()) as u64;
1534
1535 let label = if let Some(label) = desc.label {
1536 Cow::Owned(format!("{} (Internal Sampler Index Buffer)", label))
1537 } else {
1538 Cow::Borrowed("Internal Sampler Index Buffer")
1539 };
1540
1541 let buffer_desc = crate::BufferDescriptor {
1542 label: Some(&label),
1543 size: buffer_size,
1544 usage: wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::MAP_WRITE,
1545 // D3D12 backend doesn't care about the memory flags
1546 memory_flags: crate::MemoryFlags::empty(),
1547 };
1548
1549 let (buffer, allocation) =
1550 suballocation::DeviceAllocationContext::from(self).create_buffer(&buffer_desc)?;
1551
1552 let mut mapping = ptr::null_mut::<ffi::c_void>();
1553 unsafe { buffer.Map(0, None, Some(&mut mapping)) }.into_device_result("Map")?;
1554
1555 assert!(!mapping.is_null());
1556 assert_eq!(mapping as usize % 4, 0);
1557
1558 unsafe {
1559 ptr::copy_nonoverlapping(
1560 sampler_indexes.as_ptr(),
1561 mapping.cast(),
1562 sampler_indexes.len(),
1563 )
1564 };
1565
1566 // The unmapping is not needed, as all memory is coherent in d3d12, but lets be nice to our address space.
1567 unsafe { buffer.Unmap(0, None) };
1568
1569 let srv_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC {
1570 Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
1571 ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_BUFFER,
1572 Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
1573 Buffer: Direct3D12::D3D12_BUFFER_SRV {
1574 FirstElement: 0,
1575 NumElements: sampler_indexes.len() as u32,
1576 StructureByteStride: 4,
1577 Flags: Direct3D12::D3D12_BUFFER_SRV_FLAG_NONE,
1578 },
1579 },
1580 Shader4ComponentMapping: Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
1581 };
1582
1583 let inner = cpu_views.as_mut().unwrap();
1584 let cpu_index = inner.stage.len() as u32;
1585 let srv = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index);
1586
1587 unsafe {
1588 self.raw
1589 .CreateShaderResourceView(&buffer, Some(&srv_desc), srv)
1590 };
1591
1592 cpu_views.as_mut().unwrap().stage.push(srv);
1593
1594 Some(super::SamplerIndexBuffer { buffer, allocation })
1595 } else {
1596 None
1597 };
1598
1599 let handle_views = match cpu_views {
1600 Some(inner) => {
1601 let dual = unsafe {
1602 descriptor::upload(
1603 &self.raw,
1604 &inner,
1605 &self.shared.heap_views,
1606 &desc.layout.copy_counts,
1607 )
1608 }?;
1609 Some(dual)
1610 }
1611 None => None,
1612 };
1613
1614 self.counters.bind_groups.add(1);
1615
1616 Ok(super::BindGroup {
1617 handle_views,
1618 sampler_index_buffer,
1619 dynamic_buffers,
1620 })
1621 }
1622
1623 unsafe fn destroy_bind_group(&self, group: super::BindGroup) {
1624 if let Some(dual) = group.handle_views {
1625 self.shared.heap_views.free_slice(dual);
1626 }
1627
1628 if let Some(sampler_buffer) = group.sampler_index_buffer {
1629 suballocation::DeviceAllocationContext::from(self)
1630 .free_resource(sampler_buffer.buffer, sampler_buffer.allocation);
1631 }
1632
1633 self.counters.bind_groups.sub(1);
1634 }
1635
1636 unsafe fn create_shader_module(
1637 &self,
1638 desc: &crate::ShaderModuleDescriptor,
1639 shader: crate::ShaderInput,
1640 ) -> Result<super::ShaderModule, crate::ShaderError> {
1641 self.counters.shader_modules.add(1);
1642
1643 let raw_name = desc
1644 .label
1645 .and_then(|label| alloc::ffi::CString::new(label).ok());
1646 match shader {
1647 crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule {
1648 naga,
1649 raw_name,
1650 runtime_checks: desc.runtime_checks,
1651 }),
1652 crate::ShaderInput::SpirV(_) => {
1653 panic!("SPIRV_SHADER_PASSTHROUGH is not enabled for this backend")
1654 }
1655 crate::ShaderInput::Msl { .. } => {
1656 panic!("MSL_SHADER_PASSTHROUGH is not enabled for this backend")
1657 }
1658 }
1659 }
1660 unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) {
1661 self.counters.shader_modules.sub(1);
1662 // just drop
1663 }
1664
1665 unsafe fn create_render_pipeline(
1666 &self,
1667 desc: &crate::RenderPipelineDescriptor<
1668 super::PipelineLayout,
1669 super::ShaderModule,
1670 super::PipelineCache,
1671 >,
1672 ) -> Result<super::RenderPipeline, crate::PipelineError> {
1673 let (topology_class, topology) = conv::map_topology(desc.primitive.topology);
1674 let mut shader_stages = wgt::ShaderStages::VERTEX;
1675
1676 let blob_vs = self.load_shader(
1677 &desc.vertex_stage,
1678 desc.layout,
1679 naga::ShaderStage::Vertex,
1680 desc.fragment_stage.as_ref(),
1681 )?;
1682 let blob_fs = match desc.fragment_stage {
1683 Some(ref stage) => {
1684 shader_stages |= wgt::ShaderStages::FRAGMENT;
1685 Some(self.load_shader(stage, desc.layout, naga::ShaderStage::Fragment, None)?)
1686 }
1687 None => None,
1688 };
1689
1690 let mut vertex_strides = [None; crate::MAX_VERTEX_BUFFERS];
1691 let mut input_element_descs = Vec::new();
1692 for (i, (stride, vbuf)) in vertex_strides
1693 .iter_mut()
1694 .zip(desc.vertex_buffers)
1695 .enumerate()
1696 {
1697 *stride = NonZeroU32::new(vbuf.array_stride as u32);
1698 let (slot_class, step_rate) = match vbuf.step_mode {
1699 wgt::VertexStepMode::Vertex => {
1700 (Direct3D12::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0)
1701 }
1702 wgt::VertexStepMode::Instance => {
1703 (Direct3D12::D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1)
1704 }
1705 };
1706 for attribute in vbuf.attributes {
1707 input_element_descs.push(Direct3D12::D3D12_INPUT_ELEMENT_DESC {
1708 SemanticName: windows::core::PCSTR(NAGA_LOCATION_SEMANTIC.as_ptr()),
1709 SemanticIndex: attribute.shader_location,
1710 Format: auxil::dxgi::conv::map_vertex_format(attribute.format),
1711 InputSlot: i as u32,
1712 AlignedByteOffset: attribute.offset as u32,
1713 InputSlotClass: slot_class,
1714 InstanceDataStepRate: step_rate,
1715 });
1716 }
1717 }
1718
1719 let mut rtv_formats = [Dxgi::Common::DXGI_FORMAT_UNKNOWN;
1720 Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize];
1721 for (rtv_format, ct) in rtv_formats.iter_mut().zip(desc.color_targets) {
1722 if let Some(ct) = ct.as_ref() {
1723 *rtv_format = auxil::dxgi::conv::map_texture_format(ct.format);
1724 }
1725 }
1726
1727 let bias = desc
1728 .depth_stencil
1729 .as_ref()
1730 .map(|ds| ds.bias)
1731 .unwrap_or_default();
1732
1733 let raw_rasterizer = Direct3D12::D3D12_RASTERIZER_DESC {
1734 FillMode: conv::map_polygon_mode(desc.primitive.polygon_mode),
1735 CullMode: match desc.primitive.cull_mode {
1736 None => Direct3D12::D3D12_CULL_MODE_NONE,
1737 Some(wgt::Face::Front) => Direct3D12::D3D12_CULL_MODE_FRONT,
1738 Some(wgt::Face::Back) => Direct3D12::D3D12_CULL_MODE_BACK,
1739 },
1740 FrontCounterClockwise: match desc.primitive.front_face {
1741 wgt::FrontFace::Cw => Foundation::FALSE,
1742 wgt::FrontFace::Ccw => Foundation::TRUE,
1743 },
1744 DepthBias: bias.constant,
1745 DepthBiasClamp: bias.clamp,
1746 SlopeScaledDepthBias: bias.slope_scale,
1747 DepthClipEnable: Foundation::BOOL::from(!desc.primitive.unclipped_depth),
1748 MultisampleEnable: Foundation::BOOL::from(desc.multisample.count > 1),
1749 ForcedSampleCount: 0,
1750 AntialiasedLineEnable: false.into(),
1751 ConservativeRaster: if desc.primitive.conservative {
1752 Direct3D12::D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
1753 } else {
1754 Direct3D12::D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF
1755 },
1756 };
1757
1758 let raw_desc = Direct3D12::D3D12_GRAPHICS_PIPELINE_STATE_DESC {
1759 pRootSignature: unsafe {
1760 borrow_optional_interface_temporarily(&desc.layout.shared.signature)
1761 },
1762 VS: blob_vs.create_native_shader(),
1763 PS: match &blob_fs {
1764 Some(shader) => shader.create_native_shader(),
1765 None => Direct3D12::D3D12_SHADER_BYTECODE::default(),
1766 },
1767 GS: Direct3D12::D3D12_SHADER_BYTECODE::default(),
1768 DS: Direct3D12::D3D12_SHADER_BYTECODE::default(),
1769 HS: Direct3D12::D3D12_SHADER_BYTECODE::default(),
1770 StreamOutput: Direct3D12::D3D12_STREAM_OUTPUT_DESC {
1771 pSODeclaration: ptr::null(),
1772 NumEntries: 0,
1773 pBufferStrides: ptr::null(),
1774 NumStrides: 0,
1775 RasterizedStream: 0,
1776 },
1777 BlendState: Direct3D12::D3D12_BLEND_DESC {
1778 AlphaToCoverageEnable: Foundation::BOOL::from(
1779 desc.multisample.alpha_to_coverage_enabled,
1780 ),
1781 IndependentBlendEnable: true.into(),
1782 RenderTarget: conv::map_render_targets(desc.color_targets),
1783 },
1784 SampleMask: desc.multisample.mask as u32,
1785 RasterizerState: raw_rasterizer,
1786 DepthStencilState: match desc.depth_stencil {
1787 Some(ref ds) => conv::map_depth_stencil(ds),
1788 None => Default::default(),
1789 },
1790 InputLayout: Direct3D12::D3D12_INPUT_LAYOUT_DESC {
1791 pInputElementDescs: if input_element_descs.is_empty() {
1792 ptr::null()
1793 } else {
1794 input_element_descs.as_ptr()
1795 },
1796 NumElements: input_element_descs.len() as u32,
1797 },
1798 IBStripCutValue: match desc.primitive.strip_index_format {
1799 Some(wgt::IndexFormat::Uint16) => {
1800 Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF
1801 }
1802 Some(wgt::IndexFormat::Uint32) => {
1803 Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF
1804 }
1805 None => Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED,
1806 },
1807 PrimitiveTopologyType: topology_class,
1808 NumRenderTargets: desc.color_targets.len() as u32,
1809 RTVFormats: rtv_formats,
1810 DSVFormat: desc
1811 .depth_stencil
1812 .as_ref()
1813 .map_or(Dxgi::Common::DXGI_FORMAT_UNKNOWN, |ds| {
1814 auxil::dxgi::conv::map_texture_format(ds.format)
1815 }),
1816 SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
1817 Count: desc.multisample.count,
1818 Quality: 0,
1819 },
1820 NodeMask: 0,
1821 CachedPSO: Direct3D12::D3D12_CACHED_PIPELINE_STATE {
1822 pCachedBlob: ptr::null(),
1823 CachedBlobSizeInBytes: 0,
1824 },
1825 Flags: Direct3D12::D3D12_PIPELINE_STATE_FLAG_NONE,
1826 };
1827
1828 let raw: Direct3D12::ID3D12PipelineState = {
1829 profiling::scope!("ID3D12Device::CreateGraphicsPipelineState");
1830 unsafe { self.raw.CreateGraphicsPipelineState(&raw_desc) }
1831 }
1832 .map_err(|err| crate::PipelineError::Linkage(shader_stages, err.to_string()))?;
1833
1834 unsafe { blob_vs.destroy() };
1835 if let Some(blob_fs) = blob_fs {
1836 unsafe { blob_fs.destroy() };
1837 };
1838
1839 if let Some(label) = desc.label {
1840 raw.set_name(label)?;
1841 }
1842
1843 self.counters.render_pipelines.add(1);
1844
1845 Ok(super::RenderPipeline {
1846 raw,
1847 layout: desc.layout.shared.clone(),
1848 topology,
1849 vertex_strides,
1850 })
1851 }
1852
1853 unsafe fn create_mesh_pipeline(
1854 &self,
1855 _desc: &crate::MeshPipelineDescriptor<
1856 <Self::A as crate::Api>::PipelineLayout,
1857 <Self::A as crate::Api>::ShaderModule,
1858 <Self::A as crate::Api>::PipelineCache,
1859 >,
1860 ) -> Result<<Self::A as crate::Api>::RenderPipeline, crate::PipelineError> {
1861 unreachable!()
1862 }
1863
1864 unsafe fn destroy_render_pipeline(&self, _pipeline: super::RenderPipeline) {
1865 self.counters.render_pipelines.sub(1);
1866 }
1867
1868 unsafe fn create_compute_pipeline(
1869 &self,
1870 desc: &crate::ComputePipelineDescriptor<
1871 super::PipelineLayout,
1872 super::ShaderModule,
1873 super::PipelineCache,
1874 >,
1875 ) -> Result<super::ComputePipeline, crate::PipelineError> {
1876 let blob_cs =
1877 self.load_shader(&desc.stage, desc.layout, naga::ShaderStage::Compute, None)?;
1878
1879 let pair = {
1880 profiling::scope!("ID3D12Device::CreateComputePipelineState");
1881 unsafe {
1882 self.raw.CreateComputePipelineState(
1883 &Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC {
1884 pRootSignature: borrow_optional_interface_temporarily(
1885 &desc.layout.shared.signature,
1886 ),
1887 CS: blob_cs.create_native_shader(),
1888 NodeMask: 0,
1889 CachedPSO: Direct3D12::D3D12_CACHED_PIPELINE_STATE::default(),
1890 Flags: Direct3D12::D3D12_PIPELINE_STATE_FLAG_NONE,
1891 },
1892 )
1893 }
1894 };
1895
1896 unsafe { blob_cs.destroy() };
1897
1898 let raw: Direct3D12::ID3D12PipelineState = pair.map_err(|err| {
1899 crate::PipelineError::Linkage(wgt::ShaderStages::COMPUTE, err.to_string())
1900 })?;
1901
1902 if let Some(label) = desc.label {
1903 raw.set_name(label)?;
1904 }
1905
1906 self.counters.compute_pipelines.add(1);
1907
1908 Ok(super::ComputePipeline {
1909 raw,
1910 layout: desc.layout.shared.clone(),
1911 })
1912 }
1913
1914 unsafe fn destroy_compute_pipeline(&self, _pipeline: super::ComputePipeline) {
1915 self.counters.compute_pipelines.sub(1);
1916 }
1917
1918 unsafe fn create_pipeline_cache(
1919 &self,
1920 _desc: &crate::PipelineCacheDescriptor<'_>,
1921 ) -> Result<super::PipelineCache, crate::PipelineCacheError> {
1922 Ok(super::PipelineCache)
1923 }
1924 unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {}
1925
1926 unsafe fn create_query_set(
1927 &self,
1928 desc: &wgt::QuerySetDescriptor<crate::Label>,
1929 ) -> Result<super::QuerySet, crate::DeviceError> {
1930 let (heap_ty, raw_ty) = match desc.ty {
1931 wgt::QueryType::Occlusion => (
1932 Direct3D12::D3D12_QUERY_HEAP_TYPE_OCCLUSION,
1933 Direct3D12::D3D12_QUERY_TYPE_BINARY_OCCLUSION,
1934 ),
1935 wgt::QueryType::PipelineStatistics(_) => (
1936 Direct3D12::D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS,
1937 Direct3D12::D3D12_QUERY_TYPE_PIPELINE_STATISTICS,
1938 ),
1939 wgt::QueryType::Timestamp => (
1940 Direct3D12::D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
1941 Direct3D12::D3D12_QUERY_TYPE_TIMESTAMP,
1942 ),
1943 };
1944
1945 if let Some(threshold) = self
1946 .mem_allocator
1947 .memory_budget_thresholds
1948 .for_resource_creation
1949 {
1950 let info = self
1951 .shared
1952 .adapter
1953 .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?;
1954
1955 // Assume each query is 256 bytes.
1956 // On an AMD W6800 with driver version 32.0.12030.9, occlusion and pipeline statistics are 256, timestamp is 8.
1957
1958 if info.CurrentUsage + desc.count as u64 * 256 >= info.Budget / 100 * threshold as u64 {
1959 return Err(crate::DeviceError::OutOfMemory);
1960 }
1961 }
1962
1963 let mut raw = None::<Direct3D12::ID3D12QueryHeap>;
1964 unsafe {
1965 self.raw.CreateQueryHeap(
1966 &Direct3D12::D3D12_QUERY_HEAP_DESC {
1967 Type: heap_ty,
1968 Count: desc.count,
1969 NodeMask: 0,
1970 },
1971 &mut raw,
1972 )
1973 }
1974 .into_device_result("Query heap creation")?;
1975
1976 let raw = raw.ok_or(crate::DeviceError::Unexpected)?;
1977
1978 if let Some(label) = desc.label {
1979 raw.set_name(label)?;
1980 }
1981
1982 self.counters.query_sets.add(1);
1983
1984 Ok(super::QuerySet { raw, raw_ty })
1985 }
1986
1987 unsafe fn destroy_query_set(&self, _set: super::QuerySet) {
1988 self.counters.query_sets.sub(1);
1989 }
1990
1991 unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> {
1992 let raw: Direct3D12::ID3D12Fence =
1993 unsafe { self.raw.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_SHARED) }
1994 .into_device_result("Fence creation")?;
1995
1996 self.counters.fences.add(1);
1997
1998 Ok(super::Fence { raw })
1999 }
2000 unsafe fn destroy_fence(&self, _fence: super::Fence) {
2001 self.counters.fences.sub(1);
2002 }
2003
2004 unsafe fn get_fence_value(
2005 &self,
2006 fence: &super::Fence,
2007 ) -> Result<crate::FenceValue, crate::DeviceError> {
2008 Ok(unsafe { fence.raw.GetCompletedValue() })
2009 }
2010 unsafe fn wait(
2011 &self,
2012 fence: &super::Fence,
2013 value: crate::FenceValue,
2014 timeout_ms: u32,
2015 ) -> Result<bool, crate::DeviceError> {
2016 let timeout_duration = Duration::from_millis(timeout_ms as u64);
2017
2018 // We first check if the fence has already reached the value we're waiting for.
2019 let mut fence_value = unsafe { fence.raw.GetCompletedValue() };
2020 if fence_value >= value {
2021 return Ok(true);
2022 }
2023
2024 unsafe { fence.raw.SetEventOnCompletion(value, self.idler.event.0) }
2025 .into_device_result("Set event")?;
2026
2027 let start_time = Instant::now();
2028
2029 // We need to loop to get correct behavior when timeouts are involved.
2030 //
2031 // wait(0):
2032 // - We set the event from the fence value 0.
2033 // - WaitForSingleObject times out, we return false.
2034 //
2035 // wait(1):
2036 // - We set the event from the fence value 1.
2037 // - WaitForSingleObject returns. However we do not know if the fence value is 0 or 1,
2038 // just that _something_ triggered the event. We check the fence value, and if it is
2039 // 1, we return true. Otherwise, we loop and wait again.
2040 loop {
2041 let elapsed = start_time.elapsed();
2042
2043 // We need to explicitly use checked_sub. Overflow with duration panics, and if the
2044 // timing works out just right, we can get a negative remaining wait duration.
2045 //
2046 // This happens when a previous iteration WaitForSingleObject succeeded with a previous fence value,
2047 // right before the timeout would have been hit.
2048 let remaining_wait_duration = match timeout_duration.checked_sub(elapsed) {
2049 Some(remaining) => remaining,
2050 None => {
2051 log::trace!("Timeout elapsed in between waits!");
2052 break Ok(false);
2053 }
2054 };
2055
2056 log::trace!(
2057 "Waiting for fence value {} for {:?}",
2058 value,
2059 remaining_wait_duration
2060 );
2061
2062 match unsafe {
2063 Threading::WaitForSingleObject(
2064 self.idler.event.0,
2065 remaining_wait_duration.as_millis().try_into().unwrap(),
2066 )
2067 } {
2068 Foundation::WAIT_OBJECT_0 => {}
2069 Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => {
2070 log::error!("Wait failed!");
2071 break Err(crate::DeviceError::Lost);
2072 }
2073 Foundation::WAIT_TIMEOUT => {
2074 log::trace!("Wait timed out!");
2075 break Ok(false);
2076 }
2077 other => {
2078 log::error!("Unexpected wait status: 0x{:?}", other);
2079 break Err(crate::DeviceError::Lost);
2080 }
2081 };
2082
2083 fence_value = unsafe { fence.raw.GetCompletedValue() };
2084 log::trace!("Wait complete! Fence actual value: {}", fence_value);
2085
2086 if fence_value >= value {
2087 break Ok(true);
2088 }
2089 }
2090 }
2091
2092 unsafe fn start_graphics_debugger_capture(&self) -> bool {
2093 #[cfg(feature = "renderdoc")]
2094 {
2095 unsafe {
2096 self.render_doc
2097 .start_frame_capture(self.raw.as_raw(), ptr::null_mut())
2098 }
2099 }
2100 #[cfg(not(feature = "renderdoc"))]
2101 false
2102 }
2103
2104 unsafe fn stop_graphics_debugger_capture(&self) {
2105 #[cfg(feature = "renderdoc")]
2106 unsafe {
2107 self.render_doc
2108 .end_frame_capture(self.raw.as_raw(), ptr::null_mut())
2109 }
2110 }
2111
2112 unsafe fn get_acceleration_structure_build_sizes<'a>(
2113 &self,
2114 desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>,
2115 ) -> crate::AccelerationStructureBuildSizes {
2116 let mut geometry_desc;
2117 let device5 = self.raw.cast::<Direct3D12::ID3D12Device5>().unwrap();
2118 let ty;
2119 let inputs0;
2120 let num_desc;
2121 match desc.entries {
2122 AccelerationStructureEntries::Instances(instances) => {
2123 ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL;
2124 inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 {
2125 InstanceDescs: 0,
2126 };
2127 num_desc = instances.count;
2128 }
2129 AccelerationStructureEntries::Triangles(triangles) => {
2130 geometry_desc = Vec::with_capacity(triangles.len());
2131 for triangle in triangles {
2132 let index_format = triangle
2133 .indices
2134 .as_ref()
2135 .map_or(Dxgi::Common::DXGI_FORMAT_UNKNOWN, |indices| {
2136 auxil::dxgi::conv::map_index_format(indices.format)
2137 });
2138 let index_count = triangle.indices.as_ref().map_or(0, |indices| indices.count);
2139
2140 let triangle_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC {
2141 // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device5-getraytracingaccelerationstructureprebuildinfo
2142 // It may not inspect/dereference any GPU virtual addresses, other than
2143 // to check to see if a pointer is NULL or not, such as the optional
2144 // transform in D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC, without
2145 // dereferencing it.
2146 //
2147 // This suggests we could pass a non-zero invalid address here if fetching the
2148 // real address has significant overhead, but we pass the real one to be on the
2149 // safe side for now.
2150 Transform3x4: if desc
2151 .flags
2152 .contains(wgt::AccelerationStructureFlags::USE_TRANSFORM)
2153 {
2154 unsafe {
2155 triangle
2156 .transform
2157 .as_ref()
2158 .unwrap()
2159 .buffer
2160 .resource
2161 .GetGPUVirtualAddress()
2162 }
2163 } else {
2164 0
2165 },
2166 IndexFormat: index_format,
2167 VertexFormat: auxil::dxgi::conv::map_vertex_format(triangle.vertex_format),
2168 IndexCount: index_count,
2169 VertexCount: triangle.vertex_count,
2170 IndexBuffer: 0,
2171 VertexBuffer: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE {
2172 StartAddress: 0,
2173 StrideInBytes: triangle.vertex_stride,
2174 },
2175 };
2176
2177 geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC {
2178 Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES,
2179 Flags: conv::map_acceleration_structure_geometry_flags(triangle.flags),
2180 Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 {
2181 Triangles: triangle_desc,
2182 },
2183 })
2184 }
2185 ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
2186 inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 {
2187 pGeometryDescs: geometry_desc.as_ptr(),
2188 };
2189 num_desc = geometry_desc.len() as u32;
2190 }
2191 AccelerationStructureEntries::AABBs(aabbs) => {
2192 geometry_desc = Vec::with_capacity(aabbs.len());
2193 for aabb in aabbs {
2194 let aabb_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_AABBS_DESC {
2195 AABBCount: aabb.count as u64,
2196 AABBs: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE {
2197 StartAddress: 0,
2198 StrideInBytes: aabb.stride,
2199 },
2200 };
2201 geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC {
2202 Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS,
2203 Flags: conv::map_acceleration_structure_geometry_flags(aabb.flags),
2204 Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 {
2205 AABBs: aabb_desc,
2206 },
2207 })
2208 }
2209 ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL;
2210 inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 {
2211 pGeometryDescs: geometry_desc.as_ptr(),
2212 };
2213 num_desc = geometry_desc.len() as u32;
2214 }
2215 };
2216 let acceleration_structure_inputs =
2217 Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS {
2218 Type: ty,
2219 Flags: conv::map_acceleration_structure_build_flags(desc.flags, None),
2220 NumDescs: num_desc,
2221 DescsLayout: Direct3D12::D3D12_ELEMENTS_LAYOUT_ARRAY,
2222 Anonymous: inputs0,
2223 };
2224 let mut info = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default();
2225 unsafe {
2226 device5.GetRaytracingAccelerationStructurePrebuildInfo(
2227 &acceleration_structure_inputs,
2228 &mut info,
2229 )
2230 };
2231 crate::AccelerationStructureBuildSizes {
2232 acceleration_structure_size: info.ResultDataMaxSizeInBytes,
2233 update_scratch_size: info.UpdateScratchDataSizeInBytes,
2234 build_scratch_size: info.ScratchDataSizeInBytes,
2235 }
2236 }
2237
2238 unsafe fn get_acceleration_structure_device_address(
2239 &self,
2240 acceleration_structure: &super::AccelerationStructure,
2241 ) -> wgt::BufferAddress {
2242 unsafe { acceleration_structure.resource.GetGPUVirtualAddress() }
2243 }
2244
2245 unsafe fn create_acceleration_structure(
2246 &self,
2247 desc: &crate::AccelerationStructureDescriptor,
2248 ) -> Result<super::AccelerationStructure, crate::DeviceError> {
2249 // Create a D3D12 resource as per-usual.
2250 let size = desc.size;
2251
2252 let raw_desc = Direct3D12::D3D12_RESOURCE_DESC {
2253 Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER,
2254 Alignment: 0,
2255 Width: size,
2256 Height: 1,
2257 DepthOrArraySize: 1,
2258 MipLevels: 1,
2259 Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
2260 SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
2261 Count: 1,
2262 Quality: 0,
2263 },
2264 Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
2265 // TODO: when moving to enhanced barriers use Direct3D12::D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE
2266 Flags: Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
2267 };
2268
2269 let (resource, allocation) = suballocation::DeviceAllocationContext::from(self)
2270 .create_acceleration_structure(desc, raw_desc)?;
2271
2272 // for some reason there is no counter for acceleration structures
2273
2274 Ok(super::AccelerationStructure {
2275 resource,
2276 allocation,
2277 })
2278 }
2279
2280 unsafe fn destroy_acceleration_structure(
2281 &self,
2282 acceleration_structure: super::AccelerationStructure,
2283 ) {
2284 suballocation::DeviceAllocationContext::from(self).free_resource(
2285 acceleration_structure.resource,
2286 acceleration_structure.allocation,
2287 );
2288 }
2289
2290 fn get_internal_counters(&self) -> wgt::HalCounters {
2291 self.counters.as_ref().clone()
2292 }
2293
2294 fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
2295 Some(self.mem_allocator.generate_report())
2296 }
2297
2298 fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> {
2299 const MAX_U24: u32 = (1u32 << 24u32) - 1u32;
2300 let temp = Direct3D12::D3D12_RAYTRACING_INSTANCE_DESC {
2301 Transform: instance.transform,
2302 _bitfield1: (instance.custom_data & MAX_U24) | (u32::from(instance.mask) << 24),
2303 _bitfield2: 0,
2304 AccelerationStructure: instance.blas_address,
2305 };
2306
2307 wgt::bytemuck_wrapper!(unsafe struct Desc(Direct3D12::D3D12_RAYTRACING_INSTANCE_DESC));
2308
2309 bytemuck::bytes_of(&Desc::wrap(temp)).to_vec()
2310 }
2311
2312 fn check_if_oom(&self) -> Result<(), crate::DeviceError> {
2313 let Some(threshold) = self.mem_allocator.memory_budget_thresholds.for_device_loss else {
2314 return Ok(());
2315 };
2316
2317 let info = self
2318 .shared
2319 .adapter
2320 .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?;
2321
2322 if info.CurrentUsage >= info.Budget / 100 * threshold as u64 {
2323 return Err(crate::DeviceError::OutOfMemory);
2324 }
2325
2326 if matches!(
2327 self.shared.private_caps.memory_architecture,
2328 super::MemoryArchitecture::NonUnified
2329 ) {
2330 let info = self
2331 .shared
2332 .adapter
2333 .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?;
2334
2335 if info.CurrentUsage >= info.Budget / 100 * threshold as u64 {
2336 return Err(crate::DeviceError::OutOfMemory);
2337 }
2338 }
2339
2340 Ok(())
2341 }
2342 }