From 5fa4791843d7bb9df449e243e17731d72bebb436 Mon Sep 17 00:00:00 2001 From: Dave Houlton Date: Fri, 16 Feb 2018 11:02:26 -0700 Subject: demos: clang-format only Apply a whole-file clang-format to LVL demos folder. Change-Id: I5f7fc8b67e7f3f3eeaa34a2ae757004fb7334743 --- demos/cube.c | 1432 +++++++---------- demos/cube.cpp | 3765 ++++++++++++++++++++++---------------------- demos/smoke/Game.cpp | 28 +- demos/smoke/Meshes.cpp | 107 +- demos/smoke/ShellWin32.cpp | 2 +- demos/smoke/Simulation.cpp | 17 +- demos/vulkaninfo.c | 37 +- 7 files changed, 2572 insertions(+), 2816 deletions(-) diff --git a/demos/cube.c b/demos/cube.c index 5fb79c9a..d322f6ce 100644 --- a/demos/cube.c +++ b/demos/cube.c @@ -518,12 +518,12 @@ VKAPI_ATTR VkBool32 VKAPI_CALL dbgFunc(VkFlags msgFlags, VkDebugReportObjectType // clang-format on /* - * false indicates that layer should not bail-out of an - * API call that had validation failures. This may mean that the - * app dies inside the driver due to invalid parameter(s). - * That's what would happen without validation layers, so we'll - * keep that behavior here. - */ + * false indicates that layer should not bail-out of an + * API call that had validation failures. This may mean that the + * app dies inside the driver due to invalid parameter(s). + * That's what would happen without validation layers, so we'll + * keep that behavior here. + */ return false; } @@ -545,10 +545,7 @@ bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) { return false; } } -bool CanPresentEarlier(uint64_t earliest, - uint64_t actual, - uint64_t margin, - uint64_t rdur) { +bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) { if (earliest < actual) { // Consider whether this present could have occured earlier. Make sure // that earliest time was at least 2msec earlier than actual time, and @@ -567,15 +564,12 @@ bool CanPresentEarlier(uint64_t earliest, // Forward declaration: static void demo_resize(struct demo *demo); -static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, - VkFlags requirements_mask, - uint32_t *typeIndex) { +static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) { // Search memtypes to find first index with those properties for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) { if ((typeBits & 1) == 1) { // Type is available, does it match user properties? - if ((demo->memory_properties.memoryTypes[i].propertyFlags & - requirements_mask) == requirements_mask) { + if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { *typeIndex = i; return true; } @@ -591,16 +585,13 @@ static void demo_flush_init_cmd(struct demo *demo) { // This function could get called twice if the texture uses a staging buffer // In that case the second call should be ignored - if (demo->cmd == VK_NULL_HANDLE) - return; + if (demo->cmd == VK_NULL_HANDLE) return; err = vkEndCommandBuffer(demo->cmd); assert(!err); VkFence fence; - VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .pNext = NULL, - .flags = 0}; + VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0}; err = vkCreateFence(demo->device, &fence_ci, NULL, &fence); assert(!err); @@ -626,64 +617,54 @@ static void demo_flush_init_cmd(struct demo *demo) { demo->cmd = VK_NULL_HANDLE; } -static void demo_set_image_layout(struct demo *demo, VkImage image, - VkImageAspectFlags aspectMask, - VkImageLayout old_image_layout, - VkImageLayout new_image_layout, - VkAccessFlagBits srcAccessMask, - VkPipelineStageFlags src_stages, +static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout, + VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages, VkPipelineStageFlags dest_stages) { assert(demo->cmd); - VkImageMemoryBarrier image_memory_barrier = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .pNext = NULL, - .srcAccessMask = srcAccessMask, - .dstAccessMask = 0, - .oldLayout = old_image_layout, - .newLayout = new_image_layout, - .image = image, - .subresourceRange = {aspectMask, 0, 1, 0, 1}}; + VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = NULL, + .srcAccessMask = srcAccessMask, + .dstAccessMask = 0, + .oldLayout = old_image_layout, + .newLayout = new_image_layout, + .image = image, + .subresourceRange = {aspectMask, 0, 1, 0, 1}}; switch (new_image_layout) { - case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: - /* Make sure anything that was copying from this image has completed */ - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - break; - - case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: - image_memory_barrier.dstAccessMask = - VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - break; - - case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: - image_memory_barrier.dstAccessMask = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - break; - - case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: - image_memory_barrier.dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; - break; - - case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: - image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - break; - - case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: - image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; - break; - - default: - image_memory_barrier.dstAccessMask = 0; - break; - } + case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: + /* Make sure anything that was copying from this image has completed */ + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + break; + + case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: + image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + break; + + case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: + image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; + break; + + case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: + image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; + break; + + case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: + image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + break; + + case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: + image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; + break; + default: + image_memory_barrier.dstAccessMask = 0; + break; + } VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier; - vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, - NULL, 1, pmemory_barrier); + vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier); } static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { @@ -694,8 +675,8 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { .pInheritanceInfo = NULL, }; const VkClearValue clear_values[2] = { - [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}, - [1] = {.depthStencil = {1.0f, 0}}, + [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}, + [1] = {.depthStencil = {1.0f, 0}}, }; const VkRenderPassBeginInfo rp_begin = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, @@ -715,10 +696,8 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { assert(!err); vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline); - vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, - demo->pipeline_layout, 0, 1, - &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, - 0, NULL); + vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1, + &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL); VkViewport viewport; memset(&viewport, 0, sizeof(viewport)); viewport.height = (float)demo->height; @@ -745,22 +724,19 @@ static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { // to transfer from present queue family back to graphics queue family at // the start of the next frame because we don't care about the image's // contents at that point. - VkImageMemoryBarrier image_ownership_barrier = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .pNext = NULL, - .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .srcQueueFamilyIndex = demo->graphics_queue_family_index, - .dstQueueFamilyIndex = demo->present_queue_family_index, - .image = demo->swapchain_image_resources[demo->current_buffer].image, - .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - - vkCmdPipelineBarrier(cmd_buf, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, - 0, NULL, 0, NULL, 1, &image_ownership_barrier); + VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = NULL, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .srcQueueFamilyIndex = demo->graphics_queue_family_index, + .dstQueueFamilyIndex = demo->present_queue_family_index, + .image = demo->swapchain_image_resources[demo->current_buffer].image, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + + vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, + NULL, 0, NULL, 1, &image_ownership_barrier); } err = vkEndCommandBuffer(cmd_buf); assert(!err); @@ -775,26 +751,22 @@ void demo_build_image_ownership_cmd(struct demo *demo, int i) { .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT, .pInheritanceInfo = NULL, }; - err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, - &cmd_buf_info); + err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info); assert(!err); - VkImageMemoryBarrier image_ownership_barrier = { - .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .pNext = NULL, - .srcAccessMask = 0, - .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - .srcQueueFamilyIndex = demo->graphics_queue_family_index, - .dstQueueFamilyIndex = demo->present_queue_family_index, - .image = demo->swapchain_image_resources[i].image, - .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - - vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, - NULL, 0, NULL, 1, &image_ownership_barrier); + VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .pNext = NULL, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + .srcQueueFamilyIndex = demo->graphics_queue_family_index, + .dstQueueFamilyIndex = demo->present_queue_family_index, + .image = demo->swapchain_image_resources[i].image, + .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; + + vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier); err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd); assert(!err); } @@ -809,13 +781,11 @@ void demo_update_data_buffer(struct demo *demo) { // Rotate around the Y axis mat4x4_dup(Model, demo->model_matrix); - mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, - (float)degreesToRadians(demo->spin_angle)); + mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle)); mat4x4_mul(MVP, VP, demo->model_matrix); - err = vkMapMemory(demo->device, - demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0, - VK_WHOLE_SIZE, 0, (void **)&pData); + err = vkMapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, 0, + (void **)&pData); assert(!err); memcpy(pData, (const void *)&MVP[0][0], matrixSize); @@ -827,27 +797,21 @@ void DemoUpdateTargetIPD(struct demo *demo) { // Look at what happened to previous presents, and make appropriate // adjustments in timing: VkResult U_ASSERT_ONLY err; - VkPastPresentationTimingGOOGLE* past = NULL; + VkPastPresentationTimingGOOGLE *past = NULL; uint32_t count = 0; - err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, - demo->swapchain, - &count, - NULL); + err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL); assert(!err); if (count) { - past = (VkPastPresentationTimingGOOGLE*) malloc(sizeof(VkPastPresentationTimingGOOGLE) * count); + past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count); assert(past); - err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, - demo->swapchain, - &count, - past); + err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past); assert(!err); bool early = false; bool late = false; bool calibrate_next = false; - for (uint32_t i = 0 ; i < count ; i++) { + for (uint32_t i = 0; i < count; i++) { if (!demo->syncd_with_actual_presents) { // This is the first time that we've received an // actualPresentTime for this swapchain. In order to not @@ -862,9 +826,7 @@ void DemoUpdateTargetIPD(struct demo *demo) { demo->last_early_id = 0; demo->syncd_with_actual_presents = true; break; - } else if (CanPresentEarlier(past[i].earliestPresentTime, - past[i].actualPresentTime, - past[i].presentMargin, + } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin, demo->refresh_duration)) { // This image could have been presented earlier. We don't want // to decrease the target_IPD until we've seen early presents @@ -877,10 +839,8 @@ void DemoUpdateTargetIPD(struct demo *demo) { } else if (demo->last_early_id == 0) { // This is the first early present we've seen. // Calculate the presentID for two seconds from now. - uint64_t lastEarlyTime = - past[i].actualPresentTime + (2 * BILLION); - uint32_t howManyPresents = - (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD); + uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION); + uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD); demo->last_early_id = past[i].presentID + howManyPresents; } else { // We are in the midst of a set of early images, @@ -888,17 +848,14 @@ void DemoUpdateTargetIPD(struct demo *demo) { } late = false; demo->last_late_id = 0; - } else if (ActualTimeLate(past[i].desiredPresentTime, - past[i].actualPresentTime, - demo->refresh_duration)) { + } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) { // This image was presented after its desired time. Since // there's a delay between calling vkQueuePresentKHR and when // we get the timing data, several presents may have been late. // Thus, we need to threat all of the outstanding presents as // being likely late, so that we only increase the target_IPD // once for all of those presents. - if ((demo->last_late_id == 0) || - (demo->last_late_id < past[i].presentID)) { + if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) { late = true; // Record the last suspected-late present: demo->last_late_id = demo->next_present_id - 1; @@ -932,8 +889,7 @@ void DemoUpdateTargetIPD(struct demo *demo) { // try to go faster. demo->refresh_duration_multiplier = 1; } - demo->target_IPD = - demo->refresh_duration * demo->refresh_duration_multiplier; + demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier; } if (late) { // Since we found a new instance of a late present, we want to @@ -942,15 +898,12 @@ void DemoUpdateTargetIPD(struct demo *demo) { // TODO(ianelliott): Try to calculate a better target_IPD based // on the most recently-seen present (this is overly-simplistic). demo->refresh_duration_multiplier++; - demo->target_IPD = - demo->refresh_duration * demo->refresh_duration_multiplier; + demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier; } if (calibrate_next) { - int64_t multiple = demo->next_present_id - past[count-1].presentID; - demo->prev_desired_present_time = - (past[count-1].actualPresentTime + - (multiple * demo->target_IPD)); + int64_t multiple = demo->next_present_id - past[count - 1].presentID; + demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD)); } } } @@ -964,9 +917,9 @@ static void demo_draw(struct demo *demo) { do { // Get the index of the next available swapchain image: - err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, - demo->image_acquired_semaphores[demo->frame_index], - VK_NULL_HANDLE, &demo->current_buffer); + err = + demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, + demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer); if (err == VK_ERROR_OUT_OF_DATE_KHR) { // demo->swapchain is out of date (e.g. the window was resized) and @@ -1011,8 +964,7 @@ static void demo_draw(struct demo *demo) { submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index]; - err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, - demo->fences[demo->frame_index]); + err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]); assert(!err); if (demo->separate_present_queue) { @@ -1024,8 +976,7 @@ static void demo_draw(struct demo *demo) { submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index]; submit_info.commandBufferCount = 1; - submit_info.pCommandBuffers = - &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd; + submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd; submit_info.signalSemaphoreCount = 1; submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index]; err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence); @@ -1038,9 +989,8 @@ static void demo_draw(struct demo *demo) { .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .pNext = NULL, .waitSemaphoreCount = 1, - .pWaitSemaphores = (demo->separate_present_queue) - ? &demo->image_ownership_semaphores[demo->frame_index] - : &demo->draw_complete_semaphores[demo->frame_index], + .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index] + : &demo->draw_complete_semaphores[demo->frame_index], .swapchainCount = 1, .pSwapchains = &demo->swapchain, .pImageIndices = &demo->current_buffer, @@ -1094,8 +1044,7 @@ static void demo_draw(struct demo *demo) { ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1); } } else { - ptime.desiredPresentTime = (demo->prev_desired_present_time + - demo->target_IPD); + ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD); } ptime.presentID = demo->next_present_id++; demo->prev_desired_present_time = ptime.desiredPresentTime; @@ -1133,19 +1082,15 @@ static void demo_prepare_buffers(struct demo *demo) { // Check the surface capabilities and formats VkSurfaceCapabilitiesKHR surfCapabilities; - err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR( - demo->gpu, demo->surface, &surfCapabilities); + err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities); assert(!err); uint32_t presentModeCount; - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( - demo->gpu, demo->surface, &presentModeCount, NULL); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL); assert(!err); - VkPresentModeKHR *presentModes = - (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); + VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); assert(presentModes); - err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( - demo->gpu, demo->surface, &presentModeCount, presentModes); + err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes); assert(!err); VkExtent2D swapchainExtent; @@ -1162,7 +1107,7 @@ static void demo_prepare_buffers(struct demo *demo) { } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) { swapchainExtent.width = surfCapabilities.maxImageExtent.width; } - + if (swapchainExtent.height < surfCapabilities.minImageExtent.height) { swapchainExtent.height = surfCapabilities.minImageExtent.height; } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) { @@ -1206,8 +1151,7 @@ static void demo_prepare_buffers(struct demo *demo) { // the application wants the late image to be immediately displayed, even // though that may mean some tearing. - if (demo->presentMode != swapchainPresentMode) { - + if (demo->presentMode != swapchainPresentMode) { for (size_t i = 0; i < presentModeCount; ++i) { if (presentModes[i] == demo->presentMode) { swapchainPresentMode = demo->presentMode; @@ -1228,15 +1172,13 @@ static void demo_prepare_buffers(struct demo *demo) { } // If maxImageCount is 0, we can ask for as many images as we want; // otherwise we're limited to maxImageCount - if ((surfCapabilities.maxImageCount > 0) && - (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) { + if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) { // Application must settle for fewer images than desired: desiredNumOfSwapchainImages = surfCapabilities.maxImageCount; } VkSurfaceTransformFlagsKHR preTransform; - if (surfCapabilities.supportedTransforms & - VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { + if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } else { preTransform = surfCapabilities.currentTransform; @@ -1266,7 +1208,8 @@ static void demo_prepare_buffers(struct demo *demo) { .imageColorSpace = demo->color_space, .imageExtent = { - .width = swapchainExtent.width, .height = swapchainExtent.height, + .width = swapchainExtent.width, + .height = swapchainExtent.height, }, .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, .preTransform = preTransform, @@ -1280,8 +1223,7 @@ static void demo_prepare_buffers(struct demo *demo) { .clipped = true, }; uint32_t i; - err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, - &demo->swapchain); + err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain); assert(!err); // If we just re-created an existing swapchain, we should destroy the old @@ -1292,20 +1234,16 @@ static void demo_prepare_buffers(struct demo *demo) { demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL); } - err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, - &demo->swapchainImageCount, NULL); + err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL); assert(!err); - VkImage *swapchainImages = - (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage)); + VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage)); assert(swapchainImages); - err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, - &demo->swapchainImageCount, - swapchainImages); + err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages); assert(!err); - demo->swapchain_image_resources = (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * - demo->swapchainImageCount); + demo->swapchain_image_resources = + (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount); assert(demo->swapchain_image_resources); for (i = 0; i < demo->swapchainImageCount; i++) { @@ -1315,16 +1253,13 @@ static void demo_prepare_buffers(struct demo *demo) { .format = demo->format, .components = { - .r = VK_COMPONENT_SWIZZLE_R, - .g = VK_COMPONENT_SWIZZLE_G, - .b = VK_COMPONENT_SWIZZLE_B, - .a = VK_COMPONENT_SWIZZLE_A, + .r = VK_COMPONENT_SWIZZLE_R, + .g = VK_COMPONENT_SWIZZLE_G, + .b = VK_COMPONENT_SWIZZLE_B, + .a = VK_COMPONENT_SWIZZLE_A, }, - .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1}, + .subresourceRange = + {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, .viewType = VK_IMAGE_VIEW_TYPE_2D, .flags = 0, }; @@ -1333,16 +1268,13 @@ static void demo_prepare_buffers(struct demo *demo) { color_image_view.image = demo->swapchain_image_resources[i].image; - err = vkCreateImageView(demo->device, &color_image_view, NULL, - &demo->swapchain_image_resources[i].view); + err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view); assert(!err); } if (demo->VK_GOOGLE_display_timing_enabled) { VkRefreshCycleDurationGOOGLE rc_dur; - err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, - demo->swapchain, - &rc_dur); + err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur); assert(!err); demo->refresh_duration = rc_dur.refreshDuration; @@ -1380,11 +1312,8 @@ static void demo_prepare_depth(struct demo *demo) { .pNext = NULL, .image = VK_NULL_HANDLE, .format = depth_format, - .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1}, + .subresourceRange = + {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, .flags = 0, .viewType = VK_IMAGE_VIEW_TYPE_2D, }; @@ -1407,19 +1336,16 @@ static void demo_prepare_depth(struct demo *demo) { demo->depth.mem_alloc.allocationSize = mem_reqs.size; demo->depth.mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &demo->depth.mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ - err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, - &demo->depth.mem); + err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem); assert(!err); /* bind memory */ - err = - vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0); + err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0); assert(!err); /* create image view */ @@ -1429,30 +1355,31 @@ static void demo_prepare_depth(struct demo *demo) { } /* Load a ppm file into memory */ -bool loadTexture(const char *filename, uint8_t *rgba_data, - VkSubresourceLayout *layout, int32_t *width, int32_t *height) { - +bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) { #if (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)) - filename =[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: @(filename)].UTF8String; + filename = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@(filename)].UTF8String; #endif #ifdef __ANDROID__ #include char *cPtr; - cPtr = (char*)lunarg_ppm; - if ((unsigned char*)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) { + cPtr = (char *)lunarg_ppm; + if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) { return false; } - while(strncmp(cPtr++, "\n", 1)); + while (strncmp(cPtr++, "\n", 1)) + ; sscanf(cPtr, "%u %u", width, height); if (rgba_data == NULL) { return true; } - while(strncmp(cPtr++, "\n", 1)); - if ((unsigned char*)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) { + while (strncmp(cPtr++, "\n", 1)) + ; + if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) { return false; } - while(strncmp(cPtr++, "\n", 1)); + while (strncmp(cPtr++, "\n", 1)) + ; for (int y = 0; y < *height; y++) { uint8_t *rowPtr = rgba_data; @@ -1470,10 +1397,9 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, FILE *fPtr = fopen(filename, "rb"); char header[256], *cPtr, *tmp; - if (!fPtr) - return false; + if (!fPtr) return false; - cPtr = fgets(header, 256, fPtr); // P6 + cPtr = fgets(header, 256, fPtr); // P6 if (cPtr == NULL || strncmp(header, "P6\n", 3)) { fclose(fPtr); return false; @@ -1492,7 +1418,7 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, fclose(fPtr); return true; } - tmp = fgets(header, 256, fPtr); // Format + tmp = fgets(header, 256, fPtr); // Format (void)tmp; if (cPtr == NULL || strncmp(header, "255\n", 3)) { fclose(fPtr); @@ -1514,11 +1440,8 @@ bool loadTexture(const char *filename, uint8_t *rgba_data, #endif } -static void demo_prepare_texture_image(struct demo *demo, const char *filename, - struct texture_object *tex_obj, - VkImageTiling tiling, - VkImageUsageFlags usage, - VkFlags required_props) { +static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj, + VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) { const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM; int32_t tex_width; int32_t tex_height; @@ -1549,8 +1472,7 @@ static void demo_prepare_texture_image(struct demo *demo, const char *filename, VkMemoryRequirements mem_reqs; - err = - vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image); + err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image); assert(!err); vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs); @@ -1560,14 +1482,11 @@ static void demo_prepare_texture_image(struct demo *demo, const char *filename, tex_obj->mem_alloc.allocationSize = mem_reqs.size; tex_obj->mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, - required_props, - &tex_obj->mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex); assert(pass); /* allocate memory */ - err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, - &(tex_obj->mem)); + err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem)); assert(!err); /* bind memory */ @@ -1583,11 +1502,9 @@ static void demo_prepare_texture_image(struct demo *demo, const char *filename, VkSubresourceLayout layout; void *data; - vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, - &layout); + vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout); - err = vkMapMemory(demo->device, tex_obj->mem, 0, - tex_obj->mem_alloc.allocationSize, 0, &data); + err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data); assert(!err); if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) { @@ -1600,8 +1517,7 @@ static void demo_prepare_texture_image(struct demo *demo, const char *filename, tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; } -static void demo_destroy_texture_image(struct demo *demo, - struct texture_object *tex_objs) { +static void demo_destroy_texture_image(struct demo *demo, struct texture_object *tex_objs) { /* clean up staging resources */ vkFreeMemory(demo->device, tex_objs->mem, NULL); vkDestroyImage(demo->device, tex_objs->image, NULL); @@ -1617,52 +1533,34 @@ static void demo_prepare_textures(struct demo *demo) { for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { VkResult U_ASSERT_ONLY err; - if ((props.linearTilingFeatures & - VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && - !demo->use_staging_buffer) { + if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) { /* Device can texture using linear textures */ - demo_prepare_texture_image( - demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, - VK_IMAGE_USAGE_SAMPLED_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // Nothing in the pipeline needs to be complete to start, and don't allow fragment // shader to run until layout transition completes - demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PREINITIALIZED, demo->textures[i].imageLayout, - 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, + demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); demo->staging_texture.image = 0; - } else if (props.optimalTilingFeatures & - VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { + } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { /* Must use staging buffer to copy linear texture to optimized */ memset(&demo->staging_texture, 0, sizeof(demo->staging_texture)); - demo_prepare_texture_image( - demo, tex_files[i], &demo->staging_texture, VK_IMAGE_TILING_LINEAR, - VK_IMAGE_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - - demo_prepare_texture_image( - demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL, - (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - - demo_set_image_layout(demo, demo->staging_texture.image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PREINITIALIZED, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + demo_prepare_texture_image(demo, tex_files[i], &demo->staging_texture, VK_IMAGE_TILING_LINEAR, + VK_IMAGE_USAGE_TRANSFER_SRC_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + + demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL, + (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + demo_set_image_layout(demo, demo->staging_texture.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_PREINITIALIZED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); VkImageCopy copy_region = { @@ -1670,20 +1568,13 @@ static void demo_prepare_textures(struct demo *demo) { .srcOffset = {0, 0, 0}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffset = {0, 0, 0}, - .extent = {demo->staging_texture.tex_width, - demo->staging_texture.tex_height, 1}, + .extent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1}, }; - vkCmdCopyImage( - demo->cmd, demo->staging_texture.image, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); - - demo_set_image_layout(demo, demo->textures[i].image, - VK_IMAGE_ASPECT_COLOR_BIT, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - demo->textures[i].imageLayout, - VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, + vkCmdCopyImage(demo->cmd, demo->staging_texture.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); + + demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); } else { @@ -1718,22 +1609,22 @@ static void demo_prepare_textures(struct demo *demo) { .format = tex_format, .components = { - VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, - VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, + VK_COMPONENT_SWIZZLE_R, + VK_COMPONENT_SWIZZLE_G, + VK_COMPONENT_SWIZZLE_B, + VK_COMPONENT_SWIZZLE_A, }, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, .flags = 0, }; /* create sampler */ - err = vkCreateSampler(demo->device, &sampler, NULL, - &demo->textures[i].sampler); + err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler); assert(!err); /* create image view */ view.image = demo->textures[i].image; - err = vkCreateImageView(demo->device, &view, NULL, - &demo->textures[i].view); + err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view); assert(!err); } } @@ -1770,32 +1661,25 @@ void demo_prepare_cube_data_buffers(struct demo *demo) { buf_info.size = sizeof(data); for (unsigned int i = 0; i < demo->swapchainImageCount; i++) { - err = - vkCreateBuffer(demo->device, &buf_info, NULL, - &demo->swapchain_image_resources[i].uniform_buffer); + err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer); assert(!err); - vkGetBufferMemoryRequirements(demo->device, - demo->swapchain_image_resources[i].uniform_buffer, - &mem_reqs); + vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs); mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; mem_alloc.pNext = NULL; mem_alloc.allocationSize = mem_reqs.size; mem_alloc.memoryTypeIndex = 0; - pass = memory_type_from_properties( - demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - &mem_alloc.memoryTypeIndex); + pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + &mem_alloc.memoryTypeIndex); assert(pass); - err = vkAllocateMemory(demo->device, &mem_alloc, NULL, - &demo->swapchain_image_resources[i].uniform_memory); + err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory); assert(!err); - err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, - VK_WHOLE_SIZE, 0, (void **)&pData); + err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0, (void **)&pData); assert(!err); memcpy(pData, &data, sizeof data); @@ -1803,29 +1687,29 @@ void demo_prepare_cube_data_buffers(struct demo *demo) { vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory); err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer, - demo->swapchain_image_resources[i].uniform_memory, 0); + demo->swapchain_image_resources[i].uniform_memory, 0); assert(!err); } } static void demo_prepare_descriptor_layout(struct demo *demo) { const VkDescriptorSetLayoutBinding layout_bindings[2] = { - [0] = - { - .binding = 0, - .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .descriptorCount = 1, - .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, - .pImmutableSamplers = NULL, - }, - [1] = - { - .binding = 1, - .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = DEMO_TEXTURE_COUNT, - .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, - .pImmutableSamplers = NULL, - }, + [0] = + { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, + .pImmutableSamplers = NULL, + }, + [1] = + { + .binding = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = DEMO_TEXTURE_COUNT, + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + .pImmutableSamplers = NULL, + }, }; const VkDescriptorSetLayoutCreateInfo descriptor_layout = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, @@ -1835,8 +1719,7 @@ static void demo_prepare_descriptor_layout(struct demo *demo) { }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, - &demo->desc_layout); + err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout); assert(!err); const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = { @@ -1846,8 +1729,7 @@ static void demo_prepare_descriptor_layout(struct demo *demo) { .pSetLayouts = &demo->desc_layout, }; - err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, - &demo->pipeline_layout); + err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout); assert(!err); } @@ -1861,35 +1743,34 @@ static void demo_prepare_render_pass(struct demo *demo) { // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of // the renderpass, no barriers are necessary. const VkAttachmentDescription attachments[2] = { - [0] = - { - .format = demo->format, - .flags = 0, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, - }, - [1] = - { - .format = demo->depth.format, - .flags = 0, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = - VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - }, + [0] = + { + .format = demo->format, + .flags = 0, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, + }, + [1] = + { + .format = demo->depth.format, + .flags = 0, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + }, }; const VkAttachmentReference color_reference = { - .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .attachment = 0, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, }; const VkAttachmentReference depth_reference = { .attachment = 1, @@ -2007,11 +1888,9 @@ static void demo_prepare_pipeline(struct demo *demo) { memset(&vp, 0, sizeof(vp)); vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; vp.viewportCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = - VK_DYNAMIC_STATE_VIEWPORT; + dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT; vp.scissorCount = 1; - dynamicStateEnables[dynamicState.dynamicStateCount++] = - VK_DYNAMIC_STATE_SCISSOR; + dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR; memset(&ds, 0, sizeof(ds)); ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; @@ -2050,8 +1929,7 @@ static void demo_prepare_pipeline(struct demo *demo) { memset(&pipelineCache, 0, sizeof(pipelineCache)); pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; - err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, - &demo->pipelineCache); + err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache); assert(!err); pipeline.pVertexInputState = &vi; @@ -2068,8 +1946,7 @@ static void demo_prepare_pipeline(struct demo *demo) { pipeline.renderPass = demo->render_pass; - err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, - &pipeline, NULL, &demo->pipeline); + err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline); assert(!err); vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL); @@ -2078,16 +1955,16 @@ static void demo_prepare_pipeline(struct demo *demo) { static void demo_prepare_descriptor_pool(struct demo *demo) { const VkDescriptorPoolSize type_counts[2] = { - [0] = - { - .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, - .descriptorCount = demo->swapchainImageCount, - }, - [1] = - { - .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, - .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT, - }, + [0] = + { + .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + .descriptorCount = demo->swapchainImageCount, + }, + [1] = + { + .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT, + }, }; const VkDescriptorPoolCreateInfo descriptor_pool = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, @@ -2098,8 +1975,7 @@ static void demo_prepare_descriptor_pool(struct demo *demo) { }; VkResult U_ASSERT_ONLY err; - err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, - &demo->desc_pool); + err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool); assert(!err); } @@ -2108,12 +1984,11 @@ static void demo_prepare_descriptor_set(struct demo *demo) { VkWriteDescriptorSet writes[2]; VkResult U_ASSERT_ONLY err; - VkDescriptorSetAllocateInfo alloc_info = { - .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, - .pNext = NULL, - .descriptorPool = demo->desc_pool, - .descriptorSetCount = 1, - .pSetLayouts = &demo->desc_layout}; + VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .pNext = NULL, + .descriptorPool = demo->desc_pool, + .descriptorSetCount = 1, + .pSetLayouts = &demo->desc_layout}; VkDescriptorBufferInfo buffer_info; buffer_info.offset = 0; @@ -2168,8 +2043,7 @@ static void demo_prepare_framebuffers(struct demo *demo) { for (i = 0; i < demo->swapchainImageCount; i++) { attachments[0] = demo->swapchain_image_resources[i].view; - err = vkCreateFramebuffer(demo->device, &fb_info, NULL, - &demo->swapchain_image_resources[i].framebuffer); + err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer); assert(!err); } } @@ -2183,8 +2057,7 @@ static void demo_prepare(struct demo *demo) { .queueFamilyIndex = demo->graphics_queue_family_index, .flags = 0, }; - err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, - &demo->cmd_pool); + err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool); assert(!err); const VkCommandBufferAllocateInfo cmd = { @@ -2215,8 +2088,7 @@ static void demo_prepare(struct demo *demo) { demo_prepare_pipeline(demo); for (uint32_t i = 0; i < demo->swapchainImageCount; i++) { - err = - vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd); + err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd); assert(!err); } @@ -2227,8 +2099,7 @@ static void demo_prepare(struct demo *demo) { .queueFamilyIndex = demo->present_queue_family_index, .flags = 0, }; - err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, - &demo->present_cmd_pool); + err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool); assert(!err); const VkCommandBufferAllocateInfo present_cmd_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, @@ -2238,8 +2109,8 @@ static void demo_prepare(struct demo *demo) { .commandBufferCount = 1, }; for (uint32_t i = 0; i < demo->swapchainImageCount; i++) { - err = vkAllocateCommandBuffers( - demo->device, &present_cmd_info, &demo->swapchain_image_resources[i].graphics_to_present_cmd); + err = vkAllocateCommandBuffers(demo->device, &present_cmd_info, + &demo->swapchain_image_resources[i].graphics_to_present_cmd); assert(!err); demo_build_image_ownership_cmd(demo, i); } @@ -2310,8 +2181,7 @@ static void demo_cleanup(struct demo *demo) { for (i = 0; i < demo->swapchainImageCount; i++) { vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL); - vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, - &demo->swapchain_image_resources[i].cmd); + vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd); vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL); vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL); } @@ -2390,8 +2260,7 @@ static void demo_resize(struct demo *demo) { for (i = 0; i < demo->swapchainImageCount; i++) { vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL); - vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, - &demo->swapchain_image_resources[i].cmd); + vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd); vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL); vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL); } @@ -2411,8 +2280,7 @@ struct demo demo; #if defined(VK_USE_PLATFORM_WIN32_KHR) static void demo_run(struct demo *demo) { - if (!demo->prepared) - return; + if (!demo->prepared) return; demo_draw(demo); demo->curFrame++; @@ -2424,32 +2292,32 @@ static void demo_run(struct demo *demo) { // MS-Windows event handling function: LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { - case WM_CLOSE: - PostQuitMessage(validation_error); - break; - case WM_PAINT: - // The validation callback calls MessageBox which can generate paint - // events - don't make more Vulkan calls if we got here from the - // callback - if (!in_callback) { - demo_run(&demo); - } - break; - case WM_GETMINMAXINFO: // set window's minimum size - ((MINMAXINFO*)lParam)->ptMinTrackSize = demo.minsize; - return 0; - case WM_SIZE: - // Resize the application to the new window size, except when - // it was minimized. Vulkan doesn't support images or swapchains - // with width=0 and height=0. - if (wParam != SIZE_MINIMIZED) { - demo.width = lParam & 0xffff; - demo.height = (lParam & 0xffff0000) >> 16; - demo_resize(&demo); - } - break; - default: - break; + case WM_CLOSE: + PostQuitMessage(validation_error); + break; + case WM_PAINT: + // The validation callback calls MessageBox which can generate paint + // events - don't make more Vulkan calls if we got here from the + // callback + if (!in_callback) { + demo_run(&demo); + } + break; + case WM_GETMINMAXINFO: // set window's minimum size + ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize; + return 0; + case WM_SIZE: + // Resize the application to the new window size, except when + // it was minimized. Vulkan doesn't support images or swapchains + // with width=0 and height=0. + if (wParam != SIZE_MINIMIZED) { + demo.width = lParam & 0xffff; + demo.height = (lParam & 0xffff0000) >> 16; + demo_resize(&demo); + } + break; + default: + break; } return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } @@ -2463,7 +2331,7 @@ static void demo_create_window(struct demo *demo) { win_class.lpfnWndProc = WndProc; win_class.cbClsExtra = 0; win_class.cbWndExtra = 0; - win_class.hInstance = demo->connection; // hInstance + win_class.hInstance = demo->connection; // hInstance win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION); win_class.hCursor = LoadCursor(NULL, IDC_ARROW); win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); @@ -2481,17 +2349,17 @@ static void demo_create_window(struct demo *demo) { RECT wr = {0, 0, demo->width, demo->height}; AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); demo->window = CreateWindowEx(0, - demo->name, // class name - demo->name, // app name - WS_OVERLAPPEDWINDOW | // window style + demo->name, // class name + demo->name, // app name + WS_OVERLAPPEDWINDOW | // window style WS_VISIBLE | WS_SYSMENU, - 100, 100, // x/y coords - wr.right - wr.left, // width - wr.bottom - wr.top, // height - NULL, // handle to parent - NULL, // handle to menu - demo->connection, // hInstance - NULL); // no extra parameters + 100, 100, // x/y coords + wr.right - wr.left, // width + wr.bottom - wr.top, // height + NULL, // handle to parent + NULL, // handle to menu + demo->connection, // hInstance + NULL); // no extra parameters if (!demo->window) { // It didn't work, so try to give a useful error: printf("Cannot create a window in which to draw!\n"); @@ -2500,7 +2368,7 @@ static void demo_create_window(struct demo *demo) { } // Window client area size must be at least 1 pixel high, to prevent crash. demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK); - demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK)+1; + demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1; } #elif defined(VK_USE_PLATFORM_XLIB_KHR) static void demo_create_xlib_window(struct demo *demo) { @@ -2515,72 +2383,62 @@ static void demo_create_xlib_window(struct demo *demo) { demo->display = XOpenDisplay(NULL); long visualMask = VisualScreenMask; int numberOfVisuals; - XVisualInfo vInfoTemplate={}; + XVisualInfo vInfoTemplate = {}; vInfoTemplate.screen = DefaultScreen(demo->display); - XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, - &vInfoTemplate, &numberOfVisuals); + XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals); - Colormap colormap = XCreateColormap( - demo->display, RootWindow(demo->display, vInfoTemplate.screen), - visualInfo->visual, AllocNone); + Colormap colormap = + XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone); - XSetWindowAttributes windowAttributes={}; + XSetWindowAttributes windowAttributes = {}; windowAttributes.colormap = colormap; windowAttributes.background_pixel = 0xFFFFFFFF; windowAttributes.border_pixel = 0; - windowAttributes.event_mask = - KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask; + windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask; - demo->xlib_window = XCreateWindow( - demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, - demo->width, demo->height, 0, visualInfo->depth, InputOutput, - visualInfo->visual, - CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes); + demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width, + demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual, + CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes); XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask); XMapWindow(demo->display, demo->xlib_window); XFlush(demo->display); - demo->xlib_wm_delete_window = - XInternAtom(demo->display, "WM_DELETE_WINDOW", False); + demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False); } static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) { - switch(event->type) { - case ClientMessage: - if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) - demo->quit = true; - break; - case KeyPress: - switch (event->xkey.keycode) { - case 0x9: // Escape - demo->quit = true; + switch (event->type) { + case ClientMessage: + if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true; break; - case 0x71: // left arrow key - demo->spin_angle -= demo->spin_increment; + case KeyPress: + switch (event->xkey.keycode) { + case 0x9: // Escape + demo->quit = true; + break; + case 0x71: // left arrow key + demo->spin_angle -= demo->spin_increment; + break; + case 0x72: // right arrow key + demo->spin_angle += demo->spin_increment; + break; + case 0x41: // space bar + demo->pause = !demo->pause; + break; + } break; - case 0x72: // right arrow key - demo->spin_angle += demo->spin_increment; + case ConfigureNotify: + if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) { + demo->width = event->xconfigure.width; + demo->height = event->xconfigure.height; + demo_resize(demo); + } break; - case 0x41: // space bar - demo->pause = !demo->pause; + default: break; - } - break; - case ConfigureNotify: - if ((demo->width != event->xconfigure.width) || - (demo->height != event->xconfigure.height)) { - demo->width = event->xconfigure.width; - demo->height = event->xconfigure.height; - demo_resize(demo); - } - break; - default: - break; } - } static void demo_run_xlib(struct demo *demo) { - while (!demo->quit) { XEvent event; @@ -2595,54 +2453,49 @@ static void demo_run_xlib(struct demo *demo) { demo_draw(demo); demo->curFrame++; - if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) - demo->quit = true; + if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true; } } #elif defined(VK_USE_PLATFORM_XCB_KHR) -static void demo_handle_xcb_event(struct demo *demo, - const xcb_generic_event_t *event) { +static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) { uint8_t event_code = event->response_type & 0x7f; switch (event_code) { - case XCB_EXPOSE: - // TODO: Resize window - break; - case XCB_CLIENT_MESSAGE: - if ((*(xcb_client_message_event_t *)event).data.data32[0] == - (*demo->atom_wm_delete_window).atom) { - demo->quit = true; - } - break; - case XCB_KEY_RELEASE: { - const xcb_key_release_event_t *key = - (const xcb_key_release_event_t *)event; - - switch (key->detail) { - case 0x9: // Escape - demo->quit = true; + case XCB_EXPOSE: + // TODO: Resize window break; - case 0x71: // left arrow key - demo->spin_angle -= demo->spin_increment; - break; - case 0x72: // right arrow key - demo->spin_angle += demo->spin_increment; + case XCB_CLIENT_MESSAGE: + if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) { + demo->quit = true; + } break; - case 0x41: // space bar - demo->pause = !demo->pause; + case XCB_KEY_RELEASE: { + const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event; + + switch (key->detail) { + case 0x9: // Escape + demo->quit = true; + break; + case 0x71: // left arrow key + demo->spin_angle -= demo->spin_increment; + break; + case 0x72: // right arrow key + demo->spin_angle += demo->spin_increment; + break; + case 0x41: // space bar + demo->pause = !demo->pause; + break; + } + } break; + case XCB_CONFIGURE_NOTIFY: { + const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event; + if ((demo->width != cfg->width) || (demo->height != cfg->height)) { + demo->width = cfg->width; + demo->height = cfg->height; + demo_resize(demo); + } + } break; + default: break; - } - } break; - case XCB_CONFIGURE_NOTIFY: { - const xcb_configure_notify_event_t *cfg = - (const xcb_configure_notify_event_t *)event; - if ((demo->width != cfg->width) || (demo->height != cfg->height)) { - demo->width = cfg->width; - demo->height = cfg->height; - demo_resize(demo); - } - } break; - default: - break; } } @@ -2654,8 +2507,7 @@ static void demo_run_xcb(struct demo *demo) { if (demo->pause) { event = xcb_wait_for_event(demo->connection); - } - else { + } else { event = xcb_poll_for_event(demo->connection); } while (event) { @@ -2666,8 +2518,7 @@ static void demo_run_xcb(struct demo *demo) { demo_draw(demo); demo->curFrame++; - if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) - demo->quit = true; + if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true; } } @@ -2678,27 +2529,19 @@ static void demo_create_xcb_window(struct demo *demo) { value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; value_list[0] = demo->screen->black_pixel; - value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | - XCB_EVENT_MASK_STRUCTURE_NOTIFY; + value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; - xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, - demo->screen->root, 0, 0, demo->width, demo->height, 0, - XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, - value_mask, value_list); + xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height, + 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list); /* Magic code that will send notification when window is destroyed */ - xcb_intern_atom_cookie_t cookie = - xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS"); - xcb_intern_atom_reply_t *reply = - xcb_intern_atom_reply(demo->connection, cookie, 0); - - xcb_intern_atom_cookie_t cookie2 = - xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); - demo->atom_wm_delete_window = - xcb_intern_atom_reply(demo->connection, cookie2, 0); - - xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, - (*reply).atom, 4, 32, 1, + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0); + + xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); + demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0); + + xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1, &(*demo->atom_wm_delete_window).atom); free(reply); @@ -2707,8 +2550,7 @@ static void demo_create_xcb_window(struct demo *demo) { // Force the x/y coordinates to 100,100 results are identical in consecutive // runs const uint32_t coords[] = {100, 100}; - xcb_configure_window(demo->connection, demo->xcb_window, - XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); + xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); } // VK_USE_PLATFORM_XCB_KHR #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) @@ -2725,22 +2567,16 @@ static void demo_run(struct demo *demo) { } } -static void handle_ping(void *data UNUSED, - struct wl_shell_surface *shell_surface, - uint32_t serial) { +static void handle_ping(void *data UNUSED, struct wl_shell_surface *shell_surface, uint32_t serial) { wl_shell_surface_pong(shell_surface, serial); } -static void handle_configure(void *data UNUSED, - struct wl_shell_surface *shell_surface UNUSED, - uint32_t edges UNUSED, int32_t width UNUSED, - int32_t height UNUSED) {} +static void handle_configure(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED, uint32_t edges UNUSED, + int32_t width UNUSED, int32_t height UNUSED) {} -static void handle_popup_done(void *data UNUSED, - struct wl_shell_surface *shell_surface UNUSED) {} +static void handle_popup_done(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED) {} -static const struct wl_shell_surface_listener shell_surface_listener = { - handle_ping, handle_configure, handle_popup_done}; +static const struct wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done}; static void demo_create_window(struct demo *demo) { demo->window = wl_compositor_create_surface(demo->compositor); @@ -2756,15 +2592,13 @@ static void demo_create_window(struct demo *demo) { fflush(stdout); exit(1); } - wl_shell_surface_add_listener(demo->shell_surface, &shell_surface_listener, - demo); + wl_shell_surface_add_listener(demo->shell_surface, &shell_surface_listener, demo); wl_shell_surface_set_toplevel(demo->shell_surface); wl_shell_surface_set_title(demo->shell_surface, APP_SHORT_NAME); } #elif defined(VK_USE_PLATFORM_ANDROID_KHR) static void demo_run(struct demo *demo) { - if (!demo->prepared) - return; + if (!demo->prepared) return; demo_draw(demo); demo->curFrame++; @@ -2837,8 +2671,7 @@ static VkResult demo_create_display_surface(struct demo *demo) { VkDisplayKHR *supported_displays; // Disqualify planes that are bound to a different display - if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && - (plane_props[plane_index].currentDisplay != display)) { + if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) { continue; } @@ -2910,8 +2743,7 @@ static VkResult demo_create_display_surface(struct demo *demo) { return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface); } -static void demo_run_display(struct demo *demo) -{ +static void demo_run_display(struct demo *demo) { while (!demo->quit) { demo_draw(demo); demo->curFrame++; @@ -2927,9 +2759,7 @@ static void demo_run_display(struct demo *demo) * Return 1 (true) if all layer names specified in check_names * can be found in given layer properties. */ -static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, - uint32_t layer_count, - VkLayerProperties *layers) { +static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) { for (uint32_t i = 0; i < check_count; i++) { VkBool32 found = 0; for (uint32_t j = 0; j < layer_count; j++) { @@ -2955,36 +2785,26 @@ static void demo_init_vk(struct demo *demo) { demo->enabled_extension_count = 0; demo->enabled_layer_count = 0; - char *instance_validation_layers_alt1[] = { - "VK_LAYER_LUNARG_standard_validation" - }; + char *instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"}; - char *instance_validation_layers_alt2[] = { - "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", - "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", - "VK_LAYER_GOOGLE_unique_objects" - }; + char *instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", + "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", + "VK_LAYER_GOOGLE_unique_objects"}; /* Look for validation layers */ VkBool32 validation_found = 0; if (demo->validate) { - err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL); assert(!err); instance_validation_layers = instance_validation_layers_alt1; if (instance_layer_count > 0) { - VkLayerProperties *instance_layers = - malloc(sizeof (VkLayerProperties) * instance_layer_count); - err = vkEnumerateInstanceLayerProperties(&instance_layer_count, - instance_layers); + VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count); + err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers); assert(!err); - - validation_found = demo_check_layers( - ARRAY_SIZE(instance_validation_layers_alt1), - instance_validation_layers, instance_layer_count, - instance_layers); + validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers, + instance_layer_count, instance_layers); if (validation_found) { demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1); demo->enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation"; @@ -2993,12 +2813,9 @@ static void demo_init_vk(struct demo *demo) { // use alternative set of validation layers instance_validation_layers = instance_validation_layers_alt2; demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); - validation_found = demo_check_layers( - ARRAY_SIZE(instance_validation_layers_alt2), - instance_validation_layers, instance_layer_count, - instance_layers); - validation_layer_count = - ARRAY_SIZE(instance_validation_layers_alt2); + validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers, + instance_layer_count, instance_layers); + validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); for (uint32_t i = 0; i < validation_layer_count; i++) { demo->enabled_layers[i] = instance_validation_layers[i]; } @@ -3007,11 +2824,10 @@ static void demo_init_vk(struct demo *demo) { } if (!validation_found) { - ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find " - "required validation layer.\n\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT( + "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); } } @@ -3020,65 +2836,48 @@ static void demo_init_vk(struct demo *demo) { VkBool32 platformSurfaceExtFound = 0; memset(demo->extension_names, 0, sizeof(demo->extension_names)); - err = vkEnumerateInstanceExtensionProperties( - NULL, &instance_extension_count, NULL); + err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL); assert(!err); if (instance_extension_count > 0) { - VkExtensionProperties *instance_extensions = - malloc(sizeof(VkExtensionProperties) * instance_extension_count); - err = vkEnumerateInstanceExtensionProperties( - NULL, &instance_extension_count, instance_extensions); + VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count); + err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions); assert(!err); for (uint32_t i = 0; i < instance_extension_count; i++) { - if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { surfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME; } #if defined(VK_USE_PLATFORM_WIN32_KHR) - if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_WIN32_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_XLIB_KHR) - if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_XLIB_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_XCB_KHR) - if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_XCB_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_DISPLAY_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_ANDROID_KHR) - if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { platformSurfaceExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; } #elif defined(VK_USE_PLATFORM_IOS_MVK) if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { @@ -3091,11 +2890,9 @@ static void demo_init_vk(struct demo *demo) { demo->extension_names[demo->enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME; } #endif - if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, - instance_extensions[i].extensionName)) { + if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instance_extensions[i].extensionName)) { if (demo->validate) { - demo->extension_names[demo->enabled_extension_count++] = - VK_EXT_DEBUG_REPORT_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_REPORT_EXTENSION_NAME; } } assert(demo->enabled_extension_count < 64); @@ -3105,77 +2902,61 @@ static void demo_init_vk(struct demo *demo) { } if (!surfaceExtFound) { - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); } if (!platformSurfaceExtFound) { #if defined(VK_USE_PLATFORM_WIN32_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_IOS_MVK) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_MVK_IOS_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_MACOS_MVK) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " - VK_MVK_MACOS_SURFACE_EXTENSION_NAME" extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_XCB_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_DISPLAY_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_ANDROID_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_XLIB_KHR) - ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); #endif } @@ -3210,15 +2991,14 @@ static void demo_init_vk(struct demo *demo) { dbgCreateInfoTemp.pNext = NULL; dbgCreateInfoTemp.pfnCallback = demo->use_break ? BreakCallback : dbgFunc; dbgCreateInfoTemp.pUserData = demo; - dbgCreateInfoTemp.flags = - VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; + dbgCreateInfoTemp.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; if (demo->validate_checks_disabled) { val_flags.sType = VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT; val_flags.pNext = NULL; val_flags.disabledValidationCheckCount = 1; VkValidationCheckEXT disabled_check = VK_VALIDATION_CHECK_ALL_EXT; val_flags.pDisabledValidationChecks = &disabled_check; - dbgCreateInfoTemp.pNext = (void*)&val_flags; + dbgCreateInfoTemp.pNext = (void *)&val_flags; } inst_info.pNext = &dbgCreateInfoTemp; } @@ -3227,19 +3007,21 @@ static void demo_init_vk(struct demo *demo) { err = vkCreateInstance(&inst_info, NULL, &demo->inst); if (err == VK_ERROR_INCOMPATIBLE_DRIVER) { - ERR_EXIT("Cannot find a compatible Vulkan installable client driver " - "(ICD).\n\nPlease look at the Getting Started guide for " - "additional information.\n", - "vkCreateInstance Failure"); + ERR_EXIT( + "Cannot find a compatible Vulkan installable client driver (ICD).\n\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) { - ERR_EXIT("Cannot find a specified extension library" - ".\nMake sure your layers path is set appropriately.\n", - "vkCreateInstance Failure"); + ERR_EXIT( + "Cannot find a specified extension library.\n" + "Make sure your layers path is set appropriately.\n", + "vkCreateInstance Failure"); } else if (err) { - ERR_EXIT("vkCreateInstance failed.\n\nDo you have a compatible Vulkan " - "installable client driver (ICD) installed?\nPlease look at " - "the Getting Started guide for additional information.\n", - "vkCreateInstance Failure"); + ERR_EXIT( + "vkCreateInstance failed.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); } /* Make initial call to query gpu_count, then second call for gpu info*/ @@ -3254,11 +3036,11 @@ static void demo_init_vk(struct demo *demo) { demo->gpu = physical_devices[0]; free(physical_devices); } else { - ERR_EXIT("vkEnumeratePhysicalDevices reported zero accessible devices.\n\n" - "Do you have a compatible Vulkan installable client driver (ICD) " - "installed?\nPlease look at the Getting Started guide for " - "additional information.\n", - "vkEnumeratePhysicalDevices Failure"); + ERR_EXIT( + "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkEnumeratePhysicalDevices Failure"); } /* Look for device extensions */ @@ -3267,23 +3049,18 @@ static void demo_init_vk(struct demo *demo) { demo->enabled_extension_count = 0; memset(demo->extension_names, 0, sizeof(demo->extension_names)); - err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, - &device_extension_count, NULL); + err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL); assert(!err); if (device_extension_count > 0) { - VkExtensionProperties *device_extensions = - malloc(sizeof(VkExtensionProperties) * device_extension_count); - err = vkEnumerateDeviceExtensionProperties( - demo->gpu, NULL, &device_extension_count, device_extensions); + VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count); + err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions); assert(!err); for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, - device_extensions[i].extensionName)) { + if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) { swapchainExtFound = 1; - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_SWAPCHAIN_EXTENSION_NAME; + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; } assert(demo->enabled_extension_count < 64); } @@ -3295,10 +3072,8 @@ static void demo_init_vk(struct demo *demo) { // enumerated. demo->VK_KHR_incremental_present_enabled = false; for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, - device_extensions[i].extensionName)) { - demo->extension_names[demo->enabled_extension_count++] = - VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME; + if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) { + demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME; demo->VK_KHR_incremental_present_enabled = true; DbgMsg("VK_KHR_incremental_present extension enabled\n"); } @@ -3316,10 +3091,8 @@ static void demo_init_vk(struct demo *demo) { // enumerated. demo->VK_GOOGLE_display_timing_enabled = false; for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, - device_extensions[i].extensionName)) { - demo->extension_names[demo->enabled_extension_count++] = - VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME; + if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) { + demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME; demo->VK_GOOGLE_display_timing_enabled = true; DbgMsg("VK_GOOGLE_display_timing extension enabled\n"); } @@ -3334,38 +3107,26 @@ static void demo_init_vk(struct demo *demo) { } if (!swapchainExtFound) { - ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find " - "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME - " extension.\n\nDo you have a compatible " - "Vulkan installable client driver (ICD) installed?\nPlease " - "look at the Getting Started guide for additional " - "information.\n", + ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME + " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", "vkCreateInstance Failure"); } if (demo->validate) { demo->CreateDebugReportCallback = - (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr( - demo->inst, "vkCreateDebugReportCallbackEXT"); + (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugReportCallbackEXT"); demo->DestroyDebugReportCallback = - (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr( - demo->inst, "vkDestroyDebugReportCallbackEXT"); + (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugReportCallbackEXT"); if (!demo->CreateDebugReportCallback) { - ERR_EXIT( - "GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT("GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", "vkGetProcAddr Failure"); } if (!demo->DestroyDebugReportCallback) { - ERR_EXIT( - "GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT("GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n", "vkGetProcAddr Failure"); } - demo->DebugReportMessage = - (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr( - demo->inst, "vkDebugReportMessageEXT"); + demo->DebugReportMessage = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkDebugReportMessageEXT"); if (!demo->DebugReportMessage) { - ERR_EXIT("GetProcAddr: Unable to find vkDebugReportMessageEXT\n", - "vkGetProcAddr Failure"); + ERR_EXIT("GetProcAddr: Unable to find vkDebugReportMessageEXT\n", "vkGetProcAddr Failure"); } VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; @@ -3375,34 +3136,27 @@ static void demo_init_vk(struct demo *demo) { dbgCreateInfo.pNext = NULL; dbgCreateInfo.pfnCallback = callback; dbgCreateInfo.pUserData = demo; - dbgCreateInfo.flags = - VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; - err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL, - &demo->msg_callback); + dbgCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; + err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL, &demo->msg_callback); switch (err) { - case VK_SUCCESS: - break; - case VK_ERROR_OUT_OF_HOST_MEMORY: - ERR_EXIT("CreateDebugReportCallback: out of host memory\n", - "CreateDebugReportCallback Failure"); - break; - default: - ERR_EXIT("CreateDebugReportCallback: unknown failure\n", - "CreateDebugReportCallback Failure"); - break; + case VK_SUCCESS: + break; + case VK_ERROR_OUT_OF_HOST_MEMORY: + ERR_EXIT("CreateDebugReportCallback: out of host memory\n", "CreateDebugReportCallback Failure"); + break; + default: + ERR_EXIT("CreateDebugReportCallback: unknown failure\n", "CreateDebugReportCallback Failure"); + break; } } vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props); /* Call with NULL data to get count */ - vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, - &demo->queue_family_count, NULL); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL); assert(demo->queue_family_count >= 1); - demo->queue_props = (VkQueueFamilyProperties *)malloc( - demo->queue_family_count * sizeof(VkQueueFamilyProperties)); - vkGetPhysicalDeviceQueueFamilyProperties( - demo->gpu, &demo->queue_family_count, demo->queue_props); + demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties)); + vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props); // Query fine-grained feature support for this device. // If app has specific feature requirements it should check supported @@ -3437,8 +3191,7 @@ static void demo_create_device(struct demo *demo) { .ppEnabledLayerNames = NULL, .enabledExtensionCount = demo->enabled_extension_count, .ppEnabledExtensionNames = (const char *const *)demo->extension_names, - .pEnabledFeatures = - NULL, // If specific features are required, pass them in here + .pEnabledFeatures = NULL, // If specific features are required, pass them in here }; if (demo->separate_present_queue) { queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; @@ -3465,8 +3218,7 @@ static void demo_init_vk_swapchain(struct demo *demo) { createInfo.hinstance = demo->connection; createInfo.hwnd = demo->window; - err = - vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); + err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) VkWaylandSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR; @@ -3475,15 +3227,14 @@ static void demo_init_vk_swapchain(struct demo *demo) { createInfo.display = demo->display; createInfo.surface = demo->window; - err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, - &demo->surface); + err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_ANDROID_KHR) VkAndroidSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; createInfo.pNext = NULL; createInfo.flags = 0; - createInfo.window = (ANativeWindow*)(demo->window); + createInfo.window = (ANativeWindow *)(demo->window); err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #elif defined(VK_USE_PLATFORM_XLIB_KHR) @@ -3494,8 +3245,7 @@ static void demo_init_vk_swapchain(struct demo *demo) { createInfo.dpy = demo->display; createInfo.window = demo->xlib_window; - err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, - &demo->surface); + err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); #elif defined(VK_USE_PLATFORM_XCB_KHR) VkXcbSurfaceCreateInfoKHR createInfo; createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR; @@ -3527,11 +3277,9 @@ static void demo_init_vk_swapchain(struct demo *demo) { assert(!err); // Iterate over each queue to learn whether it supports presenting: - VkBool32 *supportsPresent = - (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32)); + VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32)); for (uint32_t i = 0; i < demo->queue_family_count; i++) { - demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, - &supportsPresent[i]); + demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]); } // Search for a graphics and a present queue in the array of queue @@ -3564,16 +3312,13 @@ static void demo_init_vk_swapchain(struct demo *demo) { } // Generate error if could not find both a graphics and a present queue - if (graphicsQueueFamilyIndex == UINT32_MAX || - presentQueueFamilyIndex == UINT32_MAX) { - ERR_EXIT("Could not find both graphics and present queues\n", - "Swapchain Initialization Failure"); + if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) { + ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure"); } demo->graphics_queue_family_index = graphicsQueueFamilyIndex; demo->present_queue_family_index = presentQueueFamilyIndex; - demo->separate_present_queue = - (demo->graphics_queue_family_index != demo->present_queue_family_index); + demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index); free(supportsPresent); demo_create_device(demo); @@ -3588,25 +3333,20 @@ static void demo_init_vk_swapchain(struct demo *demo) { GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE); } - vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, - &demo->graphics_queue); + vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue); if (!demo->separate_present_queue) { demo->present_queue = demo->graphics_queue; } else { - vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, - &demo->present_queue); + vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue); } // Get the list of VkFormat's that are supported: uint32_t formatCount; - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, - &formatCount, NULL); + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL); assert(!err); - VkSurfaceFormatKHR *surfFormats = - (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); - err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, - &formatCount, surfFormats); + VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); + err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats); assert(!err); // If the format list includes just one entry of VK_FORMAT_UNDEFINED, // the surface has no preferred format. Otherwise, at least one @@ -3633,25 +3373,19 @@ static void demo_init_vk_swapchain(struct demo *demo) { // Create fences that we can use to throttle if we get too far // ahead of the image presents VkFenceCreateInfo fence_ci = { - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .pNext = NULL, - .flags = VK_FENCE_CREATE_SIGNALED_BIT - }; + .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT}; for (uint32_t i = 0; i < FRAME_LAG; i++) { err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]); assert(!err); - err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, - &demo->image_acquired_semaphores[i]); + err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]); assert(!err); - err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, - &demo->draw_complete_semaphores[i]); + err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]); assert(!err); if (demo->separate_present_queue) { - err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, - &demo->image_ownership_semaphores[i]); + err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]); assert(!err); } } @@ -3755,12 +3489,9 @@ static void registry_handle_global(void *data, struct wl_registry *registry, uin } } -static void registry_handle_global_remove(void *data UNUSED, - struct wl_registry *registry UNUSED, - uint32_t name UNUSED) {} +static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {} -static const struct wl_registry_listener registry_listener = { - registry_handle_global, registry_handle_global_remove}; +static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove}; #elif defined(VK_USE_PLATFORM_MIR_KHR) #endif @@ -3779,24 +3510,21 @@ static void demo_init_connection(struct demo *demo) { demo->connection = xcb_connect(NULL, &scr); if (xcb_connection_has_error(demo->connection) > 0) { - printf("Cannot find a compatible Vulkan installable client driver " - "(ICD).\nExiting ...\n"); + printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n"); fflush(stdout); exit(1); } setup = xcb_get_setup(demo->connection); iter = xcb_setup_roots_iterator(setup); - while (scr-- > 0) - xcb_screen_next(&iter); + while (scr-- > 0) xcb_screen_next(&iter); demo->screen = iter.data; #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) demo->display = wl_display_connect(NULL); if (demo->display == NULL) { - printf("Cannot find a compatible Vulkan installable client driver " - "(ICD).\nExiting ...\n"); + printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n"); fflush(stdout); exit(1); } @@ -3822,9 +3550,8 @@ static void demo_init(struct demo *demo, int argc, char **argv) { demo->use_staging_buffer = true; continue; } - if ((strcmp(argv[i], "--present_mode") == 0) && - (i < argc - 1)) { - demo->presentMode = atoi(argv[i+1]); + if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) { + demo->presentMode = atoi(argv[i + 1]); i++; continue; } @@ -3845,9 +3572,8 @@ static void demo_init(struct demo *demo, int argc, char **argv) { fprintf(stderr, "--xlib is deprecated and no longer does anything"); continue; } - if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && - i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && - demo->frameCount >= 0) { + if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 && + sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) { i++; continue; } @@ -3896,22 +3622,20 @@ static void demo_init(struct demo *demo, int argc, char **argv) { demo->spin_increment = 0.2f; demo->pause = false; - mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), - 1.0f, 0.1f, 100.0f); + mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f); mat4x4_look_at(demo->view_matrix, eye, origin, up); mat4x4_identity(demo->model_matrix); - demo->projection_matrix[1][1]*=-1; //Flip projection matrix from GL to Vulkan orientation. + demo->projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation. } #if defined(VK_USE_PLATFORM_WIN32_KHR) // Include header required for parsing the command line options. #include -int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, - int nCmdShow) { - MSG msg; // message - bool done; // flag saying when app is complete +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) { + MSG msg; // message + bool done; // flag saying when app is complete int argc; char **argv; @@ -3940,8 +3664,7 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1)); if (argv[iii] != NULL) { - wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, - commandLineArgs[iii], wideCharLen + 1); + wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1); } } } @@ -3968,14 +3691,14 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, demo_prepare(&demo); - done = false; // initialize loop condition variable + done = false; // initialize loop condition variable // main message loop while (!done) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); - if (msg.message == WM_QUIT) // check for a quit message + if (msg.message == WM_QUIT) // check for a quit message { - done = true; // if found, quit app + done = true; // if found, quit app } else { /* Translate and dispatch to event queue*/ TranslateMessage(&msg); @@ -3990,11 +3713,11 @@ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, } #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK) -static void demo_main(struct demo *demo, void* view) { - const char* argv[] = { "CubeSample" }; - int argc = sizeof(argv) / sizeof(char*); +static void demo_main(struct demo *demo, void *view) { + const char *argv[] = {"CubeSample"}; + int argc = sizeof(argv) / sizeof(char *); - demo_init(demo, argc, (char**)argv); + demo_init(demo, argc, (char **)argv); demo->window = view; demo_init_vk_swapchain(demo); demo_prepare(demo); @@ -4018,12 +3741,10 @@ static bool initialized = false; static bool active = false; struct demo demo; -static int32_t processInput(struct android_app* app, AInputEvent* event) { - return 0; -} +static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; } -static void processCommand(struct android_app* app, int32_t cmd) { - switch(cmd) { +static void processCommand(struct android_app *app, int32_t cmd) { + switch (cmd) { case APP_CMD_INIT_WINDOW: { if (app->window) { // We're getting a new window. If the app is starting up, we @@ -4044,21 +3765,19 @@ static void processCommand(struct android_app* app, int32_t cmd) { // Use the following key to send arguments, i.e. // --es args "--validate" const char key[] = "args"; - char* appTag = (char*) APP_SHORT_NAME; + char *appTag = (char *)APP_SHORT_NAME; int argc = 0; - char** argv = get_args(app, key, appTag, &argc); + char **argv = get_args(app, key, appTag, &argc); __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc); - for (int i = 0; i < argc; i++) - __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]); + for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]); demo_init(&demo, argc, argv); // Free the argv malloc'd by get_args - for (int i = 0; i < argc; i++) - free(argv[i]); + for (int i = 0; i < argc; i++) free(argv[i]); - demo.window = (void*)app->window; + demo.window = (void *)app->window; demo_init_vk_swapchain(&demo); demo_prepare(&demo); initialized = true; @@ -4076,12 +3795,10 @@ static void processCommand(struct android_app* app, int32_t cmd) { } } -void android_main(struct android_app *app) -{ +void android_main(struct android_app *app) { #ifdef ANDROID int vulkanSupport = InitVulkan(); - if (vulkanSupport == 0) - return; + if (vulkanSupport == 0) return; #endif demo.prepared = false; @@ -4089,10 +3806,10 @@ void android_main(struct android_app *app) app->onAppCmd = processCommand; app->onInputEvent = processInput; - while(1) { + while (1) { int events; - struct android_poll_source* source; - while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void**)&source) >= 0) { + struct android_poll_source *source; + while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) { if (source) { source->process(app, source); } @@ -4106,7 +3823,6 @@ void android_main(struct android_app *app) demo_run(&demo); } } - } #else int main(int argc, char **argv) { diff --git a/demos/cube.cpp b/demos/cube.cpp index f436cd56..fe8cb7c9 100644 --- a/demos/cube.cpp +++ b/demos/cube.cpp @@ -1,22 +1,22 @@ /* -* Copyright (c) 2015-2016 The Khronos Group Inc. -* Copyright (c) 2015-2016 Valve Corporation -* Copyright (c) 2015-2016 LunarG, Inc. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -* Author: Jeremy Hayes -*/ + * Copyright (c) 2015-2016 The Khronos Group Inc. + * Copyright (c) 2015-2016 Valve Corporation + * Copyright (c) 2015-2016 LunarG, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Author: Jeremy Hayes + */ #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR) #include @@ -552,2273 +552,2226 @@ Demo::Demo() current_buffer{0}, queue_family_count{0} { #if defined(VK_USE_PLATFORM_WIN32_KHR) - memset(name, '\0', APP_NAME_STR_LEN); + memset(name, '\0', APP_NAME_STR_LEN); #endif - memset(projection_matrix, 0, sizeof(projection_matrix)); - memset(view_matrix, 0, sizeof(view_matrix)); - memset(model_matrix, 0, sizeof(model_matrix)); - } - - void Demo::build_image_ownership_cmd(uint32_t const &i) { - auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse); - auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info); - VERIFY(result == vk::Result::eSuccess); - - auto const image_ownership_barrier = - vk::ImageMemoryBarrier() - .setSrcAccessMask(vk::AccessFlags()) - .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite) - .setOldLayout(vk::ImageLayout::ePresentSrcKHR) - .setNewLayout(vk::ImageLayout::ePresentSrcKHR) - .setSrcQueueFamilyIndex(graphics_queue_family_index) - .setDstQueueFamilyIndex(present_queue_family_index) - .setImage(swapchain_image_resources[i].image) - .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - - swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier( - vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput, - vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier); + memset(projection_matrix, 0, sizeof(projection_matrix)); + memset(view_matrix, 0, sizeof(view_matrix)); + memset(model_matrix, 0, sizeof(model_matrix)); +} - result = swapchain_image_resources[i].graphics_to_present_cmd.end(); - VERIFY(result == vk::Result::eSuccess); - } +void Demo::build_image_ownership_cmd(uint32_t const &i) { + auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse); + auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info); + VERIFY(result == vk::Result::eSuccess); + + auto const image_ownership_barrier = + vk::ImageMemoryBarrier() + .setSrcAccessMask(vk::AccessFlags()) + .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite) + .setOldLayout(vk::ImageLayout::ePresentSrcKHR) + .setNewLayout(vk::ImageLayout::ePresentSrcKHR) + .setSrcQueueFamilyIndex(graphics_queue_family_index) + .setDstQueueFamilyIndex(present_queue_family_index) + .setImage(swapchain_image_resources[i].image) + .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); + + swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier( + vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput, + vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier); + + result = swapchain_image_resources[i].graphics_to_present_cmd.end(); + VERIFY(result == vk::Result::eSuccess); +} - vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count, - vk::LayerProperties *layers) { - for (uint32_t i = 0; i < check_count; i++) { - vk::Bool32 found = VK_FALSE; - for (uint32_t j = 0; j < layer_count; j++) { - if (!strcmp(check_names[i], layers[j].layerName)) { - found = VK_TRUE; - break; - } - } - if (!found) { - fprintf(stderr, "Cannot find layer: %s\n", check_names[i]); - return 0; +vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count, + vk::LayerProperties *layers) { + for (uint32_t i = 0; i < check_count; i++) { + vk::Bool32 found = VK_FALSE; + for (uint32_t j = 0; j < layer_count; j++) { + if (!strcmp(check_names[i], layers[j].layerName)) { + found = VK_TRUE; + break; } } - return VK_TRUE; + if (!found) { + fprintf(stderr, "Cannot find layer: %s\n", check_names[i]); + return 0; + } } + return VK_TRUE; +} - void Demo::cleanup() { - prepared = false; - device.waitIdle(); +void Demo::cleanup() { + prepared = false; + device.waitIdle(); - // Wait for fences from present operations - for (uint32_t i = 0; i < FRAME_LAG; i++) { - device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX); - device.destroyFence(fences[i], nullptr); - device.destroySemaphore(image_acquired_semaphores[i], nullptr); - device.destroySemaphore(draw_complete_semaphores[i], nullptr); - if (separate_present_queue) { - device.destroySemaphore(image_ownership_semaphores[i], nullptr); - } + // Wait for fences from present operations + for (uint32_t i = 0; i < FRAME_LAG; i++) { + device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX); + device.destroyFence(fences[i], nullptr); + device.destroySemaphore(image_acquired_semaphores[i], nullptr); + device.destroySemaphore(draw_complete_semaphores[i], nullptr); + if (separate_present_queue) { + device.destroySemaphore(image_ownership_semaphores[i], nullptr); } + } - for (uint32_t i = 0; i < swapchainImageCount; i++) { - device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr); - } - device.destroyDescriptorPool(desc_pool, nullptr); - - device.destroyPipeline(pipeline, nullptr); - device.destroyPipelineCache(pipelineCache, nullptr); - device.destroyRenderPass(render_pass, nullptr); - device.destroyPipelineLayout(pipeline_layout, nullptr); - device.destroyDescriptorSetLayout(desc_layout, nullptr); - - for (uint32_t i = 0; i < texture_count; i++) { - device.destroyImageView(textures[i].view, nullptr); - device.destroyImage(textures[i].image, nullptr); - device.freeMemory(textures[i].mem, nullptr); - device.destroySampler(textures[i].sampler, nullptr); - } - device.destroySwapchainKHR(swapchain, nullptr); + for (uint32_t i = 0; i < swapchainImageCount; i++) { + device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr); + } + device.destroyDescriptorPool(desc_pool, nullptr); + + device.destroyPipeline(pipeline, nullptr); + device.destroyPipelineCache(pipelineCache, nullptr); + device.destroyRenderPass(render_pass, nullptr); + device.destroyPipelineLayout(pipeline_layout, nullptr); + device.destroyDescriptorSetLayout(desc_layout, nullptr); + + for (uint32_t i = 0; i < texture_count; i++) { + device.destroyImageView(textures[i].view, nullptr); + device.destroyImage(textures[i].image, nullptr); + device.freeMemory(textures[i].mem, nullptr); + device.destroySampler(textures[i].sampler, nullptr); + } + device.destroySwapchainKHR(swapchain, nullptr); - device.destroyImageView(depth.view, nullptr); - device.destroyImage(depth.image, nullptr); - device.freeMemory(depth.mem, nullptr); + device.destroyImageView(depth.view, nullptr); + device.destroyImage(depth.image, nullptr); + device.freeMemory(depth.mem, nullptr); - for (uint32_t i = 0; i < swapchainImageCount; i++) { - device.destroyImageView(swapchain_image_resources[i].view, nullptr); - device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd); - device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr); - device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr); - } + for (uint32_t i = 0; i < swapchainImageCount; i++) { + device.destroyImageView(swapchain_image_resources[i].view, nullptr); + device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd); + device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr); + device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr); + } - device.destroyCommandPool(cmd_pool, nullptr); + device.destroyCommandPool(cmd_pool, nullptr); - if (separate_present_queue) { - device.destroyCommandPool(present_cmd_pool, nullptr); - } - device.waitIdle(); - device.destroy(nullptr); - inst.destroySurfaceKHR(surface, nullptr); + if (separate_present_queue) { + device.destroyCommandPool(present_cmd_pool, nullptr); + } + device.waitIdle(); + device.destroy(nullptr); + inst.destroySurfaceKHR(surface, nullptr); #if defined(VK_USE_PLATFORM_XLIB_KHR) - XDestroyWindow(display, xlib_window); - XCloseDisplay(display); + XDestroyWindow(display, xlib_window); + XCloseDisplay(display); #elif defined(VK_USE_PLATFORM_XCB_KHR) - xcb_destroy_window(connection, xcb_window); - xcb_disconnect(connection); - free(atom_wm_delete_window); + xcb_destroy_window(connection, xcb_window); + xcb_disconnect(connection); + free(atom_wm_delete_window); #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - wl_keyboard_destroy(keyboard); - wl_pointer_destroy(pointer); - wl_seat_destroy(seat); - wl_shell_surface_destroy(shell_surface); - wl_surface_destroy(window); - wl_shell_destroy(shell); - wl_compositor_destroy(compositor); - wl_registry_destroy(registry); - wl_display_disconnect(display); + wl_keyboard_destroy(keyboard); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + wl_shell_surface_destroy(shell_surface); + wl_surface_destroy(window); + wl_shell_destroy(shell); + wl_compositor_destroy(compositor); + wl_registry_destroy(registry); + wl_display_disconnect(display); #elif defined(VK_USE_PLATFORM_MIR_KHR) #endif - inst.destroy(nullptr); - } - - void Demo::create_device() { - float const priorities[1] = {0.0}; - - vk::DeviceQueueCreateInfo queues[2]; - queues[0].setQueueFamilyIndex(graphics_queue_family_index); - queues[0].setQueueCount(1); - queues[0].setPQueuePriorities(priorities); - - auto deviceInfo = vk::DeviceCreateInfo() - .setQueueCreateInfoCount(1) - .setPQueueCreateInfos(queues) - .setEnabledLayerCount(0) - .setPpEnabledLayerNames(nullptr) - .setEnabledExtensionCount(enabled_extension_count) - .setPpEnabledExtensionNames((const char *const *)extension_names) - .setPEnabledFeatures(nullptr); - - if (separate_present_queue) { - queues[1].setQueueFamilyIndex(present_queue_family_index); - queues[1].setQueueCount(1); - queues[1].setPQueuePriorities(priorities); - deviceInfo.setQueueCreateInfoCount(2); - } - - auto result = gpu.createDevice(&deviceInfo, nullptr, &device); - VERIFY(result == vk::Result::eSuccess); - } + inst.destroy(nullptr); +} - void Demo::destroy_texture_image(texture_object *tex_objs) { - // clean up staging resources - device.freeMemory(tex_objs->mem, nullptr); - device.destroyImage(tex_objs->image, nullptr); +void Demo::create_device() { + float const priorities[1] = {0.0}; + + vk::DeviceQueueCreateInfo queues[2]; + queues[0].setQueueFamilyIndex(graphics_queue_family_index); + queues[0].setQueueCount(1); + queues[0].setPQueuePriorities(priorities); + + auto deviceInfo = vk::DeviceCreateInfo() + .setQueueCreateInfoCount(1) + .setPQueueCreateInfos(queues) + .setEnabledLayerCount(0) + .setPpEnabledLayerNames(nullptr) + .setEnabledExtensionCount(enabled_extension_count) + .setPpEnabledExtensionNames((const char *const *)extension_names) + .setPEnabledFeatures(nullptr); + + if (separate_present_queue) { + queues[1].setQueueFamilyIndex(present_queue_family_index); + queues[1].setQueueCount(1); + queues[1].setPQueuePriorities(priorities); + deviceInfo.setQueueCreateInfoCount(2); } - void Demo::draw() { - // Ensure no more than FRAME_LAG renderings are outstanding - device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX); - device.resetFences(1, &fences[frame_index]); + auto result = gpu.createDevice(&deviceInfo, nullptr, &device); + VERIFY(result == vk::Result::eSuccess); +} - vk::Result result; - do { - result = device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], - vk::Fence(), ¤t_buffer); - if (result == vk::Result::eErrorOutOfDateKHR) { - // demo->swapchain is out of date (e.g. the window was resized) and - // must be recreated: - resize(); - } else if (result == vk::Result::eSuboptimalKHR) { - // swapchain is not as optimal as it could be, but the platform's - // presentation engine will still present the image correctly. - break; - } else { - VERIFY(result == vk::Result::eSuccess); - } - } while (result != vk::Result::eSuccess); - - update_data_buffer(); - - // Wait for the image acquired semaphore to be signaled to ensure - // that the image won't be rendered to until the presentation - // engine has fully released ownership to the application, and it is - // okay to render to the image. - vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput; - auto const submit_info = vk::SubmitInfo() - .setPWaitDstStageMask(&pipe_stage_flags) - .setWaitSemaphoreCount(1) - .setPWaitSemaphores(&image_acquired_semaphores[frame_index]) - .setCommandBufferCount(1) - .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd) - .setSignalSemaphoreCount(1) - .setPSignalSemaphores(&draw_complete_semaphores[frame_index]); - - result = graphics_queue.submit(1, &submit_info, fences[frame_index]); - VERIFY(result == vk::Result::eSuccess); +void Demo::destroy_texture_image(texture_object *tex_objs) { + // clean up staging resources + device.freeMemory(tex_objs->mem, nullptr); + device.destroyImage(tex_objs->image, nullptr); +} - if (separate_present_queue) { - // If we are using separate queues, change image ownership to the - // present queue before presenting, waiting for the draw complete - // semaphore and signalling the ownership released semaphore when - // finished - auto const present_submit_info = vk::SubmitInfo() - .setPWaitDstStageMask(&pipe_stage_flags) - .setWaitSemaphoreCount(1) - .setPWaitSemaphores(&draw_complete_semaphores[frame_index]) - .setCommandBufferCount(1) - .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd) - .setSignalSemaphoreCount(1) - .setPSignalSemaphores(&image_ownership_semaphores[frame_index]); - - result = present_queue.submit(1, &present_submit_info, vk::Fence()); - VERIFY(result == vk::Result::eSuccess); - } +void Demo::draw() { + // Ensure no more than FRAME_LAG renderings are outstanding + device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX); + device.resetFences(1, &fences[frame_index]); - // If we are using separate queues we have to wait for image ownership, - // otherwise wait for draw complete - auto const presentInfo = vk::PresentInfoKHR() - .setWaitSemaphoreCount(1) - .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index] - : &draw_complete_semaphores[frame_index]) - .setSwapchainCount(1) - .setPSwapchains(&swapchain) - .setPImageIndices(¤t_buffer); - - result = present_queue.presentKHR(&presentInfo); - frame_index += 1; - frame_index %= FRAME_LAG; + vk::Result result; + do { + result = + device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), ¤t_buffer); if (result == vk::Result::eErrorOutOfDateKHR) { - // swapchain is out of date (e.g. the window was resized) and + // demo->swapchain is out of date (e.g. the window was resized) and // must be recreated: resize(); } else if (result == vk::Result::eSuboptimalKHR) { // swapchain is not as optimal as it could be, but the platform's // presentation engine will still present the image correctly. + break; } else { VERIFY(result == vk::Result::eSuccess); } + } while (result != vk::Result::eSuccess); + + update_data_buffer(); + + // Wait for the image acquired semaphore to be signaled to ensure + // that the image won't be rendered to until the presentation + // engine has fully released ownership to the application, and it is + // okay to render to the image. + vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput; + auto const submit_info = vk::SubmitInfo() + .setPWaitDstStageMask(&pipe_stage_flags) + .setWaitSemaphoreCount(1) + .setPWaitSemaphores(&image_acquired_semaphores[frame_index]) + .setCommandBufferCount(1) + .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd) + .setSignalSemaphoreCount(1) + .setPSignalSemaphores(&draw_complete_semaphores[frame_index]); + + result = graphics_queue.submit(1, &submit_info, fences[frame_index]); + VERIFY(result == vk::Result::eSuccess); + + if (separate_present_queue) { + // If we are using separate queues, change image ownership to the + // present queue before presenting, waiting for the draw complete + // semaphore and signalling the ownership released semaphore when + // finished + auto const present_submit_info = vk::SubmitInfo() + .setPWaitDstStageMask(&pipe_stage_flags) + .setWaitSemaphoreCount(1) + .setPWaitSemaphores(&draw_complete_semaphores[frame_index]) + .setCommandBufferCount(1) + .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd) + .setSignalSemaphoreCount(1) + .setPSignalSemaphores(&image_ownership_semaphores[frame_index]); + + result = present_queue.submit(1, &present_submit_info, vk::Fence()); + VERIFY(result == vk::Result::eSuccess); } - void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) { - auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse); - - vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array({{0.2f, 0.2f, 0.2f, 0.2f}})), - vk::ClearDepthStencilValue(1.0f, 0u)}; - - auto const passInfo = vk::RenderPassBeginInfo() - .setRenderPass(render_pass) - .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer) - .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height))) - .setClearValueCount(2) - .setPClearValues(clearValues); - - auto result = commandBuffer.begin(&commandInfo); + // If we are using separate queues we have to wait for image ownership, + // otherwise wait for draw complete + auto const presentInfo = vk::PresentInfoKHR() + .setWaitSemaphoreCount(1) + .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index] + : &draw_complete_semaphores[frame_index]) + .setSwapchainCount(1) + .setPSwapchains(&swapchain) + .setPImageIndices(¤t_buffer); + + result = present_queue.presentKHR(&presentInfo); + frame_index += 1; + frame_index %= FRAME_LAG; + if (result == vk::Result::eErrorOutOfDateKHR) { + // swapchain is out of date (e.g. the window was resized) and + // must be recreated: + resize(); + } else if (result == vk::Result::eSuboptimalKHR) { + // swapchain is not as optimal as it could be, but the platform's + // presentation engine will still present the image correctly. + } else { VERIFY(result == vk::Result::eSuccess); + } +} - commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline); - commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline); - commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1, &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr); - - auto const viewport = - vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f); - commandBuffer.setViewport(0, 1, &viewport); +void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) { + auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse); + + vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array({{0.2f, 0.2f, 0.2f, 0.2f}})), + vk::ClearDepthStencilValue(1.0f, 0u)}; + + auto const passInfo = vk::RenderPassBeginInfo() + .setRenderPass(render_pass) + .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer) + .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height))) + .setClearValueCount(2) + .setPClearValues(clearValues); + + auto result = commandBuffer.begin(&commandInfo); + VERIFY(result == vk::Result::eSuccess); + + commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline); + commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline); + commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1, + &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr); + + auto const viewport = + vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f); + commandBuffer.setViewport(0, 1, &viewport); + + vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height)); + commandBuffer.setScissor(0, 1, &scissor); + commandBuffer.draw(12 * 3, 1, 0, 0); + // Note that ending the renderpass changes the image's layout from + // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR + commandBuffer.endRenderPass(); + + if (separate_present_queue) { + // We have to transfer ownership from the graphics queue family to + // the + // present queue family to be able to present. Note that we don't + // have + // to transfer from present queue family back to graphics queue + // family at + // the start of the next frame because we don't care about the + // image's + // contents at that point. + auto const image_ownership_barrier = + vk::ImageMemoryBarrier() + .setSrcAccessMask(vk::AccessFlags()) + .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite) + .setOldLayout(vk::ImageLayout::ePresentSrcKHR) + .setNewLayout(vk::ImageLayout::ePresentSrcKHR) + .setSrcQueueFamilyIndex(graphics_queue_family_index) + .setDstQueueFamilyIndex(present_queue_family_index) + .setImage(swapchain_image_resources[current_buffer].image) + .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height)); - commandBuffer.setScissor(0, 1, &scissor); - commandBuffer.draw(12 * 3, 1, 0, 0); - // Note that ending the renderpass changes the image's layout from - // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR - commandBuffer.endRenderPass(); + commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eBottomOfPipe, + vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier); + } - if (separate_present_queue) { - // We have to transfer ownership from the graphics queue family to - // the - // present queue family to be able to present. Note that we don't - // have - // to transfer from present queue family back to graphics queue - // family at - // the start of the next frame because we don't care about the - // image's - // contents at that point. - auto const image_ownership_barrier = - vk::ImageMemoryBarrier() - .setSrcAccessMask(vk::AccessFlags()) - .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite) - .setOldLayout(vk::ImageLayout::ePresentSrcKHR) - .setNewLayout(vk::ImageLayout::ePresentSrcKHR) - .setSrcQueueFamilyIndex(graphics_queue_family_index) - .setDstQueueFamilyIndex(present_queue_family_index) - .setImage(swapchain_image_resources[current_buffer].image) - .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - - commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, - vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0, - nullptr, 1, &image_ownership_barrier); - } + result = commandBuffer.end(); + VERIFY(result == vk::Result::eSuccess); +} - result = commandBuffer.end(); - VERIFY(result == vk::Result::eSuccess); +void Demo::flush_init_cmd() { + // TODO: hmm. + // This function could get called twice if the texture uses a staging + // buffer + // In that case the second call should be ignored + if (!cmd) { + return; } - void Demo::flush_init_cmd() { - // TODO: hmm. - // This function could get called twice if the texture uses a staging - // buffer - // In that case the second call should be ignored - if (!cmd) { - return; - } + auto result = cmd.end(); + VERIFY(result == vk::Result::eSuccess); - auto result = cmd.end(); - VERIFY(result == vk::Result::eSuccess); + auto const fenceInfo = vk::FenceCreateInfo(); + vk::Fence fence; + result = device.createFence(&fenceInfo, nullptr, &fence); + VERIFY(result == vk::Result::eSuccess); - auto const fenceInfo = vk::FenceCreateInfo(); - vk::Fence fence; - result = device.createFence(&fenceInfo, nullptr, &fence); - VERIFY(result == vk::Result::eSuccess); + vk::CommandBuffer const commandBuffers[] = {cmd}; + auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers); - vk::CommandBuffer const commandBuffers[] = {cmd}; - auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers); + result = graphics_queue.submit(1, &submitInfo, fence); + VERIFY(result == vk::Result::eSuccess); - result = graphics_queue.submit(1, &submitInfo, fence); - VERIFY(result == vk::Result::eSuccess); + result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX); + VERIFY(result == vk::Result::eSuccess); - result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX); - VERIFY(result == vk::Result::eSuccess); + device.freeCommandBuffers(cmd_pool, 1, commandBuffers); + device.destroyFence(fence, nullptr); - device.freeCommandBuffers(cmd_pool, 1, commandBuffers); - device.destroyFence(fence, nullptr); + cmd = vk::CommandBuffer(); +} - cmd = vk::CommandBuffer(); +void Demo::init(int argc, char **argv) { + vec3 eye = {0.0f, 3.0f, 5.0f}; + vec3 origin = {0, 0, 0}; + vec3 up = {0.0f, 1.0f, 0.0}; + + presentMode = vk::PresentModeKHR::eFifo; + frameCount = UINT32_MAX; + use_xlib = false; + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--use_staging") == 0) { + use_staging_buffer = true; + continue; + } + if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) { + presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]); + i++; + continue; + } + if (strcmp(argv[i], "--break") == 0) { + use_break = true; + continue; + } + if (strcmp(argv[i], "--validate") == 0) { + validate = true; + continue; + } + if (strcmp(argv[i], "--xlib") == 0) { + fprintf(stderr, "--xlib is deprecated and no longer does anything"); + continue; + } + if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 && + sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) { + i++; + continue; + } + if (strcmp(argv[i], "--suppress_popups") == 0) { + suppress_popups = true; + continue; + } + + fprintf(stderr, + "Usage:\n %s [--use_staging] [--validate] [--break] [--c ] \n" + " [--suppress_popups] [--present_mode {0,1,2,3}]\n" + "\n" + "Options for --present_mode:\n" + " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n" + " %d: VK_PRESENT_MODE_MAILBOX_KHR\n" + " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n" + " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n", + APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, + VK_PRESENT_MODE_FIFO_RELAXED_KHR); + fflush(stderr); + exit(1); } - void Demo::init(int argc, char **argv) { - vec3 eye = {0.0f, 3.0f, 5.0f}; - vec3 origin = {0, 0, 0}; - vec3 up = {0.0f, 1.0f, 0.0}; - - presentMode = vk::PresentModeKHR::eFifo; - frameCount = UINT32_MAX; - use_xlib = false; - - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "--use_staging") == 0) { - use_staging_buffer = true; - continue; - } - if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) { - presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]); - i++; - continue; - } - if (strcmp(argv[i], "--break") == 0) { - use_break = true; - continue; - } - if (strcmp(argv[i], "--validate") == 0) { - validate = true; - continue; - } - if (strcmp(argv[i], "--xlib") == 0) { - fprintf(stderr, "--xlib is deprecated and no longer does anything"); - continue; - } - if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 && - sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) { - i++; - continue; - } - if (strcmp(argv[i], "--suppress_popups") == 0) { - suppress_popups = true; - continue; - } - - fprintf(stderr, - "Usage:\n %s [--use_staging] [--validate] [--break] [--c ] \n" - " [--suppress_popups] [--present_mode {0,1,2,3}]\n" - "\n" - "Options for --present_mode:\n" - " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n" - " %d: VK_PRESENT_MODE_MAILBOX_KHR\n" - " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n" - " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n", - APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, - VK_PRESENT_MODE_FIFO_RELAXED_KHR); - fflush(stderr); - exit(1); - } - - if (!use_xlib) { - init_connection(); - } + if (!use_xlib) { + init_connection(); + } - init_vk(); + init_vk(); - width = 500; - height = 500; + width = 500; + height = 500; - spin_angle = 4.0f; - spin_increment = 0.2f; - pause = false; + spin_angle = 4.0f; + spin_increment = 0.2f; + pause = false; - mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f); - mat4x4_look_at(view_matrix, eye, origin, up); - mat4x4_identity(model_matrix); + mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f); + mat4x4_look_at(view_matrix, eye, origin, up); + mat4x4_identity(model_matrix); - projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation. - } + projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation. +} - void Demo::init_connection() { +void Demo::init_connection() { #if defined(VK_USE_PLATFORM_XCB_KHR) - const xcb_setup_t *setup; - xcb_screen_iterator_t iter; - int scr; - - const char *display_envar = getenv("DISPLAY"); - if (display_envar == nullptr || display_envar[0] == '\0') { - printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n"); - fflush(stdout); - exit(1); - } + const xcb_setup_t *setup; + xcb_screen_iterator_t iter; + int scr; + + const char *display_envar = getenv("DISPLAY"); + if (display_envar == nullptr || display_envar[0] == '\0') { + printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n"); + fflush(stdout); + exit(1); + } - connection = xcb_connect(nullptr, &scr); - if (xcb_connection_has_error(connection) > 0) { - printf( - "Cannot find a compatible Vulkan installable client driver " - "(ICD).\nExiting ...\n"); - fflush(stdout); - exit(1); - } + connection = xcb_connect(nullptr, &scr); + if (xcb_connection_has_error(connection) > 0) { + printf( + "Cannot find a compatible Vulkan installable client driver " + "(ICD).\nExiting ...\n"); + fflush(stdout); + exit(1); + } - setup = xcb_get_setup(connection); - iter = xcb_setup_roots_iterator(setup); - while (scr-- > 0) xcb_screen_next(&iter); + setup = xcb_get_setup(connection); + iter = xcb_setup_roots_iterator(setup); + while (scr-- > 0) xcb_screen_next(&iter); - screen = iter.data; + screen = iter.data; #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - display = wl_display_connect(nullptr); - - if (display == nullptr) { - printf( - "Cannot find a compatible Vulkan installable client driver " - "(ICD).\nExiting ...\n"); - fflush(stdout); - exit(1); - } + display = wl_display_connect(nullptr); + + if (display == nullptr) { + printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n"); + fflush(stdout); + exit(1); + } - registry = wl_display_get_registry(display); - wl_registry_add_listener(registry, ®istry_listener, this); - wl_display_dispatch(display); + registry = wl_display_get_registry(display); + wl_registry_add_listener(registry, ®istry_listener, this); + wl_display_dispatch(display); #elif defined(VK_USE_PLATFORM_MIR_KHR) #endif - } +} - void Demo::init_vk() { - uint32_t instance_extension_count = 0; - uint32_t instance_layer_count = 0; - uint32_t validation_layer_count = 0; - char const *const *instance_validation_layers = nullptr; - enabled_extension_count = 0; - enabled_layer_count = 0; +void Demo::init_vk() { + uint32_t instance_extension_count = 0; + uint32_t instance_layer_count = 0; + uint32_t validation_layer_count = 0; + char const *const *instance_validation_layers = nullptr; + enabled_extension_count = 0; + enabled_layer_count = 0; - char const *const instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"}; + char const *const instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"}; - char const *const instance_validation_layers_alt2[] = { - "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", "VK_LAYER_LUNARG_object_tracker", - "VK_LAYER_LUNARG_core_validation", "VK_LAYER_GOOGLE_unique_objects"}; + char const *const instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation", + "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation", + "VK_LAYER_GOOGLE_unique_objects"}; - // Look for validation layers - vk::Bool32 validation_found = VK_FALSE; - if (validate) { - auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr); - VERIFY(result == vk::Result::eSuccess); + // Look for validation layers + vk::Bool32 validation_found = VK_FALSE; + if (validate) { + auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - instance_validation_layers = instance_validation_layers_alt1; - if (instance_layer_count > 0) { - std::unique_ptr instance_layers(new vk::LayerProperties[instance_layer_count]); - result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get()); - VERIFY(result == vk::Result::eSuccess); + instance_validation_layers = instance_validation_layers_alt1; + if (instance_layer_count > 0) { + std::unique_ptr instance_layers(new vk::LayerProperties[instance_layer_count]); + result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get()); + VERIFY(result == vk::Result::eSuccess); - validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers, + validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers, + instance_layer_count, instance_layers.get()); + if (validation_found) { + enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1); + enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation"; + validation_layer_count = 1; + } else { + // use alternative set of validation layers + instance_validation_layers = instance_validation_layers_alt2; + enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); + validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers, instance_layer_count, instance_layers.get()); - if (validation_found) { - enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1); - enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation"; - validation_layer_count = 1; - } else { - // use alternative set of validation layers - instance_validation_layers = instance_validation_layers_alt2; - enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); - validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers, - instance_layer_count, instance_layers.get()); - validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); - for (uint32_t i = 0; i < validation_layer_count; i++) { - enabled_layers[i] = instance_validation_layers[i]; - } + validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2); + for (uint32_t i = 0; i < validation_layer_count; i++) { + enabled_layers[i] = instance_validation_layers[i]; } } + } - if (!validation_found) { - ERR_EXIT( - "vkEnumerateInstanceLayerProperties failed to find " - "required validation layer.\n\n" - "Please look at the Getting Started guide for " - "additional information.\n", - "vkCreateInstance Failure"); - } + if (!validation_found) { + ERR_EXIT( + "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); } + } - /* Look for instance extensions */ - vk::Bool32 surfaceExtFound = VK_FALSE; - vk::Bool32 platformSurfaceExtFound = VK_FALSE; - memset(extension_names, 0, sizeof(extension_names)); + /* Look for instance extensions */ + vk::Bool32 surfaceExtFound = VK_FALSE; + vk::Bool32 platformSurfaceExtFound = VK_FALSE; + memset(extension_names, 0, sizeof(extension_names)); - auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr); - VERIFY(result == vk::Result::eSuccess); + auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - if (instance_extension_count > 0) { - std::unique_ptr instance_extensions(new vk::ExtensionProperties[instance_extension_count]); - result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get()); - VERIFY(result == vk::Result::eSuccess); + if (instance_extension_count > 0) { + std::unique_ptr instance_extensions(new vk::ExtensionProperties[instance_extension_count]); + result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get()); + VERIFY(result == vk::Result::eSuccess); - for (uint32_t i = 0; i < instance_extension_count; i++) { - if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { - surfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME; - } + for (uint32_t i = 0; i < instance_extension_count; i++) { + if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + surfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME; + } #if defined(VK_USE_PLATFORM_WIN32_KHR) - if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { - platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME; - } + if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + platformSurfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME; + } #elif defined(VK_USE_PLATFORM_XLIB_KHR) - if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { - platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME; - } + if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + platformSurfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME; + } #elif defined(VK_USE_PLATFORM_XCB_KHR) - if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { - platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME; - } + if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + platformSurfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME; + } #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { - platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME; - } + if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) { + platformSurfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME; + } #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) { - platformSurfaceExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME; - } + if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) { + platformSurfaceExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME; + } #endif - assert(enabled_extension_count < 64); - } + assert(enabled_extension_count < 64); } + } - if (!surfaceExtFound) { - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_SURFACE_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); - } + if (!surfaceExtFound) { + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); + } - if (!platformSurfaceExtFound) { + if (!platformSurfaceExtFound) { #if defined(VK_USE_PLATFORM_WIN32_KHR) - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_XCB_KHR) - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_XLIB_KHR) - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - ERR_EXIT( - "vkEnumerateInstanceExtensionProperties failed to find " - "the " VK_KHR_DISPLAY_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); + ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); #endif - } - auto const app = vk::ApplicationInfo() - .setPApplicationName(APP_SHORT_NAME) - .setApplicationVersion(0) - .setPEngineName(APP_SHORT_NAME) - .setEngineVersion(0) - .setApiVersion(VK_API_VERSION_1_0); - auto const inst_info = vk::InstanceCreateInfo() - .setPApplicationInfo(&app) - .setEnabledLayerCount(enabled_layer_count) - .setPpEnabledLayerNames(instance_validation_layers) - .setEnabledExtensionCount(enabled_extension_count) - .setPpEnabledExtensionNames(extension_names); - - result = vk::createInstance(&inst_info, nullptr, &inst); - if (result == vk::Result::eErrorIncompatibleDriver) { - ERR_EXIT( - "Cannot find a compatible Vulkan installable client " - "driver (ICD).\n\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); - } else if (result == vk::Result::eErrorExtensionNotPresent) { - ERR_EXIT( - "Cannot find a specified extension library.\n" - "Make sure your layers path is set appropriately.\n", - "vkCreateInstance Failure"); - } else if (result != vk::Result::eSuccess) { - ERR_EXIT( - "vkCreateInstance failed.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); - } + } + auto const app = vk::ApplicationInfo() + .setPApplicationName(APP_SHORT_NAME) + .setApplicationVersion(0) + .setPEngineName(APP_SHORT_NAME) + .setEngineVersion(0) + .setApiVersion(VK_API_VERSION_1_0); + auto const inst_info = vk::InstanceCreateInfo() + .setPApplicationInfo(&app) + .setEnabledLayerCount(enabled_layer_count) + .setPpEnabledLayerNames(instance_validation_layers) + .setEnabledExtensionCount(enabled_extension_count) + .setPpEnabledExtensionNames(extension_names); + + result = vk::createInstance(&inst_info, nullptr, &inst); + if (result == vk::Result::eErrorIncompatibleDriver) { + ERR_EXIT( + "Cannot find a compatible Vulkan installable client driver (ICD).\n\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); + } else if (result == vk::Result::eErrorExtensionNotPresent) { + ERR_EXIT( + "Cannot find a specified extension library.\n" + "Make sure your layers path is set appropriately.\n", + "vkCreateInstance Failure"); + } else if (result != vk::Result::eSuccess) { + ERR_EXIT( + "vkCreateInstance failed.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); + } - /* Make initial call to query gpu_count, then second call for gpu info*/ - uint32_t gpu_count; - result = inst.enumeratePhysicalDevices(&gpu_count, nullptr); + /* Make initial call to query gpu_count, then second call for gpu info*/ + uint32_t gpu_count; + result = inst.enumeratePhysicalDevices(&gpu_count, nullptr); + VERIFY(result == vk::Result::eSuccess); + assert(gpu_count > 0); + + if (gpu_count > 0) { + std::unique_ptr physical_devices(new vk::PhysicalDevice[gpu_count]); + result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get()); VERIFY(result == vk::Result::eSuccess); - assert(gpu_count > 0); + /* For cube demo we just grab the first physical device */ + gpu = physical_devices[0]; + } else { + ERR_EXIT( + "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkEnumeratePhysicalDevices Failure"); + } - if (gpu_count > 0) { - std::unique_ptr physical_devices(new vk::PhysicalDevice[gpu_count]); - result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get()); - VERIFY(result == vk::Result::eSuccess); - /* For cube demo we just grab the first physical device */ - gpu = physical_devices[0]; - } else { - ERR_EXIT( - "vkEnumeratePhysicalDevices reported zero accessible " - "devices.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkEnumeratePhysicalDevices Failure"); - } + /* Look for device extensions */ + uint32_t device_extension_count = 0; + vk::Bool32 swapchainExtFound = VK_FALSE; + enabled_extension_count = 0; + memset(extension_names, 0, sizeof(extension_names)); - /* Look for device extensions */ - uint32_t device_extension_count = 0; - vk::Bool32 swapchainExtFound = VK_FALSE; - enabled_extension_count = 0; - memset(extension_names, 0, sizeof(extension_names)); + result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr); + if (device_extension_count > 0) { + std::unique_ptr device_extensions(new vk::ExtensionProperties[device_extension_count]); + result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get()); VERIFY(result == vk::Result::eSuccess); - if (device_extension_count > 0) { - std::unique_ptr device_extensions(new vk::ExtensionProperties[device_extension_count]); - result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get()); - VERIFY(result == vk::Result::eSuccess); - - for (uint32_t i = 0; i < device_extension_count; i++) { - if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) { - swapchainExtFound = 1; - extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; - } - assert(enabled_extension_count < 64); + for (uint32_t i = 0; i < device_extension_count; i++) { + if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) { + swapchainExtFound = 1; + extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME; } + assert(enabled_extension_count < 64); } + } - if (!swapchainExtFound) { - ERR_EXIT( - "vkEnumerateDeviceExtensionProperties failed to find " - "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME - " extension.\n\n" - "Do you have a compatible Vulkan installable client " - "driver (ICD) installed?\n" - "Please look at the Getting Started guide for additional " - "information.\n", - "vkCreateInstance Failure"); - } + if (!swapchainExtFound) { + ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME + " extension.\n\n" + "Do you have a compatible Vulkan installable client driver (ICD) installed?\n" + "Please look at the Getting Started guide for additional information.\n", + "vkCreateInstance Failure"); + } - gpu.getProperties(&gpu_props); + gpu.getProperties(&gpu_props); - /* Call with nullptr data to get count */ - gpu.getQueueFamilyProperties(&queue_family_count, nullptr); - assert(queue_family_count >= 1); + /* Call with nullptr data to get count */ + gpu.getQueueFamilyProperties(&queue_family_count, nullptr); + assert(queue_family_count >= 1); - queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]); - gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get()); + queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]); + gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get()); - // Query fine-grained feature support for this device. - // If app has specific feature requirements it should check supported - // features based on this query - vk::PhysicalDeviceFeatures physDevFeatures; - gpu.getFeatures(&physDevFeatures); - } + // Query fine-grained feature support for this device. + // If app has specific feature requirements it should check supported + // features based on this query + vk::PhysicalDeviceFeatures physDevFeatures; + gpu.getFeatures(&physDevFeatures); +} - void Demo::init_vk_swapchain() { - // Create a WSI surface for the window: +void Demo::init_vk_swapchain() { +// Create a WSI surface for the window: #if defined(VK_USE_PLATFORM_WIN32_KHR) - { - auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window); + { + auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window); - auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface); - VERIFY(result == vk::Result::eSuccess); - } + auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface); + VERIFY(result == vk::Result::eSuccess); + } #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - { - auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window); + { + auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window); - auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface); - VERIFY(result == vk::Result::eSuccess); - } + auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface); + VERIFY(result == vk::Result::eSuccess); + } #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_XLIB_KHR) - { - auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window); + { + auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window); - auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface); - VERIFY(result == vk::Result::eSuccess); - } + auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface); + VERIFY(result == vk::Result::eSuccess); + } #elif defined(VK_USE_PLATFORM_XCB_KHR) - { - auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window); + { + auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window); - auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface); - VERIFY(result == vk::Result::eSuccess); - } + auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface); + VERIFY(result == vk::Result::eSuccess); + } #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - { - auto result = create_display_surface(); - VERIFY(result == vk::Result::eSuccess); - } + { + auto result = create_display_surface(); + VERIFY(result == vk::Result::eSuccess); + } #endif - // Iterate over each queue to learn whether it supports presenting: - std::unique_ptr supportsPresent(new vk::Bool32[queue_family_count]); - for (uint32_t i = 0; i < queue_family_count; i++) { - gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]); - } - - uint32_t graphicsQueueFamilyIndex = UINT32_MAX; - uint32_t presentQueueFamilyIndex = UINT32_MAX; - for (uint32_t i = 0; i < queue_family_count; i++) { - if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) { - if (graphicsQueueFamilyIndex == UINT32_MAX) { - graphicsQueueFamilyIndex = i; - } + // Iterate over each queue to learn whether it supports presenting: + std::unique_ptr supportsPresent(new vk::Bool32[queue_family_count]); + for (uint32_t i = 0; i < queue_family_count; i++) { + gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]); + } - if (supportsPresent[i] == VK_TRUE) { - graphicsQueueFamilyIndex = i; - presentQueueFamilyIndex = i; - break; - } + uint32_t graphicsQueueFamilyIndex = UINT32_MAX; + uint32_t presentQueueFamilyIndex = UINT32_MAX; + for (uint32_t i = 0; i < queue_family_count; i++) { + if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) { + if (graphicsQueueFamilyIndex == UINT32_MAX) { + graphicsQueueFamilyIndex = i; } - } - if (presentQueueFamilyIndex == UINT32_MAX) { - // If didn't find a queue that supports both graphics and present, - // then - // find a separate present queue. - for (uint32_t i = 0; i < queue_family_count; ++i) { - if (supportsPresent[i] == VK_TRUE) { - presentQueueFamilyIndex = i; - break; - } + if (supportsPresent[i] == VK_TRUE) { + graphicsQueueFamilyIndex = i; + presentQueueFamilyIndex = i; + break; } } + } - // Generate error if could not find both a graphics and a present queue - if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) { - ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure"); - } - - graphics_queue_family_index = graphicsQueueFamilyIndex; - present_queue_family_index = presentQueueFamilyIndex; - separate_present_queue = (graphics_queue_family_index != present_queue_family_index); - - create_device(); - - device.getQueue(graphics_queue_family_index, 0, &graphics_queue); - if (!separate_present_queue) { - present_queue = graphics_queue; - } else { - device.getQueue(present_queue_family_index, 0, &present_queue); - } - - // Get the list of VkFormat's that are supported: - uint32_t formatCount; - auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr); - VERIFY(result == vk::Result::eSuccess); - - std::unique_ptr surfFormats(new vk::SurfaceFormatKHR[formatCount]); - result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get()); - VERIFY(result == vk::Result::eSuccess); - - // If the format list includes just one entry of VK_FORMAT_UNDEFINED, - // the surface has no preferred format. Otherwise, at least one - // supported format will be returned. - if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) { - format = vk::Format::eB8G8R8A8Unorm; - } else { - assert(formatCount >= 1); - format = surfFormats[0].format; + if (presentQueueFamilyIndex == UINT32_MAX) { + // If didn't find a queue that supports both graphics and present, + // then + // find a separate present queue. + for (uint32_t i = 0; i < queue_family_count; ++i) { + if (supportsPresent[i] == VK_TRUE) { + presentQueueFamilyIndex = i; + break; + } } - color_space = surfFormats[0].colorSpace; + } - quit = false; - curFrame = 0; + // Generate error if could not find both a graphics and a present queue + if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) { + ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure"); + } - // Create semaphores to synchronize acquiring presentable buffers before - // rendering and waiting for drawing to be complete before presenting - auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo(); + graphics_queue_family_index = graphicsQueueFamilyIndex; + present_queue_family_index = presentQueueFamilyIndex; + separate_present_queue = (graphics_queue_family_index != present_queue_family_index); - // Create fences that we can use to throttle if we get too far - // ahead of the image presents - auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled); - for (uint32_t i = 0; i < FRAME_LAG; i++) { - result = device.createFence(&fence_ci, nullptr, &fences[i]); - VERIFY(result == vk::Result::eSuccess); + create_device(); - result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]); - VERIFY(result == vk::Result::eSuccess); + device.getQueue(graphics_queue_family_index, 0, &graphics_queue); + if (!separate_present_queue) { + present_queue = graphics_queue; + } else { + device.getQueue(present_queue_family_index, 0, &present_queue); + } - result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]); - VERIFY(result == vk::Result::eSuccess); + // Get the list of VkFormat's that are supported: + uint32_t formatCount; + auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr); + VERIFY(result == vk::Result::eSuccess); - if (separate_present_queue) { - result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]); - VERIFY(result == vk::Result::eSuccess); - } - } - frame_index = 0; + std::unique_ptr surfFormats(new vk::SurfaceFormatKHR[formatCount]); + result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get()); + VERIFY(result == vk::Result::eSuccess); - // Get Memory information and properties - gpu.getMemoryProperties(&memory_properties); + // If the format list includes just one entry of VK_FORMAT_UNDEFINED, + // the surface has no preferred format. Otherwise, at least one + // supported format will be returned. + if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) { + format = vk::Format::eB8G8R8A8Unorm; + } else { + assert(formatCount >= 1); + format = surfFormats[0].format; } + color_space = surfFormats[0].colorSpace; - void Demo::prepare() { - auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index); - auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool); - VERIFY(result == vk::Result::eSuccess); + quit = false; + curFrame = 0; - auto const cmd = vk::CommandBufferAllocateInfo() - .setCommandPool(cmd_pool) - .setLevel(vk::CommandBufferLevel::ePrimary) - .setCommandBufferCount(1); + // Create semaphores to synchronize acquiring presentable buffers before + // rendering and waiting for drawing to be complete before presenting + auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo(); - result = device.allocateCommandBuffers(&cmd, &this->cmd); + // Create fences that we can use to throttle if we get too far + // ahead of the image presents + auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled); + for (uint32_t i = 0; i < FRAME_LAG; i++) { + result = device.createFence(&fence_ci, nullptr, &fences[i]); VERIFY(result == vk::Result::eSuccess); - auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr); - - result = this->cmd.begin(&cmd_buf_info); + result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]); VERIFY(result == vk::Result::eSuccess); - prepare_buffers(); - prepare_depth(); - prepare_textures(); - prepare_cube_data_buffers(); - - prepare_descriptor_layout(); - prepare_render_pass(); - prepare_pipeline(); + result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]); + VERIFY(result == vk::Result::eSuccess); - for (uint32_t i = 0; i < swapchainImageCount; ++i) { - result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd); + if (separate_present_queue) { + result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]); VERIFY(result == vk::Result::eSuccess); } + } + frame_index = 0; - if (separate_present_queue) { - auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index); - - result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool); - VERIFY(result == vk::Result::eSuccess); + // Get Memory information and properties + gpu.getMemoryProperties(&memory_properties); +} - auto const present_cmd = vk::CommandBufferAllocateInfo() - .setCommandPool(present_cmd_pool) - .setLevel(vk::CommandBufferLevel::ePrimary) - .setCommandBufferCount(1); +void Demo::prepare() { + auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index); + auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool); + VERIFY(result == vk::Result::eSuccess); - for (uint32_t i = 0; i < swapchainImageCount; i++) { - result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd); - VERIFY(result == vk::Result::eSuccess); + auto const cmd = vk::CommandBufferAllocateInfo() + .setCommandPool(cmd_pool) + .setLevel(vk::CommandBufferLevel::ePrimary) + .setCommandBufferCount(1); - build_image_ownership_cmd(i); - } - } + result = device.allocateCommandBuffers(&cmd, &this->cmd); + VERIFY(result == vk::Result::eSuccess); - prepare_descriptor_pool(); - prepare_descriptor_set(); + auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr); - prepare_framebuffers(); + result = this->cmd.begin(&cmd_buf_info); + VERIFY(result == vk::Result::eSuccess); - for (uint32_t i = 0; i < swapchainImageCount; ++i) { - current_buffer = i; - draw_build_cmd(swapchain_image_resources[i].cmd); - } + prepare_buffers(); + prepare_depth(); + prepare_textures(); + prepare_cube_data_buffers(); - /* - * Prepare functions above may generate pipeline commands - * that need to be flushed before beginning the render loop. - */ - flush_init_cmd(); - if (staging_texture.image) { - destroy_texture_image(&staging_texture); - } + prepare_descriptor_layout(); + prepare_render_pass(); + prepare_pipeline(); - current_buffer = 0; - prepared = true; + for (uint32_t i = 0; i < swapchainImageCount; ++i) { + result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd); + VERIFY(result == vk::Result::eSuccess); } - void Demo::prepare_buffers() { - vk::SwapchainKHR oldSwapchain = swapchain; + if (separate_present_queue) { + auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index); - // Check the surface capabilities and formats - vk::SurfaceCapabilitiesKHR surfCapabilities; - auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities); + result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool); VERIFY(result == vk::Result::eSuccess); - uint32_t presentModeCount; - result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr); - VERIFY(result == vk::Result::eSuccess); + auto const present_cmd = vk::CommandBufferAllocateInfo() + .setCommandPool(present_cmd_pool) + .setLevel(vk::CommandBufferLevel::ePrimary) + .setCommandBufferCount(1); - std::unique_ptr presentModes(new vk::PresentModeKHR[presentModeCount]); - result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get()); - VERIFY(result == vk::Result::eSuccess); + for (uint32_t i = 0; i < swapchainImageCount; i++) { + result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd); + VERIFY(result == vk::Result::eSuccess); - vk::Extent2D swapchainExtent; - // width and height are either both -1, or both not -1. - if (surfCapabilities.currentExtent.width == (uint32_t)-1) { - // If the surface size is undefined, the size is set to - // the size of the images requested. - swapchainExtent.width = width; - swapchainExtent.height = height; - } else { - // If the surface size is defined, the swap chain size must match - swapchainExtent = surfCapabilities.currentExtent; - width = surfCapabilities.currentExtent.width; - height = surfCapabilities.currentExtent.height; + build_image_ownership_cmd(i); } + } - // The FIFO present mode is guaranteed by the spec to be supported - // and to have no tearing. It's a great default present mode to use. - vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo; - - // There are times when you may wish to use another present mode. The - // following code shows how to select them, and the comments provide some - // reasons you may wish to use them. - // - // It should be noted that Vulkan 1.0 doesn't provide a method for - // synchronizing rendering with the presentation engine's display. There - // is a method provided for throttling rendering with the display, but - // there are some presentation engines for which this method will not work. - // If an application doesn't throttle its rendering, and if it renders much - // faster than the refresh rate of the display, this can waste power on - // mobile devices. That is because power is being spent rendering images - // that may never be seen. - - // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care - // about - // tearing, or have some way of synchronizing their rendering with the - // display. - // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that - // generally render a new presentable image every refresh cycle, but are - // occasionally early. In this case, the application wants the new - // image - // to be displayed instead of the previously-queued-for-presentation - // image - // that has not yet been displayed. - // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally - // render a new presentable image every refresh cycle, but are - // occasionally - // late. In this case (perhaps because of stuttering/latency concerns), - // the application wants the late image to be immediately displayed, - // even - // though that may mean some tearing. - - if (presentMode != swapchainPresentMode) { - for (size_t i = 0; i < presentModeCount; ++i) { - if (presentModes[i] == presentMode) { - swapchainPresentMode = presentMode; - break; - } - } - } + prepare_descriptor_pool(); + prepare_descriptor_set(); - if (swapchainPresentMode != presentMode) { - ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported"); - } + prepare_framebuffers(); - // Determine the number of VkImages to use in the swap chain. - // Application desires to acquire 3 images at a time for triple - // buffering - uint32_t desiredNumOfSwapchainImages = 3; - if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) { - desiredNumOfSwapchainImages = surfCapabilities.minImageCount; - } + for (uint32_t i = 0; i < swapchainImageCount; ++i) { + current_buffer = i; + draw_build_cmd(swapchain_image_resources[i].cmd); + } - // If maxImageCount is 0, we can ask for as many images as we want, - // otherwise - // we're limited to maxImageCount - if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) { - // Application must settle for fewer images than desired: - desiredNumOfSwapchainImages = surfCapabilities.maxImageCount; - } + /* + * Prepare functions above may generate pipeline commands + * that need to be flushed before beginning the render loop. + */ + flush_init_cmd(); + if (staging_texture.image) { + destroy_texture_image(&staging_texture); + } - vk::SurfaceTransformFlagBitsKHR preTransform; - if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) { - preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity; - } else { - preTransform = surfCapabilities.currentTransform; - } + current_buffer = 0; + prepared = true; +} + +void Demo::prepare_buffers() { + vk::SwapchainKHR oldSwapchain = swapchain; + + // Check the surface capabilities and formats + vk::SurfaceCapabilitiesKHR surfCapabilities; + auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities); + VERIFY(result == vk::Result::eSuccess); + + uint32_t presentModeCount; + result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr); + VERIFY(result == vk::Result::eSuccess); + + std::unique_ptr presentModes(new vk::PresentModeKHR[presentModeCount]); + result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get()); + VERIFY(result == vk::Result::eSuccess); + + vk::Extent2D swapchainExtent; + // width and height are either both -1, or both not -1. + if (surfCapabilities.currentExtent.width == (uint32_t)-1) { + // If the surface size is undefined, the size is set to + // the size of the images requested. + swapchainExtent.width = width; + swapchainExtent.height = height; + } else { + // If the surface size is defined, the swap chain size must match + swapchainExtent = surfCapabilities.currentExtent; + width = surfCapabilities.currentExtent.width; + height = surfCapabilities.currentExtent.height; + } - // Find a supported composite alpha mode - one of these is guaranteed to be set - vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque; - vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = { - vk::CompositeAlphaFlagBitsKHR::eOpaque, - vk::CompositeAlphaFlagBitsKHR::ePreMultiplied, - vk::CompositeAlphaFlagBitsKHR::ePostMultiplied, - vk::CompositeAlphaFlagBitsKHR::eInherit, - }; - for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) { - if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) { - compositeAlpha = compositeAlphaFlags[i]; + // The FIFO present mode is guaranteed by the spec to be supported + // and to have no tearing. It's a great default present mode to use. + vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo; + + // There are times when you may wish to use another present mode. The + // following code shows how to select them, and the comments provide some + // reasons you may wish to use them. + // + // It should be noted that Vulkan 1.0 doesn't provide a method for + // synchronizing rendering with the presentation engine's display. There + // is a method provided for throttling rendering with the display, but + // there are some presentation engines for which this method will not work. + // If an application doesn't throttle its rendering, and if it renders much + // faster than the refresh rate of the display, this can waste power on + // mobile devices. That is because power is being spent rendering images + // that may never be seen. + + // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care + // about + // tearing, or have some way of synchronizing their rendering with the + // display. + // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that + // generally render a new presentable image every refresh cycle, but are + // occasionally early. In this case, the application wants the new + // image + // to be displayed instead of the previously-queued-for-presentation + // image + // that has not yet been displayed. + // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally + // render a new presentable image every refresh cycle, but are + // occasionally + // late. In this case (perhaps because of stuttering/latency concerns), + // the application wants the late image to be immediately displayed, + // even + // though that may mean some tearing. + + if (presentMode != swapchainPresentMode) { + for (size_t i = 0; i < presentModeCount; ++i) { + if (presentModes[i] == presentMode) { + swapchainPresentMode = presentMode; break; } } + } - auto const swapchain_ci = vk::SwapchainCreateInfoKHR() - .setSurface(surface) - .setMinImageCount(desiredNumOfSwapchainImages) - .setImageFormat(format) - .setImageColorSpace(color_space) - .setImageExtent({swapchainExtent.width, swapchainExtent.height}) - .setImageArrayLayers(1) - .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment) - .setImageSharingMode(vk::SharingMode::eExclusive) - .setQueueFamilyIndexCount(0) - .setPQueueFamilyIndices(nullptr) - .setPreTransform(preTransform) - .setCompositeAlpha(compositeAlpha) - .setPresentMode(swapchainPresentMode) - .setClipped(true) - .setOldSwapchain(oldSwapchain); - - result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain); - VERIFY(result == vk::Result::eSuccess); - - // If we just re-created an existing swapchain, we should destroy the - // old - // swapchain at this point. - // Note: destroying the swapchain also cleans up all its associated - // presentable images once the platform is done with them. - if (oldSwapchain) { - device.destroySwapchainKHR(oldSwapchain, nullptr); - } - - result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr); - VERIFY(result == vk::Result::eSuccess); - - std::unique_ptr swapchainImages(new vk::Image[swapchainImageCount]); - result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get()); - VERIFY(result == vk::Result::eSuccess); - - swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]); - - for (uint32_t i = 0; i < swapchainImageCount; ++i) { - auto color_image_view = - vk::ImageViewCreateInfo() - .setViewType(vk::ImageViewType::e2D) - .setFormat(format) - .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - - swapchain_image_resources[i].image = swapchainImages[i]; - - color_image_view.image = swapchain_image_resources[i].image; - - result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view); - VERIFY(result == vk::Result::eSuccess); - } + if (swapchainPresentMode != presentMode) { + ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported"); } - void Demo::prepare_cube_data_buffers() { - mat4x4 VP; - mat4x4_mul(VP, projection_matrix, view_matrix); + // Determine the number of VkImages to use in the swap chain. + // Application desires to acquire 3 images at a time for triple + // buffering + uint32_t desiredNumOfSwapchainImages = 3; + if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) { + desiredNumOfSwapchainImages = surfCapabilities.minImageCount; + } - mat4x4 MVP; - mat4x4_mul(MVP, VP, model_matrix); + // If maxImageCount is 0, we can ask for as many images as we want, + // otherwise + // we're limited to maxImageCount + if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) { + // Application must settle for fewer images than desired: + desiredNumOfSwapchainImages = surfCapabilities.maxImageCount; + } - vktexcube_vs_uniform data; - memcpy(data.mvp, MVP, sizeof(MVP)); - // dumpMatrix("MVP", MVP) + vk::SurfaceTransformFlagBitsKHR preTransform; + if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) { + preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity; + } else { + preTransform = surfCapabilities.currentTransform; + } - for (int32_t i = 0; i < 12 * 3; i++) { - data.position[i][0] = g_vertex_buffer_data[i * 3]; - data.position[i][1] = g_vertex_buffer_data[i * 3 + 1]; - data.position[i][2] = g_vertex_buffer_data[i * 3 + 2]; - data.position[i][3] = 1.0f; - data.attr[i][0] = g_uv_buffer_data[2 * i]; - data.attr[i][1] = g_uv_buffer_data[2 * i + 1]; - data.attr[i][2] = 0; - data.attr[i][3] = 0; + // Find a supported composite alpha mode - one of these is guaranteed to be set + vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque; + vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = { + vk::CompositeAlphaFlagBitsKHR::eOpaque, + vk::CompositeAlphaFlagBitsKHR::ePreMultiplied, + vk::CompositeAlphaFlagBitsKHR::ePostMultiplied, + vk::CompositeAlphaFlagBitsKHR::eInherit, + }; + for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) { + if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) { + compositeAlpha = compositeAlphaFlags[i]; + break; } + } - auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer); - - for (unsigned int i = 0; i < swapchainImageCount; i++) { - auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer); - VERIFY(result == vk::Result::eSuccess); + auto const swapchain_ci = vk::SwapchainCreateInfoKHR() + .setSurface(surface) + .setMinImageCount(desiredNumOfSwapchainImages) + .setImageFormat(format) + .setImageColorSpace(color_space) + .setImageExtent({swapchainExtent.width, swapchainExtent.height}) + .setImageArrayLayers(1) + .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment) + .setImageSharingMode(vk::SharingMode::eExclusive) + .setQueueFamilyIndexCount(0) + .setPQueueFamilyIndices(nullptr) + .setPreTransform(preTransform) + .setCompositeAlpha(compositeAlpha) + .setPresentMode(swapchainPresentMode) + .setClipped(true) + .setOldSwapchain(oldSwapchain); + + result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain); + VERIFY(result == vk::Result::eSuccess); + + // If we just re-created an existing swapchain, we should destroy the + // old + // swapchain at this point. + // Note: destroying the swapchain also cleans up all its associated + // presentable images once the platform is done with them. + if (oldSwapchain) { + device.destroySwapchainKHR(oldSwapchain, nullptr); + } - vk::MemoryRequirements mem_reqs; - device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs); + result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr); + VERIFY(result == vk::Result::eSuccess); - auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0); + std::unique_ptr swapchainImages(new vk::Image[swapchainImageCount]); + result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get()); + VERIFY(result == vk::Result::eSuccess); - bool const pass = memory_type_from_properties( - mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, - &mem_alloc.memoryTypeIndex); - VERIFY(pass); + swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]); - result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory); - VERIFY(result == vk::Result::eSuccess); + for (uint32_t i = 0; i < swapchainImageCount; ++i) { + auto color_image_view = vk::ImageViewCreateInfo() + .setViewType(vk::ImageViewType::e2D) + .setFormat(format) + .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); - VERIFY(pData.result == vk::Result::eSuccess); + swapchain_image_resources[i].image = swapchainImages[i]; - memcpy(pData.value, &data, sizeof data); + color_image_view.image = swapchain_image_resources[i].image; - device.unmapMemory(swapchain_image_resources[i].uniform_memory); + result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view); + VERIFY(result == vk::Result::eSuccess); + } +} - result = device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0); - VERIFY(result == vk::Result::eSuccess); - } +void Demo::prepare_cube_data_buffers() { + mat4x4 VP; + mat4x4_mul(VP, projection_matrix, view_matrix); + + mat4x4 MVP; + mat4x4_mul(MVP, VP, model_matrix); + + vktexcube_vs_uniform data; + memcpy(data.mvp, MVP, sizeof(MVP)); + // dumpMatrix("MVP", MVP) + + for (int32_t i = 0; i < 12 * 3; i++) { + data.position[i][0] = g_vertex_buffer_data[i * 3]; + data.position[i][1] = g_vertex_buffer_data[i * 3 + 1]; + data.position[i][2] = g_vertex_buffer_data[i * 3 + 2]; + data.position[i][3] = 1.0f; + data.attr[i][0] = g_uv_buffer_data[2 * i]; + data.attr[i][1] = g_uv_buffer_data[2 * i + 1]; + data.attr[i][2] = 0; + data.attr[i][3] = 0; } - void Demo::prepare_depth() { - depth.format = vk::Format::eD16Unorm; - - auto const image = vk::ImageCreateInfo() - .setImageType(vk::ImageType::e2D) - .setFormat(depth.format) - .setExtent({(uint32_t)width, (uint32_t)height, 1}) - .setMipLevels(1) - .setArrayLayers(1) - .setSamples(vk::SampleCountFlagBits::e1) - .setTiling(vk::ImageTiling::eOptimal) - .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment) - .setSharingMode(vk::SharingMode::eExclusive) - .setQueueFamilyIndexCount(0) - .setPQueueFamilyIndices(nullptr) - .setInitialLayout(vk::ImageLayout::eUndefined); - - auto result = device.createImage(&image, nullptr, &depth.image); + auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer); + + for (unsigned int i = 0; i < swapchainImageCount; i++) { + auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer); VERIFY(result == vk::Result::eSuccess); vk::MemoryRequirements mem_reqs; - device.getImageMemoryRequirements(depth.image, &mem_reqs); + device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs); - depth.mem_alloc.setAllocationSize(mem_reqs.size); - depth.mem_alloc.setMemoryTypeIndex(0); + auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0); - auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal, - &depth.mem_alloc.memoryTypeIndex); + bool const pass = memory_type_from_properties( + mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent, + &mem_alloc.memoryTypeIndex); VERIFY(pass); - result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem); + result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory); VERIFY(result == vk::Result::eSuccess); - result = device.bindImageMemory(depth.image, depth.mem, 0); - VERIFY(result == vk::Result::eSuccess); - - auto const view = vk::ImageViewCreateInfo() - .setImage(depth.image) - .setViewType(vk::ImageViewType::e2D) - .setFormat(depth.format) - .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1)); - result = device.createImageView(&view, nullptr, &depth.view); - VERIFY(result == vk::Result::eSuccess); - } - - void Demo::prepare_descriptor_layout() { - vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding() - .setBinding(0) - .setDescriptorType(vk::DescriptorType::eUniformBuffer) - .setDescriptorCount(1) - .setStageFlags(vk::ShaderStageFlagBits::eVertex) - .setPImmutableSamplers(nullptr), - vk::DescriptorSetLayoutBinding() - .setBinding(1) - .setDescriptorType(vk::DescriptorType::eCombinedImageSampler) - .setDescriptorCount(texture_count) - .setStageFlags(vk::ShaderStageFlagBits::eFragment) - .setPImmutableSamplers(nullptr)}; + auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); + VERIFY(pData.result == vk::Result::eSuccess); - auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings); + memcpy(pData.value, &data, sizeof data); - auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout); - VERIFY(result == vk::Result::eSuccess); - - auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout); + device.unmapMemory(swapchain_image_resources[i].uniform_memory); - result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout); + result = + device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0); VERIFY(result == vk::Result::eSuccess); } +} - void Demo::prepare_descriptor_pool() { - vk::DescriptorPoolSize const poolSizes[2] = { - vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount), - vk::DescriptorPoolSize().setType(vk::DescriptorType::eCombinedImageSampler).setDescriptorCount(swapchainImageCount * texture_count)}; +void Demo::prepare_depth() { + depth.format = vk::Format::eD16Unorm; + + auto const image = vk::ImageCreateInfo() + .setImageType(vk::ImageType::e2D) + .setFormat(depth.format) + .setExtent({(uint32_t)width, (uint32_t)height, 1}) + .setMipLevels(1) + .setArrayLayers(1) + .setSamples(vk::SampleCountFlagBits::e1) + .setTiling(vk::ImageTiling::eOptimal) + .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment) + .setSharingMode(vk::SharingMode::eExclusive) + .setQueueFamilyIndexCount(0) + .setPQueueFamilyIndices(nullptr) + .setInitialLayout(vk::ImageLayout::eUndefined); + + auto result = device.createImage(&image, nullptr, &depth.image); + VERIFY(result == vk::Result::eSuccess); + + vk::MemoryRequirements mem_reqs; + device.getImageMemoryRequirements(depth.image, &mem_reqs); + + depth.mem_alloc.setAllocationSize(mem_reqs.size); + depth.mem_alloc.setMemoryTypeIndex(0); + + auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal, + &depth.mem_alloc.memoryTypeIndex); + VERIFY(pass); + + result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem); + VERIFY(result == vk::Result::eSuccess); + + result = device.bindImageMemory(depth.image, depth.mem, 0); + VERIFY(result == vk::Result::eSuccess); + + auto const view = vk::ImageViewCreateInfo() + .setImage(depth.image) + .setViewType(vk::ImageViewType::e2D) + .setFormat(depth.format) + .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1)); + result = device.createImageView(&view, nullptr, &depth.view); + VERIFY(result == vk::Result::eSuccess); +} - auto const descriptor_pool = vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes); +void Demo::prepare_descriptor_layout() { + vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding() + .setBinding(0) + .setDescriptorType(vk::DescriptorType::eUniformBuffer) + .setDescriptorCount(1) + .setStageFlags(vk::ShaderStageFlagBits::eVertex) + .setPImmutableSamplers(nullptr), + vk::DescriptorSetLayoutBinding() + .setBinding(1) + .setDescriptorType(vk::DescriptorType::eCombinedImageSampler) + .setDescriptorCount(texture_count) + .setStageFlags(vk::ShaderStageFlagBits::eFragment) + .setPImmutableSamplers(nullptr)}; + + auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings); + + auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout); + VERIFY(result == vk::Result::eSuccess); + + auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout); + + result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout); + VERIFY(result == vk::Result::eSuccess); +} - auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool); - VERIFY(result == vk::Result::eSuccess); - } +void Demo::prepare_descriptor_pool() { + vk::DescriptorPoolSize const poolSizes[2] = { + vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount), + vk::DescriptorPoolSize() + .setType(vk::DescriptorType::eCombinedImageSampler) + .setDescriptorCount(swapchainImageCount * texture_count)}; - void Demo::prepare_descriptor_set() { - auto const alloc_info = - vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout); + auto const descriptor_pool = + vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes); - auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform)); + auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool); + VERIFY(result == vk::Result::eSuccess); +} - vk::DescriptorImageInfo tex_descs[texture_count]; - for (uint32_t i = 0; i < texture_count; i++) { - tex_descs[i].setSampler(textures[i].sampler); - tex_descs[i].setImageView(textures[i].view); - tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral); - } +void Demo::prepare_descriptor_set() { + auto const alloc_info = + vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout); - vk::WriteDescriptorSet writes[2]; + auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform)); - writes[0].setDescriptorCount(1); - writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer); - writes[0].setPBufferInfo(&buffer_info); + vk::DescriptorImageInfo tex_descs[texture_count]; + for (uint32_t i = 0; i < texture_count; i++) { + tex_descs[i].setSampler(textures[i].sampler); + tex_descs[i].setImageView(textures[i].view); + tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral); + } - writes[1].setDstBinding(1); - writes[1].setDescriptorCount(texture_count); - writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler); - writes[1].setPImageInfo(tex_descs); + vk::WriteDescriptorSet writes[2]; - for (unsigned int i = 0; i < swapchainImageCount; i++) { - auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set); - VERIFY(result == vk::Result::eSuccess); + writes[0].setDescriptorCount(1); + writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer); + writes[0].setPBufferInfo(&buffer_info); - buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer); - writes[0].setDstSet(swapchain_image_resources[i].descriptor_set); - writes[1].setDstSet(swapchain_image_resources[i].descriptor_set); - device.updateDescriptorSets(2, writes, 0, nullptr); - } - } + writes[1].setDstBinding(1); + writes[1].setDescriptorCount(texture_count); + writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler); + writes[1].setPImageInfo(tex_descs); - void Demo::prepare_framebuffers() { - vk::ImageView attachments[2]; - attachments[1] = depth.view; + for (unsigned int i = 0; i < swapchainImageCount; i++) { + auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set); + VERIFY(result == vk::Result::eSuccess); - auto const fb_info = vk::FramebufferCreateInfo() - .setRenderPass(render_pass) - .setAttachmentCount(2) - .setPAttachments(attachments) - .setWidth((uint32_t)width) - .setHeight((uint32_t)height) - .setLayers(1); + buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer); + writes[0].setDstSet(swapchain_image_resources[i].descriptor_set); + writes[1].setDstSet(swapchain_image_resources[i].descriptor_set); + device.updateDescriptorSets(2, writes, 0, nullptr); + } +} - for (uint32_t i = 0; i < swapchainImageCount; i++) { - attachments[0] = swapchain_image_resources[i].view; - auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer); - VERIFY(result == vk::Result::eSuccess); - } +void Demo::prepare_framebuffers() { + vk::ImageView attachments[2]; + attachments[1] = depth.view; + + auto const fb_info = vk::FramebufferCreateInfo() + .setRenderPass(render_pass) + .setAttachmentCount(2) + .setPAttachments(attachments) + .setWidth((uint32_t)width) + .setHeight((uint32_t)height) + .setLayers(1); + + for (uint32_t i = 0; i < swapchainImageCount; i++) { + attachments[0] = swapchain_image_resources[i].view; + auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer); + VERIFY(result == vk::Result::eSuccess); } +} - vk::ShaderModule Demo::prepare_fs() { - const uint32_t fragShaderCode[] = { +vk::ShaderModule Demo::prepare_fs() { + const uint32_t fragShaderCode[] = { #include "cube.frag.inc" - }; + }; - frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode)); + frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode)); - return frag_shader_module; - } + return frag_shader_module; +} - void Demo::prepare_pipeline() { - vk::PipelineCacheCreateInfo const pipelineCacheInfo; - auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache); - VERIFY(result == vk::Result::eSuccess); +void Demo::prepare_pipeline() { + vk::PipelineCacheCreateInfo const pipelineCacheInfo; + auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache); + VERIFY(result == vk::Result::eSuccess); + + vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = { + vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"), + vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")}; + + vk::PipelineVertexInputStateCreateInfo const vertexInputInfo; + + auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList); + + // TODO: Where are pViewports and pScissors set? + auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1); + + auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo() + .setDepthClampEnable(VK_FALSE) + .setRasterizerDiscardEnable(VK_FALSE) + .setPolygonMode(vk::PolygonMode::eFill) + .setCullMode(vk::CullModeFlagBits::eBack) + .setFrontFace(vk::FrontFace::eCounterClockwise) + .setDepthBiasEnable(VK_FALSE) + .setLineWidth(1.0f); + + auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo(); + + auto const stencilOp = + vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways); + + auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo() + .setDepthTestEnable(VK_TRUE) + .setDepthWriteEnable(VK_TRUE) + .setDepthCompareOp(vk::CompareOp::eLessOrEqual) + .setDepthBoundsTestEnable(VK_FALSE) + .setStencilTestEnable(VK_FALSE) + .setFront(stencilOp) + .setBack(stencilOp); + + vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = { + vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | + vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)}; + + auto const colorBlendInfo = + vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments); + + vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}; + + auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2); + + auto const pipeline = vk::GraphicsPipelineCreateInfo() + .setStageCount(2) + .setPStages(shaderStageInfo) + .setPVertexInputState(&vertexInputInfo) + .setPInputAssemblyState(&inputAssemblyInfo) + .setPViewportState(&viewportInfo) + .setPRasterizationState(&rasterizationInfo) + .setPMultisampleState(&multisampleInfo) + .setPDepthStencilState(&depthStencilInfo) + .setPColorBlendState(&colorBlendInfo) + .setPDynamicState(&dynamicStateInfo) + .setLayout(pipeline_layout) + .setRenderPass(render_pass); + + result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline); + VERIFY(result == vk::Result::eSuccess); + + device.destroyShaderModule(frag_shader_module, nullptr); + device.destroyShaderModule(vert_shader_module, nullptr); +} - vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = { - vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"), - vk::PipelineShaderStageCreateInfo() - .setStage(vk::ShaderStageFlagBits::eFragment) - .setModule(prepare_fs()) - .setPName("main")}; - - vk::PipelineVertexInputStateCreateInfo const vertexInputInfo; - - auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList); - - // TODO: Where are pViewports and pScissors set? - auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1); - - auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo() - .setDepthClampEnable(VK_FALSE) - .setRasterizerDiscardEnable(VK_FALSE) - .setPolygonMode(vk::PolygonMode::eFill) - .setCullMode(vk::CullModeFlagBits::eBack) - .setFrontFace(vk::FrontFace::eCounterClockwise) - .setDepthBiasEnable(VK_FALSE) - .setLineWidth(1.0f); - - auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo(); - - auto const stencilOp = vk::StencilOpState() - .setFailOp(vk::StencilOp::eKeep) - .setPassOp(vk::StencilOp::eKeep) - .setCompareOp(vk::CompareOp::eAlways); - - auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo() - .setDepthTestEnable(VK_TRUE) - .setDepthWriteEnable(VK_TRUE) - .setDepthCompareOp(vk::CompareOp::eLessOrEqual) - .setDepthBoundsTestEnable(VK_FALSE) - .setStencilTestEnable(VK_FALSE) - .setFront(stencilOp) - .setBack(stencilOp); - - vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = { - vk::PipelineColorBlendAttachmentState().setColorWriteMask( - vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | - vk::ColorComponentFlagBits::eA)}; - - auto const colorBlendInfo = - vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments); - - vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}; - - auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2); - - auto const pipeline = vk::GraphicsPipelineCreateInfo() - .setStageCount(2) - .setPStages(shaderStageInfo) - .setPVertexInputState(&vertexInputInfo) - .setPInputAssemblyState(&inputAssemblyInfo) - .setPViewportState(&viewportInfo) - .setPRasterizationState(&rasterizationInfo) - .setPMultisampleState(&multisampleInfo) - .setPDepthStencilState(&depthStencilInfo) - .setPColorBlendState(&colorBlendInfo) - .setPDynamicState(&dynamicStateInfo) - .setLayout(pipeline_layout) - .setRenderPass(render_pass); - - result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline); - VERIFY(result == vk::Result::eSuccess); +void Demo::prepare_render_pass() { + // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED + // because at the start of the renderpass, we don't care about their contents. + // At the start of the subpass, the color attachment's layout will be transitioned + // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout + // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of + // the renderpass, the color attachment's layout will be transitioned to + // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of + // the renderpass, no barriers are necessary. + const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription() + .setFormat(format) + .setSamples(vk::SampleCountFlagBits::e1) + .setLoadOp(vk::AttachmentLoadOp::eClear) + .setStoreOp(vk::AttachmentStoreOp::eStore) + .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare) + .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare) + .setInitialLayout(vk::ImageLayout::eUndefined) + .setFinalLayout(vk::ImageLayout::ePresentSrcKHR), + vk::AttachmentDescription() + .setFormat(depth.format) + .setSamples(vk::SampleCountFlagBits::e1) + .setLoadOp(vk::AttachmentLoadOp::eClear) + .setStoreOp(vk::AttachmentStoreOp::eDontCare) + .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare) + .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare) + .setInitialLayout(vk::ImageLayout::eUndefined) + .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)}; + + auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal); + + auto const depth_reference = + vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal); + + auto const subpass = vk::SubpassDescription() + .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics) + .setInputAttachmentCount(0) + .setPInputAttachments(nullptr) + .setColorAttachmentCount(1) + .setPColorAttachments(&color_reference) + .setPResolveAttachments(nullptr) + .setPDepthStencilAttachment(&depth_reference) + .setPreserveAttachmentCount(0) + .setPPreserveAttachments(nullptr); + + auto const rp_info = vk::RenderPassCreateInfo() + .setAttachmentCount(2) + .setPAttachments(attachments) + .setSubpassCount(1) + .setPSubpasses(&subpass) + .setDependencyCount(0) + .setPDependencies(nullptr); + + auto result = device.createRenderPass(&rp_info, nullptr, &render_pass); + VERIFY(result == vk::Result::eSuccess); +} - device.destroyShaderModule(frag_shader_module, nullptr); - device.destroyShaderModule(vert_shader_module, nullptr); - } - - void Demo::prepare_render_pass() { - // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED - // because at the start of the renderpass, we don't care about their contents. - // At the start of the subpass, the color attachment's layout will be transitioned - // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout - // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of - // the renderpass, the color attachment's layout will be transitioned to - // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of - // the renderpass, no barriers are necessary. - const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription() - .setFormat(format) - .setSamples(vk::SampleCountFlagBits::e1) - .setLoadOp(vk::AttachmentLoadOp::eClear) - .setStoreOp(vk::AttachmentStoreOp::eStore) - .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare) - .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare) - .setInitialLayout(vk::ImageLayout::eUndefined) - .setFinalLayout(vk::ImageLayout::ePresentSrcKHR), - vk::AttachmentDescription() - .setFormat(depth.format) - .setSamples(vk::SampleCountFlagBits::e1) - .setLoadOp(vk::AttachmentLoadOp::eClear) - .setStoreOp(vk::AttachmentStoreOp::eDontCare) - .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare) - .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare) - .setInitialLayout(vk::ImageLayout::eUndefined) - .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)}; - - auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal); - - auto const depth_reference = - vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal); - - auto const subpass = vk::SubpassDescription() - .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics) - .setInputAttachmentCount(0) - .setPInputAttachments(nullptr) - .setColorAttachmentCount(1) - .setPColorAttachments(&color_reference) - .setPResolveAttachments(nullptr) - .setPDepthStencilAttachment(&depth_reference) - .setPreserveAttachmentCount(0) - .setPPreserveAttachments(nullptr); - - auto const rp_info = vk::RenderPassCreateInfo() - .setAttachmentCount(2) - .setPAttachments(attachments) - .setSubpassCount(1) - .setPSubpasses(&subpass) - .setDependencyCount(0) - .setPDependencies(nullptr); - - auto result = device.createRenderPass(&rp_info, nullptr, &render_pass); - VERIFY(result == vk::Result::eSuccess); - } +vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) { + const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code); - vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) { - const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code); + vk::ShaderModule module; + auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module); + VERIFY(result == vk::Result::eSuccess); - vk::ShaderModule module; - auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module); - VERIFY(result == vk::Result::eSuccess); + return module; +} - return module; +void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage, + vk::MemoryPropertyFlags required_props) { + int32_t tex_width; + int32_t tex_height; + if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) { + ERR_EXIT("Failed to load textures", "Load Texture Failure"); } - void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, - vk::ImageUsageFlags usage, vk::MemoryPropertyFlags required_props) { - int32_t tex_width; - int32_t tex_height; - if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) { - ERR_EXIT("Failed to load textures", "Load Texture Failure"); - } + tex_obj->tex_width = tex_width; + tex_obj->tex_height = tex_height; - tex_obj->tex_width = tex_width; - tex_obj->tex_height = tex_height; - - auto const image_create_info = vk::ImageCreateInfo() - .setImageType(vk::ImageType::e2D) - .setFormat(vk::Format::eR8G8B8A8Unorm) - .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1}) - .setMipLevels(1) - .setArrayLayers(1) - .setSamples(vk::SampleCountFlagBits::e1) - .setTiling(tiling) - .setUsage(usage) - .setSharingMode(vk::SharingMode::eExclusive) - .setQueueFamilyIndexCount(0) - .setPQueueFamilyIndices(nullptr) - .setInitialLayout(vk::ImageLayout::ePreinitialized); - - auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image); - VERIFY(result == vk::Result::eSuccess); + auto const image_create_info = vk::ImageCreateInfo() + .setImageType(vk::ImageType::e2D) + .setFormat(vk::Format::eR8G8B8A8Unorm) + .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1}) + .setMipLevels(1) + .setArrayLayers(1) + .setSamples(vk::SampleCountFlagBits::e1) + .setTiling(tiling) + .setUsage(usage) + .setSharingMode(vk::SharingMode::eExclusive) + .setQueueFamilyIndexCount(0) + .setPQueueFamilyIndices(nullptr) + .setInitialLayout(vk::ImageLayout::ePreinitialized); - vk::MemoryRequirements mem_reqs; - device.getImageMemoryRequirements(tex_obj->image, &mem_reqs); + auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image); + VERIFY(result == vk::Result::eSuccess); - tex_obj->mem_alloc.setAllocationSize(mem_reqs.size); - tex_obj->mem_alloc.setMemoryTypeIndex(0); + vk::MemoryRequirements mem_reqs; + device.getImageMemoryRequirements(tex_obj->image, &mem_reqs); - auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex); - VERIFY(pass == true); + tex_obj->mem_alloc.setAllocationSize(mem_reqs.size); + tex_obj->mem_alloc.setMemoryTypeIndex(0); - result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem)); - VERIFY(result == vk::Result::eSuccess); + auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex); + VERIFY(pass == true); - result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0); - VERIFY(result == vk::Result::eSuccess); + result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem)); + VERIFY(result == vk::Result::eSuccess); - if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) { - auto const subres = - vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0); - vk::SubresourceLayout layout; - device.getImageSubresourceLayout(tex_obj->image, &subres, &layout); + result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0); + VERIFY(result == vk::Result::eSuccess); - auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize); - VERIFY(data.result == vk::Result::eSuccess); + if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) { + auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0); + vk::SubresourceLayout layout; + device.getImageSubresourceLayout(tex_obj->image, &subres, &layout); - if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) { - fprintf(stderr, "Error loading texture: %s\n", filename); - } + auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize); + VERIFY(data.result == vk::Result::eSuccess); - device.unmapMemory(tex_obj->mem); + if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) { + fprintf(stderr, "Error loading texture: %s\n", filename); } - tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; - } - - void Demo::prepare_textures() { - vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm; - vk::FormatProperties props; - gpu.getFormatProperties(tex_format, &props); - - for (uint32_t i = 0; i < texture_count; i++) { - if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) { - /* Device can texture using linear textures */ - prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled, - vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); - // Nothing in the pipeline needs to be complete to start, and don't allow fragment - // shader to run until layout transition completes - set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, - textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe, - vk::PipelineStageFlagBits::eFragmentShader); - staging_texture.image = vk::Image(); - } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) { - /* Must use staging buffer to copy linear texture to optimized */ - - prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear, - vk::ImageUsageFlagBits::eTransferSrc, - vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); - - prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal, - vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, - vk::MemoryPropertyFlagBits::eDeviceLocal); - - set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, - vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlagBits(), - vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer); - - set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, - vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), - vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer); - - auto const subresource = vk::ImageSubresourceLayers() - .setAspectMask(vk::ImageAspectFlagBits::eColor) - .setMipLevel(0) - .setBaseArrayLayer(0) - .setLayerCount(1); - - auto const copy_region = - vk::ImageCopy() - .setSrcSubresource(subresource) - .setSrcOffset({0, 0, 0}) - .setDstSubresource(subresource) - .setDstOffset({0, 0, 0}) - .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1}); - - cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image, - vk::ImageLayout::eTransferDstOptimal, 1, ©_region); - - set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal, - textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer, - vk::PipelineStageFlagBits::eFragmentShader); - } else { - assert(!"No support for R8G8B8A8_UNORM as texture image format"); - } - - auto const samplerInfo = vk::SamplerCreateInfo() - .setMagFilter(vk::Filter::eNearest) - .setMinFilter(vk::Filter::eNearest) - .setMipmapMode(vk::SamplerMipmapMode::eNearest) - .setAddressModeU(vk::SamplerAddressMode::eClampToEdge) - .setAddressModeV(vk::SamplerAddressMode::eClampToEdge) - .setAddressModeW(vk::SamplerAddressMode::eClampToEdge) - .setMipLodBias(0.0f) - .setAnisotropyEnable(VK_FALSE) - .setMaxAnisotropy(1) - .setCompareEnable(VK_FALSE) - .setCompareOp(vk::CompareOp::eNever) - .setMinLod(0.0f) - .setMaxLod(0.0f) - .setBorderColor(vk::BorderColor::eFloatOpaqueWhite) - .setUnnormalizedCoordinates(VK_FALSE); - - auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler); - VERIFY(result == vk::Result::eSuccess); - - auto const viewInfo = vk::ImageViewCreateInfo() - .setImage(textures[i].image) - .setViewType(vk::ImageViewType::e2D) - .setFormat(tex_format) - .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - - result = device.createImageView(&viewInfo, nullptr, &textures[i].view); - VERIFY(result == vk::Result::eSuccess); - } + device.unmapMemory(tex_obj->mem); } - vk::ShaderModule Demo::prepare_vs() { - const uint32_t vertShaderCode[] = { -#include "cube.vert.inc" - }; + tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal; +} + +void Demo::prepare_textures() { + vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm; + vk::FormatProperties props; + gpu.getFormatProperties(tex_format, &props); + + for (uint32_t i = 0; i < texture_count; i++) { + if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) { + /* Device can texture using linear textures */ + prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled, + vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); + // Nothing in the pipeline needs to be complete to start, and don't allow fragment + // shader to run until layout transition completes + set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, + textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eFragmentShader); + staging_texture.image = vk::Image(); + } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) { + /* Must use staging buffer to copy linear texture to optimized */ + + prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eTransferSrc, + vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent); + + prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal, + vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled, + vk::MemoryPropertyFlagBits::eDeviceLocal); + + set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, + vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eTransfer); + + set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized, + vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe, + vk::PipelineStageFlagBits::eTransfer); + + auto const subresource = vk::ImageSubresourceLayers() + .setAspectMask(vk::ImageAspectFlagBits::eColor) + .setMipLevel(0) + .setBaseArrayLayer(0) + .setLayerCount(1); + + auto const copy_region = vk::ImageCopy() + .setSrcSubresource(subresource) + .setSrcOffset({0, 0, 0}) + .setDstSubresource(subresource) + .setDstOffset({0, 0, 0}) + .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1}); + + cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image, + vk::ImageLayout::eTransferDstOptimal, 1, ©_region); + + set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal, + textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader); + } else { + assert(!"No support for R8G8B8A8_UNORM as texture image format"); + } + + auto const samplerInfo = vk::SamplerCreateInfo() + .setMagFilter(vk::Filter::eNearest) + .setMinFilter(vk::Filter::eNearest) + .setMipmapMode(vk::SamplerMipmapMode::eNearest) + .setAddressModeU(vk::SamplerAddressMode::eClampToEdge) + .setAddressModeV(vk::SamplerAddressMode::eClampToEdge) + .setAddressModeW(vk::SamplerAddressMode::eClampToEdge) + .setMipLodBias(0.0f) + .setAnisotropyEnable(VK_FALSE) + .setMaxAnisotropy(1) + .setCompareEnable(VK_FALSE) + .setCompareOp(vk::CompareOp::eNever) + .setMinLod(0.0f) + .setMaxLod(0.0f) + .setBorderColor(vk::BorderColor::eFloatOpaqueWhite) + .setUnnormalizedCoordinates(VK_FALSE); + + auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler); + VERIFY(result == vk::Result::eSuccess); - vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode)); + auto const viewInfo = vk::ImageViewCreateInfo() + .setImage(textures[i].image) + .setViewType(vk::ImageViewType::e2D) + .setFormat(tex_format) + .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)); - return vert_shader_module; + result = device.createImageView(&viewInfo, nullptr, &textures[i].view); + VERIFY(result == vk::Result::eSuccess); } +} - void Demo::resize() { - uint32_t i; +vk::ShaderModule Demo::prepare_vs() { + const uint32_t vertShaderCode[] = { +#include "cube.vert.inc" + }; - // Don't react to resize until after first initialization. - if (!prepared) { - return; - } + vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode)); - // In order to properly resize the window, we must re-create the - // swapchain - // AND redo the command buffers, etc. - // - // First, perform part of the cleanup() function: - prepared = false; - auto result = device.waitIdle(); - VERIFY(result == vk::Result::eSuccess); + return vert_shader_module; +} - for (i = 0; i < swapchainImageCount; i++) { - device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr); - } +void Demo::resize() { + uint32_t i; - device.destroyDescriptorPool(desc_pool, nullptr); + // Don't react to resize until after first initialization. + if (!prepared) { + return; + } - device.destroyPipeline(pipeline, nullptr); - device.destroyPipelineCache(pipelineCache, nullptr); - device.destroyRenderPass(render_pass, nullptr); - device.destroyPipelineLayout(pipeline_layout, nullptr); - device.destroyDescriptorSetLayout(desc_layout, nullptr); + // In order to properly resize the window, we must re-create the + // swapchain + // AND redo the command buffers, etc. + // + // First, perform part of the cleanup() function: + prepared = false; + auto result = device.waitIdle(); + VERIFY(result == vk::Result::eSuccess); + + for (i = 0; i < swapchainImageCount; i++) { + device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr); + } - for (i = 0; i < texture_count; i++) { - device.destroyImageView(textures[i].view, nullptr); - device.destroyImage(textures[i].image, nullptr); - device.freeMemory(textures[i].mem, nullptr); - device.destroySampler(textures[i].sampler, nullptr); - } + device.destroyDescriptorPool(desc_pool, nullptr); - device.destroyImageView(depth.view, nullptr); - device.destroyImage(depth.image, nullptr); - device.freeMemory(depth.mem, nullptr); + device.destroyPipeline(pipeline, nullptr); + device.destroyPipelineCache(pipelineCache, nullptr); + device.destroyRenderPass(render_pass, nullptr); + device.destroyPipelineLayout(pipeline_layout, nullptr); + device.destroyDescriptorSetLayout(desc_layout, nullptr); - for (i = 0; i < swapchainImageCount; i++) { - device.destroyImageView(swapchain_image_resources[i].view, nullptr); - device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd); - device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr); - device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr); - } + for (i = 0; i < texture_count; i++) { + device.destroyImageView(textures[i].view, nullptr); + device.destroyImage(textures[i].image, nullptr); + device.freeMemory(textures[i].mem, nullptr); + device.destroySampler(textures[i].sampler, nullptr); + } - device.destroyCommandPool(cmd_pool, nullptr); - if (separate_present_queue) { - device.destroyCommandPool(present_cmd_pool, nullptr); - } + device.destroyImageView(depth.view, nullptr); + device.destroyImage(depth.image, nullptr); + device.freeMemory(depth.mem, nullptr); - // Second, re-perform the prepare() function, which will re-create the - // swapchain. - prepare(); + for (i = 0; i < swapchainImageCount; i++) { + device.destroyImageView(swapchain_image_resources[i].view, nullptr); + device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd); + device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr); + device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr); } - void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, - vk::ImageLayout newLayout, vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, - vk::PipelineStageFlags dest_stages) { - assert(cmd); + device.destroyCommandPool(cmd_pool, nullptr); + if (separate_present_queue) { + device.destroyCommandPool(present_cmd_pool, nullptr); + } - auto DstAccessMask = [](vk::ImageLayout const &layout) { - vk::AccessFlags flags; + // Second, re-perform the prepare() function, which will re-create the + // swapchain. + prepare(); +} - switch (layout) { - case vk::ImageLayout::eTransferDstOptimal: - // Make sure anything that was copying from this image has - // completed - flags = vk::AccessFlagBits::eTransferWrite; - break; - case vk::ImageLayout::eColorAttachmentOptimal: - flags = vk::AccessFlagBits::eColorAttachmentWrite; - break; - case vk::ImageLayout::eDepthStencilAttachmentOptimal: - flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite; - break; - case vk::ImageLayout::eShaderReadOnlyOptimal: - // Make sure any Copy or CPU writes to image are flushed - flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead; - break; - case vk::ImageLayout::eTransferSrcOptimal: - flags = vk::AccessFlagBits::eTransferRead; - break; - case vk::ImageLayout::ePresentSrcKHR: - flags = vk::AccessFlagBits::eMemoryRead; - break; - default: - break; - } +void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout, + vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) { + assert(cmd); - return flags; - }; + auto DstAccessMask = [](vk::ImageLayout const &layout) { + vk::AccessFlags flags; - auto const barrier = vk::ImageMemoryBarrier() - .setSrcAccessMask(srcAccessMask) - .setDstAccessMask(DstAccessMask(newLayout)) - .setOldLayout(oldLayout) - .setNewLayout(newLayout) - .setSrcQueueFamilyIndex(0) - .setDstQueueFamilyIndex(0) - .setImage(image) - .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1)); + switch (layout) { + case vk::ImageLayout::eTransferDstOptimal: + // Make sure anything that was copying from this image has + // completed + flags = vk::AccessFlagBits::eTransferWrite; + break; + case vk::ImageLayout::eColorAttachmentOptimal: + flags = vk::AccessFlagBits::eColorAttachmentWrite; + break; + case vk::ImageLayout::eDepthStencilAttachmentOptimal: + flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite; + break; + case vk::ImageLayout::eShaderReadOnlyOptimal: + // Make sure any Copy or CPU writes to image are flushed + flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead; + break; + case vk::ImageLayout::eTransferSrcOptimal: + flags = vk::AccessFlagBits::eTransferRead; + break; + case vk::ImageLayout::ePresentSrcKHR: + flags = vk::AccessFlagBits::eMemoryRead; + break; + default: + break; + } - cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier); - } + return flags; + }; - void Demo::update_data_buffer() { - mat4x4 VP; - mat4x4_mul(VP, projection_matrix, view_matrix); + auto const barrier = vk::ImageMemoryBarrier() + .setSrcAccessMask(srcAccessMask) + .setDstAccessMask(DstAccessMask(newLayout)) + .setOldLayout(oldLayout) + .setNewLayout(newLayout) + .setSrcQueueFamilyIndex(0) + .setDstQueueFamilyIndex(0) + .setImage(image) + .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1)); - // Rotate around the Y axis - mat4x4 Model; - mat4x4_dup(Model, model_matrix); - mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle)); + cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier); +} - mat4x4 MVP; - mat4x4_mul(MVP, VP, model_matrix); +void Demo::update_data_buffer() { + mat4x4 VP; + mat4x4_mul(VP, projection_matrix, view_matrix); - auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); - VERIFY(data.result == vk::Result::eSuccess); + // Rotate around the Y axis + mat4x4 Model; + mat4x4_dup(Model, model_matrix); + mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle)); - memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP)); + mat4x4 MVP; + mat4x4_mul(MVP, VP, model_matrix); - device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory); - } + auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags()); + VERIFY(data.result == vk::Result::eSuccess); - bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, - int32_t *height) { - FILE *fPtr = fopen(filename, "rb"); - if (!fPtr) { - return false; - } + memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP)); - char header[256]; - char *cPtr = fgets(header, 256, fPtr); // P6 - if (cPtr == nullptr || strncmp(header, "P6\n", 3)) { - fclose(fPtr); - return false; - } + device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory); +} - do { - cPtr = fgets(header, 256, fPtr); - if (cPtr == nullptr) { - fclose(fPtr); - return false; - } - } while (!strncmp(header, "#", 1)); +bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout *layout, int32_t *width, int32_t *height) { + FILE *fPtr = fopen(filename, "rb"); + if (!fPtr) { + return false; + } - sscanf(header, "%" SCNd32 " %" SCNd32, width, height); - if (rgba_data == nullptr) { - fclose(fPtr); - return true; - } + char header[256]; + char *cPtr = fgets(header, 256, fPtr); // P6 + if (cPtr == nullptr || strncmp(header, "P6\n", 3)) { + fclose(fPtr); + return false; + } - char *result = fgets(header, 256, fPtr); // Format - VERIFY(result != nullptr); - if (cPtr == nullptr || strncmp(header, "255\n", 3)) { + do { + cPtr = fgets(header, 256, fPtr); + if (cPtr == nullptr) { fclose(fPtr); return false; } + } while (!strncmp(header, "#", 1)); - for (int y = 0; y < *height; y++) { - uint8_t *rowPtr = rgba_data; - - for (int x = 0; x < *width; x++) { - size_t s = fread(rowPtr, 3, 1, fPtr); - (void)s; - rowPtr[3] = 255; /* Alpha of 1 */ - rowPtr += 4; - } - - rgba_data += layout->rowPitch; - } - + sscanf(header, "%" SCNd32 " %" SCNd32, width, height); + if (rgba_data == nullptr) { fclose(fPtr); return true; } - bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) { - // Search memtypes to find first index with those properties - for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) { - if ((typeBits & 1) == 1) { - // Type is available, does it match user properties? - if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { - *typeIndex = i; - return true; - } - } - typeBits >>= 1; - } - - // No memory types matched, return failure + char *result = fgets(header, 256, fPtr); // Format + VERIFY(result != nullptr); + if (cPtr == nullptr || strncmp(header, "255\n", 3)) { + fclose(fPtr); return false; } -#if defined(VK_USE_PLATFORM_WIN32_KHR) - void Demo::run() { - if (!prepared) { - return; - } - - draw(); - curFrame++; + for (int y = 0; y < *height; y++) { + uint8_t *rowPtr = rgba_data; - if (frameCount != INT_MAX && curFrame == frameCount) { - PostQuitMessage(validation_error); + for (int x = 0; x < *width; x++) { + size_t s = fread(rowPtr, 3, 1, fPtr); + (void)s; + rowPtr[3] = 255; /* Alpha of 1 */ + rowPtr += 4; } + + rgba_data += layout->rowPitch; } - void Demo::create_window() { - WNDCLASSEX win_class; - - // Initialize the window class structure: - win_class.cbSize = sizeof(WNDCLASSEX); - win_class.style = CS_HREDRAW | CS_VREDRAW; - win_class.lpfnWndProc = WndProc; - win_class.cbClsExtra = 0; - win_class.cbWndExtra = 0; - win_class.hInstance = connection; // hInstance - win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION); - win_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); - win_class.lpszMenuName = nullptr; - win_class.lpszClassName = name; - win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO); - - // Register window class: - if (!RegisterClassEx(&win_class)) { - // It didn't work, so try to give a useful error: - printf("Unexpected error trying to start the application!\n"); - fflush(stdout); - exit(1); - } + fclose(fPtr); + return true; +} - // Create window with the registered class: - RECT wr = {0, 0, static_cast(width), static_cast(height)}; - AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); - window = CreateWindowEx(0, - name, // class name - name, // app name - WS_OVERLAPPEDWINDOW | // window style - WS_VISIBLE | WS_SYSMENU, - 100, 100, // x/y coords - wr.right - wr.left, // width - wr.bottom - wr.top, // height - nullptr, // handle to parent - nullptr, // handle to menu - connection, // hInstance - nullptr); // no extra parameters - - if (!window) { - // It didn't work, so try to give a useful error: - printf("Cannot create a window in which to draw!\n"); - fflush(stdout); - exit(1); +bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) { + // Search memtypes to find first index with those properties + for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) { + if ((typeBits & 1) == 1) { + // Type is available, does it match user properties? + if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) { + *typeIndex = i; + return true; + } } - - // Window client area size must be at least 1 pixel high, to prevent - // crash. - minsize.x = GetSystemMetrics(SM_CXMINTRACK); - minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1; + typeBits >>= 1; } -#elif defined(VK_USE_PLATFORM_XLIB_KHR) - void Demo::create_xlib_window() { - const char *display_envar = getenv("DISPLAY"); - if (display_envar == nullptr || display_envar[0] == '\0') { - printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n"); - fflush(stdout); - exit(1); - } + // No memory types matched, return failure + return false; +} - XInitThreads(); - display = XOpenDisplay(nullptr); - long visualMask = VisualScreenMask; - int numberOfVisuals; - XVisualInfo vInfoTemplate = {}; - vInfoTemplate.screen = DefaultScreen(display); - XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals); +#if defined(VK_USE_PLATFORM_WIN32_KHR) +void Demo::run() { + if (!prepared) { + return; + } - Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone); + draw(); + curFrame++; - XSetWindowAttributes windowAttributes = {}; - windowAttributes.colormap = colormap; - windowAttributes.background_pixel = 0xFFFFFFFF; - windowAttributes.border_pixel = 0; - windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask; + if (frameCount != INT_MAX && curFrame == frameCount) { + PostQuitMessage(validation_error); + } +} - xlib_window = XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, - InputOutput, visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, - &windowAttributes); +void Demo::create_window() { + WNDCLASSEX win_class; + + // Initialize the window class structure: + win_class.cbSize = sizeof(WNDCLASSEX); + win_class.style = CS_HREDRAW | CS_VREDRAW; + win_class.lpfnWndProc = WndProc; + win_class.cbClsExtra = 0; + win_class.cbWndExtra = 0; + win_class.hInstance = connection; // hInstance + win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION); + win_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); + win_class.lpszMenuName = nullptr; + win_class.lpszClassName = name; + win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO); + + // Register window class: + if (!RegisterClassEx(&win_class)) { + // It didn't work, so try to give a useful error: + printf("Unexpected error trying to start the application!\n"); + fflush(stdout); + exit(1); + } - XSelectInput(display, xlib_window, ExposureMask | KeyPressMask); - XMapWindow(display, xlib_window); - XFlush(display); - xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False); + // Create window with the registered class: + RECT wr = {0, 0, static_cast(width), static_cast(height)}; + AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); + window = CreateWindowEx(0, + name, // class name + name, // app name + WS_OVERLAPPEDWINDOW | // window style + WS_VISIBLE | WS_SYSMENU, + 100, 100, // x/y coords + wr.right - wr.left, // width + wr.bottom - wr.top, // height + nullptr, // handle to parent + nullptr, // handle to menu + connection, // hInstance + nullptr); // no extra parameters + + if (!window) { + // It didn't work, so try to give a useful error: + printf("Cannot create a window in which to draw!\n"); + fflush(stdout); + exit(1); } - void Demo::handle_xlib_event(const XEvent *event) { - switch (event->type) { - case ClientMessage: - if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) { - quit = true; - } - break; - case KeyPress: - switch (event->xkey.keycode) { - case 0x9: // Escape - quit = true; - break; - case 0x71: // left arrow key - spin_angle -= spin_increment; - break; - case 0x72: // right arrow key - spin_angle += spin_increment; - break; - case 0x41: // space bar - pause = !pause; - break; - } - break; - case ConfigureNotify: - if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) { - width = event->xconfigure.width; - height = event->xconfigure.height; - resize(); - } - break; - default: - break; - } + // Window client area size must be at least 1 pixel high, to prevent + // crash. + minsize.x = GetSystemMetrics(SM_CXMINTRACK); + minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1; +} +#elif defined(VK_USE_PLATFORM_XLIB_KHR) + +void Demo::create_xlib_window() { + const char *display_envar = getenv("DISPLAY"); + if (display_envar == nullptr || display_envar[0] == '\0') { + printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n"); + fflush(stdout); + exit(1); } - void Demo::run_xlib() { - while (!quit) { - XEvent event; + XInitThreads(); + display = XOpenDisplay(nullptr); + long visualMask = VisualScreenMask; + int numberOfVisuals; + XVisualInfo vInfoTemplate = {}; + vInfoTemplate.screen = DefaultScreen(display); + XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals); + + Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone); + + XSetWindowAttributes windowAttributes = {}; + windowAttributes.colormap = colormap; + windowAttributes.background_pixel = 0xFFFFFFFF; + windowAttributes.border_pixel = 0; + windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask; + + xlib_window = + XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput, + visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes); + + XSelectInput(display, xlib_window, ExposureMask | KeyPressMask); + XMapWindow(display, xlib_window); + XFlush(display); + xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False); +} - if (pause) { - XNextEvent(display, &event); - handle_xlib_event(&event); +void Demo::handle_xlib_event(const XEvent *event) { + switch (event->type) { + case ClientMessage: + if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) { + quit = true; } - while (XPending(display) > 0) { - XNextEvent(display, &event); - handle_xlib_event(&event); + break; + case KeyPress: + switch (event->xkey.keycode) { + case 0x9: // Escape + quit = true; + break; + case 0x71: // left arrow key + spin_angle -= spin_increment; + break; + case 0x72: // right arrow key + spin_angle += spin_increment; + break; + case 0x41: // space bar + pause = !pause; + break; } + break; + case ConfigureNotify: + if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) { + width = event->xconfigure.width; + height = event->xconfigure.height; + resize(); + } + break; + default: + break; + } +} - draw(); - curFrame++; +void Demo::run_xlib() { + while (!quit) { + XEvent event; - if (frameCount != UINT32_MAX && curFrame == frameCount) { - quit = true; - } + if (pause) { + XNextEvent(display, &event); + handle_xlib_event(&event); + } + while (XPending(display) > 0) { + XNextEvent(display, &event); + handle_xlib_event(&event); + } + + draw(); + curFrame++; + + if (frameCount != UINT32_MAX && curFrame == frameCount) { + quit = true; } } +} #elif defined(VK_USE_PLATFORM_XCB_KHR) - void Demo::handle_xcb_event(const xcb_generic_event_t *event) { - uint8_t event_code = event->response_type & 0x7f; - switch (event_code) { - case XCB_EXPOSE: - // TODO: Resize window - break; - case XCB_CLIENT_MESSAGE: - if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) { +void Demo::handle_xcb_event(const xcb_generic_event_t *event) { + uint8_t event_code = event->response_type & 0x7f; + switch (event_code) { + case XCB_EXPOSE: + // TODO: Resize window + break; + case XCB_CLIENT_MESSAGE: + if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) { + quit = true; + } + break; + case XCB_KEY_RELEASE: { + const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event; + + switch (key->detail) { + case 0x9: // Escape quit = true; - } - break; - case XCB_KEY_RELEASE: { - const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event; - - switch (key->detail) { - case 0x9: // Escape - quit = true; - break; - case 0x71: // left arrow key - spin_angle -= spin_increment; - break; - case 0x72: // right arrow key - spin_angle += spin_increment; - break; - case 0x41: // space bar - pause = !pause; - break; - } - } break; - case XCB_CONFIGURE_NOTIFY: { - const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event; - if ((width != cfg->width) || (height != cfg->height)) { - width = cfg->width; - height = cfg->height; - resize(); - } - } break; - default: - break; - } + break; + case 0x71: // left arrow key + spin_angle -= spin_increment; + break; + case 0x72: // right arrow key + spin_angle += spin_increment; + break; + case 0x41: // space bar + pause = !pause; + break; + } + } break; + case XCB_CONFIGURE_NOTIFY: { + const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event; + if ((width != cfg->width) || (height != cfg->height)) { + width = cfg->width; + height = cfg->height; + resize(); + } + } break; + default: + break; } +} - void Demo::run_xcb() { - xcb_flush(connection); +void Demo::run_xcb() { + xcb_flush(connection); - while (!quit) { - xcb_generic_event_t *event; + while (!quit) { + xcb_generic_event_t *event; - if (pause) { - event = xcb_wait_for_event(connection); - } else { - event = xcb_poll_for_event(connection); - } - while (event) { - handle_xcb_event(event); - free(event); - event = xcb_poll_for_event(connection); - } + if (pause) { + event = xcb_wait_for_event(connection); + } else { + event = xcb_poll_for_event(connection); + } + while (event) { + handle_xcb_event(event); + free(event); + event = xcb_poll_for_event(connection); + } - draw(); - curFrame++; - if (frameCount != UINT32_MAX && curFrame == frameCount) { - quit = true; - } + draw(); + curFrame++; + if (frameCount != UINT32_MAX && curFrame == frameCount) { + quit = true; } } +} - void Demo::create_xcb_window() { - uint32_t value_mask, value_list[32]; +void Demo::create_xcb_window() { + uint32_t value_mask, value_list[32]; - xcb_window = xcb_generate_id(connection); + xcb_window = xcb_generate_id(connection); - value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; - value_list[0] = screen->black_pixel; - value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; + value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; + value_list[0] = screen->black_pixel; + value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY; - xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0, - XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list); + xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list); - /* Magic code that will send notification when window is destroyed */ - xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS"); - xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0); + /* Magic code that will send notification when window is destroyed */ + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS"); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0); - xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW"); - atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0); + xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW"); + atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0); - xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom); + xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom); - free(reply); + free(reply); - xcb_map_window(connection, xcb_window); + xcb_map_window(connection, xcb_window); - // Force the x/y coordinates to 100,100 results are identical in - // consecutive - // runs - const uint32_t coords[] = {100, 100}; - xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); - } + // Force the x/y coordinates to 100,100 results are identical in + // consecutive + // runs + const uint32_t coords[] = {100, 100}; + xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); +} #elif defined(VK_USE_PLATFORM_WAYLAND_KHR) - void Demo::run() { - while (!quit) { - if (pause) { - wl_display_dispatch(display); - } else { - wl_display_dispatch_pending(display); - update_data_buffer(); - draw(); - curFrame++; - if (frameCount != UINT32_MAX && curFrame == frameCount) { - quit = true; - } +void Demo::run() { + while (!quit) { + if (pause) { + wl_display_dispatch(display); + } else { + wl_display_dispatch_pending(display); + update_data_buffer(); + draw(); + curFrame++; + if (frameCount != UINT32_MAX && curFrame == frameCount) { + quit = true; } } } +} - void Demo::create_window() { - window = wl_compositor_create_surface(compositor); - if (!window) { - printf("Can not create wayland_surface from compositor!\n"); - fflush(stdout); - exit(1); - } - - shell_surface = wl_shell_get_shell_surface(shell, window); - if (!shell_surface) { - printf("Can not get shell_surface from wayland_surface!\n"); - fflush(stdout); - exit(1); - } +void Demo::create_window() { + window = wl_compositor_create_surface(compositor); + if (!window) { + printf("Can not create wayland_surface from compositor!\n"); + fflush(stdout); + exit(1); + } - wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this); - wl_shell_surface_set_toplevel(shell_surface); - wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME); + shell_surface = wl_shell_get_shell_surface(shell, window); + if (!shell_surface) { + printf("Can not get shell_surface from wayland_surface!\n"); + fflush(stdout); + exit(1); } + + wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this); + wl_shell_surface_set_toplevel(shell_surface); + wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME); +} #elif defined(VK_USE_PLATFORM_MIR_KHR) #elif defined(VK_USE_PLATFORM_DISPLAY_KHR) - vk::Result Demo::create_display_surface() { - vk::Result result; - uint32_t display_count; - uint32_t mode_count; - uint32_t plane_count; - vk::DisplayPropertiesKHR display_props; - vk::DisplayKHR display; - vk::DisplayModePropertiesKHR mode_props; - vk::DisplayPlanePropertiesKHR *plane_props; - vk::Bool32 found_plane = VK_FALSE; - uint32_t plane_index; - vk::Extent2D image_extent; - - // Get the first display - result = gpu.getDisplayPropertiesKHR(&display_count, nullptr); - VERIFY(result == vk::Result::eSuccess); - - if (display_count == 0) { - printf("Cannot find any display!\n"); - fflush(stdout); - exit(1); - } - - display_count = 1; - result = gpu.getDisplayPropertiesKHR(&display_count, &display_props); - VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete)); - - display = display_props.display; +vk::Result Demo::create_display_surface() { + vk::Result result; + uint32_t display_count; + uint32_t mode_count; + uint32_t plane_count; + vk::DisplayPropertiesKHR display_props; + vk::DisplayKHR display; + vk::DisplayModePropertiesKHR mode_props; + vk::DisplayPlanePropertiesKHR *plane_props; + vk::Bool32 found_plane = VK_FALSE; + uint32_t plane_index; + vk::Extent2D image_extent; + + // Get the first display + result = gpu.getDisplayPropertiesKHR(&display_count, nullptr); + VERIFY(result == vk::Result::eSuccess); + + if (display_count == 0) { + printf("Cannot find any display!\n"); + fflush(stdout); + exit(1); + } - // Get the first mode of the display - result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr); - VERIFY(result == vk::Result::eSuccess); + display_count = 1; + result = gpu.getDisplayPropertiesKHR(&display_count, &display_props); + VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete)); - if (mode_count == 0) { - printf("Cannot find any mode for the display!\n"); - fflush(stdout); - exit(1); - } + display = display_props.display; - mode_count = 1; - result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props); - VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete)); + // Get the first mode of the display + result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - // Get the list of planes - result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr); - VERIFY(result == vk::Result::eSuccess); + if (mode_count == 0) { + printf("Cannot find any mode for the display!\n"); + fflush(stdout); + exit(1); + } - if (plane_count == 0) { - printf("Cannot find any plane!\n"); - fflush(stdout); - exit(1); - } + mode_count = 1; + result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props); + VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete)); - plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count); - VERIFY(plane_props != nullptr); + // Get the list of planes + result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props); - VERIFY(result == vk::Result::eSuccess); + if (plane_count == 0) { + printf("Cannot find any plane!\n"); + fflush(stdout); + exit(1); + } - // Find a plane compatible with the display - for (plane_index = 0; plane_index < plane_count; plane_index++) { - uint32_t supported_count; - vk::DisplayKHR *supported_displays; + plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count); + VERIFY(plane_props != nullptr); - // Disqualify planes that are bound to a different display - if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) { - continue; - } + result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props); + VERIFY(result == vk::Result::eSuccess); - result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr); - VERIFY(result == vk::Result::eSuccess); + // Find a plane compatible with the display + for (plane_index = 0; plane_index < plane_count; plane_index++) { + uint32_t supported_count; + vk::DisplayKHR *supported_displays; - if (supported_count == 0) { - continue; - } + // Disqualify planes that are bound to a different display + if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) { + continue; + } - supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count); - VERIFY(supported_displays != nullptr); + result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr); + VERIFY(result == vk::Result::eSuccess); - result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays); - VERIFY(result == vk::Result::eSuccess); + if (supported_count == 0) { + continue; + } - for (uint32_t i = 0; i < supported_count; i++) { - if (supported_displays[i] == display) { - found_plane = VK_TRUE; - break; - } - } + supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count); + VERIFY(supported_displays != nullptr); - free(supported_displays); + result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays); + VERIFY(result == vk::Result::eSuccess); - if (found_plane) { + for (uint32_t i = 0; i < supported_count; i++) { + if (supported_displays[i] == display) { + found_plane = VK_TRUE; break; } } - if (!found_plane) { - printf("Cannot find a plane compatible with the display!\n"); - fflush(stdout); - exit(1); + free(supported_displays); + + if (found_plane) { + break; } + } - free(plane_props); - - vk::DisplayPlaneCapabilitiesKHR planeCaps; - gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps); - // Find a supported alpha mode - vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque; - vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = { - vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque, - vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal, - vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel, - vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied, - }; - for (uint32_t i = 0; i < sizeof(alphaModes); i++) { - if (planeCaps.supportedAlpha & alphaModes[i]) { - alphaMode = alphaModes[i]; - break; - } + if (!found_plane) { + printf("Cannot find a plane compatible with the display!\n"); + fflush(stdout); + exit(1); + } + + free(plane_props); + + vk::DisplayPlaneCapabilitiesKHR planeCaps; + gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps); + // Find a supported alpha mode + vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque; + vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = { + vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque, + vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal, + vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel, + vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied, + }; + for (uint32_t i = 0; i < sizeof(alphaModes); i++) { + if (planeCaps.supportedAlpha & alphaModes[i]) { + alphaMode = alphaModes[i]; + break; } + } - image_extent.setWidth(mode_props.parameters.visibleRegion.width); - image_extent.setHeight(mode_props.parameters.visibleRegion.height); + image_extent.setWidth(mode_props.parameters.visibleRegion.width); + image_extent.setHeight(mode_props.parameters.visibleRegion.height); - auto const createInfo = vk::DisplaySurfaceCreateInfoKHR() - .setDisplayMode(mode_props.displayMode) - .setPlaneIndex(plane_index) - .setPlaneStackIndex(plane_props[plane_index].currentStackIndex) - .setGlobalAlpha(1.0f) - .setAlphaMode(alphaMode) - .setImageExtent(image_extent); + auto const createInfo = vk::DisplaySurfaceCreateInfoKHR() + .setDisplayMode(mode_props.displayMode) + .setPlaneIndex(plane_index) + .setPlaneStackIndex(plane_props[plane_index].currentStackIndex) + .setGlobalAlpha(1.0f) + .setAlphaMode(alphaMode) + .setImageExtent(image_extent); - return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface); - } + return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface); +} - void Demo::run_display() { - while (!quit) { - draw(); - curFrame++; +void Demo::run_display() { + while (!quit) { + draw(); + curFrame++; - if (frameCount != INT32_MAX && curFrame == frameCount) { - quit = true; - } + if (frameCount != INT32_MAX && curFrame == frameCount) { + quit = true; } } +} #endif #if _WIN32 diff --git a/demos/smoke/Game.cpp b/demos/smoke/Game.cpp index 58fb5035..b0464687 100644 --- a/demos/smoke/Game.cpp +++ b/demos/smoke/Game.cpp @@ -1,18 +1,18 @@ /* -* Copyright (C) 2016 Google, Inc. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright (C) 2016 Google, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #include diff --git a/demos/smoke/Meshes.cpp b/demos/smoke/Meshes.cpp index e077be71..ed8c4d68 100644 --- a/demos/smoke/Meshes.cpp +++ b/demos/smoke/Meshes.cpp @@ -173,42 +173,102 @@ class BuildIcosphere { const std::vector> icosahedron_vertices = { // position normal {{ - -l1, -l2, 0.0f, -l1, -l2, 0.0f, + -l1, + -l2, + 0.0f, + -l1, + -l2, + 0.0f, }}, {{ - l1, -l2, 0.0f, l1, -l2, 0.0f, + l1, + -l2, + 0.0f, + l1, + -l2, + 0.0f, }}, {{ - l1, l2, 0.0f, l1, l2, 0.0f, + l1, + l2, + 0.0f, + l1, + l2, + 0.0f, }}, {{ - -l1, l2, 0.0f, -l1, l2, 0.0f, + -l1, + l2, + 0.0f, + -l1, + l2, + 0.0f, }}, {{ - -l2, 0.0f, -l1, -l2, 0.0f, -l1, + -l2, + 0.0f, + -l1, + -l2, + 0.0f, + -l1, }}, {{ - l2, 0.0f, -l1, l2, 0.0f, -l1, + l2, + 0.0f, + -l1, + l2, + 0.0f, + -l1, }}, {{ - l2, 0.0f, l1, l2, 0.0f, l1, + l2, + 0.0f, + l1, + l2, + 0.0f, + l1, }}, {{ - -l2, 0.0f, l1, -l2, 0.0f, l1, + -l2, + 0.0f, + l1, + -l2, + 0.0f, + l1, }}, {{ - 0.0f, -l1, -l2, 0.0f, -l1, -l2, + 0.0f, + -l1, + -l2, + 0.0f, + -l1, + -l2, }}, {{ - 0.0f, l1, -l2, 0.0f, l1, -l2, + 0.0f, + l1, + -l2, + 0.0f, + l1, + -l2, }}, {{ - 0.0f, l1, l2, 0.0f, l1, l2, + 0.0f, + l1, + l2, + 0.0f, + l1, + l2, }}, {{ - 0.0f, -l1, l2, 0.0f, -l1, l2, + 0.0f, + -l1, + l2, + 0.0f, + -l1, + l2, }}, }; const std::vector> icosahedron_faces = { @@ -280,7 +340,9 @@ class BuildIcosphere { const Mesh::Position &pos_a = mesh_.positions_[a]; const Mesh::Position &pos_b = mesh_.positions_[b]; Mesh::Position pos_mid = { - (pos_a.x + pos_b.x) / 2.0f, (pos_a.y + pos_b.y) / 2.0f, (pos_a.z + pos_b.z) / 2.0f, + (pos_a.x + pos_b.x) / 2.0f, + (pos_a.y + pos_b.y) / 2.0f, + (pos_a.z + pos_b.z) / 2.0f, }; float scale = radius_ / std::sqrt(pos_mid.x * pos_mid.x + pos_mid.y * pos_mid.y + pos_mid.z * pos_mid.z); pos_mid.x *= scale; @@ -320,12 +382,15 @@ class BuildTeapot { for (int i = 0; i < position_count; i += 3) { mesh.positions_.emplace_back(Mesh::Position{ - (teapot_positions[i + 0] + translate.x) * scale, (teapot_positions[i + 1] + translate.y) * scale, + (teapot_positions[i + 0] + translate.x) * scale, + (teapot_positions[i + 1] + translate.y) * scale, (teapot_positions[i + 2] + translate.z) * scale, }); mesh.normals_.emplace_back(Mesh::Normal{ - teapot_normals[i + 0], teapot_normals[i + 1], teapot_normals[i + 2], + teapot_normals[i + 0], + teapot_normals[i + 1], + teapot_normals[i + 2], }); } @@ -336,10 +401,14 @@ class BuildTeapot { void get_transform(const float *positions, int position_count, Mesh::Position &translate, float &scale) { float min[3] = { - positions[0], positions[1], positions[2], + positions[0], + positions[1], + positions[2], }; float max[3] = { - positions[0], positions[1], positions[2], + positions[0], + positions[1], + positions[2], }; for (int i = 3; i < position_count; i += 3) { for (int j = 0; j < 3; j++) { @@ -353,7 +422,9 @@ class BuildTeapot { translate.z = -(min[2] + max[2]) / 2.0f; float extents[3] = { - max[0] + translate.x, max[1] + translate.y, max[2] + translate.z, + max[0] + translate.x, + max[1] + translate.y, + max[2] + translate.z, }; float max_extent = extents[0]; diff --git a/demos/smoke/ShellWin32.cpp b/demos/smoke/ShellWin32.cpp index 69ef38b4..11a0eea5 100644 --- a/demos/smoke/ShellWin32.cpp +++ b/demos/smoke/ShellWin32.cpp @@ -84,7 +84,7 @@ void ShellWin32::create_window() { win_rect.right - win_rect.left, win_rect.bottom - win_rect.top, nullptr, nullptr, hinstance_, nullptr); SetForegroundWindow(hwnd_); - SetWindowLongPtr(hwnd_, GWLP_USERDATA, (LONG_PTR) this); + SetWindowLongPtr(hwnd_, GWLP_USERDATA, (LONG_PTR)this); } PFN_vkGetInstanceProcAddr ShellWin32::load_vk() { diff --git a/demos/smoke/Simulation.cpp b/demos/smoke/Simulation.cpp index cc5fbabf..0346a7ee 100644 --- a/demos/smoke/Simulation.cpp +++ b/demos/smoke/Simulation.cpp @@ -26,8 +26,16 @@ class MeshPicker { public: MeshPicker() : pattern_({{ - Meshes::MESH_PYRAMID, Meshes::MESH_ICOSPHERE, Meshes::MESH_TEAPOT, Meshes::MESH_PYRAMID, Meshes::MESH_ICOSPHERE, - Meshes::MESH_PYRAMID, Meshes::MESH_PYRAMID, Meshes::MESH_PYRAMID, Meshes::MESH_PYRAMID, Meshes::MESH_PYRAMID, + Meshes::MESH_PYRAMID, + Meshes::MESH_ICOSPHERE, + Meshes::MESH_TEAPOT, + Meshes::MESH_PYRAMID, + Meshes::MESH_ICOSPHERE, + Meshes::MESH_PYRAMID, + Meshes::MESH_PYRAMID, + Meshes::MESH_PYRAMID, + Meshes::MESH_PYRAMID, + Meshes::MESH_PYRAMID, }}), cur_(-1) {} @@ -249,7 +257,10 @@ Simulation::Simulation(int object_count) : random_dev_() { float scale = mesh.scale(type); objects_.emplace_back(Object{ - type, glm::vec3(0.5f + 0.5f * (float)i / object_count), color.pick(), Animation(random_dev_(), scale), + type, + glm::vec3(0.5f + 0.5f * (float)i / object_count), + color.pick(), + Animation(random_dev_(), scale), Path(random_dev_()), }); } diff --git a/demos/vulkaninfo.c b/demos/vulkaninfo.c index c27205a0..a1a4e458 100644 --- a/demos/vulkaninfo.c +++ b/demos/vulkaninfo.c @@ -811,27 +811,27 @@ static void AppCreateInstance(struct AppInstance *inst) { } inst->vkGetPhysicalDeviceSurfaceSupportKHR = - (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceSurfaceSupportKHR"); + (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceSurfaceSupportKHR"); inst->vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); + inst->instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); inst->vkGetPhysicalDeviceSurfaceFormatsKHR = - (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"); + (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceSurfaceFormatsKHR"); inst->vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"); + inst->instance, "vkGetPhysicalDeviceSurfacePresentModesKHR"); inst->vkGetPhysicalDeviceProperties2KHR = - (PFN_vkGetPhysicalDeviceProperties2KHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceProperties2KHR"); + (PFN_vkGetPhysicalDeviceProperties2KHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceProperties2KHR"); inst->vkGetPhysicalDeviceFormatProperties2KHR = (PFN_vkGetPhysicalDeviceFormatProperties2KHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceFormatProperties2KHR"); + inst->instance, "vkGetPhysicalDeviceFormatProperties2KHR"); inst->vkGetPhysicalDeviceQueueFamilyProperties2KHR = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceQueueFamilyProperties2KHR"); + inst->instance, "vkGetPhysicalDeviceQueueFamilyProperties2KHR"); inst->vkGetPhysicalDeviceFeatures2KHR = - (PFN_vkGetPhysicalDeviceFeatures2KHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceFeatures2KHR"); + (PFN_vkGetPhysicalDeviceFeatures2KHR)vkGetInstanceProcAddr(inst->instance, "vkGetPhysicalDeviceFeatures2KHR"); inst->vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceMemoryProperties2KHR"); + inst->instance, "vkGetPhysicalDeviceMemoryProperties2KHR"); inst->vkGetPhysicalDeviceSurfaceCapabilities2KHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceSurfaceCapabilities2KHR"); + inst->instance, "vkGetPhysicalDeviceSurfaceCapabilities2KHR"); inst->vkGetPhysicalDeviceSurfaceCapabilities2EXT = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT)vkGetInstanceProcAddr( - inst->instance, "vkGetPhysicalDeviceSurfaceCapabilities2EXT"); + inst->instance, "vkGetPhysicalDeviceSurfaceCapabilities2EXT"); } //----------------------------------------------------------- @@ -2375,7 +2375,7 @@ int main(int argc, char **argv) { AppDumpExtensions("\t\t", "Layer", inst.global_layers[i].extension_count, inst.global_layers[i].extension_properties, out); } else { - printf("%s (%s) Vulkan version %s, layer version %s\n", layer_prop->layerName, (char *) layer_prop->description, + printf("%s (%s) Vulkan version %s, layer version %s\n", layer_prop->layerName, (char *)layer_prop->description, spec_version, layer_version); AppDumpExtensions("\t", "Layer", inst.global_layers[i].extension_count, inst.global_layers[i].extension_properties, out); @@ -2403,7 +2403,9 @@ int main(int argc, char **argv) { } else { AppDumpExtensions("\t\t", "Layer-Device", count, props, out); } - if (html_output) { fprintf(out, "\t\t\t\t\t\n"); } + if (html_output) { + fprintf(out, "\t\t\t\t\t\n"); + } free(props); } if (html_output) { @@ -2413,7 +2415,9 @@ int main(int argc, char **argv) { } } - if (html_output) { fprintf(out, "\t\t\t\n"); } + if (html_output) { + fprintf(out, "\t\t\t\n"); + } fflush(out); //----------------------------- @@ -2489,7 +2493,8 @@ int main(int argc, char **argv) { } //--XLIB-- #elif VK_USE_PLATFORM_XLIB_KHR - if (has_display && CheckExtensionEnabled(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, inst.inst_extensions, inst.inst_extensions_count)) { + if (has_display && + CheckExtensionEnabled(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, inst.inst_extensions, inst.inst_extensions_count)) { AppCreateXlibWindow(&inst); for (uint32_t i = 0; i < gpu_count; i++) { AppCreateXlibSurface(&inst); @@ -2516,7 +2521,7 @@ int main(int argc, char **argv) { if (html_output) { fprintf(out, "\t\t\t\t
None found
\n"); } else { - printf( "None found\n"); + printf("None found\n"); } } -- cgit v1.2.3