1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! Exposes the physical device, which is a handle to the actual GPU used.
use std::ffi::CStr;
use anyhow::Result;
use ash::vk;
use crate::{AppSettings, Error, Instance, Surface, WindowInterface};
use crate::core::queue::{QueueInfo, QueueType};
use crate::util::string::wrap_c_str;
/// Stores queried properties of a Vulkan extension.
#[derive(Debug, Default)]
pub struct ExtensionProperties {
/// Name of the extension.
pub name: String,
/// Specification version of the extension.
pub spec_version: u32,
}
/// A physical device abstracts away an actual device, like a graphics card or integrated graphics card. This struct stores
/// its Vulkan handle, properties and requested queues.
#[derive(Default, Debug)]
pub struct PhysicalDevice {
/// Handle to the [`VkPhysicalDevice`](vk::PhysicalDevice).
handle: vk::PhysicalDevice,
/// [`VkPhysicalDeviceProperties`](vk::PhysicalDeviceProperties) structure with properties of this physical device.
properties: vk::PhysicalDeviceProperties,
/// [`VkPhysicalDeviceMemoryProperties`](crate::vk::PhysicalDeviceMemoryProperties) structure with memory properties of the physical device, such as
/// available memory types and heaps.
memory_properties: vk::PhysicalDeviceMemoryProperties,
/// Available Vulkan extensions.
extension_properties: Vec<ExtensionProperties>,
/// List of [`VkQueueFamilyProperties`](vk::QueueFamilyProperties) with properties of each queue family on the device.
queue_families: Vec<vk::QueueFamilyProperties>,
/// List of [`QueueInfo`] with requested queues abstracted away from the physical queues.
queues: Vec<QueueInfo>,
}
impl PhysicalDevice {
/// Selects the best available physical device from the given requirements and parameters.
pub fn select<Window: WindowInterface>(
instance: &Instance,
surface: Option<&Surface>,
settings: &AppSettings<Window>,
) -> Result<Self> {
let devices = unsafe { instance.enumerate_physical_devices()? };
if devices.is_empty() {
return Err(anyhow::Error::from(Error::NoGPU));
}
devices
.iter()
.find_map(|device| -> Option<PhysicalDevice> {
let mut physical_device = PhysicalDevice {
handle: *device,
properties: unsafe { instance.get_physical_device_properties(*device) },
memory_properties: unsafe {
instance.get_physical_device_memory_properties(*device)
},
extension_properties: unsafe {
instance
.enumerate_device_extension_properties(*device)
.unwrap()
.iter()
.map(|vk_properties| ExtensionProperties {
name: wrap_c_str(vk_properties.extension_name.as_ptr()),
spec_version: vk_properties.spec_version,
})
.collect()
},
queue_families: unsafe {
instance.get_physical_device_queue_family_properties(*device)
},
..Default::default()
};
if settings.gpu_requirements.dedicated
&& physical_device.properties.device_type
!= vk::PhysicalDeviceType::DISCRETE_GPU
{
return None;
}
if settings.gpu_requirements.min_video_memory > total_video_memory(&physical_device)
{
return None;
}
if settings.gpu_requirements.min_dedicated_video_memory
> total_device_memory(&physical_device)
{
return None;
}
physical_device.queues = {
settings
.gpu_requirements
.queues
.iter()
.filter_map(|request| -> Option<QueueInfo> {
let avoid = if request.dedicated {
match request.queue_type {
QueueType::Graphics => vk::QueueFlags::COMPUTE,
QueueType::Compute => vk::QueueFlags::GRAPHICS,
QueueType::Transfer => {
vk::QueueFlags::COMPUTE
| vk::QueueFlags::GRAPHICS
// In later nvidia drivers, these queues are now exposed with high family indices.
// Using them will probably not hurt performance, but we still avoid them as renderdoc does not currently
// support OPTICAL_FLOW_NV (fixed in nightly)
| vk::QueueFlags::OPTICAL_FLOW_NV
| vk::QueueFlags::VIDEO_DECODE_KHR
| vk::QueueFlags::VIDEO_ENCODE_KHR
}
}
} else {
vk::QueueFlags::default()
};
return if let Some((index, dedicated)) =
get_queue_family_prefer_dedicated(
physical_device.queue_families.as_slice(),
request.queue_type,
avoid,
) {
Some(QueueInfo {
queue_type: request.queue_type,
dedicated,
can_present: false,
family_index: index as u32,
flags: physical_device.queue_families[index].queue_flags,
})
} else {
None
};
})
.collect()
};
// We now have a list of all the queues that were found matching our request. If this amount is smaller than the number of requested queues,
// at least one is missing and could not be fulfilled. In this case we reject the device.
if physical_device.queues.len() < settings.gpu_requirements.queues.len() {
return None;
}
// Now check surface support (if we are not creating a headless context)
if let Some(surface) = surface {
// The surface is supported if one of the queues we found can present to it.
let supported_queue = physical_device.queues.iter_mut().find(|queue| unsafe {
surface
.get_physical_device_surface_support(
physical_device.handle,
queue.family_index,
surface.handle(),
)
.unwrap()
});
if let Some(queue) = supported_queue {
// Flag that we can present to it
queue.can_present = true;
} else {
// No queue to present found, reject physical device
return None;
}
}
// Check if all requested extensions are present
if !settings
.gpu_requirements
.device_extensions
.iter()
.all(|requested_extension| {
physical_device
.extension_properties
.iter()
.any(|ext| ext.name == *requested_extension)
})
{
return None;
}
let name =
unsafe { CStr::from_ptr(physical_device.properties.device_name.as_ptr()) };
info!(
"Picked physical device {:?}, driver version {:?}.",
name, physical_device.properties.driver_version
);
info!(
"Device has {} bytes of available video memory, of which {} are device local.",
total_video_memory(&physical_device),
total_device_memory(&physical_device)
);
#[cfg(feature = "log-objects")]
trace!("Created new VkPhysicalDevice {:p}", physical_device.handle);
Some(physical_device)
})
.ok_or_else(|| anyhow::Error::from(Error::NoGPU))
}
/// Selects the best available physical device and creates a surface on it.
pub fn select_with_surface<Window: WindowInterface>(
instance: &Instance,
settings: &AppSettings<Window>,
) -> Result<(Surface, Self)> {
let mut surface = Surface::new(&instance, &settings)?;
let physical_device = PhysicalDevice::select(&instance, Some(&surface), &settings)?;
surface.query_details(&physical_device)?;
Ok((surface, physical_device))
}
/// Get all queue families available on this device. This is different from
/// [`Device::queue_families()`](crate::Device::queue_families) since this knows about properties of each family, while the
/// device function only knows about family indices.
pub fn queue_families(&self) -> &[vk::QueueFamilyProperties] {
self.queue_families.as_slice()
}
/// Get information on all requested queues.
/// # Example
/// ```
/// # use phobos::*;
/// fn list_queues(device: PhysicalDevice) {
/// device.queues()
/// .iter()
/// .for_each(|info| {
/// println!("Queue #{} supports {:#?} (dedicated = {}, can_present = {})", info.family_index, info.flags, info.dedicated, info.can_present);
/// })
/// }
/// ```
pub fn queues(&self) -> &[QueueInfo] {
self.queues.as_slice()
}
/// Get unsafe access to the physical device handle
/// # Safety
/// Any vulkan calls that mutate this physical device may leave the system in an undefined
/// state.
pub unsafe fn handle(&self) -> vk::PhysicalDevice {
self.handle
}
/// This is the same function as [`Device::properties()`](crate::Device::properties)
pub fn properties(&self) -> &vk::PhysicalDeviceProperties {
&self.properties
}
/// Get the memory properties of this physical device, such as the different memory heaps available.
/// # Example
/// ```
/// # use phobos::*;
/// fn list_memory_heaps(device: PhysicalDevice) {
/// let properties = device.memory_properties();
/// for i in 0..properties.memory_heap_count {
/// let heap = properties.memory_heaps[i as usize];
/// println!("Heap #{i} has flags {:#?} and a size of {} bytes", heap.flags, heap.size);
/// }
/// }
/// ```
pub fn memory_properties(&self) -> &vk::PhysicalDeviceMemoryProperties {
&self.memory_properties
}
}
fn total_video_memory(device: &PhysicalDevice) -> usize {
device
.memory_properties
.memory_heaps
.iter()
.map(|heap| heap.size as usize)
.sum()
}
fn total_device_memory(device: &PhysicalDevice) -> usize {
device
.memory_properties
.memory_heaps
.iter()
.filter(|heap| heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL))
.map(|heap| heap.size as usize)
.sum()
}
fn get_queue_family_prefer_dedicated(
families: &[vk::QueueFamilyProperties],
queue_type: QueueType,
avoid: vk::QueueFlags,
) -> Option<(usize, bool)> {
let required = vk::QueueFlags::from_raw(queue_type as vk::Flags);
families
.iter()
.enumerate()
.fold(None, |current_best_match, (index, family)| -> Option<usize> {
// Does not contain required flags, must skip
if !family.queue_flags.contains(required) {
return current_best_match;
}
// Contains required flags and does not contain *any* flags to avoid, this is an optimal match.
// Note that to check of it doesn't contain any of the avoid flags, contains() will not work, we need to use intersects()
if !family.queue_flags.intersects(avoid) {
return Some(index);
}
// Only if we don't have a match yet, settle for a suboptimal match
if current_best_match.is_none() {
Some(index)
} else {
current_best_match
}
})
.map(|index| (index, !families[index].queue_flags.intersects(avoid)))
}