blob: 9ff103c5662a0767beeb0a1e0d4f54837f8fb178 [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
334 uint32_t width;
335 uint32_t height;
336 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;
397
398 uint32_t current_buffer;
399 uint32_t queue_family_count;
400};
401
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600402#ifdef _WIN32
403// MS-Windows event handling function:
404LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
405#endif
406
Karl Schultz23cc2182016-11-23 17:15:17 -0700407#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700408static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700409 wl_shell_surface_pong(shell_surface, serial);
410}
411
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700412static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700413
414static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
415
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700416static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700417
Joey Bzdek15eb0702017-06-07 09:40:36 -0600418static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
419 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700420
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700422
Joey Bzdek15eb0702017-06-07 09:40:36 -0600423static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
424
425static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
426 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600427 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600428 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoecklac939332019-06-26 20:55:53 -0400429 xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600430 }
431}
432
433static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
434
435static const struct wl_pointer_listener pointer_listener = {
436 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
437};
438
439static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
440
441static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
442 struct wl_array *keys) {}
443
444static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
445
446static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
447 uint32_t state) {
448 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
449 Demo *demo = (Demo *)data;
450 switch (key) {
451 case KEY_ESC: // Escape
452 demo->quit = true;
453 break;
454 case KEY_LEFT: // left arrow key
455 demo->spin_angle -= demo->spin_increment;
456 break;
457 case KEY_RIGHT: // right arrow key
458 demo->spin_angle += demo->spin_increment;
459 break;
460 case KEY_SPACE: // space bar
461 demo->pause = !demo->pause;
462 break;
463 }
464}
465
466static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
467 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
468
469static const struct wl_keyboard_listener keyboard_listener = {
470 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
471};
472
473static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
474 // Subscribe to pointer events
475 Demo *demo = (Demo *)data;
476 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
477 demo->pointer = wl_seat_get_pointer(seat);
478 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
480 wl_pointer_destroy(demo->pointer);
481 demo->pointer = NULL;
482 }
483 // Subscribe to keyboard events
484 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
485 demo->keyboard = wl_seat_get_keyboard(seat);
486 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
487 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
488 wl_keyboard_destroy(demo->keyboard);
489 demo->keyboard = NULL;
490 }
491}
492
493static const wl_seat_listener seat_listener = {
494 seat_handle_capabilities,
495};
496
Manuel Stoecklac939332019-06-26 20:55:53 -0400497static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
498
499static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
500
Joey Bzdek15eb0702017-06-07 09:40:36 -0600501static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
502 Demo *demo = (Demo *)data;
503 // pickup wayland objects when they appear
Manuel Stoecklac939332019-06-26 20:55:53 -0400504 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600505 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Manuel Stoecklac939332019-06-26 20:55:53 -0400506 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
507 demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
508 xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
509 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600510 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
511 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoecklac939332019-06-26 20:55:53 -0400512 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
513 demo->xdg_decoration_mgr =
514 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600515 }
516}
517
518static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
519
520static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700521#endif
522
Joey Bzdekbaf66472017-06-07 09:37:37 -0600523Demo::Demo()
524 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600525#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600526 connection{nullptr},
527 window{nullptr},
528 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600529#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700530
Tony Barbour78d6b572016-11-14 14:46:33 -0700531#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600532 xlib_window{0},
533 xlib_wm_delete_window{0},
534 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700535#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600536 xcb_window{0},
537 screen{nullptr},
538 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700539#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600540 display{nullptr},
541 registry{nullptr},
542 compositor{nullptr},
543 window{nullptr},
Manuel Stoecklac939332019-06-26 20:55:53 -0400544 wm_base{nullptr},
545 xdg_decoration_mgr{nullptr},
546 toplevel_decoration{nullptr},
547 window_surface{nullptr},
548 xdg_surface_has_been_configured{false},
549 window_toplevel{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600550 seat{nullptr},
551 pointer{nullptr},
552 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200553#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
554 dfb{nullptr},
555 window{nullptr},
556 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700557#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600558 prepared{false},
559 use_staging_buffer{false},
560 use_xlib{false},
561 graphics_queue_family_index{0},
562 present_queue_family_index{0},
563 enabled_extension_count{0},
564 enabled_layer_count{0},
565 width{0},
566 height{0},
567 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000568 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600569 frame_index{0},
570 spin_angle{0.0f},
571 spin_increment{0.0f},
572 pause{false},
573 quit{false},
574 curFrame{0},
575 frameCount{0},
576 validate{false},
577 use_break{false},
578 suppress_popups{false},
579 current_buffer{0},
580 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600581#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700582 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600583#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700584 memset(projection_matrix, 0, sizeof(projection_matrix));
585 memset(view_matrix, 0, sizeof(view_matrix));
586 memset(model_matrix, 0, sizeof(model_matrix));
587}
588
589void Demo::build_image_ownership_cmd(uint32_t const &i) {
590 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
591 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
592 VERIFY(result == vk::Result::eSuccess);
593
594 auto const image_ownership_barrier =
595 vk::ImageMemoryBarrier()
596 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600597 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700598 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
599 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
600 .setSrcQueueFamilyIndex(graphics_queue_family_index)
601 .setDstQueueFamilyIndex(present_queue_family_index)
602 .setImage(swapchain_image_resources[i].image)
603 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
604
605 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600606 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
607 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700608
609 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
610 VERIFY(result == vk::Result::eSuccess);
611}
612
613vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
614 vk::LayerProperties *layers) {
615 for (uint32_t i = 0; i < check_count; i++) {
616 vk::Bool32 found = VK_FALSE;
617 for (uint32_t j = 0; j < layer_count; j++) {
618 if (!strcmp(check_names[i], layers[j].layerName)) {
619 found = VK_TRUE;
620 break;
621 }
622 }
623 if (!found) {
624 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
625 return 0;
626 }
627 }
628 return VK_TRUE;
629}
630
631void Demo::cleanup() {
632 prepared = false;
633 device.waitIdle();
634
635 // Wait for fences from present operations
636 for (uint32_t i = 0; i < FRAME_LAG; i++) {
637 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
638 device.destroyFence(fences[i], nullptr);
639 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
640 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
641 if (separate_present_queue) {
642 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
643 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600644 }
645
Dave Houlton5fa47912018-02-16 11:02:26 -0700646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
648 }
649 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600650
Dave Houlton5fa47912018-02-16 11:02:26 -0700651 device.destroyPipeline(pipeline, nullptr);
652 device.destroyPipelineCache(pipelineCache, nullptr);
653 device.destroyRenderPass(render_pass, nullptr);
654 device.destroyPipelineLayout(pipeline_layout, nullptr);
655 device.destroyDescriptorSetLayout(desc_layout, nullptr);
656
657 for (uint32_t i = 0; i < texture_count; i++) {
658 device.destroyImageView(textures[i].view, nullptr);
659 device.destroyImage(textures[i].image, nullptr);
660 device.freeMemory(textures[i].mem, nullptr);
661 device.destroySampler(textures[i].sampler, nullptr);
662 }
663 device.destroySwapchainKHR(swapchain, nullptr);
664
665 device.destroyImageView(depth.view, nullptr);
666 device.destroyImage(depth.image, nullptr);
667 device.freeMemory(depth.mem, nullptr);
668
669 for (uint32_t i = 0; i < swapchainImageCount; i++) {
670 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700671 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700672 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700673 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700674 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
675 }
676
677 device.destroyCommandPool(cmd_pool, nullptr);
678
679 if (separate_present_queue) {
680 device.destroyCommandPool(present_cmd_pool, nullptr);
681 }
682 device.waitIdle();
683 device.destroy(nullptr);
684 inst.destroySurfaceKHR(surface, nullptr);
685
686#if defined(VK_USE_PLATFORM_XLIB_KHR)
687 XDestroyWindow(display, xlib_window);
688 XCloseDisplay(display);
689#elif defined(VK_USE_PLATFORM_XCB_KHR)
690 xcb_destroy_window(connection, xcb_window);
691 xcb_disconnect(connection);
692 free(atom_wm_delete_window);
693#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
694 wl_keyboard_destroy(keyboard);
695 wl_pointer_destroy(pointer);
696 wl_seat_destroy(seat);
Manuel Stoecklac939332019-06-26 20:55:53 -0400697 xdg_toplevel_destroy(window_toplevel);
698 xdg_surface_destroy(window_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700699 wl_surface_destroy(window);
Manuel Stoecklac939332019-06-26 20:55:53 -0400700 xdg_wm_base_destroy(wm_base);
701 if (xdg_decoration_mgr) {
702 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
703 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
704 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700705 wl_compositor_destroy(compositor);
706 wl_registry_destroy(registry);
707 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200708#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
709 event_buffer->Release(event_buffer);
710 window->Release(window);
711 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700712#endif
713
714 inst.destroy(nullptr);
715}
716
717void Demo::create_device() {
718 float const priorities[1] = {0.0};
719
720 vk::DeviceQueueCreateInfo queues[2];
721 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
722 queues[0].setQueueCount(1);
723 queues[0].setPQueuePriorities(priorities);
724
725 auto deviceInfo = vk::DeviceCreateInfo()
726 .setQueueCreateInfoCount(1)
727 .setPQueueCreateInfos(queues)
728 .setEnabledLayerCount(0)
729 .setPpEnabledLayerNames(nullptr)
730 .setEnabledExtensionCount(enabled_extension_count)
731 .setPpEnabledExtensionNames((const char *const *)extension_names)
732 .setPEnabledFeatures(nullptr);
733
734 if (separate_present_queue) {
735 queues[1].setQueueFamilyIndex(present_queue_family_index);
736 queues[1].setQueueCount(1);
737 queues[1].setPQueuePriorities(priorities);
738 deviceInfo.setQueueCreateInfoCount(2);
739 }
740
741 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
742 VERIFY(result == vk::Result::eSuccess);
743}
744
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600745void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700746 // clean up staging resources
747 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600748 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
749 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700750}
751
752void Demo::draw() {
753 // Ensure no more than FRAME_LAG renderings are outstanding
754 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700755 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700756
757 vk::Result result;
758 do {
759 result =
760 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
761 if (result == vk::Result::eErrorOutOfDateKHR) {
762 // demo->swapchain is out of date (e.g. the window was resized) and
763 // must be recreated:
764 resize();
765 } else if (result == vk::Result::eSuboptimalKHR) {
766 // swapchain is not as optimal as it could be, but the platform's
767 // presentation engine will still present the image correctly.
768 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600769 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
770 inst.destroySurfaceKHR(surface, nullptr);
771 create_surface();
772 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700773 } else {
774 VERIFY(result == vk::Result::eSuccess);
775 }
776 } while (result != vk::Result::eSuccess);
777
778 update_data_buffer();
779
780 // Wait for the image acquired semaphore to be signaled to ensure
781 // that the image won't be rendered to until the presentation
782 // engine has fully released ownership to the application, and it is
783 // okay to render to the image.
784 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
785 auto const submit_info = vk::SubmitInfo()
786 .setPWaitDstStageMask(&pipe_stage_flags)
787 .setWaitSemaphoreCount(1)
788 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
789 .setCommandBufferCount(1)
790 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
791 .setSignalSemaphoreCount(1)
792 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
793
794 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
795 VERIFY(result == vk::Result::eSuccess);
796
797 if (separate_present_queue) {
798 // If we are using separate queues, change image ownership to the
799 // present queue before presenting, waiting for the draw complete
800 // semaphore and signalling the ownership released semaphore when
801 // finished
802 auto const present_submit_info = vk::SubmitInfo()
803 .setPWaitDstStageMask(&pipe_stage_flags)
804 .setWaitSemaphoreCount(1)
805 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
806 .setCommandBufferCount(1)
807 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
808 .setSignalSemaphoreCount(1)
809 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
810
811 result = present_queue.submit(1, &present_submit_info, vk::Fence());
812 VERIFY(result == vk::Result::eSuccess);
813 }
814
815 // If we are using separate queues we have to wait for image ownership,
816 // otherwise wait for draw complete
817 auto const presentInfo = vk::PresentInfoKHR()
818 .setWaitSemaphoreCount(1)
819 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
820 : &draw_complete_semaphores[frame_index])
821 .setSwapchainCount(1)
822 .setPSwapchains(&swapchain)
823 .setPImageIndices(&current_buffer);
824
825 result = present_queue.presentKHR(&presentInfo);
826 frame_index += 1;
827 frame_index %= FRAME_LAG;
828 if (result == vk::Result::eErrorOutOfDateKHR) {
829 // swapchain is out of date (e.g. the window was resized) and
830 // must be recreated:
831 resize();
832 } else if (result == vk::Result::eSuboptimalKHR) {
Tony-LunarGa8e96342021-06-04 15:12:55 -0600833 // SUBOPTIMAL could be due to resize
834 vk::SurfaceCapabilitiesKHR surfCapabilities;
Tony-LunarGbbdf5842021-06-11 12:00:30 -0600835 result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
Tony-LunarGa8e96342021-06-04 15:12:55 -0600836 VERIFY(result == vk::Result::eSuccess);
837 if (surfCapabilities.currentExtent.width != width || surfCapabilities.currentExtent.height != height) {
838 resize();
839 }
Tony-LunarG6cebf142019-09-11 14:32:23 -0600840 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
841 inst.destroySurfaceKHR(surface, nullptr);
842 create_surface();
843 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700844 } else {
845 VERIFY(result == vk::Result::eSuccess);
846 }
847}
848
849void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
850 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
851
852 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
853 vk::ClearDepthStencilValue(1.0f, 0u)};
854
855 auto const passInfo = vk::RenderPassBeginInfo()
856 .setRenderPass(render_pass)
857 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
858 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
859 .setClearValueCount(2)
860 .setPClearValues(clearValues);
861
862 auto result = commandBuffer.begin(&commandInfo);
863 VERIFY(result == vk::Result::eSuccess);
864
865 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
866 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
867 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
868 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700869 float viewport_dimension;
870 float viewport_x = 0.0f;
871 float viewport_y = 0.0f;
872 if (width < height) {
873 viewport_dimension = (float)width;
874 viewport_y = (height - width) / 2.0f;
875 } else {
876 viewport_dimension = (float)height;
877 viewport_x = (width - height) / 2.0f;
878 }
879 auto const viewport = vk::Viewport()
880 .setX(viewport_x)
881 .setY(viewport_y)
882 .setWidth((float)viewport_dimension)
883 .setHeight((float)viewport_dimension)
884 .setMinDepth((float)0.0f)
885 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700886 commandBuffer.setViewport(0, 1, &viewport);
887
888 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
889 commandBuffer.setScissor(0, 1, &scissor);
890 commandBuffer.draw(12 * 3, 1, 0, 0);
891 // Note that ending the renderpass changes the image's layout from
892 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
893 commandBuffer.endRenderPass();
894
895 if (separate_present_queue) {
896 // We have to transfer ownership from the graphics queue family to
897 // the
898 // present queue family to be able to present. Note that we don't
899 // have
900 // to transfer from present queue family back to graphics queue
901 // family at
902 // the start of the next frame because we don't care about the
903 // image's
904 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600905 auto const image_ownership_barrier =
906 vk::ImageMemoryBarrier()
907 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600908 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600909 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
910 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
911 .setSrcQueueFamilyIndex(graphics_queue_family_index)
912 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700913 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700914 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600915
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600916 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700917 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600918 }
919
Dave Houlton5fa47912018-02-16 11:02:26 -0700920 result = commandBuffer.end();
921 VERIFY(result == vk::Result::eSuccess);
922}
923
924void Demo::flush_init_cmd() {
925 // TODO: hmm.
926 // This function could get called twice if the texture uses a staging
927 // buffer
928 // In that case the second call should be ignored
929 if (!cmd) {
930 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600931 }
932
Dave Houlton5fa47912018-02-16 11:02:26 -0700933 auto result = cmd.end();
934 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600935
Dave Houlton5fa47912018-02-16 11:02:26 -0700936 auto const fenceInfo = vk::FenceCreateInfo();
937 vk::Fence fence;
938 result = device.createFence(&fenceInfo, nullptr, &fence);
939 VERIFY(result == vk::Result::eSuccess);
940
941 vk::CommandBuffer const commandBuffers[] = {cmd};
942 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
943
944 result = graphics_queue.submit(1, &submitInfo, fence);
945 VERIFY(result == vk::Result::eSuccess);
946
947 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
948 VERIFY(result == vk::Result::eSuccess);
949
950 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
951 device.destroyFence(fence, nullptr);
952
953 cmd = vk::CommandBuffer();
954}
955
956void Demo::init(int argc, char **argv) {
957 vec3 eye = {0.0f, 3.0f, 5.0f};
958 vec3 origin = {0, 0, 0};
959 vec3 up = {0.0f, 1.0f, 0.0};
960
961 presentMode = vk::PresentModeKHR::eFifo;
962 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100963 width = 500;
964 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700965 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000966 /* Autodetect suitable / best GPU by default */
967 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600968
Dave Houlton5fa47912018-02-16 11:02:26 -0700969 for (int i = 1; i < argc; i++) {
970 if (strcmp(argv[i], "--use_staging") == 0) {
971 use_staging_buffer = true;
972 continue;
973 }
974 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
975 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
976 i++;
977 continue;
978 }
979 if (strcmp(argv[i], "--break") == 0) {
980 use_break = true;
981 continue;
982 }
983 if (strcmp(argv[i], "--validate") == 0) {
984 validate = true;
985 continue;
986 }
987 if (strcmp(argv[i], "--xlib") == 0) {
988 fprintf(stderr, "--xlib is deprecated and no longer does anything");
989 continue;
990 }
991 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
992 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
993 i++;
994 continue;
995 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100996 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &width) == 1 && width > 0) {
997 i++;
998 continue;
999 }
1000 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &height) == 1 && height > 0) {
1001 i++;
1002 continue;
1003 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001004 if (strcmp(argv[i], "--suppress_popups") == 0) {
1005 suppress_popups = true;
1006 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001007 }
Tony-LunarG50e737c2020-07-16 14:26:03 -06001008 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
1009 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +00001010 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -06001011 i++;
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"
Tony-LunarGd74734f2019-06-04 14:11:43 -06001020 << "\t<present_mode_enum>\n"
1021 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
1022 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
1023 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +00001024 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -06001025
1026#if defined(_WIN32)
1027 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1028#else
1029 std::cerr << usage.str();
1030 std::cerr.flush();
1031#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001032 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001033 }
1034
Dave Houlton5fa47912018-02-16 11:02:26 -07001035 if (!use_xlib) {
1036 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001037 }
1038
Dave Houlton5fa47912018-02-16 11:02:26 -07001039 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001040
Dave Houlton5fa47912018-02-16 11:02:26 -07001041 spin_angle = 4.0f;
1042 spin_increment = 0.2f;
1043 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001044
Dave Houlton5fa47912018-02-16 11:02:26 -07001045 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1046 mat4x4_look_at(view_matrix, eye, origin, up);
1047 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001048
Dave Houlton5fa47912018-02-16 11:02:26 -07001049 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1050}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001051
Dave Houlton5fa47912018-02-16 11:02:26 -07001052void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001053#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001054 const xcb_setup_t *setup;
1055 xcb_screen_iterator_t iter;
1056 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001057
Dave Houlton5fa47912018-02-16 11:02:26 -07001058 const char *display_envar = getenv("DISPLAY");
1059 if (display_envar == nullptr || display_envar[0] == '\0') {
1060 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1061 fflush(stdout);
1062 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001063 }
1064
Dave Houlton5fa47912018-02-16 11:02:26 -07001065 connection = xcb_connect(nullptr, &scr);
1066 if (xcb_connection_has_error(connection) > 0) {
1067 printf(
1068 "Cannot find a compatible Vulkan installable client driver "
1069 "(ICD).\nExiting ...\n");
1070 fflush(stdout);
1071 exit(1);
1072 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001073
Dave Houlton5fa47912018-02-16 11:02:26 -07001074 setup = xcb_get_setup(connection);
1075 iter = xcb_setup_roots_iterator(setup);
1076 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001077
Dave Houlton5fa47912018-02-16 11:02:26 -07001078 screen = iter.data;
1079#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1080 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001081
Dave Houlton5fa47912018-02-16 11:02:26 -07001082 if (display == nullptr) {
1083 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1084 fflush(stdout);
1085 exit(1);
1086 }
1087
1088 registry = wl_display_get_registry(display);
1089 wl_registry_add_listener(registry, &registry_listener, this);
1090 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001091#endif
1092}
Tony-LunarG27c21242021-03-11 16:28:19 -07001093#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1094int find_display_gpu(int gpu_number, uint32_t gpu_count, std::unique_ptr<vk::PhysicalDevice[]> &physical_devices) {
1095 uint32_t display_count = 0;
1096 vk::Result result;
1097 int gpu_return = gpu_number;
1098 if (gpu_number >= 0) {
1099 result = physical_devices[gpu_number].getDisplayPropertiesKHR(&display_count, nullptr);
1100 VERIFY(result == vk::Result::eSuccess);
1101 } else {
1102 for (uint32_t i = 0; i < gpu_count; i++) {
1103 result = physical_devices[i].getDisplayPropertiesKHR(&display_count, nullptr);
1104 VERIFY(result == vk::Result::eSuccess);
1105 if (display_count) {
1106 gpu_return = i;
1107 break;
1108 }
1109 }
1110 }
1111 if (display_count > 0)
1112 return gpu_return;
1113 else
1114 return -1;
1115}
1116#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001117void Demo::init_vk() {
1118 uint32_t instance_extension_count = 0;
1119 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001120 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001121 enabled_extension_count = 0;
1122 enabled_layer_count = 0;
1123
Dave Houlton5fa47912018-02-16 11:02:26 -07001124 // Look for validation layers
1125 vk::Bool32 validation_found = VK_FALSE;
1126 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001127 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001128 VERIFY(result == vk::Result::eSuccess);
1129
Dave Houlton5fa47912018-02-16 11:02:26 -07001130 if (instance_layer_count > 0) {
1131 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1132 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001133 VERIFY(result == vk::Result::eSuccess);
1134
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001135 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001136 instance_layer_count, instance_layers.get());
1137 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001138 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1139 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001140 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001141 }
1142
Dave Houlton5fa47912018-02-16 11:02:26 -07001143 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001144 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001145 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1146 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001147 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001148 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001149 }
1150
Dave Houlton5fa47912018-02-16 11:02:26 -07001151 /* Look for instance extensions */
1152 vk::Bool32 surfaceExtFound = VK_FALSE;
1153 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1154 memset(extension_names, 0, sizeof(extension_names));
1155
Mike Schuchardt7510c832018-10-29 13:23:08 -07001156 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1157 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001158 VERIFY(result == vk::Result::eSuccess);
1159
1160 if (instance_extension_count > 0) {
1161 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1162 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1163 VERIFY(result == vk::Result::eSuccess);
1164
1165 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001166 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1167 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1168 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001169 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1170 surfaceExtFound = 1;
1171 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1172 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001173#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001174 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1175 platformSurfaceExtFound = 1;
1176 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1177 }
1178#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1179 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1180 platformSurfaceExtFound = 1;
1181 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1182 }
1183#elif defined(VK_USE_PLATFORM_XCB_KHR)
1184 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1185 platformSurfaceExtFound = 1;
1186 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1187 }
Tony Barbour153cb062016-12-07 13:43:36 -07001188#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001189 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1190 platformSurfaceExtFound = 1;
1191 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1192 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001193#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1194 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1195 platformSurfaceExtFound = 1;
1196 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1197 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001198#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1199 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1200 platformSurfaceExtFound = 1;
1201 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1202 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001203#elif defined(VK_USE_PLATFORM_METAL_EXT)
1204 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001205 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001206 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001207 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001208#endif
1209 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001210 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001211 }
1212
1213 if (!surfaceExtFound) {
1214 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1215 " extension.\n\n"
1216 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1217 "Please look at the Getting Started guide for additional information.\n",
1218 "vkCreateInstance Failure");
1219 }
1220
1221 if (!platformSurfaceExtFound) {
1222#if defined(VK_USE_PLATFORM_WIN32_KHR)
1223 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1224 " extension.\n\n"
1225 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1226 "Please look at the Getting Started guide for additional information.\n",
1227 "vkCreateInstance Failure");
1228#elif defined(VK_USE_PLATFORM_XCB_KHR)
1229 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1230 " extension.\n\n"
1231 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1232 "Please look at the Getting Started guide for additional information.\n",
1233 "vkCreateInstance Failure");
1234#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1235 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1236 " extension.\n\n"
1237 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1238 "Please look at the Getting Started guide for additional information.\n",
1239 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001240#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001241 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1242 " extension.\n\n"
1243 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1244 "Please look at the Getting Started guide for additional information.\n",
1245 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001246#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1247 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1248 " extension.\n\n"
1249 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1250 "Please look at the Getting Started guide for additional information.\n",
1251 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001252#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001253 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1254 " extension.\n\n"
1255 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1256 "Please look at the Getting Started guide for additional information.\n",
1257 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001258#elif defined(VK_USE_PLATFORM_METAL_EXT)
1259 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001260 " extension.\n\nDo you have a compatible "
1261 "Vulkan installable client driver (ICD) installed?\nPlease "
1262 "look at the Getting Started guide for additional "
1263 "information.\n",
1264 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001265#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001266 }
1267 auto const app = vk::ApplicationInfo()
1268 .setPApplicationName(APP_SHORT_NAME)
1269 .setApplicationVersion(0)
1270 .setPEngineName(APP_SHORT_NAME)
1271 .setEngineVersion(0)
1272 .setApiVersion(VK_API_VERSION_1_0);
1273 auto const inst_info = vk::InstanceCreateInfo()
1274 .setPApplicationInfo(&app)
1275 .setEnabledLayerCount(enabled_layer_count)
1276 .setPpEnabledLayerNames(instance_validation_layers)
1277 .setEnabledExtensionCount(enabled_extension_count)
1278 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001279
Dave Houlton5fa47912018-02-16 11:02:26 -07001280 result = vk::createInstance(&inst_info, nullptr, &inst);
1281 if (result == vk::Result::eErrorIncompatibleDriver) {
1282 ERR_EXIT(
1283 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1284 "Please look at the Getting Started guide for additional information.\n",
1285 "vkCreateInstance Failure");
1286 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1287 ERR_EXIT(
1288 "Cannot find a specified extension library.\n"
1289 "Make sure your layers path is set appropriately.\n",
1290 "vkCreateInstance Failure");
1291 } else if (result != vk::Result::eSuccess) {
1292 ERR_EXIT(
1293 "vkCreateInstance failed.\n\n"
1294 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1295 "Please look at the Getting Started guide for additional information.\n",
1296 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001297 }
1298
Witold Baryluka3b988f2021-01-07 19:03:02 +00001299 /* Make initial call to query gpu_count, then second call for gpu info */
1300 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001301 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001302 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001303
Witold Baryluka3b988f2021-01-07 19:03:02 +00001304 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001305 ERR_EXIT(
1306 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1307 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1308 "Please look at the Getting Started guide for additional information.\n",
1309 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001310 }
1311
Witold Baryluka3b988f2021-01-07 19:03:02 +00001312 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1313 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1314 VERIFY(result == vk::Result::eSuccess);
1315
1316 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1317 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1318 ERR_EXIT("Specified GPU number is not present", "User Error");
1319 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001320#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1321 gpu_number = find_display_gpu(gpu_number, gpu_count, physical_devices);
1322 if (gpu_number < 0) {
1323 printf("Cannot find any display!\n");
1324 fflush(stdout);
1325 exit(1);
1326 }
1327#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00001328 /* Try to auto select most suitable device */
1329 if (gpu_number == -1) {
1330 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1331 memset(count_device_type, 0, sizeof(count_device_type));
1332
1333 for (uint32_t i = 0; i < gpu_count; i++) {
1334 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1335 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1336 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1337 }
1338
1339 const vk::PhysicalDeviceType device_type_preference[] = {
1340 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1341 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1342 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1343 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1344 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1345 search_for_device_type = device_type_preference[i];
1346 break;
1347 }
1348 }
1349
1350 for (uint32_t i = 0; i < gpu_count; i++) {
1351 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1352 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1353 gpu_number = i;
1354 break;
1355 }
1356 }
1357 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001358#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00001359 assert(gpu_number >= 0);
1360 gpu = physical_devices[gpu_number];
1361 {
1362 auto physicalDeviceProperties = gpu.getProperties();
1363 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1364 to_string(physicalDeviceProperties.deviceType).c_str());
1365 }
1366 physical_devices.reset();
1367
Dave Houlton5fa47912018-02-16 11:02:26 -07001368 /* Look for device extensions */
1369 uint32_t device_extension_count = 0;
1370 vk::Bool32 swapchainExtFound = VK_FALSE;
1371 enabled_extension_count = 0;
1372 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001373
Mike Schuchardt7510c832018-10-29 13:23:08 -07001374 result =
1375 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001376 VERIFY(result == vk::Result::eSuccess);
1377
1378 if (device_extension_count > 0) {
1379 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1380 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001381 VERIFY(result == vk::Result::eSuccess);
1382
Dave Houlton5fa47912018-02-16 11:02:26 -07001383 for (uint32_t i = 0; i < device_extension_count; i++) {
1384 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1385 swapchainExtFound = 1;
1386 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001387 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001388 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1389 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001390 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001391 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001392 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001393 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001394
Dave Houlton5fa47912018-02-16 11:02:26 -07001395 if (!swapchainExtFound) {
1396 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1397 " extension.\n\n"
1398 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1399 "Please look at the Getting Started guide for additional information.\n",
1400 "vkCreateInstance Failure");
1401 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001402
Dave Houlton5fa47912018-02-16 11:02:26 -07001403 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001404
Dave Houlton5fa47912018-02-16 11:02:26 -07001405 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001406 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001407 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001408
Dave Houlton5fa47912018-02-16 11:02:26 -07001409 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1410 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001411
Dave Houlton5fa47912018-02-16 11:02:26 -07001412 // Query fine-grained feature support for this device.
1413 // If app has specific feature requirements it should check supported
1414 // features based on this query
1415 vk::PhysicalDeviceFeatures physDevFeatures;
1416 gpu.getFeatures(&physDevFeatures);
1417}
1418
Tony-LunarG6cebf142019-09-11 14:32:23 -06001419void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001420// Create a WSI surface for the window:
1421#if defined(VK_USE_PLATFORM_WIN32_KHR)
1422 {
1423 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1424
1425 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1426 VERIFY(result == vk::Result::eSuccess);
1427 }
1428#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1429 {
1430 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1431
1432 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1433 VERIFY(result == vk::Result::eSuccess);
1434 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001435#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1436 {
1437 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1438
1439 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1440 VERIFY(result == vk::Result::eSuccess);
1441 }
1442#elif defined(VK_USE_PLATFORM_XCB_KHR)
1443 {
1444 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1445
1446 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1447 VERIFY(result == vk::Result::eSuccess);
1448 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001449#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1450 {
1451 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1452
1453 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1454 VERIFY(result == vk::Result::eSuccess);
1455 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001456#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001457 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001458 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001459
Bill Hollings0a0625a2019-07-15 17:39:18 -04001460 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001461 VERIFY(result == vk::Result::eSuccess);
1462 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001463#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1464 {
1465 auto result = create_display_surface();
1466 VERIFY(result == vk::Result::eSuccess);
1467 }
1468#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001469}
1470
1471void Demo::init_vk_swapchain() {
1472 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001473 // Iterate over each queue to learn whether it supports presenting:
1474 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1475 for (uint32_t i = 0; i < queue_family_count; i++) {
1476 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1477 }
1478
1479 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1480 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1481 for (uint32_t i = 0; i < queue_family_count; i++) {
1482 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1483 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1484 graphicsQueueFamilyIndex = i;
1485 }
1486
1487 if (supportsPresent[i] == VK_TRUE) {
1488 graphicsQueueFamilyIndex = i;
1489 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001490 break;
1491 }
1492 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001493 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001494
Dave Houlton5fa47912018-02-16 11:02:26 -07001495 if (presentQueueFamilyIndex == UINT32_MAX) {
1496 // If didn't find a queue that supports both graphics and present,
1497 // then
1498 // find a separate present queue.
1499 for (uint32_t i = 0; i < queue_family_count; ++i) {
1500 if (supportsPresent[i] == VK_TRUE) {
1501 presentQueueFamilyIndex = i;
1502 break;
1503 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001504 }
1505 }
1506
Dave Houlton5fa47912018-02-16 11:02:26 -07001507 // Generate error if could not find both a graphics and a present queue
1508 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1509 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1510 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001511
Dave Houlton5fa47912018-02-16 11:02:26 -07001512 graphics_queue_family_index = graphicsQueueFamilyIndex;
1513 present_queue_family_index = presentQueueFamilyIndex;
1514 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001515
Dave Houlton5fa47912018-02-16 11:02:26 -07001516 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001517
Dave Houlton5fa47912018-02-16 11:02:26 -07001518 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1519 if (!separate_present_queue) {
1520 present_queue = graphics_queue;
1521 } else {
1522 device.getQueue(present_queue_family_index, 0, &present_queue);
1523 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001524
Dave Houlton5fa47912018-02-16 11:02:26 -07001525 // Get the list of VkFormat's that are supported:
1526 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001527 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001528 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001529
Dave Houlton5fa47912018-02-16 11:02:26 -07001530 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1531 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1532 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001533
Dave Houlton5fa47912018-02-16 11:02:26 -07001534 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1535 // the surface has no preferred format. Otherwise, at least one
1536 // supported format will be returned.
1537 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1538 format = vk::Format::eB8G8R8A8Unorm;
1539 } else {
1540 assert(formatCount >= 1);
1541 format = surfFormats[0].format;
1542 }
1543 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001544
Dave Houlton5fa47912018-02-16 11:02:26 -07001545 quit = false;
1546 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001547
Dave Houlton5fa47912018-02-16 11:02:26 -07001548 // Create semaphores to synchronize acquiring presentable buffers before
1549 // rendering and waiting for drawing to be complete before presenting
1550 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001551
Dave Houlton5fa47912018-02-16 11:02:26 -07001552 // Create fences that we can use to throttle if we get too far
1553 // ahead of the image presents
1554 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1555 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1556 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1557 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001558
Dave Houlton5fa47912018-02-16 11:02:26 -07001559 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1560 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001561
Dave Houlton5fa47912018-02-16 11:02:26 -07001562 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1563 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001564
Dave Houlton5fa47912018-02-16 11:02:26 -07001565 if (separate_present_queue) {
1566 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001567 VERIFY(result == vk::Result::eSuccess);
1568 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001569 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001570 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001571
Dave Houlton5fa47912018-02-16 11:02:26 -07001572 // Get Memory information and properties
1573 gpu.getMemoryProperties(&memory_properties);
1574}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001575
Dave Houlton5fa47912018-02-16 11:02:26 -07001576void Demo::prepare() {
1577 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1578 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1579 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001580
Dave Houlton5fa47912018-02-16 11:02:26 -07001581 auto const cmd = vk::CommandBufferAllocateInfo()
1582 .setCommandPool(cmd_pool)
1583 .setLevel(vk::CommandBufferLevel::ePrimary)
1584 .setCommandBufferCount(1);
1585
1586 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1587 VERIFY(result == vk::Result::eSuccess);
1588
1589 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1590
1591 result = this->cmd.begin(&cmd_buf_info);
1592 VERIFY(result == vk::Result::eSuccess);
1593
1594 prepare_buffers();
1595 prepare_depth();
1596 prepare_textures();
1597 prepare_cube_data_buffers();
1598
1599 prepare_descriptor_layout();
1600 prepare_render_pass();
1601 prepare_pipeline();
1602
1603 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1604 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1605 VERIFY(result == vk::Result::eSuccess);
1606 }
1607
1608 if (separate_present_queue) {
1609 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1610
1611 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1612 VERIFY(result == vk::Result::eSuccess);
1613
1614 auto const present_cmd = vk::CommandBufferAllocateInfo()
1615 .setCommandPool(present_cmd_pool)
1616 .setLevel(vk::CommandBufferLevel::ePrimary)
1617 .setCommandBufferCount(1);
1618
1619 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1620 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1621 VERIFY(result == vk::Result::eSuccess);
1622
1623 build_image_ownership_cmd(i);
1624 }
1625 }
1626
1627 prepare_descriptor_pool();
1628 prepare_descriptor_set();
1629
1630 prepare_framebuffers();
1631
1632 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1633 current_buffer = i;
1634 draw_build_cmd(swapchain_image_resources[i].cmd);
1635 }
1636
1637 /*
1638 * Prepare functions above may generate pipeline commands
1639 * that need to be flushed before beginning the render loop.
1640 */
1641 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001642 if (staging_texture.buffer) {
1643 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001644 }
1645
1646 current_buffer = 0;
1647 prepared = true;
1648}
1649
1650void Demo::prepare_buffers() {
1651 vk::SwapchainKHR oldSwapchain = swapchain;
1652
1653 // Check the surface capabilities and formats
1654 vk::SurfaceCapabilitiesKHR surfCapabilities;
1655 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1656 VERIFY(result == vk::Result::eSuccess);
1657
1658 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001659 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001660 VERIFY(result == vk::Result::eSuccess);
1661
1662 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1663 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1664 VERIFY(result == vk::Result::eSuccess);
1665
1666 vk::Extent2D swapchainExtent;
1667 // width and height are either both -1, or both not -1.
1668 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1669 // If the surface size is undefined, the size is set to
1670 // the size of the images requested.
1671 swapchainExtent.width = width;
1672 swapchainExtent.height = height;
1673 } else {
1674 // If the surface size is defined, the swap chain size must match
1675 swapchainExtent = surfCapabilities.currentExtent;
1676 width = surfCapabilities.currentExtent.width;
1677 height = surfCapabilities.currentExtent.height;
1678 }
1679
1680 // The FIFO present mode is guaranteed by the spec to be supported
1681 // and to have no tearing. It's a great default present mode to use.
1682 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1683
1684 // There are times when you may wish to use another present mode. The
1685 // following code shows how to select them, and the comments provide some
1686 // reasons you may wish to use them.
1687 //
1688 // It should be noted that Vulkan 1.0 doesn't provide a method for
1689 // synchronizing rendering with the presentation engine's display. There
1690 // is a method provided for throttling rendering with the display, but
1691 // there are some presentation engines for which this method will not work.
1692 // If an application doesn't throttle its rendering, and if it renders much
1693 // faster than the refresh rate of the display, this can waste power on
1694 // mobile devices. That is because power is being spent rendering images
1695 // that may never be seen.
1696
1697 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1698 // about
1699 // tearing, or have some way of synchronizing their rendering with the
1700 // display.
1701 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1702 // generally render a new presentable image every refresh cycle, but are
1703 // occasionally early. In this case, the application wants the new
1704 // image
1705 // to be displayed instead of the previously-queued-for-presentation
1706 // image
1707 // that has not yet been displayed.
1708 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1709 // render a new presentable image every refresh cycle, but are
1710 // occasionally
1711 // late. In this case (perhaps because of stuttering/latency concerns),
1712 // the application wants the late image to be immediately displayed,
1713 // even
1714 // though that may mean some tearing.
1715
1716 if (presentMode != swapchainPresentMode) {
1717 for (size_t i = 0; i < presentModeCount; ++i) {
1718 if (presentModes[i] == presentMode) {
1719 swapchainPresentMode = presentMode;
1720 break;
1721 }
1722 }
1723 }
1724
1725 if (swapchainPresentMode != presentMode) {
1726 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1727 }
1728
1729 // Determine the number of VkImages to use in the swap chain.
1730 // Application desires to acquire 3 images at a time for triple
1731 // buffering
1732 uint32_t desiredNumOfSwapchainImages = 3;
1733 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1734 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1735 }
1736
1737 // If maxImageCount is 0, we can ask for as many images as we want,
1738 // otherwise
1739 // we're limited to maxImageCount
1740 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1741 // Application must settle for fewer images than desired:
1742 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1743 }
1744
1745 vk::SurfaceTransformFlagBitsKHR preTransform;
1746 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1747 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1748 } else {
1749 preTransform = surfCapabilities.currentTransform;
1750 }
1751
1752 // Find a supported composite alpha mode - one of these is guaranteed to be set
1753 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1754 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1755 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1756 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1757 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1758 vk::CompositeAlphaFlagBitsKHR::eInherit,
1759 };
1760 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1761 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1762 compositeAlpha = compositeAlphaFlags[i];
1763 break;
1764 }
1765 }
1766
1767 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1768 .setSurface(surface)
1769 .setMinImageCount(desiredNumOfSwapchainImages)
1770 .setImageFormat(format)
1771 .setImageColorSpace(color_space)
1772 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1773 .setImageArrayLayers(1)
1774 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1775 .setImageSharingMode(vk::SharingMode::eExclusive)
1776 .setQueueFamilyIndexCount(0)
1777 .setPQueueFamilyIndices(nullptr)
1778 .setPreTransform(preTransform)
1779 .setCompositeAlpha(compositeAlpha)
1780 .setPresentMode(swapchainPresentMode)
1781 .setClipped(true)
1782 .setOldSwapchain(oldSwapchain);
1783
1784 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1785 VERIFY(result == vk::Result::eSuccess);
1786
1787 // If we just re-created an existing swapchain, we should destroy the
1788 // old
1789 // swapchain at this point.
1790 // Note: destroying the swapchain also cleans up all its associated
1791 // presentable images once the platform is done with them.
1792 if (oldSwapchain) {
1793 device.destroySwapchainKHR(oldSwapchain, nullptr);
1794 }
1795
Mike Schuchardt7510c832018-10-29 13:23:08 -07001796 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001797 VERIFY(result == vk::Result::eSuccess);
1798
1799 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1800 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1801 VERIFY(result == vk::Result::eSuccess);
1802
1803 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1804
1805 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1806 auto color_image_view = vk::ImageViewCreateInfo()
1807 .setViewType(vk::ImageViewType::e2D)
1808 .setFormat(format)
1809 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1810
1811 swapchain_image_resources[i].image = swapchainImages[i];
1812
1813 color_image_view.image = swapchain_image_resources[i].image;
1814
1815 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1816 VERIFY(result == vk::Result::eSuccess);
1817 }
1818}
1819
1820void Demo::prepare_cube_data_buffers() {
1821 mat4x4 VP;
1822 mat4x4_mul(VP, projection_matrix, view_matrix);
1823
1824 mat4x4 MVP;
1825 mat4x4_mul(MVP, VP, model_matrix);
1826
1827 vktexcube_vs_uniform data;
1828 memcpy(data.mvp, MVP, sizeof(MVP));
1829 // dumpMatrix("MVP", MVP)
1830
1831 for (int32_t i = 0; i < 12 * 3; i++) {
1832 data.position[i][0] = g_vertex_buffer_data[i * 3];
1833 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1834 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1835 data.position[i][3] = 1.0f;
1836 data.attr[i][0] = g_uv_buffer_data[2 * i];
1837 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1838 data.attr[i][2] = 0;
1839 data.attr[i][3] = 0;
1840 }
1841
1842 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1843
1844 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1845 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001846 VERIFY(result == vk::Result::eSuccess);
1847
1848 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001849 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001850
Dave Houlton5fa47912018-02-16 11:02:26 -07001851 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001852
Dave Houlton5fa47912018-02-16 11:02:26 -07001853 bool const pass = memory_type_from_properties(
1854 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1855 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001856 VERIFY(pass);
1857
Dave Houlton5fa47912018-02-16 11:02:26 -07001858 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001859 VERIFY(result == vk::Result::eSuccess);
1860
Tony-LunarG37af49f2019-12-19 12:04:19 -07001861 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1862 &swapchain_image_resources[i].uniform_memory_ptr);
1863 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001864
Tony-LunarG37af49f2019-12-19 12:04:19 -07001865 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001866
1867 result =
1868 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001869 VERIFY(result == vk::Result::eSuccess);
1870 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001871}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001872
Dave Houlton5fa47912018-02-16 11:02:26 -07001873void Demo::prepare_depth() {
1874 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001875
Dave Houlton5fa47912018-02-16 11:02:26 -07001876 auto const image = vk::ImageCreateInfo()
1877 .setImageType(vk::ImageType::e2D)
1878 .setFormat(depth.format)
1879 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1880 .setMipLevels(1)
1881 .setArrayLayers(1)
1882 .setSamples(vk::SampleCountFlagBits::e1)
1883 .setTiling(vk::ImageTiling::eOptimal)
1884 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1885 .setSharingMode(vk::SharingMode::eExclusive)
1886 .setQueueFamilyIndexCount(0)
1887 .setPQueueFamilyIndices(nullptr)
1888 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001889
Dave Houlton5fa47912018-02-16 11:02:26 -07001890 auto result = device.createImage(&image, nullptr, &depth.image);
1891 VERIFY(result == vk::Result::eSuccess);
1892
1893 vk::MemoryRequirements mem_reqs;
1894 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1895
1896 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1897 depth.mem_alloc.setMemoryTypeIndex(0);
1898
1899 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1900 &depth.mem_alloc.memoryTypeIndex);
1901 VERIFY(pass);
1902
1903 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1904 VERIFY(result == vk::Result::eSuccess);
1905
1906 result = device.bindImageMemory(depth.image, depth.mem, 0);
1907 VERIFY(result == vk::Result::eSuccess);
1908
1909 auto const view = vk::ImageViewCreateInfo()
1910 .setImage(depth.image)
1911 .setViewType(vk::ImageViewType::e2D)
1912 .setFormat(depth.format)
1913 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1914 result = device.createImageView(&view, nullptr, &depth.view);
1915 VERIFY(result == vk::Result::eSuccess);
1916}
1917
1918void Demo::prepare_descriptor_layout() {
1919 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1920 .setBinding(0)
1921 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1922 .setDescriptorCount(1)
1923 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1924 .setPImmutableSamplers(nullptr),
1925 vk::DescriptorSetLayoutBinding()
1926 .setBinding(1)
1927 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1928 .setDescriptorCount(texture_count)
1929 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1930 .setPImmutableSamplers(nullptr)};
1931
1932 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1933
1934 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1935 VERIFY(result == vk::Result::eSuccess);
1936
1937 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1938
1939 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1940 VERIFY(result == vk::Result::eSuccess);
1941}
1942
1943void Demo::prepare_descriptor_pool() {
1944 vk::DescriptorPoolSize const poolSizes[2] = {
1945 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1946 vk::DescriptorPoolSize()
1947 .setType(vk::DescriptorType::eCombinedImageSampler)
1948 .setDescriptorCount(swapchainImageCount * texture_count)};
1949
1950 auto const descriptor_pool =
1951 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1952
1953 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1954 VERIFY(result == vk::Result::eSuccess);
1955}
1956
1957void Demo::prepare_descriptor_set() {
1958 auto const alloc_info =
1959 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1960
1961 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1962
1963 vk::DescriptorImageInfo tex_descs[texture_count];
1964 for (uint32_t i = 0; i < texture_count; i++) {
1965 tex_descs[i].setSampler(textures[i].sampler);
1966 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001967 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001968 }
1969
1970 vk::WriteDescriptorSet writes[2];
1971
1972 writes[0].setDescriptorCount(1);
1973 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1974 writes[0].setPBufferInfo(&buffer_info);
1975
1976 writes[1].setDstBinding(1);
1977 writes[1].setDescriptorCount(texture_count);
1978 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1979 writes[1].setPImageInfo(tex_descs);
1980
1981 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1982 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001983 VERIFY(result == vk::Result::eSuccess);
1984
Dave Houlton5fa47912018-02-16 11:02:26 -07001985 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1986 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1987 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1988 device.updateDescriptorSets(2, writes, 0, nullptr);
1989 }
1990}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001991
Dave Houlton5fa47912018-02-16 11:02:26 -07001992void Demo::prepare_framebuffers() {
1993 vk::ImageView attachments[2];
1994 attachments[1] = depth.view;
1995
1996 auto const fb_info = vk::FramebufferCreateInfo()
1997 .setRenderPass(render_pass)
1998 .setAttachmentCount(2)
1999 .setPAttachments(attachments)
2000 .setWidth((uint32_t)width)
2001 .setHeight((uint32_t)height)
2002 .setLayers(1);
2003
2004 for (uint32_t i = 0; i < swapchainImageCount; i++) {
2005 attachments[0] = swapchain_image_resources[i].view;
2006 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002007 VERIFY(result == vk::Result::eSuccess);
2008 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002009}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002010
Dave Houlton5fa47912018-02-16 11:02:26 -07002011vk::ShaderModule Demo::prepare_fs() {
2012 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002013#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07002014 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002015
Dave Houlton5fa47912018-02-16 11:02:26 -07002016 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002017
Dave Houlton5fa47912018-02-16 11:02:26 -07002018 return frag_shader_module;
2019}
2020
2021void Demo::prepare_pipeline() {
2022 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2023 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2024 VERIFY(result == vk::Result::eSuccess);
2025
2026 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
2027 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2028 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2029
2030 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2031
2032 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2033
2034 // TODO: Where are pViewports and pScissors set?
2035 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2036
2037 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2038 .setDepthClampEnable(VK_FALSE)
2039 .setRasterizerDiscardEnable(VK_FALSE)
2040 .setPolygonMode(vk::PolygonMode::eFill)
2041 .setCullMode(vk::CullModeFlagBits::eBack)
2042 .setFrontFace(vk::FrontFace::eCounterClockwise)
2043 .setDepthBiasEnable(VK_FALSE)
2044 .setLineWidth(1.0f);
2045
2046 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2047
2048 auto const stencilOp =
2049 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2050
2051 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2052 .setDepthTestEnable(VK_TRUE)
2053 .setDepthWriteEnable(VK_TRUE)
2054 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2055 .setDepthBoundsTestEnable(VK_FALSE)
2056 .setStencilTestEnable(VK_FALSE)
2057 .setFront(stencilOp)
2058 .setBack(stencilOp);
2059
2060 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2061 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2062 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2063
2064 auto const colorBlendInfo =
2065 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2066
2067 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2068
2069 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2070
2071 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2072 .setStageCount(2)
2073 .setPStages(shaderStageInfo)
2074 .setPVertexInputState(&vertexInputInfo)
2075 .setPInputAssemblyState(&inputAssemblyInfo)
2076 .setPViewportState(&viewportInfo)
2077 .setPRasterizationState(&rasterizationInfo)
2078 .setPMultisampleState(&multisampleInfo)
2079 .setPDepthStencilState(&depthStencilInfo)
2080 .setPColorBlendState(&colorBlendInfo)
2081 .setPDynamicState(&dynamicStateInfo)
2082 .setLayout(pipeline_layout)
2083 .setRenderPass(render_pass);
2084
2085 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2086 VERIFY(result == vk::Result::eSuccess);
2087
2088 device.destroyShaderModule(frag_shader_module, nullptr);
2089 device.destroyShaderModule(vert_shader_module, nullptr);
2090}
2091
2092void Demo::prepare_render_pass() {
2093 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2094 // because at the start of the renderpass, we don't care about their contents.
2095 // At the start of the subpass, the color attachment's layout will be transitioned
2096 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2097 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2098 // the renderpass, the color attachment's layout will be transitioned to
2099 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2100 // the renderpass, no barriers are necessary.
2101 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2102 .setFormat(format)
2103 .setSamples(vk::SampleCountFlagBits::e1)
2104 .setLoadOp(vk::AttachmentLoadOp::eClear)
2105 .setStoreOp(vk::AttachmentStoreOp::eStore)
2106 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2107 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2108 .setInitialLayout(vk::ImageLayout::eUndefined)
2109 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2110 vk::AttachmentDescription()
2111 .setFormat(depth.format)
2112 .setSamples(vk::SampleCountFlagBits::e1)
2113 .setLoadOp(vk::AttachmentLoadOp::eClear)
2114 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2115 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2116 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2117 .setInitialLayout(vk::ImageLayout::eUndefined)
2118 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2119
2120 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2121
2122 auto const depth_reference =
2123 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2124
2125 auto const subpass = vk::SubpassDescription()
2126 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2127 .setInputAttachmentCount(0)
2128 .setPInputAttachments(nullptr)
2129 .setColorAttachmentCount(1)
2130 .setPColorAttachments(&color_reference)
2131 .setPResolveAttachments(nullptr)
2132 .setPDepthStencilAttachment(&depth_reference)
2133 .setPreserveAttachmentCount(0)
2134 .setPPreserveAttachments(nullptr);
2135
Tony-LunarG495604b2019-06-13 15:32:05 -06002136 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2137 vk::SubpassDependency const dependencies[2] = {
2138 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2139 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2140 .setDstSubpass(0)
2141 .setSrcStageMask(stages)
2142 .setDstStageMask(stages)
2143 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2144 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2145 .setDependencyFlags(vk::DependencyFlags()),
2146 vk::SubpassDependency() // Image layout transition
2147 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2148 .setDstSubpass(0)
2149 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2150 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2151 .setSrcAccessMask(vk::AccessFlagBits())
2152 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2153 .setDependencyFlags(vk::DependencyFlags()),
2154 };
2155
Dave Houlton5fa47912018-02-16 11:02:26 -07002156 auto const rp_info = vk::RenderPassCreateInfo()
2157 .setAttachmentCount(2)
2158 .setPAttachments(attachments)
2159 .setSubpassCount(1)
2160 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002161 .setDependencyCount(2)
2162 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002163
2164 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2165 VERIFY(result == vk::Result::eSuccess);
2166}
2167
2168vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2169 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2170
2171 vk::ShaderModule module;
2172 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2173 VERIFY(result == vk::Result::eSuccess);
2174
2175 return module;
2176}
2177
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002178void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2179 int32_t tex_width;
2180 int32_t tex_height;
2181
2182 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2183 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2184 }
2185
2186 tex_obj->tex_width = tex_width;
2187 tex_obj->tex_height = tex_height;
2188
2189 auto const buffer_create_info = vk::BufferCreateInfo()
2190 .setSize(tex_width * tex_height * 4)
2191 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2192 .setSharingMode(vk::SharingMode::eExclusive)
2193 .setQueueFamilyIndexCount(0)
2194 .setPQueueFamilyIndices(nullptr);
2195
2196 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2197 VERIFY(result == vk::Result::eSuccess);
2198
2199 vk::MemoryRequirements mem_reqs;
2200 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2201
2202 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2203 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2204
2205 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2206 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2207 VERIFY(pass == true);
2208
2209 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2210 VERIFY(result == vk::Result::eSuccess);
2211
2212 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2213 VERIFY(result == vk::Result::eSuccess);
2214
2215 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002216 layout.rowPitch = tex_width * 4;
2217 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2218 VERIFY(data.result == vk::Result::eSuccess);
2219
2220 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2221 fprintf(stderr, "Error loading texture: %s\n", filename);
2222 }
2223
2224 device.unmapMemory(tex_obj->mem);
2225}
2226
Dave Houlton5fa47912018-02-16 11:02:26 -07002227void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2228 vk::MemoryPropertyFlags required_props) {
2229 int32_t tex_width;
2230 int32_t tex_height;
2231 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2232 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002233 }
2234
Dave Houlton5fa47912018-02-16 11:02:26 -07002235 tex_obj->tex_width = tex_width;
2236 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002237
Dave Houlton5fa47912018-02-16 11:02:26 -07002238 auto const image_create_info = vk::ImageCreateInfo()
2239 .setImageType(vk::ImageType::e2D)
2240 .setFormat(vk::Format::eR8G8B8A8Unorm)
2241 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2242 .setMipLevels(1)
2243 .setArrayLayers(1)
2244 .setSamples(vk::SampleCountFlagBits::e1)
2245 .setTiling(tiling)
2246 .setUsage(usage)
2247 .setSharingMode(vk::SharingMode::eExclusive)
2248 .setQueueFamilyIndexCount(0)
2249 .setPQueueFamilyIndices(nullptr)
2250 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002251
Dave Houlton5fa47912018-02-16 11:02:26 -07002252 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2253 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002254
Dave Houlton5fa47912018-02-16 11:02:26 -07002255 vk::MemoryRequirements mem_reqs;
2256 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002257
Dave Houlton5fa47912018-02-16 11:02:26 -07002258 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2259 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002260
Dave Houlton5fa47912018-02-16 11:02:26 -07002261 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2262 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002263
Dave Houlton5fa47912018-02-16 11:02:26 -07002264 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2265 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002266
Dave Houlton5fa47912018-02-16 11:02:26 -07002267 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2268 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002269
Dave Houlton5fa47912018-02-16 11:02:26 -07002270 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2271 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2272 vk::SubresourceLayout layout;
2273 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002274
Dave Houlton5fa47912018-02-16 11:02:26 -07002275 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002276 VERIFY(data.result == vk::Result::eSuccess);
2277
Dave Houlton5fa47912018-02-16 11:02:26 -07002278 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2279 fprintf(stderr, "Error loading texture: %s\n", filename);
2280 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002281
Dave Houlton5fa47912018-02-16 11:02:26 -07002282 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002283 }
2284
Dave Houlton5fa47912018-02-16 11:02:26 -07002285 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2286}
2287
2288void Demo::prepare_textures() {
2289 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2290 vk::FormatProperties props;
2291 gpu.getFormatProperties(tex_format, &props);
2292
2293 for (uint32_t i = 0; i < texture_count; i++) {
2294 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2295 /* Device can texture using linear textures */
2296 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2297 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2298 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2299 // shader to run until layout transition completes
2300 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2301 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2302 vk::PipelineStageFlagBits::eFragmentShader);
2303 staging_texture.image = vk::Image();
2304 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2305 /* Must use staging buffer to copy linear texture to optimized */
2306
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002307 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002308
2309 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2310 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2311 vk::MemoryPropertyFlagBits::eDeviceLocal);
2312
Dave Houlton5fa47912018-02-16 11:02:26 -07002313 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2314 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2315 vk::PipelineStageFlagBits::eTransfer);
2316
2317 auto const subresource = vk::ImageSubresourceLayers()
2318 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2319 .setMipLevel(0)
2320 .setBaseArrayLayer(0)
2321 .setLayerCount(1);
2322
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002323 auto const copy_region =
2324 vk::BufferImageCopy()
2325 .setBufferOffset(0)
2326 .setBufferRowLength(staging_texture.tex_width)
2327 .setBufferImageHeight(staging_texture.tex_height)
2328 .setImageSubresource(subresource)
2329 .setImageOffset({0, 0, 0})
2330 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002331
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002332 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002333
2334 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2335 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2336 vk::PipelineStageFlagBits::eFragmentShader);
2337 } else {
2338 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002339 }
2340
Dave Houlton5fa47912018-02-16 11:02:26 -07002341 auto const samplerInfo = vk::SamplerCreateInfo()
2342 .setMagFilter(vk::Filter::eNearest)
2343 .setMinFilter(vk::Filter::eNearest)
2344 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2345 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2346 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2347 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2348 .setMipLodBias(0.0f)
2349 .setAnisotropyEnable(VK_FALSE)
2350 .setMaxAnisotropy(1)
2351 .setCompareEnable(VK_FALSE)
2352 .setCompareOp(vk::CompareOp::eNever)
2353 .setMinLod(0.0f)
2354 .setMaxLod(0.0f)
2355 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2356 .setUnnormalizedCoordinates(VK_FALSE);
2357
2358 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2359 VERIFY(result == vk::Result::eSuccess);
2360
2361 auto const viewInfo = vk::ImageViewCreateInfo()
2362 .setImage(textures[i].image)
2363 .setViewType(vk::ImageViewType::e2D)
2364 .setFormat(tex_format)
2365 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2366
2367 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2368 VERIFY(result == vk::Result::eSuccess);
2369 }
2370}
2371
2372vk::ShaderModule Demo::prepare_vs() {
2373 const uint32_t vertShaderCode[] = {
2374#include "cube.vert.inc"
2375 };
2376
2377 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2378
2379 return vert_shader_module;
2380}
2381
2382void Demo::resize() {
2383 uint32_t i;
2384
2385 // Don't react to resize until after first initialization.
2386 if (!prepared) {
2387 return;
2388 }
2389
2390 // In order to properly resize the window, we must re-create the
2391 // swapchain
2392 // AND redo the command buffers, etc.
2393 //
2394 // First, perform part of the cleanup() function:
2395 prepared = false;
2396 auto result = device.waitIdle();
2397 VERIFY(result == vk::Result::eSuccess);
2398
2399 for (i = 0; i < swapchainImageCount; i++) {
2400 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2401 }
2402
2403 device.destroyDescriptorPool(desc_pool, nullptr);
2404
2405 device.destroyPipeline(pipeline, nullptr);
2406 device.destroyPipelineCache(pipelineCache, nullptr);
2407 device.destroyRenderPass(render_pass, nullptr);
2408 device.destroyPipelineLayout(pipeline_layout, nullptr);
2409 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2410
2411 for (i = 0; i < texture_count; i++) {
2412 device.destroyImageView(textures[i].view, nullptr);
2413 device.destroyImage(textures[i].image, nullptr);
2414 device.freeMemory(textures[i].mem, nullptr);
2415 device.destroySampler(textures[i].sampler, nullptr);
2416 }
2417
2418 device.destroyImageView(depth.view, nullptr);
2419 device.destroyImage(depth.image, nullptr);
2420 device.freeMemory(depth.mem, nullptr);
2421
2422 for (i = 0; i < swapchainImageCount; i++) {
2423 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002424 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002425 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002426 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002427 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2428 }
2429
2430 device.destroyCommandPool(cmd_pool, nullptr);
2431 if (separate_present_queue) {
2432 device.destroyCommandPool(present_cmd_pool, nullptr);
2433 }
2434
2435 // Second, re-perform the prepare() function, which will re-create the
2436 // swapchain.
2437 prepare();
2438}
2439
2440void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2441 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2442 assert(cmd);
2443
2444 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2445 vk::AccessFlags flags;
2446
2447 switch (layout) {
2448 case vk::ImageLayout::eTransferDstOptimal:
2449 // Make sure anything that was copying from this image has
2450 // completed
2451 flags = vk::AccessFlagBits::eTransferWrite;
2452 break;
2453 case vk::ImageLayout::eColorAttachmentOptimal:
2454 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2455 break;
2456 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2457 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2458 break;
2459 case vk::ImageLayout::eShaderReadOnlyOptimal:
2460 // Make sure any Copy or CPU writes to image are flushed
2461 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2462 break;
2463 case vk::ImageLayout::eTransferSrcOptimal:
2464 flags = vk::AccessFlagBits::eTransferRead;
2465 break;
2466 case vk::ImageLayout::ePresentSrcKHR:
2467 flags = vk::AccessFlagBits::eMemoryRead;
2468 break;
2469 default:
2470 break;
2471 }
2472
2473 return flags;
2474 };
2475
2476 auto const barrier = vk::ImageMemoryBarrier()
2477 .setSrcAccessMask(srcAccessMask)
2478 .setDstAccessMask(DstAccessMask(newLayout))
2479 .setOldLayout(oldLayout)
2480 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002481 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2482 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002483 .setImage(image)
2484 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2485
2486 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2487}
2488
2489void Demo::update_data_buffer() {
2490 mat4x4 VP;
2491 mat4x4_mul(VP, projection_matrix, view_matrix);
2492
2493 // Rotate around the Y axis
2494 mat4x4 Model;
2495 mat4x4_dup(Model, model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -07002496 mat4x4_rotate_Y(model_matrix, Model, (float)degreesToRadians(spin_angle));
2497 mat4x4_orthonormalize(model_matrix, model_matrix);
Dave Houlton5fa47912018-02-16 11:02:26 -07002498
2499 mat4x4 MVP;
2500 mat4x4_mul(MVP, VP, model_matrix);
2501
Tony-LunarG37af49f2019-12-19 12:04:19 -07002502 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002503}
2504
Karl Schultzb7940402018-05-29 13:09:22 -06002505/* Convert ppm image data from header file into RGBA texture image */
2506#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002507bool 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 -06002508 (void)filename;
2509 char *cPtr;
2510 cPtr = (char *)lunarg_ppm;
2511 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002512 return false;
2513 }
Karl Schultzb7940402018-05-29 13:09:22 -06002514 while (strncmp(cPtr++, "\n", 1))
2515 ;
2516 sscanf(cPtr, "%u %u", width, height);
2517 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002518 return true;
2519 }
Karl Schultzb7940402018-05-29 13:09:22 -06002520 while (strncmp(cPtr++, "\n", 1))
2521 ;
2522 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002523 return false;
2524 }
Karl Schultzb7940402018-05-29 13:09:22 -06002525 while (strncmp(cPtr++, "\n", 1))
2526 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002527 for (int y = 0; y < *height; y++) {
2528 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002529 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002530 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002531 rowPtr[3] = 255; /* Alpha of 1 */
2532 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002533 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002534 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002535 rgba_data += layout->rowPitch;
2536 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002537 return true;
2538}
2539
2540bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2541 // Search memtypes to find first index with those properties
2542 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2543 if ((typeBits & 1) == 1) {
2544 // Type is available, does it match user properties?
2545 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2546 *typeIndex = i;
2547 return true;
2548 }
2549 }
2550 typeBits >>= 1;
2551 }
2552
2553 // No memory types matched, return failure
2554 return false;
2555}
2556
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002557#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002558void Demo::run() {
2559 if (!prepared) {
2560 return;
2561 }
2562
2563 draw();
2564 curFrame++;
2565
Petr Krausd88e4e52019-01-23 18:45:04 +01002566 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002567 PostQuitMessage(validation_error);
2568 }
2569}
2570
2571void Demo::create_window() {
2572 WNDCLASSEX win_class;
2573
2574 // Initialize the window class structure:
2575 win_class.cbSize = sizeof(WNDCLASSEX);
2576 win_class.style = CS_HREDRAW | CS_VREDRAW;
2577 win_class.lpfnWndProc = WndProc;
2578 win_class.cbClsExtra = 0;
2579 win_class.cbWndExtra = 0;
2580 win_class.hInstance = connection; // hInstance
2581 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2582 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2583 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2584 win_class.lpszMenuName = nullptr;
2585 win_class.lpszClassName = name;
2586 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2587
2588 // Register window class:
2589 if (!RegisterClassEx(&win_class)) {
2590 // It didn't work, so try to give a useful error:
2591 printf("Unexpected error trying to start the application!\n");
2592 fflush(stdout);
2593 exit(1);
2594 }
2595
2596 // Create window with the registered class:
2597 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2598 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2599 window = CreateWindowEx(0,
2600 name, // class name
2601 name, // app name
2602 WS_OVERLAPPEDWINDOW | // window style
2603 WS_VISIBLE | WS_SYSMENU,
2604 100, 100, // x/y coords
2605 wr.right - wr.left, // width
2606 wr.bottom - wr.top, // height
2607 nullptr, // handle to parent
2608 nullptr, // handle to menu
2609 connection, // hInstance
2610 nullptr); // no extra parameters
2611
2612 if (!window) {
2613 // It didn't work, so try to give a useful error:
2614 printf("Cannot create a window in which to draw!\n");
2615 fflush(stdout);
2616 exit(1);
2617 }
2618
2619 // Window client area size must be at least 1 pixel high, to prevent
2620 // crash.
2621 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2622 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2623}
2624#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2625
2626void Demo::create_xlib_window() {
2627 const char *display_envar = getenv("DISPLAY");
2628 if (display_envar == nullptr || display_envar[0] == '\0') {
2629 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2630 fflush(stdout);
2631 exit(1);
2632 }
2633
2634 XInitThreads();
2635 display = XOpenDisplay(nullptr);
2636 long visualMask = VisualScreenMask;
2637 int numberOfVisuals;
2638 XVisualInfo vInfoTemplate = {};
2639 vInfoTemplate.screen = DefaultScreen(display);
2640 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2641
2642 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2643
2644 XSetWindowAttributes windowAttributes = {};
2645 windowAttributes.colormap = colormap;
2646 windowAttributes.background_pixel = 0xFFFFFFFF;
2647 windowAttributes.border_pixel = 0;
2648 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2649
2650 xlib_window =
2651 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2652 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2653
2654 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2655 XMapWindow(display, xlib_window);
2656 XFlush(display);
2657 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2658}
2659
2660void Demo::handle_xlib_event(const XEvent *event) {
2661 switch (event->type) {
2662 case ClientMessage:
2663 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2664 quit = true;
2665 }
2666 break;
2667 case KeyPress:
2668 switch (event->xkey.keycode) {
2669 case 0x9: // Escape
2670 quit = true;
2671 break;
2672 case 0x71: // left arrow key
2673 spin_angle -= spin_increment;
2674 break;
2675 case 0x72: // right arrow key
2676 spin_angle += spin_increment;
2677 break;
2678 case 0x41: // space bar
2679 pause = !pause;
2680 break;
2681 }
2682 break;
2683 case ConfigureNotify:
2684 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2685 width = event->xconfigure.width;
2686 height = event->xconfigure.height;
2687 resize();
2688 }
2689 break;
2690 default:
2691 break;
2692 }
2693}
2694
2695void Demo::run_xlib() {
2696 while (!quit) {
2697 XEvent event;
2698
2699 if (pause) {
2700 XNextEvent(display, &event);
2701 handle_xlib_event(&event);
2702 }
2703 while (XPending(display) > 0) {
2704 XNextEvent(display, &event);
2705 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002706 }
2707
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002708 draw();
2709 curFrame++;
2710
Dave Houlton5fa47912018-02-16 11:02:26 -07002711 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2712 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002713 }
2714 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002715}
Tony Barbour153cb062016-12-07 13:43:36 -07002716#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002717
Dave Houlton5fa47912018-02-16 11:02:26 -07002718void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2719 uint8_t event_code = event->response_type & 0x7f;
2720 switch (event_code) {
2721 case XCB_EXPOSE:
2722 // TODO: Resize window
2723 break;
2724 case XCB_CLIENT_MESSAGE:
2725 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2726 quit = true;
2727 }
2728 break;
2729 case XCB_KEY_RELEASE: {
2730 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002731
Dave Houlton5fa47912018-02-16 11:02:26 -07002732 switch (key->detail) {
2733 case 0x9: // Escape
2734 quit = true;
2735 break;
2736 case 0x71: // left arrow key
2737 spin_angle -= spin_increment;
2738 break;
2739 case 0x72: // right arrow key
2740 spin_angle += spin_increment;
2741 break;
2742 case 0x41: // space bar
2743 pause = !pause;
2744 break;
2745 }
2746 } break;
2747 case XCB_CONFIGURE_NOTIFY: {
2748 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2749 if ((width != cfg->width) || (height != cfg->height)) {
2750 width = cfg->width;
2751 height = cfg->height;
2752 resize();
2753 }
2754 } break;
2755 default:
2756 break;
2757 }
2758}
2759
2760void Demo::run_xcb() {
2761 xcb_flush(connection);
2762
2763 while (!quit) {
2764 xcb_generic_event_t *event;
2765
2766 if (pause) {
2767 event = xcb_wait_for_event(connection);
2768 } else {
2769 event = xcb_poll_for_event(connection);
2770 }
2771 while (event) {
2772 handle_xcb_event(event);
2773 free(event);
2774 event = xcb_poll_for_event(connection);
2775 }
2776
2777 draw();
2778 curFrame++;
2779 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2780 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002781 }
2782 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002783}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002784
Dave Houlton5fa47912018-02-16 11:02:26 -07002785void Demo::create_xcb_window() {
2786 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002787
Dave Houlton5fa47912018-02-16 11:02:26 -07002788 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002789
Dave Houlton5fa47912018-02-16 11:02:26 -07002790 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2791 value_list[0] = screen->black_pixel;
2792 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002793
Dave Houlton5fa47912018-02-16 11:02:26 -07002794 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2795 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2796
2797 /* Magic code that will send notification when window is destroyed */
2798 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2799 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2800
2801 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2802 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2803
2804 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2805
2806 free(reply);
2807
2808 xcb_map_window(connection, xcb_window);
2809
2810 // Force the x/y coordinates to 100,100 results are identical in
2811 // consecutive
2812 // runs
2813 const uint32_t coords[] = {100, 100};
2814 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2815}
2816#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2817
2818void Demo::run() {
2819 while (!quit) {
2820 if (pause) {
2821 wl_display_dispatch(display);
2822 } else {
2823 wl_display_dispatch_pending(display);
2824 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002825 draw();
2826 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002827 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002828 quit = true;
2829 }
2830 }
2831 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002832}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002833
Manuel Stoecklac939332019-06-26 20:55:53 -04002834static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2835 Demo *demo = (Demo *)data;
2836 xdg_surface_ack_configure(xdg_surface, serial);
2837 if (demo->xdg_surface_has_been_configured) {
2838 demo->resize();
2839 }
2840 demo->xdg_surface_has_been_configured = true;
2841}
2842
2843static const xdg_surface_listener surface_listener = {handle_surface_configure};
2844
2845static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2846 struct wl_array *states) {
2847 Demo *demo = (Demo *)data;
2848 /* zero values imply the program may choose its own size, so in that case
2849 * stay with the existing value (which on startup is the default) */
2850 if (width > 0) {
2851 demo->width = width;
2852 }
2853 if (height > 0) {
2854 demo->height = height;
2855 }
2856 // This will be followed by a surface configure
2857}
2858
2859static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2860 Demo *demo = (Demo *)data;
2861 demo->quit = true;
2862}
2863
2864static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2865
Dave Houlton5fa47912018-02-16 11:02:26 -07002866void Demo::create_window() {
Manuel Stoecklac939332019-06-26 20:55:53 -04002867 if (!wm_base) {
2868 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2869 fflush(stdout);
2870 exit(1);
2871 }
2872
Dave Houlton5fa47912018-02-16 11:02:26 -07002873 window = wl_compositor_create_surface(compositor);
2874 if (!window) {
2875 printf("Can not create wayland_surface from compositor!\n");
2876 fflush(stdout);
2877 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002878 }
2879
Manuel Stoecklac939332019-06-26 20:55:53 -04002880 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2881 if (!window_surface) {
2882 printf("Can not get xdg_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002883 fflush(stdout);
2884 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002885 }
Manuel Stoecklac939332019-06-26 20:55:53 -04002886 window_toplevel = xdg_surface_get_toplevel(window_surface);
2887 if (!window_toplevel) {
2888 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2889 fflush(stdout);
2890 exit(1);
2891 }
2892 xdg_surface_add_listener(window_surface, &surface_listener, this);
2893 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2894 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2895 if (xdg_decoration_mgr) {
2896 // if supported, let the compositor render titlebars for us
2897 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2898 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2899 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002900
Manuel Stoecklac939332019-06-26 20:55:53 -04002901 wl_surface_commit(window);
Dave Houlton5fa47912018-02-16 11:02:26 -07002902}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002903#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2904
2905void Demo::handle_directfb_event(const DFBInputEvent *event) {
2906 if (event->type != DIET_KEYPRESS) return;
2907 switch (event->key_symbol) {
2908 case DIKS_ESCAPE: // Escape
2909 quit = true;
2910 break;
2911 case DIKS_CURSOR_LEFT: // left arrow key
2912 spin_angle -= spin_increment;
2913 break;
2914 case DIKS_CURSOR_RIGHT: // right arrow key
2915 spin_angle += spin_increment;
2916 break;
2917 case DIKS_SPACE: // space bar
2918 pause = !pause;
2919 break;
2920 default:
2921 break;
2922 }
2923}
2924
2925void Demo::run_directfb() {
2926 while (!quit) {
2927 DFBInputEvent event;
2928
2929 if (pause) {
2930 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002931 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002932 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002933 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002934
2935 draw();
2936 curFrame++;
2937 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2938 quit = true;
2939 }
2940 }
2941 }
2942}
2943
2944void Demo::create_directfb_window() {
2945 DFBResult ret;
2946
2947 ret = DirectFBInit(NULL, NULL);
2948 if (ret) {
2949 printf("DirectFBInit failed to initialize DirectFB!\n");
2950 fflush(stdout);
2951 exit(1);
2952 }
2953
2954 ret = DirectFBCreate(&dfb);
2955 if (ret) {
2956 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2957 fflush(stdout);
2958 exit(1);
2959 }
2960
2961 DFBSurfaceDescription desc;
2962 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2963 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002964 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002965 desc.height = height;
2966 ret = dfb->CreateSurface(dfb, &desc, &window);
2967 if (ret) {
2968 printf("CreateSurface failed to create DirectFB surface interface!\n");
2969 fflush(stdout);
2970 exit(1);
2971 }
2972
2973 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2974 if (ret) {
2975 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2976 fflush(stdout);
2977 exit(1);
2978 }
2979}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002980#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002981void Demo::run() {
2982 draw();
2983 curFrame++;
2984 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2985 quit = true;
2986 }
2987}
Damien Leone600c3052017-01-31 10:26:07 -07002988#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2989
Dave Houlton5fa47912018-02-16 11:02:26 -07002990vk::Result Demo::create_display_surface() {
2991 vk::Result result;
2992 uint32_t display_count;
2993 uint32_t mode_count;
2994 uint32_t plane_count;
2995 vk::DisplayPropertiesKHR display_props;
2996 vk::DisplayKHR display;
2997 vk::DisplayModePropertiesKHR mode_props;
2998 vk::DisplayPlanePropertiesKHR *plane_props;
2999 vk::Bool32 found_plane = VK_FALSE;
3000 uint32_t plane_index;
3001 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07003002
Dave Houlton5fa47912018-02-16 11:02:26 -07003003 display_count = 1;
3004 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
3005 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3006
3007 display = display_props.display;
3008
3009 // Get the first mode of the display
3010 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
3011 VERIFY(result == vk::Result::eSuccess);
3012
3013 if (mode_count == 0) {
3014 printf("Cannot find any mode for the display!\n");
3015 fflush(stdout);
3016 exit(1);
3017 }
3018
3019 mode_count = 1;
3020 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
3021 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3022
3023 // Get the list of planes
3024 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
3025 VERIFY(result == vk::Result::eSuccess);
3026
3027 if (plane_count == 0) {
3028 printf("Cannot find any plane!\n");
3029 fflush(stdout);
3030 exit(1);
3031 }
3032
3033 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
3034 VERIFY(plane_props != nullptr);
3035
3036 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
3037 VERIFY(result == vk::Result::eSuccess);
3038
3039 // Find a plane compatible with the display
3040 for (plane_index = 0; plane_index < plane_count; plane_index++) {
3041 uint32_t supported_count;
3042 vk::DisplayKHR *supported_displays;
3043
3044 // Disqualify planes that are bound to a different display
3045 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
3046 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003047 }
3048
Dave Houlton5fa47912018-02-16 11:02:26 -07003049 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003050 VERIFY(result == vk::Result::eSuccess);
3051
Dave Houlton5fa47912018-02-16 11:02:26 -07003052 if (supported_count == 0) {
3053 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003054 }
3055
Dave Houlton5fa47912018-02-16 11:02:26 -07003056 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
3057 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003058
Dave Houlton5fa47912018-02-16 11:02:26 -07003059 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003060 VERIFY(result == vk::Result::eSuccess);
3061
Dave Houlton5fa47912018-02-16 11:02:26 -07003062 for (uint32_t i = 0; i < supported_count; i++) {
3063 if (supported_displays[i] == display) {
3064 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07003065 break;
3066 }
3067 }
3068
Dave Houlton5fa47912018-02-16 11:02:26 -07003069 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003070
Dave Houlton5fa47912018-02-16 11:02:26 -07003071 if (found_plane) {
3072 break;
Damien Leone600c3052017-01-31 10:26:07 -07003073 }
3074 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003075
3076 if (!found_plane) {
3077 printf("Cannot find a plane compatible with the display!\n");
3078 fflush(stdout);
3079 exit(1);
3080 }
3081
3082 free(plane_props);
3083
3084 vk::DisplayPlaneCapabilitiesKHR planeCaps;
3085 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
3086 // Find a supported alpha mode
3087 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3088 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
3089 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3090 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3091 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3092 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3093 };
3094 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3095 if (planeCaps.supportedAlpha & alphaModes[i]) {
3096 alphaMode = alphaModes[i];
3097 break;
3098 }
3099 }
3100
3101 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3102 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3103
3104 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3105 .setDisplayMode(mode_props.displayMode)
3106 .setPlaneIndex(plane_index)
3107 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3108 .setGlobalAlpha(1.0f)
3109 .setAlphaMode(alphaMode)
3110 .setImageExtent(image_extent);
3111
3112 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3113}
3114
3115void Demo::run_display() {
3116 while (!quit) {
3117 draw();
3118 curFrame++;
3119
Petr Krausd88e4e52019-01-23 18:45:04 +01003120 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003121 quit = true;
3122 }
3123 }
3124}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003125#endif
3126
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003127#if _WIN32
3128// Include header required for parsing the command line options.
3129#include <shellapi.h>
3130
3131Demo demo;
3132
3133// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003134LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3135 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003136 case WM_CLOSE:
3137 PostQuitMessage(validation_error);
3138 break;
3139 case WM_PAINT:
3140 demo.run();
3141 break;
3142 case WM_GETMINMAXINFO: // set window's minimum size
3143 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3144 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003145 case WM_ERASEBKGND:
3146 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003147 case WM_SIZE:
3148 // Resize the application to the new window size, except when
3149 // it was minimized. Vulkan doesn't support images or swapchains
3150 // with width=0 and height=0.
3151 if (wParam != SIZE_MINIMIZED) {
3152 demo.width = lParam & 0xffff;
3153 demo.height = (lParam & 0xffff0000) >> 16;
3154 demo.resize();
3155 }
3156 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003157 case WM_KEYDOWN:
3158 switch (wParam) {
3159 case VK_ESCAPE:
3160 PostQuitMessage(validation_error);
3161 break;
3162 case VK_LEFT:
3163 demo.spin_angle -= demo.spin_increment;
3164 break;
3165 case VK_RIGHT:
3166 demo.spin_angle += demo.spin_increment;
3167 break;
3168 case VK_SPACE:
3169 demo.pause = !demo.pause;
3170 break;
3171 }
3172 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003173 default:
3174 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003175 }
3176
3177 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3178}
3179
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003180int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003181 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003182 MSG msg; // message
3183 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003184 int argc;
3185 char **argv;
3186
Jamie Madillb2ff6502017-03-15 16:17:46 -04003187 // Ensure wParam is initialized.
3188 msg.wParam = 0;
3189
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003190 // Use the CommandLine functions to get the command line arguments.
3191 // Unfortunately, Microsoft outputs
3192 // this information as wide characters for Unicode, and we simply want the
3193 // Ascii version to be compatible
3194 // with the non-Windows side. So, we have to convert the information to
3195 // Ascii character strings.
3196 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003197 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003198 argc = 0;
3199 }
3200
Jeremy Hayes9d304782016-10-09 11:48:12 -06003201 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003202 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003203 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003204 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003205 } else {
3206 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003207 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3208 size_t numConverted = 0;
3209
3210 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003211 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003212 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003213 }
3214 }
3215 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003216 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003217 argv = nullptr;
3218 }
3219
3220 demo.init(argc, argv);
3221
3222 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003223 if (argc > 0 && argv != nullptr) {
3224 for (int iii = 0; iii < argc; iii++) {
3225 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003226 free(argv[iii]);
3227 }
3228 }
3229 free(argv);
3230 }
3231
3232 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003233 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003234 demo.create_window();
3235 demo.init_vk_swapchain();
3236
3237 demo.prepare();
3238
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003239 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003240
3241 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003242 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003243 if (demo.pause) {
3244 const BOOL succ = WaitMessage();
3245
3246 if (!succ) {
3247 const auto &suppress_popups = demo.suppress_popups;
3248 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3249 }
3250 }
3251
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003252 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003253 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003254 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003255 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003256 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003257 /* Translate and dispatch to event queue*/
3258 TranslateMessage(&msg);
3259 DispatchMessage(&msg);
3260 }
3261 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3262 }
3263
3264 demo.cleanup();
3265
3266 return (int)msg.wParam;
3267}
3268
3269#elif __linux__
3270
Jeremy Hayes9d304782016-10-09 11:48:12 -06003271int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003272 Demo demo;
3273
3274 demo.init(argc, argv);
3275
Tony Barbour153cb062016-12-07 13:43:36 -07003276#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003277 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003278#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003279 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003280 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003281#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003282 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003283#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3284 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003285#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003286
3287 demo.init_vk_swapchain();
3288
3289 demo.prepare();
3290
Tony Barbour153cb062016-12-07 13:43:36 -07003291#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003292 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003293#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003294 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003295#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003296 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003297#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3298 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003299#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3300 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003301#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003302
3303 demo.cleanup();
3304
3305 return validation_error;
3306}
3307
Bill Hollings0a0625a2019-07-15 17:39:18 -04003308#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003309
3310// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003311static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003312 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003313 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003314 demo.init_vk_swapchain();
3315 demo.prepare();
3316 demo.spin_angle = 0.4f;
3317}
3318
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003319#else
3320#error "Platform not supported"
3321#endif