blob: ed572e39b5686c4446430e445b3a6c9e29bd7131 [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>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060025#endif
26
27#include <cassert>
Petr Krausbc0ab752017-12-09 00:22:39 +010028#include <cinttypes>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060029#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <csignal>
Tony-LunarGd74734f2019-06-04 14:11:43 -060033#include <iostream>
34#include <sstream>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060035#include <memory>
36
37#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060038#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060039#include <vulkan/vulkan.hpp>
40#include <vulkan/vk_sdk_platform.h>
41
42#include "linmath.h"
43
44#ifndef NDEBUG
45#define VERIFY(x) assert(x)
46#else
47#define VERIFY(x) ((void)(x))
48#endif
49
Lenny Komowffe446c2018-11-19 17:08:04 -070050#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060051#ifdef _WIN32
52#define APP_NAME_STR_LEN 80
53#endif
54
55// Allow a maximum of two outstanding presentation operations.
56#define FRAME_LAG 2
57
58#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
59
60#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070061#define ERR_EXIT(err_msg, err_class) \
62 do { \
63 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
64 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060065 } while (0)
66#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070067#define ERR_EXIT(err_msg, err_class) \
68 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080069 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070070 fflush(stdout); \
71 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060072 } while (0)
73#endif
74
Jeremy Hayes9d304782016-10-09 11:48:12 -060075struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060076 vk::Sampler sampler;
77
78 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060079 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070080 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060081
82 vk::MemoryAllocateInfo mem_alloc;
83 vk::DeviceMemory mem;
84 vk::ImageView view;
85
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070086 int32_t tex_width{0};
87 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060088};
89
Jeremy Hayes9d304782016-10-09 11:48:12 -060090static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060091
92static int validation_error = 0;
93
Jeremy Hayesf56427a2016-09-07 15:55:11 -060094struct vktexcube_vs_uniform {
95 // Must start with MVP
96 float mvp[4][4];
97 float position[12 * 3][4];
98 float attr[12 * 3][4];
99};
100
101//--------------------------------------------------------------------------------------
102// Mesh and VertexFormat Data
103//--------------------------------------------------------------------------------------
104// clang-format off
105static const float g_vertex_buffer_data[] = {
106 -1.0f,-1.0f,-1.0f, // -X side
107 -1.0f,-1.0f, 1.0f,
108 -1.0f, 1.0f, 1.0f,
109 -1.0f, 1.0f, 1.0f,
110 -1.0f, 1.0f,-1.0f,
111 -1.0f,-1.0f,-1.0f,
112
113 -1.0f,-1.0f,-1.0f, // -Z side
114 1.0f, 1.0f,-1.0f,
115 1.0f,-1.0f,-1.0f,
116 -1.0f,-1.0f,-1.0f,
117 -1.0f, 1.0f,-1.0f,
118 1.0f, 1.0f,-1.0f,
119
120 -1.0f,-1.0f,-1.0f, // -Y side
121 1.0f,-1.0f,-1.0f,
122 1.0f,-1.0f, 1.0f,
123 -1.0f,-1.0f,-1.0f,
124 1.0f,-1.0f, 1.0f,
125 -1.0f,-1.0f, 1.0f,
126
127 -1.0f, 1.0f,-1.0f, // +Y side
128 -1.0f, 1.0f, 1.0f,
129 1.0f, 1.0f, 1.0f,
130 -1.0f, 1.0f,-1.0f,
131 1.0f, 1.0f, 1.0f,
132 1.0f, 1.0f,-1.0f,
133
134 1.0f, 1.0f,-1.0f, // +X side
135 1.0f, 1.0f, 1.0f,
136 1.0f,-1.0f, 1.0f,
137 1.0f,-1.0f, 1.0f,
138 1.0f,-1.0f,-1.0f,
139 1.0f, 1.0f,-1.0f,
140
141 -1.0f, 1.0f, 1.0f, // +Z side
142 -1.0f,-1.0f, 1.0f,
143 1.0f, 1.0f, 1.0f,
144 -1.0f,-1.0f, 1.0f,
145 1.0f,-1.0f, 1.0f,
146 1.0f, 1.0f, 1.0f,
147};
148
149static const float g_uv_buffer_data[] = {
150 0.0f, 1.0f, // -X side
151 1.0f, 1.0f,
152 1.0f, 0.0f,
153 1.0f, 0.0f,
154 0.0f, 0.0f,
155 0.0f, 1.0f,
156
157 1.0f, 1.0f, // -Z side
158 0.0f, 0.0f,
159 0.0f, 1.0f,
160 1.0f, 1.0f,
161 1.0f, 0.0f,
162 0.0f, 0.0f,
163
164 1.0f, 0.0f, // -Y side
165 1.0f, 1.0f,
166 0.0f, 1.0f,
167 1.0f, 0.0f,
168 0.0f, 1.0f,
169 0.0f, 0.0f,
170
171 1.0f, 0.0f, // +Y side
172 0.0f, 0.0f,
173 0.0f, 1.0f,
174 1.0f, 0.0f,
175 0.0f, 1.0f,
176 1.0f, 1.0f,
177
178 1.0f, 0.0f, // +X side
179 0.0f, 0.0f,
180 0.0f, 1.0f,
181 0.0f, 1.0f,
182 1.0f, 1.0f,
183 1.0f, 0.0f,
184
185 0.0f, 0.0f, // +Z side
186 0.0f, 1.0f,
187 1.0f, 0.0f,
188 0.0f, 1.0f,
189 1.0f, 1.0f,
190 1.0f, 0.0f,
191};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600192// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600193
Jeremy Hayes9d304782016-10-09 11:48:12 -0600194typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600195 vk::Image image;
196 vk::CommandBuffer cmd;
197 vk::CommandBuffer graphics_to_present_cmd;
198 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600199 vk::Buffer uniform_buffer;
200 vk::DeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700201 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600202 vk::Framebuffer framebuffer;
203 vk::DescriptorSet descriptor_set;
204} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600205
Joey Bzdekbaf66472017-06-07 09:37:37 -0600206struct Demo {
207 Demo();
208 void build_image_ownership_cmd(uint32_t const &);
209 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
210 void cleanup();
211 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600212 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600213 void draw();
214 void draw_build_cmd(vk::CommandBuffer);
215 void flush_init_cmd();
216 void init(int, char **);
217 void init_connection();
218 void init_vk();
219 void init_vk_swapchain();
220 void prepare();
221 void prepare_buffers();
222 void prepare_cube_data_buffers();
223 void prepare_depth();
224 void prepare_descriptor_layout();
225 void prepare_descriptor_pool();
226 void prepare_descriptor_set();
227 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100228 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
229 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600230 vk::ShaderModule prepare_fs();
231 void prepare_pipeline();
232 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600233 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600234 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600235 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100236
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600238 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600239 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
240 vk::PipelineStageFlags, vk::PipelineStageFlags);
241 void update_data_buffer();
242 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
243 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
244
245#if defined(VK_USE_PLATFORM_WIN32_KHR)
246 void run();
247 void create_window();
248#elif defined(VK_USE_PLATFORM_XLIB_KHR)
249 void create_xlib_window();
250 void handle_xlib_event(const XEvent *);
251 void run_xlib();
252#elif defined(VK_USE_PLATFORM_XCB_KHR)
253 void handle_xcb_event(const xcb_generic_event_t *);
254 void run_xcb();
255 void create_xcb_window();
256#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
257 void run();
258 void create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200259#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
260 void handle_directfb_event(const DFBInputEvent *);
261 void run_directfb();
262 void create_directfb_window();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400263#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600264 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600265#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
266 vk::Result create_display_surface();
267 void run_display();
268#endif
269
270#if defined(VK_USE_PLATFORM_WIN32_KHR)
271 HINSTANCE connection; // hInstance - Windows Instance
272 HWND window; // hWnd - window handle
273 POINT minsize; // minimum window size
274 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
275#elif defined(VK_USE_PLATFORM_XLIB_KHR)
276 Window xlib_window;
277 Atom xlib_wm_delete_window;
278 Display *display;
279#elif defined(VK_USE_PLATFORM_XCB_KHR)
280 xcb_window_t xcb_window;
281 xcb_screen_t *screen;
282 xcb_connection_t *connection;
283 xcb_intern_atom_reply_t *atom_wm_delete_window;
284#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
285 wl_display *display;
286 wl_registry *registry;
287 wl_compositor *compositor;
288 wl_surface *window;
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700289 wl_shell *shell;
290 wl_shell_surface *shell_surface;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600291 wl_seat *seat;
292 wl_pointer *pointer;
293 wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200294#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
295 IDirectFB *dfb;
296 IDirectFBSurface *window;
297 IDirectFBEventBuffer *event_buffer;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400298#elif defined(VK_USE_PLATFORM_METAL_EXT)
299 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600300#endif
301
302 vk::SurfaceKHR surface;
303 bool prepared;
304 bool use_staging_buffer;
305 bool use_xlib;
306 bool separate_present_queue;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000307 int32_t gpu_number;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600308
309 vk::Instance inst;
310 vk::PhysicalDevice gpu;
311 vk::Device device;
312 vk::Queue graphics_queue;
313 vk::Queue present_queue;
314 uint32_t graphics_queue_family_index;
315 uint32_t present_queue_family_index;
316 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
317 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
318 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
319 vk::PhysicalDeviceProperties gpu_props;
320 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
321 vk::PhysicalDeviceMemoryProperties memory_properties;
322
323 uint32_t enabled_extension_count;
324 uint32_t enabled_layer_count;
325 char const *extension_names[64];
326 char const *enabled_layers[64];
327
328 uint32_t width;
329 uint32_t height;
330 vk::Format format;
331 vk::ColorSpaceKHR color_space;
332
333 uint32_t swapchainImageCount;
334 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600335 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600336 vk::PresentModeKHR presentMode;
337 vk::Fence fences[FRAME_LAG];
338 uint32_t frame_index;
339
340 vk::CommandPool cmd_pool;
341 vk::CommandPool present_cmd_pool;
342
343 struct {
344 vk::Format format;
345 vk::Image image;
346 vk::MemoryAllocateInfo mem_alloc;
347 vk::DeviceMemory mem;
348 vk::ImageView view;
349 } depth;
350
351 static int32_t const texture_count = 1;
352 texture_object textures[texture_count];
353 texture_object staging_texture;
354
355 struct {
356 vk::Buffer buf;
357 vk::MemoryAllocateInfo mem_alloc;
358 vk::DeviceMemory mem;
359 vk::DescriptorBufferInfo buffer_info;
360 } uniform_data;
361
362 vk::CommandBuffer cmd; // Buffer for initialization commands
363 vk::PipelineLayout pipeline_layout;
364 vk::DescriptorSetLayout desc_layout;
365 vk::PipelineCache pipelineCache;
366 vk::RenderPass render_pass;
367 vk::Pipeline pipeline;
368
369 mat4x4 projection_matrix;
370 mat4x4 view_matrix;
371 mat4x4 model_matrix;
372
373 float spin_angle;
374 float spin_increment;
375 bool pause;
376
377 vk::ShaderModule vert_shader_module;
378 vk::ShaderModule frag_shader_module;
379
380 vk::DescriptorPool desc_pool;
381 vk::DescriptorSet desc_set;
382
383 std::unique_ptr<vk::Framebuffer[]> framebuffers;
384
385 bool quit;
386 uint32_t curFrame;
387 uint32_t frameCount;
388 bool validate;
389 bool use_break;
390 bool suppress_popups;
391
392 uint32_t current_buffer;
393 uint32_t queue_family_count;
394};
395
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600396#ifdef _WIN32
397// MS-Windows event handling function:
398LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
399#endif
400
Karl Schultz23cc2182016-11-23 17:15:17 -0700401#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700402static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700403 wl_shell_surface_pong(shell_surface, serial);
404}
405
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700406static void handle_configure(void *data, wl_shell_surface *shell_surface, uint32_t edges, int32_t width, int32_t height) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700407
408static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
409
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700410static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700411
Joey Bzdek15eb0702017-06-07 09:40:36 -0600412static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
413 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700414
Joey Bzdek15eb0702017-06-07 09:40:36 -0600415static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700416
Joey Bzdek15eb0702017-06-07 09:40:36 -0600417static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
418
419static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
420 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600421 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600422 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700423 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600424 }
425}
426
427static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
428
429static const struct wl_pointer_listener pointer_listener = {
430 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
431};
432
433static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
434
435static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
436 struct wl_array *keys) {}
437
438static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
439
440static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
441 uint32_t state) {
442 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
443 Demo *demo = (Demo *)data;
444 switch (key) {
445 case KEY_ESC: // Escape
446 demo->quit = true;
447 break;
448 case KEY_LEFT: // left arrow key
449 demo->spin_angle -= demo->spin_increment;
450 break;
451 case KEY_RIGHT: // right arrow key
452 demo->spin_angle += demo->spin_increment;
453 break;
454 case KEY_SPACE: // space bar
455 demo->pause = !demo->pause;
456 break;
457 }
458}
459
460static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
461 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
462
463static const struct wl_keyboard_listener keyboard_listener = {
464 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
465};
466
467static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
468 // Subscribe to pointer events
469 Demo *demo = (Demo *)data;
470 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
471 demo->pointer = wl_seat_get_pointer(seat);
472 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
473 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
474 wl_pointer_destroy(demo->pointer);
475 demo->pointer = NULL;
476 }
477 // Subscribe to keyboard events
478 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
479 demo->keyboard = wl_seat_get_keyboard(seat);
480 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
481 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
482 wl_keyboard_destroy(demo->keyboard);
483 demo->keyboard = NULL;
484 }
485}
486
487static const wl_seat_listener seat_listener = {
488 seat_handle_capabilities,
489};
490
491static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
492 Demo *demo = (Demo *)data;
493 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700494 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600495 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700496 } else if (strcmp(interface, "wl_shell") == 0) {
497 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
498 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600499 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
500 wl_seat_add_listener(demo->seat, &seat_listener, demo);
501 }
502}
503
504static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
505
506static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700507#endif
508
Joey Bzdekbaf66472017-06-07 09:37:37 -0600509Demo::Demo()
510 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600511#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600512 connection{nullptr},
513 window{nullptr},
514 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600515#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700516
Tony Barbour78d6b572016-11-14 14:46:33 -0700517#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600518 xlib_window{0},
519 xlib_wm_delete_window{0},
520 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700521#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600522 xcb_window{0},
523 screen{nullptr},
524 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700525#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600526 display{nullptr},
527 registry{nullptr},
528 compositor{nullptr},
529 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700530 shell{nullptr},
531 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600532 seat{nullptr},
533 pointer{nullptr},
534 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200535#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
536 dfb{nullptr},
537 window{nullptr},
538 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700539#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600540 prepared{false},
541 use_staging_buffer{false},
542 use_xlib{false},
543 graphics_queue_family_index{0},
544 present_queue_family_index{0},
545 enabled_extension_count{0},
546 enabled_layer_count{0},
547 width{0},
548 height{0},
549 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000550 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600551 frame_index{0},
552 spin_angle{0.0f},
553 spin_increment{0.0f},
554 pause{false},
555 quit{false},
556 curFrame{0},
557 frameCount{0},
558 validate{false},
559 use_break{false},
560 suppress_popups{false},
561 current_buffer{0},
562 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600563#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700564 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600565#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700566 memset(projection_matrix, 0, sizeof(projection_matrix));
567 memset(view_matrix, 0, sizeof(view_matrix));
568 memset(model_matrix, 0, sizeof(model_matrix));
569}
570
571void Demo::build_image_ownership_cmd(uint32_t const &i) {
572 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
573 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
574 VERIFY(result == vk::Result::eSuccess);
575
576 auto const image_ownership_barrier =
577 vk::ImageMemoryBarrier()
578 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600579 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700580 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
581 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
582 .setSrcQueueFamilyIndex(graphics_queue_family_index)
583 .setDstQueueFamilyIndex(present_queue_family_index)
584 .setImage(swapchain_image_resources[i].image)
585 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
586
587 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600588 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
589 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700590
591 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
592 VERIFY(result == vk::Result::eSuccess);
593}
594
595vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
596 vk::LayerProperties *layers) {
597 for (uint32_t i = 0; i < check_count; i++) {
598 vk::Bool32 found = VK_FALSE;
599 for (uint32_t j = 0; j < layer_count; j++) {
600 if (!strcmp(check_names[i], layers[j].layerName)) {
601 found = VK_TRUE;
602 break;
603 }
604 }
605 if (!found) {
606 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
607 return 0;
608 }
609 }
610 return VK_TRUE;
611}
612
613void Demo::cleanup() {
614 prepared = false;
615 device.waitIdle();
616
617 // Wait for fences from present operations
618 for (uint32_t i = 0; i < FRAME_LAG; i++) {
619 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
620 device.destroyFence(fences[i], nullptr);
621 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
622 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
623 if (separate_present_queue) {
624 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
625 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600626 }
627
Dave Houlton5fa47912018-02-16 11:02:26 -0700628 for (uint32_t i = 0; i < swapchainImageCount; i++) {
629 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
630 }
631 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600632
Dave Houlton5fa47912018-02-16 11:02:26 -0700633 device.destroyPipeline(pipeline, nullptr);
634 device.destroyPipelineCache(pipelineCache, nullptr);
635 device.destroyRenderPass(render_pass, nullptr);
636 device.destroyPipelineLayout(pipeline_layout, nullptr);
637 device.destroyDescriptorSetLayout(desc_layout, nullptr);
638
639 for (uint32_t i = 0; i < texture_count; i++) {
640 device.destroyImageView(textures[i].view, nullptr);
641 device.destroyImage(textures[i].image, nullptr);
642 device.freeMemory(textures[i].mem, nullptr);
643 device.destroySampler(textures[i].sampler, nullptr);
644 }
645 device.destroySwapchainKHR(swapchain, nullptr);
646
647 device.destroyImageView(depth.view, nullptr);
648 device.destroyImage(depth.image, nullptr);
649 device.freeMemory(depth.mem, nullptr);
650
651 for (uint32_t i = 0; i < swapchainImageCount; i++) {
652 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700653 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700654 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700655 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700656 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
657 }
658
659 device.destroyCommandPool(cmd_pool, nullptr);
660
661 if (separate_present_queue) {
662 device.destroyCommandPool(present_cmd_pool, nullptr);
663 }
664 device.waitIdle();
665 device.destroy(nullptr);
666 inst.destroySurfaceKHR(surface, nullptr);
667
668#if defined(VK_USE_PLATFORM_XLIB_KHR)
669 XDestroyWindow(display, xlib_window);
670 XCloseDisplay(display);
671#elif defined(VK_USE_PLATFORM_XCB_KHR)
672 xcb_destroy_window(connection, xcb_window);
673 xcb_disconnect(connection);
674 free(atom_wm_delete_window);
675#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
676 wl_keyboard_destroy(keyboard);
677 wl_pointer_destroy(pointer);
678 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700679 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700680 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700681 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700682 wl_compositor_destroy(compositor);
683 wl_registry_destroy(registry);
684 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200685#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
686 event_buffer->Release(event_buffer);
687 window->Release(window);
688 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700689#endif
690
691 inst.destroy(nullptr);
692}
693
694void Demo::create_device() {
695 float const priorities[1] = {0.0};
696
697 vk::DeviceQueueCreateInfo queues[2];
698 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
699 queues[0].setQueueCount(1);
700 queues[0].setPQueuePriorities(priorities);
701
702 auto deviceInfo = vk::DeviceCreateInfo()
703 .setQueueCreateInfoCount(1)
704 .setPQueueCreateInfos(queues)
705 .setEnabledLayerCount(0)
706 .setPpEnabledLayerNames(nullptr)
707 .setEnabledExtensionCount(enabled_extension_count)
708 .setPpEnabledExtensionNames((const char *const *)extension_names)
709 .setPEnabledFeatures(nullptr);
710
711 if (separate_present_queue) {
712 queues[1].setQueueFamilyIndex(present_queue_family_index);
713 queues[1].setQueueCount(1);
714 queues[1].setPQueuePriorities(priorities);
715 deviceInfo.setQueueCreateInfoCount(2);
716 }
717
718 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
719 VERIFY(result == vk::Result::eSuccess);
720}
721
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600722void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700723 // clean up staging resources
724 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600725 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
726 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700727}
728
729void Demo::draw() {
730 // Ensure no more than FRAME_LAG renderings are outstanding
731 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700732 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700733
734 vk::Result result;
735 do {
736 result =
737 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
738 if (result == vk::Result::eErrorOutOfDateKHR) {
739 // demo->swapchain is out of date (e.g. the window was resized) and
740 // must be recreated:
741 resize();
742 } else if (result == vk::Result::eSuboptimalKHR) {
743 // swapchain is not as optimal as it could be, but the platform's
744 // presentation engine will still present the image correctly.
745 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600746 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
747 inst.destroySurfaceKHR(surface, nullptr);
748 create_surface();
749 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700750 } else {
751 VERIFY(result == vk::Result::eSuccess);
752 }
753 } while (result != vk::Result::eSuccess);
754
755 update_data_buffer();
756
757 // Wait for the image acquired semaphore to be signaled to ensure
758 // that the image won't be rendered to until the presentation
759 // engine has fully released ownership to the application, and it is
760 // okay to render to the image.
761 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
762 auto const submit_info = vk::SubmitInfo()
763 .setPWaitDstStageMask(&pipe_stage_flags)
764 .setWaitSemaphoreCount(1)
765 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
766 .setCommandBufferCount(1)
767 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
768 .setSignalSemaphoreCount(1)
769 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
770
771 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
772 VERIFY(result == vk::Result::eSuccess);
773
774 if (separate_present_queue) {
775 // If we are using separate queues, change image ownership to the
776 // present queue before presenting, waiting for the draw complete
777 // semaphore and signalling the ownership released semaphore when
778 // finished
779 auto const present_submit_info = vk::SubmitInfo()
780 .setPWaitDstStageMask(&pipe_stage_flags)
781 .setWaitSemaphoreCount(1)
782 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
783 .setCommandBufferCount(1)
784 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
785 .setSignalSemaphoreCount(1)
786 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
787
788 result = present_queue.submit(1, &present_submit_info, vk::Fence());
789 VERIFY(result == vk::Result::eSuccess);
790 }
791
792 // If we are using separate queues we have to wait for image ownership,
793 // otherwise wait for draw complete
794 auto const presentInfo = vk::PresentInfoKHR()
795 .setWaitSemaphoreCount(1)
796 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
797 : &draw_complete_semaphores[frame_index])
798 .setSwapchainCount(1)
799 .setPSwapchains(&swapchain)
800 .setPImageIndices(&current_buffer);
801
802 result = present_queue.presentKHR(&presentInfo);
803 frame_index += 1;
804 frame_index %= FRAME_LAG;
805 if (result == vk::Result::eErrorOutOfDateKHR) {
806 // swapchain is out of date (e.g. the window was resized) and
807 // must be recreated:
808 resize();
809 } else if (result == vk::Result::eSuboptimalKHR) {
810 // swapchain is not as optimal as it could be, but the platform's
811 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600812 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
813 inst.destroySurfaceKHR(surface, nullptr);
814 create_surface();
815 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700816 } else {
817 VERIFY(result == vk::Result::eSuccess);
818 }
819}
820
821void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
822 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
823
824 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
825 vk::ClearDepthStencilValue(1.0f, 0u)};
826
827 auto const passInfo = vk::RenderPassBeginInfo()
828 .setRenderPass(render_pass)
829 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
830 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
831 .setClearValueCount(2)
832 .setPClearValues(clearValues);
833
834 auto result = commandBuffer.begin(&commandInfo);
835 VERIFY(result == vk::Result::eSuccess);
836
837 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
838 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
839 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
840 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700841 float viewport_dimension;
842 float viewport_x = 0.0f;
843 float viewport_y = 0.0f;
844 if (width < height) {
845 viewport_dimension = (float)width;
846 viewport_y = (height - width) / 2.0f;
847 } else {
848 viewport_dimension = (float)height;
849 viewport_x = (width - height) / 2.0f;
850 }
851 auto const viewport = vk::Viewport()
852 .setX(viewport_x)
853 .setY(viewport_y)
854 .setWidth((float)viewport_dimension)
855 .setHeight((float)viewport_dimension)
856 .setMinDepth((float)0.0f)
857 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700858 commandBuffer.setViewport(0, 1, &viewport);
859
860 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
861 commandBuffer.setScissor(0, 1, &scissor);
862 commandBuffer.draw(12 * 3, 1, 0, 0);
863 // Note that ending the renderpass changes the image's layout from
864 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
865 commandBuffer.endRenderPass();
866
867 if (separate_present_queue) {
868 // We have to transfer ownership from the graphics queue family to
869 // the
870 // present queue family to be able to present. Note that we don't
871 // have
872 // to transfer from present queue family back to graphics queue
873 // family at
874 // the start of the next frame because we don't care about the
875 // image's
876 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600877 auto const image_ownership_barrier =
878 vk::ImageMemoryBarrier()
879 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600880 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600881 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
882 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
883 .setSrcQueueFamilyIndex(graphics_queue_family_index)
884 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700885 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700886 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600887
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600888 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700889 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600890 }
891
Dave Houlton5fa47912018-02-16 11:02:26 -0700892 result = commandBuffer.end();
893 VERIFY(result == vk::Result::eSuccess);
894}
895
896void Demo::flush_init_cmd() {
897 // TODO: hmm.
898 // This function could get called twice if the texture uses a staging
899 // buffer
900 // In that case the second call should be ignored
901 if (!cmd) {
902 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600903 }
904
Dave Houlton5fa47912018-02-16 11:02:26 -0700905 auto result = cmd.end();
906 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600907
Dave Houlton5fa47912018-02-16 11:02:26 -0700908 auto const fenceInfo = vk::FenceCreateInfo();
909 vk::Fence fence;
910 result = device.createFence(&fenceInfo, nullptr, &fence);
911 VERIFY(result == vk::Result::eSuccess);
912
913 vk::CommandBuffer const commandBuffers[] = {cmd};
914 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
915
916 result = graphics_queue.submit(1, &submitInfo, fence);
917 VERIFY(result == vk::Result::eSuccess);
918
919 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
920 VERIFY(result == vk::Result::eSuccess);
921
922 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
923 device.destroyFence(fence, nullptr);
924
925 cmd = vk::CommandBuffer();
926}
927
928void Demo::init(int argc, char **argv) {
929 vec3 eye = {0.0f, 3.0f, 5.0f};
930 vec3 origin = {0, 0, 0};
931 vec3 up = {0.0f, 1.0f, 0.0};
932
933 presentMode = vk::PresentModeKHR::eFifo;
934 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100935 width = 500;
936 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700937 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000938 /* Autodetect suitable / best GPU by default */
939 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600940
Dave Houlton5fa47912018-02-16 11:02:26 -0700941 for (int i = 1; i < argc; i++) {
942 if (strcmp(argv[i], "--use_staging") == 0) {
943 use_staging_buffer = true;
944 continue;
945 }
946 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
947 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
948 i++;
949 continue;
950 }
951 if (strcmp(argv[i], "--break") == 0) {
952 use_break = true;
953 continue;
954 }
955 if (strcmp(argv[i], "--validate") == 0) {
956 validate = true;
957 continue;
958 }
959 if (strcmp(argv[i], "--xlib") == 0) {
960 fprintf(stderr, "--xlib is deprecated and no longer does anything");
961 continue;
962 }
963 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
964 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
965 i++;
966 continue;
967 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100968 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &width) == 1 && width > 0) {
969 i++;
970 continue;
971 }
972 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &height) == 1 && height > 0) {
973 i++;
974 continue;
975 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700976 if (strcmp(argv[i], "--suppress_popups") == 0) {
977 suppress_popups = true;
978 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600979 }
Tony-LunarG50e737c2020-07-16 14:26:03 -0600980 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
981 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +0000982 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -0600983 i++;
984 continue;
985 }
Tony-LunarGd74734f2019-06-04 14:11:43 -0600986 std::stringstream usage;
987 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
988 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -0600989 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600990 << "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100991 << "\t[--width <width>] [--height <height>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600992 << "\t<present_mode_enum>\n"
993 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
994 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
995 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +0000996 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -0600997
998#if defined(_WIN32)
999 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1000#else
1001 std::cerr << usage.str();
1002 std::cerr.flush();
1003#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001004 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001005 }
1006
Dave Houlton5fa47912018-02-16 11:02:26 -07001007 if (!use_xlib) {
1008 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001009 }
1010
Dave Houlton5fa47912018-02-16 11:02:26 -07001011 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001012
Dave Houlton5fa47912018-02-16 11:02:26 -07001013 spin_angle = 4.0f;
1014 spin_increment = 0.2f;
1015 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001016
Dave Houlton5fa47912018-02-16 11:02:26 -07001017 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1018 mat4x4_look_at(view_matrix, eye, origin, up);
1019 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001020
Dave Houlton5fa47912018-02-16 11:02:26 -07001021 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1022}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001023
Dave Houlton5fa47912018-02-16 11:02:26 -07001024void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001025#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001026 const xcb_setup_t *setup;
1027 xcb_screen_iterator_t iter;
1028 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001029
Dave Houlton5fa47912018-02-16 11:02:26 -07001030 const char *display_envar = getenv("DISPLAY");
1031 if (display_envar == nullptr || display_envar[0] == '\0') {
1032 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1033 fflush(stdout);
1034 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001035 }
1036
Dave Houlton5fa47912018-02-16 11:02:26 -07001037 connection = xcb_connect(nullptr, &scr);
1038 if (xcb_connection_has_error(connection) > 0) {
1039 printf(
1040 "Cannot find a compatible Vulkan installable client driver "
1041 "(ICD).\nExiting ...\n");
1042 fflush(stdout);
1043 exit(1);
1044 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001045
Dave Houlton5fa47912018-02-16 11:02:26 -07001046 setup = xcb_get_setup(connection);
1047 iter = xcb_setup_roots_iterator(setup);
1048 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001049
Dave Houlton5fa47912018-02-16 11:02:26 -07001050 screen = iter.data;
1051#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1052 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001053
Dave Houlton5fa47912018-02-16 11:02:26 -07001054 if (display == nullptr) {
1055 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1056 fflush(stdout);
1057 exit(1);
1058 }
1059
1060 registry = wl_display_get_registry(display);
1061 wl_registry_add_listener(registry, &registry_listener, this);
1062 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001063#endif
1064}
Tony-LunarG27c21242021-03-11 16:28:19 -07001065#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1066int find_display_gpu(int gpu_number, uint32_t gpu_count, std::unique_ptr<vk::PhysicalDevice[]> &physical_devices) {
1067 uint32_t display_count = 0;
1068 vk::Result result;
1069 int gpu_return = gpu_number;
1070 if (gpu_number >= 0) {
1071 result = physical_devices[gpu_number].getDisplayPropertiesKHR(&display_count, nullptr);
1072 VERIFY(result == vk::Result::eSuccess);
1073 } else {
1074 for (uint32_t i = 0; i < gpu_count; i++) {
1075 result = physical_devices[i].getDisplayPropertiesKHR(&display_count, nullptr);
1076 VERIFY(result == vk::Result::eSuccess);
1077 if (display_count) {
1078 gpu_return = i;
1079 break;
1080 }
1081 }
1082 }
1083 if (display_count > 0)
1084 return gpu_return;
1085 else
1086 return -1;
1087}
1088#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001089void Demo::init_vk() {
1090 uint32_t instance_extension_count = 0;
1091 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001092 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001093 enabled_extension_count = 0;
1094 enabled_layer_count = 0;
1095
Dave Houlton5fa47912018-02-16 11:02:26 -07001096 // Look for validation layers
1097 vk::Bool32 validation_found = VK_FALSE;
1098 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001099 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001100 VERIFY(result == vk::Result::eSuccess);
1101
Dave Houlton5fa47912018-02-16 11:02:26 -07001102 if (instance_layer_count > 0) {
1103 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1104 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001105 VERIFY(result == vk::Result::eSuccess);
1106
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001107 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001108 instance_layer_count, instance_layers.get());
1109 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001110 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1111 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001112 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001113 }
1114
Dave Houlton5fa47912018-02-16 11:02:26 -07001115 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001116 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001117 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1118 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001119 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001120 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001121 }
1122
Dave Houlton5fa47912018-02-16 11:02:26 -07001123 /* Look for instance extensions */
1124 vk::Bool32 surfaceExtFound = VK_FALSE;
1125 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1126 memset(extension_names, 0, sizeof(extension_names));
1127
Mike Schuchardt7510c832018-10-29 13:23:08 -07001128 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1129 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001130 VERIFY(result == vk::Result::eSuccess);
1131
1132 if (instance_extension_count > 0) {
1133 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1134 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1135 VERIFY(result == vk::Result::eSuccess);
1136
1137 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001138 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1139 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1140 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001141 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1142 surfaceExtFound = 1;
1143 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1144 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001145#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001146 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1147 platformSurfaceExtFound = 1;
1148 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1149 }
1150#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1151 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1152 platformSurfaceExtFound = 1;
1153 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1154 }
1155#elif defined(VK_USE_PLATFORM_XCB_KHR)
1156 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1157 platformSurfaceExtFound = 1;
1158 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1159 }
Tony Barbour153cb062016-12-07 13:43:36 -07001160#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001161 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1162 platformSurfaceExtFound = 1;
1163 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1164 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001165#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1166 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1167 platformSurfaceExtFound = 1;
1168 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1169 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001170#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1171 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1172 platformSurfaceExtFound = 1;
1173 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1174 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001175#elif defined(VK_USE_PLATFORM_METAL_EXT)
1176 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001177 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001178 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001179 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001180#endif
1181 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001182 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001183 }
1184
1185 if (!surfaceExtFound) {
1186 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1187 " extension.\n\n"
1188 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1189 "Please look at the Getting Started guide for additional information.\n",
1190 "vkCreateInstance Failure");
1191 }
1192
1193 if (!platformSurfaceExtFound) {
1194#if defined(VK_USE_PLATFORM_WIN32_KHR)
1195 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1196 " extension.\n\n"
1197 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1198 "Please look at the Getting Started guide for additional information.\n",
1199 "vkCreateInstance Failure");
1200#elif defined(VK_USE_PLATFORM_XCB_KHR)
1201 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1202 " extension.\n\n"
1203 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1204 "Please look at the Getting Started guide for additional information.\n",
1205 "vkCreateInstance Failure");
1206#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1207 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1208 " extension.\n\n"
1209 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1210 "Please look at the Getting Started guide for additional information.\n",
1211 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001212#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001213 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1214 " extension.\n\n"
1215 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1216 "Please look at the Getting Started guide for additional information.\n",
1217 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001218#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1219 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1220 " extension.\n\n"
1221 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1222 "Please look at the Getting Started guide for additional information.\n",
1223 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001224#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001225 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1226 " extension.\n\n"
1227 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1228 "Please look at the Getting Started guide for additional information.\n",
1229 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001230#elif defined(VK_USE_PLATFORM_METAL_EXT)
1231 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001232 " extension.\n\nDo you have a compatible "
1233 "Vulkan installable client driver (ICD) installed?\nPlease "
1234 "look at the Getting Started guide for additional "
1235 "information.\n",
1236 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001237#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001238 }
1239 auto const app = vk::ApplicationInfo()
1240 .setPApplicationName(APP_SHORT_NAME)
1241 .setApplicationVersion(0)
1242 .setPEngineName(APP_SHORT_NAME)
1243 .setEngineVersion(0)
1244 .setApiVersion(VK_API_VERSION_1_0);
1245 auto const inst_info = vk::InstanceCreateInfo()
1246 .setPApplicationInfo(&app)
1247 .setEnabledLayerCount(enabled_layer_count)
1248 .setPpEnabledLayerNames(instance_validation_layers)
1249 .setEnabledExtensionCount(enabled_extension_count)
1250 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001251
Dave Houlton5fa47912018-02-16 11:02:26 -07001252 result = vk::createInstance(&inst_info, nullptr, &inst);
1253 if (result == vk::Result::eErrorIncompatibleDriver) {
1254 ERR_EXIT(
1255 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1256 "Please look at the Getting Started guide for additional information.\n",
1257 "vkCreateInstance Failure");
1258 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1259 ERR_EXIT(
1260 "Cannot find a specified extension library.\n"
1261 "Make sure your layers path is set appropriately.\n",
1262 "vkCreateInstance Failure");
1263 } else if (result != vk::Result::eSuccess) {
1264 ERR_EXIT(
1265 "vkCreateInstance failed.\n\n"
1266 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1267 "Please look at the Getting Started guide for additional information.\n",
1268 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001269 }
1270
Witold Baryluka3b988f2021-01-07 19:03:02 +00001271 /* Make initial call to query gpu_count, then second call for gpu info */
1272 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001273 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001274 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001275
Witold Baryluka3b988f2021-01-07 19:03:02 +00001276 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001277 ERR_EXIT(
1278 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1279 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1280 "Please look at the Getting Started guide for additional information.\n",
1281 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001282 }
1283
Witold Baryluka3b988f2021-01-07 19:03:02 +00001284 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1285 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1286 VERIFY(result == vk::Result::eSuccess);
1287
1288 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1289 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1290 ERR_EXIT("Specified GPU number is not present", "User Error");
1291 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001292#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
1293 gpu_number = find_display_gpu(gpu_number, gpu_count, physical_devices);
1294 if (gpu_number < 0) {
1295 printf("Cannot find any display!\n");
1296 fflush(stdout);
1297 exit(1);
1298 }
1299#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00001300 /* Try to auto select most suitable device */
1301 if (gpu_number == -1) {
1302 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1303 memset(count_device_type, 0, sizeof(count_device_type));
1304
1305 for (uint32_t i = 0; i < gpu_count; i++) {
1306 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1307 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1308 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1309 }
1310
1311 const vk::PhysicalDeviceType device_type_preference[] = {
1312 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1313 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1314 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1315 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1316 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1317 search_for_device_type = device_type_preference[i];
1318 break;
1319 }
1320 }
1321
1322 for (uint32_t i = 0; i < gpu_count; i++) {
1323 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1324 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1325 gpu_number = i;
1326 break;
1327 }
1328 }
1329 }
Tony-LunarG27c21242021-03-11 16:28:19 -07001330#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00001331 assert(gpu_number >= 0);
1332 gpu = physical_devices[gpu_number];
1333 {
1334 auto physicalDeviceProperties = gpu.getProperties();
1335 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1336 to_string(physicalDeviceProperties.deviceType).c_str());
1337 }
1338 physical_devices.reset();
1339
Dave Houlton5fa47912018-02-16 11:02:26 -07001340 /* Look for device extensions */
1341 uint32_t device_extension_count = 0;
1342 vk::Bool32 swapchainExtFound = VK_FALSE;
1343 enabled_extension_count = 0;
1344 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001345
Mike Schuchardt7510c832018-10-29 13:23:08 -07001346 result =
1347 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001348 VERIFY(result == vk::Result::eSuccess);
1349
1350 if (device_extension_count > 0) {
1351 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1352 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001353 VERIFY(result == vk::Result::eSuccess);
1354
Dave Houlton5fa47912018-02-16 11:02:26 -07001355 for (uint32_t i = 0; i < device_extension_count; i++) {
1356 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1357 swapchainExtFound = 1;
1358 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001359 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001360 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1361 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001362 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001363 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001364 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001365 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001366
Dave Houlton5fa47912018-02-16 11:02:26 -07001367 if (!swapchainExtFound) {
1368 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1369 " extension.\n\n"
1370 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1371 "Please look at the Getting Started guide for additional information.\n",
1372 "vkCreateInstance Failure");
1373 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001374
Dave Houlton5fa47912018-02-16 11:02:26 -07001375 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001376
Dave Houlton5fa47912018-02-16 11:02:26 -07001377 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001378 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001380
Dave Houlton5fa47912018-02-16 11:02:26 -07001381 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1382 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 // Query fine-grained feature support for this device.
1385 // If app has specific feature requirements it should check supported
1386 // features based on this query
1387 vk::PhysicalDeviceFeatures physDevFeatures;
1388 gpu.getFeatures(&physDevFeatures);
1389}
1390
Tony-LunarG6cebf142019-09-11 14:32:23 -06001391void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001392// Create a WSI surface for the window:
1393#if defined(VK_USE_PLATFORM_WIN32_KHR)
1394 {
1395 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1396
1397 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1398 VERIFY(result == vk::Result::eSuccess);
1399 }
1400#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1401 {
1402 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1403
1404 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1405 VERIFY(result == vk::Result::eSuccess);
1406 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001407#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1408 {
1409 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1410
1411 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1412 VERIFY(result == vk::Result::eSuccess);
1413 }
1414#elif defined(VK_USE_PLATFORM_XCB_KHR)
1415 {
1416 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1417
1418 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1419 VERIFY(result == vk::Result::eSuccess);
1420 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001421#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1422 {
1423 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1424
1425 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1426 VERIFY(result == vk::Result::eSuccess);
1427 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001428#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001429 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001430 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001431
Bill Hollings0a0625a2019-07-15 17:39:18 -04001432 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001433 VERIFY(result == vk::Result::eSuccess);
1434 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001435#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1436 {
1437 auto result = create_display_surface();
1438 VERIFY(result == vk::Result::eSuccess);
1439 }
1440#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001441}
1442
1443void Demo::init_vk_swapchain() {
1444 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001445 // Iterate over each queue to learn whether it supports presenting:
1446 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1447 for (uint32_t i = 0; i < queue_family_count; i++) {
1448 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1449 }
1450
1451 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1452 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1453 for (uint32_t i = 0; i < queue_family_count; i++) {
1454 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1455 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1456 graphicsQueueFamilyIndex = i;
1457 }
1458
1459 if (supportsPresent[i] == VK_TRUE) {
1460 graphicsQueueFamilyIndex = i;
1461 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001462 break;
1463 }
1464 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001465 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001466
Dave Houlton5fa47912018-02-16 11:02:26 -07001467 if (presentQueueFamilyIndex == UINT32_MAX) {
1468 // If didn't find a queue that supports both graphics and present,
1469 // then
1470 // find a separate present queue.
1471 for (uint32_t i = 0; i < queue_family_count; ++i) {
1472 if (supportsPresent[i] == VK_TRUE) {
1473 presentQueueFamilyIndex = i;
1474 break;
1475 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001476 }
1477 }
1478
Dave Houlton5fa47912018-02-16 11:02:26 -07001479 // Generate error if could not find both a graphics and a present queue
1480 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1481 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1482 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001483
Dave Houlton5fa47912018-02-16 11:02:26 -07001484 graphics_queue_family_index = graphicsQueueFamilyIndex;
1485 present_queue_family_index = presentQueueFamilyIndex;
1486 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001487
Dave Houlton5fa47912018-02-16 11:02:26 -07001488 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001489
Dave Houlton5fa47912018-02-16 11:02:26 -07001490 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1491 if (!separate_present_queue) {
1492 present_queue = graphics_queue;
1493 } else {
1494 device.getQueue(present_queue_family_index, 0, &present_queue);
1495 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001496
Dave Houlton5fa47912018-02-16 11:02:26 -07001497 // Get the list of VkFormat's that are supported:
1498 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001499 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001500 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001501
Dave Houlton5fa47912018-02-16 11:02:26 -07001502 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1503 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1504 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001505
Dave Houlton5fa47912018-02-16 11:02:26 -07001506 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1507 // the surface has no preferred format. Otherwise, at least one
1508 // supported format will be returned.
1509 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1510 format = vk::Format::eB8G8R8A8Unorm;
1511 } else {
1512 assert(formatCount >= 1);
1513 format = surfFormats[0].format;
1514 }
1515 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001516
Dave Houlton5fa47912018-02-16 11:02:26 -07001517 quit = false;
1518 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001519
Dave Houlton5fa47912018-02-16 11:02:26 -07001520 // Create semaphores to synchronize acquiring presentable buffers before
1521 // rendering and waiting for drawing to be complete before presenting
1522 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001523
Dave Houlton5fa47912018-02-16 11:02:26 -07001524 // Create fences that we can use to throttle if we get too far
1525 // ahead of the image presents
1526 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1527 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1528 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1529 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001530
Dave Houlton5fa47912018-02-16 11:02:26 -07001531 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1532 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001533
Dave Houlton5fa47912018-02-16 11:02:26 -07001534 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1535 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001536
Dave Houlton5fa47912018-02-16 11:02:26 -07001537 if (separate_present_queue) {
1538 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001539 VERIFY(result == vk::Result::eSuccess);
1540 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001541 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001542 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001543
Dave Houlton5fa47912018-02-16 11:02:26 -07001544 // Get Memory information and properties
1545 gpu.getMemoryProperties(&memory_properties);
1546}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001547
Dave Houlton5fa47912018-02-16 11:02:26 -07001548void Demo::prepare() {
1549 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1550 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1551 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001552
Dave Houlton5fa47912018-02-16 11:02:26 -07001553 auto const cmd = vk::CommandBufferAllocateInfo()
1554 .setCommandPool(cmd_pool)
1555 .setLevel(vk::CommandBufferLevel::ePrimary)
1556 .setCommandBufferCount(1);
1557
1558 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1559 VERIFY(result == vk::Result::eSuccess);
1560
1561 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1562
1563 result = this->cmd.begin(&cmd_buf_info);
1564 VERIFY(result == vk::Result::eSuccess);
1565
1566 prepare_buffers();
1567 prepare_depth();
1568 prepare_textures();
1569 prepare_cube_data_buffers();
1570
1571 prepare_descriptor_layout();
1572 prepare_render_pass();
1573 prepare_pipeline();
1574
1575 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1576 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1577 VERIFY(result == vk::Result::eSuccess);
1578 }
1579
1580 if (separate_present_queue) {
1581 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1582
1583 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1584 VERIFY(result == vk::Result::eSuccess);
1585
1586 auto const present_cmd = vk::CommandBufferAllocateInfo()
1587 .setCommandPool(present_cmd_pool)
1588 .setLevel(vk::CommandBufferLevel::ePrimary)
1589 .setCommandBufferCount(1);
1590
1591 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1592 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1593 VERIFY(result == vk::Result::eSuccess);
1594
1595 build_image_ownership_cmd(i);
1596 }
1597 }
1598
1599 prepare_descriptor_pool();
1600 prepare_descriptor_set();
1601
1602 prepare_framebuffers();
1603
1604 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1605 current_buffer = i;
1606 draw_build_cmd(swapchain_image_resources[i].cmd);
1607 }
1608
1609 /*
1610 * Prepare functions above may generate pipeline commands
1611 * that need to be flushed before beginning the render loop.
1612 */
1613 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001614 if (staging_texture.buffer) {
1615 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001616 }
1617
1618 current_buffer = 0;
1619 prepared = true;
1620}
1621
1622void Demo::prepare_buffers() {
1623 vk::SwapchainKHR oldSwapchain = swapchain;
1624
1625 // Check the surface capabilities and formats
1626 vk::SurfaceCapabilitiesKHR surfCapabilities;
1627 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1628 VERIFY(result == vk::Result::eSuccess);
1629
1630 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001631 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001632 VERIFY(result == vk::Result::eSuccess);
1633
1634 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1635 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1636 VERIFY(result == vk::Result::eSuccess);
1637
1638 vk::Extent2D swapchainExtent;
1639 // width and height are either both -1, or both not -1.
1640 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1641 // If the surface size is undefined, the size is set to
1642 // the size of the images requested.
1643 swapchainExtent.width = width;
1644 swapchainExtent.height = height;
1645 } else {
1646 // If the surface size is defined, the swap chain size must match
1647 swapchainExtent = surfCapabilities.currentExtent;
1648 width = surfCapabilities.currentExtent.width;
1649 height = surfCapabilities.currentExtent.height;
1650 }
1651
1652 // The FIFO present mode is guaranteed by the spec to be supported
1653 // and to have no tearing. It's a great default present mode to use.
1654 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1655
1656 // There are times when you may wish to use another present mode. The
1657 // following code shows how to select them, and the comments provide some
1658 // reasons you may wish to use them.
1659 //
1660 // It should be noted that Vulkan 1.0 doesn't provide a method for
1661 // synchronizing rendering with the presentation engine's display. There
1662 // is a method provided for throttling rendering with the display, but
1663 // there are some presentation engines for which this method will not work.
1664 // If an application doesn't throttle its rendering, and if it renders much
1665 // faster than the refresh rate of the display, this can waste power on
1666 // mobile devices. That is because power is being spent rendering images
1667 // that may never be seen.
1668
1669 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1670 // about
1671 // tearing, or have some way of synchronizing their rendering with the
1672 // display.
1673 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1674 // generally render a new presentable image every refresh cycle, but are
1675 // occasionally early. In this case, the application wants the new
1676 // image
1677 // to be displayed instead of the previously-queued-for-presentation
1678 // image
1679 // that has not yet been displayed.
1680 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1681 // render a new presentable image every refresh cycle, but are
1682 // occasionally
1683 // late. In this case (perhaps because of stuttering/latency concerns),
1684 // the application wants the late image to be immediately displayed,
1685 // even
1686 // though that may mean some tearing.
1687
1688 if (presentMode != swapchainPresentMode) {
1689 for (size_t i = 0; i < presentModeCount; ++i) {
1690 if (presentModes[i] == presentMode) {
1691 swapchainPresentMode = presentMode;
1692 break;
1693 }
1694 }
1695 }
1696
1697 if (swapchainPresentMode != presentMode) {
1698 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1699 }
1700
1701 // Determine the number of VkImages to use in the swap chain.
1702 // Application desires to acquire 3 images at a time for triple
1703 // buffering
1704 uint32_t desiredNumOfSwapchainImages = 3;
1705 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1706 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1707 }
1708
1709 // If maxImageCount is 0, we can ask for as many images as we want,
1710 // otherwise
1711 // we're limited to maxImageCount
1712 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1713 // Application must settle for fewer images than desired:
1714 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1715 }
1716
1717 vk::SurfaceTransformFlagBitsKHR preTransform;
1718 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1719 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1720 } else {
1721 preTransform = surfCapabilities.currentTransform;
1722 }
1723
1724 // Find a supported composite alpha mode - one of these is guaranteed to be set
1725 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1726 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1727 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1728 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1729 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1730 vk::CompositeAlphaFlagBitsKHR::eInherit,
1731 };
1732 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1733 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1734 compositeAlpha = compositeAlphaFlags[i];
1735 break;
1736 }
1737 }
1738
1739 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1740 .setSurface(surface)
1741 .setMinImageCount(desiredNumOfSwapchainImages)
1742 .setImageFormat(format)
1743 .setImageColorSpace(color_space)
1744 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1745 .setImageArrayLayers(1)
1746 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1747 .setImageSharingMode(vk::SharingMode::eExclusive)
1748 .setQueueFamilyIndexCount(0)
1749 .setPQueueFamilyIndices(nullptr)
1750 .setPreTransform(preTransform)
1751 .setCompositeAlpha(compositeAlpha)
1752 .setPresentMode(swapchainPresentMode)
1753 .setClipped(true)
1754 .setOldSwapchain(oldSwapchain);
1755
1756 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1757 VERIFY(result == vk::Result::eSuccess);
1758
1759 // If we just re-created an existing swapchain, we should destroy the
1760 // old
1761 // swapchain at this point.
1762 // Note: destroying the swapchain also cleans up all its associated
1763 // presentable images once the platform is done with them.
1764 if (oldSwapchain) {
1765 device.destroySwapchainKHR(oldSwapchain, nullptr);
1766 }
1767
Mike Schuchardt7510c832018-10-29 13:23:08 -07001768 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001769 VERIFY(result == vk::Result::eSuccess);
1770
1771 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1772 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1773 VERIFY(result == vk::Result::eSuccess);
1774
1775 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1776
1777 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1778 auto color_image_view = vk::ImageViewCreateInfo()
1779 .setViewType(vk::ImageViewType::e2D)
1780 .setFormat(format)
1781 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1782
1783 swapchain_image_resources[i].image = swapchainImages[i];
1784
1785 color_image_view.image = swapchain_image_resources[i].image;
1786
1787 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1788 VERIFY(result == vk::Result::eSuccess);
1789 }
1790}
1791
1792void Demo::prepare_cube_data_buffers() {
1793 mat4x4 VP;
1794 mat4x4_mul(VP, projection_matrix, view_matrix);
1795
1796 mat4x4 MVP;
1797 mat4x4_mul(MVP, VP, model_matrix);
1798
1799 vktexcube_vs_uniform data;
1800 memcpy(data.mvp, MVP, sizeof(MVP));
1801 // dumpMatrix("MVP", MVP)
1802
1803 for (int32_t i = 0; i < 12 * 3; i++) {
1804 data.position[i][0] = g_vertex_buffer_data[i * 3];
1805 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1806 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1807 data.position[i][3] = 1.0f;
1808 data.attr[i][0] = g_uv_buffer_data[2 * i];
1809 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1810 data.attr[i][2] = 0;
1811 data.attr[i][3] = 0;
1812 }
1813
1814 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1815
1816 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1817 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001818 VERIFY(result == vk::Result::eSuccess);
1819
1820 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001821 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001822
Dave Houlton5fa47912018-02-16 11:02:26 -07001823 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001824
Dave Houlton5fa47912018-02-16 11:02:26 -07001825 bool const pass = memory_type_from_properties(
1826 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1827 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001828 VERIFY(pass);
1829
Dave Houlton5fa47912018-02-16 11:02:26 -07001830 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001831 VERIFY(result == vk::Result::eSuccess);
1832
Tony-LunarG37af49f2019-12-19 12:04:19 -07001833 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1834 &swapchain_image_resources[i].uniform_memory_ptr);
1835 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001836
Tony-LunarG37af49f2019-12-19 12:04:19 -07001837 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001838
1839 result =
1840 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001841 VERIFY(result == vk::Result::eSuccess);
1842 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001843}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001844
Dave Houlton5fa47912018-02-16 11:02:26 -07001845void Demo::prepare_depth() {
1846 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001847
Dave Houlton5fa47912018-02-16 11:02:26 -07001848 auto const image = vk::ImageCreateInfo()
1849 .setImageType(vk::ImageType::e2D)
1850 .setFormat(depth.format)
1851 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1852 .setMipLevels(1)
1853 .setArrayLayers(1)
1854 .setSamples(vk::SampleCountFlagBits::e1)
1855 .setTiling(vk::ImageTiling::eOptimal)
1856 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1857 .setSharingMode(vk::SharingMode::eExclusive)
1858 .setQueueFamilyIndexCount(0)
1859 .setPQueueFamilyIndices(nullptr)
1860 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001861
Dave Houlton5fa47912018-02-16 11:02:26 -07001862 auto result = device.createImage(&image, nullptr, &depth.image);
1863 VERIFY(result == vk::Result::eSuccess);
1864
1865 vk::MemoryRequirements mem_reqs;
1866 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1867
1868 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1869 depth.mem_alloc.setMemoryTypeIndex(0);
1870
1871 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1872 &depth.mem_alloc.memoryTypeIndex);
1873 VERIFY(pass);
1874
1875 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1876 VERIFY(result == vk::Result::eSuccess);
1877
1878 result = device.bindImageMemory(depth.image, depth.mem, 0);
1879 VERIFY(result == vk::Result::eSuccess);
1880
1881 auto const view = vk::ImageViewCreateInfo()
1882 .setImage(depth.image)
1883 .setViewType(vk::ImageViewType::e2D)
1884 .setFormat(depth.format)
1885 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1886 result = device.createImageView(&view, nullptr, &depth.view);
1887 VERIFY(result == vk::Result::eSuccess);
1888}
1889
1890void Demo::prepare_descriptor_layout() {
1891 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1892 .setBinding(0)
1893 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1894 .setDescriptorCount(1)
1895 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1896 .setPImmutableSamplers(nullptr),
1897 vk::DescriptorSetLayoutBinding()
1898 .setBinding(1)
1899 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1900 .setDescriptorCount(texture_count)
1901 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1902 .setPImmutableSamplers(nullptr)};
1903
1904 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1905
1906 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1907 VERIFY(result == vk::Result::eSuccess);
1908
1909 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1910
1911 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1912 VERIFY(result == vk::Result::eSuccess);
1913}
1914
1915void Demo::prepare_descriptor_pool() {
1916 vk::DescriptorPoolSize const poolSizes[2] = {
1917 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1918 vk::DescriptorPoolSize()
1919 .setType(vk::DescriptorType::eCombinedImageSampler)
1920 .setDescriptorCount(swapchainImageCount * texture_count)};
1921
1922 auto const descriptor_pool =
1923 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1924
1925 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1926 VERIFY(result == vk::Result::eSuccess);
1927}
1928
1929void Demo::prepare_descriptor_set() {
1930 auto const alloc_info =
1931 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1932
1933 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1934
1935 vk::DescriptorImageInfo tex_descs[texture_count];
1936 for (uint32_t i = 0; i < texture_count; i++) {
1937 tex_descs[i].setSampler(textures[i].sampler);
1938 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001939 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001940 }
1941
1942 vk::WriteDescriptorSet writes[2];
1943
1944 writes[0].setDescriptorCount(1);
1945 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1946 writes[0].setPBufferInfo(&buffer_info);
1947
1948 writes[1].setDstBinding(1);
1949 writes[1].setDescriptorCount(texture_count);
1950 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1951 writes[1].setPImageInfo(tex_descs);
1952
1953 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1954 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001955 VERIFY(result == vk::Result::eSuccess);
1956
Dave Houlton5fa47912018-02-16 11:02:26 -07001957 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1958 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1959 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1960 device.updateDescriptorSets(2, writes, 0, nullptr);
1961 }
1962}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001963
Dave Houlton5fa47912018-02-16 11:02:26 -07001964void Demo::prepare_framebuffers() {
1965 vk::ImageView attachments[2];
1966 attachments[1] = depth.view;
1967
1968 auto const fb_info = vk::FramebufferCreateInfo()
1969 .setRenderPass(render_pass)
1970 .setAttachmentCount(2)
1971 .setPAttachments(attachments)
1972 .setWidth((uint32_t)width)
1973 .setHeight((uint32_t)height)
1974 .setLayers(1);
1975
1976 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1977 attachments[0] = swapchain_image_resources[i].view;
1978 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001979 VERIFY(result == vk::Result::eSuccess);
1980 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001981}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001982
Dave Houlton5fa47912018-02-16 11:02:26 -07001983vk::ShaderModule Demo::prepare_fs() {
1984 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001985#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001986 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001987
Dave Houlton5fa47912018-02-16 11:02:26 -07001988 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001989
Dave Houlton5fa47912018-02-16 11:02:26 -07001990 return frag_shader_module;
1991}
1992
1993void Demo::prepare_pipeline() {
1994 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1995 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1996 VERIFY(result == vk::Result::eSuccess);
1997
1998 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1999 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
2000 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
2001
2002 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
2003
2004 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
2005
2006 // TODO: Where are pViewports and pScissors set?
2007 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
2008
2009 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
2010 .setDepthClampEnable(VK_FALSE)
2011 .setRasterizerDiscardEnable(VK_FALSE)
2012 .setPolygonMode(vk::PolygonMode::eFill)
2013 .setCullMode(vk::CullModeFlagBits::eBack)
2014 .setFrontFace(vk::FrontFace::eCounterClockwise)
2015 .setDepthBiasEnable(VK_FALSE)
2016 .setLineWidth(1.0f);
2017
2018 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
2019
2020 auto const stencilOp =
2021 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
2022
2023 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2024 .setDepthTestEnable(VK_TRUE)
2025 .setDepthWriteEnable(VK_TRUE)
2026 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2027 .setDepthBoundsTestEnable(VK_FALSE)
2028 .setStencilTestEnable(VK_FALSE)
2029 .setFront(stencilOp)
2030 .setBack(stencilOp);
2031
2032 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2033 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2034 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2035
2036 auto const colorBlendInfo =
2037 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2038
2039 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2040
2041 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2042
2043 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2044 .setStageCount(2)
2045 .setPStages(shaderStageInfo)
2046 .setPVertexInputState(&vertexInputInfo)
2047 .setPInputAssemblyState(&inputAssemblyInfo)
2048 .setPViewportState(&viewportInfo)
2049 .setPRasterizationState(&rasterizationInfo)
2050 .setPMultisampleState(&multisampleInfo)
2051 .setPDepthStencilState(&depthStencilInfo)
2052 .setPColorBlendState(&colorBlendInfo)
2053 .setPDynamicState(&dynamicStateInfo)
2054 .setLayout(pipeline_layout)
2055 .setRenderPass(render_pass);
2056
2057 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2058 VERIFY(result == vk::Result::eSuccess);
2059
2060 device.destroyShaderModule(frag_shader_module, nullptr);
2061 device.destroyShaderModule(vert_shader_module, nullptr);
2062}
2063
2064void Demo::prepare_render_pass() {
2065 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2066 // because at the start of the renderpass, we don't care about their contents.
2067 // At the start of the subpass, the color attachment's layout will be transitioned
2068 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2069 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2070 // the renderpass, the color attachment's layout will be transitioned to
2071 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2072 // the renderpass, no barriers are necessary.
2073 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2074 .setFormat(format)
2075 .setSamples(vk::SampleCountFlagBits::e1)
2076 .setLoadOp(vk::AttachmentLoadOp::eClear)
2077 .setStoreOp(vk::AttachmentStoreOp::eStore)
2078 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2079 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2080 .setInitialLayout(vk::ImageLayout::eUndefined)
2081 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2082 vk::AttachmentDescription()
2083 .setFormat(depth.format)
2084 .setSamples(vk::SampleCountFlagBits::e1)
2085 .setLoadOp(vk::AttachmentLoadOp::eClear)
2086 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2087 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2088 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2089 .setInitialLayout(vk::ImageLayout::eUndefined)
2090 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2091
2092 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2093
2094 auto const depth_reference =
2095 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2096
2097 auto const subpass = vk::SubpassDescription()
2098 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2099 .setInputAttachmentCount(0)
2100 .setPInputAttachments(nullptr)
2101 .setColorAttachmentCount(1)
2102 .setPColorAttachments(&color_reference)
2103 .setPResolveAttachments(nullptr)
2104 .setPDepthStencilAttachment(&depth_reference)
2105 .setPreserveAttachmentCount(0)
2106 .setPPreserveAttachments(nullptr);
2107
Tony-LunarG495604b2019-06-13 15:32:05 -06002108 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2109 vk::SubpassDependency const dependencies[2] = {
2110 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2111 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2112 .setDstSubpass(0)
2113 .setSrcStageMask(stages)
2114 .setDstStageMask(stages)
2115 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2116 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2117 .setDependencyFlags(vk::DependencyFlags()),
2118 vk::SubpassDependency() // Image layout transition
2119 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2120 .setDstSubpass(0)
2121 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2122 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2123 .setSrcAccessMask(vk::AccessFlagBits())
2124 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2125 .setDependencyFlags(vk::DependencyFlags()),
2126 };
2127
Dave Houlton5fa47912018-02-16 11:02:26 -07002128 auto const rp_info = vk::RenderPassCreateInfo()
2129 .setAttachmentCount(2)
2130 .setPAttachments(attachments)
2131 .setSubpassCount(1)
2132 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002133 .setDependencyCount(2)
2134 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002135
2136 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2137 VERIFY(result == vk::Result::eSuccess);
2138}
2139
2140vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2141 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2142
2143 vk::ShaderModule module;
2144 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2145 VERIFY(result == vk::Result::eSuccess);
2146
2147 return module;
2148}
2149
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002150void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2151 int32_t tex_width;
2152 int32_t tex_height;
2153
2154 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2155 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2156 }
2157
2158 tex_obj->tex_width = tex_width;
2159 tex_obj->tex_height = tex_height;
2160
2161 auto const buffer_create_info = vk::BufferCreateInfo()
2162 .setSize(tex_width * tex_height * 4)
2163 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2164 .setSharingMode(vk::SharingMode::eExclusive)
2165 .setQueueFamilyIndexCount(0)
2166 .setPQueueFamilyIndices(nullptr);
2167
2168 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2169 VERIFY(result == vk::Result::eSuccess);
2170
2171 vk::MemoryRequirements mem_reqs;
2172 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2173
2174 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2175 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2176
2177 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2178 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2179 VERIFY(pass == true);
2180
2181 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2182 VERIFY(result == vk::Result::eSuccess);
2183
2184 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2185 VERIFY(result == vk::Result::eSuccess);
2186
2187 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002188 layout.rowPitch = tex_width * 4;
2189 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2190 VERIFY(data.result == vk::Result::eSuccess);
2191
2192 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2193 fprintf(stderr, "Error loading texture: %s\n", filename);
2194 }
2195
2196 device.unmapMemory(tex_obj->mem);
2197}
2198
Dave Houlton5fa47912018-02-16 11:02:26 -07002199void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2200 vk::MemoryPropertyFlags required_props) {
2201 int32_t tex_width;
2202 int32_t tex_height;
2203 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2204 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002205 }
2206
Dave Houlton5fa47912018-02-16 11:02:26 -07002207 tex_obj->tex_width = tex_width;
2208 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002209
Dave Houlton5fa47912018-02-16 11:02:26 -07002210 auto const image_create_info = vk::ImageCreateInfo()
2211 .setImageType(vk::ImageType::e2D)
2212 .setFormat(vk::Format::eR8G8B8A8Unorm)
2213 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2214 .setMipLevels(1)
2215 .setArrayLayers(1)
2216 .setSamples(vk::SampleCountFlagBits::e1)
2217 .setTiling(tiling)
2218 .setUsage(usage)
2219 .setSharingMode(vk::SharingMode::eExclusive)
2220 .setQueueFamilyIndexCount(0)
2221 .setPQueueFamilyIndices(nullptr)
2222 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002223
Dave Houlton5fa47912018-02-16 11:02:26 -07002224 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2225 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002226
Dave Houlton5fa47912018-02-16 11:02:26 -07002227 vk::MemoryRequirements mem_reqs;
2228 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002229
Dave Houlton5fa47912018-02-16 11:02:26 -07002230 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2231 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002232
Dave Houlton5fa47912018-02-16 11:02:26 -07002233 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2234 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002235
Dave Houlton5fa47912018-02-16 11:02:26 -07002236 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2237 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002238
Dave Houlton5fa47912018-02-16 11:02:26 -07002239 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2240 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002241
Dave Houlton5fa47912018-02-16 11:02:26 -07002242 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2243 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2244 vk::SubresourceLayout layout;
2245 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002246
Dave Houlton5fa47912018-02-16 11:02:26 -07002247 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002248 VERIFY(data.result == vk::Result::eSuccess);
2249
Dave Houlton5fa47912018-02-16 11:02:26 -07002250 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2251 fprintf(stderr, "Error loading texture: %s\n", filename);
2252 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002253
Dave Houlton5fa47912018-02-16 11:02:26 -07002254 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002255 }
2256
Dave Houlton5fa47912018-02-16 11:02:26 -07002257 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2258}
2259
2260void Demo::prepare_textures() {
2261 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2262 vk::FormatProperties props;
2263 gpu.getFormatProperties(tex_format, &props);
2264
2265 for (uint32_t i = 0; i < texture_count; i++) {
2266 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2267 /* Device can texture using linear textures */
2268 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2269 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2270 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2271 // shader to run until layout transition completes
2272 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2273 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2274 vk::PipelineStageFlagBits::eFragmentShader);
2275 staging_texture.image = vk::Image();
2276 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2277 /* Must use staging buffer to copy linear texture to optimized */
2278
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002279 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002280
2281 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2282 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2283 vk::MemoryPropertyFlagBits::eDeviceLocal);
2284
Dave Houlton5fa47912018-02-16 11:02:26 -07002285 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2286 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2287 vk::PipelineStageFlagBits::eTransfer);
2288
2289 auto const subresource = vk::ImageSubresourceLayers()
2290 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2291 .setMipLevel(0)
2292 .setBaseArrayLayer(0)
2293 .setLayerCount(1);
2294
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002295 auto const copy_region =
2296 vk::BufferImageCopy()
2297 .setBufferOffset(0)
2298 .setBufferRowLength(staging_texture.tex_width)
2299 .setBufferImageHeight(staging_texture.tex_height)
2300 .setImageSubresource(subresource)
2301 .setImageOffset({0, 0, 0})
2302 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002303
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002304 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002305
2306 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2307 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2308 vk::PipelineStageFlagBits::eFragmentShader);
2309 } else {
2310 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002311 }
2312
Dave Houlton5fa47912018-02-16 11:02:26 -07002313 auto const samplerInfo = vk::SamplerCreateInfo()
2314 .setMagFilter(vk::Filter::eNearest)
2315 .setMinFilter(vk::Filter::eNearest)
2316 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2317 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2318 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2319 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2320 .setMipLodBias(0.0f)
2321 .setAnisotropyEnable(VK_FALSE)
2322 .setMaxAnisotropy(1)
2323 .setCompareEnable(VK_FALSE)
2324 .setCompareOp(vk::CompareOp::eNever)
2325 .setMinLod(0.0f)
2326 .setMaxLod(0.0f)
2327 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2328 .setUnnormalizedCoordinates(VK_FALSE);
2329
2330 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2331 VERIFY(result == vk::Result::eSuccess);
2332
2333 auto const viewInfo = vk::ImageViewCreateInfo()
2334 .setImage(textures[i].image)
2335 .setViewType(vk::ImageViewType::e2D)
2336 .setFormat(tex_format)
2337 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2338
2339 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2340 VERIFY(result == vk::Result::eSuccess);
2341 }
2342}
2343
2344vk::ShaderModule Demo::prepare_vs() {
2345 const uint32_t vertShaderCode[] = {
2346#include "cube.vert.inc"
2347 };
2348
2349 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2350
2351 return vert_shader_module;
2352}
2353
2354void Demo::resize() {
2355 uint32_t i;
2356
2357 // Don't react to resize until after first initialization.
2358 if (!prepared) {
2359 return;
2360 }
2361
2362 // In order to properly resize the window, we must re-create the
2363 // swapchain
2364 // AND redo the command buffers, etc.
2365 //
2366 // First, perform part of the cleanup() function:
2367 prepared = false;
2368 auto result = device.waitIdle();
2369 VERIFY(result == vk::Result::eSuccess);
2370
2371 for (i = 0; i < swapchainImageCount; i++) {
2372 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2373 }
2374
2375 device.destroyDescriptorPool(desc_pool, nullptr);
2376
2377 device.destroyPipeline(pipeline, nullptr);
2378 device.destroyPipelineCache(pipelineCache, nullptr);
2379 device.destroyRenderPass(render_pass, nullptr);
2380 device.destroyPipelineLayout(pipeline_layout, nullptr);
2381 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2382
2383 for (i = 0; i < texture_count; i++) {
2384 device.destroyImageView(textures[i].view, nullptr);
2385 device.destroyImage(textures[i].image, nullptr);
2386 device.freeMemory(textures[i].mem, nullptr);
2387 device.destroySampler(textures[i].sampler, nullptr);
2388 }
2389
2390 device.destroyImageView(depth.view, nullptr);
2391 device.destroyImage(depth.image, nullptr);
2392 device.freeMemory(depth.mem, nullptr);
2393
2394 for (i = 0; i < swapchainImageCount; i++) {
2395 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002396 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002397 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002398 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002399 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2400 }
2401
2402 device.destroyCommandPool(cmd_pool, nullptr);
2403 if (separate_present_queue) {
2404 device.destroyCommandPool(present_cmd_pool, nullptr);
2405 }
2406
2407 // Second, re-perform the prepare() function, which will re-create the
2408 // swapchain.
2409 prepare();
2410}
2411
2412void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2413 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2414 assert(cmd);
2415
2416 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2417 vk::AccessFlags flags;
2418
2419 switch (layout) {
2420 case vk::ImageLayout::eTransferDstOptimal:
2421 // Make sure anything that was copying from this image has
2422 // completed
2423 flags = vk::AccessFlagBits::eTransferWrite;
2424 break;
2425 case vk::ImageLayout::eColorAttachmentOptimal:
2426 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2427 break;
2428 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2429 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2430 break;
2431 case vk::ImageLayout::eShaderReadOnlyOptimal:
2432 // Make sure any Copy or CPU writes to image are flushed
2433 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2434 break;
2435 case vk::ImageLayout::eTransferSrcOptimal:
2436 flags = vk::AccessFlagBits::eTransferRead;
2437 break;
2438 case vk::ImageLayout::ePresentSrcKHR:
2439 flags = vk::AccessFlagBits::eMemoryRead;
2440 break;
2441 default:
2442 break;
2443 }
2444
2445 return flags;
2446 };
2447
2448 auto const barrier = vk::ImageMemoryBarrier()
2449 .setSrcAccessMask(srcAccessMask)
2450 .setDstAccessMask(DstAccessMask(newLayout))
2451 .setOldLayout(oldLayout)
2452 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002453 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2454 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002455 .setImage(image)
2456 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2457
2458 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2459}
2460
2461void Demo::update_data_buffer() {
2462 mat4x4 VP;
2463 mat4x4_mul(VP, projection_matrix, view_matrix);
2464
2465 // Rotate around the Y axis
2466 mat4x4 Model;
2467 mat4x4_dup(Model, model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -07002468 mat4x4_rotate_Y(model_matrix, Model, (float)degreesToRadians(spin_angle));
2469 mat4x4_orthonormalize(model_matrix, model_matrix);
Dave Houlton5fa47912018-02-16 11:02:26 -07002470
2471 mat4x4 MVP;
2472 mat4x4_mul(MVP, VP, model_matrix);
2473
Tony-LunarG37af49f2019-12-19 12:04:19 -07002474 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002475}
2476
Karl Schultzb7940402018-05-29 13:09:22 -06002477/* Convert ppm image data from header file into RGBA texture image */
2478#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002479bool 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 -06002480 (void)filename;
2481 char *cPtr;
2482 cPtr = (char *)lunarg_ppm;
2483 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002484 return false;
2485 }
Karl Schultzb7940402018-05-29 13:09:22 -06002486 while (strncmp(cPtr++, "\n", 1))
2487 ;
2488 sscanf(cPtr, "%u %u", width, height);
2489 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002490 return true;
2491 }
Karl Schultzb7940402018-05-29 13:09:22 -06002492 while (strncmp(cPtr++, "\n", 1))
2493 ;
2494 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002495 return false;
2496 }
Karl Schultzb7940402018-05-29 13:09:22 -06002497 while (strncmp(cPtr++, "\n", 1))
2498 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002499 for (int y = 0; y < *height; y++) {
2500 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002501 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002502 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002503 rowPtr[3] = 255; /* Alpha of 1 */
2504 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002505 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002506 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002507 rgba_data += layout->rowPitch;
2508 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002509 return true;
2510}
2511
2512bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2513 // Search memtypes to find first index with those properties
2514 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2515 if ((typeBits & 1) == 1) {
2516 // Type is available, does it match user properties?
2517 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2518 *typeIndex = i;
2519 return true;
2520 }
2521 }
2522 typeBits >>= 1;
2523 }
2524
2525 // No memory types matched, return failure
2526 return false;
2527}
2528
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002529#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002530void Demo::run() {
2531 if (!prepared) {
2532 return;
2533 }
2534
2535 draw();
2536 curFrame++;
2537
Petr Krausd88e4e52019-01-23 18:45:04 +01002538 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002539 PostQuitMessage(validation_error);
2540 }
2541}
2542
2543void Demo::create_window() {
2544 WNDCLASSEX win_class;
2545
2546 // Initialize the window class structure:
2547 win_class.cbSize = sizeof(WNDCLASSEX);
2548 win_class.style = CS_HREDRAW | CS_VREDRAW;
2549 win_class.lpfnWndProc = WndProc;
2550 win_class.cbClsExtra = 0;
2551 win_class.cbWndExtra = 0;
2552 win_class.hInstance = connection; // hInstance
2553 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2554 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2555 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2556 win_class.lpszMenuName = nullptr;
2557 win_class.lpszClassName = name;
2558 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2559
2560 // Register window class:
2561 if (!RegisterClassEx(&win_class)) {
2562 // It didn't work, so try to give a useful error:
2563 printf("Unexpected error trying to start the application!\n");
2564 fflush(stdout);
2565 exit(1);
2566 }
2567
2568 // Create window with the registered class:
2569 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2570 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2571 window = CreateWindowEx(0,
2572 name, // class name
2573 name, // app name
2574 WS_OVERLAPPEDWINDOW | // window style
2575 WS_VISIBLE | WS_SYSMENU,
2576 100, 100, // x/y coords
2577 wr.right - wr.left, // width
2578 wr.bottom - wr.top, // height
2579 nullptr, // handle to parent
2580 nullptr, // handle to menu
2581 connection, // hInstance
2582 nullptr); // no extra parameters
2583
2584 if (!window) {
2585 // It didn't work, so try to give a useful error:
2586 printf("Cannot create a window in which to draw!\n");
2587 fflush(stdout);
2588 exit(1);
2589 }
2590
2591 // Window client area size must be at least 1 pixel high, to prevent
2592 // crash.
2593 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2594 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2595}
2596#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2597
2598void Demo::create_xlib_window() {
2599 const char *display_envar = getenv("DISPLAY");
2600 if (display_envar == nullptr || display_envar[0] == '\0') {
2601 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2602 fflush(stdout);
2603 exit(1);
2604 }
2605
2606 XInitThreads();
2607 display = XOpenDisplay(nullptr);
2608 long visualMask = VisualScreenMask;
2609 int numberOfVisuals;
2610 XVisualInfo vInfoTemplate = {};
2611 vInfoTemplate.screen = DefaultScreen(display);
2612 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2613
2614 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2615
2616 XSetWindowAttributes windowAttributes = {};
2617 windowAttributes.colormap = colormap;
2618 windowAttributes.background_pixel = 0xFFFFFFFF;
2619 windowAttributes.border_pixel = 0;
2620 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2621
2622 xlib_window =
2623 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2624 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2625
2626 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2627 XMapWindow(display, xlib_window);
2628 XFlush(display);
2629 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2630}
2631
2632void Demo::handle_xlib_event(const XEvent *event) {
2633 switch (event->type) {
2634 case ClientMessage:
2635 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2636 quit = true;
2637 }
2638 break;
2639 case KeyPress:
2640 switch (event->xkey.keycode) {
2641 case 0x9: // Escape
2642 quit = true;
2643 break;
2644 case 0x71: // left arrow key
2645 spin_angle -= spin_increment;
2646 break;
2647 case 0x72: // right arrow key
2648 spin_angle += spin_increment;
2649 break;
2650 case 0x41: // space bar
2651 pause = !pause;
2652 break;
2653 }
2654 break;
2655 case ConfigureNotify:
2656 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2657 width = event->xconfigure.width;
2658 height = event->xconfigure.height;
2659 resize();
2660 }
2661 break;
2662 default:
2663 break;
2664 }
2665}
2666
2667void Demo::run_xlib() {
2668 while (!quit) {
2669 XEvent event;
2670
2671 if (pause) {
2672 XNextEvent(display, &event);
2673 handle_xlib_event(&event);
2674 }
2675 while (XPending(display) > 0) {
2676 XNextEvent(display, &event);
2677 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002678 }
2679
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002680 draw();
2681 curFrame++;
2682
Dave Houlton5fa47912018-02-16 11:02:26 -07002683 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2684 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002685 }
2686 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002687}
Tony Barbour153cb062016-12-07 13:43:36 -07002688#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002689
Dave Houlton5fa47912018-02-16 11:02:26 -07002690void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2691 uint8_t event_code = event->response_type & 0x7f;
2692 switch (event_code) {
2693 case XCB_EXPOSE:
2694 // TODO: Resize window
2695 break;
2696 case XCB_CLIENT_MESSAGE:
2697 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2698 quit = true;
2699 }
2700 break;
2701 case XCB_KEY_RELEASE: {
2702 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002703
Dave Houlton5fa47912018-02-16 11:02:26 -07002704 switch (key->detail) {
2705 case 0x9: // Escape
2706 quit = true;
2707 break;
2708 case 0x71: // left arrow key
2709 spin_angle -= spin_increment;
2710 break;
2711 case 0x72: // right arrow key
2712 spin_angle += spin_increment;
2713 break;
2714 case 0x41: // space bar
2715 pause = !pause;
2716 break;
2717 }
2718 } break;
2719 case XCB_CONFIGURE_NOTIFY: {
2720 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2721 if ((width != cfg->width) || (height != cfg->height)) {
2722 width = cfg->width;
2723 height = cfg->height;
2724 resize();
2725 }
2726 } break;
2727 default:
2728 break;
2729 }
2730}
2731
2732void Demo::run_xcb() {
2733 xcb_flush(connection);
2734
2735 while (!quit) {
2736 xcb_generic_event_t *event;
2737
2738 if (pause) {
2739 event = xcb_wait_for_event(connection);
2740 } else {
2741 event = xcb_poll_for_event(connection);
2742 }
2743 while (event) {
2744 handle_xcb_event(event);
2745 free(event);
2746 event = xcb_poll_for_event(connection);
2747 }
2748
2749 draw();
2750 curFrame++;
2751 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2752 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002753 }
2754 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002755}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002756
Dave Houlton5fa47912018-02-16 11:02:26 -07002757void Demo::create_xcb_window() {
2758 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002759
Dave Houlton5fa47912018-02-16 11:02:26 -07002760 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002761
Dave Houlton5fa47912018-02-16 11:02:26 -07002762 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2763 value_list[0] = screen->black_pixel;
2764 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002765
Dave Houlton5fa47912018-02-16 11:02:26 -07002766 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2767 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2768
2769 /* Magic code that will send notification when window is destroyed */
2770 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2771 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2772
2773 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2774 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2775
2776 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2777
2778 free(reply);
2779
2780 xcb_map_window(connection, xcb_window);
2781
2782 // Force the x/y coordinates to 100,100 results are identical in
2783 // consecutive
2784 // runs
2785 const uint32_t coords[] = {100, 100};
2786 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2787}
2788#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2789
2790void Demo::run() {
2791 while (!quit) {
2792 if (pause) {
2793 wl_display_dispatch(display);
2794 } else {
2795 wl_display_dispatch_pending(display);
2796 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002797 draw();
2798 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002799 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002800 quit = true;
2801 }
2802 }
2803 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002804}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002805
Dave Houlton5fa47912018-02-16 11:02:26 -07002806void Demo::create_window() {
2807 window = wl_compositor_create_surface(compositor);
2808 if (!window) {
2809 printf("Can not create wayland_surface from compositor!\n");
2810 fflush(stdout);
2811 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002812 }
2813
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002814 shell_surface = wl_shell_get_shell_surface(shell, window);
2815 if (!shell_surface) {
2816 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002817 fflush(stdout);
2818 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002819 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002820
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002821 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2822 wl_shell_surface_set_toplevel(shell_surface);
2823 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002824}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002825#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2826
2827void Demo::handle_directfb_event(const DFBInputEvent *event) {
2828 if (event->type != DIET_KEYPRESS) return;
2829 switch (event->key_symbol) {
2830 case DIKS_ESCAPE: // Escape
2831 quit = true;
2832 break;
2833 case DIKS_CURSOR_LEFT: // left arrow key
2834 spin_angle -= spin_increment;
2835 break;
2836 case DIKS_CURSOR_RIGHT: // right arrow key
2837 spin_angle += spin_increment;
2838 break;
2839 case DIKS_SPACE: // space bar
2840 pause = !pause;
2841 break;
2842 default:
2843 break;
2844 }
2845}
2846
2847void Demo::run_directfb() {
2848 while (!quit) {
2849 DFBInputEvent event;
2850
2851 if (pause) {
2852 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002853 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002854 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002855 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002856
2857 draw();
2858 curFrame++;
2859 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2860 quit = true;
2861 }
2862 }
2863 }
2864}
2865
2866void Demo::create_directfb_window() {
2867 DFBResult ret;
2868
2869 ret = DirectFBInit(NULL, NULL);
2870 if (ret) {
2871 printf("DirectFBInit failed to initialize DirectFB!\n");
2872 fflush(stdout);
2873 exit(1);
2874 }
2875
2876 ret = DirectFBCreate(&dfb);
2877 if (ret) {
2878 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2879 fflush(stdout);
2880 exit(1);
2881 }
2882
2883 DFBSurfaceDescription desc;
2884 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2885 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002886 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002887 desc.height = height;
2888 ret = dfb->CreateSurface(dfb, &desc, &window);
2889 if (ret) {
2890 printf("CreateSurface failed to create DirectFB surface interface!\n");
2891 fflush(stdout);
2892 exit(1);
2893 }
2894
2895 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2896 if (ret) {
2897 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2898 fflush(stdout);
2899 exit(1);
2900 }
2901}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002902#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002903void Demo::run() {
2904 draw();
2905 curFrame++;
2906 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2907 quit = true;
2908 }
2909}
Damien Leone600c3052017-01-31 10:26:07 -07002910#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2911
Dave Houlton5fa47912018-02-16 11:02:26 -07002912vk::Result Demo::create_display_surface() {
2913 vk::Result result;
2914 uint32_t display_count;
2915 uint32_t mode_count;
2916 uint32_t plane_count;
2917 vk::DisplayPropertiesKHR display_props;
2918 vk::DisplayKHR display;
2919 vk::DisplayModePropertiesKHR mode_props;
2920 vk::DisplayPlanePropertiesKHR *plane_props;
2921 vk::Bool32 found_plane = VK_FALSE;
2922 uint32_t plane_index;
2923 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002924
Dave Houlton5fa47912018-02-16 11:02:26 -07002925 display_count = 1;
2926 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2927 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2928
2929 display = display_props.display;
2930
2931 // Get the first mode of the display
2932 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2933 VERIFY(result == vk::Result::eSuccess);
2934
2935 if (mode_count == 0) {
2936 printf("Cannot find any mode for the display!\n");
2937 fflush(stdout);
2938 exit(1);
2939 }
2940
2941 mode_count = 1;
2942 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2943 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2944
2945 // Get the list of planes
2946 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2947 VERIFY(result == vk::Result::eSuccess);
2948
2949 if (plane_count == 0) {
2950 printf("Cannot find any plane!\n");
2951 fflush(stdout);
2952 exit(1);
2953 }
2954
2955 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2956 VERIFY(plane_props != nullptr);
2957
2958 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2959 VERIFY(result == vk::Result::eSuccess);
2960
2961 // Find a plane compatible with the display
2962 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2963 uint32_t supported_count;
2964 vk::DisplayKHR *supported_displays;
2965
2966 // Disqualify planes that are bound to a different display
2967 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2968 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002969 }
2970
Dave Houlton5fa47912018-02-16 11:02:26 -07002971 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002972 VERIFY(result == vk::Result::eSuccess);
2973
Dave Houlton5fa47912018-02-16 11:02:26 -07002974 if (supported_count == 0) {
2975 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002976 }
2977
Dave Houlton5fa47912018-02-16 11:02:26 -07002978 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2979 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002980
Dave Houlton5fa47912018-02-16 11:02:26 -07002981 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002982 VERIFY(result == vk::Result::eSuccess);
2983
Dave Houlton5fa47912018-02-16 11:02:26 -07002984 for (uint32_t i = 0; i < supported_count; i++) {
2985 if (supported_displays[i] == display) {
2986 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002987 break;
2988 }
2989 }
2990
Dave Houlton5fa47912018-02-16 11:02:26 -07002991 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002992
Dave Houlton5fa47912018-02-16 11:02:26 -07002993 if (found_plane) {
2994 break;
Damien Leone600c3052017-01-31 10:26:07 -07002995 }
2996 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002997
2998 if (!found_plane) {
2999 printf("Cannot find a plane compatible with the display!\n");
3000 fflush(stdout);
3001 exit(1);
3002 }
3003
3004 free(plane_props);
3005
3006 vk::DisplayPlaneCapabilitiesKHR planeCaps;
3007 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
3008 // Find a supported alpha mode
3009 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
3010 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
3011 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
3012 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
3013 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
3014 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3015 };
3016 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3017 if (planeCaps.supportedAlpha & alphaModes[i]) {
3018 alphaMode = alphaModes[i];
3019 break;
3020 }
3021 }
3022
3023 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3024 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3025
3026 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3027 .setDisplayMode(mode_props.displayMode)
3028 .setPlaneIndex(plane_index)
3029 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3030 .setGlobalAlpha(1.0f)
3031 .setAlphaMode(alphaMode)
3032 .setImageExtent(image_extent);
3033
3034 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3035}
3036
3037void Demo::run_display() {
3038 while (!quit) {
3039 draw();
3040 curFrame++;
3041
Petr Krausd88e4e52019-01-23 18:45:04 +01003042 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003043 quit = true;
3044 }
3045 }
3046}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003047#endif
3048
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003049#if _WIN32
3050// Include header required for parsing the command line options.
3051#include <shellapi.h>
3052
3053Demo demo;
3054
3055// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003056LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3057 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003058 case WM_CLOSE:
3059 PostQuitMessage(validation_error);
3060 break;
3061 case WM_PAINT:
3062 demo.run();
3063 break;
3064 case WM_GETMINMAXINFO: // set window's minimum size
3065 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3066 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003067 case WM_ERASEBKGND:
3068 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003069 case WM_SIZE:
3070 // Resize the application to the new window size, except when
3071 // it was minimized. Vulkan doesn't support images or swapchains
3072 // with width=0 and height=0.
3073 if (wParam != SIZE_MINIMIZED) {
3074 demo.width = lParam & 0xffff;
3075 demo.height = (lParam & 0xffff0000) >> 16;
3076 demo.resize();
3077 }
3078 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003079 case WM_KEYDOWN:
3080 switch (wParam) {
3081 case VK_ESCAPE:
3082 PostQuitMessage(validation_error);
3083 break;
3084 case VK_LEFT:
3085 demo.spin_angle -= demo.spin_increment;
3086 break;
3087 case VK_RIGHT:
3088 demo.spin_angle += demo.spin_increment;
3089 break;
3090 case VK_SPACE:
3091 demo.pause = !demo.pause;
3092 break;
3093 }
3094 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003095 default:
3096 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003097 }
3098
3099 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3100}
3101
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003102int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003103 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003104 MSG msg; // message
3105 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003106 int argc;
3107 char **argv;
3108
Jamie Madillb2ff6502017-03-15 16:17:46 -04003109 // Ensure wParam is initialized.
3110 msg.wParam = 0;
3111
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003112 // Use the CommandLine functions to get the command line arguments.
3113 // Unfortunately, Microsoft outputs
3114 // this information as wide characters for Unicode, and we simply want the
3115 // Ascii version to be compatible
3116 // with the non-Windows side. So, we have to convert the information to
3117 // Ascii character strings.
3118 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003119 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003120 argc = 0;
3121 }
3122
Jeremy Hayes9d304782016-10-09 11:48:12 -06003123 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003124 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003125 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003126 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003127 } else {
3128 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003129 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3130 size_t numConverted = 0;
3131
3132 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003133 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003134 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003135 }
3136 }
3137 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003138 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003139 argv = nullptr;
3140 }
3141
3142 demo.init(argc, argv);
3143
3144 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003145 if (argc > 0 && argv != nullptr) {
3146 for (int iii = 0; iii < argc; iii++) {
3147 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003148 free(argv[iii]);
3149 }
3150 }
3151 free(argv);
3152 }
3153
3154 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003155 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003156 demo.create_window();
3157 demo.init_vk_swapchain();
3158
3159 demo.prepare();
3160
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003161 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003162
3163 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003164 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003165 if (demo.pause) {
3166 const BOOL succ = WaitMessage();
3167
3168 if (!succ) {
3169 const auto &suppress_popups = demo.suppress_popups;
3170 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3171 }
3172 }
3173
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003174 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003175 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003176 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003177 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003178 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003179 /* Translate and dispatch to event queue*/
3180 TranslateMessage(&msg);
3181 DispatchMessage(&msg);
3182 }
3183 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3184 }
3185
3186 demo.cleanup();
3187
3188 return (int)msg.wParam;
3189}
3190
3191#elif __linux__
3192
Jeremy Hayes9d304782016-10-09 11:48:12 -06003193int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003194 Demo demo;
3195
3196 demo.init(argc, argv);
3197
Tony Barbour153cb062016-12-07 13:43:36 -07003198#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003199 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003200#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003201 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003202 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003203#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003204 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003205#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3206 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003207#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003208
3209 demo.init_vk_swapchain();
3210
3211 demo.prepare();
3212
Tony Barbour153cb062016-12-07 13:43:36 -07003213#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003214 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003215#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003216 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003217#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003218 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003219#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3220 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003221#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3222 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003223#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003224
3225 demo.cleanup();
3226
3227 return validation_error;
3228}
3229
Bill Hollings0a0625a2019-07-15 17:39:18 -04003230#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003231
3232// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003233static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003234 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003235 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003236 demo.init_vk_swapchain();
3237 demo.prepare();
3238 demo.spin_angle = 0.4f;
3239}
3240
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003241#else
3242#error "Platform not supported"
3243#endif