summaryrefslogtreecommitdiffstats
path: root/src/vksetup.h
blob: 8e146370e3a8d417ae1159174157a60c71aab6d0 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
#ifndef _VKSETUP_H
#define _VKSETUP_H
/* Start header file */

/**
  vulkan setup and basic vector math

  Single header file with included implementation in the spirit of
  stb_*                          <https://github.com/nothings/stb>

  ASSUMPTIONS:
  ~~~~~~~~~~~~
  - Using SDL2 for the window
  - Using cglm for maths
  - Using shaderc for compiling glsl
  - Using vulkan(!)

  This is not meant to be a generic werapper around vulkan. It is actively
  paired and chaned by the currently in development application, whatever that
  might be. Think of it as the vulkan setup configuratior and helper.

  USAGE:
  ~~~~~~
   Do this:
      #define VKSETUP_IMPLEMENTATION
   before you include this file in *one* C or C++ file to create the implementation.

   // i.e. it should look like this:
   #include ...
   #include ...
   #include ...
   #define VKSETUP_IMPLEMENTATION
   #include "vksetup.h"

 */

#include <vulkan/vulkan_core.h>
#define SDL_MAIN_HANDLED
#define VK_USE_PLATFORM_XCB_KHR
#include <stdarg.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>

#include <vulkan/vulkan.h>
#include <vulkan/vk_enum_string_helper.h> // for string_VkResult

#include <shaderc/shaderc.h>

#include "vk_mem_alloc.h"

#include "../lib/cglm/include/cglm/cglm.h"

#define VK_ARRAY_LEN(arr) sizeof((arr))/sizeof((arr)[0])

#ifdef __clang__
#define __FILENAME__ __FILE_NAME__
#else
#define __FILENAME__ __FILE__
#endif

#define VK_CHECK(x)                                   \
do {                                                  \
  VkResult err = x;                                   \
  if (err < 0) {                                      \
    fprintf(stderr, "src/%s:%d:0: vulkan error: %s   \n", \
    __FILENAME__, __LINE__, string_VkResult(err));        \
    abort();                                          \
  }                                                   \
} while (0)

typedef enum {
  VK_INFO = 0,
  VK_WARN,
  VK_ERROR,
} log_type;

static inline void
_vk_log(log_type t, const char * f, ...)
{
#ifdef VKDEBUG
  va_list args;
  va_start(args, f);
  switch (t) {
  case VK_INFO:
    printf("INFO: ");
    vprintf(f, args);
    break;
  case VK_WARN:
    fprintf(stderr, "WARN: ");
    vfprintf(stderr, f, args);
    break;
  case VK_ERROR:
    fprintf(stderr, "ERROR: ");
    vfprintf(stderr, f, args);
    break;
  }
  va_end(args);
#else
  return;
#endif
}

#ifdef VKDEBUG
#define vk_log(t, ...) do {                                \
  fprintf(t == VK_INFO ? stdout : stderr, "src/%s:%d:0: ", \
  __FILENAME__, __LINE__);                                 \
  _vk_log(t, __VA_ARGS__);                                 \
} while(0)
#else
#define vk_log(t, ...)
#endif

/**********/
/* config */
/**********/

const char *const validation_layers[] = {
  "VK_LAYER_KHRONOS_validation"
};
const uint32_t validation_layer_count = VK_ARRAY_LEN(validation_layers);

const char *const device_extensions[] = {
    VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
const uint32_t deviceExtensionCount = VK_ARRAY_LEN(device_extensions);

#ifdef VKDEBUG
    const bool enable_validation_layers = true;
#else
    const bool enable_validation_layers = false;
#endif



#ifdef __cplusplus
extern "C" {
#endif

#ifndef VKSDEF
#ifdef VKS_STATIC
#define VKSDEF static
#else
#define VKSDEF extern
#endif
#endif

typedef struct vks_swapchain {
  VkSwapchainKHR handle;

  VkFormat image_format;
  VkExtent2D extent;

  uint32_t image_count;

  // todo: relace with vks_image although
  // memory is managed by the swapchain
  VkImage images[5];
  VkImageView image_views[5]; // 5 for some reason
} vks_swapchain;

typedef struct vks_buffer {
  VkBuffer handle;
  VkDeviceMemory memory;
  VmaAllocation allocation;
} vks_buffer;

typedef struct vks_image {
  VkImage handle;
  VkDeviceMemory memory;
  VkImageView view;
  VmaAllocation allocation;
} vks_image;

typedef struct vks_pipeline {
  VkPipeline handle;
  VkPipelineLayout layout;
} vks_pipeline;

typedef struct vks_context {
  VkInstance instance;
  VkPhysicalDevice physical_device;
  VkDevice device;

  SDL_Window *window;
  VkSurfaceKHR surface;

  vks_swapchain swapchain;

  VkQueue graphics_and_compute_queue;
  VkQueue present_queue;
  VkQueue transfer_queue;

  VkCommandPool command_pool;

  vks_image color_image;
  vks_image depth_image;

  VmaAllocator allocator;

  VkSampleCountFlagBits msaa_samples;
} vks_context;

typedef struct vks_frame_data {
  VkCommandBuffer vk_command_buffer;

  VkSemaphore image_available_semaphore;
  VkSemaphore render_finished_semaphore;
  VkFence in_flight_fence;

  vks_buffer uniform_buffer;
  void * uniform_buffer_mapped;

  VkDescriptorSet vk_descriptor_set;
} vks_frame_data;

/* Info structs  */
typedef struct vks_transition_image_layout_info
{
  /* image */
  VkImage              image;
  VkFormat             format;
  VkAccessFlags        srcAccessMask;
  VkAccessFlags        dstAccessMask;
  VkPipelineStageFlags srcStageMask;
  VkPipelineStageFlags dstStageMask;
  VkImageLayout        oldLayout;
  VkImageLayout        newLayout;
  uint32_t             mipLevels;
} vks_transition_image_layout_info;


/* Exported API */
VKSDEF void        vks_create_vulkan_context   (vks_context *vk);
VKSDEF void        vks_destroy_vulkan_context  (vks_context *vk);
VKSDEF void        vks_create_buffer           (const vks_context vk, const VkDeviceSize size, const VkBufferUsageFlags usage, vks_buffer *buffer);
VKSDEF void        vks_create_image            (const vks_context vk, const uint32_t width, const uint32_t height, const uint32_t mipLevels, const VkFormat format, const VkImageTiling tiling, const VkImageUsageFlags usage, const VkSampleCountFlagBits numSamples, vks_image *image);
VKSDEF void        vks_transition_image_layout (const vks_context vk, const vks_transition_image_layout_info *info);
VKSDEF void        vks_copy_buffer             (const vks_context vk, const VkBuffer src_buffer, VkBuffer dst_buffer, const VkDeviceSize size);
VKSDEF void        vks_copy_buffer_to_image    (const vks_context vk, const VkBuffer buffer, VkImage  image, const uint32_t width, const uint32_t height);
VKSDEF void        vks_generate_mipmaps        (const vks_context vk, VkImage  image, const VkFormat imageFormat, const int32_t  texWidth, const int32_t  texHeight, const uint32_t mipLevels);
VKSDEF VkImageView vks_create_image_view       (const vks_context vk, VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
VKSDEF VkFormat    vks_find_depth_format       (const vks_context vk);
/* VKSDEF void vulkan_create_descriptor_set_layout(); */
/* VKSDEF void vulkan_create_graphics_pipeline(); */
/* VKSDEF void vulkan_create_command_pool(); */
/* VKSDEF void vulkan_create_depth_resources(); */
/* VKSDEF void vulkan_create_texture_image(); */
/* VKSDEF void vulkan_create_texture_image_view(); */
/* VKSDEF void vulkan_create_texture_sampler(); */
/* VKSDEF void vulkan_create_vertex_buffer(); */
/* VKSDEF void vulkan_create_index_buffer(); */
/* VKSDEF void vulkan_create_uniform_buffers(); */
/* VKSDEF void vulkan_create_descriptor_pool(); */
/* VKSDEF void vulkan_create_descriptor_sets(); */
/* VKSDEF void vulkan_create_command_buffer(); */
/* VKSDEF void vulkan_create_sync_objects(); */

#ifdef __cplusplus
}
#endif

/* End header file */
#endif  /* _VKSETUP_H */

#ifdef VKSETUP_IMPLEMENTATION

#include <stddef.h>
#include <stdlib.h>
#include <time.h>

#include "pds.h"

/* Vks helpers */

static bool
_vks_check_validation_layer_support(const char* const validation_layers[],
                                    uint32_t          validation_layer_count)
{
  uint32_t layerCount;
  vkEnumerateInstanceLayerProperties(&layerCount, NULL);

  VkLayerProperties availableLayers[layerCount];
  vkEnumerateInstanceLayerProperties(&layerCount, availableLayers);

  bool layerFound = false;
  for (uint32_t i = 0; i < validation_layer_count; i++) {
    for (uint32_t j = 0; j < layerCount; j++) {
      if (strcmp(validation_layers[i], availableLayers[j].layerName) == 0) {
        layerFound = true;
        break;
      }
    }
  }

  return layerFound;
}

VKSDEF VkCommandBuffer
_vks_begin_single_time_commands(const vks_context vk)
{
  VkCommandBufferAllocateInfo allocInfo = {0};
  allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  allocInfo.commandPool = vk.command_pool;
  allocInfo.commandBufferCount = 1;

  VkCommandBuffer commandBuffer;
  VK_CHECK(vkAllocateCommandBuffers(vk.device, &allocInfo, &commandBuffer));

  VkCommandBufferBeginInfo beginInfo = {0};
  beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

  VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo));

  return commandBuffer;
}
VKSDEF void
_vks_end_single_time_commands(const vks_context vk, VkCommandBuffer command_buffer)
{
  VK_CHECK(vkEndCommandBuffer(command_buffer));

  VkSubmitInfo submitInfo = {0};
  submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  submitInfo.commandBufferCount = 1;
  submitInfo.pCommandBuffers = &command_buffer;

  VK_CHECK(vkQueueSubmit(vk.graphics_and_compute_queue, 1, &submitInfo, VK_NULL_HANDLE));
  VK_CHECK(vkQueueWaitIdle(vk.graphics_and_compute_queue));

  vkFreeCommandBuffers(vk.device, vk.command_pool, 1, &command_buffer);
}

static int
_has_stencil_component(VkFormat format)
{
  return format == VK_FORMAT_D32_SFLOAT_S8_UINT ||
         format == VK_FORMAT_D24_UNORM_S8_UINT;
}

static VkInstance
_vks_create_instance(bool              validation_layers_toggle,
                     const char* const validation_layers[],
                     uint32_t          validation_layer_count,
                     SDL_Window*       window)
{
  if (validation_layers_toggle &&
      !_vks_check_validation_layer_support(validation_layers,
                                          validation_layer_count)) {
    vk_log(VK_ERROR, "validation layers requested, but not available!\n");
    abort();
  }

  uint32_t instanceVersion;
  VkResult result = vkEnumerateInstanceVersion(&instanceVersion);
  if (result == VK_SUCCESS) {
    if (instanceVersion < VK_MAKE_API_VERSION(0, 1, 3, 0)) {
      vk_log(VK_ERROR, "Vulkan version 1.3 or greater required!\n");
      exit(1);
    }
    vk_log(VK_INFO,
           "Vulkan version found (%d) %d.%d.%d\n",
           VK_API_VERSION_VARIANT(instanceVersion),
           VK_API_VERSION_MAJOR(instanceVersion),
           VK_API_VERSION_MINOR(instanceVersion),
           VK_API_VERSION_PATCH(instanceVersion));
  } else {
    vk_log(VK_ERROR,
           "Failed to retrieve vulkan version, is vulkan supported in this "
           "system?\n");
    exit(1);
  }

  // Load Vulkan and create instance
  VkApplicationInfo appInfo = {
    .sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO,
    .pApplicationName   = "Vulkan Application",
    .applicationVersion = VK_MAKE_API_VERSION(0, 1, 3, 0),
    .pEngineName        = NULL,
    .engineVersion      = VK_MAKE_API_VERSION(0, 1, 3, 0),
    .apiVersion         = VK_MAKE_API_VERSION(0, 1, 3, 0),
  };

  uint32_t sdlExtensionCount = 0;

  if (SDL_Vulkan_GetInstanceExtensions(window, &sdlExtensionCount, NULL) ==
      SDL_FALSE) {
    vk_log(VK_ERROR,
           "SDL_Vulkan_GetInstanceExtensions failed: %s\n",
           SDL_GetError());
    abort();
  }

  // make space for debug extenetion
  if (validation_layers_toggle) {
    sdlExtensionCount++;
  }

  const char* sdlExtensions[sdlExtensionCount];

  if (SDL_Vulkan_GetInstanceExtensions(
        window, &sdlExtensionCount, sdlExtensions) == SDL_FALSE) {
    vk_log(VK_ERROR,
           "SDL_Vulkan_GetInstanceExtensions failed: %s\n",
           SDL_GetError());
    abort();
  }

  // add debug extenetion
  if (validation_layers_toggle) {
    sdlExtensions[sdlExtensionCount] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
  }

  vk_log(VK_INFO, "The sdl extensions:\n");
  for (uint32_t i = 0; i < sdlExtensionCount; i++) {
    vk_log(VK_INFO, "\t%s\n", sdlExtensions[i]);
  }

  VkInstanceCreateInfo createInfo = {
    .sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
    .pApplicationInfo        = &appInfo,
    .enabledExtensionCount   = sdlExtensionCount,
    .ppEnabledExtensionNames = sdlExtensions,
    .enabledLayerCount       = 0,
  };

  if (validation_layers_toggle) {
    createInfo.enabledLayerCount   = validation_layer_count;
    createInfo.ppEnabledLayerNames = validation_layers;
  }

  VkInstance instance;

  if (vkCreateInstance(&createInfo, NULL, &instance) != VK_SUCCESS) {
    vk_log(VK_ERROR, "Can't start vulkan instance\n");
  }
  vk_log(VK_INFO, "Vulkan instance created\n");

  return instance;
}

static bool
_vulkan_check_device_extension_support(VkPhysicalDevice device)
{
  uint32_t extensionCount;
  vkEnumerateDeviceExtensionProperties(device, NULL, &extensionCount, NULL);

  VkExtensionProperties availableExtensions[extensionCount];
  vkEnumerateDeviceExtensionProperties(
    device, NULL, &extensionCount, availableExtensions);

  uint32_t flag = 0;

  for (uint32_t i = 0; i < deviceExtensionCount; i++) {
    for (uint32_t j = 0; j < extensionCount; j++) {
      if (strcmp(device_extensions[i], availableExtensions[j].extensionName) ==
          0) {
        flag++;
        break;
      }
    }
  }

  return flag == deviceExtensionCount;
}

typedef struct _QueueFamilyIndices
{
  uint32_t graphicsAndComputeFamily;
  bool     graphicsFlag;
  uint32_t presentFamily;
  bool     presentFlag;
} _QueueFamilyIndices;

static bool
_vulkan_queue_family_check_flags(_QueueFamilyIndices x)
{
  return x.graphicsFlag && x.presentFlag;
}

static _QueueFamilyIndices
_vulkan_find_queue_families(vks_context* vk, VkPhysicalDevice device)
{
  _QueueFamilyIndices indices;
  indices.graphicsFlag = false;
  indices.presentFlag  = false;

  uint32_t queueFamilyCount = 0;
  vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, NULL);

  VkQueueFamilyProperties queueFamilies[queueFamilyCount];
  vkGetPhysicalDeviceQueueFamilyProperties(
    device, &queueFamilyCount, queueFamilies);

  /* vk_log(VK_INFO, "Found %ld queues\n", queueFamilyCount); */
  /* for (uint32_t i = 0; i < queueFamilyCount; i++) { */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_GRAPHICS_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_COMPUTE_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_TRANSFER_BIT) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_TRANSFER_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_SPARSE_BINDING_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_PROTECTED_BIT) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_PROTECTED_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_VIDEO_DECODE_BIT_KHR) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_VIDEO_DECODE_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_VIDEO_ENCODE_BIT_KHR) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_VIDEO_ENCODE_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /*   if (queueFamilies[i].queueFlags & VK_QUEUE_OPTICAL_FLOW_BIT_NV) { */
  /*     vk_log(VK_INFO, "  %d: VK_QUEUE_OPTICAL_FLOW_BIT\n", queueFamilies[i].queueFlags); */
  /*   } */
  /* } */
  for (uint32_t i = 0; i < queueFamilyCount; i++) {
    if ((queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) &&
        (queueFamilies[i].queueFlags & VK_QUEUE_COMPUTE_BIT)) {
      indices.graphicsAndComputeFamily = i;
      indices.graphicsFlag             = true;
    }

    VkBool32 presentSupport = false;
    vkGetPhysicalDeviceSurfaceSupportKHR(
      device, i, vk->surface, &presentSupport);
    if (presentSupport) {
      indices.presentFamily = i;
      indices.presentFlag   = true;
    }

    if (_vulkan_queue_family_check_flags(indices))
      break;
  }

  return indices;
}

typedef struct _swap_chain_support_details
{
  VkSurfaceCapabilitiesKHR capabilities;
  VkSurfaceFormatKHR       *formats;
  VkPresentModeKHR         *presentModes;
} _swap_chain_support_details;

static _swap_chain_support_details
_query_swap_chain_support(const vks_context* vk, VkPhysicalDevice device)
{
  // TODO Make SwapChainSupportDetails malloc it;s arrays and free it after it
  // is used.
  _swap_chain_support_details details;

  vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
    device, vk->surface, &details.capabilities);

  uint32_t format_count, present_mode_count;
  
  vkGetPhysicalDeviceSurfaceFormatsKHR(
    device, vk->surface, &format_count, NULL);

  if (format_count != 0) {
    details.formats = pstack_create_ex(VkSurfaceFormatKHR, format_count);
    vkGetPhysicalDeviceSurfaceFormatsKHR(
      device, vk->surface, &format_count, details.formats);
    pstack_size_set(details.formats, format_count);
  }
  
  vkGetPhysicalDeviceSurfacePresentModesKHR(
    device, vk->surface, &present_mode_count, NULL);

  if (present_mode_count != 0) {
    details.presentModes = pstack_create_ex(VkPresentModeKHR, present_mode_count);
    vkGetPhysicalDeviceSurfacePresentModesKHR(
      device, vk->surface, &present_mode_count, details.presentModes);
    pstack_size_set(details.presentModes, present_mode_count);
  }

  return details;
}

static bool
_vulkan_is_device_suitable(vks_context* vk, VkPhysicalDevice device)
{
  _QueueFamilyIndices indices = _vulkan_find_queue_families(vk, device);
  bool extensionsSupported    = _vulkan_check_device_extension_support(device);

  bool swapChainAdequate = false;
  if (extensionsSupported) {
    _swap_chain_support_details swapChainSupport =
      _query_swap_chain_support(vk, device);
    swapChainAdequate = !(pstack_size(swapChainSupport.formats) == 0) &&
                        !(pstack_size(swapChainSupport.presentModes) == 0);

    pstack_destroy(swapChainSupport.formats);
    pstack_destroy(swapChainSupport.presentModes);
  }

  VkPhysicalDeviceFeatures supportedFeatures;
  vkGetPhysicalDeviceFeatures(device, &supportedFeatures);

  return _vulkan_queue_family_check_flags(indices) && extensionsSupported &&
         swapChainAdequate && supportedFeatures.samplerAnisotropy;
}

static VkSampleCountFlagBits
_get_max_usable_sample_count(vks_context* vk)
{
  VkPhysicalDeviceProperties physicalDeviceProperties;
  vkGetPhysicalDeviceProperties(vk->physical_device, &physicalDeviceProperties);

  VkSampleCountFlags counts =
    physicalDeviceProperties.limits.framebufferColorSampleCounts &
    physicalDeviceProperties.limits.framebufferDepthSampleCounts;
  if (counts & VK_SAMPLE_COUNT_64_BIT) {
    return VK_SAMPLE_COUNT_64_BIT;
  }
  if (counts & VK_SAMPLE_COUNT_32_BIT) {
    return VK_SAMPLE_COUNT_32_BIT;
  }
  if (counts & VK_SAMPLE_COUNT_16_BIT) {
    return VK_SAMPLE_COUNT_16_BIT;
  }
  if (counts & VK_SAMPLE_COUNT_8_BIT) {
    return VK_SAMPLE_COUNT_8_BIT;
  }
  if (counts & VK_SAMPLE_COUNT_4_BIT) {
    return VK_SAMPLE_COUNT_4_BIT;
  }
  if (counts & VK_SAMPLE_COUNT_2_BIT) {
    return VK_SAMPLE_COUNT_2_BIT;
  }

  return VK_SAMPLE_COUNT_1_BIT;
}

static void
_vulkan_pick_physical_device(vks_context* vk)
{
  uint32_t deviceCount = 0;
  vkEnumeratePhysicalDevices(vk->instance, &deviceCount, NULL);
  if (deviceCount == 0) {
    vk_log(VK_INFO, "failed to find GPUs with Vulkan support!\n");
  }

  VkPhysicalDevice devices[deviceCount];
  vkEnumeratePhysicalDevices(vk->instance, &deviceCount, devices);

  for (uint32_t i = 0; i < deviceCount; i++) {
    if (_vulkan_is_device_suitable(vk, devices[i])) {
      vk->physical_device = devices[i];
      vk->msaa_samples    = _get_max_usable_sample_count(vk);
      break;
    }
  }

  if (vk->physical_device == VK_NULL_HANDLE) {
    vk_log(VK_ERROR, "failed to find a suitable GPU!\n");
  }

  VkPhysicalDeviceProperties deviceProperties;
  vkGetPhysicalDeviceProperties(vk->physical_device, &deviceProperties);
  vk_log(
    VK_INFO, "Picked [%s] physical device.\n", deviceProperties.deviceName);

  uint32_t extensionCount = 0;
  vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, NULL);
  VkExtensionProperties extensions[extensionCount];
  vkEnumerateInstanceExtensionProperties(NULL, &extensionCount, extensions);

  vk_log(VK_INFO, "Vulkan enabled extensions:\n");
  for (uint32_t i = 0; i < extensionCount; i++) {
    vk_log(VK_INFO, "\t%s\n", extensions[i].extensionName);
  }
}

static void
_vulkan_create_logical_device(vks_context* vk)
{
  _QueueFamilyIndices indices =
    _vulkan_find_queue_families(vk, vk->physical_device);

  // TODO CREATE MULPILE QUEUES
  // https://vulkan-tutorial.com/en/Drawing_a_triangle/Presentation/Window_surface#page_Creating-the-presentation-queue

  VkDeviceQueueCreateInfo queueCreateInfo = {
    .sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
    .queueFamilyIndex = indices.graphicsAndComputeFamily,
    .queueCount       = 1,
  };

  float queuePriority              = 1.0f;
  queueCreateInfo.pQueuePriorities = &queuePriority;

  VkPhysicalDeviceFeatures deviceFeatures = { 0 };
  vkGetPhysicalDeviceFeatures(vk->physical_device, &deviceFeatures);
  deviceFeatures.samplerAnisotropy = VK_TRUE;
  // deviceFeatures.sampleRateShading = VK_TRUE;
#ifndef VKDEBUG
  /* Disable robust buffer access when building without debug */
  deviceFeatures.robustBufferAccess = VK_FALSE;
#endif

  VkPhysicalDeviceDynamicRenderingFeaturesKHR dynamic_rendering_feature = {
    .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR,
    .dynamicRendering = VK_TRUE,
  };

  VkDeviceCreateInfo createInfo = {
    .sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
    .pQueueCreateInfos       = &queueCreateInfo,
    .queueCreateInfoCount    = 1,
    .pNext                   = &dynamic_rendering_feature,
    .pEnabledFeatures        = &deviceFeatures,
    .enabledExtensionCount   = deviceExtensionCount,
    .ppEnabledExtensionNames = device_extensions,
    .enabledLayerCount       = 0,
  };

  if (vkCreateDevice(vk->physical_device, &createInfo, NULL, &vk->device) !=
      VK_SUCCESS) {
    vk_log(VK_ERROR, "failed to create logical device!\n");
  }
  vk_log(VK_INFO, "Vulkan logical device created\n");

  vkGetDeviceQueue(vk->device,
                   indices.graphicsAndComputeFamily,
                   0,
                   &vk->graphics_and_compute_queue);
  vkGetDeviceQueue(vk->device, indices.presentFamily, 0, &vk->present_queue);
}

static VkExtent2D
_chooseSwapExtent(const vks_context*              vk,
                  const VkSurfaceCapabilitiesKHR* capabilities)
{
  if (capabilities->currentExtent.width != UINT32_MAX) {
    return capabilities->currentExtent;
  } else {
    int width, height;
    SDL_GetWindowSize(vk->window, &width, &height);

    VkExtent2D actualExtent;
    actualExtent.width  = (uint32_t)width;
    actualExtent.height = (uint32_t)height;

    // Manual implementation of std::clamp since it is not available in C
    actualExtent.width =
      (actualExtent.width < capabilities->minImageExtent.width)
        ? capabilities->minImageExtent.width
      : (actualExtent.width > capabilities->maxImageExtent.width)
        ? capabilities->maxImageExtent.width
        : actualExtent.width;

    actualExtent.height =
      (actualExtent.height < capabilities->minImageExtent.height)
        ? capabilities->minImageExtent.height
      : (actualExtent.height > capabilities->maxImageExtent.height)
        ? capabilities->maxImageExtent.height
        : actualExtent.height;

    return actualExtent;
  }
}

VKSDEF void
_vulkan_create_swap_chain(vks_context* vk)
{
  _swap_chain_support_details swapChainSupport =
    _query_swap_chain_support(vk, vk->physical_device);

  VkSurfaceFormatKHR surfaceFormat;
  while (!pstack_pop(swapChainSupport.formats, &surfaceFormat)) {
  //for (uint32_t i = 0; i < formatCount; i++) {
    if (surfaceFormat.format == VK_FORMAT_B8G8R8A8_SRGB &&
        surfaceFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
      break;
    }
  }

  pstack_destroy(swapChainSupport.formats);

  VkPresentModeKHR presentMode;
  while (!pstack_pop(swapChainSupport.presentModes, &presentMode)) {
    if (presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
      break;
    }
  }

  if (pstack_size(swapChainSupport.presentModes) == 0 &&
      presentMode != VK_PRESENT_MODE_MAILBOX_KHR) {
    presentMode = VK_PRESENT_MODE_FIFO_KHR;
  }
    
  pstack_destroy(swapChainSupport.presentModes);

  VkExtent2D extent = _chooseSwapExtent(vk, &swapChainSupport.capabilities);

  uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;

  if (swapChainSupport.capabilities.maxImageCount > 0 &&
      imageCount > swapChainSupport.capabilities.maxImageCount) {
    imageCount = swapChainSupport.capabilities.maxImageCount;
  }

  VkSwapchainCreateInfoKHR createInfo = {
    .sType            = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
    .surface          = vk->surface,
    .minImageCount    = imageCount,
    .imageFormat      = surfaceFormat.format,
    .imageColorSpace  = surfaceFormat.colorSpace,
    .imageExtent      = extent,
    .imageArrayLayers = 1,
    .imageUsage       = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
  };

  _QueueFamilyIndices indices =
    _vulkan_find_queue_families(vk, vk->physical_device);

  uint32_t queueFamilyIndices[] = { indices.graphicsAndComputeFamily,
                                    indices.presentFamily };

  if (indices.graphicsAndComputeFamily != 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   = NULL; // 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;

  VK_CHECK(
    vkCreateSwapchainKHR(vk->device, &createInfo, NULL, &vk->swapchain.handle));
  /* if (result != VK_SUCCESS) { */
  /*   vk_log(VK_ERROR, "ERROR: failed to create swap chain!  %s\n",
   * string_VkResult(result)); */
  /* } */

  VK_CHECK(vkGetSwapchainImagesKHR(
    vk->device, vk->swapchain.handle, &vk->swapchain.image_count, NULL));
  // vk_log(VK_INFO, "vk_swap_chain_images count: %d\n",
  // vk->swapchain.image_count);
  //  todo alloc space for images
  VK_CHECK(vkGetSwapchainImagesKHR(vk->device,
                                   vk->swapchain.handle,
                                   &vk->swapchain.image_count,
                                   vk->swapchain.images));

  vk->swapchain.image_format = surfaceFormat.format;
  vk->swapchain.extent       = extent;

  vk_log(VK_INFO, "Vulkan swapchain created!\n");

  for (size_t i = 0; i < vk->swapchain.image_count; i++) {
    vk->swapchain.image_views[i] =
      vks_create_image_view(*vk,
                            vk->swapchain.images[i],
                            vk->swapchain.image_format,
                            VK_IMAGE_ASPECT_COLOR_BIT,
                            1);
  }
}

static void
_vulkan_create_command_pool(vks_context *vk)
{
  _QueueFamilyIndices queueFamilyIndices = _vulkan_find_queue_families(vk, vk->physical_device);

  VkCommandPoolCreateInfo poolInfo = {0};
  poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  // AMD doesn't like this flag for some reason
  poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsAndComputeFamily;

  VK_CHECK(vkCreateCommandPool(vk->device, &poolInfo, NULL, &vk->command_pool));
}

VkFormat
_findSupportedFormat(const vks_context   vk,
                    VkFormat*            candidates,
                    size_t               n,
                    VkImageTiling        tiling,
                    VkFormatFeatureFlags features)
{
  for (size_t i = 0; i < n; i++) {
    VkFormat           format = candidates[i];
    VkFormatProperties props;
    vkGetPhysicalDeviceFormatProperties(vk.physical_device, format, &props);

    if (tiling == VK_IMAGE_TILING_LINEAR &&
        (props.linearTilingFeatures & features) == features) {
      return format;
    } else if (tiling == VK_IMAGE_TILING_OPTIMAL &&
               (props.optimalTilingFeatures & features) == features) {
      return format;
    }
  }

  vk_log(VK_ERROR, "failed to find supported format!\n");
  abort();
}

VKSDEF VkFormat
vks_find_depth_format(const vks_context vk)
{
  VkFormat formats[] = { VK_FORMAT_D32_SFLOAT,
                         VK_FORMAT_D32_SFLOAT_S8_UINT,
                         VK_FORMAT_D24_UNORM_S8_UINT };
  return _findSupportedFormat(vk, formats,
                             VK_ARRAY_LEN(formats),
                             VK_IMAGE_TILING_OPTIMAL,
                             VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
}

VKSDEF void
_vulkan_create_depth_resources(vks_context *vk)
{
  VkFormat depth_format = vks_find_depth_format(*vk);
  vks_create_image(*vk,
                   vk->swapchain.extent.width,
                   vk->swapchain.extent.height,
                   1,
                   depth_format,
                   VK_IMAGE_TILING_OPTIMAL,
                   VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
                   vk->msaa_samples,
                   &vk->depth_image);
  vk->depth_image.view = vks_create_image_view(*vk, vk->depth_image.handle, depth_format,
                                               VK_IMAGE_ASPECT_DEPTH_BIT, 1);

  vks_transition_image_layout_info transition_info = { 0 };
  transition_info.image          = vk->depth_image.handle;
  transition_info.format         = depth_format;
  transition_info.srcAccessMask  = VK_ACCESS_NONE;
  transition_info.dstAccessMask  = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |
                                  VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  transition_info.srcStageMask = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  transition_info.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
  transition_info.oldLayout    = VK_IMAGE_LAYOUT_UNDEFINED;
  transition_info.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  transition_info.mipLevels = 1;

  //vks_transition_image_layout(*vk, &transition_info);
}

VKSDEF void
_vulkan_create_color_resources(vks_context *vk)
{
  VkFormat colorFormat = vk->swapchain.image_format;

  vks_create_image(*vk,
                   vk->swapchain.extent.width,
                   vk->swapchain.extent.height,
                   1,
                   colorFormat,
                   VK_IMAGE_TILING_OPTIMAL,
                   VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT |
                   VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
                   vk->msaa_samples,
                   &vk->color_image);
  vk->color_image.view = vks_create_image_view(*vk, vk->color_image.handle, colorFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1);
}

/* Vks API implementation */

VKSDEF void
vks_cleanup_swapchain(const vks_context vk)
{
  vkDestroyImageView(vk.device, vk.color_image.view, NULL);
  vmaDestroyImage(vk.allocator, vk.color_image.handle, vk.color_image.allocation);

  vkDestroyImageView(vk.device, vk.depth_image.view, NULL);
  vmaDestroyImage(vk.allocator, vk.depth_image.handle, vk.depth_image.allocation);

  for (uint32_t i = 0; i < vk.swapchain.image_count; i++) {
    vkDestroyImageView(vk.device, vk.swapchain.image_views[i], NULL);
  }
  vkDestroySwapchainKHR(vk.device, vk.swapchain.handle, NULL);
}

VKSDEF void
vks_recreate_swapchain(vks_context* vk)
{
  vkDeviceWaitIdle(vk->device);

  vks_cleanup_swapchain(*vk);

  _vulkan_create_swap_chain(vk);
  _vulkan_create_color_resources(vk);
  _vulkan_create_depth_resources(vk);
}

VKSDEF void
vks_create_vulkan_context(vks_context* vk)
{
  /* Create vulkan instance */
  vk->instance = _vks_create_instance(enable_validation_layers,
                                     validation_layers,
                                     validation_layer_count,
                                     vk->window);

  /* Create render surface */
  if (SDL_Vulkan_CreateSurface(vk->window, vk->instance, &vk->surface) ==
      SDL_FALSE) {
    vk_log(VK_ERROR, "Failed to create surface\n");
  } else {
    vk_log(VK_INFO, "Vulkan surface created\n");
  }

  /* Pick physical device */
  _vulkan_pick_physical_device(vk);

  /* Create logical device and get queues */
  /* TODO: Create vks_get_queue helpers?? */
  _vulkan_create_logical_device(vk);


  _vulkan_create_command_pool(vk);

  /* Create swapchain */
  /* TODO: Make swapchain api */
  _vulkan_create_swap_chain(vk);


  /* VMA POC */
  VmaVulkanFunctions vulkanFunctions = {0};
  vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
  vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;

  VmaAllocatorCreateInfo allocatorCreateInfo = {0};
  allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
  allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2;
  allocatorCreateInfo.physicalDevice = vk->physical_device;
  allocatorCreateInfo.device = vk->device;
  allocatorCreateInfo.instance = vk->instance;
  allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;

  vmaCreateAllocator(&allocatorCreateInfo, &vk->allocator);

  /* Create resources */
  _vulkan_create_color_resources(vk);
  _vulkan_create_depth_resources(vk);
}


VKSDEF void
vks_destroy_vulkan_context(vks_context* vk)
{
  vks_cleanup_swapchain(*vk);
  
  vmaDestroyAllocator(vk->allocator);

  vkDestroyDevice(vk->device, NULL);
  vkDestroySurfaceKHR(vk->instance, vk->surface, NULL);
  
  vkDestroyInstance(vk->instance, NULL);
}


VKSDEF VkImageView
vks_create_image_view(const vks_context  vk,
                      VkImage            image,
                      VkFormat           format,
                      VkImageAspectFlags aspectFlags,
                      uint32_t           mipLevels)
{
  VkImageViewCreateInfo viewInfo = { 0 };
  viewInfo.sType                 = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  viewInfo.image                 = image;
  viewInfo.viewType              = VK_IMAGE_VIEW_TYPE_2D;
  viewInfo.format                = format;
  viewInfo.subresourceRange.aspectMask     = aspectFlags;
  viewInfo.subresourceRange.baseMipLevel   = 0;
  viewInfo.subresourceRange.levelCount     = mipLevels;
  viewInfo.subresourceRange.baseArrayLayer = 0;
  viewInfo.subresourceRange.layerCount     = 1;

  VkImageView imageView;
  VK_CHECK(vkCreateImageView(vk.device, &viewInfo, NULL, &imageView));

  return imageView;
}

VKSDEF void
vks_generate_mipmaps(const vks_context       vk,
                     VkImage                 image,
                     const VkFormat          imageFormat,
                     const int32_t           texWidth,
                     const int32_t           texHeight,
                     const uint32_t          mipLevels)
{
  VkCommandBuffer command_buffer = _vks_begin_single_time_commands(vk);

  VkImageMemoryBarrier barrier        = { 0 };
  barrier.sType                       = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  barrier.image                       = image;
  barrier.srcQueueFamilyIndex         = VK_QUEUE_FAMILY_IGNORED;
  barrier.dstQueueFamilyIndex         = VK_QUEUE_FAMILY_IGNORED;
  barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  barrier.subresourceRange.baseArrayLayer = 0;
  barrier.subresourceRange.layerCount     = 1;
  barrier.subresourceRange.levelCount     = 1;

  int32_t mipWidth  = texWidth;
  int32_t mipHeight = texHeight;

  for (uint32_t i = 1; i < mipLevels; i++) {
    barrier.subresourceRange.baseMipLevel = i - 1;
    barrier.oldLayout     = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
    barrier.newLayout     = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
    barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
    barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;

    vkCmdPipelineBarrier(command_buffer,
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         0,
                         0,
                         NULL,
                         0,
                         NULL,
                         1,
                         &barrier);

    VkImageBlit blit                   = { 0 };
    blit.srcOffsets[0]                 = (VkOffset3D){ 0, 0, 0 };
    blit.srcOffsets[1]                 = (VkOffset3D){ mipWidth, mipHeight, 1 };
    blit.srcSubresource.aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT;
    blit.srcSubresource.mipLevel       = i - 1;
    blit.srcSubresource.baseArrayLayer = 0;
    blit.srcSubresource.layerCount     = 1;
    blit.dstOffsets[0]                 = (VkOffset3D){ 0, 0, 0 };
    blit.dstOffsets[1] = (VkOffset3D){ mipWidth > 1 ? mipWidth / 2 : 1,
                                       mipHeight > 1 ? mipHeight / 2 : 1,
                                       1 };
    blit.dstSubresource.aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT;
    blit.dstSubresource.mipLevel       = i;
    blit.dstSubresource.baseArrayLayer = 0;
    blit.dstSubresource.layerCount     = 1;

    vkCmdBlitImage(command_buffer,
                   image,
                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
                   image,
                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
                   1,
                   &blit,
                   VK_FILTER_LINEAR);

    barrier.oldLayout     = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
    barrier.newLayout     = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
    barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
    barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;

    vkCmdPipelineBarrier(command_buffer,
                         VK_PIPELINE_STAGE_TRANSFER_BIT,
                         VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
                         0,
                         0,
                         NULL,
                         0,
                         NULL,
                         1,
                         &barrier);

    if (mipWidth > 1)
      mipWidth /= 2;
    if (mipHeight > 1)
      mipHeight /= 2;
  }

  _vks_end_single_time_commands(vk, command_buffer);
}

VKSDEF void
vks_copy_buffer_to_image(const vks_context       vk,
                         const VkBuffer          buffer,
                         VkImage                 image,
                         const uint32_t          width,
                         const uint32_t          height)
{
  VkCommandBuffer command_buffer = _vks_begin_single_time_commands(vk);

  VkBufferImageCopy region = { 0 };
  region.bufferOffset      = 0;
  region.bufferRowLength   = 0;
  region.bufferImageHeight = 0;

  region.imageSubresource.aspectMask     = VK_IMAGE_ASPECT_COLOR_BIT;
  region.imageSubresource.mipLevel       = 0;
  region.imageSubresource.baseArrayLayer = 0;
  region.imageSubresource.layerCount     = 1;

  region.imageOffset = (VkOffset3D){ 0, 0, 0 };
  region.imageExtent = (VkExtent3D){ width, height, 1 };

  vkCmdCopyBufferToImage(command_buffer,
                         buffer,
                         image,
                         VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
                         1,
                         &region);

  _vks_end_single_time_commands(vk, command_buffer);
}

VKSDEF void
vks_copy_buffer(const vks_context       vk,
                const VkBuffer          src_buffer,
                VkBuffer                dst_buffer,
                const VkDeviceSize      size)
{
  VkCommandBuffer command_buffer = _vks_begin_single_time_commands(vk);

  VkBufferCopy copy_region = { 0 };
  copy_region.srcOffset    = 0; // Optional
  copy_region.dstOffset    = 0; // Optional
  copy_region.size         = size;
  vkCmdCopyBuffer(command_buffer, src_buffer, dst_buffer, 1, &copy_region);

  _vks_end_single_time_commands(vk, command_buffer);
}

VKSDEF void
vks_transition_image_layout(const vks_context vk, const vks_transition_image_layout_info* info)
{
  VkCommandBuffer command_buffer = _vks_begin_single_time_commands(vk);

  VkImageMemoryBarrier barrier = { 0 };
  barrier.sType                = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
  barrier.srcAccessMask        = info->srcAccessMask;
  barrier.dstAccessMask        = info->dstAccessMask;
  barrier.oldLayout            = info->oldLayout;
  barrier.newLayout            = info->newLayout;
  barrier.srcQueueFamilyIndex  = VK_QUEUE_FAMILY_IGNORED;
  barrier.dstQueueFamilyIndex  = VK_QUEUE_FAMILY_IGNORED;
  barrier.image                = info->image;

  if (info->newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;

    if (_has_stencil_component(info->format)) {
      barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
    }
  } else {
    barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  }

  barrier.subresourceRange.baseMipLevel   = 0;
  barrier.subresourceRange.levelCount     = info->mipLevels;
  barrier.subresourceRange.baseArrayLayer = 0;
  barrier.subresourceRange.layerCount     = 1;

  vkCmdPipelineBarrier(command_buffer,
                       info->srcStageMask,
                       info->dstStageMask,
                       0,
                       0,
                       NULL,
                       0,
                       NULL,
                       1,
                       &barrier);

  _vks_end_single_time_commands(vk, command_buffer);
}

VKSDEF void
vks_create_image(const vks_context           vk,
                 const uint32_t              width,
                 const uint32_t              height,
                 const uint32_t              mipLevels,
                 const VkFormat              format,
                 const VkImageTiling         tiling,
                 const VkImageUsageFlags     usage,
                 const VkSampleCountFlagBits numSamples,
                 vks_image*                  image)
{
  VkImageCreateInfo imageInfo = { 0 };
  imageInfo.sType             = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  imageInfo.imageType         = VK_IMAGE_TYPE_2D;
  imageInfo.extent.width      = width;
  imageInfo.extent.height     = height;
  imageInfo.extent.depth      = 1;
  imageInfo.mipLevels         = mipLevels;
  imageInfo.arrayLayers       = 1;
  imageInfo.format            = format;
  imageInfo.tiling            = tiling;
  imageInfo.initialLayout     = VK_IMAGE_LAYOUT_UNDEFINED;
  imageInfo.usage             = usage;
  imageInfo.samples           = numSamples;
  imageInfo.sharingMode       = VK_SHARING_MODE_EXCLUSIVE;

  VmaAllocationCreateInfo allocInfo = {0};
  allocInfo.usage             = VMA_MEMORY_USAGE_AUTO;

  VK_CHECK(vmaCreateImage(vk.allocator,
                          &imageInfo,
                          &allocInfo,
                          &image->handle,
                          &image->allocation,
                          NULL));
}

VKSDEF void
vks_create_buffer(const vks_context           vk,
                  const VkDeviceSize          size,
                  const VkBufferUsageFlags    usage,
                  vks_buffer*                 buffer)
{
  VkBufferCreateInfo bufferInfo = { 0 };
  bufferInfo.sType              = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  bufferInfo.size               = size;
  bufferInfo.usage              = usage;
  bufferInfo.sharingMode        = VK_SHARING_MODE_EXCLUSIVE;


  VmaAllocationCreateInfo allocInfo = {0};
  allocInfo.usage                   = VMA_MEMORY_USAGE_AUTO;
  allocInfo.flags                   = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;

  vmaCreateBuffer(vk.allocator, &bufferInfo, &allocInfo, &buffer->handle, &buffer->allocation, NULL);
}

#endif /* VKSETUP_IMPLEMENTATION */