-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVkBoostrap.cpp
2042 lines (1833 loc) · 104 KB
/
VkBoostrap.cpp
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the “Software”), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Copyright © 2020 Charles Giessen ([email protected])
*/
#include "VkBootstrap.h"
#include <cstring>
#if defined(_WIN32)
#include <fcntl.h>
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#endif // _WIN32
#if defined(__linux__) || defined(__APPLE__)
#include <dlfcn.h>
#endif
#include <mutex>
#include <algorithm>
namespace vkb {
namespace detail {
GenericFeaturesPNextNode::GenericFeaturesPNextNode() { memset(fields, UINT8_MAX, sizeof(VkBool32) * field_capacity); }
bool GenericFeaturesPNextNode::match(GenericFeaturesPNextNode const &requested, GenericFeaturesPNextNode const &supported) noexcept {
assert(requested.sType == supported.sType && "Non-matching sTypes in features nodes!");
for (uint32_t i = 0; i < field_capacity; i++) {
if (requested.fields[i] && !supported.fields[i]) return false;
}
return true;
}
class VulkanFunctions {
private:
std::mutex init_mutex;
#if defined(__linux__) || defined(__APPLE__)
void *library = nullptr;
#elif defined(_WIN32)
HMODULE library = nullptr;
#endif
bool load_vulkan_library() {
// Can immediately return if it has already been loaded
if (library) {
return true;
}
#if defined(__linux__)
library = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
if (!library) library = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
#elif defined(__APPLE__)
library = dlopen("libvulkan.dylib", RTLD_NOW | RTLD_LOCAL);
if (!library) library = dlopen("libvulkan.1.dylib", RTLD_NOW | RTLD_LOCAL);
if (!library) library = dlopen("libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
#elif defined(_WIN32)
library = LoadLibrary(TEXT("vulkan-1.dll"));
#else
assert(false && "Unsupported platform");
#endif
if (!library) return false;
load_func(ptr_vkGetInstanceProcAddr, "vkGetInstanceProcAddr");
return ptr_vkGetInstanceProcAddr != nullptr;
}
template <typename T> void load_func(T &func_dest, const char *func_name) {
#if defined(__linux__) || defined(__APPLE__)
func_dest = reinterpret_cast<T>(dlsym(library, func_name));
#elif defined(_WIN32)
func_dest = reinterpret_cast<T>(GetProcAddress(library, func_name));
#endif
}
void close() {
#if defined(__linux__) || defined(__APPLE__)
dlclose(library);
#elif defined(_WIN32)
FreeLibrary(library);
#endif
library = 0;
}
public:
bool init_vulkan_funcs(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr = nullptr) {
std::lock_guard<std::mutex> lg(init_mutex);
if (fp_vkGetInstanceProcAddr != nullptr) {
ptr_vkGetInstanceProcAddr = fp_vkGetInstanceProcAddr;
} else {
bool ret = load_vulkan_library();
if (!ret) return false;
}
fp_vkEnumerateInstanceExtensionProperties = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties>(
ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceExtensionProperties"));
fp_vkEnumerateInstanceLayerProperties = reinterpret_cast<PFN_vkEnumerateInstanceLayerProperties>(
ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties"));
fp_vkEnumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceVersion"));
fp_vkCreateInstance =
reinterpret_cast<PFN_vkCreateInstance>(ptr_vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkCreateInstance"));
return true;
}
public:
template <typename T> void get_inst_proc_addr(T &out_ptr, const char *func_name) {
out_ptr = reinterpret_cast<T>(ptr_vkGetInstanceProcAddr(instance, func_name));
}
template <typename T> void get_device_proc_addr(VkDevice device, T &out_ptr, const char *func_name) {
out_ptr = reinterpret_cast<T>(fp_vkGetDeviceProcAddr(device, func_name));
}
PFN_vkGetInstanceProcAddr ptr_vkGetInstanceProcAddr = nullptr;
VkInstance instance = nullptr;
PFN_vkEnumerateInstanceExtensionProperties fp_vkEnumerateInstanceExtensionProperties = nullptr;
PFN_vkEnumerateInstanceLayerProperties fp_vkEnumerateInstanceLayerProperties = nullptr;
PFN_vkEnumerateInstanceVersion fp_vkEnumerateInstanceVersion = nullptr;
PFN_vkCreateInstance fp_vkCreateInstance = nullptr;
PFN_vkDestroyInstance fp_vkDestroyInstance = nullptr;
PFN_vkCreateDebugUtilsMessengerEXT fp_vkCreateDebugUtilsMessengerEXT = nullptr;
PFN_vkDestroyDebugUtilsMessengerEXT fp_vkDestroyDebugUtilsMessengerEXT = nullptr;
PFN_vkEnumeratePhysicalDevices fp_vkEnumeratePhysicalDevices = nullptr;
PFN_vkGetPhysicalDeviceFeatures fp_vkGetPhysicalDeviceFeatures = nullptr;
PFN_vkGetPhysicalDeviceFeatures2 fp_vkGetPhysicalDeviceFeatures2 = nullptr;
PFN_vkGetPhysicalDeviceFeatures2KHR fp_vkGetPhysicalDeviceFeatures2KHR = nullptr;
PFN_vkGetPhysicalDeviceProperties fp_vkGetPhysicalDeviceProperties = nullptr;
PFN_vkGetPhysicalDeviceQueueFamilyProperties fp_vkGetPhysicalDeviceQueueFamilyProperties = nullptr;
PFN_vkGetPhysicalDeviceMemoryProperties fp_vkGetPhysicalDeviceMemoryProperties = nullptr;
PFN_vkEnumerateDeviceExtensionProperties fp_vkEnumerateDeviceExtensionProperties = nullptr;
PFN_vkCreateDevice fp_vkCreateDevice = nullptr;
PFN_vkGetDeviceProcAddr fp_vkGetDeviceProcAddr = nullptr;
PFN_vkDestroySurfaceKHR fp_vkDestroySurfaceKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR fp_vkGetPhysicalDeviceSurfaceSupportKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fp_vkGetPhysicalDeviceSurfaceFormatsKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fp_vkGetPhysicalDeviceSurfacePresentModesKHR = nullptr;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR = nullptr;
void init_instance_funcs(VkInstance inst) {
instance = inst;
get_inst_proc_addr(fp_vkDestroyInstance, "vkDestroyInstance");
get_inst_proc_addr(fp_vkCreateDebugUtilsMessengerEXT, "vkCreateDebugUtilsMessengerEXT");
get_inst_proc_addr(fp_vkDestroyDebugUtilsMessengerEXT, "vkDestroyDebugUtilsMessengerEXT");
get_inst_proc_addr(fp_vkEnumeratePhysicalDevices, "vkEnumeratePhysicalDevices");
get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures, "vkGetPhysicalDeviceFeatures");
get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures2, "vkGetPhysicalDeviceFeatures2");
get_inst_proc_addr(fp_vkGetPhysicalDeviceFeatures2KHR, "vkGetPhysicalDeviceFeatures2KHR");
get_inst_proc_addr(fp_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties");
get_inst_proc_addr(fp_vkGetPhysicalDeviceQueueFamilyProperties, "vkGetPhysicalDeviceQueueFamilyProperties");
get_inst_proc_addr(fp_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties");
get_inst_proc_addr(fp_vkEnumerateDeviceExtensionProperties, "vkEnumerateDeviceExtensionProperties");
get_inst_proc_addr(fp_vkCreateDevice, "vkCreateDevice");
get_inst_proc_addr(fp_vkGetDeviceProcAddr, "vkGetDeviceProcAddr");
get_inst_proc_addr(fp_vkDestroySurfaceKHR, "vkDestroySurfaceKHR");
get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceSupportKHR, "vkGetPhysicalDeviceSurfaceSupportKHR");
get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceFormatsKHR, "vkGetPhysicalDeviceSurfaceFormatsKHR");
get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfacePresentModesKHR, "vkGetPhysicalDeviceSurfacePresentModesKHR");
get_inst_proc_addr(fp_vkGetPhysicalDeviceSurfaceCapabilitiesKHR, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
}
};
static VulkanFunctions &vulkan_functions() {
static VulkanFunctions v;
return v;
}
// Helper for robustly executing the two-call pattern
template <typename T, typename F, typename... Ts> auto get_vector(std::vector<T> &out, F &&f, Ts&&... ts) -> VkResult {
uint32_t count = 0;
VkResult err;
do {
err = f(ts..., &count, nullptr);
if (err != VK_SUCCESS) {
return err;
};
out.resize(count);
err = f(ts..., &count, out.data());
out.resize(count);
} while (err == VK_INCOMPLETE);
return err;
}
template <typename T, typename F, typename... Ts> auto get_vector_noerror(F &&f, Ts&&... ts) -> std::vector<T> {
uint32_t count = 0;
std::vector<T> results;
f(ts..., &count, nullptr);
results.resize(count);
f(ts..., &count, results.data());
results.resize(count);
return results;
}
} // namespace detail
const char *to_string_message_severity(VkDebugUtilsMessageSeverityFlagBitsEXT s) {
switch (s) {
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
return "VERBOSE";
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
return "ERROR";
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
return "WARNING";
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
return "INFO";
default:
return "UNKNOWN";
}
}
const char *to_string_message_type(VkDebugUtilsMessageTypeFlagsEXT s) {
if (s == 7) return "General | Validation | Performance";
if (s == 6) return "Validation | Performance";
if (s == 5) return "General | Performance";
if (s == 4 /*VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT*/) return "Performance";
if (s == 3) return "General | Validation";
if (s == 2 /*VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT*/) return "Validation";
if (s == 1 /*VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT*/) return "General";
return "Unknown";
}
VkResult create_debug_utils_messenger(VkInstance instance,
PFN_vkDebugUtilsMessengerCallbackEXT debug_callback,
VkDebugUtilsMessageSeverityFlagsEXT severity,
VkDebugUtilsMessageTypeFlagsEXT type,
void *user_data_pointer,
VkDebugUtilsMessengerEXT *pDebugMessenger,
VkAllocationCallbacks *allocation_callbacks) {
if (debug_callback == nullptr) debug_callback = default_debug_callback;
VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = {};
messengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
messengerCreateInfo.pNext = nullptr;
messengerCreateInfo.messageSeverity = severity;
messengerCreateInfo.messageType = type;
messengerCreateInfo.pfnUserCallback = debug_callback;
messengerCreateInfo.pUserData = user_data_pointer;
if (detail::vulkan_functions().fp_vkCreateDebugUtilsMessengerEXT != nullptr) {
return detail::vulkan_functions().fp_vkCreateDebugUtilsMessengerEXT(
instance, &messengerCreateInfo, allocation_callbacks, pDebugMessenger);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void destroy_debug_utils_messenger(
VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, VkAllocationCallbacks *allocation_callbacks) {
if (detail::vulkan_functions().fp_vkDestroyDebugUtilsMessengerEXT != nullptr) {
detail::vulkan_functions().fp_vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger, allocation_callbacks);
}
}
namespace detail {
bool check_layer_supported(std::vector<VkLayerProperties> const &available_layers, const char *layer_name) {
if (!layer_name) return false;
for (const auto &layer_properties : available_layers) {
if (strcmp(layer_name, layer_properties.layerName) == 0) {
return true;
}
}
return false;
}
bool check_layers_supported(std::vector<VkLayerProperties> const &available_layers, std::vector<const char *> const &layer_names) {
bool all_found = true;
for (const auto &layer_name : layer_names) {
bool found = check_layer_supported(available_layers, layer_name);
if (!found) all_found = false;
}
return all_found;
}
bool check_extension_supported(std::vector<VkExtensionProperties> const &available_extensions, const char *extension_name) {
if (!extension_name) return false;
for (const auto &extension_properties : available_extensions) {
if (strcmp(extension_name, extension_properties.extensionName) == 0) {
return true;
}
}
return false;
}
bool check_extensions_supported(
std::vector<VkExtensionProperties> const &available_extensions, std::vector<const char *> const &extension_names) {
bool all_found = true;
for (const auto &extension_name : extension_names) {
bool found = check_extension_supported(available_extensions, extension_name);
if (!found) all_found = false;
}
return all_found;
}
template <typename T> void setup_pNext_chain(T &structure, std::vector<VkBaseOutStructure *> const &structs) {
structure.pNext = nullptr;
if (structs.size() <= 0) return;
for (size_t i = 0; i < structs.size() - 1; i++) {
structs.at(i)->pNext = structs.at(i + 1);
}
structure.pNext = structs.at(0);
}
const char *validation_layer_name = "VK_LAYER_KHRONOS_validation";
struct InstanceErrorCategory : std::error_category {
const char *name() const noexcept override { return "vkb_instance"; }
std::string message(int err) const override { return to_string(static_cast<InstanceError>(err)); }
};
const InstanceErrorCategory instance_error_category;
struct PhysicalDeviceErrorCategory : std::error_category {
const char *name() const noexcept override { return "vkb_physical_device"; }
std::string message(int err) const override { return to_string(static_cast<PhysicalDeviceError>(err)); }
};
const PhysicalDeviceErrorCategory physical_device_error_category;
struct QueueErrorCategory : std::error_category {
const char *name() const noexcept override { return "vkb_queue"; }
std::string message(int err) const override { return to_string(static_cast<QueueError>(err)); }
};
const QueueErrorCategory queue_error_category;
struct DeviceErrorCategory : std::error_category {
const char *name() const noexcept override { return "vkb_device"; }
std::string message(int err) const override { return to_string(static_cast<DeviceError>(err)); }
};
const DeviceErrorCategory device_error_category;
struct SwapchainErrorCategory : std::error_category {
const char *name() const noexcept override { return "vbk_swapchain"; }
std::string message(int err) const override { return to_string(static_cast<SwapchainError>(err)); }
};
const SwapchainErrorCategory swapchain_error_category;
} // namespace detail
std::error_code make_error_code(InstanceError instance_error) {
return { static_cast<int>(instance_error), detail::instance_error_category };
}
std::error_code make_error_code(PhysicalDeviceError physical_device_error) {
return { static_cast<int>(physical_device_error), detail::physical_device_error_category };
}
std::error_code make_error_code(QueueError queue_error) {
return { static_cast<int>(queue_error), detail::queue_error_category };
}
std::error_code make_error_code(DeviceError device_error) {
return { static_cast<int>(device_error), detail::device_error_category };
}
std::error_code make_error_code(SwapchainError swapchain_error) {
return { static_cast<int>(swapchain_error), detail::swapchain_error_category };
}
#define CASE_TO_STRING(CATEGORY, TYPE) \
case CATEGORY::TYPE: \
return #TYPE;
const char *to_string(InstanceError err) {
switch (err) {
CASE_TO_STRING(InstanceError, vulkan_unavailable)
CASE_TO_STRING(InstanceError, vulkan_version_unavailable)
CASE_TO_STRING(InstanceError, vulkan_version_1_1_unavailable)
CASE_TO_STRING(InstanceError, vulkan_version_1_2_unavailable)
CASE_TO_STRING(InstanceError, failed_create_debug_messenger)
CASE_TO_STRING(InstanceError, failed_create_instance)
CASE_TO_STRING(InstanceError, requested_layers_not_present)
CASE_TO_STRING(InstanceError, requested_extensions_not_present)
CASE_TO_STRING(InstanceError, windowing_extensions_not_present)
default:
return "";
}
}
const char *to_string(PhysicalDeviceError err) {
switch (err) {
CASE_TO_STRING(PhysicalDeviceError, no_surface_provided)
CASE_TO_STRING(PhysicalDeviceError, failed_enumerate_physical_devices)
CASE_TO_STRING(PhysicalDeviceError, no_physical_devices_found)
CASE_TO_STRING(PhysicalDeviceError, no_suitable_device)
default:
return "";
}
}
const char *to_string(QueueError err) {
switch (err) {
CASE_TO_STRING(QueueError, present_unavailable)
CASE_TO_STRING(QueueError, graphics_unavailable)
CASE_TO_STRING(QueueError, compute_unavailable)
CASE_TO_STRING(QueueError, transfer_unavailable)
CASE_TO_STRING(QueueError, queue_index_out_of_range)
CASE_TO_STRING(QueueError, invalid_queue_family_index)
default:
return "";
}
}
const char *to_string(DeviceError err) {
switch (err) {
CASE_TO_STRING(DeviceError, failed_create_device)
default:
return "";
}
}
const char *to_string(SwapchainError err) {
switch (err) {
CASE_TO_STRING(SwapchainError, surface_handle_not_provided)
CASE_TO_STRING(SwapchainError, failed_query_surface_support_details)
CASE_TO_STRING(SwapchainError, failed_create_swapchain)
CASE_TO_STRING(SwapchainError, failed_get_swapchain_images)
CASE_TO_STRING(SwapchainError, failed_create_swapchain_image_views)
CASE_TO_STRING(SwapchainError, required_min_image_count_too_low)
CASE_TO_STRING(SwapchainError, required_usage_not_supported)
default:
return "";
}
}
Result<SystemInfo> SystemInfo::get_system_info() {
if (!detail::vulkan_functions().init_vulkan_funcs(nullptr)) {
return make_error_code(InstanceError::vulkan_unavailable);
}
return SystemInfo();
}
Result<SystemInfo> SystemInfo::get_system_info(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr) {
// Using externally provided function pointers, assume the loader is available
if (!detail::vulkan_functions().init_vulkan_funcs(fp_vkGetInstanceProcAddr)) {
return make_error_code(InstanceError::vulkan_unavailable);
}
return SystemInfo();
}
SystemInfo::SystemInfo() {
auto available_layers_ret = detail::get_vector<VkLayerProperties>(
this->available_layers, detail::vulkan_functions().fp_vkEnumerateInstanceLayerProperties);
if (available_layers_ret != VK_SUCCESS) {
this->available_layers.clear();
}
for (auto &layer : this->available_layers)
if (strcmp(layer.layerName, detail::validation_layer_name) == 0) validation_layers_available = true;
auto available_extensions_ret = detail::get_vector<VkExtensionProperties>(
this->available_extensions, detail::vulkan_functions().fp_vkEnumerateInstanceExtensionProperties, nullptr);
if (available_extensions_ret != VK_SUCCESS) {
this->available_extensions.clear();
}
for (auto &ext : this->available_extensions) {
if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) {
debug_utils_available = true;
}
}
for (auto &layer : this->available_layers) {
std::vector<VkExtensionProperties> layer_extensions;
auto layer_extensions_ret = detail::get_vector<VkExtensionProperties>(
layer_extensions, detail::vulkan_functions().fp_vkEnumerateInstanceExtensionProperties, layer.layerName);
if (layer_extensions_ret == VK_SUCCESS) {
this->available_extensions.insert(
this->available_extensions.end(), layer_extensions.begin(), layer_extensions.end());
for (auto &ext : layer_extensions) {
if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) {
debug_utils_available = true;
}
}
}
}
}
bool SystemInfo::is_extension_available(const char *extension_name) const {
if (!extension_name) return false;
return detail::check_extension_supported(available_extensions, extension_name);
}
bool SystemInfo::is_layer_available(const char *layer_name) const {
if (!layer_name) return false;
return detail::check_layer_supported(available_layers, layer_name);
}
void destroy_surface(Instance const &instance, VkSurfaceKHR surface) {
if (instance.instance != VK_NULL_HANDLE && surface != VK_NULL_HANDLE) {
detail::vulkan_functions().fp_vkDestroySurfaceKHR(instance.instance, surface, instance.allocation_callbacks);
}
}
void destroy_surface(VkInstance instance, VkSurfaceKHR surface, VkAllocationCallbacks *callbacks) {
if (instance != VK_NULL_HANDLE && surface != VK_NULL_HANDLE) {
detail::vulkan_functions().fp_vkDestroySurfaceKHR(instance, surface, callbacks);
}
}
void destroy_instance(Instance const &instance) {
if (instance.instance != VK_NULL_HANDLE) {
if (instance.debug_messenger != VK_NULL_HANDLE)
destroy_debug_utils_messenger(instance.instance, instance.debug_messenger, instance.allocation_callbacks);
detail::vulkan_functions().fp_vkDestroyInstance(instance.instance, instance.allocation_callbacks);
}
}
Instance::operator VkInstance() const { return this->instance; }
InstanceDispatchTable Instance::make_table() const { return { instance, fp_vkGetInstanceProcAddr }; }
InstanceBuilder::InstanceBuilder(PFN_vkGetInstanceProcAddr fp_vkGetInstanceProcAddr) {
info.fp_vkGetInstanceProcAddr = fp_vkGetInstanceProcAddr;
}
InstanceBuilder::InstanceBuilder() {}
Result<Instance> InstanceBuilder::build() const {
auto sys_info_ret = SystemInfo::get_system_info(info.fp_vkGetInstanceProcAddr);
if (!sys_info_ret) return sys_info_ret.error();
auto system = sys_info_ret.value();
uint32_t instance_version = VKB_VK_API_VERSION_1_0;
if (info.minimum_instance_version > VKB_VK_API_VERSION_1_0 || info.required_api_version > VKB_VK_API_VERSION_1_0 ||
info.desired_api_version > VKB_VK_API_VERSION_1_0) {
PFN_vkEnumerateInstanceVersion pfn_vkEnumerateInstanceVersion = detail::vulkan_functions().fp_vkEnumerateInstanceVersion;
if (pfn_vkEnumerateInstanceVersion != nullptr) {
VkResult res = pfn_vkEnumerateInstanceVersion(&instance_version);
// Should always return VK_SUCCESS
if (res != VK_SUCCESS && info.required_api_version > 0)
return make_error_code(InstanceError::vulkan_version_unavailable);
}
if (pfn_vkEnumerateInstanceVersion == nullptr || instance_version < info.minimum_instance_version ||
(info.minimum_instance_version == 0 && instance_version < info.required_api_version)) {
if (VK_VERSION_MINOR(info.required_api_version) == 2)
return make_error_code(InstanceError::vulkan_version_1_2_unavailable);
else if (VK_VERSION_MINOR(info.required_api_version))
return make_error_code(InstanceError::vulkan_version_1_1_unavailable);
else
return make_error_code(InstanceError::vulkan_version_unavailable);
}
}
uint32_t api_version = instance_version < VKB_VK_API_VERSION_1_1 ? instance_version : info.required_api_version;
if (info.desired_api_version > VKB_VK_API_VERSION_1_0 && instance_version >= info.desired_api_version) {
instance_version = info.desired_api_version;
api_version = info.desired_api_version;
}
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = nullptr;
app_info.pApplicationName = info.app_name != nullptr ? info.app_name : "";
app_info.applicationVersion = info.application_version;
app_info.pEngineName = info.engine_name != nullptr ? info.engine_name : "";
app_info.engineVersion = info.engine_version;
app_info.apiVersion = api_version;
std::vector<const char *> extensions;
std::vector<const char *> layers;
for (auto &ext : info.extensions)
extensions.push_back(ext);
if (info.debug_callback != nullptr && info.use_debug_messenger && system.debug_utils_available) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
bool properties2_ext_enabled =
api_version < VKB_VK_API_VERSION_1_1 && detail::check_extension_supported(system.available_extensions,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
if (properties2_ext_enabled) {
extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
}
#if defined(VK_KHR_portability_enumeration)
bool portability_enumeration_support =
detail::check_extension_supported(system.available_extensions, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
if (portability_enumeration_support) {
extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
}
#else
bool portability_enumeration_support = false;
#endif
if (!info.headless_context) {
auto check_add_window_ext = [&](const char *name) -> bool {
if (!detail::check_extension_supported(system.available_extensions, name)) return false;
extensions.push_back(name);
return true;
};
bool khr_surface_added = check_add_window_ext("VK_KHR_surface");
#if defined(_WIN32)
bool added_window_exts = check_add_window_ext("VK_KHR_win32_surface");
#elif defined(__ANDROID__)
bool added_window_exts = check_add_window_ext("VK_KHR_android_surface");
#elif defined(_DIRECT2DISPLAY)
bool added_window_exts = check_add_window_ext("VK_KHR_display");
#elif defined(__linux__)
// make sure all three calls to check_add_window_ext, don't allow short circuiting
bool added_window_exts = check_add_window_ext("VK_KHR_xcb_surface");
added_window_exts = check_add_window_ext("VK_KHR_xlib_surface") || added_window_exts;
added_window_exts = check_add_window_ext("VK_KHR_wayland_surface") || added_window_exts;
#elif defined(__APPLE__)
bool added_window_exts = check_add_window_ext("VK_EXT_metal_surface");
#endif
if (!khr_surface_added || !added_window_exts)
return make_error_code(InstanceError::windowing_extensions_not_present);
}
bool all_extensions_supported = detail::check_extensions_supported(system.available_extensions, extensions);
if (!all_extensions_supported) {
return make_error_code(InstanceError::requested_extensions_not_present);
}
for (auto &layer : info.layers)
layers.push_back(layer);
if (info.enable_validation_layers || (info.request_validation_layers && system.validation_layers_available)) {
layers.push_back(detail::validation_layer_name);
}
bool all_layers_supported = detail::check_layers_supported(system.available_layers, layers);
if (!all_layers_supported) {
return make_error_code(InstanceError::requested_layers_not_present);
}
std::vector<VkBaseOutStructure *> pNext_chain;
VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = {};
if (info.use_debug_messenger) {
messengerCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
messengerCreateInfo.pNext = nullptr;
messengerCreateInfo.messageSeverity = info.debug_message_severity;
messengerCreateInfo.messageType = info.debug_message_type;
messengerCreateInfo.pfnUserCallback = info.debug_callback;
messengerCreateInfo.pUserData = info.debug_user_data_pointer;
pNext_chain.push_back(reinterpret_cast<VkBaseOutStructure *>(&messengerCreateInfo));
}
VkValidationFeaturesEXT features{};
if (info.enabled_validation_features.size() != 0 || info.disabled_validation_features.size()) {
features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
features.pNext = nullptr;
features.enabledValidationFeatureCount = static_cast<uint32_t>(info.enabled_validation_features.size());
features.pEnabledValidationFeatures = info.enabled_validation_features.data();
features.disabledValidationFeatureCount = static_cast<uint32_t>(info.disabled_validation_features.size());
features.pDisabledValidationFeatures = info.disabled_validation_features.data();
pNext_chain.push_back(reinterpret_cast<VkBaseOutStructure *>(&features));
}
VkValidationFlagsEXT checks{};
if (info.disabled_validation_checks.size() != 0) {
checks.sType = VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT;
checks.pNext = nullptr;
checks.disabledValidationCheckCount = static_cast<uint32_t>(info.disabled_validation_checks.size());
checks.pDisabledValidationChecks = info.disabled_validation_checks.data();
pNext_chain.push_back(reinterpret_cast<VkBaseOutStructure *>(&checks));
}
VkInstanceCreateInfo instance_create_info = {};
instance_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
detail::setup_pNext_chain(instance_create_info, pNext_chain);
#if !defined(NDEBUG)
for (auto &node : pNext_chain) {
assert(node->sType != VK_STRUCTURE_TYPE_APPLICATION_INFO);
}
#endif
instance_create_info.flags = info.flags;
instance_create_info.pApplicationInfo = &app_info;
instance_create_info.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
instance_create_info.ppEnabledExtensionNames = extensions.data();
instance_create_info.enabledLayerCount = static_cast<uint32_t>(layers.size());
instance_create_info.ppEnabledLayerNames = layers.data();
#if defined(VK_KHR_portability_enumeration)
if (portability_enumeration_support) {
instance_create_info.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
}
#endif
Instance instance;
VkResult res =
detail::vulkan_functions().fp_vkCreateInstance(&instance_create_info, info.allocation_callbacks, &instance.instance);
if (res != VK_SUCCESS) return Result<Instance>(InstanceError::failed_create_instance, res);
detail::vulkan_functions().init_instance_funcs(instance.instance);
if (info.use_debug_messenger) {
res = create_debug_utils_messenger(instance.instance,
info.debug_callback,
info.debug_message_severity,
info.debug_message_type,
info.debug_user_data_pointer,
&instance.debug_messenger,
info.allocation_callbacks);
if (res != VK_SUCCESS) {
return Result<Instance>(InstanceError::failed_create_debug_messenger, res);
}
}
instance.headless = info.headless_context;
instance.properties2_ext_enabled = properties2_ext_enabled;
instance.allocation_callbacks = info.allocation_callbacks;
instance.instance_version = instance_version;
instance.api_version = api_version;
instance.fp_vkGetInstanceProcAddr = detail::vulkan_functions().ptr_vkGetInstanceProcAddr;
instance.fp_vkGetDeviceProcAddr = detail::vulkan_functions().fp_vkGetDeviceProcAddr;
return instance;
}
InstanceBuilder &InstanceBuilder::set_app_name(const char *app_name) {
if (!app_name) return *this;
info.app_name = app_name;
return *this;
}
InstanceBuilder &InstanceBuilder::set_engine_name(const char *engine_name) {
if (!engine_name) return *this;
info.engine_name = engine_name;
return *this;
}
InstanceBuilder &InstanceBuilder::set_app_version(uint32_t app_version) {
info.application_version = app_version;
return *this;
}
InstanceBuilder &InstanceBuilder::set_app_version(uint32_t major, uint32_t minor, uint32_t patch) {
info.application_version = VKB_MAKE_VK_VERSION(0, major, minor, patch);
return *this;
}
InstanceBuilder &InstanceBuilder::set_engine_version(uint32_t engine_version) {
info.engine_version = engine_version;
return *this;
}
InstanceBuilder &InstanceBuilder::set_engine_version(uint32_t major, uint32_t minor, uint32_t patch) {
info.engine_version = VKB_MAKE_VK_VERSION(0, major, minor, patch);
return *this;
}
InstanceBuilder &InstanceBuilder::require_api_version(uint32_t required_api_version) {
info.required_api_version = required_api_version;
return *this;
}
InstanceBuilder &InstanceBuilder::require_api_version(uint32_t major, uint32_t minor, uint32_t patch) {
info.required_api_version = VKB_MAKE_VK_VERSION(0, major, minor, patch);
return *this;
}
InstanceBuilder &InstanceBuilder::set_minimum_instance_version(uint32_t minimum_instance_version) {
info.minimum_instance_version = minimum_instance_version;
return *this;
}
InstanceBuilder &InstanceBuilder::set_minimum_instance_version(uint32_t major, uint32_t minor, uint32_t patch) {
info.minimum_instance_version = VKB_MAKE_VK_VERSION(0, major, minor, patch);
return *this;
}
InstanceBuilder &InstanceBuilder::desire_api_version(uint32_t preferred_vulkan_version) {
info.desired_api_version = preferred_vulkan_version;
return *this;
}
InstanceBuilder &InstanceBuilder::desire_api_version(uint32_t major, uint32_t minor, uint32_t patch) {
info.desired_api_version = VKB_MAKE_VK_VERSION(0, major, minor, patch);
return *this;
}
InstanceBuilder &InstanceBuilder::enable_layer(const char *layer_name) {
if (!layer_name) return *this;
info.layers.push_back(layer_name);
return *this;
}
InstanceBuilder &InstanceBuilder::enable_extension(const char *extension_name) {
if (!extension_name) return *this;
info.extensions.push_back(extension_name);
return *this;
}
InstanceBuilder &InstanceBuilder::enable_extensions(std::vector<const char *> const &extensions) {
for (const auto extension : extensions) {
info.extensions.push_back(extension);
}
return *this;
}
InstanceBuilder &InstanceBuilder::enable_extensions(size_t count, const char *const *extensions) {
if (!extensions || count == 0) return *this;
for (size_t i = 0; i < count; i++) {
info.extensions.push_back(extensions[i]);
}
return *this;
}
InstanceBuilder &InstanceBuilder::enable_validation_layers(bool enable_validation) {
info.enable_validation_layers = enable_validation;
return *this;
}
InstanceBuilder &InstanceBuilder::request_validation_layers(bool enable_validation) {
info.request_validation_layers = enable_validation;
return *this;
}
InstanceBuilder &InstanceBuilder::use_default_debug_messenger() {
info.use_debug_messenger = true;
info.debug_callback = default_debug_callback;
return *this;
}
InstanceBuilder &InstanceBuilder::set_debug_callback(PFN_vkDebugUtilsMessengerCallbackEXT callback) {
info.use_debug_messenger = true;
info.debug_callback = callback;
return *this;
}
InstanceBuilder &InstanceBuilder::set_debug_callback_user_data_pointer(void *user_data_pointer) {
info.debug_user_data_pointer = user_data_pointer;
return *this;
}
InstanceBuilder &InstanceBuilder::set_headless(bool headless) {
info.headless_context = headless;
return *this;
}
InstanceBuilder &InstanceBuilder::set_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity) {
info.debug_message_severity = severity;
return *this;
}
InstanceBuilder &InstanceBuilder::add_debug_messenger_severity(VkDebugUtilsMessageSeverityFlagsEXT severity) {
info.debug_message_severity = info.debug_message_severity | severity;
return *this;
}
InstanceBuilder &InstanceBuilder::set_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type) {
info.debug_message_type = type;
return *this;
}
InstanceBuilder &InstanceBuilder::add_debug_messenger_type(VkDebugUtilsMessageTypeFlagsEXT type) {
info.debug_message_type = info.debug_message_type | type;
return *this;
}
InstanceBuilder &InstanceBuilder::add_validation_disable(VkValidationCheckEXT check) {
info.disabled_validation_checks.push_back(check);
return *this;
}
InstanceBuilder &InstanceBuilder::add_validation_feature_enable(VkValidationFeatureEnableEXT enable) {
info.enabled_validation_features.push_back(enable);
return *this;
}
InstanceBuilder &InstanceBuilder::add_validation_feature_disable(VkValidationFeatureDisableEXT disable) {
info.disabled_validation_features.push_back(disable);
return *this;
}
InstanceBuilder &InstanceBuilder::set_allocation_callbacks(VkAllocationCallbacks *callbacks) {
info.allocation_callbacks = callbacks;
return *this;
}
void destroy_debug_messenger(VkInstance const instance, VkDebugUtilsMessengerEXT const messenger);
// ---- Physical Device ---- //
namespace detail {
std::vector<std::string> check_device_extension_support(
std::vector<std::string> const &available_extensions, std::vector<std::string> const &desired_extensions) {
std::vector<std::string> extensions_to_enable;
for (const auto &avail_ext : available_extensions) {
for (auto &req_ext : desired_extensions) {
if (avail_ext == req_ext) {
extensions_to_enable.push_back(req_ext);
break;
}
}
}
return extensions_to_enable;
}
// clang-format off
bool supports_features(VkPhysicalDeviceFeatures supported,
VkPhysicalDeviceFeatures requested,
std::vector<GenericFeaturesPNextNode> const &extension_supported,
std::vector<GenericFeaturesPNextNode> const &extension_requested) {
if (requested.robustBufferAccess && !supported.robustBufferAccess) return false;
if (requested.fullDrawIndexUint32 && !supported.fullDrawIndexUint32) return false;
if (requested.imageCubeArray && !supported.imageCubeArray) return false;
if (requested.independentBlend && !supported.independentBlend) return false;
if (requested.geometryShader && !supported.geometryShader) return false;
if (requested.tessellationShader && !supported.tessellationShader) return false;
if (requested.sampleRateShading && !supported.sampleRateShading) return false;
if (requested.dualSrcBlend && !supported.dualSrcBlend) return false;
if (requested.logicOp && !supported.logicOp) return false;
if (requested.multiDrawIndirect && !supported.multiDrawIndirect) return false;
if (requested.drawIndirectFirstInstance && !supported.drawIndirectFirstInstance) return false;
if (requested.depthClamp && !supported.depthClamp) return false;
if (requested.depthBiasClamp && !supported.depthBiasClamp) return false;
if (requested.fillModeNonSolid && !supported.fillModeNonSolid) return false;
if (requested.depthBounds && !supported.depthBounds) return false;
if (requested.wideLines && !supported.wideLines) return false;
if (requested.largePoints && !supported.largePoints) return false;
if (requested.alphaToOne && !supported.alphaToOne) return false;
if (requested.multiViewport && !supported.multiViewport) return false;
if (requested.samplerAnisotropy && !supported.samplerAnisotropy) return false;
if (requested.textureCompressionETC2 && !supported.textureCompressionETC2) return false;
if (requested.textureCompressionASTC_LDR && !supported.textureCompressionASTC_LDR) return false;
if (requested.textureCompressionBC && !supported.textureCompressionBC) return false;
if (requested.occlusionQueryPrecise && !supported.occlusionQueryPrecise) return false;
if (requested.pipelineStatisticsQuery && !supported.pipelineStatisticsQuery) return false;
if (requested.vertexPipelineStoresAndAtomics && !supported.vertexPipelineStoresAndAtomics) return false;
if (requested.fragmentStoresAndAtomics && !supported.fragmentStoresAndAtomics) return false;
if (requested.shaderTessellationAndGeometryPointSize && !supported.shaderTessellationAndGeometryPointSize) return false;
if (requested.shaderImageGatherExtended && !supported.shaderImageGatherExtended) return false;
if (requested.shaderStorageImageExtendedFormats && !supported.shaderStorageImageExtendedFormats) return false;
if (requested.shaderStorageImageMultisample && !supported.shaderStorageImageMultisample) return false;
if (requested.shaderStorageImageReadWithoutFormat && !supported.shaderStorageImageReadWithoutFormat) return false;
if (requested.shaderStorageImageWriteWithoutFormat && !supported.shaderStorageImageWriteWithoutFormat) return false;
if (requested.shaderUniformBufferArrayDynamicIndexing && !supported.shaderUniformBufferArrayDynamicIndexing) return false;
if (requested.shaderSampledImageArrayDynamicIndexing && !supported.shaderSampledImageArrayDynamicIndexing) return false;
if (requested.shaderStorageBufferArrayDynamicIndexing && !supported.shaderStorageBufferArrayDynamicIndexing) return false;
if (requested.shaderStorageImageArrayDynamicIndexing && !supported.shaderStorageImageArrayDynamicIndexing) return false;
if (requested.shaderClipDistance && !supported.shaderClipDistance) return false;
if (requested.shaderCullDistance && !supported.shaderCullDistance) return false;
if (requested.shaderFloat64 && !supported.shaderFloat64) return false;
if (requested.shaderInt64 && !supported.shaderInt64) return false;
if (requested.shaderInt16 && !supported.shaderInt16) return false;
if (requested.shaderResourceResidency && !supported.shaderResourceResidency) return false;
if (requested.shaderResourceMinLod && !supported.shaderResourceMinLod) return false;
if (requested.sparseBinding && !supported.sparseBinding) return false;
if (requested.sparseResidencyBuffer && !supported.sparseResidencyBuffer) return false;
if (requested.sparseResidencyImage2D && !supported.sparseResidencyImage2D) return false;
if (requested.sparseResidencyImage3D && !supported.sparseResidencyImage3D) return false;
if (requested.sparseResidency2Samples && !supported.sparseResidency2Samples) return false;
if (requested.sparseResidency4Samples && !supported.sparseResidency4Samples) return false;
if (requested.sparseResidency8Samples && !supported.sparseResidency8Samples) return false;
if (requested.sparseResidency16Samples && !supported.sparseResidency16Samples) return false;
if (requested.sparseResidencyAliased && !supported.sparseResidencyAliased) return false;
if (requested.variableMultisampleRate && !supported.variableMultisampleRate) return false;
if (requested.inheritedQueries && !supported.inheritedQueries) return false;
// Should only be false if extension_supported was unable to be filled out, due to the
// physical device not supporting vkGetPhysicalDeviceFeatures2 in any capacity.
if (extension_requested.size() != extension_supported.size()) {
return false;
}
for (size_t i = 0; i < extension_requested.size() && i < extension_supported.size(); ++i) {
auto res = GenericFeaturesPNextNode::match(extension_requested[i], extension_supported[i]);
if (!res) return false;
}
return true;
}
// clang-format on
// Finds the first queue which supports the desired operations. Returns QUEUE_INDEX_MAX_VALUE if none is found
uint32_t get_first_queue_index(std::vector<VkQueueFamilyProperties> const &families, VkQueueFlags desired_flags) {
for (uint32_t i = 0; i < static_cast<uint32_t>(families.size()); i++) {
if ((families[i].queueFlags & desired_flags) == desired_flags) return i;
}
return QUEUE_INDEX_MAX_VALUE;
}
// Finds the queue which is separate from the graphics queue and has the desired flag and not the
// undesired flag, but will select it if no better options are available compute support. Returns
// QUEUE_INDEX_MAX_VALUE if none is found.
uint32_t get_separate_queue_index(
std::vector<VkQueueFamilyProperties> const &families, VkQueueFlags desired_flags, VkQueueFlags undesired_flags) {
uint32_t index = QUEUE_INDEX_MAX_VALUE;
for (uint32_t i = 0; i < static_cast<uint32_t>(families.size()); i++) {
if ((families[i].queueFlags & desired_flags) == desired_flags && ((families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) {
if ((families[i].queueFlags & undesired_flags) == 0) {
return i;
} else {
index = i;
}
}
}
return index;
}
// finds the first queue which supports only the desired flag (not graphics or transfer). Returns QUEUE_INDEX_MAX_VALUE if none is found.
uint32_t get_dedicated_queue_index(
std::vector<VkQueueFamilyProperties> const &families, VkQueueFlags desired_flags, VkQueueFlags undesired_flags) {
for (uint32_t i = 0; i < static_cast<uint32_t>(families.size()); i++) {
if ((families[i].queueFlags & desired_flags) == desired_flags &&
(families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0 && (families[i].queueFlags & undesired_flags) == 0)
return i;
}
return QUEUE_INDEX_MAX_VALUE;
}
// finds the first queue which supports presenting. returns QUEUE_INDEX_MAX_VALUE if none is found
uint32_t get_present_queue_index(
VkPhysicalDevice const phys_device, VkSurfaceKHR const surface, std::vector<VkQueueFamilyProperties> const &families) {
for (uint32_t i = 0; i < static_cast<uint32_t>(families.size()); i++) {
VkBool32 presentSupport = false;
if (surface != VK_NULL_HANDLE) {
VkResult res = detail::vulkan_functions().fp_vkGetPhysicalDeviceSurfaceSupportKHR(phys_device, i, surface, &presentSupport);
if (res != VK_SUCCESS) return QUEUE_INDEX_MAX_VALUE; // TODO: determine if this should fail another way
}
if (presentSupport == VK_TRUE) return i;
}
return QUEUE_INDEX_MAX_VALUE;
}
} // namespace detail
PhysicalDevice PhysicalDeviceSelector::populate_device_details(VkPhysicalDevice vk_phys_device,
std::vector<detail::GenericFeaturesPNextNode> const &src_extended_features_chain) const {
PhysicalDevice physical_device{};
physical_device.physical_device = vk_phys_device;
physical_device.surface = instance_info.surface;
physical_device.defer_surface_initialization = criteria.defer_surface_initialization;
physical_device.instance_version = instance_info.version;
auto queue_families = detail::get_vector_noerror<VkQueueFamilyProperties>(
detail::vulkan_functions().fp_vkGetPhysicalDeviceQueueFamilyProperties, vk_phys_device);
physical_device.queue_families = queue_families;