blob: 69da9a9fce12a2a2b2cb4c0706e892faad0f1e6b [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
94struct vkcube_vs_uniform {
95 // Must start with MVP
96 float mvp[4][4];
97 float position[12 * 3][4];
98 float color[12 * 3][4];
99};
100
101struct vktexcube_vs_uniform {
102 // Must start with MVP
103 float mvp[4][4];
104 float position[12 * 3][4];
105 float attr[12 * 3][4];
106};
107
108//--------------------------------------------------------------------------------------
109// Mesh and VertexFormat Data
110//--------------------------------------------------------------------------------------
111// clang-format off
112static const float g_vertex_buffer_data[] = {
113 -1.0f,-1.0f,-1.0f, // -X 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, // -Z 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, // +Y 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, // +X 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 -1.0f, 1.0f, 1.0f, // +Z side
149 -1.0f,-1.0f, 1.0f,
150 1.0f, 1.0f, 1.0f,
151 -1.0f,-1.0f, 1.0f,
152 1.0f,-1.0f, 1.0f,
153 1.0f, 1.0f, 1.0f,
154};
155
156static const float g_uv_buffer_data[] = {
157 0.0f, 1.0f, // -X side
158 1.0f, 1.0f,
159 1.0f, 0.0f,
160 1.0f, 0.0f,
161 0.0f, 0.0f,
162 0.0f, 1.0f,
163
164 1.0f, 1.0f, // -Z side
165 0.0f, 0.0f,
166 0.0f, 1.0f,
167 1.0f, 1.0f,
168 1.0f, 0.0f,
169 0.0f, 0.0f,
170
171 1.0f, 0.0f, // -Y side
172 1.0f, 1.0f,
173 0.0f, 1.0f,
174 1.0f, 0.0f,
175 0.0f, 1.0f,
176 0.0f, 0.0f,
177
178 1.0f, 0.0f, // +Y side
179 0.0f, 0.0f,
180 0.0f, 1.0f,
181 1.0f, 0.0f,
182 0.0f, 1.0f,
183 1.0f, 1.0f,
184
185 1.0f, 0.0f, // +X side
186 0.0f, 0.0f,
187 0.0f, 1.0f,
188 0.0f, 1.0f,
189 1.0f, 1.0f,
190 1.0f, 0.0f,
191
192 0.0f, 0.0f, // +Z side
193 0.0f, 1.0f,
194 1.0f, 0.0f,
195 0.0f, 1.0f,
196 1.0f, 1.0f,
197 1.0f, 0.0f,
198};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600199// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600200
Jeremy Hayes9d304782016-10-09 11:48:12 -0600201typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600202 vk::Image image;
203 vk::CommandBuffer cmd;
204 vk::CommandBuffer graphics_to_present_cmd;
205 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600206 vk::Buffer uniform_buffer;
207 vk::DeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700208 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600212
Joey Bzdekbaf66472017-06-07 09:37:37 -0600213struct Demo {
214 Demo();
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
217 void cleanup();
218 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600219 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600220 void draw();
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
225 void init_vk();
226 void init_vk_swapchain();
227 void prepare();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600241 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600242 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100243
Joey Bzdekbaf66472017-06-07 09:37:37 -0600244 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600245 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600246 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
247 vk::PipelineStageFlags, vk::PipelineStageFlags);
248 void update_data_buffer();
249 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
250 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
251
252#if defined(VK_USE_PLATFORM_WIN32_KHR)
253 void run();
254 void create_window();
255#elif defined(VK_USE_PLATFORM_XLIB_KHR)
256 void create_xlib_window();
257 void handle_xlib_event(const XEvent *);
258 void run_xlib();
259#elif defined(VK_USE_PLATFORM_XCB_KHR)
260 void handle_xcb_event(const xcb_generic_event_t *);
261 void run_xcb();
262 void create_xcb_window();
263#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
264 void run();
265 void create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200266#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
267 void handle_directfb_event(const DFBInputEvent *);
268 void run_directfb();
269 void create_directfb_window();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400270#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600271 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600272#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
273 vk::Result create_display_surface();
274 void run_display();
275#endif
276
277#if defined(VK_USE_PLATFORM_WIN32_KHR)
278 HINSTANCE connection; // hInstance - Windows Instance
279 HWND window; // hWnd - window handle
280 POINT minsize; // minimum window size
281 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
282#elif defined(VK_USE_PLATFORM_XLIB_KHR)
283 Window xlib_window;
284 Atom xlib_wm_delete_window;
285 Display *display;
286#elif defined(VK_USE_PLATFORM_XCB_KHR)
287 xcb_window_t xcb_window;
288 xcb_screen_t *screen;
289 xcb_connection_t *connection;
290 xcb_intern_atom_reply_t *atom_wm_delete_window;
291#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
292 wl_display *display;
293 wl_registry *registry;
294 wl_compositor *compositor;
295 wl_surface *window;
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700296 wl_shell *shell;
297 wl_shell_surface *shell_surface;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600298 wl_seat *seat;
299 wl_pointer *pointer;
300 wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200301#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
302 IDirectFB *dfb;
303 IDirectFBSurface *window;
304 IDirectFBEventBuffer *event_buffer;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400305#elif defined(VK_USE_PLATFORM_METAL_EXT)
306 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600307#endif
308
309 vk::SurfaceKHR surface;
310 bool prepared;
311 bool use_staging_buffer;
312 bool use_xlib;
313 bool separate_present_queue;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000314 int32_t gpu_number;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600315
316 vk::Instance inst;
317 vk::PhysicalDevice gpu;
318 vk::Device device;
319 vk::Queue graphics_queue;
320 vk::Queue present_queue;
321 uint32_t graphics_queue_family_index;
322 uint32_t present_queue_family_index;
323 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
324 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
325 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
326 vk::PhysicalDeviceProperties gpu_props;
327 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
328 vk::PhysicalDeviceMemoryProperties memory_properties;
329
330 uint32_t enabled_extension_count;
331 uint32_t enabled_layer_count;
332 char const *extension_names[64];
333 char const *enabled_layers[64];
334
335 uint32_t width;
336 uint32_t height;
337 vk::Format format;
338 vk::ColorSpaceKHR color_space;
339
340 uint32_t swapchainImageCount;
341 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600342 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600343 vk::PresentModeKHR presentMode;
344 vk::Fence fences[FRAME_LAG];
345 uint32_t frame_index;
346
347 vk::CommandPool cmd_pool;
348 vk::CommandPool present_cmd_pool;
349
350 struct {
351 vk::Format format;
352 vk::Image image;
353 vk::MemoryAllocateInfo mem_alloc;
354 vk::DeviceMemory mem;
355 vk::ImageView view;
356 } depth;
357
358 static int32_t const texture_count = 1;
359 texture_object textures[texture_count];
360 texture_object staging_texture;
361
362 struct {
363 vk::Buffer buf;
364 vk::MemoryAllocateInfo mem_alloc;
365 vk::DeviceMemory mem;
366 vk::DescriptorBufferInfo buffer_info;
367 } uniform_data;
368
369 vk::CommandBuffer cmd; // Buffer for initialization commands
370 vk::PipelineLayout pipeline_layout;
371 vk::DescriptorSetLayout desc_layout;
372 vk::PipelineCache pipelineCache;
373 vk::RenderPass render_pass;
374 vk::Pipeline pipeline;
375
376 mat4x4 projection_matrix;
377 mat4x4 view_matrix;
378 mat4x4 model_matrix;
379
380 float spin_angle;
381 float spin_increment;
382 bool pause;
383
384 vk::ShaderModule vert_shader_module;
385 vk::ShaderModule frag_shader_module;
386
387 vk::DescriptorPool desc_pool;
388 vk::DescriptorSet desc_set;
389
390 std::unique_ptr<vk::Framebuffer[]> framebuffers;
391
392 bool quit;
393 uint32_t curFrame;
394 uint32_t frameCount;
395 bool validate;
396 bool use_break;
397 bool suppress_popups;
398
399 uint32_t current_buffer;
400 uint32_t queue_family_count;
401};
402
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600403#ifdef _WIN32
404// MS-Windows event handling function:
405LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
406#endif
407
Karl Schultz23cc2182016-11-23 17:15:17 -0700408#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700409static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700410 wl_shell_surface_pong(shell_surface, serial);
411}
412
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700413static 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 -0700414
415static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
416
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700417static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700418
Joey Bzdek15eb0702017-06-07 09:40:36 -0600419static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
420 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700421
Joey Bzdek15eb0702017-06-07 09:40:36 -0600422static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700423
Joey Bzdek15eb0702017-06-07 09:40:36 -0600424static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
425
426static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
427 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600428 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600429 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700430 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600431 }
432}
433
434static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
435
436static const struct wl_pointer_listener pointer_listener = {
437 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
438};
439
440static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
441
442static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
443 struct wl_array *keys) {}
444
445static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
446
447static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
448 uint32_t state) {
449 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
450 Demo *demo = (Demo *)data;
451 switch (key) {
452 case KEY_ESC: // Escape
453 demo->quit = true;
454 break;
455 case KEY_LEFT: // left arrow key
456 demo->spin_angle -= demo->spin_increment;
457 break;
458 case KEY_RIGHT: // right arrow key
459 demo->spin_angle += demo->spin_increment;
460 break;
461 case KEY_SPACE: // space bar
462 demo->pause = !demo->pause;
463 break;
464 }
465}
466
467static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
468 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
469
470static const struct wl_keyboard_listener keyboard_listener = {
471 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
472};
473
474static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
475 // Subscribe to pointer events
476 Demo *demo = (Demo *)data;
477 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
478 demo->pointer = wl_seat_get_pointer(seat);
479 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
480 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
481 wl_pointer_destroy(demo->pointer);
482 demo->pointer = NULL;
483 }
484 // Subscribe to keyboard events
485 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
486 demo->keyboard = wl_seat_get_keyboard(seat);
487 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
488 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
489 wl_keyboard_destroy(demo->keyboard);
490 demo->keyboard = NULL;
491 }
492}
493
494static const wl_seat_listener seat_listener = {
495 seat_handle_capabilities,
496};
497
498static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
499 Demo *demo = (Demo *)data;
500 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700501 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600502 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700503 } else if (strcmp(interface, "wl_shell") == 0) {
504 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
505 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600506 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
507 wl_seat_add_listener(demo->seat, &seat_listener, demo);
508 }
509}
510
511static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
512
513static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700514#endif
515
Joey Bzdekbaf66472017-06-07 09:37:37 -0600516Demo::Demo()
517 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600518#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600519 connection{nullptr},
520 window{nullptr},
521 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600522#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700523
Tony Barbour78d6b572016-11-14 14:46:33 -0700524#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 xlib_window{0},
526 xlib_wm_delete_window{0},
527 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700528#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600529 xcb_window{0},
530 screen{nullptr},
531 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700532#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600533 display{nullptr},
534 registry{nullptr},
535 compositor{nullptr},
536 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700537 shell{nullptr},
538 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600539 seat{nullptr},
540 pointer{nullptr},
541 keyboard{nullptr},
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200542#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
543 dfb{nullptr},
544 window{nullptr},
545 event_buffer{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700546#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600547 prepared{false},
548 use_staging_buffer{false},
549 use_xlib{false},
550 graphics_queue_family_index{0},
551 present_queue_family_index{0},
552 enabled_extension_count{0},
553 enabled_layer_count{0},
554 width{0},
555 height{0},
556 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000557 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600558 frame_index{0},
559 spin_angle{0.0f},
560 spin_increment{0.0f},
561 pause{false},
562 quit{false},
563 curFrame{0},
564 frameCount{0},
565 validate{false},
566 use_break{false},
567 suppress_popups{false},
568 current_buffer{0},
569 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600570#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700571 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600572#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700573 memset(projection_matrix, 0, sizeof(projection_matrix));
574 memset(view_matrix, 0, sizeof(view_matrix));
575 memset(model_matrix, 0, sizeof(model_matrix));
576}
577
578void Demo::build_image_ownership_cmd(uint32_t const &i) {
579 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
580 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
581 VERIFY(result == vk::Result::eSuccess);
582
583 auto const image_ownership_barrier =
584 vk::ImageMemoryBarrier()
585 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600586 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700587 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
588 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
589 .setSrcQueueFamilyIndex(graphics_queue_family_index)
590 .setDstQueueFamilyIndex(present_queue_family_index)
591 .setImage(swapchain_image_resources[i].image)
592 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
593
594 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600595 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
596 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700597
598 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
599 VERIFY(result == vk::Result::eSuccess);
600}
601
602vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
603 vk::LayerProperties *layers) {
604 for (uint32_t i = 0; i < check_count; i++) {
605 vk::Bool32 found = VK_FALSE;
606 for (uint32_t j = 0; j < layer_count; j++) {
607 if (!strcmp(check_names[i], layers[j].layerName)) {
608 found = VK_TRUE;
609 break;
610 }
611 }
612 if (!found) {
613 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
614 return 0;
615 }
616 }
617 return VK_TRUE;
618}
619
620void Demo::cleanup() {
621 prepared = false;
622 device.waitIdle();
623
624 // Wait for fences from present operations
625 for (uint32_t i = 0; i < FRAME_LAG; i++) {
626 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
627 device.destroyFence(fences[i], nullptr);
628 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
629 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
630 if (separate_present_queue) {
631 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
632 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600633 }
634
Dave Houlton5fa47912018-02-16 11:02:26 -0700635 for (uint32_t i = 0; i < swapchainImageCount; i++) {
636 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
637 }
638 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600639
Dave Houlton5fa47912018-02-16 11:02:26 -0700640 device.destroyPipeline(pipeline, nullptr);
641 device.destroyPipelineCache(pipelineCache, nullptr);
642 device.destroyRenderPass(render_pass, nullptr);
643 device.destroyPipelineLayout(pipeline_layout, nullptr);
644 device.destroyDescriptorSetLayout(desc_layout, nullptr);
645
646 for (uint32_t i = 0; i < texture_count; i++) {
647 device.destroyImageView(textures[i].view, nullptr);
648 device.destroyImage(textures[i].image, nullptr);
649 device.freeMemory(textures[i].mem, nullptr);
650 device.destroySampler(textures[i].sampler, nullptr);
651 }
652 device.destroySwapchainKHR(swapchain, nullptr);
653
654 device.destroyImageView(depth.view, nullptr);
655 device.destroyImage(depth.image, nullptr);
656 device.freeMemory(depth.mem, nullptr);
657
658 for (uint32_t i = 0; i < swapchainImageCount; i++) {
659 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700660 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700661 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700662 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700663 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
664 }
665
666 device.destroyCommandPool(cmd_pool, nullptr);
667
668 if (separate_present_queue) {
669 device.destroyCommandPool(present_cmd_pool, nullptr);
670 }
671 device.waitIdle();
672 device.destroy(nullptr);
673 inst.destroySurfaceKHR(surface, nullptr);
674
675#if defined(VK_USE_PLATFORM_XLIB_KHR)
676 XDestroyWindow(display, xlib_window);
677 XCloseDisplay(display);
678#elif defined(VK_USE_PLATFORM_XCB_KHR)
679 xcb_destroy_window(connection, xcb_window);
680 xcb_disconnect(connection);
681 free(atom_wm_delete_window);
682#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
683 wl_keyboard_destroy(keyboard);
684 wl_pointer_destroy(pointer);
685 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700686 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700687 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700688 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700689 wl_compositor_destroy(compositor);
690 wl_registry_destroy(registry);
691 wl_display_disconnect(display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200692#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
693 event_buffer->Release(event_buffer);
694 window->Release(window);
695 dfb->Release(dfb);
Dave Houlton5fa47912018-02-16 11:02:26 -0700696#endif
697
698 inst.destroy(nullptr);
699}
700
701void Demo::create_device() {
702 float const priorities[1] = {0.0};
703
704 vk::DeviceQueueCreateInfo queues[2];
705 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
706 queues[0].setQueueCount(1);
707 queues[0].setPQueuePriorities(priorities);
708
709 auto deviceInfo = vk::DeviceCreateInfo()
710 .setQueueCreateInfoCount(1)
711 .setPQueueCreateInfos(queues)
712 .setEnabledLayerCount(0)
713 .setPpEnabledLayerNames(nullptr)
714 .setEnabledExtensionCount(enabled_extension_count)
715 .setPpEnabledExtensionNames((const char *const *)extension_names)
716 .setPEnabledFeatures(nullptr);
717
718 if (separate_present_queue) {
719 queues[1].setQueueFamilyIndex(present_queue_family_index);
720 queues[1].setQueueCount(1);
721 queues[1].setPQueuePriorities(priorities);
722 deviceInfo.setQueueCreateInfoCount(2);
723 }
724
725 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
726 VERIFY(result == vk::Result::eSuccess);
727}
728
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600729void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700730 // clean up staging resources
731 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600732 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
733 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700734}
735
736void Demo::draw() {
737 // Ensure no more than FRAME_LAG renderings are outstanding
738 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700739 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700740
741 vk::Result result;
742 do {
743 result =
744 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
745 if (result == vk::Result::eErrorOutOfDateKHR) {
746 // demo->swapchain is out of date (e.g. the window was resized) and
747 // must be recreated:
748 resize();
749 } else if (result == vk::Result::eSuboptimalKHR) {
750 // swapchain is not as optimal as it could be, but the platform's
751 // presentation engine will still present the image correctly.
752 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600753 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
754 inst.destroySurfaceKHR(surface, nullptr);
755 create_surface();
756 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700757 } else {
758 VERIFY(result == vk::Result::eSuccess);
759 }
760 } while (result != vk::Result::eSuccess);
761
762 update_data_buffer();
763
764 // Wait for the image acquired semaphore to be signaled to ensure
765 // that the image won't be rendered to until the presentation
766 // engine has fully released ownership to the application, and it is
767 // okay to render to the image.
768 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
769 auto const submit_info = vk::SubmitInfo()
770 .setPWaitDstStageMask(&pipe_stage_flags)
771 .setWaitSemaphoreCount(1)
772 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
773 .setCommandBufferCount(1)
774 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
775 .setSignalSemaphoreCount(1)
776 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
777
778 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
779 VERIFY(result == vk::Result::eSuccess);
780
781 if (separate_present_queue) {
782 // If we are using separate queues, change image ownership to the
783 // present queue before presenting, waiting for the draw complete
784 // semaphore and signalling the ownership released semaphore when
785 // finished
786 auto const present_submit_info = vk::SubmitInfo()
787 .setPWaitDstStageMask(&pipe_stage_flags)
788 .setWaitSemaphoreCount(1)
789 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
790 .setCommandBufferCount(1)
791 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
792 .setSignalSemaphoreCount(1)
793 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
794
795 result = present_queue.submit(1, &present_submit_info, vk::Fence());
796 VERIFY(result == vk::Result::eSuccess);
797 }
798
799 // If we are using separate queues we have to wait for image ownership,
800 // otherwise wait for draw complete
801 auto const presentInfo = vk::PresentInfoKHR()
802 .setWaitSemaphoreCount(1)
803 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
804 : &draw_complete_semaphores[frame_index])
805 .setSwapchainCount(1)
806 .setPSwapchains(&swapchain)
807 .setPImageIndices(&current_buffer);
808
809 result = present_queue.presentKHR(&presentInfo);
810 frame_index += 1;
811 frame_index %= FRAME_LAG;
812 if (result == vk::Result::eErrorOutOfDateKHR) {
813 // swapchain is out of date (e.g. the window was resized) and
814 // must be recreated:
815 resize();
816 } else if (result == vk::Result::eSuboptimalKHR) {
817 // swapchain is not as optimal as it could be, but the platform's
818 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600819 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
820 inst.destroySurfaceKHR(surface, nullptr);
821 create_surface();
822 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700823 } else {
824 VERIFY(result == vk::Result::eSuccess);
825 }
826}
827
828void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
829 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
830
831 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
832 vk::ClearDepthStencilValue(1.0f, 0u)};
833
834 auto const passInfo = vk::RenderPassBeginInfo()
835 .setRenderPass(render_pass)
836 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
837 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
838 .setClearValueCount(2)
839 .setPClearValues(clearValues);
840
841 auto result = commandBuffer.begin(&commandInfo);
842 VERIFY(result == vk::Result::eSuccess);
843
844 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
845 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
846 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
847 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700848 float viewport_dimension;
849 float viewport_x = 0.0f;
850 float viewport_y = 0.0f;
851 if (width < height) {
852 viewport_dimension = (float)width;
853 viewport_y = (height - width) / 2.0f;
854 } else {
855 viewport_dimension = (float)height;
856 viewport_x = (width - height) / 2.0f;
857 }
858 auto const viewport = vk::Viewport()
859 .setX(viewport_x)
860 .setY(viewport_y)
861 .setWidth((float)viewport_dimension)
862 .setHeight((float)viewport_dimension)
863 .setMinDepth((float)0.0f)
864 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700865 commandBuffer.setViewport(0, 1, &viewport);
866
867 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
868 commandBuffer.setScissor(0, 1, &scissor);
869 commandBuffer.draw(12 * 3, 1, 0, 0);
870 // Note that ending the renderpass changes the image's layout from
871 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
872 commandBuffer.endRenderPass();
873
874 if (separate_present_queue) {
875 // We have to transfer ownership from the graphics queue family to
876 // the
877 // present queue family to be able to present. Note that we don't
878 // have
879 // to transfer from present queue family back to graphics queue
880 // family at
881 // the start of the next frame because we don't care about the
882 // image's
883 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600884 auto const image_ownership_barrier =
885 vk::ImageMemoryBarrier()
886 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600887 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600888 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
889 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
890 .setSrcQueueFamilyIndex(graphics_queue_family_index)
891 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700892 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700893 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600894
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600895 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700896 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600897 }
898
Dave Houlton5fa47912018-02-16 11:02:26 -0700899 result = commandBuffer.end();
900 VERIFY(result == vk::Result::eSuccess);
901}
902
903void Demo::flush_init_cmd() {
904 // TODO: hmm.
905 // This function could get called twice if the texture uses a staging
906 // buffer
907 // In that case the second call should be ignored
908 if (!cmd) {
909 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600910 }
911
Dave Houlton5fa47912018-02-16 11:02:26 -0700912 auto result = cmd.end();
913 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600914
Dave Houlton5fa47912018-02-16 11:02:26 -0700915 auto const fenceInfo = vk::FenceCreateInfo();
916 vk::Fence fence;
917 result = device.createFence(&fenceInfo, nullptr, &fence);
918 VERIFY(result == vk::Result::eSuccess);
919
920 vk::CommandBuffer const commandBuffers[] = {cmd};
921 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
922
923 result = graphics_queue.submit(1, &submitInfo, fence);
924 VERIFY(result == vk::Result::eSuccess);
925
926 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
927 VERIFY(result == vk::Result::eSuccess);
928
929 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
930 device.destroyFence(fence, nullptr);
931
932 cmd = vk::CommandBuffer();
933}
934
935void Demo::init(int argc, char **argv) {
936 vec3 eye = {0.0f, 3.0f, 5.0f};
937 vec3 origin = {0, 0, 0};
938 vec3 up = {0.0f, 1.0f, 0.0};
939
940 presentMode = vk::PresentModeKHR::eFifo;
941 frameCount = UINT32_MAX;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100942 width = 500;
943 height = 500;
Dave Houlton5fa47912018-02-16 11:02:26 -0700944 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000945 /* Autodetect suitable / best GPU by default */
946 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600947
Dave Houlton5fa47912018-02-16 11:02:26 -0700948 for (int i = 1; i < argc; i++) {
949 if (strcmp(argv[i], "--use_staging") == 0) {
950 use_staging_buffer = true;
951 continue;
952 }
953 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
954 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
955 i++;
956 continue;
957 }
958 if (strcmp(argv[i], "--break") == 0) {
959 use_break = true;
960 continue;
961 }
962 if (strcmp(argv[i], "--validate") == 0) {
963 validate = true;
964 continue;
965 }
966 if (strcmp(argv[i], "--xlib") == 0) {
967 fprintf(stderr, "--xlib is deprecated and no longer does anything");
968 continue;
969 }
970 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
971 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
972 i++;
973 continue;
974 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100975 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &width) == 1 && width > 0) {
976 i++;
977 continue;
978 }
979 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%" SCNu32, &height) == 1 && height > 0) {
980 i++;
981 continue;
982 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700983 if (strcmp(argv[i], "--suppress_popups") == 0) {
984 suppress_popups = true;
985 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600986 }
Tony-LunarG50e737c2020-07-16 14:26:03 -0600987 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
988 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +0000989 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -0600990 i++;
991 continue;
992 }
Tony-LunarGd74734f2019-06-04 14:11:43 -0600993 std::stringstream usage;
994 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
995 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -0600996 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600997 << "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +0100998 << "\t[--width <width>] [--height <height>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600999 << "\t<present_mode_enum>\n"
1000 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
1001 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
1002 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +00001003 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -06001004
1005#if defined(_WIN32)
1006 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
1007#else
1008 std::cerr << usage.str();
1009 std::cerr.flush();
1010#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001011 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001012 }
1013
Dave Houlton5fa47912018-02-16 11:02:26 -07001014 if (!use_xlib) {
1015 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001016 }
1017
Dave Houlton5fa47912018-02-16 11:02:26 -07001018 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001019
Dave Houlton5fa47912018-02-16 11:02:26 -07001020 spin_angle = 4.0f;
1021 spin_increment = 0.2f;
1022 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001023
Dave Houlton5fa47912018-02-16 11:02:26 -07001024 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1025 mat4x4_look_at(view_matrix, eye, origin, up);
1026 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001027
Dave Houlton5fa47912018-02-16 11:02:26 -07001028 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1029}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001030
Dave Houlton5fa47912018-02-16 11:02:26 -07001031void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001032#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 const xcb_setup_t *setup;
1034 xcb_screen_iterator_t iter;
1035 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001036
Dave Houlton5fa47912018-02-16 11:02:26 -07001037 const char *display_envar = getenv("DISPLAY");
1038 if (display_envar == nullptr || display_envar[0] == '\0') {
1039 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1040 fflush(stdout);
1041 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001042 }
1043
Dave Houlton5fa47912018-02-16 11:02:26 -07001044 connection = xcb_connect(nullptr, &scr);
1045 if (xcb_connection_has_error(connection) > 0) {
1046 printf(
1047 "Cannot find a compatible Vulkan installable client driver "
1048 "(ICD).\nExiting ...\n");
1049 fflush(stdout);
1050 exit(1);
1051 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001052
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 setup = xcb_get_setup(connection);
1054 iter = xcb_setup_roots_iterator(setup);
1055 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056
Dave Houlton5fa47912018-02-16 11:02:26 -07001057 screen = iter.data;
1058#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1059 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001060
Dave Houlton5fa47912018-02-16 11:02:26 -07001061 if (display == nullptr) {
1062 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1063 fflush(stdout);
1064 exit(1);
1065 }
1066
1067 registry = wl_display_get_registry(display);
1068 wl_registry_add_listener(registry, &registry_listener, this);
1069 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001070#endif
1071}
1072
1073void Demo::init_vk() {
1074 uint32_t instance_extension_count = 0;
1075 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001076 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001077 enabled_extension_count = 0;
1078 enabled_layer_count = 0;
1079
Dave Houlton5fa47912018-02-16 11:02:26 -07001080 // Look for validation layers
1081 vk::Bool32 validation_found = VK_FALSE;
1082 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001083 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001084 VERIFY(result == vk::Result::eSuccess);
1085
Dave Houlton5fa47912018-02-16 11:02:26 -07001086 if (instance_layer_count > 0) {
1087 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1088 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001089 VERIFY(result == vk::Result::eSuccess);
1090
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001091 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001092 instance_layer_count, instance_layers.get());
1093 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001094 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1095 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001096 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001097 }
1098
Dave Houlton5fa47912018-02-16 11:02:26 -07001099 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001100 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001101 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1102 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001103 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001104 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001105 }
1106
Dave Houlton5fa47912018-02-16 11:02:26 -07001107 /* Look for instance extensions */
1108 vk::Bool32 surfaceExtFound = VK_FALSE;
1109 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1110 memset(extension_names, 0, sizeof(extension_names));
1111
Mike Schuchardt7510c832018-10-29 13:23:08 -07001112 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1113 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001114 VERIFY(result == vk::Result::eSuccess);
1115
1116 if (instance_extension_count > 0) {
1117 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1118 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1119 VERIFY(result == vk::Result::eSuccess);
1120
1121 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001122 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1123 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1124 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001125 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1126 surfaceExtFound = 1;
1127 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1128 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001129#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001130 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1131 platformSurfaceExtFound = 1;
1132 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1133 }
1134#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1135 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1136 platformSurfaceExtFound = 1;
1137 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1138 }
1139#elif defined(VK_USE_PLATFORM_XCB_KHR)
1140 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1141 platformSurfaceExtFound = 1;
1142 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1143 }
Tony Barbour153cb062016-12-07 13:43:36 -07001144#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001145 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1146 platformSurfaceExtFound = 1;
1147 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1148 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001149#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1150 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1151 platformSurfaceExtFound = 1;
1152 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1153 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001154#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1155 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1156 platformSurfaceExtFound = 1;
1157 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1158 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001159#elif defined(VK_USE_PLATFORM_METAL_EXT)
1160 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001161 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001162 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001163 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001164#endif
1165 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001166 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001167 }
1168
1169 if (!surfaceExtFound) {
1170 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1171 " extension.\n\n"
1172 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1173 "Please look at the Getting Started guide for additional information.\n",
1174 "vkCreateInstance Failure");
1175 }
1176
1177 if (!platformSurfaceExtFound) {
1178#if defined(VK_USE_PLATFORM_WIN32_KHR)
1179 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1180 " extension.\n\n"
1181 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1182 "Please look at the Getting Started guide for additional information.\n",
1183 "vkCreateInstance Failure");
1184#elif defined(VK_USE_PLATFORM_XCB_KHR)
1185 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1186 " extension.\n\n"
1187 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1188 "Please look at the Getting Started guide for additional information.\n",
1189 "vkCreateInstance Failure");
1190#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1191 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1192 " extension.\n\n"
1193 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1194 "Please look at the Getting Started guide for additional information.\n",
1195 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001196#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001197 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1198 " extension.\n\n"
1199 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1200 "Please look at the Getting Started guide for additional information.\n",
1201 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001202#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1203 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1204 " extension.\n\n"
1205 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1206 "Please look at the Getting Started guide for additional information.\n",
1207 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001208#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001209 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1210 " extension.\n\n"
1211 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1212 "Please look at the Getting Started guide for additional information.\n",
1213 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001214#elif defined(VK_USE_PLATFORM_METAL_EXT)
1215 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001216 " extension.\n\nDo you have a compatible "
1217 "Vulkan installable client driver (ICD) installed?\nPlease "
1218 "look at the Getting Started guide for additional "
1219 "information.\n",
1220 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001221#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001222 }
1223 auto const app = vk::ApplicationInfo()
1224 .setPApplicationName(APP_SHORT_NAME)
1225 .setApplicationVersion(0)
1226 .setPEngineName(APP_SHORT_NAME)
1227 .setEngineVersion(0)
1228 .setApiVersion(VK_API_VERSION_1_0);
1229 auto const inst_info = vk::InstanceCreateInfo()
1230 .setPApplicationInfo(&app)
1231 .setEnabledLayerCount(enabled_layer_count)
1232 .setPpEnabledLayerNames(instance_validation_layers)
1233 .setEnabledExtensionCount(enabled_extension_count)
1234 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001235
Dave Houlton5fa47912018-02-16 11:02:26 -07001236 result = vk::createInstance(&inst_info, nullptr, &inst);
1237 if (result == vk::Result::eErrorIncompatibleDriver) {
1238 ERR_EXIT(
1239 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1240 "Please look at the Getting Started guide for additional information.\n",
1241 "vkCreateInstance Failure");
1242 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1243 ERR_EXIT(
1244 "Cannot find a specified extension library.\n"
1245 "Make sure your layers path is set appropriately.\n",
1246 "vkCreateInstance Failure");
1247 } else if (result != vk::Result::eSuccess) {
1248 ERR_EXIT(
1249 "vkCreateInstance failed.\n\n"
1250 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1251 "Please look at the Getting Started guide for additional information.\n",
1252 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001253 }
1254
Witold Baryluka3b988f2021-01-07 19:03:02 +00001255 /* Make initial call to query gpu_count, then second call for gpu info */
1256 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001257 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001258 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001259
Witold Baryluka3b988f2021-01-07 19:03:02 +00001260 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001261 ERR_EXIT(
1262 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1263 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1264 "Please look at the Getting Started guide for additional information.\n",
1265 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001266 }
1267
Witold Baryluka3b988f2021-01-07 19:03:02 +00001268 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1269 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1270 VERIFY(result == vk::Result::eSuccess);
1271
1272 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1273 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1274 ERR_EXIT("Specified GPU number is not present", "User Error");
1275 }
1276
1277 /* Try to auto select most suitable device */
1278 if (gpu_number == -1) {
1279 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1280 memset(count_device_type, 0, sizeof(count_device_type));
1281
1282 for (uint32_t i = 0; i < gpu_count; i++) {
1283 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1284 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1285 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1286 }
1287
1288 const vk::PhysicalDeviceType device_type_preference[] = {
1289 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1290 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1291 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1292 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1293 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1294 search_for_device_type = device_type_preference[i];
1295 break;
1296 }
1297 }
1298
1299 for (uint32_t i = 0; i < gpu_count; i++) {
1300 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1301 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1302 gpu_number = i;
1303 break;
1304 }
1305 }
1306 }
1307 assert(gpu_number >= 0);
1308 gpu = physical_devices[gpu_number];
1309 {
1310 auto physicalDeviceProperties = gpu.getProperties();
1311 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1312 to_string(physicalDeviceProperties.deviceType).c_str());
1313 }
1314 physical_devices.reset();
1315
Dave Houlton5fa47912018-02-16 11:02:26 -07001316 /* Look for device extensions */
1317 uint32_t device_extension_count = 0;
1318 vk::Bool32 swapchainExtFound = VK_FALSE;
1319 enabled_extension_count = 0;
1320 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001321
Mike Schuchardt7510c832018-10-29 13:23:08 -07001322 result =
1323 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001324 VERIFY(result == vk::Result::eSuccess);
1325
1326 if (device_extension_count > 0) {
1327 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1328 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001329 VERIFY(result == vk::Result::eSuccess);
1330
Dave Houlton5fa47912018-02-16 11:02:26 -07001331 for (uint32_t i = 0; i < device_extension_count; i++) {
1332 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1333 swapchainExtFound = 1;
1334 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001335 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001336 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1337 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001338 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001339 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001340 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001341 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001342
Dave Houlton5fa47912018-02-16 11:02:26 -07001343 if (!swapchainExtFound) {
1344 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1345 " extension.\n\n"
1346 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1347 "Please look at the Getting Started guide for additional information.\n",
1348 "vkCreateInstance Failure");
1349 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001350
Dave Houlton5fa47912018-02-16 11:02:26 -07001351 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001352
Dave Houlton5fa47912018-02-16 11:02:26 -07001353 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001354 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001355 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001356
Dave Houlton5fa47912018-02-16 11:02:26 -07001357 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1358 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001359
Dave Houlton5fa47912018-02-16 11:02:26 -07001360 // Query fine-grained feature support for this device.
1361 // If app has specific feature requirements it should check supported
1362 // features based on this query
1363 vk::PhysicalDeviceFeatures physDevFeatures;
1364 gpu.getFeatures(&physDevFeatures);
1365}
1366
Tony-LunarG6cebf142019-09-11 14:32:23 -06001367void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001368// Create a WSI surface for the window:
1369#if defined(VK_USE_PLATFORM_WIN32_KHR)
1370 {
1371 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1372
1373 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1374 VERIFY(result == vk::Result::eSuccess);
1375 }
1376#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1377 {
1378 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1379
1380 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1381 VERIFY(result == vk::Result::eSuccess);
1382 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001383#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1384 {
1385 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1386
1387 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1388 VERIFY(result == vk::Result::eSuccess);
1389 }
1390#elif defined(VK_USE_PLATFORM_XCB_KHR)
1391 {
1392 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1393
1394 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1395 VERIFY(result == vk::Result::eSuccess);
1396 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001397#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1398 {
1399 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1400
1401 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1402 VERIFY(result == vk::Result::eSuccess);
1403 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001404#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001405 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001406 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001407
Bill Hollings0a0625a2019-07-15 17:39:18 -04001408 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001409 VERIFY(result == vk::Result::eSuccess);
1410 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001411#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1412 {
1413 auto result = create_display_surface();
1414 VERIFY(result == vk::Result::eSuccess);
1415 }
1416#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001417}
1418
1419void Demo::init_vk_swapchain() {
1420 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001421 // Iterate over each queue to learn whether it supports presenting:
1422 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1423 for (uint32_t i = 0; i < queue_family_count; i++) {
1424 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1425 }
1426
1427 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1428 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1429 for (uint32_t i = 0; i < queue_family_count; i++) {
1430 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1431 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1432 graphicsQueueFamilyIndex = i;
1433 }
1434
1435 if (supportsPresent[i] == VK_TRUE) {
1436 graphicsQueueFamilyIndex = i;
1437 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001438 break;
1439 }
1440 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001441 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001442
Dave Houlton5fa47912018-02-16 11:02:26 -07001443 if (presentQueueFamilyIndex == UINT32_MAX) {
1444 // If didn't find a queue that supports both graphics and present,
1445 // then
1446 // find a separate present queue.
1447 for (uint32_t i = 0; i < queue_family_count; ++i) {
1448 if (supportsPresent[i] == VK_TRUE) {
1449 presentQueueFamilyIndex = i;
1450 break;
1451 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001452 }
1453 }
1454
Dave Houlton5fa47912018-02-16 11:02:26 -07001455 // Generate error if could not find both a graphics and a present queue
1456 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1457 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1458 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001459
Dave Houlton5fa47912018-02-16 11:02:26 -07001460 graphics_queue_family_index = graphicsQueueFamilyIndex;
1461 present_queue_family_index = presentQueueFamilyIndex;
1462 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001463
Dave Houlton5fa47912018-02-16 11:02:26 -07001464 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001465
Dave Houlton5fa47912018-02-16 11:02:26 -07001466 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1467 if (!separate_present_queue) {
1468 present_queue = graphics_queue;
1469 } else {
1470 device.getQueue(present_queue_family_index, 0, &present_queue);
1471 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001472
Dave Houlton5fa47912018-02-16 11:02:26 -07001473 // Get the list of VkFormat's that are supported:
1474 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001475 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001476 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001477
Dave Houlton5fa47912018-02-16 11:02:26 -07001478 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1479 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1480 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001481
Dave Houlton5fa47912018-02-16 11:02:26 -07001482 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1483 // the surface has no preferred format. Otherwise, at least one
1484 // supported format will be returned.
1485 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1486 format = vk::Format::eB8G8R8A8Unorm;
1487 } else {
1488 assert(formatCount >= 1);
1489 format = surfFormats[0].format;
1490 }
1491 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001492
Dave Houlton5fa47912018-02-16 11:02:26 -07001493 quit = false;
1494 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001495
Dave Houlton5fa47912018-02-16 11:02:26 -07001496 // Create semaphores to synchronize acquiring presentable buffers before
1497 // rendering and waiting for drawing to be complete before presenting
1498 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001499
Dave Houlton5fa47912018-02-16 11:02:26 -07001500 // Create fences that we can use to throttle if we get too far
1501 // ahead of the image presents
1502 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1503 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1504 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1505 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001506
Dave Houlton5fa47912018-02-16 11:02:26 -07001507 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1508 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001509
Dave Houlton5fa47912018-02-16 11:02:26 -07001510 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1511 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001512
Dave Houlton5fa47912018-02-16 11:02:26 -07001513 if (separate_present_queue) {
1514 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001515 VERIFY(result == vk::Result::eSuccess);
1516 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001517 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001518 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001519
Dave Houlton5fa47912018-02-16 11:02:26 -07001520 // Get Memory information and properties
1521 gpu.getMemoryProperties(&memory_properties);
1522}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001523
Dave Houlton5fa47912018-02-16 11:02:26 -07001524void Demo::prepare() {
1525 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1526 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1527 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001528
Dave Houlton5fa47912018-02-16 11:02:26 -07001529 auto const cmd = vk::CommandBufferAllocateInfo()
1530 .setCommandPool(cmd_pool)
1531 .setLevel(vk::CommandBufferLevel::ePrimary)
1532 .setCommandBufferCount(1);
1533
1534 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1535 VERIFY(result == vk::Result::eSuccess);
1536
1537 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1538
1539 result = this->cmd.begin(&cmd_buf_info);
1540 VERIFY(result == vk::Result::eSuccess);
1541
1542 prepare_buffers();
1543 prepare_depth();
1544 prepare_textures();
1545 prepare_cube_data_buffers();
1546
1547 prepare_descriptor_layout();
1548 prepare_render_pass();
1549 prepare_pipeline();
1550
1551 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1552 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1553 VERIFY(result == vk::Result::eSuccess);
1554 }
1555
1556 if (separate_present_queue) {
1557 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1558
1559 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1560 VERIFY(result == vk::Result::eSuccess);
1561
1562 auto const present_cmd = vk::CommandBufferAllocateInfo()
1563 .setCommandPool(present_cmd_pool)
1564 .setLevel(vk::CommandBufferLevel::ePrimary)
1565 .setCommandBufferCount(1);
1566
1567 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1568 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1569 VERIFY(result == vk::Result::eSuccess);
1570
1571 build_image_ownership_cmd(i);
1572 }
1573 }
1574
1575 prepare_descriptor_pool();
1576 prepare_descriptor_set();
1577
1578 prepare_framebuffers();
1579
1580 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1581 current_buffer = i;
1582 draw_build_cmd(swapchain_image_resources[i].cmd);
1583 }
1584
1585 /*
1586 * Prepare functions above may generate pipeline commands
1587 * that need to be flushed before beginning the render loop.
1588 */
1589 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001590 if (staging_texture.buffer) {
1591 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001592 }
1593
1594 current_buffer = 0;
1595 prepared = true;
1596}
1597
1598void Demo::prepare_buffers() {
1599 vk::SwapchainKHR oldSwapchain = swapchain;
1600
1601 // Check the surface capabilities and formats
1602 vk::SurfaceCapabilitiesKHR surfCapabilities;
1603 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1604 VERIFY(result == vk::Result::eSuccess);
1605
1606 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001607 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001608 VERIFY(result == vk::Result::eSuccess);
1609
1610 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1611 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1612 VERIFY(result == vk::Result::eSuccess);
1613
1614 vk::Extent2D swapchainExtent;
1615 // width and height are either both -1, or both not -1.
1616 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1617 // If the surface size is undefined, the size is set to
1618 // the size of the images requested.
1619 swapchainExtent.width = width;
1620 swapchainExtent.height = height;
1621 } else {
1622 // If the surface size is defined, the swap chain size must match
1623 swapchainExtent = surfCapabilities.currentExtent;
1624 width = surfCapabilities.currentExtent.width;
1625 height = surfCapabilities.currentExtent.height;
1626 }
1627
1628 // The FIFO present mode is guaranteed by the spec to be supported
1629 // and to have no tearing. It's a great default present mode to use.
1630 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1631
1632 // There are times when you may wish to use another present mode. The
1633 // following code shows how to select them, and the comments provide some
1634 // reasons you may wish to use them.
1635 //
1636 // It should be noted that Vulkan 1.0 doesn't provide a method for
1637 // synchronizing rendering with the presentation engine's display. There
1638 // is a method provided for throttling rendering with the display, but
1639 // there are some presentation engines for which this method will not work.
1640 // If an application doesn't throttle its rendering, and if it renders much
1641 // faster than the refresh rate of the display, this can waste power on
1642 // mobile devices. That is because power is being spent rendering images
1643 // that may never be seen.
1644
1645 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1646 // about
1647 // tearing, or have some way of synchronizing their rendering with the
1648 // display.
1649 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1650 // generally render a new presentable image every refresh cycle, but are
1651 // occasionally early. In this case, the application wants the new
1652 // image
1653 // to be displayed instead of the previously-queued-for-presentation
1654 // image
1655 // that has not yet been displayed.
1656 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1657 // render a new presentable image every refresh cycle, but are
1658 // occasionally
1659 // late. In this case (perhaps because of stuttering/latency concerns),
1660 // the application wants the late image to be immediately displayed,
1661 // even
1662 // though that may mean some tearing.
1663
1664 if (presentMode != swapchainPresentMode) {
1665 for (size_t i = 0; i < presentModeCount; ++i) {
1666 if (presentModes[i] == presentMode) {
1667 swapchainPresentMode = presentMode;
1668 break;
1669 }
1670 }
1671 }
1672
1673 if (swapchainPresentMode != presentMode) {
1674 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1675 }
1676
1677 // Determine the number of VkImages to use in the swap chain.
1678 // Application desires to acquire 3 images at a time for triple
1679 // buffering
1680 uint32_t desiredNumOfSwapchainImages = 3;
1681 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1682 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1683 }
1684
1685 // If maxImageCount is 0, we can ask for as many images as we want,
1686 // otherwise
1687 // we're limited to maxImageCount
1688 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1689 // Application must settle for fewer images than desired:
1690 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1691 }
1692
1693 vk::SurfaceTransformFlagBitsKHR preTransform;
1694 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1695 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1696 } else {
1697 preTransform = surfCapabilities.currentTransform;
1698 }
1699
1700 // Find a supported composite alpha mode - one of these is guaranteed to be set
1701 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1702 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1703 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1704 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1705 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1706 vk::CompositeAlphaFlagBitsKHR::eInherit,
1707 };
1708 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1709 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1710 compositeAlpha = compositeAlphaFlags[i];
1711 break;
1712 }
1713 }
1714
1715 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1716 .setSurface(surface)
1717 .setMinImageCount(desiredNumOfSwapchainImages)
1718 .setImageFormat(format)
1719 .setImageColorSpace(color_space)
1720 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1721 .setImageArrayLayers(1)
1722 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1723 .setImageSharingMode(vk::SharingMode::eExclusive)
1724 .setQueueFamilyIndexCount(0)
1725 .setPQueueFamilyIndices(nullptr)
1726 .setPreTransform(preTransform)
1727 .setCompositeAlpha(compositeAlpha)
1728 .setPresentMode(swapchainPresentMode)
1729 .setClipped(true)
1730 .setOldSwapchain(oldSwapchain);
1731
1732 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1733 VERIFY(result == vk::Result::eSuccess);
1734
1735 // If we just re-created an existing swapchain, we should destroy the
1736 // old
1737 // swapchain at this point.
1738 // Note: destroying the swapchain also cleans up all its associated
1739 // presentable images once the platform is done with them.
1740 if (oldSwapchain) {
1741 device.destroySwapchainKHR(oldSwapchain, nullptr);
1742 }
1743
Mike Schuchardt7510c832018-10-29 13:23:08 -07001744 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001745 VERIFY(result == vk::Result::eSuccess);
1746
1747 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1748 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1749 VERIFY(result == vk::Result::eSuccess);
1750
1751 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1752
1753 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1754 auto color_image_view = vk::ImageViewCreateInfo()
1755 .setViewType(vk::ImageViewType::e2D)
1756 .setFormat(format)
1757 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1758
1759 swapchain_image_resources[i].image = swapchainImages[i];
1760
1761 color_image_view.image = swapchain_image_resources[i].image;
1762
1763 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1764 VERIFY(result == vk::Result::eSuccess);
1765 }
1766}
1767
1768void Demo::prepare_cube_data_buffers() {
1769 mat4x4 VP;
1770 mat4x4_mul(VP, projection_matrix, view_matrix);
1771
1772 mat4x4 MVP;
1773 mat4x4_mul(MVP, VP, model_matrix);
1774
1775 vktexcube_vs_uniform data;
1776 memcpy(data.mvp, MVP, sizeof(MVP));
1777 // dumpMatrix("MVP", MVP)
1778
1779 for (int32_t i = 0; i < 12 * 3; i++) {
1780 data.position[i][0] = g_vertex_buffer_data[i * 3];
1781 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1782 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1783 data.position[i][3] = 1.0f;
1784 data.attr[i][0] = g_uv_buffer_data[2 * i];
1785 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1786 data.attr[i][2] = 0;
1787 data.attr[i][3] = 0;
1788 }
1789
1790 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1791
1792 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1793 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001794 VERIFY(result == vk::Result::eSuccess);
1795
1796 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001797 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001798
Dave Houlton5fa47912018-02-16 11:02:26 -07001799 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001800
Dave Houlton5fa47912018-02-16 11:02:26 -07001801 bool const pass = memory_type_from_properties(
1802 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1803 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001804 VERIFY(pass);
1805
Dave Houlton5fa47912018-02-16 11:02:26 -07001806 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001807 VERIFY(result == vk::Result::eSuccess);
1808
Tony-LunarG37af49f2019-12-19 12:04:19 -07001809 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1810 &swapchain_image_resources[i].uniform_memory_ptr);
1811 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001812
Tony-LunarG37af49f2019-12-19 12:04:19 -07001813 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001814
1815 result =
1816 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001817 VERIFY(result == vk::Result::eSuccess);
1818 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001819}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001820
Dave Houlton5fa47912018-02-16 11:02:26 -07001821void Demo::prepare_depth() {
1822 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001823
Dave Houlton5fa47912018-02-16 11:02:26 -07001824 auto const image = vk::ImageCreateInfo()
1825 .setImageType(vk::ImageType::e2D)
1826 .setFormat(depth.format)
1827 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1828 .setMipLevels(1)
1829 .setArrayLayers(1)
1830 .setSamples(vk::SampleCountFlagBits::e1)
1831 .setTiling(vk::ImageTiling::eOptimal)
1832 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1833 .setSharingMode(vk::SharingMode::eExclusive)
1834 .setQueueFamilyIndexCount(0)
1835 .setPQueueFamilyIndices(nullptr)
1836 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001837
Dave Houlton5fa47912018-02-16 11:02:26 -07001838 auto result = device.createImage(&image, nullptr, &depth.image);
1839 VERIFY(result == vk::Result::eSuccess);
1840
1841 vk::MemoryRequirements mem_reqs;
1842 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1843
1844 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1845 depth.mem_alloc.setMemoryTypeIndex(0);
1846
1847 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1848 &depth.mem_alloc.memoryTypeIndex);
1849 VERIFY(pass);
1850
1851 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1852 VERIFY(result == vk::Result::eSuccess);
1853
1854 result = device.bindImageMemory(depth.image, depth.mem, 0);
1855 VERIFY(result == vk::Result::eSuccess);
1856
1857 auto const view = vk::ImageViewCreateInfo()
1858 .setImage(depth.image)
1859 .setViewType(vk::ImageViewType::e2D)
1860 .setFormat(depth.format)
1861 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1862 result = device.createImageView(&view, nullptr, &depth.view);
1863 VERIFY(result == vk::Result::eSuccess);
1864}
1865
1866void Demo::prepare_descriptor_layout() {
1867 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1868 .setBinding(0)
1869 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1870 .setDescriptorCount(1)
1871 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1872 .setPImmutableSamplers(nullptr),
1873 vk::DescriptorSetLayoutBinding()
1874 .setBinding(1)
1875 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1876 .setDescriptorCount(texture_count)
1877 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1878 .setPImmutableSamplers(nullptr)};
1879
1880 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1881
1882 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1883 VERIFY(result == vk::Result::eSuccess);
1884
1885 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1886
1887 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1888 VERIFY(result == vk::Result::eSuccess);
1889}
1890
1891void Demo::prepare_descriptor_pool() {
1892 vk::DescriptorPoolSize const poolSizes[2] = {
1893 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1894 vk::DescriptorPoolSize()
1895 .setType(vk::DescriptorType::eCombinedImageSampler)
1896 .setDescriptorCount(swapchainImageCount * texture_count)};
1897
1898 auto const descriptor_pool =
1899 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1900
1901 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1902 VERIFY(result == vk::Result::eSuccess);
1903}
1904
1905void Demo::prepare_descriptor_set() {
1906 auto const alloc_info =
1907 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1908
1909 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1910
1911 vk::DescriptorImageInfo tex_descs[texture_count];
1912 for (uint32_t i = 0; i < texture_count; i++) {
1913 tex_descs[i].setSampler(textures[i].sampler);
1914 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001915 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001916 }
1917
1918 vk::WriteDescriptorSet writes[2];
1919
1920 writes[0].setDescriptorCount(1);
1921 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1922 writes[0].setPBufferInfo(&buffer_info);
1923
1924 writes[1].setDstBinding(1);
1925 writes[1].setDescriptorCount(texture_count);
1926 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1927 writes[1].setPImageInfo(tex_descs);
1928
1929 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1930 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001931 VERIFY(result == vk::Result::eSuccess);
1932
Dave Houlton5fa47912018-02-16 11:02:26 -07001933 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1934 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1935 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1936 device.updateDescriptorSets(2, writes, 0, nullptr);
1937 }
1938}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001939
Dave Houlton5fa47912018-02-16 11:02:26 -07001940void Demo::prepare_framebuffers() {
1941 vk::ImageView attachments[2];
1942 attachments[1] = depth.view;
1943
1944 auto const fb_info = vk::FramebufferCreateInfo()
1945 .setRenderPass(render_pass)
1946 .setAttachmentCount(2)
1947 .setPAttachments(attachments)
1948 .setWidth((uint32_t)width)
1949 .setHeight((uint32_t)height)
1950 .setLayers(1);
1951
1952 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1953 attachments[0] = swapchain_image_resources[i].view;
1954 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001955 VERIFY(result == vk::Result::eSuccess);
1956 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001957}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001958
Dave Houlton5fa47912018-02-16 11:02:26 -07001959vk::ShaderModule Demo::prepare_fs() {
1960 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001961#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001962 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001963
Dave Houlton5fa47912018-02-16 11:02:26 -07001964 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001965
Dave Houlton5fa47912018-02-16 11:02:26 -07001966 return frag_shader_module;
1967}
1968
1969void Demo::prepare_pipeline() {
1970 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1971 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1972 VERIFY(result == vk::Result::eSuccess);
1973
1974 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1975 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1976 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1977
1978 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1979
1980 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1981
1982 // TODO: Where are pViewports and pScissors set?
1983 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1984
1985 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1986 .setDepthClampEnable(VK_FALSE)
1987 .setRasterizerDiscardEnable(VK_FALSE)
1988 .setPolygonMode(vk::PolygonMode::eFill)
1989 .setCullMode(vk::CullModeFlagBits::eBack)
1990 .setFrontFace(vk::FrontFace::eCounterClockwise)
1991 .setDepthBiasEnable(VK_FALSE)
1992 .setLineWidth(1.0f);
1993
1994 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1995
1996 auto const stencilOp =
1997 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1998
1999 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
2000 .setDepthTestEnable(VK_TRUE)
2001 .setDepthWriteEnable(VK_TRUE)
2002 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
2003 .setDepthBoundsTestEnable(VK_FALSE)
2004 .setStencilTestEnable(VK_FALSE)
2005 .setFront(stencilOp)
2006 .setBack(stencilOp);
2007
2008 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2009 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2010 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2011
2012 auto const colorBlendInfo =
2013 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2014
2015 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2016
2017 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2018
2019 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2020 .setStageCount(2)
2021 .setPStages(shaderStageInfo)
2022 .setPVertexInputState(&vertexInputInfo)
2023 .setPInputAssemblyState(&inputAssemblyInfo)
2024 .setPViewportState(&viewportInfo)
2025 .setPRasterizationState(&rasterizationInfo)
2026 .setPMultisampleState(&multisampleInfo)
2027 .setPDepthStencilState(&depthStencilInfo)
2028 .setPColorBlendState(&colorBlendInfo)
2029 .setPDynamicState(&dynamicStateInfo)
2030 .setLayout(pipeline_layout)
2031 .setRenderPass(render_pass);
2032
2033 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2034 VERIFY(result == vk::Result::eSuccess);
2035
2036 device.destroyShaderModule(frag_shader_module, nullptr);
2037 device.destroyShaderModule(vert_shader_module, nullptr);
2038}
2039
2040void Demo::prepare_render_pass() {
2041 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2042 // because at the start of the renderpass, we don't care about their contents.
2043 // At the start of the subpass, the color attachment's layout will be transitioned
2044 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2045 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2046 // the renderpass, the color attachment's layout will be transitioned to
2047 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2048 // the renderpass, no barriers are necessary.
2049 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2050 .setFormat(format)
2051 .setSamples(vk::SampleCountFlagBits::e1)
2052 .setLoadOp(vk::AttachmentLoadOp::eClear)
2053 .setStoreOp(vk::AttachmentStoreOp::eStore)
2054 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2055 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2056 .setInitialLayout(vk::ImageLayout::eUndefined)
2057 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2058 vk::AttachmentDescription()
2059 .setFormat(depth.format)
2060 .setSamples(vk::SampleCountFlagBits::e1)
2061 .setLoadOp(vk::AttachmentLoadOp::eClear)
2062 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2063 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2064 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2065 .setInitialLayout(vk::ImageLayout::eUndefined)
2066 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2067
2068 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2069
2070 auto const depth_reference =
2071 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2072
2073 auto const subpass = vk::SubpassDescription()
2074 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2075 .setInputAttachmentCount(0)
2076 .setPInputAttachments(nullptr)
2077 .setColorAttachmentCount(1)
2078 .setPColorAttachments(&color_reference)
2079 .setPResolveAttachments(nullptr)
2080 .setPDepthStencilAttachment(&depth_reference)
2081 .setPreserveAttachmentCount(0)
2082 .setPPreserveAttachments(nullptr);
2083
Tony-LunarG495604b2019-06-13 15:32:05 -06002084 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2085 vk::SubpassDependency const dependencies[2] = {
2086 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2087 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2088 .setDstSubpass(0)
2089 .setSrcStageMask(stages)
2090 .setDstStageMask(stages)
2091 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2092 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2093 .setDependencyFlags(vk::DependencyFlags()),
2094 vk::SubpassDependency() // Image layout transition
2095 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2096 .setDstSubpass(0)
2097 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2098 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2099 .setSrcAccessMask(vk::AccessFlagBits())
2100 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2101 .setDependencyFlags(vk::DependencyFlags()),
2102 };
2103
Dave Houlton5fa47912018-02-16 11:02:26 -07002104 auto const rp_info = vk::RenderPassCreateInfo()
2105 .setAttachmentCount(2)
2106 .setPAttachments(attachments)
2107 .setSubpassCount(1)
2108 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002109 .setDependencyCount(2)
2110 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002111
2112 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2113 VERIFY(result == vk::Result::eSuccess);
2114}
2115
2116vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2117 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2118
2119 vk::ShaderModule module;
2120 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2121 VERIFY(result == vk::Result::eSuccess);
2122
2123 return module;
2124}
2125
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002126void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2127 int32_t tex_width;
2128 int32_t tex_height;
2129
2130 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2131 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2132 }
2133
2134 tex_obj->tex_width = tex_width;
2135 tex_obj->tex_height = tex_height;
2136
2137 auto const buffer_create_info = vk::BufferCreateInfo()
2138 .setSize(tex_width * tex_height * 4)
2139 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2140 .setSharingMode(vk::SharingMode::eExclusive)
2141 .setQueueFamilyIndexCount(0)
2142 .setPQueueFamilyIndices(nullptr);
2143
2144 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2145 VERIFY(result == vk::Result::eSuccess);
2146
2147 vk::MemoryRequirements mem_reqs;
2148 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2149
2150 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2151 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2152
2153 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2154 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2155 VERIFY(pass == true);
2156
2157 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2158 VERIFY(result == vk::Result::eSuccess);
2159
2160 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2161 VERIFY(result == vk::Result::eSuccess);
2162
2163 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002164 layout.rowPitch = tex_width * 4;
2165 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2166 VERIFY(data.result == vk::Result::eSuccess);
2167
2168 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2169 fprintf(stderr, "Error loading texture: %s\n", filename);
2170 }
2171
2172 device.unmapMemory(tex_obj->mem);
2173}
2174
Dave Houlton5fa47912018-02-16 11:02:26 -07002175void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2176 vk::MemoryPropertyFlags required_props) {
2177 int32_t tex_width;
2178 int32_t tex_height;
2179 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2180 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002181 }
2182
Dave Houlton5fa47912018-02-16 11:02:26 -07002183 tex_obj->tex_width = tex_width;
2184 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002185
Dave Houlton5fa47912018-02-16 11:02:26 -07002186 auto const image_create_info = vk::ImageCreateInfo()
2187 .setImageType(vk::ImageType::e2D)
2188 .setFormat(vk::Format::eR8G8B8A8Unorm)
2189 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2190 .setMipLevels(1)
2191 .setArrayLayers(1)
2192 .setSamples(vk::SampleCountFlagBits::e1)
2193 .setTiling(tiling)
2194 .setUsage(usage)
2195 .setSharingMode(vk::SharingMode::eExclusive)
2196 .setQueueFamilyIndexCount(0)
2197 .setPQueueFamilyIndices(nullptr)
2198 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002199
Dave Houlton5fa47912018-02-16 11:02:26 -07002200 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2201 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002202
Dave Houlton5fa47912018-02-16 11:02:26 -07002203 vk::MemoryRequirements mem_reqs;
2204 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002205
Dave Houlton5fa47912018-02-16 11:02:26 -07002206 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2207 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002208
Dave Houlton5fa47912018-02-16 11:02:26 -07002209 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2210 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002211
Dave Houlton5fa47912018-02-16 11:02:26 -07002212 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2213 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002214
Dave Houlton5fa47912018-02-16 11:02:26 -07002215 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2216 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002217
Dave Houlton5fa47912018-02-16 11:02:26 -07002218 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2219 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2220 vk::SubresourceLayout layout;
2221 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002222
Dave Houlton5fa47912018-02-16 11:02:26 -07002223 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002224 VERIFY(data.result == vk::Result::eSuccess);
2225
Dave Houlton5fa47912018-02-16 11:02:26 -07002226 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2227 fprintf(stderr, "Error loading texture: %s\n", filename);
2228 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002229
Dave Houlton5fa47912018-02-16 11:02:26 -07002230 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002231 }
2232
Dave Houlton5fa47912018-02-16 11:02:26 -07002233 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2234}
2235
2236void Demo::prepare_textures() {
2237 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2238 vk::FormatProperties props;
2239 gpu.getFormatProperties(tex_format, &props);
2240
2241 for (uint32_t i = 0; i < texture_count; i++) {
2242 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2243 /* Device can texture using linear textures */
2244 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2245 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2246 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2247 // shader to run until layout transition completes
2248 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2249 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2250 vk::PipelineStageFlagBits::eFragmentShader);
2251 staging_texture.image = vk::Image();
2252 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2253 /* Must use staging buffer to copy linear texture to optimized */
2254
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002255 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002256
2257 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2258 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2259 vk::MemoryPropertyFlagBits::eDeviceLocal);
2260
Dave Houlton5fa47912018-02-16 11:02:26 -07002261 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2262 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2263 vk::PipelineStageFlagBits::eTransfer);
2264
2265 auto const subresource = vk::ImageSubresourceLayers()
2266 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2267 .setMipLevel(0)
2268 .setBaseArrayLayer(0)
2269 .setLayerCount(1);
2270
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002271 auto const copy_region =
2272 vk::BufferImageCopy()
2273 .setBufferOffset(0)
2274 .setBufferRowLength(staging_texture.tex_width)
2275 .setBufferImageHeight(staging_texture.tex_height)
2276 .setImageSubresource(subresource)
2277 .setImageOffset({0, 0, 0})
2278 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002279
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002280 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002281
2282 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2283 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2284 vk::PipelineStageFlagBits::eFragmentShader);
2285 } else {
2286 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002287 }
2288
Dave Houlton5fa47912018-02-16 11:02:26 -07002289 auto const samplerInfo = vk::SamplerCreateInfo()
2290 .setMagFilter(vk::Filter::eNearest)
2291 .setMinFilter(vk::Filter::eNearest)
2292 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2293 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2294 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2295 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2296 .setMipLodBias(0.0f)
2297 .setAnisotropyEnable(VK_FALSE)
2298 .setMaxAnisotropy(1)
2299 .setCompareEnable(VK_FALSE)
2300 .setCompareOp(vk::CompareOp::eNever)
2301 .setMinLod(0.0f)
2302 .setMaxLod(0.0f)
2303 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2304 .setUnnormalizedCoordinates(VK_FALSE);
2305
2306 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2307 VERIFY(result == vk::Result::eSuccess);
2308
2309 auto const viewInfo = vk::ImageViewCreateInfo()
2310 .setImage(textures[i].image)
2311 .setViewType(vk::ImageViewType::e2D)
2312 .setFormat(tex_format)
2313 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2314
2315 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2316 VERIFY(result == vk::Result::eSuccess);
2317 }
2318}
2319
2320vk::ShaderModule Demo::prepare_vs() {
2321 const uint32_t vertShaderCode[] = {
2322#include "cube.vert.inc"
2323 };
2324
2325 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2326
2327 return vert_shader_module;
2328}
2329
2330void Demo::resize() {
2331 uint32_t i;
2332
2333 // Don't react to resize until after first initialization.
2334 if (!prepared) {
2335 return;
2336 }
2337
2338 // In order to properly resize the window, we must re-create the
2339 // swapchain
2340 // AND redo the command buffers, etc.
2341 //
2342 // First, perform part of the cleanup() function:
2343 prepared = false;
2344 auto result = device.waitIdle();
2345 VERIFY(result == vk::Result::eSuccess);
2346
2347 for (i = 0; i < swapchainImageCount; i++) {
2348 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2349 }
2350
2351 device.destroyDescriptorPool(desc_pool, nullptr);
2352
2353 device.destroyPipeline(pipeline, nullptr);
2354 device.destroyPipelineCache(pipelineCache, nullptr);
2355 device.destroyRenderPass(render_pass, nullptr);
2356 device.destroyPipelineLayout(pipeline_layout, nullptr);
2357 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2358
2359 for (i = 0; i < texture_count; i++) {
2360 device.destroyImageView(textures[i].view, nullptr);
2361 device.destroyImage(textures[i].image, nullptr);
2362 device.freeMemory(textures[i].mem, nullptr);
2363 device.destroySampler(textures[i].sampler, nullptr);
2364 }
2365
2366 device.destroyImageView(depth.view, nullptr);
2367 device.destroyImage(depth.image, nullptr);
2368 device.freeMemory(depth.mem, nullptr);
2369
2370 for (i = 0; i < swapchainImageCount; i++) {
2371 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002372 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002373 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002374 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002375 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2376 }
2377
2378 device.destroyCommandPool(cmd_pool, nullptr);
2379 if (separate_present_queue) {
2380 device.destroyCommandPool(present_cmd_pool, nullptr);
2381 }
2382
2383 // Second, re-perform the prepare() function, which will re-create the
2384 // swapchain.
2385 prepare();
2386}
2387
2388void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2389 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2390 assert(cmd);
2391
2392 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2393 vk::AccessFlags flags;
2394
2395 switch (layout) {
2396 case vk::ImageLayout::eTransferDstOptimal:
2397 // Make sure anything that was copying from this image has
2398 // completed
2399 flags = vk::AccessFlagBits::eTransferWrite;
2400 break;
2401 case vk::ImageLayout::eColorAttachmentOptimal:
2402 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2403 break;
2404 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2405 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2406 break;
2407 case vk::ImageLayout::eShaderReadOnlyOptimal:
2408 // Make sure any Copy or CPU writes to image are flushed
2409 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2410 break;
2411 case vk::ImageLayout::eTransferSrcOptimal:
2412 flags = vk::AccessFlagBits::eTransferRead;
2413 break;
2414 case vk::ImageLayout::ePresentSrcKHR:
2415 flags = vk::AccessFlagBits::eMemoryRead;
2416 break;
2417 default:
2418 break;
2419 }
2420
2421 return flags;
2422 };
2423
2424 auto const barrier = vk::ImageMemoryBarrier()
2425 .setSrcAccessMask(srcAccessMask)
2426 .setDstAccessMask(DstAccessMask(newLayout))
2427 .setOldLayout(oldLayout)
2428 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002429 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2430 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002431 .setImage(image)
2432 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2433
2434 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2435}
2436
2437void Demo::update_data_buffer() {
2438 mat4x4 VP;
2439 mat4x4_mul(VP, projection_matrix, view_matrix);
2440
2441 // Rotate around the Y axis
2442 mat4x4 Model;
2443 mat4x4_dup(Model, model_matrix);
2444 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2445
2446 mat4x4 MVP;
2447 mat4x4_mul(MVP, VP, model_matrix);
2448
Tony-LunarG37af49f2019-12-19 12:04:19 -07002449 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002450}
2451
Karl Schultzb7940402018-05-29 13:09:22 -06002452/* Convert ppm image data from header file into RGBA texture image */
2453#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002454bool 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 -06002455 (void)filename;
2456 char *cPtr;
2457 cPtr = (char *)lunarg_ppm;
2458 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002459 return false;
2460 }
Karl Schultzb7940402018-05-29 13:09:22 -06002461 while (strncmp(cPtr++, "\n", 1))
2462 ;
2463 sscanf(cPtr, "%u %u", width, height);
2464 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002465 return true;
2466 }
Karl Schultzb7940402018-05-29 13:09:22 -06002467 while (strncmp(cPtr++, "\n", 1))
2468 ;
2469 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002470 return false;
2471 }
Karl Schultzb7940402018-05-29 13:09:22 -06002472 while (strncmp(cPtr++, "\n", 1))
2473 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002474 for (int y = 0; y < *height; y++) {
2475 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002476 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002477 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002478 rowPtr[3] = 255; /* Alpha of 1 */
2479 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002480 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002481 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002482 rgba_data += layout->rowPitch;
2483 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002484 return true;
2485}
2486
2487bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2488 // Search memtypes to find first index with those properties
2489 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2490 if ((typeBits & 1) == 1) {
2491 // Type is available, does it match user properties?
2492 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2493 *typeIndex = i;
2494 return true;
2495 }
2496 }
2497 typeBits >>= 1;
2498 }
2499
2500 // No memory types matched, return failure
2501 return false;
2502}
2503
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002504#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002505void Demo::run() {
2506 if (!prepared) {
2507 return;
2508 }
2509
2510 draw();
2511 curFrame++;
2512
Petr Krausd88e4e52019-01-23 18:45:04 +01002513 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002514 PostQuitMessage(validation_error);
2515 }
2516}
2517
2518void Demo::create_window() {
2519 WNDCLASSEX win_class;
2520
2521 // Initialize the window class structure:
2522 win_class.cbSize = sizeof(WNDCLASSEX);
2523 win_class.style = CS_HREDRAW | CS_VREDRAW;
2524 win_class.lpfnWndProc = WndProc;
2525 win_class.cbClsExtra = 0;
2526 win_class.cbWndExtra = 0;
2527 win_class.hInstance = connection; // hInstance
2528 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2529 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2530 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2531 win_class.lpszMenuName = nullptr;
2532 win_class.lpszClassName = name;
2533 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2534
2535 // Register window class:
2536 if (!RegisterClassEx(&win_class)) {
2537 // It didn't work, so try to give a useful error:
2538 printf("Unexpected error trying to start the application!\n");
2539 fflush(stdout);
2540 exit(1);
2541 }
2542
2543 // Create window with the registered class:
2544 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2545 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2546 window = CreateWindowEx(0,
2547 name, // class name
2548 name, // app name
2549 WS_OVERLAPPEDWINDOW | // window style
2550 WS_VISIBLE | WS_SYSMENU,
2551 100, 100, // x/y coords
2552 wr.right - wr.left, // width
2553 wr.bottom - wr.top, // height
2554 nullptr, // handle to parent
2555 nullptr, // handle to menu
2556 connection, // hInstance
2557 nullptr); // no extra parameters
2558
2559 if (!window) {
2560 // It didn't work, so try to give a useful error:
2561 printf("Cannot create a window in which to draw!\n");
2562 fflush(stdout);
2563 exit(1);
2564 }
2565
2566 // Window client area size must be at least 1 pixel high, to prevent
2567 // crash.
2568 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2569 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2570}
2571#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2572
2573void Demo::create_xlib_window() {
2574 const char *display_envar = getenv("DISPLAY");
2575 if (display_envar == nullptr || display_envar[0] == '\0') {
2576 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2577 fflush(stdout);
2578 exit(1);
2579 }
2580
2581 XInitThreads();
2582 display = XOpenDisplay(nullptr);
2583 long visualMask = VisualScreenMask;
2584 int numberOfVisuals;
2585 XVisualInfo vInfoTemplate = {};
2586 vInfoTemplate.screen = DefaultScreen(display);
2587 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2588
2589 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2590
2591 XSetWindowAttributes windowAttributes = {};
2592 windowAttributes.colormap = colormap;
2593 windowAttributes.background_pixel = 0xFFFFFFFF;
2594 windowAttributes.border_pixel = 0;
2595 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2596
2597 xlib_window =
2598 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2599 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2600
2601 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2602 XMapWindow(display, xlib_window);
2603 XFlush(display);
2604 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2605}
2606
2607void Demo::handle_xlib_event(const XEvent *event) {
2608 switch (event->type) {
2609 case ClientMessage:
2610 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2611 quit = true;
2612 }
2613 break;
2614 case KeyPress:
2615 switch (event->xkey.keycode) {
2616 case 0x9: // Escape
2617 quit = true;
2618 break;
2619 case 0x71: // left arrow key
2620 spin_angle -= spin_increment;
2621 break;
2622 case 0x72: // right arrow key
2623 spin_angle += spin_increment;
2624 break;
2625 case 0x41: // space bar
2626 pause = !pause;
2627 break;
2628 }
2629 break;
2630 case ConfigureNotify:
2631 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2632 width = event->xconfigure.width;
2633 height = event->xconfigure.height;
2634 resize();
2635 }
2636 break;
2637 default:
2638 break;
2639 }
2640}
2641
2642void Demo::run_xlib() {
2643 while (!quit) {
2644 XEvent event;
2645
2646 if (pause) {
2647 XNextEvent(display, &event);
2648 handle_xlib_event(&event);
2649 }
2650 while (XPending(display) > 0) {
2651 XNextEvent(display, &event);
2652 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002653 }
2654
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002655 draw();
2656 curFrame++;
2657
Dave Houlton5fa47912018-02-16 11:02:26 -07002658 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2659 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002660 }
2661 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002662}
Tony Barbour153cb062016-12-07 13:43:36 -07002663#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002664
Dave Houlton5fa47912018-02-16 11:02:26 -07002665void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2666 uint8_t event_code = event->response_type & 0x7f;
2667 switch (event_code) {
2668 case XCB_EXPOSE:
2669 // TODO: Resize window
2670 break;
2671 case XCB_CLIENT_MESSAGE:
2672 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2673 quit = true;
2674 }
2675 break;
2676 case XCB_KEY_RELEASE: {
2677 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002678
Dave Houlton5fa47912018-02-16 11:02:26 -07002679 switch (key->detail) {
2680 case 0x9: // Escape
2681 quit = true;
2682 break;
2683 case 0x71: // left arrow key
2684 spin_angle -= spin_increment;
2685 break;
2686 case 0x72: // right arrow key
2687 spin_angle += spin_increment;
2688 break;
2689 case 0x41: // space bar
2690 pause = !pause;
2691 break;
2692 }
2693 } break;
2694 case XCB_CONFIGURE_NOTIFY: {
2695 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2696 if ((width != cfg->width) || (height != cfg->height)) {
2697 width = cfg->width;
2698 height = cfg->height;
2699 resize();
2700 }
2701 } break;
2702 default:
2703 break;
2704 }
2705}
2706
2707void Demo::run_xcb() {
2708 xcb_flush(connection);
2709
2710 while (!quit) {
2711 xcb_generic_event_t *event;
2712
2713 if (pause) {
2714 event = xcb_wait_for_event(connection);
2715 } else {
2716 event = xcb_poll_for_event(connection);
2717 }
2718 while (event) {
2719 handle_xcb_event(event);
2720 free(event);
2721 event = xcb_poll_for_event(connection);
2722 }
2723
2724 draw();
2725 curFrame++;
2726 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2727 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002728 }
2729 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002730}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002731
Dave Houlton5fa47912018-02-16 11:02:26 -07002732void Demo::create_xcb_window() {
2733 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002734
Dave Houlton5fa47912018-02-16 11:02:26 -07002735 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002736
Dave Houlton5fa47912018-02-16 11:02:26 -07002737 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2738 value_list[0] = screen->black_pixel;
2739 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002740
Dave Houlton5fa47912018-02-16 11:02:26 -07002741 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2742 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2743
2744 /* Magic code that will send notification when window is destroyed */
2745 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2746 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2747
2748 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2749 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2750
2751 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2752
2753 free(reply);
2754
2755 xcb_map_window(connection, xcb_window);
2756
2757 // Force the x/y coordinates to 100,100 results are identical in
2758 // consecutive
2759 // runs
2760 const uint32_t coords[] = {100, 100};
2761 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2762}
2763#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2764
2765void Demo::run() {
2766 while (!quit) {
2767 if (pause) {
2768 wl_display_dispatch(display);
2769 } else {
2770 wl_display_dispatch_pending(display);
2771 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002772 draw();
2773 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002774 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002775 quit = true;
2776 }
2777 }
2778 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002779}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002780
Dave Houlton5fa47912018-02-16 11:02:26 -07002781void Demo::create_window() {
2782 window = wl_compositor_create_surface(compositor);
2783 if (!window) {
2784 printf("Can not create wayland_surface from compositor!\n");
2785 fflush(stdout);
2786 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002787 }
2788
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002789 shell_surface = wl_shell_get_shell_surface(shell, window);
2790 if (!shell_surface) {
2791 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002792 fflush(stdout);
2793 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002794 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002795
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002796 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2797 wl_shell_surface_set_toplevel(shell_surface);
2798 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002799}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002800#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2801
2802void Demo::handle_directfb_event(const DFBInputEvent *event) {
2803 if (event->type != DIET_KEYPRESS) return;
2804 switch (event->key_symbol) {
2805 case DIKS_ESCAPE: // Escape
2806 quit = true;
2807 break;
2808 case DIKS_CURSOR_LEFT: // left arrow key
2809 spin_angle -= spin_increment;
2810 break;
2811 case DIKS_CURSOR_RIGHT: // right arrow key
2812 spin_angle += spin_increment;
2813 break;
2814 case DIKS_SPACE: // space bar
2815 pause = !pause;
2816 break;
2817 default:
2818 break;
2819 }
2820}
2821
2822void Demo::run_directfb() {
2823 while (!quit) {
2824 DFBInputEvent event;
2825
2826 if (pause) {
2827 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002828 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002829 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002830 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002831
2832 draw();
2833 curFrame++;
2834 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2835 quit = true;
2836 }
2837 }
2838 }
2839}
2840
2841void Demo::create_directfb_window() {
2842 DFBResult ret;
2843
2844 ret = DirectFBInit(NULL, NULL);
2845 if (ret) {
2846 printf("DirectFBInit failed to initialize DirectFB!\n");
2847 fflush(stdout);
2848 exit(1);
2849 }
2850
2851 ret = DirectFBCreate(&dfb);
2852 if (ret) {
2853 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2854 fflush(stdout);
2855 exit(1);
2856 }
2857
2858 DFBSurfaceDescription desc;
2859 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2860 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002861 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002862 desc.height = height;
2863 ret = dfb->CreateSurface(dfb, &desc, &window);
2864 if (ret) {
2865 printf("CreateSurface failed to create DirectFB surface interface!\n");
2866 fflush(stdout);
2867 exit(1);
2868 }
2869
2870 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2871 if (ret) {
2872 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2873 fflush(stdout);
2874 exit(1);
2875 }
2876}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002877#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002878void Demo::run() {
2879 draw();
2880 curFrame++;
2881 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2882 quit = true;
2883 }
2884}
Damien Leone600c3052017-01-31 10:26:07 -07002885#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2886
Dave Houlton5fa47912018-02-16 11:02:26 -07002887vk::Result Demo::create_display_surface() {
2888 vk::Result result;
2889 uint32_t display_count;
2890 uint32_t mode_count;
2891 uint32_t plane_count;
2892 vk::DisplayPropertiesKHR display_props;
2893 vk::DisplayKHR display;
2894 vk::DisplayModePropertiesKHR mode_props;
2895 vk::DisplayPlanePropertiesKHR *plane_props;
2896 vk::Bool32 found_plane = VK_FALSE;
2897 uint32_t plane_index;
2898 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002899
Dave Houlton5fa47912018-02-16 11:02:26 -07002900 // Get the first display
2901 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2902 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002903
Dave Houlton5fa47912018-02-16 11:02:26 -07002904 if (display_count == 0) {
2905 printf("Cannot find any display!\n");
2906 fflush(stdout);
2907 exit(1);
2908 }
2909
2910 display_count = 1;
2911 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2912 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2913
2914 display = display_props.display;
2915
2916 // Get the first mode of the display
2917 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2918 VERIFY(result == vk::Result::eSuccess);
2919
2920 if (mode_count == 0) {
2921 printf("Cannot find any mode for the display!\n");
2922 fflush(stdout);
2923 exit(1);
2924 }
2925
2926 mode_count = 1;
2927 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2928 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2929
2930 // Get the list of planes
2931 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2932 VERIFY(result == vk::Result::eSuccess);
2933
2934 if (plane_count == 0) {
2935 printf("Cannot find any plane!\n");
2936 fflush(stdout);
2937 exit(1);
2938 }
2939
2940 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2941 VERIFY(plane_props != nullptr);
2942
2943 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2944 VERIFY(result == vk::Result::eSuccess);
2945
2946 // Find a plane compatible with the display
2947 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2948 uint32_t supported_count;
2949 vk::DisplayKHR *supported_displays;
2950
2951 // Disqualify planes that are bound to a different display
2952 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2953 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002954 }
2955
Dave Houlton5fa47912018-02-16 11:02:26 -07002956 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002957 VERIFY(result == vk::Result::eSuccess);
2958
Dave Houlton5fa47912018-02-16 11:02:26 -07002959 if (supported_count == 0) {
2960 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002961 }
2962
Dave Houlton5fa47912018-02-16 11:02:26 -07002963 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2964 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002965
Dave Houlton5fa47912018-02-16 11:02:26 -07002966 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002967 VERIFY(result == vk::Result::eSuccess);
2968
Dave Houlton5fa47912018-02-16 11:02:26 -07002969 for (uint32_t i = 0; i < supported_count; i++) {
2970 if (supported_displays[i] == display) {
2971 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002972 break;
2973 }
2974 }
2975
Dave Houlton5fa47912018-02-16 11:02:26 -07002976 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002977
Dave Houlton5fa47912018-02-16 11:02:26 -07002978 if (found_plane) {
2979 break;
Damien Leone600c3052017-01-31 10:26:07 -07002980 }
2981 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002982
2983 if (!found_plane) {
2984 printf("Cannot find a plane compatible with the display!\n");
2985 fflush(stdout);
2986 exit(1);
2987 }
2988
2989 free(plane_props);
2990
2991 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2992 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2993 // Find a supported alpha mode
2994 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2995 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2996 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2997 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2998 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2999 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
3000 };
3001 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3002 if (planeCaps.supportedAlpha & alphaModes[i]) {
3003 alphaMode = alphaModes[i];
3004 break;
3005 }
3006 }
3007
3008 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3009 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3010
3011 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3012 .setDisplayMode(mode_props.displayMode)
3013 .setPlaneIndex(plane_index)
3014 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3015 .setGlobalAlpha(1.0f)
3016 .setAlphaMode(alphaMode)
3017 .setImageExtent(image_extent);
3018
3019 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3020}
3021
3022void Demo::run_display() {
3023 while (!quit) {
3024 draw();
3025 curFrame++;
3026
Petr Krausd88e4e52019-01-23 18:45:04 +01003027 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003028 quit = true;
3029 }
3030 }
3031}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003032#endif
3033
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003034#if _WIN32
3035// Include header required for parsing the command line options.
3036#include <shellapi.h>
3037
3038Demo demo;
3039
3040// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003041LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3042 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003043 case WM_CLOSE:
3044 PostQuitMessage(validation_error);
3045 break;
3046 case WM_PAINT:
3047 demo.run();
3048 break;
3049 case WM_GETMINMAXINFO: // set window's minimum size
3050 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3051 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003052 case WM_ERASEBKGND:
3053 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003054 case WM_SIZE:
3055 // Resize the application to the new window size, except when
3056 // it was minimized. Vulkan doesn't support images or swapchains
3057 // with width=0 and height=0.
3058 if (wParam != SIZE_MINIMIZED) {
3059 demo.width = lParam & 0xffff;
3060 demo.height = (lParam & 0xffff0000) >> 16;
3061 demo.resize();
3062 }
3063 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003064 case WM_KEYDOWN:
3065 switch (wParam) {
3066 case VK_ESCAPE:
3067 PostQuitMessage(validation_error);
3068 break;
3069 case VK_LEFT:
3070 demo.spin_angle -= demo.spin_increment;
3071 break;
3072 case VK_RIGHT:
3073 demo.spin_angle += demo.spin_increment;
3074 break;
3075 case VK_SPACE:
3076 demo.pause = !demo.pause;
3077 break;
3078 }
3079 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003080 default:
3081 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003082 }
3083
3084 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3085}
3086
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003087int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003088 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003089 MSG msg; // message
3090 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003091 int argc;
3092 char **argv;
3093
Jamie Madillb2ff6502017-03-15 16:17:46 -04003094 // Ensure wParam is initialized.
3095 msg.wParam = 0;
3096
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003097 // Use the CommandLine functions to get the command line arguments.
3098 // Unfortunately, Microsoft outputs
3099 // this information as wide characters for Unicode, and we simply want the
3100 // Ascii version to be compatible
3101 // with the non-Windows side. So, we have to convert the information to
3102 // Ascii character strings.
3103 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003104 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003105 argc = 0;
3106 }
3107
Jeremy Hayes9d304782016-10-09 11:48:12 -06003108 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003109 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003110 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003111 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003112 } else {
3113 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003114 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3115 size_t numConverted = 0;
3116
3117 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003118 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003119 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003120 }
3121 }
3122 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003123 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003124 argv = nullptr;
3125 }
3126
3127 demo.init(argc, argv);
3128
3129 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003130 if (argc > 0 && argv != nullptr) {
3131 for (int iii = 0; iii < argc; iii++) {
3132 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003133 free(argv[iii]);
3134 }
3135 }
3136 free(argv);
3137 }
3138
3139 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003140 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003141 demo.create_window();
3142 demo.init_vk_swapchain();
3143
3144 demo.prepare();
3145
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003146 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003147
3148 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003149 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003150 if (demo.pause) {
3151 const BOOL succ = WaitMessage();
3152
3153 if (!succ) {
3154 const auto &suppress_popups = demo.suppress_popups;
3155 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3156 }
3157 }
3158
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003159 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003160 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003161 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003162 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003163 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003164 /* Translate and dispatch to event queue*/
3165 TranslateMessage(&msg);
3166 DispatchMessage(&msg);
3167 }
3168 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3169 }
3170
3171 demo.cleanup();
3172
3173 return (int)msg.wParam;
3174}
3175
3176#elif __linux__
3177
Jeremy Hayes9d304782016-10-09 11:48:12 -06003178int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003179 Demo demo;
3180
3181 demo.init(argc, argv);
3182
Tony Barbour153cb062016-12-07 13:43:36 -07003183#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003184 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003185#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003186 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003187 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003188#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003189 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003190#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3191 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003192#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003193
3194 demo.init_vk_swapchain();
3195
3196 demo.prepare();
3197
Tony Barbour153cb062016-12-07 13:43:36 -07003198#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003199 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003200#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003201 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003202#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003203 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003204#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3205 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003206#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3207 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003208#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003209
3210 demo.cleanup();
3211
3212 return validation_error;
3213}
3214
Bill Hollings0a0625a2019-07-15 17:39:18 -04003215#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003216
3217// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003218static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003219 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003220 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003221 demo.init_vk_swapchain();
3222 demo.prepare();
3223 demo.spin_angle = 0.4f;
3224}
3225
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003226#else
3227#error "Platform not supported"
3228#endif