Upgrade to upstream v1.3.240
[platform/upstream/Vulkan-Tools.git] / cube / cube.cpp
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: Jeremy Hayes <jeremy@lunarg.com>
19  * Author: Charles Giessen <charles@lunarg.com>
20  */
21
22 #if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
23 #include <X11/Xutil.h>
24 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
25 #include <linux/input.h>
26 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
27 #include "xdg-shell-client-header.h"
28 #endif
29 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
30 #include "xdg-decoration-client-header.h"
31 #endif
32 #endif
33 #include <wayland-client.h>
34
35 #include <cassert>
36 #include <cinttypes>
37 #include <cstdio>
38 #include <cstdlib>
39 #include <cstring>
40 #include <csignal>
41
42 #include <sstream>
43 #include <iostream>
44 #include <memory>
45
46 #define VULKAN_HPP_NO_EXCEPTIONS
47 #define VULKAN_HPP_TYPESAFE_CONVERSION
48 #include <vulkan/vulkan.hpp>
49
50 #include "linmath.h"
51
52 #ifndef NDEBUG
53 #define VERIFY(x) assert(x)
54 #else
55 #define VERIFY(x) ((void)(x))
56 #endif
57
58 #define APP_SHORT_NAME "vkcubepp"
59
60 // Allow a maximum of two outstanding presentation operations.
61 constexpr uint32_t FRAME_LAG = 2;
62
63 #ifdef _WIN32
64 #define ERR_EXIT(err_msg, err_class)                                          \
65     do {                                                                      \
66         if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
67         exit(1);                                                              \
68     } while (0)
69 #else
70 #define ERR_EXIT(err_msg, err_class) \
71     do {                             \
72         printf("%s\n", err_msg);     \
73         fflush(stdout);              \
74         exit(1);                     \
75     } while (0)
76 #endif
77
78 // easier to use the C function for extension functions
79 PFN_vkCreateDebugUtilsMessengerEXT pfnVkCreateDebugUtilsMessengerEXT;
80 PFN_vkDestroyDebugUtilsMessengerEXT pfnVkDestroyDebugUtilsMessengerEXT;
81 VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugUtilsMessengerEXT(VkInstance instance,
82                                                               const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo,
83                                                               const VkAllocationCallbacks *pAllocator,
84                                                               VkDebugUtilsMessengerEXT *pMessenger) {
85     return pfnVkCreateDebugUtilsMessengerEXT(instance, pCreateInfo, pAllocator, pMessenger);
86 }
87
88 VKAPI_ATTR void VKAPI_CALL vkDestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT messenger,
89                                                            VkAllocationCallbacks const *pAllocator) {
90     return pfnVkDestroyDebugUtilsMessengerEXT(instance, messenger, pAllocator);
91 }
92
93 struct texture_object {
94     vk::Sampler sampler;
95
96     vk::Image image;
97     vk::Buffer buffer;
98     vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
99
100     vk::MemoryAllocateInfo mem_alloc;
101     vk::DeviceMemory mem;
102     vk::ImageView view;
103
104     uint32_t tex_width{0};
105     uint32_t tex_height{0};
106 };
107
108 static char const *const tex_files[] = {"lunarg.ppm"};
109
110 static int validation_error = 0;
111
112 struct vktexcube_vs_uniform {
113     // Must start with MVP
114     float mvp[4][4];
115     float position[12 * 3][4];
116     float attr[12 * 3][4];
117 };
118
119 //--------------------------------------------------------------------------------------
120 // Mesh and VertexFormat Data
121 //--------------------------------------------------------------------------------------
122 // clang-format off
123 static const float g_vertex_buffer_data[] = {
124     -1.0f,-1.0f,-1.0f,  // -X side
125     -1.0f,-1.0f, 1.0f,
126     -1.0f, 1.0f, 1.0f,
127     -1.0f, 1.0f, 1.0f,
128     -1.0f, 1.0f,-1.0f,
129     -1.0f,-1.0f,-1.0f,
130
131     -1.0f,-1.0f,-1.0f,  // -Z side
132      1.0f, 1.0f,-1.0f,
133      1.0f,-1.0f,-1.0f,
134     -1.0f,-1.0f,-1.0f,
135     -1.0f, 1.0f,-1.0f,
136      1.0f, 1.0f,-1.0f,
137
138     -1.0f,-1.0f,-1.0f,  // -Y side
139      1.0f,-1.0f,-1.0f,
140      1.0f,-1.0f, 1.0f,
141     -1.0f,-1.0f,-1.0f,
142      1.0f,-1.0f, 1.0f,
143     -1.0f,-1.0f, 1.0f,
144
145     -1.0f, 1.0f,-1.0f,  // +Y side
146     -1.0f, 1.0f, 1.0f,
147      1.0f, 1.0f, 1.0f,
148     -1.0f, 1.0f,-1.0f,
149      1.0f, 1.0f, 1.0f,
150      1.0f, 1.0f,-1.0f,
151
152      1.0f, 1.0f,-1.0f,  // +X side
153      1.0f, 1.0f, 1.0f,
154      1.0f,-1.0f, 1.0f,
155      1.0f,-1.0f, 1.0f,
156      1.0f,-1.0f,-1.0f,
157      1.0f, 1.0f,-1.0f,
158
159     -1.0f, 1.0f, 1.0f,  // +Z side
160     -1.0f,-1.0f, 1.0f,
161      1.0f, 1.0f, 1.0f,
162     -1.0f,-1.0f, 1.0f,
163      1.0f,-1.0f, 1.0f,
164      1.0f, 1.0f, 1.0f,
165 };
166
167 static const float g_uv_buffer_data[] = {
168     0.0f, 1.0f,  // -X side
169     1.0f, 1.0f,
170     1.0f, 0.0f,
171     1.0f, 0.0f,
172     0.0f, 0.0f,
173     0.0f, 1.0f,
174
175     1.0f, 1.0f,  // -Z side
176     0.0f, 0.0f,
177     0.0f, 1.0f,
178     1.0f, 1.0f,
179     1.0f, 0.0f,
180     0.0f, 0.0f,
181
182     1.0f, 0.0f,  // -Y side
183     1.0f, 1.0f,
184     0.0f, 1.0f,
185     1.0f, 0.0f,
186     0.0f, 1.0f,
187     0.0f, 0.0f,
188
189     1.0f, 0.0f,  // +Y side
190     0.0f, 0.0f,
191     0.0f, 1.0f,
192     1.0f, 0.0f,
193     0.0f, 1.0f,
194     1.0f, 1.0f,
195
196     1.0f, 0.0f,  // +X side
197     0.0f, 0.0f,
198     0.0f, 1.0f,
199     0.0f, 1.0f,
200     1.0f, 1.0f,
201     1.0f, 0.0f,
202
203     0.0f, 0.0f,  // +Z side
204     0.0f, 1.0f,
205     1.0f, 0.0f,
206     0.0f, 1.0f,
207     1.0f, 1.0f,
208     1.0f, 0.0f,
209 };
210 // clang-format on
211
212 struct SwapchainImageResources {
213     vk::Image image;
214     vk::CommandBuffer cmd;
215     vk::CommandBuffer graphics_to_present_cmd;
216     vk::ImageView view;
217     vk::Buffer uniform_buffer;
218     vk::DeviceMemory uniform_memory;
219     void *uniform_memory_ptr = nullptr;
220     vk::Framebuffer framebuffer;
221     vk::DescriptorSet descriptor_set;
222 };
223
224 struct Demo {
225     void build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource);
226     vk::Bool32 check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers);
227     void cleanup();
228     void destroy_swapchain_related_resources();
229     void create_device();
230     void destroy_texture(texture_object &tex_objs);
231     void draw();
232     void draw_build_cmd(const SwapchainImageResources &swapchain_image_resource);
233     void prepare_init_cmd();
234     void flush_init_cmd();
235     void init(int argc, char **argv);
236     void init_connection();
237     void init_vk();
238     void init_vk_swapchain();
239     void prepare();
240     void prepare_buffers();
241     void prepare_cube_data_buffers();
242     void prepare_depth();
243     void prepare_descriptor_layout();
244     void prepare_descriptor_pool();
245     void prepare_descriptor_set();
246     void prepare_framebuffers();
247     vk::ShaderModule prepare_shader_module(const uint32_t *code, size_t size);
248     vk::ShaderModule prepare_vs();
249     vk::ShaderModule prepare_fs();
250     void prepare_pipeline();
251     void prepare_render_pass();
252     void prepare_texture_image(const char *filename, texture_object &tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
253                                vk::MemoryPropertyFlags required_props);
254     void prepare_texture_buffer(const char *filename, texture_object &tex_obj);
255     void prepare_textures();
256
257     void resize();
258     void create_surface();
259     void set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
260                           vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages);
261     void update_data_buffer();
262     bool loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout &layout, uint32_t &width, uint32_t &height);
263     bool memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t &typeIndex);
264     vk::SurfaceFormatKHR pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats);
265
266     static VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
267                                                                    VkDebugUtilsMessageTypeFlagsEXT messageType,
268                                                                    const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
269                                                                    void *pUserData);
270
271 #if defined(VK_USE_PLATFORM_WIN32_KHR)
272     void run();
273     void create_window();
274 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
275     void create_xlib_window();
276     void handle_xlib_event(const XEvent *event);
277     void run_xlib();
278 #elif defined(VK_USE_PLATFORM_XCB_KHR)
279     void handle_xcb_event(const xcb_generic_event_t *event);
280     void run_xcb();
281     void create_xcb_window();
282 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
283     void run();
284     void create_window();
285 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
286     void handle_directfb_event(const DFBInputEvent *event);
287     void run_directfb();
288     void create_directfb_window();
289 #elif defined(VK_USE_PLATFORM_METAL_EXT)
290     void run();
291 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
292     vk::Result create_display_surface();
293     void run_display();
294 #endif
295
296     std::string name = "vkcubepp";  // Name to put on the window/icon
297 #if defined(VK_USE_PLATFORM_WIN32_KHR)
298     HINSTANCE connection = nullptr;  // hInstance - Windows Instance
299     HWND window = nullptr;           // hWnd - window handle
300     POINT minsize = {0, 0};          // minimum window size
301 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
302     Window xlib_window = 0;
303     Atom xlib_wm_delete_window = 0;
304     Display *display = nullptr;
305 #elif defined(VK_USE_PLATFORM_XCB_KHR)
306     xcb_window_t xcb_window = 0;
307     xcb_screen_t *screen = nullptr;
308     xcb_connection_t *connection = nullptr;
309     xcb_intern_atom_reply_t *atom_wm_delete_window = nullptr;
310 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
311     wl_display *display = nullptr;
312     wl_registry *registry = nullptr;
313     wl_compositor *compositor = nullptr;
314     wl_surface *window = nullptr;
315 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
316     xdg_wm_base *wm_base = nullptr;
317 #endif
318 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
319     zxdg_decoration_manager_v1 *xdg_decoration_mgr = nullptr;
320     zxdg_toplevel_decoration_v1 *toplevel_decoration = nullptr;
321 #endif
322 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
323     xdg_surface *window_surface = nullptr;
324 #endif
325     bool xdg_surface_has_been_configured = false;
326     //xdg_toplevel *window_toplevel = nullptr;
327     wl_seat *seat = nullptr;
328     wl_pointer *pointer = nullptr;
329     wl_keyboard *keyboard = nullptr;
330     wl_shell *shell;
331         wl_shell_surface *window_surface;
332 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
333     IDirectFB *dfb = nullptr;
334     IDirectFBSurface *window = nullptr;
335     IDirectFBEventBuffer *event_buffer = nullptr;
336 #elif defined(VK_USE_PLATFORM_METAL_EXT)
337     void *caMetalLayer;
338 #endif
339
340     vk::SurfaceKHR surface;
341     bool prepared = false;
342     bool use_staging_buffer = false;
343     bool use_xlib = false;
344     bool separate_present_queue = false;
345     bool invalid_gpu_selection = false;
346     int32_t gpu_number = 0;
347
348     vk::Instance inst;
349     vk::DebugUtilsMessengerEXT debug_messenger;
350     vk::PhysicalDevice gpu;
351     vk::Device device;
352     vk::Queue graphics_queue;
353     vk::Queue present_queue;
354     uint32_t graphics_queue_family_index = 0;
355     uint32_t present_queue_family_index = 0;
356     std::array<vk::Semaphore, FRAME_LAG> image_acquired_semaphores;
357     std::array<vk::Semaphore, FRAME_LAG> draw_complete_semaphores;
358     std::array<vk::Semaphore, FRAME_LAG> image_ownership_semaphores;
359     vk::PhysicalDeviceProperties gpu_props;
360     std::vector<vk::QueueFamilyProperties> queue_props;
361     vk::PhysicalDeviceMemoryProperties memory_properties;
362
363     std::vector<const char *> enabled_instance_extensions;
364     std::vector<const char *> enabled_layers;
365     std::vector<const char *> enabled_device_extensions;
366
367     uint32_t width = 0;
368     uint32_t height = 0;
369     vk::Format format;
370     vk::ColorSpaceKHR color_space;
371
372     vk::SwapchainKHR swapchain;
373     std::vector<SwapchainImageResources> swapchain_image_resources;
374     vk::PresentModeKHR presentMode = vk::PresentModeKHR::eFifo;
375     std::array<vk::Fence, FRAME_LAG> fences;
376     uint32_t frame_index = 0;
377
378     vk::CommandPool cmd_pool;
379     vk::CommandPool present_cmd_pool;
380
381     struct {
382         vk::Format format;
383         vk::Image image;
384         vk::MemoryAllocateInfo mem_alloc;
385         vk::DeviceMemory mem;
386         vk::ImageView view;
387     } depth;
388
389     static int32_t const texture_count = 1;
390     std::array<texture_object, texture_count> textures;
391     texture_object staging_texture;
392
393     struct {
394         vk::Buffer buf;
395         vk::MemoryAllocateInfo mem_alloc;
396         vk::DeviceMemory mem;
397         vk::DescriptorBufferInfo buffer_info;
398     } uniform_data;
399
400     vk::CommandBuffer cmd;  // Buffer for initialization commands
401     vk::PipelineLayout pipeline_layout;
402     vk::DescriptorSetLayout desc_layout;
403     vk::PipelineCache pipelineCache;
404     vk::RenderPass render_pass;
405     vk::Pipeline pipeline;
406
407     mat4x4 projection_matrix = {};
408     mat4x4 view_matrix = {};
409     mat4x4 model_matrix = {};
410
411     float spin_angle = 0.0f;
412     float spin_increment = 0.0f;
413     bool pause = false;
414
415     vk::ShaderModule vert_shader_module;
416     vk::ShaderModule frag_shader_module;
417
418     vk::DescriptorPool desc_pool;
419     vk::DescriptorSet desc_set;
420
421     std::vector<vk::Framebuffer> framebuffers;
422
423     bool quit = false;
424     uint32_t curFrame = 0;
425     uint32_t frameCount = 0;
426     bool validate = false;
427     bool in_callback = false;
428     bool use_debug_messenger = false;
429     bool use_break = false;
430     bool suppress_popups = false;
431     bool force_errors = false;
432
433     uint32_t current_buffer = 0;
434 };
435
436 #ifdef _WIN32
437 // MS-Windows event handling function:
438 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
439 #endif
440
441 #if defined(VK_USE_PLATFORM_WAYLAND_KHR)
442 static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
443                                  wl_fixed_t sy) {}
444
445 static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
446
447 static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
448
449 static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
450                                   uint32_t state) {
451     //Demo &demo = *static_cast<Demo *>(data);
452     if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
453         //xdg_toplevel_move(demo.window_toplevel, demo.seat, serial);
454     }
455 }
456
457 static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
458
459 static const struct wl_pointer_listener pointer_listener = {
460     pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
461 };
462
463 static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
464
465 static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
466                                   struct wl_array *keys) {}
467
468 static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
469
470 static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
471                                 uint32_t state) {
472     if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
473     Demo &demo = *static_cast<Demo *>(data);
474     switch (key) {
475         case KEY_ESC:  // Escape
476             demo.quit = true;
477             break;
478         case KEY_LEFT:  // left arrow key
479             demo.spin_angle -= demo.spin_increment;
480             break;
481         case KEY_RIGHT:  // right arrow key
482             demo.spin_angle += demo.spin_increment;
483             break;
484         case KEY_SPACE:  // space bar
485             demo.pause = !demo.pause;
486             break;
487     }
488 }
489
490 static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
491                                       uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
492
493 static const struct wl_keyboard_listener keyboard_listener = {
494     keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
495 };
496
497 static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
498     // Subscribe to pointer events
499     Demo &demo = *static_cast<Demo *>(data);
500     if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo.pointer) {
501         demo.pointer = wl_seat_get_pointer(seat);
502         wl_pointer_add_listener(demo.pointer, &pointer_listener, &demo);
503     } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo.pointer) {
504         wl_pointer_destroy(demo.pointer);
505         demo.pointer = nullptr;
506     }
507     // Subscribe to keyboard events
508     if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
509         demo.keyboard = wl_seat_get_keyboard(seat);
510         wl_keyboard_add_listener(demo.keyboard, &keyboard_listener, &demo);
511     } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && demo.keyboard) {
512         wl_keyboard_destroy(demo.keyboard);
513         demo.keyboard = nullptr;
514     }
515 }
516
517 static const wl_seat_listener seat_listener = {
518     seat_handle_capabilities,
519 };
520
521 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
522 static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
523
524 static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
525 #endif
526
527 static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
528     Demo &demo = *static_cast<Demo *>(data);
529     // pickup wayland objects when they appear
530     if (strcmp(interface, wl_compositor_interface.name) == 0) {
531         demo.compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
532     } else if (strcmp(interface, "wl_shell") == 0) {
533         demo.shell = (struct wl_shell *)wl_registry_bind(registry, id,
534                                 &wl_shell_interface, 1);
535     }
536 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
537     else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
538         demo.wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
539         xdg_wm_base_add_listener(demo.wm_base, &wm_base_listener, nullptr);
540     }
541 #endif
542     else if (strcmp(interface, wl_seat_interface.name) == 0) {
543         demo.seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
544         wl_seat_add_listener(demo.seat, &seat_listener, &demo);
545     }
546 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
547     else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
548         demo.xdg_decoration_mgr =
549             (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
550     }
551 #endif
552 }
553
554 static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
555
556 static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
557 #endif
558
559 void Demo::build_image_ownership_cmd(const SwapchainImageResources &swapchain_image_resource) {
560     auto result = swapchain_image_resource.graphics_to_present_cmd.begin(
561         vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
562     VERIFY(result == vk::Result::eSuccess);
563
564     auto const image_ownership_barrier =
565         vk::ImageMemoryBarrier()
566             .setSrcAccessMask(vk::AccessFlags())
567             .setDstAccessMask(vk::AccessFlags())
568             .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
569             .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
570             .setSrcQueueFamilyIndex(graphics_queue_family_index)
571             .setDstQueueFamilyIndex(present_queue_family_index)
572             .setImage(swapchain_image_resource.image)
573             .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
574
575     swapchain_image_resource.graphics_to_present_cmd.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe,
576                                                                      vk::PipelineStageFlagBits::eBottomOfPipe,
577                                                                      vk::DependencyFlagBits(), {}, {}, image_ownership_barrier);
578
579     result = swapchain_image_resource.graphics_to_present_cmd.end();
580     VERIFY(result == vk::Result::eSuccess);
581 }
582
583 vk::Bool32 Demo::check_layers(const std::vector<const char *> &check_names, const std::vector<vk::LayerProperties> &layers) {
584     for (const auto &name : check_names) {
585         vk::Bool32 found = VK_FALSE;
586         for (const auto &layer : layers) {
587             if (!strcmp(name, layer.layerName)) {
588                 found = VK_TRUE;
589                 break;
590             }
591         }
592         if (!found) {
593             fprintf(stderr, "Cannot find layer: %s\n", name);
594             return 0;
595         }
596     }
597     return VK_TRUE;
598 }
599
600 void Demo::cleanup() {
601     prepared = false;
602     auto result = device.waitIdle();
603     VERIFY(result == vk::Result::eSuccess);
604
605     destroy_swapchain_related_resources();
606     // Wait for fences from present operations
607     for (uint32_t i = 0; i < FRAME_LAG; i++) {
608         device.destroyFence(fences[i]);
609         device.destroySemaphore(image_acquired_semaphores[i]);
610         device.destroySemaphore(draw_complete_semaphores[i]);
611         if (separate_present_queue) {
612             device.destroySemaphore(image_ownership_semaphores[i]);
613         }
614     }
615
616     device.destroySwapchainKHR(swapchain);
617
618     device.destroy();
619     inst.destroySurfaceKHR(surface);
620
621 #if defined(VK_USE_PLATFORM_XLIB_KHR)
622     XDestroyWindow(display, xlib_window);
623     XCloseDisplay(display);
624 #elif defined(VK_USE_PLATFORM_XCB_KHR)
625     xcb_destroy_window(connection, xcb_window);
626     xcb_disconnect(connection);
627     free(atom_wm_delete_window);
628 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
629     if (keyboard) wl_keyboard_destroy(keyboard);
630     if (pointer) wl_pointer_destroy(pointer);
631     if (seat) wl_seat_destroy(seat);
632     //xdg_toplevel_destroy(window_toplevel);
633     //xdg_surface_destroy(window_surface);
634     wl_shell_surface_destroy(window_surface);
635     wl_surface_destroy(window);
636 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
637     xdg_wm_base_destroy(wm_base);
638 #endif
639 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
640     if (xdg_decoration_mgr) {
641         zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
642         zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
643     }
644 #endif
645     wl_compositor_destroy(compositor);
646     wl_registry_destroy(registry);
647     wl_display_disconnect(display);
648 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
649     event_buffer->Release(event_buffer);
650     window->Release(window);
651     dfb->Release(dfb);
652 #endif
653     if (use_debug_messenger) {
654         inst.destroyDebugUtilsMessengerEXT(debug_messenger);
655     }
656     inst.destroy();
657 }
658
659 void Demo::create_device() {
660     float priorities = 0.0;
661
662     std::vector<vk::DeviceQueueCreateInfo> queues;
663     queues.push_back(vk::DeviceQueueCreateInfo().setQueueFamilyIndex(graphics_queue_family_index).setQueuePriorities(priorities));
664
665     if (separate_present_queue) {
666         queues.push_back(
667             vk::DeviceQueueCreateInfo().setQueueFamilyIndex(present_queue_family_index).setQueuePriorities(priorities));
668     }
669
670     auto deviceInfo = vk::DeviceCreateInfo().setQueueCreateInfos(queues).setPEnabledExtensionNames(enabled_device_extensions);
671     auto device_return = gpu.createDevice(deviceInfo);
672     VERIFY(device_return.result == vk::Result::eSuccess);
673     device = device_return.value;
674 }
675
676 void Demo::destroy_texture(texture_object &tex_objs) {
677     // clean up staging resources
678     device.freeMemory(tex_objs.mem);
679     if (tex_objs.image) device.destroyImage(tex_objs.image);
680     if (tex_objs.buffer) device.destroyBuffer(tex_objs.buffer);
681 }
682
683 void Demo::draw() {
684     // Ensure no more than FRAME_LAG renderings are outstanding
685     device.waitForFences(fences[frame_index], VK_TRUE, UINT64_MAX);
686     device.resetFences({fences[frame_index]});
687
688     vk::Result acquire_result;
689     do {
690         acquire_result =
691             device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
692         if (acquire_result == vk::Result::eErrorOutOfDateKHR) {
693             // demo.swapchain is out of date (e.g. the window was resized) and
694             // must be recreated:
695             resize();
696         } else if (acquire_result == vk::Result::eSuboptimalKHR) {
697             // swapchain is not as optimal as it could be, but the platform's
698             // presentation engine will still present the image correctly.
699             break;
700         } else if (acquire_result == vk::Result::eErrorSurfaceLostKHR) {
701             inst.destroySurfaceKHR(surface);
702             create_surface();
703             resize();
704         } else {
705             VERIFY(acquire_result == vk::Result::eSuccess);
706         }
707     } while (acquire_result != vk::Result::eSuccess);
708
709     update_data_buffer();
710
711     // Wait for the image acquired semaphore to be signaled to ensure
712     // that the image won't be rendered to until the presentation
713     // engine has fully released ownership to the application, and it is
714     // okay to render to the image.
715     vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
716
717     auto submit_result = graphics_queue.submit(vk::SubmitInfo()
718                                                    .setWaitDstStageMask(pipe_stage_flags)
719                                                    .setWaitSemaphores(image_acquired_semaphores[frame_index])
720                                                    .setCommandBuffers(swapchain_image_resources[current_buffer].cmd)
721                                                    .setSignalSemaphores(draw_complete_semaphores[frame_index]),
722                                                fences[frame_index]);
723     VERIFY(submit_result == vk::Result::eSuccess);
724
725     if (separate_present_queue) {
726         // If we are using separate queues, change image ownership to the
727         // present queue before presenting, waiting for the draw complete
728         // semaphore and signalling the ownership released semaphore when
729         // finished
730         auto change_owner_result =
731             present_queue.submit(vk::SubmitInfo()
732                                      .setWaitDstStageMask(pipe_stage_flags)
733                                      .setWaitSemaphores(draw_complete_semaphores[frame_index])
734                                      .setCommandBuffers(swapchain_image_resources[current_buffer].graphics_to_present_cmd)
735                                      .setSignalSemaphores(image_ownership_semaphores[frame_index]));
736         VERIFY(change_owner_result == vk::Result::eSuccess);
737     }
738
739     const auto presentInfo = vk::PresentInfoKHR()
740                                  .setWaitSemaphores(separate_present_queue ? image_ownership_semaphores[frame_index]
741                                                                            : draw_complete_semaphores[frame_index])
742                                  .setSwapchains(swapchain)
743                                  .setImageIndices(current_buffer);
744
745     // If we are using separate queues we have to wait for image ownership,
746     // otherwise wait for draw complete
747     auto present_result = present_queue.presentKHR(&presentInfo);
748     frame_index += 1;
749     frame_index %= FRAME_LAG;
750     if (present_result == vk::Result::eErrorOutOfDateKHR) {
751         // swapchain is out of date (e.g. the window was resized) and
752         // must be recreated:
753         resize();
754     } else if (present_result == vk::Result::eSuboptimalKHR) {
755         // SUBOPTIMAL could be due to resize
756         vk::SurfaceCapabilitiesKHR surfCapabilities;
757         auto caps_result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
758         VERIFY(caps_result == vk::Result::eSuccess);
759         if (surfCapabilities.currentExtent.width != width || surfCapabilities.currentExtent.height != height) {
760             resize();
761         }
762     } else if (present_result == vk::Result::eErrorSurfaceLostKHR) {
763         inst.destroySurfaceKHR(surface);
764         create_surface();
765         resize();
766     } else {
767         VERIFY(present_result == vk::Result::eSuccess);
768     }
769 }
770
771 void Demo::draw_build_cmd(const SwapchainImageResources &swapchain_image_resource) {
772     const auto commandBuffer = swapchain_image_resource.cmd;
773     vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
774                                            vk::ClearDepthStencilValue(1.0f, 0u)};
775
776     auto result = commandBuffer.begin(vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse));
777     VERIFY(result == vk::Result::eSuccess);
778
779     commandBuffer.beginRenderPass(vk::RenderPassBeginInfo()
780                                       .setRenderPass(render_pass)
781                                       .setFramebuffer(swapchain_image_resource.framebuffer)
782                                       .setRenderArea(vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)))
783                                       .setClearValueCount(2)
784                                       .setPClearValues(clearValues),
785                                   vk::SubpassContents::eInline);
786
787     commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
788     commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, swapchain_image_resource.descriptor_set,
789                                      {});
790     float viewport_dimension;
791     float viewport_x = 0.0f;
792     float viewport_y = 0.0f;
793     if (width < height) {
794         viewport_dimension = static_cast<float>(width);
795         viewport_y = (height - width) / 2.0f;
796     } else {
797         viewport_dimension = static_cast<float>(height);
798         viewport_x = (width - height) / 2.0f;
799     }
800
801     commandBuffer.setViewport(0, vk::Viewport()
802                                      .setX(viewport_x)
803                                      .setY(viewport_y)
804                                      .setWidth(viewport_dimension)
805                                      .setHeight(viewport_dimension)
806                                      .setMinDepth(0.0f)
807                                      .setMaxDepth(1.0f));
808
809     commandBuffer.setScissor(0, vk::Rect2D(vk::Offset2D{}, vk::Extent2D(width, height)));
810     commandBuffer.draw(12 * 3, 1, 0, 0);
811     // Note that ending the renderpass changes the image's layout from
812     // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
813     commandBuffer.endRenderPass();
814
815     if (separate_present_queue) {
816         // We have to transfer ownership from the graphics queue family to
817         // the
818         // present queue family to be able to present.  Note that we don't
819         // have
820         // to transfer from present queue family back to graphics queue
821         // family at
822         // the start of the next frame because we don't care about the
823         // image's
824         // contents at that point.
825         commandBuffer.pipelineBarrier(
826             vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), {}, {},
827             vk::ImageMemoryBarrier()
828                 .setSrcAccessMask(vk::AccessFlags())
829                 .setDstAccessMask(vk::AccessFlags())
830                 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
831                 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
832                 .setSrcQueueFamilyIndex(graphics_queue_family_index)
833                 .setDstQueueFamilyIndex(present_queue_family_index)
834                 .setImage(swapchain_image_resource.image)
835                 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1)));
836     }
837
838     result = commandBuffer.end();
839     VERIFY(result == vk::Result::eSuccess);
840 }
841
842 void Demo::prepare_init_cmd() {
843     auto cmd_pool_return = device.createCommandPool(vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index));
844     VERIFY(cmd_pool_return.result == vk::Result::eSuccess);
845     cmd_pool = cmd_pool_return.value;
846
847     auto cmd_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
848                                                         .setCommandPool(cmd_pool)
849                                                         .setLevel(vk::CommandBufferLevel::ePrimary)
850                                                         .setCommandBufferCount(1));
851     VERIFY(cmd_return.result == vk::Result::eSuccess);
852     cmd = cmd_return.value[0];
853
854     auto result = cmd.begin(vk::CommandBufferBeginInfo());
855     VERIFY(result == vk::Result::eSuccess);
856 }
857
858 void Demo::flush_init_cmd() {
859     auto result = cmd.end();
860     VERIFY(result == vk::Result::eSuccess);
861
862     auto fenceInfo = vk::FenceCreateInfo();
863     if (force_errors) {
864         // Remove sType to intentionally force validation layer errors.
865         fenceInfo.sType = vk::StructureType::eRenderPassBeginInfo;
866     }
867     auto fence_return = device.createFence(fenceInfo);
868     VERIFY(fence_return.result == vk::Result::eSuccess);
869     auto fence = fence_return.value;
870
871     result = graphics_queue.submit(vk::SubmitInfo().setCommandBuffers(cmd), fence);
872     VERIFY(result == vk::Result::eSuccess);
873
874     result = device.waitForFences(fence, VK_TRUE, UINT64_MAX);
875     VERIFY(result == vk::Result::eSuccess);
876
877     device.freeCommandBuffers(cmd_pool, cmd);
878     device.destroyFence(fence);
879 }
880
881 void Demo::init(int argc, char **argv) {
882     vec3 eye = {0.0f, 3.0f, 5.0f};
883     vec3 origin = {0, 0, 0};
884     vec3 up = {0.0f, 1.0f, 0.0};
885
886     presentMode = vk::PresentModeKHR::eFifo;
887     frameCount = UINT32_MAX;
888     width = 500;
889     height = 500;
890     use_xlib = false;
891     /* Autodetect suitable / best GPU by default */
892     gpu_number = -1;
893
894     for (int i = 1; i < argc; i++) {
895         if (strcmp(argv[i], "--use_staging") == 0) {
896             use_staging_buffer = true;
897             continue;
898         }
899         if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
900             presentMode = static_cast<vk::PresentModeKHR>(atoi(argv[i + 1]));
901             i++;
902             continue;
903         }
904         if (strcmp(argv[i], "--break") == 0) {
905             use_break = true;
906             continue;
907         }
908         if (strcmp(argv[i], "--validate") == 0) {
909             validate = true;
910             continue;
911         }
912         if (strcmp(argv[i], "--xlib") == 0) {
913             fprintf(stderr, "--xlib is deprecated and no longer does anything");
914             continue;
915         }
916         if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
917             sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
918             i++;
919             continue;
920         }
921         if (strcmp(argv[i], "--width") == 0) {
922             int32_t in_width = 0;
923             if (i < argc - 1 && sscanf(argv[i + 1], "%d", &in_width) == 1) {
924                 if (in_width > 0) {
925                     width = static_cast<uint32_t>(in_width);
926                     i++;
927                     continue;
928                 } else {
929                     ERR_EXIT("The --width parameter must be greater than 0", "User Error");
930                 }
931             }
932             ERR_EXIT("The --width parameter must be followed by a number", "User Error");
933         }
934         if (strcmp(argv[i], "--height") == 0) {
935             int32_t in_height = 0;
936             if (i < argc - 1 && sscanf(argv[i + 1], "%d", &height) == 1) {
937                 if (height > 0) {
938                     height = static_cast<uint32_t>(in_height);
939                     i++;
940                     continue;
941                 } else {
942                     ERR_EXIT("The --height parameter must be greater than 0", "User Error");
943                 }
944             }
945             ERR_EXIT("The --height parameter must be followed by a number", "User Error");
946         }
947         if (strcmp(argv[i], "--suppress_popups") == 0) {
948             suppress_popups = true;
949             continue;
950         }
951         if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
952             gpu_number = atoi(argv[i + 1]);
953             if (gpu_number < 0) invalid_gpu_selection = true;
954             i++;
955             continue;
956         }
957         if (strcmp(argv[i], "--force_errors") == 0) {
958             force_errors = true;
959             continue;
960         }
961         std::stringstream usage;
962         usage << "Usage:\n  " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
963               << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
964               << "\t[--gpu_number <index of physical device>]\n"
965               << "\t[--present_mode <present mode enum>]\n"
966               << "\t[--width <width>] [--height <height>]\n"
967               << "\t[--force_errors]\n"
968               << "\t<present_mode_enum>\n"
969               << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
970               << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
971               << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
972               << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
973
974 #if defined(_WIN32)
975         if (!suppress_popups) MessageBox(nullptr, usage.str().c_str(), "Usage Error", MB_OK);
976 #else
977         std::cerr << usage.str();
978         std::cerr.flush();
979 #endif
980         exit(1);
981     }
982
983     if (!use_xlib) {
984         init_connection();
985     }
986
987     init_vk();
988
989     spin_angle = 4.0f;
990     spin_increment = 0.2f;
991     pause = false;
992
993     mat4x4_perspective(projection_matrix, static_cast<float>(degreesToRadians(45.0f)), 1.0f, 0.1f, 100.0f);
994     mat4x4_look_at(view_matrix, eye, origin, up);
995     mat4x4_identity(model_matrix);
996
997     projection_matrix[1][1] *= -1;  // Flip projection matrix from GL to Vulkan orientation.
998 }
999
1000 void Demo::init_connection() {
1001 #if defined(VK_USE_PLATFORM_XCB_KHR)
1002     const xcb_setup_t *setup;
1003     xcb_screen_iterator_t iter;
1004     int scr;
1005
1006     const char *display_envar = getenv("DISPLAY");
1007     if (display_envar == nullptr || display_envar[0] == '\0') {
1008         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1009         fflush(stdout);
1010         exit(1);
1011     }
1012
1013     connection = xcb_connect(nullptr, &scr);
1014     if (xcb_connection_has_error(connection) > 0) {
1015         printf("Cannot connect to XCB.\nExiting ...\n");
1016         fflush(stdout);
1017         exit(1);
1018     }
1019
1020     setup = xcb_get_setup(connection);
1021     iter = xcb_setup_roots_iterator(setup);
1022     while (scr-- > 0) xcb_screen_next(&iter);
1023
1024     screen = iter.data;
1025 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1026     display = wl_display_connect(nullptr);
1027
1028     if (display == nullptr) {
1029         printf("Cannot connect to wayland.\nExiting ...\n");
1030         fflush(stdout);
1031         exit(1);
1032     }
1033
1034     registry = wl_display_get_registry(display);
1035     wl_registry_add_listener(registry, &registry_listener, this);
1036     wl_display_dispatch(display);
1037 #endif
1038 }
1039 #if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1040 int find_display_gpu(int gpu_number, const std::vector<vk::PhysicalDevice> &physical_devices) {
1041     uint32_t display_count = 0;
1042     int gpu_return = gpu_number;
1043     if (gpu_number >= 0) {
1044         auto display_props_return = physical_devices[gpu_number].getDisplayPropertiesKHR();
1045         VERIFY(display_props_return.result == vk::Result::eSuccess);
1046         display_count = display_props_return.value.size();
1047     } else {
1048         for (uint32_t i = 0; i < physical_devices.size(); i++) {
1049             auto display_props_return = physical_devices[i].getDisplayPropertiesKHR();
1050             VERIFY(display_props_return.result == vk::Result::eSuccess);
1051             if (display_props_return.value.size() > 0) {
1052                 display_count = display_props_return.value.size();
1053                 gpu_return = i;
1054                 break;
1055             }
1056         }
1057     }
1058     if (display_count > 0)
1059         return gpu_return;
1060     else
1061         return -1;
1062 }
1063 #endif
1064 VKAPI_ATTR VkBool32 VKAPI_CALL Demo::debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
1065                                                               VkDebugUtilsMessageTypeFlagsEXT messageType,
1066                                                               const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
1067                                                               void *pUserData) {
1068     std::ostringstream message;
1069     Demo &demo = *static_cast<Demo *>(pUserData);
1070
1071     if (demo.use_break) {
1072 #ifndef WIN32
1073         raise(SIGTRAP);
1074 #else
1075         DebugBreak();
1076 #endif
1077     }
1078     message << vk::to_string(vk::DebugUtilsMessageSeverityFlagBitsEXT(messageSeverity));
1079     message << " : " + vk::to_string(vk::DebugUtilsMessageTypeFlagsEXT(messageType));
1080
1081     if (vk::DebugUtilsMessageTypeFlagsEXT(messageType) & vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation) {
1082         validation_error = 1;
1083     }
1084
1085     message << " - Message Id Number: " << std::to_string(pCallbackData->messageIdNumber);
1086     message << " | Message Id Name: " << pCallbackData->pMessageIdName << "\n\t" << pCallbackData->pMessage << "\n";
1087
1088     if (pCallbackData->objectCount > 0) {
1089         message << "\n\tObjects - " << pCallbackData->objectCount << "\n";
1090         for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
1091             message << "\t\tObject[" << object << "] - "
1092                     << vk::to_string(vk::ObjectType(pCallbackData->pObjects[object].objectType)) << ", Handle ";
1093
1094             // Print handle correctly if it is a dispatchable handle - aka a pointer
1095             VkObjectType t = pCallbackData->pObjects[object].objectType;
1096             if (t == VK_OBJECT_TYPE_INSTANCE || t == VK_OBJECT_TYPE_PHYSICAL_DEVICE || t == VK_OBJECT_TYPE_DEVICE ||
1097                 t == VK_OBJECT_TYPE_COMMAND_BUFFER || t == VK_OBJECT_TYPE_QUEUE) {
1098                 message << reinterpret_cast<void*>(static_cast<uintptr_t>(pCallbackData->pObjects[object].objectHandle));
1099             } else {
1100                 message << pCallbackData->pObjects[object].objectHandle;
1101             }
1102             if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
1103                 message << ", Name \"" << pCallbackData->pObjects[object].pObjectName << "\"\n";
1104             } else {
1105                 message << "\n";
1106             }
1107         }
1108     }
1109     if (pCallbackData->cmdBufLabelCount > 0) {
1110         message << "\n\tCommand Buffer Labels - " << pCallbackData->cmdBufLabelCount << "\n";
1111         for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
1112             message << "\t\tLabel[" << cmd_buf_label << "] - " << pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName << " { "
1113                     << pCallbackData->pCmdBufLabels[cmd_buf_label].color[0] << ", "
1114                     << pCallbackData->pCmdBufLabels[cmd_buf_label].color[1] << ", "
1115                     << pCallbackData->pCmdBufLabels[cmd_buf_label].color[2] << ", "
1116                     << pCallbackData->pCmdBufLabels[cmd_buf_label].color[2] << "}\n";
1117         }
1118     }
1119
1120 #ifdef _WIN32
1121
1122     if (!demo.suppress_popups) {
1123         demo.in_callback = true;
1124         auto message_string = message.str();
1125         MessageBox(NULL, message_string.c_str(), "Alert", MB_OK);
1126         demo.in_callback = false;
1127     }
1128
1129 #elif defined(ANDROID)
1130
1131     if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
1132         __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message.str());
1133     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
1134         __android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message.str());
1135     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
1136         __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message.str());
1137     } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
1138         __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message.str());
1139     } else {
1140         __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message.str());
1141     }
1142
1143 #else
1144     std::cout << message.str() << std::endl;  // use endl to force a flush
1145 #endif
1146     return false;  // Don't bail out, but keep going.
1147 }
1148
1149 void Demo::init_vk() {
1150     std::vector<char const *> instance_validation_layers = {"VK_LAYER_KHRONOS_validation"};
1151
1152     // Look for validation layers
1153     vk::Bool32 validation_found = VK_FALSE;
1154     if (validate) {
1155         auto layers = vk::enumerateInstanceLayerProperties();
1156         VERIFY(layers.result == vk::Result::eSuccess);
1157
1158         validation_found = check_layers(instance_validation_layers, layers.value);
1159         if (validation_found) {
1160             enabled_layers.push_back("VK_LAYER_KHRONOS_validation");
1161         }
1162
1163         else {
1164             ERR_EXIT(
1165                 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1166                 "Please look at the Getting Started guide for additional information.\n",
1167                 "vkCreateInstance Failure");
1168         }
1169     }
1170
1171     /* Look for instance extensions */
1172     vk::Bool32 surfaceExtFound = VK_FALSE;
1173     vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1174     bool portabilityEnumerationActive = false;
1175
1176     auto instance_extensions_return = vk::enumerateInstanceExtensionProperties();
1177     VERIFY(instance_extensions_return.result == vk::Result::eSuccess);
1178
1179     for (const auto &extension : instance_extensions_return.value) {
1180         if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, extension.extensionName)) {
1181             enabled_instance_extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
1182         } else if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, extension.extensionName)) {
1183             use_debug_messenger = true;
1184             enabled_instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
1185         } else if (!strcmp(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME, extension.extensionName)) {
1186             // We want cube to be able to enumerate drivers that support the portability_subset extension, so we have to enable the
1187             // portability enumeration extension.
1188             portabilityEnumerationActive = true;
1189             enabled_instance_extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);
1190         } else if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1191             surfaceExtFound = 1;
1192             enabled_instance_extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1193         }
1194 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1195         else if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1196             platformSurfaceExtFound = 1;
1197             enabled_instance_extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1198         }
1199 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1200         else if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1201             platformSurfaceExtFound = 1;
1202             enabled_instance_extensions.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
1203         }
1204 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1205         else if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1206             platformSurfaceExtFound = 1;
1207             enabled_instance_extensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
1208         }
1209 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1210         else if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1211             platformSurfaceExtFound = 1;
1212             enabled_instance_extensions.push_back(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME);
1213         }
1214 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1215         else if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1216             platformSurfaceExtFound = 1;
1217             enabled_instance_extensions.push_back(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME);
1218         }
1219 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1220         else if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, extension.extensionName)) {
1221             platformSurfaceExtFound = 1;
1222             enabled_instance_extensions.push_back(VK_KHR_DISPLAY_EXTENSION_NAME);
1223         }
1224 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1225         else if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, extension.extensionName)) {
1226             platformSurfaceExtFound = 1;
1227             enabled_instance_extensions.push_back(VK_EXT_METAL_SURFACE_EXTENSION_NAME);
1228         }
1229 #endif
1230     }
1231
1232     if (!surfaceExtFound) {
1233         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1234                  " extension.\n\n"
1235                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1236                  "Please look at the Getting Started guide for additional information.\n",
1237                  "vkCreateInstance Failure");
1238     }
1239
1240     if (!platformSurfaceExtFound) {
1241 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1242         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1243                  " extension.\n\n"
1244                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1245                  "Please look at the Getting Started guide for additional information.\n",
1246                  "vkCreateInstance Failure");
1247 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1248         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1249                  " extension.\n\n"
1250                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1251                  "Please look at the Getting Started guide for additional information.\n",
1252                  "vkCreateInstance Failure");
1253 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1254         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1255                  " extension.\n\n"
1256                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1257                  "Please look at the Getting Started guide for additional information.\n",
1258                  "vkCreateInstance Failure");
1259 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1260         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1261                  " extension.\n\n"
1262                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1263                  "Please look at the Getting Started guide for additional information.\n",
1264                  "vkCreateInstance Failure");
1265 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1266         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1267                  " extension.\n\n"
1268                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1269                  "Please look at the Getting Started guide for additional information.\n",
1270                  "vkCreateInstance Failure");
1271 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1272         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1273                  " extension.\n\n"
1274                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1275                  "Please look at the Getting Started guide for additional information.\n",
1276                  "vkCreateInstance Failure");
1277 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1278         ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
1279                  " extension.\n\nDo you have a compatible "
1280                  "Vulkan installable client driver (ICD) installed?\nPlease "
1281                  "look at the Getting Started guide for additional "
1282                  "information.\n",
1283                  "vkCreateInstance Failure");
1284 #endif
1285     }
1286
1287     vk::DebugUtilsMessageSeverityFlagsEXT severityFlags(vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
1288                                                         vk::DebugUtilsMessageSeverityFlagBitsEXT::eError);
1289     vk::DebugUtilsMessageTypeFlagsEXT messageTypeFlags(vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
1290                                                        vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
1291                                                        vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation);
1292     auto debug_utils_create_info = vk::DebugUtilsMessengerCreateInfoEXT({}, severityFlags, messageTypeFlags,
1293                                                                         &debug_messenger_callback, static_cast<void *>(this));
1294
1295     auto const app = vk::ApplicationInfo()
1296                          .setPApplicationName(APP_SHORT_NAME)
1297                          .setApplicationVersion(0)
1298                          .setPEngineName(APP_SHORT_NAME)
1299                          .setEngineVersion(0)
1300                          .setApiVersion(VK_API_VERSION_1_0);
1301     auto const inst_info = vk::InstanceCreateInfo()
1302                                .setFlags(portabilityEnumerationActive ? vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR
1303                                                                       : static_cast<vk::InstanceCreateFlagBits>(0))
1304                                .setPNext((use_debug_messenger && validate) ? &debug_utils_create_info : nullptr)
1305                                .setPApplicationInfo(&app)
1306                                .setPEnabledLayerNames(enabled_layers)
1307                                .setPEnabledExtensionNames(enabled_instance_extensions);
1308
1309     auto instance_result = vk::createInstance(inst_info);
1310     if (instance_result.result == vk::Result::eErrorIncompatibleDriver) {
1311         ERR_EXIT(
1312             "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1313             "Please look at the Getting Started guide for additional information.\n",
1314             "vkCreateInstance Failure");
1315     } else if (instance_result.result == vk::Result::eErrorExtensionNotPresent) {
1316         ERR_EXIT(
1317             "Cannot find a specified extension library.\n"
1318             "Make sure your layers path is set appropriately.\n",
1319             "vkCreateInstance Failure");
1320     } else if (instance_result.result != vk::Result::eSuccess) {
1321         ERR_EXIT(
1322             "vkCreateInstance failed.\n\n"
1323             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1324             "Please look at the Getting Started guide for additional information.\n",
1325             "vkCreateInstance Failure");
1326     }
1327     inst = instance_result.value;
1328
1329     if (use_debug_messenger) {
1330         pfnVkCreateDebugUtilsMessengerEXT =
1331             reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(inst.getProcAddr("vkCreateDebugUtilsMessengerEXT"));
1332         pfnVkDestroyDebugUtilsMessengerEXT =
1333             reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(inst.getProcAddr("vkDestroyDebugUtilsMessengerEXT"));
1334         VERIFY(pfnVkCreateDebugUtilsMessengerEXT != nullptr && pfnVkDestroyDebugUtilsMessengerEXT != nullptr);
1335         auto create_debug_messenger_return = inst.createDebugUtilsMessengerEXT(debug_utils_create_info);
1336         VERIFY(create_debug_messenger_return.result == vk::Result::eSuccess);
1337         debug_messenger = create_debug_messenger_return.value;
1338     }
1339
1340     auto physical_device_return = inst.enumeratePhysicalDevices();
1341     VERIFY(physical_device_return.result == vk::Result::eSuccess);
1342     auto physical_devices = physical_device_return.value;
1343
1344     if (physical_devices.size() <= 0) {
1345         ERR_EXIT(
1346             "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1347             "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1348             "Please look at the Getting Started guide for additional information.\n",
1349             "vkEnumeratePhysicalDevices Failure");
1350     }
1351
1352     if (invalid_gpu_selection || (gpu_number >= 0 && !(static_cast<uint32_t>(gpu_number) < physical_devices.size()))) {
1353         fprintf(stderr, "GPU %d specified is not present, GPU count = %zu\n", gpu_number, physical_devices.size());
1354         ERR_EXIT("Specified GPU number is not present", "User Error");
1355     }
1356 #if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1357     gpu_number = find_display_gpu(gpu_number, physical_devices);
1358     if (gpu_number < 0) {
1359         printf("Cannot find any display!\n");
1360         fflush(stdout);
1361         exit(1);
1362     }
1363 #else
1364     /* Try to auto select most suitable device */
1365     if (gpu_number == -1) {
1366         constexpr uint32_t device_type_count = static_cast<uint32_t>(vk::PhysicalDeviceType::eCpu) + 1;
1367         std::array<uint32_t, device_type_count> count_device_type{};
1368
1369         for (uint32_t i = 0; i < physical_devices.size(); i++) {
1370             const auto physicalDeviceProperties = physical_devices[i].getProperties();
1371             assert(physicalDeviceProperties.deviceType <= vk::PhysicalDeviceType::eCpu);
1372             count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1373         }
1374
1375         std::array<vk::PhysicalDeviceType, device_type_count> const device_type_preference = {
1376             vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1377             vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1378
1379         vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1380         for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1381             if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1382                 search_for_device_type = device_type_preference[i];
1383                 break;
1384             }
1385         }
1386
1387         for (uint32_t i = 0; i < physical_devices.size(); i++) {
1388             const auto physicalDeviceProperties = physical_devices[i].getProperties();
1389             if (physicalDeviceProperties.deviceType == search_for_device_type) {
1390                 gpu_number = i;
1391                 break;
1392             }
1393         }
1394     }
1395 #endif
1396     assert(gpu_number >= 0);
1397     gpu = physical_devices[gpu_number];
1398     {
1399         auto physicalDeviceProperties = gpu.getProperties();
1400         fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1401                 to_string(physicalDeviceProperties.deviceType).c_str());
1402     }
1403
1404     /* Look for device extensions */
1405     vk::Bool32 swapchainExtFound = VK_FALSE;
1406
1407     auto device_extension_return = gpu.enumerateDeviceExtensionProperties();
1408     VERIFY(device_extension_return.result == vk::Result::eSuccess);
1409
1410     for (const auto &extension : device_extension_return.value) {
1411         if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, extension.extensionName)) {
1412             swapchainExtFound = 1;
1413             enabled_device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
1414         } else if (!strcmp("VK_KHR_portability_subset", extension.extensionName)) {
1415             enabled_device_extensions.push_back("VK_KHR_portability_subset");
1416         }
1417     }
1418
1419     if (!swapchainExtFound) {
1420         ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1421                  " extension.\n\n"
1422                  "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1423                  "Please look at the Getting Started guide for additional information.\n",
1424                  "vkCreateInstance Failure");
1425     }
1426
1427     gpu.getProperties(&gpu_props);
1428
1429     /* Call with nullptr data to get count */
1430     queue_props = gpu.getQueueFamilyProperties();
1431     assert(queue_props.size() >= 1);
1432
1433     // Query fine-grained feature support for this device.
1434     //  If app has specific feature requirements it should check supported
1435     //  features based on this query
1436     vk::PhysicalDeviceFeatures physDevFeatures;
1437     gpu.getFeatures(&physDevFeatures);
1438 }
1439
1440 void Demo::create_surface() {
1441 // Create a WSI surface for the window:
1442 #if defined(VK_USE_PLATFORM_WIN32_KHR)
1443     {
1444         auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1445
1446         auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1447         VERIFY(result == vk::Result::eSuccess);
1448     }
1449 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1450     {
1451         auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1452
1453         auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1454         VERIFY(result == vk::Result::eSuccess);
1455     }
1456 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
1457     {
1458         auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1459
1460         auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1461         VERIFY(result == vk::Result::eSuccess);
1462     }
1463 #elif defined(VK_USE_PLATFORM_XCB_KHR)
1464     {
1465         auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1466
1467         auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1468         VERIFY(result == vk::Result::eSuccess);
1469     }
1470 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1471     {
1472         auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1473
1474         auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1475         VERIFY(result == vk::Result::eSuccess);
1476     }
1477 #elif defined(VK_USE_PLATFORM_METAL_EXT)
1478     {
1479         auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
1480
1481         auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
1482         VERIFY(result == vk::Result::eSuccess);
1483     }
1484 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1485     {
1486         auto result = create_display_surface();
1487         VERIFY(result == vk::Result::eSuccess);
1488     }
1489 #endif
1490 }
1491
1492 void Demo::init_vk_swapchain() {
1493     create_surface();
1494     // Iterate over each queue to learn whether it supports presenting:
1495     std::vector<vk::Bool32> supportsPresent;
1496     for (uint32_t i = 0; i < static_cast<uint32_t>(queue_props.size()); i++) {
1497         auto supports = gpu.getSurfaceSupportKHR(i, surface);
1498         VERIFY(supports.result == vk::Result::eSuccess);
1499         supportsPresent.push_back(supports.value);
1500     }
1501
1502     uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1503     uint32_t presentQueueFamilyIndex = UINT32_MAX;
1504     for (uint32_t i = 0; i < static_cast<uint32_t>(queue_props.size()); i++) {
1505         if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1506             if (graphicsQueueFamilyIndex == UINT32_MAX) {
1507                 graphicsQueueFamilyIndex = i;
1508             }
1509
1510             if (supportsPresent[i] == VK_TRUE) {
1511                 graphicsQueueFamilyIndex = i;
1512                 presentQueueFamilyIndex = i;
1513                 break;
1514             }
1515         }
1516     }
1517
1518     if (presentQueueFamilyIndex == UINT32_MAX) {
1519         // If didn't find a queue that supports both graphics and present,
1520         // then
1521         // find a separate present queue.
1522         for (uint32_t i = 0; i < queue_props.size(); ++i) {
1523             if (supportsPresent[i] == VK_TRUE) {
1524                 presentQueueFamilyIndex = i;
1525                 break;
1526             }
1527         }
1528     }
1529
1530     // Generate error if could not find both a graphics and a present queue
1531     if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1532         ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1533     }
1534
1535     graphics_queue_family_index = graphicsQueueFamilyIndex;
1536     present_queue_family_index = presentQueueFamilyIndex;
1537     separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
1538
1539     create_device();
1540
1541     graphics_queue = device.getQueue(graphics_queue_family_index, 0);
1542     if (!separate_present_queue) {
1543         present_queue = graphics_queue;
1544     } else {
1545         present_queue = device.getQueue(present_queue_family_index, 0);
1546     }
1547
1548     // Get the list of VkFormat's that are supported:
1549     auto surface_formats_return = gpu.getSurfaceFormatsKHR(surface);
1550     VERIFY(surface_formats_return.result == vk::Result::eSuccess);
1551
1552     vk::SurfaceFormatKHR surfaceFormat = pick_surface_format(surface_formats_return.value);
1553     format = surfaceFormat.format;
1554     color_space = surfaceFormat.colorSpace;
1555
1556     quit = false;
1557     curFrame = 0;
1558
1559     // Create semaphores to synchronize acquiring presentable buffers before
1560     // rendering and waiting for drawing to be complete before presenting
1561     auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
1562
1563     // Create fences that we can use to throttle if we get too far
1564     // ahead of the image presents
1565     auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1566     for (uint32_t i = 0; i < FRAME_LAG; i++) {
1567         vk::Result result = device.createFence(&fence_ci, nullptr, &fences[i]);
1568         VERIFY(result == vk::Result::eSuccess);
1569
1570         result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1571         VERIFY(result == vk::Result::eSuccess);
1572
1573         result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1574         VERIFY(result == vk::Result::eSuccess);
1575
1576         if (separate_present_queue) {
1577             result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
1578             VERIFY(result == vk::Result::eSuccess);
1579         }
1580     }
1581     frame_index = 0;
1582
1583     // Get Memory information and properties
1584     memory_properties = gpu.getMemoryProperties();
1585 }
1586
1587 void Demo::prepare() {
1588     prepare_init_cmd();
1589
1590     prepare_buffers();
1591     prepare_depth();
1592     prepare_textures();
1593     prepare_cube_data_buffers();
1594
1595     prepare_descriptor_layout();
1596     prepare_render_pass();
1597     prepare_pipeline();
1598
1599     for (auto &swapchain_image_resource : swapchain_image_resources) {
1600         auto alloc_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
1601                                                               .setCommandPool(cmd_pool)
1602                                                               .setLevel(vk::CommandBufferLevel::ePrimary)
1603                                                               .setCommandBufferCount(1));
1604         VERIFY(alloc_return.result == vk::Result::eSuccess);
1605         swapchain_image_resource.cmd = alloc_return.value[0];
1606     }
1607
1608     if (separate_present_queue) {
1609         auto present_cmd_pool_return =
1610             device.createCommandPool(vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index));
1611         VERIFY(present_cmd_pool_return.result == vk::Result::eSuccess);
1612         present_cmd_pool = present_cmd_pool_return.value;
1613
1614         for (auto &swapchain_image_resource : swapchain_image_resources) {
1615             auto alloc_cmd_return = device.allocateCommandBuffers(vk::CommandBufferAllocateInfo()
1616                                                                       .setCommandPool(present_cmd_pool)
1617                                                                       .setLevel(vk::CommandBufferLevel::ePrimary)
1618                                                                       .setCommandBufferCount(1));
1619             VERIFY(alloc_cmd_return.result == vk::Result::eSuccess);
1620             swapchain_image_resource.graphics_to_present_cmd = alloc_cmd_return.value[0];
1621             build_image_ownership_cmd(swapchain_image_resource);
1622         }
1623     }
1624
1625     prepare_descriptor_pool();
1626     prepare_descriptor_set();
1627
1628     prepare_framebuffers();
1629
1630     for (const auto &swapchain_image_resource : swapchain_image_resources) {
1631         draw_build_cmd(swapchain_image_resource);
1632     }
1633
1634     /*
1635      * Prepare functions above may generate pipeline commands
1636      * that need to be flushed before beginning the render loop.
1637      */
1638     flush_init_cmd();
1639     if (staging_texture.buffer) {
1640         destroy_texture(staging_texture);
1641     }
1642
1643     current_buffer = 0;
1644     prepared = true;
1645 }
1646
1647 void Demo::prepare_buffers() {
1648     vk::SwapchainKHR oldSwapchain = swapchain;
1649
1650     // Check the surface capabilities and formats
1651     auto surface_capabilities_return = gpu.getSurfaceCapabilitiesKHR(surface);
1652     VERIFY(surface_capabilities_return.result == vk::Result::eSuccess);
1653     auto surfCapabilities = surface_capabilities_return.value;
1654
1655     auto present_modes_return = gpu.getSurfacePresentModesKHR(surface);
1656     VERIFY(present_modes_return.result == vk::Result::eSuccess);
1657     auto present_modes = present_modes_return.value;
1658
1659     vk::Extent2D swapchainExtent;
1660     // width and height are either both -1, or both not -1.
1661     if (surfCapabilities.currentExtent.width == static_cast<uint32_t>(-1)) {
1662         // If the surface size is undefined, the size is set to
1663         // the size of the images requested.
1664         swapchainExtent.width = width;
1665         swapchainExtent.height = height;
1666     } else {
1667         // If the surface size is defined, the swap chain size must match
1668         swapchainExtent = surfCapabilities.currentExtent;
1669         width = surfCapabilities.currentExtent.width;
1670         height = surfCapabilities.currentExtent.height;
1671     }
1672
1673     // The FIFO present mode is guaranteed by the spec to be supported
1674     // and to have no tearing.  It's a great default present mode to use.
1675     vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1676
1677     //  There are times when you may wish to use another present mode.  The
1678     //  following code shows how to select them, and the comments provide some
1679     //  reasons you may wish to use them.
1680     //
1681     // It should be noted that Vulkan 1.0 doesn't provide a method for
1682     // synchronizing rendering with the presentation engine's display.  There
1683     // is a method provided for throttling rendering with the display, but
1684     // there are some presentation engines for which this method will not work.
1685     // If an application doesn't throttle its rendering, and if it renders much
1686     // faster than the refresh rate of the display, this can waste power on
1687     // mobile devices.  That is because power is being spent rendering images
1688     // that may never be seen.
1689
1690     // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1691     // about
1692     // tearing, or have some way of synchronizing their rendering with the
1693     // display.
1694     // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1695     // generally render a new presentable image every refresh cycle, but are
1696     // occasionally early.  In this case, the application wants the new
1697     // image
1698     // to be displayed instead of the previously-queued-for-presentation
1699     // image
1700     // that has not yet been displayed.
1701     // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1702     // render a new presentable image every refresh cycle, but are
1703     // occasionally
1704     // late.  In this case (perhaps because of stuttering/latency concerns),
1705     // the application wants the late image to be immediately displayed,
1706     // even
1707     // though that may mean some tearing.
1708
1709     if (presentMode != swapchainPresentMode) {
1710         for (const auto &mode : present_modes) {
1711             if (mode == presentMode) {
1712                 swapchainPresentMode = mode;
1713                 break;
1714             }
1715         }
1716     }
1717
1718     if (swapchainPresentMode != presentMode) {
1719         ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1720     }
1721
1722     // Determine the number of VkImages to use in the swap chain.
1723     // Application desires to acquire 3 images at a time for triple
1724     // buffering
1725     uint32_t desiredNumOfSwapchainImages = 3;
1726     if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1727         desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1728     }
1729
1730     // If maxImageCount is 0, we can ask for as many images as we want,
1731     // otherwise
1732     // we're limited to maxImageCount
1733     if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1734         // Application must settle for fewer images than desired:
1735         desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1736     }
1737
1738     vk::SurfaceTransformFlagBitsKHR preTransform;
1739     if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1740         preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1741     } else {
1742         preTransform = surfCapabilities.currentTransform;
1743     }
1744
1745     // Find a supported composite alpha mode - one of these is guaranteed to be set
1746     vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1747     std::array<vk::CompositeAlphaFlagBitsKHR, 4> compositeAlphaFlags = {
1748         vk::CompositeAlphaFlagBitsKHR::eOpaque,
1749         vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1750         vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1751         vk::CompositeAlphaFlagBitsKHR::eInherit,
1752     };
1753     for (const auto &compositeAlphaFlag : compositeAlphaFlags) {
1754         if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlag) {
1755             compositeAlpha = compositeAlphaFlag;
1756             break;
1757         }
1758     }
1759
1760     auto swapchain_return = device.createSwapchainKHR(vk::SwapchainCreateInfoKHR()
1761                                                           .setSurface(surface)
1762                                                           .setMinImageCount(desiredNumOfSwapchainImages)
1763                                                           .setImageFormat(format)
1764                                                           .setImageColorSpace(color_space)
1765                                                           .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1766                                                           .setImageArrayLayers(1)
1767                                                           .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1768                                                           .setImageSharingMode(vk::SharingMode::eExclusive)
1769                                                           .setPreTransform(preTransform)
1770                                                           .setCompositeAlpha(compositeAlpha)
1771                                                           .setPresentMode(swapchainPresentMode)
1772                                                           .setClipped(true)
1773                                                           .setOldSwapchain(oldSwapchain));
1774     VERIFY(swapchain_return.result == vk::Result::eSuccess);
1775     swapchain = swapchain_return.value;
1776
1777     // If we just re-created an existing swapchain, we should destroy the
1778     // old
1779     // swapchain at this point.
1780     // Note: destroying the swapchain also cleans up all its associated
1781     // presentable images once the platform is done with them.
1782     if (oldSwapchain) {
1783         device.destroySwapchainKHR(oldSwapchain);
1784     }
1785
1786     auto swapchain_images_return = device.getSwapchainImagesKHR(swapchain);
1787     VERIFY(swapchain_images_return.result == vk::Result::eSuccess);
1788     swapchain_image_resources.resize(swapchain_images_return.value.size());
1789
1790     for (uint32_t i = 0; i < swapchain_image_resources.size(); ++i) {
1791         auto color_image_view = vk::ImageViewCreateInfo()
1792                                     .setViewType(vk::ImageViewType::e2D)
1793                                     .setFormat(format)
1794                                     .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1795
1796         swapchain_image_resources[i].image = swapchain_images_return.value[i];
1797
1798         color_image_view.image = swapchain_image_resources[i].image;
1799
1800         auto image_view_return = device.createImageView(color_image_view);
1801         VERIFY(image_view_return.result == vk::Result::eSuccess);
1802         swapchain_image_resources[i].view = image_view_return.value;
1803     }
1804 }
1805
1806 void Demo::prepare_cube_data_buffers() {
1807     mat4x4 VP;
1808     mat4x4_mul(VP, projection_matrix, view_matrix);
1809
1810     mat4x4 MVP;
1811     mat4x4_mul(MVP, VP, model_matrix);
1812
1813     vktexcube_vs_uniform data;
1814     memcpy(data.mvp, MVP, sizeof(MVP));
1815     //    dumpMatrix("MVP", MVP)
1816
1817     for (int32_t i = 0; i < 12 * 3; i++) {
1818         data.position[i][0] = g_vertex_buffer_data[i * 3];
1819         data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1820         data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1821         data.position[i][3] = 1.0f;
1822         data.attr[i][0] = g_uv_buffer_data[2 * i];
1823         data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1824         data.attr[i][2] = 0;
1825         data.attr[i][3] = 0;
1826     }
1827
1828     auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1829
1830     for (auto &swapchain_image_resource : swapchain_image_resources) {
1831         auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resource.uniform_buffer);
1832         VERIFY(result == vk::Result::eSuccess);
1833
1834         vk::MemoryRequirements mem_reqs;
1835         device.getBufferMemoryRequirements(swapchain_image_resource.uniform_buffer, &mem_reqs);
1836
1837         auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
1838
1839         bool const pass = memory_type_from_properties(
1840             mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1841             mem_alloc.memoryTypeIndex);
1842         VERIFY(pass);
1843
1844         result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resource.uniform_memory);
1845         VERIFY(result == vk::Result::eSuccess);
1846
1847         result = device.mapMemory(swapchain_image_resource.uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1848                                   &swapchain_image_resource.uniform_memory_ptr);
1849         VERIFY(result == vk::Result::eSuccess);
1850
1851         memcpy(swapchain_image_resource.uniform_memory_ptr, &data, sizeof data);
1852
1853         result = device.bindBufferMemory(swapchain_image_resource.uniform_buffer, swapchain_image_resource.uniform_memory, 0);
1854         VERIFY(result == vk::Result::eSuccess);
1855     }
1856 }
1857
1858 void Demo::prepare_depth() {
1859     depth.format = vk::Format::eD16Unorm;
1860
1861     auto const image = vk::ImageCreateInfo()
1862                            .setImageType(vk::ImageType::e2D)
1863                            .setFormat(depth.format)
1864                            .setExtent({width, height, 1})
1865                            .setMipLevels(1)
1866                            .setArrayLayers(1)
1867                            .setSamples(vk::SampleCountFlagBits::e1)
1868                            .setTiling(vk::ImageTiling::eOptimal)
1869                            .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1870                            .setSharingMode(vk::SharingMode::eExclusive)
1871                            .setInitialLayout(vk::ImageLayout::eUndefined);
1872
1873     auto result = device.createImage(&image, nullptr, &depth.image);
1874     VERIFY(result == vk::Result::eSuccess);
1875
1876     vk::MemoryRequirements mem_reqs;
1877     device.getImageMemoryRequirements(depth.image, &mem_reqs);
1878
1879     depth.mem_alloc.setAllocationSize(mem_reqs.size);
1880     depth.mem_alloc.setMemoryTypeIndex(0);
1881
1882     auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1883                                                   depth.mem_alloc.memoryTypeIndex);
1884     VERIFY(pass);
1885
1886     result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1887     VERIFY(result == vk::Result::eSuccess);
1888
1889     result = device.bindImageMemory(depth.image, depth.mem, 0);
1890     VERIFY(result == vk::Result::eSuccess);
1891
1892     auto view = vk::ImageViewCreateInfo()
1893                     .setImage(depth.image)
1894                     .setViewType(vk::ImageViewType::e2D)
1895                     .setFormat(depth.format)
1896                     .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1897     if (force_errors) {
1898         // Intentionally force a bad pNext value to generate a validation layer error
1899         view.pNext = &image;
1900     }
1901     result = device.createImageView(&view, nullptr, &depth.view);
1902     VERIFY(result == vk::Result::eSuccess);
1903 }
1904
1905 void Demo::prepare_descriptor_layout() {
1906     std::array<vk::DescriptorSetLayoutBinding, 2> const layout_bindings = {
1907         vk::DescriptorSetLayoutBinding()
1908             .setBinding(0)
1909             .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1910             .setDescriptorCount(1)
1911             .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1912             .setPImmutableSamplers(nullptr),
1913         vk::DescriptorSetLayoutBinding()
1914             .setBinding(1)
1915             .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1916             .setDescriptorCount(texture_count)
1917             .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1918             .setPImmutableSamplers(nullptr)};
1919
1920     auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindings(layout_bindings);
1921
1922     auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1923     VERIFY(result == vk::Result::eSuccess);
1924
1925     auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayouts(desc_layout);
1926
1927     result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1928     VERIFY(result == vk::Result::eSuccess);
1929 }
1930
1931 void Demo::prepare_descriptor_pool() {
1932     std::array<vk::DescriptorPoolSize, 2> const poolSizes = {
1933         vk::DescriptorPoolSize()
1934             .setType(vk::DescriptorType::eUniformBuffer)
1935             .setDescriptorCount(static_cast<uint32_t>(swapchain_image_resources.size())),
1936         vk::DescriptorPoolSize()
1937             .setType(vk::DescriptorType::eCombinedImageSampler)
1938             .setDescriptorCount(static_cast<uint32_t>(swapchain_image_resources.size()) * texture_count)};
1939
1940     auto const descriptor_pool =
1941         vk::DescriptorPoolCreateInfo().setMaxSets(static_cast<uint32_t>(swapchain_image_resources.size())).setPoolSizes(poolSizes);
1942
1943     auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1944     VERIFY(result == vk::Result::eSuccess);
1945 }
1946
1947 void Demo::prepare_descriptor_set() {
1948     auto const alloc_info = vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setSetLayouts(desc_layout);
1949
1950     auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(vktexcube_vs_uniform));
1951
1952     std::array<vk::DescriptorImageInfo, texture_count> tex_descs;
1953     for (uint32_t i = 0; i < texture_count; i++) {
1954         tex_descs[i].setSampler(textures[i].sampler);
1955         tex_descs[i].setImageView(textures[i].view);
1956         tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1957     }
1958
1959     std::array<vk::WriteDescriptorSet, 2> writes;
1960     writes[0].setDescriptorCount(1).setDescriptorType(vk::DescriptorType::eUniformBuffer).setPBufferInfo(&buffer_info);
1961     writes[1]
1962         .setDstBinding(1)
1963         .setDescriptorCount(texture_count)
1964         .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1965         .setImageInfo(tex_descs);
1966
1967     for (auto &swapchain_image_resource : swapchain_image_resources) {
1968         auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resource.descriptor_set);
1969         VERIFY(result == vk::Result::eSuccess);
1970
1971         buffer_info.setBuffer(swapchain_image_resource.uniform_buffer);
1972         writes[0].setDstSet(swapchain_image_resource.descriptor_set);
1973         writes[1].setDstSet(swapchain_image_resource.descriptor_set);
1974         device.updateDescriptorSets(writes, {});
1975     }
1976 }
1977
1978 void Demo::prepare_framebuffers() {
1979     std::array<vk::ImageView, 2> attachments;
1980     attachments[1] = depth.view;
1981
1982     for (auto &swapchain_image_resource : swapchain_image_resources) {
1983         attachments[0] = swapchain_image_resource.view;
1984         auto const framebuffer_return = device.createFramebuffer(vk::FramebufferCreateInfo()
1985                                                                      .setRenderPass(render_pass)
1986                                                                      .setAttachments(attachments)
1987                                                                      .setWidth(width)
1988                                                                      .setHeight(height)
1989                                                                      .setLayers(1));
1990         VERIFY(framebuffer_return.result == vk::Result::eSuccess);
1991         swapchain_image_resource.framebuffer = framebuffer_return.value;
1992     }
1993 }
1994
1995 vk::ShaderModule Demo::prepare_fs() {
1996     const uint32_t fragShaderCode[] = {
1997 #include "cube.frag.inc"
1998     };
1999
2000     frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
2001
2002     return frag_shader_module;
2003 }
2004
2005 void Demo::prepare_pipeline() {
2006     vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2007     auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2008     VERIFY(result == vk::Result::eSuccess);
2009
2010     std::array<vk::PipelineShaderStageCreateInfo, 2> const shaderStageInfo = {
2011         vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2012         vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2013
2014     vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2015
2016     auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2017
2018     // TODO: Where are pViewports and pScissors set?
2019     auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2020
2021     auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2022                                        .setDepthClampEnable(VK_FALSE)
2023                                        .setRasterizerDiscardEnable(VK_FALSE)
2024                                        .setPolygonMode(vk::PolygonMode::eFill)
2025                                        .setCullMode(vk::CullModeFlagBits::eBack)
2026                                        .setFrontFace(vk::FrontFace::eCounterClockwise)
2027                                        .setDepthBiasEnable(VK_FALSE)
2028                                        .setLineWidth(1.0f);
2029
2030     auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2031
2032     auto const stencilOp =
2033         vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2034
2035     auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2036                                       .setDepthTestEnable(VK_TRUE)
2037                                       .setDepthWriteEnable(VK_TRUE)
2038                                       .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2039                                       .setDepthBoundsTestEnable(VK_FALSE)
2040                                       .setStencilTestEnable(VK_FALSE)
2041                                       .setFront(stencilOp)
2042                                       .setBack(stencilOp);
2043
2044     std::array<vk::PipelineColorBlendAttachmentState, 1> const colorBlendAttachments = {
2045         vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2046                                                                   vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2047
2048     auto const colorBlendInfo = vk::PipelineColorBlendStateCreateInfo().setAttachments(colorBlendAttachments);
2049
2050     std::array<vk::DynamicState, 2> const dynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2051
2052     auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setDynamicStates(dynamicStates);
2053
2054     auto pipline_return = device.createGraphicsPipelines(pipelineCache, vk::GraphicsPipelineCreateInfo()
2055                                                                             .setStages(shaderStageInfo)
2056                                                                             .setPVertexInputState(&vertexInputInfo)
2057                                                                             .setPInputAssemblyState(&inputAssemblyInfo)
2058                                                                             .setPViewportState(&viewportInfo)
2059                                                                             .setPRasterizationState(&rasterizationInfo)
2060                                                                             .setPMultisampleState(&multisampleInfo)
2061                                                                             .setPDepthStencilState(&depthStencilInfo)
2062                                                                             .setPColorBlendState(&colorBlendInfo)
2063                                                                             .setPDynamicState(&dynamicStateInfo)
2064                                                                             .setLayout(pipeline_layout)
2065                                                                             .setRenderPass(render_pass));
2066     VERIFY(result == vk::Result::eSuccess);
2067     pipeline = pipline_return.value.at(0);
2068
2069     device.destroyShaderModule(frag_shader_module);
2070     device.destroyShaderModule(vert_shader_module);
2071 }
2072
2073 void Demo::prepare_render_pass() {
2074     // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2075     // because at the start of the renderpass, we don't care about their contents.
2076     // At the start of the subpass, the color attachment's layout will be transitioned
2077     // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2078     // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.  At the end of
2079     // the renderpass, the color attachment's layout will be transitioned to
2080     // LAYOUT_PRESENT_SRC_KHR to be ready to present.  This is all done as part of
2081     // the renderpass, no barriers are necessary.
2082     std::array<vk::AttachmentDescription, 2> const attachments = {
2083         vk::AttachmentDescription()
2084             .setFormat(format)
2085             .setSamples(vk::SampleCountFlagBits::e1)
2086             .setLoadOp(vk::AttachmentLoadOp::eClear)
2087             .setStoreOp(vk::AttachmentStoreOp::eStore)
2088             .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2089             .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2090             .setInitialLayout(vk::ImageLayout::eUndefined)
2091             .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2092         vk::AttachmentDescription()
2093             .setFormat(depth.format)
2094             .setSamples(vk::SampleCountFlagBits::e1)
2095             .setLoadOp(vk::AttachmentLoadOp::eClear)
2096             .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2097             .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2098             .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2099             .setInitialLayout(vk::ImageLayout::eUndefined)
2100             .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2101
2102     auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2103
2104     auto const depth_reference =
2105         vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2106
2107     auto const subpass = vk::SubpassDescription()
2108                              .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2109                              .setColorAttachments(color_reference)
2110                              .setPDepthStencilAttachment(&depth_reference);
2111
2112     vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2113     std::array<vk::SubpassDependency, 2> const dependencies = {
2114         vk::SubpassDependency()  // Depth buffer is shared between swapchain images
2115             .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2116             .setDstSubpass(0)
2117             .setSrcStageMask(stages)
2118             .setDstStageMask(stages)
2119             .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2120             .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2121             .setDependencyFlags(vk::DependencyFlags()),
2122         vk::SubpassDependency()  // Image layout transition
2123             .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2124             .setDstSubpass(0)
2125             .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2126             .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2127             .setSrcAccessMask(vk::AccessFlagBits())
2128             .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2129             .setDependencyFlags(vk::DependencyFlags()),
2130     };
2131
2132     const auto render_pass_result = device.createRenderPass(
2133         vk::RenderPassCreateInfo().setAttachments(attachments).setSubpasses(subpass).setDependencies(dependencies));
2134     VERIFY(render_pass_result.result == vk::Result::eSuccess);
2135     render_pass = render_pass_result.value;
2136 }
2137
2138 vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2139     const auto shader_module_return = device.createShaderModule(vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code));
2140     VERIFY(shader_module_return.result == vk::Result::eSuccess);
2141
2142     return shader_module_return.value;
2143 }
2144
2145 void Demo::prepare_texture_buffer(const char *filename, texture_object &tex_obj) {
2146     vk::SubresourceLayout tex_layout;
2147
2148     if (!loadTexture(filename, nullptr, tex_layout, tex_obj.tex_width, tex_obj.tex_height)) {
2149         ERR_EXIT("Failed to load textures", "Load Texture Failure");
2150     }
2151
2152     auto const buffer_create_info = vk::BufferCreateInfo()
2153                                         .setSize(tex_obj.tex_width * tex_obj.tex_height * 4)
2154                                         .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2155                                         .setSharingMode(vk::SharingMode::eExclusive);
2156
2157     auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj.buffer);
2158     VERIFY(result == vk::Result::eSuccess);
2159
2160     vk::MemoryRequirements mem_reqs;
2161     device.getBufferMemoryRequirements(tex_obj.buffer, &mem_reqs);
2162
2163     tex_obj.mem_alloc.setAllocationSize(mem_reqs.size);
2164     tex_obj.mem_alloc.setMemoryTypeIndex(0);
2165
2166     vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2167     auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, tex_obj.mem_alloc.memoryTypeIndex);
2168     VERIFY(pass == true);
2169
2170     result = device.allocateMemory(&tex_obj.mem_alloc, nullptr, &(tex_obj.mem));
2171     VERIFY(result == vk::Result::eSuccess);
2172
2173     result = device.bindBufferMemory(tex_obj.buffer, tex_obj.mem, 0);
2174     VERIFY(result == vk::Result::eSuccess);
2175
2176     vk::SubresourceLayout layout;
2177     layout.rowPitch = tex_obj.tex_width * 4;
2178     auto data = device.mapMemory(tex_obj.mem, 0, tex_obj.mem_alloc.allocationSize);
2179     VERIFY(data.result == vk::Result::eSuccess);
2180
2181     if (!loadTexture(filename, (uint8_t *)data.value, layout, tex_obj.tex_width, tex_obj.tex_height)) {
2182         fprintf(stderr, "Error loading texture: %s\n", filename);
2183     }
2184
2185     device.unmapMemory(tex_obj.mem);
2186 }
2187
2188 void Demo::prepare_texture_image(const char *filename, texture_object &tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2189                                  vk::MemoryPropertyFlags required_props) {
2190     vk::SubresourceLayout tex_layout;
2191     if (!loadTexture(filename, nullptr, tex_layout, tex_obj.tex_width, tex_obj.tex_height)) {
2192         ERR_EXIT("Failed to load textures", "Load Texture Failure");
2193     }
2194
2195     auto const image_create_info = vk::ImageCreateInfo()
2196                                        .setImageType(vk::ImageType::e2D)
2197                                        .setFormat(vk::Format::eR8G8B8A8Unorm)
2198                                        .setExtent({tex_obj.tex_width, tex_obj.tex_height, 1})
2199                                        .setMipLevels(1)
2200                                        .setArrayLayers(1)
2201                                        .setSamples(vk::SampleCountFlagBits::e1)
2202                                        .setTiling(tiling)
2203                                        .setUsage(usage)
2204                                        .setSharingMode(vk::SharingMode::eExclusive)
2205                                        .setInitialLayout(vk::ImageLayout::ePreinitialized);
2206
2207     auto result = device.createImage(&image_create_info, nullptr, &tex_obj.image);
2208     VERIFY(result == vk::Result::eSuccess);
2209
2210     vk::MemoryRequirements mem_reqs;
2211     device.getImageMemoryRequirements(tex_obj.image, &mem_reqs);
2212
2213     tex_obj.mem_alloc.setAllocationSize(mem_reqs.size);
2214     tex_obj.mem_alloc.setMemoryTypeIndex(0);
2215
2216     auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, tex_obj.mem_alloc.memoryTypeIndex);
2217     VERIFY(pass == true);
2218
2219     result = device.allocateMemory(&tex_obj.mem_alloc, nullptr, &tex_obj.mem);
2220     VERIFY(result == vk::Result::eSuccess);
2221
2222     result = device.bindImageMemory(tex_obj.image, tex_obj.mem, 0);
2223     VERIFY(result == vk::Result::eSuccess);
2224
2225     if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2226         auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2227         vk::SubresourceLayout layout;
2228         device.getImageSubresourceLayout(tex_obj.image, &subres, &layout);
2229
2230         auto data = device.mapMemory(tex_obj.mem, 0, tex_obj.mem_alloc.allocationSize);
2231         VERIFY(data.result == vk::Result::eSuccess);
2232
2233         if (!loadTexture(filename, (uint8_t *)data.value, layout, tex_obj.tex_width, tex_obj.tex_height)) {
2234             fprintf(stderr, "Error loading texture: %s\n", filename);
2235         }
2236
2237         device.unmapMemory(tex_obj.mem);
2238     }
2239
2240     tex_obj.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2241 }
2242
2243 void Demo::prepare_textures() {
2244     vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2245     vk::FormatProperties props;
2246     gpu.getFormatProperties(tex_format, &props);
2247
2248     for (uint32_t i = 0; i < texture_count; i++) {
2249         if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2250             /* Device can texture using linear textures */
2251             prepare_texture_image(tex_files[i], textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2252                                   vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2253             // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2254             // shader to run until layout transition completes
2255             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2256                              textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2257                              vk::PipelineStageFlagBits::eFragmentShader);
2258             staging_texture.image = vk::Image();
2259         } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2260             /* Must use staging buffer to copy linear texture to optimized */
2261
2262             prepare_texture_buffer(tex_files[i], staging_texture);
2263
2264             prepare_texture_image(tex_files[i], textures[i], vk::ImageTiling::eOptimal,
2265                                   vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2266                                   vk::MemoryPropertyFlagBits::eDeviceLocal);
2267
2268             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2269                              vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2270                              vk::PipelineStageFlagBits::eTransfer);
2271
2272             auto const subresource = vk::ImageSubresourceLayers()
2273                                          .setAspectMask(vk::ImageAspectFlagBits::eColor)
2274                                          .setMipLevel(0)
2275                                          .setBaseArrayLayer(0)
2276                                          .setLayerCount(1);
2277
2278             auto const copy_region = vk::BufferImageCopy()
2279                                          .setBufferOffset(0)
2280                                          .setBufferRowLength(staging_texture.tex_width)
2281                                          .setBufferImageHeight(staging_texture.tex_height)
2282                                          .setImageSubresource(subresource)
2283                                          .setImageOffset({0, 0, 0})
2284                                          .setImageExtent({staging_texture.tex_width, staging_texture.tex_height, 1});
2285
2286             cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
2287
2288             set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2289                              textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2290                              vk::PipelineStageFlagBits::eFragmentShader);
2291         } else {
2292             assert(!"No support for R8G8B8A8_UNORM as texture image format");
2293         }
2294
2295         auto const samplerInfo = vk::SamplerCreateInfo()
2296                                      .setMagFilter(vk::Filter::eNearest)
2297                                      .setMinFilter(vk::Filter::eNearest)
2298                                      .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2299                                      .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2300                                      .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2301                                      .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2302                                      .setMipLodBias(0.0f)
2303                                      .setAnisotropyEnable(VK_FALSE)
2304                                      .setMaxAnisotropy(1)
2305                                      .setCompareEnable(VK_FALSE)
2306                                      .setCompareOp(vk::CompareOp::eNever)
2307                                      .setMinLod(0.0f)
2308                                      .setMaxLod(0.0f)
2309                                      .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2310                                      .setUnnormalizedCoordinates(VK_FALSE);
2311
2312         auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2313         VERIFY(result == vk::Result::eSuccess);
2314
2315         auto const viewInfo = vk::ImageViewCreateInfo()
2316                                   .setImage(textures[i].image)
2317                                   .setViewType(vk::ImageViewType::e2D)
2318                                   .setFormat(tex_format)
2319                                   .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2320
2321         result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2322         VERIFY(result == vk::Result::eSuccess);
2323     }
2324 }
2325
2326 vk::ShaderModule Demo::prepare_vs() {
2327     const uint32_t vertShaderCode[] = {
2328 #include "cube.vert.inc"
2329     };
2330
2331     vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2332
2333     return vert_shader_module;
2334 }
2335
2336 void Demo::destroy_swapchain_related_resources() {
2337     device.destroyDescriptorPool(desc_pool);
2338
2339     device.destroyPipeline(pipeline);
2340     device.destroyPipelineCache(pipelineCache);
2341     device.destroyRenderPass(render_pass);
2342     device.destroyPipelineLayout(pipeline_layout);
2343     device.destroyDescriptorSetLayout(desc_layout);
2344
2345     for (const auto &tex : textures) {
2346         device.destroyImageView(tex.view);
2347         device.destroyImage(tex.image);
2348         device.freeMemory(tex.mem);
2349         device.destroySampler(tex.sampler);
2350     }
2351
2352     device.destroyImageView(depth.view);
2353     device.destroyImage(depth.image);
2354     device.freeMemory(depth.mem);
2355
2356     for (const auto &resource : swapchain_image_resources) {
2357         device.destroyFramebuffer(resource.framebuffer);
2358         device.destroyImageView(resource.view);
2359         device.freeCommandBuffers(cmd_pool, {resource.cmd});
2360         device.destroyBuffer(resource.uniform_buffer);
2361         device.unmapMemory(resource.uniform_memory);
2362         device.freeMemory(resource.uniform_memory);
2363     }
2364
2365     device.destroyCommandPool(cmd_pool);
2366     if (separate_present_queue) {
2367         device.destroyCommandPool(present_cmd_pool);
2368     }
2369 }
2370
2371 void Demo::resize() {
2372     // Don't react to resize until after first initialization.
2373     if (!prepared) {
2374         return;
2375     }
2376
2377     // In order to properly resize the window, we must re-create the
2378     // swapchain
2379     // AND redo the command buffers, etc.
2380     //
2381     // First, perform part of the cleanup() function:
2382     prepared = false;
2383     auto result = device.waitIdle();
2384     VERIFY(result == vk::Result::eSuccess);
2385     destroy_swapchain_related_resources();
2386
2387     // Second, re-perform the prepare() function, which will re-create the
2388     // swapchain.
2389     prepare();
2390 }
2391
2392 void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2393                             vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2394     assert(cmd);
2395
2396     auto DstAccessMask = [](vk::ImageLayout const &layout) {
2397         vk::AccessFlags flags;
2398
2399         switch (layout) {
2400             case vk::ImageLayout::eTransferDstOptimal:
2401                 // Make sure anything that was copying from this image has
2402                 // completed
2403                 flags = vk::AccessFlagBits::eTransferWrite;
2404                 break;
2405             case vk::ImageLayout::eColorAttachmentOptimal:
2406                 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2407                 break;
2408             case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2409                 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2410                 break;
2411             case vk::ImageLayout::eShaderReadOnlyOptimal:
2412                 // Make sure any Copy or CPU writes to image are flushed
2413                 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2414                 break;
2415             case vk::ImageLayout::eTransferSrcOptimal:
2416                 flags = vk::AccessFlagBits::eTransferRead;
2417                 break;
2418             case vk::ImageLayout::ePresentSrcKHR:
2419                 flags = vk::AccessFlagBits::eMemoryRead;
2420                 break;
2421             default:
2422                 break;
2423         }
2424
2425         return flags;
2426     };
2427
2428     cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), {}, {},
2429                         vk::ImageMemoryBarrier()
2430                             .setSrcAccessMask(srcAccessMask)
2431                             .setDstAccessMask(DstAccessMask(newLayout))
2432                             .setOldLayout(oldLayout)
2433                             .setNewLayout(newLayout)
2434                             .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2435                             .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2436                             .setImage(image)
2437                             .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1)));
2438 }
2439
2440 void Demo::update_data_buffer() {
2441     mat4x4 VP;
2442     mat4x4_mul(VP, projection_matrix, view_matrix);
2443
2444     // Rotate around the Y axis
2445     mat4x4 Model;
2446     mat4x4_dup(Model, model_matrix);
2447     mat4x4_rotate_Y(model_matrix, Model, static_cast<float>(degreesToRadians(spin_angle)));
2448     mat4x4_orthonormalize(model_matrix, model_matrix);
2449
2450     mat4x4 MVP;
2451     mat4x4_mul(MVP, VP, model_matrix);
2452
2453     memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
2454 }
2455
2456 /* Convert ppm image data from header file into RGBA texture image */
2457 #include "lunarg.ppm.h"
2458 bool Demo::loadTexture(const char *filename, uint8_t *rgba_data, vk::SubresourceLayout &layout, uint32_t &w, uint32_t &h) {
2459     (void)filename;
2460     char *cPtr;
2461     cPtr = (char *)lunarg_ppm;
2462     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
2463         return false;
2464     }
2465     while (strncmp(cPtr++, "\n", 1))
2466         ;
2467     sscanf(cPtr, "%u %u", &w, &h);
2468     if (rgba_data == nullptr) {
2469         return true;
2470     }
2471     while (strncmp(cPtr++, "\n", 1))
2472         ;
2473     if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
2474         return false;
2475     }
2476     while (strncmp(cPtr++, "\n", 1))
2477         ;
2478     for (uint32_t y = 0; y < h; y++) {
2479         uint8_t *rowPtr = rgba_data;
2480         for (uint32_t x = 0; x < w; x++) {
2481             memcpy(rowPtr, cPtr, 3);
2482             rowPtr[3] = 255; /* Alpha of 1 */
2483             rowPtr += 4;
2484             cPtr += 3;
2485         }
2486         rgba_data += layout.rowPitch;
2487     }
2488     return true;
2489 }
2490
2491 bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t &typeIndex) {
2492     // Search memtypes to find first index with those properties
2493     for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2494         if ((typeBits & 1) == 1) {
2495             // Type is available, does it match user properties?
2496             if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2497                 typeIndex = i;
2498                 return true;
2499             }
2500         }
2501         typeBits >>= 1;
2502     }
2503
2504     // No memory types matched, return failure
2505     return false;
2506 }
2507
2508 vk::SurfaceFormatKHR Demo::pick_surface_format(const std::vector<vk::SurfaceFormatKHR> &surface_formats) {
2509     // Prefer non-SRGB formats...
2510     for (const auto &surface_format : surface_formats) {
2511         const vk::Format format = surface_format.format;
2512
2513         if (format == vk::Format::eR8G8B8A8Unorm || format == vk::Format::eB8G8R8A8Unorm ||
2514             format == vk::Format::eA2B10G10R10UnormPack32 || format == vk::Format::eA2R10G10B10UnormPack32 ||
2515             format == vk::Format::eR16G16B16A16Sfloat) {
2516             return surface_format;
2517         }
2518     }
2519
2520     printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");
2521
2522     assert(surface_formats.size() >= 1);
2523     return surface_formats[0];
2524 }
2525
2526 #if defined(VK_USE_PLATFORM_WIN32_KHR)
2527 void Demo::run() {
2528     if (!prepared) {
2529         return;
2530     }
2531
2532     draw();
2533     curFrame++;
2534
2535     if (frameCount != UINT32_MAX && curFrame == frameCount) {
2536         PostQuitMessage(validation_error);
2537     }
2538 }
2539
2540 void Demo::create_window() {
2541     WNDCLASSEX win_class;
2542
2543     // Initialize the window class structure:
2544     win_class.cbSize = sizeof(WNDCLASSEX);
2545     win_class.style = CS_HREDRAW | CS_VREDRAW;
2546     win_class.lpfnWndProc = WndProc;
2547     win_class.cbClsExtra = 0;
2548     win_class.cbWndExtra = 0;
2549     win_class.hInstance = connection;  // hInstance
2550     win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2551     win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2552     win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2553     win_class.lpszMenuName = nullptr;
2554     win_class.lpszClassName = name.c_str();
2555     win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2556
2557     // Register window class:
2558     if (!RegisterClassEx(&win_class)) {
2559         // It didn't work, so try to give a useful error:
2560         printf("Unexpected error trying to start the application!\n");
2561         fflush(stdout);
2562         exit(1);
2563     }
2564
2565     // Create window with the registered class:
2566     RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2567     AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2568     window = CreateWindowEx(0,
2569                             name.c_str(),          // class name
2570                             name.c_str(),          // app name
2571                             WS_OVERLAPPEDWINDOW |  // window style
2572                                 WS_VISIBLE | WS_SYSMENU,
2573                             100, 100,            // x/y coords
2574                             wr.right - wr.left,  // width
2575                             wr.bottom - wr.top,  // height
2576                             nullptr,             // handle to parent
2577                             nullptr,             // handle to menu
2578                             connection,          // hInstance
2579                             nullptr);            // no extra parameters
2580
2581     if (!window) {
2582         // It didn't work, so try to give a useful error:
2583         printf("Cannot create a window in which to draw!\n");
2584         fflush(stdout);
2585         exit(1);
2586     }
2587
2588     // Window client area size must be at least 1 pixel high, to prevent
2589     // crash.
2590     minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2591     minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2592 }
2593 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
2594
2595 void Demo::create_xlib_window() {
2596     const char *display_envar = getenv("DISPLAY");
2597     if (display_envar == nullptr || display_envar[0] == '\0') {
2598         printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2599         fflush(stdout);
2600         exit(1);
2601     }
2602
2603     XInitThreads();
2604     display = XOpenDisplay(nullptr);
2605     long visualMask = VisualScreenMask;
2606     int numberOfVisuals;
2607     XVisualInfo vInfoTemplate = {};
2608     vInfoTemplate.screen = DefaultScreen(display);
2609     XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2610
2611     Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2612
2613     XSetWindowAttributes windowAttributes = {};
2614     windowAttributes.colormap = colormap;
2615     windowAttributes.background_pixel = 0xFFFFFFFF;
2616     windowAttributes.border_pixel = 0;
2617     windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2618
2619     xlib_window =
2620         XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2621                       visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2622
2623     XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2624     XMapWindow(display, xlib_window);
2625     XFlush(display);
2626     xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2627 }
2628
2629 void Demo::handle_xlib_event(const XEvent *event) {
2630     switch (event->type) {
2631         case ClientMessage:
2632             if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2633                 quit = true;
2634             }
2635             break;
2636         case KeyPress:
2637             switch (event->xkey.keycode) {
2638                 case 0x9:  // Escape
2639                     quit = true;
2640                     break;
2641                 case 0x71:  // left arrow key
2642                     spin_angle -= spin_increment;
2643                     break;
2644                 case 0x72:  // right arrow key
2645                     spin_angle += spin_increment;
2646                     break;
2647                 case 0x41:  // space bar
2648                     pause = !pause;
2649                     break;
2650             }
2651             break;
2652         case ConfigureNotify:
2653             if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2654                 width = event->xconfigure.width;
2655                 height = event->xconfigure.height;
2656                 resize();
2657             }
2658             break;
2659         default:
2660             break;
2661     }
2662 }
2663
2664 void Demo::run_xlib() {
2665     while (!quit) {
2666         XEvent event;
2667
2668         if (pause) {
2669             XNextEvent(display, &event);
2670             handle_xlib_event(&event);
2671         }
2672         while (XPending(display) > 0) {
2673             XNextEvent(display, &event);
2674             handle_xlib_event(&event);
2675         }
2676
2677         draw();
2678         curFrame++;
2679
2680         if (frameCount != UINT32_MAX && curFrame == frameCount) {
2681             quit = true;
2682         }
2683     }
2684 }
2685 #elif defined(VK_USE_PLATFORM_XCB_KHR)
2686
2687 void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2688     uint8_t event_code = event->response_type & 0x7f;
2689     switch (event_code) {
2690         case XCB_EXPOSE:
2691             // TODO: Resize window
2692             break;
2693         case XCB_CLIENT_MESSAGE:
2694             if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2695                 quit = true;
2696             }
2697             break;
2698         case XCB_KEY_RELEASE: {
2699             const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
2700
2701             switch (key->detail) {
2702                 case 0x9:  // Escape
2703                     quit = true;
2704                     break;
2705                 case 0x71:  // left arrow key
2706                     spin_angle -= spin_increment;
2707                     break;
2708                 case 0x72:  // right arrow key
2709                     spin_angle += spin_increment;
2710                     break;
2711                 case 0x41:  // space bar
2712                     pause = !pause;
2713                     break;
2714             }
2715         } break;
2716         case XCB_CONFIGURE_NOTIFY: {
2717             const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2718             if ((width != cfg->width) || (height != cfg->height)) {
2719                 width = cfg->width;
2720                 height = cfg->height;
2721                 resize();
2722             }
2723         } break;
2724         default:
2725             break;
2726     }
2727 }
2728
2729 void Demo::run_xcb() {
2730     xcb_flush(connection);
2731
2732     while (!quit) {
2733         xcb_generic_event_t *event;
2734
2735         if (pause) {
2736             event = xcb_wait_for_event(connection);
2737         } else {
2738             event = xcb_poll_for_event(connection);
2739         }
2740         while (event) {
2741             handle_xcb_event(event);
2742             free(event);
2743             event = xcb_poll_for_event(connection);
2744         }
2745
2746         draw();
2747         curFrame++;
2748         if (frameCount != UINT32_MAX && curFrame == frameCount) {
2749             quit = true;
2750         }
2751     }
2752 }
2753
2754 void Demo::create_xcb_window() {
2755     uint32_t value_mask, value_list[32];
2756
2757     xcb_window = xcb_generate_id(connection);
2758
2759     value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2760     value_list[0] = screen->black_pixel;
2761     value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
2762
2763     xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2764                       XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2765
2766     /* Magic code that will send notification when window is destroyed */
2767     xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2768     xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2769
2770     xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2771     atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2772
2773     xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2774
2775     free(reply);
2776
2777     xcb_map_window(connection, xcb_window);
2778
2779     // Force the x/y coordinates to 100,100 results are identical in
2780     // consecutive
2781     // runs
2782     std::array<uint32_t, 2> const coords = {100, 100};
2783     xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords.data());
2784 }
2785 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2786
2787 void Demo::run() {
2788     while (!quit) {
2789         if (pause) {
2790             wl_display_dispatch(display);
2791         } else {
2792             wl_display_dispatch_pending(display);
2793             draw();
2794             curFrame++;
2795             if (frameCount != UINT32_MAX && curFrame == frameCount) {
2796                 quit = true;
2797             }
2798         }
2799     }
2800 }
2801
2802 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
2803 static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2804     Demo &demo = *static_cast<Demo *>(data);
2805     xdg_surface_ack_configure(xdg_surface, serial);
2806     if (demo.xdg_surface_has_been_configured) {
2807         demo.resize();
2808     }
2809     demo.xdg_surface_has_been_configured = true;
2810 }
2811
2812 static const xdg_surface_listener surface_listener = {handle_surface_configure};
2813
2814 static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2815                                       struct wl_array *states) {
2816     Demo &demo = *static_cast<Demo *>(data);
2817     /* zero values imply the program may choose its own size, so in that case
2818      * stay with the existing value (which on startup is the default) */
2819     if (width > 0) {
2820         demo.width = static_cast<uint32_t>(width);
2821     }
2822     if (height > 0) {
2823         demo.height = static_cast<uint32_t>(height);
2824     }
2825     // This will be followed by a surface configure
2826 }
2827
2828 static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2829     Demo &demo = *static_cast<Demo *>(data);
2830     demo.quit = true;
2831 }
2832
2833 static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2834 #endif
2835
2836 static void PingCb(void *data, struct wl_shell_surface *shell_surface,
2837                                 uint32_t serial)
2838 {
2839         wl_shell_surface_pong(shell_surface, serial);
2840 }
2841
2842 static void ConfigureCb(void *data, struct wl_shell_surface *shell_surface,
2843                                 uint32_t edges, int32_t width, int32_t height)
2844 {
2845
2846 }
2847
2848 static void PopupDoneCb(void *data, struct wl_shell_surface *shell_surface)
2849 {
2850
2851 }
2852
2853 void Demo::create_window() {
2854     if (!shell) {
2855         printf("Compositor did not provide the standard protocol\n");
2856         fflush(stdout);
2857         exit(1);
2858     }
2859
2860     window = wl_compositor_create_surface(compositor);
2861     if (!window) {
2862         printf("Can not create wayland_surface from compositor!\n");
2863         fflush(stdout);
2864         exit(1);
2865     }
2866
2867         window_surface = wl_shell_get_shell_surface(shell, window);
2868         static const struct wl_shell_surface_listener shell_surface_listener =
2869                 {PingCb, ConfigureCb, PopupDoneCb};
2870         wl_shell_surface_add_listener(window_surface, &shell_surface_listener, this);
2871         wl_shell_surface_set_toplevel(window_surface);
2872         wl_shell_surface_set_title(window_surface, APP_SHORT_NAME);
2873
2874 #ifdef TIZEN_SUPPPORT_XDG_WM_BASE
2875     window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2876     if (!window_surface) {
2877         printf("Can not get xdg_surface from wayland_surface!\n");
2878         fflush(stdout);
2879         exit(1);
2880     }
2881     window_toplevel = xdg_surface_get_toplevel(window_surface);
2882     if (!window_toplevel) {
2883         printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2884         fflush(stdout);
2885         exit(1);
2886     }
2887     xdg_surface_add_listener(window_surface, &surface_listener, this);
2888     xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2889     xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2890 #endif
2891 #ifdef TIZEN_SUPPPORT_XDG_DECORATION
2892     if (xdg_decoration_mgr) {
2893         // if supported, let the compositor render titlebars for us
2894         toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2895         zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2896     }
2897 #endif
2898
2899     wl_surface_commit(window);
2900 }
2901 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2902
2903 void Demo::handle_directfb_event(const DFBInputEvent *event) {
2904     if (event->type != DIET_KEYPRESS) return;
2905     switch (event->key_symbol) {
2906         case DIKS_ESCAPE:  // Escape
2907             quit = true;
2908             break;
2909         case DIKS_CURSOR_LEFT:  // left arrow key
2910             spin_angle -= spin_increment;
2911             break;
2912         case DIKS_CURSOR_RIGHT:  // right arrow key
2913             spin_angle += spin_increment;
2914             break;
2915         case DIKS_SPACE:  // space bar
2916             pause = !pause;
2917             break;
2918         default:
2919             break;
2920     }
2921 }
2922
2923 void Demo::run_directfb() {
2924     while (!quit) {
2925         DFBInputEvent event;
2926
2927         if (pause) {
2928             event_buffer->WaitForEvent(event_buffer);
2929             if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
2930         } else {
2931             if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
2932
2933             draw();
2934             curFrame++;
2935             if (frameCount != UINT32_MAX && curFrame == frameCount) {
2936                 quit = true;
2937             }
2938         }
2939     }
2940 }
2941
2942 void Demo::create_directfb_window() {
2943     DFBResult ret;
2944
2945     ret = DirectFBInit(nullptr, nullptr);
2946     if (ret) {
2947         printf("DirectFBInit failed to initialize DirectFB!\n");
2948         fflush(stdout);
2949         exit(1);
2950     }
2951
2952     ret = DirectFBCreate(&dfb);
2953     if (ret) {
2954         printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2955         fflush(stdout);
2956         exit(1);
2957     }
2958
2959     DFBSurfaceDescription desc;
2960     desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2961     desc.caps = DSCAPS_PRIMARY;
2962     desc.width = width;
2963     desc.height = height;
2964     ret = dfb->CreateSurface(dfb, &desc, &window);
2965     if (ret) {
2966         printf("CreateSurface failed to create DirectFB surface interface!\n");
2967         fflush(stdout);
2968         exit(1);
2969     }
2970
2971     ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2972     if (ret) {
2973         printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2974         fflush(stdout);
2975         exit(1);
2976     }
2977 }
2978 #elif defined(VK_USE_PLATFORM_METAL_EXT)
2979 void Demo::run() {
2980     draw();
2981     curFrame++;
2982     if (frameCount != UINT32_MAX && curFrame == frameCount) {
2983         quit = true;
2984     }
2985 }
2986 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2987
2988 vk::Result Demo::create_display_surface() {
2989     auto display_properties_return = gpu.getDisplayPropertiesKHR();
2990     VERIFY((display_properties_return.result == vk::Result::eSuccess) ||
2991            (display_properties_return.result == vk::Result::eIncomplete));
2992
2993     auto display = display_properties_return.value.at(0).display;
2994
2995     auto display_mode_props_return = gpu.getDisplayModePropertiesKHR(display);
2996     VERIFY(display_mode_props_return.result == vk::Result::eSuccess);
2997
2998     if (display_mode_props_return.value.size() == 0) {
2999         printf("Cannot find any mode for the display!\n");
3000         fflush(stdout);
3001         exit(1);
3002     }
3003     auto display_mode_prop = display_mode_props_return.value.at(0);
3004
3005     // Get the list of planes
3006     auto display_plane_props_return = gpu.getDisplayPlanePropertiesKHR();
3007     VERIFY(display_plane_props_return.result == vk::Result::eSuccess);
3008
3009     if (display_plane_props_return.value.size() == 0) {
3010         printf("Cannot find any plane!\n");
3011         fflush(stdout);
3012         exit(1);
3013     }
3014     auto display_plane_props = display_plane_props_return.value;
3015
3016     vk::Bool32 found_plane = VK_FALSE;
3017     uint32_t plane_found = 0;
3018     // Find a plane compatible with the display
3019     for (uint32_t plane_index = 0; plane_index < display_plane_props.size(); plane_index++) {
3020         // Disqualify planes that are bound to a different display
3021         if (display_plane_props[plane_index].currentDisplay && (display_plane_props[plane_index].currentDisplay != display)) {
3022             continue;
3023         }
3024
3025         auto display_plane_supported_displays_return = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index);
3026         VERIFY(display_plane_supported_displays_return.result == vk::Result::eSuccess);
3027
3028         if (display_plane_supported_displays_return.value.size() == 0) {
3029             continue;
3030         }
3031
3032         for (const auto &supported_display : display_plane_supported_displays_return.value) {
3033             if (supported_display == display) {
3034                 found_plane = VK_TRUE;
3035                 plane_found = plane_index;
3036                 break;
3037             }
3038         }
3039
3040         if (found_plane) {
3041             break;
3042         }
3043     }
3044
3045     if (!found_plane) {
3046         printf("Cannot find a plane compatible with the display!\n");
3047         fflush(stdout);
3048         exit(1);
3049     }
3050
3051     vk::DisplayPlaneCapabilitiesKHR planeCaps =
3052         gpu.getDisplayPlaneCapabilitiesKHR(display_mode_prop.displayMode, plane_found).value;
3053     // Find a supported alpha mode
3054     vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3055     std::array<vk::DisplayPlaneAlphaFlagBitsKHR, 4> alphaModes = {
3056         vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3057         vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3058         vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3059         vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3060     };
3061     for (const auto &alpha_mode : alphaModes) {
3062         if (planeCaps.supportedAlpha & alpha_mode) {
3063             alphaMode = alpha_mode;
3064             break;
3065         }
3066     }
3067
3068     vk::Extent2D image_extent{};
3069     image_extent.setWidth(display_mode_prop.parameters.visibleRegion.width)
3070         .setHeight(display_mode_prop.parameters.visibleRegion.height);
3071
3072     auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3073                                 .setDisplayMode(display_mode_prop.displayMode)
3074                                 .setPlaneIndex(plane_found)
3075                                 .setPlaneStackIndex(display_plane_props[plane_found].currentStackIndex)
3076                                 .setGlobalAlpha(1.0f)
3077                                 .setAlphaMode(alphaMode)
3078                                 .setImageExtent(image_extent);
3079
3080     return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3081 }
3082
3083 void Demo::run_display() {
3084     while (!quit) {
3085         draw();
3086         curFrame++;
3087
3088         if (frameCount != UINT32_MAX && curFrame == frameCount) {
3089             quit = true;
3090         }
3091     }
3092 }
3093 #endif
3094
3095 #if _WIN32
3096 // Include header required for parsing the command line options.
3097 #include <shellapi.h>
3098
3099 Demo demo;
3100
3101 // MS-Windows event handling function:
3102 LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3103     switch (uMsg) {
3104         case WM_CLOSE:
3105             PostQuitMessage(validation_error);
3106             break;
3107         case WM_PAINT:
3108             if (!demo.in_callback) {
3109                 demo.run();
3110             }
3111             break;
3112         case WM_GETMINMAXINFO:  // set window's minimum size
3113             ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3114             return 0;
3115         case WM_ERASEBKGND:
3116             return 1;
3117         case WM_SIZE:
3118             // Resize the application to the new window size, except when
3119             // it was minimized. Vulkan doesn't support images or swapchains
3120             // with width=0 and height=0.
3121             if (wParam != SIZE_MINIMIZED) {
3122                 demo.width = lParam & 0xffff;
3123                 demo.height = (lParam & 0xffff0000) >> 16;
3124                 demo.resize();
3125             }
3126             break;
3127         case WM_KEYDOWN:
3128             switch (wParam) {
3129                 case VK_ESCAPE:
3130                     PostQuitMessage(validation_error);
3131                     break;
3132                 case VK_LEFT:
3133                     demo.spin_angle -= demo.spin_increment;
3134                     break;
3135                 case VK_RIGHT:
3136                     demo.spin_angle += demo.spin_increment;
3137                     break;
3138                 case VK_SPACE:
3139                     demo.pause = !demo.pause;
3140                     break;
3141             }
3142             return 0;
3143         default:
3144             break;
3145     }
3146
3147     return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3148 }
3149
3150 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
3151     // TODO: Gah.. refactor. This isn't 1989.
3152     MSG msg;    // message
3153     bool done;  // flag saying when app is complete
3154     int argc;
3155     char **argv;
3156
3157     // Ensure wParam is initialized.
3158     msg.wParam = 0;
3159
3160     // Use the CommandLine functions to get the command line arguments.
3161     // Unfortunately, Microsoft outputs
3162     // this information as wide characters for Unicode, and we simply want the
3163     // Ascii version to be compatible
3164     // with the non-Windows side.  So, we have to convert the information to
3165     // Ascii character strings.
3166     LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
3167     if (nullptr == commandLineArgs) {
3168         argc = 0;
3169     }
3170
3171     if (argc > 0) {
3172         argv = (char **)malloc(sizeof(char *) * argc);
3173         if (argv == nullptr) {
3174             argc = 0;
3175         } else {
3176             for (int iii = 0; iii < argc; iii++) {
3177                 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3178                 size_t numConverted = 0;
3179
3180                 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
3181                 if (argv[iii] != nullptr) {
3182                     wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
3183                 }
3184             }
3185         }
3186     } else {
3187         argv = nullptr;
3188     }
3189
3190     demo.init(argc, argv);
3191
3192     // Free up the items we had to allocate for the command line arguments.
3193     if (argc > 0 && argv != nullptr) {
3194         for (int iii = 0; iii < argc; iii++) {
3195             if (argv[iii] != nullptr) {
3196                 free(argv[iii]);
3197             }
3198         }
3199         free(argv);
3200     }
3201
3202     demo.connection = hInstance;
3203     demo.name = "Vulkan Cube";
3204     demo.create_window();
3205     demo.init_vk_swapchain();
3206
3207     demo.prepare();
3208
3209     done = false;  // initialize loop condition variable
3210
3211     // main message loop
3212     while (!done) {
3213         if (demo.pause) {
3214             const BOOL succ = WaitMessage();
3215
3216             if (!succ) {
3217                 const auto &suppress_popups = demo.suppress_popups;
3218                 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3219             }
3220         }
3221
3222         PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
3223         if (msg.message == WM_QUIT)  // check for a quit message
3224         {
3225             done = true;  // if found, quit app
3226         } else {
3227             /* Translate and dispatch to event queue*/
3228             TranslateMessage(&msg);
3229             DispatchMessage(&msg);
3230         }
3231         RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3232     }
3233
3234     demo.cleanup();
3235
3236     return static_cast<int>(msg.wParam);
3237 }
3238
3239 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
3240
3241 int main(int argc, char **argv) {
3242     Demo demo;
3243
3244     demo.init(argc, argv);
3245
3246 #if defined(VK_USE_PLATFORM_XCB_KHR)
3247     demo.create_xcb_window();
3248 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3249     demo.use_xlib = true;
3250     demo.create_xlib_window();
3251 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3252     demo.create_window();
3253 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3254     demo.create_directfb_window();
3255 #endif
3256
3257     demo.init_vk_swapchain();
3258
3259     demo.prepare();
3260
3261 #if defined(VK_USE_PLATFORM_XCB_KHR)
3262     demo.run_xcb();
3263 #elif defined(VK_USE_PLATFORM_XLIB_KHR)
3264     demo.run_xlib();
3265 #elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3266     demo.run();
3267 #elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3268     demo.run_directfb();
3269 #elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3270     demo.run_display();
3271 #endif
3272
3273     demo.cleanup();
3274
3275     return validation_error;
3276 }
3277
3278 #elif defined(VK_USE_PLATFORM_METAL_EXT)
3279
3280 // Global function invoked from NS or UI views and controllers to create demo
3281 static void demo_main(Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
3282     demo.init(argc, (char **)argv);
3283     demo.caMetalLayer = caMetalLayer;
3284     demo.init_vk_swapchain();
3285     demo.prepare();
3286     demo.spin_angle = 0.4f;
3287 }
3288
3289 #else
3290 #error "Platform not supported"
3291 #endif