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
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
|
#include <string.h>
#include <errno.h>
#include <cglm/cglm.h>
#include <vulkan/vulkan.h>
#include "graphics.h"
#include "common.h"
// TODO: the amount of vertices is currently
// hardcoded in command_buffer_record
// thats bad
// TODO: add more error checking
// TODO: add log output
// TODO: check for memory leaks
// TODO: vkAllocateMemory shouldn't be called for every buffer,
// a memory allocator should be used (the offset parameter)
#define SWAP_CHAIN_IMAGES 3
#define CLAMP(val, min, max) (((val) < (min)) ? (min) : ((val) > (max) ? (max) : (val)))
#define ECHECK(f, ...) if(f(__VA_ARGS__) != 0) { err(#f ": failed"); goto exit; }
#define FCHECK(f, ...) if(f(__VA_ARGS__) != 0) { err(#f ": failed"); goto fail; }
#define VCHECK(f, ...) \
do { \
VkResult res; \
if((res = f(__VA_ARGS__)) != VK_SUCCESS) { \
err(#f ": %s", str_VkResult(res)); \
goto exit; } \
} while(0)
#ifdef DEBUG
char *validation_layers[] = {
"VK_LAYER_KHRONOS_validation"
};
#endif
char *device_extensions[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
struct queue_family_idx {
u32 graphics_family;
bool has_graphics_family;
u32 present_family;
bool has_present_family;
u32 transfer_family;
bool has_transfer_family;
};
struct swap_chain_support_details {
VkSurfaceCapabilitiesKHR capabilities;
VkSurfaceFormatKHR *formats;
u32 nformats;
VkPresentModeKHR *present_modes;
u32 npresent_modes;
};
// most function that return an int follow this scheme:
// 0 - success; 1 - error; (sometimes -1 - fatal error)
// -- Major Functions ---
static int create_instance(graphics_t graphics, struct graphics_info *info);
static int create_surface(graphics_t graphics, struct graphics_info *info);
static int create_physical_device(graphics_t graphics, struct graphics_info *info);
static int create_logical_device(graphics_t graphics, struct graphics_info *info);
static int create_pipeline(graphics_t graphics, struct graphics_info *info);
static int create_swap_chain(graphics_t graphics, struct graphics_info *info);
static int create_vertex_buffer(graphics_t graphics, struct graphics_info *info);
static int create_command_pool(graphics_t graphics, struct graphics_info *info);
static int create_sync_objects(graphics_t graphics, struct graphics_info *info);
static void destroy_pipeline(graphics_t graphics);
static void destroy_swap_chain(graphics_t graphics);
// static void destroy_command_pool(graphics_t graphics);
static void destroy_sync_objects(graphics_t graphics);
static int buffer_create(graphics_t graphics, size_t size, VkBufferUsageFlags usageflg,
VkMemoryPropertyFlags propflg, buffer_t *buffer);
static int buffer_copy(graphics_t graphics, buffer_t dest, buffer_t src, size_t size);
static void buffer_destroy(graphics_t graphics, buffer_t buffer);
// --- Helper Functions ---
static int buffer_find_memory_type(VkPhysicalDevice device, u32 type_filter, VkMemoryPropertyFlags flags, u32 *memory_type_idx);
static bool device_is_suitable(VkPhysicalDevice phy_device, VkSurfaceKHR surface);
static bool device_has_extension_support(VkPhysicalDevice phy_device);
static int device_queue_families(VkPhysicalDevice phy_device, VkSurfaceKHR surface, struct queue_family_idx *queue_family);
#define PPLN graphics->pipeline
static int pipeline_load_shader_module(VkDevice device, char *path, VkShaderModule *module);
#define SWCH graphics->swap_chain
static int swap_chain_support(VkPhysicalDevice phy_device, VkSurfaceKHR surface, struct swap_chain_support_details *details);
static void swap_chain_free_support_details(struct swap_chain_support_details *details);
static int swap_chain_choose_format(VkSurfaceFormatKHR* formats, u32 nformats, VkSurfaceFormatKHR *format);
static int swap_chain_choose_present_mode(VkPresentModeKHR *modes, u32 nmodes, VkPresentModeKHR *mode);
static int swap_chain_get_extent(VkSurfaceCapabilitiesKHR capabilities, VkExtent2D *extent);
#define CMND graphics->command_graphics
#define CMND_TRNS graphics->command_transfer
static int command_buffer_record(graphics_t graphics, u32 image_index);
#define SYNC graphics->sync
#define VBFF graphics->vertex_buffer
#define IBFF graphics->index_buffer
static int graphics_buffer_create(graphics_t graphics, VkBufferUsageFlags flags, void *data, size_t size, buffer_t *buffer);
static int vertex_populate_descriptions(VkVertexInputBindingDescription *binding_desc, VkVertexInputAttributeDescription *attribute_desc);
static char *str_VkResult(VkResult result);
F_LOAD_FILE_ALIGNED(u32) // from config.h
// --- Debug Functions ---
#ifdef DEBUG
static bool instance_has_validation_layers(const char * const *layers, u32 nlayers);
static int create_debug_messenger(graphics_t graphics, struct graphics_info* info);
static void debug_messenger_populate_info(VkDebugUtilsMessengerCreateInfoEXT *info);
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData);
// Vulkan Wrappers
VkResult CreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDebugUtilsMessengerEXT* pDebugMessenger);
void DestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT debugMessenger,
const VkAllocationCallbacks* pAllocator);
#endif
#define CCHECK(f) FCHECK(f, graphics, info)
graphics_t graphics_create(struct graphics_info *info)
{
graphics_t graphics = xmalloc(sizeof(struct graphics));
graphics->instance = VK_NULL_HANDLE;
graphics->logical_device = VK_NULL_HANDLE;
PPLN.pipeline = VK_NULL_HANDLE;
PPLN.layout = VK_NULL_HANDLE;
PPLN.render_pass = VK_NULL_HANDLE;
SWCH.swap_chain = VK_NULL_HANDLE;
SWCH.nimages = 0;
CMND.pool = VK_NULL_HANDLE;
SYNC.semph_image_available = VK_NULL_HANDLE;
SYNC.semph_render_finished = VK_NULL_HANDLE;
SYNC.fence_inflight = VK_NULL_HANDLE;
VBFF.buffer = VK_NULL_HANDLE;
VBFF.memory = VK_NULL_HANDLE;
CCHECK(create_instance);
CCHECK(create_surface);
#ifdef DEBUG
CCHECK(create_debug_messenger);
#endif
CCHECK(create_physical_device);
CCHECK(create_logical_device);
CCHECK(create_pipeline);
CCHECK(create_swap_chain);
CCHECK(create_command_pool);
CCHECK(create_vertex_buffer);
CCHECK(create_sync_objects);
return graphics;
fail:
graphics_destroy(graphics);
return NULL;
}
void graphics_destroy(graphics_t graphics)
{
if(!graphics) return;
vkDeviceWaitIdle(graphics->logical_device);
destroy_sync_objects(graphics);
vkDestroyCommandPool(graphics->logical_device, CMND.pool, NULL);
vkDestroyCommandPool(graphics->logical_device, CMND_TRNS.pool, NULL);
buffer_destroy(graphics, VBFF);
buffer_destroy(graphics, IBFF);
destroy_swap_chain(graphics);
destroy_pipeline(graphics);
vkDestroyDevice(graphics->logical_device, NULL);
#ifdef DEBUG
DestroyDebugUtilsMessengerEXT(graphics->instance, graphics->debug_messenger, NULL);
#endif
vkDestroySurfaceKHR(graphics->instance, graphics->surface, NULL);
vkDestroyInstance(graphics->instance, NULL);
free(graphics);
}
int graphics_draw_frame(graphics_t graphics)
{
int ret = 1;
// wait for the previous frame to finish
vkWaitForFences(graphics->logical_device, 1, &SYNC.fence_inflight, VK_TRUE, UINT64_MAX);
// aquire the next image the form the swap chain
u32 image_index;
VkResult res = vkAcquireNextImageKHR(graphics->logical_device, SWCH.swap_chain, UINT64_MAX, SYNC.semph_image_available, VK_NULL_HANDLE, &image_index);
// recreate the swap chain on resize
if(res == VK_ERROR_OUT_OF_DATE_KHR) {
destroy_swap_chain(graphics);
create_swap_chain(graphics, NULL);
ret = 0; goto exit;
}
vkResetFences(graphics->logical_device, 1, &SYNC.fence_inflight);
// reset the command buffer
vkResetCommandBuffer(CMND.buffer, 0);
command_buffer_record(graphics, image_index);
// prepare the queue submit info
VkSubmitInfo submit_info = {0};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore wait_semaphs[] = { SYNC.semph_image_available };
VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submit_info.waitSemaphoreCount = ARR_SIZE(wait_semaphs);
submit_info.pWaitSemaphores = wait_semaphs;
submit_info.pWaitDstStageMask = wait_stages;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &CMND.buffer;
VkSemaphore signal_semphs[] = { SYNC.semph_image_available };
submit_info.signalSemaphoreCount = ARR_SIZE(signal_semphs);
submit_info.pSignalSemaphores = signal_semphs;
// submit the graphics work
VCHECK(vkQueueSubmit, graphics->graphics_queue, 1, &submit_info, SYNC.fence_inflight);
// prepare the graphics info
VkPresentInfoKHR present_info = {0};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = ARR_SIZE(signal_semphs);
present_info.pWaitSemaphores = signal_semphs;
VkSwapchainKHR swap_chains[] = { SWCH.swap_chain };
present_info.swapchainCount = ARR_SIZE(swap_chains);
present_info.pSwapchains = swap_chains;
present_info.pImageIndices = &image_index;
present_info.pResults = NULL; // Optional
vkQueuePresentKHR(graphics->present_queue, &present_info);
ret = 0;
exit:
return ret;
}
static int create_instance(graphics_t graphics, struct graphics_info *info)
{
int ret = 1;
VkApplicationInfo app_info = {0};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pEngineName = "Engine";
app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
app_info.apiVersion = VK_API_VERSION_1_0;
app_info.pApplicationName = info->name;
app_info.applicationVersion = info->version;
VkInstanceCreateInfo create_info = {0};
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
create_info.pApplicationInfo = &app_info;
create_info.enabledLayerCount = 0;
#ifdef DEBUG
// add debug utils extensions for debug callback
char **extensions = xcalloc(info->ext_count+1, sizeof(*extensions));
extensions[info->ext_count] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
for(u32 i = 0; i < info->ext_count; i++) {
extensions[i] = (char *)info->extensions[i];
}
create_info.enabledExtensionCount = info->ext_count+1;
create_info.ppEnabledExtensionNames = (const char * const *)extensions;
// validation layer support
u32 nlayers = ARR_SIZE(validation_layers);
if(!instance_has_validation_layers((const char * const *)validation_layers, nlayers)) {
err("validation_layer_support: failed");
goto exit;
}
create_info.ppEnabledLayerNames = (const char * const *)validation_layers;
create_info.enabledLayerCount = nlayers;
// add the debug messenger for instance creation and destruction
VkDebugUtilsMessengerCreateInfoEXT msg_info = {0};
debug_messenger_populate_info(&msg_info);
create_info.pNext = &msg_info;
#else
create_info.enabledExtensionCount = info->ext_count;
create_info.ppEnabledExtensionNames = (const char * const *)info->extensions;
create_info.enabledLayerCount = 0;
#endif
VCHECK(vkCreateInstance, &create_info, NULL, &graphics->instance);
ret = 0;
exit:
#ifdef DEBUG
free(extensions);
#endif
return ret;
}
static int create_surface(graphics_t graphics, struct graphics_info *info)
{
if(info->surface_func(graphics->instance, &graphics->surface)) {
err("Couldn't create a VkSurfaceKHR");
return 1;
}
return 0;
}
static int create_physical_device(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
graphics->physical_device = VK_NULL_HANDLE;
u32 dev_count = 0;
vkEnumeratePhysicalDevices(graphics->instance, &dev_count, NULL);
if(dev_count == 0) {
err("No physical devices could be found!");
goto exit;
}
VkPhysicalDevice *devices = xcalloc(dev_count, sizeof(*devices));
vkEnumeratePhysicalDevices(graphics->instance, &dev_count, devices);
for(u32 i = 0; i < dev_count; i++) {
if(device_is_suitable(devices[i], graphics->surface)) {
graphics->physical_device = devices[i];
break;
}
}
free(devices);
if(graphics->physical_device == VK_NULL_HANDLE) {
err("No suitable physical device could be found");
goto exit;
}
ret = 0;
exit:
return ret;
}
static int create_logical_device(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
// queue family data
struct queue_family_idx indices = {0};
device_queue_families(graphics->physical_device, graphics->surface, &indices);
// queue infos
u32 unique_queue_family_count = 0;
u32 queue_indices[] = {
indices.graphics_family, indices.present_family, indices.transfer_family
};
VkDeviceQueueCreateInfo queue_infos[ARR_SIZE(queue_indices)] = {0};
float queue_priority = 1.0f;
// basically get only the unique queue families
for(size_t i = 0; i < ARR_SIZE(queue_indices); i++)
{
bool unique = true;
for(size_t j = 0; j < i; j++) {
if(queue_indices[i] == queue_indices[j]) {
unique = false;
break;
}
}
if(!unique) continue;
queue_infos[unique_queue_family_count].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queue_infos[unique_queue_family_count].queueFamilyIndex = queue_indices[i];
queue_infos[unique_queue_family_count].queueCount = 1;
queue_infos[unique_queue_family_count].pQueuePriorities = &queue_priority;
unique_queue_family_count++;
}
// device features
VkPhysicalDeviceFeatures device_features = {0};
// logical device create info
VkDeviceCreateInfo create_info = {0};
create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
create_info.pQueueCreateInfos = queue_infos;
create_info.queueCreateInfoCount = unique_queue_family_count;
create_info.pEnabledFeatures = &device_features;
create_info.ppEnabledExtensionNames = (const char * const *)device_extensions;
create_info.enabledExtensionCount = ARR_SIZE(device_extensions);
// validation layers can be set, but
// newer implementations will ignore them
// so i wont bother adding them
create_info.enabledLayerCount = 0;
VCHECK(vkCreateDevice, graphics->physical_device, &create_info, NULL, &graphics->logical_device);
vkGetDeviceQueue(graphics->logical_device, indices.graphics_family, 0, &graphics->graphics_queue);
vkGetDeviceQueue(graphics->logical_device, indices.present_family, 0, &graphics->present_queue);
vkGetDeviceQueue(graphics->logical_device, indices.transfer_family, 0, &graphics->transfer_queue);
ret = 0;
exit:
return ret;
}
static int create_swap_chain(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
struct swap_chain_support_details details;
swap_chain_support(graphics->physical_device, graphics->surface, &details);
VkSurfaceFormatKHR surface_format;
VkPresentModeKHR present_mode;
VkExtent2D extent;
u32 image_count = SWAP_CHAIN_IMAGES;
swap_chain_choose_format(details.formats, details.nformats, &surface_format);
swap_chain_choose_present_mode(details.present_modes, details.npresent_modes, &present_mode);
swap_chain_get_extent(details.capabilities, &extent);
if(details.capabilities.maxImageCount > 0) {
image_count = CLAMP(image_count, details.capabilities.minImageCount, details.capabilities.maxImageCount);
}
// start filling in the create info
VkSwapchainCreateInfoKHR create_info = {0};
create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
create_info.surface = graphics->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;
create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
struct queue_family_idx indices = {0};
device_queue_families(graphics->physical_device, graphics->surface, &indices);
u32 queue_indices[] = { indices.graphics_family, indices.present_family };
// set the sharing mode of the images
if(indices.graphics_family != indices.present_family) {
create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
create_info.queueFamilyIndexCount = ARR_SIZE(queue_indices);
create_info.pQueueFamilyIndices = queue_indices;
} else {
create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
create_info.queueFamilyIndexCount = 0;
create_info.pQueueFamilyIndices = NULL;
}
create_info.preTransform = details.capabilities.currentTransform;
create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
create_info.presentMode = present_mode;
create_info.clipped = VK_TRUE;
create_info.oldSwapchain = NULL;
VCHECK(vkCreateSwapchainKHR, graphics->logical_device, &create_info, NULL, &SWCH.swap_chain);
// Get the Images
SWCH.image_format = surface_format.format;
SWCH.extent = extent;
vkGetSwapchainImagesKHR(graphics->logical_device, SWCH.swap_chain, &SWCH.nimages, NULL);
SWCH.images = xcalloc(SWCH.nimages, sizeof(*SWCH.images));
SWCH.image_views = xcalloc(SWCH.nimages, sizeof(SWCH.image_views));
SWCH.framebuffers = xcalloc(SWCH.nimages, sizeof(*SWCH.framebuffers));
vkGetSwapchainImagesKHR(graphics->logical_device, SWCH.swap_chain, &SWCH.nimages, SWCH.images);
for(u32 i = 0; i < SWCH.nimages; i++)
{
VkImageViewCreateInfo create_info = {0};
create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
create_info.image = SWCH.images[i];
create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
create_info.format = surface_format.format;
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;
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;
VCHECK(vkCreateImageView, graphics->logical_device, &create_info, NULL, &SWCH.image_views[i]);
}
for(u32 i = 0; i < SWCH.nimages; i++)
{
VkImageView attachments[] = {
SWCH.image_views[i]
};
VkFramebufferCreateInfo framebuffer_info = {0};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = PPLN.render_pass;
framebuffer_info.attachmentCount = 1;
framebuffer_info.pAttachments = attachments;
framebuffer_info.width = SWCH.extent.width;
framebuffer_info.height = SWCH.extent.height;
framebuffer_info.layers = 1;
VCHECK(vkCreateFramebuffer, graphics->logical_device, &framebuffer_info, NULL, &SWCH.framebuffers[i]);
}
ret = 0;
exit:
swap_chain_free_support_details(&details);
return ret;
}
static void destroy_swap_chain(graphics_t graphics)
{
for(u32 i = 0; i < SWCH.nimages; i++) {
vkDestroyImageView(graphics->logical_device, SWCH.image_views[i], NULL);
vkDestroyFramebuffer(graphics->logical_device, SWCH.framebuffers[i], NULL);
}
if(SWCH.nimages != 0) {
free(SWCH.images);
free(SWCH.image_views);
free(SWCH.framebuffers);
}
vkDestroySwapchainKHR(graphics->logical_device, SWCH.swap_chain, NULL);
}
static int create_pipeline(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
// Shader Things
VkShaderModule vert_shader = VK_NULL_HANDLE;
VkShaderModule frag_shader = VK_NULL_HANDLE;
pipeline_load_shader_module(graphics->logical_device, "shaders/shader1.vert.spv", &vert_shader);
pipeline_load_shader_module(graphics->logical_device, "shaders/shader1.frag.spv", &frag_shader);
VkPipelineShaderStageCreateInfo vert_stage = {0};
vert_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vert_stage.stage = VK_SHADER_STAGE_VERTEX_BIT;
vert_stage.module = vert_shader;
vert_stage.pName = "main";
VkPipelineShaderStageCreateInfo frag_stage = {0};
frag_stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
frag_stage.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
frag_stage.module = frag_shader;
frag_stage.pName = "main";
VkPipelineShaderStageCreateInfo shader_stages[] = { vert_stage, frag_stage };
VkDynamicState dynamic_states[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
// A Bunch of other things for the pipeline
VkPipelineDynamicStateCreateInfo dynamic_state = {0};
dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
dynamic_state.dynamicStateCount = ARR_SIZE(dynamic_states);
dynamic_state.pDynamicStates = dynamic_states;
// vertex things
VkVertexInputBindingDescription binding_description = {0};
VkVertexInputAttributeDescription attribute_description[2] = {0};
vertex_populate_descriptions(&binding_description, attribute_description);
VkPipelineVertexInputStateCreateInfo vertex_input = {0};
vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertex_input.vertexBindingDescriptionCount = 1;
vertex_input.pVertexBindingDescriptions = &binding_description;
vertex_input.vertexAttributeDescriptionCount = ARR_SIZE(attribute_description);
vertex_input.pVertexAttributeDescriptions = attribute_description;
VkPipelineInputAssemblyStateCreateInfo input_assembly = {0};
input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
input_assembly.primitiveRestartEnable = VK_FALSE;
VkPipelineViewportStateCreateInfo viewport_state = {0};
viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewport_state.viewportCount = 1;
viewport_state.scissorCount = 1;
VkPipelineRasterizationStateCreateInfo rasterizer = {0};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
rasterizer.depthBiasConstantFactor = 0.0f; // Optional
rasterizer.depthBiasClamp = 0.0f; // Optional
rasterizer.depthBiasSlopeFactor = 0.0f; // Optional
VkPipelineMultisampleStateCreateInfo multisampling = {0};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.minSampleShading = 1.0f; // Optional
multisampling.pSampleMask = NULL; // Optional
multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
multisampling.alphaToOneEnable = VK_FALSE; // Optional
VkPipelineColorBlendAttachmentState color_blend_attachment = {0};
color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
color_blend_attachment.blendEnable = VK_FALSE;
color_blend_attachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
color_blend_attachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
color_blend_attachment.colorBlendOp = VK_BLEND_OP_ADD; // Optional
color_blend_attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
color_blend_attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
color_blend_attachment.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
VkPipelineColorBlendStateCreateInfo color_blend = {0};
color_blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
color_blend.logicOpEnable = VK_FALSE;
color_blend.logicOp = VK_LOGIC_OP_COPY; // Optional
color_blend.attachmentCount = 1;
color_blend.pAttachments = &color_blend_attachment;
color_blend.blendConstants[0] = 0.0f; // Optional
color_blend.blendConstants[1] = 0.0f; // Optional
color_blend.blendConstants[2] = 0.0f; // Optional
color_blend.blendConstants[3] = 0.0f; // Optional
// Create Pipeline Layout
VkPipelineLayoutCreateInfo pipeline_layout_info = {0};
pipeline_layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_info.setLayoutCount = 0; // Optional
pipeline_layout_info.pSetLayouts = NULL; // Optional
pipeline_layout_info.pushConstantRangeCount = 0; // Optional
pipeline_layout_info.pPushConstantRanges = NULL; // Optional
VCHECK(vkCreatePipelineLayout, graphics->logical_device, &pipeline_layout_info, NULL, &PPLN.layout);
// get the required format
// currently the only to do that
// TOOD: fix this
VkSurfaceFormatKHR surface_format;
struct swap_chain_support_details details;
swap_chain_support(graphics->physical_device, graphics->surface, &details);
swap_chain_choose_format(details.formats, details.nformats, &surface_format);
swap_chain_free_support_details(&details);
// Create Render Pass
VkAttachmentDescription color_attachment = {0};
color_attachment.format = surface_format.format;
color_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
color_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference color_attachment_ref = {0};
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {0};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_attachment_ref;
VkSubpassDependency dependency = {0};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
VkRenderPassCreateInfo render_pass_info = {0};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_info.attachmentCount = 1;
render_pass_info.pAttachments = &color_attachment;
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
render_pass_info.dependencyCount = 1;
render_pass_info.pDependencies = &dependency;
VCHECK(vkCreateRenderPass, graphics->logical_device, &render_pass_info, NULL, &PPLN.render_pass);
// Finally Create the Pipeline
VkGraphicsPipelineCreateInfo pipeline_info = {0};
pipeline_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipeline_info.stageCount = 2;
pipeline_info.pStages = shader_stages;
pipeline_info.pVertexInputState = &vertex_input;
pipeline_info.pInputAssemblyState = &input_assembly;
pipeline_info.pViewportState = &viewport_state;
pipeline_info.pRasterizationState = &rasterizer;
pipeline_info.pMultisampleState = &multisampling;
pipeline_info.pDepthStencilState = NULL;
pipeline_info.pColorBlendState = &color_blend;
pipeline_info.pDynamicState = &dynamic_state;
pipeline_info.layout = PPLN.layout;
pipeline_info.renderPass = PPLN.render_pass;
pipeline_info.subpass = 0;
pipeline_info.basePipelineHandle = VK_NULL_HANDLE; // Optional
pipeline_info.basePipelineIndex = -1; // Optional
VCHECK(vkCreateGraphicsPipelines, graphics->logical_device, VK_NULL_HANDLE, 1, &pipeline_info, NULL, &PPLN.pipeline);
ret = 0;
exit:
vkDestroyShaderModule(graphics->logical_device, frag_shader, NULL);
vkDestroyShaderModule(graphics->logical_device, vert_shader, NULL);
return ret;
}
static void destroy_pipeline(graphics_t graphics)
{
vkDestroyPipeline(graphics->logical_device, PPLN.pipeline, NULL);
vkDestroyPipelineLayout(graphics->logical_device, PPLN.layout, NULL);
vkDestroyRenderPass(graphics->logical_device, PPLN.render_pass, NULL);
}
static int create_command_pool(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
struct queue_family_idx indices;
device_queue_families(graphics->physical_device, graphics->surface, &indices);
// graphics pool
VkCommandPoolCreateInfo graphics_pool_info = {0};
graphics_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
graphics_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
graphics_pool_info.queueFamilyIndex = indices.graphics_family;
VCHECK(vkCreateCommandPool, graphics->logical_device, &graphics_pool_info, NULL, &CMND.pool);
// graphics buffer
VkCommandBufferAllocateInfo graphics_allocate_info = {0};
graphics_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
graphics_allocate_info.commandPool = CMND.pool;
graphics_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
graphics_allocate_info.commandBufferCount = 1;
VCHECK(vkAllocateCommandBuffers, graphics->logical_device, &graphics_allocate_info, &CMND.buffer);
// transfer pool
VkCommandPoolCreateInfo transfer_pool_info = {0};
transfer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
transfer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
transfer_pool_info.queueFamilyIndex = indices.transfer_family;
VCHECK(vkCreateCommandPool, graphics->logical_device, &transfer_pool_info, NULL, &CMND_TRNS.pool);
// graphics buffer
VkCommandBufferAllocateInfo transfer_allocate_info = {0};
transfer_allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
transfer_allocate_info.commandPool = CMND_TRNS.pool;
transfer_allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
transfer_allocate_info.commandBufferCount = 1;
VCHECK(vkAllocateCommandBuffers, graphics->logical_device, &transfer_allocate_info, &CMND_TRNS.buffer);
ret = 0;
exit:
return ret;
}
static int create_sync_objects(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
VkSemaphoreCreateInfo semph_info = {0};
semph_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fence_info = {0};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
VCHECK(vkCreateSemaphore, graphics->logical_device, &semph_info, NULL, &SYNC.semph_image_available);
VCHECK(vkCreateSemaphore, graphics->logical_device, &semph_info, NULL, &SYNC.semph_render_finished);
VCHECK(vkCreateFence, graphics->logical_device, &fence_info, NULL, &SYNC.fence_inflight);
ret = 0;
exit:
return ret;
}
static void destroy_sync_objects(graphics_t graphics)
{
vkDestroySemaphore(graphics->logical_device, SYNC.semph_image_available, NULL);
vkDestroySemaphore(graphics->logical_device, SYNC.semph_render_finished, NULL);
vkDestroyFence(graphics->logical_device, SYNC.fence_inflight, NULL);
}
static int create_vertex_buffer(graphics_t graphics, struct graphics_info *info)
{
graphics_buffer_create(graphics, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, info->vertices,
sizeof(*info->vertices) *info->nvertices, &VBFF);
graphics_buffer_create(graphics, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, info->indices,
sizeof(*info->indices) * info->nindices, &IBFF);
return 0;
}
static int buffer_create(graphics_t graphics, size_t size, VkBufferUsageFlags usageflg, VkMemoryPropertyFlags propflg, buffer_t *buffer)
{
int ret = 1;
VkBufferCreateInfo buffer_info = {0};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = size;
buffer_info.usage = usageflg;
// share between the graphics nad transfer queue families
struct queue_family_idx indices;
device_queue_families(graphics->physical_device, graphics->surface, &indices);
u32 queue_family_indices[] = { indices.graphics_family, indices.transfer_family };
// buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
buffer_info.sharingMode = VK_SHARING_MODE_CONCURRENT;
buffer_info.pQueueFamilyIndices = queue_family_indices;
buffer_info.queueFamilyIndexCount = ARR_SIZE(queue_family_indices);
VCHECK(vkCreateBuffer, graphics->logical_device, &buffer_info, NULL, &buffer->buffer);
VkMemoryRequirements memory_requirements;
vkGetBufferMemoryRequirements(graphics->logical_device, buffer->buffer, &memory_requirements);
VkMemoryAllocateInfo allocate_info = {0};
allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocate_info.allocationSize = memory_requirements.size;
u32 memory_type_idx;
buffer_find_memory_type(graphics->physical_device, memory_requirements.memoryTypeBits, propflg, &memory_type_idx);
allocate_info.memoryTypeIndex = memory_type_idx;
VCHECK(vkAllocateMemory, graphics->logical_device, &allocate_info, NULL, &buffer->memory);
VCHECK(vkBindBufferMemory, graphics->logical_device, buffer->buffer, buffer->memory, 0);
ret = 0;
exit:
return ret;
}
static int buffer_copy(graphics_t graphics, buffer_t dest, buffer_t src, size_t size)
{
// TODO: add error checking
int ret = 1;
vkResetCommandBuffer(CMND_TRNS.buffer, 0);
VkCommandBufferBeginInfo begin_info = {0};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(CMND_TRNS.buffer, &begin_info);
VkBufferCopy copy_region = {0};
copy_region.srcOffset = 0; // Optional
copy_region.dstOffset = 0; // Optional
copy_region.size = size;
vkCmdCopyBuffer(CMND_TRNS.buffer, src.buffer, dest.buffer, 1, ©_region);
vkEndCommandBuffer(CMND_TRNS.buffer);
VkSubmitInfo submit_info = {0};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &CMND_TRNS.buffer;
vkQueueSubmit(graphics->transfer_queue, 1, &submit_info, VK_NULL_HANDLE);
vkQueueWaitIdle(graphics->transfer_queue);
ret = 0;
exit:
return ret;
}
static void buffer_destroy(graphics_t graphics, buffer_t buffer)
{
vkDestroyBuffer(graphics->logical_device, buffer.buffer, NULL);
vkFreeMemory(graphics->logical_device, buffer.memory, NULL);
}
static int device_queue_families(VkPhysicalDevice phy_device, VkSurfaceKHR surface, struct queue_family_idx *queue_family)
{
u32 count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(phy_device, &count, NULL);
VkQueueFamilyProperties *properties = xcalloc(count, sizeof(*properties));
vkGetPhysicalDeviceQueueFamilyProperties(phy_device, &count, properties);
for(u32 i = 0; i < count; i++) {
if(properties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) {
queue_family->graphics_family = i;
queue_family->has_graphics_family = true;
}
if(properties[i].queueFlags & VK_QUEUE_TRANSFER_BIT) {
queue_family->transfer_family = i;
queue_family->has_transfer_family = true;
}
VkBool32 present_support = false;
vkGetPhysicalDeviceSurfaceSupportKHR(phy_device, i, surface, &present_support);
if(present_support) {
queue_family->present_family = i;
queue_family->has_present_family = true;
}
}
free(properties);
return 0;
}
static bool device_is_suitable(VkPhysicalDevice phy_device, VkSurfaceKHR surface)
{
struct queue_family_idx indices;
struct swap_chain_support_details details;
return
(device_queue_families(phy_device, surface, &indices),
indices.has_graphics_family &&
indices.has_present_family &&
indices.has_transfer_family)
&&
(device_has_extension_support(phy_device))
&&
(swap_chain_support(phy_device, surface, &details),
swap_chain_free_support_details(&details),
(details.nformats > 0) && (details.npresent_modes > 0));
}
static bool device_has_extension_support(VkPhysicalDevice phy_device)
{
bool ret = false;
u32 count = 0;
vkEnumerateDeviceExtensionProperties(phy_device, NULL, &count, NULL);
VkExtensionProperties *properties = xcalloc(count, sizeof(*properties));
vkEnumerateDeviceExtensionProperties(phy_device, NULL, &count, properties);
for(size_t i = 0; i < ARR_SIZE(device_extensions); i++)
{
bool present = false;
for(u32 j = 0; j < count; j++)
if(strncmp(device_extensions[i], properties[j].extensionName, 256) == 0) {
present = true;
break;
}
if(!present) {
goto exit;
}
}
ret = true;
exit:
free(properties);
return ret;
}
static int swap_chain_support(VkPhysicalDevice phy_device, VkSurfaceKHR surface, struct swap_chain_support_details *details)
{
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(phy_device, surface, &details->capabilities);
vkGetPhysicalDeviceSurfaceFormatsKHR(phy_device, surface, &details->nformats, NULL);
if(details->nformats > 0) {
details->formats = xcalloc(details->nformats, sizeof(*details->formats));
vkGetPhysicalDeviceSurfaceFormatsKHR(phy_device, surface, &details->nformats, details->formats);
}
vkGetPhysicalDeviceSurfacePresentModesKHR(phy_device, surface, &details->npresent_modes, NULL);
if(details->npresent_modes > 0) {
details->present_modes = xcalloc(details->npresent_modes, sizeof(*details->present_modes));
vkGetPhysicalDeviceSurfacePresentModesKHR(phy_device, surface, &details->npresent_modes, details->present_modes);
}
return 0;
}
static void swap_chain_free_support_details(struct swap_chain_support_details *details)
{
if(details->nformats > 0) free(details->formats);
if(details->npresent_modes > 0) free(details->present_modes);
}
static int swap_chain_choose_format(VkSurfaceFormatKHR* formats, u32 nformats, VkSurfaceFormatKHR *format)
{
for(u32 i = 0; i < nformats; i++)
if(formats[i].format == VK_FORMAT_B8G8R8A8_SRGB &&
formats[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
*format = formats[i];
return 0;
}
*format = formats[0];
return 0;
}
static int swap_chain_choose_present_mode(VkPresentModeKHR *modes, u32 nmodes, VkPresentModeKHR *mode)
{
for(u32 i = 0; i < nmodes; i++)
if(modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
*mode = modes[i];
return 0;
}
*mode = VK_PRESENT_MODE_FIFO_KHR;
return 0;
}
static int swap_chain_get_extent(VkSurfaceCapabilitiesKHR capabilities, VkExtent2D *extent)
{
if(capabilities.currentExtent.width != UINT32_MAX) {
*extent = capabilities.currentExtent;
return 0;
}
// TODO implement
err("Not Implemented");
return 1;
}
static int pipeline_load_shader_module(VkDevice device, char *path, VkShaderModule *module)
{
int ret = 1;
size_t size = 0;
u32 *buf = NULL;
ECHECK(load_file_u32_aligned, path, &size, NULL);
buf = xmalloc(size);
ECHECK(load_file_u32_aligned, path, &size, buf);
VkShaderModuleCreateInfo create_info = {0};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.codeSize = size;
create_info.pCode = buf;
VCHECK(vkCreateShaderModule, device, &create_info, NULL, module);
ret = 0;
exit:
if(buf) free(buf);
return ret;
}
static int command_buffer_record(graphics_t graphics, u32 image_index)
{
int ret = 1;
// Begin the buffer
VkCommandBufferBeginInfo begin_info = {0};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
begin_info.flags = 0; // Optional
begin_info.pInheritanceInfo = NULL; // Optional
VCHECK(vkBeginCommandBuffer, CMND.buffer, &begin_info);
// Begin the render pass
VkRenderPassBeginInfo render_pass_info = {0};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_info.renderPass = PPLN.render_pass;
render_pass_info.framebuffer = SWCH.framebuffers[image_index];
render_pass_info.renderArea.offset = (VkOffset2D){0, 0};
render_pass_info.renderArea.extent = SWCH.extent;
VkClearValue clear_color = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
render_pass_info.clearValueCount = 1;
render_pass_info.pClearValues = &clear_color;
vkCmdBeginRenderPass(CMND.buffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
// Begin the drawing commands
vkCmdBindPipeline(CMND.buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, PPLN.pipeline);
VkBuffer vertex_buffers[] = { VBFF.buffer };
VkDeviceSize offsets[] = {0};
vkCmdBindVertexBuffers(CMND.buffer, 0, 1, vertex_buffers, offsets);
vkCmdBindIndexBuffer(CMND.buffer, IBFF.buffer, 0, VK_INDEX_TYPE_UINT32);
VkViewport viewport = {0};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)SWCH.extent.width;
viewport.height = (float)SWCH.extent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
vkCmdSetViewport(CMND.buffer, 0, 1, &viewport);
VkRect2D scissor = {0};
scissor.offset = (VkOffset2D){0, 0};
scissor.extent = SWCH.extent;
vkCmdSetScissor(CMND.buffer, 0, 1, &scissor);
// 3 is the number of vertices
// TODO: fix this
vkCmdDrawIndexed(CMND.buffer, 6, 1, 0, 0, 0);
// Cleaning up
vkCmdEndRenderPass(CMND.buffer);
VCHECK(vkEndCommandBuffer, CMND.buffer);
ret = 0;
exit:
return ret;
}
static int graphics_buffer_create(graphics_t graphics, VkBufferUsageFlags flags, void *data, size_t size, buffer_t *buffer)
{
buffer_t staging;
buffer_create(graphics, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), &staging);
void *dest_data;
vkMapMemory(graphics->logical_device, staging.memory, 0, size, 0, &dest_data);
memcpy(dest_data, data, size);
vkUnmapMemory(graphics->logical_device, staging.memory);
buffer_create(graphics, size, (flags | VK_BUFFER_USAGE_TRANSFER_DST_BIT),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, buffer);
buffer_copy(graphics, *buffer, staging, size);
buffer_destroy(graphics, staging);
return 0;
}
static int vertex_populate_descriptions(VkVertexInputBindingDescription *binding_desc, VkVertexInputAttributeDescription *attribute_desc)
{
binding_desc->binding = 0;
binding_desc->stride = sizeof(struct vertex);
binding_desc->inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
attribute_desc[0].binding = 0;
attribute_desc[0].location = 0;
attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
attribute_desc[0].offset = offsetof(struct vertex, pos);
attribute_desc[1].binding = 0;
attribute_desc[1].location = 1;
attribute_desc[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attribute_desc[1].offset = offsetof(struct vertex, color);
return 0;
}
static int buffer_find_memory_type(VkPhysicalDevice device, u32 type_filter, VkMemoryPropertyFlags flags, u32 *memory_type_idx)
{
VkPhysicalDeviceMemoryProperties properties;
vkGetPhysicalDeviceMemoryProperties(device, &properties);
for(u32 i = 0; i < properties.memoryTypeCount; i++) {
if((type_filter & (i << i)) && ((properties.memoryTypes[i].propertyFlags & flags) == flags)) {
*memory_type_idx = i;
return 0;
}
}
err("No suitable memory type was found");
return 1;
}
#define X_VK_RESULT_TABLE(X) \
X(VK_SUCCESS) \
X(VK_NOT_READY) \
X(VK_TIMEOUT) \
X(VK_EVENT_SET) \
X(VK_EVENT_RESET) \
X(VK_INCOMPLETE) \
X(VK_ERROR_OUT_OF_HOST_MEMORY) \
X(VK_ERROR_OUT_OF_DEVICE_MEMORY) \
X(VK_ERROR_INITIALIZATION_FAILED) \
X(VK_ERROR_DEVICE_LOST) \
X(VK_ERROR_MEMORY_MAP_FAILED) \
X(VK_ERROR_LAYER_NOT_PRESENT) \
X(VK_ERROR_EXTENSION_NOT_PRESENT) \
X(VK_ERROR_FEATURE_NOT_PRESENT) \
X(VK_ERROR_INCOMPATIBLE_DRIVER) \
X(VK_ERROR_TOO_MANY_OBJECTS) \
X(VK_ERROR_FORMAT_NOT_SUPPORTED) \
X(VK_ERROR_FRAGMENTED_POOL) \
X(VK_ERROR_UNKNOWN) \
X(VK_ERROR_OUT_OF_POOL_MEMORY) \
X(VK_ERROR_INVALID_EXTERNAL_HANDLE) \
X(VK_ERROR_FRAGMENTATION) \
X(VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS) \
#define X_VK_RESULT_CASE(error) \
case error: return #error;
static char *str_VkResult(VkResult result)
{
switch(result) {
X_VK_RESULT_TABLE(X_VK_RESULT_CASE)
default:
return "VK_ERROR_OTHER";
}
}
#ifdef DEBUG
static bool instance_has_validation_layers(const char * const *layers, u32 nlayers)
{
(void)layers;
(void)nlayers;
// u32 navaliable = 0;
// vkEnumerateInstanceLayerProperties(&navaliable, NULL);
// VkLayerProperties *available_layers = xcalloc(navaliable, sizeof(VkLayerProperties));
// vkEnumerateInstanceLayerProperties(&navaliable, available_layers);
return true;
}
static int create_debug_messenger(graphics_t graphics, struct graphics_info *info)
{
(void)info;
int ret = 1;
VkDebugUtilsMessengerCreateInfoEXT cinfo = {0};
debug_messenger_populate_info(&cinfo);
VCHECK(CreateDebugUtilsMessengerEXT, graphics->instance, &cinfo, NULL, &graphics->debug_messenger);
ret = 0;
exit:
return ret;
}
static void debug_messenger_populate_info(VkDebugUtilsMessengerCreateInfoEXT *info)
{
info->sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
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;
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;
info->pfnUserCallback = debug_messenger_callback;
}
static VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData)
{
(void)messageSeverity;
(void)messageType;
(void)pUserData;
warn("Validation Layer: %s", pCallbackData->pMessage);
return VK_FALSE;
}
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
PFN_vkCreateDebugUtilsMessengerEXT f = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (f != NULL) {
return f(instance, pCreateInfo, pAllocator, pDebugMessenger);
} else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) {
PFN_vkDestroyDebugUtilsMessengerEXT f = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (f != NULL) {
f(instance, debugMessenger, pAllocator);
}
}
#endif
|