-#include "vulkan/vk.h"
-extern GLFWwindow win;
+#define GLFW_INCLUDE_VULKAN
+#include <GLFW/glfw3.h>
+
+#include <alloca.h>
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <string>
+#include <vector>
+
+#include <gmath/gmath.h>
+
+#include "allocator.h"
+#include "gfxapi.h"
+#include "image.h"
+#include "vkutil.h"
+#include "vk.h"
+
+/* global variables */
+extern GLFWwindow *win;
+extern int win_w;
+extern int win_h;
+
+static VkCommandBuffer cmd_buf; // command buffer used at zbuffer creation
+//depth buffer
+static VkImage dimg;
+static VkImageView dview;
+//swapchain
+static VkImage *images;
+static VkImageView *iviews;
+static uint32_t num_images;
+
+/* static variables */
+static VkDeviceMemory gpu_mem; // to be replaced when I fix the allocator
+// zbuffer image, view:
+
+VkCommandBuffer *swapchain_cmd_bufs;
+
+/* static functions */
+static void error_callback(int error, const char *descr);
+static void clear(float r, float g, float b);
+static void viewport(int x, int y, int width, int height);
+static void zbuffer(bool enable);
+static void cull_face(Gfx_cull_face cf);
+static void reshape(int width, int height);
+static void swapbuffers();
+static void begin_drawing();
+static void end_drawing();
+
+static bool create_swapchain();
+static bool begin_command_buffer();
+static bool create_swapchain_image_views(VkFormat format);
+static bool create_zbuffer();
+
+static bool create_swapchain_cmd_bufs(VkCommandPool vk_pool);
+static bool record_cmd_clear(float r, float g, float b);
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;
+ }
+
+ //TODO: remove later
+ glfwSetErrorCallback(error_callback);
+
+ /* create device and command pool! */
+ if(!vku_create_device()) {
+ fprintf(stderr, "Failed to initialize vulkan.\n");
+ return false;
+ }
+
+ if(!glfwGetPhysicalDevicePresentationSupport(vkinst, vk_physical, 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;
+ }
+
+ VkResult res = glfwCreateWindowSurface(vkinst, win, 0, &vk_surface);
+ if(res != VK_SUCCESS) {
+ fprintf(stderr, "Failed to create KHR surface: %s\n", vku_get_vulkan_error_str(res));
+ return false;
+ }
+
+ if(!create_swapchain()) {
+ fprintf(stderr, "Failed to create swapchain.\n");
+ return false;
+ }
+
+ cmd_buf = VK_NULL_HANDLE;
+ if(!begin_command_buffer()) {
+ fprintf(stderr, "Failed to start VK_NULL_HANDLE command buffer.\n");
+ return false;
+ }
+
+ if(!create_zbuffer()) {
+ fprintf(stderr, "Failed to create depth buffer.\n");
+ return false;
+ }
+
+ gfx_clear = clear;
+ gfx_viewport = viewport;
+ gfx_zbuffer = zbuffer;
+ gfx_cull_face = cull_face;
+ gfx_reshape = reshape;
+ gfx_swapbuffers = swapbuffers;
+ gfx_begin_drawing = begin_drawing;
+ gfx_end_drawing = end_drawing;
+
+
+/*
+ if(!vku_create_semaphores())
+ return false;
+
+ if(!(vk_swapchain = vku_create_swapchain(vk_surface, win_w, win_h, 2,
+ VK_PRESENT_MODE_IMMEDIATE_KHR, 0))) {
+ fprintf(stderr, "Failed to create swapchain.\n");
+ return false;
+ }
+
+ vkswapchain_images = vku_get_swapchain_images(vk_swapchain, &vknum_swapchain_images);
+ if(!vkswapchain_images) {
+ fprintf(stderr, "Failed to get swapchain images.\n");
+ return false;
+ }
+
+// vkswapchain_views = vku_create_image_views(vkswapchain_images, vknum_swapchain_images);
+// if(!vkswapchain_views) {
+// fprintf(stderr, "Failed to create swapchain image views.\n");
+// delete [] vkswapchain_images;
+// return false;
+// }
+
+ if(!create_swapchain_cmd_bufs(vk_pool)) {
+ return false;
+ }
+
+ if(!record_cmd_clear(1.0, 0.1, 0.1))
+ return false;
+ */
+
+ return true;
+}
+
+static bool create_swapchain()
+{
+ /* surface capabilities */
+ VkSurfaceCapabilitiesKHR scap;
+ if(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vk_physical, vk_surface, &scap) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get physical device surface capabilities\n");
+ return false;
+ }
+
+ /* presentation modes */
+ uint32_t prmode_cnt;
+ if(vkGetPhysicalDeviceSurfacePresentModesKHR(vk_physical, vk_surface, &prmode_cnt, 0) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get physical device surface presentation modes count.\n");
+ return false;
+ }
+
+ if(prmode_cnt == 0) {
+ fprintf(stderr, "Presentation modes not found.\n");
+ return false;
+ }
+
+ VkPresentModeKHR scmode = VK_PRESENT_MODE_FIFO_KHR;
+ VkPresentModeKHR *modes = new VkPresentModeKHR[prmode_cnt];
+
+ if(vkGetPhysicalDeviceSurfacePresentModesKHR(vk_physical, vk_surface, &prmode_cnt, modes) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get physical device presentation modes.\n");
+ return false;
+ }
+
+ for(uint32_t i=0; i<prmode_cnt; i++) {
+ if(modes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
+ scmode = VK_PRESENT_MODE_MAILBOX_KHR;
+ break;
+ }
+ if((scmode != VK_PRESENT_MODE_MAILBOX_KHR) && (modes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) {
+ //fallback
+ scmode = VK_PRESENT_MODE_IMMEDIATE_KHR;
+ }
+ }
+
+ /* swapchain extents */
+ VkExtent2D scextent;
+ if(scap.currentExtent.width == 0xffffffff || scap.currentExtent.height == 0xffffffff) {
+ scextent.width = win_w;
+ scextent.height = win_h;
+ }
+ else {
+ scextent = scap.currentExtent;
+ win_w = scextent.width;
+ win_h = scextent.height;
+ }
+
+ /* number of swapchain images (on intel that's 3: maybe should hardcode it to 2?) */
+ num_images = scap.minImageCount; //+ 1;
+ /* intel doesn't set the maxImageCount */
+ if(scap.maxImageCount > 0 && num_images > scap.maxImageCount)
+ num_images = scap.maxImageCount;
+
+ printf("num_images : %u\n", num_images);
+ assert(num_images > 0);
+
+ /* transform flags */
+ VkSurfaceTransformFlagBitsKHR pre_transf = scap.currentTransform;
+ if(scap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
+ pre_transf = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
+
+ /* find suitable colorspace, format */
+ uint32_t fcount;
+ if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical, vk_surface, &fcount, 0) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get format count for physical device.\n");
+ return false;
+ }
+ if(fcount == 0) {
+ fprintf(stderr, "No color formats were found.\n");
+ return false;
+ }
+
+ VkFormat format;
+ VkColorSpaceKHR colorspace;
+
+ VkSurfaceFormatKHR *formats = new VkSurfaceFormatKHR[fcount];
+ if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical, vk_surface, &fcount, formats) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get surface formats.\n");
+ return false;
+ }
+ if((fcount == 1) && (formats[0].format == VK_FORMAT_UNDEFINED)) {
+ format = VK_FORMAT_B8G8R8_UNORM;
+ } else {
+ format = formats[0].format;
+ }
+ colorspace = formats[0].colorSpace;
+
+ /* creating the swapchain */
+ VkSwapchainCreateInfoKHR sinfo;
+ memset(&sinfo, 0, sizeof sinfo);
+
+ sinfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
+ sinfo.surface = vk_surface;
+ sinfo.minImageCount = num_images;
+ sinfo.imageFormat = format;
+ sinfo.imageColorSpace = colorspace;
+ sinfo.imageExtent = scextent;
+ sinfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
+ sinfo.preTransform = pre_transf;
+ sinfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
+ sinfo.imageArrayLayers = 1;
+ sinfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
+ sinfo.presentMode = scmode;
+ sinfo.oldSwapchain = VK_NULL_HANDLE; //TODO
+ sinfo.clipped = VK_TRUE; //TODO
+
+ if(vkCreateSwapchainKHR(vk_device, &sinfo, 0, &vk_swapchain) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to create swapchain.\n");
+ return false;
+ }
+
+ if(vkGetSwapchainImagesKHR(vk_device, vk_swapchain, &num_images, 0) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get the number of the swapchain images.\n");
+ return false;
+ }
+
+ images = new VkImage[num_images];
+ if(vkGetSwapchainImagesKHR(vk_device, vk_swapchain, &num_images, images) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to get the swapchain images.\n");
+ return false;
+ }
+ assert(images);
+
+ if(!create_swapchain_image_views(format)) {
+ fprintf(stderr, "Failed to create image views for the swapchain images.\n");
+ return false;
+ }
+
+ // create renderpass
+
+
+ return true;
+}
+
+static bool create_swapchain_image_views(VkFormat format)
+{
+ VkImageViewCreateInfo ivinf;
+ memset(&ivinf, 0, sizeof ivinf);
+
+ ivinf.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
+ ivinf.format = format;
+ ivinf.components = {
+ VK_COMPONENT_SWIZZLE_R,
+ VK_COMPONENT_SWIZZLE_G,
+ VK_COMPONENT_SWIZZLE_B,
+ VK_COMPONENT_SWIZZLE_A
+ };
+ ivinf.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
+ ivinf.subresourceRange.levelCount = 1;
+ ivinf.subresourceRange.layerCount = 1;
+ ivinf.viewType = VK_IMAGE_VIEW_TYPE_2D;
+
+ iviews = new VkImageView[num_images];
+ for(uint32_t i=0; i<num_images; i++) {
+ ivinf.image = images[i];
+ if(vkCreateImageView(vk_device, &ivinf, 0, &iviews[i]) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to create view for the swapchain image: %d.\n", i);
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool begin_command_buffer()
+{
+ if(cmd_buf == VK_NULL_HANDLE) {
+ cmd_buf = vku_alloc_cmdbuf(vk_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
+
+ VkCommandBufferInheritanceInfo ciinf;
+ memset(&ciinf, 0, sizeof ciinf);
+ ciinf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
+ ciinf.renderPass = VK_NULL_HANDLE;
+ ciinf.framebuffer = VK_NULL_HANDLE;
+ ciinf.occlusionQueryEnable = VK_FALSE;
+
+ VkCommandBufferBeginInfo cbinf;
+ memset(&cbinf, 0, sizeof cbinf);
+ cbinf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
+ cbinf.pInheritanceInfo = &ciinf;
+
+ if(vkBeginCommandBuffer(cmd_buf, &cbinf) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to begin command buffer.\n");
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool create_zbuffer()
+{
+ VkFormat dformat = VK_FORMAT_D32_SFLOAT_S8_UINT;
+
+ VkImageCreateInfo dinfo;
+ memset(&dinfo, 0, sizeof dinfo);
+
+ dinfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
+ dinfo.imageType = VK_IMAGE_TYPE_2D;
+ dinfo.format = dformat;
+ dinfo.extent = {win_w, win_h, 1};
+ dinfo.mipLevels = 1;
+ dinfo.arrayLayers = 1;
+ dinfo.samples = VK_SAMPLE_COUNT_1_BIT;
+ dinfo.tiling = VK_IMAGE_TILING_OPTIMAL;
+ dinfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
+
+ if(vkCreateImage(vk_device, &dinfo, 0, &dimg) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to create depth buffer image.\n");
+ return false;
+ }
+
+ VkMemoryRequirements dmem_reqs;
+ vkGetImageMemoryRequirements(vk_device, dimg, &dmem_reqs);
+
+ gpu_mem = vk_allocate(dmem_reqs.size);
+
+ if(!gpu_mem)
+ return false;
+
+ vkBindImageMemory(vk_device, dimg, gpu_mem, 0);
+
+ // XXX set image layout
+ if(!vk_image_set_layout(cmd_buf, dimg, VK_IMAGE_ASPECT_DEPTH_BIT,
+ VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
+ (VkAccessFlagBits)0)) {
+ fprintf(stderr, "Failed to set depth buffer layout.\n");
+ return false;
+ }
+
+ VkImageViewCreateInfo div_inf;
+ memset(&div_inf, 0, sizeof div_inf);
+
+ div_inf.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
+ div_inf.image = dimg;
+ div_inf.format = dformat;
+ div_inf.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
+ div_inf.subresourceRange.levelCount = 1;
+ div_inf.subresourceRange.layerCount = 1;
+ div_inf.viewType = VK_IMAGE_VIEW_TYPE_2D;
+
+ if(vkCreateImageView(vk_device, &div_inf, 0, &dview) != VK_SUCCESS) {
+ fprintf(stderr, "Failed to create image view for depth buffer.\n");
+ }
+
return true;
}
void cleanup_vulkan()
{
+ vkFreeCommandBuffers(vk_device, vk_pool, vknum_swapchain_images, swapchain_cmd_bufs);
+ if(win) {
+ glfwDestroyWindow(win);
+ }
+ glfwTerminate();
+
+ //TODOs according to the book:
+ // 1- make sure all threads have been terminated (when I add threads)
+ vku_cleanup();
+}
+
+static void error_callback(int error, const char *description)
+{
+ fprintf(stderr, "GLFW error %d: %s.\n", error, description);
+}
+
+static void reshape(int width, int height)
+{
+ VkSwapchainKHR sc;
+ if(!(sc = vku_create_swapchain(vk_surface, width, height, 2, VK_PRESENT_MODE_FIFO_KHR,
+ vk_swapchain))) {
+ fprintf(stderr, "Failed to create %dx%d double-buffered swapchain\n", width, height);
+ return;
+ }
+ vk_swapchain = sc;
+
+ delete [] vkswapchain_images;
+ vkswapchain_images = vku_get_swapchain_images(sc, 0);
+ vk_curr_swapchain_image = vku_get_next_image(vk_swapchain);
+}
+
+static void clear(float r, float g, float b)
+{
+}
+
+static void viewport(int x, int y, int width, int height)
+{
+}
+
+static void zbuffer(bool enable)
+{
+}
+
+static void cull_face(Gfx_cull_face cf)
+{
+}
+
+static void swapbuffers()
+{
}
-GLFWwindow *create_vulkan_window()
+static void begin_drawing()
{
- return 0;
+ // if((vk_curr_swapchain_image = vku_get_next_image(vk_swapchain)) == -1) {
+ // fprintf(stderr, "Failed to get swapchain image. Exiting.\n");
+ // exit(1);
+ // }
+}
+
+static void end_drawing()
+{
+ /* submit queue */
+
+ // VkSubmitInfo sinf;
+ // memset(&sinf, 0, sizeof sinf);
+ // sinf.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
+ // sinf.waitSemaphoreCount = 1;
+ // sinf.pWaitSemaphores = &vk_img_avail_sema;
+ // sinf.signalSemaphoreCount = 1;
+ // sinf.pSignalSemaphores = &vk_rend_done_sema;
+
+ // // the queue should wait on the semaphore
+
+ // VkPipelineStageFlags wait_flags = VK_PIPELINE_STAGE_TRANSFER_BIT;
+ // sinf.pWaitDstStageMask = &wait_flags;
+ // sinf.commandBufferCount = 1;
+ // sinf.pCommandBuffers = &swapchain_cmd_bufs[vk_curr_swapchain_image];
+
+ // if(vkQueueSubmit(vk_queue, 1, &sinf, VK_NULL_HANDLE) != VK_SUCCESS) {
+ // fprintf(stderr, "Failed to submit drawing command buffer\n");
+ // exit(1);
+ // }
+
+ // /* present drawn image */
+ // VkPresentInfoKHR pinf;
+ // memset(&pinf, 0, sizeof pinf);
+ // pinf.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
+ // pinf.waitSemaphoreCount = 1;
+ // pinf.pWaitSemaphores = &vk_rend_done_sema;
+ // pinf.swapchainCount = 1;
+ // pinf.pSwapchains = &vk_swapchain;
+ // pinf.pImageIndices = (uint32_t *)&vk_curr_swapchain_image;
+
+ // if(vkQueuePresentKHR(vk_queue, &pinf) != VK_SUCCESS) {
+ // fprintf(stderr, "Failed to submit presentation command buffer.\n");
+ // exit(1);
+ // }
}
-void clbk_clear_vk()
+static bool record_cmd_clear(float r, float g, float b)
{
-}
\ No newline at end of file
+// VkCommandBufferBeginInfo binf;
+// binf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
+// binf.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
+
+// /* this function must be called outside a renderpass instance */
+// const VkClearColorValue pcolor[4] = {r, g, b, 1.0};
+
+// VkImageSubresourceRange range;
+// memset(&range, 0, sizeof range);
+// range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
+// range.baseMipLevel = 0;
+// range.baseArrayLayer = 0;
+// range.layerCount = 1;
+
+// for(int i=0; i<vknum_swapchain_images; i++) {
+// /* layout for clearing */
+// VkImageMemoryBarrier cb;
+// memset(&cb, 0, sizeof cb);
+// cb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
+// cb.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
+// cb.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
+// cb.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
+// cb.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+// cb.srcQueueFamilyIndex = vkqfamily;
+// cb.dstQueueFamilyIndex = vkqfamily;
+// cb.image = vkswapchain_images[i];
+// cb.subresourceRange = range;
+
+// /* layout for presenting */
+// VkImageMemoryBarrier pb;
+// memset(&pb, 0, sizeof pb);
+// pb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
+// pb.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
+// pb.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
+// pb.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
+// pb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
+// pb.srcQueueFamilyIndex = vkqfamily;
+// pb.dstQueueFamilyIndex = vkqfamily;
+// pb.image = vkswapchain_images[i];
+// pb.subresourceRange = range;
+
+// vkBeginCommandBuffer(swapchain_cmd_bufs[i], &binf);
+// vkCmdPipelineBarrier(swapchain_cmd_bufs[i], VK_PIPELINE_STAGE_TRANSFER_BIT,
+// VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, 0, 0, 0, 1, &pb);
+
+// vkCmdClearColorImage(swapchain_cmd_bufs[i], vkswapchain_images[vk_curr_swapchain_image], VK_IMAGE_LAYOUT_GENERAL,
+// pcolor, 1, &range);
+
+// vkCmdPipelineBarrier(swapchain_cmd_bufs[i], VK_PIPELINE_STAGE_TRANSFER_BIT,
+// VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, 0, 0, 0, 1, &cb);
+
+// if(vkEndCommandBuffer(swapchain_cmd_bufs[i]) != VK_SUCCESS) {
+// fprintf(stderr, "Failed to record command buffer.\n");
+// return false;
+// }
+// }
+// return true;
+// }
+
+// static bool create_swapchain_cmd_bufs(VkCommandPool cpool)
+// {
+// swapchain_cmd_bufs = new VkCommandBuffer[vknum_swapchain_images];
+
+// VkCommandBufferAllocateInfo ainf;
+// memset(&ainf, 0, sizeof ainf);
+
+// ainf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
+// ainf.commandPool = cpool;
+// ainf.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
+// ainf.commandBufferCount = (uint32_t)vknum_swapchain_images;
+
+// if(vkAllocateCommandBuffers(vk_device, &ainf, swapchain_cmd_bufs) != VK_SUCCESS) {
+// fprintf(stderr, "Failed to allocate the swapchain command buffers.\n");
+// return false;
+// }
+
+ return true;
+}