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