871824fef12a14cc084f1fa04ab805c21f27c79e
[demo] / src / vulkan / vk.cc
1 #define GLFW_INCLUDE_VULKAN
2 #include <GLFW/glfw3.h>
3
4 #include <alloca.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <string>
8 #include <vector>
9
10 #include "gfxapi.h"
11 #include "vkutil.h"
12
13 /* global variables */
14 extern GLFWwindow *win;
15 extern int win_w;
16 extern int win_h;
17
18 /* static functions */
19 static void error_callback(int error, const char *descr);
20 static void reshape(int width, int height);
21
22 bool init_vulkan()
23 {
24         if(!glfwInit()) {
25                 fprintf(stderr, "Failed to initialize GLFW.\n");
26                 return false;
27         }
28
29         if(!glfwVulkanSupported()) {
30                 fprintf(stderr, "No Vulkan support on the device.\n");
31                 return false;
32         }
33
34         glfwSetErrorCallback(error_callback);
35
36         if(!vku_create_device()) {
37                 fprintf(stderr, "Failed to initialize vulkan.\n");
38                 return false;
39         }
40
41         if(!glfwGetPhysicalDevicePresentationSupport(vkinst, vkpdev, vkqfamily)) {
42                 fprintf(stderr, "Presentation support not found.\n");
43                 return false;
44         }
45
46         glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
47         if(!(win = glfwCreateWindow(win_w, win_h, "vkcow", 0, 0))) {
48                 fprintf(stderr, "Failed to create window.\n");
49                 return false;
50         }
51
52         if(VkResult err = glfwCreateWindowSurface(vkinst, win, 0, &vksurface)) {
53                 fprintf(stderr, "Failed to create KHR surface: %s\n", vku_get_vulkan_error_str(err));
54                 return false;
55         }
56
57         gfx_reshape = reshape;
58
59         return true;
60 }
61
62 void cleanup_vulkan()
63 {
64         //TODOs according to the book:
65         // 1- make sure all threads have been terminated (when I add threads)
66
67         // 2- destroy objects in *reverse* order
68         vkDestroySurfaceKHR(vkinst, vksurface, 0);
69
70         vku_cleanup();
71 }
72
73 static void error_callback(int error, const char *description)
74 {
75         fprintf(stderr, "GLFW error %d: %s.\n", error, description);
76 }
77
78 static void reshape(int width, int height)
79 {
80         VkSwapchainKHR sc;
81         if(!(sc = vku_create_swapchain(vksurface, width, height, 2, VK_PRESENT_MODE_FIFO_KHR,
82                                        vkswapchain))) {
83                 fprintf(stderr, "Failed to create %dx%d double-buffered swapchain\n", width, height);
84                 return;
85         }
86         vkswapchain = sc;
87
88         free(vkswapchain_images);
89         vkswapchain_images = vku_get_swapchain_images(sc, 0);
90         vknext_swapchain_image = vku_get_next_image(vkswapchain);
91 }