-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
1418 lines (1296 loc) · 59.3 KB
/
main.c
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
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedMacroInspection"
#define GLFW_INCLUDE_VULKAN
#pragma clang diagnostic pop
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define WIDTH 800
#define HEIGHT 600
#define nullptr NULL
#define MAX_FRAMES_IN_FLIGHT 2
typedef struct {
bool isGraphicsFamilySet;
uint32_t graphicsFamily;
bool isPresentFamilySet;
uint32_t presentFamily;
} QueueFamilyIndices;
typedef struct {
VkSurfaceCapabilitiesKHR capabilities;
uint32_t formatsCount;
VkSurfaceFormatKHR *formats;
uint32_t presentModesCount;
VkPresentModeKHR *presentModes;
} SwapChainSupportDetails;
uint32_t rateDeviceSuitability(VkPhysicalDevice device);
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface);
bool checkDeviceExtensionSupport(VkPhysicalDevice device, char **deviceExtensions, size_t deviceExtensionsCount);
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const VkSurfaceFormatKHR *availableFormats, int availableFormatsCount);
VkPresentModeKHR chooseSwapPresentMode(const VkPresentModeKHR *availablePresentModes, int availablePresentModesCount);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR *capabilities, GLFWwindow *window);
uint32_t *readFile(const char *filePath, size_t *len);
VkShaderModule createShaderModule(VkDevice device, const uint32_t *code, size_t codeSize);
void recordCommandBuffer(VkRenderPass renderPass, VkFramebuffer *swapChainFramebuffers, VkExtent2D swapChainExtent,
VkCommandBuffer commandBuffer, VkPipeline graphicsPipeline, uint32_t imageIndex);
void drawFrame(VkDevice device, VkPipeline graphicsPipeline, VkRenderPass renderPass, VkSwapchainKHR swapChain,
VkExtent2D swapChainExtent, VkCommandBuffer *commandBuffers, VkQueue graphicsQueue, VkQueue presentQueue,
VkFramebuffer *swapChainFramebuffers, VkSemaphore *imageAvailableSemaphores,
VkSemaphore *renderFinishedSemaphores, VkFence *inFlightFences, uint32_t currentFrame);
__attribute__((unused)) void printAvailableExtensions() {
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
VkExtensionProperties *extensions = calloc(extensionCount, sizeof(VkExtensionProperties));
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions);
printf("available extensions:\n");
for (int i = 0; i < extensionCount; ++i) {
printf("\t%3d. %s\n", i, extensions[i].extensionName);
}
fflush(stdout);
}
bool checkValidationSupport(const char **validationLayers, const size_t validationLayerCount) {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
VkLayerProperties *availableLayers = calloc(layerCount, sizeof(VkLayerProperties));
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);
bool layerFound = false;
for (int i = 0; i < validationLayerCount; ++i) {
const char *layerName = validationLayers[i];
for (int j = 0; j < layerCount; ++j) {
if (strcmp(layerName, availableLayers[j].layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
free(availableLayers);
return false;
}
}
free(availableLayers);
return true;
}
char **getRequiredExtensions(uint32_t *extensionsCount) {
const char **glfwExtensions = glfwGetRequiredInstanceExtensions(extensionsCount);
(*extensionsCount) = (*extensionsCount) + 3;
char **extensions = calloc(*extensionsCount, sizeof(char *));
for (int i = 0; i < *extensionsCount - 3; ++i) {
extensions[i] = strdup(glfwExtensions[i]);
}
extensions[*extensionsCount - 1] = strdup(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
extensions[*extensionsCount - 2] = strdup(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
extensions[*extensionsCount - 3] = strdup(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
return extensions;
}
static VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(__attribute__((unused)) VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
__attribute__((unused)) VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, __attribute__((unused)) void *pUserData) {
fprintf(stderr, "validation layer: %s\n", pCallbackData->pMessage);
fflush(stderr);
return VK_FALSE;
}
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkDebugUtilsMessengerEXT *pDebugMessenger) {
PFN_vkCreateDebugUtilsMessengerEXT func = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance,
"vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger,
const VkAllocationCallbacks *pAllocator) {
PFN_vkDestroyDebugUtilsMessengerEXT func = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance,
"vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, debugMessenger, pAllocator);
}
}
void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT *createInfo) {
createInfo->sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo->messageSeverity =
VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo->messageType =
VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo->pfnUserCallback = debugCallback;
}
bool isDeviceSuitable(VkPhysicalDevice device, VkSurfaceKHR surface, char **deviceExtensions,
const size_t deviceExtensionsCount) {
QueueFamilyIndices indices = findQueueFamilies(device, surface);
bool extensionsSupported = checkDeviceExtensionSupport(device, deviceExtensions, deviceExtensionsCount);
bool swapChainAdequate = false;
if (extensionsSupported) {
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device, surface);
swapChainAdequate = swapChainSupport.formatsCount > 0 && swapChainSupport.presentModesCount > 0;
}
return indices.isGraphicsFamilySet && indices.isPresentFamilySet && extensionsSupported && swapChainAdequate;
}
bool checkDeviceExtensionSupport(VkPhysicalDevice device, char **deviceExtensions, const size_t deviceExtensionsCount) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
VkExtensionProperties *availableExtensions = (VkExtensionProperties *) malloc(
extensionCount * sizeof(VkExtensionProperties));
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions);
for (size_t i = 0; i < deviceExtensionsCount; i++) {
bool extensionFound = false;
for (size_t j = 0; j < extensionCount; j++) {
if (strcmp(deviceExtensions[i], availableExtensions[j].extensionName) == 0) {
extensionFound = true;
break;
}
}
if (!extensionFound) {
fprintf(stderr, "%s device extension not found", deviceExtensions[i]);
free(availableExtensions);
return false;
}
}
free(availableExtensions);
return true;
}
__attribute__((unused)) VkPhysicalDevice
pickPhysicalDevice(const VkPhysicalDevice *devices, const size_t devicesCount) {
struct Candidate {
uint32_t rating;
VkPhysicalDevice device;
};
struct Candidate *candidates = calloc(devicesCount, sizeof(struct Candidate));
for (size_t i = 0; i < devicesCount; ++i) {
VkPhysicalDevice device = devices[i];
candidates[i].rating = rateDeviceSuitability(device);
candidates[i].device = device;
}
size_t maxRatingIndex = 0;
uint32_t maxRating = 0;
for (int i = 0; i < devicesCount; ++i) {
if (candidates[i].rating > maxRating) {
maxRatingIndex = i;
}
}
printf("max rating: %d", maxRating);
free(candidates);
return devices[maxRatingIndex];
}
uint32_t rateDeviceSuitability(VkPhysicalDevice device) {
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
uint32_t score = 0;
// Discrete GPUs have a significant performance advantage
if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
score += 1000;
}
// Maximum possible size of textures affects graphics quality
score += deviceProperties.limits.maxImageDimension2D;
// Application can't function without geometry shaders
if (!deviceFeatures.geometryShader) {
return 0;
}
return score;
}
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice device, VkSurfaceKHR surface) {
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
VkQueueFamilyProperties *queueFamilies = calloc(queueFamilyCount, sizeof(VkQueueFamilyProperties));
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies);
QueueFamilyIndices indices = {};
for (int i = 0; i < queueFamilyCount; ++i) {
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport) {
indices.isPresentFamilySet = true;
indices.presentFamily = i;
}
VkQueueFamilyProperties queueFamily = queueFamilies[i];
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
indices.isGraphicsFamilySet = true;
indices.graphicsFamily = i;
}
if (indices.isGraphicsFamilySet && indices.isPresentFamilySet) {
break;
}
}
return indices;
}
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) {
SwapChainSupportDetails details = {};
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &details.formatsCount, nullptr);
if (details.formatsCount > 0) {
details.formats = calloc(details.formatsCount, sizeof(*details.formats));
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &details.formatsCount, details.formats);
}
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &details.presentModesCount, nullptr);
if (details.presentModesCount > 0) {
details.presentModes = calloc(details.presentModesCount, sizeof(*details.presentModes));
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &details.presentModesCount, details.presentModes);
}
return details;
}
VkSurfaceFormatKHR
chooseSwapSurfaceFormat(const VkSurfaceFormatKHR *availableFormats, const int availableFormatsCount) {
for (int i = 0; i < availableFormatsCount; ++i) {
const VkSurfaceFormatKHR availableFormat = availableFormats[i];
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB &&
availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR chooseSwapPresentMode(const VkPresentModeKHR *availablePresentModes, int availablePresentModesCount) {
for (int i = 0; i < availablePresentModesCount; ++i) {
const VkPresentModeKHR availablePresentMode = availablePresentModes[i];
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR *capabilities, GLFWwindow *window) {
if (capabilities->currentExtent.width != UINT32_MAX) {
return capabilities->currentExtent;
} else {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actualExtent = {.width = (uint32_t) width, .height = (uint32_t) height};
if (actualExtent.width < capabilities->minImageExtent.width) {
actualExtent.width = capabilities->minImageExtent.width;
} else if (actualExtent.width > capabilities->maxImageExtent.width) {
actualExtent.width = capabilities->maxImageExtent.width;
}
if (actualExtent.height < capabilities->minImageExtent.height) {
actualExtent.height = capabilities->minImageExtent.height;
} else if (actualExtent.height > capabilities->maxImageExtent.height) {
actualExtent.height = capabilities->maxImageExtent.height;
}
return actualExtent;
}
}
uint32_t *readFile(const char *filePath, size_t *len) {
FILE *file = fopen(filePath, "rb");
fseek(file, 0, SEEK_END);
*len = ftell(file);
fseek(file, 0, SEEK_SET);
uint32_t *buffer = calloc(*len, sizeof(buffer));
fread(buffer, 1, *len, file);
fclose(file);
return buffer;
}
__attribute__((unused)) VkShaderModule
createShaderModule(VkDevice device, const uint32_t *code, const size_t codeSize) {
if (code == nullptr || codeSize < 1) {
perror("invalid code input!");
exit(EXIT_FAILURE);
}
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = codeSize;
createInfo.pCode = (const uint32_t *) code;
VkShaderModule shaderModule;
if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
perror("failed to create shader module!");
exit(EXIT_FAILURE);
}
return shaderModule;
}
void recordCommandBuffer(VkRenderPass renderPass, VkFramebuffer *swapChainFramebuffers, VkExtent2D swapChainExtent,
VkCommandBuffer commandBuffer, VkPipeline graphicsPipeline, uint32_t imageIndex) {
/**
* <h3>Command buffer recording</h3>
*
* Created with <code>VkCommandBufferBeginInfo</code> struct:
* <dl>
* <dt><code>flags</code></dt>
* <dd>
* Specifies how we're going to use the command buffer.
* <ul>
* <li><code>VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT</code>: The
* command buffer will be rerecorded right after executing it once.
* <li><code>VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT</code>:
* This is a secondary command buffer that will be entirely within a
* single render pass.
* <li><code>VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIG</code>: The
* command buffer can be resubmitted while it is also already pending
* execution.
* </ul>
* </dd>
* <dt><code>pInheritanceInfo</code></dt>
* <dd>Relevant for secondary command buffers. Specifies which state to
* inherit from the calling primary command buffers.</dd>
* <dl>
*/
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = 0; // Optional
beginInfo.pInheritanceInfo = nullptr; // Optional
if (vkBeginCommandBuffer(commandBuffer, &beginInfo) != VK_SUCCESS) {
perror("failed to begin recording command buffers!");
exit(EXIT_FAILURE);
}
/**
* <h3>Starting a render pass</h3>
*
* <p>Drawing starts by beginning the render pass with
* <code>vkCmdBeginRenderPass</code>. The render pass is configured
* using <code>VkRenderPassBeginInfo</code> struct:
* <dl>
* <dt><code>renderArea</code><dt>
* <dd>Defines the size of the render area. The render area defines
* where shader loads and stores will take place. The pixels outside
* this region will have undefined values.
* <i>It should match the size
* of the attachments for best performance.</i></dd>
* </dl>
* </p>
*/
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
#pragma clang diagnostic push
#pragma ide diagnostic ignored "NullDereference"
renderPassInfo.framebuffer = swapChainFramebuffers[imageIndex];
#pragma clang diagnostic pop
renderPassInfo.renderArea.offset.x = 0;
renderPassInfo.renderArea.offset.y = 0;
renderPassInfo.renderArea.extent = swapChainExtent;
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
/**
* The func <code>vkCmdBeginRenderPass</code>
* <dl>
* <dt><code>VkSubpassContents contents<code></dt>
* <dd>
* <ul>
* <li><code>VK_SUBPASS_CONTENTS_INLINE</code>: The render pass commands
* will be embedded in the primary command buffer itself and no
* secondary command buffers will be executed.
* <li><code>VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS</code>: The
* render pass commands will be executed from secondary command
* buffers.
* </ul>
* </dd>
* </dl>
*/
vkCmdBeginRenderPass(commandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
/**
* <h3>Basic drawing commands</h3>
*
* <p>
* use func <code>vkCmdBindPipeline</code> to bind the graphic pipeline.
* </p>
*/
vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
VkViewport viewport = {};
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = (float) swapChainExtent.width;
viewport.height = (float) swapChainExtent.height;
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
vkCmdSetViewport(commandBuffer, 0, 1, &viewport);
VkRect2D scissor = {};
scissor.offset.x = 0;
scissor.offset.y = 0;
scissor.extent = swapChainExtent;
vkCmdSetScissor(commandBuffer, 0, 1, &scissor);
/**
* issue the draw command using func <code>vkCmdDraw</code>
*
* <ul>
* <li><code>vertexCount</code>: number of vertices to draw
* <li><code>instanceCount</code>: <i>used for instanced rendering</i>
* <li><code>firstVertex</code>: Used as an offset into the vertex buffer;
* defined the lowest value of <code>gl_VertexIndex</code> in the
* vertex shader.
* <li><code>firstInstance</code>: <i>used for instanced rendering</i>.
* Defines the lowest value of <code>gl_InstanceIndex</code> in the
* vertex shader.
* </ul>
*/
vkCmdDraw(commandBuffer, 3, 1, 0, 0);
vkCmdEndRenderPass(commandBuffer);
if (vkEndCommandBuffer(commandBuffer) != VK_SUCCESS) {
perror("failed to record command buffer!");
exit(EXIT_FAILURE);
}
}
void drawFrame(VkDevice device, VkPipeline graphicsPipeline, VkRenderPass renderPass, VkSwapchainKHR swapChain,
VkExtent2D swapChainExtent, VkCommandBuffer *commandBuffers, VkQueue graphicsQueue, VkQueue presentQueue,
VkFramebuffer *swapChainFramebuffers, VkSemaphore *imageAvailableSemaphores,
VkSemaphore *renderFinishedSemaphores, VkFence *inFlightFences, uint32_t currentFrame) {
if (commandBuffers == nullptr || imageAvailableSemaphores == nullptr || renderFinishedSemaphores == nullptr ||
inFlightFences == nullptr) {
errno = EINVAL;
perror("commandBuffers, imageAvailableSemaphores, renderFinishedSemaphores, "
"and inFlightFences shouldn't be null");
exit(EXIT_FAILURE);
}
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE,
&imageIndex);
vkResetCommandBuffer(commandBuffers[currentFrame], 0);
recordCommandBuffer(renderPass, swapChainFramebuffers, swapChainExtent, commandBuffers[currentFrame],
graphicsPipeline, imageIndex);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = {imageAvailableSemaphores[currentFrame]};
VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[currentFrame];
VkSemaphore signalSemaphores[] = {renderFinishedSemaphores[currentFrame]};
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]) != VK_SUCCESS) {
perror("failed to submit draw command buffer!");
exit(EXIT_FAILURE);
}
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = {swapChain};
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(presentQueue, &presentInfo);
}
int main(void) {
// region globals
const size_t validationLayersCount = 1;
char **validationLayers = calloc(validationLayersCount, sizeof(char *));
validationLayers[0] = strdup("VK_LAYER_KHRONOS_validation");
const size_t deviceExtensionsCount = 2;
char **deviceExtensions = calloc(deviceExtensionsCount, sizeof(*deviceExtensions));
deviceExtensions[0] = strdup(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
deviceExtensions[1] = strdup("VK_KHR_portability_subset"); // `VUID-VkDeviceCreateInfo-pProperties-04451` fix
// endregion globals
// region initWindow
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWwindow *window = glfwCreateWindow(WIDTH, HEIGHT, "Vulkan", NULL, NULL);
if (window == nullptr) {
perror("failed to create window");
exit(EXIT_FAILURE);
}
// endregion
// region initVulkan
// region createInstance
if (!checkValidationSupport((const char **) validationLayers, validationLayersCount)) {
perror("validation layers requested, but not available");
exit(EXIT_FAILURE);
}
VkInstance instance;
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hello Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo = {};
populateDebugMessengerCreateInfo(&debugCreateInfo);
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &appInfo;
instanceCreateInfo.pNext = (VkDebugUtilsMessengerCreateInfoEXT *) &debugCreateInfo;
uint32_t extensionCount = 0;
char **extensions = (char **) getRequiredExtensions(&extensionCount);
instanceCreateInfo.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
instanceCreateInfo.enabledExtensionCount = extensionCount;
instanceCreateInfo.ppEnabledExtensionNames = (const char *const *) extensions;
instanceCreateInfo.enabledLayerCount = validationLayersCount;
instanceCreateInfo.ppEnabledLayerNames = (const char *const *) validationLayers;
if (vkCreateInstance(&instanceCreateInfo, NULL, &instance) != VK_SUCCESS) {
perror("failed to create instance");
exit(EXIT_FAILURE);
}
// endregion createInstance
// region setup debug logger
VkDebugUtilsMessengerEXT debugMessenger;
if (CreateDebugUtilsMessengerEXT(instance, &debugCreateInfo, nullptr, &debugMessenger) != VK_SUCCESS) {
perror("failed to set up debug messenger!");
exit(EXIT_FAILURE);
}
// endregion
// region window surface
VkSurfaceKHR surface;
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
perror("failed to create window surface!");
exit(EXIT_FAILURE);
}
// endregion
// region pickup physical device
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0) {
perror("failed to find GPUs with Vulkan support!");
exit(EXIT_FAILURE);
}
VkPhysicalDevice *devices = calloc(deviceCount, sizeof(VkPhysicalDevice));
vkEnumeratePhysicalDevices(instance, &deviceCount, devices);
for (int i = 0; i < deviceCount; ++i) {
if (isDeviceSuitable(devices[i], surface, deviceExtensions, deviceExtensionsCount)) {
physicalDevice = devices[i];
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
perror("failed to find a suitable GPU");
exit(EXIT_FAILURE);
}
// endregion
// region logical devices and queues
VkDevice device;
QueueFamilyIndices indices = findQueueFamilies(physicalDevice, surface);
uint32_t queueCreateInfosCount;
if (indices.graphicsFamily != indices.presentFamily) {
queueCreateInfosCount = 2;
} else {
queueCreateInfosCount = 1;
}
VkDeviceQueueCreateInfo *queueCreateInfos = calloc(queueCreateInfosCount, sizeof(VkDeviceQueueCreateInfo));
float queuePriority = 1.0f;
for (int i = 0; i < queueCreateInfosCount; ++i) {
queueCreateInfos[i].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfos[i].queueFamilyIndex = indices.graphicsFamily;
queueCreateInfos[i].queueCount = 1;
queueCreateInfos[i].pQueuePriorities = &queuePriority;
}
VkPhysicalDeviceFeatures deviceFeatures = {};
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = queueCreateInfosCount;
createInfo.pQueueCreateInfos = queueCreateInfos;
createInfo.enabledLayerCount = validationLayersCount;
createInfo.ppEnabledLayerNames = (const char *const *) validationLayers;
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = deviceExtensionsCount;
createInfo.ppEnabledExtensionNames = (const char *const *) deviceExtensions;
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
perror("failed to create logical device!");
exit(EXIT_FAILURE);
}
VkQueue graphicsQueue = VK_NULL_HANDLE;
vkGetDeviceQueue(device, indices.graphicsFamily, 0, &graphicsQueue);
if (graphicsQueue == VK_NULL_HANDLE) {
perror("failed to get reference to graphicsQueue!");
exit(EXIT_FAILURE);
}
VkQueue presentQueue = VK_NULL_HANDLE;
vkGetDeviceQueue(device, indices.presentFamily, 0, &presentQueue);
if (presentQueue == VK_NULL_HANDLE) {
perror("failed to get reference to presentQueue!");
exit(EXIT_FAILURE);
}
// endregion
// region swap chain
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice, surface);
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats,
(int) swapChainSupport.formatsCount);
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes,
(int) swapChainSupport.presentModesCount);
VkExtent2D extent = chooseSwapExtent(&swapChainSupport.capabilities, window);
uint32_t swapChainImageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 &&
swapChainImageCount > swapChainSupport.capabilities.maxImageCount) {
swapChainImageCount = swapChainSupport.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR swapchainCreateInfo = {};
swapchainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainCreateInfo.surface = surface;
swapchainCreateInfo.minImageCount = swapChainImageCount;
swapchainCreateInfo.imageFormat = surfaceFormat.format;
swapchainCreateInfo.imageColorSpace = surfaceFormat.colorSpace;
swapchainCreateInfo.imageExtent = extent;
swapchainCreateInfo.imageArrayLayers = 1;
swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
uint32_t queueFamilyIndices[] = {indices.graphicsFamily, indices.presentFamily};
if (indices.graphicsFamily != indices.presentFamily) {
swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapchainCreateInfo.queueFamilyIndexCount = 2;
swapchainCreateInfo.pQueueFamilyIndices = queueFamilyIndices;
} else {
swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
swapchainCreateInfo.preTransform = swapChainSupport.capabilities.currentTransform;
swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchainCreateInfo.presentMode = presentMode;
swapchainCreateInfo.clipped = VK_TRUE;
swapchainCreateInfo.oldSwapchain = VK_NULL_HANDLE;
VkSwapchainKHR swapChain;
if (vkCreateSwapchainKHR(device, &swapchainCreateInfo, nullptr, &swapChain) != VK_SUCCESS) {
perror("failed to create swap chain!");
exit(EXIT_FAILURE);
}
vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, nullptr);
VkImage *swapChainImages = calloc(swapChainImageCount, sizeof(VkImage));
vkGetSwapchainImagesKHR(device, swapChain, &swapChainImageCount, swapChainImages);
VkFormat swapChainImageFormat = surfaceFormat.format;
VkExtent2D swapChainExtent = extent;
// endregion
// region image views
uint32_t swapChainImageViewsCount = swapChainImageCount;
VkImageView *swapChainImageViews = calloc(swapChainImageViewsCount, sizeof(VkImageView));
for (int i = 0; i < swapChainImageViewsCount; ++i) {
VkImageViewCreateInfo imageViewCreateInfo = {};
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.image = swapChainImages[i];
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = swapChainImageFormat;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &imageViewCreateInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) {
perror("failed ot create image views!");
exit(EXIT_FAILURE);
}
}
// endregion
// region render passes
/**
* <h2>Attachment description</h2>
*
* <p>Before creating the pipeline, we need to tell Vulkan about the
* <i>framebuffer attachments</i> that will be used while rendering.</p>
*
* We need to specify:
* <ul>
* <li>how many color and depth buffers there will be
* <li>how many samples to use for each of them
* <li>how their contents should be handled throughout the rendering ops.
* </ul>
*
* <p>All of the info is wrapped in a <i>render pass</i> object.<p>
*
* <p>Textures and frame-buffers in Vulkan are represented by
* <code>VkImage</code> objects with a certain pixel format,
* however the layout of the pixels in memory can change based on what
* we're trying to do with the an image.
*
* <dl>
* <dt><code>format</code></dt>
* <dd>The <code>format</code> of the colour attachment should match the
* format of the swap chain images.</dd>
* <dt><code>samples</code></dt>
* <dd>for <i>multisampling</i></dd>
* <dt><code>loadOp</code></dt>
* <dd>determines what to do with the data in the attachment before
* rendering. <i>applies to color and depth data</i> Possible values:
* <ul>
* <li><code>VK_ATTACHMENT_LOAD_OP_LOAD</code>: Preserve the existing contents
* of the attachment
* <li><code>VK_ATTACHMENT_LOAD_OP_CLEAR</code>: Clear the values to a
* constant at the start
* <li><code>VK_ATTACHMENT_OP_DONT_CARE</code>: Existing contents are undefined;
* we don't care about them
* </ul>
* </dd>
* <dt><code>storeOp</code></dt>
* <dd>determines what to do with the data in the attachment after rendering.
* <i>applies to color and depth data</i>
* Possible values:
* <ul>
* <li><code>VK_ATTACHMENT_STORE_OP_STORE</code>: Rendered contents will be
* stored in memory and can be read later
* <li><code>VK_ATTACHMENT_STORE_OP_DONT_CARE</code>: Contents of the
* framebuffer will be undefined after the rendering operation
* </ul>
* </dd>
* <dt><code>stencilLoadOp</code></dt>
* <dd>Same as <code>loadOp</code>, but for <i>stencil data</i></dd>
* <dt><code>stencilStoreOp</code></dt>
* <dd>Same as <code>storeOp</code>, but for <i>stencil data</i></dd>
* <dt><code>initialLayout</code></dt>
* <dd>specifies which layout the image will have before the render pass.
* Possible values:
* <ul>
* <li><code>VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL</code>: Images used as
* colour attachment
* <li><code>VK_IMAGE_LAYOUT_PRESENT_SRC_KHR</code>: Images to be presented
* in the swap chain
* <li><code>VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL</code>: Images to be used
* as destination for a memory copy operation
* </ul>
* </dd>
* <dt><code>finalLayout</code></dt>
* <dd>specifies the layout to automatically transition to when the render
* pass finishes. Possible values are the same as <code>initialLayout</code></dd>
* </dl>
*/
VkAttachmentDescription colorAttachment = {};
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
/**
* <h2>Subpasses and attachment references</h2>
*
* <p>A single <i>render pass</i> can consist of multiple <i>subpasses</i>.
* Subpasses are subsequent rendering operations that depend on the contents
* of framebuffers in previous passes.</p>
*
* <p>E.g., a sequence of post-processing effects that are applied one after
* another. If you group these rendering operations into one render pass,
* then Vulkan is able to reorder the operations and conserve memory
* bandwidth for possibly better performance.</p>
*
* <p>
* The <code>VkAttachmentReference</code> struct
* <dl>
* <dt><code>attachment</code></dt>
* <dd>Specifies which attachment to reference by its index in the attachment
* description array.</dd>
* <dt><code>layout</code></dt>
* <dd>Specifies which layout we would like the attachment to have during
* a subpass that uses this reference.</dd>
* </dl>
* </p>
*
* <p>
* The subpass is described using a <code>VkSubpassDescription</code> struct.
* <dl>
* <dt><code>pipelineBindPoint</code></dt>
* <dd>Specifies this subpass to be a Graphics subpass</dd>
* <dt><code>pColorAttachments</code></dt>
* <dd>
* <p>reference to the attachment referenced from the fragment shader.<p>
* E.g., in our example, the index of the attachment in this array
* is directly referenced from the fragment shader with
* <code>layout(location = 0) out vec4 outColor</code></p>
* </dd>
* <dt><code>pInputAttachments</code></dt>
* <dd>Attachments that are read from a shader</dd>
* <dt><code>pResolveAttachments</code></dt>
* <dd>Attachments used for multisampling color attachments</dd>
* <dt><code>pDepthStencilAttachment</code></dt>
* <dd>Attachment for depth and stencil data</dd>
* <dt><code>pPreserveAttachments</code></dt>
* <dd>Attachments that are not used by this subpass, but for which the data
* must be preserved.</dd>
* </dl>
* </p>
*/
VkAttachmentReference colorAttachmentRef = {};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
/**
* <h2>Render pass</h2>
*
*
*/
VkRenderPass renderPass;
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
perror("failed to create render pass!");
exit(EXIT_FAILURE);
}
// endregion
// region graphics pipeline
size_t vertShaderCodeLen = 0;
uint32_t *const vertShaderCode = readFile("/Users/samuel_paul_v/CLionProjects/vulkan_in_c/vert.spv",
&vertShaderCodeLen);
size_t fragShaderCodeLen = 0;
uint32_t *const fragShaderCode = readFile("/Users/samuel_paul_v/CLionProjects/vulkan_in_c/frag.spv",
&fragShaderCodeLen);
VkShaderModule vertShaderModule = createShaderModule(device, vertShaderCode, vertShaderCodeLen);
VkShaderModule fragShaderModule = createShaderModule(device, fragShaderCode, fragShaderCodeLen);
VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
// region fixed functions
/**
* <h2>Dynamic State</h2>
*
* most of the pipeline state needs to be baked into the pipeline state.
* But a limited amount of the state can actually be changed without
* recreating the pipeline at draw time.
*/
const uint32_t dynamicStatesCount = 2;
VkDynamicState *dynamicStates = calloc(2, sizeof(dynamicStates));
dynamicStates[0] = VK_DYNAMIC_STATE_VIEWPORT;
dynamicStates[1] = VK_DYNAMIC_STATE_SCISSOR;
VkPipelineDynamicStateCreateInfo dynamicState = {};
dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamicState.dynamicStateCount = dynamicStatesCount;
dynamicState.pDynamicStates = dynamicStates;
/**
* <h2>Vertex input</h2>
*
* The <code>VkPipelineVertexInputStateCreateInfo</code> structure
* describes the format of the vertex data that will be passes to the
* vertex shader. Describes in two ways:
*
* <ol>
* <li><strong>Binding</strong>: spacing between data and whether
* the data is per-vertex or per-instance</li>
* <li><strong>Attribute descriptions</strong>: type of the attributes
* passed to the vertex shader, which binding to load them from and at
* which offset.</li>
* </ol>
*/
VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 0;
vertexInputInfo.pVertexBindingDescriptions = nullptr; // Optional
vertexInputInfo.vertexAttributeDescriptionCount = 0;
vertexInputInfo.pVertexAttributeDescriptions = nullptr; // Optional
/**
* <h2>Input Assembly</h2>
*
* The <code>VkPipelineInputAssemblyStateCreateInfo</code> struct describes
* two things:
* <ul>