blob: a626c3705efb54f45e0b7452fa8b54d74e3a55f8 [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
Joey Bzdek15eb0702017-06-07 09:40:36 -0600416static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
417 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700418
Joey Bzdek15eb0702017-06-07 09:40:36 -0600419static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700420
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
422
423static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
424 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600425 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600426 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoecklac939332019-06-26 20:55:53 -0400427 xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600428 }
429}
430
431static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
432
433static const struct wl_pointer_listener pointer_listener = {
434 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
435};
436
437static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
438
439static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
440 struct wl_array *keys) {}
441
442static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
443
444static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
445 uint32_t state) {
446 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
447 Demo *demo = (Demo *)data;
448 switch (key) {
449 case KEY_ESC: // Escape
450 demo->quit = true;
451 break;
452 case KEY_LEFT: // left arrow key
453 demo->spin_angle -= demo->spin_increment;
454 break;
455 case KEY_RIGHT: // right arrow key
456 demo->spin_angle += demo->spin_increment;
457 break;
458 case KEY_SPACE: // space bar
459 demo->pause = !demo->pause;
460 break;
461 }
462}
463
464static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
465 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
466
467static const struct wl_keyboard_listener keyboard_listener = {
468 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
469};
470
471static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
472 // Subscribe to pointer events
473 Demo *demo = (Demo *)data;
474 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
475 demo->pointer = wl_seat_get_pointer(seat);
476 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
477 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
478 wl_pointer_destroy(demo->pointer);
479 demo->pointer = NULL;
480 }
481 // Subscribe to keyboard events
482 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
483 demo->keyboard = wl_seat_get_keyboard(seat);
484 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
485 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
486 wl_keyboard_destroy(demo->keyboard);
487 demo->keyboard = NULL;
488 }
489}
490
491static const wl_seat_listener seat_listener = {
492 seat_handle_capabilities,
493};
494
Manuel Stoecklac939332019-06-26 20:55:53 -0400495static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
496
497static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
498
Joey Bzdek15eb0702017-06-07 09:40:36 -0600499static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
500 Demo *demo = (Demo *)data;
501 // pickup wayland objects when they appear
Manuel Stoecklac939332019-06-26 20:55:53 -0400502 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600503 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Manuel Stoecklac939332019-06-26 20:55:53 -0400504 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
505 demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
506 xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
507 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600508 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
509 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoecklac939332019-06-26 20:55:53 -0400510 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
511 demo->xdg_decoration_mgr =
512 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600513 }
514}
515
516static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
517
518static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700519#endif
520
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521Demo::Demo()
522 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600523#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600524 connection{nullptr},
525 window{nullptr},
526 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600527#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700528
Tony Barbour78d6b572016-11-14 14:46:33 -0700529#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600530 xlib_window{0},
531 xlib_wm_delete_window{0},
532 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700533#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600534 xcb_window{0},
535 screen{nullptr},
536 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700537#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600538 display{nullptr},
539 registry{nullptr},
540 compositor{nullptr},
541 window{nullptr},
Manuel Stoecklac939332019-06-26 20:55:53 -0400542 wm_base{nullptr},
543 xdg_decoration_mgr{nullptr},
544 toplevel_decoration{nullptr},
545 window_surface{nullptr},
546 xdg_surface_has_been_configured{false},
547 window_toplevel{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600548 seat{nullptr},
549 pointer{nullptr},
550 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200551#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
552 dfb{nullptr},
553 window{nullptr},
554 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700555#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600556 prepared{false},
557 use_staging_buffer{false},
558 use_xlib{false},
559 graphics_queue_family_index{0},
560 present_queue_family_index{0},
561 enabled_extension_count{0},
562 enabled_layer_count{0},
563 width{0},
564 height{0},
565 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000566 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600567 frame_index{0},
568 spin_angle{0.0f},
569 spin_increment{0.0f},
570 pause{false},
571 quit{false},
572 curFrame{0},
573 frameCount{0},
574 validate{false},
575 use_break{false},
576 suppress_popups{false},
577 current_buffer{0},
578 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600579#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700580 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600581#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700582 memset(projection_matrix, 0, sizeof(projection_matrix));
583 memset(view_matrix, 0, sizeof(view_matrix));
584 memset(model_matrix, 0, sizeof(model_matrix));
585}
586
587void Demo::build_image_ownership_cmd(uint32_t const &i) {
588 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
589 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
590 VERIFY(result == vk::Result::eSuccess);
591
592 auto const image_ownership_barrier =
593 vk::ImageMemoryBarrier()
594 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600595 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700596 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
597 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
598 .setSrcQueueFamilyIndex(graphics_queue_family_index)
599 .setDstQueueFamilyIndex(present_queue_family_index)
600 .setImage(swapchain_image_resources[i].image)
601 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
602
603 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600604 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
605 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700606
607 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
608 VERIFY(result == vk::Result::eSuccess);
609}
610
611vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
612 vk::LayerProperties *layers) {
613 for (uint32_t i = 0; i < check_count; i++) {
614 vk::Bool32 found = VK_FALSE;
615 for (uint32_t j = 0; j < layer_count; j++) {
616 if (!strcmp(check_names[i], layers[j].layerName)) {
617 found = VK_TRUE;
618 break;
619 }
620 }
621 if (!found) {
622 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
623 return 0;
624 }
625 }
626 return VK_TRUE;
627}
628
629void Demo::cleanup() {
630 prepared = false;
631 device.waitIdle();
632
633 // Wait for fences from present operations
634 for (uint32_t i = 0; i < FRAME_LAG; i++) {
635 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
636 device.destroyFence(fences[i], nullptr);
637 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
638 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
639 if (separate_present_queue) {
640 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
641 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600642 }
643
Dave Houlton5fa47912018-02-16 11:02:26 -0700644 for (uint32_t i = 0; i < swapchainImageCount; i++) {
645 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
646 }
647 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600648
Dave Houlton5fa47912018-02-16 11:02:26 -0700649 device.destroyPipeline(pipeline, nullptr);
650 device.destroyPipelineCache(pipelineCache, nullptr);
651 device.destroyRenderPass(render_pass, nullptr);
652 device.destroyPipelineLayout(pipeline_layout, nullptr);
653 device.destroyDescriptorSetLayout(desc_layout, nullptr);
654
655 for (uint32_t i = 0; i < texture_count; i++) {
656 device.destroyImageView(textures[i].view, nullptr);
657 device.destroyImage(textures[i].image, nullptr);
658 device.freeMemory(textures[i].mem, nullptr);
659 device.destroySampler(textures[i].sampler, nullptr);
660 }
661 device.destroySwapchainKHR(swapchain, nullptr);
662
663 device.destroyImageView(depth.view, nullptr);
664 device.destroyImage(depth.image, nullptr);
665 device.freeMemory(depth.mem, nullptr);
666
667 for (uint32_t i = 0; i < swapchainImageCount; i++) {
668 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700669 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700670 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700671 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700672 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
673 }
674
675 device.destroyCommandPool(cmd_pool, nullptr);
676
677 if (separate_present_queue) {
678 device.destroyCommandPool(present_cmd_pool, nullptr);
679 }
680 device.waitIdle();
681 device.destroy(nullptr);
682 inst.destroySurfaceKHR(surface, nullptr);
683
684#if defined(VK_USE_PLATFORM_XLIB_KHR)
685 XDestroyWindow(display, xlib_window);
686 XCloseDisplay(display);
687#elif defined(VK_USE_PLATFORM_XCB_KHR)
688 xcb_destroy_window(connection, xcb_window);
689 xcb_disconnect(connection);
690 free(atom_wm_delete_window);
691#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
692 wl_keyboard_destroy(keyboard);
693 wl_pointer_destroy(pointer);
694 wl_seat_destroy(seat);
Manuel Stoecklac939332019-06-26 20:55:53 -0400695 xdg_toplevel_destroy(window_toplevel);
696 xdg_surface_destroy(window_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700697 wl_surface_destroy(window);
Manuel Stoecklac939332019-06-26 20:55:53 -0400698 xdg_wm_base_destroy(wm_base);
699 if (xdg_decoration_mgr) {
700 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
701 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
702 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700703 wl_compositor_destroy(compositor);
704 wl_registry_destroy(registry);
705 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200706#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
707 event_buffer->Release(event_buffer);
708 window->Release(window);
709 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700710#endif
711
712 inst.destroy(nullptr);
713}
714
715void Demo::create_device() {
716 float const priorities[1] = {0.0};
717
718 vk::DeviceQueueCreateInfo queues[2];
719 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
720 queues[0].setQueueCount(1);
721 queues[0].setPQueuePriorities(priorities);
722
723 auto deviceInfo = vk::DeviceCreateInfo()
724 .setQueueCreateInfoCount(1)
725 .setPQueueCreateInfos(queues)
726 .setEnabledLayerCount(0)
727 .setPpEnabledLayerNames(nullptr)
728 .setEnabledExtensionCount(enabled_extension_count)
729 .setPpEnabledExtensionNames((const char *const *)extension_names)
730 .setPEnabledFeatures(nullptr);
731
732 if (separate_present_queue) {
733 queues[1].setQueueFamilyIndex(present_queue_family_index);
734 queues[1].setQueueCount(1);
735 queues[1].setPQueuePriorities(priorities);
736 deviceInfo.setQueueCreateInfoCount(2);
737 }
738
739 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
740 VERIFY(result == vk::Result::eSuccess);
741}
742
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600743void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700744 // clean up staging resources
745 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600746 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
747 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700748}
749
750void Demo::draw() {
751 // Ensure no more than FRAME_LAG renderings are outstanding
752 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700753 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700754
755 vk::Result result;
756 do {
757 result =
758 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
759 if (result == vk::Result::eErrorOutOfDateKHR) {
760 // demo->swapchain is out of date (e.g. the window was resized) and
761 // must be recreated:
762 resize();
763 } else if (result == vk::Result::eSuboptimalKHR) {
764 // swapchain is not as optimal as it could be, but the platform's
765 // presentation engine will still present the image correctly.
766 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600767 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
768 inst.destroySurfaceKHR(surface, nullptr);
769 create_surface();
770 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700771 } else {
772 VERIFY(result == vk::Result::eSuccess);
773 }
774 } while (result != vk::Result::eSuccess);
775
776 update_data_buffer();
777
778 // Wait for the image acquired semaphore to be signaled to ensure
779 // that the image won't be rendered to until the presentation
780 // engine has fully released ownership to the application, and it is
781 // okay to render to the image.
782 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
783 auto const submit_info = vk::SubmitInfo()
784 .setPWaitDstStageMask(&pipe_stage_flags)
785 .setWaitSemaphoreCount(1)
786 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
787 .setCommandBufferCount(1)
788 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
789 .setSignalSemaphoreCount(1)
790 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
791
792 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
793 VERIFY(result == vk::Result::eSuccess);
794
795 if (separate_present_queue) {
796 // If we are using separate queues, change image ownership to the
797 // present queue before presenting, waiting for the draw complete
798 // semaphore and signalling the ownership released semaphore when
799 // finished
800 auto const present_submit_info = vk::SubmitInfo()
801 .setPWaitDstStageMask(&pipe_stage_flags)
802 .setWaitSemaphoreCount(1)
803 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
804 .setCommandBufferCount(1)
805 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
806 .setSignalSemaphoreCount(1)
807 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
808
809 result = present_queue.submit(1, &present_submit_info, vk::Fence());
810 VERIFY(result == vk::Result::eSuccess);
811 }
812
813 // If we are using separate queues we have to wait for image ownership,
814 // otherwise wait for draw complete
815 auto const presentInfo = vk::PresentInfoKHR()
816 .setWaitSemaphoreCount(1)
817 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
818 : &draw_complete_semaphores[frame_index])
819 .setSwapchainCount(1)
820 .setPSwapchains(&swapchain)
821 .setPImageIndices(&current_buffer);
822
823 result = present_queue.presentKHR(&presentInfo);
824 frame_index += 1;
825 frame_index %= FRAME_LAG;
826 if (result == vk::Result::eErrorOutOfDateKHR) {
827 // swapchain is out of date (e.g. the window was resized) and
828 // must be recreated:
829 resize();
830 } else if (result == vk::Result::eSuboptimalKHR) {
Tony-LunarGa8e96342021-06-04 15:12:55 -0600831 // SUBOPTIMAL could be due to resize
832 vk::SurfaceCapabilitiesKHR surfCapabilities;
Tony-LunarGbbdf5842021-06-11 12:00:30 -0600833 result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
Tony-LunarGa8e96342021-06-04 15:12:55 -0600834 VERIFY(result == vk::Result::eSuccess);
835 if (surfCapabilities.currentExtent.width != width || surfCapabilities.currentExtent.height != height) {
836 resize();
837 }
Tony-LunarG6cebf142019-09-11 14:32:23 -0600838 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
839 inst.destroySurfaceKHR(surface, nullptr);
840 create_surface();
841 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700842 } else {
843 VERIFY(result == vk::Result::eSuccess);
844 }
845}
846
847void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
848 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
849
850 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
851 vk::ClearDepthStencilValue(1.0f, 0u)};
852
853 auto const passInfo = vk::RenderPassBeginInfo()
854 .setRenderPass(render_pass)
855 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
856 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
857 .setClearValueCount(2)
858 .setPClearValues(clearValues);
859
860 auto result = commandBuffer.begin(&commandInfo);
861 VERIFY(result == vk::Result::eSuccess);
862
863 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
864 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
865 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
866 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700867 float viewport_dimension;
868 float viewport_x = 0.0f;
869 float viewport_y = 0.0f;
870 if (width < height) {
871 viewport_dimension = (float)width;
872 viewport_y = (height - width) / 2.0f;
873 } else {
874 viewport_dimension = (float)height;
875 viewport_x = (width - height) / 2.0f;
876 }
877 auto const viewport = vk::Viewport()
878 .setX(viewport_x)
879 .setY(viewport_y)
880 .setWidth((float)viewport_dimension)
881 .setHeight((float)viewport_dimension)
882 .setMinDepth((float)0.0f)
883 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700884 commandBuffer.setViewport(0, 1, &viewport);
885
886 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
887 commandBuffer.setScissor(0, 1, &scissor);
888 commandBuffer.draw(12 * 3, 1, 0, 0);
889 // Note that ending the renderpass changes the image's layout from
890 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
891 commandBuffer.endRenderPass();
892
893 if (separate_present_queue) {
894 // We have to transfer ownership from the graphics queue family to
895 // the
896 // present queue family to be able to present. Note that we don't
897 // have
898 // to transfer from present queue family back to graphics queue
899 // family at
900 // the start of the next frame because we don't care about the
901 // image's
902 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600903 auto const image_ownership_barrier =
904 vk::ImageMemoryBarrier()
905 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600906 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600907 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
908 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
909 .setSrcQueueFamilyIndex(graphics_queue_family_index)
910 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700911 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700912 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600913
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600914 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700915 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600916 }
917
Dave Houlton5fa47912018-02-16 11:02:26 -0700918 result = commandBuffer.end();
919 VERIFY(result == vk::Result::eSuccess);
920}
921
922void Demo::flush_init_cmd() {
923 // TODO: hmm.
924 // This function could get called twice if the texture uses a staging
925 // buffer
926 // In that case the second call should be ignored
927 if (!cmd) {
928 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600929 }
930
Dave Houlton5fa47912018-02-16 11:02:26 -0700931 auto result = cmd.end();
932 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600933
Dave Houlton5fa47912018-02-16 11:02:26 -0700934 auto const fenceInfo = vk::FenceCreateInfo();
935 vk::Fence fence;
936 result = device.createFence(&fenceInfo, nullptr, &fence);
937 VERIFY(result == vk::Result::eSuccess);
938
939 vk::CommandBuffer const commandBuffers[] = {cmd};
940 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
941
942 result = graphics_queue.submit(1, &submitInfo, fence);
943 VERIFY(result == vk::Result::eSuccess);
944
945 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
946 VERIFY(result == vk::Result::eSuccess);
947
948 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
949 device.destroyFence(fence, nullptr);
950
951 cmd = vk::CommandBuffer();
952}
953
954void Demo::init(int argc, char **argv) {
955 vec3 eye = {0.0f, 3.0f, 5.0f};
956 vec3 origin = {0, 0, 0};
957 vec3 up = {0.0f, 1.0f, 0.0};
958
959 presentMode = vk::PresentModeKHR::eFifo;
960 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100961 width = 500;
962 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700963 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000964 /* Autodetect suitable / best GPU by default */
965 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600966
Dave Houlton5fa47912018-02-16 11:02:26 -0700967 for (int i = 1; i < argc; i++) {
968 if (strcmp(argv[i], "--use_staging") == 0) {
969 use_staging_buffer = true;
970 continue;
971 }
972 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
973 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
974 i++;
975 continue;
976 }
977 if (strcmp(argv[i], "--break") == 0) {
978 use_break = true;
979 continue;
980 }
981 if (strcmp(argv[i], "--validate") == 0) {
982 validate = true;
983 continue;
984 }
985 if (strcmp(argv[i], "--xlib") == 0) {
986 fprintf(stderr, "--xlib is deprecated and no longer does anything");
987 continue;
988 }
989 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
990 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
991 i++;
992 continue;
993 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100994 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &width) == 1 && width > 0) {
995 i++;
996 continue;
997 }
998 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &height) == 1 && height > 0) {
999 i++;
1000 continue;
1001 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001002 if (strcmp(argv[i], "--suppress_popups") == 0) {
1003 suppress_popups = true;
1004 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001005 }
Tony-LunarG50e737c2020-07-16 14:26:03 -06001006 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
1007 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +00001008 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -06001009 i++;
1010 continue;
1011 }
Tony-LunarGd74734f2019-06-04 14:11:43 -06001012 std::stringstream usage;
1013 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
1014 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -06001015 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06001016 << "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01001017 << "\t[--width <width>] [--height <height>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06001018 << "\t<present_mode_enum>\n"
1019 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
1020 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
1021 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +00001022 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -06001023
1024#if defined(_WIN32)
1025 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1026#else
1027 std::cerr << usage.str();
1028 std::cerr.flush();
1029#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001030 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001031 }
1032
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 if (!use_xlib) {
1034 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001035 }
1036
Dave Houlton5fa47912018-02-16 11:02:26 -07001037 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001038
Dave Houlton5fa47912018-02-16 11:02:26 -07001039 spin_angle = 4.0f;
1040 spin_increment = 0.2f;
1041 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001042
Dave Houlton5fa47912018-02-16 11:02:26 -07001043 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1044 mat4x4_look_at(view_matrix, eye, origin, up);
1045 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001046
Dave Houlton5fa47912018-02-16 11:02:26 -07001047 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1048}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001049
Dave Houlton5fa47912018-02-16 11:02:26 -07001050void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001051#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001052 const xcb_setup_t *setup;
1053 xcb_screen_iterator_t iter;
1054 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001055
Dave Houlton5fa47912018-02-16 11:02:26 -07001056 const char *display_envar = getenv("DISPLAY");
1057 if (display_envar == nullptr || display_envar[0] == '\0') {
1058 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1059 fflush(stdout);
1060 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001061 }
1062
Dave Houlton5fa47912018-02-16 11:02:26 -07001063 connection = xcb_connect(nullptr, &scr);
1064 if (xcb_connection_has_error(connection) > 0) {
1065 printf(
1066 "Cannot find a compatible Vulkan installable client driver "
1067 "(ICD).\nExiting ...\n");
1068 fflush(stdout);
1069 exit(1);
1070 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001071
Dave Houlton5fa47912018-02-16 11:02:26 -07001072 setup = xcb_get_setup(connection);
1073 iter = xcb_setup_roots_iterator(setup);
1074 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001075
Dave Houlton5fa47912018-02-16 11:02:26 -07001076 screen = iter.data;
1077#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1078 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001079
Dave Houlton5fa47912018-02-16 11:02:26 -07001080 if (display == nullptr) {
1081 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1082 fflush(stdout);
1083 exit(1);
1084 }
1085
1086 registry = wl_display_get_registry(display);
1087 wl_registry_add_listener(registry, &registry_listener, this);
1088 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001089#endif
1090}
Tony-LunarG27c21242021-03-11 16:28:19 -07001091#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1092int find_display_gpu(int gpu_number, uint32_t gpu_count, std::unique_ptr<vk::PhysicalDevice[]> &physical_devices) {
1093 uint32_t display_count = 0;
1094 vk::Result result;
1095 int gpu_return = gpu_number;
1096 if (gpu_number >= 0) {
1097 result = physical_devices[gpu_number].getDisplayPropertiesKHR(&display_count, nullptr);
1098 VERIFY(result == vk::Result::eSuccess);
1099 } else {
1100 for (uint32_t i = 0; i < gpu_count; i++) {
1101 result = physical_devices[i].getDisplayPropertiesKHR(&display_count, nullptr);
1102 VERIFY(result == vk::Result::eSuccess);
1103 if (display_count) {
1104 gpu_return = i;
1105 break;
1106 }
1107 }
1108 }
1109 if (display_count > 0)
1110 return gpu_return;
1111 else
1112 return -1;
1113}
1114#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001115void Demo::init_vk() {
1116 uint32_t instance_extension_count = 0;
1117 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001118 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001119 enabled_extension_count = 0;
1120 enabled_layer_count = 0;
1121
Dave Houlton5fa47912018-02-16 11:02:26 -07001122 // Look for validation layers
1123 vk::Bool32 validation_found = VK_FALSE;
1124 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001125 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001126 VERIFY(result == vk::Result::eSuccess);
1127
Dave Houlton5fa47912018-02-16 11:02:26 -07001128 if (instance_layer_count > 0) {
1129 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1130 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001131 VERIFY(result == vk::Result::eSuccess);
1132
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001133 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001134 instance_layer_count, instance_layers.get());
1135 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001136 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1137 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001138 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001139 }
1140
Dave Houlton5fa47912018-02-16 11:02:26 -07001141 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001142 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001143 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1144 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001145 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001146 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001147 }
1148
Dave Houlton5fa47912018-02-16 11:02:26 -07001149 /* Look for instance extensions */
1150 vk::Bool32 surfaceExtFound = VK_FALSE;
1151 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1152 memset(extension_names, 0, sizeof(extension_names));
1153
Mike Schuchardt7510c832018-10-29 13:23:08 -07001154 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1155 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001156 VERIFY(result == vk::Result::eSuccess);
1157
1158 if (instance_extension_count > 0) {
1159 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1160 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1161 VERIFY(result == vk::Result::eSuccess);
1162
1163 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001164 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1165 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1166 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001167 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1168 surfaceExtFound = 1;
1169 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1170 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001171#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001172 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1173 platformSurfaceExtFound = 1;
1174 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1175 }
1176#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1177 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1178 platformSurfaceExtFound = 1;
1179 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1180 }
1181#elif defined(VK_USE_PLATFORM_XCB_KHR)
1182 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1183 platformSurfaceExtFound = 1;
1184 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1185 }
Tony Barbour153cb062016-12-07 13:43:36 -07001186#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001187 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1188 platformSurfaceExtFound = 1;
1189 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1190 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001191#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1192 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1193 platformSurfaceExtFound = 1;
1194 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1195 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001196#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1197 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1198 platformSurfaceExtFound = 1;
1199 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1200 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001201#elif defined(VK_USE_PLATFORM_METAL_EXT)
1202 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001203 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001204 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001205 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001206#endif
1207 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001208 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001209 }
1210
1211 if (!surfaceExtFound) {
1212 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1213 " extension.\n\n"
1214 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1215 "Please look at the Getting Started guide for additional information.\n",
1216 "vkCreateInstance Failure");
1217 }
1218
1219 if (!platformSurfaceExtFound) {
1220#if defined(VK_USE_PLATFORM_WIN32_KHR)
1221 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1222 " extension.\n\n"
1223 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1224 "Please look at the Getting Started guide for additional information.\n",
1225 "vkCreateInstance Failure");
1226#elif defined(VK_USE_PLATFORM_XCB_KHR)
1227 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1228 " extension.\n\n"
1229 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1230 "Please look at the Getting Started guide for additional information.\n",
1231 "vkCreateInstance Failure");
1232#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1233 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1234 " extension.\n\n"
1235 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1236 "Please look at the Getting Started guide for additional information.\n",
1237 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001238#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001239 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1240 " extension.\n\n"
1241 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1242 "Please look at the Getting Started guide for additional information.\n",
1243 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001244#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1245 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1246 " extension.\n\n"
1247 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1248 "Please look at the Getting Started guide for additional information.\n",
1249 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001250#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001251 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1252 " extension.\n\n"
1253 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1254 "Please look at the Getting Started guide for additional information.\n",
1255 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001256#elif defined(VK_USE_PLATFORM_METAL_EXT)
1257 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001258 " extension.\n\nDo you have a compatible "
1259 "Vulkan installable client driver (ICD) installed?\nPlease "
1260 "look at the Getting Started guide for additional "
1261 "information.\n",
1262 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001263#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001264 }
1265 auto const app = vk::ApplicationInfo()
1266 .setPApplicationName(APP_SHORT_NAME)
1267 .setApplicationVersion(0)
1268 .setPEngineName(APP_SHORT_NAME)
1269 .setEngineVersion(0)
1270 .setApiVersion(VK_API_VERSION_1_0);
1271 auto const inst_info = vk::InstanceCreateInfo()
1272 .setPApplicationInfo(&app)
1273 .setEnabledLayerCount(enabled_layer_count)
1274 .setPpEnabledLayerNames(instance_validation_layers)
1275 .setEnabledExtensionCount(enabled_extension_count)
1276 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001277
Dave Houlton5fa47912018-02-16 11:02:26 -07001278 result = vk::createInstance(&inst_info, nullptr, &inst);
1279 if (result == vk::Result::eErrorIncompatibleDriver) {
1280 ERR_EXIT(
1281 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1282 "Please look at the Getting Started guide for additional information.\n",
1283 "vkCreateInstance Failure");
1284 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1285 ERR_EXIT(
1286 "Cannot find a specified extension library.\n"
1287 "Make sure your layers path is set appropriately.\n",
1288 "vkCreateInstance Failure");
1289 } else if (result != vk::Result::eSuccess) {
1290 ERR_EXIT(
1291 "vkCreateInstance failed.\n\n"
1292 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1293 "Please look at the Getting Started guide for additional information.\n",
1294 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001295 }
1296
Witold Baryluka3b988f2021-01-07 19:03:02 +00001297 /* Make initial call to query gpu_count, then second call for gpu info */
1298 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001299 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001300 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001301
Witold Baryluka3b988f2021-01-07 19:03:02 +00001302 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001303 ERR_EXIT(
1304 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1305 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1306 "Please look at the Getting Started guide for additional information.\n",
1307 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001308 }
1309
Witold Baryluka3b988f2021-01-07 19:03:02 +00001310 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1311 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1312 VERIFY(result == vk::Result::eSuccess);
1313
1314 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1315 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1316 ERR_EXIT("Specified GPU number is not present", "User Error");
1317 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001318#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1319 gpu_number = find_display_gpu(gpu_number, gpu_count, physical_devices);
1320 if (gpu_number < 0) {
1321 printf("Cannot find any display!\n");
1322 fflush(stdout);
1323 exit(1);
1324 }
1325#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00001326 /* Try to auto select most suitable device */
1327 if (gpu_number == -1) {
1328 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1329 memset(count_device_type, 0, sizeof(count_device_type));
1330
1331 for (uint32_t i = 0; i < gpu_count; i++) {
1332 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1333 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1334 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1335 }
1336
1337 const vk::PhysicalDeviceType device_type_preference[] = {
1338 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1339 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1340 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1341 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1342 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1343 search_for_device_type = device_type_preference[i];
1344 break;
1345 }
1346 }
1347
1348 for (uint32_t i = 0; i < gpu_count; i++) {
1349 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1350 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1351 gpu_number = i;
1352 break;
1353 }
1354 }
1355 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001356#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00001357 assert(gpu_number >= 0);
1358 gpu = physical_devices[gpu_number];
1359 {
1360 auto physicalDeviceProperties = gpu.getProperties();
1361 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1362 to_string(physicalDeviceProperties.deviceType).c_str());
1363 }
1364 physical_devices.reset();
1365
Dave Houlton5fa47912018-02-16 11:02:26 -07001366 /* Look for device extensions */
1367 uint32_t device_extension_count = 0;
1368 vk::Bool32 swapchainExtFound = VK_FALSE;
1369 enabled_extension_count = 0;
1370 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001371
Mike Schuchardt7510c832018-10-29 13:23:08 -07001372 result =
1373 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001374 VERIFY(result == vk::Result::eSuccess);
1375
1376 if (device_extension_count > 0) {
1377 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1378 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001379 VERIFY(result == vk::Result::eSuccess);
1380
Dave Houlton5fa47912018-02-16 11:02:26 -07001381 for (uint32_t i = 0; i < device_extension_count; i++) {
1382 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1383 swapchainExtFound = 1;
1384 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001385 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001386 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1387 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001388 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001389 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001390 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001391 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001392
Dave Houlton5fa47912018-02-16 11:02:26 -07001393 if (!swapchainExtFound) {
1394 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1395 " extension.\n\n"
1396 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1397 "Please look at the Getting Started guide for additional information.\n",
1398 "vkCreateInstance Failure");
1399 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001400
Dave Houlton5fa47912018-02-16 11:02:26 -07001401 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001402
Dave Houlton5fa47912018-02-16 11:02:26 -07001403 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001404 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001405 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001406
Dave Houlton5fa47912018-02-16 11:02:26 -07001407 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1408 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001409
Dave Houlton5fa47912018-02-16 11:02:26 -07001410 // Query fine-grained feature support for this device.
1411 // If app has specific feature requirements it should check supported
1412 // features based on this query
1413 vk::PhysicalDeviceFeatures physDevFeatures;
1414 gpu.getFeatures(&physDevFeatures);
1415}
1416
Tony-LunarG6cebf142019-09-11 14:32:23 -06001417void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001418// Create a WSI surface for the window:
1419#if defined(VK_USE_PLATFORM_WIN32_KHR)
1420 {
1421 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1422
1423 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1424 VERIFY(result == vk::Result::eSuccess);
1425 }
1426#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1427 {
1428 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1429
1430 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1431 VERIFY(result == vk::Result::eSuccess);
1432 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001433#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1434 {
1435 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1436
1437 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1438 VERIFY(result == vk::Result::eSuccess);
1439 }
1440#elif defined(VK_USE_PLATFORM_XCB_KHR)
1441 {
1442 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1443
1444 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1445 VERIFY(result == vk::Result::eSuccess);
1446 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001447#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1448 {
1449 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1450
1451 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1452 VERIFY(result == vk::Result::eSuccess);
1453 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001454#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001455 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001456 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001457
Bill Hollings0a0625a2019-07-15 17:39:18 -04001458 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001459 VERIFY(result == vk::Result::eSuccess);
1460 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001461#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1462 {
1463 auto result = create_display_surface();
1464 VERIFY(result == vk::Result::eSuccess);
1465 }
1466#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001467}
1468
1469void Demo::init_vk_swapchain() {
1470 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001471 // Iterate over each queue to learn whether it supports presenting:
1472 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1473 for (uint32_t i = 0; i < queue_family_count; i++) {
1474 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1475 }
1476
1477 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1478 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1479 for (uint32_t i = 0; i < queue_family_count; i++) {
1480 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1481 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1482 graphicsQueueFamilyIndex = i;
1483 }
1484
1485 if (supportsPresent[i] == VK_TRUE) {
1486 graphicsQueueFamilyIndex = i;
1487 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001488 break;
1489 }
1490 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001491 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001492
Dave Houlton5fa47912018-02-16 11:02:26 -07001493 if (presentQueueFamilyIndex == UINT32_MAX) {
1494 // If didn't find a queue that supports both graphics and present,
1495 // then
1496 // find a separate present queue.
1497 for (uint32_t i = 0; i < queue_family_count; ++i) {
1498 if (supportsPresent[i] == VK_TRUE) {
1499 presentQueueFamilyIndex = i;
1500 break;
1501 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001502 }
1503 }
1504
Dave Houlton5fa47912018-02-16 11:02:26 -07001505 // Generate error if could not find both a graphics and a present queue
1506 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1507 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1508 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001509
Dave Houlton5fa47912018-02-16 11:02:26 -07001510 graphics_queue_family_index = graphicsQueueFamilyIndex;
1511 present_queue_family_index = presentQueueFamilyIndex;
1512 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001513
Dave Houlton5fa47912018-02-16 11:02:26 -07001514 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001515
Dave Houlton5fa47912018-02-16 11:02:26 -07001516 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1517 if (!separate_present_queue) {
1518 present_queue = graphics_queue;
1519 } else {
1520 device.getQueue(present_queue_family_index, 0, &present_queue);
1521 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001522
Dave Houlton5fa47912018-02-16 11:02:26 -07001523 // Get the list of VkFormat's that are supported:
1524 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001525 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001526 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001527
Dave Houlton5fa47912018-02-16 11:02:26 -07001528 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1529 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1530 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001531
Dave Houlton5fa47912018-02-16 11:02:26 -07001532 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1533 // the surface has no preferred format. Otherwise, at least one
1534 // supported format will be returned.
1535 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1536 format = vk::Format::eB8G8R8A8Unorm;
1537 } else {
1538 assert(formatCount >= 1);
1539 format = surfFormats[0].format;
1540 }
1541 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001542
Dave Houlton5fa47912018-02-16 11:02:26 -07001543 quit = false;
1544 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001545
Dave Houlton5fa47912018-02-16 11:02:26 -07001546 // Create semaphores to synchronize acquiring presentable buffers before
1547 // rendering and waiting for drawing to be complete before presenting
1548 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001549
Dave Houlton5fa47912018-02-16 11:02:26 -07001550 // Create fences that we can use to throttle if we get too far
1551 // ahead of the image presents
1552 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1553 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1554 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1555 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001556
Dave Houlton5fa47912018-02-16 11:02:26 -07001557 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1558 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001559
Dave Houlton5fa47912018-02-16 11:02:26 -07001560 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1561 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001562
Dave Houlton5fa47912018-02-16 11:02:26 -07001563 if (separate_present_queue) {
1564 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001565 VERIFY(result == vk::Result::eSuccess);
1566 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001567 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001568 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001569
Dave Houlton5fa47912018-02-16 11:02:26 -07001570 // Get Memory information and properties
1571 gpu.getMemoryProperties(&memory_properties);
1572}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001573
Dave Houlton5fa47912018-02-16 11:02:26 -07001574void Demo::prepare() {
1575 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1576 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1577 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001578
Dave Houlton5fa47912018-02-16 11:02:26 -07001579 auto const cmd = vk::CommandBufferAllocateInfo()
1580 .setCommandPool(cmd_pool)
1581 .setLevel(vk::CommandBufferLevel::ePrimary)
1582 .setCommandBufferCount(1);
1583
1584 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1585 VERIFY(result == vk::Result::eSuccess);
1586
1587 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1588
1589 result = this->cmd.begin(&cmd_buf_info);
1590 VERIFY(result == vk::Result::eSuccess);
1591
1592 prepare_buffers();
1593 prepare_depth();
1594 prepare_textures();
1595 prepare_cube_data_buffers();
1596
1597 prepare_descriptor_layout();
1598 prepare_render_pass();
1599 prepare_pipeline();
1600
1601 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1602 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1603 VERIFY(result == vk::Result::eSuccess);
1604 }
1605
1606 if (separate_present_queue) {
1607 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1608
1609 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1610 VERIFY(result == vk::Result::eSuccess);
1611
1612 auto const present_cmd = vk::CommandBufferAllocateInfo()
1613 .setCommandPool(present_cmd_pool)
1614 .setLevel(vk::CommandBufferLevel::ePrimary)
1615 .setCommandBufferCount(1);
1616
1617 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1618 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1619 VERIFY(result == vk::Result::eSuccess);
1620
1621 build_image_ownership_cmd(i);
1622 }
1623 }
1624
1625 prepare_descriptor_pool();
1626 prepare_descriptor_set();
1627
1628 prepare_framebuffers();
1629
1630 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1631 current_buffer = i;
1632 draw_build_cmd(swapchain_image_resources[i].cmd);
1633 }
1634
1635 /*
1636 * Prepare functions above may generate pipeline commands
1637 * that need to be flushed before beginning the render loop.
1638 */
1639 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001640 if (staging_texture.buffer) {
1641 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001642 }
1643
1644 current_buffer = 0;
1645 prepared = true;
1646}
1647
1648void Demo::prepare_buffers() {
1649 vk::SwapchainKHR oldSwapchain = swapchain;
1650
1651 // Check the surface capabilities and formats
1652 vk::SurfaceCapabilitiesKHR surfCapabilities;
1653 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1654 VERIFY(result == vk::Result::eSuccess);
1655
1656 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001657 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001658 VERIFY(result == vk::Result::eSuccess);
1659
1660 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1661 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1662 VERIFY(result == vk::Result::eSuccess);
1663
1664 vk::Extent2D swapchainExtent;
1665 // width and height are either both -1, or both not -1.
1666 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1667 // If the surface size is undefined, the size is set to
1668 // the size of the images requested.
1669 swapchainExtent.width = width;
1670 swapchainExtent.height = height;
1671 } else {
1672 // If the surface size is defined, the swap chain size must match
1673 swapchainExtent = surfCapabilities.currentExtent;
1674 width = surfCapabilities.currentExtent.width;
1675 height = surfCapabilities.currentExtent.height;
1676 }
1677
1678 // The FIFO present mode is guaranteed by the spec to be supported
1679 // and to have no tearing. It's a great default present mode to use.
1680 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1681
1682 // There are times when you may wish to use another present mode. The
1683 // following code shows how to select them, and the comments provide some
1684 // reasons you may wish to use them.
1685 //
1686 // It should be noted that Vulkan 1.0 doesn't provide a method for
1687 // synchronizing rendering with the presentation engine's display. There
1688 // is a method provided for throttling rendering with the display, but
1689 // there are some presentation engines for which this method will not work.
1690 // If an application doesn't throttle its rendering, and if it renders much
1691 // faster than the refresh rate of the display, this can waste power on
1692 // mobile devices. That is because power is being spent rendering images
1693 // that may never be seen.
1694
1695 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1696 // about
1697 // tearing, or have some way of synchronizing their rendering with the
1698 // display.
1699 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1700 // generally render a new presentable image every refresh cycle, but are
1701 // occasionally early. In this case, the application wants the new
1702 // image
1703 // to be displayed instead of the previously-queued-for-presentation
1704 // image
1705 // that has not yet been displayed.
1706 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1707 // render a new presentable image every refresh cycle, but are
1708 // occasionally
1709 // late. In this case (perhaps because of stuttering/latency concerns),
1710 // the application wants the late image to be immediately displayed,
1711 // even
1712 // though that may mean some tearing.
1713
1714 if (presentMode != swapchainPresentMode) {
1715 for (size_t i = 0; i < presentModeCount; ++i) {
1716 if (presentModes[i] == presentMode) {
1717 swapchainPresentMode = presentMode;
1718 break;
1719 }
1720 }
1721 }
1722
1723 if (swapchainPresentMode != presentMode) {
1724 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1725 }
1726
1727 // Determine the number of VkImages to use in the swap chain.
1728 // Application desires to acquire 3 images at a time for triple
1729 // buffering
1730 uint32_t desiredNumOfSwapchainImages = 3;
1731 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1732 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1733 }
1734
1735 // If maxImageCount is 0, we can ask for as many images as we want,
1736 // otherwise
1737 // we're limited to maxImageCount
1738 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1739 // Application must settle for fewer images than desired:
1740 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1741 }
1742
1743 vk::SurfaceTransformFlagBitsKHR preTransform;
1744 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1745 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1746 } else {
1747 preTransform = surfCapabilities.currentTransform;
1748 }
1749
1750 // Find a supported composite alpha mode - one of these is guaranteed to be set
1751 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1752 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1753 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1754 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1755 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1756 vk::CompositeAlphaFlagBitsKHR::eInherit,
1757 };
1758 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1759 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1760 compositeAlpha = compositeAlphaFlags[i];
1761 break;
1762 }
1763 }
1764
1765 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1766 .setSurface(surface)
1767 .setMinImageCount(desiredNumOfSwapchainImages)
1768 .setImageFormat(format)
1769 .setImageColorSpace(color_space)
1770 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1771 .setImageArrayLayers(1)
1772 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1773 .setImageSharingMode(vk::SharingMode::eExclusive)
1774 .setQueueFamilyIndexCount(0)
1775 .setPQueueFamilyIndices(nullptr)
1776 .setPreTransform(preTransform)
1777 .setCompositeAlpha(compositeAlpha)
1778 .setPresentMode(swapchainPresentMode)
1779 .setClipped(true)
1780 .setOldSwapchain(oldSwapchain);
1781
1782 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1783 VERIFY(result == vk::Result::eSuccess);
1784
1785 // If we just re-created an existing swapchain, we should destroy the
1786 // old
1787 // swapchain at this point.
1788 // Note: destroying the swapchain also cleans up all its associated
1789 // presentable images once the platform is done with them.
1790 if (oldSwapchain) {
1791 device.destroySwapchainKHR(oldSwapchain, nullptr);
1792 }
1793
Mike Schuchardt7510c832018-10-29 13:23:08 -07001794 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001795 VERIFY(result == vk::Result::eSuccess);
1796
1797 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1798 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1799 VERIFY(result == vk::Result::eSuccess);
1800
1801 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1802
1803 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1804 auto color_image_view = vk::ImageViewCreateInfo()
1805 .setViewType(vk::ImageViewType::e2D)
1806 .setFormat(format)
1807 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1808
1809 swapchain_image_resources[i].image = swapchainImages[i];
1810
1811 color_image_view.image = swapchain_image_resources[i].image;
1812
1813 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1814 VERIFY(result == vk::Result::eSuccess);
1815 }
1816}
1817
1818void Demo::prepare_cube_data_buffers() {
1819 mat4x4 VP;
1820 mat4x4_mul(VP, projection_matrix, view_matrix);
1821
1822 mat4x4 MVP;
1823 mat4x4_mul(MVP, VP, model_matrix);
1824
1825 vktexcube_vs_uniform data;
1826 memcpy(data.mvp, MVP, sizeof(MVP));
1827 // dumpMatrix("MVP", MVP)
1828
1829 for (int32_t i = 0; i < 12 * 3; i++) {
1830 data.position[i][0] = g_vertex_buffer_data[i * 3];
1831 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1832 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1833 data.position[i][3] = 1.0f;
1834 data.attr[i][0] = g_uv_buffer_data[2 * i];
1835 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1836 data.attr[i][2] = 0;
1837 data.attr[i][3] = 0;
1838 }
1839
1840 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1841
1842 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1843 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001844 VERIFY(result == vk::Result::eSuccess);
1845
1846 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001847 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001848
Dave Houlton5fa47912018-02-16 11:02:26 -07001849 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001850
Dave Houlton5fa47912018-02-16 11:02:26 -07001851 bool const pass = memory_type_from_properties(
1852 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1853 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001854 VERIFY(pass);
1855
Dave Houlton5fa47912018-02-16 11:02:26 -07001856 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001857 VERIFY(result == vk::Result::eSuccess);
1858
Tony-LunarG37af49f2019-12-19 12:04:19 -07001859 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1860 &swapchain_image_resources[i].uniform_memory_ptr);
1861 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001862
Tony-LunarG37af49f2019-12-19 12:04:19 -07001863 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001864
1865 result =
1866 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001867 VERIFY(result == vk::Result::eSuccess);
1868 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001869}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001870
Dave Houlton5fa47912018-02-16 11:02:26 -07001871void Demo::prepare_depth() {
1872 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001873
Dave Houlton5fa47912018-02-16 11:02:26 -07001874 auto const image = vk::ImageCreateInfo()
1875 .setImageType(vk::ImageType::e2D)
1876 .setFormat(depth.format)
1877 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1878 .setMipLevels(1)
1879 .setArrayLayers(1)
1880 .setSamples(vk::SampleCountFlagBits::e1)
1881 .setTiling(vk::ImageTiling::eOptimal)
1882 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1883 .setSharingMode(vk::SharingMode::eExclusive)
1884 .setQueueFamilyIndexCount(0)
1885 .setPQueueFamilyIndices(nullptr)
1886 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001887
Dave Houlton5fa47912018-02-16 11:02:26 -07001888 auto result = device.createImage(&image, nullptr, &depth.image);
1889 VERIFY(result == vk::Result::eSuccess);
1890
1891 vk::MemoryRequirements mem_reqs;
1892 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1893
1894 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1895 depth.mem_alloc.setMemoryTypeIndex(0);
1896
1897 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1898 &depth.mem_alloc.memoryTypeIndex);
1899 VERIFY(pass);
1900
1901 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1902 VERIFY(result == vk::Result::eSuccess);
1903
1904 result = device.bindImageMemory(depth.image, depth.mem, 0);
1905 VERIFY(result == vk::Result::eSuccess);
1906
1907 auto const view = vk::ImageViewCreateInfo()
1908 .setImage(depth.image)
1909 .setViewType(vk::ImageViewType::e2D)
1910 .setFormat(depth.format)
1911 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1912 result = device.createImageView(&view, nullptr, &depth.view);
1913 VERIFY(result == vk::Result::eSuccess);
1914}
1915
1916void Demo::prepare_descriptor_layout() {
1917 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1918 .setBinding(0)
1919 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1920 .setDescriptorCount(1)
1921 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1922 .setPImmutableSamplers(nullptr),
1923 vk::DescriptorSetLayoutBinding()
1924 .setBinding(1)
1925 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1926 .setDescriptorCount(texture_count)
1927 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1928 .setPImmutableSamplers(nullptr)};
1929
1930 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1931
1932 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1933 VERIFY(result == vk::Result::eSuccess);
1934
1935 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1936
1937 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1938 VERIFY(result == vk::Result::eSuccess);
1939}
1940
1941void Demo::prepare_descriptor_pool() {
1942 vk::DescriptorPoolSize const poolSizes[2] = {
1943 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1944 vk::DescriptorPoolSize()
1945 .setType(vk::DescriptorType::eCombinedImageSampler)
1946 .setDescriptorCount(swapchainImageCount * texture_count)};
1947
1948 auto const descriptor_pool =
1949 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1950
1951 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1952 VERIFY(result == vk::Result::eSuccess);
1953}
1954
1955void Demo::prepare_descriptor_set() {
1956 auto const alloc_info =
1957 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1958
1959 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1960
1961 vk::DescriptorImageInfo tex_descs[texture_count];
1962 for (uint32_t i = 0; i < texture_count; i++) {
1963 tex_descs[i].setSampler(textures[i].sampler);
1964 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001965 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001966 }
1967
1968 vk::WriteDescriptorSet writes[2];
1969
1970 writes[0].setDescriptorCount(1);
1971 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1972 writes[0].setPBufferInfo(&buffer_info);
1973
1974 writes[1].setDstBinding(1);
1975 writes[1].setDescriptorCount(texture_count);
1976 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1977 writes[1].setPImageInfo(tex_descs);
1978
1979 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1980 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001981 VERIFY(result == vk::Result::eSuccess);
1982
Dave Houlton5fa47912018-02-16 11:02:26 -07001983 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1984 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1985 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1986 device.updateDescriptorSets(2, writes, 0, nullptr);
1987 }
1988}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001989
Dave Houlton5fa47912018-02-16 11:02:26 -07001990void Demo::prepare_framebuffers() {
1991 vk::ImageView attachments[2];
1992 attachments[1] = depth.view;
1993
1994 auto const fb_info = vk::FramebufferCreateInfo()
1995 .setRenderPass(render_pass)
1996 .setAttachmentCount(2)
1997 .setPAttachments(attachments)
1998 .setWidth((uint32_t)width)
1999 .setHeight((uint32_t)height)
2000 .setLayers(1);
2001
2002 for (uint32_t i = 0; i < swapchainImageCount; i++) {
2003 attachments[0] = swapchain_image_resources[i].view;
2004 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002005 VERIFY(result == vk::Result::eSuccess);
2006 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002007}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002008
Dave Houlton5fa47912018-02-16 11:02:26 -07002009vk::ShaderModule Demo::prepare_fs() {
2010 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002011#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07002012 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002013
Dave Houlton5fa47912018-02-16 11:02:26 -07002014 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002015
Dave Houlton5fa47912018-02-16 11:02:26 -07002016 return frag_shader_module;
2017}
2018
2019void Demo::prepare_pipeline() {
2020 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
2021 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
2022 VERIFY(result == vk::Result::eSuccess);
2023
2024 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
2025 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2026 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2027
2028 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2029
2030 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2031
2032 // TODO: Where are pViewports and pScissors set?
2033 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2034
2035 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2036 .setDepthClampEnable(VK_FALSE)
2037 .setRasterizerDiscardEnable(VK_FALSE)
2038 .setPolygonMode(vk::PolygonMode::eFill)
2039 .setCullMode(vk::CullModeFlagBits::eBack)
2040 .setFrontFace(vk::FrontFace::eCounterClockwise)
2041 .setDepthBiasEnable(VK_FALSE)
2042 .setLineWidth(1.0f);
2043
2044 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2045
2046 auto const stencilOp =
2047 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2048
2049 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2050 .setDepthTestEnable(VK_TRUE)
2051 .setDepthWriteEnable(VK_TRUE)
2052 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2053 .setDepthBoundsTestEnable(VK_FALSE)
2054 .setStencilTestEnable(VK_FALSE)
2055 .setFront(stencilOp)
2056 .setBack(stencilOp);
2057
2058 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2059 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2060 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2061
2062 auto const colorBlendInfo =
2063 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2064
2065 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2066
2067 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2068
2069 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2070 .setStageCount(2)
2071 .setPStages(shaderStageInfo)
2072 .setPVertexInputState(&vertexInputInfo)
2073 .setPInputAssemblyState(&inputAssemblyInfo)
2074 .setPViewportState(&viewportInfo)
2075 .setPRasterizationState(&rasterizationInfo)
2076 .setPMultisampleState(&multisampleInfo)
2077 .setPDepthStencilState(&depthStencilInfo)
2078 .setPColorBlendState(&colorBlendInfo)
2079 .setPDynamicState(&dynamicStateInfo)
2080 .setLayout(pipeline_layout)
2081 .setRenderPass(render_pass);
2082
2083 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2084 VERIFY(result == vk::Result::eSuccess);
2085
2086 device.destroyShaderModule(frag_shader_module, nullptr);
2087 device.destroyShaderModule(vert_shader_module, nullptr);
2088}
2089
2090void Demo::prepare_render_pass() {
2091 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2092 // because at the start of the renderpass, we don't care about their contents.
2093 // At the start of the subpass, the color attachment's layout will be transitioned
2094 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2095 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2096 // the renderpass, the color attachment's layout will be transitioned to
2097 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2098 // the renderpass, no barriers are necessary.
2099 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2100 .setFormat(format)
2101 .setSamples(vk::SampleCountFlagBits::e1)
2102 .setLoadOp(vk::AttachmentLoadOp::eClear)
2103 .setStoreOp(vk::AttachmentStoreOp::eStore)
2104 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2105 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2106 .setInitialLayout(vk::ImageLayout::eUndefined)
2107 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2108 vk::AttachmentDescription()
2109 .setFormat(depth.format)
2110 .setSamples(vk::SampleCountFlagBits::e1)
2111 .setLoadOp(vk::AttachmentLoadOp::eClear)
2112 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2113 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2114 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2115 .setInitialLayout(vk::ImageLayout::eUndefined)
2116 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2117
2118 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2119
2120 auto const depth_reference =
2121 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2122
2123 auto const subpass = vk::SubpassDescription()
2124 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2125 .setInputAttachmentCount(0)
2126 .setPInputAttachments(nullptr)
2127 .setColorAttachmentCount(1)
2128 .setPColorAttachments(&color_reference)
2129 .setPResolveAttachments(nullptr)
2130 .setPDepthStencilAttachment(&depth_reference)
2131 .setPreserveAttachmentCount(0)
2132 .setPPreserveAttachments(nullptr);
2133
Tony-LunarG495604b2019-06-13 15:32:05 -06002134 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2135 vk::SubpassDependency const dependencies[2] = {
2136 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2137 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2138 .setDstSubpass(0)
2139 .setSrcStageMask(stages)
2140 .setDstStageMask(stages)
2141 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2142 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2143 .setDependencyFlags(vk::DependencyFlags()),
2144 vk::SubpassDependency() // Image layout transition
2145 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2146 .setDstSubpass(0)
2147 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2148 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2149 .setSrcAccessMask(vk::AccessFlagBits())
2150 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2151 .setDependencyFlags(vk::DependencyFlags()),
2152 };
2153
Dave Houlton5fa47912018-02-16 11:02:26 -07002154 auto const rp_info = vk::RenderPassCreateInfo()
2155 .setAttachmentCount(2)
2156 .setPAttachments(attachments)
2157 .setSubpassCount(1)
2158 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002159 .setDependencyCount(2)
2160 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002161
2162 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2163 VERIFY(result == vk::Result::eSuccess);
2164}
2165
2166vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2167 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2168
2169 vk::ShaderModule module;
2170 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2171 VERIFY(result == vk::Result::eSuccess);
2172
2173 return module;
2174}
2175
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002176void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2177 int32_t tex_width;
2178 int32_t tex_height;
2179
2180 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2181 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2182 }
2183
2184 tex_obj->tex_width = tex_width;
2185 tex_obj->tex_height = tex_height;
2186
2187 auto const buffer_create_info = vk::BufferCreateInfo()
2188 .setSize(tex_width * tex_height * 4)
2189 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2190 .setSharingMode(vk::SharingMode::eExclusive)
2191 .setQueueFamilyIndexCount(0)
2192 .setPQueueFamilyIndices(nullptr);
2193
2194 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2195 VERIFY(result == vk::Result::eSuccess);
2196
2197 vk::MemoryRequirements mem_reqs;
2198 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2199
2200 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2201 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2202
2203 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2204 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2205 VERIFY(pass == true);
2206
2207 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2208 VERIFY(result == vk::Result::eSuccess);
2209
2210 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2211 VERIFY(result == vk::Result::eSuccess);
2212
2213 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002214 layout.rowPitch = tex_width * 4;
2215 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2216 VERIFY(data.result == vk::Result::eSuccess);
2217
2218 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2219 fprintf(stderr, "Error loading texture: %s\n", filename);
2220 }
2221
2222 device.unmapMemory(tex_obj->mem);
2223}
2224
Dave Houlton5fa47912018-02-16 11:02:26 -07002225void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2226 vk::MemoryPropertyFlags required_props) {
2227 int32_t tex_width;
2228 int32_t tex_height;
2229 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2230 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002231 }
2232
Dave Houlton5fa47912018-02-16 11:02:26 -07002233 tex_obj->tex_width = tex_width;
2234 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002235
Dave Houlton5fa47912018-02-16 11:02:26 -07002236 auto const image_create_info = vk::ImageCreateInfo()
2237 .setImageType(vk::ImageType::e2D)
2238 .setFormat(vk::Format::eR8G8B8A8Unorm)
2239 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2240 .setMipLevels(1)
2241 .setArrayLayers(1)
2242 .setSamples(vk::SampleCountFlagBits::e1)
2243 .setTiling(tiling)
2244 .setUsage(usage)
2245 .setSharingMode(vk::SharingMode::eExclusive)
2246 .setQueueFamilyIndexCount(0)
2247 .setPQueueFamilyIndices(nullptr)
2248 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002249
Dave Houlton5fa47912018-02-16 11:02:26 -07002250 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2251 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002252
Dave Houlton5fa47912018-02-16 11:02:26 -07002253 vk::MemoryRequirements mem_reqs;
2254 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002255
Dave Houlton5fa47912018-02-16 11:02:26 -07002256 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2257 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002258
Dave Houlton5fa47912018-02-16 11:02:26 -07002259 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2260 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002261
Dave Houlton5fa47912018-02-16 11:02:26 -07002262 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2263 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002264
Dave Houlton5fa47912018-02-16 11:02:26 -07002265 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2266 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002267
Dave Houlton5fa47912018-02-16 11:02:26 -07002268 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2269 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2270 vk::SubresourceLayout layout;
2271 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002272
Dave Houlton5fa47912018-02-16 11:02:26 -07002273 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002274 VERIFY(data.result == vk::Result::eSuccess);
2275
Dave Houlton5fa47912018-02-16 11:02:26 -07002276 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2277 fprintf(stderr, "Error loading texture: %s\n", filename);
2278 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002279
Dave Houlton5fa47912018-02-16 11:02:26 -07002280 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002281 }
2282
Dave Houlton5fa47912018-02-16 11:02:26 -07002283 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2284}
2285
2286void Demo::prepare_textures() {
2287 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2288 vk::FormatProperties props;
2289 gpu.getFormatProperties(tex_format, &props);
2290
2291 for (uint32_t i = 0; i < texture_count; i++) {
2292 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2293 /* Device can texture using linear textures */
2294 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2295 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2296 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2297 // shader to run until layout transition completes
2298 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2299 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2300 vk::PipelineStageFlagBits::eFragmentShader);
2301 staging_texture.image = vk::Image();
2302 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2303 /* Must use staging buffer to copy linear texture to optimized */
2304
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002305 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002306
2307 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2308 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2309 vk::MemoryPropertyFlagBits::eDeviceLocal);
2310
Dave Houlton5fa47912018-02-16 11:02:26 -07002311 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2312 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2313 vk::PipelineStageFlagBits::eTransfer);
2314
2315 auto const subresource = vk::ImageSubresourceLayers()
2316 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2317 .setMipLevel(0)
2318 .setBaseArrayLayer(0)
2319 .setLayerCount(1);
2320
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002321 auto const copy_region =
2322 vk::BufferImageCopy()
2323 .setBufferOffset(0)
2324 .setBufferRowLength(staging_texture.tex_width)
2325 .setBufferImageHeight(staging_texture.tex_height)
2326 .setImageSubresource(subresource)
2327 .setImageOffset({0, 0, 0})
2328 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002329
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002330 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002331
2332 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2333 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2334 vk::PipelineStageFlagBits::eFragmentShader);
2335 } else {
2336 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002337 }
2338
Dave Houlton5fa47912018-02-16 11:02:26 -07002339 auto const samplerInfo = vk::SamplerCreateInfo()
2340 .setMagFilter(vk::Filter::eNearest)
2341 .setMinFilter(vk::Filter::eNearest)
2342 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2343 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2344 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2345 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2346 .setMipLodBias(0.0f)
2347 .setAnisotropyEnable(VK_FALSE)
2348 .setMaxAnisotropy(1)
2349 .setCompareEnable(VK_FALSE)
2350 .setCompareOp(vk::CompareOp::eNever)
2351 .setMinLod(0.0f)
2352 .setMaxLod(0.0f)
2353 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2354 .setUnnormalizedCoordinates(VK_FALSE);
2355
2356 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2357 VERIFY(result == vk::Result::eSuccess);
2358
2359 auto const viewInfo = vk::ImageViewCreateInfo()
2360 .setImage(textures[i].image)
2361 .setViewType(vk::ImageViewType::e2D)
2362 .setFormat(tex_format)
2363 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2364
2365 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2366 VERIFY(result == vk::Result::eSuccess);
2367 }
2368}
2369
2370vk::ShaderModule Demo::prepare_vs() {
2371 const uint32_t vertShaderCode[] = {
2372#include "cube.vert.inc"
2373 };
2374
2375 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2376
2377 return vert_shader_module;
2378}
2379
2380void Demo::resize() {
2381 uint32_t i;
2382
2383 // Don't react to resize until after first initialization.
2384 if (!prepared) {
2385 return;
2386 }
2387
2388 // In order to properly resize the window, we must re-create the
2389 // swapchain
2390 // AND redo the command buffers, etc.
2391 //
2392 // First, perform part of the cleanup() function:
2393 prepared = false;
2394 auto result = device.waitIdle();
2395 VERIFY(result == vk::Result::eSuccess);
2396
2397 for (i = 0; i < swapchainImageCount; i++) {
2398 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2399 }
2400
2401 device.destroyDescriptorPool(desc_pool, nullptr);
2402
2403 device.destroyPipeline(pipeline, nullptr);
2404 device.destroyPipelineCache(pipelineCache, nullptr);
2405 device.destroyRenderPass(render_pass, nullptr);
2406 device.destroyPipelineLayout(pipeline_layout, nullptr);
2407 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2408
2409 for (i = 0; i < texture_count; i++) {
2410 device.destroyImageView(textures[i].view, nullptr);
2411 device.destroyImage(textures[i].image, nullptr);
2412 device.freeMemory(textures[i].mem, nullptr);
2413 device.destroySampler(textures[i].sampler, nullptr);
2414 }
2415
2416 device.destroyImageView(depth.view, nullptr);
2417 device.destroyImage(depth.image, nullptr);
2418 device.freeMemory(depth.mem, nullptr);
2419
2420 for (i = 0; i < swapchainImageCount; i++) {
2421 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002422 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002423 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002424 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002425 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2426 }
2427
2428 device.destroyCommandPool(cmd_pool, nullptr);
2429 if (separate_present_queue) {
2430 device.destroyCommandPool(present_cmd_pool, nullptr);
2431 }
2432
2433 // Second, re-perform the prepare() function, which will re-create the
2434 // swapchain.
2435 prepare();
2436}
2437
2438void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2439 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2440 assert(cmd);
2441
2442 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2443 vk::AccessFlags flags;
2444
2445 switch (layout) {
2446 case vk::ImageLayout::eTransferDstOptimal:
2447 // Make sure anything that was copying from this image has
2448 // completed
2449 flags = vk::AccessFlagBits::eTransferWrite;
2450 break;
2451 case vk::ImageLayout::eColorAttachmentOptimal:
2452 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2453 break;
2454 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2455 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2456 break;
2457 case vk::ImageLayout::eShaderReadOnlyOptimal:
2458 // Make sure any Copy or CPU writes to image are flushed
2459 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2460 break;
2461 case vk::ImageLayout::eTransferSrcOptimal:
2462 flags = vk::AccessFlagBits::eTransferRead;
2463 break;
2464 case vk::ImageLayout::ePresentSrcKHR:
2465 flags = vk::AccessFlagBits::eMemoryRead;
2466 break;
2467 default:
2468 break;
2469 }
2470
2471 return flags;
2472 };
2473
2474 auto const barrier = vk::ImageMemoryBarrier()
2475 .setSrcAccessMask(srcAccessMask)
2476 .setDstAccessMask(DstAccessMask(newLayout))
2477 .setOldLayout(oldLayout)
2478 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002479 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2480 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002481 .setImage(image)
2482 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2483
2484 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2485}
2486
2487void Demo::update_data_buffer() {
2488 mat4x4 VP;
2489 mat4x4_mul(VP, projection_matrix, view_matrix);
2490
2491 // Rotate around the Y axis
2492 mat4x4 Model;
2493 mat4x4_dup(Model, model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -07002494 mat4x4_rotate_Y(model_matrix, Model, (float)degreesToRadians(spin_angle));
2495 mat4x4_orthonormalize(model_matrix, model_matrix);
Dave Houlton5fa47912018-02-16 11:02:26 -07002496
2497 mat4x4 MVP;
2498 mat4x4_mul(MVP, VP, model_matrix);
2499
Tony-LunarG37af49f2019-12-19 12:04:19 -07002500 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002501}
2502
Karl Schultzb7940402018-05-29 13:09:22 -06002503/* Convert ppm image data from header file into RGBA texture image */
2504#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002505bool 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 -06002506 (void)filename;
2507 char *cPtr;
2508 cPtr = (char *)lunarg_ppm;
2509 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002510 return false;
2511 }
Karl Schultzb7940402018-05-29 13:09:22 -06002512 while (strncmp(cPtr++, "\n", 1))
2513 ;
2514 sscanf(cPtr, "%u %u", width, height);
2515 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002516 return true;
2517 }
Karl Schultzb7940402018-05-29 13:09:22 -06002518 while (strncmp(cPtr++, "\n", 1))
2519 ;
2520 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002521 return false;
2522 }
Karl Schultzb7940402018-05-29 13:09:22 -06002523 while (strncmp(cPtr++, "\n", 1))
2524 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002525 for (int y = 0; y < *height; y++) {
2526 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002527 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002528 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002529 rowPtr[3] = 255; /* Alpha of 1 */
2530 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002531 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002532 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002533 rgba_data += layout->rowPitch;
2534 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002535 return true;
2536}
2537
2538bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2539 // Search memtypes to find first index with those properties
2540 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2541 if ((typeBits & 1) == 1) {
2542 // Type is available, does it match user properties?
2543 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2544 *typeIndex = i;
2545 return true;
2546 }
2547 }
2548 typeBits >>= 1;
2549 }
2550
2551 // No memory types matched, return failure
2552 return false;
2553}
2554
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002555#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002556void Demo::run() {
2557 if (!prepared) {
2558 return;
2559 }
2560
2561 draw();
2562 curFrame++;
2563
Petr Krausd88e4e52019-01-23 18:45:04 +01002564 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002565 PostQuitMessage(validation_error);
2566 }
2567}
2568
2569void Demo::create_window() {
2570 WNDCLASSEX win_class;
2571
2572 // Initialize the window class structure:
2573 win_class.cbSize = sizeof(WNDCLASSEX);
2574 win_class.style = CS_HREDRAW | CS_VREDRAW;
2575 win_class.lpfnWndProc = WndProc;
2576 win_class.cbClsExtra = 0;
2577 win_class.cbWndExtra = 0;
2578 win_class.hInstance = connection; // hInstance
2579 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2580 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2581 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2582 win_class.lpszMenuName = nullptr;
2583 win_class.lpszClassName = name;
2584 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2585
2586 // Register window class:
2587 if (!RegisterClassEx(&win_class)) {
2588 // It didn't work, so try to give a useful error:
2589 printf("Unexpected error trying to start the application!\n");
2590 fflush(stdout);
2591 exit(1);
2592 }
2593
2594 // Create window with the registered class:
2595 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2596 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2597 window = CreateWindowEx(0,
2598 name, // class name
2599 name, // app name
2600 WS_OVERLAPPEDWINDOW | // window style
2601 WS_VISIBLE | WS_SYSMENU,
2602 100, 100, // x/y coords
2603 wr.right - wr.left, // width
2604 wr.bottom - wr.top, // height
2605 nullptr, // handle to parent
2606 nullptr, // handle to menu
2607 connection, // hInstance
2608 nullptr); // no extra parameters
2609
2610 if (!window) {
2611 // It didn't work, so try to give a useful error:
2612 printf("Cannot create a window in which to draw!\n");
2613 fflush(stdout);
2614 exit(1);
2615 }
2616
2617 // Window client area size must be at least 1 pixel high, to prevent
2618 // crash.
2619 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2620 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2621}
2622#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2623
2624void Demo::create_xlib_window() {
2625 const char *display_envar = getenv("DISPLAY");
2626 if (display_envar == nullptr || display_envar[0] == '\0') {
2627 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2628 fflush(stdout);
2629 exit(1);
2630 }
2631
2632 XInitThreads();
2633 display = XOpenDisplay(nullptr);
2634 long visualMask = VisualScreenMask;
2635 int numberOfVisuals;
2636 XVisualInfo vInfoTemplate = {};
2637 vInfoTemplate.screen = DefaultScreen(display);
2638 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2639
2640 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2641
2642 XSetWindowAttributes windowAttributes = {};
2643 windowAttributes.colormap = colormap;
2644 windowAttributes.background_pixel = 0xFFFFFFFF;
2645 windowAttributes.border_pixel = 0;
2646 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2647
2648 xlib_window =
2649 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2650 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2651
2652 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2653 XMapWindow(display, xlib_window);
2654 XFlush(display);
2655 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2656}
2657
2658void Demo::handle_xlib_event(const XEvent *event) {
2659 switch (event->type) {
2660 case ClientMessage:
2661 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2662 quit = true;
2663 }
2664 break;
2665 case KeyPress:
2666 switch (event->xkey.keycode) {
2667 case 0x9: // Escape
2668 quit = true;
2669 break;
2670 case 0x71: // left arrow key
2671 spin_angle -= spin_increment;
2672 break;
2673 case 0x72: // right arrow key
2674 spin_angle += spin_increment;
2675 break;
2676 case 0x41: // space bar
2677 pause = !pause;
2678 break;
2679 }
2680 break;
2681 case ConfigureNotify:
2682 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2683 width = event->xconfigure.width;
2684 height = event->xconfigure.height;
2685 resize();
2686 }
2687 break;
2688 default:
2689 break;
2690 }
2691}
2692
2693void Demo::run_xlib() {
2694 while (!quit) {
2695 XEvent event;
2696
2697 if (pause) {
2698 XNextEvent(display, &event);
2699 handle_xlib_event(&event);
2700 }
2701 while (XPending(display) > 0) {
2702 XNextEvent(display, &event);
2703 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002704 }
2705
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002706 draw();
2707 curFrame++;
2708
Dave Houlton5fa47912018-02-16 11:02:26 -07002709 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2710 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002711 }
2712 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002713}
Tony Barbour153cb062016-12-07 13:43:36 -07002714#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002715
Dave Houlton5fa47912018-02-16 11:02:26 -07002716void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2717 uint8_t event_code = event->response_type & 0x7f;
2718 switch (event_code) {
2719 case XCB_EXPOSE:
2720 // TODO: Resize window
2721 break;
2722 case XCB_CLIENT_MESSAGE:
2723 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2724 quit = true;
2725 }
2726 break;
2727 case XCB_KEY_RELEASE: {
2728 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002729
Dave Houlton5fa47912018-02-16 11:02:26 -07002730 switch (key->detail) {
2731 case 0x9: // Escape
2732 quit = true;
2733 break;
2734 case 0x71: // left arrow key
2735 spin_angle -= spin_increment;
2736 break;
2737 case 0x72: // right arrow key
2738 spin_angle += spin_increment;
2739 break;
2740 case 0x41: // space bar
2741 pause = !pause;
2742 break;
2743 }
2744 } break;
2745 case XCB_CONFIGURE_NOTIFY: {
2746 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2747 if ((width != cfg->width) || (height != cfg->height)) {
2748 width = cfg->width;
2749 height = cfg->height;
2750 resize();
2751 }
2752 } break;
2753 default:
2754 break;
2755 }
2756}
2757
2758void Demo::run_xcb() {
2759 xcb_flush(connection);
2760
2761 while (!quit) {
2762 xcb_generic_event_t *event;
2763
2764 if (pause) {
2765 event = xcb_wait_for_event(connection);
2766 } else {
2767 event = xcb_poll_for_event(connection);
2768 }
2769 while (event) {
2770 handle_xcb_event(event);
2771 free(event);
2772 event = xcb_poll_for_event(connection);
2773 }
2774
2775 draw();
2776 curFrame++;
2777 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2778 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002779 }
2780 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002781}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002782
Dave Houlton5fa47912018-02-16 11:02:26 -07002783void Demo::create_xcb_window() {
2784 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002785
Dave Houlton5fa47912018-02-16 11:02:26 -07002786 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002787
Dave Houlton5fa47912018-02-16 11:02:26 -07002788 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2789 value_list[0] = screen->black_pixel;
2790 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002791
Dave Houlton5fa47912018-02-16 11:02:26 -07002792 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2793 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2794
2795 /* Magic code that will send notification when window is destroyed */
2796 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2797 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2798
2799 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2800 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2801
2802 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2803
2804 free(reply);
2805
2806 xcb_map_window(connection, xcb_window);
2807
2808 // Force the x/y coordinates to 100,100 results are identical in
2809 // consecutive
2810 // runs
2811 const uint32_t coords[] = {100, 100};
2812 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2813}
2814#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2815
2816void Demo::run() {
2817 while (!quit) {
2818 if (pause) {
2819 wl_display_dispatch(display);
2820 } else {
2821 wl_display_dispatch_pending(display);
2822 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002823 draw();
2824 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002825 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002826 quit = true;
2827 }
2828 }
2829 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002830}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002831
Manuel Stoecklac939332019-06-26 20:55:53 -04002832static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2833 Demo *demo = (Demo *)data;
2834 xdg_surface_ack_configure(xdg_surface, serial);
2835 if (demo->xdg_surface_has_been_configured) {
2836 demo->resize();
2837 }
2838 demo->xdg_surface_has_been_configured = true;
2839}
2840
2841static const xdg_surface_listener surface_listener = {handle_surface_configure};
2842
2843static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2844 struct wl_array *states) {
2845 Demo *demo = (Demo *)data;
2846 /* zero values imply the program may choose its own size, so in that case
2847 * stay with the existing value (which on startup is the default) */
2848 if (width > 0) {
2849 demo->width = width;
2850 }
2851 if (height > 0) {
2852 demo->height = height;
2853 }
2854 // This will be followed by a surface configure
2855}
2856
2857static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2858 Demo *demo = (Demo *)data;
2859 demo->quit = true;
2860}
2861
2862static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2863
Dave Houlton5fa47912018-02-16 11:02:26 -07002864void Demo::create_window() {
Manuel Stoecklac939332019-06-26 20:55:53 -04002865 if (!wm_base) {
2866 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2867 fflush(stdout);
2868 exit(1);
2869 }
2870
Dave Houlton5fa47912018-02-16 11:02:26 -07002871 window = wl_compositor_create_surface(compositor);
2872 if (!window) {
2873 printf("Can not create wayland_surface from compositor!\n");
2874 fflush(stdout);
2875 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002876 }
2877
Manuel Stoecklac939332019-06-26 20:55:53 -04002878 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2879 if (!window_surface) {
2880 printf("Can not get xdg_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002881 fflush(stdout);
2882 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002883 }
Manuel Stoecklac939332019-06-26 20:55:53 -04002884 window_toplevel = xdg_surface_get_toplevel(window_surface);
2885 if (!window_toplevel) {
2886 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2887 fflush(stdout);
2888 exit(1);
2889 }
2890 xdg_surface_add_listener(window_surface, &surface_listener, this);
2891 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2892 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2893 if (xdg_decoration_mgr) {
2894 // if supported, let the compositor render titlebars for us
2895 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2896 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2897 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002898
Manuel Stoecklac939332019-06-26 20:55:53 -04002899 wl_surface_commit(window);
Dave Houlton5fa47912018-02-16 11:02:26 -07002900}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002901#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2902
2903void Demo::handle_directfb_event(const DFBInputEvent *event) {
2904 if (event->type != DIET_KEYPRESS) return;
2905 switch (event->key_symbol) {
2906 case DIKS_ESCAPE: // Escape
2907 quit = true;
2908 break;
2909 case DIKS_CURSOR_LEFT: // left arrow key
2910 spin_angle -= spin_increment;
2911 break;
2912 case DIKS_CURSOR_RIGHT: // right arrow key
2913 spin_angle += spin_increment;
2914 break;
2915 case DIKS_SPACE: // space bar
2916 pause = !pause;
2917 break;
2918 default:
2919 break;
2920 }
2921}
2922
2923void Demo::run_directfb() {
2924 while (!quit) {
2925 DFBInputEvent event;
2926
2927 if (pause) {
2928 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002929 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002930 } else {
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
2933 draw();
2934 curFrame++;
2935 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2936 quit = true;
2937 }
2938 }
2939 }
2940}
2941
2942void Demo::create_directfb_window() {
2943 DFBResult ret;
2944
2945 ret = DirectFBInit(NULL, NULL);
2946 if (ret) {
2947 printf("DirectFBInit failed to initialize DirectFB!\n");
2948 fflush(stdout);
2949 exit(1);
2950 }
2951
2952 ret = DirectFBCreate(&dfb);
2953 if (ret) {
2954 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2955 fflush(stdout);
2956 exit(1);
2957 }
2958
2959 DFBSurfaceDescription desc;
2960 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2961 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002962 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002963 desc.height = height;
2964 ret = dfb->CreateSurface(dfb, &desc, &window);
2965 if (ret) {
2966 printf("CreateSurface failed to create DirectFB surface interface!\n");
2967 fflush(stdout);
2968 exit(1);
2969 }
2970
2971 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2972 if (ret) {
2973 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2974 fflush(stdout);
2975 exit(1);
2976 }
2977}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002978#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002979void Demo::run() {
2980 draw();
2981 curFrame++;
2982 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2983 quit = true;
2984 }
2985}
Damien Leone600c3052017-01-31 10:26:07 -07002986#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2987
Dave Houlton5fa47912018-02-16 11:02:26 -07002988vk::Result Demo::create_display_surface() {
2989 vk::Result result;
2990 uint32_t display_count;
2991 uint32_t mode_count;
2992 uint32_t plane_count;
2993 vk::DisplayPropertiesKHR display_props;
2994 vk::DisplayKHR display;
2995 vk::DisplayModePropertiesKHR mode_props;
2996 vk::DisplayPlanePropertiesKHR *plane_props;
2997 vk::Bool32 found_plane = VK_FALSE;
2998 uint32_t plane_index;
2999 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07003000
Dave Houlton5fa47912018-02-16 11:02:26 -07003001 display_count = 1;
3002 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
3003 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3004
3005 display = display_props.display;
3006
3007 // Get the first mode of the display
3008 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
3009 VERIFY(result == vk::Result::eSuccess);
3010
3011 if (mode_count == 0) {
3012 printf("Cannot find any mode for the display!\n");
3013 fflush(stdout);
3014 exit(1);
3015 }
3016
3017 mode_count = 1;
3018 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
3019 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
3020
3021 // Get the list of planes
3022 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
3023 VERIFY(result == vk::Result::eSuccess);
3024
3025 if (plane_count == 0) {
3026 printf("Cannot find any plane!\n");
3027 fflush(stdout);
3028 exit(1);
3029 }
3030
3031 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
3032 VERIFY(plane_props != nullptr);
3033
3034 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
3035 VERIFY(result == vk::Result::eSuccess);
3036
3037 // Find a plane compatible with the display
3038 for (plane_index = 0; plane_index < plane_count; plane_index++) {
3039 uint32_t supported_count;
3040 vk::DisplayKHR *supported_displays;
3041
3042 // Disqualify planes that are bound to a different display
3043 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
3044 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003045 }
3046
Dave Houlton5fa47912018-02-16 11:02:26 -07003047 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003048 VERIFY(result == vk::Result::eSuccess);
3049
Dave Houlton5fa47912018-02-16 11:02:26 -07003050 if (supported_count == 0) {
3051 continue;
Damien Leone600c3052017-01-31 10:26:07 -07003052 }
3053
Dave Houlton5fa47912018-02-16 11:02:26 -07003054 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
3055 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07003056
Dave Houlton5fa47912018-02-16 11:02:26 -07003057 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003058 VERIFY(result == vk::Result::eSuccess);
3059
Dave Houlton5fa47912018-02-16 11:02:26 -07003060 for (uint32_t i = 0; i < supported_count; i++) {
3061 if (supported_displays[i] == display) {
3062 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07003063 break;
3064 }
3065 }
3066
Dave Houlton5fa47912018-02-16 11:02:26 -07003067 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07003068
Dave Houlton5fa47912018-02-16 11:02:26 -07003069 if (found_plane) {
3070 break;
Damien Leone600c3052017-01-31 10:26:07 -07003071 }
3072 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003073
3074 if (!found_plane) {
3075 printf("Cannot find a plane compatible with the display!\n");
3076 fflush(stdout);
3077 exit(1);
3078 }
3079
3080 free(plane_props);
3081
3082 vk::DisplayPlaneCapabilitiesKHR planeCaps;
3083 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
3084 // Find a supported alpha mode
3085 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3086 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
3087 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3088 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3089 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3090 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3091 };
3092 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3093 if (planeCaps.supportedAlpha & alphaModes[i]) {
3094 alphaMode = alphaModes[i];
3095 break;
3096 }
3097 }
3098
3099 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3100 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3101
3102 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3103 .setDisplayMode(mode_props.displayMode)
3104 .setPlaneIndex(plane_index)
3105 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3106 .setGlobalAlpha(1.0f)
3107 .setAlphaMode(alphaMode)
3108 .setImageExtent(image_extent);
3109
3110 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3111}
3112
3113void Demo::run_display() {
3114 while (!quit) {
3115 draw();
3116 curFrame++;
3117
Petr Krausd88e4e52019-01-23 18:45:04 +01003118 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003119 quit = true;
3120 }
3121 }
3122}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003123#endif
3124
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003125#if _WIN32
3126// Include header required for parsing the command line options.
3127#include <shellapi.h>
3128
3129Demo demo;
3130
3131// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003132LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3133 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003134 case WM_CLOSE:
3135 PostQuitMessage(validation_error);
3136 break;
3137 case WM_PAINT:
3138 demo.run();
3139 break;
3140 case WM_GETMINMAXINFO: // set window's minimum size
3141 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3142 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003143 case WM_ERASEBKGND:
3144 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003145 case WM_SIZE:
3146 // Resize the application to the new window size, except when
3147 // it was minimized. Vulkan doesn't support images or swapchains
3148 // with width=0 and height=0.
3149 if (wParam != SIZE_MINIMIZED) {
3150 demo.width = lParam & 0xffff;
3151 demo.height = (lParam & 0xffff0000) >> 16;
3152 demo.resize();
3153 }
3154 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003155 case WM_KEYDOWN:
3156 switch (wParam) {
3157 case VK_ESCAPE:
3158 PostQuitMessage(validation_error);
3159 break;
3160 case VK_LEFT:
3161 demo.spin_angle -= demo.spin_increment;
3162 break;
3163 case VK_RIGHT:
3164 demo.spin_angle += demo.spin_increment;
3165 break;
3166 case VK_SPACE:
3167 demo.pause = !demo.pause;
3168 break;
3169 }
3170 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003171 default:
3172 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003173 }
3174
3175 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3176}
3177
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003178int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003179 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003180 MSG msg; // message
3181 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003182 int argc;
3183 char **argv;
3184
Jamie Madillb2ff6502017-03-15 16:17:46 -04003185 // Ensure wParam is initialized.
3186 msg.wParam = 0;
3187
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003188 // Use the CommandLine functions to get the command line arguments.
3189 // Unfortunately, Microsoft outputs
3190 // this information as wide characters for Unicode, and we simply want the
3191 // Ascii version to be compatible
3192 // with the non-Windows side. So, we have to convert the information to
3193 // Ascii character strings.
3194 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003195 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003196 argc = 0;
3197 }
3198
Jeremy Hayes9d304782016-10-09 11:48:12 -06003199 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003200 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003201 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003202 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003203 } else {
3204 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003205 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3206 size_t numConverted = 0;
3207
3208 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003209 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003210 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003211 }
3212 }
3213 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003214 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003215 argv = nullptr;
3216 }
3217
3218 demo.init(argc, argv);
3219
3220 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003221 if (argc > 0 && argv != nullptr) {
3222 for (int iii = 0; iii < argc; iii++) {
3223 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003224 free(argv[iii]);
3225 }
3226 }
3227 free(argv);
3228 }
3229
3230 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003231 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003232 demo.create_window();
3233 demo.init_vk_swapchain();
3234
3235 demo.prepare();
3236
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003237 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003238
3239 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003240 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003241 if (demo.pause) {
3242 const BOOL succ = WaitMessage();
3243
3244 if (!succ) {
3245 const auto &suppress_popups = demo.suppress_popups;
3246 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3247 }
3248 }
3249
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003250 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003251 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003252 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003253 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003254 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003255 /* Translate and dispatch to event queue*/
3256 TranslateMessage(&msg);
3257 DispatchMessage(&msg);
3258 }
3259 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3260 }
3261
3262 demo.cleanup();
3263
3264 return (int)msg.wParam;
3265}
3266
3267#elif __linux__
3268
Jeremy Hayes9d304782016-10-09 11:48:12 -06003269int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003270 Demo demo;
3271
3272 demo.init(argc, argv);
3273
Tony Barbour153cb062016-12-07 13:43:36 -07003274#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003275 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003276#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003277 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003278 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003279#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003280 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003281#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3282 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003283#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003284
3285 demo.init_vk_swapchain();
3286
3287 demo.prepare();
3288
Tony Barbour153cb062016-12-07 13:43:36 -07003289#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003290 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003291#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003292 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003293#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003294 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003295#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3296 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003297#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3298 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003299#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003300
3301 demo.cleanup();
3302
3303 return validation_error;
3304}
3305
Bill Hollings0a0625a2019-07-15 17:39:18 -04003306#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003307
3308// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003309static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003310 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003311 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003312 demo.init_vk_swapchain();
3313 demo.prepare();
3314 demo.spin_angle = 0.4f;
3315}
3316
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003317#else
3318#error "Platform not supported"
3319#endif