summaryrefslogtreecommitdiff
path: root/main.cpp
blob: 2b7ac6911b4bf1aba24177b4bb91efe1f2e6cfa9 (plain)
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
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
/*
Second Attempt at starting vulkan-tutorial.
Goal: Keep things simple, Use as much C as possible.
Don't do anything stupid or fancy with the code.

I created my own basic string helpers.
I reused my arena helpers for memory allocation.
This allowed me to avoid polluting lifetimes.
I have a few notes on that. I used a temporary arena and I use the calls
`temp_arena_begin` and `temp_arena_end` to use that.
I have found a simpler approach though. In block scopes {} / functions,
I just create an Arena variable via copy. This gets cleaned up when the scope ends
and I don't have to write temp_arena_begin or temp_arena_end as there is some additional
things I have to cater to with that.
*/

/*
Progress Notes: Hello Triangle Lesson Completed
- setup chapter completed.
- Presentation chapter completed
- Graphics Pipeline chapter completed
- Drawing chapter completed.
- Swapchain recreation (resizing completed)
- Vextex Buffer completed
- Uniform Buffer completed
*/

/*
* @research:
* 1. why does mapping all colors to red channel give me a monochrome image?
* 2. what is a render target?
* 3. read about framebuffers a bit: https://docs.vulkan.org/spec/latest/chapters/framebuffer.html
* 4. I am interested in learning about the difference between renderpasses and dynamic rendering:
        https://www.team-nutshell.dev/nutshellengine/articles/vulkan-renderpass.html
* 5. I am trying to see how I can get VK_SUBOPTIMAL_KHR surface issues to show up. I have not
*       handled them currently, and unless I get to see what exactly changes in their case, I cannot.
*   Most likely I would have to rework a small amount of functionality.
* 6. Regarding resize swapchain, create swapchain, swapchain image view, framebuffer
*       When do items like surface format, surface capabilities and surface present change dynamically,
*       due to window events
* 7. resize is broken on linux, no idea why. It could just be linux being linux but like, 
*   the resize window is very choppy/laggy on wayland and the resize operation is laggy on x11.
*   Meanwhile, everything works correctly on W11.
* 8. Driver developers recommend that you also store multiple
*   buffers, like the vertex and index buffer, into a single VkBuffer 
*   and use offsets in commands like vkCmdBindVertexBuffers
* 9. Push Constants: a more effective way of passing a small buffer of data to
*   shaders
* 10. Desriptors -> Descriptor Sets -> Descriptor Pools, I need to clarify the
* relationship between these items a bit better.
*/

#include <array>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <vulkan/vulkan_core.h>

#include "SDL2/SDL.h"
#include "SDL2/SDL_scancode.h"
#include "SDL2/SDL_timer.h"
#include "SDL2/SDL_video.h"
#include "SDL2/SDL_vulkan.h"
#include "vulkan/vulkan.h"

#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

//      Start utils

typedef uint8_t         u8;
typedef uint16_t        u16;
typedef uint32_t        u32;
typedef uint64_t        u64;

typedef int8_t          s8;
typedef int16_t         s16;
typedef int32_t         s32;
typedef int64_t         s64;

typedef float           r32;
typedef double          r64;

typedef u8              b8;
typedef unsigned char   uchar;

#define KB(x) ((x)*1024U)
#define MB(x) ((x)*KB(1024U))
#define GB(x) ((x)*MB(1024U))

#define internal static

#ifdef NDEBUG
#define assert(x)
#define SDL_assert(x)
#else
#endif
#include "arena.h"

struct Vertex {
    glm::vec2 pos;
    glm::vec3 col;
};

struct UniformBufferObject {
    alignas(16) glm::mat4 model;
    alignas(16) glm::mat4 view;
    alignas(16) glm::mat4 proj;
};

// string
struct Str256 {
    char buffer[256];
    u32 len;
};
typedef struct Str256 Str256;

internal Str256 str256(const char* str) {
    Str256 res = {};

    u32 i = 0;
    while (str[i] != '\0' && i < 256) {
            res.buffer[i] = str[i];
            res.len++;
            i++;
    }

    return res;
}

internal bool str256_match(Str256 a, Str256 b) {
    if (a.len != b.len) {
            return false;
    }

    return memcmp(a.buffer, b.buffer, a.len) == 0;
}

#define ARR_LEN(x) ((x) ? (sizeof((x))/sizeof((x)[0])) : 0)

u32 clamp_u32(u32 val, u32 bot, u32 top) {
        if (val < bot) {
                return bot;
        }
        else if (val > top) {
                return top;
        }

        return val;
}

// Alternate generic way to define VK arrays.
// This is separate because VK Image and ImageViews use u32 size
//      Example:
//      DefineArrVk(VkImage);
//      DefineArrVk(VkImageView);

#define DefineArrVk(Type) \
        struct Arr##Type { u32 size; Type *buffer; };

DefineArrVk(VkImage)
DefineArrVk(VkImageView)
DefineArrVk(VkFramebuffer)

struct ArrUChar {
        size_t size;
        uchar *buffer;
};

// END utils

#ifdef NDEBUG
bool enable_validation_layers = false;
const char **required_validation_layers = nullptr;
const char **required_extensions_internal = nullptr;
#else
bool enable_validation_layers = true;
const char* required_extensions_internal[] = {
        VK_EXT_DEBUG_UTILS_EXTENSION_NAME
};
const char *required_validation_layers[] = {
        "VK_LAYER_KHRONOS_validation"
};
#endif

struct MegaState {
        Arena arena;
        SDL_Window* window;

        VkInstance vk_instance;
        VkPhysicalDevice vk_physical_device;
        s32 queue_family_gfx_index;
        s32 queue_family_present_index;
        VkDevice vk_device;
        VkQueue vk_queue_gfx;
        VkQueue vk_queue_present;

        VkSurfaceKHR vk_khr_surface;
        // surface attributes
        VkSurfaceCapabilitiesKHR surface_capabilities;
        VkSurfaceFormatKHR surface_format;
        VkPresentModeKHR present_mode;
        VkExtent2D surface_resolution;
        u32 surface_image_count;

        VkSwapchainKHR vk_khr_swapchain;
        ArrVkImage vk_swapchain_images;
        ArrVkImageView vk_swapchain_image_views;
        ArrVkFramebuffer vk_framebuffers;

        VkRenderPass vk_render_pass;

        VkBuffer vk_vertex_buffer;
        VkDeviceMemory vk_mem_vertex_buffer;
        VkBuffer vk_index_buffer;
        VkDeviceMemory vk_mem_index_buffer;
        std::vector<VkBuffer> vk_uniform_buffers;
        std::vector<VkDeviceMemory> vk_mem_uniform_buffers;
        std::vector<void*> vk_mapped_uniform_buffers;

        VkImage vk_tex_img;
        VkDeviceMemory vk_mem_tex_img;

        VkDescriptorSetLayout vk_descriptor_set_layout;
        VkDescriptorPool vk_descriptor_pool;
        std::vector<VkDescriptorSet> vk_descriptor_sets;
        VkPipelineLayout vk_pipeline_layout;
        VkPipeline vk_pipeline;
};

internal b8 resizable = 0;
const u32 MAX_FRAMES_IN_FLIGHT = 2;

internal const char* required_device_extensions[] = {
        VK_KHR_SWAPCHAIN_EXTENSION_NAME
};

static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
        VkDebugUtilsMessageSeverityFlagBitsEXT  messageSeverity,
        VkDebugUtilsMessageTypeFlagsEXT messageTypes,
        const VkDebugUtilsMessengerCallbackDataEXT*     pCallbackData,
        void*   pUserData
) {
        if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
                printf("VK_VALIDATION_MESSAGE :: %s\n\n", pCallbackData->pMessage);
        }
        return VK_FALSE;
}

u32 resize_swapchain(MegaState* state) {
        /* @todo: implement this functionality as I guess extra practise.
        * biggest challenge I see here is clearing up the lifetimes
        * REF: vulkan-tutorial
        * the disadvantage of this
        * approach is that we need to stop all rendering before creating the new swap
        * chain. It is possible to create a new swap chain while drawing commands on an
        * image from the old swap chain are still in - flight.You need to pass the previous
        * swap chain to the oldSwapChain field in the VkSwapchainCreateInfoKHR struct
        * and destroy the old swap chain as soon as you've finished using it.
        */
        vkDeviceWaitIdle(state->vk_device);

        // get surface attributes
        {
                vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
                        state->vk_physical_device, state->vk_khr_surface, &state->surface_capabilities
                );

                // choose swap extent
                // get new swapchain pixel resolution
                {
                        s32 fb_width, fb_height;
                        SDL_Vulkan_GetDrawableSize(state->window, &fb_width, &fb_height);

                        VkExtent2D vk_extent = {
                                (u32)fb_width, (u32)fb_height
                        };
                        vk_extent.width = clamp_u32(
                                vk_extent.width,
                                state->surface_capabilities.minImageExtent.width,
                                state->surface_capabilities.maxImageExtent.width
                        );
                        vk_extent.height = clamp_u32(
                                vk_extent.height,
                                state->surface_capabilities.minImageExtent.height,
                                state->surface_capabilities.maxImageExtent.height
                        );

                        state->surface_resolution = vk_extent;
                }

        }
        // recreate swapchain
        VkSwapchainKHR old_swapchain = state->vk_khr_swapchain;
        {
                VkSwapchainCreateInfoKHR swapchain_create_info = {};
                swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
                swapchain_create_info.surface = state->vk_khr_surface;
                swapchain_create_info.minImageCount = state->surface_image_count;
                swapchain_create_info.imageFormat = state->surface_format.format;
                swapchain_create_info.imageColorSpace = state->surface_format.colorSpace;
                swapchain_create_info.imageExtent = state->surface_resolution;
                swapchain_create_info.imageArrayLayers = 1;
                swapchain_create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;

                u32 queue_family_indices[2] = { (u32)state->queue_family_gfx_index, (u32)state->queue_family_present_index };
                if (state->queue_family_gfx_index == state->queue_family_present_index) {
                        swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
                        swapchain_create_info.queueFamilyIndexCount = 0;
                        swapchain_create_info.pQueueFamilyIndices = NULL;
                }
                else {
                        swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
                        swapchain_create_info.queueFamilyIndexCount = 2;
                        swapchain_create_info.pQueueFamilyIndices = queue_family_indices;
                }

                swapchain_create_info.preTransform = state->surface_capabilities.currentTransform;
                swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
                swapchain_create_info.presentMode = state->present_mode;
                swapchain_create_info.clipped = VK_TRUE;
                swapchain_create_info.oldSwapchain = old_swapchain;

                VkResult vk_result = vkCreateSwapchainKHR(state->vk_device, &swapchain_create_info, nullptr, &state->vk_khr_swapchain);
                if (vk_result != VK_SUCCESS) {
                        printf("failed to create swapchain. Error: %d", vk_result);
                        return -1;
                }

                u32 new_img_count = 0;
                vkGetSwapchainImagesKHR(state->vk_device, state->vk_khr_swapchain, &new_img_count, NULL);
                SDL_assert(("new swapchain image count != existing image count. These should be the same and resizing is not supported",
                        new_img_count == state->vk_swapchain_images.size));

                vkGetSwapchainImagesKHR(
                        state->vk_device, state->vk_khr_swapchain,
                        &state->vk_swapchain_images.size,
                        state->vk_swapchain_images.buffer);
        }
        {
                for (u32 i = 0; i < state->surface_image_count; i++) {
                        VkFramebuffer framebuffer = state->vk_framebuffers.buffer[i];
                        vkDestroyFramebuffer(state->vk_device, framebuffer, nullptr);

                        VkImageView imageview = state->vk_swapchain_image_views.buffer[i];
                        vkDestroyImageView(state->vk_device, imageview, nullptr);
                }
                // @note: will destroy old swapchain later, once it's done rendering
                vkDestroySwapchainKHR(state->vk_device, old_swapchain, nullptr);
        }
        // recreate swapchain image views
        {
                for (u32 i = 0; i < state->vk_swapchain_images.size; i++) {
                        VkImageViewCreateInfo image_view_create_info = {};
                        image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
                        image_view_create_info.image = state->vk_swapchain_images.buffer[i];
                        image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
                        image_view_create_info.format = state->surface_format.format;

                        image_view_create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
                        image_view_create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
                        image_view_create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
                        image_view_create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;

                        image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
                        image_view_create_info.subresourceRange.baseMipLevel = 0;
                        image_view_create_info.subresourceRange.levelCount = 1;
                        image_view_create_info.subresourceRange.baseArrayLayer = 0;
                        image_view_create_info.subresourceRange.layerCount = 1;

                        VkResult vk_result = vkCreateImageView(state->vk_device, &image_view_create_info, NULL, &state->vk_swapchain_image_views.buffer[i]);

                        if (vk_result != VK_SUCCESS) {
                                printf("failed to create image view for image index %d, Error: %d", i, vk_result);
                                return -1;
                        }
                }
        }
        // recreate framebuffer
        {
                for (u32 i = 0; i < state->vk_swapchain_image_views.size; i++) {
                        VkImageView attachments[] = { state->vk_swapchain_image_views.buffer[i] };

                        VkFramebufferCreateInfo ci_framebuffer = {};
                        ci_framebuffer.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
                        ci_framebuffer.renderPass = state->vk_render_pass;
                        ci_framebuffer.attachmentCount = ARR_LEN(attachments);
                        ci_framebuffer.pAttachments = attachments;
                        ci_framebuffer.width = state->surface_resolution.width;
                        ci_framebuffer.height = state->surface_resolution.height;
                        ci_framebuffer.layers = 1;

                        if (vkCreateFramebuffer(state->vk_device, &ci_framebuffer, nullptr, &state->vk_framebuffers.buffer[i]) != VK_SUCCESS) {
                                return -1;
                        }
                }
        }

        printf("swapchain resized successfully\n");
        resizable = 0;
        return 0;
}

b8 vk_find_memory_type_index(VkPhysicalDevice physical_device,
                              VkMemoryRequirements mem_req, 
                              VkMemoryPropertyFlags property_flags,
                              s32 *memory_index) {
    *memory_index = -1;

    VkPhysicalDeviceMemoryProperties memory_properties;
    vkGetPhysicalDeviceMemoryProperties(physical_device, &memory_properties);

    // find memory meeting type requirements
    for (u32 i = 0; i < memory_properties.memoryTypeCount; i++) {
        b8 type_match = mem_req.memoryTypeBits & (1 << i);
        b8 properties_match = (memory_properties.memoryTypes[i].propertyFlags
                               & property_flags) == property_flags;

        if (type_match && properties_match) {
            *memory_index = i;
            printf("Success::vk_find_memory_type_index: Found memory type index\n");
            return 1;
        }
    }

    // memory requirements did not match any memory properties
    printf("Error::vk_find_memory_type_index: Failed to find memory type index\n");
    return 0;
}

b8 vk_create_buffer(VkDevice device, 
                    VkPhysicalDevice physical_device,
                    VkDeviceSize size, 
                    VkBufferUsageFlags usage, 
                    VkMemoryPropertyFlags property_flags,
                    VkBuffer *buffer, 
                    VkDeviceMemory *buffer_memory) 
{
    VkBufferCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
    ci.size = size;
    ci.usage = usage;
    ci.sharingMode = VK_SHARING_MODE_EXCLUSIVE;

    if (vkCreateBuffer(device, &ci, nullptr, buffer) != VK_SUCCESS) {
        printf("Error::vk_create_buffer: Failed to create buffer\n");
        return 0;
    }
    printf("Success::vk_create_buffer: Created vulkan buffer\n");

    // find_matched_memory:
    VkMemoryRequirements mem_req;
    vkGetBufferMemoryRequirements(device, *buffer, &mem_req);

    s32 matched_mem_index = -1;
    if (vk_find_memory_type_index(physical_device, 
                              mem_req, 
                              property_flags, 
                              &matched_mem_index) == 0) {
        return 0;
    }

    // allocate_memory: (debug_only)
    {
        VkMemoryAllocateInfo ai_memory{};
        ai_memory.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
        ai_memory.allocationSize = mem_req.size;
        ai_memory.memoryTypeIndex = matched_mem_index;

        if (vkAllocateMemory(device, &ai_memory, nullptr, buffer_memory) != VK_SUCCESS) {
            printf("Error::vk_create_buffer: failed to allocate device memory\n");
            return 0;
        }
        printf("Success::vk_create_buffer: Allocated device memory\n");
    }

    vkBindBufferMemory(device, *buffer, *buffer_memory, 0);

    return 1;
}

b8 vk_create_image(VkDevice vk_device, VkPhysicalDevice vk_physical_device,
                   u32 width, u32 height,
                   VkFormat format, 
                   VkImageTiling tiling, 
                   VkImageUsageFlags usage,
                   VkMemoryPropertyFlags memory_properties,
                   VkImage *vk_image,
                   VkDeviceMemory *vk_mem_image) {

    VkImageCreateInfo ci_img{};
    ci_img.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
    ci_img.imageType = VK_IMAGE_TYPE_2D;
    ci_img.extent.width = width;
    ci_img.extent.height = height;
    ci_img.extent.depth = 1;
    ci_img.mipLevels = 1;
    ci_img.arrayLayers = 1;
    ci_img.format = format;
    ci_img.tiling = tiling;
    ci_img.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
    ci_img.usage = usage;
    ci_img.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
    ci_img.samples = VK_SAMPLE_COUNT_1_BIT;
    ci_img.flags = 0;

    if (vkCreateImage(vk_device, &ci_img, nullptr, vk_image)
                      != VK_SUCCESS) {
        printf("Error :: Failed to create image\n");
        return 0;
    }

    // allocate_img_memory
    VkMemoryRequirements img_mem_req;
    vkGetImageMemoryRequirements(vk_device, 
                                 *vk_image, 
                                 &img_mem_req);

    s32 img_mem_type_index = -1;
    if (vk_find_memory_type_index(vk_physical_device, img_mem_req,
                                  memory_properties,
                                  &img_mem_type_index) == 0) {
        return 0;
    }

    VkMemoryAllocateInfo ai_mem{};
    ai_mem.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    ai_mem.allocationSize = img_mem_req.size;

    ai_mem.memoryTypeIndex = img_mem_type_index;
    
    if (vkAllocateMemory(vk_device, 
                         &ai_mem, nullptr, 
                         vk_mem_image) != VK_SUCCESS) {
        printf("Error:: Failed to allocate image memory\n");
        return 0;
    }

    vkBindImageMemory(vk_device, 
                      *vk_image, 
                      *vk_mem_image,
                      0);

    return 1;
}

int main() {

    MegaState state = {};

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        printf("Failed to initialize SDL2: %s\n", SDL_GetError());
        return 1;
    }

    if (SDL_Vulkan_LoadLibrary(nullptr) != 0) {
        printf("Failed to load vulkan library: %s\n", SDL_GetError());
        return 1;
    }

    state.window = SDL_CreateWindow(
        "vulkan-tutorial", 
        SDL_WINDOWPOS_CENTERED, 
        SDL_WINDOWPOS_CENTERED,
        800, 600,
        SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE
    );


    uchar* raw_memory = (uchar *)malloc(sizeof(uchar)*MB(16));
    arena_init(&state.arena, raw_memory, MB(100U) * sizeof(uchar));


    VkDebugUtilsMessengerEXT vk_debug_messenger = {};
    // Create Vulkan Instance
    {
        Arena vk_instance_arena = state.arena;

        VkApplicationInfo vk_app_info = {};
        vk_app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
        vk_app_info.pApplicationName = "Vulkan Hello Triangle";
        vk_app_info.applicationVersion = VK_MAKE_API_VERSION(0, 1, 0, 0);
        vk_app_info.pEngineName = "Sndgine";
        vk_app_info.engineVersion = VK_MAKE_API_VERSION(0, 1, 0, 0);
        vk_app_info.apiVersion = VK_MAKE_API_VERSION(0, 1, 0, 0);

        VkInstanceCreateInfo vk_create_info = {};
        vk_create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        vk_create_info.pApplicationInfo = &vk_app_info;

        char* required_extensions_256[8] = {};
        {
            // Set extensions

            // 1. get sdl extensions required to create a vulkan instance
            u32 sdl_extension_count = 0;
            SDL_Vulkan_GetInstanceExtensions(state.window, &sdl_extension_count, nullptr);
            const char *sdl_extensions[sdl_extension_count] = {};
            SDL_Vulkan_GetInstanceExtensions(state.window, &sdl_extension_count, sdl_extensions);
            u32 internal_extension_count = ARR_LEN(required_extensions_internal);

            u32 required_extension_count = sdl_extension_count + internal_extension_count;
            SDL_assert(("required extensions exceed the size of storage array",
                    (sdl_extension_count + internal_extension_count) <= 8));

            // 1.1. add required extensions to a common list
            for (int i = 0; i < sdl_extension_count; i++) {
                    required_extensions_256[i] = (char*)arena_alloc(&vk_instance_arena, sizeof(char) * 256);
                    Str256 extension_iter = str256(sdl_extensions[i]);
                    memcpy(required_extensions_256[i], extension_iter.buffer, extension_iter.len*sizeof(extension_iter.buffer));
            }
            for (int i = sdl_extension_count; i < sdl_extension_count + internal_extension_count; i++) {
                    required_extensions_256[i] = (char*)arena_alloc(&vk_instance_arena, sizeof(char) * 256);
                    Str256 extension_iter = str256(required_extensions_internal[i - sdl_extension_count]);
                    memcpy(
                            required_extensions_256[i],
                            extension_iter.buffer, extension_iter.len*sizeof(extension_iter.buffer)
                    );
            }

            // 2. get all supported extensions
            u32 supported_extensions_count = 0;
            VkExtensionProperties supported_extensions[32] = {};

            // 3. get extension count
            vkEnumerateInstanceExtensionProperties(nullptr, &supported_extensions_count, nullptr);
            SDL_assert(("supported extensions exceed the size of storage array", supported_extensions_count <= 32));

            // 4. get extension list
            vkEnumerateInstanceExtensionProperties(nullptr, &supported_extensions_count, supported_extensions);


            // 5. Enumerate and check if glfw Extensions are supported.
            u32 available_extensions = 0;
            for (u32 g = 0; g < required_extension_count; g++) {
                    for (u32 i = 0; i < supported_extensions_count; i++) {
                            if (str256_match(str256(required_extensions_256[g]), str256(supported_extensions[i].extensionName))) {
                                    available_extensions++;
                            }
                    }
            }

            SDL_assert((
                    "Not all required GLFW extensions are supported by this device",
                    required_extension_count == available_extensions
                    ));

            vk_create_info.enabledExtensionCount = required_extension_count;
            vk_create_info.ppEnabledExtensionNames = required_extensions_256;
        }
        {
            // Set validation layers
            u32 supported_validation_layers_count = 0;
            VkLayerProperties supported_validation_layers[32] = {};
            // 1. get validation layer count
            vkEnumerateInstanceLayerProperties(&supported_validation_layers_count, nullptr);
            SDL_assert(("supported validation layers exceed storage size", supported_validation_layers_count <= 32));
            // 2. get validation layers
            vkEnumerateInstanceLayerProperties(&supported_validation_layers_count, supported_validation_layers);

            // 3. check that required validation layers are in supported list
            u32 required_validation_layers_count = ARR_LEN(required_validation_layers);
            u32 available_validation_layers = 0;
            for (int v = 0; v < required_validation_layers_count; v++) {
                for (int i = 0; i < supported_validation_layers_count; i++) {
                    if (str256_match(str256(required_validation_layers[v]), str256(supported_validation_layers[i].layerName))) {
                        available_validation_layers++;
                    }
                }

            }

            SDL_assert(("Not all required validation layers are supported by this device",
                        required_validation_layers_count == available_validation_layers
                        ));

            vk_create_info.enabledLayerCount = required_validation_layers_count;
            vk_create_info.ppEnabledLayerNames = required_validation_layers;
        }

        VkDebugUtilsMessengerCreateInfoEXT debug_create_info = {};
        if (enable_validation_layers) {
            // setup debug info struct
            debug_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
            debug_create_info.messageSeverity =
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
            debug_create_info.messageType =
                    VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
            debug_create_info.pfnUserCallback = debugCallback;
            debug_create_info.pUserData = nullptr;

            vk_create_info.pNext = (VkDebugUtilsMessengerCreateInfoEXT*)&debug_create_info;
        }

        VkResult vk_result = vkCreateInstance(&vk_create_info, nullptr, &state.vk_instance);

        if (vk_result != VK_SUCCESS) {
            printf("failure in creating vulkan instance. Error: %d", vk_result);
            return -1;
        }

        printf("successfully created vulkan instance\n");
    }

    // Setup Debug Info
    if (enable_validation_layers) {
            // setup debug create info struct
            VkDebugUtilsMessengerCreateInfoEXT debug_create_info = {};
            debug_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
            debug_create_info.messageSeverity =
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
            debug_create_info.messageType =
                    VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
                    VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
            debug_create_info.pfnUserCallback = debugCallback;
            debug_create_info.pUserData = NULL;

            // load vkCreateDebugUtilsMessengerEXT
            {
                    auto fn = (PFN_vkCreateDebugUtilsMessengerEXT)
                            vkGetInstanceProcAddr(state.vk_instance, "vkCreateDebugUtilsMessengerEXT");
                    SDL_assert(("failed to load function symbols", fn != NULL));
                    VkResult res = fn(state.vk_instance, &debug_create_info, NULL, &vk_debug_messenger);
                    SDL_assert(("failed to create debug utils messenger", res == VK_SUCCESS));
            }
    }
    // setup vulkan surface
    {
        SDL_bool vk_result = SDL_Vulkan_CreateSurface(state.window, state.vk_instance, &state.vk_khr_surface);
        if (vk_result != SDL_TRUE) {
            printf("failed to create vulkan window surface. Error: %s", SDL_GetError());
            return -1;
        }
    }
    // select physical device
    state.queue_family_gfx_index = -1;
    state.queue_family_present_index = -1;
    // swap chain (surface) details
    // find suitable device
    // get surface capabilities
    // get queue family indexes
    {
            Arena vk_physical_device_arena = state.arena;
            u32 physical_device_count = 0;
            vkEnumeratePhysicalDevices(state.vk_instance, &physical_device_count, NULL);
            if (physical_device_count == 0) {
                    printf("no physical devices available, this is most likely an issue with the gpu or the drivers");
            }
            SDL_assert(("number of physical devices larger than storage size", physical_device_count <= 8));
            VkPhysicalDevice physical_devices[8] = {};
            vkEnumeratePhysicalDevices(state.vk_instance, &physical_device_count, physical_devices);

            u32 best_device_score = 0;
            VkPhysicalDevice best_physical_device = VK_NULL_HANDLE;
            for (int i = 0; i < physical_device_count; i++) {
                    u32 current_device_score = 0;
                    s32 current_graphics_index = -1;
                    s32 current_present_index = -1;

                    // @func: check if device is suitable
                    VkPhysicalDevice current_physical_device = physical_devices[i];

                    // get device properties
                    VkPhysicalDeviceProperties device_properties;
                    vkGetPhysicalDeviceProperties(current_physical_device, &device_properties);

                    // get device features
                    VkPhysicalDeviceFeatures device_features;
                    vkGetPhysicalDeviceFeatures(current_physical_device, &device_features);

                    if (device_properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
                            current_device_score += 1000;

                    current_device_score += device_properties.limits.maxImageDimension2D;

                    if (device_features.geometryShader == 0) {
                            continue;
                    }

                    {
                            // @func: check device extensions support
                            u32 extension_count = 0;
                            vkEnumerateDeviceExtensionProperties(current_physical_device, NULL, &extension_count, NULL);

                            VkExtensionProperties* supported_extensions =
                                    (VkExtensionProperties*)arena_alloc(&vk_physical_device_arena, sizeof(VkExtensionProperties) * extension_count);

                            vkEnumerateDeviceExtensionProperties(current_physical_device, NULL, &extension_count, supported_extensions);

                            u32 available_extension_count = 0;
                            for (u32 si = 0; si < extension_count; si++) {
                                    VkExtensionProperties supported_extension = supported_extensions[si];
                                    for (u32 ri = 0; ri < ARR_LEN(required_device_extensions); ri++) {
                                            const char* required_extension = required_device_extensions[ri];
                                            if (str256_match(str256(supported_extension.extensionName), str256(required_extension))) {
                                                    available_extension_count++;
                                            }
                                    }
                            }

                            if (available_extension_count != ARR_LEN(required_device_extensions)) {
                                    // if required extensions are not available, we can't run anything, skip device.
                                    continue;
                            }
                    }

                    // check swapchain support
                    {
                            // check swapchain has attributes
                            u32 surface_format_count = 0;
                            vkGetPhysicalDeviceSurfaceFormatsKHR(
                                    current_physical_device, state.vk_khr_surface, &surface_format_count, NULL
                            );

                            u32 surface_present_mode_count = 0;
                            vkGetPhysicalDeviceSurfacePresentModesKHR(
                                    current_physical_device, state.vk_khr_surface, &surface_present_mode_count, NULL
                            );

                            if (surface_format_count == 0 || surface_present_mode_count == 0) {
                                    // It is impossible to do anything without these. Skip the device
                                    continue;
                            }

                    }

                    // check physical device queue families
                    {
                            // get vulkan queue families
                            u32 queue_family_count = 0;
                            vkGetPhysicalDeviceQueueFamilyProperties(current_physical_device, &queue_family_count, NULL);

                            VkQueueFamilyProperties queue_families[16] = {};
                            SDL_assert(("queue family count larger than storage size", queue_family_count < 16));

                            vkGetPhysicalDeviceQueueFamilyProperties(current_physical_device, &queue_family_count, queue_families);

                            for (int i = 0; i < queue_family_count; i++) {
                                    VkQueueFamilyProperties entry_queue_family = queue_families[i];
                                    u32 has_present_family = 0;

                                    if (
                                            vkGetPhysicalDeviceSurfaceSupportKHR(
                                                    current_physical_device,
                                                    i, state.vk_khr_surface, &has_present_family
                                            ) == VK_SUCCESS)
                                    {
                                            current_device_score += 100;
                                            current_present_index = i;
                                    }

                                    if (entry_queue_family.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
                                            current_device_score += 100;
                                            current_graphics_index = i;
                                    }

                                    if (current_graphics_index >= 0 &&
                                            current_graphics_index == current_present_index) {
                                            break;
                                    }

                            }

                    }

                    if (best_device_score < current_device_score &&
                            current_graphics_index != -1 && current_present_index != -1) {
                            best_device_score = current_device_score;
                            best_physical_device = current_physical_device;
                            state.queue_family_gfx_index = current_graphics_index;
                            state.queue_family_present_index = current_present_index;
                    }
            }
            state.vk_physical_device = best_physical_device;
    }

    // create a logical device
    {
            // 1.1 specify device queue

            SDL_assert(("graphics queue family index must exist", state.queue_family_gfx_index != -1));
            SDL_assert(("present queue family index must exist", state.queue_family_present_index != -1));

            r32 queue_priority = 1.0;
            VkDeviceQueueCreateInfo queue_create_info[2] = {};
            u32 queue_size = 0;
            {
                    // a. graphics queue
                    VkDeviceQueueCreateInfo create_info_gfx = {};
                    create_info_gfx.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
                    create_info_gfx.queueFamilyIndex = state.queue_family_gfx_index;
                    create_info_gfx.queueCount = 1;
                    create_info_gfx.pQueuePriorities = &queue_priority;
                    queue_create_info[0] = create_info_gfx;
                    queue_size++;

                    // check if the present queue index is different.
                    // In case it is, only then should we create another queue entry.
                    if (state.queue_family_gfx_index != state.queue_family_present_index) {
                            // b. presentation
                            VkDeviceQueueCreateInfo create_info_present = {};
                            create_info_present.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
                            create_info_present.queueFamilyIndex = state.queue_family_present_index;
                            create_info_present.queueCount = 1;
                            create_info_present.pQueuePriorities = &queue_priority;
                            queue_create_info[1] = create_info_present;
                            queue_size++;
                    }
            }

            // 2. specify device features to use
            VkPhysicalDeviceFeatures device_features = {};

            // 3. create logical device
            VkDeviceCreateInfo device_create_info = {};
            device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
            device_create_info.pQueueCreateInfos = queue_create_info;
            device_create_info.queueCreateInfoCount = queue_size;
            device_create_info.pEnabledFeatures = &device_features;

            device_create_info.enabledExtensionCount = ARR_LEN(required_device_extensions);
            device_create_info.ppEnabledExtensionNames = required_device_extensions;

            // deprecated, done for legacy reasons
            device_create_info.enabledLayerCount = ARR_LEN(required_validation_layers);
            device_create_info.ppEnabledLayerNames = required_validation_layers;

            // create vulkan device
            VkResult vk_result = vkCreateDevice(state.vk_physical_device, &device_create_info, NULL, &state.vk_device);
            if (vk_result != VK_SUCCESS) {
                    printf("failed to create a vulkan device. Error %d\n", vk_result);
                    return -1;
            }

            // get queue family handle
            vkGetDeviceQueue(state.vk_device, state.queue_family_gfx_index, 0, &state.vk_queue_gfx);
            vkGetDeviceQueue(state.vk_device, state.queue_family_present_index, 0, &state.vk_queue_present);
    }
    // get surface attributes
    {
            Arena attribs_arena_temp = state.arena;
            vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
                    state.vk_physical_device, state.vk_khr_surface, &state.surface_capabilities
            );

            u32 surface_format_count = 0;
            vkGetPhysicalDeviceSurfaceFormatsKHR(
                    state.vk_physical_device, state.vk_khr_surface, &surface_format_count, NULL
            );
            VkSurfaceFormatKHR* surface_formats =
                    (VkSurfaceFormatKHR*)arena_alloc(&attribs_arena_temp, sizeof(VkSurfaceFormatKHR) * surface_format_count);
            vkGetPhysicalDeviceSurfaceFormatsKHR(
                    state.vk_physical_device, state.vk_khr_surface, &surface_format_count, surface_formats
            );

            u32 surface_present_mode_count = 0;
            vkGetPhysicalDeviceSurfacePresentModesKHR(
                    state.vk_physical_device, state.vk_khr_surface, &surface_present_mode_count, NULL
            );
            VkPresentModeKHR* surface_present_modes =
                    (VkPresentModeKHR*)arena_alloc(
                            &attribs_arena_temp,
                            sizeof(VkPresentModeKHR) * surface_present_mode_count
                    );
            vkGetPhysicalDeviceSurfacePresentModesKHR(
                    state.vk_physical_device, state.vk_khr_surface, &surface_present_mode_count, surface_present_modes
            );

            // check swapchain attribute properties for application requirements
            // swap chain surface formats
            state.surface_format = surface_formats[0];
            for (int sws_i = 0; sws_i < surface_format_count; sws_i++) {
                    VkSurfaceFormatKHR sf_iter = surface_formats[sws_i];

                    if (sf_iter.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR &&
                            sf_iter.format == VK_FORMAT_R8G8B8A8_SRGB) {
                            state.surface_format = sf_iter;
                            break;
                    }
            }

            // check swapchain surface present modes
            // this mode is always guaranteed to exist
            state.present_mode = VK_PRESENT_MODE_FIFO_KHR;
            for (int swp_i = 0; swp_i < surface_present_mode_count; swp_i++) {
                    VkPresentModeKHR pm_iter = surface_present_modes[swp_i];

                    if (pm_iter == VK_PRESENT_MODE_MAILBOX_KHR) {
                        state.present_mode = pm_iter;
                        break;
                    }                
            }

            // choose swap extent
            // get swapchain pixel resolution
            {
                    s32 fb_width, fb_height;
                    SDL_Vulkan_GetDrawableSize(state.window, &fb_width, &fb_height);

                    VkExtent2D vk_extent = {
                            (u32)fb_width, (u32)fb_height
                    };
                    vk_extent.width = clamp_u32(
                            vk_extent.width,
                            state.surface_capabilities.minImageExtent.width,
                            state.surface_capabilities.maxImageExtent.width
                    );
                    vk_extent.height = clamp_u32(
                            vk_extent.height,
                            state.surface_capabilities.minImageExtent.height,
                            state.surface_capabilities.maxImageExtent.height
                    );

                    state.surface_resolution = vk_extent;
            }

    }
    // create swap chain (surface)
    {
            state.surface_image_count = state.surface_capabilities.minImageCount + 1;
            if (state.surface_capabilities.maxImageCount > 0 &&
                    state.surface_image_count > state.surface_capabilities.maxImageCount) {
                    state.surface_image_count = state.surface_capabilities.maxImageCount;
            }

            VkSwapchainCreateInfoKHR swapchain_create_info = {};
            swapchain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
            swapchain_create_info.surface = state.vk_khr_surface;
            swapchain_create_info.minImageCount = state.surface_image_count;
            swapchain_create_info.imageFormat = state.surface_format.format;
            swapchain_create_info.imageColorSpace = state.surface_format.colorSpace;
            swapchain_create_info.imageExtent = state.surface_resolution;
            swapchain_create_info.imageArrayLayers = 1;
            swapchain_create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;

            u32 queue_family_indices[2] = { (u32)state.queue_family_gfx_index, (u32)state.queue_family_present_index };
            if (state.queue_family_gfx_index == state.queue_family_present_index) {
                    swapchain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
                    swapchain_create_info.queueFamilyIndexCount = 0;
                    swapchain_create_info.pQueueFamilyIndices = NULL;
            }
            else {
                    swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
                    swapchain_create_info.queueFamilyIndexCount = 2;
                    swapchain_create_info.pQueueFamilyIndices = queue_family_indices;
            }

            swapchain_create_info.preTransform = state.surface_capabilities.currentTransform;
            swapchain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
            swapchain_create_info.presentMode = state.present_mode;
            swapchain_create_info.clipped = VK_TRUE;
            swapchain_create_info.oldSwapchain = VK_NULL_HANDLE;

            VkResult vk_result = vkCreateSwapchainKHR(state.vk_device, &swapchain_create_info, nullptr, &state.vk_khr_swapchain);
            if (vk_result != VK_SUCCESS) {
                    printf("failed to create swapchain. Error: %d", vk_result);
                    return -1;
            }

            vkGetSwapchainImagesKHR(state.vk_device, state.vk_khr_swapchain, &state.vk_swapchain_images.size, NULL);
            state.vk_swapchain_images.buffer = (VkImage*)arena_alloc(&state.arena, sizeof(VkImage) * state.vk_swapchain_images.size);
            vkGetSwapchainImagesKHR(
                    state.vk_device, state.vk_khr_swapchain,
                    &state.vk_swapchain_images.size,
                    state.vk_swapchain_images.buffer);
    }
    // create image views
    {
            state.vk_swapchain_image_views.size = state.vk_swapchain_images.size;
            state.vk_swapchain_image_views.buffer = (VkImageView*)arena_alloc(&state.arena, sizeof(VkImageView) * state.vk_swapchain_image_views.size);

            for (u32 i = 0; i < state.vk_swapchain_images.size; i++) {
                    VkImageViewCreateInfo image_view_create_info = {};
                    image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
                    image_view_create_info.image = state.vk_swapchain_images.buffer[i];
                    image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
                    image_view_create_info.format = state.surface_format.format;

                    image_view_create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
                    image_view_create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
                    image_view_create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
                    image_view_create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;

                    image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
                    image_view_create_info.subresourceRange.baseMipLevel = 0;
                    image_view_create_info.subresourceRange.levelCount = 1;
                    image_view_create_info.subresourceRange.baseArrayLayer = 0;
                    image_view_create_info.subresourceRange.layerCount = 1;

                    VkResult vk_result = vkCreateImageView(state.vk_device, &image_view_create_info, NULL, &state.vk_swapchain_image_views.buffer[i]);

                    if (vk_result != VK_SUCCESS) {
                            printf("failed to create image view for image index %d, Error: %d", i, vk_result);
                            return -1;
                    }
            }
    }
    // create render pass
    {
            VkAttachmentDescription color_attachment = {};
            color_attachment.format = state.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;

            // renderpass
            VkAttachmentReference color_attachment_ref = {};
            color_attachment_ref.attachment = 0;
            color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

            // subpass
            VkSubpassDescription subpass_description = {};
            subpass_description.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
            subpass_description.colorAttachmentCount = 1;
            subpass_description.pColorAttachments = &color_attachment_ref;

            // create subpass dependency
            VkSubpassDependency subpass_dependency = {};
            subpass_dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
            subpass_dependency.dstSubpass = 0;
            subpass_dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            subpass_dependency.srcAccessMask = 0;
            subpass_dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
            subpass_dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;

            VkRenderPassCreateInfo ci_render_pass = {};
            ci_render_pass.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
            ci_render_pass.attachmentCount = 1;
            ci_render_pass.pAttachments = &color_attachment;
            ci_render_pass.subpassCount = 1;
            ci_render_pass.pSubpasses = &subpass_description;
            ci_render_pass.dependencyCount = 1;
            ci_render_pass.pDependencies = &subpass_dependency;

            VkResult vk_result = vkCreateRenderPass(state.vk_device, &ci_render_pass, nullptr, &state.vk_render_pass);
            if (vk_result != VK_SUCCESS) {
                    printf("failed to create the render pass. Error: %d", vk_result);
                    return -1;
            }
    }
    // @func: create_descriptor_set_layout:
    {
        VkDescriptorSetLayoutBinding lb_ubo{};
        lb_ubo.binding = 0;
        lb_ubo.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
        lb_ubo.descriptorCount = 1;
        lb_ubo.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
        lb_ubo.pImmutableSamplers = nullptr;

        VkDescriptorSetLayoutCreateInfo ci_desc_set{};
        ci_desc_set.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
        ci_desc_set.bindingCount = 1;
        ci_desc_set.pBindings = &lb_ubo;

        if (vkCreateDescriptorSetLayout(state.vk_device, &ci_desc_set, nullptr, 
                                        &state.vk_descriptor_set_layout) 
            != VK_SUCCESS) {
            printf("Failed to create descriptor set layout\n");
            return -1;
        }
    }
    // @func: create_graphics_pipeline
    // Vertex Data
    const std::vector<Vertex> vertices = {
        {{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}},
        {{0.5f,  -0.5f}, {0.0f, 1.0f, 0.0f}},
        {{0.5f,  0.5f},  {0.0f, 0.0f, 1.0f}},
        {{-0.5f, 0.5f},  {1.0f, 1.0f, 1.0f}}
    };

    const std::vector<u16> indices = {
        0, 1, 2, 2, 3, 0
    };

    {
            Arena temp_pipeline_arena = state.arena;
            ArrUChar vertex_shader = {};
            ArrUChar fragment_shader = {};
            // read vertex shader
            {
                    u64 fsize = 0;
                    const char filename[256] = "shaders/triangle.vert.spv";

                    // get a FILE pointer
                    FILE* fp = fopen(filename, "rb");
                    if (fp != nullptr) {
                            // set fp to end of file
                            fseek(fp, 0, SEEK_END);
                            // get filesize
                            fsize = ftell(fp);
                            vertex_shader.size = fsize;

                            vertex_shader.buffer = (uchar*)arena_alloc(&temp_pipeline_arena, vertex_shader.size);

                            fseek(fp, 0, SEEK_SET);
                            fread(vertex_shader.buffer, sizeof(uchar), vertex_shader.size, fp);

                            fclose(fp);
                    }
            }
            // read fragment shader
            {
                    u64 fsize = 0;
                    const char filename[256] = "shaders/triangle.frag.spv";

                    // get a FILE pointer
                    FILE* fp = fopen(filename, "rb");
                    if (fp != nullptr) {
                            // set fp to end of file
                            fseek(fp, 0, SEEK_END);
                            // get filesize
                            fsize = ftell(fp);
                            fragment_shader.size = fsize;

                            fragment_shader.buffer = (uchar*)arena_alloc(&temp_pipeline_arena, fragment_shader.size);
                            fseek(fp, 0, SEEK_SET);
                            fread(fragment_shader.buffer, sizeof(uchar), fragment_shader.size, fp);

                            fclose(fp);
                    }
            }

            VkShaderModule vertex_shader_module = {};
            // create vertex shader module
            {
                    VkShaderModuleCreateInfo create_info = {};
                    create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
                    create_info.codeSize = vertex_shader.size;
                    create_info.pCode = (u32*)vertex_shader.buffer;

                    VkResult vk_result = vkCreateShaderModule(state.vk_device, &create_info, nullptr, &vertex_shader_module);
                    if (vk_result != VK_SUCCESS) {
                            printf("failed to create vertex shader module. Error: %d", vk_result);
                            return -1;
                    }
            }
            // create fragment shader module
            VkShaderModule fragment_shader_module = {};
            {
                    VkShaderModuleCreateInfo create_info = {};
                    create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
                    create_info.codeSize = fragment_shader.size;
                    create_info.pCode = (u32*)fragment_shader.buffer;

                    VkResult vk_result = vkCreateShaderModule(state.vk_device, &create_info, NULL, &fragment_shader_module);
                    if (vk_result != VK_SUCCESS) {
                            printf("failed to create fragment shader module. Error: %d", vk_result);
                            return -1;
                    }
            }

            // shader stage creation
            VkPipelineShaderStageCreateInfo ci_pipeline_shader_stages[2] = {};
            {
                    ci_pipeline_shader_stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
                    ci_pipeline_shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
                    ci_pipeline_shader_stages[0].module = vertex_shader_module;
                    ci_pipeline_shader_stages[0].pName = "main";
            }
            {
                    ci_pipeline_shader_stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
                    ci_pipeline_shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
                    ci_pipeline_shader_stages[1].module = fragment_shader_module;
                    ci_pipeline_shader_stages[1].pName = "main";
            }

            // pipeline dynamic state
            VkDynamicState pipeline_dynamic_states[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
            VkPipelineDynamicStateCreateInfo ci_pipeline_dynamic_state = {};
            ci_pipeline_dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
            ci_pipeline_dynamic_state.dynamicStateCount = ARR_LEN(pipeline_dynamic_states);
            ci_pipeline_dynamic_state.pDynamicStates = pipeline_dynamic_states;

            // vertex input
            VkPipelineVertexInputStateCreateInfo ci_pipeline_vertex_input = {};
            VkVertexInputBindingDescription bind_desc{};
            std::array<VkVertexInputAttributeDescription, 2> attr_desc{};
            {
                bind_desc.binding = 0;
                bind_desc.stride = sizeof(Vertex);
                bind_desc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;

                attr_desc[0].binding = 0;
                attr_desc[0].location = 0;
                attr_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
                attr_desc[0].offset = 0;

                attr_desc[1].binding = 0;
                attr_desc[1].location = 1;
                attr_desc[1].format = VK_FORMAT_R32G32B32_SFLOAT;
                attr_desc[1].offset = sizeof(glm::vec2);

                ci_pipeline_vertex_input.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
                ci_pipeline_vertex_input.vertexBindingDescriptionCount = 1;
                ci_pipeline_vertex_input.pVertexBindingDescriptions = &bind_desc;
                ci_pipeline_vertex_input.vertexAttributeDescriptionCount = (u32)attr_desc.size();
                ci_pipeline_vertex_input.pVertexAttributeDescriptions = attr_desc.data();
            }

            // input assembly
            VkPipelineInputAssemblyStateCreateInfo ci_pipeline_input_assembly = {};
            ci_pipeline_input_assembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
            ci_pipeline_input_assembly.primitiveRestartEnable = VK_FALSE;
            ci_pipeline_input_assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;

            // viewports & scissors
            VkPipelineViewportStateCreateInfo ci_pipeline_viewport_state = {};
            ci_pipeline_viewport_state.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
            ci_pipeline_viewport_state.viewportCount = 1;
            ci_pipeline_viewport_state.scissorCount = 1;

            // rasterizer
            VkPipelineRasterizationStateCreateInfo ci_pipeline_raster = {};
            ci_pipeline_raster.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
            ci_pipeline_raster.depthClampEnable = VK_FALSE;
            ci_pipeline_raster.rasterizerDiscardEnable = VK_FALSE;
            ci_pipeline_raster.polygonMode = VK_POLYGON_MODE_FILL;
            ci_pipeline_raster.lineWidth = 1.0f;
            ci_pipeline_raster.cullMode = VK_CULL_MODE_BACK_BIT;
            ci_pipeline_raster.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
            ci_pipeline_raster.depthBiasEnable = VK_FALSE;
            ci_pipeline_raster.depthBiasClamp = 0.0f;
            ci_pipeline_raster.depthBiasConstantFactor = 0.0f;
            ci_pipeline_raster.depthBiasSlopeFactor = 0.0f;

            // vk pipeline multisample create info
            // disabled for now
            VkPipelineMultisampleStateCreateInfo ci_pipeline_multisample = {};
            ci_pipeline_multisample.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
            ci_pipeline_multisample.sampleShadingEnable = VK_FALSE;
            ci_pipeline_multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
            ci_pipeline_multisample.minSampleShading = 1.0f;
            ci_pipeline_multisample.pSampleMask = NULL;
            ci_pipeline_multisample.alphaToCoverageEnable = VK_FALSE;
            ci_pipeline_multisample.alphaToOneEnable = VK_FALSE;

            // depth and stencil testing
            // not needed so: NULL
            VkPipelineDepthStencilStateCreateInfo* ci_pipeline_depth_stencil = nullptr;

            // color blending
            VkPipelineColorBlendAttachmentState pipeline_color_blend_attachment = {};
            pipeline_color_blend_attachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
                    VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
            pipeline_color_blend_attachment.blendEnable = VK_FALSE;
            pipeline_color_blend_attachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
            pipeline_color_blend_attachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
            pipeline_color_blend_attachment.colorBlendOp = VK_BLEND_OP_ADD;
            pipeline_color_blend_attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
            pipeline_color_blend_attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
            pipeline_color_blend_attachment.alphaBlendOp = VK_BLEND_OP_ADD;

            VkPipelineColorBlendStateCreateInfo ci_pipeline_color_blend = {};
            ci_pipeline_color_blend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
            ci_pipeline_color_blend.logicOpEnable = VK_FALSE;
            ci_pipeline_color_blend.logicOp = VK_LOGIC_OP_COPY;
            ci_pipeline_color_blend.attachmentCount = 1;
            ci_pipeline_color_blend.pAttachments = &pipeline_color_blend_attachment;
            ci_pipeline_color_blend.blendConstants[0] = 0.0f;
            ci_pipeline_color_blend.blendConstants[1] = 0.0f;
            ci_pipeline_color_blend.blendConstants[2] = 0.0f;
            ci_pipeline_color_blend.blendConstants[3] = 0.0f;

            // pipeline layout
            VkPipelineLayoutCreateInfo ci_pipeline_layout = {};
            ci_pipeline_layout.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
            ci_pipeline_layout.setLayoutCount = 1;
            ci_pipeline_layout.pSetLayouts = &state.vk_descriptor_set_layout;
            ci_pipeline_layout.pushConstantRangeCount = 0;
            ci_pipeline_layout.pPushConstantRanges = nullptr;
            VkResult vk_result = vkCreatePipelineLayout(state.vk_device, 
                                                        &ci_pipeline_layout, 
                                                        nullptr, 
                                                        &state.vk_pipeline_layout);
            if (vk_result != VK_SUCCESS) {
                    printf("failed to create a pipeline layout. Error: %d", vk_result);
                    return -1;
            }

            // create the graphics pipeline
            VkGraphicsPipelineCreateInfo ci_pipeline_graphics = {};
            ci_pipeline_graphics.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
            ci_pipeline_graphics.stageCount = 2;
            ci_pipeline_graphics.pStages = ci_pipeline_shader_stages;

            ci_pipeline_graphics.pDynamicState = &ci_pipeline_dynamic_state;
            ci_pipeline_graphics.pVertexInputState = &ci_pipeline_vertex_input;
            ci_pipeline_graphics.pInputAssemblyState = &ci_pipeline_input_assembly;
            ci_pipeline_graphics.pViewportState = &ci_pipeline_viewport_state;
            ci_pipeline_graphics.pRasterizationState = &ci_pipeline_raster;
            ci_pipeline_graphics.pMultisampleState = &ci_pipeline_multisample;
            ci_pipeline_graphics.pDepthStencilState = ci_pipeline_depth_stencil;
            ci_pipeline_graphics.pColorBlendState = &ci_pipeline_color_blend;

            ci_pipeline_graphics.layout = state.vk_pipeline_layout;
            ci_pipeline_graphics.renderPass = state.vk_render_pass;
            ci_pipeline_graphics.subpass = 0;

            ci_pipeline_graphics.basePipelineHandle = VK_NULL_HANDLE;
            ci_pipeline_graphics.basePipelineIndex = -1;

            if (vkCreateGraphicsPipelines(state.vk_device, 
                                          VK_NULL_HANDLE, 1, 
                                          &ci_pipeline_graphics, 
                                          nullptr, 
                                          &state.vk_pipeline) != VK_SUCCESS) {
                    // no printf from this point as validation layers should cover it.
                    // todo: remove older printf.
                    return -1;
            }
            // destroy shader modules
            vkDestroyShaderModule(state.vk_device, vertex_shader_module, NULL);
            vkDestroyShaderModule(state.vk_device, fragment_shader_module, NULL);
    }
    // create framebuffers
    {
            state.vk_framebuffers.size = state.vk_swapchain_image_views.size;
            state.vk_framebuffers.buffer = (VkFramebuffer*)arena_alloc(
                    &state.arena,
                    sizeof(VkFramebuffer) * state.vk_framebuffers.size
            );

            for (u32 i = 0; i < state.vk_swapchain_image_views.size; i++) {
                    VkImageView attachments[] = { state.vk_swapchain_image_views.buffer[i] };

                    VkFramebufferCreateInfo ci_framebuffer = {};
                    ci_framebuffer.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
                    ci_framebuffer.renderPass = state.vk_render_pass;
                    ci_framebuffer.attachmentCount = ARR_LEN(attachments);
                    ci_framebuffer.pAttachments = attachments;
                    ci_framebuffer.width = state.surface_resolution.width;
                    ci_framebuffer.height = state.surface_resolution.height;
                    ci_framebuffer.layers = 1;

                    if (vkCreateFramebuffer(state.vk_device, &ci_framebuffer, nullptr, &state.vk_framebuffers.buffer[i]) != VK_SUCCESS) {
                            return -1;
                    }
            }
    }
    // create_command_pools:
    VkCommandPool vk_command_pool;
    {
            VkCommandPoolCreateInfo ci_command_pool = {};
            ci_command_pool.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
            ci_command_pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
            ci_command_pool.queueFamilyIndex = state.queue_family_gfx_index;

            if (vkCreateCommandPool(state.vk_device, &ci_command_pool, nullptr, &vk_command_pool) != VK_SUCCESS) {
                    return -1;
            }
    }
    // @func: create_texture_image:
    {
        s32 tex_width, tex_height, tex_chan;
        stbi_uc *pixels = stbi_load("textures/spike_noodles.jpg", 
                                    &tex_width, &tex_height, &tex_chan, 
                                    STBI_rgb_alpha);
        // shouldn't 4 be tex_chan (i.e. number of channels)
        VkDeviceSize image_size = tex_width * tex_height * 4;

        if (!pixels) {
            printf("Error :: Failed to load image\n");
            return -1;
        }

        VkBuffer staging_buffer;
        VkDeviceMemory staging_buffer_memory;

        vk_create_buffer(state.vk_device, state.vk_physical_device, image_size,
                         VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                         VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | 
                         VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                         &staging_buffer,
                         &staging_buffer_memory);

        void *staging_data;
        vkMapMemory(state.vk_device, staging_buffer_memory, 0, image_size, 0,
                    &staging_data);
        memcpy(staging_data, pixels, (size_t)image_size);
        vkUnmapMemory(state.vk_device, staging_buffer_memory);

        stbi_image_free(pixels);

        vk_create_image(state.vk_device, state.vk_physical_device,
                        (s32)tex_width, (s32)tex_height,
                        VK_FORMAT_R8G8B8A8_SRGB,
                        VK_IMAGE_TILING_OPTIMAL,
                        VK_IMAGE_USAGE_TRANSFER_DST_BIT |
                        VK_IMAGE_USAGE_SAMPLED_BIT,
                        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
                        &state.vk_tex_img,
                        &state.vk_mem_tex_img);

        // copy_buffer:
        {
            VkCommandBufferAllocateInfo ai_cmd{};
            ai_cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            ai_cmd.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            ai_cmd.commandPool = vk_command_pool;
            ai_cmd.commandBufferCount = 1;

            VkCommandBuffer vk_command_buffer;
            vkAllocateCommandBuffers(state.vk_device, 
                                     &ai_cmd, 
                                     &vk_command_buffer);
            {
                VkCommandBufferBeginInfo bi_cmd{};
                bi_cmd.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
                bi_cmd.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

                vkBeginCommandBuffer(vk_command_buffer, &bi_cmd);

                // transition_image_layout:

                // transition barrier access masks and pipeline stages
                //  CASE:   old: VK_IMAGE_LAYOUT_UNDEFINED
                //          new: VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
                //  srcAccessMask = 0
                //  dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT
                //  sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
                //  destStage   = VK_PIPELINE_STAGE_TRANSFER_BIT
                //
                //  CASE:   old: VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
                //          new: VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
                //  srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT
                //  dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
                //  sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT
                //  destStage   = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT
                //


                VkImageMemoryBarrier img_transition_barrier{};
                img_transition_barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
                img_transition_barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
                img_transition_barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
                img_transition_barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
                img_transition_barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
                img_transition_barrier.image = state.vk_tex_img;
                img_transition_barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
                img_transition_barrier.subresourceRange.baseMipLevel = 0;
                img_transition_barrier.subresourceRange.levelCount = 1;
                img_transition_barrier.subresourceRange.baseArrayLayer = 0;
                img_transition_barrier.subresourceRange.layerCount = 1;
                img_transition_barrier.srcAccessMask = 0;
                img_transition_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;

                vkCmdPipelineBarrier(vk_command_buffer,
                                     VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 
                                     VK_PIPELINE_STAGE_TRANSFER_BIT, 
                                     0, 
                                     0, nullptr,
                                     0, nullptr,
                                     1, &img_transition_barrier);

                // copy_pixel_buffer_to_image:
                VkBufferImageCopy region{};
                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 = {0, 0, 0};
                region.imageExtent = { (u32)tex_width, (u32)tex_height, 1};

                vkCmdCopyBufferToImage(vk_command_buffer,
                                       staging_buffer,
                                       state.vk_tex_img,
                                       VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
                                       1,
                                       &region);


                vkEndCommandBuffer(vk_command_buffer);
            }

            vkFreeCommandBuffers(state.vk_device, vk_command_pool, 1, &vk_command_buffer);
        }
        vkDestroyBuffer(state.vk_device, staging_buffer, nullptr);
        vkFreeMemory(state.vk_device, staging_buffer_memory, nullptr);
        
    }
    // @func: create_index_buffer:
    {
        u64 buffer_size = sizeof(indices[0]) * indices.size();
        VkBuffer staging_buffer;
        VkDeviceMemory staging_buffer_memory;
        vk_create_buffer(state.vk_device, state.vk_physical_device,
                         buffer_size,
                         VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                         VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                         VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                         &staging_buffer, 
                         &staging_buffer_memory);

        // fill index buffer
        void *index_data;
        vkMapMemory(state.vk_device, staging_buffer_memory, 0, buffer_size, 0,
                    &index_data);
        memcpy(index_data, indices.data(), buffer_size);
        vkUnmapMemory(state.vk_device, staging_buffer_memory);

        vk_create_buffer(state.vk_device, state.vk_physical_device,
                         buffer_size,
                         VK_BUFFER_USAGE_TRANSFER_DST_BIT |
                         VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
                         VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
                         &state.vk_index_buffer,
                         &state.vk_mem_index_buffer);

        // copy buffer from SRC -> DEST
        // vk_copy_buffer:
        {
            VkCommandBufferAllocateInfo alloc_info{};
            alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            alloc_info.commandPool = vk_command_pool;
            alloc_info.commandBufferCount = 1;

            VkCommandBuffer command_buffer;
            vkAllocateCommandBuffers(state.vk_device, &alloc_info, &command_buffer);

            {
                VkCommandBufferBeginInfo begin_info{};
                begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
                begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

                vkBeginCommandBuffer(command_buffer, &begin_info);

                VkBufferCopy copy_region{};
                copy_region.srcOffset = 0;
                copy_region.dstOffset = 0;
                copy_region.size = buffer_size;
                vkCmdCopyBuffer(command_buffer, staging_buffer, 
                                state.vk_index_buffer, 1, &copy_region);

                vkEndCommandBuffer(command_buffer);

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

                vkQueueSubmit(state.vk_queue_gfx, 1, &submit_info, VK_NULL_HANDLE);
                vkQueueWaitIdle(state.vk_queue_gfx);

            }

            vkFreeCommandBuffers(state.vk_device, vk_command_pool, 
                                 1, &command_buffer);
        }

        vkDestroyBuffer(state.vk_device, staging_buffer, nullptr);
        vkFreeMemory(state.vk_device, staging_buffer_memory, nullptr);

    }
    // @func: create_vertex_buffer:
    {

        // staging buffer
        u32 buffer_size = sizeof(vertices[0]) * vertices.size();
        VkBuffer staging_buffer;
        VkDeviceMemory staging_buffer_memory;
        vk_create_buffer(state.vk_device, state.vk_physical_device,
                         buffer_size, 
                         VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                         VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                         VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                         &staging_buffer, 
                         &staging_buffer_memory);

        // fill vertex buffer
        void *vertex_data;
        vkMapMemory(state.vk_device, staging_buffer_memory, 
                    0, buffer_size, 0, &vertex_data);
        memcpy(vertex_data, vertices.data(), buffer_size); 
        vkUnmapMemory(state.vk_device, staging_buffer_memory);

        vk_create_buffer(state.vk_device, state.vk_physical_device,
                         buffer_size,
                         VK_BUFFER_USAGE_TRANSFER_DST_BIT |
                            VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
                         VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
                         &state.vk_vertex_buffer,
                         &state.vk_mem_vertex_buffer);

        // copy buffer from SRC -> DEST
        // vk_copy_buffer:
        {
            VkCommandBufferAllocateInfo alloc_info{};
            alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            alloc_info.commandPool = vk_command_pool;
            alloc_info.commandBufferCount = 1;

            VkCommandBuffer command_buffer;
            vkAllocateCommandBuffers(state.vk_device, &alloc_info, &command_buffer);

            {
                VkCommandBufferBeginInfo begin_info{};
                begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
                begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

                vkBeginCommandBuffer(command_buffer, &begin_info);

                VkBufferCopy copy_region{};
                copy_region.srcOffset = 0;
                copy_region.dstOffset = 0;
                copy_region.size = buffer_size;
                vkCmdCopyBuffer(command_buffer, staging_buffer, state.vk_vertex_buffer, 1, &copy_region);

                vkEndCommandBuffer(command_buffer);

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

                vkQueueSubmit(state.vk_queue_gfx, 1, &submit_info, VK_NULL_HANDLE);
                vkQueueWaitIdle(state.vk_queue_gfx);

            }

            vkFreeCommandBuffers(state.vk_device, vk_command_pool, 1, &command_buffer);
        }

        vkDestroyBuffer(state.vk_device, staging_buffer, nullptr);
        vkFreeMemory(state.vk_device, staging_buffer_memory, nullptr);
    }
    // create_uniform_buffer:
    {
        VkDeviceSize buffer_size = sizeof(UniformBufferObject);

        state.vk_uniform_buffers.resize(MAX_FRAMES_IN_FLIGHT);
        state.vk_mem_uniform_buffers.resize(MAX_FRAMES_IN_FLIGHT);
        state.vk_mapped_uniform_buffers.resize(MAX_FRAMES_IN_FLIGHT);

        for (u32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
            vk_create_buffer(state.vk_device, 
                             state.vk_physical_device, 
                             buffer_size, 
                             VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, 
                             VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                             VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 
                             &state.vk_uniform_buffers[i], 
                             &state.vk_mem_uniform_buffers[i]);

            vkMapMemory(state.vk_device, 
                        state.vk_mem_uniform_buffers[i], 
                        0, buffer_size, 0, 
                        &state.vk_mapped_uniform_buffers[i]);
        }
    }
    // create_descriptor_pool:
    {
        VkDescriptorPoolSize pool_size;
        pool_size.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
        pool_size.descriptorCount = (u32)MAX_FRAMES_IN_FLIGHT;

        VkDescriptorPoolCreateInfo ci_desc_pool{};
        ci_desc_pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
        ci_desc_pool.poolSizeCount = 1;
        ci_desc_pool.pPoolSizes = &pool_size;
        ci_desc_pool.maxSets = (u32)MAX_FRAMES_IN_FLIGHT;

        if (vkCreateDescriptorPool(state.vk_device, 
                                   &ci_desc_pool, nullptr, 
                                   &state.vk_descriptor_pool) != VK_SUCCESS) {
            printf("Error :: Failed to create descriptor pool\n");
            return -1;
        }
    }
    // create_descriptor_sets:
    {
        std::vector<VkDescriptorSetLayout> layouts(MAX_FRAMES_IN_FLIGHT, 
                                                   state.vk_descriptor_set_layout);
        VkDescriptorSetAllocateInfo alloc_info{};
        alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
        alloc_info.descriptorPool = state.vk_descriptor_pool;
        alloc_info.descriptorSetCount = (u32)MAX_FRAMES_IN_FLIGHT;
        alloc_info.pSetLayouts = layouts.data();

        state.vk_descriptor_sets.resize(MAX_FRAMES_IN_FLIGHT);
        if(vkAllocateDescriptorSets(state.vk_device, 
                                    &alloc_info, 
                                    state.vk_descriptor_sets.data()) 
           != VK_SUCCESS) {
            printf("Error :: Failed to allocate descriptor sets\n");
            return -1;
        }

        // populate_descriptors:
        {
            for (u32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
                VkDescriptorBufferInfo buffer_info{};
                buffer_info.buffer = state.vk_uniform_buffers[i];
                buffer_info.offset = 0;
                buffer_info.range = sizeof(UniformBufferObject);

                VkWriteDescriptorSet desc_write{};
                desc_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
                desc_write.dstSet = state.vk_descriptor_sets[i];
                desc_write.dstBinding = 0;
                desc_write.dstArrayElement = 0;
                desc_write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
                desc_write.descriptorCount = 1;
                desc_write.pBufferInfo = &buffer_info;
                desc_write.pImageInfo = nullptr;
                desc_write.pTexelBufferView = nullptr;

                vkUpdateDescriptorSets(state.vk_device, 1, &desc_write,
                                       0, nullptr);
            }
        }
    }
    // create command buffer
    VkCommandBuffer vk_command_buffer[MAX_FRAMES_IN_FLIGHT] = {};
    {
            VkCommandBufferAllocateInfo ai_command_buffer = {};
            ai_command_buffer.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            ai_command_buffer.commandPool = vk_command_pool;
            ai_command_buffer.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            ai_command_buffer.commandBufferCount = MAX_FRAMES_IN_FLIGHT;

            if (vkAllocateCommandBuffers(state.vk_device, &ai_command_buffer, vk_command_buffer) != VK_SUCCESS) {
                    return -1;
            }
    }
    // create synchronization objects
    VkSemaphore vk_smp_image_available[MAX_FRAMES_IN_FLIGHT] = {};
    VkSemaphore vk_smp_render_done[state.surface_image_count] = {};
    VkFence vk_fence_frame_flight[MAX_FRAMES_IN_FLIGHT] = {};
    {
            VkSemaphoreCreateInfo ci_semaphore = {};
            ci_semaphore.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;

            VkFenceCreateInfo ci_fence = {};
            ci_fence.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
            ci_fence.flags = VK_FENCE_CREATE_SIGNALED_BIT;

            for (u32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
                    VkResult res_image_available = vkCreateSemaphore(state.vk_device, &ci_semaphore, nullptr, &vk_smp_image_available[i]);
                    VkResult res_frame_flight = vkCreateFence(state.vk_device, &ci_fence, nullptr, &vk_fence_frame_flight[i]);

                    if (res_image_available != VK_SUCCESS ||
                        res_frame_flight != VK_SUCCESS) {
                            return -1;
                    }
            }
            // submit (render done semaphore)
            for (u32 i = 0; i < state.surface_image_count; i++) {
                VkResult res_render_done = vkCreateSemaphore(state.vk_device, &ci_semaphore, nullptr, &vk_smp_render_done[i]);
                if (res_render_done != VK_SUCCESS) {
                    return -1;
                }
            }
    }

    u32 current_frame = 0;
    b8 running = 1;
    u32 start_time = SDL_GetTicks();
    while (running) {
        u32 current_time = SDL_GetTicks();
        // draw frame
        SDL_Event event;
        while(SDL_PollEvent(&event)) {
            switch(event.type) {
                case SDL_QUIT: {
                    running = 0;
                } break;

                case SDL_WINDOWEVENT: {
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_RESIZED: {
                            resizable = 1;
                        } break;

                        default:
                            break;
                    }
                } break;

                case SDL_KEYDOWN: {
                    switch (event.key.keysym.scancode)
                    {
                        case SDL_SCANCODE_ESCAPE:{
                            printf("Escape code, closing app\n");
                            running = 0;
                        } break;

                        default:
                            break;
                    }
                } break;

                default:
                    break;
            }
        }
        // wait until previous frame finishes
        vkWaitForFences(state.vk_device, 1, vk_fence_frame_flight, VK_TRUE, UINT64_MAX);

        // get an image from the swapchain (sw)
        u32 sw_image_index = 0;
        VkResult vk_result = vkAcquireNextImageKHR(state.vk_device, state.vk_khr_swapchain, 
                                                   UINT64_MAX, vk_smp_image_available[current_frame], 
                                                   VK_NULL_HANDLE, &sw_image_index);

        if (vk_result == VK_ERROR_OUT_OF_DATE_KHR) {
            // recreate swapchain -> currently only resizing is supported
            if (resize_swapchain(&state) != 0) {
                return -1;
            }
            // go to next frame
            // @note: we go to the next frame because the images are no longer valid.
            // technically nothing is valid, but the image needs to be acquired after creation
            // so that should perhaps help explain this directly
            //continue;
        }
        else if (vk_result != VK_SUCCESS && vk_result != VK_SUBOPTIMAL_KHR) {
            // suboptimal swapchain is allowed to proceed without recreation
            return -1;
        }

        // reset fence once we are sure we will be submitting work to the device
        vkResetFences(state.vk_device, 1, &vk_fence_frame_flight[current_frame]);
        vkResetCommandBuffer(vk_command_buffer[current_frame], 0);

        // @func: update_uniform_buffer:
        {
            r32 rotation_inc = (r32)(current_time - start_time)/1000.0f;
            UniformBufferObject ubo{};
            ubo.model = glm::rotate(glm::mat4(1.0f), 
                                    rotation_inc*glm::radians(90.0f), 
                                    glm::vec3(0.0f, 0.0f, 1.0f));
            ubo.view = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f),
                                   glm::vec3(0.0f, 0.0f, 0.0f),
                                   glm::vec3(0.0f, 0.0f, 1.0f));
            ubo.proj = glm::perspective(glm::radians(45.0f),
                                        state.surface_resolution.width / 
                                        (r32)state.surface_resolution.height,
                                        0.0f, 10.0f);
            ubo.proj[1][1] *= -1;

            memcpy(state.vk_mapped_uniform_buffers[current_frame],
                   &ubo, sizeof(ubo));
        }

        // @func: record_command_buffer
        {
            VkCommandBufferBeginInfo bi_command_buffer = {};
            bi_command_buffer.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
            bi_command_buffer.flags = 0;
            bi_command_buffer.pInheritanceInfo = nullptr;

            if (vkBeginCommandBuffer(vk_command_buffer[current_frame], &bi_command_buffer) != VK_SUCCESS) {
                return -1;
            }
            // start render pass
            {
                VkRenderPassBeginInfo bi_render_pass = {};
                bi_render_pass.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
                bi_render_pass.renderPass = state.vk_render_pass;
                bi_render_pass.framebuffer = state.vk_framebuffers.buffer[sw_image_index];

                bi_render_pass.renderArea.offset = { 0, 0 };
                bi_render_pass.renderArea.extent = state.surface_resolution;

                VkClearValue clear_color = { {{0.0f, 0.0f, 0.0f, 1.0f}} };
                bi_render_pass.clearValueCount = 1;
                bi_render_pass.pClearValues = &clear_color;

                vkCmdBeginRenderPass(vk_command_buffer[current_frame], 
                                     &bi_render_pass, 
                                     VK_SUBPASS_CONTENTS_INLINE);
                {
                    vkCmdBindPipeline(vk_command_buffer[current_frame], 
                                      VK_PIPELINE_BIND_POINT_GRAPHICS, 
                                      state.vk_pipeline);

                    // viewport
                    VkViewport vk_viewport = {};
                    vk_viewport.x = 0.0f;
                    vk_viewport.y = 0.0f;
                    vk_viewport.width = (r32)state.surface_resolution.width;
                    vk_viewport.height = (r32)state.surface_resolution.height;
                    vk_viewport.minDepth = 0.0f;
                    vk_viewport.maxDepth = 1.0f;
                    vkCmdSetViewport(vk_command_buffer[current_frame], 0, 1, &vk_viewport);

                    // scissor
                    VkRect2D scissor = {};
                    scissor.offset = { 0, 0 };
                    scissor.extent = state.surface_resolution;
                    vkCmdSetScissor(vk_command_buffer[current_frame], 0, 1, &scissor);

                    // vertex buffer
                    VkBuffer vertex_buffers[] = {state.vk_vertex_buffer};
                    VkDeviceSize offsets[] = {0};
                    vkCmdBindVertexBuffers(vk_command_buffer[current_frame], 
                                           0, 1, vertex_buffers, offsets);
                    vkCmdBindIndexBuffer(vk_command_buffer[current_frame], 
                                         state.vk_index_buffer, 
                                         0, VK_INDEX_TYPE_UINT16);
                    vkCmdBindDescriptorSets(vk_command_buffer[current_frame], 
                                            VK_PIPELINE_BIND_POINT_GRAPHICS, 
                                            state.vk_pipeline_layout, 
                                            0, 1, 
                                            &state.vk_descriptor_sets[current_frame], 
                                            0, nullptr);
                    vkCmdDrawIndexed(vk_command_buffer[current_frame],
                                     indices.size(), 1, 0, 0, 0);
                }
                vkCmdEndRenderPass(vk_command_buffer[current_frame]);
            }
            if (vkEndCommandBuffer(vk_command_buffer[current_frame]) != VK_SUCCESS) {
                    return -1;
            }
        }

        // submit the command buffer
        VkSemaphore wait_semaphores[] = { vk_smp_image_available[current_frame] };
        VkSemaphore signal_semaphores[] = { vk_smp_render_done[sw_image_index] };
        {
            VkSubmitInfo si_command_buffer = {};
            si_command_buffer.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

            VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
            si_command_buffer.waitSemaphoreCount = 1;
            si_command_buffer.pWaitSemaphores = wait_semaphores;
            si_command_buffer.pWaitDstStageMask = wait_stages;

            si_command_buffer.commandBufferCount = 1;
            si_command_buffer.pCommandBuffers = &vk_command_buffer[current_frame];

            si_command_buffer.signalSemaphoreCount = 1;
            si_command_buffer.pSignalSemaphores = signal_semaphores;

            if (vkQueueSubmit(state.vk_queue_gfx, 1, 
                              &si_command_buffer, 
                              vk_fence_frame_flight[current_frame]) != VK_SUCCESS) {
                return -1;
            }
        }

    // submit result back to swapchain
        {
            VkPresentInfoKHR present_info = {};
            present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;

            present_info.waitSemaphoreCount = 1;
            present_info.pWaitSemaphores = signal_semaphores;

            VkSwapchainKHR swapchain_list[] = { state.vk_khr_swapchain };
            present_info.swapchainCount = 1;
            present_info.pSwapchains = swapchain_list;
            present_info.pImageIndices = &sw_image_index;

            present_info.pResults = nullptr;

            VkResult vk_result = vkQueuePresentKHR(state.vk_queue_present, &present_info);

            if ((vk_result == VK_ERROR_OUT_OF_DATE_KHR ||
                vk_result == VK_SUBOPTIMAL_KHR) || resizable) {
                // @note: the suboptimal check which usually works when the 
                // surface is changed will not change anything because 
                // the recreate function only resizes swapchain
                // @todo: I guess I can add that for completeness,
                // even though I have no way to test it out realistically
                
                if (resize_swapchain(&state) != 0) return -1;
            }
            else if (vk_result != VK_SUCCESS) {
                return -1;
            }
        }

        current_frame = (current_frame + 1) % MAX_FRAMES_IN_FLIGHT;

        SDL_Delay(16);
    }
    // wait for logical device to finish operations
    vkDeviceWaitIdle(state.vk_device);

    // cleanup
    for (u32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
        vkDestroyFence(state.vk_device, vk_fence_frame_flight[i], nullptr);
        vkDestroySemaphore(state.vk_device, vk_smp_image_available[i], nullptr);
    }
    for (u32 i = 0; i < state.surface_image_count; i++) {
        vkDestroySemaphore(state.vk_device, vk_smp_render_done[i], nullptr);
    }
    vkDestroyCommandPool(state.vk_device, vk_command_pool, nullptr);

    // destroy buffers
    vkDestroyBuffer(state.vk_device, state.vk_vertex_buffer, nullptr);
    vkDestroyBuffer(state.vk_device, state.vk_index_buffer, nullptr);
    vkFreeMemory(state.vk_device, state.vk_mem_vertex_buffer, nullptr);
    vkFreeMemory(state.vk_device, state.vk_mem_index_buffer, nullptr);
    vkDestroyImage(state.vk_device, state.vk_tex_img, nullptr);
    vkFreeMemory(state.vk_device, state.vk_mem_tex_img, nullptr);

    // destroy framebuffers
    {
        for (u32 i= 0; i < state.vk_framebuffers.size; i++) {
            VkFramebuffer framebuffer_item = state.vk_framebuffers.buffer[i];
            vkDestroyFramebuffer(state.vk_device, framebuffer_item, nullptr);
        }
    }
    vkDestroyPipeline(state.vk_device, state.vk_pipeline, NULL);
    vkDestroyPipelineLayout(state.vk_device, state.vk_pipeline_layout, NULL);
    vkDestroyRenderPass(state.vk_device, state.vk_render_pass, NULL);
    // destroy image views
    {
        for (u32 i = 0; i < state.vk_swapchain_image_views.size; i++) {
            vkDestroyImageView(state.vk_device, state.vk_swapchain_image_views.buffer[i], NULL);
        }
    }
    vkDestroySwapchainKHR(state.vk_device, state.vk_khr_swapchain, NULL);
    for (u32 i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
        vkDestroyBuffer(state.vk_device, 
                        state.vk_uniform_buffers[i], nullptr);
        vkFreeMemory(state.vk_device, state.vk_mem_uniform_buffers[i], nullptr);
    }
    vkDestroyDescriptorPool(state.vk_device, 
                            state.vk_descriptor_pool,
                            nullptr);
    vkDestroyDescriptorSetLayout(state.vk_device, state.vk_descriptor_set_layout, 
                                 nullptr);
    vkDestroyDevice(state.vk_device, NULL);

    if (enable_validation_layers) {
        auto fn = (PFN_vkDestroyDebugUtilsMessengerEXT)
            vkGetInstanceProcAddr(state.vk_instance, "vkDestroyDebugUtilsMessengerEXT");
        SDL_assert(("failed to load function symbols", fn != NULL));
        fn(state.vk_instance, vk_debug_messenger, NULL);
    }

    // @revise: why are we destroying surface here? after destroying the logical device
    vkDestroySurfaceKHR(state.vk_instance, state.vk_khr_surface, NULL);
    vkDestroyInstance(state.vk_instance, NULL);
    SDL_DestroyWindow(state.window);
    SDL_Quit();
}