-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello_triangle_application.cpp
1983 lines (1661 loc) · 80.1 KB
/
hello_triangle_application.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 <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <optional>
#include <set>
#include <stdexcept>
#pragma warning(disable : 4201) // nameless struct/union
#include <glm/glm.hpp>
#pragma warning(default : 4201)
#pragma warning(disable : 4127) // consider constexpr
#include <glm/gtc/matrix_transform.hpp>
#pragma warning(default : 4127)
#define STB_IMAGE_IMPLEMENTATION
#pragma warning(disable : 4100) // unreferenced formal parameter
#include <stb_image.h>
#pragma warning(default : 4100)
#include "hello_triangle_application.h"
#include "shaders.h"
namespace {
const int max_frames_in_flight =
2; // Number of frames to be process concurrently
const std::vector<const char*> validation_layers = {
"VK_LAYER_LUNARG_standard_validation"};
const std::vector<const char*> device_extensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME};
VkResult CreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* p_create_info,
const VkAllocationCallbacks* p_allocator,
VkDebugUtilsMessengerEXT* p_callback) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
return func(instance, p_create_info, p_allocator, p_callback);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance,
VkDebugUtilsMessengerEXT callback,
const VkAllocationCallbacks* p_allocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(
instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, callback, p_allocator);
}
}
// Callback invoked by validation layers
VKAPI_ATTR VkBool32 VKAPI_CALL
debugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT /*messageSeverity*/,
VkDebugUtilsMessageTypeFlagsEXT /*messageType*/,
const VkDebugUtilsMessengerCallbackDataEXT* p_callback_data,
void* /*pUserData*/) {
std::cerr << "validation layer: " << p_callback_data->pMessage << std::endl;
// PFN_vkDebugUtilsMessengerCallbackEXT functions should always return
// VK_FALSE
return VK_FALSE;
}
// Checks if physical device supports all the extensions we require
bool checkDeviceExtensionSupport(VkPhysicalDevice device) {
uint32_t extension_count;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count,
nullptr);
std::vector<VkExtensionProperties> available_extensions(extension_count);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extension_count,
available_extensions.data());
std::set<std::string> required_extensions(device_extensions.begin(),
device_extensions.end());
for (const auto& extension : available_extensions) {
required_extensions.erase(extension.extensionName);
}
return required_extensions.empty();
}
bool checkValidationLayerSupport() {
uint32_t layer_count;
vkEnumerateInstanceLayerProperties(&layer_count, nullptr);
std::vector<VkLayerProperties> available_layers(layer_count);
vkEnumerateInstanceLayerProperties(&layer_count, available_layers.data());
for (const char* layer_name : validation_layers) {
bool layer_found = false;
for (const auto& layer_properties : available_layers) {
if (strcmp(layer_name, layer_properties.layerName) == 0) {
layer_found = true;
break;
}
}
if (!layer_found) {
return false;
}
}
return true;
}
std::vector<const char*> getRequiredExtensions() {
uint32_t glfw_extension_count = 0;
const char** glfw_extensions =
glfwGetRequiredInstanceExtensions(&glfw_extension_count);
std::vector<const char*> extensions(glfw_extensions,
glfw_extensions + glfw_extension_count);
#ifdef ENABLE_VALIDATION
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
return extensions;
}
VkPresentModeKHR chooseSwapPresentMode(
const std::vector<VkPresentModeKHR> available_present_modes) {
// VK_PRESENT_MODE_FIFO_KHR is guarantted to be available:
// The swap chain is a queue where the display takes an image from the front
// of the queue when the display is refreshed and the program inserts rendered
// images at the back of the queue.If the queue is full then the program has
// to wait.This is most similar to vertical sync as found in modern
// games.The moment that the display is refreshed is known as
//"vertical blank"
VkPresentModeKHR best_mode = VK_PRESENT_MODE_FIFO_KHR;
for (const auto& mode : available_present_modes) {
if (mode == VK_PRESENT_MODE_MAILBOX_KHR) {
// Instead of blocking the application when the queue is full,
// the images that are already queued are simply replaced with the newer
// ones.This mode can be used to implement triple buffering,
// which allows you to avoid tearing with significantly less latency
// issues than standard vertical sync that uses double buffering.
return mode;
} else if (mode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
// images are transferred to screen right away, may result in tearing
best_mode = mode;
}
}
return best_mode;
}
VkSurfaceFormatKHR chooseSwapSurfaceFormat(
const std::vector<VkSurfaceFormatKHR>& available_formats) {
// VkSurfaceFormatKHR is made up of a format(channel + type) and colour space
// If the surface has no preferred format VK_FORMAT_UNDEFINED is set, in
// which case use one of the most common RGB formats VK_FORMAT_B8G8R8A8_UNORM
if (available_formats.size() == 1 &&
available_formats[0].format == VK_FORMAT_UNDEFINED) {
return {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR};
}
// More than one format available, see if our preffered format is available
for (const auto& available_format : available_formats) {
if (available_format.format == VK_FORMAT_B8G8R8A8_UNORM &&
available_format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return available_format;
}
}
// Fallback to first format from queried list
return available_formats[0];
}
VkExtent2D chooseSwapExtent(GLFWwindow* window,
const VkSurfaceCapabilitiesKHR& capabilities) {
// Extent is the resolution of swap chain images and is almost always equal
// to the resolution of the window.
if (capabilities.currentExtent.width !=
std::numeric_limits<uint32_t>::max()) {
// Window manager allows resolution to differ
return capabilities.currentExtent;
} else {
// GLFW retrieves the size, in pixels, of the framebuffer of the specified
// window
assert(window != nullptr);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D actual_extent = {static_cast<uint32_t>(width),
static_cast<uint32_t>(height)};
// clamp width and height to implementation capabilities
actual_extent.width =
std::clamp(actual_extent.width, capabilities.minImageExtent.width,
capabilities.maxImageExtent.width);
actual_extent.height =
std::clamp(actual_extent.height, capabilities.minImageExtent.height,
capabilities.maxImageExtent.height);
return actual_extent;
}
}
// Queue's in Vulkan are grouped into families encapsulating subsets of
// functionality.
struct QueueFamilyIndices final {
bool isComplete() const {
return graphics_family.has_value() && present_family.has_value();
}
std::optional<uint32_t> graphics_family; // graphics queue available
std::optional<uint32_t> present_family; // WSI presentation queue available
};
VkShaderModule createShaderModule(VkDevice logical_device,
const std::vector<uint8_t>& code) {
VkShaderModuleCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = code.size();
create_info.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule shader_module;
if (vkCreateShaderModule(logical_device, &create_info, nullptr,
&shader_module) != VK_SUCCESS) {
throw std::runtime_error("failed to create shader module!");
}
return shader_module;
}
QueueFamilyIndices findQueueFamilies(VkSurfaceKHR surface,
VkPhysicalDevice device) {
// Find queue families supported by device
uint32_t queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_family_count,
nullptr);
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queue_family_count,
queue_families.data());
QueueFamilyIndices indices;
int i = 0;
for (const auto& queue_family : queue_families) {
// Check that family contains at least one queue, and that queues family
// support graphics operations
if ((queue_family.queueCount > 0) &&
(queue_family.queueFlags & VK_QUEUE_GRAPHICS_BIT)) {
indices.graphics_family = i;
}
// Not all devices support WSI(windows system integration), and not all
// queue families support presentation to a surface
VkBool32 present_support = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &present_support);
if ((queue_family.queueCount > 0) && present_support) {
indices.present_family = i;
}
if (indices.isComplete()) {
break;
}
i++;
}
return indices;
}
// Holds propeties for our surface relevant to swapchains
struct SwapChainSupportDetails final {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> present_modes;
};
SwapChainSupportDetails querySwapChainSupport(VkSurfaceKHR surface,
VkPhysicalDevice device) {
// Query capabilities of surface
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface,
&details.capabilities);
// Query supported surface formats, e.g. RGB, SRGB representations
uint32_t format_count;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &format_count, nullptr);
if (format_count != 0) {
details.formats.resize(format_count);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &format_count,
details.formats.data());
}
// Query supported surface presentation modes, e.g immediately or blocking
uint32_t present_mode_count;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface,
&present_mode_count, nullptr);
if (present_mode_count != 0) {
details.present_modes.resize(present_mode_count);
vkGetPhysicalDeviceSurfacePresentModesKHR(
device, surface, &present_mode_count, details.present_modes.data());
}
return details;
}
// Holds data needed by vertex shader
struct Vertex final {
glm::vec2 pos;
glm::vec3 colour;
glm::vec2 tex_coord;
static VkVertexInputBindingDescription getBindingDescription() {
// A vertex binding describes how to load data from memory throughout the
// vertices
VkVertexInputBindingDescription binding_description = {};
// Only have 1 binding as all data is packed into a single array
binding_description.binding = 0;
// Stride is number of bytes between 2 continugous elements in buffer
binding_description.stride = sizeof(Vertex);
// Per vertex rendering rather than instance rendering
binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return binding_description;
}
static std::array<VkVertexInputAttributeDescription, 3>
getAttributeDescriptions() {
// attribute description desfines how to extract a vertex attribute
// from a chunk of vertex data originating from a binding description.
// We have 2 attributes, colour and position
std::array<VkVertexInputAttributeDescription, 3> attribute_descriptions =
{};
// position attribute
attribute_descriptions[0].binding = 0; // we only have 1 binding
attribute_descriptions[0].location =
0; // location 0 in shader
// 2-component vector of 32-bit single precision floats
attribute_descriptions[0].format = VK_FORMAT_R32G32_SFLOAT;
attribute_descriptions[0].offset = offsetof(Vertex, pos);
// colour attribute
attribute_descriptions[1].binding = 0; // we only have 1 binding
attribute_descriptions[1].location = 1; // location 1 in shader
// 3-component vector of 32-bit single precision floats
attribute_descriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attribute_descriptions[1].offset = offsetof(Vertex, colour);
// Texture coordinates
attribute_descriptions[2].binding = 0;
attribute_descriptions[2].location = 2;
attribute_descriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attribute_descriptions[2].offset = offsetof(Vertex, tex_coord);
return attribute_descriptions;
}
};
uint32_t findMemoryType(uint32_t type_filter, VkMemoryPropertyFlags properties,
VkPhysicalDevice device) {
// Physical memory is defined in terms of heaps and types
// Memory heaps are distinct memory resources like dedicated VRAM and swap
// space in RAM for when VRAM runs out. The different types of memory exist
// within these heaps
VkPhysicalDeviceMemoryProperties mem_properties;
vkGetPhysicalDeviceMemoryProperties(device, &mem_properties);
for (uint32_t i = 0; i < mem_properties.memoryTypeCount; i++) {
// type_filter is bitfield of suitable memory types
const bool suitable_type = type_filter & (1 << i);
// check desired properties of memory, like writable & coherence
if (suitable_type && (mem_properties.memoryTypes[i].propertyFlags &
properties) == properties) {
// Return first matching memory type
return i;
}
}
throw std::runtime_error("failed to find suitable memory type!");
}
VkCommandBuffer beginSingleTimeCommands(VkDevice logical_device,
VkCommandPool command_pool) {
// Allocate command buffer to submit
VkCommandBufferAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
alloc_info.commandPool = command_pool;
alloc_info.commandBufferCount = 1; // Single
VkCommandBuffer command_buffer;
vkAllocateCommandBuffers(logical_device, &alloc_info, &command_buffer);
// Only submitted once
VkCommandBufferBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// start recording
vkBeginCommandBuffer(command_buffer, &begin_info);
return command_buffer;
}
void endSingleTimeCommands(VkCommandBuffer command_buffer, VkQueue queue,
VkDevice logical_device,
VkCommandPool command_pool) {
// end recording
vkEndCommandBuffer(command_buffer);
// Submit single command buffer
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffer;
// Submit commands
vkQueueSubmit(queue, 1, &submit_info, VK_NULL_HANDLE);
// wait for operations to finish
vkQueueWaitIdle(queue);
vkFreeCommandBuffers(logical_device, command_pool, 1, &command_buffer);
}
void createBuffer(VkDevice logical_device, VkPhysicalDevice physical_device,
VkDeviceSize size, VkBufferUsageFlags usage,
VkMemoryPropertyFlags properties, VkBuffer& buffer,
VkDeviceMemory& buffer_memory) {
VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = size;
// Puropse of buffer, e.g. vertex or staging
buffer_info.usage = usage;
// Only owened by graphics queue
buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(logical_device, &buffer_info, nullptr, &buffer) !=
VK_SUCCESS) {
throw std::runtime_error("failed to create vertex buffer!");
}
// Query memory properties of device; size, alignment, and type
VkMemoryRequirements mem_requirements;
vkGetBufferMemoryRequirements(logical_device, buffer, &mem_requirements);
// Allocate on device memory
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
// required size of allocation to hold buffer
alloc_info.allocationSize = mem_requirements.size;
alloc_info.memoryTypeIndex = findMemoryType(mem_requirements.memoryTypeBits,
properties, physical_device);
if (vkAllocateMemory(logical_device, &alloc_info, nullptr, &buffer_memory) !=
VK_SUCCESS) {
throw std::runtime_error("failed to allocate vertex buffer memory!");
}
// Binds device memory to buffer
vkBindBufferMemory(logical_device, buffer, buffer_memory,
0 /* offset into memory region*/);
}
// Needs to match struct in vertex shader source
struct UniformBufferObject final {
alignas(16) glm::mat4 model; // Model in world space relative to origin
alignas(16) glm::mat4 view; // Camera view, rotation around origin
alignas(16)
glm::mat4 proj; // Project to screen, so 3D model can be rendered in 2D
};
void updateUniformBuffer(VkDevice device, VkDeviceMemory ubo_image,
VkExtent2D swap_chain_extent) {
// Rotate geometry 90 degrees per second regardless of frame rate
static auto start_time = std::chrono::high_resolution_clock::now();
const auto current_time = std::chrono::high_resolution_clock::now();
const float time = std::chrono::duration<float, std::chrono::seconds::period>(
current_time - start_time)
.count();
UniformBufferObject ubo = {};
// Model to world
const glm::f32 model_angle = time * glm::radians(90.0f); // 90 degrees
const glm::vec3 model_axis = glm::vec3(0.0f, 0.0f, 1.0f); // Z rotation axis
ubo.model = glm::rotate(glm::mat4(1.0f), model_angle, model_axis);
// Position of camera's viewpoint
const glm::vec3 view_eye = glm::vec3(2.0f, 2.0f, 2.0f);
// Center is where you are looking at, the origin
const glm::vec3 view_center = glm::vec3(0.0f, 0.0f, 0.0f);
// Defines worlds upwards direction towards positive
const glm::vec3 view_up = glm::vec3(0.0f, 0.0f, 1.0f);
// View from camera space
ubo.view = glm::lookAt(view_eye, view_center, view_up);
// 45 degree field of view
const float proj_fov = glm::radians(45.0f);
// Aspect ratio should match window size
const float proj_aspect_ratio = static_cast<float>(swap_chain_extent.width) /
static_cast<float>(swap_chain_extent.height);
// Near and far clip distance thresholds
const float proj_near = 0.1f;
const float proj_far = 10.0f;
// Create projection matrix from 3D to 2D
ubo.proj = glm::perspective(proj_fov, proj_aspect_ratio, proj_near, proj_far);
// In OpenGL the Y coordinate of the clip coordinates is inverted, Flip the
// sign on the scaling factor of the Y axis to compensate
ubo.proj[1][1] *= -1;
// Copy data MVP matricies to uniform buffer so it's available to the device
void* data;
vkMapMemory(device, ubo_image, 0, sizeof(ubo), 0, &data);
std::memcpy(data, &ubo, sizeof(ubo));
vkUnmapMemory(device, ubo_image);
}
void createImage(VkDevice device, VkPhysicalDevice physical_device,
uint32_t width, uint32_t height, VkFormat format,
VkImageTiling tiling, VkImageUsageFlags usage,
VkMemoryPropertyFlags properties, VkImage& image,
VkDeviceMemory& image_memory) {
VkImageCreateInfo image_info = {};
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
// 1D could be used for gradients, or 3D for Voxels, but 2D works for texture
image_info.imageType = VK_IMAGE_TYPE_2D;
// Extent described dimenions as texels per axis
image_info.extent.width = width;
image_info.extent.height = height;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.format = format;
image_info.tiling = tiling;
// First transition will discard texels, okay since we're first going to
// transition the image to be a transfer destination and then copy texel
// data to it from a buffer object
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.usage = usage;
// Only 11 sample since we're not mutlisampling
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
// Image only used by our graphics queue family
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateImage(device, &image_info, nullptr, &image) != VK_SUCCESS) {
throw std::runtime_error("failed to create image!");
}
// Query image for device specific memory requirements
VkMemoryRequirements mem_requirements;
vkGetImageMemoryRequirements(device, image, &mem_requirements);
// Allocate device memory for image
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.allocationSize = mem_requirements.size;
alloc_info.memoryTypeIndex = findMemoryType(mem_requirements.memoryTypeBits,
properties, physical_device);
// Allocate device memory
if (vkAllocateMemory(device, &alloc_info, nullptr, &image_memory) !=
VK_SUCCESS) {
throw std::runtime_error("failed to allocate image memory!");
}
// Bind device memory to image object
vkBindImageMemory(device, image, image_memory, 0);
}
VkImageView createImageView(VkDevice device, VkImage image, VkFormat format) {
VkImageViewCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
create_info.image = image;
create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
create_info.format = format;
// Default mapping, don't swizzle channels
create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
// Colour view without any mipmapping or layering
create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
create_info.subresourceRange.baseMipLevel = 0;
create_info.subresourceRange.levelCount = 1;
create_info.subresourceRange.baseArrayLayer = 0;
create_info.subresourceRange.layerCount = 1;
VkImageView image_view;
if (vkCreateImageView(device, &create_info, nullptr, &image_view) !=
VK_SUCCESS) {
throw std::runtime_error("failed to create image view!");
}
return image_view;
}
// Colour & Position of our rectangles vertices
const std::vector<Vertex> vertices = {
{{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {1.0f, 0.0f}}, // Top-left red
{{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f}}, // Top-right green
{{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}, {0.0f, 1.0f}}, // Bottom-right blue
{{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {1.0f, 1.0f}} // Bottom-right white
};
// Indicies into vertex buffer of 2 triangles used to make
// rectangle, rather than redunancy in vertex buffer.
const std::vector<uint16_t> vertex_indices = {0, 1, 2, 2, 3, 0};
} // namespace
void HelloTriangleApplication::runMainLoop() {
// While windows not closed
while (!glfwWindowShouldClose(window)) {
glfwPollEvents(); // check for events
// Acquire an image from the swap chain, execute the command buffer with
// that image as attachment in the framebuffer, then finally return the
// image to the swap chain for presentation
drawFrame();
}
}
void HelloTriangleApplication::initVulkan() {
createInstance(); // Initalize VkInstance member
setupDebugCallback(); // Set message handler for validation layers
// Create a surface for our window so we have have something to render to.
// A VkSurfaceKHR represents an abstract type of surface which is platform
// independent.
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) !=
VK_SUCCESS) {
throw std::runtime_error("failed to create window surface!");
}
// Find a physical device with support for all vulkan features we need
pickPhysicalDevice();
// A logical device represents a connection to a physical device describing
// the features we want to use.
createLogicalDevice();
// A swapchain provides the ability to present rendering results to a WSI
// surface. Used as a framebuffer holding a queue of images that are waitin
// to be presented to the screen.
createSwapChain();
// An image view is a view into an image, describing how to access the image
// and which part of the image to access. Create a view for our swap chain
createImageViews();
// A renderpass contains the structure of the frame, encapsulating the set of
// framebuffer attachments.
createRenderPass();
// We use Uniform Buffer descriptors in our vertex shader, initalize the
// description set layout so we can pass it to the pipeline layout step of
// graphics pipeline creation.
createDescriptorSetLayout();
// Load SPIR-V vertex & framgement shaders then setup graphics pipeline
createGraphicsPipeline();
// A framebuffer object references all of the VkImageView objects that
// represent the renderpass attachments.
createFramebuffers();
// Command pools manage memory used to store command buffers
createCommandPool();
// Loads an to use as a textire and turns it into a Vulkan image object.
createTextureImage();
// Create view to access our texture image
createTextureImageView();
// Creaye a sampler to read colours from the texture in the shader, samplers
// apply filtering(e.g bilinear, anisotropic) and transformations(e.g clamp
// to egde, mirror repeat) to compute the final color that is retrieved.
createTextureSampler();
// Create a buffer to store our vertex data
createVertexBuffer();
// Create buffer storing indicies into vertex buffer
createIndexBuffer();
// Create uniform buffer per swap chain image which our vertex shader reads
// MVP matricies from.
createUniformBuffers();
// Create pool to allocate descriptor sets from, then allocate the sets
// themselves
createDescriptorPool();
createDescriptorSets();
// Create a command buffer for every image in swapchain
createCommandBuffers();
// Create semaphores and fences to synchronise frame processing
createSyncObjects();
}
void HelloTriangleApplication::createInstance() {
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pApplicationName = "Hello Triangle";
app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.pEngineName = "No Engine";
app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pApplicationInfo = &app_info;
const auto extensions = getRequiredExtensions();
create_info.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
create_info.ppEnabledExtensionNames = extensions.data();
#ifdef ENABLE_VALIDATION
if (!checkValidationLayerSupport()) {
throw std::runtime_error("validation layers requested, but not available!");
}
create_info.enabledLayerCount =
static_cast<uint32_t>(validation_layers.size());
create_info.ppEnabledLayerNames = validation_layers.data();
#else
create_info.enabledLayerCount = 0;
#endif
if (vkCreateInstance(&create_info, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance!");
}
#ifndef NDEBUG
uint32_t extension_count = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, nullptr);
std::vector<VkExtensionProperties> vk_extensions(extension_count);
vkEnumerateInstanceExtensionProperties(nullptr, &extension_count,
vk_extensions.data());
std::cout << "available extensions:" << std::endl;
for (const auto& extension : vk_extensions) {
std::cout << "\t" << extension.extensionName << std::endl;
}
#endif // !NDEBUG
}
void HelloTriangleApplication::setupDebugCallback() {
#ifdef ENABLE_VALIDATION
VkDebugUtilsMessengerCreateInfoEXT create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
create_info.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;
create_info.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;
create_info.pfnUserCallback =
debugCallback; // callback function invoked by validation layer
create_info.pUserData = nullptr;
// Assign debug callback triggered when an event occurs
if (CreateDebugUtilsMessengerEXT(instance, &create_info, nullptr,
&validation_callback) != VK_SUCCESS) {
throw std::runtime_error("failed to set up debug callback!");
}
#endif
}
void HelloTriangleApplication::pickPhysicalDevice() {
physical_device = VK_NULL_HANDLE;
uint32_t device_count = 0;
vkEnumeratePhysicalDevices(instance, &device_count, nullptr);
if (device_count == 0) {
throw std::runtime_error("failed to find any devices with Vulkan support");
}
std::vector<VkPhysicalDevice> devices(device_count);
vkEnumeratePhysicalDevices(instance, &device_count, devices.data());
// Iterate over all discoverd Vulkan enabled devices
for (const auto& dev : devices) {
// Check device supports all the extensions we require
const bool extensions_supported = checkDeviceExtensionSupport(dev);
if (!extensions_supported) {
continue;
}
// Check supports queue families with all the functionality we need
const QueueFamilyIndices q_indices = findQueueFamilies(surface, dev);
if (!q_indices.isComplete()) {
continue;
}
// Check surface supports properties we need for swapchains, one supported
// image format and one supported presentation mode will do for now
const SwapChainSupportDetails swap_chain_support =
querySwapChainSupport(surface, dev);
if (swap_chain_support.formats.empty() ||
swap_chain_support.present_modes.empty()) {
continue;
}
// Check support for ansiotropic filtering for our texure sampler
VkPhysicalDeviceFeatures supported_features;
vkGetPhysicalDeviceFeatures(dev, &supported_features);
if (!supported_features.samplerAnisotropy) {
continue;
}
// Physcial device meets all our criteria for suitablilty
physical_device = dev;
}
if (physical_device == VK_NULL_HANDLE) {
throw std::runtime_error("failed to find a suitable GPU!");
}
}
void HelloTriangleApplication::createLogicalDevice() {
const QueueFamilyIndices indices =
findQueueFamilies(surface, physical_device);
const std::set<uint32_t> unique_queue_families = {
indices.graphics_family.value(), indices.present_family.value()};
// Priority is between 0.0 and 1.0, higher values indicate a higher priority
const float queue_priority = 1.0f;
// Create infos for queue families we need
std::vector<VkDeviceQueueCreateInfo> queue_create_infos;
for (uint32_t queue_family : unique_queue_families) {
VkDeviceQueueCreateInfo queue_create_info = {};
queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_create_info.queueFamilyIndex = queue_family;
queue_create_info.queueCount = 1; // Only want a single queue per family
queue_create_info.pQueuePriorities = &queue_priority;
queue_create_infos.push_back(queue_create_info);
}
// Don't need any special features, all entries default to VK_FALSE
VkPhysicalDeviceFeatures device_features = {};
device_features.samplerAnisotropy = VK_TRUE; // Used in texture samper
VkDeviceCreateInfo create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.queueCreateInfoCount =
static_cast<uint32_t>(queue_create_infos.size());
create_info.pQueueCreateInfos = queue_create_infos.data();
create_info.pEnabledFeatures = &device_features;
create_info.enabledExtensionCount =
static_cast<uint32_t>(device_extensions.size());
create_info.ppEnabledExtensionNames = device_extensions.data();
#ifdef ENABLE_VALIDATION
create_info.enabledLayerCount =
static_cast<uint32_t>(validation_layers.size());
create_info.ppEnabledLayerNames = validation_layers.data();
#else
create_info.enabledLayerCount = 0;
#endif
if (vkCreateDevice(physical_device, &create_info, nullptr, &logical_device) !=
VK_SUCCESS) {
throw std::runtime_error("failed to create logical device!");
}
// Queues are created along with the logical device, but we need to retrieve
// the handles. Because we've only created a single queue in each family we
// can hardcode the index to 0.
vkGetDeviceQueue(logical_device, indices.graphics_family.value(), 0,
&graphics_queue);
vkGetDeviceQueue(logical_device, indices.present_family.value(), 0,
&present_queue);
}
void HelloTriangleApplication::createSwapChain() {
// Find properties surface has relevant to swap chains
const SwapChainSupportDetails swap_chain_support =
querySwapChainSupport(surface, physical_device);
// Select a colour depth from available list
const VkSurfaceFormatKHR surface_format =
chooseSwapSurfaceFormat(swap_chain_support.formats);
// Select the conditions for swapping images to screen from available list
const VkPresentModeKHR present_mode =
chooseSwapPresentMode(swap_chain_support.present_modes);
// Select resolution of images in swapchain from avilable bitfield
const VkExtent2D extent =
chooseSwapExtent(window, swap_chain_support.capabilities);
// Set number of images in swap chain, i.e the queue length, try min+1 to
// implement triple buffering
uint32_t image_count = swap_chain_support.capabilities.minImageCount + 1;
if (swap_chain_support.capabilities.maxImageCount > 0 &&
image_count > swap_chain_support.capabilities.maxImageCount) {
image_count = swap_chain_support.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
create_info.surface = surface;
create_info.minImageCount = image_count;
create_info.imageFormat = surface_format.format;
create_info.imageColorSpace = surface_format.colorSpace;
create_info.imageExtent = extent;
create_info.imageArrayLayers = 1; // Layers are only >1 for stereoscopic 3D
create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
// How to handle images used across multiple queue families
const QueueFamilyIndices indices =
findQueueFamilies(surface, physical_device);
const uint32_t queue_family_indices[] = {indices.graphics_family.value(),
indices.present_family.value()};
if (indices.graphics_family != indices.present_family) {
// Images can be used across multiple queues without expilict
// ownership transfers.
create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
create_info.queueFamilyIndexCount = 2;
create_info.pQueueFamilyIndices = queue_family_indices;
} else {
// Image is owned by 1 queue family at a time, and must be explicitly
// transferred.
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
create_info.preTransform = swap_chain_support.capabilities.currentTransform;
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create_info.presentMode = present_mode;
create_info.clipped = VK_TRUE;
create_info.oldSwapchain = VK_NULL_HANDLE;
if (vkCreateSwapchainKHR(logical_device, &create_info, nullptr,
&swap_chain) != VK_SUCCESS) {
throw std::runtime_error("failed to create swap chain!");
}
// Get array of presentable images associated with a swapchain
vkGetSwapchainImagesKHR(logical_device, swap_chain, &image_count, nullptr);
swap_chain_images.resize(image_count);
vkGetSwapchainImagesKHR(logical_device, swap_chain, &image_count,
swap_chain_images.data());
swap_chain_image_format = surface_format.format;
swap_chain_extent = extent;
}
void HelloTriangleApplication::createImageViews() {
// Create a view for every image in our swap chain
swap_chain_image_views.resize(swap_chain_images.size());
for (size_t i = 0; i < swap_chain_images.size(); i++) {
swap_chain_image_views[i] = createImageView(
logical_device, swap_chain_images[i], swap_chain_image_format);
}
}
void HelloTriangleApplication::transitionImageLayout(VkImage image,
VkFormat format,
VkImageLayout old_layout,
VkImageLayout new_layout) {
// Format will be used later for special transitions in the depth buffer
(void)format;
// Start recording command buffer for our transition operations
VkCommandBuffer command_buffer =
beginSingleTimeCommands(logical_device, command_pool);
// Pipeline barrier, rather than host<->device sync
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = old_layout;
barrier.newLayout = new_layout;
// We're not transferring queue ownwership
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
// Specifies operations that should happen before the barrier
VkPipelineStageFlags source_stage;
// Specifies operations that should happen after the barrier
VkPipelineStageFlags destination_stage;
if (old_layout == VK_IMAGE_LAYOUT_UNDEFINED &&