-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvulkan_test.cpp
More file actions
3355 lines (2594 loc) · 118 KB
/
vulkan_test.cpp
File metadata and controls
3355 lines (2594 loc) · 118 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
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <limits>
#include <algorithm>
#include <string.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#include <array>
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const bool enableValidationLayers = true;
const int MAX_FRAMES_IN_FLIGHT = 2;
int currentFrame = 0;
int frame = 0;
const int numRootBVs = 1;
bool framebufferResized = false;
GLFWwindow* window;
VkSurfaceKHR surface;
VkInstance instance;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice logicalDevice;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkQueue computeQueue;
VkSwapchainKHR swapChain;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkFormat swapChainImageFormat;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
VkDescriptorSetLayout descriptorSetLayout;
VkPipelineLayout pipelineLayout;
VkPipeline graphicsPipeline;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkCommandPool commandPool;
std::vector<VkCommandBuffer> commandBuffers;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
VkImage depthImage;
VkDeviceMemory depthImageMemory;
VkImageView depthImageView;
std::vector<VkBuffer> uniformBuffers;
std::vector<VkDeviceMemory> uniformBuffersMemory;
std::vector<void*> uniformBuffersMapped;
VkDescriptorPool descriptorPool;
std::vector<VkDescriptorSet> descriptorSets;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
std::vector<VkFence> computeInFlightFences;
std::vector<VkSemaphore> computeFinishedSemaphores;
VkSampler imageSampler;
VkImage computeOutImage;
VkImageView computeOutImageView;
VkDeviceMemory computeOutImageMemory;
VkImage computeLastOutImage;
VkImageView computeLastOutImageView;
VkDeviceMemory computeLastOutImageMemory;
VkPipeline computePipeline;
VkPipelineLayout computePipelineLayout;
VkDescriptorSetLayout computeDescriptorSetLayout;
std::vector<VkCommandBuffer> computeCommandBuffers;
std::vector<VkDescriptorSet> computeDescriptorSets;
struct UniformBufferObject {
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
};
struct vecTwo {
alignas(8) glm::vec2 xy;
};
struct ivecOne {
alignas(4) glm::ivec1 x;
};
struct sphere {
alignas(16) glm::vec4 dim;
};
// need to set size in shader
const int spheresSize = 1024;
struct spheres {
alignas(16) glm::vec4 dims[spheresSize];
alignas(16) glm::ivec4 mats[spheresSize/4];
};
struct material {
alignas(16) glm::vec4 colAndR;
alignas(16) glm::vec3 emmision;
};
struct materials {
alignas(16) glm::vec4 colAndR[16];
alignas(16) glm::vec4 emmision[16];
alignas(16) glm::vec4 refractionVals[16];
};
struct triangle {
alignas(16) glm::vec3 v1;
alignas(16) glm::vec3 v2;
alignas(16) glm::vec3 v3;
};
struct triangles {
// xyz are pos w is if needed
alignas(16) glm::vec4 v1[16];
alignas(16) glm::vec4 v2[16];
alignas(16) glm::vec4 v3[16];
};
const int indsSize = 131072;
struct indicies {
// xyz are index w is mat
alignas(16) glm::ivec4 indx[indsSize];
};
const int vertsSize = 65536;
struct verticies {
// xyz are pos w is if needed
alignas(16) glm::vec4 verts[vertsSize];
};
const int bvhSize = 262144;
struct bvh{
//
alignas(16) glm::vec4 data[bvhSize];
};
struct computeState{
alignas(16) glm::vec3 pos;
alignas(8) glm::vec2 angles;
alignas(8) glm::vec2 screenExtent;
alignas(4) glm::ivec1 x;
alignas(4) glm::ivec1 numRootBVs;
};
struct Vertex{
glm::vec3 pos;
glm::vec3 col;
static VkVertexInputBindingDescription getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;// can be VK_VERTEX_INPUT_RATE_INSTANCED
return bindingDescription;
}
static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, col);
return attributeDescriptions;
}
};
const float size = 4.0;
const std::vector<Vertex> vertices = {
{{-size, -size, size}, {0.0f, 0.0f, 0.0f}},
{{size, -size, size}, {0.0f, 0.0f, 1.0f}},
{{size, size, size}, {0.0f, 1.0f, 0.0f}},
{{-size, size, size}, {0.0f, 1.0f, 1.0f}},
{{-size, -size, -size}, {1.0f, 0.0f, 0.0f}},
{{size, -size, -size}, {1.0f, 0.0f, 1.0f}},
{{size, size, -size}, {1.0f, 1.0f, 0.0f}},
{{-size, size, -size}, {1.0f, 1.0f, 1.0f}}
};
const std::vector<uint16_t> indices = {
//0, 1, 2, 2, 3, 0
0,3,1,
4,5,7,// open cube
0,1,4,
1,2,5,
3,7,2,
4,7,0,
3,2,1,
5,6,7,
1,5,4,
2,6,5,
7,6,2,
7,3,0
};
const std::vector<const char *> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
struct QueueStruct {
int graphicsFamily = -1;
int presentFamily = -1;
int graphicsAndComputeFamily = -1;
bool isComplete() {
return (graphicsFamily != -1)&&(presentFamily != -1);
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
bool checkValidationLayerSupport();
void initWindow();
void initVulkan();
void createInstance();
void createSurface();
void pickHardWareDevices();
bool validDevice(VkPhysicalDevice device);
QueueStruct findQueues(VkPhysicalDevice device);
bool hasNeededExtensions(VkPhysicalDevice device);
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device);
void createLogicalDevice();
void createSwapChain();
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities);
void createImageViews();
void createDescriptorSetLayout();
void createGraphicsPipeline();
static std::vector<char> readFile(const std::string& filename);
VkShaderModule createShaderModule(const std::vector<char>& code);
void createRenderPass();
void createFramebuffers();
void createCommandPool();
void createDepthResources();
VkFormat findDepthFormat();
void createVertexBuffer();
uint32_t findMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
void createIndexBuffer();
void createUniformBuffers();
void createDescriptorPool();
void createDescriptorSets();
void createCommandBuffers();
void recordCommandBuffer(VkCommandBuffer commandBuffer, uint32_t imageIndex);
void createSyncObjects();
void createSampler();
void mainLoop();
void updateUniformBuffer(uint32_t currentImage);
void drawFrame();
void cleanUp();
void createComputeCommandBuffers();
void createComputeImages();
void createComputePipeLine();
void createComputeDescriptorSetLayout();
void createComputeDescriptorSets();
void recordComputeCommandBuffer(VkCommandBuffer commandBuffer,int i);
bool hasStencilComponent(VkFormat format);
void transitionImageLayout(VkImage image, VkFormat format, VkImageLayout startLayout, VkImageLayout endLayout);
VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags);
VkFormat findSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features);
void recreateSwapChain();// incase current one is invalidated
void cleanupSwapChain();
static void framebufferResizeCallback(GLFWwindow* window, int width, int height);
void createImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory);
void createBuffer(VkDeviceSize size, VkBufferUsageFlags usage,VkMemoryPropertyFlags properties, VkBuffer &returnBuffer, VkDeviceMemory &returnBufferMemory);
void copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
class Model{
public:
Model(std::vector<Vertex> vertices, std::vector<uint16_t> indices);
~Model();
// only use when recording the command buffer
void showSelf(VkCommandBuffer commandBuffer);
private:
void setUpVertexBuffer(std::vector<Vertex> verts);
void setUpIndexBuffer(std::vector<uint16_t> inds);
VkBuffer mVertexBuffer;
VkDeviceMemory mVertexBufferMemory;
VkBuffer mIndexBuffer;
VkDeviceMemory mIndexBufferMemory;
int numIndicies;
int numVerticies;
};
std::vector<Model> models;
bool mainBvhNeedGenerating = true;
class bvhDataManager{
public:
bvhDataManager(){
for (int i = 0; i < bvhSize; i++){
bvhData.data[i] = glm::vec4(0);
dataAlloc[i] = -1;
}
}
// change a length of dataAlloc to set type can be used to dealloc
void allocateMem(int start, int length, int type){
if (start + length > bvhSize){
length = bvhSize-start;
}
for (int i = 0; i < length; i++){
dataAlloc[i+start] = type;
}
}
int findUnAllocSpace(int length){
int consecutive = 0;
for (int i = 0; i < bvhSize; i++){
if (dataAlloc[i] == -1){
consecutive++;
}
else{
consecutive = 0;
}
if (consecutive == length){
return i-length+1;
}
}
return -1;
}
bvh bvhData;
int dataAlloc[bvhSize];
};
bvhDataManager mainBvhDM;
int main() {
initWindow();
initVulkan();
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
std::cout << extensionCount << " extensions supported\n";
const std::vector<Vertex> verts = {
{{-2.0f, -2.0f, -2.0f}, {1.0f, 0.0f, 0.0f}},
{{-2.0f, -2.0f, 2.0f}, {1.0f, 0.0f, 1.0f}},
{{-2.0f, 2.0f, -2.0f}, {0.0f, 1.0f, 0.0f}},
{{2.0f, -2.0f, -2.0f}, {1.0f, 0.0f, 0.0f}}
};
const std::vector<uint16_t> inds = {
0,1,2,
3,1,0,
3,2,0,
3,2,1
};
//Model newModel = Model(verts,inds);
//models.push_back(newModel);
mainLoop();
cleanUp();
return 0;
}
void initWindow(){
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
//glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // due to being able to recreate the swap chain is not needed
window = glfwCreateWindow(800, 608, "Vulkan window", nullptr, nullptr);
glfwSetFramebufferSizeCallback(window, framebufferResizeCallback);
}
void initVulkan(){
createInstance();
createSurface();
pickHardWareDevices();
createLogicalDevice();
createSwapChain();
createImageViews();
createCommandPool();
createComputeImages();// must be before descriptors made
transitionImageLayout(computeOutImage, VK_FORMAT_R16G16B16A16_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
transitionImageLayout(computeLastOutImage, VK_FORMAT_R16G16B16A16_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
createSampler();
createRenderPass();
createDescriptorSetLayout();
createGraphicsPipeline();
createDepthResources();
createFramebuffers();
createVertexBuffer();
createIndexBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createComputeDescriptorSetLayout();
createComputeDescriptorSets();
createComputeCommandBuffers();
createComputePipeLine();
createSyncObjects();
}
void createInstance(){
if (enableValidationLayers && !checkValidationLayerSupport()) {
throw std::runtime_error("validation layers requested, but not available!");
}
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;
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> requiredExtensions;
for(uint32_t i = 0; i < glfwExtensionCount; i++) {
requiredExtensions.emplace_back(glfwExtensions[i]);
}
#if __APPLE__
requiredExtensions.emplace_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
createInfo.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR;
#endif
createInfo.enabledExtensionCount = (uint32_t) requiredExtensions.size();
createInfo.ppEnabledExtensionNames = requiredExtensions.data();
VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);
std::cout << result << "\n";
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance!");
}
}
bool checkValidationLayerSupport() {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const VkLayerProperties& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}
void createSurface() {
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
throw std::runtime_error("failed to create window surface!");
}
}
void pickHardWareDevices(){
physicalDevice = VK_NULL_HANDLE;
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0){
std::cout << "no gpus with vulkan support\n";
throw std::runtime_error("failed to find GPUs with Vulkan support!");
}
std::cout << deviceCount << " gpus\n";
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const VkPhysicalDevice& device : devices) {
std::cout << device << "hi\n";
std::cout << devices.size() << "\n";
if (device == VK_NULL_HANDLE){
std::cout << "??\n";
}
if (validDevice(device)) {
physicalDevice = device;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU!");
}
}
bool validDevice(VkPhysicalDevice device){
// version supported and other stuff
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
std::cout << deviceProperties.deviceName << "\n";
// what optional support is there
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
QueueStruct indcies = findQueues(device);
if (!indcies.isComplete()){
std::cout << "error missing vital queue\n";
return false;
}
std::cout << indcies.graphicsFamily << " graphic queue\n";
if (!hasNeededExtensions(device)){
std::cout << "lacks extentions\n";
return false;
}
bool swapChainAdequate = false;
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
std::cout << swapChainSupport.formats.size() << " " << swapChainSupport.presentModes.size() << "\n";
if (!swapChainAdequate){
std::cout << "not swap chain adequate\n";
return false;
}
return true;
}
QueueStruct findQueues(VkPhysicalDevice device){
QueueStruct indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const VkQueueFamilyProperties& queueFamily : queueFamilies){
std::cout << i << " queue\n";
std::cout << queueFamily.queueFlags << "\n";
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT){
indices.graphicsFamily = i;
}
VkBool32 canPresent = false;
std::cout << surface << "\n";
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &canPresent);
if (canPresent){
indices.presentFamily = i;
}
if((queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT)){
indices.graphicsAndComputeFamily = i;
}
if (indices.isComplete()){
//break;
}
i++;
}
return indices;
}
bool hasNeededExtensions(VkPhysicalDevice device){
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const VkExtensionProperties& extension : availableExtensions) {
std::cout << extension.extensionName << "\n";
requiredExtensions.erase(extension.extensionName);
}
for (auto i = requiredExtensions.begin(); i != requiredExtensions.end(); i++){
std::cout << "does not have extension " << *i << "\n";
}
return requiredExtensions.empty();
}
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device) {
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0) {
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0) {
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
void createLogicalDevice(){
QueueStruct indices = findQueues(physicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies;
uniqueQueueFamilies.insert(indices.graphicsFamily);
uniqueQueueFamilies.insert(indices.presentFamily);
uniqueQueueFamilies.insert(indices.graphicsAndComputeFamily);
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies) {
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures{};
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &logicalDevice) != VK_SUCCESS) {
throw std::runtime_error("failed to create logical device!");
}
vkGetDeviceQueue(logicalDevice, indices.graphicsFamily, 0, &graphicsQueue);
vkGetDeviceQueue(logicalDevice, indices.presentFamily, 0, &presentQueue);
vkGetDeviceQueue(logicalDevice, indices.graphicsAndComputeFamily, 0, &computeQueue);
}
void createSwapChain(){
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;// +1 so dont have to wait for driver to finish as much
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {// 0 means no max
imageCount = swapChainSupport.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueStruct indices = findQueues(physicalDevice);
uint32_t queueFamilyIndices[] = {static_cast<uint32_t>(indices.graphicsFamily), static_cast<uint32_t>(indices.presentFamily)};
if (indices.graphicsFamily != indices.presentFamily) {
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
} else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0; // Optional
createInfo.pQueueFamilyIndices = nullptr; // Optional
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = VK_NULL_HANDLE;
if (vkCreateSwapchainKHR(logicalDevice, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
throw std::runtime_error("failed to create swap chain!");
}
vkGetSwapchainImagesKHR(logicalDevice, swapChain, &imageCount, nullptr);
swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(logicalDevice, swapChain, &imageCount, swapChainImages.data());
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
}
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
for (const VkSurfaceFormatKHR& availableFormat : availableFormats) {
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) {
for (const VkPresentModeKHR& availablePresentMode : availablePresentModes) {
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
return capabilities.currentExtent;
} else {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actualExtent = {
static_cast<uint32_t>(width),
static_cast<uint32_t>(height)
};
actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
return actualExtent;
}
}
void createImageViews(){
swapChainImageViews.resize(swapChainImages.size());
for (int i = 0; i < swapChainImages.size(); i++) {
swapChainImageViews[i] = createImageView(swapChainImages[i],swapChainImageFormat,VK_IMAGE_ASPECT_COLOR_BIT);
}
}
VkImageView createImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags){
VkImageViewCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = image;
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = format;
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 = aspectFlags;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
if (vkCreateImageView(logicalDevice, &createInfo, nullptr, &imageView) != VK_SUCCESS) {
throw std::runtime_error("failed to create image views!");
}
return imageView;
}
void createDescriptorSetLayout() {
std::array<VkDescriptorSetLayoutBinding,3> uboLayoutBindings{};
uboLayoutBindings[0].binding = 0;
uboLayoutBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBindings[0].descriptorCount = 1;
uboLayoutBindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBindings[0].pImmutableSamplers = nullptr; // Optional
uboLayoutBindings[1].binding = 1;
uboLayoutBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
uboLayoutBindings[1].descriptorCount = 1;
uboLayoutBindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
uboLayoutBindings[1].pImmutableSamplers = nullptr; // Optional??
uboLayoutBindings[2].binding = 2;
uboLayoutBindings[2].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBindings[2].descriptorCount = 1;
uboLayoutBindings[2].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
uboLayoutBindings[2].pImmutableSamplers = nullptr; // Optional
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = uboLayoutBindings.size();
layoutInfo.pBindings = uboLayoutBindings.data();
if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("failed to create descriptor set layout!");
}
}
void createGraphicsPipeline(){
std::vector<char> vertShaderCode = readFile("vulkan_shaders/shader_vert.spv");
std::vector<char> fragShaderCode = readFile("vulkan_shaders/shader_frag.spv");
VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
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";
VkPipelineShaderStageCreateInfo shaderStages[] = {vertShaderStageInfo, fragShaderStageInfo};
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
auto bindingDescription = Vertex::getBindingDescription();
auto attributeDescriptions = Vertex::getAttributeDescriptions();
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
std::vector<VkDynamicState> dynamicStates = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR