blob: ff760893567014f7f2bbbf50184f71c10233045c [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();
Karl Schultz206b1c52018-04-13 18:02:07 -0600264#elif defined(VK_USE_PLATFORM_MACOS_MVK)
265 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600266#elif defined(VK_USE_PLATFORM_MIR_KHR)
267#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
268 vk::Result create_display_surface();
269 void run_display();
270#endif
271
272#if defined(VK_USE_PLATFORM_WIN32_KHR)
273 HINSTANCE connection; // hInstance - Windows Instance
274 HWND window; // hWnd - window handle
275 POINT minsize; // minimum window size
276 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
277#elif defined(VK_USE_PLATFORM_XLIB_KHR)
278 Window xlib_window;
279 Atom xlib_wm_delete_window;
280 Display *display;
281#elif defined(VK_USE_PLATFORM_XCB_KHR)
282 xcb_window_t xcb_window;
283 xcb_screen_t *screen;
284 xcb_connection_t *connection;
285 xcb_intern_atom_reply_t *atom_wm_delete_window;
286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
287 wl_display *display;
288 wl_registry *registry;
289 wl_compositor *compositor;
290 wl_surface *window;
291 wl_shell *shell;
292 wl_shell_surface *shell_surface;
293 wl_seat *seat;
294 wl_pointer *pointer;
295 wl_keyboard *keyboard;
296#elif defined(VK_USE_PLATFORM_MIR_KHR)
Karl Schultz9ceac062017-12-12 10:33:01 -0500297#elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
298 void *window;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600299#endif
300
301 vk::SurfaceKHR surface;
302 bool prepared;
303 bool use_staging_buffer;
304 bool use_xlib;
305 bool separate_present_queue;
306
307 vk::Instance inst;
308 vk::PhysicalDevice gpu;
309 vk::Device device;
310 vk::Queue graphics_queue;
311 vk::Queue present_queue;
312 uint32_t graphics_queue_family_index;
313 uint32_t present_queue_family_index;
314 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
315 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
316 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
317 vk::PhysicalDeviceProperties gpu_props;
318 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
319 vk::PhysicalDeviceMemoryProperties memory_properties;
320
321 uint32_t enabled_extension_count;
322 uint32_t enabled_layer_count;
323 char const *extension_names[64];
324 char const *enabled_layers[64];
325
326 uint32_t width;
327 uint32_t height;
328 vk::Format format;
329 vk::ColorSpaceKHR color_space;
330
331 uint32_t swapchainImageCount;
332 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600333 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600334 vk::PresentModeKHR presentMode;
335 vk::Fence fences[FRAME_LAG];
336 uint32_t frame_index;
337
338 vk::CommandPool cmd_pool;
339 vk::CommandPool present_cmd_pool;
340
341 struct {
342 vk::Format format;
343 vk::Image image;
344 vk::MemoryAllocateInfo mem_alloc;
345 vk::DeviceMemory mem;
346 vk::ImageView view;
347 } depth;
348
349 static int32_t const texture_count = 1;
350 texture_object textures[texture_count];
351 texture_object staging_texture;
352
353 struct {
354 vk::Buffer buf;
355 vk::MemoryAllocateInfo mem_alloc;
356 vk::DeviceMemory mem;
357 vk::DescriptorBufferInfo buffer_info;
358 } uniform_data;
359
360 vk::CommandBuffer cmd; // Buffer for initialization commands
361 vk::PipelineLayout pipeline_layout;
362 vk::DescriptorSetLayout desc_layout;
363 vk::PipelineCache pipelineCache;
364 vk::RenderPass render_pass;
365 vk::Pipeline pipeline;
366
367 mat4x4 projection_matrix;
368 mat4x4 view_matrix;
369 mat4x4 model_matrix;
370
371 float spin_angle;
372 float spin_increment;
373 bool pause;
374
375 vk::ShaderModule vert_shader_module;
376 vk::ShaderModule frag_shader_module;
377
378 vk::DescriptorPool desc_pool;
379 vk::DescriptorSet desc_set;
380
381 std::unique_ptr<vk::Framebuffer[]> framebuffers;
382
383 bool quit;
384 uint32_t curFrame;
385 uint32_t frameCount;
386 bool validate;
387 bool use_break;
388 bool suppress_popups;
389
390 uint32_t current_buffer;
391 uint32_t queue_family_count;
392};
393
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600394#ifdef _WIN32
395// MS-Windows event handling function:
396LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
397#endif
398
Karl Schultz23cc2182016-11-23 17:15:17 -0700399#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700400static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700401 wl_shell_surface_pong(shell_surface, serial);
402}
403
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700404static 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 -0700405
406static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
407
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700408static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700409
Joey Bzdek15eb0702017-06-07 09:40:36 -0600410static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
411 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700412
Joey Bzdek15eb0702017-06-07 09:40:36 -0600413static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700414
Joey Bzdek15eb0702017-06-07 09:40:36 -0600415static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
416
417static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
418 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600419 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600420 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
421 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
422 }
423}
424
425static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
426
427static const struct wl_pointer_listener pointer_listener = {
428 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
429};
430
431static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
432
433static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
434 struct wl_array *keys) {}
435
436static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
437
438static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
439 uint32_t state) {
440 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
441 Demo *demo = (Demo *)data;
442 switch (key) {
443 case KEY_ESC: // Escape
444 demo->quit = true;
445 break;
446 case KEY_LEFT: // left arrow key
447 demo->spin_angle -= demo->spin_increment;
448 break;
449 case KEY_RIGHT: // right arrow key
450 demo->spin_angle += demo->spin_increment;
451 break;
452 case KEY_SPACE: // space bar
453 demo->pause = !demo->pause;
454 break;
455 }
456}
457
458static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
459 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
460
461static const struct wl_keyboard_listener keyboard_listener = {
462 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
463};
464
465static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
466 // Subscribe to pointer events
467 Demo *demo = (Demo *)data;
468 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
469 demo->pointer = wl_seat_get_pointer(seat);
470 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
471 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
472 wl_pointer_destroy(demo->pointer);
473 demo->pointer = NULL;
474 }
475 // Subscribe to keyboard events
476 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
477 demo->keyboard = wl_seat_get_keyboard(seat);
478 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
480 wl_keyboard_destroy(demo->keyboard);
481 demo->keyboard = NULL;
482 }
483}
484
485static const wl_seat_listener seat_listener = {
486 seat_handle_capabilities,
487};
488
489static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
490 Demo *demo = (Demo *)data;
491 // pickup wayland objects when they appear
492 if (strcmp(interface, "wl_compositor") == 0) {
493 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
494 } else if (strcmp(interface, "wl_shell") == 0) {
495 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
496 } else if (strcmp(interface, "wl_seat") == 0) {
497 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
498 wl_seat_add_listener(demo->seat, &seat_listener, demo);
499 }
500}
501
502static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
503
504static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Tony Barbourefd0c5a2016-12-07 14:45:12 -0700505#elif defined(VK_USE_PLATFORM_MIR_KHR)
Karl Schultz23cc2182016-11-23 17:15:17 -0700506#endif
507
Joey Bzdekbaf66472017-06-07 09:37:37 -0600508Demo::Demo()
509 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600510#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600511 connection{nullptr},
512 window{nullptr},
513 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600514#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700515
Tony Barbour78d6b572016-11-14 14:46:33 -0700516#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 xlib_window{0},
518 xlib_wm_delete_window{0},
519 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700520#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521 xcb_window{0},
522 screen{nullptr},
523 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700524#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 display{nullptr},
526 registry{nullptr},
527 compositor{nullptr},
528 window{nullptr},
529 shell{nullptr},
530 shell_surface{nullptr},
531 seat{nullptr},
532 pointer{nullptr},
533 keyboard{nullptr},
Tony Barbourefd0c5a2016-12-07 14:45:12 -0700534#elif defined(VK_USE_PLATFORM_MIR_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -0700535#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600536 prepared{false},
537 use_staging_buffer{false},
538 use_xlib{false},
539 graphics_queue_family_index{0},
540 present_queue_family_index{0},
541 enabled_extension_count{0},
542 enabled_layer_count{0},
543 width{0},
544 height{0},
545 swapchainImageCount{0},
546 frame_index{0},
547 spin_angle{0.0f},
548 spin_increment{0.0f},
549 pause{false},
550 quit{false},
551 curFrame{0},
552 frameCount{0},
553 validate{false},
554 use_break{false},
555 suppress_popups{false},
556 current_buffer{0},
557 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600558#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700559 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600560#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700561 memset(projection_matrix, 0, sizeof(projection_matrix));
562 memset(view_matrix, 0, sizeof(view_matrix));
563 memset(model_matrix, 0, sizeof(model_matrix));
564}
565
566void Demo::build_image_ownership_cmd(uint32_t const &i) {
567 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
568 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
569 VERIFY(result == vk::Result::eSuccess);
570
571 auto const image_ownership_barrier =
572 vk::ImageMemoryBarrier()
573 .setSrcAccessMask(vk::AccessFlags())
574 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
575 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
577 .setSrcQueueFamilyIndex(graphics_queue_family_index)
578 .setDstQueueFamilyIndex(present_queue_family_index)
579 .setImage(swapchain_image_resources[i].image)
580 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
581
582 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
583 vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput,
584 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
585
586 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
587 VERIFY(result == vk::Result::eSuccess);
588}
589
590vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
591 vk::LayerProperties *layers) {
592 for (uint32_t i = 0; i < check_count; i++) {
593 vk::Bool32 found = VK_FALSE;
594 for (uint32_t j = 0; j < layer_count; j++) {
595 if (!strcmp(check_names[i], layers[j].layerName)) {
596 found = VK_TRUE;
597 break;
598 }
599 }
600 if (!found) {
601 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
602 return 0;
603 }
604 }
605 return VK_TRUE;
606}
607
608void Demo::cleanup() {
609 prepared = false;
610 device.waitIdle();
611
612 // Wait for fences from present operations
613 for (uint32_t i = 0; i < FRAME_LAG; i++) {
614 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
615 device.destroyFence(fences[i], nullptr);
616 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
617 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
618 if (separate_present_queue) {
619 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
620 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600621 }
622
Dave Houlton5fa47912018-02-16 11:02:26 -0700623 for (uint32_t i = 0; i < swapchainImageCount; i++) {
624 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
625 }
626 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600627
Dave Houlton5fa47912018-02-16 11:02:26 -0700628 device.destroyPipeline(pipeline, nullptr);
629 device.destroyPipelineCache(pipelineCache, nullptr);
630 device.destroyRenderPass(render_pass, nullptr);
631 device.destroyPipelineLayout(pipeline_layout, nullptr);
632 device.destroyDescriptorSetLayout(desc_layout, nullptr);
633
634 for (uint32_t i = 0; i < texture_count; i++) {
635 device.destroyImageView(textures[i].view, nullptr);
636 device.destroyImage(textures[i].image, nullptr);
637 device.freeMemory(textures[i].mem, nullptr);
638 device.destroySampler(textures[i].sampler, nullptr);
639 }
640 device.destroySwapchainKHR(swapchain, nullptr);
641
642 device.destroyImageView(depth.view, nullptr);
643 device.destroyImage(depth.image, nullptr);
644 device.freeMemory(depth.mem, nullptr);
645
646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
648 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
649 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
650 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
651 }
652
653 device.destroyCommandPool(cmd_pool, nullptr);
654
655 if (separate_present_queue) {
656 device.destroyCommandPool(present_cmd_pool, nullptr);
657 }
658 device.waitIdle();
659 device.destroy(nullptr);
660 inst.destroySurfaceKHR(surface, nullptr);
661
662#if defined(VK_USE_PLATFORM_XLIB_KHR)
663 XDestroyWindow(display, xlib_window);
664 XCloseDisplay(display);
665#elif defined(VK_USE_PLATFORM_XCB_KHR)
666 xcb_destroy_window(connection, xcb_window);
667 xcb_disconnect(connection);
668 free(atom_wm_delete_window);
669#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
670 wl_keyboard_destroy(keyboard);
671 wl_pointer_destroy(pointer);
672 wl_seat_destroy(seat);
673 wl_shell_surface_destroy(shell_surface);
674 wl_surface_destroy(window);
675 wl_shell_destroy(shell);
676 wl_compositor_destroy(compositor);
677 wl_registry_destroy(registry);
678 wl_display_disconnect(display);
679#elif defined(VK_USE_PLATFORM_MIR_KHR)
680#endif
681
682 inst.destroy(nullptr);
683}
684
685void Demo::create_device() {
686 float const priorities[1] = {0.0};
687
688 vk::DeviceQueueCreateInfo queues[2];
689 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
690 queues[0].setQueueCount(1);
691 queues[0].setPQueuePriorities(priorities);
692
693 auto deviceInfo = vk::DeviceCreateInfo()
694 .setQueueCreateInfoCount(1)
695 .setPQueueCreateInfos(queues)
696 .setEnabledLayerCount(0)
697 .setPpEnabledLayerNames(nullptr)
698 .setEnabledExtensionCount(enabled_extension_count)
699 .setPpEnabledExtensionNames((const char *const *)extension_names)
700 .setPEnabledFeatures(nullptr);
701
702 if (separate_present_queue) {
703 queues[1].setQueueFamilyIndex(present_queue_family_index);
704 queues[1].setQueueCount(1);
705 queues[1].setPQueuePriorities(priorities);
706 deviceInfo.setQueueCreateInfoCount(2);
707 }
708
709 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
710 VERIFY(result == vk::Result::eSuccess);
711}
712
713void Demo::destroy_texture_image(texture_object *tex_objs) {
714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
716 device.destroyImage(tex_objs->image, nullptr);
717}
718
719void Demo::draw() {
720 // Ensure no more than FRAME_LAG renderings are outstanding
721 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
722 device.resetFences(1, &fences[frame_index]);
723
724 vk::Result result;
725 do {
726 result =
727 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
728 if (result == vk::Result::eErrorOutOfDateKHR) {
729 // demo->swapchain is out of date (e.g. the window was resized) and
730 // must be recreated:
731 resize();
732 } else if (result == vk::Result::eSuboptimalKHR) {
733 // swapchain is not as optimal as it could be, but the platform's
734 // presentation engine will still present the image correctly.
735 break;
736 } else {
737 VERIFY(result == vk::Result::eSuccess);
738 }
739 } while (result != vk::Result::eSuccess);
740
741 update_data_buffer();
742
743 // Wait for the image acquired semaphore to be signaled to ensure
744 // that the image won't be rendered to until the presentation
745 // engine has fully released ownership to the application, and it is
746 // okay to render to the image.
747 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
748 auto const submit_info = vk::SubmitInfo()
749 .setPWaitDstStageMask(&pipe_stage_flags)
750 .setWaitSemaphoreCount(1)
751 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
752 .setCommandBufferCount(1)
753 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
754 .setSignalSemaphoreCount(1)
755 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
756
757 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
758 VERIFY(result == vk::Result::eSuccess);
759
760 if (separate_present_queue) {
761 // If we are using separate queues, change image ownership to the
762 // present queue before presenting, waiting for the draw complete
763 // semaphore and signalling the ownership released semaphore when
764 // finished
765 auto const present_submit_info = vk::SubmitInfo()
766 .setPWaitDstStageMask(&pipe_stage_flags)
767 .setWaitSemaphoreCount(1)
768 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
769 .setCommandBufferCount(1)
770 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
771 .setSignalSemaphoreCount(1)
772 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
773
774 result = present_queue.submit(1, &present_submit_info, vk::Fence());
775 VERIFY(result == vk::Result::eSuccess);
776 }
777
778 // If we are using separate queues we have to wait for image ownership,
779 // otherwise wait for draw complete
780 auto const presentInfo = vk::PresentInfoKHR()
781 .setWaitSemaphoreCount(1)
782 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
783 : &draw_complete_semaphores[frame_index])
784 .setSwapchainCount(1)
785 .setPSwapchains(&swapchain)
786 .setPImageIndices(&current_buffer);
787
788 result = present_queue.presentKHR(&presentInfo);
789 frame_index += 1;
790 frame_index %= FRAME_LAG;
791 if (result == vk::Result::eErrorOutOfDateKHR) {
792 // swapchain is out of date (e.g. the window was resized) and
793 // must be recreated:
794 resize();
795 } else if (result == vk::Result::eSuboptimalKHR) {
796 // swapchain is not as optimal as it could be, but the platform's
797 // presentation engine will still present the image correctly.
798 } else {
799 VERIFY(result == vk::Result::eSuccess);
800 }
801}
802
803void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
804 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
805
806 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
807 vk::ClearDepthStencilValue(1.0f, 0u)};
808
809 auto const passInfo = vk::RenderPassBeginInfo()
810 .setRenderPass(render_pass)
811 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
812 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
813 .setClearValueCount(2)
814 .setPClearValues(clearValues);
815
816 auto result = commandBuffer.begin(&commandInfo);
817 VERIFY(result == vk::Result::eSuccess);
818
819 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
820 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
821 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
822 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
823
824 auto const viewport =
825 vk::Viewport().setWidth((float)width).setHeight((float)height).setMinDepth((float)0.0f).setMaxDepth((float)1.0f);
826 commandBuffer.setViewport(0, 1, &viewport);
827
828 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
829 commandBuffer.setScissor(0, 1, &scissor);
830 commandBuffer.draw(12 * 3, 1, 0, 0);
831 // Note that ending the renderpass changes the image's layout from
832 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
833 commandBuffer.endRenderPass();
834
835 if (separate_present_queue) {
836 // We have to transfer ownership from the graphics queue family to
837 // the
838 // present queue family to be able to present. Note that we don't
839 // have
840 // to transfer from present queue family back to graphics queue
841 // family at
842 // the start of the next frame because we don't care about the
843 // image's
844 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600845 auto const image_ownership_barrier =
846 vk::ImageMemoryBarrier()
847 .setSrcAccessMask(vk::AccessFlags())
848 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite)
849 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
850 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
851 .setSrcQueueFamilyIndex(graphics_queue_family_index)
852 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700853 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700854 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600855
Dave Houlton5fa47912018-02-16 11:02:26 -0700856 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eBottomOfPipe,
857 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600858 }
859
Dave Houlton5fa47912018-02-16 11:02:26 -0700860 result = commandBuffer.end();
861 VERIFY(result == vk::Result::eSuccess);
862}
863
864void Demo::flush_init_cmd() {
865 // TODO: hmm.
866 // This function could get called twice if the texture uses a staging
867 // buffer
868 // In that case the second call should be ignored
869 if (!cmd) {
870 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600871 }
872
Dave Houlton5fa47912018-02-16 11:02:26 -0700873 auto result = cmd.end();
874 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600875
Dave Houlton5fa47912018-02-16 11:02:26 -0700876 auto const fenceInfo = vk::FenceCreateInfo();
877 vk::Fence fence;
878 result = device.createFence(&fenceInfo, nullptr, &fence);
879 VERIFY(result == vk::Result::eSuccess);
880
881 vk::CommandBuffer const commandBuffers[] = {cmd};
882 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
883
884 result = graphics_queue.submit(1, &submitInfo, fence);
885 VERIFY(result == vk::Result::eSuccess);
886
887 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
888 VERIFY(result == vk::Result::eSuccess);
889
890 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
891 device.destroyFence(fence, nullptr);
892
893 cmd = vk::CommandBuffer();
894}
895
896void Demo::init(int argc, char **argv) {
897 vec3 eye = {0.0f, 3.0f, 5.0f};
898 vec3 origin = {0, 0, 0};
899 vec3 up = {0.0f, 1.0f, 0.0};
900
901 presentMode = vk::PresentModeKHR::eFifo;
902 frameCount = UINT32_MAX;
903 use_xlib = false;
904
905 for (int i = 1; i < argc; i++) {
906 if (strcmp(argv[i], "--use_staging") == 0) {
907 use_staging_buffer = true;
908 continue;
909 }
910 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
911 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
912 i++;
913 continue;
914 }
915 if (strcmp(argv[i], "--break") == 0) {
916 use_break = true;
917 continue;
918 }
919 if (strcmp(argv[i], "--validate") == 0) {
920 validate = true;
921 continue;
922 }
923 if (strcmp(argv[i], "--xlib") == 0) {
924 fprintf(stderr, "--xlib is deprecated and no longer does anything");
925 continue;
926 }
927 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
928 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
929 i++;
930 continue;
931 }
932 if (strcmp(argv[i], "--suppress_popups") == 0) {
933 suppress_popups = true;
934 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600935 }
936
Dave Houlton5fa47912018-02-16 11:02:26 -0700937 fprintf(stderr,
938 "Usage:\n %s [--use_staging] [--validate] [--break] [--c <framecount>] \n"
939 " [--suppress_popups] [--present_mode {0,1,2,3}]\n"
940 "\n"
941 "Options for --present_mode:\n"
942 " %d: VK_PRESENT_MODE_IMMEDIATE_KHR\n"
943 " %d: VK_PRESENT_MODE_MAILBOX_KHR\n"
944 " %d: VK_PRESENT_MODE_FIFO_KHR (default)\n"
945 " %d: VK_PRESENT_MODE_FIFO_RELAXED_KHR\n",
946 APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
947 VK_PRESENT_MODE_FIFO_RELAXED_KHR);
948 fflush(stderr);
949 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600950 }
951
Dave Houlton5fa47912018-02-16 11:02:26 -0700952 if (!use_xlib) {
953 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600954 }
955
Dave Houlton5fa47912018-02-16 11:02:26 -0700956 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600957
Dave Houlton5fa47912018-02-16 11:02:26 -0700958 width = 500;
959 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600960
Dave Houlton5fa47912018-02-16 11:02:26 -0700961 spin_angle = 4.0f;
962 spin_increment = 0.2f;
963 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600964
Dave Houlton5fa47912018-02-16 11:02:26 -0700965 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
966 mat4x4_look_at(view_matrix, eye, origin, up);
967 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600968
Dave Houlton5fa47912018-02-16 11:02:26 -0700969 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
970}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600971
Dave Houlton5fa47912018-02-16 11:02:26 -0700972void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600973#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700974 const xcb_setup_t *setup;
975 xcb_screen_iterator_t iter;
976 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600977
Dave Houlton5fa47912018-02-16 11:02:26 -0700978 const char *display_envar = getenv("DISPLAY");
979 if (display_envar == nullptr || display_envar[0] == '\0') {
980 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
981 fflush(stdout);
982 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600983 }
984
Dave Houlton5fa47912018-02-16 11:02:26 -0700985 connection = xcb_connect(nullptr, &scr);
986 if (xcb_connection_has_error(connection) > 0) {
987 printf(
988 "Cannot find a compatible Vulkan installable client driver "
989 "(ICD).\nExiting ...\n");
990 fflush(stdout);
991 exit(1);
992 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600993
Dave Houlton5fa47912018-02-16 11:02:26 -0700994 setup = xcb_get_setup(connection);
995 iter = xcb_setup_roots_iterator(setup);
996 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600997
Dave Houlton5fa47912018-02-16 11:02:26 -0700998 screen = iter.data;
999#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1000 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001001
Dave Houlton5fa47912018-02-16 11:02:26 -07001002 if (display == nullptr) {
1003 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1004 fflush(stdout);
1005 exit(1);
1006 }
1007
1008 registry = wl_display_get_registry(display);
1009 wl_registry_add_listener(registry, &registry_listener, this);
1010 wl_display_dispatch(display);
1011#elif defined(VK_USE_PLATFORM_MIR_KHR)
1012#endif
1013}
1014
1015void Demo::init_vk() {
1016 uint32_t instance_extension_count = 0;
1017 uint32_t instance_layer_count = 0;
1018 uint32_t validation_layer_count = 0;
1019 char const *const *instance_validation_layers = nullptr;
1020 enabled_extension_count = 0;
1021 enabled_layer_count = 0;
1022
1023 char const *const instance_validation_layers_alt1[] = {"VK_LAYER_LUNARG_standard_validation"};
1024
1025 char const *const instance_validation_layers_alt2[] = {"VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
1026 "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_core_validation",
1027 "VK_LAYER_GOOGLE_unique_objects"};
1028
1029 // Look for validation layers
1030 vk::Bool32 validation_found = VK_FALSE;
1031 if (validate) {
1032 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, nullptr);
1033 VERIFY(result == vk::Result::eSuccess);
1034
1035 instance_validation_layers = instance_validation_layers_alt1;
1036 if (instance_layer_count > 0) {
1037 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1038 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001039 VERIFY(result == vk::Result::eSuccess);
1040
Dave Houlton5fa47912018-02-16 11:02:26 -07001041 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt1), instance_validation_layers,
1042 instance_layer_count, instance_layers.get());
1043 if (validation_found) {
1044 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt1);
1045 enabled_layers[0] = "VK_LAYER_LUNARG_standard_validation";
1046 validation_layer_count = 1;
1047 } else {
1048 // use alternative set of validation layers
1049 instance_validation_layers = instance_validation_layers_alt2;
1050 enabled_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1051 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers_alt2), instance_validation_layers,
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07001052 instance_layer_count, instance_layers.get());
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 validation_layer_count = ARRAY_SIZE(instance_validation_layers_alt2);
1054 for (uint32_t i = 0; i < validation_layer_count; i++) {
1055 enabled_layers[i] = instance_validation_layers[i];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056 }
1057 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001058 }
1059
Dave Houlton5fa47912018-02-16 11:02:26 -07001060 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001061 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001062 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1063 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001064 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001065 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001066 }
1067
Dave Houlton5fa47912018-02-16 11:02:26 -07001068 /* Look for instance extensions */
1069 vk::Bool32 surfaceExtFound = VK_FALSE;
1070 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1071 memset(extension_names, 0, sizeof(extension_names));
1072
1073 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, nullptr);
1074 VERIFY(result == vk::Result::eSuccess);
1075
1076 if (instance_extension_count > 0) {
1077 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1078 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1079 VERIFY(result == vk::Result::eSuccess);
1080
1081 for (uint32_t i = 0; i < instance_extension_count; i++) {
1082 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1083 surfaceExtFound = 1;
1084 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1085 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001086#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001087 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1088 platformSurfaceExtFound = 1;
1089 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1090 }
1091#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1092 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1093 platformSurfaceExtFound = 1;
1094 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1095 }
1096#elif defined(VK_USE_PLATFORM_XCB_KHR)
1097 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098 platformSurfaceExtFound = 1;
1099 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1100 }
Tony Barbour153cb062016-12-07 13:43:36 -07001101#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001102 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103 platformSurfaceExtFound = 1;
1104 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1105 }
1106#elif defined(VK_USE_PLATFORM_MIR_KHR)
1107#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1108 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1109 platformSurfaceExtFound = 1;
1110 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1111 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001112#elif defined(VK_USE_PLATFORM_IOS_MVK)
1113 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1114 platformSurfaceExtFound = 1;
1115 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1116 }
1117#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1118 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1119 platformSurfaceExtFound = 1;
1120 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1121 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001122
Dave Houlton5fa47912018-02-16 11:02:26 -07001123#endif
1124 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001125 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001126 }
1127
1128 if (!surfaceExtFound) {
1129 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1130 " extension.\n\n"
1131 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1132 "Please look at the Getting Started guide for additional information.\n",
1133 "vkCreateInstance Failure");
1134 }
1135
1136 if (!platformSurfaceExtFound) {
1137#if defined(VK_USE_PLATFORM_WIN32_KHR)
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1139 " extension.\n\n"
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143#elif defined(VK_USE_PLATFORM_XCB_KHR)
1144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1145 " extension.\n\n"
1146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1147 "Please look at the Getting Started guide for additional information.\n",
1148 "vkCreateInstance Failure");
1149#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1151 " extension.\n\n"
1152 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1153 "Please look at the Getting Started guide for additional information.\n",
1154 "vkCreateInstance Failure");
Tony Barbourefd0c5a2016-12-07 14:45:12 -07001155#elif defined(VK_USE_PLATFORM_MIR_KHR)
Tony Barbour153cb062016-12-07 13:43:36 -07001156#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1158 " extension.\n\n"
1159 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1160 "Please look at the Getting Started guide for additional information.\n",
1161 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001162#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001163 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1164 " extension.\n\n"
1165 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1166 "Please look at the Getting Started guide for additional information.\n",
1167 "vkCreateInstance Failure");
Karl Schultz9ceac062017-12-12 10:33:01 -05001168#elif defined(VK_USE_PLATFORM_IOS_MVK)
1169 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1170 " extension.\n\nDo you have a compatible "
1171 "Vulkan installable client driver (ICD) installed?\nPlease "
1172 "look at the Getting Started guide for additional "
1173 "information.\n",
1174 "vkCreateInstance Failure");
1175#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1176 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1177 " extension.\n\nDo you have a compatible "
1178 "Vulkan installable client driver (ICD) installed?\nPlease "
1179 "look at the Getting Started guide for additional "
1180 "information.\n",
1181 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001182#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001183 }
1184 auto const app = vk::ApplicationInfo()
1185 .setPApplicationName(APP_SHORT_NAME)
1186 .setApplicationVersion(0)
1187 .setPEngineName(APP_SHORT_NAME)
1188 .setEngineVersion(0)
1189 .setApiVersion(VK_API_VERSION_1_0);
1190 auto const inst_info = vk::InstanceCreateInfo()
1191 .setPApplicationInfo(&app)
1192 .setEnabledLayerCount(enabled_layer_count)
1193 .setPpEnabledLayerNames(instance_validation_layers)
1194 .setEnabledExtensionCount(enabled_extension_count)
1195 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001196
Dave Houlton5fa47912018-02-16 11:02:26 -07001197 result = vk::createInstance(&inst_info, nullptr, &inst);
1198 if (result == vk::Result::eErrorIncompatibleDriver) {
1199 ERR_EXIT(
1200 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1201 "Please look at the Getting Started guide for additional information.\n",
1202 "vkCreateInstance Failure");
1203 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1204 ERR_EXIT(
1205 "Cannot find a specified extension library.\n"
1206 "Make sure your layers path is set appropriately.\n",
1207 "vkCreateInstance Failure");
1208 } else if (result != vk::Result::eSuccess) {
1209 ERR_EXIT(
1210 "vkCreateInstance failed.\n\n"
1211 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1212 "Please look at the Getting Started guide for additional information.\n",
1213 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001214 }
1215
Dave Houlton5fa47912018-02-16 11:02:26 -07001216 /* Make initial call to query gpu_count, then second call for gpu info*/
1217 uint32_t gpu_count;
1218 result = inst.enumeratePhysicalDevices(&gpu_count, nullptr);
1219 VERIFY(result == vk::Result::eSuccess);
1220 assert(gpu_count > 0);
1221
1222 if (gpu_count > 0) {
1223 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1224 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001225 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001226 /* For cube demo we just grab the first physical device */
1227 gpu = physical_devices[0];
1228 } else {
1229 ERR_EXIT(
1230 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1231 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1232 "Please look at the Getting Started guide for additional information.\n",
1233 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001234 }
1235
Dave Houlton5fa47912018-02-16 11:02:26 -07001236 /* Look for device extensions */
1237 uint32_t device_extension_count = 0;
1238 vk::Bool32 swapchainExtFound = VK_FALSE;
1239 enabled_extension_count = 0;
1240 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001241
Dave Houlton5fa47912018-02-16 11:02:26 -07001242 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, nullptr);
1243 VERIFY(result == vk::Result::eSuccess);
1244
1245 if (device_extension_count > 0) {
1246 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1247 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001248 VERIFY(result == vk::Result::eSuccess);
1249
Dave Houlton5fa47912018-02-16 11:02:26 -07001250 for (uint32_t i = 0; i < device_extension_count; i++) {
1251 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1252 swapchainExtFound = 1;
1253 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001254 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001255 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001256 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001257 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001258
Dave Houlton5fa47912018-02-16 11:02:26 -07001259 if (!swapchainExtFound) {
1260 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1261 " extension.\n\n"
1262 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1263 "Please look at the Getting Started guide for additional information.\n",
1264 "vkCreateInstance Failure");
1265 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001266
Dave Houlton5fa47912018-02-16 11:02:26 -07001267 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001268
Dave Houlton5fa47912018-02-16 11:02:26 -07001269 /* Call with nullptr data to get count */
1270 gpu.getQueueFamilyProperties(&queue_family_count, nullptr);
1271 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001272
Dave Houlton5fa47912018-02-16 11:02:26 -07001273 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1274 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001275
Dave Houlton5fa47912018-02-16 11:02:26 -07001276 // Query fine-grained feature support for this device.
1277 // If app has specific feature requirements it should check supported
1278 // features based on this query
1279 vk::PhysicalDeviceFeatures physDevFeatures;
1280 gpu.getFeatures(&physDevFeatures);
1281}
1282
1283void Demo::init_vk_swapchain() {
1284// Create a WSI surface for the window:
1285#if defined(VK_USE_PLATFORM_WIN32_KHR)
1286 {
1287 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1288
1289 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1290 VERIFY(result == vk::Result::eSuccess);
1291 }
1292#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1293 {
1294 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1295
1296 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1297 VERIFY(result == vk::Result::eSuccess);
1298 }
1299#elif defined(VK_USE_PLATFORM_MIR_KHR)
1300#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1301 {
1302 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1303
1304 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1305 VERIFY(result == vk::Result::eSuccess);
1306 }
1307#elif defined(VK_USE_PLATFORM_XCB_KHR)
1308 {
1309 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1310
1311 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1312 VERIFY(result == vk::Result::eSuccess);
1313 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001314#elif defined(VK_USE_PLATFORM_IOS_MVK)
1315 {
1316 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1317
1318 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1319 VERIFY(result == vk::Result::eSuccess);
1320 }
1321#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1322 {
1323 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1324
1325 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1326 VERIFY(result == vk::Result::eSuccess);
1327 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001328#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1329 {
1330 auto result = create_display_surface();
1331 VERIFY(result == vk::Result::eSuccess);
1332 }
1333#endif
1334 // Iterate over each queue to learn whether it supports presenting:
1335 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1336 for (uint32_t i = 0; i < queue_family_count; i++) {
1337 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1338 }
1339
1340 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1341 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1342 for (uint32_t i = 0; i < queue_family_count; i++) {
1343 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1344 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1345 graphicsQueueFamilyIndex = i;
1346 }
1347
1348 if (supportsPresent[i] == VK_TRUE) {
1349 graphicsQueueFamilyIndex = i;
1350 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001351 break;
1352 }
1353 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001354 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001355
Dave Houlton5fa47912018-02-16 11:02:26 -07001356 if (presentQueueFamilyIndex == UINT32_MAX) {
1357 // If didn't find a queue that supports both graphics and present,
1358 // then
1359 // find a separate present queue.
1360 for (uint32_t i = 0; i < queue_family_count; ++i) {
1361 if (supportsPresent[i] == VK_TRUE) {
1362 presentQueueFamilyIndex = i;
1363 break;
1364 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001365 }
1366 }
1367
Dave Houlton5fa47912018-02-16 11:02:26 -07001368 // Generate error if could not find both a graphics and a present queue
1369 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1370 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1371 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001372
Dave Houlton5fa47912018-02-16 11:02:26 -07001373 graphics_queue_family_index = graphicsQueueFamilyIndex;
1374 present_queue_family_index = presentQueueFamilyIndex;
1375 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001376
Dave Houlton5fa47912018-02-16 11:02:26 -07001377 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001378
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1380 if (!separate_present_queue) {
1381 present_queue = graphics_queue;
1382 } else {
1383 device.getQueue(present_queue_family_index, 0, &present_queue);
1384 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001385
Dave Houlton5fa47912018-02-16 11:02:26 -07001386 // Get the list of VkFormat's that are supported:
1387 uint32_t formatCount;
1388 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, nullptr);
1389 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001390
Dave Houlton5fa47912018-02-16 11:02:26 -07001391 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1392 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1393 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001394
Dave Houlton5fa47912018-02-16 11:02:26 -07001395 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1396 // the surface has no preferred format. Otherwise, at least one
1397 // supported format will be returned.
1398 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1399 format = vk::Format::eB8G8R8A8Unorm;
1400 } else {
1401 assert(formatCount >= 1);
1402 format = surfFormats[0].format;
1403 }
1404 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001405
Dave Houlton5fa47912018-02-16 11:02:26 -07001406 quit = false;
1407 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001408
Dave Houlton5fa47912018-02-16 11:02:26 -07001409 // Create semaphores to synchronize acquiring presentable buffers before
1410 // rendering and waiting for drawing to be complete before presenting
1411 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001412
Dave Houlton5fa47912018-02-16 11:02:26 -07001413 // Create fences that we can use to throttle if we get too far
1414 // ahead of the image presents
1415 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1416 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1417 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1418 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001419
Dave Houlton5fa47912018-02-16 11:02:26 -07001420 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1421 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001422
Dave Houlton5fa47912018-02-16 11:02:26 -07001423 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1424 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001425
Dave Houlton5fa47912018-02-16 11:02:26 -07001426 if (separate_present_queue) {
1427 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001428 VERIFY(result == vk::Result::eSuccess);
1429 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001430 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001431 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001432
Dave Houlton5fa47912018-02-16 11:02:26 -07001433 // Get Memory information and properties
1434 gpu.getMemoryProperties(&memory_properties);
1435}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001436
Dave Houlton5fa47912018-02-16 11:02:26 -07001437void Demo::prepare() {
1438 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1439 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1440 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001441
Dave Houlton5fa47912018-02-16 11:02:26 -07001442 auto const cmd = vk::CommandBufferAllocateInfo()
1443 .setCommandPool(cmd_pool)
1444 .setLevel(vk::CommandBufferLevel::ePrimary)
1445 .setCommandBufferCount(1);
1446
1447 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1448 VERIFY(result == vk::Result::eSuccess);
1449
1450 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1451
1452 result = this->cmd.begin(&cmd_buf_info);
1453 VERIFY(result == vk::Result::eSuccess);
1454
1455 prepare_buffers();
1456 prepare_depth();
1457 prepare_textures();
1458 prepare_cube_data_buffers();
1459
1460 prepare_descriptor_layout();
1461 prepare_render_pass();
1462 prepare_pipeline();
1463
1464 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1465 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1466 VERIFY(result == vk::Result::eSuccess);
1467 }
1468
1469 if (separate_present_queue) {
1470 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1471
1472 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1473 VERIFY(result == vk::Result::eSuccess);
1474
1475 auto const present_cmd = vk::CommandBufferAllocateInfo()
1476 .setCommandPool(present_cmd_pool)
1477 .setLevel(vk::CommandBufferLevel::ePrimary)
1478 .setCommandBufferCount(1);
1479
1480 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1481 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1482 VERIFY(result == vk::Result::eSuccess);
1483
1484 build_image_ownership_cmd(i);
1485 }
1486 }
1487
1488 prepare_descriptor_pool();
1489 prepare_descriptor_set();
1490
1491 prepare_framebuffers();
1492
1493 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1494 current_buffer = i;
1495 draw_build_cmd(swapchain_image_resources[i].cmd);
1496 }
1497
1498 /*
1499 * Prepare functions above may generate pipeline commands
1500 * that need to be flushed before beginning the render loop.
1501 */
1502 flush_init_cmd();
1503 if (staging_texture.image) {
1504 destroy_texture_image(&staging_texture);
1505 }
1506
1507 current_buffer = 0;
1508 prepared = true;
1509}
1510
1511void Demo::prepare_buffers() {
1512 vk::SwapchainKHR oldSwapchain = swapchain;
1513
1514 // Check the surface capabilities and formats
1515 vk::SurfaceCapabilitiesKHR surfCapabilities;
1516 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1517 VERIFY(result == vk::Result::eSuccess);
1518
1519 uint32_t presentModeCount;
1520 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, nullptr);
1521 VERIFY(result == vk::Result::eSuccess);
1522
1523 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1524 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1525 VERIFY(result == vk::Result::eSuccess);
1526
1527 vk::Extent2D swapchainExtent;
1528 // width and height are either both -1, or both not -1.
1529 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1530 // If the surface size is undefined, the size is set to
1531 // the size of the images requested.
1532 swapchainExtent.width = width;
1533 swapchainExtent.height = height;
1534 } else {
1535 // If the surface size is defined, the swap chain size must match
1536 swapchainExtent = surfCapabilities.currentExtent;
1537 width = surfCapabilities.currentExtent.width;
1538 height = surfCapabilities.currentExtent.height;
1539 }
1540
1541 // The FIFO present mode is guaranteed by the spec to be supported
1542 // and to have no tearing. It's a great default present mode to use.
1543 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1544
1545 // There are times when you may wish to use another present mode. The
1546 // following code shows how to select them, and the comments provide some
1547 // reasons you may wish to use them.
1548 //
1549 // It should be noted that Vulkan 1.0 doesn't provide a method for
1550 // synchronizing rendering with the presentation engine's display. There
1551 // is a method provided for throttling rendering with the display, but
1552 // there are some presentation engines for which this method will not work.
1553 // If an application doesn't throttle its rendering, and if it renders much
1554 // faster than the refresh rate of the display, this can waste power on
1555 // mobile devices. That is because power is being spent rendering images
1556 // that may never be seen.
1557
1558 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1559 // about
1560 // tearing, or have some way of synchronizing their rendering with the
1561 // display.
1562 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1563 // generally render a new presentable image every refresh cycle, but are
1564 // occasionally early. In this case, the application wants the new
1565 // image
1566 // to be displayed instead of the previously-queued-for-presentation
1567 // image
1568 // that has not yet been displayed.
1569 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1570 // render a new presentable image every refresh cycle, but are
1571 // occasionally
1572 // late. In this case (perhaps because of stuttering/latency concerns),
1573 // the application wants the late image to be immediately displayed,
1574 // even
1575 // though that may mean some tearing.
1576
1577 if (presentMode != swapchainPresentMode) {
1578 for (size_t i = 0; i < presentModeCount; ++i) {
1579 if (presentModes[i] == presentMode) {
1580 swapchainPresentMode = presentMode;
1581 break;
1582 }
1583 }
1584 }
1585
1586 if (swapchainPresentMode != presentMode) {
1587 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1588 }
1589
1590 // Determine the number of VkImages to use in the swap chain.
1591 // Application desires to acquire 3 images at a time for triple
1592 // buffering
1593 uint32_t desiredNumOfSwapchainImages = 3;
1594 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1595 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1596 }
1597
1598 // If maxImageCount is 0, we can ask for as many images as we want,
1599 // otherwise
1600 // we're limited to maxImageCount
1601 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1602 // Application must settle for fewer images than desired:
1603 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1604 }
1605
1606 vk::SurfaceTransformFlagBitsKHR preTransform;
1607 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1608 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1609 } else {
1610 preTransform = surfCapabilities.currentTransform;
1611 }
1612
1613 // Find a supported composite alpha mode - one of these is guaranteed to be set
1614 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1615 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1616 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1617 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1618 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1619 vk::CompositeAlphaFlagBitsKHR::eInherit,
1620 };
1621 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1622 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1623 compositeAlpha = compositeAlphaFlags[i];
1624 break;
1625 }
1626 }
1627
1628 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1629 .setSurface(surface)
1630 .setMinImageCount(desiredNumOfSwapchainImages)
1631 .setImageFormat(format)
1632 .setImageColorSpace(color_space)
1633 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1634 .setImageArrayLayers(1)
1635 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1636 .setImageSharingMode(vk::SharingMode::eExclusive)
1637 .setQueueFamilyIndexCount(0)
1638 .setPQueueFamilyIndices(nullptr)
1639 .setPreTransform(preTransform)
1640 .setCompositeAlpha(compositeAlpha)
1641 .setPresentMode(swapchainPresentMode)
1642 .setClipped(true)
1643 .setOldSwapchain(oldSwapchain);
1644
1645 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1646 VERIFY(result == vk::Result::eSuccess);
1647
1648 // If we just re-created an existing swapchain, we should destroy the
1649 // old
1650 // swapchain at this point.
1651 // Note: destroying the swapchain also cleans up all its associated
1652 // presentable images once the platform is done with them.
1653 if (oldSwapchain) {
1654 device.destroySwapchainKHR(oldSwapchain, nullptr);
1655 }
1656
1657 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, nullptr);
1658 VERIFY(result == vk::Result::eSuccess);
1659
1660 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1661 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1662 VERIFY(result == vk::Result::eSuccess);
1663
1664 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1665
1666 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1667 auto color_image_view = vk::ImageViewCreateInfo()
1668 .setViewType(vk::ImageViewType::e2D)
1669 .setFormat(format)
1670 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1671
1672 swapchain_image_resources[i].image = swapchainImages[i];
1673
1674 color_image_view.image = swapchain_image_resources[i].image;
1675
1676 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1677 VERIFY(result == vk::Result::eSuccess);
1678 }
1679}
1680
1681void Demo::prepare_cube_data_buffers() {
1682 mat4x4 VP;
1683 mat4x4_mul(VP, projection_matrix, view_matrix);
1684
1685 mat4x4 MVP;
1686 mat4x4_mul(MVP, VP, model_matrix);
1687
1688 vktexcube_vs_uniform data;
1689 memcpy(data.mvp, MVP, sizeof(MVP));
1690 // dumpMatrix("MVP", MVP)
1691
1692 for (int32_t i = 0; i < 12 * 3; i++) {
1693 data.position[i][0] = g_vertex_buffer_data[i * 3];
1694 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1695 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1696 data.position[i][3] = 1.0f;
1697 data.attr[i][0] = g_uv_buffer_data[2 * i];
1698 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1699 data.attr[i][2] = 0;
1700 data.attr[i][3] = 0;
1701 }
1702
1703 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1704
1705 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1706 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001707 VERIFY(result == vk::Result::eSuccess);
1708
1709 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001710 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001711
Dave Houlton5fa47912018-02-16 11:02:26 -07001712 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001713
Dave Houlton5fa47912018-02-16 11:02:26 -07001714 bool const pass = memory_type_from_properties(
1715 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1716 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001717 VERIFY(pass);
1718
Dave Houlton5fa47912018-02-16 11:02:26 -07001719 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001720 VERIFY(result == vk::Result::eSuccess);
1721
Dave Houlton5fa47912018-02-16 11:02:26 -07001722 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1723 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001724
Dave Houlton5fa47912018-02-16 11:02:26 -07001725 memcpy(pData.value, &data, sizeof data);
1726
1727 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1728
1729 result =
1730 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001731 VERIFY(result == vk::Result::eSuccess);
1732 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001733}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001734
Dave Houlton5fa47912018-02-16 11:02:26 -07001735void Demo::prepare_depth() {
1736 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001737
Dave Houlton5fa47912018-02-16 11:02:26 -07001738 auto const image = vk::ImageCreateInfo()
1739 .setImageType(vk::ImageType::e2D)
1740 .setFormat(depth.format)
1741 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1742 .setMipLevels(1)
1743 .setArrayLayers(1)
1744 .setSamples(vk::SampleCountFlagBits::e1)
1745 .setTiling(vk::ImageTiling::eOptimal)
1746 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1747 .setSharingMode(vk::SharingMode::eExclusive)
1748 .setQueueFamilyIndexCount(0)
1749 .setPQueueFamilyIndices(nullptr)
1750 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001751
Dave Houlton5fa47912018-02-16 11:02:26 -07001752 auto result = device.createImage(&image, nullptr, &depth.image);
1753 VERIFY(result == vk::Result::eSuccess);
1754
1755 vk::MemoryRequirements mem_reqs;
1756 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1757
1758 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1759 depth.mem_alloc.setMemoryTypeIndex(0);
1760
1761 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1762 &depth.mem_alloc.memoryTypeIndex);
1763 VERIFY(pass);
1764
1765 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1766 VERIFY(result == vk::Result::eSuccess);
1767
1768 result = device.bindImageMemory(depth.image, depth.mem, 0);
1769 VERIFY(result == vk::Result::eSuccess);
1770
1771 auto const view = vk::ImageViewCreateInfo()
1772 .setImage(depth.image)
1773 .setViewType(vk::ImageViewType::e2D)
1774 .setFormat(depth.format)
1775 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1776 result = device.createImageView(&view, nullptr, &depth.view);
1777 VERIFY(result == vk::Result::eSuccess);
1778}
1779
1780void Demo::prepare_descriptor_layout() {
1781 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1782 .setBinding(0)
1783 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1784 .setDescriptorCount(1)
1785 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1786 .setPImmutableSamplers(nullptr),
1787 vk::DescriptorSetLayoutBinding()
1788 .setBinding(1)
1789 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1790 .setDescriptorCount(texture_count)
1791 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1792 .setPImmutableSamplers(nullptr)};
1793
1794 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1795
1796 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1797 VERIFY(result == vk::Result::eSuccess);
1798
1799 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1800
1801 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1802 VERIFY(result == vk::Result::eSuccess);
1803}
1804
1805void Demo::prepare_descriptor_pool() {
1806 vk::DescriptorPoolSize const poolSizes[2] = {
1807 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1808 vk::DescriptorPoolSize()
1809 .setType(vk::DescriptorType::eCombinedImageSampler)
1810 .setDescriptorCount(swapchainImageCount * texture_count)};
1811
1812 auto const descriptor_pool =
1813 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1814
1815 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1816 VERIFY(result == vk::Result::eSuccess);
1817}
1818
1819void Demo::prepare_descriptor_set() {
1820 auto const alloc_info =
1821 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1822
1823 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1824
1825 vk::DescriptorImageInfo tex_descs[texture_count];
1826 for (uint32_t i = 0; i < texture_count; i++) {
1827 tex_descs[i].setSampler(textures[i].sampler);
1828 tex_descs[i].setImageView(textures[i].view);
1829 tex_descs[i].setImageLayout(vk::ImageLayout::eGeneral);
1830 }
1831
1832 vk::WriteDescriptorSet writes[2];
1833
1834 writes[0].setDescriptorCount(1);
1835 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1836 writes[0].setPBufferInfo(&buffer_info);
1837
1838 writes[1].setDstBinding(1);
1839 writes[1].setDescriptorCount(texture_count);
1840 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1841 writes[1].setPImageInfo(tex_descs);
1842
1843 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1844 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001845 VERIFY(result == vk::Result::eSuccess);
1846
Dave Houlton5fa47912018-02-16 11:02:26 -07001847 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1848 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1849 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1850 device.updateDescriptorSets(2, writes, 0, nullptr);
1851 }
1852}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001853
Dave Houlton5fa47912018-02-16 11:02:26 -07001854void Demo::prepare_framebuffers() {
1855 vk::ImageView attachments[2];
1856 attachments[1] = depth.view;
1857
1858 auto const fb_info = vk::FramebufferCreateInfo()
1859 .setRenderPass(render_pass)
1860 .setAttachmentCount(2)
1861 .setPAttachments(attachments)
1862 .setWidth((uint32_t)width)
1863 .setHeight((uint32_t)height)
1864 .setLayers(1);
1865
1866 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1867 attachments[0] = swapchain_image_resources[i].view;
1868 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001869 VERIFY(result == vk::Result::eSuccess);
1870 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001871}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001872
Dave Houlton5fa47912018-02-16 11:02:26 -07001873vk::ShaderModule Demo::prepare_fs() {
1874 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001875#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001876 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001877
Dave Houlton5fa47912018-02-16 11:02:26 -07001878 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001879
Dave Houlton5fa47912018-02-16 11:02:26 -07001880 return frag_shader_module;
1881}
1882
1883void Demo::prepare_pipeline() {
1884 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1885 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1886 VERIFY(result == vk::Result::eSuccess);
1887
1888 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1889 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1890 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1891
1892 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1893
1894 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1895
1896 // TODO: Where are pViewports and pScissors set?
1897 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1898
1899 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1900 .setDepthClampEnable(VK_FALSE)
1901 .setRasterizerDiscardEnable(VK_FALSE)
1902 .setPolygonMode(vk::PolygonMode::eFill)
1903 .setCullMode(vk::CullModeFlagBits::eBack)
1904 .setFrontFace(vk::FrontFace::eCounterClockwise)
1905 .setDepthBiasEnable(VK_FALSE)
1906 .setLineWidth(1.0f);
1907
1908 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1909
1910 auto const stencilOp =
1911 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1912
1913 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1914 .setDepthTestEnable(VK_TRUE)
1915 .setDepthWriteEnable(VK_TRUE)
1916 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1917 .setDepthBoundsTestEnable(VK_FALSE)
1918 .setStencilTestEnable(VK_FALSE)
1919 .setFront(stencilOp)
1920 .setBack(stencilOp);
1921
1922 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1923 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1924 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1925
1926 auto const colorBlendInfo =
1927 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1928
1929 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1930
1931 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1932
1933 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1934 .setStageCount(2)
1935 .setPStages(shaderStageInfo)
1936 .setPVertexInputState(&vertexInputInfo)
1937 .setPInputAssemblyState(&inputAssemblyInfo)
1938 .setPViewportState(&viewportInfo)
1939 .setPRasterizationState(&rasterizationInfo)
1940 .setPMultisampleState(&multisampleInfo)
1941 .setPDepthStencilState(&depthStencilInfo)
1942 .setPColorBlendState(&colorBlendInfo)
1943 .setPDynamicState(&dynamicStateInfo)
1944 .setLayout(pipeline_layout)
1945 .setRenderPass(render_pass);
1946
1947 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1948 VERIFY(result == vk::Result::eSuccess);
1949
1950 device.destroyShaderModule(frag_shader_module, nullptr);
1951 device.destroyShaderModule(vert_shader_module, nullptr);
1952}
1953
1954void Demo::prepare_render_pass() {
1955 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1956 // because at the start of the renderpass, we don't care about their contents.
1957 // At the start of the subpass, the color attachment's layout will be transitioned
1958 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1959 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1960 // the renderpass, the color attachment's layout will be transitioned to
1961 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1962 // the renderpass, no barriers are necessary.
1963 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1964 .setFormat(format)
1965 .setSamples(vk::SampleCountFlagBits::e1)
1966 .setLoadOp(vk::AttachmentLoadOp::eClear)
1967 .setStoreOp(vk::AttachmentStoreOp::eStore)
1968 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1969 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1970 .setInitialLayout(vk::ImageLayout::eUndefined)
1971 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1972 vk::AttachmentDescription()
1973 .setFormat(depth.format)
1974 .setSamples(vk::SampleCountFlagBits::e1)
1975 .setLoadOp(vk::AttachmentLoadOp::eClear)
1976 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1977 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1978 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1979 .setInitialLayout(vk::ImageLayout::eUndefined)
1980 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1981
1982 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1983
1984 auto const depth_reference =
1985 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1986
1987 auto const subpass = vk::SubpassDescription()
1988 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1989 .setInputAttachmentCount(0)
1990 .setPInputAttachments(nullptr)
1991 .setColorAttachmentCount(1)
1992 .setPColorAttachments(&color_reference)
1993 .setPResolveAttachments(nullptr)
1994 .setPDepthStencilAttachment(&depth_reference)
1995 .setPreserveAttachmentCount(0)
1996 .setPPreserveAttachments(nullptr);
1997
1998 auto const rp_info = vk::RenderPassCreateInfo()
1999 .setAttachmentCount(2)
2000 .setPAttachments(attachments)
2001 .setSubpassCount(1)
2002 .setPSubpasses(&subpass)
2003 .setDependencyCount(0)
2004 .setPDependencies(nullptr);
2005
2006 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2007 VERIFY(result == vk::Result::eSuccess);
2008}
2009
2010vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2011 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2012
2013 vk::ShaderModule module;
2014 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2015 VERIFY(result == vk::Result::eSuccess);
2016
2017 return module;
2018}
2019
2020void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2021 vk::MemoryPropertyFlags required_props) {
2022 int32_t tex_width;
2023 int32_t tex_height;
2024 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2025 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002026 }
2027
Dave Houlton5fa47912018-02-16 11:02:26 -07002028 tex_obj->tex_width = tex_width;
2029 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002030
Dave Houlton5fa47912018-02-16 11:02:26 -07002031 auto const image_create_info = vk::ImageCreateInfo()
2032 .setImageType(vk::ImageType::e2D)
2033 .setFormat(vk::Format::eR8G8B8A8Unorm)
2034 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2035 .setMipLevels(1)
2036 .setArrayLayers(1)
2037 .setSamples(vk::SampleCountFlagBits::e1)
2038 .setTiling(tiling)
2039 .setUsage(usage)
2040 .setSharingMode(vk::SharingMode::eExclusive)
2041 .setQueueFamilyIndexCount(0)
2042 .setPQueueFamilyIndices(nullptr)
2043 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002044
Dave Houlton5fa47912018-02-16 11:02:26 -07002045 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2046 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002047
Dave Houlton5fa47912018-02-16 11:02:26 -07002048 vk::MemoryRequirements mem_reqs;
2049 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002050
Dave Houlton5fa47912018-02-16 11:02:26 -07002051 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2052 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002053
Dave Houlton5fa47912018-02-16 11:02:26 -07002054 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2055 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002056
Dave Houlton5fa47912018-02-16 11:02:26 -07002057 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2058 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002059
Dave Houlton5fa47912018-02-16 11:02:26 -07002060 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2061 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002062
Dave Houlton5fa47912018-02-16 11:02:26 -07002063 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2064 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2065 vk::SubresourceLayout layout;
2066 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002067
Dave Houlton5fa47912018-02-16 11:02:26 -07002068 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002069 VERIFY(data.result == vk::Result::eSuccess);
2070
Dave Houlton5fa47912018-02-16 11:02:26 -07002071 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2072 fprintf(stderr, "Error loading texture: %s\n", filename);
2073 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002074
Dave Houlton5fa47912018-02-16 11:02:26 -07002075 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002076 }
2077
Dave Houlton5fa47912018-02-16 11:02:26 -07002078 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2079}
2080
2081void Demo::prepare_textures() {
2082 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2083 vk::FormatProperties props;
2084 gpu.getFormatProperties(tex_format, &props);
2085
2086 for (uint32_t i = 0; i < texture_count; i++) {
2087 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2088 /* Device can texture using linear textures */
2089 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2090 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2091 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2092 // shader to run until layout transition completes
2093 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2094 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2095 vk::PipelineStageFlagBits::eFragmentShader);
2096 staging_texture.image = vk::Image();
2097 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2098 /* Must use staging buffer to copy linear texture to optimized */
2099
2100 prepare_texture_image(tex_files[i], &staging_texture, vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eTransferSrc,
2101 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2102
2103 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2104 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2105 vk::MemoryPropertyFlagBits::eDeviceLocal);
2106
2107 set_image_layout(staging_texture.image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2108 vk::ImageLayout::eTransferSrcOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2109 vk::PipelineStageFlagBits::eTransfer);
2110
2111 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2112 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2113 vk::PipelineStageFlagBits::eTransfer);
2114
2115 auto const subresource = vk::ImageSubresourceLayers()
2116 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2117 .setMipLevel(0)
2118 .setBaseArrayLayer(0)
2119 .setLayerCount(1);
2120
2121 auto const copy_region = vk::ImageCopy()
2122 .setSrcSubresource(subresource)
2123 .setSrcOffset({0, 0, 0})
2124 .setDstSubresource(subresource)
2125 .setDstOffset({0, 0, 0})
2126 .setExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
2127
2128 cmd.copyImage(staging_texture.image, vk::ImageLayout::eTransferSrcOptimal, textures[i].image,
2129 vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
2130
2131 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2132 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2133 vk::PipelineStageFlagBits::eFragmentShader);
2134 } else {
2135 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002136 }
2137
Dave Houlton5fa47912018-02-16 11:02:26 -07002138 auto const samplerInfo = vk::SamplerCreateInfo()
2139 .setMagFilter(vk::Filter::eNearest)
2140 .setMinFilter(vk::Filter::eNearest)
2141 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2142 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2143 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2144 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2145 .setMipLodBias(0.0f)
2146 .setAnisotropyEnable(VK_FALSE)
2147 .setMaxAnisotropy(1)
2148 .setCompareEnable(VK_FALSE)
2149 .setCompareOp(vk::CompareOp::eNever)
2150 .setMinLod(0.0f)
2151 .setMaxLod(0.0f)
2152 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2153 .setUnnormalizedCoordinates(VK_FALSE);
2154
2155 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2156 VERIFY(result == vk::Result::eSuccess);
2157
2158 auto const viewInfo = vk::ImageViewCreateInfo()
2159 .setImage(textures[i].image)
2160 .setViewType(vk::ImageViewType::e2D)
2161 .setFormat(tex_format)
2162 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2163
2164 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2165 VERIFY(result == vk::Result::eSuccess);
2166 }
2167}
2168
2169vk::ShaderModule Demo::prepare_vs() {
2170 const uint32_t vertShaderCode[] = {
2171#include "cube.vert.inc"
2172 };
2173
2174 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2175
2176 return vert_shader_module;
2177}
2178
2179void Demo::resize() {
2180 uint32_t i;
2181
2182 // Don't react to resize until after first initialization.
2183 if (!prepared) {
2184 return;
2185 }
2186
2187 // In order to properly resize the window, we must re-create the
2188 // swapchain
2189 // AND redo the command buffers, etc.
2190 //
2191 // First, perform part of the cleanup() function:
2192 prepared = false;
2193 auto result = device.waitIdle();
2194 VERIFY(result == vk::Result::eSuccess);
2195
2196 for (i = 0; i < swapchainImageCount; i++) {
2197 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2198 }
2199
2200 device.destroyDescriptorPool(desc_pool, nullptr);
2201
2202 device.destroyPipeline(pipeline, nullptr);
2203 device.destroyPipelineCache(pipelineCache, nullptr);
2204 device.destroyRenderPass(render_pass, nullptr);
2205 device.destroyPipelineLayout(pipeline_layout, nullptr);
2206 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2207
2208 for (i = 0; i < texture_count; i++) {
2209 device.destroyImageView(textures[i].view, nullptr);
2210 device.destroyImage(textures[i].image, nullptr);
2211 device.freeMemory(textures[i].mem, nullptr);
2212 device.destroySampler(textures[i].sampler, nullptr);
2213 }
2214
2215 device.destroyImageView(depth.view, nullptr);
2216 device.destroyImage(depth.image, nullptr);
2217 device.freeMemory(depth.mem, nullptr);
2218
2219 for (i = 0; i < swapchainImageCount; i++) {
2220 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2221 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2222 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2223 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2224 }
2225
2226 device.destroyCommandPool(cmd_pool, nullptr);
2227 if (separate_present_queue) {
2228 device.destroyCommandPool(present_cmd_pool, nullptr);
2229 }
2230
2231 // Second, re-perform the prepare() function, which will re-create the
2232 // swapchain.
2233 prepare();
2234}
2235
2236void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2237 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2238 assert(cmd);
2239
2240 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2241 vk::AccessFlags flags;
2242
2243 switch (layout) {
2244 case vk::ImageLayout::eTransferDstOptimal:
2245 // Make sure anything that was copying from this image has
2246 // completed
2247 flags = vk::AccessFlagBits::eTransferWrite;
2248 break;
2249 case vk::ImageLayout::eColorAttachmentOptimal:
2250 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2251 break;
2252 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2253 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2254 break;
2255 case vk::ImageLayout::eShaderReadOnlyOptimal:
2256 // Make sure any Copy or CPU writes to image are flushed
2257 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2258 break;
2259 case vk::ImageLayout::eTransferSrcOptimal:
2260 flags = vk::AccessFlagBits::eTransferRead;
2261 break;
2262 case vk::ImageLayout::ePresentSrcKHR:
2263 flags = vk::AccessFlagBits::eMemoryRead;
2264 break;
2265 default:
2266 break;
2267 }
2268
2269 return flags;
2270 };
2271
2272 auto const barrier = vk::ImageMemoryBarrier()
2273 .setSrcAccessMask(srcAccessMask)
2274 .setDstAccessMask(DstAccessMask(newLayout))
2275 .setOldLayout(oldLayout)
2276 .setNewLayout(newLayout)
2277 .setSrcQueueFamilyIndex(0)
2278 .setDstQueueFamilyIndex(0)
2279 .setImage(image)
2280 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2281
2282 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2283}
2284
2285void Demo::update_data_buffer() {
2286 mat4x4 VP;
2287 mat4x4_mul(VP, projection_matrix, view_matrix);
2288
2289 // Rotate around the Y axis
2290 mat4x4 Model;
2291 mat4x4_dup(Model, model_matrix);
2292 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2293
2294 mat4x4 MVP;
2295 mat4x4_mul(MVP, VP, model_matrix);
2296
2297 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2298 VERIFY(data.result == vk::Result::eSuccess);
2299
2300 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2301
2302 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2303}
2304
2305bool 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 -05002306#if (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
2307 filename = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@(filename)].UTF8String;
2308#endif
2309
Dave Houlton5fa47912018-02-16 11:02:26 -07002310 FILE *fPtr = fopen(filename, "rb");
2311 if (!fPtr) {
2312 return false;
2313 }
2314
2315 char header[256];
2316 char *cPtr = fgets(header, 256, fPtr); // P6
2317 if (cPtr == nullptr || strncmp(header, "P6\n", 3)) {
2318 fclose(fPtr);
2319 return false;
2320 }
2321
2322 do {
2323 cPtr = fgets(header, 256, fPtr);
2324 if (cPtr == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002325 fclose(fPtr);
2326 return false;
2327 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002328 } while (!strncmp(header, "#", 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002329
Dave Houlton5fa47912018-02-16 11:02:26 -07002330 sscanf(header, "%" SCNd32 " %" SCNd32, width, height);
2331 if (rgba_data == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002332 fclose(fPtr);
2333 return true;
2334 }
2335
Dave Houlton5fa47912018-02-16 11:02:26 -07002336 char *result = fgets(header, 256, fPtr); // Format
2337 VERIFY(result != nullptr);
2338 if (cPtr == nullptr || strncmp(header, "255\n", 3)) {
2339 fclose(fPtr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002340 return false;
2341 }
2342
Dave Houlton5fa47912018-02-16 11:02:26 -07002343 for (int y = 0; y < *height; y++) {
2344 uint8_t *rowPtr = rgba_data;
2345
2346 for (int x = 0; x < *width; x++) {
2347 size_t s = fread(rowPtr, 3, 1, fPtr);
2348 (void)s;
2349 rowPtr[3] = 255; /* Alpha of 1 */
2350 rowPtr += 4;
2351 }
2352
2353 rgba_data += layout->rowPitch;
2354 }
2355
2356 fclose(fPtr);
2357 return true;
2358}
2359
2360bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2361 // Search memtypes to find first index with those properties
2362 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2363 if ((typeBits & 1) == 1) {
2364 // Type is available, does it match user properties?
2365 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2366 *typeIndex = i;
2367 return true;
2368 }
2369 }
2370 typeBits >>= 1;
2371 }
2372
2373 // No memory types matched, return failure
2374 return false;
2375}
2376
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002377#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002378void Demo::run() {
2379 if (!prepared) {
2380 return;
2381 }
2382
2383 draw();
2384 curFrame++;
2385
2386 if (frameCount != INT_MAX && curFrame == frameCount) {
2387 PostQuitMessage(validation_error);
2388 }
2389}
2390
2391void Demo::create_window() {
2392 WNDCLASSEX win_class;
2393
2394 // Initialize the window class structure:
2395 win_class.cbSize = sizeof(WNDCLASSEX);
2396 win_class.style = CS_HREDRAW | CS_VREDRAW;
2397 win_class.lpfnWndProc = WndProc;
2398 win_class.cbClsExtra = 0;
2399 win_class.cbWndExtra = 0;
2400 win_class.hInstance = connection; // hInstance
2401 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2402 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2403 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2404 win_class.lpszMenuName = nullptr;
2405 win_class.lpszClassName = name;
2406 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2407
2408 // Register window class:
2409 if (!RegisterClassEx(&win_class)) {
2410 // It didn't work, so try to give a useful error:
2411 printf("Unexpected error trying to start the application!\n");
2412 fflush(stdout);
2413 exit(1);
2414 }
2415
2416 // Create window with the registered class:
2417 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2418 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2419 window = CreateWindowEx(0,
2420 name, // class name
2421 name, // app name
2422 WS_OVERLAPPEDWINDOW | // window style
2423 WS_VISIBLE | WS_SYSMENU,
2424 100, 100, // x/y coords
2425 wr.right - wr.left, // width
2426 wr.bottom - wr.top, // height
2427 nullptr, // handle to parent
2428 nullptr, // handle to menu
2429 connection, // hInstance
2430 nullptr); // no extra parameters
2431
2432 if (!window) {
2433 // It didn't work, so try to give a useful error:
2434 printf("Cannot create a window in which to draw!\n");
2435 fflush(stdout);
2436 exit(1);
2437 }
2438
2439 // Window client area size must be at least 1 pixel high, to prevent
2440 // crash.
2441 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2442 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2443}
2444#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2445
2446void Demo::create_xlib_window() {
2447 const char *display_envar = getenv("DISPLAY");
2448 if (display_envar == nullptr || display_envar[0] == '\0') {
2449 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2450 fflush(stdout);
2451 exit(1);
2452 }
2453
2454 XInitThreads();
2455 display = XOpenDisplay(nullptr);
2456 long visualMask = VisualScreenMask;
2457 int numberOfVisuals;
2458 XVisualInfo vInfoTemplate = {};
2459 vInfoTemplate.screen = DefaultScreen(display);
2460 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2461
2462 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2463
2464 XSetWindowAttributes windowAttributes = {};
2465 windowAttributes.colormap = colormap;
2466 windowAttributes.background_pixel = 0xFFFFFFFF;
2467 windowAttributes.border_pixel = 0;
2468 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2469
2470 xlib_window =
2471 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2472 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2473
2474 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2475 XMapWindow(display, xlib_window);
2476 XFlush(display);
2477 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2478}
2479
2480void Demo::handle_xlib_event(const XEvent *event) {
2481 switch (event->type) {
2482 case ClientMessage:
2483 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2484 quit = true;
2485 }
2486 break;
2487 case KeyPress:
2488 switch (event->xkey.keycode) {
2489 case 0x9: // Escape
2490 quit = true;
2491 break;
2492 case 0x71: // left arrow key
2493 spin_angle -= spin_increment;
2494 break;
2495 case 0x72: // right arrow key
2496 spin_angle += spin_increment;
2497 break;
2498 case 0x41: // space bar
2499 pause = !pause;
2500 break;
2501 }
2502 break;
2503 case ConfigureNotify:
2504 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2505 width = event->xconfigure.width;
2506 height = event->xconfigure.height;
2507 resize();
2508 }
2509 break;
2510 default:
2511 break;
2512 }
2513}
2514
2515void Demo::run_xlib() {
2516 while (!quit) {
2517 XEvent event;
2518
2519 if (pause) {
2520 XNextEvent(display, &event);
2521 handle_xlib_event(&event);
2522 }
2523 while (XPending(display) > 0) {
2524 XNextEvent(display, &event);
2525 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002526 }
2527
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002528 draw();
2529 curFrame++;
2530
Dave Houlton5fa47912018-02-16 11:02:26 -07002531 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2532 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002533 }
2534 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002535}
Tony Barbour153cb062016-12-07 13:43:36 -07002536#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002537
Dave Houlton5fa47912018-02-16 11:02:26 -07002538void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2539 uint8_t event_code = event->response_type & 0x7f;
2540 switch (event_code) {
2541 case XCB_EXPOSE:
2542 // TODO: Resize window
2543 break;
2544 case XCB_CLIENT_MESSAGE:
2545 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2546 quit = true;
2547 }
2548 break;
2549 case XCB_KEY_RELEASE: {
2550 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002551
Dave Houlton5fa47912018-02-16 11:02:26 -07002552 switch (key->detail) {
2553 case 0x9: // Escape
2554 quit = true;
2555 break;
2556 case 0x71: // left arrow key
2557 spin_angle -= spin_increment;
2558 break;
2559 case 0x72: // right arrow key
2560 spin_angle += spin_increment;
2561 break;
2562 case 0x41: // space bar
2563 pause = !pause;
2564 break;
2565 }
2566 } break;
2567 case XCB_CONFIGURE_NOTIFY: {
2568 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2569 if ((width != cfg->width) || (height != cfg->height)) {
2570 width = cfg->width;
2571 height = cfg->height;
2572 resize();
2573 }
2574 } break;
2575 default:
2576 break;
2577 }
2578}
2579
2580void Demo::run_xcb() {
2581 xcb_flush(connection);
2582
2583 while (!quit) {
2584 xcb_generic_event_t *event;
2585
2586 if (pause) {
2587 event = xcb_wait_for_event(connection);
2588 } else {
2589 event = xcb_poll_for_event(connection);
2590 }
2591 while (event) {
2592 handle_xcb_event(event);
2593 free(event);
2594 event = xcb_poll_for_event(connection);
2595 }
2596
2597 draw();
2598 curFrame++;
2599 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2600 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002601 }
2602 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002603}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002604
Dave Houlton5fa47912018-02-16 11:02:26 -07002605void Demo::create_xcb_window() {
2606 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002607
Dave Houlton5fa47912018-02-16 11:02:26 -07002608 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002609
Dave Houlton5fa47912018-02-16 11:02:26 -07002610 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2611 value_list[0] = screen->black_pixel;
2612 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002613
Dave Houlton5fa47912018-02-16 11:02:26 -07002614 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2615 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2616
2617 /* Magic code that will send notification when window is destroyed */
2618 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2619 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2620
2621 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2622 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2623
2624 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2625
2626 free(reply);
2627
2628 xcb_map_window(connection, xcb_window);
2629
2630 // Force the x/y coordinates to 100,100 results are identical in
2631 // consecutive
2632 // runs
2633 const uint32_t coords[] = {100, 100};
2634 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2635}
2636#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2637
2638void Demo::run() {
2639 while (!quit) {
2640 if (pause) {
2641 wl_display_dispatch(display);
2642 } else {
2643 wl_display_dispatch_pending(display);
2644 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002645 draw();
2646 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002647 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002648 quit = true;
2649 }
2650 }
2651 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002652}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002653
Dave Houlton5fa47912018-02-16 11:02:26 -07002654void Demo::create_window() {
2655 window = wl_compositor_create_surface(compositor);
2656 if (!window) {
2657 printf("Can not create wayland_surface from compositor!\n");
2658 fflush(stdout);
2659 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002660 }
2661
Dave Houlton5fa47912018-02-16 11:02:26 -07002662 shell_surface = wl_shell_get_shell_surface(shell, window);
2663 if (!shell_surface) {
2664 printf("Can not get shell_surface from wayland_surface!\n");
2665 fflush(stdout);
2666 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002667 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002668
2669 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2670 wl_shell_surface_set_toplevel(shell_surface);
2671 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
2672}
Karl Schultz206b1c52018-04-13 18:02:07 -06002673#elif defined(VK_USE_PLATFORM_MACOS_MVK)
2674void Demo::run() {
2675 draw();
2676 curFrame++;
2677 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2678 quit = true;
2679 }
2680}
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002681#elif defined(VK_USE_PLATFORM_MIR_KHR)
Damien Leone600c3052017-01-31 10:26:07 -07002682#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2683
Dave Houlton5fa47912018-02-16 11:02:26 -07002684vk::Result Demo::create_display_surface() {
2685 vk::Result result;
2686 uint32_t display_count;
2687 uint32_t mode_count;
2688 uint32_t plane_count;
2689 vk::DisplayPropertiesKHR display_props;
2690 vk::DisplayKHR display;
2691 vk::DisplayModePropertiesKHR mode_props;
2692 vk::DisplayPlanePropertiesKHR *plane_props;
2693 vk::Bool32 found_plane = VK_FALSE;
2694 uint32_t plane_index;
2695 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002696
Dave Houlton5fa47912018-02-16 11:02:26 -07002697 // Get the first display
2698 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2699 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002700
Dave Houlton5fa47912018-02-16 11:02:26 -07002701 if (display_count == 0) {
2702 printf("Cannot find any display!\n");
2703 fflush(stdout);
2704 exit(1);
2705 }
2706
2707 display_count = 1;
2708 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2709 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2710
2711 display = display_props.display;
2712
2713 // Get the first mode of the display
2714 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2715 VERIFY(result == vk::Result::eSuccess);
2716
2717 if (mode_count == 0) {
2718 printf("Cannot find any mode for the display!\n");
2719 fflush(stdout);
2720 exit(1);
2721 }
2722
2723 mode_count = 1;
2724 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2725 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2726
2727 // Get the list of planes
2728 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2729 VERIFY(result == vk::Result::eSuccess);
2730
2731 if (plane_count == 0) {
2732 printf("Cannot find any plane!\n");
2733 fflush(stdout);
2734 exit(1);
2735 }
2736
2737 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2738 VERIFY(plane_props != nullptr);
2739
2740 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2741 VERIFY(result == vk::Result::eSuccess);
2742
2743 // Find a plane compatible with the display
2744 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2745 uint32_t supported_count;
2746 vk::DisplayKHR *supported_displays;
2747
2748 // Disqualify planes that are bound to a different display
2749 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2750 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002751 }
2752
Dave Houlton5fa47912018-02-16 11:02:26 -07002753 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002754 VERIFY(result == vk::Result::eSuccess);
2755
Dave Houlton5fa47912018-02-16 11:02:26 -07002756 if (supported_count == 0) {
2757 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002758 }
2759
Dave Houlton5fa47912018-02-16 11:02:26 -07002760 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2761 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002762
Dave Houlton5fa47912018-02-16 11:02:26 -07002763 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002764 VERIFY(result == vk::Result::eSuccess);
2765
Dave Houlton5fa47912018-02-16 11:02:26 -07002766 for (uint32_t i = 0; i < supported_count; i++) {
2767 if (supported_displays[i] == display) {
2768 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002769 break;
2770 }
2771 }
2772
Dave Houlton5fa47912018-02-16 11:02:26 -07002773 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002774
Dave Houlton5fa47912018-02-16 11:02:26 -07002775 if (found_plane) {
2776 break;
Damien Leone600c3052017-01-31 10:26:07 -07002777 }
2778 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002779
2780 if (!found_plane) {
2781 printf("Cannot find a plane compatible with the display!\n");
2782 fflush(stdout);
2783 exit(1);
2784 }
2785
2786 free(plane_props);
2787
2788 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2789 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2790 // Find a supported alpha mode
2791 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2792 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2793 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2794 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2795 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2796 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2797 };
2798 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2799 if (planeCaps.supportedAlpha & alphaModes[i]) {
2800 alphaMode = alphaModes[i];
2801 break;
2802 }
2803 }
2804
2805 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2806 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2807
2808 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2809 .setDisplayMode(mode_props.displayMode)
2810 .setPlaneIndex(plane_index)
2811 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2812 .setGlobalAlpha(1.0f)
2813 .setAlphaMode(alphaMode)
2814 .setImageExtent(image_extent);
2815
2816 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2817}
2818
2819void Demo::run_display() {
2820 while (!quit) {
2821 draw();
2822 curFrame++;
2823
2824 if (frameCount != INT32_MAX && curFrame == frameCount) {
2825 quit = true;
2826 }
2827 }
2828}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002829#endif
2830
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002831#if _WIN32
2832// Include header required for parsing the command line options.
2833#include <shellapi.h>
2834
2835Demo demo;
2836
2837// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002838LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2839 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002840 case WM_CLOSE:
2841 PostQuitMessage(validation_error);
2842 break;
2843 case WM_PAINT:
2844 demo.run();
2845 break;
2846 case WM_GETMINMAXINFO: // set window's minimum size
2847 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2848 return 0;
2849 case WM_SIZE:
2850 // Resize the application to the new window size, except when
2851 // it was minimized. Vulkan doesn't support images or swapchains
2852 // with width=0 and height=0.
2853 if (wParam != SIZE_MINIMIZED) {
2854 demo.width = lParam & 0xffff;
2855 demo.height = (lParam & 0xffff0000) >> 16;
2856 demo.resize();
2857 }
2858 break;
2859 default:
2860 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002861 }
2862
2863 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2864}
2865
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002866int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002867 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002868 MSG msg; // message
2869 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002870 int argc;
2871 char **argv;
2872
Jamie Madillb2ff6502017-03-15 16:17:46 -04002873 // Ensure wParam is initialized.
2874 msg.wParam = 0;
2875
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002876 // Use the CommandLine functions to get the command line arguments.
2877 // Unfortunately, Microsoft outputs
2878 // this information as wide characters for Unicode, and we simply want the
2879 // Ascii version to be compatible
2880 // with the non-Windows side. So, we have to convert the information to
2881 // Ascii character strings.
2882 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002883 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002884 argc = 0;
2885 }
2886
Jeremy Hayes9d304782016-10-09 11:48:12 -06002887 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002888 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002889 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002890 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002891 } else {
2892 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002893 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2894 size_t numConverted = 0;
2895
2896 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002897 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002898 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002899 }
2900 }
2901 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002902 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002903 argv = nullptr;
2904 }
2905
2906 demo.init(argc, argv);
2907
2908 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002909 if (argc > 0 && argv != nullptr) {
2910 for (int iii = 0; iii < argc; iii++) {
2911 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002912 free(argv[iii]);
2913 }
2914 }
2915 free(argv);
2916 }
2917
2918 demo.connection = hInstance;
2919 strncpy(demo.name, "cube", APP_NAME_STR_LEN);
2920 demo.create_window();
2921 demo.init_vk_swapchain();
2922
2923 demo.prepare();
2924
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002925 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002926
2927 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002928 while (!done) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002929 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002930 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002931 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002932 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002933 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002934 /* Translate and dispatch to event queue*/
2935 TranslateMessage(&msg);
2936 DispatchMessage(&msg);
2937 }
2938 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2939 }
2940
2941 demo.cleanup();
2942
2943 return (int)msg.wParam;
2944}
2945
2946#elif __linux__
2947
Jeremy Hayes9d304782016-10-09 11:48:12 -06002948int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002949 Demo demo;
2950
2951 demo.init(argc, argv);
2952
Tony Barbour153cb062016-12-07 13:43:36 -07002953#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002954 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002955#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07002956 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002957 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002958#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06002959 demo.create_window();
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002960#elif defined(VK_USE_PLATFORM_MIR_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002961#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002962
2963 demo.init_vk_swapchain();
2964
2965 demo.prepare();
2966
Tony Barbour153cb062016-12-07 13:43:36 -07002967#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002968 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002969#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002970 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002971#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002972 demo.run();
Tony Barbourefd0c5a2016-12-07 14:45:12 -07002973#elif defined(VK_USE_PLATFORM_MIR_KHR)
Damien Leone600c3052017-01-31 10:26:07 -07002974#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2975 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002976#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002977
2978 demo.cleanup();
2979
2980 return validation_error;
2981}
2982
Karl Schultz9ceac062017-12-12 10:33:01 -05002983#elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
2984
2985// Global function invoked from NS or UI views and controllers to create demo
Karl Schultz206b1c52018-04-13 18:02:07 -06002986static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05002987
2988 demo.init(argc, (char **)argv);
2989 demo.window = view;
2990 demo.init_vk_swapchain();
2991 demo.prepare();
2992 demo.spin_angle = 0.4f;
2993}
2994
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002995#else
2996#error "Platform not supported"
2997#endif