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