-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy path33_vulkan_profiles.cpp
More file actions
1804 lines (1509 loc) · 66.6 KB
/
33_vulkan_profiles.cpp
File metadata and controls
1804 lines (1509 loc) · 66.6 KB
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
#include <algorithm>
#include <array>
#include <assert.h>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <optional>
#include <stdexcept>
#include <vector>
#if defined(__INTELLISENSE__) || !defined(USE_CPP20_MODULES)
# include <vulkan/vulkan_raii.hpp>
#else
import vulkan_hpp;
#endif
#include <vulkan/vulkan_profiles.hpp>
#define GLFW_INCLUDE_VULKAN // REQUIRED only for GLFW CreateWindowSurface.
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/hash.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>
constexpr uint32_t WIDTH = 800;
constexpr uint32_t HEIGHT = 600;
const std::string MODEL_PATH = "models/viking_room.obj";
const std::string TEXTURE_PATH = "textures/viking_room.png";
constexpr int MAX_FRAMES_IN_FLIGHT = 2;
// Application info structure to store profile support flags
struct AppInfo
{
bool profileSupported = false;
VpProfileProperties profile;
};
// Moved struct definitions inside the class
struct Vertex
{
glm::vec3 pos;
glm::vec3 color;
glm::vec2 texCoord;
static vk::VertexInputBindingDescription getBindingDescription()
{
return {0, sizeof(Vertex), vk::VertexInputRate::eVertex};
}
static std::array<vk::VertexInputAttributeDescription, 3> getAttributeDescriptions()
{
return {
vk::VertexInputAttributeDescription(0, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, pos)),
vk::VertexInputAttributeDescription(1, 0, vk::Format::eR32G32B32Sfloat, offsetof(Vertex, color)),
vk::VertexInputAttributeDescription(2, 0, vk::Format::eR32G32Sfloat, offsetof(Vertex, texCoord))};
}
bool operator==(const Vertex &other) const
{
return pos == other.pos && color == other.color && texCoord == other.texCoord;
}
};
template <>
struct std::hash<Vertex>
{
size_t operator()(Vertex const &vertex) const noexcept
{
return ((hash<glm::vec3>()(vertex.pos) ^ (hash<glm::vec3>()(vertex.color) << 1)) >> 1) ^ (hash<glm::vec2>()(vertex.texCoord) << 1);
}
};
struct UniformBufferObject
{
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
};
class HelloTriangleApplication
{
public:
void run()
{
initWindow();
initVulkan();
mainLoop();
cleanup();
}
private:
GLFWwindow *window = nullptr;
vk::raii::Context context;
vk::raii::Instance instance = nullptr;
vk::raii::DebugUtilsMessengerEXT debugMessenger = nullptr;
vk::raii::SurfaceKHR surface = nullptr;
vk::raii::PhysicalDevice physicalDevice = nullptr;
vk::raii::Device device = nullptr;
uint32_t queueIndex = ~0;
vk::raii::Queue queue = nullptr;
vk::raii::SwapchainKHR swapChain = nullptr;
std::vector<vk::Image> swapChainImages;
vk::SurfaceFormatKHR swapChainSurfaceFormat;
vk::Extent2D swapChainExtent;
std::vector<vk::raii::ImageView> swapChainImageViews;
vk::raii::RenderPass renderPass = nullptr;
vk::raii::DescriptorSetLayout descriptorSetLayout = nullptr;
vk::raii::PipelineLayout pipelineLayout = nullptr;
vk::raii::Pipeline graphicsPipeline = nullptr;
std::vector<vk::raii::Framebuffer> swapChainFramebuffers;
vk::raii::CommandPool commandPool = nullptr;
std::vector<vk::raii::CommandBuffer> commandBuffers;
std::vector<vk::raii::Semaphore> imageAvailableSemaphores;
std::vector<vk::raii::Semaphore> renderFinishedSemaphores;
std::vector<vk::raii::Fence> inFlightFences;
std::vector<vk::raii::Semaphore> presentCompleteSemaphore;
uint32_t frameIndex = 0;
bool framebufferResized = false;
vk::raii::Buffer vertexBuffer = nullptr;
vk::raii::DeviceMemory vertexBufferMemory = nullptr;
vk::raii::Buffer indexBuffer = nullptr;
vk::raii::DeviceMemory indexBufferMemory = nullptr;
std::vector<vk::raii::Buffer> uniformBuffers;
std::vector<vk::raii::DeviceMemory> uniformBuffersMemory;
std::vector<void *> uniformBuffersMapped;
vk::raii::DescriptorPool descriptorPool = nullptr;
std::vector<vk::raii::DescriptorSet> descriptorSets;
vk::raii::Image textureImage = nullptr;
vk::raii::DeviceMemory textureImageMemory = nullptr;
vk::raii::ImageView textureImageView = nullptr;
vk::raii::Sampler textureSampler = nullptr;
vk::raii::Image depthImage = nullptr;
vk::raii::DeviceMemory depthImageMemory = nullptr;
vk::raii::ImageView depthImageView = nullptr;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
vk::SampleCountFlagBits msaaSamples = vk::SampleCountFlagBits::e1;
vk::raii::Image colorImage = nullptr;
vk::raii::DeviceMemory colorImageMemory = nullptr;
vk::raii::ImageView colorImageView = nullptr;
// Application info to store profile support
AppInfo appInfo = {};
struct SwapChainSupportDetails
{
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
const std::vector<const char *> requiredDeviceExtension = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME};
void initWindow()
{
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan Profiles Demo", nullptr, nullptr);
glfwSetWindowUserPointer(window, this);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
static void framebufferResizeCallback(GLFWwindow *window, int, int)
{
auto app = reinterpret_cast<HelloTriangleApplication *>(glfwGetWindowUserPointer(window));
app->framebufferResized = true;
}
void initVulkan()
{
createInstance();
setupDebugMessenger();
createSurface();
pickPhysicalDevice();
checkFeatureSupport();
createLogicalDevice();
createSwapChain();
createImageViews();
// Create render pass only if not using dynamic rendering
if (!appInfo.profileSupported)
{
createRenderPass();
}
createDescriptorSetLayout();
createGraphicsPipeline();
// Create framebuffers only if not using dynamic rendering
if (!appInfo.profileSupported)
{
createFramebuffers();
}
createCommandPool();
createColorResources();
createDepthResources();
createTextureImage();
createTextureImageView();
createTextureSampler();
loadModel();
createVertexBuffer();
createIndexBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
}
void mainLoop()
{
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
drawFrame();
}
device.waitIdle();
}
void cleanupSwapChain()
{
swapChainFramebuffers.clear();
swapChainImageViews.clear();
// Semaphores tied to swapchain image indices need to be rebuilt on resize
presentCompleteSemaphore.clear();
for (auto &imageView : swapChainImageViews)
{
imageView = nullptr;
}
swapChainImageViews.clear();
swapChain = nullptr;
}
void cleanup()
{
glfwDestroyWindow(window);
glfwTerminate();
}
void recreateSwapChain()
{
int width = 0, height = 0;
glfwGetFramebufferSize(window, &width, &height);
while (width == 0 || height == 0)
{
glfwGetFramebufferSize(window, &width, &height);
glfwWaitEvents();
}
device.waitIdle();
cleanupSwapChain();
createSwapChain();
createImageViews();
// Recreate traditional render pass and framebuffers if not using profiles
if (!appInfo.profileSupported)
{
createRenderPass();
createFramebuffers();
}
createColorResources();
createDepthResources();
// Recreate per-swapchain-image present semaphores after resize
presentCompleteSemaphore.reserve(swapChainImages.size());
vk::SemaphoreCreateInfo semaphoreInfo{};
for (size_t i = 0; i < swapChainImages.size(); ++i)
{
presentCompleteSemaphore.push_back(device.createSemaphore(semaphoreInfo));
}
}
void createInstance()
{
constexpr vk::ApplicationInfo appInfo{
.pApplicationName = "Vulkan Profiles Demo",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "No Engine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = vk::ApiVersion14};
auto extensions = getRequiredInstanceExtensions();
vk::InstanceCreateInfo createInfo{
.pApplicationInfo = &appInfo,
.enabledExtensionCount = static_cast<uint32_t>(extensions.size()),
.ppEnabledExtensionNames = extensions.data()};
instance = vk::raii::Instance(context, createInfo);
}
void setupDebugMessenger()
{
// Always set up the debug messenger
// It will only be used if validation layers are enabled via vulkanconfig
vk::DebugUtilsMessageSeverityFlagsEXT severityFlags(
vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError);
vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags(
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation);
vk::DebugUtilsMessengerCreateInfoEXT debugUtilsMessengerCreateInfoEXT{
.messageSeverity = severityFlags,
.messageType = messageTypeFlags,
.pfnUserCallback = &debugCallback};
try
{
debugMessenger = instance.createDebugUtilsMessengerEXT(debugUtilsMessengerCreateInfoEXT);
}
catch (vk::SystemError &err)
{
// If the debug utils extension is not available, this will fail
// That's okay, it just means validation layers aren't enabled
std::cout << "Debug messenger not available. Validation layers may not be enabled." << std::endl;
}
}
void createSurface()
{
VkSurfaceKHR _surface;
if (glfwCreateWindowSurface(*instance, window, nullptr, &_surface) != 0)
{
throw std::runtime_error("failed to create window surface!");
}
surface = vk::raii::SurfaceKHR(instance, _surface);
}
bool isDeviceSuitable(vk::raii::PhysicalDevice const &physicalDevice)
{
// Check if the physicalDevice supports the Vulkan 1.3 API version
bool supportsVulkan1_3 = physicalDevice.getProperties().apiVersion >= VK_API_VERSION_1_3;
// Check if any of the queue families support graphics operations
auto queueFamilies = physicalDevice.getQueueFamilyProperties();
bool supportsGraphics = std::ranges::any_of(queueFamilies, [](auto const &qfp) { return !!(qfp.queueFlags & vk::QueueFlagBits::eGraphics); });
// Check if all required physicalDevice extensions are available
auto availableDeviceExtensions = physicalDevice.enumerateDeviceExtensionProperties();
bool supportsAllRequiredExtensions =
std::ranges::all_of(requiredDeviceExtension,
[&availableDeviceExtensions](auto const &requiredDeviceExtension) {
return std::ranges::any_of(availableDeviceExtensions,
[requiredDeviceExtension](auto const &availableDeviceExtension) { return strcmp(availableDeviceExtension.extensionName, requiredDeviceExtension) == 0; });
});
// Return true if the physicalDevice meets all the criteria
return supportsVulkan1_3 && supportsGraphics && supportsAllRequiredExtensions;
}
void pickPhysicalDevice()
{
std::vector<vk::raii::PhysicalDevice> physicalDevices = instance.enumeratePhysicalDevices();
auto const devIter = std::ranges::find_if(physicalDevices, [&](auto const &physicalDevice) { return isDeviceSuitable(physicalDevice); });
if (devIter == physicalDevices.end())
{
throw std::runtime_error("failed to find a suitable GPU!");
}
physicalDevice = *devIter;
msaaSamples = getMaxUsableSampleCount();
// Print device information
vk::PhysicalDeviceProperties deviceProperties = physicalDevice.getProperties();
std::cout << "Selected GPU: " << deviceProperties.deviceName << std::endl;
std::cout << "API Version: " << VK_VERSION_MAJOR(deviceProperties.apiVersion) << "."
<< VK_VERSION_MINOR(deviceProperties.apiVersion) << "."
<< VK_VERSION_PATCH(deviceProperties.apiVersion) << std::endl;
}
void checkFeatureSupport()
{
// Define the KHR roadmap 2022 profile - more widely supported than 2024
appInfo.profile = {
VP_KHR_ROADMAP_2022_NAME,
VP_KHR_ROADMAP_2022_SPEC_VERSION};
// Check if the profile is supported
VkBool32 supported = VK_FALSE;
VkResult result = vpGetPhysicalDeviceProfileSupport(
*instance,
*physicalDevice,
&appInfo.profile,
&supported);
if (result == VK_SUCCESS && supported == VK_TRUE)
{
appInfo.profileSupported = true;
std::cout << "Using KHR roadmap 2022 profile" << std::endl;
}
else
{
appInfo.profileSupported = false;
std::cout << "Falling back to traditional rendering (profile not supported)" << std::endl;
// If we wanted to implement fallback, we would call detectFeatureSupport() here
// But for this example, we'll just use traditional rendering if the profile isn't supported
}
}
void createLogicalDevice()
{
std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice.getQueueFamilyProperties();
// get the first index into queueFamilyProperties which supports both graphics and present
for (uint32_t qfpIndex = 0; qfpIndex < queueFamilyProperties.size(); qfpIndex++)
{
if ((queueFamilyProperties[qfpIndex].queueFlags & vk::QueueFlagBits::eGraphics) &&
physicalDevice.getSurfaceSupportKHR(qfpIndex, *surface))
{
// found a queue family that supports both graphics and present
queueIndex = qfpIndex;
break;
}
}
if (queueIndex == ~0)
{
throw std::runtime_error("Could not find a queue for graphics and present -> terminating");
}
float queuePriority = 0.5f;
vk::DeviceQueueCreateInfo deviceQueueCreateInfo{.queueFamilyIndex = queueIndex, .queueCount = 1, .pQueuePriorities = &queuePriority};
if (appInfo.profileSupported)
{
// Create device with Best Practices profile
// Enable required features
vk::PhysicalDeviceFeatures2 features2;
vk::PhysicalDeviceFeatures deviceFeatures{};
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.sampleRateShading = VK_TRUE;
features2.features = deviceFeatures;
// Enable dynamic rendering
vk::PhysicalDeviceDynamicRenderingFeatures dynamicRenderingFeatures;
dynamicRenderingFeatures.dynamicRendering = VK_TRUE;
features2.pNext = &dynamicRenderingFeatures;
// Create a vk::DeviceCreateInfo with the required features
vk::DeviceCreateInfo vkDeviceCreateInfo{
.pNext = &features2,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &deviceQueueCreateInfo,
.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtension.size()),
.ppEnabledExtensionNames = requiredDeviceExtension.data()};
// Create the device with the vk::DeviceCreateInfo
device = vk::raii::Device(physicalDevice, vkDeviceCreateInfo);
std::cout << "Created logical device using KHR roadmap 2022 profile" << std::endl;
}
else
{
// Fallback to manual device creation
vk::PhysicalDeviceFeatures deviceFeatures{};
deviceFeatures.samplerAnisotropy = VK_TRUE;
deviceFeatures.sampleRateShading = VK_TRUE;
vk::DeviceCreateInfo createInfo{
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &deviceQueueCreateInfo,
.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtension.size()),
.ppEnabledExtensionNames = requiredDeviceExtension.data(),
.pEnabledFeatures = &deviceFeatures};
device = vk::raii::Device(physicalDevice, createInfo);
std::cout << "Created logical device using manual feature selection" << std::endl;
}
queue = device.getQueue(queueIndex, 0);
}
void createSwapChain()
{
vk::SurfaceCapabilitiesKHR surfaceCapabilities = physicalDevice.getSurfaceCapabilitiesKHR(*surface);
swapChainExtent = chooseSwapExtent(surfaceCapabilities);
uint32_t minImageCount = chooseSwapMinImageCount(surfaceCapabilities);
std::vector<vk::SurfaceFormatKHR> availableFormats = physicalDevice.getSurfaceFormatsKHR(*surface);
swapChainSurfaceFormat = chooseSwapSurfaceFormat(availableFormats);
std::vector<vk::PresentModeKHR> availablePresentModes = physicalDevice.getSurfacePresentModesKHR(*surface);
vk::PresentModeKHR presentMode = chooseSwapPresentMode(availablePresentModes);
vk::SwapchainCreateInfoKHR swapChainCreateInfo{.surface = *surface,
.minImageCount = minImageCount,
.imageFormat = swapChainSurfaceFormat.format,
.imageColorSpace = swapChainSurfaceFormat.colorSpace,
.imageExtent = swapChainExtent,
.imageArrayLayers = 1,
.imageUsage = vk::ImageUsageFlagBits::eColorAttachment,
.imageSharingMode = vk::SharingMode::eExclusive,
.preTransform = surfaceCapabilities.currentTransform,
.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque,
.presentMode = presentMode,
.clipped = true};
swapChain = device.createSwapchainKHR(swapChainCreateInfo);
swapChainImages = swapChain.getImages();
}
void createImageViews()
{
assert(swapChainImageViews.empty());
swapChainImageViews.reserve(swapChainImages.size());
for (const auto &image : swapChainImages)
{
swapChainImageViews.push_back(createImageView(image, swapChainSurfaceFormat.format, vk::ImageAspectFlagBits::eColor, 1));
}
}
void createRenderPass()
{
// This is only called if the Best Practices profile is not supported
// or if dynamic rendering is not available
vk::AttachmentDescription colorAttachment{
.format = swapChainSurfaceFormat.format,
.samples = msaaSamples,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.stencilLoadOp = vk::AttachmentLoadOp::eDontCare,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal};
vk::AttachmentDescription depthAttachment{
.format = findDepthFormat(),
.samples = msaaSamples,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eDontCare,
.stencilLoadOp = vk::AttachmentLoadOp::eDontCare,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal};
vk::AttachmentDescription colorAttachmentResolve{
.format = swapChainSurfaceFormat.format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eDontCare,
.storeOp = vk::AttachmentStoreOp::eStore,
.stencilLoadOp = vk::AttachmentLoadOp::eDontCare,
.stencilStoreOp = vk::AttachmentStoreOp::eDontCare,
.initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = vk::ImageLayout::ePresentSrcKHR};
vk::AttachmentReference colorAttachmentRef{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal};
vk::AttachmentReference depthAttachmentRef{
.attachment = 1,
.layout = vk::ImageLayout::eDepthStencilAttachmentOptimal};
vk::AttachmentReference colorAttachmentResolveRef{
.attachment = 2,
.layout = vk::ImageLayout::eColorAttachmentOptimal};
vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAttachmentRef,
.pResolveAttachments = &colorAttachmentResolveRef,
.pDepthStencilAttachment = &depthAttachmentRef};
vk::SubpassDependency dependency{
.srcSubpass = VK_SUBPASS_EXTERNAL,
.dstSubpass = 0,
.srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
.dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite};
std::array<vk::AttachmentDescription, 3> attachments = {colorAttachment, depthAttachment, colorAttachmentResolve};
vk::RenderPassCreateInfo renderPassInfo{
.attachmentCount = static_cast<uint32_t>(attachments.size()),
.pAttachments = attachments.data(),
.subpassCount = 1,
.pSubpasses = &subpass,
.dependencyCount = 1,
.pDependencies = &dependency};
renderPass = device.createRenderPass(renderPassInfo);
}
void createDescriptorSetLayout()
{
vk::DescriptorSetLayoutBinding uboLayoutBinding{
.binding = 0,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex};
vk::DescriptorSetLayoutBinding samplerLayoutBinding{
.binding = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eFragment};
std::array<vk::DescriptorSetLayoutBinding, 2> bindings = {uboLayoutBinding, samplerLayoutBinding};
vk::DescriptorSetLayoutCreateInfo layoutInfo{
.bindingCount = static_cast<uint32_t>(bindings.size()),
.pBindings = bindings.data()};
descriptorSetLayout = device.createDescriptorSetLayout(layoutInfo);
}
void createGraphicsPipeline()
{
auto vertShaderCode = readFile("shaders/vert.spv");
auto fragShaderCode = readFile("shaders/frag.spv");
vk::raii::ShaderModule vertShaderModule = createShaderModule(vertShaderCode);
vk::raii::ShaderModule fragShaderModule = createShaderModule(fragShaderCode);
vk::PipelineShaderStageCreateInfo vertShaderStageInfo{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertShaderModule,
.pName = "main"};
vk::PipelineShaderStageCreateInfo fragShaderStageInfo{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragShaderModule,
.pName = "main"};
vk::PipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vk::PipelineVertexInputStateCreateInfo vertexInputInfo{
.vertexBindingDescriptionCount = 1,
.pVertexBindingDescriptions = &bindingDescription,
.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()),
.pVertexAttributeDescriptions = attributeDescriptions.data()};
vk::PipelineInputAssemblyStateCreateInfo inputAssembly{
.topology = vk::PrimitiveTopology::eTriangleList,
.primitiveRestartEnable = VK_FALSE};
vk::PipelineViewportStateCreateInfo viewportState{
.viewportCount = 1,
.scissorCount = 1};
vk::PipelineRasterizationStateCreateInfo rasterizer{
.depthClampEnable = VK_FALSE,
.rasterizerDiscardEnable = VK_FALSE,
.polygonMode = vk::PolygonMode::eFill,
.cullMode = vk::CullModeFlagBits::eBack,
.frontFace = vk::FrontFace::eCounterClockwise,
.depthBiasEnable = VK_FALSE,
.lineWidth = 1.0f};
vk::PipelineMultisampleStateCreateInfo multisampling{
.rasterizationSamples = msaaSamples,
.sampleShadingEnable = VK_TRUE,
.minSampleShading = 0.2f};
vk::PipelineDepthStencilStateCreateInfo depthStencil{
.depthTestEnable = VK_TRUE,
.depthWriteEnable = VK_TRUE,
.depthCompareOp = vk::CompareOp::eLess,
.depthBoundsTestEnable = VK_FALSE,
.stencilTestEnable = VK_FALSE};
vk::PipelineColorBlendAttachmentState colorBlendAttachment{
.blendEnable = VK_FALSE,
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA};
vk::PipelineColorBlendStateCreateInfo colorBlending{
.logicOpEnable = VK_FALSE,
.logicOp = vk::LogicOp::eCopy,
.attachmentCount = 1,
.pAttachments = &colorBlendAttachment};
std::vector<vk::DynamicState> dynamicStates = {
vk::DynamicState::eViewport,
vk::DynamicState::eScissor};
vk::PipelineDynamicStateCreateInfo dynamicState{
.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size()),
.pDynamicStates = dynamicStates.data()};
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{
.setLayoutCount = 1,
.pSetLayouts = &*descriptorSetLayout};
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
// Configure pipeline based on whether we're using the KHR roadmap 2022 profile
// With the KHR roadmap 2022 profile, we can use dynamic rendering
vk::StructureChain<vk::GraphicsPipelineCreateInfo, vk::PipelineRenderingCreateInfo> pipelineCreateInfoChain = {
{.stageCount = 2,
.pStages = shaderStages,
.pVertexInputState = &vertexInputInfo,
.pInputAssemblyState = &inputAssembly,
.pViewportState = &viewportState,
.pRasterizationState = &rasterizer,
.pMultisampleState = &multisampling,
.pDepthStencilState = &depthStencil,
.pColorBlendState = &colorBlending,
.pDynamicState = &dynamicState,
.layout = pipelineLayout,
.renderPass = nullptr},
{.colorAttachmentCount = 1, .pColorAttachmentFormats = &swapChainSurfaceFormat.format, .depthAttachmentFormat = findDepthFormat()}};
if (appInfo.profileSupported)
{
std::cout << "Creating pipeline with dynamic rendering (KHR roadmap 2022 profile)" << std::endl;
}
else
{
std::cout << "Creating pipeline with traditional render pass (fallback)" << std::endl;
pipelineCreateInfoChain.unlink<vk::PipelineRenderingCreateInfo>();
pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>().renderPass = *renderPass;
}
graphicsPipeline = vk::raii::Pipeline(device, nullptr, pipelineCreateInfoChain.get<vk::GraphicsPipelineCreateInfo>());
}
void createFramebuffers()
{
// This is only called if the Best Practices profile is not supported
// or if dynamic rendering is not available
swapChainFramebuffers.reserve(swapChainImageViews.size());
for (size_t i = 0; i < swapChainImageViews.size(); i++)
{
std::array<vk::ImageView, 3> attachments = {
*colorImageView,
*depthImageView,
*swapChainImageViews[i]};
vk::FramebufferCreateInfo framebufferInfo{
.renderPass = *renderPass,
.attachmentCount = static_cast<uint32_t>(attachments.size()),
.pAttachments = attachments.data(),
.width = swapChainExtent.width,
.height = swapChainExtent.height,
.layers = 1};
swapChainFramebuffers.push_back(device.createFramebuffer(framebufferInfo));
}
}
void createCommandPool()
{
vk::CommandPoolCreateInfo poolInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queueIndex};
commandPool = device.createCommandPool(poolInfo);
}
void createColorResources()
{
vk::Format colorFormat = swapChainSurfaceFormat.format;
createImage(swapChainExtent.width, swapChainExtent.height, 1, msaaSamples, colorFormat, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eTransientAttachment | vk::ImageUsageFlagBits::eColorAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, colorImage, colorImageMemory);
colorImageView = createImageView(*colorImage, colorFormat, vk::ImageAspectFlagBits::eColor, 1);
}
void createDepthResources()
{
vk::Format depthFormat = findDepthFormat();
createImage(swapChainExtent.width, swapChainExtent.height, 1, msaaSamples, depthFormat, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eDepthStencilAttachment, vk::MemoryPropertyFlagBits::eDeviceLocal, depthImage, depthImageMemory);
depthImageView = createImageView(*depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth, 1);
}
vk::Format findSupportedFormat(const std::vector<vk::Format> &candidates, vk::ImageTiling tiling, vk::FormatFeatureFlags features)
{
for (vk::Format format : candidates)
{
vk::FormatProperties props = physicalDevice.getFormatProperties(format);
if (tiling == vk::ImageTiling::eLinear && (props.linearTilingFeatures & features) == features)
{
return format;
}
else if (tiling == vk::ImageTiling::eOptimal && (props.optimalTilingFeatures & features) == features)
{
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
vk::Format findDepthFormat()
{
return findSupportedFormat(
{vk::Format::eD32Sfloat, vk::Format::eD32SfloatS8Uint, vk::Format::eD24UnormS8Uint},
vk::ImageTiling::eOptimal,
vk::FormatFeatureFlagBits::eDepthStencilAttachment);
}
bool hasStencilComponent(vk::Format format)
{
return format == vk::Format::eD32SfloatS8Uint || format == vk::Format::eD24UnormS8Uint;
}
void createTextureImage()
{
int texWidth, texHeight, texChannels;
stbi_uc *pixels = stbi_load(TEXTURE_PATH.c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha);
vk::DeviceSize imageSize = texWidth * texHeight * 4;
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(texWidth, texHeight)))) + 1;
if (!pixels)
{
throw std::runtime_error("failed to load texture image!");
}
vk::raii::Buffer stagingBuffer = nullptr;
vk::raii::DeviceMemory stagingBufferMemory = nullptr;
createBuffer(imageSize, vk::BufferUsageFlagBits::eTransferSrc, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, stagingBuffer, stagingBufferMemory);
void *data = stagingBufferMemory.mapMemory(0, imageSize);
memcpy(data, pixels, static_cast<size_t>(imageSize));
stagingBufferMemory.unmapMemory();
stbi_image_free(pixels);
createImage(texWidth, texHeight, mipLevels, vk::SampleCountFlagBits::e1, vk::Format::eR8G8B8A8Srgb, vk::ImageTiling::eOptimal, vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, vk::MemoryPropertyFlagBits::eDeviceLocal, textureImage, textureImageMemory);
transitionImageLayout(*textureImage, vk::Format::eR8G8B8A8Srgb, vk::ImageLayout::eUndefined, vk::ImageLayout::eTransferDstOptimal, mipLevels);
copyBufferToImage(*stagingBuffer, *textureImage, static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight));
generateMipmaps(*textureImage, vk::Format::eR8G8B8A8Srgb, texWidth, texHeight, mipLevels);
}
void generateMipmaps(vk::Image image, vk::Format imageFormat, int32_t texWidth, int32_t texHeight, uint32_t mipLevels)
{
vk::FormatProperties formatProperties = physicalDevice.getFormatProperties(imageFormat);
if (!(formatProperties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImageFilterLinear))
{
throw std::runtime_error("texture image format does not support linear blitting!");
}
vk::raii::CommandBuffer commandBuffer = beginSingleTimeCommands();
vk::ImageMemoryBarrier barrier{
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
}};
int32_t mipWidth = texWidth;
int32_t mipHeight = texHeight;
for (uint32_t i = 1; i < mipLevels; i++)
{
barrier.subresourceRange.baseMipLevel = i - 1;
barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal;
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead;
commandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eTransfer,
{},
std::array<vk::MemoryBarrier, 0>{},
std::array<vk::BufferMemoryBarrier, 0>{},
std::array<vk::ImageMemoryBarrier, 1>{barrier});
vk::ImageBlit blit{
.srcSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = i - 1,
.baseArrayLayer = 0,
.layerCount = 1},
.srcOffsets = std::array<vk::Offset3D, 2>{vk::Offset3D{0, 0, 0}, vk::Offset3D{mipWidth, mipHeight, 1}},
.dstSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = i, .baseArrayLayer = 0, .layerCount = 1},
.dstOffsets = std::array<vk::Offset3D, 2>{vk::Offset3D{0, 0, 0}, vk::Offset3D{mipWidth > 1 ? mipWidth / 2 : 1, mipHeight > 1 ? mipHeight / 2 : 1, 1}}};
commandBuffer.blitImage(
image, vk::ImageLayout::eTransferSrcOptimal,
image, vk::ImageLayout::eTransferDstOptimal,
std::array<vk::ImageBlit, 1>{blit},
vk::Filter::eLinear);
barrier.oldLayout = vk::ImageLayout::eTransferSrcOptimal;
barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
commandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eFragmentShader,
{},
std::array<vk::MemoryBarrier, 0>{},
std::array<vk::BufferMemoryBarrier, 0>{},
std::array<vk::ImageMemoryBarrier, 1>{barrier});
if (mipWidth > 1)
mipWidth /= 2;
if (mipHeight > 1)
mipHeight /= 2;
}
barrier.subresourceRange.baseMipLevel = mipLevels - 1;
barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
commandBuffer.pipelineBarrier(
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eFragmentShader,
{},
std::array<vk::MemoryBarrier, 0>{},
std::array<vk::BufferMemoryBarrier, 0>{},
std::array<vk::ImageMemoryBarrier, 1>{barrier});
endSingleTimeCommands(commandBuffer);
}
vk::raii::ImageView createImageView(vk::Image image, vk::Format format, vk::ImageAspectFlags aspectFlags, uint32_t mipLevels)
{
vk::ImageViewCreateInfo viewInfo{
.image = image,
.viewType = vk::ImageViewType::e2D,
.format = format,
.subresourceRange = {
.aspectMask = aspectFlags,
.baseMipLevel = 0,
.levelCount = mipLevels,
.baseArrayLayer = 0,
.layerCount = 1}};
return device.createImageView(viewInfo);
}
void createTextureImageView()
{
textureImageView = createImageView(*textureImage, vk::Format::eR8G8B8A8Srgb, vk::ImageAspectFlagBits::eColor, 1);
}
void createTextureSampler()
{
vk::PhysicalDeviceProperties properties = physicalDevice.getProperties();
vk::SamplerCreateInfo samplerInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eLinear,
.addressModeU = vk::SamplerAddressMode::eRepeat,
.addressModeV = vk::SamplerAddressMode::eRepeat,
.addressModeW = vk::SamplerAddressMode::eRepeat,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_TRUE,
.maxAnisotropy = properties.limits.maxSamplerAnisotropy,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eAlways,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eIntOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE};
textureSampler = device.createSampler(samplerInfo);