Debian Codegraph @

third_party/rust/gpu-allocator/examples/d3d12-buffer.rs

raw
1 //! Example showcasing [`winapi`] interop with [`gpu-allocator`] which is driven by the [`windows`] crate.
2 use winapi::{
3 shared::{dxgiformat, winerror},
4 um::{d3d12, d3dcommon},
5 Interface,
6 };
7
8 mod all_dxgi {
9 pub use winapi::shared::{dxgi1_3::*, dxgi1_6::*, dxgitype::*};
10 }
11
12 use gpu_allocator::{
13 d3d12::{
14 AllocationCreateDesc, Allocator, AllocatorCreateDesc, ID3D12DeviceVersion,
15 ResourceCategory, ToWinapi, ToWindows,
16 },
17 MemoryLocation,
18 };
19 use log::*;
20
21 fn create_d3d12_device(
22 dxgi_factory: *mut all_dxgi::IDXGIFactory6,
23 ) -> Option<*mut d3d12::ID3D12Device> {
24 for idx in 0.. {
25 let mut adapter4: *mut all_dxgi::IDXGIAdapter4 = std::ptr::null_mut();
26 let hr = unsafe {
27 dxgi_factory.as_ref().unwrap().EnumAdapters1(
28 idx,
29 <*mut *mut all_dxgi::IDXGIAdapter4>::cast(&mut adapter4),
30 )
31 };
32
33 if hr == winerror::DXGI_ERROR_NOT_FOUND {
34 break;
35 }
36
37 assert_eq!(hr, winerror::S_OK);
38
39 let mut desc = all_dxgi::DXGI_ADAPTER_DESC3::default();
40 let hr = unsafe { adapter4.as_ref().unwrap().GetDesc3(&mut desc) };
41 if hr != winerror::S_OK {
42 error!("Failed to get adapter description for adapter");
43 continue;
44 }
45
46 // Skip software adapters
47 if (desc.Flags & all_dxgi::DXGI_ADAPTER_FLAG3_SOFTWARE)
48 == all_dxgi::DXGI_ADAPTER_FLAG3_SOFTWARE
49 {
50 continue;
51 }
52
53 let feature_levels = [
54 (d3dcommon::D3D_FEATURE_LEVEL_11_0, "D3D_FEATURE_LEVEL_11_0"),
55 (d3dcommon::D3D_FEATURE_LEVEL_11_1, "D3D_FEATURE_LEVEL_11_1"),
56 (d3dcommon::D3D_FEATURE_LEVEL_12_0, "D3D_FEATURE_LEVEL_12_0"),
57 ];
58
59 let device =
60 feature_levels
61 .iter()
62 .rev()
63 .find_map(|&(feature_level, feature_level_name)| {
64 let mut device: *mut d3d12::ID3D12Device = std::ptr::null_mut();
65 let hr = unsafe {
66 d3d12::D3D12CreateDevice(
67 adapter4.cast(),
68 feature_level,
69 &d3d12::ID3D12Device::uuidof(),
70 <*mut *mut d3d12::ID3D12Device>::cast(&mut device),
71 )
72 };
73 match hr {
74 winerror::S_OK => {
75 info!("Using D3D12 feature level: {}.", feature_level_name);
76 Some(device)
77 }
78 winerror::E_NOINTERFACE => {
79 error!("ID3D12Device interface not supported.");
80 None
81 }
82 _ => {
83 info!(
84 "D3D12 feature level: {} not supported: {:x}",
85 feature_level_name, hr
86 );
87 None
88 }
89 }
90 });
91 if device.is_some() {
92 return device;
93 }
94 }
95
96 None
97 }
98
99 fn main() {
100 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("trace")).init();
101
102 let dxgi_factory = {
103 let mut dxgi_factory: *mut all_dxgi::IDXGIFactory6 = std::ptr::null_mut();
104 let hr = unsafe {
105 all_dxgi::CreateDXGIFactory2(
106 0,
107 &all_dxgi::IID_IDXGIFactory6,
108 <*mut *mut all_dxgi::IDXGIFactory6>::cast(&mut dxgi_factory),
109 )
110 };
111
112 assert_eq!(hr, winerror::S_OK, "Failed to create DXGI factory");
113 dxgi_factory
114 };
115
116 let device = create_d3d12_device(dxgi_factory).expect("Failed to create D3D12 device.");
117
118 // Setting up the allocator
119 let mut allocator = Allocator::new(&AllocatorCreateDesc {
120 device: ID3D12DeviceVersion::Device(device.as_windows().clone()),
121 debug_settings: Default::default(),
122 allocation_sizes: Default::default(),
123 })
124 .unwrap();
125
126 let device = unsafe { device.as_ref() }.unwrap();
127
128 // Test allocating Gpu Only memory
129 {
130 let test_buffer_desc = d3d12::D3D12_RESOURCE_DESC {
131 Dimension: d3d12::D3D12_RESOURCE_DIMENSION_BUFFER,
132 Alignment: d3d12::D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64,
133 Width: 512,
134 Height: 1,
135 DepthOrArraySize: 1,
136 MipLevels: 1,
137 Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
138 SampleDesc: all_dxgi::DXGI_SAMPLE_DESC {
139 Count: 1,
140 Quality: 0,
141 },
142 Layout: d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
143 Flags: d3d12::D3D12_RESOURCE_FLAG_NONE,
144 };
145
146 let allocation_desc = AllocationCreateDesc::from_winapi_d3d12_resource_desc(
147 device,
148 &test_buffer_desc,
149 "Test allocation (Gpu Only)",
150 MemoryLocation::GpuOnly,
151 );
152 let allocation = allocator.allocate(&allocation_desc).unwrap();
153
154 let mut resource: *mut d3d12::ID3D12Resource = std::ptr::null_mut();
155 let hr = unsafe {
156 device.CreatePlacedResource(
157 allocation.heap().as_winapi() as *mut _,
158 allocation.offset(),
159 &test_buffer_desc,
160 d3d12::D3D12_RESOURCE_STATE_COMMON,
161 std::ptr::null(),
162 &d3d12::IID_ID3D12Resource,
163 <*mut *mut d3d12::ID3D12Resource>::cast(&mut resource),
164 )
165 };
166 if hr != winerror::S_OK {
167 panic!("Failed to create placed resource.");
168 }
169
170 unsafe { resource.as_ref().unwrap().Release() };
171
172 allocator.free(allocation).unwrap();
173 info!("Allocation and deallocation of GpuOnly memory was successful.");
174 }
175
176 // Test allocating Cpu to Gpu memory
177 {
178 let test_buffer_desc = d3d12::D3D12_RESOURCE_DESC {
179 Dimension: d3d12::D3D12_RESOURCE_DIMENSION_BUFFER,
180 Alignment: d3d12::D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64,
181 Width: 512,
182 Height: 1,
183 DepthOrArraySize: 1,
184 MipLevels: 1,
185 Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
186 SampleDesc: all_dxgi::DXGI_SAMPLE_DESC {
187 Count: 1,
188 Quality: 0,
189 },
190 Layout: d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
191 Flags: d3d12::D3D12_RESOURCE_FLAG_NONE,
192 };
193
194 let alloc_info = unsafe { device.GetResourceAllocationInfo(0, 1, &test_buffer_desc) };
195
196 let allocation = allocator
197 .allocate(&AllocationCreateDesc {
198 name: "Test allocation (Cpu to Gpu)",
199 location: MemoryLocation::CpuToGpu,
200 size: alloc_info.SizeInBytes,
201 alignment: alloc_info.Alignment,
202 resource_category: ResourceCategory::Buffer,
203 })
204 .unwrap();
205
206 let mut resource: *mut d3d12::ID3D12Resource = std::ptr::null_mut();
207 let hr = unsafe {
208 device.CreatePlacedResource(
209 allocation.heap().as_winapi() as *mut _,
210 allocation.offset(),
211 &test_buffer_desc,
212 d3d12::D3D12_RESOURCE_STATE_COMMON,
213 std::ptr::null(),
214 &d3d12::IID_ID3D12Resource,
215 <*mut *mut d3d12::ID3D12Resource>::cast(&mut resource),
216 )
217 };
218 if hr != winerror::S_OK {
219 panic!("Failed to create placed resource.");
220 }
221
222 unsafe { resource.as_ref().unwrap().Release() };
223
224 allocator.free(allocation).unwrap();
225 info!("Allocation and deallocation of CpuToGpu memory was successful.");
226 }
227
228 // Test allocating Gpu to Cpu memory
229 {
230 let test_buffer_desc = d3d12::D3D12_RESOURCE_DESC {
231 Dimension: d3d12::D3D12_RESOURCE_DIMENSION_BUFFER,
232 Alignment: d3d12::D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64,
233 Width: 512,
234 Height: 1,
235 DepthOrArraySize: 1,
236 MipLevels: 1,
237 Format: dxgiformat::DXGI_FORMAT_UNKNOWN,
238 SampleDesc: all_dxgi::DXGI_SAMPLE_DESC {
239 Count: 1,
240 Quality: 0,
241 },
242 Layout: d3d12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
243 Flags: d3d12::D3D12_RESOURCE_FLAG_NONE,
244 };
245
246 let alloc_info = unsafe { device.GetResourceAllocationInfo(0, 1, &test_buffer_desc) };
247
248 let allocation = allocator
249 .allocate(&AllocationCreateDesc {
250 name: "Test allocation (Gpu to Cpu)",
251 location: MemoryLocation::GpuToCpu,
252 size: alloc_info.SizeInBytes,
253 alignment: alloc_info.Alignment,
254 resource_category: ResourceCategory::Buffer,
255 })
256 .unwrap();
257
258 let mut resource: *mut d3d12::ID3D12Resource = std::ptr::null_mut();
259 let hr = unsafe {
260 device.CreatePlacedResource(
261 allocation.heap().as_winapi() as *mut _,
262 allocation.offset(),
263 &test_buffer_desc,
264 d3d12::D3D12_RESOURCE_STATE_COMMON,
265 std::ptr::null(),
266 &d3d12::IID_ID3D12Resource,
267 <*mut *mut d3d12::ID3D12Resource>::cast(&mut resource),
268 )
269 };
270 if hr != winerror::S_OK {
271 panic!("Failed to create placed resource.");
272 }
273
274 unsafe { resource.as_ref().unwrap().Release() };
275
276 allocator.free(allocation).unwrap();
277 info!("Allocation and deallocation of CpuToGpu memory was successful.");
278 }
279
280 drop(allocator); // Explicitly drop before destruction of device.
281 unsafe { device.Release() };
282 unsafe { dxgi_factory.as_ref().unwrap().Release() };
283 }