2 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 LunarG, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * Author: Chia-I Wu <olv@lunarg.com>
19 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
20 * Author: Ian Elliott <ian@LunarG.com>
21 * Author: Ian Elliott <ianelliott@google.com>
22 * Author: Jon Ashburn <jon@lunarg.com>
23 * Author: Gwan-gyeong Mun <elongbug@gmail.com>
24 * Author: Tony Barbour <tony@LunarG.com>
25 * Author: Bill Hollings <bill.hollings@brenwill.com>
36 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
37 #include <X11/Xutil.h>
38 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
39 #include <linux/input.h>
40 #include "xdg-shell-client-header.h"
41 #include "xdg-decoration-client-header.h"
45 #pragma comment(linker, "/subsystem:windows")
46 #define APP_NAME_STR_LEN 80
50 #include "vulkan_wrapper.h"
52 #include <vulkan/vulkan.h>
55 #include <vulkan/vk_sdk_platform.h>
57 #include "object_type_string_helper.h"
61 #define MILLION 1000000L
62 #define BILLION 1000000000L
64 #define DEMO_TEXTURE_COUNT 1
65 #define APP_SHORT_NAME "vkcube"
66 #define APP_LONG_NAME "Vulkan Cube"
68 // Allow a maximum of two outstanding presentation operations.
71 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
73 #if defined(NDEBUG) && defined(__GNUC__)
74 #define U_ASSERT_ONLY __attribute__((unused))
80 #define UNUSED __attribute__((unused))
86 bool in_callback = false;
87 #define ERR_EXIT(err_msg, err_class) \
89 if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
92 void DbgMsg(char *fmt, ...) {
100 #elif defined __ANDROID__
101 #include <android/log.h>
102 #define ERR_EXIT(err_msg, err_class) \
104 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
107 #ifdef VARARGS_WORKS_ON_ANDROID
108 void DbgMsg(const char *fmt, ...) {
111 __android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
114 #else // VARARGS_WORKS_ON_ANDROID
115 #define DbgMsg(fmt, ...) \
117 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
119 #endif // VARARGS_WORKS_ON_ANDROID
121 #define ERR_EXIT(err_msg, err_class) \
123 printf("%s\n", err_msg); \
127 void DbgMsg(char *fmt, ...) {
136 #define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
138 demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
139 if (demo->fp##entrypoint == NULL) { \
140 ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
144 static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
146 #define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
148 if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
149 demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
150 if (demo->fp##entrypoint == NULL) { \
151 ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure"); \
156 * structure to track all objects related to a texture.
158 struct texture_object {
163 VkImageLayout imageLayout;
165 VkMemoryAllocateInfo mem_alloc;
168 int32_t tex_width, tex_height;
171 static char *tex_files[] = {"lunarg.ppm"};
173 static int validation_error = 0;
175 struct vktexcube_vs_uniform {
176 // Must start with MVP
178 float position[12 * 3][4];
179 float attr[12 * 3][4];
182 //--------------------------------------------------------------------------------------
183 // Mesh and VertexFormat Data
184 //--------------------------------------------------------------------------------------
186 static const float g_vertex_buffer_data[] = {
187 -1.0f,-1.0f,-1.0f, // -X side
194 -1.0f,-1.0f,-1.0f, // -Z side
201 -1.0f,-1.0f,-1.0f, // -Y side
208 -1.0f, 1.0f,-1.0f, // +Y side
215 1.0f, 1.0f,-1.0f, // +X side
222 -1.0f, 1.0f, 1.0f, // +Z side
230 static const float g_uv_buffer_data[] = {
231 0.0f, 1.0f, // -X side
238 1.0f, 1.0f, // -Z side
245 1.0f, 0.0f, // -Y side
252 1.0f, 0.0f, // +Y side
259 1.0f, 0.0f, // +X side
266 0.0f, 0.0f, // +Z side
275 void dumpMatrix(const char *note, mat4x4 MVP) {
278 printf("%s: \n", note);
279 for (i = 0; i < 4; i++) {
280 printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
286 void dumpVec4(const char *note, vec4 vector) {
287 printf("%s: \n", note);
288 printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
296 VkCommandBuffer graphics_to_present_cmd;
298 VkBuffer uniform_buffer;
299 VkDeviceMemory uniform_memory;
300 VkFramebuffer framebuffer;
301 VkDescriptorSet descriptor_set;
302 } SwapchainImageResources;
305 #if defined(VK_USE_PLATFORM_WIN32_KHR)
306 #define APP_NAME_STR_LEN 80
307 HINSTANCE connection; // hInstance - Windows Instance
308 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
309 HWND window; // hWnd - window handle
310 POINT minsize; // minimum window size
311 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
314 Atom xlib_wm_delete_window;
315 #elif defined(VK_USE_PLATFORM_XCB_KHR)
317 xcb_connection_t *connection;
318 xcb_screen_t *screen;
319 xcb_window_t xcb_window;
320 xcb_intern_atom_reply_t *atom_wm_delete_window;
321 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
322 struct wl_display *display;
323 struct wl_registry *registry;
324 struct wl_compositor *compositor;
325 struct wl_surface *window;
326 struct xdg_wm_base *xdg_wm_base;
327 struct zxdg_decoration_manager_v1 *xdg_decoration_mgr;
328 struct zxdg_toplevel_decoration_v1 *toplevel_decoration;
329 struct xdg_surface *xdg_surface;
330 int xdg_surface_has_been_configured;
331 struct xdg_toplevel *xdg_toplevel;
332 struct wl_seat *seat;
333 struct wl_pointer *pointer;
334 struct wl_keyboard *keyboard;
335 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
336 struct ANativeWindow *window;
337 #elif defined(VK_USE_PLATFORM_METAL_EXT)
340 VkSurfaceKHR surface;
342 bool use_staging_buffer;
343 bool separate_present_queue;
346 bool VK_KHR_incremental_present_enabled;
348 bool VK_GOOGLE_display_timing_enabled;
349 bool syncd_with_actual_presents;
350 uint64_t refresh_duration;
351 uint64_t refresh_duration_multiplier;
352 uint64_t target_IPD; // image present duration (inverse of frame rate)
353 uint64_t prev_desired_present_time;
354 uint32_t next_present_id;
355 uint32_t last_early_id; // 0 if no early images
356 uint32_t last_late_id; // 0 if no late images
359 VkPhysicalDevice gpu;
361 VkQueue graphics_queue;
362 VkQueue present_queue;
363 uint32_t graphics_queue_family_index;
364 uint32_t present_queue_family_index;
365 VkSemaphore image_acquired_semaphores[FRAME_LAG];
366 VkSemaphore draw_complete_semaphores[FRAME_LAG];
367 VkSemaphore image_ownership_semaphores[FRAME_LAG];
368 VkPhysicalDeviceProperties gpu_props;
369 VkQueueFamilyProperties *queue_props;
370 VkPhysicalDeviceMemoryProperties memory_properties;
372 uint32_t enabled_extension_count;
373 uint32_t enabled_layer_count;
374 char *extension_names[64];
375 char *enabled_layers[64];
379 VkColorSpaceKHR color_space;
381 PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
382 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
383 PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
384 PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
385 PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
386 PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
387 PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
388 PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
389 PFN_vkQueuePresentKHR fpQueuePresentKHR;
390 PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
391 PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
392 uint32_t swapchainImageCount;
393 VkSwapchainKHR swapchain;
394 SwapchainImageResources *swapchain_image_resources;
395 VkPresentModeKHR presentMode;
396 VkFence fences[FRAME_LAG];
399 VkCommandPool cmd_pool;
400 VkCommandPool present_cmd_pool;
406 VkMemoryAllocateInfo mem_alloc;
411 struct texture_object textures[DEMO_TEXTURE_COUNT];
412 struct texture_object staging_texture;
414 VkCommandBuffer cmd; // Buffer for initialization commands
415 VkPipelineLayout pipeline_layout;
416 VkDescriptorSetLayout desc_layout;
417 VkPipelineCache pipelineCache;
418 VkRenderPass render_pass;
421 mat4x4 projection_matrix;
426 float spin_increment;
429 VkShaderModule vert_shader_module;
430 VkShaderModule frag_shader_module;
432 VkDescriptorPool desc_pool;
438 bool validate_checks_disabled;
440 bool suppress_popups;
442 PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
443 PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
444 PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
445 PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
446 PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
447 PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
448 PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
449 VkDebugUtilsMessengerEXT dbg_messenger;
451 uint32_t current_buffer;
452 uint32_t queue_family_count;
455 VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
456 VkDebugUtilsMessageTypeFlagsEXT messageType,
457 const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
459 char prefix[64] = "";
460 char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
462 struct demo *demo = (struct demo *)pUserData;
464 if (demo->use_break) {
472 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
473 strcat(prefix, "VERBOSE : ");
474 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
475 strcat(prefix, "INFO : ");
476 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
477 strcat(prefix, "WARNING : ");
478 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
479 strcat(prefix, "ERROR : ");
482 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
483 strcat(prefix, "GENERAL");
485 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
486 strcat(prefix, "VALIDATION");
487 validation_error = 1;
489 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
490 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
493 strcat(prefix, "PERFORMANCE");
497 sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
498 pCallbackData->pMessageIdName, pCallbackData->pMessage);
499 if (pCallbackData->objectCount > 0) {
500 char tmp_message[500];
501 sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
502 strcat(message, tmp_message);
503 for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
504 if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
505 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
506 string_VkObjectType(pCallbackData->pObjects[object].objectType),
507 (void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
509 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
510 string_VkObjectType(pCallbackData->pObjects[object].objectType),
511 (void *)(pCallbackData->pObjects[object].objectHandle));
513 strcat(message, tmp_message);
516 if (pCallbackData->cmdBufLabelCount > 0) {
517 char tmp_message[500];
518 sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
519 strcat(message, tmp_message);
520 for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
521 sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
522 pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
523 pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
524 pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
525 strcat(message, tmp_message);
532 if (!demo->suppress_popups) MessageBox(NULL, message, "Alert", MB_OK);
535 #elif defined(ANDROID)
537 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
538 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
539 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
540 __android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message);
541 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
542 __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
543 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
544 __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
546 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
551 printf("%s\n", message);
558 // Don't bail out, but keep going.
562 bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
563 // The desired time was the earliest time that the present should have
564 // occured. In almost every case, the actual time should be later than the
565 // desired time. We should only consider the actual time "late" if it is
566 // after "desired + rdur".
567 if (actual <= desired) {
568 // The actual time was before or equal to the desired time. This will
569 // probably never happen, but in case it does, return false since the
570 // present was obviously NOT late.
573 uint64_t deadline = desired + rdur;
574 if (actual > deadline) {
580 bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
581 if (earliest < actual) {
582 // Consider whether this present could have occured earlier. Make sure
583 // that earliest time was at least 2msec earlier than actual time, and
584 // that the margin was at least 2msec:
585 uint64_t diff = actual - earliest;
586 if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
587 // This present could have occured earlier because both: 1) the
588 // earliest time was at least 2 msec before actual time, and 2) the
589 // margin was at least 2msec.
596 // Forward declarations:
597 static void demo_resize(struct demo *demo);
598 static void demo_create_surface(struct demo *demo);
600 static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
601 // Search memtypes to find first index with those properties
602 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
603 if ((typeBits & 1) == 1) {
604 // Type is available, does it match user properties?
605 if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
612 // No memory types matched, return failure
616 static void demo_flush_init_cmd(struct demo *demo) {
617 VkResult U_ASSERT_ONLY err;
619 // This function could get called twice if the texture uses a staging buffer
620 // In that case the second call should be ignored
621 if (demo->cmd == VK_NULL_HANDLE) return;
623 err = vkEndCommandBuffer(demo->cmd);
627 VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
628 err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
631 const VkCommandBuffer cmd_bufs[] = {demo->cmd};
632 VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
634 .waitSemaphoreCount = 0,
635 .pWaitSemaphores = NULL,
636 .pWaitDstStageMask = NULL,
637 .commandBufferCount = 1,
638 .pCommandBuffers = cmd_bufs,
639 .signalSemaphoreCount = 0,
640 .pSignalSemaphores = NULL};
642 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
645 err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
648 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
649 vkDestroyFence(demo->device, fence, NULL);
650 demo->cmd = VK_NULL_HANDLE;
653 static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
654 VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
655 VkPipelineStageFlags dest_stages) {
658 VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
660 .srcAccessMask = srcAccessMask,
662 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
663 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
664 .oldLayout = old_image_layout,
665 .newLayout = new_image_layout,
667 .subresourceRange = {aspectMask, 0, 1, 0, 1}};
669 switch (new_image_layout) {
670 case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
671 /* Make sure anything that was copying from this image has completed */
672 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
675 case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
676 image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
679 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
680 image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
683 case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
684 image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
687 case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
688 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
691 case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
692 image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
696 image_memory_barrier.dstAccessMask = 0;
700 VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
702 vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
705 static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
706 VkDebugUtilsLabelEXT label;
707 memset(&label, 0, sizeof(label));
708 const VkCommandBufferBeginInfo cmd_buf_info = {
709 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
711 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
712 .pInheritanceInfo = NULL,
714 const VkClearValue clear_values[2] = {
715 [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
716 [1] = {.depthStencil = {1.0f, 0}},
718 const VkRenderPassBeginInfo rp_begin = {
719 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
721 .renderPass = demo->render_pass,
722 .framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
723 .renderArea.offset.x = 0,
724 .renderArea.offset.y = 0,
725 .renderArea.extent.width = demo->width,
726 .renderArea.extent.height = demo->height,
727 .clearValueCount = 2,
728 .pClearValues = clear_values,
730 VkResult U_ASSERT_ONLY err;
732 err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
734 if (demo->validate) {
735 // Set a name for the command buffer
736 VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
737 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
739 .objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
740 .objectHandle = (uint64_t)cmd_buf,
741 .pObjectName = "CubeDrawCommandBuf",
743 demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
745 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
747 label.pLabelName = "DrawBegin";
748 label.color[0] = 0.4f;
749 label.color[1] = 0.3f;
750 label.color[2] = 0.2f;
751 label.color[3] = 0.1f;
752 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
756 vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
758 if (demo->validate) {
759 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
761 label.pLabelName = "InsideRenderPass";
762 label.color[0] = 8.4f;
763 label.color[1] = 7.3f;
764 label.color[2] = 6.2f;
765 label.color[3] = 7.1f;
766 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
769 vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
770 vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
771 &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
773 memset(&viewport, 0, sizeof(viewport));
774 float viewport_dimension;
775 if (demo->width < demo->height) {
776 viewport_dimension = (float)demo->width;
777 viewport.y = (demo->height - demo->width) / 2.0f;
779 viewport_dimension = (float)demo->height;
780 viewport.x = (demo->width - demo->height) / 2.0f;
782 viewport.height = viewport_dimension;
783 viewport.width = viewport_dimension;
784 viewport.minDepth = (float)0.0f;
785 viewport.maxDepth = (float)1.0f;
786 vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
789 memset(&scissor, 0, sizeof(scissor));
790 scissor.extent.width = demo->width;
791 scissor.extent.height = demo->height;
792 scissor.offset.x = 0;
793 scissor.offset.y = 0;
794 vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
796 if (demo->validate) {
797 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
799 label.pLabelName = "ActualDraw";
800 label.color[0] = -0.4f;
801 label.color[1] = -0.3f;
802 label.color[2] = -0.2f;
803 label.color[3] = -0.1f;
804 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
807 vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
808 if (demo->validate) {
809 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
812 // Note that ending the renderpass changes the image's layout from
813 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
814 vkCmdEndRenderPass(cmd_buf);
815 if (demo->validate) {
816 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
819 if (demo->separate_present_queue) {
820 // We have to transfer ownership from the graphics queue family to the
821 // present queue family to be able to present. Note that we don't have
822 // to transfer from present queue family back to graphics queue family at
823 // the start of the next frame because we don't care about the image's
824 // contents at that point.
825 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
829 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
830 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
831 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
832 .dstQueueFamilyIndex = demo->present_queue_family_index,
833 .image = demo->swapchain_image_resources[demo->current_buffer].image,
834 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
836 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
837 NULL, 1, &image_ownership_barrier);
839 if (demo->validate) {
840 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
842 err = vkEndCommandBuffer(cmd_buf);
846 void demo_build_image_ownership_cmd(struct demo *demo, int i) {
847 VkResult U_ASSERT_ONLY err;
849 const VkCommandBufferBeginInfo cmd_buf_info = {
850 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
852 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
853 .pInheritanceInfo = NULL,
855 err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
858 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
862 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
863 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
864 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
865 .dstQueueFamilyIndex = demo->present_queue_family_index,
866 .image = demo->swapchain_image_resources[i].image,
867 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
869 vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
870 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
871 err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
875 void demo_update_data_buffer(struct demo *demo) {
876 mat4x4 MVP, Model, VP;
877 int matrixSize = sizeof(MVP);
879 VkResult U_ASSERT_ONLY err;
881 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
883 // Rotate around the Y axis
884 mat4x4_dup(Model, demo->model_matrix);
885 mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle));
886 mat4x4_mul(MVP, VP, demo->model_matrix);
888 err = vkMapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, 0,
892 memcpy(pData, (const void *)&MVP[0][0], matrixSize);
894 vkUnmapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory);
897 void DemoUpdateTargetIPD(struct demo *demo) {
898 // Look at what happened to previous presents, and make appropriate
899 // adjustments in timing:
900 VkResult U_ASSERT_ONLY err;
901 VkPastPresentationTimingGOOGLE *past = NULL;
904 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
907 past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
909 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
914 bool calibrate_next = false;
915 for (uint32_t i = 0; i < count; i++) {
916 if (!demo->syncd_with_actual_presents) {
917 // This is the first time that we've received an
918 // actualPresentTime for this swapchain. In order to not
919 // perceive these early frames as "late", we need to sync-up
920 // our future desiredPresentTime's with the
921 // actualPresentTime(s) that we're receiving now.
922 calibrate_next = true;
924 // So that we don't suspect any pending presents as late,
925 // record them all as suspected-late presents:
926 demo->last_late_id = demo->next_present_id - 1;
927 demo->last_early_id = 0;
928 demo->syncd_with_actual_presents = true;
930 } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
931 demo->refresh_duration)) {
932 // This image could have been presented earlier. We don't want
933 // to decrease the target_IPD until we've seen early presents
934 // for at least two seconds.
935 if (demo->last_early_id == past[i].presentID) {
936 // We've now seen two seconds worth of early presents.
937 // Flag it as such, and reset the counter:
939 demo->last_early_id = 0;
940 } else if (demo->last_early_id == 0) {
941 // This is the first early present we've seen.
942 // Calculate the presentID for two seconds from now.
943 uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
944 uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
945 demo->last_early_id = past[i].presentID + howManyPresents;
947 // We are in the midst of a set of early images,
948 // and so we won't do anything.
951 demo->last_late_id = 0;
952 } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
953 // This image was presented after its desired time. Since
954 // there's a delay between calling vkQueuePresentKHR and when
955 // we get the timing data, several presents may have been late.
956 // Thus, we need to threat all of the outstanding presents as
957 // being likely late, so that we only increase the target_IPD
958 // once for all of those presents.
959 if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
961 // Record the last suspected-late present:
962 demo->last_late_id = demo->next_present_id - 1;
964 // We are in the midst of a set of likely-late images,
965 // and so we won't do anything.
968 demo->last_early_id = 0;
970 // Since this image was not presented early or late, reset
971 // any sets of early or late presentIDs:
974 calibrate_next = true;
975 demo->last_early_id = 0;
976 demo->last_late_id = 0;
981 // Since we've seen at least two-seconds worth of presnts that
982 // could have occured earlier than desired, let's decrease the
983 // target_IPD (i.e. increase the frame rate):
985 // TODO(ianelliott): Try to calculate a better target_IPD based
986 // on the most recently-seen present (this is overly-simplistic).
987 demo->refresh_duration_multiplier--;
988 if (demo->refresh_duration_multiplier == 0) {
989 // This should never happen, but in case it does, don't
991 demo->refresh_duration_multiplier = 1;
993 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
996 // Since we found a new instance of a late present, we want to
997 // increase the target_IPD (i.e. decrease the frame rate):
999 // TODO(ianelliott): Try to calculate a better target_IPD based
1000 // on the most recently-seen present (this is overly-simplistic).
1001 demo->refresh_duration_multiplier++;
1002 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
1005 if (calibrate_next) {
1006 int64_t multiple = demo->next_present_id - past[count - 1].presentID;
1007 demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
1013 static void demo_draw(struct demo *demo) {
1014 VkResult U_ASSERT_ONLY err;
1016 // Ensure no more than FRAME_LAG renderings are outstanding
1017 vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
1018 vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
1021 // Get the index of the next available swapchain image:
1023 demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
1024 demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer);
1026 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1027 // demo->swapchain is out of date (e.g. the window was resized) and
1028 // must be recreated:
1030 } else if (err == VK_SUBOPTIMAL_KHR) {
1031 // demo->swapchain is not as optimal as it could be, but the platform's
1032 // presentation engine will still present the image correctly.
1034 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1035 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1036 demo_create_surface(demo);
1041 } while (err != VK_SUCCESS);
1043 demo_update_data_buffer(demo);
1045 if (demo->VK_GOOGLE_display_timing_enabled) {
1046 // Look at what happened to previous presents, and make appropriate
1047 // adjustments in timing:
1048 DemoUpdateTargetIPD(demo);
1050 // Note: a real application would position its geometry to that it's in
1051 // the correct locatoin for when the next image is presented. It might
1052 // also wait, so that there's less latency between any input and when
1053 // the next image is rendered/presented. This demo program is so
1054 // simple that it doesn't do either of those.
1057 // Wait for the image acquired semaphore to be signaled to ensure
1058 // that the image won't be rendered to until the presentation
1059 // engine has fully released ownership to the application, and it is
1060 // okay to render to the image.
1061 VkPipelineStageFlags pipe_stage_flags;
1062 VkSubmitInfo submit_info;
1063 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1064 submit_info.pNext = NULL;
1065 submit_info.pWaitDstStageMask = &pipe_stage_flags;
1066 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1067 submit_info.waitSemaphoreCount = 1;
1068 submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
1069 submit_info.commandBufferCount = 1;
1070 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
1071 submit_info.signalSemaphoreCount = 1;
1072 submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1073 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
1076 if (demo->separate_present_queue) {
1077 // If we are using separate queues, change image ownership to the
1078 // present queue before presenting, waiting for the draw complete
1079 // semaphore and signalling the ownership released semaphore when finished
1080 VkFence nullFence = VK_NULL_HANDLE;
1081 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1082 submit_info.waitSemaphoreCount = 1;
1083 submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1084 submit_info.commandBufferCount = 1;
1085 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
1086 submit_info.signalSemaphoreCount = 1;
1087 submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
1088 err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
1092 // If we are using separate queues we have to wait for image ownership,
1093 // otherwise wait for draw complete
1094 VkPresentInfoKHR present = {
1095 .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1097 .waitSemaphoreCount = 1,
1098 .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index]
1099 : &demo->draw_complete_semaphores[demo->frame_index],
1100 .swapchainCount = 1,
1101 .pSwapchains = &demo->swapchain,
1102 .pImageIndices = &demo->current_buffer,
1105 VkRectLayerKHR rect;
1106 VkPresentRegionKHR region;
1107 VkPresentRegionsKHR regions;
1108 if (demo->VK_KHR_incremental_present_enabled) {
1109 // If using VK_KHR_incremental_present, we provide a hint of the region
1110 // that contains changed content relative to the previously-presented
1111 // image. The implementation can use this hint in order to save
1112 // work/power (by only copying the region in the hint). The
1113 // implementation is free to ignore the hint though, and so we must
1114 // ensure that the entire image has the correctly-drawn content.
1115 uint32_t eighthOfWidth = demo->width / 8;
1116 uint32_t eighthOfHeight = demo->height / 8;
1118 rect.offset.x = eighthOfWidth;
1119 rect.offset.y = eighthOfHeight;
1120 rect.extent.width = eighthOfWidth * 6;
1121 rect.extent.height = eighthOfHeight * 6;
1124 region.rectangleCount = 1;
1125 region.pRectangles = ▭
1127 regions.sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR;
1128 regions.pNext = present.pNext;
1129 regions.swapchainCount = present.swapchainCount;
1130 regions.pRegions = ®ion;
1131 present.pNext = ®ions;
1134 if (demo->VK_GOOGLE_display_timing_enabled) {
1135 VkPresentTimeGOOGLE ptime;
1136 if (demo->prev_desired_present_time == 0) {
1137 // This must be the first present for this swapchain.
1139 // We don't know where we are relative to the presentation engine's
1140 // display's refresh cycle. We also don't know how long rendering
1141 // takes. Let's make a grossly-simplified assumption that the
1142 // desiredPresentTime should be half way between now and
1143 // now+target_IPD. We will adjust over time.
1144 uint64_t curtime = getTimeInNanoseconds();
1146 // Since we didn't find out the current time, don't give a
1147 // desiredPresentTime:
1148 ptime.desiredPresentTime = 0;
1150 ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
1153 ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
1155 ptime.presentID = demo->next_present_id++;
1156 demo->prev_desired_present_time = ptime.desiredPresentTime;
1158 VkPresentTimesInfoGOOGLE present_time = {
1159 .sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
1160 .pNext = present.pNext,
1161 .swapchainCount = present.swapchainCount,
1164 if (demo->VK_GOOGLE_display_timing_enabled) {
1165 present.pNext = &present_time;
1169 err = demo->fpQueuePresentKHR(demo->present_queue, &present);
1170 demo->frame_index += 1;
1171 demo->frame_index %= FRAME_LAG;
1173 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1174 // demo->swapchain is out of date (e.g. the window was resized) and
1175 // must be recreated:
1177 } else if (err == VK_SUBOPTIMAL_KHR) {
1178 // demo->swapchain is not as optimal as it could be, but the platform's
1179 // presentation engine will still present the image correctly.
1180 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1181 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1182 demo_create_surface(demo);
1189 static void demo_prepare_buffers(struct demo *demo) {
1190 VkResult U_ASSERT_ONLY err;
1191 VkSwapchainKHR oldSwapchain = demo->swapchain;
1193 // Check the surface capabilities and formats
1194 VkSurfaceCapabilitiesKHR surfCapabilities;
1195 err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
1198 uint32_t presentModeCount;
1199 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
1201 VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
1202 assert(presentModes);
1203 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
1206 VkExtent2D swapchainExtent;
1207 // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
1208 if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
1209 // If the surface size is undefined, the size is set to the size
1210 // of the images requested, which must fit within the minimum and
1212 swapchainExtent.width = demo->width;
1213 swapchainExtent.height = demo->height;
1215 if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
1216 swapchainExtent.width = surfCapabilities.minImageExtent.width;
1217 } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
1218 swapchainExtent.width = surfCapabilities.maxImageExtent.width;
1221 if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
1222 swapchainExtent.height = surfCapabilities.minImageExtent.height;
1223 } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
1224 swapchainExtent.height = surfCapabilities.maxImageExtent.height;
1227 // If the surface size is defined, the swap chain size must match
1228 swapchainExtent = surfCapabilities.currentExtent;
1229 demo->width = surfCapabilities.currentExtent.width;
1230 demo->height = surfCapabilities.currentExtent.height;
1233 if (demo->width == 0 || demo->height == 0) {
1234 demo->is_minimized = true;
1237 demo->is_minimized = false;
1240 // The FIFO present mode is guaranteed by the spec to be supported
1241 // and to have no tearing. It's a great default present mode to use.
1242 VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
1244 // There are times when you may wish to use another present mode. The
1245 // following code shows how to select them, and the comments provide some
1246 // reasons you may wish to use them.
1248 // It should be noted that Vulkan 1.0 doesn't provide a method for
1249 // synchronizing rendering with the presentation engine's display. There
1250 // is a method provided for throttling rendering with the display, but
1251 // there are some presentation engines for which this method will not work.
1252 // If an application doesn't throttle its rendering, and if it renders much
1253 // faster than the refresh rate of the display, this can waste power on
1254 // mobile devices. That is because power is being spent rendering images
1255 // that may never be seen.
1257 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1258 // tearing, or have some way of synchronizing their rendering with the
1260 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1261 // generally render a new presentable image every refresh cycle, but are
1262 // occasionally early. In this case, the application wants the new image
1263 // to be displayed instead of the previously-queued-for-presentation image
1264 // that has not yet been displayed.
1265 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1266 // render a new presentable image every refresh cycle, but are occasionally
1267 // late. In this case (perhaps because of stuttering/latency concerns),
1268 // the application wants the late image to be immediately displayed, even
1269 // though that may mean some tearing.
1271 if (demo->presentMode != swapchainPresentMode) {
1272 for (size_t i = 0; i < presentModeCount; ++i) {
1273 if (presentModes[i] == demo->presentMode) {
1274 swapchainPresentMode = demo->presentMode;
1279 if (swapchainPresentMode != demo->presentMode) {
1280 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1283 // Determine the number of VkImages to use in the swap chain.
1284 // Application desires to acquire 3 images at a time for triple
1286 uint32_t desiredNumOfSwapchainImages = 3;
1287 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1288 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1290 // If maxImageCount is 0, we can ask for as many images as we want;
1291 // otherwise we're limited to maxImageCount
1292 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1293 // Application must settle for fewer images than desired:
1294 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1297 VkSurfaceTransformFlagsKHR preTransform;
1298 if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
1299 preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
1301 preTransform = surfCapabilities.currentTransform;
1304 // Find a supported composite alpha mode - one of these is guaranteed to be set
1305 VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1306 VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1307 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
1308 VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
1309 VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
1310 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
1312 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1313 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1314 compositeAlpha = compositeAlphaFlags[i];
1319 VkSwapchainCreateInfoKHR swapchain_ci = {
1320 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
1322 .surface = demo->surface,
1323 .minImageCount = desiredNumOfSwapchainImages,
1324 .imageFormat = demo->format,
1325 .imageColorSpace = demo->color_space,
1328 .width = swapchainExtent.width,
1329 .height = swapchainExtent.height,
1331 .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
1332 .preTransform = preTransform,
1333 .compositeAlpha = compositeAlpha,
1334 .imageArrayLayers = 1,
1335 .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
1336 .queueFamilyIndexCount = 0,
1337 .pQueueFamilyIndices = NULL,
1338 .presentMode = swapchainPresentMode,
1339 .oldSwapchain = oldSwapchain,
1343 err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
1346 // If we just re-created an existing swapchain, we should destroy the old
1347 // swapchain at this point.
1348 // Note: destroying the swapchain also cleans up all its associated
1349 // presentable images once the platform is done with them.
1350 if (oldSwapchain != VK_NULL_HANDLE) {
1351 demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
1354 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
1357 VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
1358 assert(swapchainImages);
1359 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
1362 demo->swapchain_image_resources =
1363 (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
1364 assert(demo->swapchain_image_resources);
1366 for (i = 0; i < demo->swapchainImageCount; i++) {
1367 VkImageViewCreateInfo color_image_view = {
1368 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1370 .format = demo->format,
1373 .r = VK_COMPONENT_SWIZZLE_R,
1374 .g = VK_COMPONENT_SWIZZLE_G,
1375 .b = VK_COMPONENT_SWIZZLE_B,
1376 .a = VK_COMPONENT_SWIZZLE_A,
1379 {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1380 .viewType = VK_IMAGE_VIEW_TYPE_2D,
1384 demo->swapchain_image_resources[i].image = swapchainImages[i];
1386 color_image_view.image = demo->swapchain_image_resources[i].image;
1388 err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view);
1392 if (demo->VK_GOOGLE_display_timing_enabled) {
1393 VkRefreshCycleDurationGOOGLE rc_dur;
1394 err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
1396 demo->refresh_duration = rc_dur.refreshDuration;
1398 demo->syncd_with_actual_presents = false;
1399 // Initially target 1X the refresh duration:
1400 demo->target_IPD = demo->refresh_duration;
1401 demo->refresh_duration_multiplier = 1;
1402 demo->prev_desired_present_time = 0;
1403 demo->next_present_id = 1;
1406 if (NULL != swapchainImages) {
1407 free(swapchainImages);
1410 if (NULL != presentModes) {
1415 static void demo_prepare_depth(struct demo *demo) {
1416 const VkFormat depth_format = VK_FORMAT_D16_UNORM;
1417 const VkImageCreateInfo image = {
1418 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1420 .imageType = VK_IMAGE_TYPE_2D,
1421 .format = depth_format,
1422 .extent = {demo->width, demo->height, 1},
1425 .samples = VK_SAMPLE_COUNT_1_BIT,
1426 .tiling = VK_IMAGE_TILING_OPTIMAL,
1427 .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
1431 VkImageViewCreateInfo view = {
1432 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1434 .image = VK_NULL_HANDLE,
1435 .format = depth_format,
1437 {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1439 .viewType = VK_IMAGE_VIEW_TYPE_2D,
1442 VkMemoryRequirements mem_reqs;
1443 VkResult U_ASSERT_ONLY err;
1444 bool U_ASSERT_ONLY pass;
1446 demo->depth.format = depth_format;
1449 err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
1452 vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
1455 demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1456 demo->depth.mem_alloc.pNext = NULL;
1457 demo->depth.mem_alloc.allocationSize = mem_reqs.size;
1458 demo->depth.mem_alloc.memoryTypeIndex = 0;
1460 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1461 &demo->depth.mem_alloc.memoryTypeIndex);
1464 /* allocate memory */
1465 err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
1469 err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
1472 /* create image view */
1473 view.image = demo->depth.image;
1474 err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
1478 /* Convert ppm image data from header file into RGBA texture image */
1479 #include "lunarg.ppm.h"
1480 bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
1483 cPtr = (char *)lunarg_ppm;
1484 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
1487 while (strncmp(cPtr++, "\n", 1))
1489 sscanf(cPtr, "%u %u", width, height);
1490 if (rgba_data == NULL) {
1493 while (strncmp(cPtr++, "\n", 1))
1495 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
1498 while (strncmp(cPtr++, "\n", 1))
1500 for (int y = 0; y < *height; y++) {
1501 uint8_t *rowPtr = rgba_data;
1502 for (int x = 0; x < *width; x++) {
1503 memcpy(rowPtr, cPtr, 3);
1504 rowPtr[3] = 255; /* Alpha of 1 */
1508 rgba_data += layout->rowPitch;
1513 static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
1516 VkResult U_ASSERT_ONLY err;
1517 bool U_ASSERT_ONLY pass;
1519 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1520 ERR_EXIT("Failed to load textures", "Load Texture Failure");
1523 tex_obj->tex_width = tex_width;
1524 tex_obj->tex_height = tex_height;
1526 const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1529 .size = tex_width * tex_height * 4,
1530 .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1531 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1532 .queueFamilyIndexCount = 0,
1533 .pQueueFamilyIndices = NULL};
1535 err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
1538 VkMemoryRequirements mem_reqs;
1539 vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
1541 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1542 tex_obj->mem_alloc.pNext = NULL;
1543 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1544 tex_obj->mem_alloc.memoryTypeIndex = 0;
1546 VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1547 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
1550 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1554 err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
1557 VkSubresourceLayout layout;
1558 memset(&layout, 0, sizeof(layout));
1559 layout.rowPitch = tex_width * 4;
1562 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1565 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1566 fprintf(stderr, "Error loading texture: %s\n", filename);
1569 vkUnmapMemory(demo->device, tex_obj->mem);
1572 static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
1573 VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
1574 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1577 VkResult U_ASSERT_ONLY err;
1578 bool U_ASSERT_ONLY pass;
1580 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1581 ERR_EXIT("Failed to load textures", "Load Texture Failure");
1584 tex_obj->tex_width = tex_width;
1585 tex_obj->tex_height = tex_height;
1587 const VkImageCreateInfo image_create_info = {
1588 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1590 .imageType = VK_IMAGE_TYPE_2D,
1591 .format = tex_format,
1592 .extent = {tex_width, tex_height, 1},
1595 .samples = VK_SAMPLE_COUNT_1_BIT,
1599 .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
1602 VkMemoryRequirements mem_reqs;
1604 err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
1607 vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
1609 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1610 tex_obj->mem_alloc.pNext = NULL;
1611 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1612 tex_obj->mem_alloc.memoryTypeIndex = 0;
1614 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
1617 /* allocate memory */
1618 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1622 err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
1625 if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
1626 const VkImageSubresource subres = {
1627 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1631 VkSubresourceLayout layout;
1634 vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
1636 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1639 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1640 fprintf(stderr, "Error loading texture: %s\n", filename);
1643 vkUnmapMemory(demo->device, tex_obj->mem);
1646 tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1649 static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
1650 /* clean up staging resources */
1651 vkFreeMemory(demo->device, tex_objs->mem, NULL);
1652 if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
1653 if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
1656 static void demo_prepare_textures(struct demo *demo) {
1657 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1658 VkFormatProperties props;
1661 vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
1663 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1664 VkResult U_ASSERT_ONLY err;
1666 if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
1667 /* Device can texture using linear textures */
1668 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
1669 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
1670 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
1671 // shader to run until layout transition completes
1672 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1673 demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1674 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1675 demo->staging_texture.image = 0;
1676 } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
1677 /* Must use staging buffer to copy linear texture to optimized */
1679 memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
1680 demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
1682 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
1683 (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1684 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1686 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1687 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1688 VK_PIPELINE_STAGE_TRANSFER_BIT);
1690 VkBufferImageCopy copy_region = {
1692 .bufferRowLength = demo->staging_texture.tex_width,
1693 .bufferImageHeight = demo->staging_texture.tex_height,
1694 .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
1695 .imageOffset = {0, 0, 0},
1696 .imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
1699 vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
1700 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region);
1702 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1703 demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1704 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1707 /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
1708 assert(!"No support for R8G8B8A8_UNORM as texture image format");
1711 const VkSamplerCreateInfo sampler = {
1712 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
1714 .magFilter = VK_FILTER_NEAREST,
1715 .minFilter = VK_FILTER_NEAREST,
1716 .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
1717 .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1718 .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1719 .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1721 .anisotropyEnable = VK_FALSE,
1723 .compareOp = VK_COMPARE_OP_NEVER,
1726 .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
1727 .unnormalizedCoordinates = VK_FALSE,
1730 VkImageViewCreateInfo view = {
1731 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1733 .image = VK_NULL_HANDLE,
1734 .viewType = VK_IMAGE_VIEW_TYPE_2D,
1735 .format = tex_format,
1738 VK_COMPONENT_SWIZZLE_R,
1739 VK_COMPONENT_SWIZZLE_G,
1740 VK_COMPONENT_SWIZZLE_B,
1741 VK_COMPONENT_SWIZZLE_A,
1743 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
1747 /* create sampler */
1748 err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
1751 /* create image view */
1752 view.image = demo->textures[i].image;
1753 err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
1758 void demo_prepare_cube_data_buffers(struct demo *demo) {
1759 VkBufferCreateInfo buf_info;
1760 VkMemoryRequirements mem_reqs;
1761 VkMemoryAllocateInfo mem_alloc;
1764 VkResult U_ASSERT_ONLY err;
1765 bool U_ASSERT_ONLY pass;
1766 struct vktexcube_vs_uniform data;
1768 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
1769 mat4x4_mul(MVP, VP, demo->model_matrix);
1770 memcpy(data.mvp, MVP, sizeof(MVP));
1771 // dumpMatrix("MVP", MVP);
1773 for (unsigned int i = 0; i < 12 * 3; i++) {
1774 data.position[i][0] = g_vertex_buffer_data[i * 3];
1775 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1776 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1777 data.position[i][3] = 1.0f;
1778 data.attr[i][0] = g_uv_buffer_data[2 * i];
1779 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1780 data.attr[i][2] = 0;
1781 data.attr[i][3] = 0;
1784 memset(&buf_info, 0, sizeof(buf_info));
1785 buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1786 buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
1787 buf_info.size = sizeof(data);
1789 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
1790 err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer);
1793 vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1795 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1796 mem_alloc.pNext = NULL;
1797 mem_alloc.allocationSize = mem_reqs.size;
1798 mem_alloc.memoryTypeIndex = 0;
1800 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
1801 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1802 &mem_alloc.memoryTypeIndex);
1805 err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory);
1808 err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0, (void **)&pData);
1811 memcpy(pData, &data, sizeof data);
1813 vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
1815 err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer,
1816 demo->swapchain_image_resources[i].uniform_memory, 0);
1821 static void demo_prepare_descriptor_layout(struct demo *demo) {
1822 const VkDescriptorSetLayoutBinding layout_bindings[2] = {
1826 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1827 .descriptorCount = 1,
1828 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
1829 .pImmutableSamplers = NULL,
1834 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1835 .descriptorCount = DEMO_TEXTURE_COUNT,
1836 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
1837 .pImmutableSamplers = NULL,
1840 const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
1841 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
1844 .pBindings = layout_bindings,
1846 VkResult U_ASSERT_ONLY err;
1848 err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
1851 const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
1852 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1854 .setLayoutCount = 1,
1855 .pSetLayouts = &demo->desc_layout,
1858 err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
1862 static void demo_prepare_render_pass(struct demo *demo) {
1863 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1864 // because at the start of the renderpass, we don't care about their contents.
1865 // At the start of the subpass, the color attachment's layout will be transitioned
1866 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1867 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1868 // the renderpass, the color attachment's layout will be transitioned to
1869 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1870 // the renderpass, no barriers are necessary.
1871 const VkAttachmentDescription attachments[2] = {
1874 .format = demo->format,
1876 .samples = VK_SAMPLE_COUNT_1_BIT,
1877 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1878 .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
1879 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1880 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1881 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1882 .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1886 .format = demo->depth.format,
1888 .samples = VK_SAMPLE_COUNT_1_BIT,
1889 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1890 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1891 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1892 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1893 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1894 .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1897 const VkAttachmentReference color_reference = {
1899 .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1901 const VkAttachmentReference depth_reference = {
1903 .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1905 const VkSubpassDescription subpass = {
1906 .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
1908 .inputAttachmentCount = 0,
1909 .pInputAttachments = NULL,
1910 .colorAttachmentCount = 1,
1911 .pColorAttachments = &color_reference,
1912 .pResolveAttachments = NULL,
1913 .pDepthStencilAttachment = &depth_reference,
1914 .preserveAttachmentCount = 0,
1915 .pPreserveAttachments = NULL,
1918 VkSubpassDependency attachmentDependencies[2] = {
1921 // Depth buffer is shared between swapchain images
1922 .srcSubpass = VK_SUBPASS_EXTERNAL,
1924 .srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1925 .dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1926 .srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1927 .dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1928 .dependencyFlags = 0,
1932 // Image Layout Transition
1933 .srcSubpass = VK_SUBPASS_EXTERNAL,
1935 .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1936 .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1938 .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
1939 .dependencyFlags = 0,
1943 const VkRenderPassCreateInfo rp_info = {
1944 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
1947 .attachmentCount = 2,
1948 .pAttachments = attachments,
1950 .pSubpasses = &subpass,
1951 .dependencyCount = 2,
1952 .pDependencies = attachmentDependencies,
1954 VkResult U_ASSERT_ONLY err;
1956 err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
1960 static VkShaderModule demo_prepare_shader_module(struct demo *demo, const uint32_t *code, size_t size) {
1961 VkShaderModule module;
1962 VkShaderModuleCreateInfo moduleCreateInfo;
1963 VkResult U_ASSERT_ONLY err;
1965 moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1966 moduleCreateInfo.pNext = NULL;
1967 moduleCreateInfo.flags = 0;
1968 moduleCreateInfo.codeSize = size;
1969 moduleCreateInfo.pCode = code;
1971 err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
1977 static void demo_prepare_vs(struct demo *demo) {
1978 const uint32_t vs_code[] = {
1979 #include "cube.vert.inc"
1981 demo->vert_shader_module = demo_prepare_shader_module(demo, vs_code, sizeof(vs_code));
1984 static void demo_prepare_fs(struct demo *demo) {
1985 const uint32_t fs_code[] = {
1986 #include "cube.frag.inc"
1988 demo->frag_shader_module = demo_prepare_shader_module(demo, fs_code, sizeof(fs_code));
1991 static void demo_prepare_pipeline(struct demo *demo) {
1992 VkGraphicsPipelineCreateInfo pipeline;
1993 VkPipelineCacheCreateInfo pipelineCache;
1994 VkPipelineVertexInputStateCreateInfo vi;
1995 VkPipelineInputAssemblyStateCreateInfo ia;
1996 VkPipelineRasterizationStateCreateInfo rs;
1997 VkPipelineColorBlendStateCreateInfo cb;
1998 VkPipelineDepthStencilStateCreateInfo ds;
1999 VkPipelineViewportStateCreateInfo vp;
2000 VkPipelineMultisampleStateCreateInfo ms;
2001 VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
2002 VkPipelineDynamicStateCreateInfo dynamicState;
2003 VkResult U_ASSERT_ONLY err;
2005 memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
2006 memset(&dynamicState, 0, sizeof dynamicState);
2007 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
2008 dynamicState.pDynamicStates = dynamicStateEnables;
2010 memset(&pipeline, 0, sizeof(pipeline));
2011 pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
2012 pipeline.layout = demo->pipeline_layout;
2014 memset(&vi, 0, sizeof(vi));
2015 vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
2017 memset(&ia, 0, sizeof(ia));
2018 ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
2019 ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
2021 memset(&rs, 0, sizeof(rs));
2022 rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
2023 rs.polygonMode = VK_POLYGON_MODE_FILL;
2024 rs.cullMode = VK_CULL_MODE_BACK_BIT;
2025 rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
2026 rs.depthClampEnable = VK_FALSE;
2027 rs.rasterizerDiscardEnable = VK_FALSE;
2028 rs.depthBiasEnable = VK_FALSE;
2029 rs.lineWidth = 1.0f;
2031 memset(&cb, 0, sizeof(cb));
2032 cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
2033 VkPipelineColorBlendAttachmentState att_state[1];
2034 memset(att_state, 0, sizeof(att_state));
2035 att_state[0].colorWriteMask = 0xf;
2036 att_state[0].blendEnable = VK_FALSE;
2037 cb.attachmentCount = 1;
2038 cb.pAttachments = att_state;
2040 memset(&vp, 0, sizeof(vp));
2041 vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
2042 vp.viewportCount = 1;
2043 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
2044 vp.scissorCount = 1;
2045 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
2047 memset(&ds, 0, sizeof(ds));
2048 ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
2049 ds.depthTestEnable = VK_TRUE;
2050 ds.depthWriteEnable = VK_TRUE;
2051 ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
2052 ds.depthBoundsTestEnable = VK_FALSE;
2053 ds.back.failOp = VK_STENCIL_OP_KEEP;
2054 ds.back.passOp = VK_STENCIL_OP_KEEP;
2055 ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
2056 ds.stencilTestEnable = VK_FALSE;
2059 memset(&ms, 0, sizeof(ms));
2060 ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
2061 ms.pSampleMask = NULL;
2062 ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
2064 demo_prepare_vs(demo);
2065 demo_prepare_fs(demo);
2067 // Two stages: vs and fs
2068 VkPipelineShaderStageCreateInfo shaderStages[2];
2069 memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
2071 shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2072 shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
2073 shaderStages[0].module = demo->vert_shader_module;
2074 shaderStages[0].pName = "main";
2076 shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2077 shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
2078 shaderStages[1].module = demo->frag_shader_module;
2079 shaderStages[1].pName = "main";
2081 memset(&pipelineCache, 0, sizeof(pipelineCache));
2082 pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2084 err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
2087 pipeline.pVertexInputState = &vi;
2088 pipeline.pInputAssemblyState = &ia;
2089 pipeline.pRasterizationState = &rs;
2090 pipeline.pColorBlendState = &cb;
2091 pipeline.pMultisampleState = &ms;
2092 pipeline.pViewportState = &vp;
2093 pipeline.pDepthStencilState = &ds;
2094 pipeline.stageCount = ARRAY_SIZE(shaderStages);
2095 pipeline.pStages = shaderStages;
2096 pipeline.renderPass = demo->render_pass;
2097 pipeline.pDynamicState = &dynamicState;
2099 pipeline.renderPass = demo->render_pass;
2101 err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
2104 vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
2105 vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
2108 static void demo_prepare_descriptor_pool(struct demo *demo) {
2109 const VkDescriptorPoolSize type_counts[2] = {
2112 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
2113 .descriptorCount = demo->swapchainImageCount,
2117 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2118 .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT,
2121 const VkDescriptorPoolCreateInfo descriptor_pool = {
2122 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
2124 .maxSets = demo->swapchainImageCount,
2126 .pPoolSizes = type_counts,
2128 VkResult U_ASSERT_ONLY err;
2130 err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
2134 static void demo_prepare_descriptor_set(struct demo *demo) {
2135 VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
2136 VkWriteDescriptorSet writes[2];
2137 VkResult U_ASSERT_ONLY err;
2139 VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
2141 .descriptorPool = demo->desc_pool,
2142 .descriptorSetCount = 1,
2143 .pSetLayouts = &demo->desc_layout};
2145 VkDescriptorBufferInfo buffer_info;
2146 buffer_info.offset = 0;
2147 buffer_info.range = sizeof(struct vktexcube_vs_uniform);
2149 memset(&tex_descs, 0, sizeof(tex_descs));
2150 for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2151 tex_descs[i].sampler = demo->textures[i].sampler;
2152 tex_descs[i].imageView = demo->textures[i].view;
2153 tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
2156 memset(&writes, 0, sizeof(writes));
2158 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2159 writes[0].descriptorCount = 1;
2160 writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
2161 writes[0].pBufferInfo = &buffer_info;
2163 writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2164 writes[1].dstBinding = 1;
2165 writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
2166 writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
2167 writes[1].pImageInfo = tex_descs;
2169 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
2170 err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->swapchain_image_resources[i].descriptor_set);
2172 buffer_info.buffer = demo->swapchain_image_resources[i].uniform_buffer;
2173 writes[0].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2174 writes[1].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2175 vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
2179 static void demo_prepare_framebuffers(struct demo *demo) {
2180 VkImageView attachments[2];
2181 attachments[1] = demo->depth.view;
2183 const VkFramebufferCreateInfo fb_info = {
2184 .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
2186 .renderPass = demo->render_pass,
2187 .attachmentCount = 2,
2188 .pAttachments = attachments,
2189 .width = demo->width,
2190 .height = demo->height,
2193 VkResult U_ASSERT_ONLY err;
2196 for (i = 0; i < demo->swapchainImageCount; i++) {
2197 attachments[0] = demo->swapchain_image_resources[i].view;
2198 err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer);
2203 static void demo_prepare(struct demo *demo) {
2204 VkResult U_ASSERT_ONLY err;
2205 if (demo->cmd_pool == VK_NULL_HANDLE) {
2206 const VkCommandPoolCreateInfo cmd_pool_info = {
2207 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2209 .queueFamilyIndex = demo->graphics_queue_family_index,
2212 err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
2216 const VkCommandBufferAllocateInfo cmd = {
2217 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2219 .commandPool = demo->cmd_pool,
2220 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2221 .commandBufferCount = 1,
2223 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
2225 VkCommandBufferBeginInfo cmd_buf_info = {
2226 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2229 .pInheritanceInfo = NULL,
2231 err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
2234 demo_prepare_buffers(demo);
2236 if (demo->is_minimized) {
2237 demo->prepared = false;
2241 demo_prepare_depth(demo);
2242 demo_prepare_textures(demo);
2243 demo_prepare_cube_data_buffers(demo);
2245 demo_prepare_descriptor_layout(demo);
2246 demo_prepare_render_pass(demo);
2247 demo_prepare_pipeline(demo);
2249 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2250 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd);
2254 if (demo->separate_present_queue) {
2255 const VkCommandPoolCreateInfo present_cmd_pool_info = {
2256 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2258 .queueFamilyIndex = demo->present_queue_family_index,
2261 err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
2263 const VkCommandBufferAllocateInfo present_cmd_info = {
2264 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2266 .commandPool = demo->present_cmd_pool,
2267 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2268 .commandBufferCount = 1,
2270 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2271 err = vkAllocateCommandBuffers(demo->device, &present_cmd_info,
2272 &demo->swapchain_image_resources[i].graphics_to_present_cmd);
2274 demo_build_image_ownership_cmd(demo, i);
2278 demo_prepare_descriptor_pool(demo);
2279 demo_prepare_descriptor_set(demo);
2281 demo_prepare_framebuffers(demo);
2283 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2284 demo->current_buffer = i;
2285 demo_draw_build_cmd(demo, demo->swapchain_image_resources[i].cmd);
2289 * Prepare functions above may generate pipeline commands
2290 * that need to be flushed before beginning the render loop.
2292 demo_flush_init_cmd(demo);
2293 if (demo->staging_texture.buffer) {
2294 demo_destroy_texture(demo, &demo->staging_texture);
2297 demo->current_buffer = 0;
2298 demo->prepared = true;
2301 static void demo_cleanup(struct demo *demo) {
2304 demo->prepared = false;
2305 vkDeviceWaitIdle(demo->device);
2307 // Wait for fences from present operations
2308 for (i = 0; i < FRAME_LAG; i++) {
2309 vkWaitForFences(demo->device, 1, &demo->fences[i], VK_TRUE, UINT64_MAX);
2310 vkDestroyFence(demo->device, demo->fences[i], NULL);
2311 vkDestroySemaphore(demo->device, demo->image_acquired_semaphores[i], NULL);
2312 vkDestroySemaphore(demo->device, demo->draw_complete_semaphores[i], NULL);
2313 if (demo->separate_present_queue) {
2314 vkDestroySemaphore(demo->device, demo->image_ownership_semaphores[i], NULL);
2318 // If the window is currently minimized, demo_resize has already done some cleanup for us.
2319 if (!demo->is_minimized) {
2320 for (i = 0; i < demo->swapchainImageCount; i++) {
2321 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2323 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2325 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2326 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2327 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2328 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2329 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2331 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2332 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2333 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2334 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2335 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2337 demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
2339 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2340 vkDestroyImage(demo->device, demo->depth.image, NULL);
2341 vkFreeMemory(demo->device, demo->depth.mem, NULL);
2343 for (i = 0; i < demo->swapchainImageCount; i++) {
2344 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2345 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2346 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2347 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2349 free(demo->swapchain_image_resources);
2350 free(demo->queue_props);
2351 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2353 if (demo->separate_present_queue) {
2354 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2357 vkDeviceWaitIdle(demo->device);
2358 vkDestroyDevice(demo->device, NULL);
2359 if (demo->validate) {
2360 demo->DestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
2362 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
2364 #if defined(VK_USE_PLATFORM_XLIB_KHR)
2365 XDestroyWindow(demo->display, demo->xlib_window);
2366 XCloseDisplay(demo->display);
2367 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2368 xcb_destroy_window(demo->connection, demo->xcb_window);
2369 xcb_disconnect(demo->connection);
2370 free(demo->atom_wm_delete_window);
2371 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2372 wl_keyboard_destroy(demo->keyboard);
2373 wl_pointer_destroy(demo->pointer);
2374 wl_seat_destroy(demo->seat);
2375 xdg_toplevel_destroy(demo->xdg_toplevel);
2376 xdg_surface_destroy(demo->xdg_surface);
2377 wl_surface_destroy(demo->window);
2378 xdg_wm_base_destroy(demo->xdg_wm_base);
2379 if (demo->xdg_decoration_mgr) {
2380 zxdg_toplevel_decoration_v1_destroy(demo->toplevel_decoration);
2381 zxdg_decoration_manager_v1_destroy(demo->xdg_decoration_mgr);
2383 wl_compositor_destroy(demo->compositor);
2384 wl_registry_destroy(demo->registry);
2385 wl_display_disconnect(demo->display);
2388 vkDestroyInstance(demo->inst, NULL);
2391 static void demo_resize(struct demo *demo) {
2394 // Don't react to resize until after first initialization.
2395 if (!demo->prepared) {
2396 if (demo->is_minimized) {
2401 // In order to properly resize the window, we must re-create the swapchain
2402 // AND redo the command buffers, etc.
2404 // First, perform part of the demo_cleanup() function:
2405 demo->prepared = false;
2406 vkDeviceWaitIdle(demo->device);
2408 for (i = 0; i < demo->swapchainImageCount; i++) {
2409 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2411 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2413 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2414 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2415 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2416 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2417 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2419 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2420 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2421 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2422 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2423 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2426 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2427 vkDestroyImage(demo->device, demo->depth.image, NULL);
2428 vkFreeMemory(demo->device, demo->depth.mem, NULL);
2430 for (i = 0; i < demo->swapchainImageCount; i++) {
2431 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2432 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2433 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2434 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2436 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2437 demo->cmd_pool = VK_NULL_HANDLE;
2438 if (demo->separate_present_queue) {
2439 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2441 free(demo->swapchain_image_resources);
2443 // Second, re-perform the demo_prepare() function, which will re-create the
2448 // On MS-Windows, make this a global, so it's available to WndProc()
2451 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2452 static void demo_run(struct demo *demo) {
2453 if (!demo->prepared) return;
2457 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2458 PostQuitMessage(validation_error);
2462 // MS-Windows event handling function:
2463 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2466 PostQuitMessage(validation_error);
2469 // The validation callback calls MessageBox which can generate paint
2470 // events - don't make more Vulkan calls if we got here from the
2476 case WM_GETMINMAXINFO: // set window's minimum size
2477 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2482 // Resize the application to the new window size, except when
2483 // it was minimized. Vulkan doesn't support images or swapchains
2484 // with width=0 and height=0.
2485 if (wParam != SIZE_MINIMIZED) {
2486 demo.width = lParam & 0xffff;
2487 demo.height = (lParam & 0xffff0000) >> 16;
2494 PostQuitMessage(validation_error);
2497 demo.spin_angle -= demo.spin_increment;
2500 demo.spin_angle += demo.spin_increment;
2503 demo.pause = !demo.pause;
2510 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2513 static void demo_create_window(struct demo *demo) {
2514 WNDCLASSEX win_class;
2516 // Initialize the window class structure:
2517 win_class.cbSize = sizeof(WNDCLASSEX);
2518 win_class.style = CS_HREDRAW | CS_VREDRAW;
2519 win_class.lpfnWndProc = WndProc;
2520 win_class.cbClsExtra = 0;
2521 win_class.cbWndExtra = 0;
2522 win_class.hInstance = demo->connection; // hInstance
2523 win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2524 win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
2525 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2526 win_class.lpszMenuName = NULL;
2527 win_class.lpszClassName = demo->name;
2528 win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
2529 // Register window class:
2530 if (!RegisterClassEx(&win_class)) {
2531 // It didn't work, so try to give a useful error:
2532 printf("Unexpected error trying to start the application!\n");
2536 // Create window with the registered class:
2537 RECT wr = {0, 0, demo->width, demo->height};
2538 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2539 demo->window = CreateWindowEx(0,
2540 demo->name, // class name
2541 demo->name, // app name
2542 WS_OVERLAPPEDWINDOW | // window style
2543 WS_VISIBLE | WS_SYSMENU,
2544 100, 100, // x/y coords
2545 wr.right - wr.left, // width
2546 wr.bottom - wr.top, // height
2547 NULL, // handle to parent
2548 NULL, // handle to menu
2549 demo->connection, // hInstance
2550 NULL); // no extra parameters
2551 if (!demo->window) {
2552 // It didn't work, so try to give a useful error:
2553 printf("Cannot create a window in which to draw!\n");
2557 // Window client area size must be at least 1 pixel high, to prevent crash.
2558 demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2559 demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2561 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2562 static void demo_create_xlib_window(struct demo *demo) {
2563 const char *display_envar = getenv("DISPLAY");
2564 if (display_envar == NULL || display_envar[0] == '\0') {
2565 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2571 demo->display = XOpenDisplay(NULL);
2572 long visualMask = VisualScreenMask;
2573 int numberOfVisuals;
2574 XVisualInfo vInfoTemplate = {};
2575 vInfoTemplate.screen = DefaultScreen(demo->display);
2576 XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals);
2579 XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2581 XSetWindowAttributes windowAttributes = {};
2582 windowAttributes.colormap = colormap;
2583 windowAttributes.background_pixel = 0xFFFFFFFF;
2584 windowAttributes.border_pixel = 0;
2585 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2587 demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width,
2588 demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
2589 CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2591 XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
2592 XMapWindow(demo->display, demo->xlib_window);
2593 XFlush(demo->display);
2594 demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
2596 static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
2597 switch (event->type) {
2599 if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
2602 switch (event->xkey.keycode) {
2606 case 0x71: // left arrow key
2607 demo->spin_angle -= demo->spin_increment;
2609 case 0x72: // right arrow key
2610 demo->spin_angle += demo->spin_increment;
2612 case 0x41: // space bar
2613 demo->pause = !demo->pause;
2617 case ConfigureNotify:
2618 if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
2619 demo->width = event->xconfigure.width;
2620 demo->height = event->xconfigure.height;
2629 static void demo_run_xlib(struct demo *demo) {
2630 while (!demo->quit) {
2634 XNextEvent(demo->display, &event);
2635 demo_handle_xlib_event(demo, &event);
2637 while (XPending(demo->display) > 0) {
2638 XNextEvent(demo->display, &event);
2639 demo_handle_xlib_event(demo, &event);
2644 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2647 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2648 static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
2649 uint8_t event_code = event->response_type & 0x7f;
2650 switch (event_code) {
2652 // TODO: Resize window
2654 case XCB_CLIENT_MESSAGE:
2655 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
2659 case XCB_KEY_RELEASE: {
2660 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2662 switch (key->detail) {
2666 case 0x71: // left arrow key
2667 demo->spin_angle -= demo->spin_increment;
2669 case 0x72: // right arrow key
2670 demo->spin_angle += demo->spin_increment;
2672 case 0x41: // space bar
2673 demo->pause = !demo->pause;
2677 case XCB_CONFIGURE_NOTIFY: {
2678 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2679 if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
2680 demo->width = cfg->width;
2681 demo->height = cfg->height;
2690 static void demo_run_xcb(struct demo *demo) {
2691 xcb_flush(demo->connection);
2693 while (!demo->quit) {
2694 xcb_generic_event_t *event;
2697 event = xcb_wait_for_event(demo->connection);
2699 event = xcb_poll_for_event(demo->connection);
2702 demo_handle_xcb_event(demo, event);
2704 event = xcb_poll_for_event(demo->connection);
2709 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2713 static void demo_create_xcb_window(struct demo *demo) {
2714 uint32_t value_mask, value_list[32];
2716 demo->xcb_window = xcb_generate_id(demo->connection);
2718 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2719 value_list[0] = demo->screen->black_pixel;
2720 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2722 xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
2723 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
2725 /* Magic code that will send notification when window is destroyed */
2726 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
2727 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
2729 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
2730 demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
2732 xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
2733 &(*demo->atom_wm_delete_window).atom);
2736 xcb_map_window(demo->connection, demo->xcb_window);
2738 // Force the x/y coordinates to 100,100 results are identical in consecutive
2740 const uint32_t coords[] = {100, 100};
2741 xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2743 // VK_USE_PLATFORM_XCB_KHR
2744 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2745 static void demo_run(struct demo *demo) {
2746 while (!demo->quit) {
2748 wl_display_dispatch(demo->display); // block and wait for input
2750 wl_display_dispatch_pending(demo->display); // don't block
2753 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2758 static void handle_surface_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {
2759 struct demo *demo = (struct demo *)data;
2760 xdg_surface_ack_configure(xdg_surface, serial);
2761 if (demo->xdg_surface_has_been_configured) {
2764 demo->xdg_surface_has_been_configured = 1;
2767 static const struct xdg_surface_listener xdg_surface_listener = {handle_surface_configure};
2769 static void handle_toplevel_configure(void *data, struct xdg_toplevel *xdg_toplevel UNUSED, int32_t width, int32_t height,
2770 struct wl_array *states UNUSED) {
2771 struct demo *demo = (struct demo *)data;
2772 demo->width = width;
2773 demo->height = height;
2774 /* This should be followed by a surface configure */
2777 static void handle_toplevel_close(void *data, struct xdg_toplevel *xdg_toplevel UNUSED) {
2778 struct demo *demo = (struct demo *)data;
2782 static const struct xdg_toplevel_listener xdg_toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2784 static void demo_create_window(struct demo *demo) {
2785 if (!demo->xdg_wm_base) {
2786 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2791 demo->window = wl_compositor_create_surface(demo->compositor);
2792 if (!demo->window) {
2793 printf("Can not create wayland_surface from compositor!\n");
2798 demo->xdg_surface = xdg_wm_base_get_xdg_surface(demo->xdg_wm_base, demo->window);
2799 if (!demo->xdg_surface) {
2800 printf("Can not get xdg_surface from wayland_surface!\n");
2804 demo->xdg_toplevel = xdg_surface_get_toplevel(demo->xdg_surface);
2805 if (!demo->xdg_toplevel) {
2806 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2810 xdg_surface_add_listener(demo->xdg_surface, &xdg_surface_listener, demo);
2811 xdg_toplevel_add_listener(demo->xdg_toplevel, &xdg_toplevel_listener, demo);
2812 xdg_toplevel_set_title(demo->xdg_toplevel, APP_SHORT_NAME);
2813 if (demo->xdg_decoration_mgr) {
2814 // if supported, let the compositor render titlebars for us
2815 demo->toplevel_decoration =
2816 zxdg_decoration_manager_v1_get_toplevel_decoration(demo->xdg_decoration_mgr, demo->xdg_toplevel);
2817 zxdg_toplevel_decoration_v1_set_mode(demo->toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2820 wl_surface_commit(demo->window);
2822 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
2823 static void demo_run(struct demo *demo) {
2824 if (!demo->prepared) return;
2829 #elif defined(VK_USE_PLATFORM_METAL_EXT)
2830 static void demo_run(struct demo *demo) {
2833 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2837 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2838 static VkResult demo_create_display_surface(struct demo *demo) {
2839 VkResult U_ASSERT_ONLY err;
2840 uint32_t display_count;
2841 uint32_t mode_count;
2842 uint32_t plane_count;
2843 VkDisplayPropertiesKHR display_props;
2844 VkDisplayKHR display;
2845 VkDisplayModePropertiesKHR mode_props;
2846 VkDisplayPlanePropertiesKHR *plane_props;
2847 VkBool32 found_plane = VK_FALSE;
2848 uint32_t plane_index;
2849 VkExtent2D image_extent;
2850 VkDisplaySurfaceCreateInfoKHR create_info;
2852 // Get the first display
2853 err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, NULL);
2856 if (display_count == 0) {
2857 printf("Cannot find any display!\n");
2863 err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
2864 assert(!err || (err == VK_INCOMPLETE));
2866 display = display_props.display;
2868 // Get the first mode of the display
2869 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
2872 if (mode_count == 0) {
2873 printf("Cannot find any mode for the display!\n");
2879 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
2880 assert(!err || (err == VK_INCOMPLETE));
2882 // Get the list of planes
2883 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
2886 if (plane_count == 0) {
2887 printf("Cannot find any plane!\n");
2892 plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
2893 assert(plane_props);
2895 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
2898 // Find a plane compatible with the display
2899 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2900 uint32_t supported_count;
2901 VkDisplayKHR *supported_displays;
2903 // Disqualify planes that are bound to a different display
2904 if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
2908 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
2911 if (supported_count == 0) {
2915 supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
2916 assert(supported_displays);
2918 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
2921 for (uint32_t i = 0; i < supported_count; i++) {
2922 if (supported_displays[i] == display) {
2923 found_plane = VK_TRUE;
2928 free(supported_displays);
2936 printf("Cannot find a plane compatible with the display!\n");
2943 VkDisplayPlaneCapabilitiesKHR planeCaps;
2944 vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
2945 // Find a supported alpha mode
2946 VkCompositeAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
2947 VkCompositeAlphaFlagBitsKHR alphaModes[4] = {
2948 VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
2949 VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
2950 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
2951 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
2953 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2954 if (planeCaps.supportedAlpha & alphaModes[i]) {
2955 alphaMode = alphaModes[i];
2959 image_extent.width = mode_props.parameters.visibleRegion.width;
2960 image_extent.height = mode_props.parameters.visibleRegion.height;
2962 create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
2963 create_info.pNext = NULL;
2964 create_info.flags = 0;
2965 create_info.displayMode = mode_props.displayMode;
2966 create_info.planeIndex = plane_index;
2967 create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
2968 create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
2969 create_info.alphaMode = alphaMode;
2970 create_info.globalAlpha = 1.0f;
2971 create_info.imageExtent = image_extent;
2973 return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
2976 static void demo_run_display(struct demo *demo) {
2977 while (!demo->quit) {
2981 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2989 * Return 1 (true) if all layer names specified in check_names
2990 * can be found in given layer properties.
2992 static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
2993 for (uint32_t i = 0; i < check_count; i++) {
2995 for (uint32_t j = 0; j < layer_count; j++) {
2996 if (!strcmp(check_names[i], layers[j].layerName)) {
3002 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
3009 static void demo_init_vk(struct demo *demo) {
3011 uint32_t instance_extension_count = 0;
3012 uint32_t instance_layer_count = 0;
3013 char *instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
3014 demo->enabled_extension_count = 0;
3015 demo->enabled_layer_count = 0;
3016 demo->is_minimized = false;
3017 demo->cmd_pool = VK_NULL_HANDLE;
3019 // Look for validation layers
3020 VkBool32 validation_found = 0;
3021 if (demo->validate) {
3022 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
3025 if (instance_layer_count > 0) {
3026 VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
3027 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
3030 validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
3031 instance_layer_count, instance_layers);
3032 if (validation_found) {
3033 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
3034 demo->enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
3036 free(instance_layers);
3039 if (!validation_found) {
3041 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
3042 "Please look at the Getting Started guide for additional information.\n",
3043 "vkCreateInstance Failure");
3047 /* Look for instance extensions */
3048 VkBool32 surfaceExtFound = 0;
3049 VkBool32 platformSurfaceExtFound = 0;
3050 memset(demo->extension_names, 0, sizeof(demo->extension_names));
3052 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
3055 if (instance_extension_count > 0) {
3056 VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
3057 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
3059 for (uint32_t i = 0; i < instance_extension_count; i++) {
3060 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3061 surfaceExtFound = 1;
3062 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
3064 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3065 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3066 platformSurfaceExtFound = 1;
3067 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
3069 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3070 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3071 platformSurfaceExtFound = 1;
3072 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
3074 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3075 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3076 platformSurfaceExtFound = 1;
3077 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
3079 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3080 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3081 platformSurfaceExtFound = 1;
3082 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
3084 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3085 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3086 platformSurfaceExtFound = 1;
3087 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
3089 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3090 if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3091 platformSurfaceExtFound = 1;
3092 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
3094 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3095 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3096 platformSurfaceExtFound = 1;
3097 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
3100 if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3101 if (demo->validate) {
3102 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
3105 assert(demo->enabled_extension_count < 64);
3108 free(instance_extensions);
3111 if (!surfaceExtFound) {
3112 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
3114 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3115 "Please look at the Getting Started guide for additional information.\n",
3116 "vkCreateInstance Failure");
3118 if (!platformSurfaceExtFound) {
3119 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3120 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
3122 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3123 "Please look at the Getting Started guide for additional information.\n",
3124 "vkCreateInstance Failure");
3125 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3126 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
3128 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3129 "Please look at the Getting Started guide for additional information.\n",
3130 "vkCreateInstance Failure");
3131 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3132 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
3134 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3135 "Please look at the Getting Started guide for additional information.\n",
3136 "vkCreateInstance Failure");
3137 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
3140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3141 "Please look at the Getting Started guide for additional information.\n",
3142 "vkCreateInstance Failure");
3143 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
3146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3147 "Please look at the Getting Started guide for additional information.\n",
3148 "vkCreateInstance Failure");
3149 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
3152 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3153 "Please look at the Getting Started guide for additional information.\n",
3154 "vkCreateInstance Failure");
3155 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3156 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
3158 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3159 "Please look at the Getting Started guide for additional information.\n",
3160 "vkCreateInstance Failure");
3163 const VkApplicationInfo app = {
3164 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
3166 .pApplicationName = APP_SHORT_NAME,
3167 .applicationVersion = 0,
3168 .pEngineName = APP_SHORT_NAME,
3170 .apiVersion = VK_API_VERSION_1_0,
3172 VkInstanceCreateInfo inst_info = {
3173 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
3175 .pApplicationInfo = &app,
3176 .enabledLayerCount = demo->enabled_layer_count,
3177 .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
3178 .enabledExtensionCount = demo->enabled_extension_count,
3179 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3183 * This is info for a temp callback to use during CreateInstance.
3184 * After the instance is created, we use the instance-based
3185 * function to register the final callback.
3187 VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
3188 if (demo->validate) {
3189 // VK_EXT_debug_utils style
3190 dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
3191 dbg_messenger_create_info.pNext = NULL;
3192 dbg_messenger_create_info.flags = 0;
3193 dbg_messenger_create_info.messageSeverity =
3194 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
3195 dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
3196 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
3197 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
3198 dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
3199 dbg_messenger_create_info.pUserData = demo;
3200 inst_info.pNext = &dbg_messenger_create_info;
3205 err = vkCreateInstance(&inst_info, NULL, &demo->inst);
3206 if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
3208 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
3209 "Please look at the Getting Started guide for additional information.\n",
3210 "vkCreateInstance Failure");
3211 } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
3213 "Cannot find a specified extension library.\n"
3214 "Make sure your layers path is set appropriately.\n",
3215 "vkCreateInstance Failure");
3218 "vkCreateInstance failed.\n\n"
3219 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3220 "Please look at the Getting Started guide for additional information.\n",
3221 "vkCreateInstance Failure");
3224 /* Make initial call to query gpu_count, then second call for gpu info*/
3225 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
3228 if (gpu_count > 0) {
3229 VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
3230 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
3232 /* For cube demo we just grab the first physical device */
3233 demo->gpu = physical_devices[0];
3234 free(physical_devices);
3237 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
3238 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3239 "Please look at the Getting Started guide for additional information.\n",
3240 "vkEnumeratePhysicalDevices Failure");
3243 /* Look for device extensions */
3244 uint32_t device_extension_count = 0;
3245 VkBool32 swapchainExtFound = 0;
3246 demo->enabled_extension_count = 0;
3247 memset(demo->extension_names, 0, sizeof(demo->extension_names));
3249 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
3252 if (device_extension_count > 0) {
3253 VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
3254 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
3257 for (uint32_t i = 0; i < device_extension_count; i++) {
3258 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
3259 swapchainExtFound = 1;
3260 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
3262 assert(demo->enabled_extension_count < 64);
3265 if (demo->VK_KHR_incremental_present_enabled) {
3266 // Even though the user "enabled" the extension via the command
3267 // line, we must make sure that it's enumerated for use with the
3268 // device. Therefore, disable it here, and re-enable it again if
3270 demo->VK_KHR_incremental_present_enabled = false;
3271 for (uint32_t i = 0; i < device_extension_count; i++) {
3272 if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
3273 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
3274 demo->VK_KHR_incremental_present_enabled = true;
3275 DbgMsg("VK_KHR_incremental_present extension enabled\n");
3277 assert(demo->enabled_extension_count < 64);
3279 if (!demo->VK_KHR_incremental_present_enabled) {
3280 DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
3284 if (demo->VK_GOOGLE_display_timing_enabled) {
3285 // Even though the user "enabled" the extension via the command
3286 // line, we must make sure that it's enumerated for use with the
3287 // device. Therefore, disable it here, and re-enable it again if
3289 demo->VK_GOOGLE_display_timing_enabled = false;
3290 for (uint32_t i = 0; i < device_extension_count; i++) {
3291 if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
3292 demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
3293 demo->VK_GOOGLE_display_timing_enabled = true;
3294 DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
3296 assert(demo->enabled_extension_count < 64);
3298 if (!demo->VK_GOOGLE_display_timing_enabled) {
3299 DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
3303 free(device_extensions);
3306 if (!swapchainExtFound) {
3307 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
3308 " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
3309 "Please look at the Getting Started guide for additional information.\n",
3310 "vkCreateInstance Failure");
3313 if (demo->validate) {
3314 // Setup VK_EXT_debug_utils function pointers always (we use them for
3315 // debug labels and names).
3316 demo->CreateDebugUtilsMessengerEXT =
3317 (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugUtilsMessengerEXT");
3318 demo->DestroyDebugUtilsMessengerEXT =
3319 (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugUtilsMessengerEXT");
3320 demo->SubmitDebugUtilsMessageEXT =
3321 (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkSubmitDebugUtilsMessageEXT");
3322 demo->CmdBeginDebugUtilsLabelEXT =
3323 (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdBeginDebugUtilsLabelEXT");
3324 demo->CmdEndDebugUtilsLabelEXT =
3325 (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdEndDebugUtilsLabelEXT");
3326 demo->CmdInsertDebugUtilsLabelEXT =
3327 (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdInsertDebugUtilsLabelEXT");
3328 demo->SetDebugUtilsObjectNameEXT =
3329 (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(demo->inst, "vkSetDebugUtilsObjectNameEXT");
3330 if (NULL == demo->CreateDebugUtilsMessengerEXT || NULL == demo->DestroyDebugUtilsMessengerEXT ||
3331 NULL == demo->SubmitDebugUtilsMessageEXT || NULL == demo->CmdBeginDebugUtilsLabelEXT ||
3332 NULL == demo->CmdEndDebugUtilsLabelEXT || NULL == demo->CmdInsertDebugUtilsLabelEXT ||
3333 NULL == demo->SetDebugUtilsObjectNameEXT) {
3334 ERR_EXIT("GetProcAddr: Failed to init VK_EXT_debug_utils\n", "GetProcAddr: Failure");
3337 err = demo->CreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
3341 case VK_ERROR_OUT_OF_HOST_MEMORY:
3342 ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
3345 ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
3349 vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
3351 /* Call with NULL data to get count */
3352 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
3353 assert(demo->queue_family_count >= 1);
3355 demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
3356 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
3358 // Query fine-grained feature support for this device.
3359 // If app has specific feature requirements it should check supported
3360 // features based on this query
3361 VkPhysicalDeviceFeatures physDevFeatures;
3362 vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
3364 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
3365 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
3366 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
3367 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
3368 GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
3371 static void demo_create_device(struct demo *demo) {
3372 VkResult U_ASSERT_ONLY err;
3373 float queue_priorities[1] = {0.0};
3374 VkDeviceQueueCreateInfo queues[2];
3375 queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3376 queues[0].pNext = NULL;
3377 queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
3378 queues[0].queueCount = 1;
3379 queues[0].pQueuePriorities = queue_priorities;
3380 queues[0].flags = 0;
3382 VkDeviceCreateInfo device = {
3383 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
3385 .queueCreateInfoCount = 1,
3386 .pQueueCreateInfos = queues,
3387 .enabledLayerCount = 0,
3388 .ppEnabledLayerNames = NULL,
3389 .enabledExtensionCount = demo->enabled_extension_count,
3390 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3391 .pEnabledFeatures = NULL, // If specific features are required, pass them in here
3393 if (demo->separate_present_queue) {
3394 queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3395 queues[1].pNext = NULL;
3396 queues[1].queueFamilyIndex = demo->present_queue_family_index;
3397 queues[1].queueCount = 1;
3398 queues[1].pQueuePriorities = queue_priorities;
3399 queues[1].flags = 0;
3400 device.queueCreateInfoCount = 2;
3402 err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
3406 static void demo_create_surface(struct demo *demo) {
3407 VkResult U_ASSERT_ONLY err;
3409 // Create a WSI surface for the window:
3410 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3411 VkWin32SurfaceCreateInfoKHR createInfo;
3412 createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
3413 createInfo.pNext = NULL;
3414 createInfo.flags = 0;
3415 createInfo.hinstance = demo->connection;
3416 createInfo.hwnd = demo->window;
3418 err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3419 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3420 VkWaylandSurfaceCreateInfoKHR createInfo;
3421 createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
3422 createInfo.pNext = NULL;
3423 createInfo.flags = 0;
3424 createInfo.display = demo->display;
3425 createInfo.surface = demo->window;
3427 err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3428 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3429 VkAndroidSurfaceCreateInfoKHR createInfo;
3430 createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
3431 createInfo.pNext = NULL;
3432 createInfo.flags = 0;
3433 createInfo.window = (struct ANativeWindow *)(demo->window);
3435 err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3436 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3437 VkXlibSurfaceCreateInfoKHR createInfo;
3438 createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
3439 createInfo.pNext = NULL;
3440 createInfo.flags = 0;
3441 createInfo.dpy = demo->display;
3442 createInfo.window = demo->xlib_window;
3444 err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3445 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3446 VkXcbSurfaceCreateInfoKHR createInfo;
3447 createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
3448 createInfo.pNext = NULL;
3449 createInfo.flags = 0;
3450 createInfo.connection = demo->connection;
3451 createInfo.window = demo->xcb_window;
3453 err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3454 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3455 err = demo_create_display_surface(demo);
3456 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3457 VkMetalSurfaceCreateInfoEXT surface;
3458 surface.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
3459 surface.pNext = NULL;
3461 surface.pLayer = demo->caMetalLayer;
3463 err = vkCreateMetalSurfaceEXT(demo->inst, &surface, NULL, &demo->surface);
3468 static void demo_init_vk_swapchain(struct demo *demo) {
3469 VkResult U_ASSERT_ONLY err;
3471 demo_create_surface(demo);
3473 // Iterate over each queue to learn whether it supports presenting:
3474 VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
3475 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3476 demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
3479 // Search for a graphics and a present queue in the array of queue
3480 // families, try to find one that supports both
3481 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
3482 uint32_t presentQueueFamilyIndex = UINT32_MAX;
3483 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3484 if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
3485 if (graphicsQueueFamilyIndex == UINT32_MAX) {
3486 graphicsQueueFamilyIndex = i;
3489 if (supportsPresent[i] == VK_TRUE) {
3490 graphicsQueueFamilyIndex = i;
3491 presentQueueFamilyIndex = i;
3497 if (presentQueueFamilyIndex == UINT32_MAX) {
3498 // If didn't find a queue that supports both graphics and present, then
3499 // find a separate present queue.
3500 for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
3501 if (supportsPresent[i] == VK_TRUE) {
3502 presentQueueFamilyIndex = i;
3508 // Generate error if could not find both a graphics and a present queue
3509 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
3510 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
3513 demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
3514 demo->present_queue_family_index = presentQueueFamilyIndex;
3515 demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
3516 free(supportsPresent);
3518 demo_create_device(demo);
3520 GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
3521 GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
3522 GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
3523 GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
3524 GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
3525 if (demo->VK_GOOGLE_display_timing_enabled) {
3526 GET_DEVICE_PROC_ADDR(demo->device, GetRefreshCycleDurationGOOGLE);
3527 GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE);
3530 vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
3532 if (!demo->separate_present_queue) {
3533 demo->present_queue = demo->graphics_queue;
3535 vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
3538 // Get the list of VkFormat's that are supported:
3539 uint32_t formatCount;
3540 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
3542 VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
3543 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
3545 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
3546 // the surface has no preferred format. Otherwise, at least one
3547 // supported format will be returned.
3548 if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
3549 demo->format = VK_FORMAT_B8G8R8A8_UNORM;
3551 assert(formatCount >= 1);
3552 demo->format = surfFormats[0].format;
3554 demo->color_space = surfFormats[0].colorSpace;
3560 // Create semaphores to synchronize acquiring presentable buffers before
3561 // rendering and waiting for drawing to be complete before presenting
3562 VkSemaphoreCreateInfo semaphoreCreateInfo = {
3563 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
3568 // Create fences that we can use to throttle if we get too far
3569 // ahead of the image presents
3570 VkFenceCreateInfo fence_ci = {
3571 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
3572 for (uint32_t i = 0; i < FRAME_LAG; i++) {
3573 err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]);
3576 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]);
3579 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]);
3582 if (demo->separate_present_queue) {
3583 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]);
3587 demo->frame_index = 0;
3589 // Get Memory information and properties
3590 vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
3593 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
3594 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
3597 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
3599 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
3601 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
3603 struct demo *demo = data;
3604 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
3605 xdg_toplevel_move(demo->xdg_toplevel, demo->seat, serial);
3609 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
3611 static const struct wl_pointer_listener pointer_listener = {
3612 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
3615 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
3617 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
3618 struct wl_array *keys) {}
3620 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
3622 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
3624 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
3625 struct demo *demo = data;
3627 case KEY_ESC: // Escape
3630 case KEY_LEFT: // left arrow key
3631 demo->spin_angle -= demo->spin_increment;
3633 case KEY_RIGHT: // right arrow key
3634 demo->spin_angle += demo->spin_increment;
3636 case KEY_SPACE: // space bar
3637 demo->pause = !demo->pause;
3642 static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
3643 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
3645 static const struct wl_keyboard_listener keyboard_listener = {
3646 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
3649 static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
3650 // Subscribe to pointer events
3651 struct demo *demo = data;
3652 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
3653 demo->pointer = wl_seat_get_pointer(seat);
3654 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
3655 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
3656 wl_pointer_destroy(demo->pointer);
3657 demo->pointer = NULL;
3659 // Subscribe to keyboard events
3660 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
3661 demo->keyboard = wl_seat_get_keyboard(seat);
3662 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
3663 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
3664 wl_keyboard_destroy(demo->keyboard);
3665 demo->keyboard = NULL;
3669 static const struct wl_seat_listener seat_listener = {
3670 seat_handle_capabilities,
3673 static void wm_base_ping(void *data UNUSED, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {
3674 xdg_wm_base_pong(xdg_wm_base, serial);
3677 static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
3679 static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
3680 uint32_t version UNUSED) {
3681 struct demo *demo = data;
3682 // pickup wayland objects when they appear
3683 if (strcmp(interface, wl_compositor_interface.name) == 0) {
3684 uint32_t minVersion = version < 4 ? version : 4;
3685 demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, minVersion);
3686 if (demo->VK_KHR_incremental_present_enabled && minVersion < 4) {
3687 fprintf(stderr, "Wayland compositor doesn't support VK_KHR_incremental_present, disabling.\n");
3688 demo->VK_KHR_incremental_present_enabled = false;
3690 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
3691 demo->xdg_wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
3692 xdg_wm_base_add_listener(demo->xdg_wm_base, &wm_base_listener, NULL);
3693 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
3694 demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
3695 wl_seat_add_listener(demo->seat, &seat_listener, demo);
3696 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
3697 demo->xdg_decoration_mgr = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
3701 static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
3703 static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
3706 static void demo_init_connection(struct demo *demo) {
3707 #if defined(VK_USE_PLATFORM_XCB_KHR)
3708 const xcb_setup_t *setup;
3709 xcb_screen_iterator_t iter;
3712 const char *display_envar = getenv("DISPLAY");
3713 if (display_envar == NULL || display_envar[0] == '\0') {
3714 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
3719 demo->connection = xcb_connect(NULL, &scr);
3720 if (xcb_connection_has_error(demo->connection) > 0) {
3721 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3726 setup = xcb_get_setup(demo->connection);
3727 iter = xcb_setup_roots_iterator(setup);
3728 while (scr-- > 0) xcb_screen_next(&iter);
3730 demo->screen = iter.data;
3731 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3732 demo->display = wl_display_connect(NULL);
3734 if (demo->display == NULL) {
3735 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3740 demo->registry = wl_display_get_registry(demo->display);
3741 wl_registry_add_listener(demo->registry, ®istry_listener, demo);
3742 wl_display_dispatch(demo->display);
3746 static void demo_init(struct demo *demo, int argc, char **argv) {
3747 vec3 eye = {0.0f, 3.0f, 5.0f};
3748 vec3 origin = {0, 0, 0};
3749 vec3 up = {0.0f, 1.0f, 0.0};
3751 memset(demo, 0, sizeof(*demo));
3752 demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
3753 demo->frameCount = INT32_MAX;
3755 for (int i = 1; i < argc; i++) {
3756 if (strcmp(argv[i], "--use_staging") == 0) {
3757 demo->use_staging_buffer = true;
3760 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
3761 demo->presentMode = atoi(argv[i + 1]);
3765 if (strcmp(argv[i], "--break") == 0) {
3766 demo->use_break = true;
3769 if (strcmp(argv[i], "--validate") == 0) {
3770 demo->validate = true;
3773 if (strcmp(argv[i], "--validate-checks-disabled") == 0) {
3774 demo->validate = true;
3775 demo->validate_checks_disabled = true;
3778 if (strcmp(argv[i], "--xlib") == 0) {
3779 fprintf(stderr, "--xlib is deprecated and no longer does anything");
3782 if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
3783 sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
3787 if (strcmp(argv[i], "--suppress_popups") == 0) {
3788 demo->suppress_popups = true;
3791 if (strcmp(argv[i], "--display_timing") == 0) {
3792 demo->VK_GOOGLE_display_timing_enabled = true;
3795 if (strcmp(argv[i], "--incremental_present") == 0) {
3796 demo->VK_KHR_incremental_present_enabled = true;
3800 #if defined(ANDROID)
3801 ERR_EXIT("Usage: vkcube [--validate]\n", "Usage");
3804 "Usage:\n %s\t[--use_staging] [--validate] [--validate-checks-disabled]\n"
3805 "\t[--break] [--c <framecount>] [--suppress_popups]\n"
3806 "\t[--incremental_present] [--display_timing]\n"
3807 "\t[--present_mode <present mode enum>]\n"
3808 "\t<present_mode_enum>\n"
3809 "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
3810 "\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
3811 "\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
3812 "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n";
3813 int length = snprintf(NULL, 0, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
3814 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
3815 char *usage = (char *)malloc(length + 1);
3819 snprintf(usage, length + 1, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
3820 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
3822 if (!demo->suppress_popups) MessageBox(NULL, usage, "Usage Error", MB_OK);
3824 fprintf(stderr, "%s", usage);
3832 demo_init_connection(demo);
3839 demo->spin_angle = 4.0f;
3840 demo->spin_increment = 0.2f;
3841 demo->pause = false;
3843 mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
3844 mat4x4_look_at(demo->view_matrix, eye, origin, up);
3845 mat4x4_identity(demo->model_matrix);
3847 demo->projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
3850 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3851 // Include header required for parsing the command line options.
3852 #include <shellapi.h>
3854 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
3856 bool done; // flag saying when app is complete
3860 // Ensure wParam is initialized.
3863 // Use the CommandLine functions to get the command line arguments.
3864 // Unfortunately, Microsoft outputs
3865 // this information as wide characters for Unicode, and we simply want the
3866 // Ascii version to be compatible
3867 // with the non-Windows side. So, we have to convert the information to
3868 // Ascii character strings.
3869 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3870 if (NULL == commandLineArgs) {
3875 argv = (char **)malloc(sizeof(char *) * argc);
3879 for (int iii = 0; iii < argc; iii++) {
3880 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3881 size_t numConverted = 0;
3883 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3884 if (argv[iii] != NULL) {
3885 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3893 demo_init(&demo, argc, argv);
3895 // Free up the items we had to allocate for the command line arguments.
3896 if (argc > 0 && argv != NULL) {
3897 for (int iii = 0; iii < argc; iii++) {
3898 if (argv[iii] != NULL) {
3905 demo.connection = hInstance;
3906 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
3907 demo_create_window(&demo);
3908 demo_init_vk_swapchain(&demo);
3910 demo_prepare(&demo);
3912 done = false; // initialize loop condition variable
3914 // main message loop
3917 const BOOL succ = WaitMessage();
3920 struct demo *tmp = &demo;
3921 struct demo *demo = tmp;
3922 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3925 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
3926 if (msg.message == WM_QUIT) // check for a quit message
3928 done = true; // if found, quit app
3930 /* Translate and dispatch to event queue*/
3931 TranslateMessage(&msg);
3932 DispatchMessage(&msg);
3934 RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
3937 demo_cleanup(&demo);
3939 return (int)msg.wParam;
3942 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3943 static void demo_main(struct demo *demo, void *caMetalLayer, int argc, const char *argv[]) {
3944 demo_init(demo, argc, (char **)argv);
3945 demo->caMetalLayer = caMetalLayer;
3946 demo_init_vk_swapchain(demo);
3948 demo->spin_angle = 0.4f;
3951 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3952 #include <android/log.h>
3953 #include <android_native_app_glue.h>
3954 #include "android_util.h"
3956 static bool initialized = false;
3957 static bool active = false;
3960 static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
3962 static void processCommand(struct android_app *app, int32_t cmd) {
3964 case APP_CMD_INIT_WINDOW: {
3966 // We're getting a new window. If the app is starting up, we
3967 // need to initialize. If the app has already been
3968 // initialized, that means that we lost our previous window,
3969 // which means that we have a lot of work to do. At a minimum,
3970 // we need to destroy the swapchain and surface associated with
3971 // the old window, and create a new surface and swapchain.
3972 // However, since there are a lot of other objects/state that
3973 // is tied to the swapchain, it's easiest to simply cleanup and
3974 // start over (i.e. use a brute-force approach of re-starting
3976 if (demo.prepared) {
3977 demo_cleanup(&demo);
3980 // Parse Intents into argc, argv
3981 // Use the following key to send arguments, i.e.
3982 // --es args "--validate"
3983 const char key[] = "args";
3984 char *appTag = (char *)APP_SHORT_NAME;
3986 char **argv = get_args(app, key, appTag, &argc);
3988 __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
3989 for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
3991 demo_init(&demo, argc, argv);
3993 // Free the argv malloc'd by get_args
3994 for (int i = 0; i < argc; i++) free(argv[i]);
3996 demo.window = (void *)app->window;
3997 demo_init_vk_swapchain(&demo);
3998 demo_prepare(&demo);
4003 case APP_CMD_GAINED_FOCUS: {
4007 case APP_CMD_LOST_FOCUS: {
4014 void android_main(struct android_app *app) {
4016 int vulkanSupport = InitVulkan();
4017 if (vulkanSupport == 0) return;
4020 demo.prepared = false;
4022 app->onAppCmd = processCommand;
4023 app->onInputEvent = processInput;
4027 struct android_poll_source *source;
4028 while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
4030 source->process(app, source);
4033 if (app->destroyRequested != 0) {
4034 demo_cleanup(&demo);
4038 if (initialized && active) {
4044 int main(int argc, char **argv) {
4047 demo_init(&demo, argc, argv);
4048 #if defined(VK_USE_PLATFORM_XCB_KHR)
4049 demo_create_xcb_window(&demo);
4050 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
4051 demo_create_xlib_window(&demo);
4052 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4053 demo_create_window(&demo);
4056 demo_init_vk_swapchain(&demo);
4058 demo_prepare(&demo);
4060 #if defined(VK_USE_PLATFORM_XCB_KHR)
4061 demo_run_xcb(&demo);
4062 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
4063 demo_run_xlib(&demo);
4064 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4066 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
4067 demo_run_display(&demo);
4070 demo_cleanup(&demo);
4072 return validation_error;