blob: ddbd1fc946acd4e4ee432da543ed16347a5e4050 [file] [log] [blame]
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001/*
Tony-LunarG495604b2019-06-13 15:32:05 -06002 * Copyright (c) 2015-2019 The Khronos Group Inc.
3 * Copyright (c) 2015-2019 Valve Corporation
4 * Copyright (c) 2015-2019 LunarG, Inc.
Dave Houlton5fa47912018-02-16 11:02:26 -07005 *
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 */
Richard S. Wright Jra7825742021-01-06 16:02:12 -050020
Jeremy Hayesf56427a2016-09-07 15:55:11 -060021#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>
Manuel Stoecklac939332019-06-26 20:55:53 -040025#include "xdg-shell-client-header.h"
26#include "xdg-decoration-client-header.h"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060027#endif
28
29#include <cassert>
Petr Krausbc0ab752017-12-09 00:22:39 +010030#include <cinttypes>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060031#include <cstdio>
32#include <cstdlib>
33#include <cstring>
34#include <csignal>
Tony-LunarGd74734f2019-06-04 14:11:43 -060035#include <iostream>
36#include <sstream>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060037#include <memory>
38
39#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060040#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060041#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
Lenny Komowffe446c2018-11-19 17:08:04 -070052#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060053#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
Jeremy Hayesf56427a2016-09-07 15:55:11 -060096struct vktexcube_vs_uniform {
97 // Must start with MVP
98 float mvp[4][4];
99 float position[12 * 3][4];
100 float attr[12 * 3][4];
101};
102
103//--------------------------------------------------------------------------------------
104// Mesh and VertexFormat Data
105//--------------------------------------------------------------------------------------
106// clang-format off
107static const float g_vertex_buffer_data[] = {
108 -1.0f,-1.0f,-1.0f, // -X side
109 -1.0f,-1.0f, 1.0f,
110 -1.0f, 1.0f, 1.0f,
111 -1.0f, 1.0f, 1.0f,
112 -1.0f, 1.0f,-1.0f,
113 -1.0f,-1.0f,-1.0f,
114
115 -1.0f,-1.0f,-1.0f, // -Z 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, // -Y 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, // +X 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, // +Z 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
151static const float g_uv_buffer_data[] = {
152 0.0f, 1.0f, // -X side
153 1.0f, 1.0f,
154 1.0f, 0.0f,
155 1.0f, 0.0f,
156 0.0f, 0.0f,
157 0.0f, 1.0f,
158
159 1.0f, 1.0f, // -Z side
160 0.0f, 0.0f,
161 0.0f, 1.0f,
162 1.0f, 1.0f,
163 1.0f, 0.0f,
164 0.0f, 0.0f,
165
166 1.0f, 0.0f, // -Y side
167 1.0f, 1.0f,
168 0.0f, 1.0f,
169 1.0f, 0.0f,
170 0.0f, 1.0f,
171 0.0f, 0.0f,
172
173 1.0f, 0.0f, // +Y side
174 0.0f, 0.0f,
175 0.0f, 1.0f,
176 1.0f, 0.0f,
177 0.0f, 1.0f,
178 1.0f, 1.0f,
179
180 1.0f, 0.0f, // +X side
181 0.0f, 0.0f,
182 0.0f, 1.0f,
183 0.0f, 1.0f,
184 1.0f, 1.0f,
185 1.0f, 0.0f,
186
187 0.0f, 0.0f, // +Z side
188 0.0f, 1.0f,
189 1.0f, 0.0f,
190 0.0f, 1.0f,
191 1.0f, 1.0f,
192 1.0f, 0.0f,
193};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600194// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600195
Jeremy Hayes9d304782016-10-09 11:48:12 -0600196typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600197 vk::Image image;
198 vk::CommandBuffer cmd;
199 vk::CommandBuffer graphics_to_present_cmd;
200 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600201 vk::Buffer uniform_buffer;
202 vk::DeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700203 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600204 vk::Framebuffer framebuffer;
205 vk::DescriptorSet descriptor_set;
206} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600207
Joey Bzdekbaf66472017-06-07 09:37:37 -0600208struct Demo {
209 Demo();
210 void build_image_ownership_cmd(uint32_t const &);
211 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
212 void cleanup();
213 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600214 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600215 void draw();
216 void draw_build_cmd(vk::CommandBuffer);
217 void flush_init_cmd();
218 void init(int, char **);
219 void init_connection();
220 void init_vk();
221 void init_vk_swapchain();
222 void prepare();
223 void prepare_buffers();
224 void prepare_cube_data_buffers();
225 void prepare_depth();
226 void prepare_descriptor_layout();
227 void prepare_descriptor_pool();
228 void prepare_descriptor_set();
229 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100230 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
231 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600232 vk::ShaderModule prepare_fs();
233 void prepare_pipeline();
234 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600235 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600236 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100238
Joey Bzdekbaf66472017-06-07 09:37:37 -0600239 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600240 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600241 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
242 vk::PipelineStageFlags, vk::PipelineStageFlags);
243 void update_data_buffer();
244 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
245 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
246
247#if defined(VK_USE_PLATFORM_WIN32_KHR)
248 void run();
249 void create_window();
250#elif defined(VK_USE_PLATFORM_XLIB_KHR)
251 void create_xlib_window();
252 void handle_xlib_event(const XEvent *);
253 void run_xlib();
254#elif defined(VK_USE_PLATFORM_XCB_KHR)
255 void handle_xcb_event(const xcb_generic_event_t *);
256 void run_xcb();
257 void create_xcb_window();
258#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
259 void run();
260 void create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200261#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
262 void handle_directfb_event(const DFBInputEvent *);
263 void run_directfb();
264 void create_directfb_window();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400265#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600266 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600267#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
268 vk::Result create_display_surface();
269 void run_display();
270#endif
271
272#if defined(VK_USE_PLATFORM_WIN32_KHR)
273 HINSTANCE connection; // hInstance - Windows Instance
274 HWND window; // hWnd - window handle
275 POINT minsize; // minimum window size
276 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
277#elif defined(VK_USE_PLATFORM_XLIB_KHR)
278 Window xlib_window;
279 Atom xlib_wm_delete_window;
280 Display *display;
281#elif defined(VK_USE_PLATFORM_XCB_KHR)
282 xcb_window_t xcb_window;
283 xcb_screen_t *screen;
284 xcb_connection_t *connection;
285 xcb_intern_atom_reply_t *atom_wm_delete_window;
286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
287 wl_display *display;
288 wl_registry *registry;
289 wl_compositor *compositor;
290 wl_surface *window;
Manuel Stoecklac939332019-06-26 20:55:53 -0400291 xdg_wm_base *wm_base;
292 zxdg_decoration_manager_v1 *xdg_decoration_mgr;
293 zxdg_toplevel_decoration_v1 *toplevel_decoration;
294 xdg_surface *window_surface;
295 bool xdg_surface_has_been_configured;
296 xdg_toplevel *window_toplevel;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600297 wl_seat *seat;
298 wl_pointer *pointer;
299 wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200300#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
301 IDirectFB *dfb;
302 IDirectFBSurface *window;
303 IDirectFBEventBuffer *event_buffer;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400304#elif defined(VK_USE_PLATFORM_METAL_EXT)
305 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600306#endif
307
308 vk::SurfaceKHR surface;
309 bool prepared;
310 bool use_staging_buffer;
311 bool use_xlib;
312 bool separate_present_queue;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000313 int32_t gpu_number;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600314
315 vk::Instance inst;
316 vk::PhysicalDevice gpu;
317 vk::Device device;
318 vk::Queue graphics_queue;
319 vk::Queue present_queue;
320 uint32_t graphics_queue_family_index;
321 uint32_t present_queue_family_index;
322 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
323 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
324 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
325 vk::PhysicalDeviceProperties gpu_props;
326 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
327 vk::PhysicalDeviceMemoryProperties memory_properties;
328
329 uint32_t enabled_extension_count;
330 uint32_t enabled_layer_count;
331 char const *extension_names[64];
332 char const *enabled_layers[64];
333
Jeremy Hayescf9d49e2021-08-30 18:04:09 -0600334 int32_t width;
335 int32_t height;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600336 vk::Format format;
337 vk::ColorSpaceKHR color_space;
338
339 uint32_t swapchainImageCount;
340 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600341 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600342 vk::PresentModeKHR presentMode;
343 vk::Fence fences[FRAME_LAG];
344 uint32_t frame_index;
345
346 vk::CommandPool cmd_pool;
347 vk::CommandPool present_cmd_pool;
348
349 struct {
350 vk::Format format;
351 vk::Image image;
352 vk::MemoryAllocateInfo mem_alloc;
353 vk::DeviceMemory mem;
354 vk::ImageView view;
355 } depth;
356
357 static int32_t const texture_count = 1;
358 texture_object textures[texture_count];
359 texture_object staging_texture;
360
361 struct {
362 vk::Buffer buf;
363 vk::MemoryAllocateInfo mem_alloc;
364 vk::DeviceMemory mem;
365 vk::DescriptorBufferInfo buffer_info;
366 } uniform_data;
367
368 vk::CommandBuffer cmd; // Buffer for initialization commands
369 vk::PipelineLayout pipeline_layout;
370 vk::DescriptorSetLayout desc_layout;
371 vk::PipelineCache pipelineCache;
372 vk::RenderPass render_pass;
373 vk::Pipeline pipeline;
374
375 mat4x4 projection_matrix;
376 mat4x4 view_matrix;
377 mat4x4 model_matrix;
378
379 float spin_angle;
380 float spin_increment;
381 bool pause;
382
383 vk::ShaderModule vert_shader_module;
384 vk::ShaderModule frag_shader_module;
385
386 vk::DescriptorPool desc_pool;
387 vk::DescriptorSet desc_set;
388
389 std::unique_ptr<vk::Framebuffer[]> framebuffers;
390
391 bool quit;
392 uint32_t curFrame;
393 uint32_t frameCount;
394 bool validate;
395 bool use_break;
396 bool suppress_popups;
Mark Young43c08f82021-11-30 16:38:25 -0700397 bool force_errors;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600398
399 uint32_t current_buffer;
400 uint32_t queue_family_count;
401};
402
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600403#ifdef _WIN32
404// MS-Windows event handling function:
405LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
406#endif
407
Karl Schultz23cc2182016-11-23 17:15:17 -0700408#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdek15eb0702017-06-07 09:40:36 -0600409static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
410 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700411
Joey Bzdek15eb0702017-06-07 09:40:36 -0600412static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700413
Joey Bzdek15eb0702017-06-07 09:40:36 -0600414static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
415
416static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
417 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600418 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600419 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoecklac939332019-06-26 20:55:53 -0400420 xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421 }
422}
423
424static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
425
426static const struct wl_pointer_listener pointer_listener = {
427 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
428};
429
430static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
431
432static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
433 struct wl_array *keys) {}
434
435static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
436
437static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
438 uint32_t state) {
439 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
440 Demo *demo = (Demo *)data;
441 switch (key) {
442 case KEY_ESC: // Escape
443 demo->quit = true;
444 break;
445 case KEY_LEFT: // left arrow key
446 demo->spin_angle -= demo->spin_increment;
447 break;
448 case KEY_RIGHT: // right arrow key
449 demo->spin_angle += demo->spin_increment;
450 break;
451 case KEY_SPACE: // space bar
452 demo->pause = !demo->pause;
453 break;
454 }
455}
456
457static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
458 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
459
460static const struct wl_keyboard_listener keyboard_listener = {
461 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
462};
463
464static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
465 // Subscribe to pointer events
466 Demo *demo = (Demo *)data;
467 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
468 demo->pointer = wl_seat_get_pointer(seat);
469 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
470 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
471 wl_pointer_destroy(demo->pointer);
472 demo->pointer = NULL;
473 }
474 // Subscribe to keyboard events
475 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
476 demo->keyboard = wl_seat_get_keyboard(seat);
477 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
478 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
479 wl_keyboard_destroy(demo->keyboard);
480 demo->keyboard = NULL;
481 }
482}
483
484static const wl_seat_listener seat_listener = {
485 seat_handle_capabilities,
486};
487
Manuel Stoecklac939332019-06-26 20:55:53 -0400488static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
489
490static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
491
Joey Bzdek15eb0702017-06-07 09:40:36 -0600492static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
493 Demo *demo = (Demo *)data;
494 // pickup wayland objects when they appear
Manuel Stoecklac939332019-06-26 20:55:53 -0400495 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600496 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Manuel Stoecklac939332019-06-26 20:55:53 -0400497 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
498 demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
499 xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
500 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600501 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
502 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoecklac939332019-06-26 20:55:53 -0400503 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
504 demo->xdg_decoration_mgr =
505 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600506 }
507}
508
509static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
510
511static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700512#endif
513
Joey Bzdekbaf66472017-06-07 09:37:37 -0600514Demo::Demo()
515 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600516#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 connection{nullptr},
518 window{nullptr},
519 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600520#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700521
Tony Barbour78d6b572016-11-14 14:46:33 -0700522#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600523 xlib_window{0},
524 xlib_wm_delete_window{0},
525 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700526#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600527 xcb_window{0},
528 screen{nullptr},
529 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700530#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600531 display{nullptr},
532 registry{nullptr},
533 compositor{nullptr},
534 window{nullptr},
Manuel Stoecklac939332019-06-26 20:55:53 -0400535 wm_base{nullptr},
536 xdg_decoration_mgr{nullptr},
537 toplevel_decoration{nullptr},
538 window_surface{nullptr},
539 xdg_surface_has_been_configured{false},
540 window_toplevel{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600541 seat{nullptr},
542 pointer{nullptr},
543 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200544#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
545 dfb{nullptr},
546 window{nullptr},
547 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700548#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600549 prepared{false},
550 use_staging_buffer{false},
551 use_xlib{false},
552 graphics_queue_family_index{0},
553 present_queue_family_index{0},
554 enabled_extension_count{0},
555 enabled_layer_count{0},
556 width{0},
557 height{0},
558 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000559 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600560 frame_index{0},
561 spin_angle{0.0f},
562 spin_increment{0.0f},
563 pause{false},
564 quit{false},
565 curFrame{0},
566 frameCount{0},
567 validate{false},
568 use_break{false},
569 suppress_popups{false},
Mark Young43c08f82021-11-30 16:38:25 -0700570 force_errors{false},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600571 current_buffer{0},
572 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600573#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700574 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600575#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700576 memset(projection_matrix, 0, sizeof(projection_matrix));
577 memset(view_matrix, 0, sizeof(view_matrix));
578 memset(model_matrix, 0, sizeof(model_matrix));
579}
580
581void Demo::build_image_ownership_cmd(uint32_t const &i) {
582 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
583 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
584 VERIFY(result == vk::Result::eSuccess);
585
586 auto const image_ownership_barrier =
587 vk::ImageMemoryBarrier()
588 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600589 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700590 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
591 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
592 .setSrcQueueFamilyIndex(graphics_queue_family_index)
593 .setDstQueueFamilyIndex(present_queue_family_index)
594 .setImage(swapchain_image_resources[i].image)
595 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
596
597 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600598 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
599 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700600
601 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
602 VERIFY(result == vk::Result::eSuccess);
603}
604
605vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
606 vk::LayerProperties *layers) {
607 for (uint32_t i = 0; i < check_count; i++) {
608 vk::Bool32 found = VK_FALSE;
609 for (uint32_t j = 0; j < layer_count; j++) {
610 if (!strcmp(check_names[i], layers[j].layerName)) {
611 found = VK_TRUE;
612 break;
613 }
614 }
615 if (!found) {
616 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
617 return 0;
618 }
619 }
620 return VK_TRUE;
621}
622
623void Demo::cleanup() {
624 prepared = false;
625 device.waitIdle();
626
627 // Wait for fences from present operations
628 for (uint32_t i = 0; i < FRAME_LAG; i++) {
629 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
630 device.destroyFence(fences[i], nullptr);
631 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
632 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
633 if (separate_present_queue) {
634 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
635 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600636 }
637
Dave Houlton5fa47912018-02-16 11:02:26 -0700638 for (uint32_t i = 0; i < swapchainImageCount; i++) {
639 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
640 }
641 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600642
Dave Houlton5fa47912018-02-16 11:02:26 -0700643 device.destroyPipeline(pipeline, nullptr);
644 device.destroyPipelineCache(pipelineCache, nullptr);
645 device.destroyRenderPass(render_pass, nullptr);
646 device.destroyPipelineLayout(pipeline_layout, nullptr);
647 device.destroyDescriptorSetLayout(desc_layout, nullptr);
648
649 for (uint32_t i = 0; i < texture_count; i++) {
650 device.destroyImageView(textures[i].view, nullptr);
651 device.destroyImage(textures[i].image, nullptr);
652 device.freeMemory(textures[i].mem, nullptr);
653 device.destroySampler(textures[i].sampler, nullptr);
654 }
655 device.destroySwapchainKHR(swapchain, nullptr);
656
657 device.destroyImageView(depth.view, nullptr);
658 device.destroyImage(depth.image, nullptr);
659 device.freeMemory(depth.mem, nullptr);
660
661 for (uint32_t i = 0; i < swapchainImageCount; i++) {
662 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700663 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700664 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700665 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700666 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
667 }
668
669 device.destroyCommandPool(cmd_pool, nullptr);
670
671 if (separate_present_queue) {
672 device.destroyCommandPool(present_cmd_pool, nullptr);
673 }
674 device.waitIdle();
675 device.destroy(nullptr);
676 inst.destroySurfaceKHR(surface, nullptr);
677
678#if defined(VK_USE_PLATFORM_XLIB_KHR)
679 XDestroyWindow(display, xlib_window);
680 XCloseDisplay(display);
681#elif defined(VK_USE_PLATFORM_XCB_KHR)
682 xcb_destroy_window(connection, xcb_window);
683 xcb_disconnect(connection);
684 free(atom_wm_delete_window);
685#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
686 wl_keyboard_destroy(keyboard);
687 wl_pointer_destroy(pointer);
688 wl_seat_destroy(seat);
Manuel Stoecklac939332019-06-26 20:55:53 -0400689 xdg_toplevel_destroy(window_toplevel);
690 xdg_surface_destroy(window_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700691 wl_surface_destroy(window);
Manuel Stoecklac939332019-06-26 20:55:53 -0400692 xdg_wm_base_destroy(wm_base);
693 if (xdg_decoration_mgr) {
694 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
695 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
696 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700697 wl_compositor_destroy(compositor);
698 wl_registry_destroy(registry);
699 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200700#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
701 event_buffer->Release(event_buffer);
702 window->Release(window);
703 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700704#endif
705
706 inst.destroy(nullptr);
707}
708
709void Demo::create_device() {
710 float const priorities[1] = {0.0};
711
712 vk::DeviceQueueCreateInfo queues[2];
713 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
714 queues[0].setQueueCount(1);
715 queues[0].setPQueuePriorities(priorities);
716
717 auto deviceInfo = vk::DeviceCreateInfo()
718 .setQueueCreateInfoCount(1)
719 .setPQueueCreateInfos(queues)
720 .setEnabledLayerCount(0)
721 .setPpEnabledLayerNames(nullptr)
722 .setEnabledExtensionCount(enabled_extension_count)
723 .setPpEnabledExtensionNames((const char *const *)extension_names)
724 .setPEnabledFeatures(nullptr);
725
726 if (separate_present_queue) {
727 queues[1].setQueueFamilyIndex(present_queue_family_index);
728 queues[1].setQueueCount(1);
729 queues[1].setPQueuePriorities(priorities);
730 deviceInfo.setQueueCreateInfoCount(2);
731 }
732
733 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
734 VERIFY(result == vk::Result::eSuccess);
735}
736
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600737void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700738 // clean up staging resources
739 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600740 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
741 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700742}
743
744void Demo::draw() {
745 // Ensure no more than FRAME_LAG renderings are outstanding
746 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700747 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700748
749 vk::Result result;
750 do {
751 result =
752 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
753 if (result == vk::Result::eErrorOutOfDateKHR) {
754 // demo->swapchain is out of date (e.g. the window was resized) and
755 // must be recreated:
756 resize();
757 } else if (result == vk::Result::eSuboptimalKHR) {
758 // swapchain is not as optimal as it could be, but the platform's
759 // presentation engine will still present the image correctly.
760 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600761 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
762 inst.destroySurfaceKHR(surface, nullptr);
763 create_surface();
764 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700765 } else {
766 VERIFY(result == vk::Result::eSuccess);
767 }
768 } while (result != vk::Result::eSuccess);
769
770 update_data_buffer();
771
772 // Wait for the image acquired semaphore to be signaled to ensure
773 // that the image won't be rendered to until the presentation
774 // engine has fully released ownership to the application, and it is
775 // okay to render to the image.
776 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
777 auto const submit_info = vk::SubmitInfo()
778 .setPWaitDstStageMask(&pipe_stage_flags)
779 .setWaitSemaphoreCount(1)
780 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
781 .setCommandBufferCount(1)
782 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
783 .setSignalSemaphoreCount(1)
784 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
785
786 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
787 VERIFY(result == vk::Result::eSuccess);
788
789 if (separate_present_queue) {
790 // If we are using separate queues, change image ownership to the
791 // present queue before presenting, waiting for the draw complete
792 // semaphore and signalling the ownership released semaphore when
793 // finished
794 auto const present_submit_info = vk::SubmitInfo()
795 .setPWaitDstStageMask(&pipe_stage_flags)
796 .setWaitSemaphoreCount(1)
797 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
798 .setCommandBufferCount(1)
799 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
800 .setSignalSemaphoreCount(1)
801 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
802
803 result = present_queue.submit(1, &present_submit_info, vk::Fence());
804 VERIFY(result == vk::Result::eSuccess);
805 }
806
807 // If we are using separate queues we have to wait for image ownership,
808 // otherwise wait for draw complete
809 auto const presentInfo = vk::PresentInfoKHR()
810 .setWaitSemaphoreCount(1)
811 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
812 : &draw_complete_semaphores[frame_index])
813 .setSwapchainCount(1)
814 .setPSwapchains(&swapchain)
815 .setPImageIndices(&current_buffer);
816
817 result = present_queue.presentKHR(&presentInfo);
818 frame_index += 1;
819 frame_index %= FRAME_LAG;
820 if (result == vk::Result::eErrorOutOfDateKHR) {
821 // swapchain is out of date (e.g. the window was resized) and
822 // must be recreated:
823 resize();
824 } else if (result == vk::Result::eSuboptimalKHR) {
Tony-LunarGa8e96342021-06-04 15:12:55 -0600825 // SUBOPTIMAL could be due to resize
826 vk::SurfaceCapabilitiesKHR surfCapabilities;
Tony-LunarGbbdf5842021-06-11 12:00:30 -0600827 result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
Tony-LunarGa8e96342021-06-04 15:12:55 -0600828 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayescf9d49e2021-08-30 18:04:09 -0600829 if (surfCapabilities.currentExtent.width != static_cast<uint32_t>(width) || surfCapabilities.currentExtent.height != static_cast<uint32_t>(height)) {
Tony-LunarGa8e96342021-06-04 15:12:55 -0600830 resize();
831 }
Tony-LunarG6cebf142019-09-11 14:32:23 -0600832 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
833 inst.destroySurfaceKHR(surface, nullptr);
834 create_surface();
835 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700836 } else {
837 VERIFY(result == vk::Result::eSuccess);
838 }
839}
840
841void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
842 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
843
844 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
845 vk::ClearDepthStencilValue(1.0f, 0u)};
846
847 auto const passInfo = vk::RenderPassBeginInfo()
848 .setRenderPass(render_pass)
849 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
850 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
851 .setClearValueCount(2)
852 .setPClearValues(clearValues);
853
854 auto result = commandBuffer.begin(&commandInfo);
855 VERIFY(result == vk::Result::eSuccess);
856
857 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
858 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
859 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
860 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700861 float viewport_dimension;
862 float viewport_x = 0.0f;
863 float viewport_y = 0.0f;
864 if (width < height) {
865 viewport_dimension = (float)width;
866 viewport_y = (height - width) / 2.0f;
867 } else {
868 viewport_dimension = (float)height;
869 viewport_x = (width - height) / 2.0f;
870 }
871 auto const viewport = vk::Viewport()
872 .setX(viewport_x)
873 .setY(viewport_y)
874 .setWidth((float)viewport_dimension)
875 .setHeight((float)viewport_dimension)
876 .setMinDepth((float)0.0f)
877 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700878 commandBuffer.setViewport(0, 1, &viewport);
879
880 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
881 commandBuffer.setScissor(0, 1, &scissor);
882 commandBuffer.draw(12 * 3, 1, 0, 0);
883 // Note that ending the renderpass changes the image's layout from
884 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
885 commandBuffer.endRenderPass();
886
887 if (separate_present_queue) {
888 // We have to transfer ownership from the graphics queue family to
889 // the
890 // present queue family to be able to present. Note that we don't
891 // have
892 // to transfer from present queue family back to graphics queue
893 // family at
894 // the start of the next frame because we don't care about the
895 // image's
896 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600897 auto const image_ownership_barrier =
898 vk::ImageMemoryBarrier()
899 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600900 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600901 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
902 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
903 .setSrcQueueFamilyIndex(graphics_queue_family_index)
904 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700905 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700906 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600907
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600908 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700909 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600910 }
911
Dave Houlton5fa47912018-02-16 11:02:26 -0700912 result = commandBuffer.end();
913 VERIFY(result == vk::Result::eSuccess);
914}
915
916void Demo::flush_init_cmd() {
917 // TODO: hmm.
918 // This function could get called twice if the texture uses a staging
919 // buffer
920 // In that case the second call should be ignored
921 if (!cmd) {
922 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600923 }
924
Dave Houlton5fa47912018-02-16 11:02:26 -0700925 auto result = cmd.end();
926 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600927
Mark Young43c08f82021-11-30 16:38:25 -0700928 auto fenceInfo = vk::FenceCreateInfo();
929 if (force_errors) {
930 // Remove sType to intentionally force validation layer errors.
931 fenceInfo.sType = vk::StructureType::eRenderPassBeginInfo;
932 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700933 vk::Fence fence;
934 result = device.createFence(&fenceInfo, nullptr, &fence);
935 VERIFY(result == vk::Result::eSuccess);
936
937 vk::CommandBuffer const commandBuffers[] = {cmd};
938 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
939
940 result = graphics_queue.submit(1, &submitInfo, fence);
941 VERIFY(result == vk::Result::eSuccess);
942
943 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
944 VERIFY(result == vk::Result::eSuccess);
945
946 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
947 device.destroyFence(fence, nullptr);
948
949 cmd = vk::CommandBuffer();
950}
951
952void Demo::init(int argc, char **argv) {
953 vec3 eye = {0.0f, 3.0f, 5.0f};
954 vec3 origin = {0, 0, 0};
955 vec3 up = {0.0f, 1.0f, 0.0};
956
957 presentMode = vk::PresentModeKHR::eFifo;
958 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100959 width = 500;
960 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700961 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000962 /* Autodetect suitable / best GPU by default */
963 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600964
Dave Houlton5fa47912018-02-16 11:02:26 -0700965 for (int i = 1; i < argc; i++) {
966 if (strcmp(argv[i], "--use_staging") == 0) {
967 use_staging_buffer = true;
968 continue;
969 }
970 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
971 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
972 i++;
973 continue;
974 }
975 if (strcmp(argv[i], "--break") == 0) {
976 use_break = true;
977 continue;
978 }
979 if (strcmp(argv[i], "--validate") == 0) {
980 validate = true;
981 continue;
982 }
983 if (strcmp(argv[i], "--xlib") == 0) {
984 fprintf(stderr, "--xlib is deprecated and no longer does anything");
985 continue;
986 }
987 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
988 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
989 i++;
990 continue;
991 }
Jeremy Hayescf9d49e2021-08-30 18:04:09 -0600992 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNi32, &width) == 1 && width > 0) {
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100993 i++;
994 continue;
995 }
Jeremy Hayescf9d49e2021-08-30 18:04:09 -0600996 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNi32, &height) == 1 && height > 0) {
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100997 i++;
998 continue;
999 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001000 if (strcmp(argv[i], "--suppress_popups") == 0) {
1001 suppress_popups = true;
1002 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001003 }
Tony-LunarG50e737c2020-07-16 14:26:03 -06001004 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
1005 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +00001006 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -06001007 i++;
1008 continue;
1009 }
Mark Young43c08f82021-11-30 16:38:25 -07001010 if (strcmp(argv[i], "--force_errors") == 0) {
1011 force_errors = true;
1012 continue;
1013 }
Tony-LunarGd74734f2019-06-04 14:11:43 -06001014 std::stringstream usage;
1015 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
1016 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -06001017 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06001018 << "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01001019 << "\t[--width <width>] [--height <height>]\n"
Mark Young43c08f82021-11-30 16:38:25 -07001020 << "\t[--force_errors]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06001021 << "\t<present_mode_enum>\n"
1022 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
1023 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
1024 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +00001025 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -06001026
1027#if defined(_WIN32)
1028 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1029#else
1030 std::cerr << usage.str();
1031 std::cerr.flush();
1032#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001034 }
1035
Dave Houlton5fa47912018-02-16 11:02:26 -07001036 if (!use_xlib) {
1037 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001038 }
1039
Dave Houlton5fa47912018-02-16 11:02:26 -07001040 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001041
Dave Houlton5fa47912018-02-16 11:02:26 -07001042 spin_angle = 4.0f;
1043 spin_increment = 0.2f;
1044 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001045
Dave Houlton5fa47912018-02-16 11:02:26 -07001046 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1047 mat4x4_look_at(view_matrix, eye, origin, up);
1048 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001049
Dave Houlton5fa47912018-02-16 11:02:26 -07001050 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1051}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001052
Dave Houlton5fa47912018-02-16 11:02:26 -07001053void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001054#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001055 const xcb_setup_t *setup;
1056 xcb_screen_iterator_t iter;
1057 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001058
Dave Houlton5fa47912018-02-16 11:02:26 -07001059 const char *display_envar = getenv("DISPLAY");
1060 if (display_envar == nullptr || display_envar[0] == '\0') {
1061 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1062 fflush(stdout);
1063 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001064 }
1065
Dave Houlton5fa47912018-02-16 11:02:26 -07001066 connection = xcb_connect(nullptr, &scr);
1067 if (xcb_connection_has_error(connection) > 0) {
1068 printf(
1069 "Cannot find a compatible Vulkan installable client driver "
1070 "(ICD).\nExiting ...\n");
1071 fflush(stdout);
1072 exit(1);
1073 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001074
Dave Houlton5fa47912018-02-16 11:02:26 -07001075 setup = xcb_get_setup(connection);
1076 iter = xcb_setup_roots_iterator(setup);
1077 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001078
Dave Houlton5fa47912018-02-16 11:02:26 -07001079 screen = iter.data;
1080#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1081 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001082
Dave Houlton5fa47912018-02-16 11:02:26 -07001083 if (display == nullptr) {
1084 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1085 fflush(stdout);
1086 exit(1);
1087 }
1088
1089 registry = wl_display_get_registry(display);
1090 wl_registry_add_listener(registry, &registry_listener, this);
1091 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001092#endif
1093}
Tony-LunarG27c21242021-03-11 16:28:19 -07001094#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1095int find_display_gpu(int gpu_number, uint32_t gpu_count, std::unique_ptr<vk::PhysicalDevice[]> &physical_devices) {
1096 uint32_t display_count = 0;
1097 vk::Result result;
1098 int gpu_return = gpu_number;
1099 if (gpu_number >= 0) {
1100 result = physical_devices[gpu_number].getDisplayPropertiesKHR(&display_count, nullptr);
1101 VERIFY(result == vk::Result::eSuccess);
1102 } else {
1103 for (uint32_t i = 0; i < gpu_count; i++) {
1104 result = physical_devices[i].getDisplayPropertiesKHR(&display_count, nullptr);
1105 VERIFY(result == vk::Result::eSuccess);
1106 if (display_count) {
1107 gpu_return = i;
1108 break;
1109 }
1110 }
1111 }
1112 if (display_count > 0)
1113 return gpu_return;
1114 else
1115 return -1;
1116}
1117#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001118void Demo::init_vk() {
1119 uint32_t instance_extension_count = 0;
1120 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001121 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001122 enabled_extension_count = 0;
1123 enabled_layer_count = 0;
1124
Dave Houlton5fa47912018-02-16 11:02:26 -07001125 // Look for validation layers
1126 vk::Bool32 validation_found = VK_FALSE;
1127 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001128 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001129 VERIFY(result == vk::Result::eSuccess);
1130
Dave Houlton5fa47912018-02-16 11:02:26 -07001131 if (instance_layer_count > 0) {
1132 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1133 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001134 VERIFY(result == vk::Result::eSuccess);
1135
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001136 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001137 instance_layer_count, instance_layers.get());
1138 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001139 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1140 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001141 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001142 }
1143
Dave Houlton5fa47912018-02-16 11:02:26 -07001144 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001145 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001146 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1147 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001148 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001149 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001150 }
1151
Dave Houlton5fa47912018-02-16 11:02:26 -07001152 /* Look for instance extensions */
1153 vk::Bool32 surfaceExtFound = VK_FALSE;
1154 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1155 memset(extension_names, 0, sizeof(extension_names));
1156
Mike Schuchardt7510c832018-10-29 13:23:08 -07001157 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1158 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001159 VERIFY(result == vk::Result::eSuccess);
1160
1161 if (instance_extension_count > 0) {
1162 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1163 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1164 VERIFY(result == vk::Result::eSuccess);
1165
1166 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001167 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1168 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1169 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001170 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1171 surfaceExtFound = 1;
1172 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1173 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001174#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001175 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1176 platformSurfaceExtFound = 1;
1177 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1178 }
1179#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1180 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1181 platformSurfaceExtFound = 1;
1182 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1183 }
1184#elif defined(VK_USE_PLATFORM_XCB_KHR)
1185 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1186 platformSurfaceExtFound = 1;
1187 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1188 }
Tony Barbour153cb062016-12-07 13:43:36 -07001189#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001190 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1191 platformSurfaceExtFound = 1;
1192 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1193 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001194#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1195 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1196 platformSurfaceExtFound = 1;
1197 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1198 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001199#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1200 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1201 platformSurfaceExtFound = 1;
1202 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1203 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001204#elif defined(VK_USE_PLATFORM_METAL_EXT)
1205 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001206 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001207 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001208 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001209#endif
1210 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001211 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001212 }
1213
1214 if (!surfaceExtFound) {
1215 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1216 " extension.\n\n"
1217 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1218 "Please look at the Getting Started guide for additional information.\n",
1219 "vkCreateInstance Failure");
1220 }
1221
1222 if (!platformSurfaceExtFound) {
1223#if defined(VK_USE_PLATFORM_WIN32_KHR)
1224 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1225 " extension.\n\n"
1226 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1227 "Please look at the Getting Started guide for additional information.\n",
1228 "vkCreateInstance Failure");
1229#elif defined(VK_USE_PLATFORM_XCB_KHR)
1230 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1231 " extension.\n\n"
1232 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1233 "Please look at the Getting Started guide for additional information.\n",
1234 "vkCreateInstance Failure");
1235#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1236 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1237 " extension.\n\n"
1238 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1239 "Please look at the Getting Started guide for additional information.\n",
1240 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001241#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001242 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1243 " extension.\n\n"
1244 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1245 "Please look at the Getting Started guide for additional information.\n",
1246 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001247#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1248 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1249 " extension.\n\n"
1250 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1251 "Please look at the Getting Started guide for additional information.\n",
1252 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001253#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001254 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1255 " extension.\n\n"
1256 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1257 "Please look at the Getting Started guide for additional information.\n",
1258 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001259#elif defined(VK_USE_PLATFORM_METAL_EXT)
1260 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001261 " extension.\n\nDo you have a compatible "
1262 "Vulkan installable client driver (ICD) installed?\nPlease "
1263 "look at the Getting Started guide for additional "
1264 "information.\n",
1265 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001266#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001267 }
1268 auto const app = vk::ApplicationInfo()
1269 .setPApplicationName(APP_SHORT_NAME)
1270 .setApplicationVersion(0)
1271 .setPEngineName(APP_SHORT_NAME)
1272 .setEngineVersion(0)
1273 .setApiVersion(VK_API_VERSION_1_0);
1274 auto const inst_info = vk::InstanceCreateInfo()
1275 .setPApplicationInfo(&app)
1276 .setEnabledLayerCount(enabled_layer_count)
1277 .setPpEnabledLayerNames(instance_validation_layers)
1278 .setEnabledExtensionCount(enabled_extension_count)
1279 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001280
Dave Houlton5fa47912018-02-16 11:02:26 -07001281 result = vk::createInstance(&inst_info, nullptr, &inst);
1282 if (result == vk::Result::eErrorIncompatibleDriver) {
1283 ERR_EXIT(
1284 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1285 "Please look at the Getting Started guide for additional information.\n",
1286 "vkCreateInstance Failure");
1287 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1288 ERR_EXIT(
1289 "Cannot find a specified extension library.\n"
1290 "Make sure your layers path is set appropriately.\n",
1291 "vkCreateInstance Failure");
1292 } else if (result != vk::Result::eSuccess) {
1293 ERR_EXIT(
1294 "vkCreateInstance failed.\n\n"
1295 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1296 "Please look at the Getting Started guide for additional information.\n",
1297 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001298 }
1299
Witold Baryluka3b988f2021-01-07 19:03:02 +00001300 /* Make initial call to query gpu_count, then second call for gpu info */
1301 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001302 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001303 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001304
Witold Baryluka3b988f2021-01-07 19:03:02 +00001305 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001306 ERR_EXIT(
1307 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1308 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1309 "Please look at the Getting Started guide for additional information.\n",
1310 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001311 }
1312
Witold Baryluka3b988f2021-01-07 19:03:02 +00001313 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1314 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1315 VERIFY(result == vk::Result::eSuccess);
1316
1317 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1318 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1319 ERR_EXIT("Specified GPU number is not present", "User Error");
1320 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001321#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1322 gpu_number = find_display_gpu(gpu_number, gpu_count, physical_devices);
1323 if (gpu_number < 0) {
1324 printf("Cannot find any display!\n");
1325 fflush(stdout);
1326 exit(1);
1327 }
1328#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00001329 /* Try to auto select most suitable device */
1330 if (gpu_number == -1) {
1331 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1332 memset(count_device_type, 0, sizeof(count_device_type));
1333
1334 for (uint32_t i = 0; i < gpu_count; i++) {
1335 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1336 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1337 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1338 }
1339
1340 const vk::PhysicalDeviceType device_type_preference[] = {
1341 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1342 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1343 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1344 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1345 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1346 search_for_device_type = device_type_preference[i];
1347 break;
1348 }
1349 }
1350
1351 for (uint32_t i = 0; i < gpu_count; i++) {
1352 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1353 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1354 gpu_number = i;
1355 break;
1356 }
1357 }
1358 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001359#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00001360 assert(gpu_number >= 0);
1361 gpu = physical_devices[gpu_number];
1362 {
1363 auto physicalDeviceProperties = gpu.getProperties();
1364 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1365 to_string(physicalDeviceProperties.deviceType).c_str());
1366 }
1367 physical_devices.reset();
1368
Dave Houlton5fa47912018-02-16 11:02:26 -07001369 /* Look for device extensions */
1370 uint32_t device_extension_count = 0;
1371 vk::Bool32 swapchainExtFound = VK_FALSE;
1372 enabled_extension_count = 0;
1373 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001374
Mike Schuchardt7510c832018-10-29 13:23:08 -07001375 result =
1376 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001377 VERIFY(result == vk::Result::eSuccess);
1378
1379 if (device_extension_count > 0) {
1380 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1381 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001382 VERIFY(result == vk::Result::eSuccess);
1383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 for (uint32_t i = 0; i < device_extension_count; i++) {
1385 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1386 swapchainExtFound = 1;
1387 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001388 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001389 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1390 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001391 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001392 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001393 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001394 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001395
Dave Houlton5fa47912018-02-16 11:02:26 -07001396 if (!swapchainExtFound) {
1397 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1398 " extension.\n\n"
1399 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1400 "Please look at the Getting Started guide for additional information.\n",
1401 "vkCreateInstance Failure");
1402 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001403
Dave Houlton5fa47912018-02-16 11:02:26 -07001404 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001405
Dave Houlton5fa47912018-02-16 11:02:26 -07001406 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001407 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001408 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001409
Dave Houlton5fa47912018-02-16 11:02:26 -07001410 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1411 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001412
Dave Houlton5fa47912018-02-16 11:02:26 -07001413 // Query fine-grained feature support for this device.
1414 // If app has specific feature requirements it should check supported
1415 // features based on this query
1416 vk::PhysicalDeviceFeatures physDevFeatures;
1417 gpu.getFeatures(&physDevFeatures);
1418}
1419
Tony-LunarG6cebf142019-09-11 14:32:23 -06001420void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001421// Create a WSI surface for the window:
1422#if defined(VK_USE_PLATFORM_WIN32_KHR)
1423 {
1424 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1425
1426 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1427 VERIFY(result == vk::Result::eSuccess);
1428 }
1429#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1430 {
1431 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1432
1433 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1434 VERIFY(result == vk::Result::eSuccess);
1435 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001436#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1437 {
1438 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1439
1440 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1441 VERIFY(result == vk::Result::eSuccess);
1442 }
1443#elif defined(VK_USE_PLATFORM_XCB_KHR)
1444 {
1445 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1446
1447 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1448 VERIFY(result == vk::Result::eSuccess);
1449 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001450#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1451 {
1452 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1453
1454 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1455 VERIFY(result == vk::Result::eSuccess);
1456 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001457#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001458 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001459 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001460
Bill Hollings0a0625a2019-07-15 17:39:18 -04001461 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001462 VERIFY(result == vk::Result::eSuccess);
1463 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001464#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1465 {
1466 auto result = create_display_surface();
1467 VERIFY(result == vk::Result::eSuccess);
1468 }
1469#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001470}
1471
1472void Demo::init_vk_swapchain() {
1473 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001474 // Iterate over each queue to learn whether it supports presenting:
1475 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1476 for (uint32_t i = 0; i < queue_family_count; i++) {
1477 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1478 }
1479
1480 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1481 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1482 for (uint32_t i = 0; i < queue_family_count; i++) {
1483 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1484 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1485 graphicsQueueFamilyIndex = i;
1486 }
1487
1488 if (supportsPresent[i] == VK_TRUE) {
1489 graphicsQueueFamilyIndex = i;
1490 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001491 break;
1492 }
1493 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001494 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001495
Dave Houlton5fa47912018-02-16 11:02:26 -07001496 if (presentQueueFamilyIndex == UINT32_MAX) {
1497 // If didn't find a queue that supports both graphics and present,
1498 // then
1499 // find a separate present queue.
1500 for (uint32_t i = 0; i < queue_family_count; ++i) {
1501 if (supportsPresent[i] == VK_TRUE) {
1502 presentQueueFamilyIndex = i;
1503 break;
1504 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001505 }
1506 }
1507
Dave Houlton5fa47912018-02-16 11:02:26 -07001508 // Generate error if could not find both a graphics and a present queue
1509 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1510 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1511 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001512
Dave Houlton5fa47912018-02-16 11:02:26 -07001513 graphics_queue_family_index = graphicsQueueFamilyIndex;
1514 present_queue_family_index = presentQueueFamilyIndex;
1515 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001516
Dave Houlton5fa47912018-02-16 11:02:26 -07001517 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001518
Dave Houlton5fa47912018-02-16 11:02:26 -07001519 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1520 if (!separate_present_queue) {
1521 present_queue = graphics_queue;
1522 } else {
1523 device.getQueue(present_queue_family_index, 0, &present_queue);
1524 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001525
Dave Houlton5fa47912018-02-16 11:02:26 -07001526 // Get the list of VkFormat's that are supported:
1527 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001528 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001529 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001530
Dave Houlton5fa47912018-02-16 11:02:26 -07001531 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1532 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1533 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001534
Dave Houlton5fa47912018-02-16 11:02:26 -07001535 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1536 // the surface has no preferred format. Otherwise, at least one
1537 // supported format will be returned.
1538 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1539 format = vk::Format::eB8G8R8A8Unorm;
1540 } else {
1541 assert(formatCount >= 1);
1542 format = surfFormats[0].format;
1543 }
1544 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001545
Dave Houlton5fa47912018-02-16 11:02:26 -07001546 quit = false;
1547 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001548
Dave Houlton5fa47912018-02-16 11:02:26 -07001549 // Create semaphores to synchronize acquiring presentable buffers before
1550 // rendering and waiting for drawing to be complete before presenting
1551 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001552
Dave Houlton5fa47912018-02-16 11:02:26 -07001553 // Create fences that we can use to throttle if we get too far
1554 // ahead of the image presents
1555 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1556 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1557 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1558 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001559
Dave Houlton5fa47912018-02-16 11:02:26 -07001560 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1561 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001562
Dave Houlton5fa47912018-02-16 11:02:26 -07001563 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1564 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001565
Dave Houlton5fa47912018-02-16 11:02:26 -07001566 if (separate_present_queue) {
1567 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001568 VERIFY(result == vk::Result::eSuccess);
1569 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001570 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001571 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001572
Dave Houlton5fa47912018-02-16 11:02:26 -07001573 // Get Memory information and properties
1574 gpu.getMemoryProperties(&memory_properties);
1575}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001576
Dave Houlton5fa47912018-02-16 11:02:26 -07001577void Demo::prepare() {
1578 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1579 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1580 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001581
Dave Houlton5fa47912018-02-16 11:02:26 -07001582 auto const cmd = vk::CommandBufferAllocateInfo()
1583 .setCommandPool(cmd_pool)
1584 .setLevel(vk::CommandBufferLevel::ePrimary)
1585 .setCommandBufferCount(1);
1586
1587 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1588 VERIFY(result == vk::Result::eSuccess);
1589
1590 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1591
1592 result = this->cmd.begin(&cmd_buf_info);
1593 VERIFY(result == vk::Result::eSuccess);
1594
1595 prepare_buffers();
1596 prepare_depth();
1597 prepare_textures();
1598 prepare_cube_data_buffers();
1599
1600 prepare_descriptor_layout();
1601 prepare_render_pass();
1602 prepare_pipeline();
1603
1604 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1605 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1606 VERIFY(result == vk::Result::eSuccess);
1607 }
1608
1609 if (separate_present_queue) {
1610 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1611
1612 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1613 VERIFY(result == vk::Result::eSuccess);
1614
1615 auto const present_cmd = vk::CommandBufferAllocateInfo()
1616 .setCommandPool(present_cmd_pool)
1617 .setLevel(vk::CommandBufferLevel::ePrimary)
1618 .setCommandBufferCount(1);
1619
1620 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1621 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1622 VERIFY(result == vk::Result::eSuccess);
1623
1624 build_image_ownership_cmd(i);
1625 }
1626 }
1627
1628 prepare_descriptor_pool();
1629 prepare_descriptor_set();
1630
1631 prepare_framebuffers();
1632
1633 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1634 current_buffer = i;
1635 draw_build_cmd(swapchain_image_resources[i].cmd);
1636 }
1637
1638 /*
1639 * Prepare functions above may generate pipeline commands
1640 * that need to be flushed before beginning the render loop.
1641 */
1642 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001643 if (staging_texture.buffer) {
1644 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001645 }
1646
1647 current_buffer = 0;
1648 prepared = true;
1649}
1650
1651void Demo::prepare_buffers() {
1652 vk::SwapchainKHR oldSwapchain = swapchain;
1653
1654 // Check the surface capabilities and formats
1655 vk::SurfaceCapabilitiesKHR surfCapabilities;
1656 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1657 VERIFY(result == vk::Result::eSuccess);
1658
1659 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001660 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001661 VERIFY(result == vk::Result::eSuccess);
1662
1663 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1664 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1665 VERIFY(result == vk::Result::eSuccess);
1666
1667 vk::Extent2D swapchainExtent;
1668 // width and height are either both -1, or both not -1.
1669 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1670 // If the surface size is undefined, the size is set to
1671 // the size of the images requested.
1672 swapchainExtent.width = width;
1673 swapchainExtent.height = height;
1674 } else {
1675 // If the surface size is defined, the swap chain size must match
1676 swapchainExtent = surfCapabilities.currentExtent;
1677 width = surfCapabilities.currentExtent.width;
1678 height = surfCapabilities.currentExtent.height;
1679 }
1680
1681 // The FIFO present mode is guaranteed by the spec to be supported
1682 // and to have no tearing. It's a great default present mode to use.
1683 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1684
1685 // There are times when you may wish to use another present mode. The
1686 // following code shows how to select them, and the comments provide some
1687 // reasons you may wish to use them.
1688 //
1689 // It should be noted that Vulkan 1.0 doesn't provide a method for
1690 // synchronizing rendering with the presentation engine's display. There
1691 // is a method provided for throttling rendering with the display, but
1692 // there are some presentation engines for which this method will not work.
1693 // If an application doesn't throttle its rendering, and if it renders much
1694 // faster than the refresh rate of the display, this can waste power on
1695 // mobile devices. That is because power is being spent rendering images
1696 // that may never be seen.
1697
1698 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1699 // about
1700 // tearing, or have some way of synchronizing their rendering with the
1701 // display.
1702 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1703 // generally render a new presentable image every refresh cycle, but are
1704 // occasionally early. In this case, the application wants the new
1705 // image
1706 // to be displayed instead of the previously-queued-for-presentation
1707 // image
1708 // that has not yet been displayed.
1709 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1710 // render a new presentable image every refresh cycle, but are
1711 // occasionally
1712 // late. In this case (perhaps because of stuttering/latency concerns),
1713 // the application wants the late image to be immediately displayed,
1714 // even
1715 // though that may mean some tearing.
1716
1717 if (presentMode != swapchainPresentMode) {
1718 for (size_t i = 0; i < presentModeCount; ++i) {
1719 if (presentModes[i] == presentMode) {
1720 swapchainPresentMode = presentMode;
1721 break;
1722 }
1723 }
1724 }
1725
1726 if (swapchainPresentMode != presentMode) {
1727 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1728 }
1729
1730 // Determine the number of VkImages to use in the swap chain.
1731 // Application desires to acquire 3 images at a time for triple
1732 // buffering
1733 uint32_t desiredNumOfSwapchainImages = 3;
1734 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1735 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1736 }
1737
1738 // If maxImageCount is 0, we can ask for as many images as we want,
1739 // otherwise
1740 // we're limited to maxImageCount
1741 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1742 // Application must settle for fewer images than desired:
1743 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1744 }
1745
1746 vk::SurfaceTransformFlagBitsKHR preTransform;
1747 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1748 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1749 } else {
1750 preTransform = surfCapabilities.currentTransform;
1751 }
1752
1753 // Find a supported composite alpha mode - one of these is guaranteed to be set
1754 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1755 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1756 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1757 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1758 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1759 vk::CompositeAlphaFlagBitsKHR::eInherit,
1760 };
1761 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1762 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1763 compositeAlpha = compositeAlphaFlags[i];
1764 break;
1765 }
1766 }
1767
1768 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1769 .setSurface(surface)
1770 .setMinImageCount(desiredNumOfSwapchainImages)
1771 .setImageFormat(format)
1772 .setImageColorSpace(color_space)
1773 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1774 .setImageArrayLayers(1)
1775 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1776 .setImageSharingMode(vk::SharingMode::eExclusive)
1777 .setQueueFamilyIndexCount(0)
1778 .setPQueueFamilyIndices(nullptr)
1779 .setPreTransform(preTransform)
1780 .setCompositeAlpha(compositeAlpha)
1781 .setPresentMode(swapchainPresentMode)
1782 .setClipped(true)
1783 .setOldSwapchain(oldSwapchain);
1784
1785 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1786 VERIFY(result == vk::Result::eSuccess);
1787
1788 // If we just re-created an existing swapchain, we should destroy the
1789 // old
1790 // swapchain at this point.
1791 // Note: destroying the swapchain also cleans up all its associated
1792 // presentable images once the platform is done with them.
1793 if (oldSwapchain) {
1794 device.destroySwapchainKHR(oldSwapchain, nullptr);
1795 }
1796
Mike Schuchardt7510c832018-10-29 13:23:08 -07001797 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001798 VERIFY(result == vk::Result::eSuccess);
1799
1800 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1801 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1802 VERIFY(result == vk::Result::eSuccess);
1803
1804 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1805
1806 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1807 auto color_image_view = vk::ImageViewCreateInfo()
1808 .setViewType(vk::ImageViewType::e2D)
1809 .setFormat(format)
1810 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1811
1812 swapchain_image_resources[i].image = swapchainImages[i];
1813
1814 color_image_view.image = swapchain_image_resources[i].image;
1815
1816 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1817 VERIFY(result == vk::Result::eSuccess);
1818 }
1819}
1820
1821void Demo::prepare_cube_data_buffers() {
1822 mat4x4 VP;
1823 mat4x4_mul(VP, projection_matrix, view_matrix);
1824
1825 mat4x4 MVP;
1826 mat4x4_mul(MVP, VP, model_matrix);
1827
1828 vktexcube_vs_uniform data;
1829 memcpy(data.mvp, MVP, sizeof(MVP));
1830 // dumpMatrix("MVP", MVP)
1831
1832 for (int32_t i = 0; i < 12 * 3; i++) {
1833 data.position[i][0] = g_vertex_buffer_data[i * 3];
1834 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1835 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1836 data.position[i][3] = 1.0f;
1837 data.attr[i][0] = g_uv_buffer_data[2 * i];
1838 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1839 data.attr[i][2] = 0;
1840 data.attr[i][3] = 0;
1841 }
1842
1843 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1844
1845 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1846 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001847 VERIFY(result == vk::Result::eSuccess);
1848
1849 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001850 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001851
Dave Houlton5fa47912018-02-16 11:02:26 -07001852 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001853
Dave Houlton5fa47912018-02-16 11:02:26 -07001854 bool const pass = memory_type_from_properties(
1855 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1856 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001857 VERIFY(pass);
1858
Dave Houlton5fa47912018-02-16 11:02:26 -07001859 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001860 VERIFY(result == vk::Result::eSuccess);
1861
Tony-LunarG37af49f2019-12-19 12:04:19 -07001862 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1863 &swapchain_image_resources[i].uniform_memory_ptr);
1864 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001865
Tony-LunarG37af49f2019-12-19 12:04:19 -07001866 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001867
1868 result =
1869 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001870 VERIFY(result == vk::Result::eSuccess);
1871 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001872}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001873
Dave Houlton5fa47912018-02-16 11:02:26 -07001874void Demo::prepare_depth() {
1875 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001876
Dave Houlton5fa47912018-02-16 11:02:26 -07001877 auto const image = vk::ImageCreateInfo()
1878 .setImageType(vk::ImageType::e2D)
1879 .setFormat(depth.format)
1880 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1881 .setMipLevels(1)
1882 .setArrayLayers(1)
1883 .setSamples(vk::SampleCountFlagBits::e1)
1884 .setTiling(vk::ImageTiling::eOptimal)
1885 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1886 .setSharingMode(vk::SharingMode::eExclusive)
1887 .setQueueFamilyIndexCount(0)
1888 .setPQueueFamilyIndices(nullptr)
1889 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001890
Dave Houlton5fa47912018-02-16 11:02:26 -07001891 auto result = device.createImage(&image, nullptr, &depth.image);
1892 VERIFY(result == vk::Result::eSuccess);
1893
1894 vk::MemoryRequirements mem_reqs;
1895 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1896
1897 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1898 depth.mem_alloc.setMemoryTypeIndex(0);
1899
1900 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1901 &depth.mem_alloc.memoryTypeIndex);
1902 VERIFY(pass);
1903
1904 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1905 VERIFY(result == vk::Result::eSuccess);
1906
1907 result = device.bindImageMemory(depth.image, depth.mem, 0);
1908 VERIFY(result == vk::Result::eSuccess);
1909
Mark Young43c08f82021-11-30 16:38:25 -07001910 auto view = vk::ImageViewCreateInfo()
Dave Houlton5fa47912018-02-16 11:02:26 -07001911 .setImage(depth.image)
1912 .setViewType(vk::ImageViewType::e2D)
1913 .setFormat(depth.format)
1914 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
Mark Young43c08f82021-11-30 16:38:25 -07001915 if (force_errors) {
1916 // Intentionally force a bad pNext value to generate a validation layer error
1917 view.pNext = &image;
1918 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001919 result = device.createImageView(&view, nullptr, &depth.view);
1920 VERIFY(result == vk::Result::eSuccess);
1921}
1922
1923void Demo::prepare_descriptor_layout() {
1924 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1925 .setBinding(0)
1926 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1927 .setDescriptorCount(1)
1928 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1929 .setPImmutableSamplers(nullptr),
1930 vk::DescriptorSetLayoutBinding()
1931 .setBinding(1)
1932 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1933 .setDescriptorCount(texture_count)
1934 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1935 .setPImmutableSamplers(nullptr)};
1936
1937 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1938
1939 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1940 VERIFY(result == vk::Result::eSuccess);
1941
1942 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1943
1944 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1945 VERIFY(result == vk::Result::eSuccess);
1946}
1947
1948void Demo::prepare_descriptor_pool() {
1949 vk::DescriptorPoolSize const poolSizes[2] = {
1950 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1951 vk::DescriptorPoolSize()
1952 .setType(vk::DescriptorType::eCombinedImageSampler)
1953 .setDescriptorCount(swapchainImageCount * texture_count)};
1954
1955 auto const descriptor_pool =
1956 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1957
1958 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1959 VERIFY(result == vk::Result::eSuccess);
1960}
1961
1962void Demo::prepare_descriptor_set() {
1963 auto const alloc_info =
1964 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1965
1966 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1967
1968 vk::DescriptorImageInfo tex_descs[texture_count];
1969 for (uint32_t i = 0; i < texture_count; i++) {
1970 tex_descs[i].setSampler(textures[i].sampler);
1971 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001972 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001973 }
1974
1975 vk::WriteDescriptorSet writes[2];
1976
1977 writes[0].setDescriptorCount(1);
1978 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1979 writes[0].setPBufferInfo(&buffer_info);
1980
1981 writes[1].setDstBinding(1);
1982 writes[1].setDescriptorCount(texture_count);
1983 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1984 writes[1].setPImageInfo(tex_descs);
1985
1986 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1987 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001988 VERIFY(result == vk::Result::eSuccess);
1989
Dave Houlton5fa47912018-02-16 11:02:26 -07001990 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1991 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1992 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1993 device.updateDescriptorSets(2, writes, 0, nullptr);
1994 }
1995}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001996
Dave Houlton5fa47912018-02-16 11:02:26 -07001997void Demo::prepare_framebuffers() {
1998 vk::ImageView attachments[2];
1999 attachments[1] = depth.view;
2000
2001 auto const fb_info = vk::FramebufferCreateInfo()
2002 .setRenderPass(render_pass)
2003 .setAttachmentCount(2)
2004 .setPAttachments(attachments)
2005 .setWidth((uint32_t)width)
2006 .setHeight((uint32_t)height)
2007 .setLayers(1);
2008
2009 for (uint32_t i = 0; i < swapchainImageCount; i++) {
2010 attachments[0] = swapchain_image_resources[i].view;
2011 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002012 VERIFY(result == vk::Result::eSuccess);
2013 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002014}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002015
Dave Houlton5fa47912018-02-16 11:02:26 -07002016vk::ShaderModule Demo::prepare_fs() {
2017 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002018#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07002019 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002020
Dave Houlton5fa47912018-02-16 11:02:26 -07002021 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002022
Dave Houlton5fa47912018-02-16 11:02:26 -07002023 return frag_shader_module;
2024}
2025
2026void Demo::prepare_pipeline() {
2027 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2028 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2029 VERIFY(result == vk::Result::eSuccess);
2030
2031 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
2032 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2033 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2034
2035 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2036
2037 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2038
2039 // TODO: Where are pViewports and pScissors set?
2040 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2041
2042 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2043 .setDepthClampEnable(VK_FALSE)
2044 .setRasterizerDiscardEnable(VK_FALSE)
2045 .setPolygonMode(vk::PolygonMode::eFill)
2046 .setCullMode(vk::CullModeFlagBits::eBack)
2047 .setFrontFace(vk::FrontFace::eCounterClockwise)
2048 .setDepthBiasEnable(VK_FALSE)
2049 .setLineWidth(1.0f);
2050
2051 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2052
2053 auto const stencilOp =
2054 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2055
2056 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2057 .setDepthTestEnable(VK_TRUE)
2058 .setDepthWriteEnable(VK_TRUE)
2059 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2060 .setDepthBoundsTestEnable(VK_FALSE)
2061 .setStencilTestEnable(VK_FALSE)
2062 .setFront(stencilOp)
2063 .setBack(stencilOp);
2064
2065 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2066 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2067 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2068
2069 auto const colorBlendInfo =
2070 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2071
2072 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2073
2074 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2075
2076 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2077 .setStageCount(2)
2078 .setPStages(shaderStageInfo)
2079 .setPVertexInputState(&vertexInputInfo)
2080 .setPInputAssemblyState(&inputAssemblyInfo)
2081 .setPViewportState(&viewportInfo)
2082 .setPRasterizationState(&rasterizationInfo)
2083 .setPMultisampleState(&multisampleInfo)
2084 .setPDepthStencilState(&depthStencilInfo)
2085 .setPColorBlendState(&colorBlendInfo)
2086 .setPDynamicState(&dynamicStateInfo)
2087 .setLayout(pipeline_layout)
2088 .setRenderPass(render_pass);
2089
2090 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2091 VERIFY(result == vk::Result::eSuccess);
2092
2093 device.destroyShaderModule(frag_shader_module, nullptr);
2094 device.destroyShaderModule(vert_shader_module, nullptr);
2095}
2096
2097void Demo::prepare_render_pass() {
2098 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2099 // because at the start of the renderpass, we don't care about their contents.
2100 // At the start of the subpass, the color attachment's layout will be transitioned
2101 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2102 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2103 // the renderpass, the color attachment's layout will be transitioned to
2104 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2105 // the renderpass, no barriers are necessary.
2106 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2107 .setFormat(format)
2108 .setSamples(vk::SampleCountFlagBits::e1)
2109 .setLoadOp(vk::AttachmentLoadOp::eClear)
2110 .setStoreOp(vk::AttachmentStoreOp::eStore)
2111 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2112 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2113 .setInitialLayout(vk::ImageLayout::eUndefined)
2114 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2115 vk::AttachmentDescription()
2116 .setFormat(depth.format)
2117 .setSamples(vk::SampleCountFlagBits::e1)
2118 .setLoadOp(vk::AttachmentLoadOp::eClear)
2119 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2120 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2121 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2122 .setInitialLayout(vk::ImageLayout::eUndefined)
2123 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2124
2125 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2126
2127 auto const depth_reference =
2128 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2129
2130 auto const subpass = vk::SubpassDescription()
2131 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2132 .setInputAttachmentCount(0)
2133 .setPInputAttachments(nullptr)
2134 .setColorAttachmentCount(1)
2135 .setPColorAttachments(&color_reference)
2136 .setPResolveAttachments(nullptr)
2137 .setPDepthStencilAttachment(&depth_reference)
2138 .setPreserveAttachmentCount(0)
2139 .setPPreserveAttachments(nullptr);
2140
Tony-LunarG495604b2019-06-13 15:32:05 -06002141 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2142 vk::SubpassDependency const dependencies[2] = {
2143 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2144 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2145 .setDstSubpass(0)
2146 .setSrcStageMask(stages)
2147 .setDstStageMask(stages)
2148 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2149 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2150 .setDependencyFlags(vk::DependencyFlags()),
2151 vk::SubpassDependency() // Image layout transition
2152 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2153 .setDstSubpass(0)
2154 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2155 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2156 .setSrcAccessMask(vk::AccessFlagBits())
2157 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2158 .setDependencyFlags(vk::DependencyFlags()),
2159 };
2160
Dave Houlton5fa47912018-02-16 11:02:26 -07002161 auto const rp_info = vk::RenderPassCreateInfo()
2162 .setAttachmentCount(2)
2163 .setPAttachments(attachments)
2164 .setSubpassCount(1)
2165 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002166 .setDependencyCount(2)
2167 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002168
2169 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2170 VERIFY(result == vk::Result::eSuccess);
2171}
2172
2173vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2174 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2175
2176 vk::ShaderModule module;
2177 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2178 VERIFY(result == vk::Result::eSuccess);
2179
2180 return module;
2181}
2182
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002183void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2184 int32_t tex_width;
2185 int32_t tex_height;
2186
2187 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2188 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2189 }
2190
2191 tex_obj->tex_width = tex_width;
2192 tex_obj->tex_height = tex_height;
2193
2194 auto const buffer_create_info = vk::BufferCreateInfo()
2195 .setSize(tex_width * tex_height * 4)
2196 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2197 .setSharingMode(vk::SharingMode::eExclusive)
2198 .setQueueFamilyIndexCount(0)
2199 .setPQueueFamilyIndices(nullptr);
2200
2201 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2202 VERIFY(result == vk::Result::eSuccess);
2203
2204 vk::MemoryRequirements mem_reqs;
2205 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2206
2207 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2208 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2209
2210 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2211 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2212 VERIFY(pass == true);
2213
2214 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2215 VERIFY(result == vk::Result::eSuccess);
2216
2217 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2218 VERIFY(result == vk::Result::eSuccess);
2219
2220 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002221 layout.rowPitch = tex_width * 4;
2222 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2223 VERIFY(data.result == vk::Result::eSuccess);
2224
2225 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2226 fprintf(stderr, "Error loading texture: %s\n", filename);
2227 }
2228
2229 device.unmapMemory(tex_obj->mem);
2230}
2231
Dave Houlton5fa47912018-02-16 11:02:26 -07002232void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2233 vk::MemoryPropertyFlags required_props) {
2234 int32_t tex_width;
2235 int32_t tex_height;
2236 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2237 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002238 }
2239
Dave Houlton5fa47912018-02-16 11:02:26 -07002240 tex_obj->tex_width = tex_width;
2241 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002242
Dave Houlton5fa47912018-02-16 11:02:26 -07002243 auto const image_create_info = vk::ImageCreateInfo()
2244 .setImageType(vk::ImageType::e2D)
2245 .setFormat(vk::Format::eR8G8B8A8Unorm)
2246 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2247 .setMipLevels(1)
2248 .setArrayLayers(1)
2249 .setSamples(vk::SampleCountFlagBits::e1)
2250 .setTiling(tiling)
2251 .setUsage(usage)
2252 .setSharingMode(vk::SharingMode::eExclusive)
2253 .setQueueFamilyIndexCount(0)
2254 .setPQueueFamilyIndices(nullptr)
2255 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002256
Dave Houlton5fa47912018-02-16 11:02:26 -07002257 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2258 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002259
Dave Houlton5fa47912018-02-16 11:02:26 -07002260 vk::MemoryRequirements mem_reqs;
2261 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002262
Dave Houlton5fa47912018-02-16 11:02:26 -07002263 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2264 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002265
Dave Houlton5fa47912018-02-16 11:02:26 -07002266 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2267 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002268
Dave Houlton5fa47912018-02-16 11:02:26 -07002269 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2270 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002271
Dave Houlton5fa47912018-02-16 11:02:26 -07002272 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2273 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002274
Dave Houlton5fa47912018-02-16 11:02:26 -07002275 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2276 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2277 vk::SubresourceLayout layout;
2278 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002279
Dave Houlton5fa47912018-02-16 11:02:26 -07002280 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002281 VERIFY(data.result == vk::Result::eSuccess);
2282
Dave Houlton5fa47912018-02-16 11:02:26 -07002283 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2284 fprintf(stderr, "Error loading texture: %s\n", filename);
2285 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002286
Dave Houlton5fa47912018-02-16 11:02:26 -07002287 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002288 }
2289
Dave Houlton5fa47912018-02-16 11:02:26 -07002290 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2291}
2292
2293void Demo::prepare_textures() {
2294 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2295 vk::FormatProperties props;
2296 gpu.getFormatProperties(tex_format, &props);
2297
2298 for (uint32_t i = 0; i < texture_count; i++) {
2299 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2300 /* Device can texture using linear textures */
2301 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2302 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2303 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2304 // shader to run until layout transition completes
2305 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2306 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2307 vk::PipelineStageFlagBits::eFragmentShader);
2308 staging_texture.image = vk::Image();
2309 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2310 /* Must use staging buffer to copy linear texture to optimized */
2311
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002312 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002313
2314 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2315 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2316 vk::MemoryPropertyFlagBits::eDeviceLocal);
2317
Dave Houlton5fa47912018-02-16 11:02:26 -07002318 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2319 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2320 vk::PipelineStageFlagBits::eTransfer);
2321
2322 auto const subresource = vk::ImageSubresourceLayers()
2323 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2324 .setMipLevel(0)
2325 .setBaseArrayLayer(0)
2326 .setLayerCount(1);
2327
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002328 auto const copy_region =
2329 vk::BufferImageCopy()
2330 .setBufferOffset(0)
2331 .setBufferRowLength(staging_texture.tex_width)
2332 .setBufferImageHeight(staging_texture.tex_height)
2333 .setImageSubresource(subresource)
2334 .setImageOffset({0, 0, 0})
2335 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002336
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002337 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002338
2339 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2340 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2341 vk::PipelineStageFlagBits::eFragmentShader);
2342 } else {
2343 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002344 }
2345
Dave Houlton5fa47912018-02-16 11:02:26 -07002346 auto const samplerInfo = vk::SamplerCreateInfo()
2347 .setMagFilter(vk::Filter::eNearest)
2348 .setMinFilter(vk::Filter::eNearest)
2349 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2350 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2351 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2352 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2353 .setMipLodBias(0.0f)
2354 .setAnisotropyEnable(VK_FALSE)
2355 .setMaxAnisotropy(1)
2356 .setCompareEnable(VK_FALSE)
2357 .setCompareOp(vk::CompareOp::eNever)
2358 .setMinLod(0.0f)
2359 .setMaxLod(0.0f)
2360 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2361 .setUnnormalizedCoordinates(VK_FALSE);
2362
2363 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2364 VERIFY(result == vk::Result::eSuccess);
2365
2366 auto const viewInfo = vk::ImageViewCreateInfo()
2367 .setImage(textures[i].image)
2368 .setViewType(vk::ImageViewType::e2D)
2369 .setFormat(tex_format)
2370 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2371
2372 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2373 VERIFY(result == vk::Result::eSuccess);
2374 }
2375}
2376
2377vk::ShaderModule Demo::prepare_vs() {
2378 const uint32_t vertShaderCode[] = {
2379#include "cube.vert.inc"
2380 };
2381
2382 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2383
2384 return vert_shader_module;
2385}
2386
2387void Demo::resize() {
2388 uint32_t i;
2389
2390 // Don't react to resize until after first initialization.
2391 if (!prepared) {
2392 return;
2393 }
2394
2395 // In order to properly resize the window, we must re-create the
2396 // swapchain
2397 // AND redo the command buffers, etc.
2398 //
2399 // First, perform part of the cleanup() function:
2400 prepared = false;
2401 auto result = device.waitIdle();
2402 VERIFY(result == vk::Result::eSuccess);
2403
2404 for (i = 0; i < swapchainImageCount; i++) {
2405 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2406 }
2407
2408 device.destroyDescriptorPool(desc_pool, nullptr);
2409
2410 device.destroyPipeline(pipeline, nullptr);
2411 device.destroyPipelineCache(pipelineCache, nullptr);
2412 device.destroyRenderPass(render_pass, nullptr);
2413 device.destroyPipelineLayout(pipeline_layout, nullptr);
2414 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2415
2416 for (i = 0; i < texture_count; i++) {
2417 device.destroyImageView(textures[i].view, nullptr);
2418 device.destroyImage(textures[i].image, nullptr);
2419 device.freeMemory(textures[i].mem, nullptr);
2420 device.destroySampler(textures[i].sampler, nullptr);
2421 }
2422
2423 device.destroyImageView(depth.view, nullptr);
2424 device.destroyImage(depth.image, nullptr);
2425 device.freeMemory(depth.mem, nullptr);
2426
2427 for (i = 0; i < swapchainImageCount; i++) {
2428 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002429 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002430 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002431 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002432 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2433 }
2434
2435 device.destroyCommandPool(cmd_pool, nullptr);
2436 if (separate_present_queue) {
2437 device.destroyCommandPool(present_cmd_pool, nullptr);
2438 }
2439
2440 // Second, re-perform the prepare() function, which will re-create the
2441 // swapchain.
2442 prepare();
2443}
2444
2445void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2446 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2447 assert(cmd);
2448
2449 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2450 vk::AccessFlags flags;
2451
2452 switch (layout) {
2453 case vk::ImageLayout::eTransferDstOptimal:
2454 // Make sure anything that was copying from this image has
2455 // completed
2456 flags = vk::AccessFlagBits::eTransferWrite;
2457 break;
2458 case vk::ImageLayout::eColorAttachmentOptimal:
2459 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2460 break;
2461 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2462 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2463 break;
2464 case vk::ImageLayout::eShaderReadOnlyOptimal:
2465 // Make sure any Copy or CPU writes to image are flushed
2466 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2467 break;
2468 case vk::ImageLayout::eTransferSrcOptimal:
2469 flags = vk::AccessFlagBits::eTransferRead;
2470 break;
2471 case vk::ImageLayout::ePresentSrcKHR:
2472 flags = vk::AccessFlagBits::eMemoryRead;
2473 break;
2474 default:
2475 break;
2476 }
2477
2478 return flags;
2479 };
2480
2481 auto const barrier = vk::ImageMemoryBarrier()
2482 .setSrcAccessMask(srcAccessMask)
2483 .setDstAccessMask(DstAccessMask(newLayout))
2484 .setOldLayout(oldLayout)
2485 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002486 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2487 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002488 .setImage(image)
2489 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2490
2491 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2492}
2493
2494void Demo::update_data_buffer() {
2495 mat4x4 VP;
2496 mat4x4_mul(VP, projection_matrix, view_matrix);
2497
2498 // Rotate around the Y axis
2499 mat4x4 Model;
2500 mat4x4_dup(Model, model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -07002501 mat4x4_rotate_Y(model_matrix, Model, (float)degreesToRadians(spin_angle));
2502 mat4x4_orthonormalize(model_matrix, model_matrix);
Dave Houlton5fa47912018-02-16 11:02:26 -07002503
2504 mat4x4 MVP;
2505 mat4x4_mul(MVP, VP, model_matrix);
2506
Tony-LunarG37af49f2019-12-19 12:04:19 -07002507 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002508}
2509
Karl Schultzb7940402018-05-29 13:09:22 -06002510/* Convert ppm image data from header file into RGBA texture image */
2511#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002512bool 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 -06002513 (void)filename;
2514 char *cPtr;
2515 cPtr = (char *)lunarg_ppm;
2516 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002517 return false;
2518 }
Karl Schultzb7940402018-05-29 13:09:22 -06002519 while (strncmp(cPtr++, "\n", 1))
2520 ;
2521 sscanf(cPtr, "%u %u", width, height);
2522 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002523 return true;
2524 }
Karl Schultzb7940402018-05-29 13:09:22 -06002525 while (strncmp(cPtr++, "\n", 1))
2526 ;
2527 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002528 return false;
2529 }
Karl Schultzb7940402018-05-29 13:09:22 -06002530 while (strncmp(cPtr++, "\n", 1))
2531 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002532 for (int y = 0; y < *height; y++) {
2533 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002534 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002535 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002536 rowPtr[3] = 255; /* Alpha of 1 */
2537 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002538 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002539 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002540 rgba_data += layout->rowPitch;
2541 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002542 return true;
2543}
2544
2545bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2546 // Search memtypes to find first index with those properties
2547 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2548 if ((typeBits & 1) == 1) {
2549 // Type is available, does it match user properties?
2550 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2551 *typeIndex = i;
2552 return true;
2553 }
2554 }
2555 typeBits >>= 1;
2556 }
2557
2558 // No memory types matched, return failure
2559 return false;
2560}
2561
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002562#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002563void Demo::run() {
2564 if (!prepared) {
2565 return;
2566 }
2567
2568 draw();
2569 curFrame++;
2570
Petr Krausd88e4e52019-01-23 18:45:04 +01002571 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002572 PostQuitMessage(validation_error);
2573 }
2574}
2575
2576void Demo::create_window() {
2577 WNDCLASSEX win_class;
2578
2579 // Initialize the window class structure:
2580 win_class.cbSize = sizeof(WNDCLASSEX);
2581 win_class.style = CS_HREDRAW | CS_VREDRAW;
2582 win_class.lpfnWndProc = WndProc;
2583 win_class.cbClsExtra = 0;
2584 win_class.cbWndExtra = 0;
2585 win_class.hInstance = connection; // hInstance
2586 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2587 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2588 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2589 win_class.lpszMenuName = nullptr;
2590 win_class.lpszClassName = name;
2591 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2592
2593 // Register window class:
2594 if (!RegisterClassEx(&win_class)) {
2595 // It didn't work, so try to give a useful error:
2596 printf("Unexpected error trying to start the application!\n");
2597 fflush(stdout);
2598 exit(1);
2599 }
2600
2601 // Create window with the registered class:
2602 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2603 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2604 window = CreateWindowEx(0,
2605 name, // class name
2606 name, // app name
2607 WS_OVERLAPPEDWINDOW | // window style
2608 WS_VISIBLE | WS_SYSMENU,
2609 100, 100, // x/y coords
2610 wr.right - wr.left, // width
2611 wr.bottom - wr.top, // height
2612 nullptr, // handle to parent
2613 nullptr, // handle to menu
2614 connection, // hInstance
2615 nullptr); // no extra parameters
2616
2617 if (!window) {
2618 // It didn't work, so try to give a useful error:
2619 printf("Cannot create a window in which to draw!\n");
2620 fflush(stdout);
2621 exit(1);
2622 }
2623
2624 // Window client area size must be at least 1 pixel high, to prevent
2625 // crash.
2626 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2627 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2628}
2629#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2630
2631void Demo::create_xlib_window() {
2632 const char *display_envar = getenv("DISPLAY");
2633 if (display_envar == nullptr || display_envar[0] == '\0') {
2634 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2635 fflush(stdout);
2636 exit(1);
2637 }
2638
2639 XInitThreads();
2640 display = XOpenDisplay(nullptr);
2641 long visualMask = VisualScreenMask;
2642 int numberOfVisuals;
2643 XVisualInfo vInfoTemplate = {};
2644 vInfoTemplate.screen = DefaultScreen(display);
2645 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2646
2647 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2648
2649 XSetWindowAttributes windowAttributes = {};
2650 windowAttributes.colormap = colormap;
2651 windowAttributes.background_pixel = 0xFFFFFFFF;
2652 windowAttributes.border_pixel = 0;
2653 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2654
2655 xlib_window =
2656 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2657 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2658
2659 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2660 XMapWindow(display, xlib_window);
2661 XFlush(display);
2662 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2663}
2664
2665void Demo::handle_xlib_event(const XEvent *event) {
2666 switch (event->type) {
2667 case ClientMessage:
2668 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2669 quit = true;
2670 }
2671 break;
2672 case KeyPress:
2673 switch (event->xkey.keycode) {
2674 case 0x9: // Escape
2675 quit = true;
2676 break;
2677 case 0x71: // left arrow key
2678 spin_angle -= spin_increment;
2679 break;
2680 case 0x72: // right arrow key
2681 spin_angle += spin_increment;
2682 break;
2683 case 0x41: // space bar
2684 pause = !pause;
2685 break;
2686 }
2687 break;
2688 case ConfigureNotify:
2689 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2690 width = event->xconfigure.width;
2691 height = event->xconfigure.height;
2692 resize();
2693 }
2694 break;
2695 default:
2696 break;
2697 }
2698}
2699
2700void Demo::run_xlib() {
2701 while (!quit) {
2702 XEvent event;
2703
2704 if (pause) {
2705 XNextEvent(display, &event);
2706 handle_xlib_event(&event);
2707 }
2708 while (XPending(display) > 0) {
2709 XNextEvent(display, &event);
2710 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002711 }
2712
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002713 draw();
2714 curFrame++;
2715
Dave Houlton5fa47912018-02-16 11:02:26 -07002716 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2717 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002718 }
2719 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002720}
Tony Barbour153cb062016-12-07 13:43:36 -07002721#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002722
Dave Houlton5fa47912018-02-16 11:02:26 -07002723void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2724 uint8_t event_code = event->response_type & 0x7f;
2725 switch (event_code) {
2726 case XCB_EXPOSE:
2727 // TODO: Resize window
2728 break;
2729 case XCB_CLIENT_MESSAGE:
2730 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2731 quit = true;
2732 }
2733 break;
2734 case XCB_KEY_RELEASE: {
2735 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002736
Dave Houlton5fa47912018-02-16 11:02:26 -07002737 switch (key->detail) {
2738 case 0x9: // Escape
2739 quit = true;
2740 break;
2741 case 0x71: // left arrow key
2742 spin_angle -= spin_increment;
2743 break;
2744 case 0x72: // right arrow key
2745 spin_angle += spin_increment;
2746 break;
2747 case 0x41: // space bar
2748 pause = !pause;
2749 break;
2750 }
2751 } break;
2752 case XCB_CONFIGURE_NOTIFY: {
2753 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2754 if ((width != cfg->width) || (height != cfg->height)) {
2755 width = cfg->width;
2756 height = cfg->height;
2757 resize();
2758 }
2759 } break;
2760 default:
2761 break;
2762 }
2763}
2764
2765void Demo::run_xcb() {
2766 xcb_flush(connection);
2767
2768 while (!quit) {
2769 xcb_generic_event_t *event;
2770
2771 if (pause) {
2772 event = xcb_wait_for_event(connection);
2773 } else {
2774 event = xcb_poll_for_event(connection);
2775 }
2776 while (event) {
2777 handle_xcb_event(event);
2778 free(event);
2779 event = xcb_poll_for_event(connection);
2780 }
2781
2782 draw();
2783 curFrame++;
2784 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2785 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002786 }
2787 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002788}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002789
Dave Houlton5fa47912018-02-16 11:02:26 -07002790void Demo::create_xcb_window() {
2791 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002792
Dave Houlton5fa47912018-02-16 11:02:26 -07002793 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002794
Dave Houlton5fa47912018-02-16 11:02:26 -07002795 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2796 value_list[0] = screen->black_pixel;
2797 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002798
Dave Houlton5fa47912018-02-16 11:02:26 -07002799 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2800 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2801
2802 /* Magic code that will send notification when window is destroyed */
2803 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2804 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2805
2806 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2807 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2808
2809 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2810
2811 free(reply);
2812
2813 xcb_map_window(connection, xcb_window);
2814
2815 // Force the x/y coordinates to 100,100 results are identical in
2816 // consecutive
2817 // runs
2818 const uint32_t coords[] = {100, 100};
2819 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2820}
2821#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2822
2823void Demo::run() {
2824 while (!quit) {
2825 if (pause) {
2826 wl_display_dispatch(display);
2827 } else {
2828 wl_display_dispatch_pending(display);
2829 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002830 draw();
2831 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002832 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002833 quit = true;
2834 }
2835 }
2836 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002837}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002838
Manuel Stoecklac939332019-06-26 20:55:53 -04002839static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2840 Demo *demo = (Demo *)data;
2841 xdg_surface_ack_configure(xdg_surface, serial);
2842 if (demo->xdg_surface_has_been_configured) {
2843 demo->resize();
2844 }
2845 demo->xdg_surface_has_been_configured = true;
2846}
2847
2848static const xdg_surface_listener surface_listener = {handle_surface_configure};
2849
2850static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2851 struct wl_array *states) {
2852 Demo *demo = (Demo *)data;
2853 /* zero values imply the program may choose its own size, so in that case
2854 * stay with the existing value (which on startup is the default) */
2855 if (width > 0) {
2856 demo->width = width;
2857 }
2858 if (height > 0) {
2859 demo->height = height;
2860 }
2861 // This will be followed by a surface configure
2862}
2863
2864static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2865 Demo *demo = (Demo *)data;
2866 demo->quit = true;
2867}
2868
2869static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2870
Dave Houlton5fa47912018-02-16 11:02:26 -07002871void Demo::create_window() {
Manuel Stoecklac939332019-06-26 20:55:53 -04002872 if (!wm_base) {
2873 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2874 fflush(stdout);
2875 exit(1);
2876 }
2877
Dave Houlton5fa47912018-02-16 11:02:26 -07002878 window = wl_compositor_create_surface(compositor);
2879 if (!window) {
2880 printf("Can not create wayland_surface from compositor!\n");
2881 fflush(stdout);
2882 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002883 }
2884
Manuel Stoecklac939332019-06-26 20:55:53 -04002885 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2886 if (!window_surface) {
2887 printf("Can not get xdg_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002888 fflush(stdout);
2889 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002890 }
Manuel Stoecklac939332019-06-26 20:55:53 -04002891 window_toplevel = xdg_surface_get_toplevel(window_surface);
2892 if (!window_toplevel) {
2893 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2894 fflush(stdout);
2895 exit(1);
2896 }
2897 xdg_surface_add_listener(window_surface, &surface_listener, this);
2898 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2899 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2900 if (xdg_decoration_mgr) {
2901 // if supported, let the compositor render titlebars for us
2902 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2903 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2904 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002905
Manuel Stoecklac939332019-06-26 20:55:53 -04002906 wl_surface_commit(window);
Dave Houlton5fa47912018-02-16 11:02:26 -07002907}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002908#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2909
2910void Demo::handle_directfb_event(const DFBInputEvent *event) {
2911 if (event->type != DIET_KEYPRESS) return;
2912 switch (event->key_symbol) {
2913 case DIKS_ESCAPE: // Escape
2914 quit = true;
2915 break;
2916 case DIKS_CURSOR_LEFT: // left arrow key
2917 spin_angle -= spin_increment;
2918 break;
2919 case DIKS_CURSOR_RIGHT: // right arrow key
2920 spin_angle += spin_increment;
2921 break;
2922 case DIKS_SPACE: // space bar
2923 pause = !pause;
2924 break;
2925 default:
2926 break;
2927 }
2928}
2929
2930void Demo::run_directfb() {
2931 while (!quit) {
2932 DFBInputEvent event;
2933
2934 if (pause) {
2935 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002936 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002937 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002938 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002939
2940 draw();
2941 curFrame++;
2942 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2943 quit = true;
2944 }
2945 }
2946 }
2947}
2948
2949void Demo::create_directfb_window() {
2950 DFBResult ret;
2951
2952 ret = DirectFBInit(NULL, NULL);
2953 if (ret) {
2954 printf("DirectFBInit failed to initialize DirectFB!\n");
2955 fflush(stdout);
2956 exit(1);
2957 }
2958
2959 ret = DirectFBCreate(&dfb);
2960 if (ret) {
2961 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2962 fflush(stdout);
2963 exit(1);
2964 }
2965
2966 DFBSurfaceDescription desc;
2967 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2968 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002969 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002970 desc.height = height;
2971 ret = dfb->CreateSurface(dfb, &desc, &window);
2972 if (ret) {
2973 printf("CreateSurface failed to create DirectFB surface interface!\n");
2974 fflush(stdout);
2975 exit(1);
2976 }
2977
2978 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2979 if (ret) {
2980 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2981 fflush(stdout);
2982 exit(1);
2983 }
2984}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002985#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002986void Demo::run() {
2987 draw();
2988 curFrame++;
2989 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2990 quit = true;
2991 }
2992}
Damien Leone600c3052017-01-31 10:26:07 -07002993#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2994
Dave Houlton5fa47912018-02-16 11:02:26 -07002995vk::Result Demo::create_display_surface() {
2996 vk::Result result;
2997 uint32_t display_count;
2998 uint32_t mode_count;
2999 uint32_t plane_count;
3000 vk::DisplayPropertiesKHR display_props;
3001 vk::DisplayKHR display;
3002 vk::DisplayModePropertiesKHR mode_props;
3003 vk::DisplayPlanePropertiesKHR *plane_props;
3004 vk::Bool32 found_plane = VK_FALSE;
3005 uint32_t plane_index;
3006 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07003007
Dave Houlton5fa47912018-02-16 11:02:26 -07003008 display_count = 1;
3009 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
3010 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3011
3012 display = display_props.display;
3013
3014 // Get the first mode of the display
3015 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
3016 VERIFY(result == vk::Result::eSuccess);
3017
3018 if (mode_count == 0) {
3019 printf("Cannot find any mode for the display!\n");
3020 fflush(stdout);
3021 exit(1);
3022 }
3023
3024 mode_count = 1;
3025 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
3026 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3027
3028 // Get the list of planes
3029 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
3030 VERIFY(result == vk::Result::eSuccess);
3031
3032 if (plane_count == 0) {
3033 printf("Cannot find any plane!\n");
3034 fflush(stdout);
3035 exit(1);
3036 }
3037
3038 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
3039 VERIFY(plane_props != nullptr);
3040
3041 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
3042 VERIFY(result == vk::Result::eSuccess);
3043
3044 // Find a plane compatible with the display
3045 for (plane_index = 0; plane_index < plane_count; plane_index++) {
3046 uint32_t supported_count;
3047 vk::DisplayKHR *supported_displays;
3048
3049 // Disqualify planes that are bound to a different display
3050 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
3051 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003052 }
3053
Dave Houlton5fa47912018-02-16 11:02:26 -07003054 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003055 VERIFY(result == vk::Result::eSuccess);
3056
Dave Houlton5fa47912018-02-16 11:02:26 -07003057 if (supported_count == 0) {
3058 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003059 }
3060
Dave Houlton5fa47912018-02-16 11:02:26 -07003061 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
3062 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003063
Dave Houlton5fa47912018-02-16 11:02:26 -07003064 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003065 VERIFY(result == vk::Result::eSuccess);
3066
Dave Houlton5fa47912018-02-16 11:02:26 -07003067 for (uint32_t i = 0; i < supported_count; i++) {
3068 if (supported_displays[i] == display) {
3069 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07003070 break;
3071 }
3072 }
3073
Dave Houlton5fa47912018-02-16 11:02:26 -07003074 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003075
Dave Houlton5fa47912018-02-16 11:02:26 -07003076 if (found_plane) {
3077 break;
Damien Leone600c3052017-01-31 10:26:07 -07003078 }
3079 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003080
3081 if (!found_plane) {
3082 printf("Cannot find a plane compatible with the display!\n");
3083 fflush(stdout);
3084 exit(1);
3085 }
3086
3087 free(plane_props);
3088
3089 vk::DisplayPlaneCapabilitiesKHR planeCaps;
3090 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
3091 // Find a supported alpha mode
3092 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3093 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
3094 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3095 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3096 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3097 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3098 };
3099 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3100 if (planeCaps.supportedAlpha & alphaModes[i]) {
3101 alphaMode = alphaModes[i];
3102 break;
3103 }
3104 }
3105
3106 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3107 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3108
3109 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3110 .setDisplayMode(mode_props.displayMode)
3111 .setPlaneIndex(plane_index)
3112 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3113 .setGlobalAlpha(1.0f)
3114 .setAlphaMode(alphaMode)
3115 .setImageExtent(image_extent);
3116
3117 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3118}
3119
3120void Demo::run_display() {
3121 while (!quit) {
3122 draw();
3123 curFrame++;
3124
Petr Krausd88e4e52019-01-23 18:45:04 +01003125 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003126 quit = true;
3127 }
3128 }
3129}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003130#endif
3131
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003132#if _WIN32
3133// Include header required for parsing the command line options.
3134#include <shellapi.h>
3135
3136Demo demo;
3137
3138// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003139LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3140 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003141 case WM_CLOSE:
3142 PostQuitMessage(validation_error);
3143 break;
3144 case WM_PAINT:
3145 demo.run();
3146 break;
3147 case WM_GETMINMAXINFO: // set window's minimum size
3148 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3149 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003150 case WM_ERASEBKGND:
3151 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003152 case WM_SIZE:
3153 // Resize the application to the new window size, except when
3154 // it was minimized. Vulkan doesn't support images or swapchains
3155 // with width=0 and height=0.
3156 if (wParam != SIZE_MINIMIZED) {
3157 demo.width = lParam & 0xffff;
3158 demo.height = (lParam & 0xffff0000) >> 16;
3159 demo.resize();
3160 }
3161 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003162 case WM_KEYDOWN:
3163 switch (wParam) {
3164 case VK_ESCAPE:
3165 PostQuitMessage(validation_error);
3166 break;
3167 case VK_LEFT:
3168 demo.spin_angle -= demo.spin_increment;
3169 break;
3170 case VK_RIGHT:
3171 demo.spin_angle += demo.spin_increment;
3172 break;
3173 case VK_SPACE:
3174 demo.pause = !demo.pause;
3175 break;
3176 }
3177 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003178 default:
3179 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003180 }
3181
3182 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3183}
3184
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003185int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003186 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003187 MSG msg; // message
3188 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003189 int argc;
3190 char **argv;
3191
Jamie Madillb2ff6502017-03-15 16:17:46 -04003192 // Ensure wParam is initialized.
3193 msg.wParam = 0;
3194
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003195 // Use the CommandLine functions to get the command line arguments.
3196 // Unfortunately, Microsoft outputs
3197 // this information as wide characters for Unicode, and we simply want the
3198 // Ascii version to be compatible
3199 // with the non-Windows side. So, we have to convert the information to
3200 // Ascii character strings.
3201 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003202 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003203 argc = 0;
3204 }
3205
Jeremy Hayes9d304782016-10-09 11:48:12 -06003206 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003207 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003208 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003209 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003210 } else {
3211 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003212 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3213 size_t numConverted = 0;
3214
3215 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003216 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003217 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003218 }
3219 }
3220 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003221 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003222 argv = nullptr;
3223 }
3224
3225 demo.init(argc, argv);
3226
3227 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003228 if (argc > 0 && argv != nullptr) {
3229 for (int iii = 0; iii < argc; iii++) {
3230 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003231 free(argv[iii]);
3232 }
3233 }
3234 free(argv);
3235 }
3236
3237 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003238 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003239 demo.create_window();
3240 demo.init_vk_swapchain();
3241
3242 demo.prepare();
3243
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003244 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003245
3246 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003247 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003248 if (demo.pause) {
3249 const BOOL succ = WaitMessage();
3250
3251 if (!succ) {
3252 const auto &suppress_popups = demo.suppress_popups;
3253 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3254 }
3255 }
3256
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003257 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003258 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003259 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003260 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003261 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003262 /* Translate and dispatch to event queue*/
3263 TranslateMessage(&msg);
3264 DispatchMessage(&msg);
3265 }
3266 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3267 }
3268
3269 demo.cleanup();
3270
3271 return (int)msg.wParam;
3272}
3273
Eleni Maria Stea8b86fba2021-07-03 17:12:30 +03003274#elif defined(__linux__) || defined(__FreeBSD__)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003275
Jeremy Hayes9d304782016-10-09 11:48:12 -06003276int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003277 Demo demo;
3278
3279 demo.init(argc, argv);
3280
Tony Barbour153cb062016-12-07 13:43:36 -07003281#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003282 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003283#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003284 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003285 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003286#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003287 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003288#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3289 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003290#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003291
3292 demo.init_vk_swapchain();
3293
3294 demo.prepare();
3295
Tony Barbour153cb062016-12-07 13:43:36 -07003296#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003297 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003298#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003299 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003300#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003301 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003302#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3303 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003304#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3305 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003306#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003307
3308 demo.cleanup();
3309
3310 return validation_error;
3311}
3312
Bill Hollings0a0625a2019-07-15 17:39:18 -04003313#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003314
3315// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003316static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003317 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003318 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003319 demo.init_vk_swapchain();
3320 demo.prepare();
3321 demo.spin_angle = 0.4f;
3322}
3323
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003324#else
3325#error "Platform not supported"
3326#endif