forked from GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVulkanSample.cpp
2722 lines (2333 loc) · 109 KB
/
VulkanSample.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
//
// Copyright (c) 2017-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// 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.
//
#ifdef _WIN32
#include "SparseBindingTest.h"
#include "Tests.h"
#include "VmaUsage.h"
#include "Common.h"
#include <atomic>
#include <Shlwapi.h>
#include <unordered_set>
#pragma comment(lib, "shlwapi.lib")
static const char* const SHADER_PATH1 = "./Shaders/";
static const char* const SHADER_PATH2 = "../bin/";
static const wchar_t* const WINDOW_CLASS_NAME = L"VULKAN_MEMORY_ALLOCATOR_SAMPLE";
static const char* const VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation";
static const char* const APP_TITLE_A = "Vulkan Memory Allocator Sample 3.2.1";
static const wchar_t* const APP_TITLE_W = L"Vulkan Memory Allocator Sample 3.2.1";
static const bool VSYNC = true;
static const uint32_t COMMAND_BUFFER_COUNT = 2;
static void* const CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA = (void*)(intptr_t)43564544;
static const bool USE_CUSTOM_CPU_ALLOCATION_CALLBACKS = true;
enum class ExitCode : int
{
GPUList = 2,
Help = 1,
Success = 0,
RuntimeError = -1,
CommandLineError = -2,
};
VkPhysicalDevice g_hPhysicalDevice;
VkDevice g_hDevice;
VmaAllocator g_hAllocator;
VkInstance g_hVulkanInstance;
bool g_EnableValidationLayer = true;
bool VK_KHR_get_memory_requirements2_enabled = false;
bool VK_KHR_get_physical_device_properties2_enabled = false;
bool VK_KHR_dedicated_allocation_enabled = false;
bool VK_KHR_bind_memory2_enabled = false;
bool VK_EXT_memory_budget_enabled = false;
bool VK_AMD_device_coherent_memory_enabled = false;
bool VK_KHR_buffer_device_address_enabled = false;
bool VK_EXT_memory_priority_enabled = false;
bool VK_EXT_debug_utils_enabled = false;
bool VK_KHR_maintenance5_enabled = false;
bool VK_KHR_external_memory_win32_enabled = false;
bool g_SparseBindingEnabled = false;
// # Pointers to functions from extensions
PFN_vkGetBufferDeviceAddressKHR g_vkGetBufferDeviceAddressKHR;
static HINSTANCE g_hAppInstance;
static HWND g_hWnd;
static LONG g_SizeX = 1280, g_SizeY = 720;
static VkSurfaceKHR g_hSurface;
static VkQueue g_hPresentQueue;
static VkSurfaceFormatKHR g_SurfaceFormat;
static VkExtent2D g_Extent;
static VkSwapchainKHR g_hSwapchain;
static std::vector<VkImage> g_SwapchainImages;
static std::vector<VkImageView> g_SwapchainImageViews;
static std::vector<VkFramebuffer> g_Framebuffers;
static VkCommandPool g_hCommandPool;
static VkCommandBuffer g_MainCommandBuffers[COMMAND_BUFFER_COUNT];
static VkFence g_MainCommandBufferExecutedFences[COMMAND_BUFFER_COUNT];
VkFence g_ImmediateFence;
static uint32_t g_NextCommandBufferIndex;
// Notice we need as many semaphores as there are swapchain images
static std::vector<VkSemaphore> g_hImageAvailableSemaphores;
static std::vector<VkSemaphore> g_hRenderFinishedSemaphores;
static uint32_t g_SwapchainImageCount = 0;
static uint32_t g_SwapchainImageIndex = 0;
static uint32_t g_GraphicsQueueFamilyIndex = UINT_MAX;
static uint32_t g_PresentQueueFamilyIndex = UINT_MAX;
static uint32_t g_SparseBindingQueueFamilyIndex = UINT_MAX;
static VkDescriptorSetLayout g_hDescriptorSetLayout;
static VkDescriptorPool g_hDescriptorPool;
static VkDescriptorSet g_hDescriptorSet; // Automatically destroyed with m_DescriptorPool.
static VkSampler g_hSampler;
static VkFormat g_DepthFormat;
static VkImage g_hDepthImage;
static VmaAllocation g_hDepthImageAlloc;
static VkImageView g_hDepthImageView;
static VkSurfaceCapabilitiesKHR g_SurfaceCapabilities;
static std::vector<VkSurfaceFormatKHR> g_SurfaceFormats;
static std::vector<VkPresentModeKHR> g_PresentModes;
static const VkDebugUtilsMessageSeverityFlagsEXT DEBUG_UTILS_MESSENGER_MESSAGE_SEVERITY =
//VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
//VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
static const VkDebugUtilsMessageTypeFlagsEXT DEBUG_UTILS_MESSENGER_MESSAGE_TYPE =
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
static PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT_Func;
static PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT_Func;
static PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT_Func;
static VkQueue g_hGraphicsQueue;
VkQueue g_hSparseBindingQueue;
VkCommandBuffer g_hTemporaryCommandBuffer;
static VkPipelineLayout g_hPipelineLayout;
static VkRenderPass g_hRenderPass;
static VkPipeline g_hPipeline;
static VkBuffer g_hVertexBuffer;
static VmaAllocation g_hVertexBufferAlloc;
static VkBuffer g_hIndexBuffer;
static VmaAllocation g_hIndexBufferAlloc;
static uint32_t g_VertexCount;
static uint32_t g_IndexCount;
static VkImage g_hTextureImage;
static VmaAllocation g_hTextureImageAlloc;
static VkImageView g_hTextureImageView;
static std::atomic_uint32_t g_CpuAllocCount;
static void* CustomCpuAllocation(
void* pUserData, size_t size, size_t alignment,
VkSystemAllocationScope allocationScope)
{
assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
void* const result = _aligned_malloc(size, alignment);
if(result)
{
++g_CpuAllocCount;
}
return result;
}
static void* CustomCpuReallocation(
void* pUserData, void* pOriginal, size_t size, size_t alignment,
VkSystemAllocationScope allocationScope)
{
assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
void* const result = _aligned_realloc(pOriginal, size, alignment);
if(pOriginal && !result)
{
--g_CpuAllocCount;
}
else if(!pOriginal && result)
{
++g_CpuAllocCount;
}
return result;
}
static void CustomCpuFree(void* pUserData, void* pMemory)
{
assert(pUserData == CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA);
if(pMemory)
{
const uint32_t oldAllocCount = g_CpuAllocCount.fetch_sub(1);
TEST(oldAllocCount > 0);
_aligned_free(pMemory);
}
}
static const VkAllocationCallbacks g_CpuAllocationCallbacks = {
CUSTOM_CPU_ALLOCATION_CALLBACK_USER_DATA, // pUserData
&CustomCpuAllocation, // pfnAllocation
&CustomCpuReallocation, // pfnReallocation
&CustomCpuFree // pfnFree
};
const VkAllocationCallbacks* g_Allocs;
struct GPUSelection
{
uint32_t Index = UINT32_MAX;
std::wstring Substring;
};
class VulkanUsage
{
public:
void Init();
~VulkanUsage();
void PrintPhysicalDeviceList() const;
// If failed, returns VK_NULL_HANDLE.
VkPhysicalDevice SelectPhysicalDevice(const GPUSelection& GPUSelection) const;
private:
VkDebugUtilsMessengerEXT m_DebugUtilsMessenger = VK_NULL_HANDLE;
void RegisterDebugCallbacks();
static bool IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName);
};
struct CommandLineParameters
{
bool m_Help = false;
bool m_List = false;
bool m_Test = false;
bool m_TestSparseBinding = false;
GPUSelection m_GPUSelection;
bool Parse(int argc, wchar_t** argv)
{
for(int i = 1; i < argc; ++i)
{
if(_wcsicmp(argv[i], L"-h") == 0 || _wcsicmp(argv[i], L"--Help") == 0)
{
m_Help = true;
}
else if(_wcsicmp(argv[i], L"-l") == 0 || _wcsicmp(argv[i], L"--List") == 0)
{
m_List = true;
}
else if((_wcsicmp(argv[i], L"-g") == 0 || _wcsicmp(argv[i], L"--GPU") == 0) && i + 1 < argc)
{
m_GPUSelection.Substring = argv[i + 1];
++i;
}
else if((_wcsicmp(argv[i], L"-i") == 0 || _wcsicmp(argv[i], L"--GPUIndex") == 0) && i + 1 < argc)
{
m_GPUSelection.Index = _wtoi(argv[i + 1]);
++i;
}
else if (_wcsicmp(argv[i], L"-t") == 0 || _wcsicmp(argv[i], L"--Test") == 0)
{
m_Test = true;
}
else if (_wcsicmp(argv[i], L"-s") == 0 || _wcsicmp(argv[i], L"--TestSparseBinding") == 0)
{
m_TestSparseBinding = true;
}
else
return false;
}
return true;
}
} g_CommandLineParameters;
void SetDebugUtilsObjectName(VkObjectType type, uint64_t handle, const std::string &name)
{
if (vkSetDebugUtilsObjectNameEXT_Func == nullptr)
return;
VkDebugUtilsObjectNameInfoEXT info = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT };
info.objectType = type;
info.objectHandle = handle;
info.pObjectName = name.c_str();
ERR_GUARD_VULKAN( vkSetDebugUtilsObjectNameEXT_Func(g_hDevice, &info) );
}
void BeginSingleTimeCommands()
{
VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
cmdBufBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
ERR_GUARD_VULKAN( vkBeginCommandBuffer(g_hTemporaryCommandBuffer, &cmdBufBeginInfo) );
}
void EndSingleTimeCommands()
{
ERR_GUARD_VULKAN( vkEndCommandBuffer(g_hTemporaryCommandBuffer) );
SetDebugUtilsObjectName(VK_OBJECT_TYPE_COMMAND_BUFFER, reinterpret_cast<std::uint64_t>(g_hTemporaryCommandBuffer), "g_hTemporaryCommandBuffer");
VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &g_hTemporaryCommandBuffer;
ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) );
ERR_GUARD_VULKAN( vkQueueWaitIdle(g_hGraphicsQueue) );
}
void LoadShader(std::vector<char>& out, const char* fileName)
{
std::ifstream file(std::string(SHADER_PATH1) + fileName, std::ios::ate | std::ios::binary);
if(file.is_open() == false)
file.open(std::string(SHADER_PATH2) + fileName, std::ios::ate | std::ios::binary);
assert(file.is_open());
size_t fileSize = (size_t)file.tellg();
if(fileSize > 0)
{
out.resize(fileSize);
file.seekg(0);
file.read(out.data(), fileSize);
file.close();
}
else
out.clear();
}
static VkBool32 VKAPI_PTR MyDebugReportCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
assert(pCallbackData && pCallbackData->pMessageIdName && pCallbackData->pMessage);
switch(messageSeverity)
{
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
SetConsoleColor(CONSOLE_COLOR::WARNING);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
SetConsoleColor(CONSOLE_COLOR::ERROR_);
break;
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
SetConsoleColor(CONSOLE_COLOR::NORMAL);
break;
default: // VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT
SetConsoleColor(CONSOLE_COLOR::INFO);
}
printf("%s \xBA %s\n", pCallbackData->pMessageIdName, pCallbackData->pMessage);
SetConsoleColor(CONSOLE_COLOR::NORMAL);
if(messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT ||
messageSeverity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
{
OutputDebugStringA(pCallbackData->pMessage);
OutputDebugStringA("\n");
}
return VK_FALSE;
}
static VkSurfaceFormatKHR ChooseSurfaceFormat()
{
assert(!g_SurfaceFormats.empty());
if((g_SurfaceFormats.size() == 1) && (g_SurfaceFormats[0].format == VK_FORMAT_UNDEFINED))
{
VkSurfaceFormatKHR result = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
return result;
}
for(const auto& format : g_SurfaceFormats)
{
if((format.format == VK_FORMAT_B8G8R8A8_UNORM) &&
(format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
{
return format;
}
}
return g_SurfaceFormats[0];
}
VkPresentModeKHR ChooseSwapPresentMode()
{
VkPresentModeKHR preferredMode = VSYNC ? VK_PRESENT_MODE_MAILBOX_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
if(std::find(g_PresentModes.begin(), g_PresentModes.end(), preferredMode) !=
g_PresentModes.end())
{
return preferredMode;
}
return VK_PRESENT_MODE_FIFO_KHR;
}
static VkExtent2D ChooseSwapExtent()
{
if(g_SurfaceCapabilities.currentExtent.width != UINT_MAX)
return g_SurfaceCapabilities.currentExtent;
VkExtent2D result = {
std::max(g_SurfaceCapabilities.minImageExtent.width,
std::min(g_SurfaceCapabilities.maxImageExtent.width, (uint32_t)g_SizeX)),
std::max(g_SurfaceCapabilities.minImageExtent.height,
std::min(g_SurfaceCapabilities.maxImageExtent.height, (uint32_t)g_SizeY)) };
return result;
}
static constexpr uint32_t GetVulkanApiVersion()
{
#if VMA_VULKAN_VERSION == 1003000
return VK_API_VERSION_1_3;
#elif VMA_VULKAN_VERSION == 1002000
return VK_API_VERSION_1_2;
#elif VMA_VULKAN_VERSION == 1001000
return VK_API_VERSION_1_1;
#elif VMA_VULKAN_VERSION == 1000000
return VK_API_VERSION_1_0;
#else
#error Invalid VMA_VULKAN_VERSION.
return UINT32_MAX;
#endif
}
void VulkanUsage::Init()
{
g_hAppInstance = (HINSTANCE)GetModuleHandle(NULL);
if(USE_CUSTOM_CPU_ALLOCATION_CALLBACKS)
{
g_Allocs = &g_CpuAllocationCallbacks;
}
uint32_t instanceLayerPropCount = 0;
ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, nullptr) );
std::vector<VkLayerProperties> instanceLayerProps(instanceLayerPropCount);
if(instanceLayerPropCount > 0)
{
ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, instanceLayerProps.data()) );
}
if(g_EnableValidationLayer)
{
if(IsLayerSupported(instanceLayerProps.data(), instanceLayerProps.size(), VALIDATION_LAYER_NAME) == false)
{
wprintf(L"Layer \"%hs\" not supported.", VALIDATION_LAYER_NAME);
g_EnableValidationLayer = false;
}
}
uint32_t availableInstanceExtensionCount = 0;
ERR_GUARD_VULKAN( vkEnumerateInstanceExtensionProperties(nullptr, &availableInstanceExtensionCount, nullptr) );
std::vector<VkExtensionProperties> availableInstanceExtensions(availableInstanceExtensionCount);
if(availableInstanceExtensionCount > 0)
{
ERR_GUARD_VULKAN( vkEnumerateInstanceExtensionProperties(nullptr, &availableInstanceExtensionCount, availableInstanceExtensions.data()) );
}
std::vector<const char*> enabledInstanceExtensions;
enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
enabledInstanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
std::vector<const char*> instanceLayers;
if(g_EnableValidationLayer)
{
instanceLayers.push_back(VALIDATION_LAYER_NAME);
}
for(const auto& extensionProperties : availableInstanceExtensions)
{
if(strcmp(extensionProperties.extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == 0)
{
if(GetVulkanApiVersion() == VK_API_VERSION_1_0)
{
enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
VK_KHR_get_physical_device_properties2_enabled = true;
}
}
else if(strcmp(extensionProperties.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0)
{
enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
VK_EXT_debug_utils_enabled = true;
}
}
VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
appInfo.pApplicationName = APP_TITLE_A;
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Adam Sawicki Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = GetVulkanApiVersion();
VkInstanceCreateInfo instInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
instInfo.pApplicationInfo = &appInfo;
instInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
instInfo.ppEnabledExtensionNames = enabledInstanceExtensions.data();
instInfo.enabledLayerCount = static_cast<uint32_t>(instanceLayers.size());
instInfo.ppEnabledLayerNames = instanceLayers.data();
wprintf(L"Vulkan API version used: ");
switch(appInfo.apiVersion)
{
case VK_API_VERSION_1_0: wprintf(L"1.0\n"); break;
#ifdef VK_VERSION_1_1
case VK_API_VERSION_1_1: wprintf(L"1.1\n"); break;
#endif
#ifdef VK_VERSION_1_2
case VK_API_VERSION_1_2: wprintf(L"1.2\n"); break;
#endif
#ifdef VK_VERSION_1_3
case VK_API_VERSION_1_3: wprintf(L"1.3\n"); break;
#endif
default: assert(0);
}
ERR_GUARD_VULKAN( vkCreateInstance(&instInfo, g_Allocs, &g_hVulkanInstance) );
if(VK_EXT_debug_utils_enabled)
{
RegisterDebugCallbacks();
}
}
VulkanUsage::~VulkanUsage()
{
if(m_DebugUtilsMessenger)
{
vkDestroyDebugUtilsMessengerEXT_Func(g_hVulkanInstance, m_DebugUtilsMessenger, g_Allocs);
}
if(g_hVulkanInstance)
{
vkDestroyInstance(g_hVulkanInstance, g_Allocs);
g_hVulkanInstance = VK_NULL_HANDLE;
}
}
void VulkanUsage::PrintPhysicalDeviceList() const
{
uint32_t deviceCount = 0;
ERR_GUARD_VULKAN(vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr));
std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
if(deviceCount > 0)
{
ERR_GUARD_VULKAN(vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()));
}
for(size_t i = 0; i < deviceCount; ++i)
{
VkPhysicalDeviceProperties props = {};
vkGetPhysicalDeviceProperties(physicalDevices[i], &props);
wprintf(L"Physical device %zu: %hs\n", i, props.deviceName);
}
}
VkPhysicalDevice VulkanUsage::SelectPhysicalDevice(const GPUSelection& GPUSelection) const
{
uint32_t deviceCount = 0;
ERR_GUARD_VULKAN(vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr));
std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
if(deviceCount > 0)
{
ERR_GUARD_VULKAN(vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()));
}
if(GPUSelection.Index != UINT32_MAX)
{
// Cannot specify both index and name.
if(!GPUSelection.Substring.empty())
{
return VK_NULL_HANDLE;
}
return GPUSelection.Index < deviceCount ? physicalDevices[GPUSelection.Index] : VK_NULL_HANDLE;
}
if(!GPUSelection.Substring.empty())
{
VkPhysicalDevice result = VK_NULL_HANDLE;
std::wstring name;
for(uint32_t i = 0; i < deviceCount; ++i)
{
VkPhysicalDeviceProperties props = {};
vkGetPhysicalDeviceProperties(physicalDevices[i], &props);
if(ConvertCharsToUnicode(&name, props.deviceName, strlen(props.deviceName), CP_UTF8) &&
StrStrI(name.c_str(), GPUSelection.Substring.c_str()))
{
// Second matching device found - error.
if(result != VK_NULL_HANDLE)
{
return VK_NULL_HANDLE;
}
// First matching device found.
result = physicalDevices[i];
}
}
// Found or not, return it.
return result;
}
// Select first one.
return deviceCount > 0 ? physicalDevices[0] : VK_NULL_HANDLE;
}
void VulkanUsage::RegisterDebugCallbacks()
{
vkCreateDebugUtilsMessengerEXT_Func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
g_hVulkanInstance, "vkCreateDebugUtilsMessengerEXT");
vkDestroyDebugUtilsMessengerEXT_Func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
g_hVulkanInstance, "vkDestroyDebugUtilsMessengerEXT");
vkSetDebugUtilsObjectNameEXT_Func = (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(
g_hVulkanInstance, "vkSetDebugUtilsObjectNameEXT");
assert(vkCreateDebugUtilsMessengerEXT_Func);
assert(vkDestroyDebugUtilsMessengerEXT_Func);
assert(vkSetDebugUtilsObjectNameEXT_Func);
VkDebugUtilsMessengerCreateInfoEXT messengerCreateInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
messengerCreateInfo.messageSeverity = DEBUG_UTILS_MESSENGER_MESSAGE_SEVERITY;
messengerCreateInfo.messageType = DEBUG_UTILS_MESSENGER_MESSAGE_TYPE;
messengerCreateInfo.pfnUserCallback = MyDebugReportCallback;
ERR_GUARD_VULKAN( vkCreateDebugUtilsMessengerEXT_Func(g_hVulkanInstance, &messengerCreateInfo, g_Allocs, &m_DebugUtilsMessenger) );
}
bool VulkanUsage::IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName)
{
const VkLayerProperties* propsEnd = pProps + propCount;
return std::find_if(
pProps,
propsEnd,
[pLayerName](const VkLayerProperties& prop) -> bool {
return strcmp(pLayerName, prop.layerName) == 0;
}) != propsEnd;
}
struct Vertex
{
float pos[3];
float color[3];
float texCoord[2];
};
static void CreateMesh()
{
assert(g_hAllocator);
static Vertex vertices[] = {
// -X
{ { -1.f, -1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 0.f} },
{ { -1.f, -1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 0.f} },
{ { -1.f, 1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 1.f} },
{ { -1.f, 1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 1.f} },
// +X
{ { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 0.f} },
{ { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 0.f} },
{ { 1.f, 1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 1.f} },
{ { 1.f, 1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 1.f} },
// -Z
{ { 1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 0.f} },
{ {-1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 0.f} },
{ { 1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 1.f} },
{ {-1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 1.f} },
// +Z
{ {-1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 0.f} },
{ { 1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 0.f} },
{ {-1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 1.f} },
{ { 1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 1.f} },
// -Y
{ {-1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 0.f} },
{ { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 0.f} },
{ {-1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 1.f} },
{ { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 1.f} },
// +Y
{ { 1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 0.f} },
{ {-1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 0.f} },
{ { 1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 1.f} },
{ {-1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 1.f} },
};
static uint16_t indices[] = {
0, 1, 2, 3, USHRT_MAX,
4, 5, 6, 7, USHRT_MAX,
8, 9, 10, 11, USHRT_MAX,
12, 13, 14, 15, USHRT_MAX,
16, 17, 18, 19, USHRT_MAX,
20, 21, 22, 23, USHRT_MAX,
};
size_t vertexBufferSize = sizeof(Vertex) * _countof(vertices);
size_t indexBufferSize = sizeof(uint16_t) * _countof(indices);
g_IndexCount = (uint32_t)_countof(indices);
// Create vertex buffer
VkBufferCreateInfo vbInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
vbInfo.size = vertexBufferSize;
vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
vbInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo vbAllocCreateInfo = {};
vbAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
vbAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer stagingVertexBuffer = VK_NULL_HANDLE;
VmaAllocation stagingVertexBufferAlloc = VK_NULL_HANDLE;
VmaAllocationInfo stagingVertexBufferAllocInfo = {};
ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbAllocCreateInfo, &stagingVertexBuffer, &stagingVertexBufferAlloc, &stagingVertexBufferAllocInfo) );
memcpy(stagingVertexBufferAllocInfo.pMappedData, vertices, vertexBufferSize);
// No need to flush stagingVertexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
vbAllocCreateInfo.flags = 0;
ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbAllocCreateInfo, &g_hVertexBuffer, &g_hVertexBufferAlloc, nullptr) );
SetDebugUtilsObjectName(VK_OBJECT_TYPE_BUFFER, reinterpret_cast<std::uint64_t>(g_hVertexBuffer), "g_hVertexBuffer");
// Create index buffer
VkBufferCreateInfo ibInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
ibInfo.size = indexBufferSize;
ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
ibInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VmaAllocationCreateInfo ibAllocCreateInfo = {};
ibAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
ibAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer stagingIndexBuffer = VK_NULL_HANDLE;
VmaAllocation stagingIndexBufferAlloc = VK_NULL_HANDLE;
VmaAllocationInfo stagingIndexBufferAllocInfo = {};
ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibAllocCreateInfo, &stagingIndexBuffer, &stagingIndexBufferAlloc, &stagingIndexBufferAllocInfo) );
memcpy(stagingIndexBufferAllocInfo.pMappedData, indices, indexBufferSize);
// No need to flush stagingIndexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
ibAllocCreateInfo.flags = 0;
ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibAllocCreateInfo, &g_hIndexBuffer, &g_hIndexBufferAlloc, nullptr) );
SetDebugUtilsObjectName(VK_OBJECT_TYPE_BUFFER, reinterpret_cast<std::uint64_t>(g_hIndexBuffer), "g_hIndexBuffer");
// Copy buffers
BeginSingleTimeCommands();
VkBufferCopy vbCopyRegion = {};
vbCopyRegion.srcOffset = 0;
vbCopyRegion.dstOffset = 0;
vbCopyRegion.size = vbInfo.size;
vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingVertexBuffer, g_hVertexBuffer, 1, &vbCopyRegion);
VkBufferCopy ibCopyRegion = {};
ibCopyRegion.srcOffset = 0;
ibCopyRegion.dstOffset = 0;
ibCopyRegion.size = ibInfo.size;
vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingIndexBuffer, g_hIndexBuffer, 1, &ibCopyRegion);
EndSingleTimeCommands();
vmaDestroyBuffer(g_hAllocator, stagingIndexBuffer, stagingIndexBufferAlloc);
vmaDestroyBuffer(g_hAllocator, stagingVertexBuffer, stagingVertexBufferAlloc);
}
static void CreateTexture(uint32_t sizeX, uint32_t sizeY)
{
// Create staging buffer.
const VkDeviceSize imageSize = sizeX * sizeY * 4;
VkBufferCreateInfo stagingBufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
stagingBufInfo.size = imageSize;
stagingBufInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
VmaAllocationCreateInfo stagingBufAllocCreateInfo = {};
stagingBufAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
stagingBufAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer stagingBuf = VK_NULL_HANDLE;
VmaAllocation stagingBufAlloc = VK_NULL_HANDLE;
VmaAllocationInfo stagingBufAllocInfo = {};
ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &stagingBufInfo, &stagingBufAllocCreateInfo, &stagingBuf, &stagingBufAlloc, &stagingBufAllocInfo) );
char* const pImageData = (char*)stagingBufAllocInfo.pMappedData;
uint8_t* pRowData = (uint8_t*)pImageData;
for(uint32_t y = 0; y < sizeY; ++y)
{
uint32_t* pPixelData = (uint32_t*)pRowData;
for(uint32_t x = 0; x < sizeX; ++x)
{
*pPixelData =
((x & 0x18) == 0x08 ? 0x000000FF : 0x00000000) |
((x & 0x18) == 0x10 ? 0x0000FFFF : 0x00000000) |
((y & 0x18) == 0x08 ? 0x0000FF00 : 0x00000000) |
((y & 0x18) == 0x10 ? 0x00FF0000 : 0x00000000);
++pPixelData;
}
pRowData += sizeX * 4;
}
// No need to flush stagingImage memory because CPU_ONLY memory is always HOST_COHERENT.
// Create g_hTextureImage in GPU memory.
VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = sizeX;
imageInfo.extent.height = sizeY;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.flags = 0;
VmaAllocationCreateInfo imageAllocCreateInfo = {};
imageAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
VmaAllocationInfo textureImageAllocInfo = {};
ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &imageInfo, &imageAllocCreateInfo, &g_hTextureImage, &g_hTextureImageAlloc, &textureImageAllocInfo) );
SetDebugUtilsObjectName(VK_OBJECT_TYPE_IMAGE, reinterpret_cast<std::uint64_t>(g_hTextureImage), "g_hTextureImage");
SetDebugUtilsObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, reinterpret_cast<std::uint64_t>(textureImageAllocInfo.deviceMemory), "textureImageAllocInfo.deviceMemory");
// Transition image layouts, copy image.
BeginSingleTimeCommands();
VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imgMemBarrier.subresourceRange.baseMipLevel = 0;
imgMemBarrier.subresourceRange.levelCount = 1;
imgMemBarrier.subresourceRange.baseArrayLayer = 0;
imgMemBarrier.subresourceRange.layerCount = 1;
imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
imgMemBarrier.image = g_hTextureImage;
imgMemBarrier.srcAccessMask = 0;
imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
vkCmdPipelineBarrier(
g_hTemporaryCommandBuffer,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0,
0, nullptr,
0, nullptr,
1, &imgMemBarrier);
VkBufferImageCopy region = {};
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.layerCount = 1;
region.imageExtent.width = sizeX;
region.imageExtent.height = sizeY;
region.imageExtent.depth = 1;
vkCmdCopyBufferToImage(g_hTemporaryCommandBuffer, stagingBuf, g_hTextureImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
imgMemBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
imgMemBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imgMemBarrier.image = g_hTextureImage;
imgMemBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imgMemBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
vkCmdPipelineBarrier(
g_hTemporaryCommandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
1, &imgMemBarrier);
EndSingleTimeCommands();
vmaDestroyBuffer(g_hAllocator, stagingBuf, stagingBufAlloc);
// Create ImageView
VkImageViewCreateInfo textureImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
textureImageViewInfo.image = g_hTextureImage;
textureImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
textureImageViewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
textureImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
textureImageViewInfo.subresourceRange.baseMipLevel = 0;
textureImageViewInfo.subresourceRange.levelCount = 1;
textureImageViewInfo.subresourceRange.baseArrayLayer = 0;
textureImageViewInfo.subresourceRange.layerCount = 1;
ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &textureImageViewInfo, g_Allocs, &g_hTextureImageView) );
SetDebugUtilsObjectName(VK_OBJECT_TYPE_IMAGE_VIEW, reinterpret_cast<std::uint64_t>(g_hTextureImageView), "g_hTextureImageView");
}
struct UniformBufferObject
{
mat4 ModelViewProj;
};
static VkFormat FindSupportedFormat(
const std::vector<VkFormat>& candidates,
VkImageTiling tiling,
VkFormatFeatureFlags features)
{
for (VkFormat format : candidates)
{
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(g_hPhysicalDevice, format, &props);
if ((tiling == VK_IMAGE_TILING_LINEAR) &&
((props.linearTilingFeatures & features) == features))
{
return format;
}
else if ((tiling == VK_IMAGE_TILING_OPTIMAL) &&
((props.optimalTilingFeatures & features) == features))
{
return format;
}
}
return VK_FORMAT_UNDEFINED;
}
static VkFormat FindDepthFormat()
{
std::vector<VkFormat> formats;
formats.push_back(VK_FORMAT_D32_SFLOAT);
formats.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT);
formats.push_back(VK_FORMAT_D24_UNORM_S8_UINT);
return FindSupportedFormat(
formats,
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
}
static void CreateSwapchain()
{
// Query surface formats.
ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_hPhysicalDevice, g_hSurface, &g_SurfaceCapabilities) );
uint32_t formatCount = 0;
ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, nullptr) );
g_SurfaceFormats.resize(formatCount);
ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, g_SurfaceFormats.data()) );
uint32_t presentModeCount = 0;
ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, nullptr) );
g_PresentModes.resize(presentModeCount);
ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, g_PresentModes.data()) );
// Create swap chain
g_SurfaceFormat = ChooseSurfaceFormat();
VkPresentModeKHR presentMode = ChooseSwapPresentMode();
g_Extent = ChooseSwapExtent();
g_SwapchainImageCount = g_SurfaceCapabilities.minImageCount + 1;
if((g_SurfaceCapabilities.maxImageCount > 0) &&
(g_SwapchainImageCount > g_SurfaceCapabilities.maxImageCount))
{
g_SwapchainImageCount = g_SurfaceCapabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR swapChainInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
swapChainInfo.surface = g_hSurface;
swapChainInfo.minImageCount = g_SwapchainImageCount;
swapChainInfo.imageFormat = g_SurfaceFormat.format;
swapChainInfo.imageColorSpace = g_SurfaceFormat.colorSpace;
swapChainInfo.imageExtent = g_Extent;
swapChainInfo.imageArrayLayers = 1;
swapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapChainInfo.preTransform = g_SurfaceCapabilities.currentTransform;
swapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapChainInfo.presentMode = presentMode;
swapChainInfo.clipped = VK_TRUE;
swapChainInfo.oldSwapchain = g_hSwapchain;
uint32_t queueFamilyIndices[] = { g_GraphicsQueueFamilyIndex, g_PresentQueueFamilyIndex };
if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
{
swapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapChainInfo.queueFamilyIndexCount = 2;
swapChainInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else
{
swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
VkSwapchainKHR hNewSwapchain = VK_NULL_HANDLE;
ERR_GUARD_VULKAN( vkCreateSwapchainKHR(g_hDevice, &swapChainInfo, g_Allocs, &hNewSwapchain) );
if(g_hSwapchain != VK_NULL_HANDLE)
vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, g_Allocs);
g_hSwapchain = hNewSwapchain;
SetDebugUtilsObjectName(VK_OBJECT_TYPE_SWAPCHAIN_KHR, reinterpret_cast<std::uint64_t>(g_hSwapchain), "g_hSwapchain");
// Retrieve swapchain images.
uint32_t swapchainImageCount = 0;
ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, nullptr) );
g_SwapchainImages.resize(swapchainImageCount);
ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, g_SwapchainImages.data()) );