-
Notifications
You must be signed in to change notification settings - Fork 0
/
triangle-example.cpp
1379 lines (1118 loc) · 52.2 KB
/
triangle-example.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
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <chrono>
#include <functional>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <glm/gtc/matrix_transform.hpp>
using namespace std::placeholders;
// Configuration
const uint32_t WIDTH = 640;
const uint32_t HEIGHT = 480;
const bool ENABLE_DEBUGGING = false;
const char* DEBUG_LAYER = "VK_LAYER_LUNARG_standard_validation";
// Debug callback
VkBool32 debugCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject, size_t location, int32_t msgCode, const char* pLayerPrefix, const char* pMsg, void* pUserData) {
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
std::cerr << "ERROR: [" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << std::endl;
} else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
std::cerr << "WARNING: [" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << std::endl;
}
//exit(1);
return VK_FALSE;
}
// Vertex layout
struct Vertex {
float pos[3];
float color[3];
};
bool windowResized = false;
// Note: support swap chain recreation (not only required for resized windows!)
// Note: window resize may not result in Vulkan telling that the swap chain should be recreated, should be handled explicitly!
class TriangleApplication {
public:
TriangleApplication() {
timeStart = std::chrono::high_resolution_clock::now();
}
void run() {
// Note: dynamically loading loader may be a better idea to fail gracefully when Vulkan is not supported
// Create window for Vulkan
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
window = glfwCreateWindow(WIDTH, HEIGHT, "The spinning triangle that took 1397 lines of code", nullptr, nullptr);
glfwSetWindowSizeCallback(window, TriangleApplication::onWindowResized);
// Use Vulkan
setupVulkan();
mainLoop();
cleanup(true);
}
private:
GLFWwindow* window;
VkInstance instance;
VkSurfaceKHR windowSurface;
VkPhysicalDevice physicalDevice;
VkDevice device;
VkDebugReportCallbackEXT callback;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkPhysicalDeviceMemoryProperties deviceMemoryProperties;
VkSemaphore imageAvailableSemaphore;
VkSemaphore renderingFinishedSemaphore;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
VkVertexInputBindingDescription vertexBindingDescription;
std::vector<VkVertexInputAttributeDescription> vertexAttributeDescriptions;
struct {
glm::mat4 transformationMatrix;
} uniformBufferData;
VkBuffer uniformBuffer;
VkDeviceMemory uniformBufferMemory;
VkDescriptorSetLayout descriptorSetLayout;
VkDescriptorPool descriptorPool;
VkDescriptorSet descriptorSet;
VkExtent2D swapChainExtent;
VkFormat swapChainFormat;
VkSwapchainKHR oldSwapChain;
VkSwapchainKHR swapChain;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkRenderPass renderPass;
VkPipeline graphicsPipeline;
VkPipelineLayout pipelineLayout;
VkCommandPool commandPool;
std::vector<VkCommandBuffer> graphicsCommandBuffers;
uint32_t graphicsQueueFamily;
uint32_t presentQueueFamily;
std::chrono::high_resolution_clock::time_point timeStart;
void setupVulkan() {
oldSwapChain = VK_NULL_HANDLE;
createInstance();
createDebugCallback();
createWindowSurface();
findPhysicalDevice();
checkSwapChainSupport();
findQueueFamilies();
createLogicalDevice();
createSemaphores();
createCommandPool();
createVertexBuffer();
createUniformBuffer();
createSwapChain();
createRenderPass();
createImageViews();
createFramebuffers();
createGraphicsPipeline();
createDescriptorPool();
createDescriptorSet();
createCommandBuffers();
}
void mainLoop() {
while (!glfwWindowShouldClose(window)) {
updateUniformData();
draw();
glfwPollEvents();
}
}
static void onWindowResized(GLFWwindow* window, int width, int height) {
windowResized = true;
}
void onWindowSizeChanged() {
windowResized = false;
// Only recreate objects that are affected by framebuffer size changes
cleanup(false);
createSwapChain();
createRenderPass();
createImageViews();
createFramebuffers();
createGraphicsPipeline();
createCommandBuffers();
}
void cleanup(bool fullClean) {
vkDeviceWaitIdle(device);
vkFreeCommandBuffers(device, commandPool, (uint32_t) graphicsCommandBuffers.size(), graphicsCommandBuffers.data());
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDestroyRenderPass(device, renderPass, nullptr);
for (size_t i = 0; i < swapChainImages.size(); i++) {
vkDestroyFramebuffer(device, swapChainFramebuffers[i], nullptr);
vkDestroyImageView(device, swapChainImageViews[i], nullptr);
}
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
if (fullClean) {
vkDestroySemaphore(device, imageAvailableSemaphore, nullptr);
vkDestroySemaphore(device, renderingFinishedSemaphore, nullptr);
vkDestroyCommandPool(device, commandPool, nullptr);
// Clean up uniform buffer related objects
vkDestroyDescriptorPool(device, descriptorPool, nullptr);
vkDestroyBuffer(device, uniformBuffer, nullptr);
vkFreeMemory(device, uniformBufferMemory, nullptr);
// Buffers must be destroyed after no command buffers are referring to them anymore
vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr);
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
// Note: implicitly destroys images (in fact, we're not allowed to do that explicitly)
vkDestroySwapchainKHR(device, swapChain, nullptr);
vkDestroyDevice(device, nullptr);
vkDestroySurfaceKHR(instance, windowSurface, nullptr);
if (ENABLE_DEBUGGING) {
PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
DestroyDebugReportCallback(instance, callback, nullptr);
}
vkDestroyInstance(instance, nullptr);
}
}
void createInstance() {
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "VulkanClear";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "ClearScreenEngine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
// Get instance extensions required by GLFW to draw to window
unsigned int glfwExtensionCount;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions;
for (size_t i = 0; i < glfwExtensionCount; i++) {
extensions.push_back(glfwExtensions[i]);
}
if (ENABLE_DEBUGGING) {
extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
}
// Check for extensions
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
if (extensionCount == 0) {
std::cerr << "no extensions supported!" << std::endl;
exit(1);
}
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, availableExtensions.data());
std::cout << "supported extensions:" << std::endl;
for (const auto& extension : availableExtensions) {
std::cout << "\t" << extension.extensionName << std::endl;
}
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = (uint32_t) extensions.size();
createInfo.ppEnabledExtensionNames = extensions.data();
if (ENABLE_DEBUGGING) {
createInfo.enabledLayerCount = 1;
createInfo.ppEnabledLayerNames = &DEBUG_LAYER;
}
// Initialize Vulkan instance
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
std::cerr << "failed to create instance!" << std::endl;
exit(1);
} else {
std::cout << "created vulkan instance" << std::endl;
}
}
void createWindowSurface() {
if (glfwCreateWindowSurface(instance, window, NULL, &windowSurface) != VK_SUCCESS) {
std::cerr << "failed to create window surface!" << std::endl;
exit(1);
}
std::cout << "created window surface" << std::endl;
}
void findPhysicalDevice() {
// Try to find 1 Vulkan supported device
// Note: perhaps refactor to loop through devices and find first one that supports all required features and extensions
uint32_t deviceCount = 0;
if (vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr) != VK_SUCCESS || deviceCount == 0) {
std::cerr << "failed to get number of physical devices" << std::endl;
exit(1);
}
deviceCount = 1;
VkResult res = vkEnumeratePhysicalDevices(instance, &deviceCount, &physicalDevice);
if (res != VK_SUCCESS && res != VK_INCOMPLETE) {
std::cerr << "enumerating physical devices failed!" << std::endl;
exit(1);
}
if (deviceCount == 0) {
std::cerr << "no physical devices that support vulkan!" << std::endl;
exit(1);
}
std::cout << "physical device with vulkan support found" << std::endl;
// Check device features
// Note: will apiVersion >= appInfo.apiVersion? Probably yes, but spec is unclear.
VkPhysicalDeviceProperties deviceProperties;
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
vkGetPhysicalDeviceFeatures(physicalDevice, &deviceFeatures);
uint32_t supportedVersion[] = {
VK_VERSION_MAJOR(deviceProperties.apiVersion),
VK_VERSION_MINOR(deviceProperties.apiVersion),
VK_VERSION_PATCH(deviceProperties.apiVersion)
};
std::cout << "physical device supports version " << supportedVersion[0] << "." << supportedVersion[1] << "." << supportedVersion[2] << std::endl;
}
void checkSwapChainSupport() {
uint32_t extensionCount = 0;
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
if (extensionCount == 0) {
std::cerr << "physical device doesn't support any extensions" << std::endl;
exit(1);
}
std::vector<VkExtensionProperties> deviceExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, deviceExtensions.data());
for (const auto& extension : deviceExtensions) {
if (strcmp(extension.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0) {
std::cout << "physical device supports swap chains" << std::endl;
return;
}
}
std::cerr << "physical device doesn't support swap chains" << std::endl;
exit(1);
}
void findQueueFamilies() {
// Check queue families
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr);
if (queueFamilyCount == 0) {
std::cout << "physical device has no queue families!" << std::endl;
exit(1);
}
// Find queue family with graphics support
// Note: is a transfer queue necessary to copy vertices to the gpu or can a graphics queue handle that?
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data());
std::cout << "physical device has " << queueFamilyCount << " queue families" << std::endl;
bool foundGraphicsQueueFamily = false;
bool foundPresentQueueFamily = false;
for (uint32_t i = 0; i < queueFamilyCount; i++) {
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, windowSurface, &presentSupport);
if (queueFamilies[i].queueCount > 0 && queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
graphicsQueueFamily = i;
foundGraphicsQueueFamily = true;
if (presentSupport) {
presentQueueFamily = i;
foundPresentQueueFamily = true;
break;
}
}
if (!foundPresentQueueFamily && presentSupport) {
presentQueueFamily = i;
foundPresentQueueFamily = true;
}
}
if (foundGraphicsQueueFamily) {
std::cout << "queue family #" << graphicsQueueFamily << " supports graphics" << std::endl;
if (foundPresentQueueFamily) {
std::cout << "queue family #" << presentQueueFamily << " supports presentation" << std::endl;
} else {
std::cerr << "could not find a valid queue family with present support" << std::endl;
exit(1);
}
} else {
std::cerr << "could not find a valid queue family with graphics support" << std::endl;
exit(1);
}
}
void createLogicalDevice() {
// Greate one graphics queue and optionally a separate presentation queue
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo[2] = {};
queueCreateInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo[0].queueFamilyIndex = graphicsQueueFamily;
queueCreateInfo[0].queueCount = 1;
queueCreateInfo[0].pQueuePriorities = &queuePriority;
queueCreateInfo[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo[0].queueFamilyIndex = presentQueueFamily;
queueCreateInfo[0].queueCount = 1;
queueCreateInfo[0].pQueuePriorities = &queuePriority;
// Create logical device from physical device
// Note: there are separate instance and device extensions!
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.pQueueCreateInfos = queueCreateInfo;
if (graphicsQueueFamily == presentQueueFamily) {
deviceCreateInfo.queueCreateInfoCount = 1;
} else {
deviceCreateInfo.queueCreateInfoCount = 2;
}
// Necessary for shader (for some reason)
VkPhysicalDeviceFeatures enabledFeatures = {};
enabledFeatures.shaderClipDistance = VK_TRUE;
enabledFeatures.shaderCullDistance = VK_TRUE;
const char* deviceExtensions = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
deviceCreateInfo.enabledExtensionCount = 1;
deviceCreateInfo.ppEnabledExtensionNames = &deviceExtensions;
deviceCreateInfo.pEnabledFeatures = &enabledFeatures;
if (ENABLE_DEBUGGING) {
deviceCreateInfo.enabledLayerCount = 1;
deviceCreateInfo.ppEnabledLayerNames = &DEBUG_LAYER;
}
if (vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &device) != VK_SUCCESS) {
std::cerr << "failed to create logical device" << std::endl;
exit(1);
}
std::cout << "created logical device" << std::endl;
// Get graphics and presentation queues (which may be the same)
vkGetDeviceQueue(device, graphicsQueueFamily, 0, &graphicsQueue);
vkGetDeviceQueue(device, presentQueueFamily, 0, &presentQueue);
std::cout << "acquired graphics and presentation queues" << std::endl;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &deviceMemoryProperties);
}
void createDebugCallback() {
if (ENABLE_DEBUGGING) {
VkDebugReportCallbackCreateInfoEXT createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
createInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT) debugCallback;
createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
if (CreateDebugReportCallback(instance, &createInfo, nullptr, &callback) != VK_SUCCESS) {
std::cerr << "failed to create debug callback" << std::endl;
exit(1);
} else {
std::cout << "created debug callback" << std::endl;
}
} else {
std::cout << "skipped creating debug callback" << std::endl;
}
}
void createSemaphores() {
VkSemaphoreCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if (vkCreateSemaphore(device, &createInfo, nullptr, &imageAvailableSemaphore) != VK_SUCCESS ||
vkCreateSemaphore(device, &createInfo, nullptr, &renderingFinishedSemaphore) != VK_SUCCESS) {
std::cerr << "failed to create semaphores" << std::endl;
exit(1);
} else {
std::cout << "created semaphores" << std::endl;
}
}
void createCommandPool() {
// Create graphics command pool
VkCommandPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolCreateInfo.queueFamilyIndex = graphicsQueueFamily;
if (vkCreateCommandPool(device, &poolCreateInfo, nullptr, &commandPool) != VK_SUCCESS) {
std::cerr << "failed to create command queue for graphics queue family" << std::endl;
exit(1);
} else {
std::cout << "created command pool for graphics queue family" << std::endl;
}
}
void createVertexBuffer() {
// Setup vertices
std::vector<Vertex> vertices = {
{ { -0.5f, -0.5f, 0.0f }, { 1.0f, 0.0f, 0.0f } },
{ { -0.5f, 0.5f, 0.0f }, { 0.0f, 1.0f, 0.0f } },
{ { 0.5f, 0.5f, 0.0f }, { 0.0f, 0.0f, 1.0f } }
};
uint32_t verticesSize = (uint32_t) (vertices.size() * sizeof(vertices[0]));
// Setup indices
std::vector<uint32_t> indices = { 0, 1, 2 };
uint32_t indicesSize = (uint32_t) (indices.size() * sizeof(indices[0]));
VkMemoryAllocateInfo memAlloc = {};
memAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
VkMemoryRequirements memReqs;
void* data;
struct StagingBuffer {
VkDeviceMemory memory;
VkBuffer buffer;
};
struct {
StagingBuffer vertices;
StagingBuffer indices;
} stagingBuffers;
// Allocate command buffer for copy operation
VkCommandBufferAllocateInfo cmdBufInfo = {};
cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmdBufInfo.commandPool = commandPool;
cmdBufInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmdBufInfo.commandBufferCount = 1;
VkCommandBuffer copyCommandBuffer;
vkAllocateCommandBuffers(device, &cmdBufInfo, ©CommandBuffer);
// First copy vertices to host accessible vertex buffer memory
VkBufferCreateInfo vertexBufferInfo = {};
vertexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vertexBufferInfo.size = verticesSize;
vertexBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
vkCreateBuffer(device, &vertexBufferInfo, nullptr, &stagingBuffers.vertices.buffer);
vkGetBufferMemoryRequirements(device, stagingBuffers.vertices.buffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAlloc.memoryTypeIndex);
vkAllocateMemory(device, &memAlloc, nullptr, &stagingBuffers.vertices.memory);
vkMapMemory(device, stagingBuffers.vertices.memory, 0, verticesSize, 0, &data);
memcpy(data, vertices.data(), verticesSize);
vkUnmapMemory(device, stagingBuffers.vertices.memory);
vkBindBufferMemory(device, stagingBuffers.vertices.buffer, stagingBuffers.vertices.memory, 0);
// Then allocate a gpu only buffer for vertices
vertexBufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
vkCreateBuffer(device, &vertexBufferInfo, nullptr, &vertexBuffer);
vkGetBufferMemoryRequirements(device, vertexBuffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memAlloc.memoryTypeIndex);
vkAllocateMemory(device, &memAlloc, nullptr, &vertexBufferMemory);
vkBindBufferMemory(device, vertexBuffer, vertexBufferMemory, 0);
// Next copy indices to host accessible index buffer memory
VkBufferCreateInfo indexBufferInfo = {};
indexBufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
indexBufferInfo.size = indicesSize;
indexBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
vkCreateBuffer(device, &indexBufferInfo, nullptr, &stagingBuffers.indices.buffer);
vkGetBufferMemoryRequirements(device, stagingBuffers.indices.buffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAlloc.memoryTypeIndex);
vkAllocateMemory(device, &memAlloc, nullptr, &stagingBuffers.indices.memory);
vkMapMemory(device, stagingBuffers.indices.memory, 0, indicesSize, 0, &data);
memcpy(data, indices.data(), indicesSize);
vkUnmapMemory(device, stagingBuffers.indices.memory);
vkBindBufferMemory(device, stagingBuffers.indices.buffer, stagingBuffers.indices.memory, 0);
// And allocate another gpu only buffer for indices
indexBufferInfo.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
vkCreateBuffer(device, &indexBufferInfo, nullptr, &indexBuffer);
vkGetBufferMemoryRequirements(device, indexBuffer, &memReqs);
memAlloc.allocationSize = memReqs.size;
getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memAlloc.memoryTypeIndex);
vkAllocateMemory(device, &memAlloc, nullptr, &indexBufferMemory);
vkBindBufferMemory(device, indexBuffer, indexBufferMemory, 0);
// Now copy data from host visible buffer to gpu only buffer
VkCommandBufferBeginInfo bufferBeginInfo = {};
bufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
bufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(copyCommandBuffer, &bufferBeginInfo);
VkBufferCopy copyRegion = {};
copyRegion.size = verticesSize;
vkCmdCopyBuffer(copyCommandBuffer, stagingBuffers.vertices.buffer, vertexBuffer, 1, ©Region);
copyRegion.size = indicesSize;
vkCmdCopyBuffer(copyCommandBuffer, stagingBuffers.indices.buffer, indexBuffer, 1, ©Region);
vkEndCommandBuffer(copyCommandBuffer);
// Submit to queue
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ©CommandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, ©CommandBuffer);
vkDestroyBuffer(device, stagingBuffers.vertices.buffer, nullptr);
vkFreeMemory(device, stagingBuffers.vertices.memory, nullptr);
vkDestroyBuffer(device, stagingBuffers.indices.buffer, nullptr);
vkFreeMemory(device, stagingBuffers.indices.memory, nullptr);
std::cout << "set up vertex and index buffers" << std::endl;
// Binding and attribute descriptions
vertexBindingDescription.binding = 0;
vertexBindingDescription.stride = sizeof(vertices[0]);
vertexBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
// vec2 position
vertexAttributeDescriptions.resize(2);
vertexAttributeDescriptions[0].binding = 0;
vertexAttributeDescriptions[0].location = 0;
vertexAttributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
// vec3 color
vertexAttributeDescriptions[1].binding = 0;
vertexAttributeDescriptions[1].location = 1;
vertexAttributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
vertexAttributeDescriptions[1].offset = sizeof(float) * 3;
}
void createUniformBuffer() {
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = sizeof(uniformBufferData);
bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
vkCreateBuffer(device, &bufferInfo, nullptr, &uniformBuffer);
VkMemoryRequirements memReqs;
vkGetBufferMemoryRequirements(device, uniformBuffer, &memReqs);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memReqs.size;
getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &allocInfo.memoryTypeIndex);
vkAllocateMemory(device, &allocInfo, nullptr, &uniformBufferMemory);
vkBindBufferMemory(device, uniformBuffer, uniformBufferMemory, 0);
updateUniformData();
}
void updateUniformData() {
// Rotate based on time
auto timeNow = std::chrono::high_resolution_clock::now();
long long millis = std::chrono::duration_cast<std::chrono::milliseconds>(timeStart - timeNow).count();
float angle = (millis % 4000) / 4000.0f * glm::radians(360.f);
glm::mat4 modelMatrix;
modelMatrix = glm::rotate(modelMatrix, angle, glm::vec3(0, 0, 1));
modelMatrix = glm::translate(modelMatrix, glm::vec3(0.5f / 3.0f, -0.5f / 3.0f, 0.0f));
// Set up view
auto viewMatrix = glm::lookAt(glm::vec3(1, 1, 1), glm::vec3(0, 0, 0), glm::vec3(0, 0, -1));
// Set up projection
auto projMatrix = glm::perspective(glm::radians(70.f), swapChainExtent.width / (float) swapChainExtent.height, 0.1f, 10.0f);
uniformBufferData.transformationMatrix = projMatrix * viewMatrix * modelMatrix;
void* data;
vkMapMemory(device, uniformBufferMemory, 0, sizeof(uniformBufferData), 0, &data);
memcpy(data, &uniformBufferData, sizeof(uniformBufferData));
vkUnmapMemory(device, uniformBufferMemory);
}
// Find device memory that is supported by the requirements (typeBits) and meets the desired properties
VkBool32 getMemoryType(uint32_t typeBits, VkFlags properties, uint32_t* typeIndex) {
for (uint32_t i = 0; i < 32; i++) {
if ((typeBits & 1) == 1) {
if ((deviceMemoryProperties.memoryTypes[i].propertyFlags & properties) == properties) {
*typeIndex = i;
return true;
}
}
typeBits >>= 1;
}
return false;
}
void createSwapChain() {
// Find surface capabilities
VkSurfaceCapabilitiesKHR surfaceCapabilities;
if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, windowSurface, &surfaceCapabilities) != VK_SUCCESS) {
std::cerr << "failed to acquire presentation surface capabilities" << std::endl;
exit(1);
}
// Find supported surface formats
uint32_t formatCount;
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, windowSurface, &formatCount, nullptr) != VK_SUCCESS || formatCount == 0) {
std::cerr << "failed to get number of supported surface formats" << std::endl;
exit(1);
}
std::vector<VkSurfaceFormatKHR> surfaceFormats(formatCount);
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, windowSurface, &formatCount, surfaceFormats.data()) != VK_SUCCESS) {
std::cerr << "failed to get supported surface formats" << std::endl;
exit(1);
}
// Find supported present modes
uint32_t presentModeCount;
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, windowSurface, &presentModeCount, nullptr) != VK_SUCCESS || presentModeCount == 0) {
std::cerr << "failed to get number of supported presentation modes" << std::endl;
exit(1);
}
std::vector<VkPresentModeKHR> presentModes(presentModeCount);
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, windowSurface, &presentModeCount, presentModes.data()) != VK_SUCCESS) {
std::cerr << "failed to get supported presentation modes" << std::endl;
exit(1);
}
// Determine number of images for swap chain
uint32_t imageCount = surfaceCapabilities.minImageCount + 1;
if (surfaceCapabilities.maxImageCount != 0 && imageCount > surfaceCapabilities.maxImageCount) {
imageCount = surfaceCapabilities.maxImageCount;
}
std::cout << "using " << imageCount << " images for swap chain" << std::endl;
// Select a surface format
VkSurfaceFormatKHR surfaceFormat = chooseSurfaceFormat(surfaceFormats);
// Select swap chain size
swapChainExtent = chooseSwapExtent(surfaceCapabilities);
// Determine transformation to use (preferring no transform)
VkSurfaceTransformFlagBitsKHR surfaceTransform;
if (surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
surfaceTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
} else {
surfaceTransform = surfaceCapabilities.currentTransform;
}
// Choose presentation mode (preferring MAILBOX ~= triple buffering)
VkPresentModeKHR presentMode = choosePresentMode(presentModes);
// Finally, create the swap chain
VkSwapchainCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = windowSurface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = swapChainExtent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
createInfo.preTransform = surfaceTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = oldSwapChain;
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
std::cerr << "failed to create swap chain" << std::endl;
exit(1);
} else {
std::cout << "created swap chain" << std::endl;
}
if (oldSwapChain != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(device, oldSwapChain, nullptr);
}
oldSwapChain = swapChain;
swapChainFormat = surfaceFormat.format;
// Store the images used by the swap chain
// Note: these are the images that swap chain image indices refer to
// Note: actual number of images may differ from requested number, since it's a lower bound
uint32_t actualImageCount = 0;
if (vkGetSwapchainImagesKHR(device, swapChain, &actualImageCount, nullptr) != VK_SUCCESS || actualImageCount == 0) {
std::cerr << "failed to acquire number of swap chain images" << std::endl;
exit(1);
}
swapChainImages.resize(actualImageCount);
if (vkGetSwapchainImagesKHR(device, swapChain, &actualImageCount, swapChainImages.data()) != VK_SUCCESS) {
std::cerr << "failed to acquire swap chain images" << std::endl;
exit(1);
}
std::cout << "acquired swap chain images" << std::endl;
}
VkSurfaceFormatKHR chooseSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
// We can either choose any format
if (availableFormats.size() == 1 && availableFormats[0].format == VK_FORMAT_UNDEFINED) {
return{ VK_FORMAT_R8G8B8A8_UNORM, VK_COLORSPACE_SRGB_NONLINEAR_KHR };
}
// Or go with the standard format - if available
for (const auto& availableSurfaceFormat : availableFormats) {
if (availableSurfaceFormat.format == VK_FORMAT_R8G8B8A8_UNORM) {
return availableSurfaceFormat;
}
}
// Or fall back to the first available one
return availableFormats[0];
}
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& surfaceCapabilities) {
if (surfaceCapabilities.currentExtent.width == -1) {
VkExtent2D swapChainExtent = {};
swapChainExtent.width = std::min(std::max(WIDTH, surfaceCapabilities.minImageExtent.width), surfaceCapabilities.maxImageExtent.width);
swapChainExtent.height = std::min(std::max(HEIGHT, surfaceCapabilities.minImageExtent.height), surfaceCapabilities.maxImageExtent.height);
return swapChainExtent;
} else {
return surfaceCapabilities.currentExtent;
}
}
VkPresentModeKHR choosePresentMode(const std::vector<VkPresentModeKHR> presentModes) {
for (const auto& presentMode : presentModes) {
if (presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
return presentMode;
}
}
// If mailbox is unavailable, fall back to FIFO (guaranteed to be available)
return VK_PRESENT_MODE_FIFO_KHR;
}
void createRenderPass() {
VkAttachmentDescription attachmentDescription = {};
attachmentDescription.format = swapChainFormat;
attachmentDescription.samples = VK_SAMPLE_COUNT_1_BIT;
attachmentDescription.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachmentDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachmentDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachmentDescription.initialLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachmentDescription.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
// Note: hardware will automatically transition attachment to the specified layout
// Note: index refers to attachment descriptions array
VkAttachmentReference colorAttachmentReference = {};
colorAttachmentReference.attachment = 0;
colorAttachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
// Note: this is a description of how the attachments of the render pass will be used in this sub pass
// e.g. if they will be read in shaders and/or drawn to
VkSubpassDescription subPassDescription = {};
subPassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subPassDescription.colorAttachmentCount = 1;
subPassDescription.pColorAttachments = &colorAttachmentReference;
// Create the render pass
VkRenderPassCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
createInfo.attachmentCount = 1;
createInfo.pAttachments = &attachmentDescription;
createInfo.subpassCount = 1;
createInfo.pSubpasses = &subPassDescription;
if (vkCreateRenderPass(device, &createInfo, nullptr, &renderPass) != VK_SUCCESS) {
std::cerr << "failed to create render pass" << std::endl;
exit(1);
} else {
std::cout << "created render pass" << std::endl;
}
}
void createImageViews() {
swapChainImageViews.resize(swapChainImages.size());
// Create an image view for every image in the swap chain
for (size_t i = 0; i < swapChainImages.size(); i++) {
VkImageViewCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = swapChainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = swapChainFormat;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) {
std::cerr << "failed to create image view for swap chain image #" << i << std::endl;
exit(1);
}
}
std::cout << "created image views for swap chain images" << std::endl;
}
void createFramebuffers() {
swapChainFramebuffers.resize(swapChainImages.size());
// Note: Framebuffer is basically a specific choice of attachments for a render pass
// That means all attachments must have the same dimensions, interesting restriction
for (size_t i = 0; i < swapChainImages.size(); i++) {
VkFramebufferCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
createInfo.renderPass = renderPass;
createInfo.attachmentCount = 1;
createInfo.pAttachments = &swapChainImageViews[i];
createInfo.width = swapChainExtent.width;
createInfo.height = swapChainExtent.height;
createInfo.layers = 1;
if (vkCreateFramebuffer(device, &createInfo, nullptr, &swapChainFramebuffers[i]) != VK_SUCCESS) {
std::cerr << "failed to create framebuffer for swap chain image view #" << i << std::endl;
exit(1);
}
}
std::cout << "created framebuffers for swap chain image views" << std::endl;
}
VkShaderModule createShaderModule(const std::string& filename) {
std::ifstream file(filename, std::ios::ate | std::ios::binary);
std::vector<char> fileBytes(file.tellg());
file.seekg(0, std::ios::beg);
file.read(fileBytes.data(), fileBytes.size());
file.close();
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = fileBytes.size();
createInfo.pCode = (uint32_t*) fileBytes.data();
VkShaderModule shaderModule;
if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
std::cerr << "failed to create shader module for " << filename << std::endl;
exit(1);
}
std::cout << "created shader module for " << filename << std::endl;
return shaderModule;
}
void createGraphicsPipeline() {
VkShaderModule vertexShaderModule = createShaderModule("shaders/vert.spv");
VkShaderModule fragmentShaderModule = createShaderModule("shaders/frag.spv");
// Set up shader stage info
VkPipelineShaderStageCreateInfo vertexShaderCreateInfo = {};
vertexShaderCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertexShaderCreateInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertexShaderCreateInfo.module = vertexShaderModule;
vertexShaderCreateInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragmentShaderCreateInfo = {};
fragmentShaderCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragmentShaderCreateInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragmentShaderCreateInfo.module = fragmentShaderModule;
fragmentShaderCreateInfo.pName = "main";