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