cube: Use staging buffer instead of staging image
[platform/upstream/Vulkan-Tools.git] / cube / cube.c
1 /*
2  * Copyright (c) 2015-2016 The Khronos Group Inc.
3  * Copyright (c) 2015-2016 Valve Corporation
4  * Copyright (c) 2015-2016 LunarG, Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Author: Chia-I Wu <olv@lunarg.com>
19  * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
20  * Author: Ian Elliott <ian@LunarG.com>
21  * Author: 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>
26  */
27
28 #define _GNU_SOURCE
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdbool.h>
34 #include <assert.h>
35 #include <signal.h>
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 #endif
41
42 #ifdef _WIN32
43 #pragma comment(linker, "/subsystem:windows")
44 #define APP_NAME_STR_LEN 80
45 #endif  // _WIN32
46
47 #if defined(VK_USE_PLATFORM_MIR_KHR)
48 #warning "Cube does not have code for Mir at this time"
49 #endif
50
51 #ifdef ANDROID
52 #include "vulkan_wrapper.h"
53 #else
54 #include <vulkan/vulkan.h>
55 #endif
56
57 #include <vulkan/vk_sdk_platform.h>
58 #include "linmath.h"
59 #include "object_type_string_helper.h"
60
61 #include "gettime.h"
62 #include "inttypes.h"
63 #define MILLION 1000000L
64 #define BILLION 1000000000L
65
66 #define DEMO_TEXTURE_COUNT 1
67 #define APP_SHORT_NAME "cube"
68 #define APP_LONG_NAME "The Vulkan Cube Demo Program"
69
70 // Allow a maximum of two outstanding presentation operations.
71 #define FRAME_LAG 2
72
73 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
74
75 #if defined(NDEBUG) && defined(__GNUC__)
76 #define U_ASSERT_ONLY __attribute__((unused))
77 #else
78 #define U_ASSERT_ONLY
79 #endif
80
81 #if defined(__GNUC__)
82 #define UNUSED __attribute__((unused))
83 #else
84 #define UNUSED
85 #endif
86
87 #ifdef _WIN32
88 bool in_callback = false;
89 #define ERR_EXIT(err_msg, err_class)                                             \
90     do {                                                                         \
91         if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
92         exit(1);                                                                 \
93     } while (0)
94 void DbgMsg(char *fmt, ...) {
95     va_list va;
96     va_start(va, fmt);
97     printf(fmt, va);
98     fflush(stdout);
99     va_end(va);
100 }
101
102 #elif defined __ANDROID__
103 #include <android/log.h>
104 #define ERR_EXIT(err_msg, err_class)                                    \
105     do {                                                                \
106         ((void)__android_log_print(ANDROID_LOG_INFO, "Cube", err_msg)); \
107         exit(1);                                                        \
108     } while (0)
109 #ifdef VARARGS_WORKS_ON_ANDROID
110 void DbgMsg(const char *fmt, ...) {
111     va_list va;
112     va_start(va, fmt);
113     __android_log_print(ANDROID_LOG_INFO, "Cube", fmt, va);
114     va_end(va);
115 }
116 #else  // VARARGS_WORKS_ON_ANDROID
117 #define DbgMsg(fmt, ...)                                                           \
118     do {                                                                           \
119         ((void)__android_log_print(ANDROID_LOG_INFO, "Cube", fmt, ##__VA_ARGS__)); \
120     } while (0)
121 #endif  // VARARGS_WORKS_ON_ANDROID
122 #else
123 #define ERR_EXIT(err_msg, err_class) \
124     do {                             \
125         printf("%s\n", err_msg);     \
126         fflush(stdout);              \
127         exit(1);                     \
128     } while (0)
129 void DbgMsg(char *fmt, ...) {
130     va_list va;
131     va_start(va, fmt);
132     printf(fmt, va);
133     fflush(stdout);
134     va_end(va);
135 }
136 #endif
137
138 #define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                                                              \
139     {                                                                                                         \
140         demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint);             \
141         if (demo->fp##entrypoint == NULL) {                                                                   \
142             ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
143         }                                                                                                     \
144     }
145
146 static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
147
148 #define GET_DEVICE_PROC_ADDR(dev, entrypoint)                                                                    \
149     {                                                                                                            \
150         if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
151         demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint);                                \
152         if (demo->fp##entrypoint == NULL) {                                                                      \
153             ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure");        \
154         }                                                                                                        \
155     }
156
157 /*
158  * structure to track all objects related to a texture.
159  */
160 struct texture_object {
161     VkSampler sampler;
162
163     VkImage image;
164     VkBuffer buffer;
165     VkImageLayout imageLayout;
166
167     VkMemoryAllocateInfo mem_alloc;
168     VkDeviceMemory mem;
169     VkImageView view;
170     int32_t tex_width, tex_height;
171 };
172
173 static char *tex_files[] = {"lunarg.ppm"};
174
175 static int validation_error = 0;
176
177 struct vktexcube_vs_uniform {
178     // Must start with MVP
179     float mvp[4][4];
180     float position[12 * 3][4];
181     float attr[12 * 3][4];
182 };
183
184 //--------------------------------------------------------------------------------------
185 // Mesh and VertexFormat Data
186 //--------------------------------------------------------------------------------------
187 // clang-format off
188 static const float g_vertex_buffer_data[] = {
189     -1.0f,-1.0f,-1.0f,  // -X side
190     -1.0f,-1.0f, 1.0f,
191     -1.0f, 1.0f, 1.0f,
192     -1.0f, 1.0f, 1.0f,
193     -1.0f, 1.0f,-1.0f,
194     -1.0f,-1.0f,-1.0f,
195
196     -1.0f,-1.0f,-1.0f,  // -Z side
197      1.0f, 1.0f,-1.0f,
198      1.0f,-1.0f,-1.0f,
199     -1.0f,-1.0f,-1.0f,
200     -1.0f, 1.0f,-1.0f,
201      1.0f, 1.0f,-1.0f,
202
203     -1.0f,-1.0f,-1.0f,  // -Y side
204      1.0f,-1.0f,-1.0f,
205      1.0f,-1.0f, 1.0f,
206     -1.0f,-1.0f,-1.0f,
207      1.0f,-1.0f, 1.0f,
208     -1.0f,-1.0f, 1.0f,
209
210     -1.0f, 1.0f,-1.0f,  // +Y side
211     -1.0f, 1.0f, 1.0f,
212      1.0f, 1.0f, 1.0f,
213     -1.0f, 1.0f,-1.0f,
214      1.0f, 1.0f, 1.0f,
215      1.0f, 1.0f,-1.0f,
216
217      1.0f, 1.0f,-1.0f,  // +X side
218      1.0f, 1.0f, 1.0f,
219      1.0f,-1.0f, 1.0f,
220      1.0f,-1.0f, 1.0f,
221      1.0f,-1.0f,-1.0f,
222      1.0f, 1.0f,-1.0f,
223
224     -1.0f, 1.0f, 1.0f,  // +Z side
225     -1.0f,-1.0f, 1.0f,
226      1.0f, 1.0f, 1.0f,
227     -1.0f,-1.0f, 1.0f,
228      1.0f,-1.0f, 1.0f,
229      1.0f, 1.0f, 1.0f,
230 };
231
232 static const float g_uv_buffer_data[] = {
233     0.0f, 1.0f,  // -X side
234     1.0f, 1.0f,
235     1.0f, 0.0f,
236     1.0f, 0.0f,
237     0.0f, 0.0f,
238     0.0f, 1.0f,
239
240     1.0f, 1.0f,  // -Z side
241     0.0f, 0.0f,
242     0.0f, 1.0f,
243     1.0f, 1.0f,
244     1.0f, 0.0f,
245     0.0f, 0.0f,
246
247     1.0f, 0.0f,  // -Y side
248     1.0f, 1.0f,
249     0.0f, 1.0f,
250     1.0f, 0.0f,
251     0.0f, 1.0f,
252     0.0f, 0.0f,
253
254     1.0f, 0.0f,  // +Y side
255     0.0f, 0.0f,
256     0.0f, 1.0f,
257     1.0f, 0.0f,
258     0.0f, 1.0f,
259     1.0f, 1.0f,
260
261     1.0f, 0.0f,  // +X side
262     0.0f, 0.0f,
263     0.0f, 1.0f,
264     0.0f, 1.0f,
265     1.0f, 1.0f,
266     1.0f, 0.0f,
267
268     0.0f, 0.0f,  // +Z side
269     0.0f, 1.0f,
270     1.0f, 0.0f,
271     0.0f, 1.0f,
272     1.0f, 1.0f,
273     1.0f, 0.0f,
274 };
275 // clang-format on
276
277 void dumpMatrix(const char *note, mat4x4 MVP) {
278     int i;
279
280     printf("%s: \n", note);
281     for (i = 0; i < 4; i++) {
282         printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
283     }
284     printf("\n");
285     fflush(stdout);
286 }
287
288 void dumpVec4(const char *note, vec4 vector) {
289     printf("%s: \n", note);
290     printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
291     printf("\n");
292     fflush(stdout);
293 }
294
295 typedef struct {
296     VkImage image;
297     VkCommandBuffer cmd;
298     VkCommandBuffer graphics_to_present_cmd;
299     VkImageView view;
300     VkBuffer uniform_buffer;
301     VkDeviceMemory uniform_memory;
302     VkFramebuffer framebuffer;
303     VkDescriptorSet descriptor_set;
304 } SwapchainImageResources;
305
306 struct demo {
307 #if defined(VK_USE_PLATFORM_WIN32_KHR)
308 #define APP_NAME_STR_LEN 80
309     HINSTANCE connection;         // hInstance - Windows Instance
310     char name[APP_NAME_STR_LEN];  // Name to put on the window/icon
311     HWND window;                  // hWnd - window handle
312     POINT minsize;                // minimum window size
313 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
314     Display *display;
315     Window xlib_window;
316     Atom xlib_wm_delete_window;
317 #elif defined(VK_USE_PLATFORM_XCB_KHR)
318     Display *display;
319     xcb_connection_t *connection;
320     xcb_screen_t *screen;
321     xcb_window_t xcb_window;
322     xcb_intern_atom_reply_t *atom_wm_delete_window;
323 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
324     struct wl_display *display;
325     struct wl_registry *registry;
326     struct wl_compositor *compositor;
327     struct wl_surface *window;
328     struct wl_shell *shell;
329     struct wl_shell_surface *shell_surface;
330     struct wl_seat *seat;
331     struct wl_pointer *pointer;
332     struct wl_keyboard *keyboard;
333 #elif defined(VK_USE_PLATFORM_MIR_KHR)
334 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
335     struct ANativeWindow *window;
336 #elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
337     void *window;
338 #endif
339     VkSurfaceKHR surface;
340     bool prepared;
341     bool use_staging_buffer;
342     bool separate_present_queue;
343     bool is_minimized;
344
345     bool VK_KHR_incremental_present_enabled;
346
347     bool VK_GOOGLE_display_timing_enabled;
348     bool syncd_with_actual_presents;
349     uint64_t refresh_duration;
350     uint64_t refresh_duration_multiplier;
351     uint64_t target_IPD;  // image present duration (inverse of frame rate)
352     uint64_t prev_desired_present_time;
353     uint32_t next_present_id;
354     uint32_t last_early_id;  // 0 if no early images
355     uint32_t last_late_id;   // 0 if no late images
356
357     VkInstance inst;
358     VkPhysicalDevice gpu;
359     VkDevice device;
360     VkQueue graphics_queue;
361     VkQueue present_queue;
362     uint32_t graphics_queue_family_index;
363     uint32_t present_queue_family_index;
364     VkSemaphore image_acquired_semaphores[FRAME_LAG];
365     VkSemaphore draw_complete_semaphores[FRAME_LAG];
366     VkSemaphore image_ownership_semaphores[FRAME_LAG];
367     VkPhysicalDeviceProperties gpu_props;
368     VkQueueFamilyProperties *queue_props;
369     VkPhysicalDeviceMemoryProperties memory_properties;
370
371     uint32_t enabled_extension_count;
372     uint32_t enabled_layer_count;
373     char *extension_names[64];
374     char *enabled_layers[64];
375
376     int width, height;
377     VkFormat format;
378     VkColorSpaceKHR color_space;
379
380     PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
381     PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
382     PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
383     PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
384     PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
385     PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
386     PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
387     PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
388     PFN_vkQueuePresentKHR fpQueuePresentKHR;
389     PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
390     PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
391     uint32_t swapchainImageCount;
392     VkSwapchainKHR swapchain;
393     SwapchainImageResources *swapchain_image_resources;
394     VkPresentModeKHR presentMode;
395     VkFence fences[FRAME_LAG];
396     int frame_index;
397
398     VkCommandPool cmd_pool;
399     VkCommandPool present_cmd_pool;
400
401     struct {
402         VkFormat format;
403
404         VkImage image;
405         VkMemoryAllocateInfo mem_alloc;
406         VkDeviceMemory mem;
407         VkImageView view;
408     } depth;
409
410     struct texture_object textures[DEMO_TEXTURE_COUNT];
411     struct texture_object staging_texture;
412
413     VkCommandBuffer cmd;  // Buffer for initialization commands
414     VkPipelineLayout pipeline_layout;
415     VkDescriptorSetLayout desc_layout;
416     VkPipelineCache pipelineCache;
417     VkRenderPass render_pass;
418     VkPipeline pipeline;
419
420     mat4x4 projection_matrix;
421     mat4x4 view_matrix;
422     mat4x4 model_matrix;
423
424     float spin_angle;
425     float spin_increment;
426     bool pause;
427
428     VkShaderModule vert_shader_module;
429     VkShaderModule frag_shader_module;
430
431     VkDescriptorPool desc_pool;
432
433     bool quit;
434     int32_t curFrame;
435     int32_t frameCount;
436     bool validate;
437     bool validate_checks_disabled;
438     bool use_break;
439     bool suppress_popups;
440
441     PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
442     PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
443     PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
444     PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
445     PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
446     PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
447     PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
448     VkDebugUtilsMessengerEXT dbg_messenger;
449
450     uint32_t current_buffer;
451     uint32_t queue_family_count;
452 };
453
454 VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
455                                                         VkDebugUtilsMessageTypeFlagsEXT messageType,
456                                                         const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
457                                                         void *pUserData) {
458     char prefix[64] = "";
459     char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
460     assert(message);
461     struct demo *demo = (struct demo *)pUserData;
462
463     if (demo->use_break) {
464 #ifndef WIN32
465         raise(SIGTRAP);
466 #else
467         DebugBreak();
468 #endif
469     }
470
471     if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
472         strcat(prefix, "VERBOSE : ");
473     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
474         strcat(prefix, "INFO : ");
475     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
476         strcat(prefix, "WARNING : ");
477     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
478         strcat(prefix, "ERROR : ");
479     }
480
481     if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
482         strcat(prefix, "GENERAL");
483     } else {
484         if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
485             strcat(prefix, "VALIDATION");
486             validation_error = 1;
487         }
488         if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
489             if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
490                 strcat(prefix, "|");
491             }
492             strcat(prefix, "PERFORMANCE");
493         }
494     }
495
496     sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
497             pCallbackData->pMessageIdName, pCallbackData->pMessage);
498     if (pCallbackData->objectCount > 0) {
499         char tmp_message[500];
500         sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
501         strcat(message, tmp_message);
502         for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
503             if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
504                 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
505                         string_VkObjectType(pCallbackData->pObjects[object].objectType),
506                         (void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
507             } else {
508                 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
509                         string_VkObjectType(pCallbackData->pObjects[object].objectType),
510                         (void *)(pCallbackData->pObjects[object].objectHandle));
511             }
512             strcat(message, tmp_message);
513         }
514     }
515     if (pCallbackData->cmdBufLabelCount > 0) {
516         char tmp_message[500];
517         sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
518         strcat(message, tmp_message);
519         for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
520             sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
521                     pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
522                     pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
523                     pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
524             strcat(message, tmp_message);
525         }
526     }
527
528 #ifdef _WIN32
529
530     in_callback = true;
531     if (!demo->suppress_popups)
532         MessageBox(NULL, message, "Alert", MB_OK);
533     in_callback = false;
534
535 #elif defined(ANDROID)
536
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);
545     } else {
546         __android_log_print(ANDROID_LOG_INFO,  APP_SHORT_NAME, "%s", message);
547     }
548
549 #else
550
551     printf("%s\n", message);
552     fflush(stdout);
553
554 #endif
555
556     free(message);
557
558     // Don't bail out, but keep going.
559     return false;
560 }
561
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.
571         return false;
572     }
573     uint64_t deadline = desired + rdur;
574     if (actual > deadline) {
575         return true;
576     } else {
577         return false;
578     }
579 }
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.
590             return true;
591         }
592     }
593     return false;
594 }
595
596 // Forward declaration:
597 static void demo_resize(struct demo *demo);
598
599 static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
600     // Search memtypes to find first index with those properties
601     for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
602         if ((typeBits & 1) == 1) {
603             // Type is available, does it match user properties?
604             if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
605                 *typeIndex = i;
606                 return true;
607             }
608         }
609         typeBits >>= 1;
610     }
611     // No memory types matched, return failure
612     return false;
613 }
614
615 static void demo_flush_init_cmd(struct demo *demo) {
616     VkResult U_ASSERT_ONLY err;
617
618     // This function could get called twice if the texture uses a staging buffer
619     // In that case the second call should be ignored
620     if (demo->cmd == VK_NULL_HANDLE) return;
621
622     err = vkEndCommandBuffer(demo->cmd);
623     assert(!err);
624
625     VkFence fence;
626     VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
627     err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
628     assert(!err);
629
630     const VkCommandBuffer cmd_bufs[] = {demo->cmd};
631     VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
632                                 .pNext = NULL,
633                                 .waitSemaphoreCount = 0,
634                                 .pWaitSemaphores = NULL,
635                                 .pWaitDstStageMask = NULL,
636                                 .commandBufferCount = 1,
637                                 .pCommandBuffers = cmd_bufs,
638                                 .signalSemaphoreCount = 0,
639                                 .pSignalSemaphores = NULL};
640
641     err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
642     assert(!err);
643
644     err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
645     assert(!err);
646
647     vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
648     vkDestroyFence(demo->device, fence, NULL);
649     demo->cmd = VK_NULL_HANDLE;
650 }
651
652 static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
653                                   VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
654                                   VkPipelineStageFlags dest_stages) {
655     assert(demo->cmd);
656
657     VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
658                                                  .pNext = NULL,
659                                                  .srcAccessMask = srcAccessMask,
660                                                  .dstAccessMask = 0,
661                                                  .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
662                                                  .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
663                                                  .oldLayout = old_image_layout,
664                                                  .newLayout = new_image_layout,
665                                                  .image = image,
666                                                  .subresourceRange = {aspectMask, 0, 1, 0, 1}};
667
668     switch (new_image_layout) {
669         case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
670             /* Make sure anything that was copying from this image has completed */
671             image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
672             break;
673
674         case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
675             image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
676             break;
677
678         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
679             image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
680             break;
681
682         case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
683             image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
684             break;
685
686         case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
687             image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
688             break;
689
690         case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
691             image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
692             break;
693
694         default:
695             image_memory_barrier.dstAccessMask = 0;
696             break;
697     }
698
699     VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
700
701     vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
702 }
703
704 static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
705     VkDebugUtilsLabelEXT label;
706     memset(&label, 0, sizeof(label));
707     const VkCommandBufferBeginInfo cmd_buf_info = {
708         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
709         .pNext = NULL,
710         .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
711         .pInheritanceInfo = NULL,
712     };
713     const VkClearValue clear_values[2] = {
714         [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
715         [1] = {.depthStencil = {1.0f, 0}},
716     };
717     const VkRenderPassBeginInfo rp_begin = {
718         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
719         .pNext = NULL,
720         .renderPass = demo->render_pass,
721         .framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
722         .renderArea.offset.x = 0,
723         .renderArea.offset.y = 0,
724         .renderArea.extent.width = demo->width,
725         .renderArea.extent.height = demo->height,
726         .clearValueCount = 2,
727         .pClearValues = clear_values,
728     };
729     VkResult U_ASSERT_ONLY err;
730
731     err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
732
733     if (demo->validate) {
734         // Set a name for the command buffer
735         VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
736             .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
737             .pNext = NULL,
738             .objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
739             .objectHandle = (uint64_t)cmd_buf,
740             .pObjectName = "CubeDrawCommandBuf",
741         };
742         demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
743
744         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
745         label.pNext = NULL;
746         label.pLabelName = "DrawBegin";
747         label.color[0] = 0.4f;
748         label.color[1] = 0.3f;
749         label.color[2] = 0.2f;
750         label.color[3] = 0.1f;
751         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
752     }
753
754     assert(!err);
755     vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
756
757     if (demo->validate) {
758         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
759         label.pNext = NULL;
760         label.pLabelName = "InsideRenderPass";
761         label.color[0] = 8.4f;
762         label.color[1] = 7.3f;
763         label.color[2] = 6.2f;
764         label.color[3] = 7.1f;
765         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
766     }
767
768     vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
769     vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
770                             &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
771     VkViewport viewport;
772     memset(&viewport, 0, sizeof(viewport));
773     viewport.height = (float)demo->height;
774     viewport.width = (float)demo->width;
775     viewport.minDepth = (float)0.0f;
776     viewport.maxDepth = (float)1.0f;
777     vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
778
779     VkRect2D scissor;
780     memset(&scissor, 0, sizeof(scissor));
781     scissor.extent.width = demo->width;
782     scissor.extent.height = demo->height;
783     scissor.offset.x = 0;
784     scissor.offset.y = 0;
785     vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
786
787     if (demo->validate) {
788         label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
789         label.pNext = NULL;
790         label.pLabelName = "ActualDraw";
791         label.color[0] = -0.4f;
792         label.color[1] = -0.3f;
793         label.color[2] = -0.2f;
794         label.color[3] = -0.1f;
795         demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
796     }
797
798     vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
799     if (demo->validate) {
800         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
801     }
802
803     // Note that ending the renderpass changes the image's layout from
804     // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
805     vkCmdEndRenderPass(cmd_buf);
806     if (demo->validate) {
807         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
808     }
809
810     if (demo->separate_present_queue) {
811         // We have to transfer ownership from the graphics queue family to the
812         // present queue family to be able to present.  Note that we don't have
813         // to transfer from present queue family back to graphics queue family at
814         // the start of the next frame because we don't care about the image's
815         // contents at that point.
816         VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
817                                                         .pNext = NULL,
818                                                         .srcAccessMask = 0,
819                                                         .dstAccessMask = 0,
820                                                         .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
821                                                         .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
822                                                         .srcQueueFamilyIndex = demo->graphics_queue_family_index,
823                                                         .dstQueueFamilyIndex = demo->present_queue_family_index,
824                                                         .image = demo->swapchain_image_resources[demo->current_buffer].image,
825                                                         .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
826
827         vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
828                              NULL, 1, &image_ownership_barrier);
829     }
830     if (demo->validate) {
831         demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
832     }
833     err = vkEndCommandBuffer(cmd_buf);
834     assert(!err);
835 }
836
837 void demo_build_image_ownership_cmd(struct demo *demo, int i) {
838     VkResult U_ASSERT_ONLY err;
839
840     const VkCommandBufferBeginInfo cmd_buf_info = {
841         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
842         .pNext = NULL,
843         .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
844         .pInheritanceInfo = NULL,
845     };
846     err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
847     assert(!err);
848
849     VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
850                                                     .pNext = NULL,
851                                                     .srcAccessMask = 0,
852                                                     .dstAccessMask = 0,
853                                                     .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
854                                                     .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
855                                                     .srcQueueFamilyIndex = demo->graphics_queue_family_index,
856                                                     .dstQueueFamilyIndex = demo->present_queue_family_index,
857                                                     .image = demo->swapchain_image_resources[i].image,
858                                                     .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
859
860     vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
861                          VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
862     err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
863     assert(!err);
864 }
865
866 void demo_update_data_buffer(struct demo *demo) {
867     mat4x4 MVP, Model, VP;
868     int matrixSize = sizeof(MVP);
869     uint8_t *pData;
870     VkResult U_ASSERT_ONLY err;
871
872     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
873
874     // Rotate around the Y axis
875     mat4x4_dup(Model, demo->model_matrix);
876     mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(demo->spin_angle));
877     mat4x4_mul(MVP, VP, demo->model_matrix);
878
879     err = vkMapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, 0,
880                       (void **)&pData);
881     assert(!err);
882
883     memcpy(pData, (const void *)&MVP[0][0], matrixSize);
884
885     vkUnmapMemory(demo->device, demo->swapchain_image_resources[demo->current_buffer].uniform_memory);
886 }
887
888 void DemoUpdateTargetIPD(struct demo *demo) {
889     // Look at what happened to previous presents, and make appropriate
890     // adjustments in timing:
891     VkResult U_ASSERT_ONLY err;
892     VkPastPresentationTimingGOOGLE *past = NULL;
893     uint32_t count = 0;
894
895     err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
896     assert(!err);
897     if (count) {
898         past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
899         assert(past);
900         err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
901         assert(!err);
902
903         bool early = false;
904         bool late = false;
905         bool calibrate_next = false;
906         for (uint32_t i = 0; i < count; i++) {
907             if (!demo->syncd_with_actual_presents) {
908                 // This is the first time that we've received an
909                 // actualPresentTime for this swapchain.  In order to not
910                 // perceive these early frames as "late", we need to sync-up
911                 // our future desiredPresentTime's with the
912                 // actualPresentTime(s) that we're receiving now.
913                 calibrate_next = true;
914
915                 // So that we don't suspect any pending presents as late,
916                 // record them all as suspected-late presents:
917                 demo->last_late_id = demo->next_present_id - 1;
918                 demo->last_early_id = 0;
919                 demo->syncd_with_actual_presents = true;
920                 break;
921             } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
922                                          demo->refresh_duration)) {
923                 // This image could have been presented earlier.  We don't want
924                 // to decrease the target_IPD until we've seen early presents
925                 // for at least two seconds.
926                 if (demo->last_early_id == past[i].presentID) {
927                     // We've now seen two seconds worth of early presents.
928                     // Flag it as such, and reset the counter:
929                     early = true;
930                     demo->last_early_id = 0;
931                 } else if (demo->last_early_id == 0) {
932                     // This is the first early present we've seen.
933                     // Calculate the presentID for two seconds from now.
934                     uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
935                     uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
936                     demo->last_early_id = past[i].presentID + howManyPresents;
937                 } else {
938                     // We are in the midst of a set of early images,
939                     // and so we won't do anything.
940                 }
941                 late = false;
942                 demo->last_late_id = 0;
943             } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
944                 // This image was presented after its desired time.  Since
945                 // there's a delay between calling vkQueuePresentKHR and when
946                 // we get the timing data, several presents may have been late.
947                 // Thus, we need to threat all of the outstanding presents as
948                 // being likely late, so that we only increase the target_IPD
949                 // once for all of those presents.
950                 if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
951                     late = true;
952                     // Record the last suspected-late present:
953                     demo->last_late_id = demo->next_present_id - 1;
954                 } else {
955                     // We are in the midst of a set of likely-late images,
956                     // and so we won't do anything.
957                 }
958                 early = false;
959                 demo->last_early_id = 0;
960             } else {
961                 // Since this image was not presented early or late, reset
962                 // any sets of early or late presentIDs:
963                 early = false;
964                 late = false;
965                 calibrate_next = true;
966                 demo->last_early_id = 0;
967                 demo->last_late_id = 0;
968             }
969         }
970
971         if (early) {
972             // Since we've seen at least two-seconds worth of presnts that
973             // could have occured earlier than desired, let's decrease the
974             // target_IPD (i.e. increase the frame rate):
975             //
976             // TODO(ianelliott): Try to calculate a better target_IPD based
977             // on the most recently-seen present (this is overly-simplistic).
978             demo->refresh_duration_multiplier--;
979             if (demo->refresh_duration_multiplier == 0) {
980                 // This should never happen, but in case it does, don't
981                 // try to go faster.
982                 demo->refresh_duration_multiplier = 1;
983             }
984             demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
985         }
986         if (late) {
987             // Since we found a new instance of a late present, we want to
988             // increase the target_IPD (i.e. decrease the frame rate):
989             //
990             // TODO(ianelliott): Try to calculate a better target_IPD based
991             // on the most recently-seen present (this is overly-simplistic).
992             demo->refresh_duration_multiplier++;
993             demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
994         }
995
996         if (calibrate_next) {
997             int64_t multiple = demo->next_present_id - past[count - 1].presentID;
998             demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
999         }
1000         free(past);
1001     }
1002 }
1003
1004 static void demo_draw(struct demo *demo) {
1005     VkResult U_ASSERT_ONLY err;
1006
1007     // Ensure no more than FRAME_LAG renderings are outstanding
1008     vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
1009     vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
1010
1011     do {
1012         // Get the index of the next available swapchain image:
1013         err =
1014             demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
1015                                         demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer);
1016
1017         if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1018             // demo->swapchain is out of date (e.g. the window was resized) and
1019             // must be recreated:
1020             demo_resize(demo);
1021         } else if (err == VK_SUBOPTIMAL_KHR) {
1022             // demo->swapchain is not as optimal as it could be, but the platform's
1023             // presentation engine will still present the image correctly.
1024             break;
1025         } else {
1026             assert(!err);
1027         }
1028     } while (err != VK_SUCCESS);
1029
1030     demo_update_data_buffer(demo);
1031
1032     if (demo->VK_GOOGLE_display_timing_enabled) {
1033         // Look at what happened to previous presents, and make appropriate
1034         // adjustments in timing:
1035         DemoUpdateTargetIPD(demo);
1036
1037         // Note: a real application would position its geometry to that it's in
1038         // the correct locatoin for when the next image is presented.  It might
1039         // also wait, so that there's less latency between any input and when
1040         // the next image is rendered/presented.  This demo program is so
1041         // simple that it doesn't do either of those.
1042     }
1043
1044     // Wait for the image acquired semaphore to be signaled to ensure
1045     // that the image won't be rendered to until the presentation
1046     // engine has fully released ownership to the application, and it is
1047     // okay to render to the image.
1048     VkPipelineStageFlags pipe_stage_flags;
1049     VkSubmitInfo submit_info;
1050     submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1051     submit_info.pNext = NULL;
1052     submit_info.pWaitDstStageMask = &pipe_stage_flags;
1053     pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1054     submit_info.waitSemaphoreCount = 1;
1055     submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
1056     submit_info.commandBufferCount = 1;
1057     submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
1058     submit_info.signalSemaphoreCount = 1;
1059     submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1060     err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
1061     assert(!err);
1062
1063     if (demo->separate_present_queue) {
1064         // If we are using separate queues, change image ownership to the
1065         // present queue before presenting, waiting for the draw complete
1066         // semaphore and signalling the ownership released semaphore when finished
1067         VkFence nullFence = VK_NULL_HANDLE;
1068         pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1069         submit_info.waitSemaphoreCount = 1;
1070         submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
1071         submit_info.commandBufferCount = 1;
1072         submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
1073         submit_info.signalSemaphoreCount = 1;
1074         submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
1075         err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
1076         assert(!err);
1077     }
1078
1079     // If we are using separate queues we have to wait for image ownership,
1080     // otherwise wait for draw complete
1081     VkPresentInfoKHR present = {
1082         .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1083         .pNext = NULL,
1084         .waitSemaphoreCount = 1,
1085         .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index]
1086                                                           : &demo->draw_complete_semaphores[demo->frame_index],
1087         .swapchainCount = 1,
1088         .pSwapchains = &demo->swapchain,
1089         .pImageIndices = &demo->current_buffer,
1090     };
1091
1092     if (demo->VK_KHR_incremental_present_enabled) {
1093         // If using VK_KHR_incremental_present, we provide a hint of the region
1094         // that contains changed content relative to the previously-presented
1095         // image.  The implementation can use this hint in order to save
1096         // work/power (by only copying the region in the hint).  The
1097         // implementation is free to ignore the hint though, and so we must
1098         // ensure that the entire image has the correctly-drawn content.
1099         uint32_t eighthOfWidth = demo->width / 8;
1100         uint32_t eighthOfHeight = demo->height / 8;
1101         VkRectLayerKHR rect = {
1102             .offset.x = eighthOfWidth,
1103             .offset.y = eighthOfHeight,
1104             .extent.width = eighthOfWidth * 6,
1105             .extent.height = eighthOfHeight * 6,
1106             .layer = 0,
1107         };
1108         VkPresentRegionKHR region = {
1109             .rectangleCount = 1,
1110             .pRectangles = &rect,
1111         };
1112         VkPresentRegionsKHR regions = {
1113             .sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR,
1114             .pNext = present.pNext,
1115             .swapchainCount = present.swapchainCount,
1116             .pRegions = &region,
1117         };
1118         present.pNext = &regions;
1119     }
1120
1121     if (demo->VK_GOOGLE_display_timing_enabled) {
1122         VkPresentTimeGOOGLE ptime;
1123         if (demo->prev_desired_present_time == 0) {
1124             // This must be the first present for this swapchain.
1125             //
1126             // We don't know where we are relative to the presentation engine's
1127             // display's refresh cycle.  We also don't know how long rendering
1128             // takes.  Let's make a grossly-simplified assumption that the
1129             // desiredPresentTime should be half way between now and
1130             // now+target_IPD.  We will adjust over time.
1131             uint64_t curtime = getTimeInNanoseconds();
1132             if (curtime == 0) {
1133                 // Since we didn't find out the current time, don't give a
1134                 // desiredPresentTime:
1135                 ptime.desiredPresentTime = 0;
1136             } else {
1137                 ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
1138             }
1139         } else {
1140             ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
1141         }
1142         ptime.presentID = demo->next_present_id++;
1143         demo->prev_desired_present_time = ptime.desiredPresentTime;
1144
1145         VkPresentTimesInfoGOOGLE present_time = {
1146             .sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
1147             .pNext = present.pNext,
1148             .swapchainCount = present.swapchainCount,
1149             .pTimes = &ptime,
1150         };
1151         if (demo->VK_GOOGLE_display_timing_enabled) {
1152             present.pNext = &present_time;
1153         }
1154     }
1155
1156     err = demo->fpQueuePresentKHR(demo->present_queue, &present);
1157     demo->frame_index += 1;
1158     demo->frame_index %= FRAME_LAG;
1159
1160     if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1161         // demo->swapchain is out of date (e.g. the window was resized) and
1162         // must be recreated:
1163         demo_resize(demo);
1164     } else if (err == VK_SUBOPTIMAL_KHR) {
1165         // demo->swapchain is not as optimal as it could be, but the platform's
1166         // presentation engine will still present the image correctly.
1167     } else {
1168         assert(!err);
1169     }
1170 }
1171
1172 static void demo_prepare_buffers(struct demo *demo) {
1173     VkResult U_ASSERT_ONLY err;
1174     VkSwapchainKHR oldSwapchain = demo->swapchain;
1175
1176     // Check the surface capabilities and formats
1177     VkSurfaceCapabilitiesKHR surfCapabilities;
1178     err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
1179     assert(!err);
1180
1181     uint32_t presentModeCount;
1182     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
1183     assert(!err);
1184     VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
1185     assert(presentModes);
1186     err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
1187     assert(!err);
1188
1189     VkExtent2D swapchainExtent;
1190     // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
1191     if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
1192         // If the surface size is undefined, the size is set to the size
1193         // of the images requested, which must fit within the minimum and
1194         // maximum values.
1195         swapchainExtent.width = demo->width;
1196         swapchainExtent.height = demo->height;
1197
1198         if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
1199             swapchainExtent.width = surfCapabilities.minImageExtent.width;
1200         } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
1201             swapchainExtent.width = surfCapabilities.maxImageExtent.width;
1202         }
1203
1204         if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
1205             swapchainExtent.height = surfCapabilities.minImageExtent.height;
1206         } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
1207             swapchainExtent.height = surfCapabilities.maxImageExtent.height;
1208         }
1209     } else {
1210         // If the surface size is defined, the swap chain size must match
1211         swapchainExtent = surfCapabilities.currentExtent;
1212         demo->width = surfCapabilities.currentExtent.width;
1213         demo->height = surfCapabilities.currentExtent.height;
1214     }
1215
1216     if (demo->width == 0 || demo->height == 0) {
1217         demo->is_minimized = true;
1218         return;
1219     } else {
1220         demo->is_minimized = false;
1221     }
1222
1223     // The FIFO present mode is guaranteed by the spec to be supported
1224     // and to have no tearing.  It's a great default present mode to use.
1225     VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
1226
1227     //  There are times when you may wish to use another present mode.  The
1228     //  following code shows how to select them, and the comments provide some
1229     //  reasons you may wish to use them.
1230     //
1231     // It should be noted that Vulkan 1.0 doesn't provide a method for
1232     // synchronizing rendering with the presentation engine's display.  There
1233     // is a method provided for throttling rendering with the display, but
1234     // there are some presentation engines for which this method will not work.
1235     // If an application doesn't throttle its rendering, and if it renders much
1236     // faster than the refresh rate of the display, this can waste power on
1237     // mobile devices.  That is because power is being spent rendering images
1238     // that may never be seen.
1239
1240     // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1241     // tearing, or have some way of synchronizing their rendering with the
1242     // display.
1243     // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1244     // generally render a new presentable image every refresh cycle, but are
1245     // occasionally early.  In this case, the application wants the new image
1246     // to be displayed instead of the previously-queued-for-presentation image
1247     // that has not yet been displayed.
1248     // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1249     // render a new presentable image every refresh cycle, but are occasionally
1250     // late.  In this case (perhaps because of stuttering/latency concerns),
1251     // the application wants the late image to be immediately displayed, even
1252     // though that may mean some tearing.
1253
1254     if (demo->presentMode != swapchainPresentMode) {
1255         for (size_t i = 0; i < presentModeCount; ++i) {
1256             if (presentModes[i] == demo->presentMode) {
1257                 swapchainPresentMode = demo->presentMode;
1258                 break;
1259             }
1260         }
1261     }
1262     if (swapchainPresentMode != demo->presentMode) {
1263         ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1264     }
1265
1266     // Determine the number of VkImages to use in the swap chain.
1267     // Application desires to acquire 3 images at a time for triple
1268     // buffering
1269     uint32_t desiredNumOfSwapchainImages = 3;
1270     if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1271         desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1272     }
1273     // If maxImageCount is 0, we can ask for as many images as we want;
1274     // otherwise we're limited to maxImageCount
1275     if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1276         // Application must settle for fewer images than desired:
1277         desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1278     }
1279
1280     VkSurfaceTransformFlagsKHR preTransform;
1281     if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
1282         preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
1283     } else {
1284         preTransform = surfCapabilities.currentTransform;
1285     }
1286
1287     // Find a supported composite alpha mode - one of these is guaranteed to be set
1288     VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1289     VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1290         VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
1291         VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
1292         VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
1293         VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
1294     };
1295     for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1296         if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1297             compositeAlpha = compositeAlphaFlags[i];
1298             break;
1299         }
1300     }
1301
1302     VkSwapchainCreateInfoKHR swapchain_ci = {
1303         .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
1304         .pNext = NULL,
1305         .surface = demo->surface,
1306         .minImageCount = desiredNumOfSwapchainImages,
1307         .imageFormat = demo->format,
1308         .imageColorSpace = demo->color_space,
1309         .imageExtent =
1310             {
1311                 .width = swapchainExtent.width,
1312                 .height = swapchainExtent.height,
1313             },
1314         .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
1315         .preTransform = preTransform,
1316         .compositeAlpha = compositeAlpha,
1317         .imageArrayLayers = 1,
1318         .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
1319         .queueFamilyIndexCount = 0,
1320         .pQueueFamilyIndices = NULL,
1321         .presentMode = swapchainPresentMode,
1322         .oldSwapchain = oldSwapchain,
1323         .clipped = true,
1324     };
1325     uint32_t i;
1326     err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
1327     assert(!err);
1328
1329     // If we just re-created an existing swapchain, we should destroy the old
1330     // swapchain at this point.
1331     // Note: destroying the swapchain also cleans up all its associated
1332     // presentable images once the platform is done with them.
1333     if (oldSwapchain != VK_NULL_HANDLE) {
1334         demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
1335     }
1336
1337     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
1338     assert(!err);
1339
1340     VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
1341     assert(swapchainImages);
1342     err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
1343     assert(!err);
1344
1345     demo->swapchain_image_resources =
1346         (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
1347     assert(demo->swapchain_image_resources);
1348
1349     for (i = 0; i < demo->swapchainImageCount; i++) {
1350         VkImageViewCreateInfo color_image_view = {
1351             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1352             .pNext = NULL,
1353             .format = demo->format,
1354             .components =
1355                 {
1356                     .r = VK_COMPONENT_SWIZZLE_R,
1357                     .g = VK_COMPONENT_SWIZZLE_G,
1358                     .b = VK_COMPONENT_SWIZZLE_B,
1359                     .a = VK_COMPONENT_SWIZZLE_A,
1360                 },
1361             .subresourceRange =
1362                 {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1363             .viewType = VK_IMAGE_VIEW_TYPE_2D,
1364             .flags = 0,
1365         };
1366
1367         demo->swapchain_image_resources[i].image = swapchainImages[i];
1368
1369         color_image_view.image = demo->swapchain_image_resources[i].image;
1370
1371         err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view);
1372         assert(!err);
1373     }
1374
1375     if (demo->VK_GOOGLE_display_timing_enabled) {
1376         VkRefreshCycleDurationGOOGLE rc_dur;
1377         err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
1378         assert(!err);
1379         demo->refresh_duration = rc_dur.refreshDuration;
1380
1381         demo->syncd_with_actual_presents = false;
1382         // Initially target 1X the refresh duration:
1383         demo->target_IPD = demo->refresh_duration;
1384         demo->refresh_duration_multiplier = 1;
1385         demo->prev_desired_present_time = 0;
1386         demo->next_present_id = 1;
1387     }
1388
1389     if (NULL != presentModes) {
1390         free(presentModes);
1391     }
1392 }
1393
1394 static void demo_prepare_depth(struct demo *demo) {
1395     const VkFormat depth_format = VK_FORMAT_D16_UNORM;
1396     const VkImageCreateInfo image = {
1397         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1398         .pNext = NULL,
1399         .imageType = VK_IMAGE_TYPE_2D,
1400         .format = depth_format,
1401         .extent = {demo->width, demo->height, 1},
1402         .mipLevels = 1,
1403         .arrayLayers = 1,
1404         .samples = VK_SAMPLE_COUNT_1_BIT,
1405         .tiling = VK_IMAGE_TILING_OPTIMAL,
1406         .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
1407         .flags = 0,
1408     };
1409
1410     VkImageViewCreateInfo view = {
1411         .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1412         .pNext = NULL,
1413         .image = VK_NULL_HANDLE,
1414         .format = depth_format,
1415         .subresourceRange =
1416             {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
1417         .flags = 0,
1418         .viewType = VK_IMAGE_VIEW_TYPE_2D,
1419     };
1420
1421     VkMemoryRequirements mem_reqs;
1422     VkResult U_ASSERT_ONLY err;
1423     bool U_ASSERT_ONLY pass;
1424
1425     demo->depth.format = depth_format;
1426
1427     /* create image */
1428     err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
1429     assert(!err);
1430
1431     vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
1432     assert(!err);
1433
1434     demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1435     demo->depth.mem_alloc.pNext = NULL;
1436     demo->depth.mem_alloc.allocationSize = mem_reqs.size;
1437     demo->depth.mem_alloc.memoryTypeIndex = 0;
1438
1439     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1440                                        &demo->depth.mem_alloc.memoryTypeIndex);
1441     assert(pass);
1442
1443     /* allocate memory */
1444     err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
1445     assert(!err);
1446
1447     /* bind memory */
1448     err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
1449     assert(!err);
1450
1451     /* create image view */
1452     view.image = demo->depth.image;
1453     err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
1454     assert(!err);
1455 }
1456
1457 /* Convert ppm image data from header file into RGBA texture image */
1458 #include "lunarg.ppm.h"
1459 bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
1460     (void)filename;
1461     char *cPtr;
1462     cPtr = (char *)lunarg_ppm;
1463     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
1464         return false;
1465     }
1466     while (strncmp(cPtr++, "\n", 1))
1467         ;
1468     sscanf(cPtr, "%u %u", width, height);
1469     if (rgba_data == NULL) {
1470         return true;
1471     }
1472     while (strncmp(cPtr++, "\n", 1))
1473         ;
1474     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
1475         return false;
1476     }
1477     while (strncmp(cPtr++, "\n", 1))
1478         ;
1479     for (int y = 0; y < *height; y++) {
1480         uint8_t *rowPtr = rgba_data;
1481         for (int x = 0; x < *width; x++) {
1482             memcpy(rowPtr, cPtr, 3);
1483             rowPtr[3] = 255; /* Alpha of 1 */
1484             rowPtr += 4;
1485             cPtr += 3;
1486         }
1487         rgba_data += layout->rowPitch;
1488     }
1489     return true;
1490 }
1491
1492 static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
1493     int32_t tex_width;
1494     int32_t tex_height;
1495     VkResult U_ASSERT_ONLY err;
1496     bool U_ASSERT_ONLY pass;
1497
1498     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1499         ERR_EXIT("Failed to load textures", "Load Texture Failure");
1500     }
1501
1502     tex_obj->tex_width = tex_width;
1503     tex_obj->tex_height = tex_height;
1504
1505     const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1506                                                    .pNext = NULL,
1507                                                    .flags = 0,
1508                                                    .size = tex_width * tex_height * 4,
1509                                                    .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1510                                                    .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1511                                                    .queueFamilyIndexCount = 0,
1512                                                    .pQueueFamilyIndices = NULL};
1513
1514     err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
1515     assert(!err);
1516
1517     VkMemoryRequirements mem_reqs;
1518     vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
1519
1520     tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1521     tex_obj->mem_alloc.pNext = NULL;
1522     tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1523     tex_obj->mem_alloc.memoryTypeIndex = 0;
1524
1525     VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1526     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
1527     assert(pass);
1528
1529     err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1530     assert(!err);
1531
1532     /* bind memory */
1533     err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
1534     assert(!err);
1535
1536     VkSubresourceLayout layout;
1537     memset(&layout, 0, sizeof(layout));
1538     layout.rowPitch = tex_width * 4;
1539
1540     void *data;
1541     err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1542     assert(!err);
1543
1544     if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1545         fprintf(stderr, "Error loading texture: %s\n", filename);
1546     }
1547
1548     vkUnmapMemory(demo->device, tex_obj->mem);
1549 }
1550
1551 static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
1552                                        VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
1553     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1554     int32_t tex_width;
1555     int32_t tex_height;
1556     VkResult U_ASSERT_ONLY err;
1557     bool U_ASSERT_ONLY pass;
1558
1559     if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1560         ERR_EXIT("Failed to load textures", "Load Texture Failure");
1561     }
1562
1563     tex_obj->tex_width = tex_width;
1564     tex_obj->tex_height = tex_height;
1565
1566     const VkImageCreateInfo image_create_info = {
1567         .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1568         .pNext = NULL,
1569         .imageType = VK_IMAGE_TYPE_2D,
1570         .format = tex_format,
1571         .extent = {tex_width, tex_height, 1},
1572         .mipLevels = 1,
1573         .arrayLayers = 1,
1574         .samples = VK_SAMPLE_COUNT_1_BIT,
1575         .tiling = tiling,
1576         .usage = usage,
1577         .flags = 0,
1578         .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
1579     };
1580
1581     VkMemoryRequirements mem_reqs;
1582
1583     err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
1584     assert(!err);
1585
1586     vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
1587
1588     tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1589     tex_obj->mem_alloc.pNext = NULL;
1590     tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1591     tex_obj->mem_alloc.memoryTypeIndex = 0;
1592
1593     pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
1594     assert(pass);
1595
1596     /* allocate memory */
1597     err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1598     assert(!err);
1599
1600     /* bind memory */
1601     err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
1602     assert(!err);
1603
1604     if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
1605         const VkImageSubresource subres = {
1606             .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
1607             .mipLevel = 0,
1608             .arrayLayer = 0,
1609         };
1610         VkSubresourceLayout layout;
1611         void *data;
1612
1613         vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
1614
1615         err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1616         assert(!err);
1617
1618         if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1619             fprintf(stderr, "Error loading texture: %s\n", filename);
1620         }
1621
1622         vkUnmapMemory(demo->device, tex_obj->mem);
1623     }
1624
1625     tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1626 }
1627
1628 static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
1629     /* clean up staging resources */
1630     vkFreeMemory(demo->device, tex_objs->mem, NULL);
1631     if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
1632     if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
1633 }
1634
1635 static void demo_prepare_textures(struct demo *demo) {
1636     const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
1637     VkFormatProperties props;
1638     uint32_t i;
1639
1640     vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
1641
1642     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1643         VkResult U_ASSERT_ONLY err;
1644
1645         if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
1646             /* Device can texture using linear textures */
1647             demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
1648                                        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
1649             // Nothing in the pipeline needs to be complete to start, and don't allow fragment
1650             // shader to run until layout transition completes
1651             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1652                                   demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1653                                   VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1654             demo->staging_texture.image = 0;
1655         } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
1656             /* Must use staging buffer to copy linear texture to optimized */
1657
1658             memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
1659             demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
1660
1661             demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
1662                                        (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1663                                        VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1664
1665             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1666                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
1667                                   VK_PIPELINE_STAGE_TRANSFER_BIT);
1668
1669             VkBufferImageCopy copy_region = {
1670                 .bufferOffset = 0,
1671                 .bufferRowLength = demo->staging_texture.tex_width,
1672                 .bufferImageHeight = demo->staging_texture.tex_height,
1673                 .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
1674                 .imageOffset = {0, 0, 0},
1675                 .imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
1676             };
1677
1678             vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
1679                                    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);
1680
1681             demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1682                                   demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
1683                                   VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
1684
1685         } else {
1686             /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
1687             assert(!"No support for R8G8B8A8_UNORM as texture image format");
1688         }
1689
1690         const VkSamplerCreateInfo sampler = {
1691             .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
1692             .pNext = NULL,
1693             .magFilter = VK_FILTER_NEAREST,
1694             .minFilter = VK_FILTER_NEAREST,
1695             .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
1696             .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1697             .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1698             .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1699             .mipLodBias = 0.0f,
1700             .anisotropyEnable = VK_FALSE,
1701             .maxAnisotropy = 1,
1702             .compareOp = VK_COMPARE_OP_NEVER,
1703             .minLod = 0.0f,
1704             .maxLod = 0.0f,
1705             .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
1706             .unnormalizedCoordinates = VK_FALSE,
1707         };
1708
1709         VkImageViewCreateInfo view = {
1710             .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
1711             .pNext = NULL,
1712             .image = VK_NULL_HANDLE,
1713             .viewType = VK_IMAGE_VIEW_TYPE_2D,
1714             .format = tex_format,
1715             .components =
1716                 {
1717                     VK_COMPONENT_SWIZZLE_R,
1718                     VK_COMPONENT_SWIZZLE_G,
1719                     VK_COMPONENT_SWIZZLE_B,
1720                     VK_COMPONENT_SWIZZLE_A,
1721                 },
1722             .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
1723             .flags = 0,
1724         };
1725
1726         /* create sampler */
1727         err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
1728         assert(!err);
1729
1730         /* create image view */
1731         view.image = demo->textures[i].image;
1732         err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
1733         assert(!err);
1734     }
1735 }
1736
1737 void demo_prepare_cube_data_buffers(struct demo *demo) {
1738     VkBufferCreateInfo buf_info;
1739     VkMemoryRequirements mem_reqs;
1740     VkMemoryAllocateInfo mem_alloc;
1741     uint8_t *pData;
1742     mat4x4 MVP, VP;
1743     VkResult U_ASSERT_ONLY err;
1744     bool U_ASSERT_ONLY pass;
1745     struct vktexcube_vs_uniform data;
1746
1747     mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
1748     mat4x4_mul(MVP, VP, demo->model_matrix);
1749     memcpy(data.mvp, MVP, sizeof(MVP));
1750     //    dumpMatrix("MVP", MVP);
1751
1752     for (unsigned int i = 0; i < 12 * 3; i++) {
1753         data.position[i][0] = g_vertex_buffer_data[i * 3];
1754         data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1755         data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1756         data.position[i][3] = 1.0f;
1757         data.attr[i][0] = g_uv_buffer_data[2 * i];
1758         data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1759         data.attr[i][2] = 0;
1760         data.attr[i][3] = 0;
1761     }
1762
1763     memset(&buf_info, 0, sizeof(buf_info));
1764     buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1765     buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
1766     buf_info.size = sizeof(data);
1767
1768     for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
1769         err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer);
1770         assert(!err);
1771
1772         vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs);
1773
1774         mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1775         mem_alloc.pNext = NULL;
1776         mem_alloc.allocationSize = mem_reqs.size;
1777         mem_alloc.memoryTypeIndex = 0;
1778
1779         pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
1780                                            VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1781                                            &mem_alloc.memoryTypeIndex);
1782         assert(pass);
1783
1784         err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory);
1785         assert(!err);
1786
1787         err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0, (void **)&pData);
1788         assert(!err);
1789
1790         memcpy(pData, &data, sizeof data);
1791
1792         vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
1793
1794         err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer,
1795                                  demo->swapchain_image_resources[i].uniform_memory, 0);
1796         assert(!err);
1797     }
1798 }
1799
1800 static void demo_prepare_descriptor_layout(struct demo *demo) {
1801     const VkDescriptorSetLayoutBinding layout_bindings[2] = {
1802         [0] =
1803             {
1804                 .binding = 0,
1805                 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1806                 .descriptorCount = 1,
1807                 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
1808                 .pImmutableSamplers = NULL,
1809             },
1810         [1] =
1811             {
1812                 .binding = 1,
1813                 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1814                 .descriptorCount = DEMO_TEXTURE_COUNT,
1815                 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
1816                 .pImmutableSamplers = NULL,
1817             },
1818     };
1819     const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
1820         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
1821         .pNext = NULL,
1822         .bindingCount = 2,
1823         .pBindings = layout_bindings,
1824     };
1825     VkResult U_ASSERT_ONLY err;
1826
1827     err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
1828     assert(!err);
1829
1830     const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
1831         .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1832         .pNext = NULL,
1833         .setLayoutCount = 1,
1834         .pSetLayouts = &demo->desc_layout,
1835     };
1836
1837     err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
1838     assert(!err);
1839 }
1840
1841 static void demo_prepare_render_pass(struct demo *demo) {
1842     // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1843     // because at the start of the renderpass, we don't care about their contents.
1844     // At the start of the subpass, the color attachment's layout will be transitioned
1845     // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1846     // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.  At the end of
1847     // the renderpass, the color attachment's layout will be transitioned to
1848     // LAYOUT_PRESENT_SRC_KHR to be ready to present.  This is all done as part of
1849     // the renderpass, no barriers are necessary.
1850     const VkAttachmentDescription attachments[2] = {
1851         [0] =
1852             {
1853                 .format = demo->format,
1854                 .flags = 0,
1855                 .samples = VK_SAMPLE_COUNT_1_BIT,
1856                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1857                 .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
1858                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1859                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1860                 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1861                 .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1862             },
1863         [1] =
1864             {
1865                 .format = demo->depth.format,
1866                 .flags = 0,
1867                 .samples = VK_SAMPLE_COUNT_1_BIT,
1868                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1869                 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1870                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1871                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1872                 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1873                 .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1874             },
1875     };
1876     const VkAttachmentReference color_reference = {
1877         .attachment = 0,
1878         .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
1879     };
1880     const VkAttachmentReference depth_reference = {
1881         .attachment = 1,
1882         .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1883     };
1884     const VkSubpassDescription subpass = {
1885         .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
1886         .flags = 0,
1887         .inputAttachmentCount = 0,
1888         .pInputAttachments = NULL,
1889         .colorAttachmentCount = 1,
1890         .pColorAttachments = &color_reference,
1891         .pResolveAttachments = NULL,
1892         .pDepthStencilAttachment = &depth_reference,
1893         .preserveAttachmentCount = 0,
1894         .pPreserveAttachments = NULL,
1895     };
1896     const VkRenderPassCreateInfo rp_info = {
1897         .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
1898         .pNext = NULL,
1899         .flags = 0,
1900         .attachmentCount = 2,
1901         .pAttachments = attachments,
1902         .subpassCount = 1,
1903         .pSubpasses = &subpass,
1904         .dependencyCount = 0,
1905         .pDependencies = NULL,
1906     };
1907     VkResult U_ASSERT_ONLY err;
1908
1909     err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
1910     assert(!err);
1911 }
1912
1913 static VkShaderModule demo_prepare_shader_module(struct demo *demo, const uint32_t *code, size_t size) {
1914     VkShaderModule module;
1915     VkShaderModuleCreateInfo moduleCreateInfo;
1916     VkResult U_ASSERT_ONLY err;
1917
1918     moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1919     moduleCreateInfo.pNext = NULL;
1920     moduleCreateInfo.flags = 0;
1921     moduleCreateInfo.codeSize = size;
1922     moduleCreateInfo.pCode = code;
1923
1924     err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
1925     assert(!err);
1926
1927     return module;
1928 }
1929
1930 static void demo_prepare_vs(struct demo *demo) {
1931     const uint32_t vs_code[] = {
1932 #include "cube.vert.inc"
1933     };
1934     demo->vert_shader_module = demo_prepare_shader_module(demo, vs_code, sizeof(vs_code));
1935 }
1936
1937 static void demo_prepare_fs(struct demo *demo) {
1938     const uint32_t fs_code[] = {
1939 #include "cube.frag.inc"
1940     };
1941     demo->frag_shader_module = demo_prepare_shader_module(demo, fs_code, sizeof(fs_code));
1942 }
1943
1944 static void demo_prepare_pipeline(struct demo *demo) {
1945     VkGraphicsPipelineCreateInfo pipeline;
1946     VkPipelineCacheCreateInfo pipelineCache;
1947     VkPipelineVertexInputStateCreateInfo vi;
1948     VkPipelineInputAssemblyStateCreateInfo ia;
1949     VkPipelineRasterizationStateCreateInfo rs;
1950     VkPipelineColorBlendStateCreateInfo cb;
1951     VkPipelineDepthStencilStateCreateInfo ds;
1952     VkPipelineViewportStateCreateInfo vp;
1953     VkPipelineMultisampleStateCreateInfo ms;
1954     VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE];
1955     VkPipelineDynamicStateCreateInfo dynamicState;
1956     VkResult U_ASSERT_ONLY err;
1957
1958     memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
1959     memset(&dynamicState, 0, sizeof dynamicState);
1960     dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1961     dynamicState.pDynamicStates = dynamicStateEnables;
1962
1963     memset(&pipeline, 0, sizeof(pipeline));
1964     pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1965     pipeline.layout = demo->pipeline_layout;
1966
1967     memset(&vi, 0, sizeof(vi));
1968     vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1969
1970     memset(&ia, 0, sizeof(ia));
1971     ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1972     ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1973
1974     memset(&rs, 0, sizeof(rs));
1975     rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1976     rs.polygonMode = VK_POLYGON_MODE_FILL;
1977     rs.cullMode = VK_CULL_MODE_BACK_BIT;
1978     rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1979     rs.depthClampEnable = VK_FALSE;
1980     rs.rasterizerDiscardEnable = VK_FALSE;
1981     rs.depthBiasEnable = VK_FALSE;
1982     rs.lineWidth = 1.0f;
1983
1984     memset(&cb, 0, sizeof(cb));
1985     cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1986     VkPipelineColorBlendAttachmentState att_state[1];
1987     memset(att_state, 0, sizeof(att_state));
1988     att_state[0].colorWriteMask = 0xf;
1989     att_state[0].blendEnable = VK_FALSE;
1990     cb.attachmentCount = 1;
1991     cb.pAttachments = att_state;
1992
1993     memset(&vp, 0, sizeof(vp));
1994     vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1995     vp.viewportCount = 1;
1996     dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
1997     vp.scissorCount = 1;
1998     dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
1999
2000     memset(&ds, 0, sizeof(ds));
2001     ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
2002     ds.depthTestEnable = VK_TRUE;
2003     ds.depthWriteEnable = VK_TRUE;
2004     ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
2005     ds.depthBoundsTestEnable = VK_FALSE;
2006     ds.back.failOp = VK_STENCIL_OP_KEEP;
2007     ds.back.passOp = VK_STENCIL_OP_KEEP;
2008     ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
2009     ds.stencilTestEnable = VK_FALSE;
2010     ds.front = ds.back;
2011
2012     memset(&ms, 0, sizeof(ms));
2013     ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
2014     ms.pSampleMask = NULL;
2015     ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
2016
2017     demo_prepare_vs(demo);
2018     demo_prepare_fs(demo);
2019
2020     // Two stages: vs and fs
2021     VkPipelineShaderStageCreateInfo shaderStages[2];
2022     memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
2023
2024     shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2025     shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
2026     shaderStages[0].module = demo->vert_shader_module;
2027     shaderStages[0].pName = "main";
2028
2029     shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2030     shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
2031     shaderStages[1].module = demo->frag_shader_module;
2032     shaderStages[1].pName = "main";
2033
2034     memset(&pipelineCache, 0, sizeof(pipelineCache));
2035     pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2036
2037     err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
2038     assert(!err);
2039
2040     pipeline.pVertexInputState = &vi;
2041     pipeline.pInputAssemblyState = &ia;
2042     pipeline.pRasterizationState = &rs;
2043     pipeline.pColorBlendState = &cb;
2044     pipeline.pMultisampleState = &ms;
2045     pipeline.pViewportState = &vp;
2046     pipeline.pDepthStencilState = &ds;
2047     pipeline.stageCount = ARRAY_SIZE(shaderStages);
2048     pipeline.pStages = shaderStages;
2049     pipeline.renderPass = demo->render_pass;
2050     pipeline.pDynamicState = &dynamicState;
2051
2052     pipeline.renderPass = demo->render_pass;
2053
2054     err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
2055     assert(!err);
2056
2057     vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
2058     vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
2059 }
2060
2061 static void demo_prepare_descriptor_pool(struct demo *demo) {
2062     const VkDescriptorPoolSize type_counts[2] = {
2063         [0] =
2064             {
2065                 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
2066                 .descriptorCount = demo->swapchainImageCount,
2067             },
2068         [1] =
2069             {
2070                 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2071                 .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT,
2072             },
2073     };
2074     const VkDescriptorPoolCreateInfo descriptor_pool = {
2075         .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
2076         .pNext = NULL,
2077         .maxSets = demo->swapchainImageCount,
2078         .poolSizeCount = 2,
2079         .pPoolSizes = type_counts,
2080     };
2081     VkResult U_ASSERT_ONLY err;
2082
2083     err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
2084     assert(!err);
2085 }
2086
2087 static void demo_prepare_descriptor_set(struct demo *demo) {
2088     VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
2089     VkWriteDescriptorSet writes[2];
2090     VkResult U_ASSERT_ONLY err;
2091
2092     VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
2093                                               .pNext = NULL,
2094                                               .descriptorPool = demo->desc_pool,
2095                                               .descriptorSetCount = 1,
2096                                               .pSetLayouts = &demo->desc_layout};
2097
2098     VkDescriptorBufferInfo buffer_info;
2099     buffer_info.offset = 0;
2100     buffer_info.range = sizeof(struct vktexcube_vs_uniform);
2101
2102     memset(&tex_descs, 0, sizeof(tex_descs));
2103     for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2104         tex_descs[i].sampler = demo->textures[i].sampler;
2105         tex_descs[i].imageView = demo->textures[i].view;
2106         tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
2107     }
2108
2109     memset(&writes, 0, sizeof(writes));
2110
2111     writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2112     writes[0].descriptorCount = 1;
2113     writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
2114     writes[0].pBufferInfo = &buffer_info;
2115
2116     writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
2117     writes[1].dstBinding = 1;
2118     writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
2119     writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
2120     writes[1].pImageInfo = tex_descs;
2121
2122     for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
2123         err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->swapchain_image_resources[i].descriptor_set);
2124         assert(!err);
2125         buffer_info.buffer = demo->swapchain_image_resources[i].uniform_buffer;
2126         writes[0].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2127         writes[1].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2128         vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
2129     }
2130 }
2131
2132 static void demo_prepare_framebuffers(struct demo *demo) {
2133     VkImageView attachments[2];
2134     attachments[1] = demo->depth.view;
2135
2136     const VkFramebufferCreateInfo fb_info = {
2137         .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
2138         .pNext = NULL,
2139         .renderPass = demo->render_pass,
2140         .attachmentCount = 2,
2141         .pAttachments = attachments,
2142         .width = demo->width,
2143         .height = demo->height,
2144         .layers = 1,
2145     };
2146     VkResult U_ASSERT_ONLY err;
2147     uint32_t i;
2148
2149     for (i = 0; i < demo->swapchainImageCount; i++) {
2150         attachments[0] = demo->swapchain_image_resources[i].view;
2151         err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer);
2152         assert(!err);
2153     }
2154 }
2155
2156 static void demo_prepare(struct demo *demo) {
2157     VkResult U_ASSERT_ONLY err;
2158     if (demo->cmd_pool == VK_NULL_HANDLE) {
2159         const VkCommandPoolCreateInfo cmd_pool_info = {
2160             .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2161             .pNext = NULL,
2162             .queueFamilyIndex = demo->graphics_queue_family_index,
2163             .flags = 0,
2164         };
2165         err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
2166         assert(!err);
2167     }
2168
2169     const VkCommandBufferAllocateInfo cmd = {
2170         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2171         .pNext = NULL,
2172         .commandPool = demo->cmd_pool,
2173         .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2174         .commandBufferCount = 1,
2175     };
2176     err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
2177     assert(!err);
2178     VkCommandBufferBeginInfo cmd_buf_info = {
2179         .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2180         .pNext = NULL,
2181         .flags = 0,
2182         .pInheritanceInfo = NULL,
2183     };
2184     err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
2185     assert(!err);
2186
2187     demo_prepare_buffers(demo);
2188
2189     if (demo->is_minimized) {
2190         demo->prepared = false;
2191         return;
2192     }
2193
2194     demo_prepare_depth(demo);
2195     demo_prepare_textures(demo);
2196     demo_prepare_cube_data_buffers(demo);
2197
2198     demo_prepare_descriptor_layout(demo);
2199     demo_prepare_render_pass(demo);
2200     demo_prepare_pipeline(demo);
2201
2202     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2203         err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd);
2204         assert(!err);
2205     }
2206
2207     if (demo->separate_present_queue) {
2208         const VkCommandPoolCreateInfo present_cmd_pool_info = {
2209             .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2210             .pNext = NULL,
2211             .queueFamilyIndex = demo->present_queue_family_index,
2212             .flags = 0,
2213         };
2214         err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
2215         assert(!err);
2216         const VkCommandBufferAllocateInfo present_cmd_info = {
2217             .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2218             .pNext = NULL,
2219             .commandPool = demo->present_cmd_pool,
2220             .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2221             .commandBufferCount = 1,
2222         };
2223         for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2224             err = vkAllocateCommandBuffers(demo->device, &present_cmd_info,
2225                                            &demo->swapchain_image_resources[i].graphics_to_present_cmd);
2226             assert(!err);
2227             demo_build_image_ownership_cmd(demo, i);
2228         }
2229     }
2230
2231     demo_prepare_descriptor_pool(demo);
2232     demo_prepare_descriptor_set(demo);
2233
2234     demo_prepare_framebuffers(demo);
2235
2236     for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
2237         demo->current_buffer = i;
2238         demo_draw_build_cmd(demo, demo->swapchain_image_resources[i].cmd);
2239     }
2240
2241     /*
2242      * Prepare functions above may generate pipeline commands
2243      * that need to be flushed before beginning the render loop.
2244      */
2245     demo_flush_init_cmd(demo);
2246     if (demo->staging_texture.buffer) {
2247         demo_destroy_texture(demo, &demo->staging_texture);
2248     }
2249
2250     demo->current_buffer = 0;
2251     demo->prepared = true;
2252 }
2253
2254 static void demo_cleanup(struct demo *demo) {
2255     uint32_t i;
2256
2257     demo->prepared = false;
2258     vkDeviceWaitIdle(demo->device);
2259
2260     // Wait for fences from present operations
2261     for (i = 0; i < FRAME_LAG; i++) {
2262         vkWaitForFences(demo->device, 1, &demo->fences[i], VK_TRUE, UINT64_MAX);
2263         vkDestroyFence(demo->device, demo->fences[i], NULL);
2264         vkDestroySemaphore(demo->device, demo->image_acquired_semaphores[i], NULL);
2265         vkDestroySemaphore(demo->device, demo->draw_complete_semaphores[i], NULL);
2266         if (demo->separate_present_queue) {
2267             vkDestroySemaphore(demo->device, demo->image_ownership_semaphores[i], NULL);
2268         }
2269     }
2270
2271     // If the window is currently minimized, demo_resize has already done some cleanup for us.
2272     if (!demo->is_minimized) {
2273         for (i = 0; i < demo->swapchainImageCount; i++) {
2274             vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2275         }
2276         vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2277
2278         vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2279         vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2280         vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2281         vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2282         vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2283
2284         for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2285             vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2286             vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2287             vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2288             vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2289         }
2290         demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
2291
2292         vkDestroyImageView(demo->device, demo->depth.view, NULL);
2293         vkDestroyImage(demo->device, demo->depth.image, NULL);
2294         vkFreeMemory(demo->device, demo->depth.mem, NULL);
2295
2296         for (i = 0; i < demo->swapchainImageCount; i++) {
2297             vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2298             vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2299             vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2300             vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2301         }
2302         free(demo->swapchain_image_resources);
2303         free(demo->queue_props);
2304         vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2305
2306         if (demo->separate_present_queue) {
2307             vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2308         }
2309     }
2310     vkDeviceWaitIdle(demo->device);
2311     vkDestroyDevice(demo->device, NULL);
2312     if (demo->validate) {
2313         demo->DestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
2314     }
2315     vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
2316
2317 #if defined(VK_USE_PLATFORM_XLIB_KHR)
2318     XDestroyWindow(demo->display, demo->xlib_window);
2319     XCloseDisplay(demo->display);
2320 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2321     xcb_destroy_window(demo->connection, demo->xcb_window);
2322     xcb_disconnect(demo->connection);
2323     free(demo->atom_wm_delete_window);
2324 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2325     wl_keyboard_destroy(demo->keyboard);
2326     wl_pointer_destroy(demo->pointer);
2327     wl_seat_destroy(demo->seat);
2328     wl_shell_surface_destroy(demo->shell_surface);
2329     wl_surface_destroy(demo->window);
2330     wl_shell_destroy(demo->shell);
2331     wl_compositor_destroy(demo->compositor);
2332     wl_registry_destroy(demo->registry);
2333     wl_display_disconnect(demo->display);
2334 #elif defined(VK_USE_PLATFORM_MIR_KHR)
2335 #endif
2336
2337     vkDestroyInstance(demo->inst, NULL);
2338 }
2339
2340 static void demo_resize(struct demo *demo) {
2341     uint32_t i;
2342
2343     // Don't react to resize until after first initialization.
2344     if (!demo->prepared) {
2345         if (demo->is_minimized) {
2346             demo_prepare(demo);
2347         }
2348         return;
2349     }
2350     // In order to properly resize the window, we must re-create the swapchain
2351     // AND redo the command buffers, etc.
2352     //
2353     // First, perform part of the demo_cleanup() function:
2354     demo->prepared = false;
2355     vkDeviceWaitIdle(demo->device);
2356
2357     for (i = 0; i < demo->swapchainImageCount; i++) {
2358         vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2359     }
2360     vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
2361
2362     vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2363     vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2364     vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2365     vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2366     vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
2367
2368     for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2369         vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2370         vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2371         vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2372         vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2373     }
2374
2375     vkDestroyImageView(demo->device, demo->depth.view, NULL);
2376     vkDestroyImage(demo->device, demo->depth.image, NULL);
2377     vkFreeMemory(demo->device, demo->depth.mem, NULL);
2378
2379     for (i = 0; i < demo->swapchainImageCount; i++) {
2380         vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2381         vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2382         vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
2383         vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2384     }
2385     vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
2386     demo->cmd_pool = VK_NULL_HANDLE;
2387     if (demo->separate_present_queue) {
2388         vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2389     }
2390     free(demo->swapchain_image_resources);
2391
2392     // Second, re-perform the demo_prepare() function, which will re-create the
2393     // swapchain:
2394     demo_prepare(demo);
2395 }
2396
2397 // On MS-Windows, make this a global, so it's available to WndProc()
2398 struct demo demo;
2399
2400 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2401 static void demo_run(struct demo *demo) {
2402     if (!demo->prepared) return;
2403
2404     demo_draw(demo);
2405     demo->curFrame++;
2406     if (demo->frameCount != INT_MAX && demo->curFrame == demo->frameCount) {
2407         PostQuitMessage(validation_error);
2408     }
2409 }
2410
2411 // MS-Windows event handling function:
2412 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2413     switch (uMsg) {
2414         case WM_CLOSE:
2415             PostQuitMessage(validation_error);
2416             break;
2417         case WM_PAINT:
2418             // The validation callback calls MessageBox which can generate paint
2419             // events - don't make more Vulkan calls if we got here from the
2420             // callback
2421             if (!in_callback) {
2422                 demo_run(&demo);
2423             }
2424             break;
2425         case WM_GETMINMAXINFO:  // set window's minimum size
2426             ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2427             return 0;
2428         case WM_SIZE:
2429             // Resize the application to the new window size, except when
2430             // it was minimized. Vulkan doesn't support images or swapchains
2431             // with width=0 and height=0.
2432             if (wParam != SIZE_MINIMIZED) {
2433                 demo.width = lParam & 0xffff;
2434                 demo.height = (lParam & 0xffff0000) >> 16;
2435                 demo_resize(&demo);
2436             }
2437             break;
2438         default:
2439             break;
2440     }
2441     return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2442 }
2443
2444 static void demo_create_window(struct demo *demo) {
2445     WNDCLASSEX win_class;
2446
2447     // Initialize the window class structure:
2448     win_class.cbSize = sizeof(WNDCLASSEX);
2449     win_class.style = CS_HREDRAW | CS_VREDRAW;
2450     win_class.lpfnWndProc = WndProc;
2451     win_class.cbClsExtra = 0;
2452     win_class.cbWndExtra = 0;
2453     win_class.hInstance = demo->connection;  // hInstance
2454     win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2455     win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
2456     win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2457     win_class.lpszMenuName = NULL;
2458     win_class.lpszClassName = demo->name;
2459     win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
2460     // Register window class:
2461     if (!RegisterClassEx(&win_class)) {
2462         // It didn't work, so try to give a useful error:
2463         printf("Unexpected error trying to start the application!\n");
2464         fflush(stdout);
2465         exit(1);
2466     }
2467     // Create window with the registered class:
2468     RECT wr = {0, 0, demo->width, demo->height};
2469     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2470     demo->window = CreateWindowEx(0,
2471                                   demo->name,            // class name
2472                                   demo->name,            // app name
2473                                   WS_OVERLAPPEDWINDOW |  // window style
2474                                       WS_VISIBLE | WS_SYSMENU,
2475                                   100, 100,            // x/y coords
2476                                   wr.right - wr.left,  // width
2477                                   wr.bottom - wr.top,  // height
2478                                   NULL,                // handle to parent
2479                                   NULL,                // handle to menu
2480                                   demo->connection,    // hInstance
2481                                   NULL);               // no extra parameters
2482     if (!demo->window) {
2483         // It didn't work, so try to give a useful error:
2484         printf("Cannot create a window in which to draw!\n");
2485         fflush(stdout);
2486         exit(1);
2487     }
2488     // Window client area size must be at least 1 pixel high, to prevent crash.
2489     demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2490     demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2491 }
2492 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2493 static void demo_create_xlib_window(struct demo *demo) {
2494     const char *display_envar = getenv("DISPLAY");
2495     if (display_envar == NULL || display_envar[0] == '\0') {
2496         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2497         fflush(stdout);
2498         exit(1);
2499     }
2500
2501     XInitThreads();
2502     demo->display = XOpenDisplay(NULL);
2503     long visualMask = VisualScreenMask;
2504     int numberOfVisuals;
2505     XVisualInfo vInfoTemplate = {};
2506     vInfoTemplate.screen = DefaultScreen(demo->display);
2507     XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals);
2508
2509     Colormap colormap =
2510         XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2511
2512     XSetWindowAttributes windowAttributes = {};
2513     windowAttributes.colormap = colormap;
2514     windowAttributes.background_pixel = 0xFFFFFFFF;
2515     windowAttributes.border_pixel = 0;
2516     windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2517
2518     demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width,
2519                                       demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
2520                                       CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2521
2522     XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
2523     XMapWindow(demo->display, demo->xlib_window);
2524     XFlush(demo->display);
2525     demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
2526 }
2527 static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
2528     switch (event->type) {
2529         case ClientMessage:
2530             if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
2531             break;
2532         case KeyPress:
2533             switch (event->xkey.keycode) {
2534                 case 0x9:  // Escape
2535                     demo->quit = true;
2536                     break;
2537                 case 0x71:  // left arrow key
2538                     demo->spin_angle -= demo->spin_increment;
2539                     break;
2540                 case 0x72:  // right arrow key
2541                     demo->spin_angle += demo->spin_increment;
2542                     break;
2543                 case 0x41:  // space bar
2544                     demo->pause = !demo->pause;
2545                     break;
2546             }
2547             break;
2548         case ConfigureNotify:
2549             if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
2550                 demo->width = event->xconfigure.width;
2551                 demo->height = event->xconfigure.height;
2552                 demo_resize(demo);
2553             }
2554             break;
2555         default:
2556             break;
2557     }
2558 }
2559
2560 static void demo_run_xlib(struct demo *demo) {
2561     while (!demo->quit) {
2562         XEvent event;
2563
2564         if (demo->pause) {
2565             XNextEvent(demo->display, &event);
2566             demo_handle_xlib_event(demo, &event);
2567         }
2568         while (XPending(demo->display) > 0) {
2569             XNextEvent(demo->display, &event);
2570             demo_handle_xlib_event(demo, &event);
2571         }
2572
2573         demo_draw(demo);
2574         demo->curFrame++;
2575         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2576     }
2577 }
2578 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2579 static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
2580     uint8_t event_code = event->response_type & 0x7f;
2581     switch (event_code) {
2582         case XCB_EXPOSE:
2583             // TODO: Resize window
2584             break;
2585         case XCB_CLIENT_MESSAGE:
2586             if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
2587                 demo->quit = true;
2588             }
2589             break;
2590         case XCB_KEY_RELEASE: {
2591             const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2592
2593             switch (key->detail) {
2594                 case 0x9:  // Escape
2595                     demo->quit = true;
2596                     break;
2597                 case 0x71:  // left arrow key
2598                     demo->spin_angle -= demo->spin_increment;
2599                     break;
2600                 case 0x72:  // right arrow key
2601                     demo->spin_angle += demo->spin_increment;
2602                     break;
2603                 case 0x41:  // space bar
2604                     demo->pause = !demo->pause;
2605                     break;
2606             }
2607         } break;
2608         case XCB_CONFIGURE_NOTIFY: {
2609             const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2610             if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
2611                 demo->width = cfg->width;
2612                 demo->height = cfg->height;
2613                 demo_resize(demo);
2614             }
2615         } break;
2616         default:
2617             break;
2618     }
2619 }
2620
2621 static void demo_run_xcb(struct demo *demo) {
2622     xcb_flush(demo->connection);
2623
2624     while (!demo->quit) {
2625         xcb_generic_event_t *event;
2626
2627         if (demo->pause) {
2628             event = xcb_wait_for_event(demo->connection);
2629         } else {
2630             event = xcb_poll_for_event(demo->connection);
2631         }
2632         while (event) {
2633             demo_handle_xcb_event(demo, event);
2634             free(event);
2635             event = xcb_poll_for_event(demo->connection);
2636         }
2637
2638         demo_draw(demo);
2639         demo->curFrame++;
2640         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2641     }
2642 }
2643
2644 static void demo_create_xcb_window(struct demo *demo) {
2645     uint32_t value_mask, value_list[32];
2646
2647     demo->xcb_window = xcb_generate_id(demo->connection);
2648
2649     value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2650     value_list[0] = demo->screen->black_pixel;
2651     value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2652
2653     xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
2654                       0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
2655
2656     /* Magic code that will send notification when window is destroyed */
2657     xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
2658     xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
2659
2660     xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
2661     demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
2662
2663     xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
2664                         &(*demo->atom_wm_delete_window).atom);
2665     free(reply);
2666
2667     xcb_map_window(demo->connection, demo->xcb_window);
2668
2669     // Force the x/y coordinates to 100,100 results are identical in consecutive
2670     // runs
2671     const uint32_t coords[] = {100, 100};
2672     xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2673 }
2674 // VK_USE_PLATFORM_XCB_KHR
2675 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2676 static void demo_run(struct demo *demo) {
2677     while (!demo->quit) {
2678         if (demo->pause) {
2679             wl_display_dispatch(demo->display);  // block and wait for input
2680         } else {
2681             wl_display_dispatch_pending(demo->display);  // don't block
2682             demo_draw(demo);
2683             demo->curFrame++;
2684             if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2685         }
2686     }
2687 }
2688
2689 static void handle_ping(void *data UNUSED, struct wl_shell_surface *shell_surface, uint32_t serial) {
2690     wl_shell_surface_pong(shell_surface, serial);
2691 }
2692
2693 static void handle_configure(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED, uint32_t edges UNUSED,
2694                              int32_t width UNUSED, int32_t height UNUSED) {}
2695
2696 static void handle_popup_done(void *data UNUSED, struct wl_shell_surface *shell_surface UNUSED) {}
2697
2698 static const struct wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
2699
2700 static void demo_create_window(struct demo *demo) {
2701     demo->window = wl_compositor_create_surface(demo->compositor);
2702     if (!demo->window) {
2703         printf("Can not create wayland_surface from compositor!\n");
2704         fflush(stdout);
2705         exit(1);
2706     }
2707
2708     demo->shell_surface = wl_shell_get_shell_surface(demo->shell, demo->window);
2709     if (!demo->shell_surface) {
2710         printf("Can not get shell_surface from wayland_surface!\n");
2711         fflush(stdout);
2712         exit(1);
2713     }
2714     wl_shell_surface_add_listener(demo->shell_surface, &shell_surface_listener, demo);
2715     wl_shell_surface_set_toplevel(demo->shell_surface);
2716     wl_shell_surface_set_title(demo->shell_surface, APP_SHORT_NAME);
2717 }
2718 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
2719 static void demo_run(struct demo *demo) {
2720     if (!demo->prepared) return;
2721
2722     demo_draw(demo);
2723     demo->curFrame++;
2724 }
2725 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
2726 static void demo_run(struct demo *demo) {
2727     demo_draw(demo);
2728     demo->curFrame++;
2729     if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2730         demo->quit = TRUE;
2731     }
2732 }
2733 #elif defined(VK_USE_PLATFORM_MIR_KHR)
2734 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2735 static VkResult demo_create_display_surface(struct demo *demo) {
2736     VkResult U_ASSERT_ONLY err;
2737     uint32_t display_count;
2738     uint32_t mode_count;
2739     uint32_t plane_count;
2740     VkDisplayPropertiesKHR display_props;
2741     VkDisplayKHR display;
2742     VkDisplayModePropertiesKHR mode_props;
2743     VkDisplayPlanePropertiesKHR *plane_props;
2744     VkBool32 found_plane = VK_FALSE;
2745     uint32_t plane_index;
2746     VkExtent2D image_extent;
2747     VkDisplaySurfaceCreateInfoKHR create_info;
2748
2749     // Get the first display
2750     err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, NULL);
2751     assert(!err);
2752
2753     if (display_count == 0) {
2754         printf("Cannot find any display!\n");
2755         fflush(stdout);
2756         exit(1);
2757     }
2758
2759     display_count = 1;
2760     err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
2761     assert(!err || (err == VK_INCOMPLETE));
2762
2763     display = display_props.display;
2764
2765     // Get the first mode of the display
2766     err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
2767     assert(!err);
2768
2769     if (mode_count == 0) {
2770         printf("Cannot find any mode for the display!\n");
2771         fflush(stdout);
2772         exit(1);
2773     }
2774
2775     mode_count = 1;
2776     err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
2777     assert(!err || (err == VK_INCOMPLETE));
2778
2779     // Get the list of planes
2780     err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
2781     assert(!err);
2782
2783     if (plane_count == 0) {
2784         printf("Cannot find any plane!\n");
2785         fflush(stdout);
2786         exit(1);
2787     }
2788
2789     plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
2790     assert(plane_props);
2791
2792     err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
2793     assert(!err);
2794
2795     // Find a plane compatible with the display
2796     for (plane_index = 0; plane_index < plane_count; plane_index++) {
2797         uint32_t supported_count;
2798         VkDisplayKHR *supported_displays;
2799
2800         // Disqualify planes that are bound to a different display
2801         if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
2802             continue;
2803         }
2804
2805         err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
2806         assert(!err);
2807
2808         if (supported_count == 0) {
2809             continue;
2810         }
2811
2812         supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
2813         assert(supported_displays);
2814
2815         err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
2816         assert(!err);
2817
2818         for (uint32_t i = 0; i < supported_count; i++) {
2819             if (supported_displays[i] == display) {
2820                 found_plane = VK_TRUE;
2821                 break;
2822             }
2823         }
2824
2825         free(supported_displays);
2826
2827         if (found_plane) {
2828             break;
2829         }
2830     }
2831
2832     if (!found_plane) {
2833         printf("Cannot find a plane compatible with the display!\n");
2834         fflush(stdout);
2835         exit(1);
2836     }
2837
2838     free(plane_props);
2839
2840     VkDisplayPlaneCapabilitiesKHR planeCaps;
2841     vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
2842     // Find a supported alpha mode
2843     VkCompositeAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
2844     VkCompositeAlphaFlagBitsKHR alphaModes[4] = {
2845         VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
2846         VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
2847         VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
2848         VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
2849     };
2850     for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2851         if (planeCaps.supportedAlpha & alphaModes[i]) {
2852             alphaMode = alphaModes[i];
2853             break;
2854         }
2855     }
2856     image_extent.width = mode_props.parameters.visibleRegion.width;
2857     image_extent.height = mode_props.parameters.visibleRegion.height;
2858
2859     create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
2860     create_info.pNext = NULL;
2861     create_info.flags = 0;
2862     create_info.displayMode = mode_props.displayMode;
2863     create_info.planeIndex = plane_index;
2864     create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
2865     create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
2866     create_info.alphaMode = alphaMode;
2867     create_info.globalAlpha = 1.0f;
2868     create_info.imageExtent = image_extent;
2869
2870     return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
2871 }
2872
2873 static void demo_run_display(struct demo *demo) {
2874     while (!demo->quit) {
2875         demo_draw(demo);
2876         demo->curFrame++;
2877
2878         if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2879             demo->quit = true;
2880         }
2881     }
2882 }
2883 #endif
2884
2885 /*
2886  * Return 1 (true) if all layer names specified in check_names
2887  * can be found in given layer properties.
2888  */
2889 static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
2890     for (uint32_t i = 0; i < check_count; i++) {
2891         VkBool32 found = 0;
2892         for (uint32_t j = 0; j < layer_count; j++) {
2893             if (!strcmp(check_names[i], layers[j].layerName)) {
2894                 found = 1;
2895                 break;
2896             }
2897         }
2898         if (!found) {
2899             fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
2900             return 0;
2901         }
2902     }
2903     return 1;
2904 }
2905
2906 static void demo_init_vk(struct demo *demo) {
2907     VkResult err;
2908     uint32_t instance_extension_count = 0;
2909     uint32_t instance_layer_count = 0;
2910     uint32_t validation_layer_count = 0;
2911     char **instance_validation_layers = NULL;
2912     demo->enabled_extension_count = 0;
2913     demo->enabled_layer_count = 0;
2914     demo->is_minimized = false;
2915     demo->cmd_pool = VK_NULL_HANDLE;
2916
2917     char *instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"};
2918
2919     char *instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
2920                                                "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
2921                                                "VK_LAYER_GOOGLE_unique_objects"};
2922
2923     /* Look for validation layers */
2924     VkBool32 validation_found = 0;
2925     if (demo->validate) {
2926         err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
2927         assert(!err);
2928
2929         instance_validation_layers = instance_validation_layers_alt1;
2930         if (instance_layer_count > 0) {
2931             VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
2932             err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
2933             assert(!err);
2934
2935             validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
2936                                                  instance_layer_count, instance_layers);
2937             if (validation_found) {
2938                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
2939                 demo->enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
2940                 validation_layer_count = 1;
2941             } else {
2942                 // use alternative set of validation layers
2943                 instance_validation_layers = instance_validation_layers_alt2;
2944                 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
2945                 validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
2946                                                      instance_layer_count, instance_layers);
2947                 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
2948                 for (uint32_t i = 0; i < validation_layer_count; i++) {
2949                     demo->enabled_layers[i] = instance_validation_layers[i];
2950                 }
2951             }
2952             free(instance_layers);
2953         }
2954
2955         if (!validation_found) {
2956             ERR_EXIT(
2957                 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
2958                 "Please look at the Getting Started guide for additional information.\n",
2959                 "vkCreateInstance Failure");
2960         }
2961     }
2962
2963     /* Look for instance extensions */
2964     VkBool32 surfaceExtFound = 0;
2965     VkBool32 platformSurfaceExtFound = 0;
2966     memset(demo->extension_names, 0, sizeof(demo->extension_names));
2967
2968     err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
2969     assert(!err);
2970
2971     if (instance_extension_count > 0) {
2972         VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
2973         err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
2974         assert(!err);
2975         for (uint32_t i = 0; i < instance_extension_count; i++) {
2976             if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2977                 surfaceExtFound = 1;
2978                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
2979             }
2980 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2981             if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2982                 platformSurfaceExtFound = 1;
2983                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
2984             }
2985 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2986             if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2987                 platformSurfaceExtFound = 1;
2988                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
2989             }
2990 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2991             if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2992                 platformSurfaceExtFound = 1;
2993                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
2994             }
2995 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2996             if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
2997                 platformSurfaceExtFound = 1;
2998                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
2999             }
3000 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3001 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3002             if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3003                 platformSurfaceExtFound = 1;
3004                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
3005             }
3006 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3007             if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3008                 platformSurfaceExtFound = 1;
3009                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
3010             }
3011 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3012             if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3013                 platformSurfaceExtFound = 1;
3014                 demo->extension_names[demo->enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
3015             }
3016 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3017             if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3018                 platformSurfaceExtFound = 1;
3019                 demo->extension_names[demo->enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
3020             }
3021 #endif
3022             if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3023                 if (demo->validate) {
3024                     demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
3025                 }
3026             }
3027             assert(demo->enabled_extension_count < 64);
3028         }
3029
3030         free(instance_extensions);
3031     }
3032
3033     if (!surfaceExtFound) {
3034         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
3035                  " extension.\n\n"
3036                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3037                  "Please look at the Getting Started guide for additional information.\n",
3038                  "vkCreateInstance Failure");
3039     }
3040     if (!platformSurfaceExtFound) {
3041 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3042         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
3043                  " extension.\n\n"
3044                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3045                  "Please look at the Getting Started guide for additional information.\n",
3046                  "vkCreateInstance Failure");
3047 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3048         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
3049                  " extension.\n\n"
3050                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3051                  "Please look at the Getting Started guide for additional information.\n",
3052                  "vkCreateInstance Failure");
3053 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3054         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
3055                  " extension.\n\n"
3056                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3057                  "Please look at the Getting Started guide for additional information.\n",
3058                  "vkCreateInstance Failure");
3059 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3060         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
3061                  " extension.\n\n"
3062                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3063                  "Please look at the Getting Started guide for additional information.\n",
3064                  "vkCreateInstance Failure");
3065 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3066         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
3067                  " extension.\n\n"
3068                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3069                  "Please look at the Getting Started guide for additional information.\n",
3070                  "vkCreateInstance Failure");
3071 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3072 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3073         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
3074                  " extension.\n\n"
3075                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3076                  "Please look at the Getting Started guide for additional information.\n",
3077                  "vkCreateInstance Failure");
3078 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3079         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
3080                  " extension.\n\n"
3081                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3082                  "Please look at the Getting Started guide for additional information.\n",
3083                  "vkCreateInstance Failure");
3084 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3085         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
3086                  " extension.\n\n"
3087                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3088                  "Please look at the Getting Started guide for additional information.\n",
3089                  "vkCreateInstance Failure");
3090 #endif
3091     }
3092     const VkApplicationInfo app = {
3093         .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
3094         .pNext = NULL,
3095         .pApplicationName = APP_SHORT_NAME,
3096         .applicationVersion = 0,
3097         .pEngineName = APP_SHORT_NAME,
3098         .engineVersion = 0,
3099         .apiVersion = VK_API_VERSION_1_0,
3100     };
3101     VkInstanceCreateInfo inst_info = {
3102         .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
3103         .pNext = NULL,
3104         .pApplicationInfo = &app,
3105         .enabledLayerCount = demo->enabled_layer_count,
3106         .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
3107         .enabledExtensionCount = demo->enabled_extension_count,
3108         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3109     };
3110
3111     /*
3112      * This is info for a temp callback to use during CreateInstance.
3113      * After the instance is created, we use the instance-based
3114      * function to register the final callback.
3115      */
3116     VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
3117     if (demo->validate) {
3118         // VK_EXT_debug_utils style
3119         dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
3120         dbg_messenger_create_info.pNext = NULL;
3121         dbg_messenger_create_info.flags = 0;
3122         dbg_messenger_create_info.messageSeverity =
3123             VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
3124         dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
3125                                                 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
3126                                                 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
3127         dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
3128         dbg_messenger_create_info.pUserData = demo;
3129         inst_info.pNext = &dbg_messenger_create_info;
3130     }
3131
3132     uint32_t gpu_count;
3133
3134     err = vkCreateInstance(&inst_info, NULL, &demo->inst);
3135     if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
3136         ERR_EXIT(
3137             "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
3138             "Please look at the Getting Started guide for additional information.\n",
3139             "vkCreateInstance Failure");
3140     } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
3141         ERR_EXIT(
3142             "Cannot find a specified extension library.\n"
3143             "Make sure your layers path is set appropriately.\n",
3144             "vkCreateInstance Failure");
3145     } else if (err) {
3146         ERR_EXIT(
3147             "vkCreateInstance failed.\n\n"
3148             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3149             "Please look at the Getting Started guide for additional information.\n",
3150             "vkCreateInstance Failure");
3151     }
3152
3153     /* Make initial call to query gpu_count, then second call for gpu info*/
3154     err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
3155     assert(!err);
3156
3157     if (gpu_count > 0) {
3158         VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
3159         err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
3160         assert(!err);
3161         /* For cube demo we just grab the first physical device */
3162         demo->gpu = physical_devices[0];
3163         free(physical_devices);
3164     } else {
3165         ERR_EXIT(
3166             "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
3167             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3168             "Please look at the Getting Started guide for additional information.\n",
3169             "vkEnumeratePhysicalDevices Failure");
3170     }
3171
3172     /* Look for device extensions */
3173     uint32_t device_extension_count = 0;
3174     VkBool32 swapchainExtFound = 0;
3175     demo->enabled_extension_count = 0;
3176     memset(demo->extension_names, 0, sizeof(demo->extension_names));
3177
3178     err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
3179     assert(!err);
3180
3181     if (device_extension_count > 0) {
3182         VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
3183         err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
3184         assert(!err);
3185
3186         for (uint32_t i = 0; i < device_extension_count; i++) {
3187             if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
3188                 swapchainExtFound = 1;
3189                 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
3190             }
3191             assert(demo->enabled_extension_count < 64);
3192         }
3193
3194         if (demo->VK_KHR_incremental_present_enabled) {
3195             // Even though the user "enabled" the extension via the command
3196             // line, we must make sure that it's enumerated for use with the
3197             // device.  Therefore, disable it here, and re-enable it again if
3198             // enumerated.
3199             demo->VK_KHR_incremental_present_enabled = false;
3200             for (uint32_t i = 0; i < device_extension_count; i++) {
3201                 if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
3202                     demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
3203                     demo->VK_KHR_incremental_present_enabled = true;
3204                     DbgMsg("VK_KHR_incremental_present extension enabled\n");
3205                 }
3206                 assert(demo->enabled_extension_count < 64);
3207             }
3208             if (!demo->VK_KHR_incremental_present_enabled) {
3209                 DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
3210             }
3211         }
3212
3213         if (demo->VK_GOOGLE_display_timing_enabled) {
3214             // Even though the user "enabled" the extension via the command
3215             // line, we must make sure that it's enumerated for use with the
3216             // device.  Therefore, disable it here, and re-enable it again if
3217             // enumerated.
3218             demo->VK_GOOGLE_display_timing_enabled = false;
3219             for (uint32_t i = 0; i < device_extension_count; i++) {
3220                 if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
3221                     demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
3222                     demo->VK_GOOGLE_display_timing_enabled = true;
3223                     DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
3224                 }
3225                 assert(demo->enabled_extension_count < 64);
3226             }
3227             if (!demo->VK_GOOGLE_display_timing_enabled) {
3228                 DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
3229             }
3230         }
3231
3232         free(device_extensions);
3233     }
3234
3235     if (!swapchainExtFound) {
3236         ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
3237                  " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
3238                  "Please look at the Getting Started guide for additional information.\n",
3239                  "vkCreateInstance Failure");
3240     }
3241
3242     if (demo->validate) {
3243         // Setup VK_EXT_debug_utils function pointers always (we use them for
3244         // debug labels and names).
3245         demo->CreateDebugUtilsMessengerEXT =
3246             (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugUtilsMessengerEXT");
3247         demo->DestroyDebugUtilsMessengerEXT =
3248             (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugUtilsMessengerEXT");
3249         demo->SubmitDebugUtilsMessageEXT =
3250             (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkSubmitDebugUtilsMessageEXT");
3251         demo->CmdBeginDebugUtilsLabelEXT =
3252             (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdBeginDebugUtilsLabelEXT");
3253         demo->CmdEndDebugUtilsLabelEXT =
3254             (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdEndDebugUtilsLabelEXT");
3255         demo->CmdInsertDebugUtilsLabelEXT =
3256             (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdInsertDebugUtilsLabelEXT");
3257         demo->SetDebugUtilsObjectNameEXT =
3258             (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(demo->inst, "vkSetDebugUtilsObjectNameEXT");
3259         if (NULL == demo->CreateDebugUtilsMessengerEXT || NULL == demo->DestroyDebugUtilsMessengerEXT ||
3260             NULL == demo->SubmitDebugUtilsMessageEXT || NULL == demo->CmdBeginDebugUtilsLabelEXT ||
3261             NULL == demo->CmdEndDebugUtilsLabelEXT || NULL == demo->CmdInsertDebugUtilsLabelEXT ||
3262             NULL == demo->SetDebugUtilsObjectNameEXT) {
3263             ERR_EXIT("GetProcAddr: Failed to init VK_EXT_debug_utils\n", "GetProcAddr: Failure");
3264         }
3265
3266         err = demo->CreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
3267         switch (err) {
3268             case VK_SUCCESS:
3269                 break;
3270             case VK_ERROR_OUT_OF_HOST_MEMORY:
3271                 ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
3272                 break;
3273             default:
3274                 ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
3275                 break;
3276         }
3277     }
3278     vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
3279
3280     /* Call with NULL data to get count */
3281     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
3282     assert(demo->queue_family_count >= 1);
3283
3284     demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
3285     vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
3286
3287     // Query fine-grained feature support for this device.
3288     //  If app has specific feature requirements it should check supported
3289     //  features based on this query
3290     VkPhysicalDeviceFeatures physDevFeatures;
3291     vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
3292
3293     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
3294     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
3295     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
3296     GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
3297     GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
3298 }
3299
3300 static void demo_create_device(struct demo *demo) {
3301     VkResult U_ASSERT_ONLY err;
3302     float queue_priorities[1] = {0.0};
3303     VkDeviceQueueCreateInfo queues[2];
3304     queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3305     queues[0].pNext = NULL;
3306     queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
3307     queues[0].queueCount = 1;
3308     queues[0].pQueuePriorities = queue_priorities;
3309     queues[0].flags = 0;
3310
3311     VkDeviceCreateInfo device = {
3312         .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
3313         .pNext = NULL,
3314         .queueCreateInfoCount = 1,
3315         .pQueueCreateInfos = queues,
3316         .enabledLayerCount = 0,
3317         .ppEnabledLayerNames = NULL,
3318         .enabledExtensionCount = demo->enabled_extension_count,
3319         .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
3320         .pEnabledFeatures = NULL,  // If specific features are required, pass them in here
3321     };
3322     if (demo->separate_present_queue) {
3323         queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3324         queues[1].pNext = NULL;
3325         queues[1].queueFamilyIndex = demo->present_queue_family_index;
3326         queues[1].queueCount = 1;
3327         queues[1].pQueuePriorities = queue_priorities;
3328         queues[1].flags = 0;
3329         device.queueCreateInfoCount = 2;
3330     }
3331     err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
3332     assert(!err);
3333 }
3334
3335 static void demo_init_vk_swapchain(struct demo *demo) {
3336     VkResult U_ASSERT_ONLY err;
3337
3338 // Create a WSI surface for the window:
3339 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3340     VkWin32SurfaceCreateInfoKHR createInfo;
3341     createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
3342     createInfo.pNext = NULL;
3343     createInfo.flags = 0;
3344     createInfo.hinstance = demo->connection;
3345     createInfo.hwnd = demo->window;
3346
3347     err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3348 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3349     VkWaylandSurfaceCreateInfoKHR createInfo;
3350     createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
3351     createInfo.pNext = NULL;
3352     createInfo.flags = 0;
3353     createInfo.display = demo->display;
3354     createInfo.surface = demo->window;
3355
3356     err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3357 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3358 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3359     VkAndroidSurfaceCreateInfoKHR createInfo;
3360     createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
3361     createInfo.pNext = NULL;
3362     createInfo.flags = 0;
3363     createInfo.window = (struct ANativeWindow *)(demo->window);
3364
3365     err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3366 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3367     VkXlibSurfaceCreateInfoKHR createInfo;
3368     createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
3369     createInfo.pNext = NULL;
3370     createInfo.flags = 0;
3371     createInfo.dpy = demo->display;
3372     createInfo.window = demo->xlib_window;
3373
3374     err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3375 #elif defined(VK_USE_PLATFORM_XCB_KHR)
3376     VkXcbSurfaceCreateInfoKHR createInfo;
3377     createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
3378     createInfo.pNext = NULL;
3379     createInfo.flags = 0;
3380     createInfo.connection = demo->connection;
3381     createInfo.window = demo->xcb_window;
3382
3383     err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
3384 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3385     err = demo_create_display_surface(demo);
3386 #elif defined(VK_USE_PLATFORM_IOS_MVK)
3387     VkIOSSurfaceCreateInfoMVK surface;
3388     surface.sType = VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK;
3389     surface.pNext = NULL;
3390     surface.flags = 0;
3391     surface.pView = demo->window;
3392
3393     err = vkCreateIOSSurfaceMVK(demo->inst, &surface, NULL, &demo->surface);
3394 #elif defined(VK_USE_PLATFORM_MACOS_MVK)
3395     VkMacOSSurfaceCreateInfoMVK surface;
3396     surface.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
3397     surface.pNext = NULL;
3398     surface.flags = 0;
3399     surface.pView = demo->window;
3400
3401     err = vkCreateMacOSSurfaceMVK(demo->inst, &surface, NULL, &demo->surface);
3402 #endif
3403     assert(!err);
3404
3405     // Iterate over each queue to learn whether it supports presenting:
3406     VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
3407     for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3408         demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
3409     }
3410
3411     // Search for a graphics and a present queue in the array of queue
3412     // families, try to find one that supports both
3413     uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
3414     uint32_t presentQueueFamilyIndex = UINT32_MAX;
3415     for (uint32_t i = 0; i < demo->queue_family_count; i++) {
3416         if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
3417             if (graphicsQueueFamilyIndex == UINT32_MAX) {
3418                 graphicsQueueFamilyIndex = i;
3419             }
3420
3421             if (supportsPresent[i] == VK_TRUE) {
3422                 graphicsQueueFamilyIndex = i;
3423                 presentQueueFamilyIndex = i;
3424                 break;
3425             }
3426         }
3427     }
3428
3429     if (presentQueueFamilyIndex == UINT32_MAX) {
3430         // If didn't find a queue that supports both graphics and present, then
3431         // find a separate present queue.
3432         for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
3433             if (supportsPresent[i] == VK_TRUE) {
3434                 presentQueueFamilyIndex = i;
3435                 break;
3436             }
3437         }
3438     }
3439
3440     // Generate error if could not find both a graphics and a present queue
3441     if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
3442         ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
3443     }
3444
3445     demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
3446     demo->present_queue_family_index = presentQueueFamilyIndex;
3447     demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
3448     free(supportsPresent);
3449
3450     demo_create_device(demo);
3451
3452     GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
3453     GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
3454     GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
3455     GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
3456     GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
3457     if (demo->VK_GOOGLE_display_timing_enabled) {
3458         GET_DEVICE_PROC_ADDR(demo->device, GetRefreshCycleDurationGOOGLE);
3459         GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE);
3460     }
3461
3462     vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
3463
3464     if (!demo->separate_present_queue) {
3465         demo->present_queue = demo->graphics_queue;
3466     } else {
3467         vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
3468     }
3469
3470     // Get the list of VkFormat's that are supported:
3471     uint32_t formatCount;
3472     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
3473     assert(!err);
3474     VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
3475     err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
3476     assert(!err);
3477     // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
3478     // the surface has no preferred format.  Otherwise, at least one
3479     // supported format will be returned.
3480     if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) {
3481         demo->format = VK_FORMAT_B8G8R8A8_UNORM;
3482     } else {
3483         assert(formatCount >= 1);
3484         demo->format = surfFormats[0].format;
3485     }
3486     demo->color_space = surfFormats[0].colorSpace;
3487
3488     demo->quit = false;
3489     demo->curFrame = 0;
3490
3491     // Create semaphores to synchronize acquiring presentable buffers before
3492     // rendering and waiting for drawing to be complete before presenting
3493     VkSemaphoreCreateInfo semaphoreCreateInfo = {
3494         .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
3495         .pNext = NULL,
3496         .flags = 0,
3497     };
3498
3499     // Create fences that we can use to throttle if we get too far
3500     // ahead of the image presents
3501     VkFenceCreateInfo fence_ci = {
3502         .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
3503     for (uint32_t i = 0; i < FRAME_LAG; i++) {
3504         err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]);
3505         assert(!err);
3506
3507         err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]);
3508         assert(!err);
3509
3510         err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]);
3511         assert(!err);
3512
3513         if (demo->separate_present_queue) {
3514             err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]);
3515             assert(!err);
3516         }
3517     }
3518     demo->frame_index = 0;
3519
3520     // Get Memory information and properties
3521     vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
3522 }
3523
3524 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
3525 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
3526                                  wl_fixed_t sy) {}
3527
3528 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
3529
3530 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
3531
3532 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
3533                                   uint32_t state) {
3534     struct demo *demo = data;
3535     if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
3536         wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
3537     }
3538 }
3539
3540 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
3541
3542 static const struct wl_pointer_listener pointer_listener = {
3543     pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
3544 };
3545
3546 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
3547
3548 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
3549                                   struct wl_array *keys) {}
3550
3551 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
3552
3553 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
3554                                 uint32_t state) {
3555     if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
3556     struct demo *demo = data;
3557     switch (key) {
3558         case KEY_ESC:  // Escape
3559             demo->quit = true;
3560             break;
3561         case KEY_LEFT:  // left arrow key
3562             demo->spin_angle -= demo->spin_increment;
3563             break;
3564         case KEY_RIGHT:  // right arrow key
3565             demo->spin_angle += demo->spin_increment;
3566             break;
3567         case KEY_SPACE:  // space bar
3568             demo->pause = !demo->pause;
3569             break;
3570     }
3571 }
3572
3573 static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
3574                                       uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
3575
3576 static const struct wl_keyboard_listener keyboard_listener = {
3577     keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
3578 };
3579
3580 static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
3581     // Subscribe to pointer events
3582     struct demo *demo = data;
3583     if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
3584         demo->pointer = wl_seat_get_pointer(seat);
3585         wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
3586     } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
3587         wl_pointer_destroy(demo->pointer);
3588         demo->pointer = NULL;
3589     }
3590     // Subscribe to keyboard events
3591     if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
3592         demo->keyboard = wl_seat_get_keyboard(seat);
3593         wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
3594     } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
3595         wl_keyboard_destroy(demo->keyboard);
3596         demo->keyboard = NULL;
3597     }
3598 }
3599
3600 static const struct wl_seat_listener seat_listener = {
3601     seat_handle_capabilities,
3602 };
3603
3604 static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
3605                                    uint32_t version UNUSED) {
3606     struct demo *demo = data;
3607     // pickup wayland objects when they appear
3608     if (strcmp(interface, "wl_compositor") == 0) {
3609         demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, 1);
3610     } else if (strcmp(interface, "wl_shell") == 0) {
3611         demo->shell = wl_registry_bind(registry, id, &wl_shell_interface, 1);
3612     } else if (strcmp(interface, "wl_seat") == 0) {
3613         demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
3614         wl_seat_add_listener(demo->seat, &seat_listener, demo);
3615     }
3616 }
3617
3618 static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
3619
3620 static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
3621 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3622 #endif
3623
3624 static void demo_init_connection(struct demo *demo) {
3625 #if defined(VK_USE_PLATFORM_XCB_KHR)
3626     const xcb_setup_t *setup;
3627     xcb_screen_iterator_t iter;
3628     int scr;
3629
3630     const char *display_envar = getenv("DISPLAY");
3631     if (display_envar == NULL || display_envar[0] == '\0') {
3632         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
3633         fflush(stdout);
3634         exit(1);
3635     }
3636
3637     demo->connection = xcb_connect(NULL, &scr);
3638     if (xcb_connection_has_error(demo->connection) > 0) {
3639         printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3640         fflush(stdout);
3641         exit(1);
3642     }
3643
3644     setup = xcb_get_setup(demo->connection);
3645     iter = xcb_setup_roots_iterator(setup);
3646     while (scr-- > 0) xcb_screen_next(&iter);
3647
3648     demo->screen = iter.data;
3649 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3650     demo->display = wl_display_connect(NULL);
3651
3652     if (demo->display == NULL) {
3653         printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
3654         fflush(stdout);
3655         exit(1);
3656     }
3657
3658     demo->registry = wl_display_get_registry(demo->display);
3659     wl_registry_add_listener(demo->registry, &registry_listener, demo);
3660     wl_display_dispatch(demo->display);
3661 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3662 #endif
3663 }
3664
3665 static void demo_init(struct demo *demo, int argc, char **argv) {
3666     vec3 eye = {0.0f, 3.0f, 5.0f};
3667     vec3 origin = {0, 0, 0};
3668     vec3 up = {0.0f, 1.0f, 0.0};
3669
3670     memset(demo, 0, sizeof(*demo));
3671     demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
3672     demo->frameCount = INT32_MAX;
3673
3674     for (int i = 1; i < argc; i++) {
3675         if (strcmp(argv[i], "--use_staging") == 0) {
3676             demo->use_staging_buffer = true;
3677             continue;
3678         }
3679         if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
3680             demo->presentMode = atoi(argv[i + 1]);
3681             i++;
3682             continue;
3683         }
3684         if (strcmp(argv[i], "--break") == 0) {
3685             demo->use_break = true;
3686             continue;
3687         }
3688         if (strcmp(argv[i], "--validate") == 0) {
3689             demo->validate = true;
3690             continue;
3691         }
3692         if (strcmp(argv[i], "--validate-checks-disabled") == 0) {
3693             demo->validate = true;
3694             demo->validate_checks_disabled = true;
3695             continue;
3696         }
3697         if (strcmp(argv[i], "--xlib") == 0) {
3698             fprintf(stderr, "--xlib is deprecated and no longer does anything");
3699             continue;
3700         }
3701         if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
3702             sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
3703             i++;
3704             continue;
3705         }
3706         if (strcmp(argv[i], "--suppress_popups") == 0) {
3707             demo->suppress_popups = true;
3708             continue;
3709         }
3710         if (strcmp(argv[i], "--display_timing") == 0) {
3711             demo->VK_GOOGLE_display_timing_enabled = true;
3712             continue;
3713         }
3714         if (strcmp(argv[i], "--incremental_present") == 0) {
3715             demo->VK_KHR_incremental_present_enabled = true;
3716             continue;
3717         }
3718
3719 #if defined(ANDROID)
3720         ERR_EXIT("Usage: cube [--validate]\n", "Usage");
3721 #else
3722         fprintf(stderr,
3723                 "Usage:\n  %s\t[--use_staging] [--validate] [--validate-checks-disabled] [--break]\n"
3724                 "\t[--c <framecount>] [--suppress_popups] [--incremental_present] [--display_timing]\n"
3725                 "\t[--present_mode <present mode enum>]\n"
3726                 "\t <present_mode_enum>\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
3727                 "\t\t\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
3728                 "\t\t\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
3729                 "\t\t\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n",
3730                 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
3731                 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
3732         fflush(stderr);
3733         exit(1);
3734 #endif
3735     }
3736
3737     demo_init_connection(demo);
3738
3739     demo_init_vk(demo);
3740
3741     demo->width = 500;
3742     demo->height = 500;
3743
3744     demo->spin_angle = 4.0f;
3745     demo->spin_increment = 0.2f;
3746     demo->pause = false;
3747
3748     mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
3749     mat4x4_look_at(demo->view_matrix, eye, origin, up);
3750     mat4x4_identity(demo->model_matrix);
3751
3752     demo->projection_matrix[1][1] *= -1;  // Flip projection matrix from GL to Vulkan orientation.
3753 }
3754
3755 #if defined(VK_USE_PLATFORM_WIN32_KHR)
3756 // Include header required for parsing the command line options.
3757 #include <shellapi.h>
3758
3759 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
3760     MSG msg;    // message
3761     bool done;  // flag saying when app is complete
3762     int argc;
3763     char **argv;
3764
3765     // Ensure wParam is initialized.
3766     msg.wParam = 0;
3767
3768     // Use the CommandLine functions to get the command line arguments.
3769     // Unfortunately, Microsoft outputs
3770     // this information as wide characters for Unicode, and we simply want the
3771     // Ascii version to be compatible
3772     // with the non-Windows side.  So, we have to convert the information to
3773     // Ascii character strings.
3774     LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3775     if (NULL == commandLineArgs) {
3776         argc = 0;
3777     }
3778
3779     if (argc > 0) {
3780         argv = (char **)malloc(sizeof(char *) * argc);
3781         if (argv == NULL) {
3782             argc = 0;
3783         } else {
3784             for (int iii = 0; iii < argc; iii++) {
3785                 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3786                 size_t numConverted = 0;
3787
3788                 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3789                 if (argv[iii] != NULL) {
3790                     wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3791                 }
3792             }
3793         }
3794     } else {
3795         argv = NULL;
3796     }
3797
3798     demo_init(&demo, argc, argv);
3799
3800     // Free up the items we had to allocate for the command line arguments.
3801     if (argc > 0 && argv != NULL) {
3802         for (int iii = 0; iii < argc; iii++) {
3803             if (argv[iii] != NULL) {
3804                 free(argv[iii]);
3805             }
3806         }
3807         free(argv);
3808     }
3809
3810     demo.connection = hInstance;
3811     strncpy(demo.name, "cube", APP_NAME_STR_LEN);
3812     demo_create_window(&demo);
3813     demo_init_vk_swapchain(&demo);
3814
3815     demo_prepare(&demo);
3816
3817     done = false;  // initialize loop condition variable
3818
3819     // main message loop
3820     while (!done) {
3821         PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
3822         if (msg.message == WM_QUIT)  // check for a quit message
3823         {
3824             done = true;  // if found, quit app
3825         } else {
3826             /* Translate and dispatch to event queue*/
3827             TranslateMessage(&msg);
3828             DispatchMessage(&msg);
3829         }
3830         RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
3831     }
3832
3833     demo_cleanup(&demo);
3834
3835     return (int)msg.wParam;
3836 }
3837
3838 #elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3839 static void demo_main(struct demo *demo, void *view, int argc, const char *argv[]) {
3840
3841     demo_init(demo, argc, (char **)argv);
3842     demo->window = view;
3843     demo_init_vk_swapchain(demo);
3844     demo_prepare(demo);
3845     demo->spin_angle = 0.4f;
3846 }
3847
3848 #elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3849 #include <android/log.h>
3850 #include <android_native_app_glue.h>
3851 #include "android_util.h"
3852
3853 static bool initialized = false;
3854 static bool active = false;
3855 struct demo demo;
3856
3857 static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
3858
3859 static void processCommand(struct android_app *app, int32_t cmd) {
3860     switch (cmd) {
3861         case APP_CMD_INIT_WINDOW: {
3862             if (app->window) {
3863                 // We're getting a new window.  If the app is starting up, we
3864                 // need to initialize.  If the app has already been
3865                 // initialized, that means that we lost our previous window,
3866                 // which means that we have a lot of work to do.  At a minimum,
3867                 // we need to destroy the swapchain and surface associated with
3868                 // the old window, and create a new surface and swapchain.
3869                 // However, since there are a lot of other objects/state that
3870                 // is tied to the swapchain, it's easiest to simply cleanup and
3871                 // start over (i.e. use a brute-force approach of re-starting
3872                 // the app)
3873                 if (demo.prepared) {
3874                     demo_cleanup(&demo);
3875                 }
3876
3877                 // Parse Intents into argc, argv
3878                 // Use the following key to send arguments, i.e.
3879                 // --es args "--validate"
3880                 const char key[] = "args";
3881                 char *appTag = (char *)APP_SHORT_NAME;
3882                 int argc = 0;
3883                 char **argv = get_args(app, key, appTag, &argc);
3884
3885                 __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
3886                 for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
3887
3888                 demo_init(&demo, argc, argv);
3889
3890                 // Free the argv malloc'd by get_args
3891                 for (int i = 0; i < argc; i++) free(argv[i]);
3892
3893                 demo.window = (void *)app->window;
3894                 demo_init_vk_swapchain(&demo);
3895                 demo_prepare(&demo);
3896                 initialized = true;
3897             }
3898             break;
3899         }
3900         case APP_CMD_GAINED_FOCUS: {
3901             active = true;
3902             break;
3903         }
3904         case APP_CMD_LOST_FOCUS: {
3905             active = false;
3906             break;
3907         }
3908     }
3909 }
3910
3911 void android_main(struct android_app *app) {
3912 #ifdef ANDROID
3913     int vulkanSupport = InitVulkan();
3914     if (vulkanSupport == 0) return;
3915 #endif
3916
3917     demo.prepared = false;
3918
3919     app->onAppCmd = processCommand;
3920     app->onInputEvent = processInput;
3921
3922     while (1) {
3923         int events;
3924         struct android_poll_source *source;
3925         while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
3926             if (source) {
3927                 source->process(app, source);
3928             }
3929
3930             if (app->destroyRequested != 0) {
3931                 demo_cleanup(&demo);
3932                 return;
3933             }
3934         }
3935         if (initialized && active) {
3936             demo_run(&demo);
3937         }
3938     }
3939 }
3940 #else
3941 int main(int argc, char **argv) {
3942     struct demo demo;
3943
3944     demo_init(&demo, argc, argv);
3945 #if defined(VK_USE_PLATFORM_XCB_KHR)
3946     demo_create_xcb_window(&demo);
3947 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3948     demo_create_xlib_window(&demo);
3949 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3950     demo_create_window(&demo);
3951 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3952 #endif
3953
3954     demo_init_vk_swapchain(&demo);
3955
3956     demo_prepare(&demo);
3957
3958 #if defined(VK_USE_PLATFORM_XCB_KHR)
3959     demo_run_xcb(&demo);
3960 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3961     demo_run_xlib(&demo);
3962 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3963     demo_run(&demo);
3964 #elif defined(VK_USE_PLATFORM_MIR_KHR)
3965 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3966     demo_run_display(&demo);
3967 #endif
3968
3969     demo_cleanup(&demo);
3970
3971     return validation_error;
3972 }
3973 #endif