blob: 8efea2a211e838ebd2e82e44e362b09615247365 [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;
942 use_xlib = false;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000943 /* Autodetect suitable / best GPU by default */
944 gpu_number = -1;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600945
Dave Houlton5fa47912018-02-16 11:02:26 -0700946 for (int i = 1; i < argc; i++) {
947 if (strcmp(argv[i], "--use_staging") == 0) {
948 use_staging_buffer = true;
949 continue;
950 }
951 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
952 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
953 i++;
954 continue;
955 }
956 if (strcmp(argv[i], "--break") == 0) {
957 use_break = true;
958 continue;
959 }
960 if (strcmp(argv[i], "--validate") == 0) {
961 validate = true;
962 continue;
963 }
964 if (strcmp(argv[i], "--xlib") == 0) {
965 fprintf(stderr, "--xlib is deprecated and no longer does anything");
966 continue;
967 }
968 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
969 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
970 i++;
971 continue;
972 }
973 if (strcmp(argv[i], "--suppress_popups") == 0) {
974 suppress_popups = true;
975 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600976 }
Tony-LunarG50e737c2020-07-16 14:26:03 -0600977 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
978 gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +0000979 assert(gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -0600980 i++;
981 continue;
982 }
Tony-LunarGd74734f2019-06-04 14:11:43 -0600983 std::stringstream usage;
984 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
985 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -0600986 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600987 << "\t[--present_mode <present mode enum>]\n"
988 << "\t<present_mode_enum>\n"
989 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
990 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
991 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
Witold Baryluka3b988f2021-01-07 19:03:02 +0000992 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR << "\n";
Tony-LunarGd74734f2019-06-04 14:11:43 -0600993
994#if defined(_WIN32)
995 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
996#else
997 std::cerr << usage.str();
998 std::cerr.flush();
999#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001000 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001001 }
1002
Dave Houlton5fa47912018-02-16 11:02:26 -07001003 if (!use_xlib) {
1004 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001005 }
1006
Dave Houlton5fa47912018-02-16 11:02:26 -07001007 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001008
Dave Houlton5fa47912018-02-16 11:02:26 -07001009 width = 500;
1010 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001011
Dave Houlton5fa47912018-02-16 11:02:26 -07001012 spin_angle = 4.0f;
1013 spin_increment = 0.2f;
1014 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001015
Dave Houlton5fa47912018-02-16 11:02:26 -07001016 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1017 mat4x4_look_at(view_matrix, eye, origin, up);
1018 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001019
Dave Houlton5fa47912018-02-16 11:02:26 -07001020 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1021}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001022
Dave Houlton5fa47912018-02-16 11:02:26 -07001023void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001024#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001025 const xcb_setup_t *setup;
1026 xcb_screen_iterator_t iter;
1027 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001028
Dave Houlton5fa47912018-02-16 11:02:26 -07001029 const char *display_envar = getenv("DISPLAY");
1030 if (display_envar == nullptr || display_envar[0] == '\0') {
1031 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1032 fflush(stdout);
1033 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001034 }
1035
Dave Houlton5fa47912018-02-16 11:02:26 -07001036 connection = xcb_connect(nullptr, &scr);
1037 if (xcb_connection_has_error(connection) > 0) {
1038 printf(
1039 "Cannot find a compatible Vulkan installable client driver "
1040 "(ICD).\nExiting ...\n");
1041 fflush(stdout);
1042 exit(1);
1043 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001044
Dave Houlton5fa47912018-02-16 11:02:26 -07001045 setup = xcb_get_setup(connection);
1046 iter = xcb_setup_roots_iterator(setup);
1047 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001048
Dave Houlton5fa47912018-02-16 11:02:26 -07001049 screen = iter.data;
1050#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1051 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001052
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 if (display == nullptr) {
1054 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1055 fflush(stdout);
1056 exit(1);
1057 }
1058
1059 registry = wl_display_get_registry(display);
1060 wl_registry_add_listener(registry, &registry_listener, this);
1061 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001062#endif
1063}
1064
1065void Demo::init_vk() {
1066 uint32_t instance_extension_count = 0;
1067 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001068 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001069 enabled_extension_count = 0;
1070 enabled_layer_count = 0;
1071
Dave Houlton5fa47912018-02-16 11:02:26 -07001072 // Look for validation layers
1073 vk::Bool32 validation_found = VK_FALSE;
1074 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001075 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001076 VERIFY(result == vk::Result::eSuccess);
1077
Dave Houlton5fa47912018-02-16 11:02:26 -07001078 if (instance_layer_count > 0) {
1079 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1080 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001081 VERIFY(result == vk::Result::eSuccess);
1082
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001083 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001084 instance_layer_count, instance_layers.get());
1085 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001086 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1087 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001088 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001089 }
1090
Dave Houlton5fa47912018-02-16 11:02:26 -07001091 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001092 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001093 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1094 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001095 "vkCreateInstance Failure");
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 /* Look for instance extensions */
1100 vk::Bool32 surfaceExtFound = VK_FALSE;
1101 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1102 memset(extension_names, 0, sizeof(extension_names));
1103
Mike Schuchardt7510c832018-10-29 13:23:08 -07001104 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1105 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001106 VERIFY(result == vk::Result::eSuccess);
1107
1108 if (instance_extension_count > 0) {
1109 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1110 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1111 VERIFY(result == vk::Result::eSuccess);
1112
1113 for (uint32_t i = 0; i < instance_extension_count; i++) {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001114 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1115 extension_names[enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
1116 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001117 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1118 surfaceExtFound = 1;
1119 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1120 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001121#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001122 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1123 platformSurfaceExtFound = 1;
1124 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1125 }
1126#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1127 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1128 platformSurfaceExtFound = 1;
1129 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1130 }
1131#elif defined(VK_USE_PLATFORM_XCB_KHR)
1132 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1133 platformSurfaceExtFound = 1;
1134 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1135 }
Tony Barbour153cb062016-12-07 13:43:36 -07001136#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001137 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1138 platformSurfaceExtFound = 1;
1139 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1140 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001141#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1142 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1143 platformSurfaceExtFound = 1;
1144 extension_names[enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
1145 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001146#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1147 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1148 platformSurfaceExtFound = 1;
1149 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1150 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001151#elif defined(VK_USE_PLATFORM_METAL_EXT)
1152 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001153 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001154 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001155 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001156#endif
1157 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001158 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001159 }
1160
1161 if (!surfaceExtFound) {
1162 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1163 " extension.\n\n"
1164 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1165 "Please look at the Getting Started guide for additional information.\n",
1166 "vkCreateInstance Failure");
1167 }
1168
1169 if (!platformSurfaceExtFound) {
1170#if defined(VK_USE_PLATFORM_WIN32_KHR)
1171 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1172 " extension.\n\n"
1173 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1174 "Please look at the Getting Started guide for additional information.\n",
1175 "vkCreateInstance Failure");
1176#elif defined(VK_USE_PLATFORM_XCB_KHR)
1177 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1178 " extension.\n\n"
1179 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1180 "Please look at the Getting Started guide for additional information.\n",
1181 "vkCreateInstance Failure");
1182#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1183 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1184 " extension.\n\n"
1185 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1186 "Please look at the Getting Started guide for additional information.\n",
1187 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001188#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001189 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1190 " extension.\n\n"
1191 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1192 "Please look at the Getting Started guide for additional information.\n",
1193 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001194#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1195 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
1196 " extension.\n\n"
1197 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1198 "Please look at the Getting Started guide for additional information.\n",
1199 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001200#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001201 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1202 " extension.\n\n"
1203 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1204 "Please look at the Getting Started guide for additional information.\n",
1205 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001206#elif defined(VK_USE_PLATFORM_METAL_EXT)
1207 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001208 " extension.\n\nDo you have a compatible "
1209 "Vulkan installable client driver (ICD) installed?\nPlease "
1210 "look at the Getting Started guide for additional "
1211 "information.\n",
1212 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001213#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001214 }
1215 auto const app = vk::ApplicationInfo()
1216 .setPApplicationName(APP_SHORT_NAME)
1217 .setApplicationVersion(0)
1218 .setPEngineName(APP_SHORT_NAME)
1219 .setEngineVersion(0)
1220 .setApiVersion(VK_API_VERSION_1_0);
1221 auto const inst_info = vk::InstanceCreateInfo()
1222 .setPApplicationInfo(&app)
1223 .setEnabledLayerCount(enabled_layer_count)
1224 .setPpEnabledLayerNames(instance_validation_layers)
1225 .setEnabledExtensionCount(enabled_extension_count)
1226 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001227
Dave Houlton5fa47912018-02-16 11:02:26 -07001228 result = vk::createInstance(&inst_info, nullptr, &inst);
1229 if (result == vk::Result::eErrorIncompatibleDriver) {
1230 ERR_EXIT(
1231 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1232 "Please look at the Getting Started guide for additional information.\n",
1233 "vkCreateInstance Failure");
1234 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1235 ERR_EXIT(
1236 "Cannot find a specified extension library.\n"
1237 "Make sure your layers path is set appropriately.\n",
1238 "vkCreateInstance Failure");
1239 } else if (result != vk::Result::eSuccess) {
1240 ERR_EXIT(
1241 "vkCreateInstance failed.\n\n"
1242 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1243 "Please look at the Getting Started guide for additional information.\n",
1244 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001245 }
1246
Witold Baryluka3b988f2021-01-07 19:03:02 +00001247 /* Make initial call to query gpu_count, then second call for gpu info */
1248 uint32_t gpu_count = 0;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001249 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001250 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001251
Witold Baryluka3b988f2021-01-07 19:03:02 +00001252 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001253 ERR_EXIT(
1254 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1255 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1256 "Please look at the Getting Started guide for additional information.\n",
1257 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001258 }
1259
Witold Baryluka3b988f2021-01-07 19:03:02 +00001260 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1261 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
1262 VERIFY(result == vk::Result::eSuccess);
1263
1264 if (gpu_number >= 0 && !((uint32_t)gpu_number < gpu_count)) {
1265 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", gpu_number, gpu_count);
1266 ERR_EXIT("Specified GPU number is not present", "User Error");
1267 }
1268
1269 /* Try to auto select most suitable device */
1270 if (gpu_number == -1) {
1271 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
1272 memset(count_device_type, 0, sizeof(count_device_type));
1273
1274 for (uint32_t i = 0; i < gpu_count; i++) {
1275 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1276 assert(static_cast<int>(physicalDeviceProperties.deviceType) <= VK_PHYSICAL_DEVICE_TYPE_CPU);
1277 count_device_type[static_cast<int>(physicalDeviceProperties.deviceType)]++;
1278 }
1279
1280 const vk::PhysicalDeviceType device_type_preference[] = {
1281 vk::PhysicalDeviceType::eDiscreteGpu, vk::PhysicalDeviceType::eIntegratedGpu, vk::PhysicalDeviceType::eVirtualGpu,
1282 vk::PhysicalDeviceType::eCpu, vk::PhysicalDeviceType::eOther};
1283 vk::PhysicalDeviceType search_for_device_type = vk::PhysicalDeviceType::eDiscreteGpu;
1284 for (uint32_t i = 0; i < sizeof(device_type_preference) / sizeof(vk::PhysicalDeviceType); i++) {
1285 if (count_device_type[static_cast<int>(device_type_preference[i])]) {
1286 search_for_device_type = device_type_preference[i];
1287 break;
1288 }
1289 }
1290
1291 for (uint32_t i = 0; i < gpu_count; i++) {
1292 const auto physicalDeviceProperties = physical_devices[i].getProperties();
1293 if (physicalDeviceProperties.deviceType == search_for_device_type) {
1294 gpu_number = i;
1295 break;
1296 }
1297 }
1298 }
1299 assert(gpu_number >= 0);
1300 gpu = physical_devices[gpu_number];
1301 {
1302 auto physicalDeviceProperties = gpu.getProperties();
1303 fprintf(stderr, "Selected GPU %d: %s, type: %s\n", gpu_number, physicalDeviceProperties.deviceName.data(),
1304 to_string(physicalDeviceProperties.deviceType).c_str());
1305 }
1306 physical_devices.reset();
1307
Dave Houlton5fa47912018-02-16 11:02:26 -07001308 /* Look for device extensions */
1309 uint32_t device_extension_count = 0;
1310 vk::Bool32 swapchainExtFound = VK_FALSE;
1311 enabled_extension_count = 0;
1312 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001313
Mike Schuchardt7510c832018-10-29 13:23:08 -07001314 result =
1315 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001316 VERIFY(result == vk::Result::eSuccess);
1317
1318 if (device_extension_count > 0) {
1319 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1320 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001321 VERIFY(result == vk::Result::eSuccess);
1322
Dave Houlton5fa47912018-02-16 11:02:26 -07001323 for (uint32_t i = 0; i < device_extension_count; i++) {
1324 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1325 swapchainExtFound = 1;
1326 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001327 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05001328 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
1329 extension_names[enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001330 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001331 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001332 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001333 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001334
Dave Houlton5fa47912018-02-16 11:02:26 -07001335 if (!swapchainExtFound) {
1336 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1337 " extension.\n\n"
1338 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1339 "Please look at the Getting Started guide for additional information.\n",
1340 "vkCreateInstance Failure");
1341 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001342
Dave Houlton5fa47912018-02-16 11:02:26 -07001343 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001344
Dave Houlton5fa47912018-02-16 11:02:26 -07001345 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001346 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001347 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001348
Dave Houlton5fa47912018-02-16 11:02:26 -07001349 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1350 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001351
Dave Houlton5fa47912018-02-16 11:02:26 -07001352 // Query fine-grained feature support for this device.
1353 // If app has specific feature requirements it should check supported
1354 // features based on this query
1355 vk::PhysicalDeviceFeatures physDevFeatures;
1356 gpu.getFeatures(&physDevFeatures);
1357}
1358
Tony-LunarG6cebf142019-09-11 14:32:23 -06001359void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001360// Create a WSI surface for the window:
1361#if defined(VK_USE_PLATFORM_WIN32_KHR)
1362 {
1363 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1364
1365 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1366 VERIFY(result == vk::Result::eSuccess);
1367 }
1368#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1369 {
1370 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1371
1372 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1373 VERIFY(result == vk::Result::eSuccess);
1374 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001375#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1376 {
1377 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1378
1379 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1380 VERIFY(result == vk::Result::eSuccess);
1381 }
1382#elif defined(VK_USE_PLATFORM_XCB_KHR)
1383 {
1384 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1385
1386 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1387 VERIFY(result == vk::Result::eSuccess);
1388 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02001389#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
1390 {
1391 auto const createInfo = vk::DirectFBSurfaceCreateInfoEXT().setDfb(dfb).setSurface(window);
1392
1393 auto result = inst.createDirectFBSurfaceEXT(&createInfo, nullptr, &surface);
1394 VERIFY(result == vk::Result::eSuccess);
1395 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001396#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001397 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001398 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001399
Bill Hollings0a0625a2019-07-15 17:39:18 -04001400 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001401 VERIFY(result == vk::Result::eSuccess);
1402 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001403#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1404 {
1405 auto result = create_display_surface();
1406 VERIFY(result == vk::Result::eSuccess);
1407 }
1408#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001409}
1410
1411void Demo::init_vk_swapchain() {
1412 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001413 // Iterate over each queue to learn whether it supports presenting:
1414 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1415 for (uint32_t i = 0; i < queue_family_count; i++) {
1416 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1417 }
1418
1419 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1420 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1421 for (uint32_t i = 0; i < queue_family_count; i++) {
1422 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1423 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1424 graphicsQueueFamilyIndex = i;
1425 }
1426
1427 if (supportsPresent[i] == VK_TRUE) {
1428 graphicsQueueFamilyIndex = i;
1429 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001430 break;
1431 }
1432 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001433 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001434
Dave Houlton5fa47912018-02-16 11:02:26 -07001435 if (presentQueueFamilyIndex == UINT32_MAX) {
1436 // If didn't find a queue that supports both graphics and present,
1437 // then
1438 // find a separate present queue.
1439 for (uint32_t i = 0; i < queue_family_count; ++i) {
1440 if (supportsPresent[i] == VK_TRUE) {
1441 presentQueueFamilyIndex = i;
1442 break;
1443 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001444 }
1445 }
1446
Dave Houlton5fa47912018-02-16 11:02:26 -07001447 // Generate error if could not find both a graphics and a present queue
1448 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1449 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1450 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001451
Dave Houlton5fa47912018-02-16 11:02:26 -07001452 graphics_queue_family_index = graphicsQueueFamilyIndex;
1453 present_queue_family_index = presentQueueFamilyIndex;
1454 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001455
Dave Houlton5fa47912018-02-16 11:02:26 -07001456 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001457
Dave Houlton5fa47912018-02-16 11:02:26 -07001458 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1459 if (!separate_present_queue) {
1460 present_queue = graphics_queue;
1461 } else {
1462 device.getQueue(present_queue_family_index, 0, &present_queue);
1463 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001464
Dave Houlton5fa47912018-02-16 11:02:26 -07001465 // Get the list of VkFormat's that are supported:
1466 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001467 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001468 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001469
Dave Houlton5fa47912018-02-16 11:02:26 -07001470 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1471 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1472 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001473
Dave Houlton5fa47912018-02-16 11:02:26 -07001474 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1475 // the surface has no preferred format. Otherwise, at least one
1476 // supported format will be returned.
1477 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1478 format = vk::Format::eB8G8R8A8Unorm;
1479 } else {
1480 assert(formatCount >= 1);
1481 format = surfFormats[0].format;
1482 }
1483 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001484
Dave Houlton5fa47912018-02-16 11:02:26 -07001485 quit = false;
1486 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001487
Dave Houlton5fa47912018-02-16 11:02:26 -07001488 // Create semaphores to synchronize acquiring presentable buffers before
1489 // rendering and waiting for drawing to be complete before presenting
1490 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001491
Dave Houlton5fa47912018-02-16 11:02:26 -07001492 // Create fences that we can use to throttle if we get too far
1493 // ahead of the image presents
1494 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1495 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1496 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1497 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001498
Dave Houlton5fa47912018-02-16 11:02:26 -07001499 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1500 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001501
Dave Houlton5fa47912018-02-16 11:02:26 -07001502 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1503 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001504
Dave Houlton5fa47912018-02-16 11:02:26 -07001505 if (separate_present_queue) {
1506 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001507 VERIFY(result == vk::Result::eSuccess);
1508 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001509 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001510 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001511
Dave Houlton5fa47912018-02-16 11:02:26 -07001512 // Get Memory information and properties
1513 gpu.getMemoryProperties(&memory_properties);
1514}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001515
Dave Houlton5fa47912018-02-16 11:02:26 -07001516void Demo::prepare() {
1517 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1518 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1519 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001520
Dave Houlton5fa47912018-02-16 11:02:26 -07001521 auto const cmd = vk::CommandBufferAllocateInfo()
1522 .setCommandPool(cmd_pool)
1523 .setLevel(vk::CommandBufferLevel::ePrimary)
1524 .setCommandBufferCount(1);
1525
1526 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1527 VERIFY(result == vk::Result::eSuccess);
1528
1529 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1530
1531 result = this->cmd.begin(&cmd_buf_info);
1532 VERIFY(result == vk::Result::eSuccess);
1533
1534 prepare_buffers();
1535 prepare_depth();
1536 prepare_textures();
1537 prepare_cube_data_buffers();
1538
1539 prepare_descriptor_layout();
1540 prepare_render_pass();
1541 prepare_pipeline();
1542
1543 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1544 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1545 VERIFY(result == vk::Result::eSuccess);
1546 }
1547
1548 if (separate_present_queue) {
1549 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1550
1551 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1552 VERIFY(result == vk::Result::eSuccess);
1553
1554 auto const present_cmd = vk::CommandBufferAllocateInfo()
1555 .setCommandPool(present_cmd_pool)
1556 .setLevel(vk::CommandBufferLevel::ePrimary)
1557 .setCommandBufferCount(1);
1558
1559 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1560 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1561 VERIFY(result == vk::Result::eSuccess);
1562
1563 build_image_ownership_cmd(i);
1564 }
1565 }
1566
1567 prepare_descriptor_pool();
1568 prepare_descriptor_set();
1569
1570 prepare_framebuffers();
1571
1572 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1573 current_buffer = i;
1574 draw_build_cmd(swapchain_image_resources[i].cmd);
1575 }
1576
1577 /*
1578 * Prepare functions above may generate pipeline commands
1579 * that need to be flushed before beginning the render loop.
1580 */
1581 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001582 if (staging_texture.buffer) {
1583 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001584 }
1585
1586 current_buffer = 0;
1587 prepared = true;
1588}
1589
1590void Demo::prepare_buffers() {
1591 vk::SwapchainKHR oldSwapchain = swapchain;
1592
1593 // Check the surface capabilities and formats
1594 vk::SurfaceCapabilitiesKHR surfCapabilities;
1595 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1596 VERIFY(result == vk::Result::eSuccess);
1597
1598 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001599 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001600 VERIFY(result == vk::Result::eSuccess);
1601
1602 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1603 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1604 VERIFY(result == vk::Result::eSuccess);
1605
1606 vk::Extent2D swapchainExtent;
1607 // width and height are either both -1, or both not -1.
1608 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1609 // If the surface size is undefined, the size is set to
1610 // the size of the images requested.
1611 swapchainExtent.width = width;
1612 swapchainExtent.height = height;
1613 } else {
1614 // If the surface size is defined, the swap chain size must match
1615 swapchainExtent = surfCapabilities.currentExtent;
1616 width = surfCapabilities.currentExtent.width;
1617 height = surfCapabilities.currentExtent.height;
1618 }
1619
1620 // The FIFO present mode is guaranteed by the spec to be supported
1621 // and to have no tearing. It's a great default present mode to use.
1622 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1623
1624 // There are times when you may wish to use another present mode. The
1625 // following code shows how to select them, and the comments provide some
1626 // reasons you may wish to use them.
1627 //
1628 // It should be noted that Vulkan 1.0 doesn't provide a method for
1629 // synchronizing rendering with the presentation engine's display. There
1630 // is a method provided for throttling rendering with the display, but
1631 // there are some presentation engines for which this method will not work.
1632 // If an application doesn't throttle its rendering, and if it renders much
1633 // faster than the refresh rate of the display, this can waste power on
1634 // mobile devices. That is because power is being spent rendering images
1635 // that may never be seen.
1636
1637 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1638 // about
1639 // tearing, or have some way of synchronizing their rendering with the
1640 // display.
1641 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1642 // generally render a new presentable image every refresh cycle, but are
1643 // occasionally early. In this case, the application wants the new
1644 // image
1645 // to be displayed instead of the previously-queued-for-presentation
1646 // image
1647 // that has not yet been displayed.
1648 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1649 // render a new presentable image every refresh cycle, but are
1650 // occasionally
1651 // late. In this case (perhaps because of stuttering/latency concerns),
1652 // the application wants the late image to be immediately displayed,
1653 // even
1654 // though that may mean some tearing.
1655
1656 if (presentMode != swapchainPresentMode) {
1657 for (size_t i = 0; i < presentModeCount; ++i) {
1658 if (presentModes[i] == presentMode) {
1659 swapchainPresentMode = presentMode;
1660 break;
1661 }
1662 }
1663 }
1664
1665 if (swapchainPresentMode != presentMode) {
1666 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1667 }
1668
1669 // Determine the number of VkImages to use in the swap chain.
1670 // Application desires to acquire 3 images at a time for triple
1671 // buffering
1672 uint32_t desiredNumOfSwapchainImages = 3;
1673 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1674 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1675 }
1676
1677 // If maxImageCount is 0, we can ask for as many images as we want,
1678 // otherwise
1679 // we're limited to maxImageCount
1680 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1681 // Application must settle for fewer images than desired:
1682 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1683 }
1684
1685 vk::SurfaceTransformFlagBitsKHR preTransform;
1686 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1687 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1688 } else {
1689 preTransform = surfCapabilities.currentTransform;
1690 }
1691
1692 // Find a supported composite alpha mode - one of these is guaranteed to be set
1693 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1694 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1695 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1696 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1697 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1698 vk::CompositeAlphaFlagBitsKHR::eInherit,
1699 };
1700 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1701 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1702 compositeAlpha = compositeAlphaFlags[i];
1703 break;
1704 }
1705 }
1706
1707 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1708 .setSurface(surface)
1709 .setMinImageCount(desiredNumOfSwapchainImages)
1710 .setImageFormat(format)
1711 .setImageColorSpace(color_space)
1712 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1713 .setImageArrayLayers(1)
1714 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1715 .setImageSharingMode(vk::SharingMode::eExclusive)
1716 .setQueueFamilyIndexCount(0)
1717 .setPQueueFamilyIndices(nullptr)
1718 .setPreTransform(preTransform)
1719 .setCompositeAlpha(compositeAlpha)
1720 .setPresentMode(swapchainPresentMode)
1721 .setClipped(true)
1722 .setOldSwapchain(oldSwapchain);
1723
1724 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1725 VERIFY(result == vk::Result::eSuccess);
1726
1727 // If we just re-created an existing swapchain, we should destroy the
1728 // old
1729 // swapchain at this point.
1730 // Note: destroying the swapchain also cleans up all its associated
1731 // presentable images once the platform is done with them.
1732 if (oldSwapchain) {
1733 device.destroySwapchainKHR(oldSwapchain, nullptr);
1734 }
1735
Mike Schuchardt7510c832018-10-29 13:23:08 -07001736 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001737 VERIFY(result == vk::Result::eSuccess);
1738
1739 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1740 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1741 VERIFY(result == vk::Result::eSuccess);
1742
1743 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1744
1745 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1746 auto color_image_view = vk::ImageViewCreateInfo()
1747 .setViewType(vk::ImageViewType::e2D)
1748 .setFormat(format)
1749 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1750
1751 swapchain_image_resources[i].image = swapchainImages[i];
1752
1753 color_image_view.image = swapchain_image_resources[i].image;
1754
1755 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1756 VERIFY(result == vk::Result::eSuccess);
1757 }
1758}
1759
1760void Demo::prepare_cube_data_buffers() {
1761 mat4x4 VP;
1762 mat4x4_mul(VP, projection_matrix, view_matrix);
1763
1764 mat4x4 MVP;
1765 mat4x4_mul(MVP, VP, model_matrix);
1766
1767 vktexcube_vs_uniform data;
1768 memcpy(data.mvp, MVP, sizeof(MVP));
1769 // dumpMatrix("MVP", MVP)
1770
1771 for (int32_t i = 0; i < 12 * 3; i++) {
1772 data.position[i][0] = g_vertex_buffer_data[i * 3];
1773 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1774 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1775 data.position[i][3] = 1.0f;
1776 data.attr[i][0] = g_uv_buffer_data[2 * i];
1777 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1778 data.attr[i][2] = 0;
1779 data.attr[i][3] = 0;
1780 }
1781
1782 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1783
1784 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1785 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001786 VERIFY(result == vk::Result::eSuccess);
1787
1788 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001789 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001790
Dave Houlton5fa47912018-02-16 11:02:26 -07001791 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001792
Dave Houlton5fa47912018-02-16 11:02:26 -07001793 bool const pass = memory_type_from_properties(
1794 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1795 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001796 VERIFY(pass);
1797
Dave Houlton5fa47912018-02-16 11:02:26 -07001798 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001799 VERIFY(result == vk::Result::eSuccess);
1800
Tony-LunarG37af49f2019-12-19 12:04:19 -07001801 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1802 &swapchain_image_resources[i].uniform_memory_ptr);
1803 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001804
Tony-LunarG37af49f2019-12-19 12:04:19 -07001805 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001806
1807 result =
1808 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001809 VERIFY(result == vk::Result::eSuccess);
1810 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001811}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001812
Dave Houlton5fa47912018-02-16 11:02:26 -07001813void Demo::prepare_depth() {
1814 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001815
Dave Houlton5fa47912018-02-16 11:02:26 -07001816 auto const image = vk::ImageCreateInfo()
1817 .setImageType(vk::ImageType::e2D)
1818 .setFormat(depth.format)
1819 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1820 .setMipLevels(1)
1821 .setArrayLayers(1)
1822 .setSamples(vk::SampleCountFlagBits::e1)
1823 .setTiling(vk::ImageTiling::eOptimal)
1824 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1825 .setSharingMode(vk::SharingMode::eExclusive)
1826 .setQueueFamilyIndexCount(0)
1827 .setPQueueFamilyIndices(nullptr)
1828 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001829
Dave Houlton5fa47912018-02-16 11:02:26 -07001830 auto result = device.createImage(&image, nullptr, &depth.image);
1831 VERIFY(result == vk::Result::eSuccess);
1832
1833 vk::MemoryRequirements mem_reqs;
1834 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1835
1836 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1837 depth.mem_alloc.setMemoryTypeIndex(0);
1838
1839 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1840 &depth.mem_alloc.memoryTypeIndex);
1841 VERIFY(pass);
1842
1843 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1844 VERIFY(result == vk::Result::eSuccess);
1845
1846 result = device.bindImageMemory(depth.image, depth.mem, 0);
1847 VERIFY(result == vk::Result::eSuccess);
1848
1849 auto const view = vk::ImageViewCreateInfo()
1850 .setImage(depth.image)
1851 .setViewType(vk::ImageViewType::e2D)
1852 .setFormat(depth.format)
1853 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1854 result = device.createImageView(&view, nullptr, &depth.view);
1855 VERIFY(result == vk::Result::eSuccess);
1856}
1857
1858void Demo::prepare_descriptor_layout() {
1859 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1860 .setBinding(0)
1861 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1862 .setDescriptorCount(1)
1863 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1864 .setPImmutableSamplers(nullptr),
1865 vk::DescriptorSetLayoutBinding()
1866 .setBinding(1)
1867 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1868 .setDescriptorCount(texture_count)
1869 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1870 .setPImmutableSamplers(nullptr)};
1871
1872 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1873
1874 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1875 VERIFY(result == vk::Result::eSuccess);
1876
1877 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1878
1879 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1880 VERIFY(result == vk::Result::eSuccess);
1881}
1882
1883void Demo::prepare_descriptor_pool() {
1884 vk::DescriptorPoolSize const poolSizes[2] = {
1885 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1886 vk::DescriptorPoolSize()
1887 .setType(vk::DescriptorType::eCombinedImageSampler)
1888 .setDescriptorCount(swapchainImageCount * texture_count)};
1889
1890 auto const descriptor_pool =
1891 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1892
1893 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1894 VERIFY(result == vk::Result::eSuccess);
1895}
1896
1897void Demo::prepare_descriptor_set() {
1898 auto const alloc_info =
1899 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1900
1901 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1902
1903 vk::DescriptorImageInfo tex_descs[texture_count];
1904 for (uint32_t i = 0; i < texture_count; i++) {
1905 tex_descs[i].setSampler(textures[i].sampler);
1906 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001907 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001908 }
1909
1910 vk::WriteDescriptorSet writes[2];
1911
1912 writes[0].setDescriptorCount(1);
1913 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1914 writes[0].setPBufferInfo(&buffer_info);
1915
1916 writes[1].setDstBinding(1);
1917 writes[1].setDescriptorCount(texture_count);
1918 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1919 writes[1].setPImageInfo(tex_descs);
1920
1921 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1922 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001923 VERIFY(result == vk::Result::eSuccess);
1924
Dave Houlton5fa47912018-02-16 11:02:26 -07001925 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1926 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1927 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1928 device.updateDescriptorSets(2, writes, 0, nullptr);
1929 }
1930}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001931
Dave Houlton5fa47912018-02-16 11:02:26 -07001932void Demo::prepare_framebuffers() {
1933 vk::ImageView attachments[2];
1934 attachments[1] = depth.view;
1935
1936 auto const fb_info = vk::FramebufferCreateInfo()
1937 .setRenderPass(render_pass)
1938 .setAttachmentCount(2)
1939 .setPAttachments(attachments)
1940 .setWidth((uint32_t)width)
1941 .setHeight((uint32_t)height)
1942 .setLayers(1);
1943
1944 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1945 attachments[0] = swapchain_image_resources[i].view;
1946 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001947 VERIFY(result == vk::Result::eSuccess);
1948 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001949}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001950
Dave Houlton5fa47912018-02-16 11:02:26 -07001951vk::ShaderModule Demo::prepare_fs() {
1952 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001953#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001954 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001955
Dave Houlton5fa47912018-02-16 11:02:26 -07001956 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001957
Dave Houlton5fa47912018-02-16 11:02:26 -07001958 return frag_shader_module;
1959}
1960
1961void Demo::prepare_pipeline() {
1962 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1963 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1964 VERIFY(result == vk::Result::eSuccess);
1965
1966 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1967 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1968 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1969
1970 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1971
1972 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1973
1974 // TODO: Where are pViewports and pScissors set?
1975 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1976
1977 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1978 .setDepthClampEnable(VK_FALSE)
1979 .setRasterizerDiscardEnable(VK_FALSE)
1980 .setPolygonMode(vk::PolygonMode::eFill)
1981 .setCullMode(vk::CullModeFlagBits::eBack)
1982 .setFrontFace(vk::FrontFace::eCounterClockwise)
1983 .setDepthBiasEnable(VK_FALSE)
1984 .setLineWidth(1.0f);
1985
1986 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1987
1988 auto const stencilOp =
1989 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1990
1991 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1992 .setDepthTestEnable(VK_TRUE)
1993 .setDepthWriteEnable(VK_TRUE)
1994 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1995 .setDepthBoundsTestEnable(VK_FALSE)
1996 .setStencilTestEnable(VK_FALSE)
1997 .setFront(stencilOp)
1998 .setBack(stencilOp);
1999
2000 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
2001 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
2002 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
2003
2004 auto const colorBlendInfo =
2005 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
2006
2007 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
2008
2009 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
2010
2011 auto const pipeline = vk::GraphicsPipelineCreateInfo()
2012 .setStageCount(2)
2013 .setPStages(shaderStageInfo)
2014 .setPVertexInputState(&vertexInputInfo)
2015 .setPInputAssemblyState(&inputAssemblyInfo)
2016 .setPViewportState(&viewportInfo)
2017 .setPRasterizationState(&rasterizationInfo)
2018 .setPMultisampleState(&multisampleInfo)
2019 .setPDepthStencilState(&depthStencilInfo)
2020 .setPColorBlendState(&colorBlendInfo)
2021 .setPDynamicState(&dynamicStateInfo)
2022 .setLayout(pipeline_layout)
2023 .setRenderPass(render_pass);
2024
2025 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
2026 VERIFY(result == vk::Result::eSuccess);
2027
2028 device.destroyShaderModule(frag_shader_module, nullptr);
2029 device.destroyShaderModule(vert_shader_module, nullptr);
2030}
2031
2032void Demo::prepare_render_pass() {
2033 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
2034 // because at the start of the renderpass, we don't care about their contents.
2035 // At the start of the subpass, the color attachment's layout will be transitioned
2036 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
2037 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
2038 // the renderpass, the color attachment's layout will be transitioned to
2039 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
2040 // the renderpass, no barriers are necessary.
2041 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
2042 .setFormat(format)
2043 .setSamples(vk::SampleCountFlagBits::e1)
2044 .setLoadOp(vk::AttachmentLoadOp::eClear)
2045 .setStoreOp(vk::AttachmentStoreOp::eStore)
2046 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2047 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2048 .setInitialLayout(vk::ImageLayout::eUndefined)
2049 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2050 vk::AttachmentDescription()
2051 .setFormat(depth.format)
2052 .setSamples(vk::SampleCountFlagBits::e1)
2053 .setLoadOp(vk::AttachmentLoadOp::eClear)
2054 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2055 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2056 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2057 .setInitialLayout(vk::ImageLayout::eUndefined)
2058 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2059
2060 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2061
2062 auto const depth_reference =
2063 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2064
2065 auto const subpass = vk::SubpassDescription()
2066 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2067 .setInputAttachmentCount(0)
2068 .setPInputAttachments(nullptr)
2069 .setColorAttachmentCount(1)
2070 .setPColorAttachments(&color_reference)
2071 .setPResolveAttachments(nullptr)
2072 .setPDepthStencilAttachment(&depth_reference)
2073 .setPreserveAttachmentCount(0)
2074 .setPPreserveAttachments(nullptr);
2075
Tony-LunarG495604b2019-06-13 15:32:05 -06002076 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2077 vk::SubpassDependency const dependencies[2] = {
2078 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2079 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2080 .setDstSubpass(0)
2081 .setSrcStageMask(stages)
2082 .setDstStageMask(stages)
2083 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2084 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2085 .setDependencyFlags(vk::DependencyFlags()),
2086 vk::SubpassDependency() // Image layout transition
2087 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2088 .setDstSubpass(0)
2089 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2090 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2091 .setSrcAccessMask(vk::AccessFlagBits())
2092 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2093 .setDependencyFlags(vk::DependencyFlags()),
2094 };
2095
Dave Houlton5fa47912018-02-16 11:02:26 -07002096 auto const rp_info = vk::RenderPassCreateInfo()
2097 .setAttachmentCount(2)
2098 .setPAttachments(attachments)
2099 .setSubpassCount(1)
2100 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002101 .setDependencyCount(2)
2102 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002103
2104 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2105 VERIFY(result == vk::Result::eSuccess);
2106}
2107
2108vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2109 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2110
2111 vk::ShaderModule module;
2112 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2113 VERIFY(result == vk::Result::eSuccess);
2114
2115 return module;
2116}
2117
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002118void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2119 int32_t tex_width;
2120 int32_t tex_height;
2121
2122 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2123 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2124 }
2125
2126 tex_obj->tex_width = tex_width;
2127 tex_obj->tex_height = tex_height;
2128
2129 auto const buffer_create_info = vk::BufferCreateInfo()
2130 .setSize(tex_width * tex_height * 4)
2131 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2132 .setSharingMode(vk::SharingMode::eExclusive)
2133 .setQueueFamilyIndexCount(0)
2134 .setPQueueFamilyIndices(nullptr);
2135
2136 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2137 VERIFY(result == vk::Result::eSuccess);
2138
2139 vk::MemoryRequirements mem_reqs;
2140 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2141
2142 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2143 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2144
2145 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2146 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2147 VERIFY(pass == true);
2148
2149 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2150 VERIFY(result == vk::Result::eSuccess);
2151
2152 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2153 VERIFY(result == vk::Result::eSuccess);
2154
2155 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002156 layout.rowPitch = tex_width * 4;
2157 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2158 VERIFY(data.result == vk::Result::eSuccess);
2159
2160 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2161 fprintf(stderr, "Error loading texture: %s\n", filename);
2162 }
2163
2164 device.unmapMemory(tex_obj->mem);
2165}
2166
Dave Houlton5fa47912018-02-16 11:02:26 -07002167void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2168 vk::MemoryPropertyFlags required_props) {
2169 int32_t tex_width;
2170 int32_t tex_height;
2171 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2172 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002173 }
2174
Dave Houlton5fa47912018-02-16 11:02:26 -07002175 tex_obj->tex_width = tex_width;
2176 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002177
Dave Houlton5fa47912018-02-16 11:02:26 -07002178 auto const image_create_info = vk::ImageCreateInfo()
2179 .setImageType(vk::ImageType::e2D)
2180 .setFormat(vk::Format::eR8G8B8A8Unorm)
2181 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2182 .setMipLevels(1)
2183 .setArrayLayers(1)
2184 .setSamples(vk::SampleCountFlagBits::e1)
2185 .setTiling(tiling)
2186 .setUsage(usage)
2187 .setSharingMode(vk::SharingMode::eExclusive)
2188 .setQueueFamilyIndexCount(0)
2189 .setPQueueFamilyIndices(nullptr)
2190 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002191
Dave Houlton5fa47912018-02-16 11:02:26 -07002192 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2193 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002194
Dave Houlton5fa47912018-02-16 11:02:26 -07002195 vk::MemoryRequirements mem_reqs;
2196 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002197
Dave Houlton5fa47912018-02-16 11:02:26 -07002198 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2199 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002200
Dave Houlton5fa47912018-02-16 11:02:26 -07002201 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2202 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002203
Dave Houlton5fa47912018-02-16 11:02:26 -07002204 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2205 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002206
Dave Houlton5fa47912018-02-16 11:02:26 -07002207 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2208 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002209
Dave Houlton5fa47912018-02-16 11:02:26 -07002210 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2211 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2212 vk::SubresourceLayout layout;
2213 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002214
Dave Houlton5fa47912018-02-16 11:02:26 -07002215 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002216 VERIFY(data.result == vk::Result::eSuccess);
2217
Dave Houlton5fa47912018-02-16 11:02:26 -07002218 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2219 fprintf(stderr, "Error loading texture: %s\n", filename);
2220 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002221
Dave Houlton5fa47912018-02-16 11:02:26 -07002222 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002223 }
2224
Dave Houlton5fa47912018-02-16 11:02:26 -07002225 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2226}
2227
2228void Demo::prepare_textures() {
2229 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2230 vk::FormatProperties props;
2231 gpu.getFormatProperties(tex_format, &props);
2232
2233 for (uint32_t i = 0; i < texture_count; i++) {
2234 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2235 /* Device can texture using linear textures */
2236 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2237 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2238 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2239 // shader to run until layout transition completes
2240 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2241 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2242 vk::PipelineStageFlagBits::eFragmentShader);
2243 staging_texture.image = vk::Image();
2244 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2245 /* Must use staging buffer to copy linear texture to optimized */
2246
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002247 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002248
2249 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2250 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2251 vk::MemoryPropertyFlagBits::eDeviceLocal);
2252
Dave Houlton5fa47912018-02-16 11:02:26 -07002253 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2254 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2255 vk::PipelineStageFlagBits::eTransfer);
2256
2257 auto const subresource = vk::ImageSubresourceLayers()
2258 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2259 .setMipLevel(0)
2260 .setBaseArrayLayer(0)
2261 .setLayerCount(1);
2262
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002263 auto const copy_region =
2264 vk::BufferImageCopy()
2265 .setBufferOffset(0)
2266 .setBufferRowLength(staging_texture.tex_width)
2267 .setBufferImageHeight(staging_texture.tex_height)
2268 .setImageSubresource(subresource)
2269 .setImageOffset({0, 0, 0})
2270 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002271
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002272 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002273
2274 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2275 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2276 vk::PipelineStageFlagBits::eFragmentShader);
2277 } else {
2278 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002279 }
2280
Dave Houlton5fa47912018-02-16 11:02:26 -07002281 auto const samplerInfo = vk::SamplerCreateInfo()
2282 .setMagFilter(vk::Filter::eNearest)
2283 .setMinFilter(vk::Filter::eNearest)
2284 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2285 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2286 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2287 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2288 .setMipLodBias(0.0f)
2289 .setAnisotropyEnable(VK_FALSE)
2290 .setMaxAnisotropy(1)
2291 .setCompareEnable(VK_FALSE)
2292 .setCompareOp(vk::CompareOp::eNever)
2293 .setMinLod(0.0f)
2294 .setMaxLod(0.0f)
2295 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2296 .setUnnormalizedCoordinates(VK_FALSE);
2297
2298 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2299 VERIFY(result == vk::Result::eSuccess);
2300
2301 auto const viewInfo = vk::ImageViewCreateInfo()
2302 .setImage(textures[i].image)
2303 .setViewType(vk::ImageViewType::e2D)
2304 .setFormat(tex_format)
2305 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2306
2307 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2308 VERIFY(result == vk::Result::eSuccess);
2309 }
2310}
2311
2312vk::ShaderModule Demo::prepare_vs() {
2313 const uint32_t vertShaderCode[] = {
2314#include "cube.vert.inc"
2315 };
2316
2317 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2318
2319 return vert_shader_module;
2320}
2321
2322void Demo::resize() {
2323 uint32_t i;
2324
2325 // Don't react to resize until after first initialization.
2326 if (!prepared) {
2327 return;
2328 }
2329
2330 // In order to properly resize the window, we must re-create the
2331 // swapchain
2332 // AND redo the command buffers, etc.
2333 //
2334 // First, perform part of the cleanup() function:
2335 prepared = false;
2336 auto result = device.waitIdle();
2337 VERIFY(result == vk::Result::eSuccess);
2338
2339 for (i = 0; i < swapchainImageCount; i++) {
2340 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2341 }
2342
2343 device.destroyDescriptorPool(desc_pool, nullptr);
2344
2345 device.destroyPipeline(pipeline, nullptr);
2346 device.destroyPipelineCache(pipelineCache, nullptr);
2347 device.destroyRenderPass(render_pass, nullptr);
2348 device.destroyPipelineLayout(pipeline_layout, nullptr);
2349 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2350
2351 for (i = 0; i < texture_count; i++) {
2352 device.destroyImageView(textures[i].view, nullptr);
2353 device.destroyImage(textures[i].image, nullptr);
2354 device.freeMemory(textures[i].mem, nullptr);
2355 device.destroySampler(textures[i].sampler, nullptr);
2356 }
2357
2358 device.destroyImageView(depth.view, nullptr);
2359 device.destroyImage(depth.image, nullptr);
2360 device.freeMemory(depth.mem, nullptr);
2361
2362 for (i = 0; i < swapchainImageCount; i++) {
2363 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002364 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002365 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002366 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002367 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2368 }
2369
2370 device.destroyCommandPool(cmd_pool, nullptr);
2371 if (separate_present_queue) {
2372 device.destroyCommandPool(present_cmd_pool, nullptr);
2373 }
2374
2375 // Second, re-perform the prepare() function, which will re-create the
2376 // swapchain.
2377 prepare();
2378}
2379
2380void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2381 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2382 assert(cmd);
2383
2384 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2385 vk::AccessFlags flags;
2386
2387 switch (layout) {
2388 case vk::ImageLayout::eTransferDstOptimal:
2389 // Make sure anything that was copying from this image has
2390 // completed
2391 flags = vk::AccessFlagBits::eTransferWrite;
2392 break;
2393 case vk::ImageLayout::eColorAttachmentOptimal:
2394 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2395 break;
2396 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2397 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2398 break;
2399 case vk::ImageLayout::eShaderReadOnlyOptimal:
2400 // Make sure any Copy or CPU writes to image are flushed
2401 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2402 break;
2403 case vk::ImageLayout::eTransferSrcOptimal:
2404 flags = vk::AccessFlagBits::eTransferRead;
2405 break;
2406 case vk::ImageLayout::ePresentSrcKHR:
2407 flags = vk::AccessFlagBits::eMemoryRead;
2408 break;
2409 default:
2410 break;
2411 }
2412
2413 return flags;
2414 };
2415
2416 auto const barrier = vk::ImageMemoryBarrier()
2417 .setSrcAccessMask(srcAccessMask)
2418 .setDstAccessMask(DstAccessMask(newLayout))
2419 .setOldLayout(oldLayout)
2420 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002421 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2422 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002423 .setImage(image)
2424 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2425
2426 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2427}
2428
2429void Demo::update_data_buffer() {
2430 mat4x4 VP;
2431 mat4x4_mul(VP, projection_matrix, view_matrix);
2432
2433 // Rotate around the Y axis
2434 mat4x4 Model;
2435 mat4x4_dup(Model, model_matrix);
2436 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2437
2438 mat4x4 MVP;
2439 mat4x4_mul(MVP, VP, model_matrix);
2440
Tony-LunarG37af49f2019-12-19 12:04:19 -07002441 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002442}
2443
Karl Schultzb7940402018-05-29 13:09:22 -06002444/* Convert ppm image data from header file into RGBA texture image */
2445#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002446bool 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 -06002447 (void)filename;
2448 char *cPtr;
2449 cPtr = (char *)lunarg_ppm;
2450 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002451 return false;
2452 }
Karl Schultzb7940402018-05-29 13:09:22 -06002453 while (strncmp(cPtr++, "\n", 1))
2454 ;
2455 sscanf(cPtr, "%u %u", width, height);
2456 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002457 return true;
2458 }
Karl Schultzb7940402018-05-29 13:09:22 -06002459 while (strncmp(cPtr++, "\n", 1))
2460 ;
2461 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002462 return false;
2463 }
Karl Schultzb7940402018-05-29 13:09:22 -06002464 while (strncmp(cPtr++, "\n", 1))
2465 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002466 for (int y = 0; y < *height; y++) {
2467 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002468 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002469 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002470 rowPtr[3] = 255; /* Alpha of 1 */
2471 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002472 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002473 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002474 rgba_data += layout->rowPitch;
2475 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002476 return true;
2477}
2478
2479bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2480 // Search memtypes to find first index with those properties
2481 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2482 if ((typeBits & 1) == 1) {
2483 // Type is available, does it match user properties?
2484 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2485 *typeIndex = i;
2486 return true;
2487 }
2488 }
2489 typeBits >>= 1;
2490 }
2491
2492 // No memory types matched, return failure
2493 return false;
2494}
2495
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002496#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002497void Demo::run() {
2498 if (!prepared) {
2499 return;
2500 }
2501
2502 draw();
2503 curFrame++;
2504
Petr Krausd88e4e52019-01-23 18:45:04 +01002505 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002506 PostQuitMessage(validation_error);
2507 }
2508}
2509
2510void Demo::create_window() {
2511 WNDCLASSEX win_class;
2512
2513 // Initialize the window class structure:
2514 win_class.cbSize = sizeof(WNDCLASSEX);
2515 win_class.style = CS_HREDRAW | CS_VREDRAW;
2516 win_class.lpfnWndProc = WndProc;
2517 win_class.cbClsExtra = 0;
2518 win_class.cbWndExtra = 0;
2519 win_class.hInstance = connection; // hInstance
2520 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2521 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2522 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2523 win_class.lpszMenuName = nullptr;
2524 win_class.lpszClassName = name;
2525 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2526
2527 // Register window class:
2528 if (!RegisterClassEx(&win_class)) {
2529 // It didn't work, so try to give a useful error:
2530 printf("Unexpected error trying to start the application!\n");
2531 fflush(stdout);
2532 exit(1);
2533 }
2534
2535 // Create window with the registered class:
2536 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2537 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2538 window = CreateWindowEx(0,
2539 name, // class name
2540 name, // app name
2541 WS_OVERLAPPEDWINDOW | // window style
2542 WS_VISIBLE | WS_SYSMENU,
2543 100, 100, // x/y coords
2544 wr.right - wr.left, // width
2545 wr.bottom - wr.top, // height
2546 nullptr, // handle to parent
2547 nullptr, // handle to menu
2548 connection, // hInstance
2549 nullptr); // no extra parameters
2550
2551 if (!window) {
2552 // It didn't work, so try to give a useful error:
2553 printf("Cannot create a window in which to draw!\n");
2554 fflush(stdout);
2555 exit(1);
2556 }
2557
2558 // Window client area size must be at least 1 pixel high, to prevent
2559 // crash.
2560 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2561 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2562}
2563#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2564
2565void Demo::create_xlib_window() {
2566 const char *display_envar = getenv("DISPLAY");
2567 if (display_envar == nullptr || display_envar[0] == '\0') {
2568 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2569 fflush(stdout);
2570 exit(1);
2571 }
2572
2573 XInitThreads();
2574 display = XOpenDisplay(nullptr);
2575 long visualMask = VisualScreenMask;
2576 int numberOfVisuals;
2577 XVisualInfo vInfoTemplate = {};
2578 vInfoTemplate.screen = DefaultScreen(display);
2579 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2580
2581 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2582
2583 XSetWindowAttributes windowAttributes = {};
2584 windowAttributes.colormap = colormap;
2585 windowAttributes.background_pixel = 0xFFFFFFFF;
2586 windowAttributes.border_pixel = 0;
2587 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2588
2589 xlib_window =
2590 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2591 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2592
2593 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2594 XMapWindow(display, xlib_window);
2595 XFlush(display);
2596 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2597}
2598
2599void Demo::handle_xlib_event(const XEvent *event) {
2600 switch (event->type) {
2601 case ClientMessage:
2602 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2603 quit = true;
2604 }
2605 break;
2606 case KeyPress:
2607 switch (event->xkey.keycode) {
2608 case 0x9: // Escape
2609 quit = true;
2610 break;
2611 case 0x71: // left arrow key
2612 spin_angle -= spin_increment;
2613 break;
2614 case 0x72: // right arrow key
2615 spin_angle += spin_increment;
2616 break;
2617 case 0x41: // space bar
2618 pause = !pause;
2619 break;
2620 }
2621 break;
2622 case ConfigureNotify:
2623 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2624 width = event->xconfigure.width;
2625 height = event->xconfigure.height;
2626 resize();
2627 }
2628 break;
2629 default:
2630 break;
2631 }
2632}
2633
2634void Demo::run_xlib() {
2635 while (!quit) {
2636 XEvent event;
2637
2638 if (pause) {
2639 XNextEvent(display, &event);
2640 handle_xlib_event(&event);
2641 }
2642 while (XPending(display) > 0) {
2643 XNextEvent(display, &event);
2644 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002645 }
2646
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002647 draw();
2648 curFrame++;
2649
Dave Houlton5fa47912018-02-16 11:02:26 -07002650 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2651 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002652 }
2653 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002654}
Tony Barbour153cb062016-12-07 13:43:36 -07002655#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002656
Dave Houlton5fa47912018-02-16 11:02:26 -07002657void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2658 uint8_t event_code = event->response_type & 0x7f;
2659 switch (event_code) {
2660 case XCB_EXPOSE:
2661 // TODO: Resize window
2662 break;
2663 case XCB_CLIENT_MESSAGE:
2664 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2665 quit = true;
2666 }
2667 break;
2668 case XCB_KEY_RELEASE: {
2669 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002670
Dave Houlton5fa47912018-02-16 11:02:26 -07002671 switch (key->detail) {
2672 case 0x9: // Escape
2673 quit = true;
2674 break;
2675 case 0x71: // left arrow key
2676 spin_angle -= spin_increment;
2677 break;
2678 case 0x72: // right arrow key
2679 spin_angle += spin_increment;
2680 break;
2681 case 0x41: // space bar
2682 pause = !pause;
2683 break;
2684 }
2685 } break;
2686 case XCB_CONFIGURE_NOTIFY: {
2687 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2688 if ((width != cfg->width) || (height != cfg->height)) {
2689 width = cfg->width;
2690 height = cfg->height;
2691 resize();
2692 }
2693 } break;
2694 default:
2695 break;
2696 }
2697}
2698
2699void Demo::run_xcb() {
2700 xcb_flush(connection);
2701
2702 while (!quit) {
2703 xcb_generic_event_t *event;
2704
2705 if (pause) {
2706 event = xcb_wait_for_event(connection);
2707 } else {
2708 event = xcb_poll_for_event(connection);
2709 }
2710 while (event) {
2711 handle_xcb_event(event);
2712 free(event);
2713 event = xcb_poll_for_event(connection);
2714 }
2715
2716 draw();
2717 curFrame++;
2718 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2719 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002720 }
2721 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002722}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002723
Dave Houlton5fa47912018-02-16 11:02:26 -07002724void Demo::create_xcb_window() {
2725 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002726
Dave Houlton5fa47912018-02-16 11:02:26 -07002727 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002728
Dave Houlton5fa47912018-02-16 11:02:26 -07002729 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2730 value_list[0] = screen->black_pixel;
2731 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002732
Dave Houlton5fa47912018-02-16 11:02:26 -07002733 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2734 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2735
2736 /* Magic code that will send notification when window is destroyed */
2737 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2738 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2739
2740 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2741 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2742
2743 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2744
2745 free(reply);
2746
2747 xcb_map_window(connection, xcb_window);
2748
2749 // Force the x/y coordinates to 100,100 results are identical in
2750 // consecutive
2751 // runs
2752 const uint32_t coords[] = {100, 100};
2753 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2754}
2755#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2756
2757void Demo::run() {
2758 while (!quit) {
2759 if (pause) {
2760 wl_display_dispatch(display);
2761 } else {
2762 wl_display_dispatch_pending(display);
2763 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002764 draw();
2765 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002766 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002767 quit = true;
2768 }
2769 }
2770 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002771}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002772
Dave Houlton5fa47912018-02-16 11:02:26 -07002773void Demo::create_window() {
2774 window = wl_compositor_create_surface(compositor);
2775 if (!window) {
2776 printf("Can not create wayland_surface from compositor!\n");
2777 fflush(stdout);
2778 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002779 }
2780
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002781 shell_surface = wl_shell_get_shell_surface(shell, window);
2782 if (!shell_surface) {
2783 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002784 fflush(stdout);
2785 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002786 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002787
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002788 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2789 wl_shell_surface_set_toplevel(shell_surface);
2790 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002791}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002792#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2793
2794void Demo::handle_directfb_event(const DFBInputEvent *event) {
2795 if (event->type != DIET_KEYPRESS) return;
2796 switch (event->key_symbol) {
2797 case DIKS_ESCAPE: // Escape
2798 quit = true;
2799 break;
2800 case DIKS_CURSOR_LEFT: // left arrow key
2801 spin_angle -= spin_increment;
2802 break;
2803 case DIKS_CURSOR_RIGHT: // right arrow key
2804 spin_angle += spin_increment;
2805 break;
2806 case DIKS_SPACE: // space bar
2807 pause = !pause;
2808 break;
2809 default:
2810 break;
2811 }
2812}
2813
2814void Demo::run_directfb() {
2815 while (!quit) {
2816 DFBInputEvent event;
2817
2818 if (pause) {
2819 event_buffer->WaitForEvent(event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002820 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002821 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002822 if (!event_buffer->GetEvent(event_buffer, DFB_EVENT(&event))) handle_directfb_event(&event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002823
2824 draw();
2825 curFrame++;
2826 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2827 quit = true;
2828 }
2829 }
2830 }
2831}
2832
2833void Demo::create_directfb_window() {
2834 DFBResult ret;
2835
2836 ret = DirectFBInit(NULL, NULL);
2837 if (ret) {
2838 printf("DirectFBInit failed to initialize DirectFB!\n");
2839 fflush(stdout);
2840 exit(1);
2841 }
2842
2843 ret = DirectFBCreate(&dfb);
2844 if (ret) {
2845 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2846 fflush(stdout);
2847 exit(1);
2848 }
2849
2850 DFBSurfaceDescription desc;
2851 desc.flags = (DFBSurfaceDescriptionFlags)(DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT);
2852 desc.caps = DSCAPS_PRIMARY;
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002853 desc.width = width;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002854 desc.height = height;
2855 ret = dfb->CreateSurface(dfb, &desc, &window);
2856 if (ret) {
2857 printf("CreateSurface failed to create DirectFB surface interface!\n");
2858 fflush(stdout);
2859 exit(1);
2860 }
2861
2862 ret = dfb->CreateInputEventBuffer(dfb, DICAPS_KEYS, DFB_FALSE, &event_buffer);
2863 if (ret) {
2864 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2865 fflush(stdout);
2866 exit(1);
2867 }
2868}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002869#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002870void Demo::run() {
2871 draw();
2872 curFrame++;
2873 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2874 quit = true;
2875 }
2876}
Damien Leone600c3052017-01-31 10:26:07 -07002877#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2878
Dave Houlton5fa47912018-02-16 11:02:26 -07002879vk::Result Demo::create_display_surface() {
2880 vk::Result result;
2881 uint32_t display_count;
2882 uint32_t mode_count;
2883 uint32_t plane_count;
2884 vk::DisplayPropertiesKHR display_props;
2885 vk::DisplayKHR display;
2886 vk::DisplayModePropertiesKHR mode_props;
2887 vk::DisplayPlanePropertiesKHR *plane_props;
2888 vk::Bool32 found_plane = VK_FALSE;
2889 uint32_t plane_index;
2890 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002891
Dave Houlton5fa47912018-02-16 11:02:26 -07002892 // Get the first display
2893 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2894 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002895
Dave Houlton5fa47912018-02-16 11:02:26 -07002896 if (display_count == 0) {
2897 printf("Cannot find any display!\n");
2898 fflush(stdout);
2899 exit(1);
2900 }
2901
2902 display_count = 1;
2903 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2904 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2905
2906 display = display_props.display;
2907
2908 // Get the first mode of the display
2909 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2910 VERIFY(result == vk::Result::eSuccess);
2911
2912 if (mode_count == 0) {
2913 printf("Cannot find any mode for the display!\n");
2914 fflush(stdout);
2915 exit(1);
2916 }
2917
2918 mode_count = 1;
2919 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2920 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2921
2922 // Get the list of planes
2923 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2924 VERIFY(result == vk::Result::eSuccess);
2925
2926 if (plane_count == 0) {
2927 printf("Cannot find any plane!\n");
2928 fflush(stdout);
2929 exit(1);
2930 }
2931
2932 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2933 VERIFY(plane_props != nullptr);
2934
2935 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2936 VERIFY(result == vk::Result::eSuccess);
2937
2938 // Find a plane compatible with the display
2939 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2940 uint32_t supported_count;
2941 vk::DisplayKHR *supported_displays;
2942
2943 // Disqualify planes that are bound to a different display
2944 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2945 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002946 }
2947
Dave Houlton5fa47912018-02-16 11:02:26 -07002948 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002949 VERIFY(result == vk::Result::eSuccess);
2950
Dave Houlton5fa47912018-02-16 11:02:26 -07002951 if (supported_count == 0) {
2952 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002953 }
2954
Dave Houlton5fa47912018-02-16 11:02:26 -07002955 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2956 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002957
Dave Houlton5fa47912018-02-16 11:02:26 -07002958 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002959 VERIFY(result == vk::Result::eSuccess);
2960
Dave Houlton5fa47912018-02-16 11:02:26 -07002961 for (uint32_t i = 0; i < supported_count; i++) {
2962 if (supported_displays[i] == display) {
2963 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002964 break;
2965 }
2966 }
2967
Dave Houlton5fa47912018-02-16 11:02:26 -07002968 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002969
Dave Houlton5fa47912018-02-16 11:02:26 -07002970 if (found_plane) {
2971 break;
Damien Leone600c3052017-01-31 10:26:07 -07002972 }
2973 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002974
2975 if (!found_plane) {
2976 printf("Cannot find a plane compatible with the display!\n");
2977 fflush(stdout);
2978 exit(1);
2979 }
2980
2981 free(plane_props);
2982
2983 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2984 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2985 // Find a supported alpha mode
2986 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2987 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2988 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2989 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2990 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2991 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2992 };
2993 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2994 if (planeCaps.supportedAlpha & alphaModes[i]) {
2995 alphaMode = alphaModes[i];
2996 break;
2997 }
2998 }
2999
3000 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
3001 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
3002
3003 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
3004 .setDisplayMode(mode_props.displayMode)
3005 .setPlaneIndex(plane_index)
3006 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
3007 .setGlobalAlpha(1.0f)
3008 .setAlphaMode(alphaMode)
3009 .setImageExtent(image_extent);
3010
3011 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
3012}
3013
3014void Demo::run_display() {
3015 while (!quit) {
3016 draw();
3017 curFrame++;
3018
Petr Krausd88e4e52019-01-23 18:45:04 +01003019 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003020 quit = true;
3021 }
3022 }
3023}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003024#endif
3025
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003026#if _WIN32
3027// Include header required for parsing the command line options.
3028#include <shellapi.h>
3029
3030Demo demo;
3031
3032// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06003033LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
3034 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003035 case WM_CLOSE:
3036 PostQuitMessage(validation_error);
3037 break;
3038 case WM_PAINT:
3039 demo.run();
3040 break;
3041 case WM_GETMINMAXINFO: // set window's minimum size
3042 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
3043 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04003044 case WM_ERASEBKGND:
3045 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003046 case WM_SIZE:
3047 // Resize the application to the new window size, except when
3048 // it was minimized. Vulkan doesn't support images or swapchains
3049 // with width=0 and height=0.
3050 if (wParam != SIZE_MINIMIZED) {
3051 demo.width = lParam & 0xffff;
3052 demo.height = (lParam & 0xffff0000) >> 16;
3053 demo.resize();
3054 }
3055 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01003056 case WM_KEYDOWN:
3057 switch (wParam) {
3058 case VK_ESCAPE:
3059 PostQuitMessage(validation_error);
3060 break;
3061 case VK_LEFT:
3062 demo.spin_angle -= demo.spin_increment;
3063 break;
3064 case VK_RIGHT:
3065 demo.spin_angle += demo.spin_increment;
3066 break;
3067 case VK_SPACE:
3068 demo.pause = !demo.pause;
3069 break;
3070 }
3071 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003072 default:
3073 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003074 }
3075
3076 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3077}
3078
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003079int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003080 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003081 MSG msg; // message
3082 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003083 int argc;
3084 char **argv;
3085
Jamie Madillb2ff6502017-03-15 16:17:46 -04003086 // Ensure wParam is initialized.
3087 msg.wParam = 0;
3088
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003089 // Use the CommandLine functions to get the command line arguments.
3090 // Unfortunately, Microsoft outputs
3091 // this information as wide characters for Unicode, and we simply want the
3092 // Ascii version to be compatible
3093 // with the non-Windows side. So, we have to convert the information to
3094 // Ascii character strings.
3095 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003096 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003097 argc = 0;
3098 }
3099
Jeremy Hayes9d304782016-10-09 11:48:12 -06003100 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003101 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003102 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003103 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003104 } else {
3105 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003106 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3107 size_t numConverted = 0;
3108
3109 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003110 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003111 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003112 }
3113 }
3114 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003115 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003116 argv = nullptr;
3117 }
3118
3119 demo.init(argc, argv);
3120
3121 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003122 if (argc > 0 && argv != nullptr) {
3123 for (int iii = 0; iii < argc; iii++) {
3124 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003125 free(argv[iii]);
3126 }
3127 }
3128 free(argv);
3129 }
3130
3131 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003132 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003133 demo.create_window();
3134 demo.init_vk_swapchain();
3135
3136 demo.prepare();
3137
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003138 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003139
3140 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003141 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003142 if (demo.pause) {
3143 const BOOL succ = WaitMessage();
3144
3145 if (!succ) {
3146 const auto &suppress_popups = demo.suppress_popups;
3147 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3148 }
3149 }
3150
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003151 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003152 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003153 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003154 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003155 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003156 /* Translate and dispatch to event queue*/
3157 TranslateMessage(&msg);
3158 DispatchMessage(&msg);
3159 }
3160 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3161 }
3162
3163 demo.cleanup();
3164
3165 return (int)msg.wParam;
3166}
3167
3168#elif __linux__
3169
Jeremy Hayes9d304782016-10-09 11:48:12 -06003170int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003171 Demo demo;
3172
3173 demo.init(argc, argv);
3174
Tony Barbour153cb062016-12-07 13:43:36 -07003175#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003176 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003177#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003178 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003179 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003180#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003181 demo.create_window();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003182#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3183 demo.create_directfb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003184#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003185
3186 demo.init_vk_swapchain();
3187
3188 demo.prepare();
3189
Tony Barbour153cb062016-12-07 13:43:36 -07003190#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003191 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003192#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003193 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003194#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003195 demo.run();
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003196#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3197 demo.run_directfb();
Damien Leone600c3052017-01-31 10:26:07 -07003198#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3199 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003200#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003201
3202 demo.cleanup();
3203
3204 return validation_error;
3205}
3206
Bill Hollings0a0625a2019-07-15 17:39:18 -04003207#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003208
3209// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003210static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003211 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003212 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003213 demo.init_vk_swapchain();
3214 demo.prepare();
3215 demo.spin_angle = 0.4f;
3216}
3217
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003218#else
3219#error "Platform not supported"
3220#endif