tmp to switch computer: there are logical errors in main, needs fixing
[vkrt] / src / main.cc
index af4277c..ea70715 100644 (file)
@@ -2,14 +2,29 @@
 
 #define GLFW_INCLUDE_VULKAN
 #include <GLFW/glfw3.h>
+
+#include <assert.h>
 #include <stdlib.h>
 #include <string.h>
 
+#include <vector>
+
+#include <gmath/gmath.h>
+
+/* extern "C": vulkan framework */
 #include "vk.h"
 #include "util.h"
 
+/* C++ */
+#include "camera.h"
+
+/* defines */
 
+#define FENCE_TIMEOUT 100000000000
+
+/**************************/
 /* static glfw callbacks */
+/**************************/
 
 static void
 clb_key(GLFWwindow *win, int key, int scancode, int action, int mods);
@@ -17,38 +32,75 @@ clb_key(GLFWwindow *win, int key, int scancode, int action, int mods);
 static void
 clb_reshape(GLFWwindow *win, int width, int height);
 
+static void
+clb_motion(GLFWwindow *win, double x, double y);
+
+static void
+clb_mouse(GLFWwindow *win, int button, int action, int mods);
+
+/**************************/
 /* static functions */
+/**************************/
+
+/* init, cleanup, display */
 
 static bool
-init(void);
+init();
 
 static void
-cleanup(void);
+cleanup();
 
 static void
-display(void);
+display();
 
-/* static variables */
+/* vulkan, glfw */
+
+static bool
+vk_init();
+
+static void
+vk_cleanup();
+
+/***************************/
+/* static/global variables */
+/***************************/
 
 static GLFWwindow *win;
-static bool redraw_pending;
+/* static bool redraw_pending; */
+static bool move_camera;
 
-static bool vk_enable_layers = true;
+/* camera */
+static float cam_phi = 25;
+static float cam_theta = 0;
+static float cam_dist = 16;
+static Vec3 cam_pos;
 
+static OrbitCamera *camera;
+
+static float aspect;
+static Mat4 mproj;
+
+/* win etc */
 static int win_w = 800;
 static int win_h = 600;
 
+/* vulkan */
+static bool vk_enable_layers = true;
 static struct vk_ctx vk_core;
 static VkSurfaceKHR vk_surf;
-static struct vk_renderer vk_rnd;
 static struct vk_swapchain vk_chain;
+static uint32_t vk_chain_idx;
 static struct vk_semaphores vk_sema;
+
+/* for the moment: one cmd buffer per swapchain image */
+static std::vector<VkCommandBuffer>vk_cmd_buffers;
+static std::vector<VkFence>vk_wait_fences;
+
+/* FIXME make them part of each object's functions/params */
+static struct vk_renderer vk_rnd;
 static struct vk_attachment vk_depth_att;
 static float vk_fb_color[4] = { 0.0, 0.0, 0.5, 1.0 };
 
-/* make array later if many cmd buffers */
-static VkCommandBuffer vk_cmd_buf;
-
 /* empty for as long as we hardcode the vertices in the vertex shader */
 static struct vk_vertex_info vk_vert_info;
 
@@ -56,25 +108,25 @@ int main(int argc, char** argv)
 {
     atexit(cleanup);
 
-    if (!init()) {
+    if (!glfwInit()) {
+        fprintf(stderr, "Failed to initialize GLFW.\n");
         return 1;
     }
 
-    /* reshape window once just in case */
+    if (!init()) {
+        return 1;
+    }
 
+#if 0
     glfwGetWindowSize(win, &win_w, &win_h);
     clb_reshape(win, win_w, win_h);
+#endif
 
-    /* event loop */
-    redraw_pending = true;
-
-    while(!glfwWindowShouldClose(win)) {
-        glfwWaitEvents();
-        if (redraw_pending) {
-            redraw_pending = false;
-            display();
-        }
-    }
+       while(!glfwWindowShouldClose(win)) {
+               glfwPollEvents();
+               display();
+       }
+    vkDeviceWaitIdle(vk_core.dev);
 
     return 0;
 }
@@ -82,19 +134,8 @@ int main(int argc, char** argv)
 /* static functions */
 
 static bool
-init(void)
+vk_init()
 {
-    char *vsdr = 0;
-    char *fsdr = 0;
-    int vsz, fsz;
-
-    /* initialize GLFW */
-
-    if (!glfwInit()) {
-        fprintf(stderr, "Failed to initialize GLFW.\n");
-        return false;
-    }
-
     if (glfwVulkanSupported() != GLFW_TRUE) {
         fprintf(stderr, "Vulkan is not supported on this device.\n");
         return false;
@@ -128,6 +169,11 @@ init(void)
         return false;
     }
 
+    /* load shaders */
+    int vsz, fsz;
+    char *vsdr = sdr_load("data/main.vert.spv", &vsz);
+    char *fsdr = sdr_load("data/main.frag.spv", &fsz);
+
     /* create semaphores */
     if (!vk_create_semaphores(&vk_core, false, &vk_sema)) {
         fprintf(stderr, "No semaphores were created.\n");
@@ -145,9 +191,7 @@ init(void)
         goto fail;
     }
 
-    /* create shaders */
-    vsdr = sdr_load("data/main.vert.spv", &vsz);
-    fsdr = sdr_load("data/main.frag.spv", &fsz);
+    /* FIXME: this part is going to be part of each object's functions */
 
     /* create depth attachment (for the moment we are going to use this
      * for all images */
@@ -178,53 +222,101 @@ init(void)
         goto fail;
     }
 
-    /* create cmd buffer */
-    if ((vk_cmd_buf = vk_create_cmd_buffer(&vk_core)) == VK_NULL_HANDLE) {
-        fprintf(stderr, "Failed to create command buffer.\n");
-        goto fail;
-    }
+    /* create cmd buffers */
+    for (size_t i = 0; i < vk_chain.num_atts; i++) {
+        VkCommandBuffer cmd_buf;
+        VkFence fence;
+        if(!(vk_create_fence(&vk_core, &fence))) {
+            fprintf(stderr, "Failed to create fence: %d.\n", (int)i);
+            goto fail;
+        }
+        vk_wait_fences.push_back(fence);
 
-    /* record cmd buffer */
-    if (!vk_record_cmd_buffer(&vk_core, vk_cmd_buf,
-                              &vk_rnd, 0,
-                              4, vk_fb_color,
-                              vk_chain.num_atts + 1, 0,
-                              0, 0, win_w, win_h)) {
-        fprintf(stderr, "Failed to record command buffer.\n");
-        goto fail;
+        if (!(cmd_buf = vk_create_cmd_buffer(&vk_core))) {
+            fprintf(stderr, "Failed to create command buffer: %d.\n", (int)i);
+            goto fail;
+        }
+
+        /* record cmd buffer FIXME:
+         * part of each objects draw? loop for each
+         * renderer */
+        if (!vk_record_cmd_buffer(&vk_core, cmd_buf,
+                                  &vk_rnd, 0,
+                                  4, vk_fb_color,
+                                  vk_chain.num_atts + 1, 0,
+                                  0, 0, win_w, win_h)) {
+            fprintf(stderr, "Failed to record command buffer.\n");
+            goto fail;
+        }
+
+        vk_cmd_buffers.push_back(cmd_buf);
     }
 
+    vkResetFences(vk_core.dev, vk_wait_fences.size(), vk_wait_fences.data());
+
     free(vsdr);
     free(fsdr);
 
     /* set GLFW callbacks */
 
-    /* glfwSetWindowSizeCallback(win, clb_reshape); */
+    glfwSetWindowSizeCallback(win, clb_reshape);
 
-    /*
     glfwSetCursorPosCallback(win, clb_motion);
     glfwSetMouseButtonCallback(win, clb_mouse);
-    */
 
     return true;
 
 fail:
+    for (size_t i = 0; i < vk_wait_fences.size(); i++) {
+        vk_destroy_fences(&vk_core, vk_wait_fences.size(), vk_wait_fences.data());
+    }
+    vk_wait_fences.clear();
+
+    for (size_t i = 0; i < vk_cmd_buffers.size(); i++) {
+        vk_destroy_cmd_buffers(&vk_core, vk_cmd_buffers.size(), vk_cmd_buffers.data());
+    }
+    vk_cmd_buffers.clear();
+
+    if (vk_depth_att.obj.img != VK_NULL_HANDLE) {
+        vk_destroy_image(&vk_core, &vk_depth_att.obj);
+    }
+
     free(vsdr);
     free(fsdr);
 
     return false;
 }
 
+static bool
+init()
+{
+    if (!vk_init()) {
+        fprintf(stderr, "Failed to initialize Vulkan structs.\n");
+        return false;
+    }
+
+    camera = new OrbitCamera;
+    return true;
+}
+
+static void
+cleanup()
+{
+    delete camera;
+
+    vk_cleanup();
+}
+
+static int count;
 static void
-display(void)
+display()
 {
-    uint32_t img_idx;
+    /* each object should have a command buffer renderpass etc? */
     VkSubmitInfo sinfo;
     VkPipelineStageFlags wait_stages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
-       VkPresentInfoKHR pinfo;
 
     vkAcquireNextImageKHR(vk_core.dev, vk_chain.swapchain,
-                          UINT64_MAX, vk_sema.frame_ready, 0, &img_idx);
+                          UINT64_MAX, vk_sema.frame_ready, 0, &vk_chain_idx);
 
     memset(&sinfo, 0, sizeof sinfo);
     sinfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
@@ -232,70 +324,142 @@ display(void)
     sinfo.pWaitSemaphores = &vk_sema.frame_ready;
     sinfo.pWaitDstStageMask = &wait_stages;
     sinfo.commandBufferCount = 1;
-    sinfo.pCommandBuffers = &vk_cmd_buf;
+    sinfo.pCommandBuffers = &vk_cmd_buffers[vk_chain_idx];
     sinfo.signalSemaphoreCount = 1;
        sinfo.pSignalSemaphores = &vk_sema.frame_done;
 
-    if (vkQueueSubmit(vk_core.queue, 1, &sinfo, 0) != 0) {
+    if (vkQueueSubmit(vk_core.queue, 1, &sinfo, vk_wait_fences[vk_chain_idx]) != 0) {
         fprintf(stderr, "Failed to submit draw commands.\n");
         abort();
     }
 
+    if (vkQueueWaitIdle(vk_core.queue) != VK_SUCCESS) {
+        fprintf(stderr, "Failed to wait idle.\n");
+        abort();
+    }
+
+    if (vkWaitForFences(vk_core.dev, 1, &vk_wait_fences[vk_chain_idx],
+                        VK_TRUE, FENCE_TIMEOUT) != VK_SUCCESS) {
+        fprintf(stderr, "Waiting for fence: %u failed.\n", vk_chain_idx);
+        abort();
+    }
+
+#if 0
     memset(&pinfo, 0, sizeof pinfo);
     pinfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
     pinfo.waitSemaphoreCount = 1;
     pinfo.pWaitSemaphores = &vk_sema.frame_done;
     pinfo.swapchainCount = 1;
     pinfo.pSwapchains = &vk_chain.swapchain;
-    pinfo.pImageIndices = &img_idx;
+    pinfo.pImageIndices = &vk_chain_idx;
+#endif
 
-    vkQueuePresentKHR(vk_core.queue, &pinfo);
+    if (!vk_queue_present(&vk_chain, vk_core.queue, vk_chain_idx, vk_sema.frame_done)) {
+        abort();
+    }
+    vkResetFences(vk_core.dev, 1, &vk_wait_fences[vk_chain_idx]);
+
+    printf("display %d\n", count++);
 }
 
 static void
-cleanup(void)
+vk_cleanup()
 {
     vkQueueWaitIdle(vk_core.queue);
 
-    if (vk_cmd_buf != VK_NULL_HANDLE) {
-        vkResetCommandBuffer(vk_cmd_buf, VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
-    }
-
     vk_destroy_image(&vk_core, &vk_depth_att.obj);
-    vk_destroy_semaphores(&vk_core, &vk_sema);
     vk_destroy_renderer(&vk_core, &vk_rnd);
+    vk_destroy_semaphores(&vk_core, &vk_sema);
+
+    glfwDestroyWindow(win);
 
     if (vk_chain.swapchain) {
         vk_destroy_swapchain(&vk_core, &vk_chain);
         vkDestroySurfaceKHR(vk_core.inst, vk_surf, 0);
     }
 
-    glfwDestroyWindow(win);
-
-    if (!vk_enable_layers)
-        vkFreeCommandBuffers(vk_core.dev, vk_core.cmd_pool, 1, &vk_cmd_buf);
-
-    vk_cleanup_ctx(&vk_core, vk_enable_layers);
+    if (vk_enable_layers)
+        return;
 
+    vk_destroy_cmd_buffers(&vk_core, vk_cmd_buffers.size(), vk_cmd_buffers.data());
     glfwTerminate();
+
+    vk_cleanup_ctx(&vk_core);
 }
 
 /* glfw callbacks */
 
 static void
+clb_reshape(GLFWwindow *win,
+            int width,
+            int height)
+{
+    aspect = (float)width / (float)height;
+    mproj = calc_projection_matrix(45, aspect, 0.5, 1000.0f);
+
+    /* FIXME near and far clipping planes */
+    vk_set_viewport(&vk_core, vk_cmd_buffers[vk_chain_idx],
+                    0, 0, win_w, win_h, 0.0f, 1.0f);
+    win_w = width;
+    win_h = height;
+}
+
+static void
 clb_key(GLFWwindow *win, int key, int scancode,
         int action, int mods)
 {
+    if (action == GLFW_REPEAT) return;
+
     if (action == GLFW_PRESS) {
         switch(key) {
         case GLFW_KEY_ESCAPE:
             glfwSetWindowShouldClose(win, GLFW_TRUE);
-            return;
+            exit(0);
+        case ' ':
+            move_camera = !move_camera;
+            break;
+        default:
+            break;
         }
     }
 }
 
+static double prev_x, prev_y;
+static bool button[8];
+
+static void
+clb_motion(GLFWwindow *win,
+           double x,
+           double y)
+{
+       double dx = x - prev_x;
+       double dy = y - prev_y;
+
+       prev_x = x;
+       prev_y = y;
+
+       if(button[0]) {
+               cam_theta += dx * 0.5;
+               cam_phi += dy * 0.5;
+
+               if(cam_phi < 0)
+                       cam_phi = 0;
+               if(cam_phi > 90)
+                       cam_phi = 90;
+       }
+
+       if(button[1]) {
+               cam_dist += dy * 0.1;
+               if(cam_dist < 0.0) {
+                       cam_dist = 0.0;
+               }
+       }
+}
+
 static void
-clb_reshape(GLFWwindow *win, int width, int height)
+clb_mouse(GLFWwindow *win,
+          int button,
+          int action,
+          int mods)
 {
 }