Advertisement
Guest User

Vulkan Timer Queries

a guest
May 19th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 108.77 KB | None | 0 0
  1. /*
  2.  * Copyright (c) 2015-2016 The Khronos Group Inc.
  3.  * Copyright (c) 2015-2016 Valve Corporation
  4.  * Copyright (c) 2015-2016 LunarG, Inc.
  5.  *
  6.  * Licensed under the Apache License, Version 2.0 (the "License");
  7.  * you may not use this file except in compliance with the License.
  8.  * You may obtain a copy of the License at
  9.  *
  10.  *     http://www.apache.org/licenses/LICENSE-2.0
  11.  *
  12.  * Unless required by applicable law or agreed to in writing, software
  13.  * distributed under the License is distributed on an "AS IS" BASIS,
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15.  * See the License for the specific language governing permissions and
  16.  * limitations under the License.
  17.  *
  18.  * Author: Chia-I Wu <olv@lunarg.com>
  19.  * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
  20.  * Author: Ian Elliott <ian@LunarG.com>
  21.  * Author: Jon Ashburn <jon@lunarg.com>
  22.  */
  23.  
  24. #define _GNU_SOURCE
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdbool.h>
  29. #include <assert.h>
  30. #include <signal.h>
  31. #ifdef __linux__
  32. #include <X11/Xutil.h>
  33. #endif
  34.  
  35. #ifdef _WIN32
  36. #pragma comment(linker, "/subsystem:windows")
  37. #define APP_NAME_STR_LEN 80
  38. #endif // _WIN32
  39.  
  40. #include <vulkan/vulkan.h>
  41.  
  42. #include <vulkan/vk_sdk_platform.h>
  43. #include "linmath.h"
  44.  
  45. #define DEMO_TEXTURE_COUNT 1
  46. #define APP_SHORT_NAME "cube"
  47. #define APP_LONG_NAME "The Vulkan Cube Demo Program"
  48.  
  49. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
  50.  
  51. #if defined(NDEBUG) && defined(__GNUC__)
  52. #define U_ASSERT_ONLY __attribute__((unused))
  53. #else
  54. #define U_ASSERT_ONLY
  55. #endif
  56.  
  57. #ifdef _WIN32
  58. #define ERR_EXIT(err_msg, err_class)                                           \
  59.     do {                                                                       \
  60.         MessageBox(NULL, err_msg, err_class, MB_OK);                           \
  61.         exit(1);                                                               \
  62.     } while (0)
  63.  
  64. #else // _WIN32
  65.  
  66. #define ERR_EXIT(err_msg, err_class)                                           \
  67.     do {                                                                       \
  68.         printf(err_msg);                                                       \
  69.         fflush(stdout);                                                        \
  70.         exit(1);                                                               \
  71.     } while (0)
  72. #endif // _WIN32
  73.  
  74. #define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                               \
  75.     {                                                                          \
  76.         demo->fp##entrypoint =                                                 \
  77.             (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
  78.         if (demo->fp##entrypoint == NULL) {                                    \
  79.             ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint,    \
  80.                      "vkGetInstanceProcAddr Failure");                         \
  81.         }                                                                      \
  82.     }
  83.  
  84. static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
  85.  
  86. #define GET_DEVICE_PROC_ADDR(dev, entrypoint)                                  \
  87.     {                                                                          \
  88.         if (!g_gdpa)                                                           \
  89.             g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(           \
  90.                 demo->inst, "vkGetDeviceProcAddr");                            \
  91.         demo->fp##entrypoint =                                                 \
  92.             (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint);                 \
  93.         if (demo->fp##entrypoint == NULL) {                                    \
  94.             ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint,      \
  95.                      "vkGetDeviceProcAddr Failure");                           \
  96.         }                                                                      \
  97.     }
  98.  
  99. /*
  100.  * structure to track all objects related to a texture.
  101.  */
  102. struct texture_object {
  103.     VkSampler sampler;
  104.  
  105.     VkImage image;
  106.     VkImageLayout imageLayout;
  107.  
  108.     VkMemoryAllocateInfo mem_alloc;
  109.     VkDeviceMemory mem;
  110.     VkImageView view;
  111.     int32_t tex_width, tex_height;
  112. };
  113.  
  114. static char *tex_files[] = {"lunarg.ppm"};
  115.  
  116. static int validation_error = 0;
  117.  
  118. struct vkcube_vs_uniform {
  119.     // Must start with MVP
  120.     float mvp[4][4];
  121.     float position[12 * 3][4];
  122.     float color[12 * 3][4];
  123. };
  124.  
  125. struct vktexcube_vs_uniform {
  126.     // Must start with MVP
  127.     float mvp[4][4];
  128.     float position[12 * 3][4];
  129.     float attr[12 * 3][4];
  130. };
  131.  
  132. //--------------------------------------------------------------------------------------
  133. // Mesh and VertexFormat Data
  134. //--------------------------------------------------------------------------------------
  135. // clang-format off
  136. struct Vertex
  137. {
  138.     float     posX, posY, posZ, posW;    // Position data
  139.     float     r, g, b, a;                // Color
  140. };
  141.  
  142. struct VertexPosTex
  143. {
  144.     float     posX, posY, posZ, posW;    // Position data
  145.     float     u, v, s, t;                // Texcoord
  146. };
  147.  
  148. #define XYZ1(_x_, _y_, _z_)         (_x_), (_y_), (_z_), 1.f
  149. #define UV(_u_, _v_)                (_u_), (_v_), 0.f, 1.f
  150.  
  151. static const float g_vertex_buffer_data[] = {
  152.     -1.0f,-1.0f,-1.0f,  // -X side
  153.     -1.0f,-1.0f, 1.0f,
  154.     -1.0f, 1.0f, 1.0f,
  155.     -1.0f, 1.0f, 1.0f,
  156.     -1.0f, 1.0f,-1.0f,
  157.     -1.0f,-1.0f,-1.0f,
  158.  
  159.     -1.0f,-1.0f,-1.0f,  // -Z side
  160.      1.0f, 1.0f,-1.0f,
  161.      1.0f,-1.0f,-1.0f,
  162.     -1.0f,-1.0f,-1.0f,
  163.     -1.0f, 1.0f,-1.0f,
  164.      1.0f, 1.0f,-1.0f,
  165.  
  166.     -1.0f,-1.0f,-1.0f,  // -Y side
  167.      1.0f,-1.0f,-1.0f,
  168.      1.0f,-1.0f, 1.0f,
  169.     -1.0f,-1.0f,-1.0f,
  170.      1.0f,-1.0f, 1.0f,
  171.     -1.0f,-1.0f, 1.0f,
  172.  
  173.     -1.0f, 1.0f,-1.0f,  // +Y side
  174.     -1.0f, 1.0f, 1.0f,
  175.      1.0f, 1.0f, 1.0f,
  176.     -1.0f, 1.0f,-1.0f,
  177.      1.0f, 1.0f, 1.0f,
  178.      1.0f, 1.0f,-1.0f,
  179.  
  180.      1.0f, 1.0f,-1.0f,  // +X side
  181.      1.0f, 1.0f, 1.0f,
  182.      1.0f,-1.0f, 1.0f,
  183.      1.0f,-1.0f, 1.0f,
  184.      1.0f,-1.0f,-1.0f,
  185.      1.0f, 1.0f,-1.0f,
  186.  
  187.     -1.0f, 1.0f, 1.0f,  // +Z side
  188.     -1.0f,-1.0f, 1.0f,
  189.      1.0f, 1.0f, 1.0f,
  190.     -1.0f,-1.0f, 1.0f,
  191.      1.0f,-1.0f, 1.0f,
  192.      1.0f, 1.0f, 1.0f,
  193. };
  194.  
  195. static const float g_uv_buffer_data[] = {
  196.     0.0f, 0.0f,  // -X side
  197.     1.0f, 0.0f,
  198.     1.0f, 1.0f,
  199.     1.0f, 1.0f,
  200.     0.0f, 1.0f,
  201.     0.0f, 0.0f,
  202.  
  203.     1.0f, 0.0f,  // -Z side
  204.     0.0f, 1.0f,
  205.     0.0f, 0.0f,
  206.     1.0f, 0.0f,
  207.     1.0f, 1.0f,
  208.     0.0f, 1.0f,
  209.  
  210.     1.0f, 1.0f,  // -Y side
  211.     1.0f, 0.0f,
  212.     0.0f, 0.0f,
  213.     1.0f, 1.0f,
  214.     0.0f, 0.0f,
  215.     0.0f, 1.0f,
  216.  
  217.     1.0f, 1.0f,  // +Y side
  218.     0.0f, 1.0f,
  219.     0.0f, 0.0f,
  220.     1.0f, 1.0f,
  221.     0.0f, 0.0f,
  222.     1.0f, 0.0f,
  223.  
  224.     1.0f, 1.0f,  // +X side
  225.     0.0f, 1.0f,
  226.     0.0f, 0.0f,
  227.     0.0f, 0.0f,
  228.     1.0f, 0.0f,
  229.     1.0f, 1.0f,
  230.  
  231.     0.0f, 1.0f,  // +Z side
  232.     0.0f, 0.0f,
  233.     1.0f, 1.0f,
  234.     0.0f, 0.0f,
  235.     1.0f, 0.0f,
  236.     1.0f, 1.0f,
  237. };
  238. // clang-format on
  239.  
  240. void dumpMatrix(const char *note, mat4x4 MVP) {
  241.     int i;
  242.  
  243.     printf("%s: \n", note);
  244.     for (i = 0; i < 4; i++) {
  245.         printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
  246.     }
  247.     printf("\n");
  248.     fflush(stdout);
  249. }
  250.  
  251. void dumpVec4(const char *note, vec4 vector) {
  252.     printf("%s: \n", note);
  253.     printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
  254.     printf("\n");
  255.     fflush(stdout);
  256. }
  257.  
  258. VKAPI_ATTR VkBool32 VKAPI_CALL
  259. dbgFunc(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType,
  260.         uint64_t srcObject, size_t location, int32_t msgCode,
  261.         const char *pLayerPrefix, const char *pMsg, void *pUserData) {
  262.     char *message = (char *)malloc(strlen(pMsg) + 100);
  263.  
  264.     assert(message);
  265.  
  266.     if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
  267.         sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode,
  268.                 pMsg);
  269.         validation_error = 1;
  270.     } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
  271.         // We know that we're submitting queues without fences, ignore this
  272.         // warning
  273.         if (strstr(pMsg,
  274.                    "vkQueueSubmit parameter, VkFence fence, is null pointer")) {
  275.             return false;
  276.         }
  277.         sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode,
  278.                 pMsg);
  279.         validation_error = 1;
  280.     } else {
  281.         validation_error = 1;
  282.         return false;
  283.     }
  284.  
  285. #ifdef _WIN32
  286.     MessageBox(NULL, message, "Alert", MB_OK);
  287. #else
  288.     printf("%s\n", message);
  289.     fflush(stdout);
  290. #endif
  291.     free(message);
  292.  
  293.     /*
  294.      * false indicates that layer should not bail-out of an
  295.      * API call that had validation failures. This may mean that the
  296.      * app dies inside the driver due to invalid parameter(s).
  297.      * That's what would happen without validation layers, so we'll
  298.      * keep that behavior here.
  299.      */
  300.     return false;
  301. }
  302.  
  303. VKAPI_ATTR VkBool32 VKAPI_CALL
  304. BreakCallback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType,
  305.               uint64_t srcObject, size_t location, int32_t msgCode,
  306.               const char *pLayerPrefix, const char *pMsg,
  307.               void *pUserData) {
  308. #ifndef WIN32
  309.     raise(SIGTRAP);
  310. #else
  311.     DebugBreak();
  312. #endif
  313.  
  314.     return false;
  315. }
  316.  
  317. typedef struct _SwapchainBuffers {
  318.     VkImage image;
  319.     VkCommandBuffer cmd;
  320.     VkImageView view;
  321. } SwapchainBuffers;
  322.  
  323. struct demo {
  324. #ifdef _WIN32
  325. #define APP_NAME_STR_LEN 80
  326.     HINSTANCE connection;        // hInstance - Windows Instance
  327.     char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
  328.     HWND window;                 // hWnd - window handle
  329. #else
  330.     Display* display;
  331.     Window xlib_window;
  332.     Atom xlib_wm_delete_window;
  333.     xcb_connection_t *connection;
  334.     xcb_screen_t *screen;
  335.     xcb_window_t xcb_window;
  336.     xcb_intern_atom_reply_t *atom_wm_delete_window;
  337. #endif                           // _WIN32
  338.     VkSurfaceKHR surface;
  339.     bool prepared;
  340.     bool use_staging_buffer;
  341.     bool use_xlib;
  342.  
  343.     VkInstance inst;
  344.     VkPhysicalDevice gpu;
  345.     VkDevice device;
  346.     VkQueue queue;
  347.     uint32_t graphics_queue_node_index;
  348.     VkPhysicalDeviceProperties gpu_props;
  349.     VkQueueFamilyProperties *queue_props;
  350.     VkPhysicalDeviceMemoryProperties memory_properties;
  351.  
  352.     uint32_t enabled_extension_count;
  353.     uint32_t enabled_layer_count;
  354.     char *extension_names[64];
  355.     char *device_validation_layers[64];
  356.  
  357.     int width, height;
  358.     VkFormat format;
  359.     VkColorSpaceKHR color_space;
  360.  
  361.     PFN_vkGetPhysicalDeviceSurfaceSupportKHR
  362.         fpGetPhysicalDeviceSurfaceSupportKHR;
  363.     PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR
  364.         fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
  365.     PFN_vkGetPhysicalDeviceSurfaceFormatsKHR
  366.         fpGetPhysicalDeviceSurfaceFormatsKHR;
  367.     PFN_vkGetPhysicalDeviceSurfacePresentModesKHR
  368.         fpGetPhysicalDeviceSurfacePresentModesKHR;
  369.     PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
  370.     PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
  371.     PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
  372.     PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
  373.     PFN_vkQueuePresentKHR fpQueuePresentKHR;
  374.     uint32_t swapchainImageCount;
  375.     VkSwapchainKHR swapchain;
  376.     SwapchainBuffers *buffers;
  377.  
  378.     VkCommandPool cmd_pool;
  379.  
  380.     struct {
  381.         VkFormat format;
  382.  
  383.         VkImage image;
  384.         VkMemoryAllocateInfo mem_alloc;
  385.         VkDeviceMemory mem;
  386.         VkImageView view;
  387.     } depth;
  388.  
  389.     struct texture_object textures[DEMO_TEXTURE_COUNT];
  390.  
  391.     struct {
  392.         VkBuffer buf;
  393.         VkMemoryAllocateInfo mem_alloc;
  394.         VkDeviceMemory mem;
  395.         VkDescriptorBufferInfo buffer_info;
  396.     } uniform_data;
  397.  
  398.     VkCommandBuffer cmd; // Buffer for initialization commands
  399.     VkPipelineLayout pipeline_layout;
  400.     VkDescriptorSetLayout desc_layout;
  401.     VkPipelineCache pipelineCache;
  402.     VkRenderPass render_pass;
  403.     VkPipeline pipeline;
  404.  
  405.     mat4x4 projection_matrix;
  406.     mat4x4 view_matrix;
  407.     mat4x4 model_matrix;
  408.  
  409.     float spin_angle;
  410.     float spin_increment;
  411.     bool pause;
  412.  
  413.     VkShaderModule vert_shader_module;
  414.     VkShaderModule frag_shader_module;
  415.  
  416.     VkDescriptorPool desc_pool;
  417.     VkDescriptorSet desc_set;
  418.  
  419.     VkFramebuffer *framebuffers;
  420.  
  421.     bool quit;
  422.     int32_t curFrame;
  423.     int32_t frameCount;
  424.     bool validate;
  425.     bool use_break;
  426.     PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback;
  427.     PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback;
  428.     VkDebugReportCallbackEXT msg_callback;
  429.     PFN_vkDebugReportMessageEXT DebugReportMessage;
  430.  
  431.     uint32_t current_buffer;
  432.     uint32_t queue_count;
  433. };
  434.  
  435. // Forward declaration:
  436. static void demo_resize(struct demo *demo);
  437.  
  438. static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits,
  439.                                         VkFlags requirements_mask,
  440.                                         uint32_t *typeIndex) {
  441.     // Search memtypes to find first index with those properties
  442.     for (uint32_t i = 0; i < 32; i++) {
  443.         if ((typeBits & 1) == 1) {
  444.             // Type is available, does it match user properties?
  445.             if ((demo->memory_properties.memoryTypes[i].propertyFlags &
  446.                  requirements_mask) == requirements_mask) {
  447.                 *typeIndex = i;
  448.                 return true;
  449.             }
  450.         }
  451.         typeBits >>= 1;
  452.     }
  453.     // No memory types matched, return failure
  454.     return false;
  455. }
  456.  
  457. static void demo_flush_init_cmd(struct demo *demo) {
  458.     VkResult U_ASSERT_ONLY err;
  459.  
  460.     if (demo->cmd == VK_NULL_HANDLE)
  461.         return;
  462.  
  463.     err = vkEndCommandBuffer(demo->cmd);
  464.     assert(!err);
  465.  
  466.     const VkCommandBuffer cmd_bufs[] = {demo->cmd};
  467.     VkFence nullFence = VK_NULL_HANDLE;
  468.     VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  469.                                 .pNext = NULL,
  470.                                 .waitSemaphoreCount = 0,
  471.                                 .pWaitSemaphores = NULL,
  472.                                 .pWaitDstStageMask = NULL,
  473.                                 .commandBufferCount = 1,
  474.                                 .pCommandBuffers = cmd_bufs,
  475.                                 .signalSemaphoreCount = 0,
  476.                                 .pSignalSemaphores = NULL};
  477.  
  478.     err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence);
  479.     assert(!err);
  480.  
  481.     err = vkQueueWaitIdle(demo->queue);
  482.     assert(!err);
  483.  
  484.     vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
  485.     demo->cmd = VK_NULL_HANDLE;
  486. }
  487.  
  488. static void demo_set_image_layout(struct demo *demo, VkImage image,
  489.                                   VkImageAspectFlags aspectMask,
  490.                                   VkImageLayout old_image_layout,
  491.                                   VkImageLayout new_image_layout,
  492.                                   VkAccessFlagBits srcAccessMask) {
  493.     VkResult U_ASSERT_ONLY err;
  494.  
  495.     if (demo->cmd == VK_NULL_HANDLE) {
  496.         const VkCommandBufferAllocateInfo cmd = {
  497.             .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  498.             .pNext = NULL,
  499.             .commandPool = demo->cmd_pool,
  500.             .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  501.             .commandBufferCount = 1,
  502.         };
  503.  
  504.         err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
  505.         assert(!err);
  506.  
  507.         VkCommandBufferInheritanceInfo cmd_buf_hinfo = {
  508.             .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
  509.             .pNext = NULL,
  510.             .renderPass = VK_NULL_HANDLE,
  511.             .subpass = 0,
  512.             .framebuffer = VK_NULL_HANDLE,
  513.             .occlusionQueryEnable = VK_FALSE,
  514.             .queryFlags = 0,
  515.             .pipelineStatistics = 0,
  516.         };
  517.         VkCommandBufferBeginInfo cmd_buf_info = {
  518.             .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  519.             .pNext = NULL,
  520.             .flags = 0,
  521.             .pInheritanceInfo = &cmd_buf_hinfo,
  522.         };
  523.         err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
  524.         assert(!err);
  525.     }
  526.  
  527.     VkImageMemoryBarrier image_memory_barrier = {
  528.         .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
  529.         .pNext = NULL,
  530.         .srcAccessMask = srcAccessMask,
  531.         .dstAccessMask = 0,
  532.         .oldLayout = old_image_layout,
  533.         .newLayout = new_image_layout,
  534.         .image = image,
  535.         .subresourceRange = {aspectMask, 0, 1, 0, 1}};
  536.  
  537.     if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
  538.         /* Make sure anything that was copying from this image has completed */
  539.         image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  540.     }
  541.  
  542.     if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
  543.         image_memory_barrier.dstAccessMask =
  544.             VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  545.     }
  546.  
  547.     if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
  548.         image_memory_barrier.dstAccessMask =
  549.             VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  550.     }
  551.  
  552.     if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
  553.         /* Make sure any Copy or CPU writes to image are flushed */
  554.         image_memory_barrier.dstAccessMask =
  555.             VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
  556.     }
  557.  
  558.     VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
  559.  
  560.     VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  561.     VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
  562.  
  563.     vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0,
  564.                          NULL, 1, pmemory_barrier);
  565. }
  566.  
  567. static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
  568.     VkCommandBufferInheritanceInfo cmd_buf_hinfo = {
  569.         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
  570.         .pNext = NULL,
  571.         .renderPass = VK_NULL_HANDLE,
  572.         .subpass = 0,
  573.         .framebuffer = VK_NULL_HANDLE,
  574.         .occlusionQueryEnable = VK_FALSE,
  575.         .queryFlags = 0,
  576.         .pipelineStatistics = 0,
  577.     };
  578.     const VkCommandBufferBeginInfo cmd_buf_info = {
  579.         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  580.         .pNext = NULL,
  581.         .flags = 0,
  582.         .pInheritanceInfo = &cmd_buf_hinfo,
  583.     };
  584.     const VkClearValue clear_values[2] = {
  585.             [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
  586.             [1] = {.depthStencil = {1.0f, 0}},
  587.     };
  588.     const VkRenderPassBeginInfo rp_begin = {
  589.         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
  590.         .pNext = NULL,
  591.         .renderPass = demo->render_pass,
  592.         .framebuffer = demo->framebuffers[demo->current_buffer],
  593.         .renderArea.offset.x = 0,
  594.         .renderArea.offset.y = 0,
  595.         .renderArea.extent.width = demo->width,
  596.         .renderArea.extent.height = demo->height,
  597.         .clearValueCount = 2,
  598.         .pClearValues = clear_values,
  599.     };
  600.     VkResult U_ASSERT_ONLY err;
  601.  
  602.     err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
  603.     assert(!err);
  604.  
  605.     vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
  606.  
  607.     vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
  608.     vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS,
  609.                             demo->pipeline_layout, 0, 1, &demo->desc_set, 0,
  610.                             NULL);
  611.  
  612.     VkViewport viewport;
  613.     memset(&viewport, 0, sizeof(viewport));
  614.     viewport.height = (float)demo->height;
  615.     viewport.width = (float)demo->width;
  616.     viewport.minDepth = (float)0.0f;
  617.     viewport.maxDepth = (float)1.0f;
  618.     vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
  619.  
  620.     VkRect2D scissor;
  621.     memset(&scissor, 0, sizeof(scissor));
  622.     scissor.extent.width = demo->width;
  623.     scissor.extent.height = demo->height;
  624.     scissor.offset.x = 0;
  625.     scissor.offset.y = 0;
  626.     vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
  627.  
  628.     vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
  629.     vkCmdEndRenderPass(cmd_buf);
  630.  
  631.     VkImageMemoryBarrier prePresentBarrier = {
  632.         .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
  633.         .pNext = NULL,
  634.         .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
  635.         .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT,
  636.         .oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  637.         .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  638.         .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
  639.         .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
  640.         .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
  641.  
  642.     prePresentBarrier.image = demo->buffers[demo->current_buffer].image;
  643.     VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier;
  644.     vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
  645.                          VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
  646.                          NULL, 1, pmemory_barrier);
  647.  
  648.     err = vkEndCommandBuffer(cmd_buf);
  649.     assert(!err);
  650. }
  651.  
  652. void demo_update_data_buffer(struct demo *demo) {
  653.     mat4x4 MVP, Model, VP;
  654.     int matrixSize = sizeof(MVP);
  655.     uint8_t *pData;
  656.     VkResult U_ASSERT_ONLY err;
  657.  
  658.     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
  659.  
  660.     // Rotate 22.5 degrees around the Y axis
  661.     mat4x4_dup(Model, demo->model_matrix);
  662.     mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f,
  663.                   (float)degreesToRadians(demo->spin_angle));
  664.     mat4x4_mul(MVP, VP, demo->model_matrix);
  665.  
  666.     err = vkMapMemory(demo->device, demo->uniform_data.mem, 0,
  667.                       demo->uniform_data.mem_alloc.allocationSize, 0,
  668.                       (void **)&pData);
  669.     assert(!err);
  670.  
  671.     memcpy(pData, (const void *)&MVP[0][0], matrixSize);
  672.  
  673.     vkUnmapMemory(demo->device, demo->uniform_data.mem);
  674. }
  675.  
  676. static void open_console()
  677. {
  678.   AllocConsole() ;
  679.   AttachConsole( GetCurrentProcessId() ) ;
  680.   freopen( "CON", "w", stdout ) ;
  681. }
  682.  
  683. static void demo_draw(struct demo *demo) {
  684.     // Timestamp Query Start
  685.     static VkQueryPool queryPool = NULL;
  686.     if(queryPool == NULL)
  687.     {
  688.         open_console();
  689.         VkQueryPoolCreateInfo info;
  690.         info.flags = 0;
  691.         info.pipelineStatistics = 0;
  692.         info.pNext = NULL;
  693.         info.queryCount = 2;
  694.         info.queryType = VK_QUERY_TYPE_TIMESTAMP;
  695.         info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO;
  696.  
  697.         VkResult r = vkCreateQueryPool(demo->device,&info,NULL,&queryPool);
  698.         assert(!r);
  699.     }
  700.     // Timestamp Query End
  701.  
  702.  
  703.     VkResult U_ASSERT_ONLY err;
  704.     VkSemaphore presentCompleteSemaphore;
  705.     VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo = {
  706.         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  707.         .pNext = NULL,
  708.         .flags = 0,
  709.     };
  710.     VkFence nullFence = VK_NULL_HANDLE;
  711.  
  712.     err = vkCreateSemaphore(demo->device, &presentCompleteSemaphoreCreateInfo,
  713.                             NULL, &presentCompleteSemaphore);
  714.     assert(!err);
  715.  
  716.     // Get the index of the next available swapchain image:
  717.     err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
  718.                                       presentCompleteSemaphore,
  719.                                       (VkFence)0, // TODO: Show use of fence
  720.                                       &demo->current_buffer);
  721.     if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  722.         // demo->swapchain is out of date (e.g. the window was resized) and
  723.         // must be recreated:
  724.         demo_resize(demo);
  725.         demo_draw(demo);
  726.         vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL);
  727.         return;
  728.     } else if (err == VK_SUBOPTIMAL_KHR) {
  729.         // demo->swapchain is not as optimal as it could be, but the platform's
  730.         // presentation engine will still present the image correctly.
  731.     } else {
  732.         assert(!err);
  733.     }
  734.  
  735.     // Assume the command buffer has been run on current_buffer before so
  736.     // we need to set the image layout back to COLOR_ATTACHMENT_OPTIMAL
  737.     demo_set_image_layout(demo, demo->buffers[demo->current_buffer].image,
  738.                           VK_IMAGE_ASPECT_COLOR_BIT,
  739.                           VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  740.                           VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  741.                           0);
  742.  
  743.     vkCmdResetQueryPool(demo->cmd,queryPool,0,1); // Reset query #1
  744.     vkCmdWriteTimestamp(demo->cmd,VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,queryPool,0); // Write query #1
  745.     vkCmdResetQueryPool(demo->cmd,queryPool,1,1); // Reset query #2
  746.     //vkCmdWriteTimestamp(demo->cmd,VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,queryPool,1); // Write query #2
  747.  
  748.     demo_flush_init_cmd(demo);
  749.  
  750.     // Wait for the present complete semaphore to be signaled to ensure
  751.     // that the image won't be rendered to until the presentation
  752.     // engine has fully released ownership to the application, and it is
  753.     // okay to render to the image.
  754.  
  755.     // FIXME/TODO: DEAL WITH VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
  756.     VkPipelineStageFlags pipe_stage_flags =
  757.         VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
  758.     VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
  759.                                 .pNext = NULL,
  760.                                 .waitSemaphoreCount = 1,
  761.                                 .pWaitSemaphores = &presentCompleteSemaphore,
  762.                                 .pWaitDstStageMask = &pipe_stage_flags,
  763.                                 .commandBufferCount = 1,
  764.                                 .pCommandBuffers =
  765.                                     &demo->buffers[demo->current_buffer].cmd,
  766.                                 .signalSemaphoreCount = 0,
  767.                                 .pSignalSemaphores = NULL};
  768.  
  769.     err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence);
  770.     assert(!err);
  771.  
  772.     VkPresentInfoKHR present = {
  773.         .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
  774.         .pNext = NULL,
  775.         .swapchainCount = 1,
  776.         .pSwapchains = &demo->swapchain,
  777.         .pImageIndices = &demo->current_buffer,
  778.     };
  779.  
  780.     // TBD/TODO: SHOULD THE "present" PARAMETER BE "const" IN THE HEADER?
  781.     err = demo->fpQueuePresentKHR(demo->queue, &present);
  782.     if (err == VK_ERROR_OUT_OF_DATE_KHR) {
  783.         // demo->swapchain is out of date (e.g. the window was resized) and
  784.         // must be recreated:
  785.         demo_resize(demo);
  786.     } else if (err == VK_SUBOPTIMAL_KHR) {
  787.         // demo->swapchain is not as optimal as it could be, but the platform's
  788.         // presentation engine will still present the image correctly.
  789.     } else {
  790.         assert(!err);
  791.     }
  792.  
  793.     err = vkQueueWaitIdle(demo->queue);
  794.     assert(err == VK_SUCCESS);
  795.  
  796.     uint32_t resultData[2] = {0,0};
  797.     VkResult r = vkGetQueryPoolResults(demo->device,queryPool,0,1,sizeof(uint32_t) *2,resultData,sizeof(uint32_t) *2,VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
  798.     if(resultData[1] != 0)
  799.         printf("Result available %i,%i\n",resultData[0],resultData[2]);
  800.     else
  801.         printf("Result not available\n");
  802.  
  803.     vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL);
  804. }
  805.  
  806. static void demo_prepare_buffers(struct demo *demo) {
  807.     VkResult U_ASSERT_ONLY err;
  808.     VkSwapchainKHR oldSwapchain = demo->swapchain;
  809.  
  810.     // Check the surface capabilities and formats
  811.     VkSurfaceCapabilitiesKHR surfCapabilities;
  812.     err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(
  813.         demo->gpu, demo->surface, &surfCapabilities);
  814.     assert(!err);
  815.  
  816.     uint32_t presentModeCount;
  817.     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(
  818.         demo->gpu, demo->surface, &presentModeCount, NULL);
  819.     assert(!err);
  820.     VkPresentModeKHR *presentModes =
  821.         (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
  822.     assert(presentModes);
  823.     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(
  824.         demo->gpu, demo->surface, &presentModeCount, presentModes);
  825.     assert(!err);
  826.  
  827.     VkExtent2D swapchainExtent;
  828.     // width and height are either both -1, or both not -1.
  829.     if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
  830.         // If the surface size is undefined, the size is set to
  831.         // the size of the images requested.
  832.         swapchainExtent.width = demo->width;
  833.         swapchainExtent.height = demo->height;
  834.     } else {
  835.         // If the surface size is defined, the swap chain size must match
  836.         swapchainExtent = surfCapabilities.currentExtent;
  837.         demo->width = surfCapabilities.currentExtent.width;
  838.         demo->height = surfCapabilities.currentExtent.height;
  839.     }
  840.  
  841.     // If mailbox mode is available, use it, as is the lowest-latency non-
  842.     // tearing mode.  If not, try IMMEDIATE which will usually be available,
  843.     // and is fastest (though it tears).  If not, fall back to FIFO which is
  844.     // always available.
  845.     VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
  846.     for (size_t i = 0; i < presentModeCount; i++) {
  847.         if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) {
  848.             swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
  849.             break;
  850.         }
  851.         if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) &&
  852.             (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) {
  853.             swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
  854.         }
  855.     }
  856.  
  857.     // Determine the number of VkImage's to use in the swap chain (we desire to
  858.     // own only 1 image at a time, besides the images being displayed and
  859.     // queued for display):
  860.     uint32_t desiredNumberOfSwapchainImages =
  861.         surfCapabilities.minImageCount + 1;
  862.     if ((surfCapabilities.maxImageCount > 0) &&
  863.         (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) {
  864.         // Application must settle for fewer images than desired:
  865.         desiredNumberOfSwapchainImages = surfCapabilities.maxImageCount;
  866.     }
  867.  
  868.     VkSurfaceTransformFlagsKHR preTransform;
  869.     if (surfCapabilities.supportedTransforms &
  870.         VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
  871.         preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
  872.     } else {
  873.         preTransform = surfCapabilities.currentTransform;
  874.     }
  875.  
  876.     const VkSwapchainCreateInfoKHR swapchain = {
  877.         .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
  878.         .pNext = NULL,
  879.         .surface = demo->surface,
  880.         .minImageCount = desiredNumberOfSwapchainImages,
  881.         .imageFormat = demo->format,
  882.         .imageColorSpace = demo->color_space,
  883.         .imageExtent =
  884.             {
  885.              .width = swapchainExtent.width, .height = swapchainExtent.height,
  886.             },
  887.         .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
  888.         .preTransform = preTransform,
  889.         .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
  890.         .imageArrayLayers = 1,
  891.         .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
  892.         .queueFamilyIndexCount = 0,
  893.         .pQueueFamilyIndices = NULL,
  894.         .presentMode = swapchainPresentMode,
  895.         .oldSwapchain = oldSwapchain,
  896.         .clipped = true,
  897.     };
  898.     uint32_t i;
  899.  
  900.     err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL,
  901.                                      &demo->swapchain);
  902.     assert(!err);
  903.  
  904.     // If we just re-created an existing swapchain, we should destroy the old
  905.     // swapchain at this point.
  906.     // Note: destroying the swapchain also cleans up all its associated
  907.     // presentable images once the platform is done with them.
  908.     if (oldSwapchain != VK_NULL_HANDLE) {
  909.         demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
  910.     }
  911.  
  912.     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain,
  913.                                         &demo->swapchainImageCount, NULL);
  914.     assert(!err);
  915.  
  916.     VkImage *swapchainImages =
  917.         (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
  918.     assert(swapchainImages);
  919.     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain,
  920.                                         &demo->swapchainImageCount,
  921.                                         swapchainImages);
  922.     assert(!err);
  923.  
  924.     demo->buffers = (SwapchainBuffers *)malloc(sizeof(SwapchainBuffers) *
  925.                                                demo->swapchainImageCount);
  926.     assert(demo->buffers);
  927.  
  928.     for (i = 0; i < demo->swapchainImageCount; i++) {
  929.         VkImageViewCreateInfo color_image_view = {
  930.             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  931.             .pNext = NULL,
  932.             .format = demo->format,
  933.             .components =
  934.                 {
  935.                  .r = VK_COMPONENT_SWIZZLE_R,
  936.                  .g = VK_COMPONENT_SWIZZLE_G,
  937.                  .b = VK_COMPONENT_SWIZZLE_B,
  938.                  .a = VK_COMPONENT_SWIZZLE_A,
  939.                 },
  940.             .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  941.                                  .baseMipLevel = 0,
  942.                                  .levelCount = 1,
  943.                                  .baseArrayLayer = 0,
  944.                                  .layerCount = 1},
  945.             .viewType = VK_IMAGE_VIEW_TYPE_2D,
  946.             .flags = 0,
  947.         };
  948.  
  949.         demo->buffers[i].image = swapchainImages[i];
  950.  
  951.         // Render loop will expect image to have been used before and in
  952.         // VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
  953.         // layout and will change to COLOR_ATTACHMENT_OPTIMAL, so init the image
  954.         // to that state
  955.         demo_set_image_layout(
  956.             demo, demo->buffers[i].image, VK_IMAGE_ASPECT_COLOR_BIT,
  957.             VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
  958.             0);
  959.  
  960.         color_image_view.image = demo->buffers[i].image;
  961.  
  962.         err = vkCreateImageView(demo->device, &color_image_view, NULL,
  963.                                 &demo->buffers[i].view);
  964.         assert(!err);
  965.     }
  966.  
  967.     if (NULL != presentModes) {
  968.         free(presentModes);
  969.     }
  970. }
  971.  
  972. static void demo_prepare_depth(struct demo *demo) {
  973.     const VkFormat depth_format = VK_FORMAT_D16_UNORM;
  974.     const VkImageCreateInfo image = {
  975.         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  976.         .pNext = NULL,
  977.         .imageType = VK_IMAGE_TYPE_2D,
  978.         .format = depth_format,
  979.         .extent = {demo->width, demo->height, 1},
  980.         .mipLevels = 1,
  981.         .arrayLayers = 1,
  982.         .samples = VK_SAMPLE_COUNT_1_BIT,
  983.         .tiling = VK_IMAGE_TILING_OPTIMAL,
  984.         .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
  985.         .flags = 0,
  986.     };
  987.  
  988.     VkImageViewCreateInfo view = {
  989.         .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  990.         .pNext = NULL,
  991.         .image = VK_NULL_HANDLE,
  992.         .format = depth_format,
  993.         .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT,
  994.                              .baseMipLevel = 0,
  995.                              .levelCount = 1,
  996.                              .baseArrayLayer = 0,
  997.                              .layerCount = 1},
  998.         .flags = 0,
  999.         .viewType = VK_IMAGE_VIEW_TYPE_2D,
  1000.     };
  1001.  
  1002.     VkMemoryRequirements mem_reqs;
  1003.     VkResult U_ASSERT_ONLY err;
  1004.     bool U_ASSERT_ONLY pass;
  1005.  
  1006.     demo->depth.format = depth_format;
  1007.  
  1008.     /* create image */
  1009.     err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
  1010.     assert(!err);
  1011.  
  1012.     vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
  1013.     assert(!err);
  1014.  
  1015.     demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  1016.     demo->depth.mem_alloc.pNext = NULL;
  1017.     demo->depth.mem_alloc.allocationSize = mem_reqs.size;
  1018.     demo->depth.mem_alloc.memoryTypeIndex = 0;
  1019.  
  1020.     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
  1021.                                        0, /* No requirements */
  1022.                                        &demo->depth.mem_alloc.memoryTypeIndex);
  1023.     assert(pass);
  1024.  
  1025.     /* allocate memory */
  1026.     err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL,
  1027.                            &demo->depth.mem);
  1028.     assert(!err);
  1029.  
  1030.     /* bind memory */
  1031.     err =
  1032.         vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
  1033.     assert(!err);
  1034.  
  1035.     demo_set_image_layout(demo, demo->depth.image, VK_IMAGE_ASPECT_DEPTH_BIT,
  1036.                           VK_IMAGE_LAYOUT_UNDEFINED,
  1037.                           VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
  1038.                           0);
  1039.  
  1040.     /* create image view */
  1041.     view.image = demo->depth.image;
  1042.     err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
  1043.     assert(!err);
  1044. }
  1045.  
  1046. /* Load a ppm file into memory */
  1047. bool loadTexture(const char *filename, uint8_t *rgba_data,
  1048.                  VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
  1049.     FILE *fPtr = fopen(filename, "rb");
  1050.     char header[256], *cPtr, *tmp;
  1051.  
  1052.     if (!fPtr)
  1053.         return false;
  1054.  
  1055.     cPtr = fgets(header, 256, fPtr); // P6
  1056.     if (cPtr == NULL || strncmp(header, "P6\n", 3)) {
  1057.         fclose(fPtr);
  1058.         return false;
  1059.     }
  1060.  
  1061.     do {
  1062.         cPtr = fgets(header, 256, fPtr);
  1063.         if (cPtr == NULL) {
  1064.             fclose(fPtr);
  1065.             return false;
  1066.         }
  1067.     } while (!strncmp(header, "#", 1));
  1068.  
  1069.     sscanf(header, "%u %u", height, width);
  1070.     if (rgba_data == NULL) {
  1071.         fclose(fPtr);
  1072.         return true;
  1073.     }
  1074.     tmp = fgets(header, 256, fPtr); // Format
  1075.     (void)tmp;
  1076.     if (cPtr == NULL || strncmp(header, "255\n", 3)) {
  1077.         fclose(fPtr);
  1078.         return false;
  1079.     }
  1080.  
  1081.     for (int y = 0; y < *height; y++) {
  1082.         uint8_t *rowPtr = rgba_data;
  1083.         for (int x = 0; x < *width; x++) {
  1084.             size_t s = fread(rowPtr, 3, 1, fPtr);
  1085.             (void)s;
  1086.             rowPtr[3] = 255; /* Alpha of 1 */
  1087.             rowPtr += 4;
  1088.         }
  1089.         rgba_data += layout->rowPitch;
  1090.     }
  1091.     fclose(fPtr);
  1092.     return true;
  1093. }
  1094.  
  1095. static void demo_prepare_texture_image(struct demo *demo, const char *filename,
  1096.                                        struct texture_object *tex_obj,
  1097.                                        VkImageTiling tiling,
  1098.                                        VkImageUsageFlags usage,
  1099.                                        VkFlags required_props) {
  1100.     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
  1101.     int32_t tex_width;
  1102.     int32_t tex_height;
  1103.     VkResult U_ASSERT_ONLY err;
  1104.     bool U_ASSERT_ONLY pass;
  1105.  
  1106.     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
  1107.         printf("Failed to load textures\n");
  1108.         fflush(stdout);
  1109.         exit(1);
  1110.     }
  1111.  
  1112.     tex_obj->tex_width = tex_width;
  1113.     tex_obj->tex_height = tex_height;
  1114.  
  1115.     const VkImageCreateInfo image_create_info = {
  1116.         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
  1117.         .pNext = NULL,
  1118.         .imageType = VK_IMAGE_TYPE_2D,
  1119.         .format = tex_format,
  1120.         .extent = {tex_width, tex_height, 1},
  1121.         .mipLevels = 1,
  1122.         .arrayLayers = 1,
  1123.         .samples = VK_SAMPLE_COUNT_1_BIT,
  1124.         .tiling = tiling,
  1125.         .usage = usage,
  1126.         .flags = 0,
  1127.         .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
  1128.     };
  1129.  
  1130.     VkMemoryRequirements mem_reqs;
  1131.  
  1132.     err =
  1133.         vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
  1134.     assert(!err);
  1135.  
  1136.     vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
  1137.  
  1138.     tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  1139.     tex_obj->mem_alloc.pNext = NULL;
  1140.     tex_obj->mem_alloc.allocationSize = mem_reqs.size;
  1141.     tex_obj->mem_alloc.memoryTypeIndex = 0;
  1142.  
  1143.     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
  1144.                                        required_props,
  1145.                                        &tex_obj->mem_alloc.memoryTypeIndex);
  1146.     assert(pass);
  1147.  
  1148.     /* allocate memory */
  1149.     err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL,
  1150.                            &(tex_obj->mem));
  1151.     assert(!err);
  1152.  
  1153.     /* bind memory */
  1154.     err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
  1155.     assert(!err);
  1156.  
  1157.     if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
  1158.         const VkImageSubresource subres = {
  1159.             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
  1160.             .mipLevel = 0,
  1161.             .arrayLayer = 0,
  1162.         };
  1163.         VkSubresourceLayout layout;
  1164.         void *data;
  1165.  
  1166.         vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres,
  1167.                                     &layout);
  1168.  
  1169.         err = vkMapMemory(demo->device, tex_obj->mem, 0,
  1170.                           tex_obj->mem_alloc.allocationSize, 0, &data);
  1171.         assert(!err);
  1172.  
  1173.         if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
  1174.             fprintf(stderr, "Error loading texture: %s\n", filename);
  1175.         }
  1176.  
  1177.         vkUnmapMemory(demo->device, tex_obj->mem);
  1178.     }
  1179.  
  1180.     tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  1181.     demo_set_image_layout(demo, tex_obj->image, VK_IMAGE_ASPECT_COLOR_BIT,
  1182.                           VK_IMAGE_LAYOUT_PREINITIALIZED, tex_obj->imageLayout,
  1183.                           VK_ACCESS_HOST_WRITE_BIT);
  1184.     /* setting the image layout does not reference the actual memory so no need
  1185.      * to add a mem ref */
  1186. }
  1187.  
  1188. static void demo_destroy_texture_image(struct demo *demo,
  1189.                                        struct texture_object *tex_objs) {
  1190.     /* clean up staging resources */
  1191.     vkFreeMemory(demo->device, tex_objs->mem, NULL);
  1192.     vkDestroyImage(demo->device, tex_objs->image, NULL);
  1193. }
  1194.  
  1195. static void demo_prepare_textures(struct demo *demo) {
  1196.     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
  1197.     VkFormatProperties props;
  1198.     uint32_t i;
  1199.  
  1200.     vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
  1201.  
  1202.     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
  1203.         VkResult U_ASSERT_ONLY err;
  1204.  
  1205.         if ((props.linearTilingFeatures &
  1206.              VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) &&
  1207.             !demo->use_staging_buffer) {
  1208.             /* Device can texture using linear textures */
  1209.             demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i],
  1210.                                        VK_IMAGE_TILING_LINEAR,
  1211.                                        VK_IMAGE_USAGE_SAMPLED_BIT,
  1212.                                        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
  1213.         } else if (props.optimalTilingFeatures &
  1214.                    VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
  1215.             /* Must use staging buffer to copy linear texture to optimized */
  1216.             struct texture_object staging_texture;
  1217.  
  1218.             memset(&staging_texture, 0, sizeof(staging_texture));
  1219.             demo_prepare_texture_image(demo, tex_files[i], &staging_texture,
  1220.                                        VK_IMAGE_TILING_LINEAR,
  1221.                                        VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
  1222.                                        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
  1223.  
  1224.             demo_prepare_texture_image(
  1225.                 demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
  1226.                 (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
  1227.                 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
  1228.  
  1229.             demo_set_image_layout(demo, staging_texture.image,
  1230.                                   VK_IMAGE_ASPECT_COLOR_BIT,
  1231.                                   staging_texture.imageLayout,
  1232.                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  1233.                                   0);
  1234.  
  1235.             demo_set_image_layout(demo, demo->textures[i].image,
  1236.                                   VK_IMAGE_ASPECT_COLOR_BIT,
  1237.                                   demo->textures[i].imageLayout,
  1238.                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  1239.                                   0);
  1240.  
  1241.             VkImageCopy copy_region = {
  1242.                 .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
  1243.                 .srcOffset = {0, 0, 0},
  1244.                 .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
  1245.                 .dstOffset = {0, 0, 0},
  1246.                 .extent = {staging_texture.tex_width,
  1247.                            staging_texture.tex_height, 1},
  1248.             };
  1249.             vkCmdCopyImage(
  1250.                 demo->cmd, staging_texture.image,
  1251.                 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image,
  1252.                 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);
  1253.  
  1254.             demo_set_image_layout(demo, demo->textures[i].image,
  1255.                                   VK_IMAGE_ASPECT_COLOR_BIT,
  1256.                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  1257.                                   demo->textures[i].imageLayout,
  1258.                                   0);
  1259.  
  1260.             demo_flush_init_cmd(demo);
  1261.  
  1262.             demo_destroy_texture_image(demo, &staging_texture);
  1263.         } else {
  1264.             /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
  1265.             assert(!"No support for R8G8B8A8_UNORM as texture image format");
  1266.         }
  1267.  
  1268.         const VkSamplerCreateInfo sampler = {
  1269.             .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
  1270.             .pNext = NULL,
  1271.             .magFilter = VK_FILTER_NEAREST,
  1272.             .minFilter = VK_FILTER_NEAREST,
  1273.             .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
  1274.             .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1275.             .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1276.             .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
  1277.             .mipLodBias = 0.0f,
  1278.             .anisotropyEnable = VK_FALSE,
  1279.             .maxAnisotropy = 1,
  1280.             .compareOp = VK_COMPARE_OP_NEVER,
  1281.             .minLod = 0.0f,
  1282.             .maxLod = 0.0f,
  1283.             .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
  1284.             .unnormalizedCoordinates = VK_FALSE,
  1285.         };
  1286.  
  1287.         VkImageViewCreateInfo view = {
  1288.             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
  1289.             .pNext = NULL,
  1290.             .image = VK_NULL_HANDLE,
  1291.             .viewType = VK_IMAGE_VIEW_TYPE_2D,
  1292.             .format = tex_format,
  1293.             .components =
  1294.                 {
  1295.                  VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
  1296.                  VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A,
  1297.                 },
  1298.             .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
  1299.             .flags = 0,
  1300.         };
  1301.  
  1302.         /* create sampler */
  1303.         err = vkCreateSampler(demo->device, &sampler, NULL,
  1304.                               &demo->textures[i].sampler);
  1305.         assert(!err);
  1306.  
  1307.         /* create image view */
  1308.         view.image = demo->textures[i].image;
  1309.         err = vkCreateImageView(demo->device, &view, NULL,
  1310.                                 &demo->textures[i].view);
  1311.         assert(!err);
  1312.     }
  1313. }
  1314.  
  1315. void demo_prepare_cube_data_buffer(struct demo *demo) {
  1316.     VkBufferCreateInfo buf_info;
  1317.     VkMemoryRequirements mem_reqs;
  1318.     uint8_t *pData;
  1319.     int i;
  1320.     mat4x4 MVP, VP;
  1321.     VkResult U_ASSERT_ONLY err;
  1322.     bool U_ASSERT_ONLY pass;
  1323.     struct vktexcube_vs_uniform data;
  1324.  
  1325.     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
  1326.     mat4x4_mul(MVP, VP, demo->model_matrix);
  1327.     memcpy(data.mvp, MVP, sizeof(MVP));
  1328.     //    dumpMatrix("MVP", MVP);
  1329.  
  1330.     for (i = 0; i < 12 * 3; i++) {
  1331.         data.position[i][0] = g_vertex_buffer_data[i * 3];
  1332.         data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
  1333.         data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
  1334.         data.position[i][3] = 1.0f;
  1335.         data.attr[i][0] = g_uv_buffer_data[2 * i];
  1336.         data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
  1337.         data.attr[i][2] = 0;
  1338.         data.attr[i][3] = 0;
  1339.     }
  1340.  
  1341.     memset(&buf_info, 0, sizeof(buf_info));
  1342.     buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1343.     buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
  1344.     buf_info.size = sizeof(data);
  1345.     err =
  1346.         vkCreateBuffer(demo->device, &buf_info, NULL, &demo->uniform_data.buf);
  1347.     assert(!err);
  1348.  
  1349.     vkGetBufferMemoryRequirements(demo->device, demo->uniform_data.buf,
  1350.                                   &mem_reqs);
  1351.  
  1352.     demo->uniform_data.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  1353.     demo->uniform_data.mem_alloc.pNext = NULL;
  1354.     demo->uniform_data.mem_alloc.allocationSize = mem_reqs.size;
  1355.     demo->uniform_data.mem_alloc.memoryTypeIndex = 0;
  1356.  
  1357.     pass = memory_type_from_properties(
  1358.         demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
  1359.         &demo->uniform_data.mem_alloc.memoryTypeIndex);
  1360.     assert(pass);
  1361.  
  1362.     err = vkAllocateMemory(demo->device, &demo->uniform_data.mem_alloc, NULL,
  1363.                            &(demo->uniform_data.mem));
  1364.     assert(!err);
  1365.  
  1366.     err = vkMapMemory(demo->device, demo->uniform_data.mem, 0,
  1367.                       demo->uniform_data.mem_alloc.allocationSize, 0,
  1368.                       (void **)&pData);
  1369.     assert(!err);
  1370.  
  1371.     memcpy(pData, &data, sizeof data);
  1372.  
  1373.     vkUnmapMemory(demo->device, demo->uniform_data.mem);
  1374.  
  1375.     err = vkBindBufferMemory(demo->device, demo->uniform_data.buf,
  1376.                              demo->uniform_data.mem, 0);
  1377.     assert(!err);
  1378.  
  1379.     demo->uniform_data.buffer_info.buffer = demo->uniform_data.buf;
  1380.     demo->uniform_data.buffer_info.offset = 0;
  1381.     demo->uniform_data.buffer_info.range = sizeof(data);
  1382. }
  1383.  
  1384. static void demo_prepare_descriptor_layout(struct demo *demo) {
  1385.     const VkDescriptorSetLayoutBinding layout_bindings[2] = {
  1386.             [0] =
  1387.                 {
  1388.                  .binding = 0,
  1389.                  .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
  1390.                  .descriptorCount = 1,
  1391.                  .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
  1392.                  .pImmutableSamplers = NULL,
  1393.                 },
  1394.             [1] =
  1395.                 {
  1396.                  .binding = 1,
  1397.                  .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
  1398.                  .descriptorCount = DEMO_TEXTURE_COUNT,
  1399.                  .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
  1400.                  .pImmutableSamplers = NULL,
  1401.                 },
  1402.     };
  1403.     const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
  1404.         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
  1405.         .pNext = NULL,
  1406.         .bindingCount = 2,
  1407.         .pBindings = layout_bindings,
  1408.     };
  1409.     VkResult U_ASSERT_ONLY err;
  1410.  
  1411.     err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL,
  1412.                                       &demo->desc_layout);
  1413.     assert(!err);
  1414.  
  1415.     const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
  1416.         .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
  1417.         .pNext = NULL,
  1418.         .setLayoutCount = 1,
  1419.         .pSetLayouts = &demo->desc_layout,
  1420.     };
  1421.  
  1422.     err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL,
  1423.                                  &demo->pipeline_layout);
  1424.     assert(!err);
  1425. }
  1426.  
  1427. static void demo_prepare_render_pass(struct demo *demo) {
  1428.     const VkAttachmentDescription attachments[2] = {
  1429.             [0] =
  1430.                 {
  1431.                  .format = demo->format,
  1432.                  .samples = VK_SAMPLE_COUNT_1_BIT,
  1433.                  .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
  1434.                  .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
  1435.                  .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
  1436.                  .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
  1437.                  .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  1438.                  .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  1439.                 },
  1440.             [1] =
  1441.                 {
  1442.                  .format = demo->depth.format,
  1443.                  .samples = VK_SAMPLE_COUNT_1_BIT,
  1444.                  .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
  1445.                  .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
  1446.                  .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
  1447.                  .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
  1448.                  .initialLayout =
  1449.                      VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
  1450.                  .finalLayout =
  1451.                      VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
  1452.                 },
  1453.     };
  1454.     const VkAttachmentReference color_reference = {
  1455.         .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  1456.     };
  1457.     const VkAttachmentReference depth_reference = {
  1458.         .attachment = 1,
  1459.         .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
  1460.     };
  1461.     const VkSubpassDescription subpass = {
  1462.         .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
  1463.         .flags = 0,
  1464.         .inputAttachmentCount = 0,
  1465.         .pInputAttachments = NULL,
  1466.         .colorAttachmentCount = 1,
  1467.         .pColorAttachments = &color_reference,
  1468.         .pResolveAttachments = NULL,
  1469.         .pDepthStencilAttachment = &depth_reference,
  1470.         .preserveAttachmentCount = 0,
  1471.         .pPreserveAttachments = NULL,
  1472.     };
  1473.     const VkRenderPassCreateInfo rp_info = {
  1474.         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
  1475.         .pNext = NULL,
  1476.         .attachmentCount = 2,
  1477.         .pAttachments = attachments,
  1478.         .subpassCount = 1,
  1479.         .pSubpasses = &subpass,
  1480.         .dependencyCount = 0,
  1481.         .pDependencies = NULL,
  1482.     };
  1483.     VkResult U_ASSERT_ONLY err;
  1484.  
  1485.     err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
  1486.     assert(!err);
  1487. }
  1488.  
  1489. static VkShaderModule
  1490. demo_prepare_shader_module(struct demo *demo, const void *code, size_t size) {
  1491.     VkShaderModule module;
  1492.     VkShaderModuleCreateInfo moduleCreateInfo;
  1493.     VkResult U_ASSERT_ONLY err;
  1494.  
  1495.     moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  1496.     moduleCreateInfo.pNext = NULL;
  1497.  
  1498.     moduleCreateInfo.codeSize = size;
  1499.     moduleCreateInfo.pCode = code;
  1500.     moduleCreateInfo.flags = 0;
  1501.     err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
  1502.     assert(!err);
  1503.  
  1504.     return module;
  1505. }
  1506.  
  1507. char *demo_read_spv(const char *filename, size_t *psize) {
  1508.     long int size;
  1509.     size_t U_ASSERT_ONLY retval;
  1510.     void *shader_code;
  1511.  
  1512.     FILE *fp = fopen(filename, "rb");
  1513.     if (!fp)
  1514.         return NULL;
  1515.  
  1516.     fseek(fp, 0L, SEEK_END);
  1517.     size = ftell(fp);
  1518.  
  1519.     fseek(fp, 0L, SEEK_SET);
  1520.  
  1521.     shader_code = malloc(size);
  1522.     retval = fread(shader_code, size, 1, fp);
  1523.     assert(retval == 1);
  1524.  
  1525.     *psize = size;
  1526.  
  1527.     fclose(fp);
  1528.     return shader_code;
  1529. }
  1530.  
  1531. static VkShaderModule demo_prepare_vs(struct demo *demo) {
  1532.     void *vertShaderCode;
  1533.     size_t size;
  1534.  
  1535.     vertShaderCode = demo_read_spv("cube-vert.spv", &size);
  1536.  
  1537.     demo->vert_shader_module =
  1538.         demo_prepare_shader_module(demo, vertShaderCode, size);
  1539.  
  1540.     free(vertShaderCode);
  1541.  
  1542.     return demo->vert_shader_module;
  1543. }
  1544.  
  1545. static VkShaderModule demo_prepare_fs(struct demo *demo) {
  1546.     void *fragShaderCode;
  1547.     size_t size;
  1548.  
  1549.     fragShaderCode = demo_read_spv("cube-frag.spv", &size);
  1550.  
  1551.     demo->frag_shader_module =
  1552.         demo_prepare_shader_module(demo, fragShaderCode, size);
  1553.  
  1554.     free(fragShaderCode);
  1555.  
  1556.     return demo->frag_shader_module;
  1557. }
  1558.  
  1559. static void demo_prepare_pipeline(struct demo *demo) {
  1560.     VkGraphicsPipelineCreateInfo pipeline;
  1561.     VkPipelineCacheCreateInfo pipelineCache;
  1562.     VkPipelineVertexInputStateCreateInfo vi;
  1563.     VkPipelineInputAssemblyStateCreateInfo ia;
  1564.     VkPipelineRasterizationStateCreateInfo rs;
  1565.     VkPipelineColorBlendStateCreateInfo cb;
  1566.     VkPipelineDepthStencilStateCreateInfo ds;
  1567.     VkPipelineViewportStateCreateInfo vp;
  1568.     VkPipelineMultisampleStateCreateInfo ms;
  1569.     VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
  1570.     VkPipelineDynamicStateCreateInfo dynamicState;
  1571.     VkResult U_ASSERT_ONLY err;
  1572.  
  1573.     memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
  1574.     memset(&dynamicState, 0, sizeof dynamicState);
  1575.     dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  1576.     dynamicState.pDynamicStates = dynamicStateEnables;
  1577.  
  1578.     memset(&pipeline, 0, sizeof(pipeline));
  1579.     pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  1580.     pipeline.layout = demo->pipeline_layout;
  1581.  
  1582.     memset(&vi, 0, sizeof(vi));
  1583.     vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  1584.  
  1585.     memset(&ia, 0, sizeof(ia));
  1586.     ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  1587.     ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  1588.  
  1589.     memset(&rs, 0, sizeof(rs));
  1590.     rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  1591.     rs.polygonMode = VK_POLYGON_MODE_FILL;
  1592.     rs.cullMode = VK_CULL_MODE_BACK_BIT;
  1593.     rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
  1594.     rs.depthClampEnable = VK_FALSE;
  1595.     rs.rasterizerDiscardEnable = VK_FALSE;
  1596.     rs.depthBiasEnable = VK_FALSE;
  1597.     rs.lineWidth = 1.0f;
  1598.  
  1599.     memset(&cb, 0, sizeof(cb));
  1600.     cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  1601.     VkPipelineColorBlendAttachmentState att_state[1];
  1602.     memset(att_state, 0, sizeof(att_state));
  1603.     att_state[0].colorWriteMask = 0xf;
  1604.     att_state[0].blendEnable = VK_FALSE;
  1605.     cb.attachmentCount = 1;
  1606.     cb.pAttachments = att_state;
  1607.  
  1608.     memset(&vp, 0, sizeof(vp));
  1609.     vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  1610.     vp.viewportCount = 1;
  1611.     dynamicStateEnables[dynamicState.dynamicStateCount++] =
  1612.         VK_DYNAMIC_STATE_VIEWPORT;
  1613.     vp.scissorCount = 1;
  1614.     dynamicStateEnables[dynamicState.dynamicStateCount++] =
  1615.         VK_DYNAMIC_STATE_SCISSOR;
  1616.  
  1617.     memset(&ds, 0, sizeof(ds));
  1618.     ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  1619.     ds.depthTestEnable = VK_TRUE;
  1620.     ds.depthWriteEnable = VK_TRUE;
  1621.     ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
  1622.     ds.depthBoundsTestEnable = VK_FALSE;
  1623.     ds.back.failOp = VK_STENCIL_OP_KEEP;
  1624.     ds.back.passOp = VK_STENCIL_OP_KEEP;
  1625.     ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
  1626.     ds.stencilTestEnable = VK_FALSE;
  1627.     ds.front = ds.back;
  1628.  
  1629.     memset(&ms, 0, sizeof(ms));
  1630.     ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  1631.     ms.pSampleMask = NULL;
  1632.     ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  1633.  
  1634.     // Two stages: vs and fs
  1635.     pipeline.stageCount = 2;
  1636.     VkPipelineShaderStageCreateInfo shaderStages[2];
  1637.     memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
  1638.  
  1639.     shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  1640.     shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
  1641.     shaderStages[0].module = demo_prepare_vs(demo);
  1642.     shaderStages[0].pName = "main";
  1643.  
  1644.     shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  1645.     shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  1646.     shaderStages[1].module = demo_prepare_fs(demo);
  1647.     shaderStages[1].pName = "main";
  1648.  
  1649.     memset(&pipelineCache, 0, sizeof(pipelineCache));
  1650.     pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
  1651.  
  1652.     err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL,
  1653.                                 &demo->pipelineCache);
  1654.     assert(!err);
  1655.  
  1656.     pipeline.pVertexInputState = &vi;
  1657.     pipeline.pInputAssemblyState = &ia;
  1658.     pipeline.pRasterizationState = &rs;
  1659.     pipeline.pColorBlendState = &cb;
  1660.     pipeline.pMultisampleState = &ms;
  1661.     pipeline.pViewportState = &vp;
  1662.     pipeline.pDepthStencilState = &ds;
  1663.     pipeline.pStages = shaderStages;
  1664.     pipeline.renderPass = demo->render_pass;
  1665.     pipeline.pDynamicState = &dynamicState;
  1666.  
  1667.     pipeline.renderPass = demo->render_pass;
  1668.  
  1669.     err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1,
  1670.                                     &pipeline, NULL, &demo->pipeline);
  1671.     assert(!err);
  1672.  
  1673.     vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
  1674.     vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
  1675. }
  1676.  
  1677. static void demo_prepare_descriptor_pool(struct demo *demo) {
  1678.     const VkDescriptorPoolSize type_counts[2] = {
  1679.             [0] =
  1680.                 {
  1681.                  .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
  1682.                  .descriptorCount = 1,
  1683.                 },
  1684.             [1] =
  1685.                 {
  1686.                  .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
  1687.                  .descriptorCount = DEMO_TEXTURE_COUNT,
  1688.                 },
  1689.     };
  1690.     const VkDescriptorPoolCreateInfo descriptor_pool = {
  1691.         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
  1692.         .pNext = NULL,
  1693.         .maxSets = 1,
  1694.         .poolSizeCount = 2,
  1695.         .pPoolSizes = type_counts,
  1696.     };
  1697.     VkResult U_ASSERT_ONLY err;
  1698.  
  1699.     err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL,
  1700.                                  &demo->desc_pool);
  1701.     assert(!err);
  1702. }
  1703.  
  1704. static void demo_prepare_descriptor_set(struct demo *demo) {
  1705.     VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
  1706.     VkWriteDescriptorSet writes[2];
  1707.     VkResult U_ASSERT_ONLY err;
  1708.     uint32_t i;
  1709.  
  1710.     VkDescriptorSetAllocateInfo alloc_info = {
  1711.         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
  1712.         .pNext = NULL,
  1713.         .descriptorPool = demo->desc_pool,
  1714.         .descriptorSetCount = 1,
  1715.         .pSetLayouts = &demo->desc_layout};
  1716.     err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->desc_set);
  1717.     assert(!err);
  1718.  
  1719.     memset(&tex_descs, 0, sizeof(tex_descs));
  1720.     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
  1721.         tex_descs[i].sampler = demo->textures[i].sampler;
  1722.         tex_descs[i].imageView = demo->textures[i].view;
  1723.         tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL;
  1724.     }
  1725.  
  1726.     memset(&writes, 0, sizeof(writes));
  1727.  
  1728.     writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  1729.     writes[0].dstSet = demo->desc_set;
  1730.     writes[0].descriptorCount = 1;
  1731.     writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  1732.     writes[0].pBufferInfo = &demo->uniform_data.buffer_info;
  1733.  
  1734.     writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  1735.     writes[1].dstSet = demo->desc_set;
  1736.     writes[1].dstBinding = 1;
  1737.     writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
  1738.     writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  1739.     writes[1].pImageInfo = tex_descs;
  1740.  
  1741.     vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
  1742. }
  1743.  
  1744. static void demo_prepare_framebuffers(struct demo *demo) {
  1745.     VkImageView attachments[2];
  1746.     attachments[1] = demo->depth.view;
  1747.  
  1748.     const VkFramebufferCreateInfo fb_info = {
  1749.         .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
  1750.         .pNext = NULL,
  1751.         .renderPass = demo->render_pass,
  1752.         .attachmentCount = 2,
  1753.         .pAttachments = attachments,
  1754.         .width = demo->width,
  1755.         .height = demo->height,
  1756.         .layers = 1,
  1757.     };
  1758.     VkResult U_ASSERT_ONLY err;
  1759.     uint32_t i;
  1760.  
  1761.     demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount *
  1762.                                                  sizeof(VkFramebuffer));
  1763.     assert(demo->framebuffers);
  1764.  
  1765.     for (i = 0; i < demo->swapchainImageCount; i++) {
  1766.         attachments[0] = demo->buffers[i].view;
  1767.         err = vkCreateFramebuffer(demo->device, &fb_info, NULL,
  1768.                                   &demo->framebuffers[i]);
  1769.         assert(!err);
  1770.     }
  1771. }
  1772.  
  1773. static void demo_prepare(struct demo *demo) {
  1774.     VkResult U_ASSERT_ONLY err;
  1775.  
  1776.     const VkCommandPoolCreateInfo cmd_pool_info = {
  1777.         .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
  1778.         .pNext = NULL,
  1779.         .queueFamilyIndex = demo->graphics_queue_node_index,
  1780.         .flags = 0,
  1781.     };
  1782.     err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL,
  1783.                               &demo->cmd_pool);
  1784.     assert(!err);
  1785.  
  1786.     const VkCommandBufferAllocateInfo cmd = {
  1787.         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
  1788.         .pNext = NULL,
  1789.         .commandPool = demo->cmd_pool,
  1790.         .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
  1791.         .commandBufferCount = 1,
  1792.     };
  1793.  
  1794.     demo_prepare_buffers(demo);
  1795.     demo_prepare_depth(demo);
  1796.     demo_prepare_textures(demo);
  1797.     demo_prepare_cube_data_buffer(demo);
  1798.  
  1799.     demo_prepare_descriptor_layout(demo);
  1800.     demo_prepare_render_pass(demo);
  1801.     demo_prepare_pipeline(demo);
  1802.  
  1803.     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
  1804.         err =
  1805.             vkAllocateCommandBuffers(demo->device, &cmd, &demo->buffers[i].cmd);
  1806.         assert(!err);
  1807.     }
  1808.  
  1809.     demo_prepare_descriptor_pool(demo);
  1810.     demo_prepare_descriptor_set(demo);
  1811.  
  1812.     demo_prepare_framebuffers(demo);
  1813.  
  1814.     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
  1815.         demo->current_buffer = i;
  1816.         demo_draw_build_cmd(demo, demo->buffers[i].cmd);
  1817.     }
  1818.  
  1819.     /*
  1820.      * Prepare functions above may generate pipeline commands
  1821.      * that need to be flushed before beginning the render loop.
  1822.      */
  1823.     demo_flush_init_cmd(demo);
  1824.  
  1825.     demo->current_buffer = 0;
  1826.     demo->prepared = true;
  1827. }
  1828.  
  1829. static void demo_cleanup(struct demo *demo) {
  1830.     uint32_t i;
  1831.  
  1832.     demo->prepared = false;
  1833.  
  1834.     for (i = 0; i < demo->swapchainImageCount; i++) {
  1835.         vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL);
  1836.     }
  1837.     free(demo->framebuffers);
  1838.     vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
  1839.  
  1840.     vkDestroyPipeline(demo->device, demo->pipeline, NULL);
  1841.     vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
  1842.     vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
  1843.     vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
  1844.     vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
  1845.  
  1846.     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
  1847.         vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
  1848.         vkDestroyImage(demo->device, demo->textures[i].image, NULL);
  1849.         vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
  1850.         vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
  1851.     }
  1852.     demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
  1853.  
  1854.     vkDestroyImageView(demo->device, demo->depth.view, NULL);
  1855.     vkDestroyImage(demo->device, demo->depth.image, NULL);
  1856.     vkFreeMemory(demo->device, demo->depth.mem, NULL);
  1857.  
  1858.     vkDestroyBuffer(demo->device, demo->uniform_data.buf, NULL);
  1859.     vkFreeMemory(demo->device, demo->uniform_data.mem, NULL);
  1860.  
  1861.     for (i = 0; i < demo->swapchainImageCount; i++) {
  1862.         vkDestroyImageView(demo->device, demo->buffers[i].view, NULL);
  1863.         vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1,
  1864.                              &demo->buffers[i].cmd);
  1865.     }
  1866.     free(demo->buffers);
  1867.  
  1868.     free(demo->queue_props);
  1869.  
  1870.     vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
  1871.     vkDestroyDevice(demo->device, NULL);
  1872.     if (demo->validate) {
  1873.         demo->DestroyDebugReportCallback(demo->inst, demo->msg_callback, NULL);
  1874.     }
  1875.     vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
  1876.     vkDestroyInstance(demo->inst, NULL);
  1877.  
  1878. #ifndef _WIN32
  1879.     if (demo->use_xlib) {
  1880.         XDestroyWindow(demo->display, demo->xlib_window);
  1881.         XCloseDisplay(demo->display);
  1882.     } else {
  1883.         xcb_destroy_window(demo->connection, demo->xcb_window);
  1884.         xcb_disconnect(demo->connection);
  1885.     }
  1886.     free(demo->atom_wm_delete_window);
  1887. #endif // _WIN32
  1888.  
  1889. }
  1890.  
  1891. static void demo_resize(struct demo *demo) {
  1892.     uint32_t i;
  1893.  
  1894.     // Don't react to resize until after first initialization.
  1895.     if (!demo->prepared) {
  1896.         return;
  1897.     }
  1898.     // In order to properly resize the window, we must re-create the swapchain
  1899.     // AND redo the command buffers, etc.
  1900.     //
  1901.     // First, perform part of the demo_cleanup() function:
  1902.     demo->prepared = false;
  1903.  
  1904.     for (i = 0; i < demo->swapchainImageCount; i++) {
  1905.         vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL);
  1906.     }
  1907.     free(demo->framebuffers);
  1908.     vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
  1909.  
  1910.     vkDestroyPipeline(demo->device, demo->pipeline, NULL);
  1911.     vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
  1912.     vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
  1913.     vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
  1914.     vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
  1915.  
  1916.     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
  1917.         vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
  1918.         vkDestroyImage(demo->device, demo->textures[i].image, NULL);
  1919.         vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
  1920.         vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
  1921.     }
  1922.  
  1923.     vkDestroyImageView(demo->device, demo->depth.view, NULL);
  1924.     vkDestroyImage(demo->device, demo->depth.image, NULL);
  1925.     vkFreeMemory(demo->device, demo->depth.mem, NULL);
  1926.  
  1927.     vkDestroyBuffer(demo->device, demo->uniform_data.buf, NULL);
  1928.     vkFreeMemory(demo->device, demo->uniform_data.mem, NULL);
  1929.  
  1930.     for (i = 0; i < demo->swapchainImageCount; i++) {
  1931.         vkDestroyImageView(demo->device, demo->buffers[i].view, NULL);
  1932.         vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1,
  1933.                              &demo->buffers[i].cmd);
  1934.     }
  1935.     vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
  1936.     free(demo->buffers);
  1937.  
  1938.     // Second, re-perform the demo_prepare() function, which will re-create the
  1939.     // swapchain:
  1940.     demo_prepare(demo);
  1941. }
  1942.  
  1943. // On MS-Windows, make this a global, so it's available to WndProc()
  1944. struct demo demo;
  1945.  
  1946. #ifdef _WIN32
  1947. static void demo_run(struct demo *demo) {
  1948.     if (!demo->prepared)
  1949.         return;
  1950.     // Wait for work to finish before updating MVP.
  1951.     vkDeviceWaitIdle(demo->device);
  1952.     demo_update_data_buffer(demo);
  1953.  
  1954.     demo_draw(demo);
  1955.  
  1956.     // Wait for work to finish before updating MVP.
  1957.     vkDeviceWaitIdle(demo->device);
  1958.  
  1959.     demo->curFrame++;
  1960.     if (demo->frameCount != INT_MAX && demo->curFrame == demo->frameCount) {
  1961.         PostQuitMessage(validation_error);
  1962.     }
  1963. }
  1964.  
  1965. // MS-Windows event handling function:
  1966. LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  1967.     switch (uMsg) {
  1968.     case WM_CLOSE:
  1969.         PostQuitMessage(validation_error);
  1970.         break;
  1971.     case WM_PAINT:
  1972.         demo_run(&demo);
  1973.         break;
  1974.     case WM_SIZE:
  1975.         // Resize the application to the new window size, except when
  1976.         // it was minimized. Vulkan doesn't support images or swapchains
  1977.         // with width=0 and height=0.
  1978.         if (wParam != SIZE_MINIMIZED) {
  1979.             demo.width = lParam & 0xffff;
  1980.             demo.height = lParam & 0xffff0000 >> 16;
  1981.             demo_resize(&demo);
  1982.         }
  1983.         break;
  1984.     default:
  1985.         break;
  1986.     }
  1987.     return (DefWindowProc(hWnd, uMsg, wParam, lParam));
  1988. }
  1989.  
  1990. static void demo_create_window(struct demo *demo) {
  1991.     WNDCLASSEX win_class;
  1992.  
  1993.     // Initialize the window class structure:
  1994.     win_class.cbSize = sizeof(WNDCLASSEX);
  1995.     win_class.style = CS_HREDRAW | CS_VREDRAW;
  1996.     win_class.lpfnWndProc = WndProc;
  1997.     win_class.cbClsExtra = 0;
  1998.     win_class.cbWndExtra = 0;
  1999.     win_class.hInstance = demo->connection; // hInstance
  2000.     win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  2001.     win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
  2002.     win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
  2003.     win_class.lpszMenuName = NULL;
  2004.     win_class.lpszClassName = demo->name;
  2005.     win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
  2006.     // Register window class:
  2007.     if (!RegisterClassEx(&win_class)) {
  2008.         // It didn't work, so try to give a useful error:
  2009.         printf("Unexpected error trying to start the application!\n");
  2010.         fflush(stdout);
  2011.         exit(1);
  2012.     }
  2013.     // Create window with the registered class:
  2014.     RECT wr = {0, 0, demo->width, demo->height};
  2015.     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
  2016.     demo->window = CreateWindowEx(0,
  2017.                                   demo->name,           // class name
  2018.                                   demo->name,           // app name
  2019.                                   WS_OVERLAPPEDWINDOW | // window style
  2020.                                       WS_VISIBLE | WS_SYSMENU,
  2021.                                   100, 100,           // x/y coords
  2022.                                   wr.right - wr.left, // width
  2023.                                   wr.bottom - wr.top, // height
  2024.                                   NULL,               // handle to parent
  2025.                                   NULL,               // handle to menu
  2026.                                   demo->connection,   // hInstance
  2027.                                   NULL);              // no extra parameters
  2028.     if (!demo->window) {
  2029.         // It didn't work, so try to give a useful error:
  2030.         printf("Cannot create a window in which to draw!\n");
  2031.         fflush(stdout);
  2032.         exit(1);
  2033.     }
  2034. }
  2035. #else
  2036. static void demo_create_xlib_window(struct demo *demo) {
  2037.  
  2038.     demo->display = XOpenDisplay(NULL);
  2039.     long visualMask = VisualScreenMask;
  2040.     int numberOfVisuals;
  2041.     XVisualInfo vInfoTemplate;
  2042.     vInfoTemplate.screen = DefaultScreen(demo->display);
  2043.     XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask,
  2044.                                              &vInfoTemplate, &numberOfVisuals);
  2045.  
  2046.     Colormap colormap = XCreateColormap(
  2047.                 demo->display, RootWindow(demo->display, vInfoTemplate.screen),
  2048.                 visualInfo->visual, AllocNone);
  2049.  
  2050.     XSetWindowAttributes windowAttributes;
  2051.     windowAttributes.colormap = colormap;
  2052.     windowAttributes.background_pixel = 0xFFFFFFFF;
  2053.     windowAttributes.border_pixel = 0;
  2054.     windowAttributes.event_mask =
  2055.             KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
  2056.  
  2057.     demo->xlib_window = XCreateWindow(
  2058.                 demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0,
  2059.                 demo->width, demo->height, 0, visualInfo->depth, InputOutput,
  2060.                 visualInfo->visual,
  2061.                 CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
  2062.  
  2063.     XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
  2064.     XMapWindow(demo->display, demo->xlib_window);
  2065.     XFlush(demo->display);
  2066.     demo->xlib_wm_delete_window =
  2067.             XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
  2068. }
  2069. static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
  2070.     switch(event->type) {
  2071.     case ClientMessage:
  2072.         if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window)
  2073.             demo->quit = true;
  2074.         break;
  2075.     case KeyPress:
  2076.         switch (event->xkey.keycode) {
  2077.         case 0x9: // Escape
  2078.             demo->quit = true;
  2079.             break;
  2080.         case 0x71: // left arrow key
  2081.             demo->spin_angle += demo->spin_increment;
  2082.             break;
  2083.         case 0x72: // right arrow key
  2084.             demo->spin_angle -= demo->spin_increment;
  2085.             break;
  2086.         case 0x41:
  2087.             demo->pause = !demo->pause;
  2088.             break;
  2089.         }
  2090.         break;
  2091.     case ConfigureNotify:
  2092.         if ((demo->width != event->xconfigure.width) ||
  2093.             (demo->height != event->xconfigure.height)) {
  2094.             demo->width = event->xconfigure.width;
  2095.             demo->height = event->xconfigure.height;
  2096.             demo_resize(demo);
  2097.         }
  2098.         break;
  2099.     default:
  2100.         break;
  2101.     }
  2102.  
  2103. }
  2104.  
  2105. static void demo_run_xlib(struct demo *demo) {
  2106.  
  2107.     while (!demo->quit) {
  2108.         XEvent event;
  2109.  
  2110.         if (demo->pause) {
  2111.             XNextEvent(demo->display, &event);
  2112.             demo_handle_xlib_event(demo, &event);
  2113.         } else {
  2114.             while (XPending(demo->display) > 0) {
  2115.                 XNextEvent(demo->display, &event);
  2116.                 demo_handle_xlib_event(demo, &event);
  2117.             }
  2118.         }
  2119.  
  2120.         // Wait for work to finish before updating MVP.
  2121.         vkDeviceWaitIdle(demo->device);
  2122.         demo_update_data_buffer(demo);
  2123.  
  2124.         demo_draw(demo);
  2125.  
  2126.         // Wait for work to finish before updating MVP.
  2127.         vkDeviceWaitIdle(demo->device);
  2128.         demo->curFrame++;
  2129.         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount)
  2130.             demo->quit = true;
  2131.     }
  2132. }
  2133.  
  2134. static void demo_handle_xcb_event(struct demo *demo,
  2135.                               const xcb_generic_event_t *event) {
  2136.     uint8_t event_code = event->response_type & 0x7f;
  2137.     switch (event_code) {
  2138.     case XCB_EXPOSE:
  2139.         // TODO: Resize window
  2140.         break;
  2141.     case XCB_CLIENT_MESSAGE:
  2142.         if ((*(xcb_client_message_event_t *)event).data.data32[0] ==
  2143.             (*demo->atom_wm_delete_window).atom) {
  2144.             demo->quit = true;
  2145.         }
  2146.         break;
  2147.     case XCB_KEY_RELEASE: {
  2148.         const xcb_key_release_event_t *key =
  2149.             (const xcb_key_release_event_t *)event;
  2150.  
  2151.         switch (key->detail) {
  2152.         case 0x9: // Escape
  2153.             demo->quit = true;
  2154.             break;
  2155.         case 0x71: // left arrow key
  2156.             demo->spin_angle += demo->spin_increment;
  2157.             break;
  2158.         case 0x72: // right arrow key
  2159.             demo->spin_angle -= demo->spin_increment;
  2160.             break;
  2161.         case 0x41:
  2162.             demo->pause = !demo->pause;
  2163.             break;
  2164.         }
  2165.     } break;
  2166.     case XCB_CONFIGURE_NOTIFY: {
  2167.         const xcb_configure_notify_event_t *cfg =
  2168.             (const xcb_configure_notify_event_t *)event;
  2169.         if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
  2170.             demo->width = cfg->width;
  2171.             demo->height = cfg->height;
  2172.             demo_resize(demo);
  2173.         }
  2174.     } break;
  2175.     default:
  2176.         break;
  2177.     }
  2178. }
  2179.  
  2180. static void demo_run_xcb(struct demo *demo) {
  2181.     xcb_flush(demo->connection);
  2182.  
  2183.     while (!demo->quit) {
  2184.         xcb_generic_event_t *event;
  2185.  
  2186.         if (demo->pause) {
  2187.             event = xcb_wait_for_event(demo->connection);
  2188.         } else {
  2189.             event = xcb_poll_for_event(demo->connection);
  2190.         }
  2191.         if (event) {
  2192.             demo_handle_xcb_event(demo, event);
  2193.             free(event);
  2194.         }
  2195.  
  2196.         // Wait for work to finish before updating MVP.
  2197.         vkDeviceWaitIdle(demo->device);
  2198.         demo_update_data_buffer(demo);
  2199.  
  2200.         demo_draw(demo);
  2201.  
  2202.         // Wait for work to finish before updating MVP.
  2203.         vkDeviceWaitIdle(demo->device);
  2204.         demo->curFrame++;
  2205.         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount)
  2206.             demo->quit = true;
  2207.     }
  2208. }
  2209.  
  2210. static void demo_create_xcb_window(struct demo *demo) {
  2211.     uint32_t value_mask, value_list[32];
  2212.  
  2213.     demo->xcb_window = xcb_generate_id(demo->connection);
  2214.  
  2215.     value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
  2216.     value_list[0] = demo->screen->black_pixel;
  2217.     value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE |
  2218.                     XCB_EVENT_MASK_STRUCTURE_NOTIFY;
  2219.  
  2220.     xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window,
  2221.                       demo->screen->root, 0, 0, demo->width, demo->height, 0,
  2222.                       XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual,
  2223.                       value_mask, value_list);
  2224.  
  2225.     /* Magic code that will send notification when window is destroyed */
  2226.     xcb_intern_atom_cookie_t cookie =
  2227.         xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
  2228.     xcb_intern_atom_reply_t *reply =
  2229.         xcb_intern_atom_reply(demo->connection, cookie, 0);
  2230.  
  2231.     xcb_intern_atom_cookie_t cookie2 =
  2232.         xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
  2233.     demo->atom_wm_delete_window =
  2234.         xcb_intern_atom_reply(demo->connection, cookie2, 0);
  2235.  
  2236.     xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window,
  2237.                         (*reply).atom, 4, 32, 1,
  2238.                         &(*demo->atom_wm_delete_window).atom);
  2239.     free(reply);
  2240.  
  2241.     xcb_map_window(demo->connection, demo->xcb_window);
  2242.  
  2243.     // Force the x/y coordinates to 100,100 results are identical in consecutive
  2244.     // runs
  2245.     const uint32_t coords[] = {100, 100};
  2246.     xcb_configure_window(demo->connection, demo->xcb_window,
  2247.                          XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
  2248. }
  2249. #endif // _WIN32
  2250.  
  2251. /*
  2252.  * Return 1 (true) if all layer names specified in check_names
  2253.  * can be found in given layer properties.
  2254.  */
  2255. static VkBool32 demo_check_layers(uint32_t check_count, char **check_names,
  2256.                                   uint32_t layer_count,
  2257.                                   VkLayerProperties *layers) {
  2258.     for (uint32_t i = 0; i < check_count; i++) {
  2259.         VkBool32 found = 0;
  2260.         for (uint32_t j = 0; j < layer_count; j++) {
  2261.             if (!strcmp(check_names[i], layers[j].layerName)) {
  2262.                 found = 1;
  2263.                 break;
  2264.             }
  2265.         }
  2266.         if (!found) {
  2267.             fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
  2268.             return 0;
  2269.         }
  2270.     }
  2271.     return 1;
  2272. }
  2273.  
  2274. static void demo_init_vk(struct demo *demo) {
  2275.     VkResult err;
  2276.     uint32_t instance_extension_count = 0;
  2277.     uint32_t instance_layer_count = 0;
  2278.     uint32_t device_validation_layer_count = 0;
  2279.     char **instance_validation_layers = NULL;
  2280.     demo->enabled_extension_count = 0;
  2281.     demo->enabled_layer_count = 0;
  2282.  
  2283.     char *instance_validation_layers_alt1[] = {
  2284.         "VK_LAYER_LUNARG_standard_validation"
  2285.     };
  2286.  
  2287.     char *instance_validation_layers_alt2[] = {
  2288.         "VK_LAYER_GOOGLE_threading",     "VK_LAYER_LUNARG_parameter_validation",
  2289.         "VK_LAYER_LUNARG_device_limits", "VK_LAYER_LUNARG_object_tracker",
  2290.         "VK_LAYER_LUNARG_image",         "VK_LAYER_LUNARG_core_validation",
  2291.         "VK_LAYER_LUNARG_swapchain",     "VK_LAYER_GOOGLE_unique_objects"
  2292.     };
  2293.  
  2294.     /* Look for validation layers */
  2295.     VkBool32 validation_found = 0;
  2296.     if (demo->validate) {
  2297.  
  2298.         err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
  2299.         assert(!err);
  2300.  
  2301.         instance_validation_layers = instance_validation_layers_alt1;
  2302.         if (instance_layer_count > 0) {
  2303.             VkLayerProperties *instance_layers =
  2304.                     malloc(sizeof (VkLayerProperties) * instance_layer_count);
  2305.             err = vkEnumerateInstanceLayerProperties(&instance_layer_count,
  2306.                     instance_layers);
  2307.             assert(!err);
  2308.  
  2309.  
  2310.             validation_found = demo_check_layers(
  2311.                     ARRAY_SIZE(instance_validation_layers_alt1),
  2312.                     instance_validation_layers, instance_layer_count,
  2313.                     instance_layers);
  2314.             if (validation_found) {
  2315.                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
  2316.                 demo->device_validation_layers[0] = "VK_LAYER_LUNARG_standard_validation";
  2317.                 device_validation_layer_count = 1;
  2318.             } else {
  2319.                 // use alternative set of validation layers
  2320.                 instance_validation_layers = instance_validation_layers_alt2;
  2321.                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
  2322.                 validation_found = demo_check_layers(
  2323.                     ARRAY_SIZE(instance_validation_layers_alt2),
  2324.                     instance_validation_layers, instance_layer_count,
  2325.                     instance_layers);
  2326.                 device_validation_layer_count =
  2327.                         ARRAY_SIZE(instance_validation_layers_alt2);
  2328.                 for (uint32_t i = 0; i < device_validation_layer_count; i++) {
  2329.                     demo->device_validation_layers[i] =
  2330.                             instance_validation_layers[i];
  2331.                 }
  2332.             }
  2333.             free(instance_layers);
  2334.         }
  2335.  
  2336.         if (!validation_found) {
  2337.             ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find "
  2338.                     "required validation layer.\n\n"
  2339.                     "Please look at the Getting Started guide for additional "
  2340.                     "information.\n",
  2341.                     "vkCreateInstance Failure");
  2342.         }
  2343.     }
  2344.  
  2345.     /* Look for instance extensions */
  2346.     VkBool32 surfaceExtFound = 0;
  2347.     VkBool32 platformSurfaceExtFound = 0;
  2348.     VkBool32 xlibSurfaceExtFound = 0;
  2349.     memset(demo->extension_names, 0, sizeof(demo->extension_names));
  2350.  
  2351.     err = vkEnumerateInstanceExtensionProperties(
  2352.         NULL, &instance_extension_count, NULL);
  2353.     assert(!err);
  2354.  
  2355.     if (instance_extension_count > 0) {
  2356.         VkExtensionProperties *instance_extensions =
  2357.             malloc(sizeof(VkExtensionProperties) * instance_extension_count);
  2358.         err = vkEnumerateInstanceExtensionProperties(
  2359.             NULL, &instance_extension_count, instance_extensions);
  2360.         assert(!err);
  2361.         for (uint32_t i = 0; i < instance_extension_count; i++) {
  2362.             if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME,
  2363.                         instance_extensions[i].extensionName)) {
  2364.                 surfaceExtFound = 1;
  2365.                 demo->extension_names[demo->enabled_extension_count++] =
  2366.                     VK_KHR_SURFACE_EXTENSION_NAME;
  2367.             }
  2368. #ifdef _WIN32
  2369.             if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME,
  2370.                         instance_extensions[i].extensionName)) {
  2371.                 platformSurfaceExtFound = 1;
  2372.                 demo->extension_names[demo->enabled_extension_count++] =
  2373.                     VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
  2374.             }
  2375. #else  // _WIN32
  2376.             if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
  2377.                         instance_extensions[i].extensionName)) {
  2378.                 platformSurfaceExtFound = 1;
  2379.                 xlibSurfaceExtFound = 1;
  2380.                 demo->extension_names[demo->enabled_extension_count++] =
  2381.                     VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
  2382.             }
  2383.             if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME,
  2384.                         instance_extensions[i].extensionName)) {
  2385.                 platformSurfaceExtFound = 1;
  2386.                 demo->extension_names[demo->enabled_extension_count++] =
  2387.                     VK_KHR_XCB_SURFACE_EXTENSION_NAME;
  2388.             }
  2389. #endif // _WIN32
  2390.             if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME,
  2391.                         instance_extensions[i].extensionName)) {
  2392.                 if (demo->validate) {
  2393.                     demo->extension_names[demo->enabled_extension_count++] =
  2394.                         VK_EXT_DEBUG_REPORT_EXTENSION_NAME;
  2395.                 }
  2396.             }
  2397.             assert(demo->enabled_extension_count < 64);
  2398.         }
  2399.  
  2400.         free(instance_extensions);
  2401.     }
  2402.  
  2403.     if (!surfaceExtFound) {
  2404.         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find "
  2405.                  "the " VK_KHR_SURFACE_EXTENSION_NAME
  2406.                  " extension.\n\nDo you have a compatible "
  2407.                  "Vulkan installable client driver (ICD) installed?\nPlease "
  2408.                  "look at the Getting Started guide for additional "
  2409.                  "information.\n",
  2410.                  "vkCreateInstance Failure");
  2411.     }
  2412.     if (!platformSurfaceExtFound) {
  2413. #ifdef _WIN32
  2414.         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find "
  2415.                  "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
  2416.                  " extension.\n\nDo you have a compatible "
  2417.                  "Vulkan installable client driver (ICD) installed?\nPlease "
  2418.                  "look at the Getting Started guide for additional "
  2419.                  "information.\n",
  2420.                  "vkCreateInstance Failure");
  2421.     }
  2422. #else  // _WIN32
  2423.         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find "
  2424.                  "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
  2425.                  " extension.\n\nDo you have a compatible "
  2426.                  "Vulkan installable client driver (ICD) installed?\nPlease "
  2427.                  "look at the Getting Started guide for additional "
  2428.                  "information.\n",
  2429.                  "vkCreateInstance Failure");
  2430.     }
  2431.     if (demo->use_xlib && !xlibSurfaceExtFound) {
  2432.         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find "
  2433.                  "the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
  2434.                  " extension.\n\nDo you have a compatible "
  2435.                  "Vulkan installable client driver (ICD) installed?\nPlease "
  2436.                  "look at the Getting Started guide for additional "
  2437.                  "information.\n",
  2438.                  "vkCreateInstance Failure");
  2439.     }
  2440. #endif // _WIN32
  2441.     const VkApplicationInfo app = {
  2442.         .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
  2443.         .pNext = NULL,
  2444.         .pApplicationName = APP_SHORT_NAME,
  2445.         .applicationVersion = 0,
  2446.         .pEngineName = APP_SHORT_NAME,
  2447.         .engineVersion = 0,
  2448.         .apiVersion = VK_API_VERSION_1_0,
  2449.     };
  2450.     VkInstanceCreateInfo inst_info = {
  2451.         .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
  2452.         .pNext = NULL,
  2453.         .pApplicationInfo = &app,
  2454.         .enabledLayerCount = demo->enabled_layer_count,
  2455.         .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
  2456.         .enabledExtensionCount = demo->enabled_extension_count,
  2457.         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
  2458.     };
  2459.  
  2460.     /*
  2461.      * This is info for a temp callback to use during CreateInstance.
  2462.      * After the instance is created, we use the instance-based
  2463.      * function to register the final callback.
  2464.      */
  2465.     VkDebugReportCallbackCreateInfoEXT dbgCreateInfo;
  2466.     if (demo->validate) {
  2467.         dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
  2468.         dbgCreateInfo.pNext = NULL;
  2469.         dbgCreateInfo.pfnCallback = demo->use_break ? BreakCallback : dbgFunc;
  2470.         dbgCreateInfo.pUserData = NULL;
  2471.         dbgCreateInfo.flags =
  2472.             VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
  2473.         inst_info.pNext = &dbgCreateInfo;
  2474.     }
  2475.  
  2476.     uint32_t gpu_count;
  2477.  
  2478.     err = vkCreateInstance(&inst_info, NULL, &demo->inst);
  2479.     if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
  2480.         ERR_EXIT("Cannot find a compatible Vulkan installable client driver "
  2481.                  "(ICD).\n\nPlease look at the Getting Started guide for "
  2482.                  "additional information.\n",
  2483.                  "vkCreateInstance Failure");
  2484.     } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
  2485.         ERR_EXIT("Cannot find a specified extension library"
  2486.                  ".\nMake sure your layers path is set appropriately.\n",
  2487.                  "vkCreateInstance Failure");
  2488.     } else if (err) {
  2489.         ERR_EXIT("vkCreateInstance failed.\n\nDo you have a compatible Vulkan "
  2490.                  "installable client driver (ICD) installed?\nPlease look at "
  2491.                  "the Getting Started guide for additional information.\n",
  2492.                  "vkCreateInstance Failure");
  2493.     }
  2494.  
  2495.     /* Make initial call to query gpu_count, then second call for gpu info*/
  2496.     err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
  2497.     assert(!err && gpu_count > 0);
  2498.  
  2499.     if (gpu_count > 0) {
  2500.         VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
  2501.         err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
  2502.         assert(!err);
  2503.         /* For cube demo we just grab the first physical device */
  2504.         demo->gpu = physical_devices[0];
  2505.         free(physical_devices);
  2506.     } else {
  2507.         ERR_EXIT("vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
  2508.                  "Do you have a compatible Vulkan installable client driver (ICD) "
  2509.                  "installed?\nPlease look at the Getting Started guide for "
  2510.                  "additional information.\n",
  2511.                  "vkEnumeratePhysicalDevices Failure");
  2512.     }
  2513.  
  2514.     /* Look for validation layers */
  2515.     validation_found = 0;
  2516.     demo->enabled_layer_count = 0;
  2517.     uint32_t device_layer_count = 0;
  2518.     err =
  2519.         vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL);
  2520.     assert(!err);
  2521.  
  2522.     if (device_layer_count > 0) {
  2523.         VkLayerProperties *device_layers =
  2524.             malloc(sizeof(VkLayerProperties) * device_layer_count);
  2525.         err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count,
  2526.                                                device_layers);
  2527.         assert(!err);
  2528.  
  2529.         if (demo->validate) {
  2530.             validation_found = demo_check_layers(device_validation_layer_count,
  2531.                                                  demo->device_validation_layers,
  2532.                                                  device_layer_count,
  2533.                                                  device_layers);
  2534.             demo->enabled_layer_count = device_validation_layer_count;
  2535.         }
  2536.  
  2537.         free(device_layers);
  2538.     }
  2539.  
  2540.     if (demo->validate && !validation_found) {
  2541.         ERR_EXIT("vkEnumerateDeviceLayerProperties failed to find "
  2542.                  "a required validation layer.\n\n"
  2543.                  "Please look at the Getting Started guide for additional "
  2544.                  "information.\n",
  2545.                  "vkCreateDevice Failure");
  2546.     }
  2547.  
  2548.     /* Look for device extensions */
  2549.     uint32_t device_extension_count = 0;
  2550.     VkBool32 swapchainExtFound = 0;
  2551.     demo->enabled_extension_count = 0;
  2552.     memset(demo->extension_names, 0, sizeof(demo->extension_names));
  2553.  
  2554.     err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL,
  2555.                                                &device_extension_count, NULL);
  2556.     assert(!err);
  2557.  
  2558.     if (device_extension_count > 0) {
  2559.         VkExtensionProperties *device_extensions =
  2560.             malloc(sizeof(VkExtensionProperties) * device_extension_count);
  2561.         err = vkEnumerateDeviceExtensionProperties(
  2562.             demo->gpu, NULL, &device_extension_count, device_extensions);
  2563.         assert(!err);
  2564.  
  2565.         for (uint32_t i = 0; i < device_extension_count; i++) {
  2566.             if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME,
  2567.                         device_extensions[i].extensionName)) {
  2568.                 swapchainExtFound = 1;
  2569.                 demo->extension_names[demo->enabled_extension_count++] =
  2570.                     VK_KHR_SWAPCHAIN_EXTENSION_NAME;
  2571.             }
  2572.             assert(demo->enabled_extension_count < 64);
  2573.         }
  2574.  
  2575.         free(device_extensions);
  2576.     }
  2577.  
  2578.     if (!swapchainExtFound) {
  2579.         ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find "
  2580.                  "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
  2581.                  " extension.\n\nDo you have a compatible "
  2582.                  "Vulkan installable client driver (ICD) installed?\nPlease "
  2583.                  "look at the Getting Started guide for additional "
  2584.                  "information.\n",
  2585.                  "vkCreateInstance Failure");
  2586.     }
  2587.  
  2588.     if (demo->validate) {
  2589.         demo->CreateDebugReportCallback =
  2590.             (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(
  2591.                 demo->inst, "vkCreateDebugReportCallbackEXT");
  2592.         demo->DestroyDebugReportCallback =
  2593.             (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(
  2594.                 demo->inst, "vkDestroyDebugReportCallbackEXT");
  2595.         if (!demo->CreateDebugReportCallback) {
  2596.             ERR_EXIT(
  2597.                 "GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n",
  2598.                 "vkGetProcAddr Failure");
  2599.         }
  2600.         if (!demo->DestroyDebugReportCallback) {
  2601.             ERR_EXIT(
  2602.                 "GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n",
  2603.                 "vkGetProcAddr Failure");
  2604.         }
  2605.         demo->DebugReportMessage =
  2606.             (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(
  2607.                 demo->inst, "vkDebugReportMessageEXT");
  2608.         if (!demo->DebugReportMessage) {
  2609.             ERR_EXIT("GetProcAddr: Unable to find vkDebugReportMessageEXT\n",
  2610.                      "vkGetProcAddr Failure");
  2611.         }
  2612.  
  2613.         VkDebugReportCallbackCreateInfoEXT dbgCreateInfo;
  2614.         PFN_vkDebugReportCallbackEXT callback;
  2615.         callback = demo->use_break ? BreakCallback : dbgFunc;
  2616.         dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
  2617.         dbgCreateInfo.pNext = NULL;
  2618.         dbgCreateInfo.pfnCallback = callback;
  2619.         dbgCreateInfo.pUserData = NULL;
  2620.         dbgCreateInfo.flags =
  2621.             VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
  2622.         err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL,
  2623.                                               &demo->msg_callback);
  2624.         switch (err) {
  2625.         case VK_SUCCESS:
  2626.             break;
  2627.         case VK_ERROR_OUT_OF_HOST_MEMORY:
  2628.             ERR_EXIT("CreateDebugReportCallback: out of host memory\n",
  2629.                      "CreateDebugReportCallback Failure");
  2630.             break;
  2631.         default:
  2632.             ERR_EXIT("CreateDebugReportCallback: unknown failure\n",
  2633.                      "CreateDebugReportCallback Failure");
  2634.             break;
  2635.         }
  2636.     }
  2637.     vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
  2638.  
  2639.     /* Call with NULL data to get count */
  2640.     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count,
  2641.                                              NULL);
  2642.     assert(demo->queue_count >= 1);
  2643.  
  2644.     demo->queue_props = (VkQueueFamilyProperties *)malloc(
  2645.         demo->queue_count * sizeof(VkQueueFamilyProperties));
  2646.     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count,
  2647.                                              demo->queue_props);
  2648.     // Find a queue that supports gfx
  2649.     uint32_t gfx_queue_idx = 0;
  2650.     for (gfx_queue_idx = 0; gfx_queue_idx < demo->queue_count;
  2651.          gfx_queue_idx++) {
  2652.         if (demo->queue_props[gfx_queue_idx].queueFlags & VK_QUEUE_GRAPHICS_BIT)
  2653.             break;
  2654.     }
  2655.     assert(gfx_queue_idx < demo->queue_count);
  2656.     // Query fine-grained feature support for this device.
  2657.     //  If app has specific feature requirements it should check supported
  2658.     //  features based on this query
  2659.     VkPhysicalDeviceFeatures physDevFeatures;
  2660.     vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
  2661.  
  2662.     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
  2663.     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
  2664.     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
  2665.     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
  2666.     GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
  2667. }
  2668.  
  2669. static void demo_create_device(struct demo *demo) {
  2670.     VkResult U_ASSERT_ONLY err;
  2671.     float queue_priorities[1] = {0.0};
  2672.     const VkDeviceQueueCreateInfo queue = {
  2673.         .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
  2674.         .pNext = NULL,
  2675.         .queueFamilyIndex = demo->graphics_queue_node_index,
  2676.         .queueCount = 1,
  2677.         .pQueuePriorities = queue_priorities};
  2678.  
  2679.     VkDeviceCreateInfo device = {
  2680.         .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
  2681.         .pNext = NULL,
  2682.         .queueCreateInfoCount = 1,
  2683.         .pQueueCreateInfos = &queue,
  2684.         .enabledLayerCount = demo->enabled_layer_count,
  2685.         .ppEnabledLayerNames =
  2686.             (const char *const *)((demo->validate)
  2687.                                       ? demo->device_validation_layers
  2688.                                       : NULL),
  2689.         .enabledExtensionCount = demo->enabled_extension_count,
  2690.         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
  2691.         .pEnabledFeatures =
  2692.             NULL, // If specific features are required, pass them in here
  2693.     };
  2694.  
  2695.     err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
  2696.     assert(!err);
  2697. }
  2698.  
  2699. static void demo_init_vk_swapchain(struct demo *demo) {
  2700.     VkResult U_ASSERT_ONLY err;
  2701.     uint32_t i;
  2702.  
  2703. // Create a WSI surface for the window:
  2704. #ifdef _WIN32
  2705.     VkWin32SurfaceCreateInfoKHR createInfo;
  2706.     createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
  2707.     createInfo.pNext = NULL;
  2708.     createInfo.flags = 0;
  2709.     createInfo.hinstance = demo->connection;
  2710.     createInfo.hwnd = demo->window;
  2711.  
  2712.     err =
  2713.         vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
  2714. #else
  2715.  
  2716.     if (demo->use_xlib) {
  2717.         VkXlibSurfaceCreateInfoKHR createInfo;
  2718.         createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
  2719.         createInfo.pNext = NULL;
  2720.         createInfo.flags = 0;
  2721.         createInfo.dpy = demo->display;
  2722.         createInfo.window = demo->xlib_window;
  2723.  
  2724.         err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL,
  2725.                                      &demo->surface);
  2726.     }
  2727.     else {
  2728.         VkXcbSurfaceCreateInfoKHR createInfo;
  2729.         createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
  2730.         createInfo.pNext = NULL;
  2731.         createInfo.flags = 0;
  2732.         createInfo.connection = demo->connection;
  2733.         createInfo.window = demo->xcb_window;
  2734.  
  2735.         err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
  2736.     }
  2737. #endif // _WIN32
  2738.     assert(!err);
  2739.  
  2740.     // Iterate over each queue to learn whether it supports presenting:
  2741.     VkBool32 *supportsPresent =
  2742.         (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32));
  2743.     for (i = 0; i < demo->queue_count; i++) {
  2744.         demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface,
  2745.                                                    &supportsPresent[i]);
  2746.     }
  2747.  
  2748.     // Search for a graphics and a present queue in the array of queue
  2749.     // families, try to find one that supports both
  2750.     uint32_t graphicsQueueNodeIndex = UINT32_MAX;
  2751.     uint32_t presentQueueNodeIndex = UINT32_MAX;
  2752.     for (i = 0; i < demo->queue_count; i++) {
  2753.         if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
  2754.             if (graphicsQueueNodeIndex == UINT32_MAX) {
  2755.                 graphicsQueueNodeIndex = i;
  2756.             }
  2757.  
  2758.             if (supportsPresent[i] == VK_TRUE) {
  2759.                 graphicsQueueNodeIndex = i;
  2760.                 presentQueueNodeIndex = i;
  2761.                 break;
  2762.             }
  2763.         }
  2764.     }
  2765.     if (presentQueueNodeIndex == UINT32_MAX) {
  2766.         // If didn't find a queue that supports both graphics and present, then
  2767.         // find a separate present queue.
  2768.         for (uint32_t i = 0; i < demo->queue_count; ++i) {
  2769.             if (supportsPresent[i] == VK_TRUE) {
  2770.                 presentQueueNodeIndex = i;
  2771.                 break;
  2772.             }
  2773.         }
  2774.     }
  2775.     free(supportsPresent);
  2776.  
  2777.     // Generate error if could not find both a graphics and a present queue
  2778.     if (graphicsQueueNodeIndex == UINT32_MAX ||
  2779.         presentQueueNodeIndex == UINT32_MAX) {
  2780.         ERR_EXIT("Could not find a graphics and a present queue\n",
  2781.                  "Swapchain Initialization Failure");
  2782.     }
  2783.  
  2784.     // TODO: Add support for separate queues, including presentation,
  2785.     //       synchronization, and appropriate tracking for QueueSubmit.
  2786.     // NOTE: While it is possible for an application to use a separate graphics
  2787.     //       and a present queues, this demo program assumes it is only using
  2788.     //       one:
  2789.     if (graphicsQueueNodeIndex != presentQueueNodeIndex) {
  2790.         ERR_EXIT("Could not find a common graphics and a present queue\n",
  2791.                  "Swapchain Initialization Failure");
  2792.     }
  2793.  
  2794.     demo->graphics_queue_node_index = graphicsQueueNodeIndex;
  2795.  
  2796.     demo_create_device(demo);
  2797.  
  2798.     GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
  2799.     GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
  2800.     GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
  2801.     GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
  2802.     GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
  2803.  
  2804.     vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, 0,
  2805.                      &demo->queue);
  2806.  
  2807.     // Get the list of VkFormat's that are supported:
  2808.     uint32_t formatCount;
  2809.     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface,
  2810.                                                      &formatCount, NULL);
  2811.     assert(!err);
  2812.     VkSurfaceFormatKHR *surfFormats =
  2813.         (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
  2814.     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface,
  2815.                                                      &formatCount, surfFormats);
  2816.     assert(!err);
  2817.     // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
  2818.     // the surface has no preferred format.  Otherwise, at least one
  2819.     // supported format will be returned.
  2820.     if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
  2821.         demo->format = VK_FORMAT_B8G8R8A8_UNORM;
  2822.     } else {
  2823.         assert(formatCount >= 1);
  2824.         demo->format = surfFormats[0].format;
  2825.     }
  2826.     demo->color_space = surfFormats[0].colorSpace;
  2827.  
  2828.     demo->quit = false;
  2829.     demo->curFrame = 0;
  2830.  
  2831.     // Get Memory information and properties
  2832.     vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
  2833. }
  2834.  
  2835. static void demo_init_connection(struct demo *demo) {
  2836. #ifndef _WIN32
  2837.     const xcb_setup_t *setup;
  2838.     xcb_screen_iterator_t iter;
  2839.     int scr;
  2840.  
  2841.     demo->connection = xcb_connect(NULL, &scr);
  2842.     if (demo->connection == NULL) {
  2843.         printf("Cannot find a compatible Vulkan installable client driver "
  2844.                "(ICD).\nExiting ...\n");
  2845.         fflush(stdout);
  2846.         exit(1);
  2847.     }
  2848.  
  2849.     setup = xcb_get_setup(demo->connection);
  2850.     iter = xcb_setup_roots_iterator(setup);
  2851.     while (scr-- > 0)
  2852.         xcb_screen_next(&iter);
  2853.  
  2854.     demo->screen = iter.data;
  2855. #endif // _WIN32
  2856. }
  2857.  
  2858. static void demo_init(struct demo *demo, int argc, char **argv) {
  2859.     vec3 eye = {0.0f, 3.0f, 5.0f};
  2860.     vec3 origin = {0, 0, 0};
  2861.     vec3 up = {0.0f, 1.0f, 0.0};
  2862.  
  2863.     memset(demo, 0, sizeof(*demo));
  2864.     demo->frameCount = INT32_MAX;
  2865.  
  2866.     for (int i = 1; i < argc; i++) {
  2867.         if (strcmp(argv[i], "--use_staging") == 0) {
  2868.             demo->use_staging_buffer = true;
  2869.             continue;
  2870.         }
  2871.         if (strcmp(argv[i], "--break") == 0) {
  2872.             demo->use_break = true;
  2873.             continue;
  2874.         }
  2875.         if (strcmp(argv[i], "--validate") == 0) {
  2876.             demo->validate = true;
  2877.             continue;
  2878.         }
  2879.         if (strcmp(argv[i], "--xlib") == 0) {
  2880.             demo->use_xlib = true;
  2881.             continue;
  2882.         }
  2883.         if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX &&
  2884.             i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 &&
  2885.             demo->frameCount >= 0) {
  2886.             i++;
  2887.             continue;
  2888.         }
  2889.  
  2890.         fprintf(stderr, "Usage:\n  %s [--use_staging] [--validate] [--break] "
  2891.                         "[--c <framecount>]\n",
  2892.                 APP_SHORT_NAME);
  2893.         fflush(stderr);
  2894.         exit(1);
  2895.     }
  2896.  
  2897.     if (!demo->use_xlib)
  2898.         demo_init_connection(demo);
  2899.  
  2900.     demo_init_vk(demo);
  2901.  
  2902.     demo->width = 500;
  2903.     demo->height = 500;
  2904.  
  2905.     demo->spin_angle = 0.01f;
  2906.     demo->spin_increment = 0.01f;
  2907.     demo->pause = false;
  2908.  
  2909.     mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f),
  2910.                        1.0f, 0.1f, 100.0f);
  2911.     mat4x4_look_at(demo->view_matrix, eye, origin, up);
  2912.     mat4x4_identity(demo->model_matrix);
  2913. }
  2914.  
  2915. #ifdef _WIN32
  2916. // Include header required for parsing the command line options.
  2917. #include <shellapi.h>
  2918.  
  2919. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine,
  2920.                    int nCmdShow) {
  2921.     MSG msg;   // message
  2922.     bool done; // flag saying when app is complete
  2923.     int argc;
  2924.     char **argv;
  2925.  
  2926.     // Use the CommandLine functions to get the command line arguments.
  2927.     // Unfortunately, Microsoft outputs
  2928.     // this information as wide characters for Unicode, and we simply want the
  2929.     // Ascii version to be compatible
  2930.     // with the non-Windows side.  So, we have to convert the information to
  2931.     // Ascii character strings.
  2932.     LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
  2933.     if (NULL == commandLineArgs) {
  2934.         argc = 0;
  2935.     }
  2936.  
  2937.     if (argc > 0) {
  2938.         argv = (char **)malloc(sizeof(char *) * argc);
  2939.         if (argv == NULL) {
  2940.             argc = 0;
  2941.         } else {
  2942.             for (int iii = 0; iii < argc; iii++) {
  2943.                 size_t wideCharLen = wcslen(commandLineArgs[iii]);
  2944.                 size_t numConverted = 0;
  2945.  
  2946.                 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
  2947.                 if (argv[iii] != NULL) {
  2948.                     wcstombs_s(&numConverted, argv[iii], wideCharLen + 1,
  2949.                                commandLineArgs[iii], wideCharLen + 1);
  2950.                 }
  2951.             }
  2952.         }
  2953.     } else {
  2954.         argv = NULL;
  2955.     }
  2956.  
  2957.     demo_init(&demo, argc, argv);
  2958.  
  2959.     // Free up the items we had to allocate for the command line arguments.
  2960.     if (argc > 0 && argv != NULL) {
  2961.         for (int iii = 0; iii < argc; iii++) {
  2962.             if (argv[iii] != NULL) {
  2963.                 free(argv[iii]);
  2964.             }
  2965.         }
  2966.         free(argv);
  2967.     }
  2968.  
  2969.     demo.connection = hInstance;
  2970.     strncpy(demo.name, "cube", APP_NAME_STR_LEN);
  2971.     demo_create_window(&demo);
  2972.     demo_init_vk_swapchain(&demo);
  2973.  
  2974.     demo_prepare(&demo);
  2975.  
  2976.     done = false; // initialize loop condition variable
  2977.  
  2978.     // main message loop
  2979.     while (!done) {
  2980.         PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
  2981.         if (msg.message == WM_QUIT) // check for a quit message
  2982.         {
  2983.             done = true; // if found, quit app
  2984.         } else {
  2985.             /* Translate and dispatch to event queue*/
  2986.             TranslateMessage(&msg);
  2987.             DispatchMessage(&msg);
  2988.         }
  2989.         RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
  2990.     }
  2991.  
  2992.     demo_cleanup(&demo);
  2993.  
  2994.     return (int)msg.wParam;
  2995. }
  2996. #else  // _WIN32
  2997. int main(int argc, char **argv) {
  2998.     struct demo demo;
  2999.  
  3000.     demo_init(&demo, argc, argv);
  3001.     if (demo.use_xlib)
  3002.         demo_create_xlib_window(&demo);
  3003.     else
  3004.         demo_create_xcb_window(&demo);
  3005.  
  3006.     demo_init_vk_swapchain(&demo);
  3007.  
  3008.     demo_prepare(&demo);
  3009.  
  3010.     if (demo.use_xlib)
  3011.         demo_run_xlib(&demo);
  3012.     else
  3013.         demo_run_xcb(&demo);
  3014.  
  3015.     demo_cleanup(&demo);
  3016.  
  3017.     return validation_error;
  3018. }
  3019. #endif // _WIN32
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement