summaryrefslogtreecommitdiff
path: root/main.c
blob: 706397967db79069cd3c721c6f11d4547eb092dd (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
#include <stdio.h>
#include <vulkan/vulkan.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
#include <stdbool.h>
#include <string.h>

#define MAX_FRAMES_INFLIGHT 2

static SDL_Window *window = NULL;
static VkDebugUtilsMessengerEXT debug_messenger;
static VkInstance instance = VK_NULL_HANDLE;
static VkPhysicalDevice phy_gpu = VK_NULL_HANDLE;
static VkDevice gpu = VK_NULL_HANDLE;
static VkSurfaceKHR surface = VK_NULL_HANDLE;
static VkQueue gfx_queue;
static VkQueue present_queue;
static VkSwapchainKHR swapchain;
static VkFormat swapchain_format;
static VkExtent2D swapchain_extent;
static VkRenderPass render_pass;
static VkPipelineLayout pipeline_layout;
static VkCommandPool command_pool;
static VkCommandBuffer command_buffers[MAX_FRAMES_INFLIGHT];
static VkPipeline graphics_pipeline;
static VkSemaphore image_avail[MAX_FRAMES_INFLIGHT];
static VkSemaphore render_finished[MAX_FRAMES_INFLIGHT];
static VkFence in_flight_fence[MAX_FRAMES_INFLIGHT];
static uint32_t current_frame = 0;
static struct {
	size_t len;
	VkImage data[];
} *swapchain_images;
static struct {
	size_t len;
	VkImageView data[];
} *swapchain_image_views;
static struct {
	size_t len;
	VkFramebuffer data[];
} *framebuffers;

struct code {
	size_t len;
	uint8_t data[];
};

struct swapchain_details {
	VkSurfaceCapabilitiesKHR caps;
	struct surface_formats {
		size_t len;
		VkSurfaceFormatKHR data[];
	} *formats;
	struct present_modes {
		size_t len;
		VkPresentModeKHR data[];
	} *present_modes;
};

void free_swapchain_details(struct swapchain_details details) {
	free(details.formats);
	free(details.present_modes);
}

struct swapchain_details query_swapchain(VkPhysicalDevice dev) {
	struct swapchain_details details = {0};
	vkGetPhysicalDeviceSurfaceCapabilitiesKHR(dev, surface, &details.caps);

	uint32_t format_count = 0;
	vkGetPhysicalDeviceSurfaceFormatsKHR(dev, surface, &format_count, NULL);
	if (format_count != 0) {
		details.formats = malloc(sizeof(*details.formats) + sizeof(*details.formats->data) * format_count);
		vkGetPhysicalDeviceSurfaceFormatsKHR(dev, surface, &format_count, details.formats->data);
		details.formats->len = format_count;
	}

	uint32_t present_mode_count = 0;
	vkGetPhysicalDeviceSurfaceFormatsKHR(dev, surface, &present_mode_count, NULL);
	if (present_mode_count != 0) {
		details.present_modes = malloc(sizeof(*details.present_modes) + sizeof(*details.present_modes->data) * format_count);
		vkGetPhysicalDeviceSurfacePresentModesKHR(dev, surface, &present_mode_count, details.present_modes->data);
		details.present_modes->len = present_mode_count;
	}

	return details;
}

VkSurfaceFormatKHR pick_swapchain_format(const struct surface_formats *formats) {
	for (size_t i = 0; i < formats->len; i++)
		if (formats->data[i].format == VK_FORMAT_B8G8R8A8_SRGB
				&& formats->data[i].colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
			return formats->data[i];
	return formats->data[0];
}

VkPresentModeKHR pick_present_mode(const struct present_modes *modes) {
	for (size_t i = 0; i < modes->len; i++)
		if (modes->data[i] == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
			return modes->data[i];

	return VK_PRESENT_MODE_FIFO_KHR;
}

VkExtent2D pick_swap_extent(const VkSurfaceCapabilitiesKHR *caps) {
	if (caps->currentExtent.width != UINT32_MAX)
		return caps->currentExtent;

	int32_t w, h;
	SDL_GetWindowSize(window, &w, &h);

	VkExtent2D actual_extent = {
		.width = w > caps->minImageExtent.width ? w < caps->maxImageExtent.width ? w : caps->maxImageExtent.width : caps->minImageExtent.width,
		.height = h > caps->minImageExtent.height ? h < caps->maxImageExtent.height ? h : caps->maxImageExtent.height : caps->minImageExtent.height,
	};

	return actual_extent;
}

struct queue_indices {
	enum {
		GRAPHICS = (1 << 0),
		PRESENT = (1 << 1)
	} found_queues;

	uint32_t graphics;
	uint32_t present;
};

bool found_queue_indx(struct queue_indices inds) {
	return inds.found_queues == (GRAPHICS | PRESENT);
}

void cleanup_swapchain() {
	for (size_t i = 0; i < framebuffers->len; i++) {
		vkDestroyFramebuffer(gpu, framebuffers->data[i], NULL);
	}
	for (size_t i = 0; i < swapchain_image_views->len; i++) {
		vkDestroyImageView(gpu, swapchain_image_views->data[i], NULL);
	}
	vkDestroySwapchainKHR(gpu, swapchain, NULL);
}

void cleanup() {
	vkDeviceWaitIdle(gpu);
	for (size_t i = 0; i < MAX_FRAMES_INFLIGHT; i++) {
		vkDestroySemaphore(gpu, image_avail[i], NULL);
		vkDestroySemaphore(gpu, render_finished[i], NULL);
		vkDestroyFence(gpu, in_flight_fence[i], NULL);
	}
	cleanup_swapchain();
	vkDestroyCommandPool(gpu, command_pool, NULL);
	vkDestroyPipeline(gpu, graphics_pipeline, NULL);
	vkDestroyPipelineLayout(gpu, pipeline_layout, NULL);
	vkDestroyRenderPass(gpu, render_pass, NULL);
	vkDestroySurfaceKHR(instance, surface, NULL);
	vkDestroyDevice(gpu, NULL);
	vkDestroyInstance(instance, NULL);
	SDL_DestroyWindow(window);
}

static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback( VkDebugUtilsMessageSeverityFlagBitsEXT severity,
		VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *data) {
	fprintf(stderr, "validation layer: %s\n", callback_data->pMessage);
	return VK_FALSE;
}

void create_instance() {
	VkApplicationInfo app_info = {
		.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
		.pApplicationName = "vk",
		.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
		.pEngineName = "void",
		.engineVersion = VK_MAKE_VERSION(1, 0, 0),
		.apiVersion = VK_API_VERSION_1_0
	};

	uint32_t sdl_exts = 0;
	SDL_Vulkan_GetInstanceExtensions(window, &sdl_exts, NULL);

	const char *sdl_exts_names[sdl_exts + 1];
	SDL_Vulkan_GetInstanceExtensions(window, &sdl_exts, sdl_exts_names);

	sdl_exts_names[sdl_exts++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;

	for (size_t i = 0; i < sdl_exts; i++) {
		puts(sdl_exts_names[i]);
	};

	const char *validation_layers[] = { "VK_LAYER_KHRONOS_validation" };

	VkInstanceCreateInfo create_info = {
		.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
		.pApplicationInfo = &app_info,
		.enabledLayerCount = 1,
		.ppEnabledLayerNames = validation_layers,
		.enabledExtensionCount = sdl_exts,
		.ppEnabledExtensionNames = sdl_exts_names,
	};

	VkResult res = vkCreateInstance(&create_info, NULL, &instance);
	if (res != VK_SUCCESS) {
		fputs("failed to create vk instance", stderr);
		exit(-1);
	}

	VkDebugUtilsMessengerCreateInfoEXT debug_create_info = {
		.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
		.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,
		.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,
		.pfnUserCallback = debug_callback
	};

	((PFN_vkCreateDebugUtilsMessengerEXT)
		 vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT"))(instance, &debug_create_info, NULL, &debug_messenger);
}

struct queue_indices find_queue_families(VkPhysicalDevice dev) {
	struct queue_indices queues_ind = {0};

	uint32_t queue_count = 0;
	vkGetPhysicalDeviceQueueFamilyProperties(dev, &queue_count, NULL);

	VkQueueFamilyProperties *queues = calloc(queue_count, sizeof(*queues));
	vkGetPhysicalDeviceQueueFamilyProperties(dev, &queue_count, queues);

	for (size_t i = 0; i < queue_count; i++) {
		if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
			queues_ind.found_queues |= GRAPHICS;
			queues_ind.graphics = i;
		}

		VkBool32 present_support = false;
		vkGetPhysicalDeviceSurfaceSupportKHR(dev, i, surface, &present_support);

		if (present_support) {
			queues_ind.found_queues |= PRESENT;
			queues_ind.present = i;
		}
	}

	free(queues);
	return queues_ind;
}

bool is_device_ok(VkPhysicalDevice dev) {
	uint32_t ext_count;

	vkEnumerateDeviceExtensionProperties(dev, NULL, &ext_count, NULL);

	VkExtensionProperties *props = calloc(ext_count, sizeof(*props));
	vkEnumerateDeviceExtensionProperties(dev, NULL, &ext_count, props);

	bool swapchain = false;
	for (size_t i = 0; i < ext_count; i++) {
		if (strcmp(props[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0) {
			swapchain = true;
			break;
		}
	}

	free(props);

	bool adequate_swapchain = false;
	if (swapchain) {
		struct swapchain_details details = query_swapchain(dev);
		adequate_swapchain = details.present_modes != NULL && details.formats != NULL;
		free_swapchain_details(details);
	}

	return found_queue_indx(find_queue_families(dev)) && swapchain && adequate_swapchain;
}

void pick_physical_dev() {
	uint32_t dev_count = 0;
	vkEnumeratePhysicalDevices(instance, &dev_count, NULL);

	if (dev_count == 0) {
		fputs("no vulkan enabled gpus", stderr);
		exit(-1);
	}

	VkPhysicalDevice *devs = calloc(dev_count, sizeof(*devs));
	vkEnumeratePhysicalDevices(instance, &dev_count, devs);

	for (size_t i = 0; i < dev_count; i++)
		if (is_device_ok(devs[i])) {
			phy_gpu = devs[i];
			break;
		}

	free(devs);

	if (phy_gpu == VK_NULL_HANDLE) {
		fputs("couldn't find appropriate gpu", stderr);
		exit(-1);
	}
}

void create_logical_dev() {
	struct queue_indices inds = find_queue_families(phy_gpu);

	float queue_prio = 1.0f;

	VkDeviceQueueCreateInfo queue_create_info[] = {
		{
			.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
			.queueFamilyIndex = inds.graphics,
			.queueCount = 1,
			.pQueuePriorities = &queue_prio
		},
		{
			.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
			.queueFamilyIndex = inds.present,
			.queueCount = 1,
			.pQueuePriorities = &queue_prio
		},
	};

	VkPhysicalDeviceFeatures dev_features = { 0 };

	const char * const ext = VK_KHR_SWAPCHAIN_EXTENSION_NAME;

	VkDeviceCreateInfo create_info = {
		.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
		.pQueueCreateInfos = queue_create_info,
		.queueCreateInfoCount = 2,
		.pEnabledFeatures = &dev_features,
		.enabledExtensionCount = 1,
		.ppEnabledExtensionNames = &ext,
	};

	VkResult res = vkCreateDevice(phy_gpu, &create_info, NULL, &gpu);
	if (res != VK_SUCCESS) {
		fputs("failed to create logical device", stderr);
		exit(-1);
	}

	vkGetDeviceQueue(gpu, inds.graphics, 0, &gfx_queue);
	vkGetDeviceQueue(gpu, inds.present, 0, &present_queue);
}

void create_swapchain() {
	struct swapchain_details details = query_swapchain(phy_gpu);

	VkSurfaceFormatKHR surface_format = pick_swapchain_format(details.formats);
	VkPresentModeKHR present_mode = pick_present_mode(details.present_modes);
	VkExtent2D extent = pick_swap_extent(&details.caps);

	swapchain_format = surface_format.format;
	swapchain_extent = extent;

	uint32_t image_count = details.caps.minImageCount + 1;
	if (details.caps.maxImageCount > 0 && image_count > details.caps.maxImageCount)
		image_count = details.caps.maxImageCount;

	VkSwapchainCreateInfoKHR create_info = {
		.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
		.surface = surface,
		.minImageCount = image_count,
		.imageFormat = surface_format.format,
		.imageColorSpace = surface_format.colorSpace,
		.imageExtent = extent,
		.imageArrayLayers = 1,
		.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
		.preTransform = details.caps.currentTransform,
		.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
		.presentMode = present_mode,
		.clipped = VK_TRUE,
		.oldSwapchain = VK_NULL_HANDLE,
	};

	struct queue_indices indx = find_queue_families(phy_gpu);
	uint32_t fam_indx[] = { indx.graphics, indx.present };

	if (indx.graphics != indx.present) {
		create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
		create_info.queueFamilyIndexCount = 2;
		create_info.pQueueFamilyIndices = fam_indx;
	} else {
		create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
	}

	VkResult res = vkCreateSwapchainKHR(gpu, &create_info, NULL, &swapchain);
	if (res != VK_SUCCESS) {
		fputs("failed to create swapchain", stderr);
		exit(-1);
	}

	free_swapchain_details(details);

	uint32_t img_count = 0;
	vkGetSwapchainImagesKHR(gpu, swapchain, &img_count, NULL);

	swapchain_images = malloc(sizeof(*swapchain_images) + sizeof(*swapchain_images->data) * img_count);
	swapchain_images->len = img_count;
	vkGetSwapchainImagesKHR(gpu, swapchain, &img_count, swapchain_images->data);

}

void create_image_views() {
	swapchain_image_views = malloc(sizeof(*swapchain_image_views) + sizeof(*swapchain_image_views->data) * swapchain_images->len);
	swapchain_image_views->len = swapchain_images->len;

	for (size_t i = 0; i < swapchain_images->len; i++) {
		VkImageViewCreateInfo create_info = {
			.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
			.image = swapchain_images->data[i],
			.viewType = VK_IMAGE_VIEW_TYPE_2D,
			.format = swapchain_format,
			.components = {
				.r = VK_COMPONENT_SWIZZLE_IDENTITY,
				.g = VK_COMPONENT_SWIZZLE_IDENTITY,
				.b = VK_COMPONENT_SWIZZLE_IDENTITY,
				.a = VK_COMPONENT_SWIZZLE_IDENTITY,
			},
			.subresourceRange = {
				.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
				.baseMipLevel = 0,
				.levelCount = 1,
				.baseArrayLayer = 0,
				.layerCount = 1
			}
		};

		VkResult res = vkCreateImageView(gpu, &create_info, NULL, &swapchain_image_views->data[i]);
		if (res != VK_SUCCESS) {
			fputs("failed to create image view", stderr);
			exit(-1);
		}
	}
}

struct code *readfile(const char *filename) {
	FILE *fp = fopen(filename, "rb");
	if (!fp) {
		fprintf(stderr, "failed to open file %s", filename);
		exit(-1);
	}

	fseek(fp, 0, SEEK_END);
	size_t len = ftell(fp);
	rewind(fp);

	struct code *bytes = malloc(sizeof(*bytes) + sizeof(*bytes->data) * len);
	bytes->len = len;
	fread(bytes->data, sizeof(*bytes->data), len, fp);

	fclose(fp);
	return bytes;
}

VkShaderModule create_shader_module(const struct code *code) {
	VkShaderModuleCreateInfo create_info = {
		.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
		.codeSize = code->len,
		.pCode = (uint32_t *)code->data
	};

	VkShaderModule module;
	VkResult res = vkCreateShaderModule(gpu, &create_info, NULL, &module);
	if (res != VK_SUCCESS) {
		fputs("failed to create shader module.", stderr);
		exit(-1);
	}

	return module;
}

void create_graphics_pipeline() {
	struct code *vert_shader_code = readfile("vert.spv");
	struct code *frag_shader_code = readfile("frag.spv");

	VkShaderModule vert_shader = create_shader_module(vert_shader_code);
	VkShaderModule frag_shader = create_shader_module(frag_shader_code);

	VkPipelineShaderStageCreateInfo vert_shader_info = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
		.stage = VK_SHADER_STAGE_VERTEX_BIT,
		.module = vert_shader,
		.pName = "main"
	};

	VkPipelineShaderStageCreateInfo frag_shader_info = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
		.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
		.module = frag_shader,
		.pName = "main"
	};

	VkPipelineShaderStageCreateInfo shader_stages[] = { vert_shader_info, frag_shader_info };

	VkPipelineVertexInputStateCreateInfo vertex_input_info = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
	};

	VkPipelineInputAssemblyStateCreateInfo input_assembly = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
		.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
		.primitiveRestartEnable = VK_FALSE
	};

	VkViewport viewport = {
		.x = 0.0f,
		.y = 0.0f,
		.width = swapchain_extent.width,
		.height = swapchain_extent.height,
		.minDepth = 0.0f,
		.maxDepth = 1.0f
	};

	VkRect2D scissor = {
		.offset = { 0, 0 },
		.extent = swapchain_extent
	};

	VkDynamicState dyn_states[] = {
		VK_DYNAMIC_STATE_VIEWPORT,
		VK_DYNAMIC_STATE_SCISSOR
	};

	VkPipelineDynamicStateCreateInfo dynamic_state_info = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
		.dynamicStateCount = 2,
		.pDynamicStates = dyn_states
	};

	VkPipelineViewportStateCreateInfo viewport_state = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
		.viewportCount = 1,
		.scissorCount = 1
	};

	VkPipelineRasterizationStateCreateInfo rasterizer = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
		.depthClampEnable = VK_FALSE,
		.rasterizerDiscardEnable = VK_FALSE,
		.polygonMode = VK_POLYGON_MODE_FILL,
		.lineWidth = 1.0f,
		.cullMode = VK_CULL_MODE_BACK_BIT,
		.frontFace = VK_FRONT_FACE_CLOCKWISE,
		.depthBiasEnable = VK_FALSE,
	};

	VkPipelineMultisampleStateCreateInfo multisampling = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
		.sampleShadingEnable = VK_FALSE,
		.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
		.minSampleShading = 1.0f,
	};

	VkPipelineColorBlendAttachmentState color_state = {
		.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
		.blendEnable = VK_FALSE
	};

	VkPipelineColorBlendStateCreateInfo color_blending = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
		.logicOpEnable = VK_FALSE,
		.attachmentCount = 1,
		.pAttachments = &color_state
	};

	VkPipelineLayoutCreateInfo pipeline_layout_create_info = {
		.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
	};

	VkResult res = vkCreatePipelineLayout(gpu, &pipeline_layout_create_info, NULL, &pipeline_layout);
	if (res != VK_SUCCESS) {
		fputs("failed to create pipeline layout", stderr);
		exit(-1);
	}

	VkGraphicsPipelineCreateInfo pipeline_info = {
		.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
		.stageCount = 2,
		.pStages = shader_stages,
		.pVertexInputState = &vertex_input_info,
		.pInputAssemblyState = &input_assembly,
		.pViewportState = &viewport_state,
		.pRasterizationState = &rasterizer,
		.pMultisampleState = &multisampling,
		.pColorBlendState = &color_blending,
		.pDynamicState = &dynamic_state_info,
		.layout = pipeline_layout,
		.renderPass = render_pass,
		.subpass = 0,
		.basePipelineHandle = VK_NULL_HANDLE,
		.basePipelineIndex = -1
	};

	res = vkCreateGraphicsPipelines(gpu, VK_NULL_HANDLE, 1, &pipeline_info, NULL, &graphics_pipeline);
	if (res != VK_SUCCESS) {
		fputs("failed to create graphics pipeline", stderr);
		exit(-1);
	}

	vkDestroyShaderModule(gpu, frag_shader, NULL);
	vkDestroyShaderModule(gpu, vert_shader, NULL);
}

void create_render_pass() {
	VkAttachmentDescription color_attach = {
		.format = swapchain_format,
		.samples = VK_SAMPLE_COUNT_1_BIT,
		.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
		.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
		.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
		.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
		.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
		.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
	};

	VkAttachmentReference color_attach_ref = {
		.attachment = 0,
		.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
	};

	VkSubpassDescription subpass = {
		.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
		.colorAttachmentCount = 1,
		.pColorAttachments = &color_attach_ref
	};

	VkSubpassDependency dep = {
		.srcSubpass = VK_SUBPASS_EXTERNAL,
		.dstSubpass = 0,
		.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
		.srcAccessMask = 0,
		.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
		.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT
	};

	VkRenderPassCreateInfo create_info = {
		.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
		.attachmentCount = 1,
		.pAttachments = &color_attach,
		.subpassCount = 1,
		.pSubpasses = &subpass,
		.dependencyCount = 1,
		.pDependencies = &dep
	};

	VkResult res = vkCreateRenderPass(gpu, &create_info, NULL, &render_pass);
	if (res != VK_SUCCESS) {
		fputs("failed to create render pass", stderr);
		exit(-1);
	}
}

void create_framebuffers() {
	framebuffers = malloc(sizeof(*framebuffers) + sizeof(*framebuffers->data) * swapchain_image_views->len);
	framebuffers->len = swapchain_image_views->len;

	for (size_t i = 0; i < swapchain_image_views->len; i++) {
		VkImageView attachs[] = {
			swapchain_image_views->data[i]
		};

		VkFramebufferCreateInfo framebuffer_info = {
			.sType =VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
			.renderPass = render_pass,
			.attachmentCount = 1,
			.pAttachments = attachs,
			.width = swapchain_extent.width,
			.height = swapchain_extent.height,
			.layers = 1
		};

		VkResult res = vkCreateFramebuffer(gpu, &framebuffer_info, NULL, &framebuffers->data[i]);
		if (res != VK_SUCCESS) {
			fputs("failed to create framebuffer", stderr);
			exit(-1);
		}
	}
}

void create_command_pool() {
	struct queue_indices indx = find_queue_families(phy_gpu);

	VkCommandPoolCreateInfo pool_info = {
		.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
		.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
		.queueFamilyIndex = indx.graphics
	};

	VkResult res = vkCreateCommandPool(gpu, &pool_info, NULL, &command_pool);
	if (res != VK_SUCCESS) {
		fputs("failed to create command pool", stderr);
		exit(-1);
	}
}

void create_command_buffers() {
	VkCommandBufferAllocateInfo alloc_info = {
		.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
		.commandPool = command_pool,
		.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
		.commandBufferCount = MAX_FRAMES_INFLIGHT
	};

	VkResult res = vkAllocateCommandBuffers(gpu, &alloc_info, command_buffers);
	if (res != VK_SUCCESS) {
		fputs("failed to allocate command buffer", stderr);
		exit(-1);
	}
}

void record_command_buffer(VkCommandBuffer buffer, uint32_t image_index) {
	VkCommandBufferBeginInfo begin_info = {
		.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
	};

	VkResult res = vkBeginCommandBuffer(buffer, &begin_info);
	if (res != VK_SUCCESS) {
		fputs("failed to begin command buffer", stderr);
		exit(-1);
	}

	VkClearValue clear_color = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
	VkRenderPassBeginInfo render_pass_info = {
		.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
		.renderPass = render_pass,
		.framebuffer = framebuffers->data[image_index],
		.renderArea = {
			.extent = swapchain_extent,
			.offset = {0, 0}
		},
		.clearValueCount = 1,
		.pClearValues = &clear_color
	};

	vkCmdBeginRenderPass(buffer, &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
	vkCmdBindPipeline(buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics_pipeline);

	VkViewport viewport = {
		.x = 0.0f,
		.y = 0.0f,
		.width = swapchain_extent.width,
		.height = swapchain_extent.height,
		.minDepth = 0.0f,
		.maxDepth = 1.0f,
	};
	vkCmdSetViewport(buffer, 0, 1, &viewport);

	VkRect2D scissor = {
		.offset = {0, 0},
		.extent = swapchain_extent
	};

	vkCmdSetScissor(buffer, 0, 1, &scissor);
	vkCmdDraw(buffer, 3, 1, 0, 0);

	vkCmdEndRenderPass(buffer);

	res = vkEndCommandBuffer(buffer);
	if (res != VK_SUCCESS) {
		fputs("failed to record command buffer", stderr);
		exit(-1);
	}
}

void create_sync_objects() {
	VkSemaphoreCreateInfo semaphore_info = {
		.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO
	};
	VkFenceCreateInfo fence_info = {
		.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
		.flags = VK_FENCE_CREATE_SIGNALED_BIT
	};
	for (size_t i = 0; i < MAX_FRAMES_INFLIGHT; i++)
		if (vkCreateSemaphore(gpu, &semaphore_info, NULL, &image_avail[i]) != VK_SUCCESS
				|| vkCreateSemaphore(gpu, &semaphore_info, NULL, &render_finished[i]) != VK_SUCCESS
				|| vkCreateFence(gpu, &fence_info, NULL, &in_flight_fence[i]) != VK_SUCCESS) {
			fputs("failed to create semaphores and fence", stderr);
			exit(-1);
		}
}

void recreate_swapchain() {
	int32_t width = 0, height = 0;
	SDL_GetWindowSize(window, &width, &height);
	while (width == 0 || height == 0) {
		SDL_Event e;
		SDL_PollEvent(&e);
		SDL_GetWindowSize(window, &width, &height);
	}

	vkDeviceWaitIdle(gpu);

	cleanup_swapchain();

	create_swapchain();
	create_image_views();
	create_framebuffers();
}

void init() {
	SDL_Init(SDL_INIT_VIDEO);
	window = SDL_CreateWindow("vk", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_VULKAN | SDL_WINDOW_RESIZABLE);
	if (!window) {
		fputs("failed to create sdl window", stderr);
		exit(-1);
	}

	uint32_t extension_count = 0;
	vkEnumerateInstanceExtensionProperties(NULL, &extension_count, NULL);

	VkExtensionProperties *exts = calloc(extension_count, sizeof(*exts));
	vkEnumerateInstanceExtensionProperties(NULL, &extension_count, exts);

	puts("available extensions:");
	for (size_t i = 0; i < extension_count; i++) {
		printf("\t%s\n", exts[i].extensionName);
	}

	free(exts);

	create_instance();

	if (SDL_Vulkan_CreateSurface(window, instance, &surface) != SDL_TRUE) {
		fputs("failed to create surface", stderr);
		exit(-1);
	}

	pick_physical_dev();
	create_logical_dev();
	create_swapchain();
	create_image_views();
	create_render_pass();
	create_graphics_pipeline();
	create_framebuffers();
	create_command_pool();
	create_command_buffers();
	create_sync_objects();
}

void draw() {
	vkWaitForFences(gpu, 1, &in_flight_fence[current_frame], VK_TRUE, UINT64_MAX);

	uint32_t image_index;
	VkResult res = vkAcquireNextImageKHR(gpu, swapchain, UINT64_MAX, image_avail[current_frame], VK_NULL_HANDLE, &image_index);
	switch (res) {
		case VK_SUCCESS:
			break;
		case VK_ERROR_OUT_OF_DATE_KHR:
		case VK_SUBOPTIMAL_KHR:
			recreate_swapchain();
			return;
		default:
			fputs("failed to acquire swapchain images", stderr);
			exit(-1);
	}

	vkResetFences(gpu, 1, &in_flight_fence[current_frame]);
	vkResetCommandBuffer(command_buffers[current_frame], 0);
	record_command_buffer(command_buffers[current_frame], image_index);

	VkSemaphore wait_semaphores[] = { image_avail[current_frame] };
	VkSemaphore signal_semaphores[] = { render_finished[current_frame] };
	VkPipelineStageFlags wait_stages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
	VkSubmitInfo submit_info = {
		.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
		.waitSemaphoreCount = 1,
		.pWaitSemaphores = wait_semaphores,
		.pWaitDstStageMask = wait_stages,
		.signalSemaphoreCount = 1,
		.pSignalSemaphores = signal_semaphores,
		.commandBufferCount = 1,
		.pCommandBuffers = &command_buffers[current_frame]
	};

	res = vkQueueSubmit(gfx_queue, 1, &submit_info, in_flight_fence[current_frame]);
	if (res != VK_SUCCESS) {
		fputs("failed to submit draw command buffer", stderr);
		exit(-1);
	}

	VkSwapchainKHR swapchains[] = { swapchain };
	VkPresentInfoKHR present_info = {
		.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
		.waitSemaphoreCount = 1,
		.pWaitSemaphores = signal_semaphores,
		.swapchainCount = 1,
		.pSwapchains = swapchains,
		.pImageIndices = &image_index
	};

	vkQueuePresentKHR(present_queue, &present_info);

	current_frame = (current_frame + 1) % MAX_FRAMES_INFLIGHT;
}

int main() {
	init();

	SDL_Event e;
	while (SDL_PollEvent(&e), e.type != SDL_QUIT) {
		if (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_RESIZED) {
			recreate_swapchain();
		}
		draw();
	}

	cleanup();
	return 0;
}