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