blob: ddaa5a5b9c125e0abf850375e2a8b14d2e0c3cc8 [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 */
Jeremy Hayesf56427a2016-09-07 15:55:11 -060020
21#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
Mark Lobodzinskidefadcf2017-10-23 09:23:06 -060037#define VULKAN_HPP_NO_SMART_HANDLE
Jeremy Hayesf56427a2016-09-07 15:55:11 -060038#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060039#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060040#include <vulkan/vulkan.hpp>
41#include <vulkan/vk_sdk_platform.h>
42
43#include "linmath.h"
44
45#ifndef NDEBUG
46#define VERIFY(x) assert(x)
47#else
48#define VERIFY(x) ((void)(x))
49#endif
50
Lenny Komowffe446c2018-11-19 17:08:04 -070051#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060052#ifdef _WIN32
53#define APP_NAME_STR_LEN 80
54#endif
55
56// Allow a maximum of two outstanding presentation operations.
57#define FRAME_LAG 2
58
59#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
60
61#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070062#define ERR_EXIT(err_msg, err_class) \
63 do { \
64 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
65 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060066 } while (0)
67#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070068#define ERR_EXIT(err_msg, err_class) \
69 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080070 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070071 fflush(stdout); \
72 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060073 } while (0)
74#endif
75
Jeremy Hayes9d304782016-10-09 11:48:12 -060076struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060077 vk::Sampler sampler;
78
79 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060080 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070081 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060082
83 vk::MemoryAllocateInfo mem_alloc;
84 vk::DeviceMemory mem;
85 vk::ImageView view;
86
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070087 int32_t tex_width{0};
88 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060089};
90
Jeremy Hayes9d304782016-10-09 11:48:12 -060091static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060092
93static int validation_error = 0;
94
95struct vkcube_vs_uniform {
96 // Must start with MVP
97 float mvp[4][4];
98 float position[12 * 3][4];
99 float color[12 * 3][4];
100};
101
102struct vktexcube_vs_uniform {
103 // Must start with MVP
104 float mvp[4][4];
105 float position[12 * 3][4];
106 float attr[12 * 3][4];
107};
108
109//--------------------------------------------------------------------------------------
110// Mesh and VertexFormat Data
111//--------------------------------------------------------------------------------------
112// clang-format off
113static const float g_vertex_buffer_data[] = {
114 -1.0f,-1.0f,-1.0f, // -X side
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 -1.0f,-1.0f,-1.0f,
120
121 -1.0f,-1.0f,-1.0f, // -Z side
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 1.0f, 1.0f,-1.0f,
127
128 -1.0f,-1.0f,-1.0f, // -Y side
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 -1.0f,-1.0f, 1.0f,
134
135 -1.0f, 1.0f,-1.0f, // +Y side
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 1.0f, 1.0f,-1.0f,
141
142 1.0f, 1.0f,-1.0f, // +X side
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 1.0f, 1.0f,-1.0f,
148
149 -1.0f, 1.0f, 1.0f, // +Z side
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 1.0f, 1.0f, 1.0f,
155};
156
157static const float g_uv_buffer_data[] = {
158 0.0f, 1.0f, // -X side
159 1.0f, 1.0f,
160 1.0f, 0.0f,
161 1.0f, 0.0f,
162 0.0f, 0.0f,
163 0.0f, 1.0f,
164
165 1.0f, 1.0f, // -Z side
166 0.0f, 0.0f,
167 0.0f, 1.0f,
168 1.0f, 1.0f,
169 1.0f, 0.0f,
170 0.0f, 0.0f,
171
172 1.0f, 0.0f, // -Y side
173 1.0f, 1.0f,
174 0.0f, 1.0f,
175 1.0f, 0.0f,
176 0.0f, 1.0f,
177 0.0f, 0.0f,
178
179 1.0f, 0.0f, // +Y side
180 0.0f, 0.0f,
181 0.0f, 1.0f,
182 1.0f, 0.0f,
183 0.0f, 1.0f,
184 1.0f, 1.0f,
185
186 1.0f, 0.0f, // +X side
187 0.0f, 0.0f,
188 0.0f, 1.0f,
189 0.0f, 1.0f,
190 1.0f, 1.0f,
191 1.0f, 0.0f,
192
193 0.0f, 0.0f, // +Z side
194 0.0f, 1.0f,
195 1.0f, 0.0f,
196 0.0f, 1.0f,
197 1.0f, 1.0f,
198 1.0f, 0.0f,
199};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600200// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600201
Jeremy Hayes9d304782016-10-09 11:48:12 -0600202typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600203 vk::Image image;
204 vk::CommandBuffer cmd;
205 vk::CommandBuffer graphics_to_present_cmd;
206 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600207 vk::Buffer uniform_buffer;
208 vk::DeviceMemory uniform_memory;
209 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();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400266#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600267 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600268#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
269 vk::Result create_display_surface();
270 void run_display();
271#endif
272
273#if defined(VK_USE_PLATFORM_WIN32_KHR)
274 HINSTANCE connection; // hInstance - Windows Instance
275 HWND window; // hWnd - window handle
276 POINT minsize; // minimum window size
277 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
278#elif defined(VK_USE_PLATFORM_XLIB_KHR)
279 Window xlib_window;
280 Atom xlib_wm_delete_window;
281 Display *display;
282#elif defined(VK_USE_PLATFORM_XCB_KHR)
283 xcb_window_t xcb_window;
284 xcb_screen_t *screen;
285 xcb_connection_t *connection;
286 xcb_intern_atom_reply_t *atom_wm_delete_window;
287#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
288 wl_display *display;
289 wl_registry *registry;
290 wl_compositor *compositor;
291 wl_surface *window;
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700292 wl_shell *shell;
293 wl_shell_surface *shell_surface;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600294 wl_seat *seat;
295 wl_pointer *pointer;
296 wl_keyboard *keyboard;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400297#elif defined(VK_USE_PLATFORM_METAL_EXT)
298 void *caMetalLayer;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600299#endif
300
301 vk::SurfaceKHR surface;
302 bool prepared;
303 bool use_staging_buffer;
304 bool use_xlib;
305 bool separate_present_queue;
306
307 vk::Instance inst;
308 vk::PhysicalDevice gpu;
309 vk::Device device;
310 vk::Queue graphics_queue;
311 vk::Queue present_queue;
312 uint32_t graphics_queue_family_index;
313 uint32_t present_queue_family_index;
314 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
315 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
316 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
317 vk::PhysicalDeviceProperties gpu_props;
318 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
319 vk::PhysicalDeviceMemoryProperties memory_properties;
320
321 uint32_t enabled_extension_count;
322 uint32_t enabled_layer_count;
323 char const *extension_names[64];
324 char const *enabled_layers[64];
325
326 uint32_t width;
327 uint32_t height;
328 vk::Format format;
329 vk::ColorSpaceKHR color_space;
330
331 uint32_t swapchainImageCount;
332 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600333 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600334 vk::PresentModeKHR presentMode;
335 vk::Fence fences[FRAME_LAG];
336 uint32_t frame_index;
337
338 vk::CommandPool cmd_pool;
339 vk::CommandPool present_cmd_pool;
340
341 struct {
342 vk::Format format;
343 vk::Image image;
344 vk::MemoryAllocateInfo mem_alloc;
345 vk::DeviceMemory mem;
346 vk::ImageView view;
347 } depth;
348
349 static int32_t const texture_count = 1;
350 texture_object textures[texture_count];
351 texture_object staging_texture;
352
353 struct {
354 vk::Buffer buf;
355 vk::MemoryAllocateInfo mem_alloc;
356 vk::DeviceMemory mem;
357 vk::DescriptorBufferInfo buffer_info;
358 } uniform_data;
359
360 vk::CommandBuffer cmd; // Buffer for initialization commands
361 vk::PipelineLayout pipeline_layout;
362 vk::DescriptorSetLayout desc_layout;
363 vk::PipelineCache pipelineCache;
364 vk::RenderPass render_pass;
365 vk::Pipeline pipeline;
366
367 mat4x4 projection_matrix;
368 mat4x4 view_matrix;
369 mat4x4 model_matrix;
370
371 float spin_angle;
372 float spin_increment;
373 bool pause;
374
375 vk::ShaderModule vert_shader_module;
376 vk::ShaderModule frag_shader_module;
377
378 vk::DescriptorPool desc_pool;
379 vk::DescriptorSet desc_set;
380
381 std::unique_ptr<vk::Framebuffer[]> framebuffers;
382
383 bool quit;
384 uint32_t curFrame;
385 uint32_t frameCount;
386 bool validate;
387 bool use_break;
388 bool suppress_popups;
389
390 uint32_t current_buffer;
391 uint32_t queue_family_count;
392};
393
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600394#ifdef _WIN32
395// MS-Windows event handling function:
396LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
397#endif
398
Karl Schultz23cc2182016-11-23 17:15:17 -0700399#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700400static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700401 wl_shell_surface_pong(shell_surface, serial);
402}
403
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700404static 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 -0700405
406static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
407
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700408static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700409
Joey Bzdek15eb0702017-06-07 09:40:36 -0600410static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
411 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700412
Joey Bzdek15eb0702017-06-07 09:40:36 -0600413static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700414
Joey Bzdek15eb0702017-06-07 09:40:36 -0600415static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
416
417static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
418 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600419 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600420 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700421 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600422 }
423}
424
425static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
426
427static const struct wl_pointer_listener pointer_listener = {
428 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
429};
430
431static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
432
433static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
434 struct wl_array *keys) {}
435
436static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
437
438static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
439 uint32_t state) {
440 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
441 Demo *demo = (Demo *)data;
442 switch (key) {
443 case KEY_ESC: // Escape
444 demo->quit = true;
445 break;
446 case KEY_LEFT: // left arrow key
447 demo->spin_angle -= demo->spin_increment;
448 break;
449 case KEY_RIGHT: // right arrow key
450 demo->spin_angle += demo->spin_increment;
451 break;
452 case KEY_SPACE: // space bar
453 demo->pause = !demo->pause;
454 break;
455 }
456}
457
458static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
459 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
460
461static const struct wl_keyboard_listener keyboard_listener = {
462 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
463};
464
465static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
466 // Subscribe to pointer events
467 Demo *demo = (Demo *)data;
468 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
469 demo->pointer = wl_seat_get_pointer(seat);
470 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
471 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
472 wl_pointer_destroy(demo->pointer);
473 demo->pointer = NULL;
474 }
475 // Subscribe to keyboard events
476 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
477 demo->keyboard = wl_seat_get_keyboard(seat);
478 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
479 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
480 wl_keyboard_destroy(demo->keyboard);
481 demo->keyboard = NULL;
482 }
483}
484
485static const wl_seat_listener seat_listener = {
486 seat_handle_capabilities,
487};
488
489static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
490 Demo *demo = (Demo *)data;
491 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700492 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600493 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700494 } else if (strcmp(interface, "wl_shell") == 0) {
495 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
496 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600497 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
498 wl_seat_add_listener(demo->seat, &seat_listener, demo);
499 }
500}
501
502static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
503
504static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700505#endif
506
Joey Bzdekbaf66472017-06-07 09:37:37 -0600507Demo::Demo()
508 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600509#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600510 connection{nullptr},
511 window{nullptr},
512 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600513#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700514
Tony Barbour78d6b572016-11-14 14:46:33 -0700515#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600516 xlib_window{0},
517 xlib_wm_delete_window{0},
518 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700519#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600520 xcb_window{0},
521 screen{nullptr},
522 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700523#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600524 display{nullptr},
525 registry{nullptr},
526 compositor{nullptr},
527 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700528 shell{nullptr},
529 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600530 seat{nullptr},
531 pointer{nullptr},
532 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700533#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600534 prepared{false},
535 use_staging_buffer{false},
536 use_xlib{false},
537 graphics_queue_family_index{0},
538 present_queue_family_index{0},
539 enabled_extension_count{0},
540 enabled_layer_count{0},
541 width{0},
542 height{0},
543 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000544 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600545 frame_index{0},
546 spin_angle{0.0f},
547 spin_increment{0.0f},
548 pause{false},
549 quit{false},
550 curFrame{0},
551 frameCount{0},
552 validate{false},
553 use_break{false},
554 suppress_popups{false},
555 current_buffer{0},
556 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600557#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700558 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600559#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700560 memset(projection_matrix, 0, sizeof(projection_matrix));
561 memset(view_matrix, 0, sizeof(view_matrix));
562 memset(model_matrix, 0, sizeof(model_matrix));
563}
564
565void Demo::build_image_ownership_cmd(uint32_t const &i) {
566 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
567 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
568 VERIFY(result == vk::Result::eSuccess);
569
570 auto const image_ownership_barrier =
571 vk::ImageMemoryBarrier()
572 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600573 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700574 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
575 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setSrcQueueFamilyIndex(graphics_queue_family_index)
577 .setDstQueueFamilyIndex(present_queue_family_index)
578 .setImage(swapchain_image_resources[i].image)
579 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
580
581 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600582 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
583 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700584
585 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
586 VERIFY(result == vk::Result::eSuccess);
587}
588
589vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
590 vk::LayerProperties *layers) {
591 for (uint32_t i = 0; i < check_count; i++) {
592 vk::Bool32 found = VK_FALSE;
593 for (uint32_t j = 0; j < layer_count; j++) {
594 if (!strcmp(check_names[i], layers[j].layerName)) {
595 found = VK_TRUE;
596 break;
597 }
598 }
599 if (!found) {
600 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
601 return 0;
602 }
603 }
604 return VK_TRUE;
605}
606
607void Demo::cleanup() {
608 prepared = false;
609 device.waitIdle();
610
611 // Wait for fences from present operations
612 for (uint32_t i = 0; i < FRAME_LAG; i++) {
613 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
614 device.destroyFence(fences[i], nullptr);
615 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
616 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
617 if (separate_present_queue) {
618 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
619 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600620 }
621
Dave Houlton5fa47912018-02-16 11:02:26 -0700622 for (uint32_t i = 0; i < swapchainImageCount; i++) {
623 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
624 }
625 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600626
Dave Houlton5fa47912018-02-16 11:02:26 -0700627 device.destroyPipeline(pipeline, nullptr);
628 device.destroyPipelineCache(pipelineCache, nullptr);
629 device.destroyRenderPass(render_pass, nullptr);
630 device.destroyPipelineLayout(pipeline_layout, nullptr);
631 device.destroyDescriptorSetLayout(desc_layout, nullptr);
632
633 for (uint32_t i = 0; i < texture_count; i++) {
634 device.destroyImageView(textures[i].view, nullptr);
635 device.destroyImage(textures[i].image, nullptr);
636 device.freeMemory(textures[i].mem, nullptr);
637 device.destroySampler(textures[i].sampler, nullptr);
638 }
639 device.destroySwapchainKHR(swapchain, nullptr);
640
641 device.destroyImageView(depth.view, nullptr);
642 device.destroyImage(depth.image, nullptr);
643 device.freeMemory(depth.mem, nullptr);
644
645 for (uint32_t i = 0; i < swapchainImageCount; i++) {
646 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
647 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
648 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
649 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
650 }
651
652 device.destroyCommandPool(cmd_pool, nullptr);
653
654 if (separate_present_queue) {
655 device.destroyCommandPool(present_cmd_pool, nullptr);
656 }
657 device.waitIdle();
658 device.destroy(nullptr);
659 inst.destroySurfaceKHR(surface, nullptr);
660
661#if defined(VK_USE_PLATFORM_XLIB_KHR)
662 XDestroyWindow(display, xlib_window);
663 XCloseDisplay(display);
664#elif defined(VK_USE_PLATFORM_XCB_KHR)
665 xcb_destroy_window(connection, xcb_window);
666 xcb_disconnect(connection);
667 free(atom_wm_delete_window);
668#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
669 wl_keyboard_destroy(keyboard);
670 wl_pointer_destroy(pointer);
671 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700672 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700673 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700674 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700675 wl_compositor_destroy(compositor);
676 wl_registry_destroy(registry);
677 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700678#endif
679
680 inst.destroy(nullptr);
681}
682
683void Demo::create_device() {
684 float const priorities[1] = {0.0};
685
686 vk::DeviceQueueCreateInfo queues[2];
687 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
688 queues[0].setQueueCount(1);
689 queues[0].setPQueuePriorities(priorities);
690
691 auto deviceInfo = vk::DeviceCreateInfo()
692 .setQueueCreateInfoCount(1)
693 .setPQueueCreateInfos(queues)
694 .setEnabledLayerCount(0)
695 .setPpEnabledLayerNames(nullptr)
696 .setEnabledExtensionCount(enabled_extension_count)
697 .setPpEnabledExtensionNames((const char *const *)extension_names)
698 .setPEnabledFeatures(nullptr);
699
700 if (separate_present_queue) {
701 queues[1].setQueueFamilyIndex(present_queue_family_index);
702 queues[1].setQueueCount(1);
703 queues[1].setPQueuePriorities(priorities);
704 deviceInfo.setQueueCreateInfoCount(2);
705 }
706
707 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
708 VERIFY(result == vk::Result::eSuccess);
709}
710
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600711void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700712 // clean up staging resources
713 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600714 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
715 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700716}
717
718void Demo::draw() {
719 // Ensure no more than FRAME_LAG renderings are outstanding
720 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
721 device.resetFences(1, &fences[frame_index]);
722
723 vk::Result result;
724 do {
725 result =
726 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
727 if (result == vk::Result::eErrorOutOfDateKHR) {
728 // demo->swapchain is out of date (e.g. the window was resized) and
729 // must be recreated:
730 resize();
731 } else if (result == vk::Result::eSuboptimalKHR) {
732 // swapchain is not as optimal as it could be, but the platform's
733 // presentation engine will still present the image correctly.
734 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600735 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
736 inst.destroySurfaceKHR(surface, nullptr);
737 create_surface();
738 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700739 } else {
740 VERIFY(result == vk::Result::eSuccess);
741 }
742 } while (result != vk::Result::eSuccess);
743
744 update_data_buffer();
745
746 // Wait for the image acquired semaphore to be signaled to ensure
747 // that the image won't be rendered to until the presentation
748 // engine has fully released ownership to the application, and it is
749 // okay to render to the image.
750 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
751 auto const submit_info = vk::SubmitInfo()
752 .setPWaitDstStageMask(&pipe_stage_flags)
753 .setWaitSemaphoreCount(1)
754 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
755 .setCommandBufferCount(1)
756 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
757 .setSignalSemaphoreCount(1)
758 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
759
760 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
761 VERIFY(result == vk::Result::eSuccess);
762
763 if (separate_present_queue) {
764 // If we are using separate queues, change image ownership to the
765 // present queue before presenting, waiting for the draw complete
766 // semaphore and signalling the ownership released semaphore when
767 // finished
768 auto const present_submit_info = vk::SubmitInfo()
769 .setPWaitDstStageMask(&pipe_stage_flags)
770 .setWaitSemaphoreCount(1)
771 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
772 .setCommandBufferCount(1)
773 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
774 .setSignalSemaphoreCount(1)
775 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
776
777 result = present_queue.submit(1, &present_submit_info, vk::Fence());
778 VERIFY(result == vk::Result::eSuccess);
779 }
780
781 // If we are using separate queues we have to wait for image ownership,
782 // otherwise wait for draw complete
783 auto const presentInfo = vk::PresentInfoKHR()
784 .setWaitSemaphoreCount(1)
785 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
786 : &draw_complete_semaphores[frame_index])
787 .setSwapchainCount(1)
788 .setPSwapchains(&swapchain)
789 .setPImageIndices(&current_buffer);
790
791 result = present_queue.presentKHR(&presentInfo);
792 frame_index += 1;
793 frame_index %= FRAME_LAG;
794 if (result == vk::Result::eErrorOutOfDateKHR) {
795 // swapchain is out of date (e.g. the window was resized) and
796 // must be recreated:
797 resize();
798 } else if (result == vk::Result::eSuboptimalKHR) {
799 // swapchain is not as optimal as it could be, but the platform's
800 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600801 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
802 inst.destroySurfaceKHR(surface, nullptr);
803 create_surface();
804 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700805 } else {
806 VERIFY(result == vk::Result::eSuccess);
807 }
808}
809
810void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
811 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
812
813 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
814 vk::ClearDepthStencilValue(1.0f, 0u)};
815
816 auto const passInfo = vk::RenderPassBeginInfo()
817 .setRenderPass(render_pass)
818 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
819 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
820 .setClearValueCount(2)
821 .setPClearValues(clearValues);
822
823 auto result = commandBuffer.begin(&commandInfo);
824 VERIFY(result == vk::Result::eSuccess);
825
826 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
827 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
828 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
829 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700830 float viewport_dimension;
831 float viewport_x = 0.0f;
832 float viewport_y = 0.0f;
833 if (width < height) {
834 viewport_dimension = (float)width;
835 viewport_y = (height - width) / 2.0f;
836 } else {
837 viewport_dimension = (float)height;
838 viewport_x = (width - height) / 2.0f;
839 }
840 auto const viewport = vk::Viewport()
841 .setX(viewport_x)
842 .setY(viewport_y)
843 .setWidth((float)viewport_dimension)
844 .setHeight((float)viewport_dimension)
845 .setMinDepth((float)0.0f)
846 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700847 commandBuffer.setViewport(0, 1, &viewport);
848
849 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
850 commandBuffer.setScissor(0, 1, &scissor);
851 commandBuffer.draw(12 * 3, 1, 0, 0);
852 // Note that ending the renderpass changes the image's layout from
853 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
854 commandBuffer.endRenderPass();
855
856 if (separate_present_queue) {
857 // We have to transfer ownership from the graphics queue family to
858 // the
859 // present queue family to be able to present. Note that we don't
860 // have
861 // to transfer from present queue family back to graphics queue
862 // family at
863 // the start of the next frame because we don't care about the
864 // image's
865 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600866 auto const image_ownership_barrier =
867 vk::ImageMemoryBarrier()
868 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600869 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600870 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
871 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
872 .setSrcQueueFamilyIndex(graphics_queue_family_index)
873 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700874 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700875 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600876
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600877 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700878 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600879 }
880
Dave Houlton5fa47912018-02-16 11:02:26 -0700881 result = commandBuffer.end();
882 VERIFY(result == vk::Result::eSuccess);
883}
884
885void Demo::flush_init_cmd() {
886 // TODO: hmm.
887 // This function could get called twice if the texture uses a staging
888 // buffer
889 // In that case the second call should be ignored
890 if (!cmd) {
891 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600892 }
893
Dave Houlton5fa47912018-02-16 11:02:26 -0700894 auto result = cmd.end();
895 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600896
Dave Houlton5fa47912018-02-16 11:02:26 -0700897 auto const fenceInfo = vk::FenceCreateInfo();
898 vk::Fence fence;
899 result = device.createFence(&fenceInfo, nullptr, &fence);
900 VERIFY(result == vk::Result::eSuccess);
901
902 vk::CommandBuffer const commandBuffers[] = {cmd};
903 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
904
905 result = graphics_queue.submit(1, &submitInfo, fence);
906 VERIFY(result == vk::Result::eSuccess);
907
908 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
909 VERIFY(result == vk::Result::eSuccess);
910
911 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
912 device.destroyFence(fence, nullptr);
913
914 cmd = vk::CommandBuffer();
915}
916
917void Demo::init(int argc, char **argv) {
918 vec3 eye = {0.0f, 3.0f, 5.0f};
919 vec3 origin = {0, 0, 0};
920 vec3 up = {0.0f, 1.0f, 0.0};
921
922 presentMode = vk::PresentModeKHR::eFifo;
923 frameCount = UINT32_MAX;
924 use_xlib = false;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600925
Dave Houlton5fa47912018-02-16 11:02:26 -0700926 for (int i = 1; i < argc; i++) {
927 if (strcmp(argv[i], "--use_staging") == 0) {
928 use_staging_buffer = true;
929 continue;
930 }
931 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
932 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
933 i++;
934 continue;
935 }
936 if (strcmp(argv[i], "--break") == 0) {
937 use_break = true;
938 continue;
939 }
940 if (strcmp(argv[i], "--validate") == 0) {
941 validate = true;
942 continue;
943 }
944 if (strcmp(argv[i], "--xlib") == 0) {
945 fprintf(stderr, "--xlib is deprecated and no longer does anything");
946 continue;
947 }
948 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
949 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
950 i++;
951 continue;
952 }
953 if (strcmp(argv[i], "--suppress_popups") == 0) {
954 suppress_popups = true;
955 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600956 }
957
Tony-LunarGd74734f2019-06-04 14:11:43 -0600958 std::stringstream usage;
959 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
960 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
961 << "\t[--present_mode <present mode enum>]\n"
962 << "\t<present_mode_enum>\n"
963 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
964 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
965 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
966 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
967
968#if defined(_WIN32)
969 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
970#else
971 std::cerr << usage.str();
972 std::cerr.flush();
973#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700974 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600975 }
976
Dave Houlton5fa47912018-02-16 11:02:26 -0700977 if (!use_xlib) {
978 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600979 }
980
Dave Houlton5fa47912018-02-16 11:02:26 -0700981 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600982
Dave Houlton5fa47912018-02-16 11:02:26 -0700983 width = 500;
984 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600985
Dave Houlton5fa47912018-02-16 11:02:26 -0700986 spin_angle = 4.0f;
987 spin_increment = 0.2f;
988 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600989
Dave Houlton5fa47912018-02-16 11:02:26 -0700990 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
991 mat4x4_look_at(view_matrix, eye, origin, up);
992 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600993
Dave Houlton5fa47912018-02-16 11:02:26 -0700994 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
995}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600996
Dave Houlton5fa47912018-02-16 11:02:26 -0700997void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600998#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700999 const xcb_setup_t *setup;
1000 xcb_screen_iterator_t iter;
1001 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001002
Dave Houlton5fa47912018-02-16 11:02:26 -07001003 const char *display_envar = getenv("DISPLAY");
1004 if (display_envar == nullptr || display_envar[0] == '\0') {
1005 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1006 fflush(stdout);
1007 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001008 }
1009
Dave Houlton5fa47912018-02-16 11:02:26 -07001010 connection = xcb_connect(nullptr, &scr);
1011 if (xcb_connection_has_error(connection) > 0) {
1012 printf(
1013 "Cannot find a compatible Vulkan installable client driver "
1014 "(ICD).\nExiting ...\n");
1015 fflush(stdout);
1016 exit(1);
1017 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001018
Dave Houlton5fa47912018-02-16 11:02:26 -07001019 setup = xcb_get_setup(connection);
1020 iter = xcb_setup_roots_iterator(setup);
1021 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001022
Dave Houlton5fa47912018-02-16 11:02:26 -07001023 screen = iter.data;
1024#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1025 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001026
Dave Houlton5fa47912018-02-16 11:02:26 -07001027 if (display == nullptr) {
1028 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1029 fflush(stdout);
1030 exit(1);
1031 }
1032
1033 registry = wl_display_get_registry(display);
1034 wl_registry_add_listener(registry, &registry_listener, this);
1035 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001036#endif
1037}
1038
1039void Demo::init_vk() {
1040 uint32_t instance_extension_count = 0;
1041 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001042 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001043 enabled_extension_count = 0;
1044 enabled_layer_count = 0;
1045
Dave Houlton5fa47912018-02-16 11:02:26 -07001046 // Look for validation layers
1047 vk::Bool32 validation_found = VK_FALSE;
1048 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001049 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001050 VERIFY(result == vk::Result::eSuccess);
1051
Dave Houlton5fa47912018-02-16 11:02:26 -07001052 if (instance_layer_count > 0) {
1053 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1054 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001055 VERIFY(result == vk::Result::eSuccess);
1056
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001057 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001058 instance_layer_count, instance_layers.get());
1059 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001060 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1061 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001062 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001063 }
1064
Dave Houlton5fa47912018-02-16 11:02:26 -07001065 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001066 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001067 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1068 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001069 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001070 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001071 }
1072
Dave Houlton5fa47912018-02-16 11:02:26 -07001073 /* Look for instance extensions */
1074 vk::Bool32 surfaceExtFound = VK_FALSE;
1075 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1076 memset(extension_names, 0, sizeof(extension_names));
1077
Mike Schuchardt7510c832018-10-29 13:23:08 -07001078 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1079 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001080 VERIFY(result == vk::Result::eSuccess);
1081
1082 if (instance_extension_count > 0) {
1083 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1084 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1085 VERIFY(result == vk::Result::eSuccess);
1086
1087 for (uint32_t i = 0; i < instance_extension_count; i++) {
1088 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1089 surfaceExtFound = 1;
1090 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1091 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001092#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001093 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1094 platformSurfaceExtFound = 1;
1095 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1096 }
1097#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1098 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1099 platformSurfaceExtFound = 1;
1100 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1101 }
1102#elif defined(VK_USE_PLATFORM_XCB_KHR)
1103 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1104 platformSurfaceExtFound = 1;
1105 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1106 }
Tony Barbour153cb062016-12-07 13:43:36 -07001107#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001108 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1109 platformSurfaceExtFound = 1;
1110 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1111 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001112#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1113 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1114 platformSurfaceExtFound = 1;
1115 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1116 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001117#elif defined(VK_USE_PLATFORM_METAL_EXT)
1118 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001119 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001120 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001121 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001122
Dave Houlton5fa47912018-02-16 11:02:26 -07001123#endif
1124 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001125 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001126 }
1127
1128 if (!surfaceExtFound) {
1129 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1130 " extension.\n\n"
1131 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1132 "Please look at the Getting Started guide for additional information.\n",
1133 "vkCreateInstance Failure");
1134 }
1135
1136 if (!platformSurfaceExtFound) {
1137#if defined(VK_USE_PLATFORM_WIN32_KHR)
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1139 " extension.\n\n"
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143#elif defined(VK_USE_PLATFORM_XCB_KHR)
1144 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1145 " extension.\n\n"
1146 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1147 "Please look at the Getting Started guide for additional information.\n",
1148 "vkCreateInstance Failure");
1149#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1150 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1151 " extension.\n\n"
1152 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1153 "Please look at the Getting Started guide for additional information.\n",
1154 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001155#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001156 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1157 " extension.\n\n"
1158 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1159 "Please look at the Getting Started guide for additional information.\n",
1160 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001161#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001162 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_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");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001167#elif defined(VK_USE_PLATFORM_METAL_EXT)
1168 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001169 " extension.\n\nDo you have a compatible "
1170 "Vulkan installable client driver (ICD) installed?\nPlease "
1171 "look at the Getting Started guide for additional "
1172 "information.\n",
1173 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001174#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001175 }
1176 auto const app = vk::ApplicationInfo()
1177 .setPApplicationName(APP_SHORT_NAME)
1178 .setApplicationVersion(0)
1179 .setPEngineName(APP_SHORT_NAME)
1180 .setEngineVersion(0)
1181 .setApiVersion(VK_API_VERSION_1_0);
1182 auto const inst_info = vk::InstanceCreateInfo()
1183 .setPApplicationInfo(&app)
1184 .setEnabledLayerCount(enabled_layer_count)
1185 .setPpEnabledLayerNames(instance_validation_layers)
1186 .setEnabledExtensionCount(enabled_extension_count)
1187 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001188
Dave Houlton5fa47912018-02-16 11:02:26 -07001189 result = vk::createInstance(&inst_info, nullptr, &inst);
1190 if (result == vk::Result::eErrorIncompatibleDriver) {
1191 ERR_EXIT(
1192 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1193 "Please look at the Getting Started guide for additional information.\n",
1194 "vkCreateInstance Failure");
1195 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1196 ERR_EXIT(
1197 "Cannot find a specified extension library.\n"
1198 "Make sure your layers path is set appropriately.\n",
1199 "vkCreateInstance Failure");
1200 } else if (result != vk::Result::eSuccess) {
1201 ERR_EXIT(
1202 "vkCreateInstance failed.\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");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001206 }
1207
Dave Houlton5fa47912018-02-16 11:02:26 -07001208 /* Make initial call to query gpu_count, then second call for gpu info*/
1209 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001210 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001211 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001212
1213 if (gpu_count > 0) {
1214 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1215 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001216 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001217 /* For cube demo we just grab the first physical device */
1218 gpu = physical_devices[0];
1219 } else {
1220 ERR_EXIT(
1221 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1222 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1223 "Please look at the Getting Started guide for additional information.\n",
1224 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001225 }
1226
Dave Houlton5fa47912018-02-16 11:02:26 -07001227 /* Look for device extensions */
1228 uint32_t device_extension_count = 0;
1229 vk::Bool32 swapchainExtFound = VK_FALSE;
1230 enabled_extension_count = 0;
1231 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001232
Mike Schuchardt7510c832018-10-29 13:23:08 -07001233 result =
1234 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001235 VERIFY(result == vk::Result::eSuccess);
1236
1237 if (device_extension_count > 0) {
1238 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1239 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001240 VERIFY(result == vk::Result::eSuccess);
1241
Dave Houlton5fa47912018-02-16 11:02:26 -07001242 for (uint32_t i = 0; i < device_extension_count; i++) {
1243 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1244 swapchainExtFound = 1;
1245 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001246 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001247 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001248 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001249 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001250
Dave Houlton5fa47912018-02-16 11:02:26 -07001251 if (!swapchainExtFound) {
1252 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1253 " extension.\n\n"
1254 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1255 "Please look at the Getting Started guide for additional information.\n",
1256 "vkCreateInstance Failure");
1257 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001258
Dave Houlton5fa47912018-02-16 11:02:26 -07001259 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001260
Dave Houlton5fa47912018-02-16 11:02:26 -07001261 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001262 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001263 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001264
Dave Houlton5fa47912018-02-16 11:02:26 -07001265 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1266 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001267
Dave Houlton5fa47912018-02-16 11:02:26 -07001268 // Query fine-grained feature support for this device.
1269 // If app has specific feature requirements it should check supported
1270 // features based on this query
1271 vk::PhysicalDeviceFeatures physDevFeatures;
1272 gpu.getFeatures(&physDevFeatures);
1273}
1274
Tony-LunarG6cebf142019-09-11 14:32:23 -06001275void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001276// Create a WSI surface for the window:
1277#if defined(VK_USE_PLATFORM_WIN32_KHR)
1278 {
1279 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1280
1281 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1282 VERIFY(result == vk::Result::eSuccess);
1283 }
1284#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1285 {
1286 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1287
1288 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1289 VERIFY(result == vk::Result::eSuccess);
1290 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001291#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1292 {
1293 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1294
1295 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1296 VERIFY(result == vk::Result::eSuccess);
1297 }
1298#elif defined(VK_USE_PLATFORM_XCB_KHR)
1299 {
1300 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1301
1302 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1303 VERIFY(result == vk::Result::eSuccess);
1304 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001305#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001306 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001307 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001308
Bill Hollings0a0625a2019-07-15 17:39:18 -04001309 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001310 VERIFY(result == vk::Result::eSuccess);
1311 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001312#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1313 {
1314 auto result = create_display_surface();
1315 VERIFY(result == vk::Result::eSuccess);
1316 }
1317#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001318}
1319
1320void Demo::init_vk_swapchain() {
1321 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001322 // Iterate over each queue to learn whether it supports presenting:
1323 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1324 for (uint32_t i = 0; i < queue_family_count; i++) {
1325 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1326 }
1327
1328 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1329 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1330 for (uint32_t i = 0; i < queue_family_count; i++) {
1331 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1332 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1333 graphicsQueueFamilyIndex = i;
1334 }
1335
1336 if (supportsPresent[i] == VK_TRUE) {
1337 graphicsQueueFamilyIndex = i;
1338 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001339 break;
1340 }
1341 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001342 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001343
Dave Houlton5fa47912018-02-16 11:02:26 -07001344 if (presentQueueFamilyIndex == UINT32_MAX) {
1345 // If didn't find a queue that supports both graphics and present,
1346 // then
1347 // find a separate present queue.
1348 for (uint32_t i = 0; i < queue_family_count; ++i) {
1349 if (supportsPresent[i] == VK_TRUE) {
1350 presentQueueFamilyIndex = i;
1351 break;
1352 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001353 }
1354 }
1355
Dave Houlton5fa47912018-02-16 11:02:26 -07001356 // Generate error if could not find both a graphics and a present queue
1357 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1358 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1359 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001360
Dave Houlton5fa47912018-02-16 11:02:26 -07001361 graphics_queue_family_index = graphicsQueueFamilyIndex;
1362 present_queue_family_index = presentQueueFamilyIndex;
1363 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001364
Dave Houlton5fa47912018-02-16 11:02:26 -07001365 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001366
Dave Houlton5fa47912018-02-16 11:02:26 -07001367 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1368 if (!separate_present_queue) {
1369 present_queue = graphics_queue;
1370 } else {
1371 device.getQueue(present_queue_family_index, 0, &present_queue);
1372 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001373
Dave Houlton5fa47912018-02-16 11:02:26 -07001374 // Get the list of VkFormat's that are supported:
1375 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001376 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001377 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001378
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1380 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1381 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001382
Dave Houlton5fa47912018-02-16 11:02:26 -07001383 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1384 // the surface has no preferred format. Otherwise, at least one
1385 // supported format will be returned.
1386 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1387 format = vk::Format::eB8G8R8A8Unorm;
1388 } else {
1389 assert(formatCount >= 1);
1390 format = surfFormats[0].format;
1391 }
1392 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001393
Dave Houlton5fa47912018-02-16 11:02:26 -07001394 quit = false;
1395 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001396
Dave Houlton5fa47912018-02-16 11:02:26 -07001397 // Create semaphores to synchronize acquiring presentable buffers before
1398 // rendering and waiting for drawing to be complete before presenting
1399 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001400
Dave Houlton5fa47912018-02-16 11:02:26 -07001401 // Create fences that we can use to throttle if we get too far
1402 // ahead of the image presents
1403 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1404 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1405 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1406 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001407
Dave Houlton5fa47912018-02-16 11:02:26 -07001408 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1409 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001410
Dave Houlton5fa47912018-02-16 11:02:26 -07001411 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1412 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001413
Dave Houlton5fa47912018-02-16 11:02:26 -07001414 if (separate_present_queue) {
1415 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001416 VERIFY(result == vk::Result::eSuccess);
1417 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001418 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001419 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001420
Dave Houlton5fa47912018-02-16 11:02:26 -07001421 // Get Memory information and properties
1422 gpu.getMemoryProperties(&memory_properties);
1423}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001424
Dave Houlton5fa47912018-02-16 11:02:26 -07001425void Demo::prepare() {
1426 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1427 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1428 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001429
Dave Houlton5fa47912018-02-16 11:02:26 -07001430 auto const cmd = vk::CommandBufferAllocateInfo()
1431 .setCommandPool(cmd_pool)
1432 .setLevel(vk::CommandBufferLevel::ePrimary)
1433 .setCommandBufferCount(1);
1434
1435 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1436 VERIFY(result == vk::Result::eSuccess);
1437
1438 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1439
1440 result = this->cmd.begin(&cmd_buf_info);
1441 VERIFY(result == vk::Result::eSuccess);
1442
1443 prepare_buffers();
1444 prepare_depth();
1445 prepare_textures();
1446 prepare_cube_data_buffers();
1447
1448 prepare_descriptor_layout();
1449 prepare_render_pass();
1450 prepare_pipeline();
1451
1452 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1453 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1454 VERIFY(result == vk::Result::eSuccess);
1455 }
1456
1457 if (separate_present_queue) {
1458 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1459
1460 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1461 VERIFY(result == vk::Result::eSuccess);
1462
1463 auto const present_cmd = vk::CommandBufferAllocateInfo()
1464 .setCommandPool(present_cmd_pool)
1465 .setLevel(vk::CommandBufferLevel::ePrimary)
1466 .setCommandBufferCount(1);
1467
1468 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1469 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1470 VERIFY(result == vk::Result::eSuccess);
1471
1472 build_image_ownership_cmd(i);
1473 }
1474 }
1475
1476 prepare_descriptor_pool();
1477 prepare_descriptor_set();
1478
1479 prepare_framebuffers();
1480
1481 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1482 current_buffer = i;
1483 draw_build_cmd(swapchain_image_resources[i].cmd);
1484 }
1485
1486 /*
1487 * Prepare functions above may generate pipeline commands
1488 * that need to be flushed before beginning the render loop.
1489 */
1490 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001491 if (staging_texture.buffer) {
1492 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001493 }
1494
1495 current_buffer = 0;
1496 prepared = true;
1497}
1498
1499void Demo::prepare_buffers() {
1500 vk::SwapchainKHR oldSwapchain = swapchain;
1501
1502 // Check the surface capabilities and formats
1503 vk::SurfaceCapabilitiesKHR surfCapabilities;
1504 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1505 VERIFY(result == vk::Result::eSuccess);
1506
1507 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001508 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001509 VERIFY(result == vk::Result::eSuccess);
1510
1511 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1512 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1513 VERIFY(result == vk::Result::eSuccess);
1514
1515 vk::Extent2D swapchainExtent;
1516 // width and height are either both -1, or both not -1.
1517 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1518 // If the surface size is undefined, the size is set to
1519 // the size of the images requested.
1520 swapchainExtent.width = width;
1521 swapchainExtent.height = height;
1522 } else {
1523 // If the surface size is defined, the swap chain size must match
1524 swapchainExtent = surfCapabilities.currentExtent;
1525 width = surfCapabilities.currentExtent.width;
1526 height = surfCapabilities.currentExtent.height;
1527 }
1528
1529 // The FIFO present mode is guaranteed by the spec to be supported
1530 // and to have no tearing. It's a great default present mode to use.
1531 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1532
1533 // There are times when you may wish to use another present mode. The
1534 // following code shows how to select them, and the comments provide some
1535 // reasons you may wish to use them.
1536 //
1537 // It should be noted that Vulkan 1.0 doesn't provide a method for
1538 // synchronizing rendering with the presentation engine's display. There
1539 // is a method provided for throttling rendering with the display, but
1540 // there are some presentation engines for which this method will not work.
1541 // If an application doesn't throttle its rendering, and if it renders much
1542 // faster than the refresh rate of the display, this can waste power on
1543 // mobile devices. That is because power is being spent rendering images
1544 // that may never be seen.
1545
1546 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1547 // about
1548 // tearing, or have some way of synchronizing their rendering with the
1549 // display.
1550 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1551 // generally render a new presentable image every refresh cycle, but are
1552 // occasionally early. In this case, the application wants the new
1553 // image
1554 // to be displayed instead of the previously-queued-for-presentation
1555 // image
1556 // that has not yet been displayed.
1557 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1558 // render a new presentable image every refresh cycle, but are
1559 // occasionally
1560 // late. In this case (perhaps because of stuttering/latency concerns),
1561 // the application wants the late image to be immediately displayed,
1562 // even
1563 // though that may mean some tearing.
1564
1565 if (presentMode != swapchainPresentMode) {
1566 for (size_t i = 0; i < presentModeCount; ++i) {
1567 if (presentModes[i] == presentMode) {
1568 swapchainPresentMode = presentMode;
1569 break;
1570 }
1571 }
1572 }
1573
1574 if (swapchainPresentMode != presentMode) {
1575 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1576 }
1577
1578 // Determine the number of VkImages to use in the swap chain.
1579 // Application desires to acquire 3 images at a time for triple
1580 // buffering
1581 uint32_t desiredNumOfSwapchainImages = 3;
1582 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1583 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1584 }
1585
1586 // If maxImageCount is 0, we can ask for as many images as we want,
1587 // otherwise
1588 // we're limited to maxImageCount
1589 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1590 // Application must settle for fewer images than desired:
1591 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1592 }
1593
1594 vk::SurfaceTransformFlagBitsKHR preTransform;
1595 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1596 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1597 } else {
1598 preTransform = surfCapabilities.currentTransform;
1599 }
1600
1601 // Find a supported composite alpha mode - one of these is guaranteed to be set
1602 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1603 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1604 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1605 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1606 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1607 vk::CompositeAlphaFlagBitsKHR::eInherit,
1608 };
1609 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1610 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1611 compositeAlpha = compositeAlphaFlags[i];
1612 break;
1613 }
1614 }
1615
1616 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1617 .setSurface(surface)
1618 .setMinImageCount(desiredNumOfSwapchainImages)
1619 .setImageFormat(format)
1620 .setImageColorSpace(color_space)
1621 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1622 .setImageArrayLayers(1)
1623 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1624 .setImageSharingMode(vk::SharingMode::eExclusive)
1625 .setQueueFamilyIndexCount(0)
1626 .setPQueueFamilyIndices(nullptr)
1627 .setPreTransform(preTransform)
1628 .setCompositeAlpha(compositeAlpha)
1629 .setPresentMode(swapchainPresentMode)
1630 .setClipped(true)
1631 .setOldSwapchain(oldSwapchain);
1632
1633 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1634 VERIFY(result == vk::Result::eSuccess);
1635
1636 // If we just re-created an existing swapchain, we should destroy the
1637 // old
1638 // swapchain at this point.
1639 // Note: destroying the swapchain also cleans up all its associated
1640 // presentable images once the platform is done with them.
1641 if (oldSwapchain) {
1642 device.destroySwapchainKHR(oldSwapchain, nullptr);
1643 }
1644
Mike Schuchardt7510c832018-10-29 13:23:08 -07001645 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001646 VERIFY(result == vk::Result::eSuccess);
1647
1648 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1649 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1650 VERIFY(result == vk::Result::eSuccess);
1651
1652 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1653
1654 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1655 auto color_image_view = vk::ImageViewCreateInfo()
1656 .setViewType(vk::ImageViewType::e2D)
1657 .setFormat(format)
1658 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1659
1660 swapchain_image_resources[i].image = swapchainImages[i];
1661
1662 color_image_view.image = swapchain_image_resources[i].image;
1663
1664 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1665 VERIFY(result == vk::Result::eSuccess);
1666 }
1667}
1668
1669void Demo::prepare_cube_data_buffers() {
1670 mat4x4 VP;
1671 mat4x4_mul(VP, projection_matrix, view_matrix);
1672
1673 mat4x4 MVP;
1674 mat4x4_mul(MVP, VP, model_matrix);
1675
1676 vktexcube_vs_uniform data;
1677 memcpy(data.mvp, MVP, sizeof(MVP));
1678 // dumpMatrix("MVP", MVP)
1679
1680 for (int32_t i = 0; i < 12 * 3; i++) {
1681 data.position[i][0] = g_vertex_buffer_data[i * 3];
1682 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1683 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1684 data.position[i][3] = 1.0f;
1685 data.attr[i][0] = g_uv_buffer_data[2 * i];
1686 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1687 data.attr[i][2] = 0;
1688 data.attr[i][3] = 0;
1689 }
1690
1691 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1692
1693 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1694 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001695 VERIFY(result == vk::Result::eSuccess);
1696
1697 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001698 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001699
Dave Houlton5fa47912018-02-16 11:02:26 -07001700 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001701
Dave Houlton5fa47912018-02-16 11:02:26 -07001702 bool const pass = memory_type_from_properties(
1703 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1704 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001705 VERIFY(pass);
1706
Dave Houlton5fa47912018-02-16 11:02:26 -07001707 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001708 VERIFY(result == vk::Result::eSuccess);
1709
Dave Houlton5fa47912018-02-16 11:02:26 -07001710 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1711 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001712
Dave Houlton5fa47912018-02-16 11:02:26 -07001713 memcpy(pData.value, &data, sizeof data);
1714
1715 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1716
1717 result =
1718 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001719 VERIFY(result == vk::Result::eSuccess);
1720 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001721}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001722
Dave Houlton5fa47912018-02-16 11:02:26 -07001723void Demo::prepare_depth() {
1724 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001725
Dave Houlton5fa47912018-02-16 11:02:26 -07001726 auto const image = vk::ImageCreateInfo()
1727 .setImageType(vk::ImageType::e2D)
1728 .setFormat(depth.format)
1729 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1730 .setMipLevels(1)
1731 .setArrayLayers(1)
1732 .setSamples(vk::SampleCountFlagBits::e1)
1733 .setTiling(vk::ImageTiling::eOptimal)
1734 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1735 .setSharingMode(vk::SharingMode::eExclusive)
1736 .setQueueFamilyIndexCount(0)
1737 .setPQueueFamilyIndices(nullptr)
1738 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001739
Dave Houlton5fa47912018-02-16 11:02:26 -07001740 auto result = device.createImage(&image, nullptr, &depth.image);
1741 VERIFY(result == vk::Result::eSuccess);
1742
1743 vk::MemoryRequirements mem_reqs;
1744 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1745
1746 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1747 depth.mem_alloc.setMemoryTypeIndex(0);
1748
1749 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1750 &depth.mem_alloc.memoryTypeIndex);
1751 VERIFY(pass);
1752
1753 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1754 VERIFY(result == vk::Result::eSuccess);
1755
1756 result = device.bindImageMemory(depth.image, depth.mem, 0);
1757 VERIFY(result == vk::Result::eSuccess);
1758
1759 auto const view = vk::ImageViewCreateInfo()
1760 .setImage(depth.image)
1761 .setViewType(vk::ImageViewType::e2D)
1762 .setFormat(depth.format)
1763 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1764 result = device.createImageView(&view, nullptr, &depth.view);
1765 VERIFY(result == vk::Result::eSuccess);
1766}
1767
1768void Demo::prepare_descriptor_layout() {
1769 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1770 .setBinding(0)
1771 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1772 .setDescriptorCount(1)
1773 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1774 .setPImmutableSamplers(nullptr),
1775 vk::DescriptorSetLayoutBinding()
1776 .setBinding(1)
1777 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1778 .setDescriptorCount(texture_count)
1779 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1780 .setPImmutableSamplers(nullptr)};
1781
1782 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1783
1784 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1785 VERIFY(result == vk::Result::eSuccess);
1786
1787 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1788
1789 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1790 VERIFY(result == vk::Result::eSuccess);
1791}
1792
1793void Demo::prepare_descriptor_pool() {
1794 vk::DescriptorPoolSize const poolSizes[2] = {
1795 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1796 vk::DescriptorPoolSize()
1797 .setType(vk::DescriptorType::eCombinedImageSampler)
1798 .setDescriptorCount(swapchainImageCount * texture_count)};
1799
1800 auto const descriptor_pool =
1801 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1802
1803 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1804 VERIFY(result == vk::Result::eSuccess);
1805}
1806
1807void Demo::prepare_descriptor_set() {
1808 auto const alloc_info =
1809 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1810
1811 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1812
1813 vk::DescriptorImageInfo tex_descs[texture_count];
1814 for (uint32_t i = 0; i < texture_count; i++) {
1815 tex_descs[i].setSampler(textures[i].sampler);
1816 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001817 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001818 }
1819
1820 vk::WriteDescriptorSet writes[2];
1821
1822 writes[0].setDescriptorCount(1);
1823 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1824 writes[0].setPBufferInfo(&buffer_info);
1825
1826 writes[1].setDstBinding(1);
1827 writes[1].setDescriptorCount(texture_count);
1828 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1829 writes[1].setPImageInfo(tex_descs);
1830
1831 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1832 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001833 VERIFY(result == vk::Result::eSuccess);
1834
Dave Houlton5fa47912018-02-16 11:02:26 -07001835 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1836 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1837 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1838 device.updateDescriptorSets(2, writes, 0, nullptr);
1839 }
1840}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001841
Dave Houlton5fa47912018-02-16 11:02:26 -07001842void Demo::prepare_framebuffers() {
1843 vk::ImageView attachments[2];
1844 attachments[1] = depth.view;
1845
1846 auto const fb_info = vk::FramebufferCreateInfo()
1847 .setRenderPass(render_pass)
1848 .setAttachmentCount(2)
1849 .setPAttachments(attachments)
1850 .setWidth((uint32_t)width)
1851 .setHeight((uint32_t)height)
1852 .setLayers(1);
1853
1854 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1855 attachments[0] = swapchain_image_resources[i].view;
1856 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001857 VERIFY(result == vk::Result::eSuccess);
1858 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001859}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001860
Dave Houlton5fa47912018-02-16 11:02:26 -07001861vk::ShaderModule Demo::prepare_fs() {
1862 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001863#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001864 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001865
Dave Houlton5fa47912018-02-16 11:02:26 -07001866 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001867
Dave Houlton5fa47912018-02-16 11:02:26 -07001868 return frag_shader_module;
1869}
1870
1871void Demo::prepare_pipeline() {
1872 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1873 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1874 VERIFY(result == vk::Result::eSuccess);
1875
1876 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1877 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1878 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1879
1880 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1881
1882 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1883
1884 // TODO: Where are pViewports and pScissors set?
1885 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1886
1887 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1888 .setDepthClampEnable(VK_FALSE)
1889 .setRasterizerDiscardEnable(VK_FALSE)
1890 .setPolygonMode(vk::PolygonMode::eFill)
1891 .setCullMode(vk::CullModeFlagBits::eBack)
1892 .setFrontFace(vk::FrontFace::eCounterClockwise)
1893 .setDepthBiasEnable(VK_FALSE)
1894 .setLineWidth(1.0f);
1895
1896 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1897
1898 auto const stencilOp =
1899 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1900
1901 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1902 .setDepthTestEnable(VK_TRUE)
1903 .setDepthWriteEnable(VK_TRUE)
1904 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1905 .setDepthBoundsTestEnable(VK_FALSE)
1906 .setStencilTestEnable(VK_FALSE)
1907 .setFront(stencilOp)
1908 .setBack(stencilOp);
1909
1910 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1911 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1912 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1913
1914 auto const colorBlendInfo =
1915 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1916
1917 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1918
1919 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1920
1921 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1922 .setStageCount(2)
1923 .setPStages(shaderStageInfo)
1924 .setPVertexInputState(&vertexInputInfo)
1925 .setPInputAssemblyState(&inputAssemblyInfo)
1926 .setPViewportState(&viewportInfo)
1927 .setPRasterizationState(&rasterizationInfo)
1928 .setPMultisampleState(&multisampleInfo)
1929 .setPDepthStencilState(&depthStencilInfo)
1930 .setPColorBlendState(&colorBlendInfo)
1931 .setPDynamicState(&dynamicStateInfo)
1932 .setLayout(pipeline_layout)
1933 .setRenderPass(render_pass);
1934
1935 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1936 VERIFY(result == vk::Result::eSuccess);
1937
1938 device.destroyShaderModule(frag_shader_module, nullptr);
1939 device.destroyShaderModule(vert_shader_module, nullptr);
1940}
1941
1942void Demo::prepare_render_pass() {
1943 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1944 // because at the start of the renderpass, we don't care about their contents.
1945 // At the start of the subpass, the color attachment's layout will be transitioned
1946 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1947 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1948 // the renderpass, the color attachment's layout will be transitioned to
1949 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1950 // the renderpass, no barriers are necessary.
1951 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1952 .setFormat(format)
1953 .setSamples(vk::SampleCountFlagBits::e1)
1954 .setLoadOp(vk::AttachmentLoadOp::eClear)
1955 .setStoreOp(vk::AttachmentStoreOp::eStore)
1956 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1957 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1958 .setInitialLayout(vk::ImageLayout::eUndefined)
1959 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1960 vk::AttachmentDescription()
1961 .setFormat(depth.format)
1962 .setSamples(vk::SampleCountFlagBits::e1)
1963 .setLoadOp(vk::AttachmentLoadOp::eClear)
1964 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1965 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1966 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1967 .setInitialLayout(vk::ImageLayout::eUndefined)
1968 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1969
1970 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1971
1972 auto const depth_reference =
1973 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1974
1975 auto const subpass = vk::SubpassDescription()
1976 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1977 .setInputAttachmentCount(0)
1978 .setPInputAttachments(nullptr)
1979 .setColorAttachmentCount(1)
1980 .setPColorAttachments(&color_reference)
1981 .setPResolveAttachments(nullptr)
1982 .setPDepthStencilAttachment(&depth_reference)
1983 .setPreserveAttachmentCount(0)
1984 .setPPreserveAttachments(nullptr);
1985
Tony-LunarG495604b2019-06-13 15:32:05 -06001986 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
1987 vk::SubpassDependency const dependencies[2] = {
1988 vk::SubpassDependency() // Depth buffer is shared between swapchain images
1989 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1990 .setDstSubpass(0)
1991 .setSrcStageMask(stages)
1992 .setDstStageMask(stages)
1993 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1994 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1995 .setDependencyFlags(vk::DependencyFlags()),
1996 vk::SubpassDependency() // Image layout transition
1997 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1998 .setDstSubpass(0)
1999 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2000 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2001 .setSrcAccessMask(vk::AccessFlagBits())
2002 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2003 .setDependencyFlags(vk::DependencyFlags()),
2004 };
2005
Dave Houlton5fa47912018-02-16 11:02:26 -07002006 auto const rp_info = vk::RenderPassCreateInfo()
2007 .setAttachmentCount(2)
2008 .setPAttachments(attachments)
2009 .setSubpassCount(1)
2010 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002011 .setDependencyCount(2)
2012 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002013
2014 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2015 VERIFY(result == vk::Result::eSuccess);
2016}
2017
2018vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2019 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2020
2021 vk::ShaderModule module;
2022 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2023 VERIFY(result == vk::Result::eSuccess);
2024
2025 return module;
2026}
2027
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002028void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2029 int32_t tex_width;
2030 int32_t tex_height;
2031
2032 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2033 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2034 }
2035
2036 tex_obj->tex_width = tex_width;
2037 tex_obj->tex_height = tex_height;
2038
2039 auto const buffer_create_info = vk::BufferCreateInfo()
2040 .setSize(tex_width * tex_height * 4)
2041 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2042 .setSharingMode(vk::SharingMode::eExclusive)
2043 .setQueueFamilyIndexCount(0)
2044 .setPQueueFamilyIndices(nullptr);
2045
2046 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2047 VERIFY(result == vk::Result::eSuccess);
2048
2049 vk::MemoryRequirements mem_reqs;
2050 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2051
2052 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2053 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2054
2055 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2056 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2057 VERIFY(pass == true);
2058
2059 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2060 VERIFY(result == vk::Result::eSuccess);
2061
2062 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2063 VERIFY(result == vk::Result::eSuccess);
2064
2065 vk::SubresourceLayout layout;
2066 memset(&layout, 0, sizeof(layout));
2067 layout.rowPitch = tex_width * 4;
2068 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2069 VERIFY(data.result == vk::Result::eSuccess);
2070
2071 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2072 fprintf(stderr, "Error loading texture: %s\n", filename);
2073 }
2074
2075 device.unmapMemory(tex_obj->mem);
2076}
2077
Dave Houlton5fa47912018-02-16 11:02:26 -07002078void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2079 vk::MemoryPropertyFlags required_props) {
2080 int32_t tex_width;
2081 int32_t tex_height;
2082 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2083 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002084 }
2085
Dave Houlton5fa47912018-02-16 11:02:26 -07002086 tex_obj->tex_width = tex_width;
2087 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002088
Dave Houlton5fa47912018-02-16 11:02:26 -07002089 auto const image_create_info = vk::ImageCreateInfo()
2090 .setImageType(vk::ImageType::e2D)
2091 .setFormat(vk::Format::eR8G8B8A8Unorm)
2092 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2093 .setMipLevels(1)
2094 .setArrayLayers(1)
2095 .setSamples(vk::SampleCountFlagBits::e1)
2096 .setTiling(tiling)
2097 .setUsage(usage)
2098 .setSharingMode(vk::SharingMode::eExclusive)
2099 .setQueueFamilyIndexCount(0)
2100 .setPQueueFamilyIndices(nullptr)
2101 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002102
Dave Houlton5fa47912018-02-16 11:02:26 -07002103 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2104 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002105
Dave Houlton5fa47912018-02-16 11:02:26 -07002106 vk::MemoryRequirements mem_reqs;
2107 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002108
Dave Houlton5fa47912018-02-16 11:02:26 -07002109 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2110 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002111
Dave Houlton5fa47912018-02-16 11:02:26 -07002112 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2113 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002114
Dave Houlton5fa47912018-02-16 11:02:26 -07002115 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2116 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002117
Dave Houlton5fa47912018-02-16 11:02:26 -07002118 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2119 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002120
Dave Houlton5fa47912018-02-16 11:02:26 -07002121 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2122 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2123 vk::SubresourceLayout layout;
2124 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002125
Dave Houlton5fa47912018-02-16 11:02:26 -07002126 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002127 VERIFY(data.result == vk::Result::eSuccess);
2128
Dave Houlton5fa47912018-02-16 11:02:26 -07002129 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2130 fprintf(stderr, "Error loading texture: %s\n", filename);
2131 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002132
Dave Houlton5fa47912018-02-16 11:02:26 -07002133 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002134 }
2135
Dave Houlton5fa47912018-02-16 11:02:26 -07002136 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2137}
2138
2139void Demo::prepare_textures() {
2140 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2141 vk::FormatProperties props;
2142 gpu.getFormatProperties(tex_format, &props);
2143
2144 for (uint32_t i = 0; i < texture_count; i++) {
2145 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2146 /* Device can texture using linear textures */
2147 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2148 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2149 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2150 // shader to run until layout transition completes
2151 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2152 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2153 vk::PipelineStageFlagBits::eFragmentShader);
2154 staging_texture.image = vk::Image();
2155 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2156 /* Must use staging buffer to copy linear texture to optimized */
2157
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002158 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002159
2160 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2161 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2162 vk::MemoryPropertyFlagBits::eDeviceLocal);
2163
Dave Houlton5fa47912018-02-16 11:02:26 -07002164 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2165 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2166 vk::PipelineStageFlagBits::eTransfer);
2167
2168 auto const subresource = vk::ImageSubresourceLayers()
2169 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2170 .setMipLevel(0)
2171 .setBaseArrayLayer(0)
2172 .setLayerCount(1);
2173
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002174 auto const copy_region =
2175 vk::BufferImageCopy()
2176 .setBufferOffset(0)
2177 .setBufferRowLength(staging_texture.tex_width)
2178 .setBufferImageHeight(staging_texture.tex_height)
2179 .setImageSubresource(subresource)
2180 .setImageOffset({0, 0, 0})
2181 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002182
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002183 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002184
2185 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2186 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2187 vk::PipelineStageFlagBits::eFragmentShader);
2188 } else {
2189 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002190 }
2191
Dave Houlton5fa47912018-02-16 11:02:26 -07002192 auto const samplerInfo = vk::SamplerCreateInfo()
2193 .setMagFilter(vk::Filter::eNearest)
2194 .setMinFilter(vk::Filter::eNearest)
2195 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2196 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2197 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2198 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2199 .setMipLodBias(0.0f)
2200 .setAnisotropyEnable(VK_FALSE)
2201 .setMaxAnisotropy(1)
2202 .setCompareEnable(VK_FALSE)
2203 .setCompareOp(vk::CompareOp::eNever)
2204 .setMinLod(0.0f)
2205 .setMaxLod(0.0f)
2206 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2207 .setUnnormalizedCoordinates(VK_FALSE);
2208
2209 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2210 VERIFY(result == vk::Result::eSuccess);
2211
2212 auto const viewInfo = vk::ImageViewCreateInfo()
2213 .setImage(textures[i].image)
2214 .setViewType(vk::ImageViewType::e2D)
2215 .setFormat(tex_format)
2216 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2217
2218 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2219 VERIFY(result == vk::Result::eSuccess);
2220 }
2221}
2222
2223vk::ShaderModule Demo::prepare_vs() {
2224 const uint32_t vertShaderCode[] = {
2225#include "cube.vert.inc"
2226 };
2227
2228 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2229
2230 return vert_shader_module;
2231}
2232
2233void Demo::resize() {
2234 uint32_t i;
2235
2236 // Don't react to resize until after first initialization.
2237 if (!prepared) {
2238 return;
2239 }
2240
2241 // In order to properly resize the window, we must re-create the
2242 // swapchain
2243 // AND redo the command buffers, etc.
2244 //
2245 // First, perform part of the cleanup() function:
2246 prepared = false;
2247 auto result = device.waitIdle();
2248 VERIFY(result == vk::Result::eSuccess);
2249
2250 for (i = 0; i < swapchainImageCount; i++) {
2251 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2252 }
2253
2254 device.destroyDescriptorPool(desc_pool, nullptr);
2255
2256 device.destroyPipeline(pipeline, nullptr);
2257 device.destroyPipelineCache(pipelineCache, nullptr);
2258 device.destroyRenderPass(render_pass, nullptr);
2259 device.destroyPipelineLayout(pipeline_layout, nullptr);
2260 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2261
2262 for (i = 0; i < texture_count; i++) {
2263 device.destroyImageView(textures[i].view, nullptr);
2264 device.destroyImage(textures[i].image, nullptr);
2265 device.freeMemory(textures[i].mem, nullptr);
2266 device.destroySampler(textures[i].sampler, nullptr);
2267 }
2268
2269 device.destroyImageView(depth.view, nullptr);
2270 device.destroyImage(depth.image, nullptr);
2271 device.freeMemory(depth.mem, nullptr);
2272
2273 for (i = 0; i < swapchainImageCount; i++) {
2274 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2275 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2276 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2277 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2278 }
2279
2280 device.destroyCommandPool(cmd_pool, nullptr);
2281 if (separate_present_queue) {
2282 device.destroyCommandPool(present_cmd_pool, nullptr);
2283 }
2284
2285 // Second, re-perform the prepare() function, which will re-create the
2286 // swapchain.
2287 prepare();
2288}
2289
2290void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2291 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2292 assert(cmd);
2293
2294 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2295 vk::AccessFlags flags;
2296
2297 switch (layout) {
2298 case vk::ImageLayout::eTransferDstOptimal:
2299 // Make sure anything that was copying from this image has
2300 // completed
2301 flags = vk::AccessFlagBits::eTransferWrite;
2302 break;
2303 case vk::ImageLayout::eColorAttachmentOptimal:
2304 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2305 break;
2306 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2307 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2308 break;
2309 case vk::ImageLayout::eShaderReadOnlyOptimal:
2310 // Make sure any Copy or CPU writes to image are flushed
2311 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2312 break;
2313 case vk::ImageLayout::eTransferSrcOptimal:
2314 flags = vk::AccessFlagBits::eTransferRead;
2315 break;
2316 case vk::ImageLayout::ePresentSrcKHR:
2317 flags = vk::AccessFlagBits::eMemoryRead;
2318 break;
2319 default:
2320 break;
2321 }
2322
2323 return flags;
2324 };
2325
2326 auto const barrier = vk::ImageMemoryBarrier()
2327 .setSrcAccessMask(srcAccessMask)
2328 .setDstAccessMask(DstAccessMask(newLayout))
2329 .setOldLayout(oldLayout)
2330 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002331 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2332 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002333 .setImage(image)
2334 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2335
2336 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2337}
2338
2339void Demo::update_data_buffer() {
2340 mat4x4 VP;
2341 mat4x4_mul(VP, projection_matrix, view_matrix);
2342
2343 // Rotate around the Y axis
2344 mat4x4 Model;
2345 mat4x4_dup(Model, model_matrix);
2346 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2347
2348 mat4x4 MVP;
2349 mat4x4_mul(MVP, VP, model_matrix);
2350
2351 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2352 VERIFY(data.result == vk::Result::eSuccess);
2353
2354 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2355
2356 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2357}
2358
Karl Schultzb7940402018-05-29 13:09:22 -06002359/* Convert ppm image data from header file into RGBA texture image */
2360#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002361bool 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 -06002362 (void)filename;
2363 char *cPtr;
2364 cPtr = (char *)lunarg_ppm;
2365 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002366 return false;
2367 }
Karl Schultzb7940402018-05-29 13:09:22 -06002368 while (strncmp(cPtr++, "\n", 1))
2369 ;
2370 sscanf(cPtr, "%u %u", width, height);
2371 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002372 return true;
2373 }
Karl Schultzb7940402018-05-29 13:09:22 -06002374 while (strncmp(cPtr++, "\n", 1))
2375 ;
2376 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002377 return false;
2378 }
Karl Schultzb7940402018-05-29 13:09:22 -06002379 while (strncmp(cPtr++, "\n", 1))
2380 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002381 for (int y = 0; y < *height; y++) {
2382 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002383 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002384 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002385 rowPtr[3] = 255; /* Alpha of 1 */
2386 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002387 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002388 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002389 rgba_data += layout->rowPitch;
2390 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002391 return true;
2392}
2393
2394bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2395 // Search memtypes to find first index with those properties
2396 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2397 if ((typeBits & 1) == 1) {
2398 // Type is available, does it match user properties?
2399 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2400 *typeIndex = i;
2401 return true;
2402 }
2403 }
2404 typeBits >>= 1;
2405 }
2406
2407 // No memory types matched, return failure
2408 return false;
2409}
2410
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002411#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002412void Demo::run() {
2413 if (!prepared) {
2414 return;
2415 }
2416
2417 draw();
2418 curFrame++;
2419
Petr Krausd88e4e52019-01-23 18:45:04 +01002420 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002421 PostQuitMessage(validation_error);
2422 }
2423}
2424
2425void Demo::create_window() {
2426 WNDCLASSEX win_class;
2427
2428 // Initialize the window class structure:
2429 win_class.cbSize = sizeof(WNDCLASSEX);
2430 win_class.style = CS_HREDRAW | CS_VREDRAW;
2431 win_class.lpfnWndProc = WndProc;
2432 win_class.cbClsExtra = 0;
2433 win_class.cbWndExtra = 0;
2434 win_class.hInstance = connection; // hInstance
2435 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2436 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2437 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2438 win_class.lpszMenuName = nullptr;
2439 win_class.lpszClassName = name;
2440 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2441
2442 // Register window class:
2443 if (!RegisterClassEx(&win_class)) {
2444 // It didn't work, so try to give a useful error:
2445 printf("Unexpected error trying to start the application!\n");
2446 fflush(stdout);
2447 exit(1);
2448 }
2449
2450 // Create window with the registered class:
2451 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2452 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2453 window = CreateWindowEx(0,
2454 name, // class name
2455 name, // app name
2456 WS_OVERLAPPEDWINDOW | // window style
2457 WS_VISIBLE | WS_SYSMENU,
2458 100, 100, // x/y coords
2459 wr.right - wr.left, // width
2460 wr.bottom - wr.top, // height
2461 nullptr, // handle to parent
2462 nullptr, // handle to menu
2463 connection, // hInstance
2464 nullptr); // no extra parameters
2465
2466 if (!window) {
2467 // It didn't work, so try to give a useful error:
2468 printf("Cannot create a window in which to draw!\n");
2469 fflush(stdout);
2470 exit(1);
2471 }
2472
2473 // Window client area size must be at least 1 pixel high, to prevent
2474 // crash.
2475 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2476 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2477}
2478#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2479
2480void Demo::create_xlib_window() {
2481 const char *display_envar = getenv("DISPLAY");
2482 if (display_envar == nullptr || display_envar[0] == '\0') {
2483 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2484 fflush(stdout);
2485 exit(1);
2486 }
2487
2488 XInitThreads();
2489 display = XOpenDisplay(nullptr);
2490 long visualMask = VisualScreenMask;
2491 int numberOfVisuals;
2492 XVisualInfo vInfoTemplate = {};
2493 vInfoTemplate.screen = DefaultScreen(display);
2494 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2495
2496 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2497
2498 XSetWindowAttributes windowAttributes = {};
2499 windowAttributes.colormap = colormap;
2500 windowAttributes.background_pixel = 0xFFFFFFFF;
2501 windowAttributes.border_pixel = 0;
2502 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2503
2504 xlib_window =
2505 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2506 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2507
2508 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2509 XMapWindow(display, xlib_window);
2510 XFlush(display);
2511 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2512}
2513
2514void Demo::handle_xlib_event(const XEvent *event) {
2515 switch (event->type) {
2516 case ClientMessage:
2517 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2518 quit = true;
2519 }
2520 break;
2521 case KeyPress:
2522 switch (event->xkey.keycode) {
2523 case 0x9: // Escape
2524 quit = true;
2525 break;
2526 case 0x71: // left arrow key
2527 spin_angle -= spin_increment;
2528 break;
2529 case 0x72: // right arrow key
2530 spin_angle += spin_increment;
2531 break;
2532 case 0x41: // space bar
2533 pause = !pause;
2534 break;
2535 }
2536 break;
2537 case ConfigureNotify:
2538 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2539 width = event->xconfigure.width;
2540 height = event->xconfigure.height;
2541 resize();
2542 }
2543 break;
2544 default:
2545 break;
2546 }
2547}
2548
2549void Demo::run_xlib() {
2550 while (!quit) {
2551 XEvent event;
2552
2553 if (pause) {
2554 XNextEvent(display, &event);
2555 handle_xlib_event(&event);
2556 }
2557 while (XPending(display) > 0) {
2558 XNextEvent(display, &event);
2559 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002560 }
2561
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002562 draw();
2563 curFrame++;
2564
Dave Houlton5fa47912018-02-16 11:02:26 -07002565 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2566 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002567 }
2568 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002569}
Tony Barbour153cb062016-12-07 13:43:36 -07002570#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002571
Dave Houlton5fa47912018-02-16 11:02:26 -07002572void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2573 uint8_t event_code = event->response_type & 0x7f;
2574 switch (event_code) {
2575 case XCB_EXPOSE:
2576 // TODO: Resize window
2577 break;
2578 case XCB_CLIENT_MESSAGE:
2579 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2580 quit = true;
2581 }
2582 break;
2583 case XCB_KEY_RELEASE: {
2584 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002585
Dave Houlton5fa47912018-02-16 11:02:26 -07002586 switch (key->detail) {
2587 case 0x9: // Escape
2588 quit = true;
2589 break;
2590 case 0x71: // left arrow key
2591 spin_angle -= spin_increment;
2592 break;
2593 case 0x72: // right arrow key
2594 spin_angle += spin_increment;
2595 break;
2596 case 0x41: // space bar
2597 pause = !pause;
2598 break;
2599 }
2600 } break;
2601 case XCB_CONFIGURE_NOTIFY: {
2602 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2603 if ((width != cfg->width) || (height != cfg->height)) {
2604 width = cfg->width;
2605 height = cfg->height;
2606 resize();
2607 }
2608 } break;
2609 default:
2610 break;
2611 }
2612}
2613
2614void Demo::run_xcb() {
2615 xcb_flush(connection);
2616
2617 while (!quit) {
2618 xcb_generic_event_t *event;
2619
2620 if (pause) {
2621 event = xcb_wait_for_event(connection);
2622 } else {
2623 event = xcb_poll_for_event(connection);
2624 }
2625 while (event) {
2626 handle_xcb_event(event);
2627 free(event);
2628 event = xcb_poll_for_event(connection);
2629 }
2630
2631 draw();
2632 curFrame++;
2633 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2634 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002635 }
2636 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002637}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002638
Dave Houlton5fa47912018-02-16 11:02:26 -07002639void Demo::create_xcb_window() {
2640 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002641
Dave Houlton5fa47912018-02-16 11:02:26 -07002642 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002643
Dave Houlton5fa47912018-02-16 11:02:26 -07002644 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2645 value_list[0] = screen->black_pixel;
2646 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002647
Dave Houlton5fa47912018-02-16 11:02:26 -07002648 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2649 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2650
2651 /* Magic code that will send notification when window is destroyed */
2652 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2653 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2654
2655 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2656 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2657
2658 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2659
2660 free(reply);
2661
2662 xcb_map_window(connection, xcb_window);
2663
2664 // Force the x/y coordinates to 100,100 results are identical in
2665 // consecutive
2666 // runs
2667 const uint32_t coords[] = {100, 100};
2668 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2669}
2670#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2671
2672void Demo::run() {
2673 while (!quit) {
2674 if (pause) {
2675 wl_display_dispatch(display);
2676 } else {
2677 wl_display_dispatch_pending(display);
2678 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002679 draw();
2680 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002681 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002682 quit = true;
2683 }
2684 }
2685 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002686}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002687
Dave Houlton5fa47912018-02-16 11:02:26 -07002688void Demo::create_window() {
2689 window = wl_compositor_create_surface(compositor);
2690 if (!window) {
2691 printf("Can not create wayland_surface from compositor!\n");
2692 fflush(stdout);
2693 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002694 }
2695
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002696 shell_surface = wl_shell_get_shell_surface(shell, window);
2697 if (!shell_surface) {
2698 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002699 fflush(stdout);
2700 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002701 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002702
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002703 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2704 wl_shell_surface_set_toplevel(shell_surface);
2705 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002706}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002707#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002708void Demo::run() {
2709 draw();
2710 curFrame++;
2711 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2712 quit = true;
2713 }
2714}
Damien Leone600c3052017-01-31 10:26:07 -07002715#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2716
Dave Houlton5fa47912018-02-16 11:02:26 -07002717vk::Result Demo::create_display_surface() {
2718 vk::Result result;
2719 uint32_t display_count;
2720 uint32_t mode_count;
2721 uint32_t plane_count;
2722 vk::DisplayPropertiesKHR display_props;
2723 vk::DisplayKHR display;
2724 vk::DisplayModePropertiesKHR mode_props;
2725 vk::DisplayPlanePropertiesKHR *plane_props;
2726 vk::Bool32 found_plane = VK_FALSE;
2727 uint32_t plane_index;
2728 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002729
Dave Houlton5fa47912018-02-16 11:02:26 -07002730 // Get the first display
2731 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2732 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002733
Dave Houlton5fa47912018-02-16 11:02:26 -07002734 if (display_count == 0) {
2735 printf("Cannot find any display!\n");
2736 fflush(stdout);
2737 exit(1);
2738 }
2739
2740 display_count = 1;
2741 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2742 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2743
2744 display = display_props.display;
2745
2746 // Get the first mode of the display
2747 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2748 VERIFY(result == vk::Result::eSuccess);
2749
2750 if (mode_count == 0) {
2751 printf("Cannot find any mode for the display!\n");
2752 fflush(stdout);
2753 exit(1);
2754 }
2755
2756 mode_count = 1;
2757 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2758 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2759
2760 // Get the list of planes
2761 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2762 VERIFY(result == vk::Result::eSuccess);
2763
2764 if (plane_count == 0) {
2765 printf("Cannot find any plane!\n");
2766 fflush(stdout);
2767 exit(1);
2768 }
2769
2770 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2771 VERIFY(plane_props != nullptr);
2772
2773 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2774 VERIFY(result == vk::Result::eSuccess);
2775
2776 // Find a plane compatible with the display
2777 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2778 uint32_t supported_count;
2779 vk::DisplayKHR *supported_displays;
2780
2781 // Disqualify planes that are bound to a different display
2782 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2783 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002784 }
2785
Dave Houlton5fa47912018-02-16 11:02:26 -07002786 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002787 VERIFY(result == vk::Result::eSuccess);
2788
Dave Houlton5fa47912018-02-16 11:02:26 -07002789 if (supported_count == 0) {
2790 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002791 }
2792
Dave Houlton5fa47912018-02-16 11:02:26 -07002793 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2794 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002795
Dave Houlton5fa47912018-02-16 11:02:26 -07002796 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002797 VERIFY(result == vk::Result::eSuccess);
2798
Dave Houlton5fa47912018-02-16 11:02:26 -07002799 for (uint32_t i = 0; i < supported_count; i++) {
2800 if (supported_displays[i] == display) {
2801 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002802 break;
2803 }
2804 }
2805
Dave Houlton5fa47912018-02-16 11:02:26 -07002806 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002807
Dave Houlton5fa47912018-02-16 11:02:26 -07002808 if (found_plane) {
2809 break;
Damien Leone600c3052017-01-31 10:26:07 -07002810 }
2811 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002812
2813 if (!found_plane) {
2814 printf("Cannot find a plane compatible with the display!\n");
2815 fflush(stdout);
2816 exit(1);
2817 }
2818
2819 free(plane_props);
2820
2821 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2822 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2823 // Find a supported alpha mode
2824 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2825 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2826 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2827 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2828 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2829 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2830 };
2831 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2832 if (planeCaps.supportedAlpha & alphaModes[i]) {
2833 alphaMode = alphaModes[i];
2834 break;
2835 }
2836 }
2837
2838 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2839 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2840
2841 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2842 .setDisplayMode(mode_props.displayMode)
2843 .setPlaneIndex(plane_index)
2844 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2845 .setGlobalAlpha(1.0f)
2846 .setAlphaMode(alphaMode)
2847 .setImageExtent(image_extent);
2848
2849 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2850}
2851
2852void Demo::run_display() {
2853 while (!quit) {
2854 draw();
2855 curFrame++;
2856
Petr Krausd88e4e52019-01-23 18:45:04 +01002857 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002858 quit = true;
2859 }
2860 }
2861}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002862#endif
2863
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002864#if _WIN32
2865// Include header required for parsing the command line options.
2866#include <shellapi.h>
2867
2868Demo demo;
2869
2870// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002871LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2872 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002873 case WM_CLOSE:
2874 PostQuitMessage(validation_error);
2875 break;
2876 case WM_PAINT:
2877 demo.run();
2878 break;
2879 case WM_GETMINMAXINFO: // set window's minimum size
2880 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2881 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002882 case WM_ERASEBKGND:
2883 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002884 case WM_SIZE:
2885 // Resize the application to the new window size, except when
2886 // it was minimized. Vulkan doesn't support images or swapchains
2887 // with width=0 and height=0.
2888 if (wParam != SIZE_MINIMIZED) {
2889 demo.width = lParam & 0xffff;
2890 demo.height = (lParam & 0xffff0000) >> 16;
2891 demo.resize();
2892 }
2893 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002894 case WM_KEYDOWN:
2895 switch (wParam) {
2896 case VK_ESCAPE:
2897 PostQuitMessage(validation_error);
2898 break;
2899 case VK_LEFT:
2900 demo.spin_angle -= demo.spin_increment;
2901 break;
2902 case VK_RIGHT:
2903 demo.spin_angle += demo.spin_increment;
2904 break;
2905 case VK_SPACE:
2906 demo.pause = !demo.pause;
2907 break;
2908 }
2909 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002910 default:
2911 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002912 }
2913
2914 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2915}
2916
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002917int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002918 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002919 MSG msg; // message
2920 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002921 int argc;
2922 char **argv;
2923
Jamie Madillb2ff6502017-03-15 16:17:46 -04002924 // Ensure wParam is initialized.
2925 msg.wParam = 0;
2926
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002927 // Use the CommandLine functions to get the command line arguments.
2928 // Unfortunately, Microsoft outputs
2929 // this information as wide characters for Unicode, and we simply want the
2930 // Ascii version to be compatible
2931 // with the non-Windows side. So, we have to convert the information to
2932 // Ascii character strings.
2933 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002934 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002935 argc = 0;
2936 }
2937
Jeremy Hayes9d304782016-10-09 11:48:12 -06002938 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002939 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002940 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002941 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002942 } else {
2943 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002944 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2945 size_t numConverted = 0;
2946
2947 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002948 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002949 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002950 }
2951 }
2952 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002953 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002954 argv = nullptr;
2955 }
2956
2957 demo.init(argc, argv);
2958
2959 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002960 if (argc > 0 && argv != nullptr) {
2961 for (int iii = 0; iii < argc; iii++) {
2962 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002963 free(argv[iii]);
2964 }
2965 }
2966 free(argv);
2967 }
2968
2969 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002970 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002971 demo.create_window();
2972 demo.init_vk_swapchain();
2973
2974 demo.prepare();
2975
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002976 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002977
2978 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002979 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002980 if (demo.pause) {
2981 const BOOL succ = WaitMessage();
2982
2983 if (!succ) {
2984 const auto &suppress_popups = demo.suppress_popups;
2985 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2986 }
2987 }
2988
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002989 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002990 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002991 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002992 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002993 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002994 /* Translate and dispatch to event queue*/
2995 TranslateMessage(&msg);
2996 DispatchMessage(&msg);
2997 }
2998 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2999 }
3000
3001 demo.cleanup();
3002
3003 return (int)msg.wParam;
3004}
3005
3006#elif __linux__
3007
Jeremy Hayes9d304782016-10-09 11:48:12 -06003008int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003009 Demo demo;
3010
3011 demo.init(argc, argv);
3012
Tony Barbour153cb062016-12-07 13:43:36 -07003013#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003014 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003015#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003016 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003017 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003018#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003019 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003020#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003021
3022 demo.init_vk_swapchain();
3023
3024 demo.prepare();
3025
Tony Barbour153cb062016-12-07 13:43:36 -07003026#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003027 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003028#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003029 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003030#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003031 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003032#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3033 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003034#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003035
3036 demo.cleanup();
3037
3038 return validation_error;
3039}
3040
Bill Hollings0a0625a2019-07-15 17:39:18 -04003041#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003042
3043// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003044static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003045 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003046 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003047 demo.init_vk_swapchain();
3048 demo.prepare();
3049 demo.spin_angle = 0.4f;
3050}
3051
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003052#else
3053#error "Platform not supported"
3054#endif