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