added a vulkan util (vkutil.h/.cc)
[demo] / src / vulkan / vk.cc
index a49fa5c..871824f 100644 (file)
@@ -1,16 +1,91 @@
-#include "vulkan/vk.h"
-extern GLFWwindow win;
+#define GLFW_INCLUDE_VULKAN
+#include <GLFW/glfw3.h>
+
+#include <alloca.h>
+#include <stdio.h>
+#include <string.h>
+#include <string>
+#include <vector>
+
+#include "gfxapi.h"
+#include "vkutil.h"
+
+/* global variables */
+extern GLFWwindow *win;
+extern int win_w;
+extern int win_h;
+
+/* static functions */
+static void error_callback(int error, const char *descr);
+static void reshape(int width, int height);
 
 bool init_vulkan()
 {
+       if(!glfwInit()) {
+               fprintf(stderr, "Failed to initialize GLFW.\n");
+               return false;
+       }
+
+       if(!glfwVulkanSupported()) {
+               fprintf(stderr, "No Vulkan support on the device.\n");
+               return false;
+       }
+
+       glfwSetErrorCallback(error_callback);
+
+       if(!vku_create_device()) {
+               fprintf(stderr, "Failed to initialize vulkan.\n");
+               return false;
+       }
+
+       if(!glfwGetPhysicalDevicePresentationSupport(vkinst, vkpdev, vkqfamily)) {
+               fprintf(stderr, "Presentation support not found.\n");
+               return false;
+       }
+
+       glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
+       if(!(win = glfwCreateWindow(win_w, win_h, "vkcow", 0, 0))) {
+               fprintf(stderr, "Failed to create window.\n");
+               return false;
+       }
+
+       if(VkResult err = glfwCreateWindowSurface(vkinst, win, 0, &vksurface)) {
+               fprintf(stderr, "Failed to create KHR surface: %s\n", vku_get_vulkan_error_str(err));
+               return false;
+       }
+
+       gfx_reshape = reshape;
+
        return true;
 }
 
 void cleanup_vulkan()
 {
+       //TODOs according to the book:
+       // 1- make sure all threads have been terminated (when I add threads)
+
+       // 2- destroy objects in *reverse* order
+       vkDestroySurfaceKHR(vkinst, vksurface, 0);
+
+       vku_cleanup();
 }
 
-GLFWwindow *create_vulkan_window()
+static void error_callback(int error, const char *description)
 {
-       return 0;
+       fprintf(stderr, "GLFW error %d: %s.\n", error, description);
+}
+
+static void reshape(int width, int height)
+{
+       VkSwapchainKHR sc;
+       if(!(sc = vku_create_swapchain(vksurface, width, height, 2, VK_PRESENT_MODE_FIFO_KHR,
+                                      vkswapchain))) {
+               fprintf(stderr, "Failed to create %dx%d double-buffered swapchain\n", width, height);
+               return;
+       }
+       vkswapchain = sc;
+
+       free(vkswapchain_images);
+       vkswapchain_images = vku_get_swapchain_images(sc, 0);
+       vknext_swapchain_image = vku_get_next_image(vkswapchain);
 }
\ No newline at end of file