Debian Codegraph @

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

raw
1 use alloc::vec::Vec;
2 use core::fmt;
3
4 use bit_set::BitSet;
5 use parking_lot::Mutex;
6 use range_alloc::RangeAllocator;
7 use windows::Win32::Graphics::Direct3D12;
8
9 use crate::auxil::dxgi::result::HResult as _;
10
11 const HEAP_SIZE_FIXED: usize = 64;
12
13 #[derive(Copy, Clone)]
14 pub(super) struct DualHandle {
15 cpu: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
16 pub gpu: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE,
17 /// How large the block allocated to this handle is.
18 count: u64,
19 }
20
21 impl fmt::Debug for DualHandle {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 f.debug_struct("DualHandle")
24 .field("cpu", &self.cpu.ptr)
25 .field("gpu", &self.gpu.ptr)
26 .field("count", &self.count)
27 .finish()
28 }
29 }
30
31 type DescriptorIndex = u64;
32
33 pub(super) struct GeneralHeap {
34 pub raw: Direct3D12::ID3D12DescriptorHeap,
35 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
36 handle_size: u64,
37 total_handles: u64,
38 start: DualHandle,
39 ranges: Mutex<RangeAllocator<DescriptorIndex>>,
40 }
41
42 impl GeneralHeap {
43 pub(super) fn new(
44 device: &Direct3D12::ID3D12Device,
45 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
46 total_handles: u64,
47 ) -> Result<Self, crate::DeviceError> {
48 let raw = {
49 profiling::scope!("ID3D12Device::CreateDescriptorHeap");
50 let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
51 Type: ty,
52 NumDescriptors: total_handles as u32,
53 Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
54 NodeMask: 0,
55 };
56 unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
57 .into_device_result("Descriptor heap creation")?
58 };
59
60 let start = DualHandle {
61 cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
62 gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
63 count: 0,
64 };
65
66 Ok(Self {
67 raw,
68 ty,
69 handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64,
70 total_handles,
71 start,
72 ranges: Mutex::new(RangeAllocator::new(0..total_handles)),
73 })
74 }
75
76 pub(super) fn at(&self, index: DescriptorIndex, count: u64) -> DualHandle {
77 assert!(index < self.total_handles);
78 DualHandle {
79 cpu: self.cpu_descriptor_at(index),
80 gpu: self.gpu_descriptor_at(index),
81 count,
82 }
83 }
84
85 fn cpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
86 Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
87 ptr: self.start.cpu.ptr + (self.handle_size * index) as usize,
88 }
89 }
90
91 fn gpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
92 Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
93 ptr: self.start.gpu.ptr + self.handle_size * index,
94 }
95 }
96
97 pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> {
98 let range = self.ranges.lock().allocate_range(count).map_err(|err| {
99 log::error!("Unable to allocate descriptors: {:?}", err);
100 crate::DeviceError::OutOfMemory
101 })?;
102 Ok(range.start)
103 }
104
105 /// Free handles previously given out by this `DescriptorHeapSlice`.
106 /// Do not use this with handles not given out by this `DescriptorHeapSlice`.
107 pub(crate) fn free_slice(&self, handle: DualHandle) {
108 let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size;
109 self.ranges.lock().free_range(start..start + handle.count);
110 }
111 }
112
113 /// Fixed-size free-list allocator for CPU descriptors.
114 struct FixedSizeHeap {
115 _raw: Direct3D12::ID3D12DescriptorHeap,
116 /// Bit flag representation of available handles in the heap.
117 ///
118 /// 0 - Occupied
119 /// 1 - free
120 availability: u64,
121 handle_size: usize,
122 start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
123 }
124
125 impl FixedSizeHeap {
126 fn new(
127 device: &Direct3D12::ID3D12Device,
128 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
129 ) -> Result<Self, crate::DeviceError> {
130 let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
131 Type: ty,
132 NumDescriptors: HEAP_SIZE_FIXED as u32,
133 Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
134 NodeMask: 0,
135 };
136 let heap =
137 unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
138 .into_device_result("Descriptor heap creation")?;
139
140 Ok(Self {
141 handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as usize,
142 availability: !0, // all free!
143 start: unsafe { heap.GetCPUDescriptorHandleForHeapStart() },
144 _raw: heap,
145 })
146 }
147
148 fn alloc_handle(
149 &mut self,
150 ) -> Result<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, crate::DeviceError> {
151 // Find first free slot.
152 let slot = self.availability.trailing_zeros() as usize;
153 if slot >= HEAP_SIZE_FIXED {
154 log::error!("Failed to allocate a handle form a fixed size heap");
155 return Err(crate::DeviceError::OutOfMemory);
156 }
157 // Set the slot as occupied.
158 self.availability ^= 1 << slot;
159
160 Ok(Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
161 ptr: self.start.ptr + self.handle_size * slot,
162 })
163 }
164
165 fn free_handle(&mut self, handle: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE) {
166 let slot = (handle.ptr - self.start.ptr) / self.handle_size;
167 assert!(slot < HEAP_SIZE_FIXED);
168 assert_eq!(self.availability & (1 << slot), 0);
169 self.availability ^= 1 << slot;
170 }
171
172 fn is_full(&self) -> bool {
173 self.availability == 0
174 }
175 }
176
177 #[derive(Clone, Copy)]
178 pub(super) struct Handle {
179 pub raw: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
180 heap_index: usize,
181 }
182
183 impl fmt::Debug for Handle {
184 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
185 fmt.debug_struct("Handle")
186 .field("ptr", &self.raw.ptr)
187 .field("heap_index", &self.heap_index)
188 .finish()
189 }
190 }
191
192 pub(super) struct CpuPool {
193 device: Direct3D12::ID3D12Device,
194 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
195 heaps: Vec<FixedSizeHeap>,
196 available_heap_indices: BitSet,
197 }
198
199 impl CpuPool {
200 pub(super) fn new(
201 device: Direct3D12::ID3D12Device,
202 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
203 ) -> Self {
204 Self {
205 device,
206 ty,
207 heaps: Vec::new(),
208 available_heap_indices: BitSet::new(),
209 }
210 }
211
212 pub(super) fn alloc_handle(&mut self) -> Result<Handle, crate::DeviceError> {
213 let heap_index = self
214 .available_heap_indices
215 .iter()
216 .next()
217 .unwrap_or(self.heaps.len());
218
219 // Allocate a new heap
220 if heap_index == self.heaps.len() {
221 self.heaps.push(FixedSizeHeap::new(&self.device, self.ty)?);
222 self.available_heap_indices.insert(heap_index);
223 }
224
225 let heap = &mut self.heaps[heap_index];
226 let handle = Handle {
227 raw: heap.alloc_handle()?,
228 heap_index,
229 };
230 if heap.is_full() {
231 self.available_heap_indices.remove(heap_index);
232 }
233
234 Ok(handle)
235 }
236
237 pub(super) fn free_handle(&mut self, handle: Handle) {
238 self.heaps[handle.heap_index].free_handle(handle.raw);
239 self.available_heap_indices.insert(handle.heap_index);
240 }
241 }
242
243 pub(super) struct CpuHeapInner {
244 pub _raw: Direct3D12::ID3D12DescriptorHeap,
245 pub stage: Vec<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE>,
246 }
247
248 pub(super) struct CpuHeap {
249 pub inner: Mutex<CpuHeapInner>,
250 start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
251 handle_size: u32,
252 total: u32,
253 }
254
255 unsafe impl Send for CpuHeap {}
256 unsafe impl Sync for CpuHeap {}
257
258 impl CpuHeap {
259 pub(super) fn new(
260 device: &Direct3D12::ID3D12Device,
261 ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
262 total: u32,
263 ) -> Result<Self, crate::DeviceError> {
264 let handle_size = unsafe { device.GetDescriptorHandleIncrementSize(ty) };
265 let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
266 Type: ty,
267 NumDescriptors: total,
268 Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
269 NodeMask: 0,
270 };
271 let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
272 .into_device_result("CPU descriptor heap creation")?;
273
274 let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() };
275
276 Ok(Self {
277 inner: Mutex::new(CpuHeapInner {
278 _raw: raw,
279 stage: Vec::new(),
280 }),
281 start,
282 handle_size,
283 total,
284 })
285 }
286
287 pub(super) fn at(&self, index: u32) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
288 debug_assert!(
289 index < self.total,
290 "Index ({index}) out of bounds {total}",
291 total = self.total
292 );
293 Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
294 ptr: self.start.ptr + (self.handle_size * index) as usize,
295 }
296 }
297 }
298
299 impl fmt::Debug for CpuHeap {
300 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301 f.debug_struct("CpuHeap")
302 .field("start", &self.start.ptr)
303 .field("handle_size", &self.handle_size)
304 .field("total", &self.total)
305 .finish()
306 }
307 }
308
309 pub(super) unsafe fn upload(
310 device: &Direct3D12::ID3D12Device,
311 src: &CpuHeapInner,
312 dst: &GeneralHeap,
313 dummy_copy_counts: &[u32],
314 ) -> Result<DualHandle, crate::DeviceError> {
315 let count = src.stage.len() as u32;
316 let index = dst.allocate_slice(count as u64)?;
317 unsafe {
318 device.CopyDescriptors(
319 1,
320 &dst.cpu_descriptor_at(index),
321 Some(&count),
322 count,
323 src.stage.as_ptr(),
324 Some(dummy_copy_counts.as_ptr()),
325 dst.ty,
326 )
327 };
328 Ok(dst.at(index, count as u64))
329 }