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