blob: 9a43ec9d413521fcbc3c929ae1968ade00fafc35 [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
37#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060038#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060039#include <vulkan/vulkan.hpp>
40#include <vulkan/vk_sdk_platform.h>
41
42#include "linmath.h"
43
44#ifndef NDEBUG
45#define VERIFY(x) assert(x)
46#else
47#define VERIFY(x) ((void)(x))
48#endif
49
Lenny Komowffe446c2018-11-19 17:08:04 -070050#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060051#ifdef _WIN32
52#define APP_NAME_STR_LEN 80
53#endif
54
55// Allow a maximum of two outstanding presentation operations.
56#define FRAME_LAG 2
57
58#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
59
60#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070061#define ERR_EXIT(err_msg, err_class) \
62 do { \
63 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
64 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060065 } while (0)
66#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070067#define ERR_EXIT(err_msg, err_class) \
68 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080069 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070070 fflush(stdout); \
71 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060072 } while (0)
73#endif
74
Jeremy Hayes9d304782016-10-09 11:48:12 -060075struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060076 vk::Sampler sampler;
77
78 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060079 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070080 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060081
82 vk::MemoryAllocateInfo mem_alloc;
83 vk::DeviceMemory mem;
84 vk::ImageView view;
85
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070086 int32_t tex_width{0};
87 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060088};
89
Jeremy Hayes9d304782016-10-09 11:48:12 -060090static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060091
92static int validation_error = 0;
93
94struct vkcube_vs_uniform {
95 // Must start with MVP
96 float mvp[4][4];
97 float position[12 * 3][4];
98 float color[12 * 3][4];
99};
100
101struct vktexcube_vs_uniform {
102 // Must start with MVP
103 float mvp[4][4];
104 float position[12 * 3][4];
105 float attr[12 * 3][4];
106};
107
108//--------------------------------------------------------------------------------------
109// Mesh and VertexFormat Data
110//--------------------------------------------------------------------------------------
111// clang-format off
112static const float g_vertex_buffer_data[] = {
113 -1.0f,-1.0f,-1.0f, // -X side
114 -1.0f,-1.0f, 1.0f,
115 -1.0f, 1.0f, 1.0f,
116 -1.0f, 1.0f, 1.0f,
117 -1.0f, 1.0f,-1.0f,
118 -1.0f,-1.0f,-1.0f,
119
120 -1.0f,-1.0f,-1.0f, // -Z side
121 1.0f, 1.0f,-1.0f,
122 1.0f,-1.0f,-1.0f,
123 -1.0f,-1.0f,-1.0f,
124 -1.0f, 1.0f,-1.0f,
125 1.0f, 1.0f,-1.0f,
126
127 -1.0f,-1.0f,-1.0f, // -Y side
128 1.0f,-1.0f,-1.0f,
129 1.0f,-1.0f, 1.0f,
130 -1.0f,-1.0f,-1.0f,
131 1.0f,-1.0f, 1.0f,
132 -1.0f,-1.0f, 1.0f,
133
134 -1.0f, 1.0f,-1.0f, // +Y side
135 -1.0f, 1.0f, 1.0f,
136 1.0f, 1.0f, 1.0f,
137 -1.0f, 1.0f,-1.0f,
138 1.0f, 1.0f, 1.0f,
139 1.0f, 1.0f,-1.0f,
140
141 1.0f, 1.0f,-1.0f, // +X side
142 1.0f, 1.0f, 1.0f,
143 1.0f,-1.0f, 1.0f,
144 1.0f,-1.0f, 1.0f,
145 1.0f,-1.0f,-1.0f,
146 1.0f, 1.0f,-1.0f,
147
148 -1.0f, 1.0f, 1.0f, // +Z side
149 -1.0f,-1.0f, 1.0f,
150 1.0f, 1.0f, 1.0f,
151 -1.0f,-1.0f, 1.0f,
152 1.0f,-1.0f, 1.0f,
153 1.0f, 1.0f, 1.0f,
154};
155
156static const float g_uv_buffer_data[] = {
157 0.0f, 1.0f, // -X side
158 1.0f, 1.0f,
159 1.0f, 0.0f,
160 1.0f, 0.0f,
161 0.0f, 0.0f,
162 0.0f, 1.0f,
163
164 1.0f, 1.0f, // -Z side
165 0.0f, 0.0f,
166 0.0f, 1.0f,
167 1.0f, 1.0f,
168 1.0f, 0.0f,
169 0.0f, 0.0f,
170
171 1.0f, 0.0f, // -Y side
172 1.0f, 1.0f,
173 0.0f, 1.0f,
174 1.0f, 0.0f,
175 0.0f, 1.0f,
176 0.0f, 0.0f,
177
178 1.0f, 0.0f, // +Y side
179 0.0f, 0.0f,
180 0.0f, 1.0f,
181 1.0f, 0.0f,
182 0.0f, 1.0f,
183 1.0f, 1.0f,
184
185 1.0f, 0.0f, // +X side
186 0.0f, 0.0f,
187 0.0f, 1.0f,
188 0.0f, 1.0f,
189 1.0f, 1.0f,
190 1.0f, 0.0f,
191
192 0.0f, 0.0f, // +Z side
193 0.0f, 1.0f,
194 1.0f, 0.0f,
195 0.0f, 1.0f,
196 1.0f, 1.0f,
197 1.0f, 0.0f,
198};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600199// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600200
Jeremy Hayes9d304782016-10-09 11:48:12 -0600201typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600202 vk::Image image;
203 vk::CommandBuffer cmd;
204 vk::CommandBuffer graphics_to_present_cmd;
205 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600206 vk::Buffer uniform_buffer;
207 vk::DeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700208 void *uniform_memory_ptr;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600209 vk::Framebuffer framebuffer;
210 vk::DescriptorSet descriptor_set;
211} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600212
Joey Bzdekbaf66472017-06-07 09:37:37 -0600213struct Demo {
214 Demo();
215 void build_image_ownership_cmd(uint32_t const &);
216 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
217 void cleanup();
218 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600219 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600220 void draw();
221 void draw_build_cmd(vk::CommandBuffer);
222 void flush_init_cmd();
223 void init(int, char **);
224 void init_connection();
225 void init_vk();
226 void init_vk_swapchain();
227 void prepare();
228 void prepare_buffers();
229 void prepare_cube_data_buffers();
230 void prepare_depth();
231 void prepare_descriptor_layout();
232 void prepare_descriptor_pool();
233 void prepare_descriptor_set();
234 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100235 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
236 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600237 vk::ShaderModule prepare_fs();
238 void prepare_pipeline();
239 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600240 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600241 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600242 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100243
Joey Bzdekbaf66472017-06-07 09:37:37 -0600244 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600245 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600246 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
247 vk::PipelineStageFlags, vk::PipelineStageFlags);
248 void update_data_buffer();
249 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
250 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
251
252#if defined(VK_USE_PLATFORM_WIN32_KHR)
253 void run();
254 void create_window();
255#elif defined(VK_USE_PLATFORM_XLIB_KHR)
256 void create_xlib_window();
257 void handle_xlib_event(const XEvent *);
258 void run_xlib();
259#elif defined(VK_USE_PLATFORM_XCB_KHR)
260 void handle_xcb_event(const xcb_generic_event_t *);
261 void run_xcb();
262 void create_xcb_window();
263#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
264 void run();
265 void create_window();
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);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700647 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700648 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700649 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700650 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
651 }
652
653 device.destroyCommandPool(cmd_pool, nullptr);
654
655 if (separate_present_queue) {
656 device.destroyCommandPool(present_cmd_pool, nullptr);
657 }
658 device.waitIdle();
659 device.destroy(nullptr);
660 inst.destroySurfaceKHR(surface, nullptr);
661
662#if defined(VK_USE_PLATFORM_XLIB_KHR)
663 XDestroyWindow(display, xlib_window);
664 XCloseDisplay(display);
665#elif defined(VK_USE_PLATFORM_XCB_KHR)
666 xcb_destroy_window(connection, xcb_window);
667 xcb_disconnect(connection);
668 free(atom_wm_delete_window);
669#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
670 wl_keyboard_destroy(keyboard);
671 wl_pointer_destroy(pointer);
672 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700673 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700674 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700675 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700676 wl_compositor_destroy(compositor);
677 wl_registry_destroy(registry);
678 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700679#endif
680
681 inst.destroy(nullptr);
682}
683
684void Demo::create_device() {
685 float const priorities[1] = {0.0};
686
687 vk::DeviceQueueCreateInfo queues[2];
688 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
689 queues[0].setQueueCount(1);
690 queues[0].setPQueuePriorities(priorities);
691
692 auto deviceInfo = vk::DeviceCreateInfo()
693 .setQueueCreateInfoCount(1)
694 .setPQueueCreateInfos(queues)
695 .setEnabledLayerCount(0)
696 .setPpEnabledLayerNames(nullptr)
697 .setEnabledExtensionCount(enabled_extension_count)
698 .setPpEnabledExtensionNames((const char *const *)extension_names)
699 .setPEnabledFeatures(nullptr);
700
701 if (separate_present_queue) {
702 queues[1].setQueueFamilyIndex(present_queue_family_index);
703 queues[1].setQueueCount(1);
704 queues[1].setPQueuePriorities(priorities);
705 deviceInfo.setQueueCreateInfoCount(2);
706 }
707
708 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
709 VERIFY(result == vk::Result::eSuccess);
710}
711
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600712void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700713 // clean up staging resources
714 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600715 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
716 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700717}
718
719void Demo::draw() {
720 // Ensure no more than FRAME_LAG renderings are outstanding
721 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700722 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700723
724 vk::Result result;
725 do {
726 result =
727 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
728 if (result == vk::Result::eErrorOutOfDateKHR) {
729 // demo->swapchain is out of date (e.g. the window was resized) and
730 // must be recreated:
731 resize();
732 } else if (result == vk::Result::eSuboptimalKHR) {
733 // swapchain is not as optimal as it could be, but the platform's
734 // presentation engine will still present the image correctly.
735 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600736 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
737 inst.destroySurfaceKHR(surface, nullptr);
738 create_surface();
739 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700740 } else {
741 VERIFY(result == vk::Result::eSuccess);
742 }
743 } while (result != vk::Result::eSuccess);
744
745 update_data_buffer();
746
747 // Wait for the image acquired semaphore to be signaled to ensure
748 // that the image won't be rendered to until the presentation
749 // engine has fully released ownership to the application, and it is
750 // okay to render to the image.
751 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
752 auto const submit_info = vk::SubmitInfo()
753 .setPWaitDstStageMask(&pipe_stage_flags)
754 .setWaitSemaphoreCount(1)
755 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
756 .setCommandBufferCount(1)
757 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
758 .setSignalSemaphoreCount(1)
759 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
760
761 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
762 VERIFY(result == vk::Result::eSuccess);
763
764 if (separate_present_queue) {
765 // If we are using separate queues, change image ownership to the
766 // present queue before presenting, waiting for the draw complete
767 // semaphore and signalling the ownership released semaphore when
768 // finished
769 auto const present_submit_info = vk::SubmitInfo()
770 .setPWaitDstStageMask(&pipe_stage_flags)
771 .setWaitSemaphoreCount(1)
772 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
773 .setCommandBufferCount(1)
774 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
775 .setSignalSemaphoreCount(1)
776 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
777
778 result = present_queue.submit(1, &present_submit_info, vk::Fence());
779 VERIFY(result == vk::Result::eSuccess);
780 }
781
782 // If we are using separate queues we have to wait for image ownership,
783 // otherwise wait for draw complete
784 auto const presentInfo = vk::PresentInfoKHR()
785 .setWaitSemaphoreCount(1)
786 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
787 : &draw_complete_semaphores[frame_index])
788 .setSwapchainCount(1)
789 .setPSwapchains(&swapchain)
790 .setPImageIndices(&current_buffer);
791
792 result = present_queue.presentKHR(&presentInfo);
793 frame_index += 1;
794 frame_index %= FRAME_LAG;
795 if (result == vk::Result::eErrorOutOfDateKHR) {
796 // swapchain is out of date (e.g. the window was resized) and
797 // must be recreated:
798 resize();
799 } else if (result == vk::Result::eSuboptimalKHR) {
800 // swapchain is not as optimal as it could be, but the platform's
801 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600802 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
803 inst.destroySurfaceKHR(surface, nullptr);
804 create_surface();
805 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700806 } else {
807 VERIFY(result == vk::Result::eSuccess);
808 }
809}
810
811void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
812 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
813
814 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
815 vk::ClearDepthStencilValue(1.0f, 0u)};
816
817 auto const passInfo = vk::RenderPassBeginInfo()
818 .setRenderPass(render_pass)
819 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
820 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
821 .setClearValueCount(2)
822 .setPClearValues(clearValues);
823
824 auto result = commandBuffer.begin(&commandInfo);
825 VERIFY(result == vk::Result::eSuccess);
826
827 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
828 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
829 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
830 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700831 float viewport_dimension;
832 float viewport_x = 0.0f;
833 float viewport_y = 0.0f;
834 if (width < height) {
835 viewport_dimension = (float)width;
836 viewport_y = (height - width) / 2.0f;
837 } else {
838 viewport_dimension = (float)height;
839 viewport_x = (width - height) / 2.0f;
840 }
841 auto const viewport = vk::Viewport()
842 .setX(viewport_x)
843 .setY(viewport_y)
844 .setWidth((float)viewport_dimension)
845 .setHeight((float)viewport_dimension)
846 .setMinDepth((float)0.0f)
847 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700848 commandBuffer.setViewport(0, 1, &viewport);
849
850 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
851 commandBuffer.setScissor(0, 1, &scissor);
852 commandBuffer.draw(12 * 3, 1, 0, 0);
853 // Note that ending the renderpass changes the image's layout from
854 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
855 commandBuffer.endRenderPass();
856
857 if (separate_present_queue) {
858 // We have to transfer ownership from the graphics queue family to
859 // the
860 // present queue family to be able to present. Note that we don't
861 // have
862 // to transfer from present queue family back to graphics queue
863 // family at
864 // the start of the next frame because we don't care about the
865 // image's
866 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600867 auto const image_ownership_barrier =
868 vk::ImageMemoryBarrier()
869 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600870 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600871 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
872 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
873 .setSrcQueueFamilyIndex(graphics_queue_family_index)
874 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700875 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700876 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600877
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600878 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700879 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600880 }
881
Dave Houlton5fa47912018-02-16 11:02:26 -0700882 result = commandBuffer.end();
883 VERIFY(result == vk::Result::eSuccess);
884}
885
886void Demo::flush_init_cmd() {
887 // TODO: hmm.
888 // This function could get called twice if the texture uses a staging
889 // buffer
890 // In that case the second call should be ignored
891 if (!cmd) {
892 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600893 }
894
Dave Houlton5fa47912018-02-16 11:02:26 -0700895 auto result = cmd.end();
896 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600897
Dave Houlton5fa47912018-02-16 11:02:26 -0700898 auto const fenceInfo = vk::FenceCreateInfo();
899 vk::Fence fence;
900 result = device.createFence(&fenceInfo, nullptr, &fence);
901 VERIFY(result == vk::Result::eSuccess);
902
903 vk::CommandBuffer const commandBuffers[] = {cmd};
904 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
905
906 result = graphics_queue.submit(1, &submitInfo, fence);
907 VERIFY(result == vk::Result::eSuccess);
908
909 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
910 VERIFY(result == vk::Result::eSuccess);
911
912 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
913 device.destroyFence(fence, nullptr);
914
915 cmd = vk::CommandBuffer();
916}
917
918void Demo::init(int argc, char **argv) {
919 vec3 eye = {0.0f, 3.0f, 5.0f};
920 vec3 origin = {0, 0, 0};
921 vec3 up = {0.0f, 1.0f, 0.0};
922
923 presentMode = vk::PresentModeKHR::eFifo;
924 frameCount = UINT32_MAX;
925 use_xlib = false;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600926
Dave Houlton5fa47912018-02-16 11:02:26 -0700927 for (int i = 1; i < argc; i++) {
928 if (strcmp(argv[i], "--use_staging") == 0) {
929 use_staging_buffer = true;
930 continue;
931 }
932 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
933 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
934 i++;
935 continue;
936 }
937 if (strcmp(argv[i], "--break") == 0) {
938 use_break = true;
939 continue;
940 }
941 if (strcmp(argv[i], "--validate") == 0) {
942 validate = true;
943 continue;
944 }
945 if (strcmp(argv[i], "--xlib") == 0) {
946 fprintf(stderr, "--xlib is deprecated and no longer does anything");
947 continue;
948 }
949 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
950 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
951 i++;
952 continue;
953 }
954 if (strcmp(argv[i], "--suppress_popups") == 0) {
955 suppress_popups = true;
956 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600957 }
958
Tony-LunarGd74734f2019-06-04 14:11:43 -0600959 std::stringstream usage;
960 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
961 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
962 << "\t[--present_mode <present mode enum>]\n"
963 << "\t<present_mode_enum>\n"
964 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
965 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
966 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
967 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
968
969#if defined(_WIN32)
970 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
971#else
972 std::cerr << usage.str();
973 std::cerr.flush();
974#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700975 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600976 }
977
Dave Houlton5fa47912018-02-16 11:02:26 -0700978 if (!use_xlib) {
979 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600980 }
981
Dave Houlton5fa47912018-02-16 11:02:26 -0700982 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600983
Dave Houlton5fa47912018-02-16 11:02:26 -0700984 width = 500;
985 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600986
Dave Houlton5fa47912018-02-16 11:02:26 -0700987 spin_angle = 4.0f;
988 spin_increment = 0.2f;
989 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600990
Dave Houlton5fa47912018-02-16 11:02:26 -0700991 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
992 mat4x4_look_at(view_matrix, eye, origin, up);
993 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600994
Dave Houlton5fa47912018-02-16 11:02:26 -0700995 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
996}
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600997
Dave Houlton5fa47912018-02-16 11:02:26 -0700998void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600999#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001000 const xcb_setup_t *setup;
1001 xcb_screen_iterator_t iter;
1002 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001003
Dave Houlton5fa47912018-02-16 11:02:26 -07001004 const char *display_envar = getenv("DISPLAY");
1005 if (display_envar == nullptr || display_envar[0] == '\0') {
1006 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1007 fflush(stdout);
1008 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001009 }
1010
Dave Houlton5fa47912018-02-16 11:02:26 -07001011 connection = xcb_connect(nullptr, &scr);
1012 if (xcb_connection_has_error(connection) > 0) {
1013 printf(
1014 "Cannot find a compatible Vulkan installable client driver "
1015 "(ICD).\nExiting ...\n");
1016 fflush(stdout);
1017 exit(1);
1018 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001019
Dave Houlton5fa47912018-02-16 11:02:26 -07001020 setup = xcb_get_setup(connection);
1021 iter = xcb_setup_roots_iterator(setup);
1022 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001023
Dave Houlton5fa47912018-02-16 11:02:26 -07001024 screen = iter.data;
1025#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1026 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001027
Dave Houlton5fa47912018-02-16 11:02:26 -07001028 if (display == nullptr) {
1029 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1030 fflush(stdout);
1031 exit(1);
1032 }
1033
1034 registry = wl_display_get_registry(display);
1035 wl_registry_add_listener(registry, &registry_listener, this);
1036 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001037#endif
1038}
1039
1040void Demo::init_vk() {
1041 uint32_t instance_extension_count = 0;
1042 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001043 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001044 enabled_extension_count = 0;
1045 enabled_layer_count = 0;
1046
Dave Houlton5fa47912018-02-16 11:02:26 -07001047 // Look for validation layers
1048 vk::Bool32 validation_found = VK_FALSE;
1049 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001050 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001051 VERIFY(result == vk::Result::eSuccess);
1052
Dave Houlton5fa47912018-02-16 11:02:26 -07001053 if (instance_layer_count > 0) {
1054 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1055 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001056 VERIFY(result == vk::Result::eSuccess);
1057
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001058 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001059 instance_layer_count, instance_layers.get());
1060 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001061 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1062 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001063 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001064 }
1065
Dave Houlton5fa47912018-02-16 11:02:26 -07001066 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001067 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001068 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1069 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001070 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001071 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001072 }
1073
Dave Houlton5fa47912018-02-16 11:02:26 -07001074 /* Look for instance extensions */
1075 vk::Bool32 surfaceExtFound = VK_FALSE;
1076 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1077 memset(extension_names, 0, sizeof(extension_names));
1078
Mike Schuchardt7510c832018-10-29 13:23:08 -07001079 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1080 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001081 VERIFY(result == vk::Result::eSuccess);
1082
1083 if (instance_extension_count > 0) {
1084 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1085 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1086 VERIFY(result == vk::Result::eSuccess);
1087
1088 for (uint32_t i = 0; i < instance_extension_count; i++) {
1089 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1090 surfaceExtFound = 1;
1091 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1092 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001093#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001094 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1095 platformSurfaceExtFound = 1;
1096 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1097 }
1098#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1099 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1100 platformSurfaceExtFound = 1;
1101 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1102 }
1103#elif defined(VK_USE_PLATFORM_XCB_KHR)
1104 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1105 platformSurfaceExtFound = 1;
1106 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1107 }
Tony Barbour153cb062016-12-07 13:43:36 -07001108#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001109 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1110 platformSurfaceExtFound = 1;
1111 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1112 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001113#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1114 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1115 platformSurfaceExtFound = 1;
1116 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1117 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001118#elif defined(VK_USE_PLATFORM_METAL_EXT)
1119 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001120 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001121 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001122 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001123
Dave Houlton5fa47912018-02-16 11:02:26 -07001124#endif
1125 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001126 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001127 }
1128
1129 if (!surfaceExtFound) {
1130 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1131 " extension.\n\n"
1132 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1133 "Please look at the Getting Started guide for additional information.\n",
1134 "vkCreateInstance Failure");
1135 }
1136
1137 if (!platformSurfaceExtFound) {
1138#if defined(VK_USE_PLATFORM_WIN32_KHR)
1139 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1140 " extension.\n\n"
1141 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1142 "Please look at the Getting Started guide for additional information.\n",
1143 "vkCreateInstance Failure");
1144#elif defined(VK_USE_PLATFORM_XCB_KHR)
1145 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1146 " extension.\n\n"
1147 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1148 "Please look at the Getting Started guide for additional information.\n",
1149 "vkCreateInstance Failure");
1150#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1151 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1152 " extension.\n\n"
1153 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1154 "Please look at the Getting Started guide for additional information.\n",
1155 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001156#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1158 " extension.\n\n"
1159 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1160 "Please look at the Getting Started guide for additional information.\n",
1161 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001162#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001163 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1164 " extension.\n\n"
1165 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1166 "Please look at the Getting Started guide for additional information.\n",
1167 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001168#elif defined(VK_USE_PLATFORM_METAL_EXT)
1169 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001170 " extension.\n\nDo you have a compatible "
1171 "Vulkan installable client driver (ICD) installed?\nPlease "
1172 "look at the Getting Started guide for additional "
1173 "information.\n",
1174 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001175#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001176 }
1177 auto const app = vk::ApplicationInfo()
1178 .setPApplicationName(APP_SHORT_NAME)
1179 .setApplicationVersion(0)
1180 .setPEngineName(APP_SHORT_NAME)
1181 .setEngineVersion(0)
1182 .setApiVersion(VK_API_VERSION_1_0);
1183 auto const inst_info = vk::InstanceCreateInfo()
1184 .setPApplicationInfo(&app)
1185 .setEnabledLayerCount(enabled_layer_count)
1186 .setPpEnabledLayerNames(instance_validation_layers)
1187 .setEnabledExtensionCount(enabled_extension_count)
1188 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001189
Dave Houlton5fa47912018-02-16 11:02:26 -07001190 result = vk::createInstance(&inst_info, nullptr, &inst);
1191 if (result == vk::Result::eErrorIncompatibleDriver) {
1192 ERR_EXIT(
1193 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1194 "Please look at the Getting Started guide for additional information.\n",
1195 "vkCreateInstance Failure");
1196 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1197 ERR_EXIT(
1198 "Cannot find a specified extension library.\n"
1199 "Make sure your layers path is set appropriately.\n",
1200 "vkCreateInstance Failure");
1201 } else if (result != vk::Result::eSuccess) {
1202 ERR_EXIT(
1203 "vkCreateInstance failed.\n\n"
1204 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1205 "Please look at the Getting Started guide for additional information.\n",
1206 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001207 }
1208
Dave Houlton5fa47912018-02-16 11:02:26 -07001209 /* Make initial call to query gpu_count, then second call for gpu info*/
1210 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001211 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001212 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001213
1214 if (gpu_count > 0) {
1215 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1216 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001217 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001218 /* For cube demo we just grab the first physical device */
1219 gpu = physical_devices[0];
1220 } else {
1221 ERR_EXIT(
1222 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1223 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1224 "Please look at the Getting Started guide for additional information.\n",
1225 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001226 }
1227
Dave Houlton5fa47912018-02-16 11:02:26 -07001228 /* Look for device extensions */
1229 uint32_t device_extension_count = 0;
1230 vk::Bool32 swapchainExtFound = VK_FALSE;
1231 enabled_extension_count = 0;
1232 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001233
Mike Schuchardt7510c832018-10-29 13:23:08 -07001234 result =
1235 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001236 VERIFY(result == vk::Result::eSuccess);
1237
1238 if (device_extension_count > 0) {
1239 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1240 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001241 VERIFY(result == vk::Result::eSuccess);
1242
Dave Houlton5fa47912018-02-16 11:02:26 -07001243 for (uint32_t i = 0; i < device_extension_count; i++) {
1244 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1245 swapchainExtFound = 1;
1246 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001247 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001248 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001249 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001250 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001251
Dave Houlton5fa47912018-02-16 11:02:26 -07001252 if (!swapchainExtFound) {
1253 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1254 " extension.\n\n"
1255 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1256 "Please look at the Getting Started guide for additional information.\n",
1257 "vkCreateInstance Failure");
1258 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001259
Dave Houlton5fa47912018-02-16 11:02:26 -07001260 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001261
Dave Houlton5fa47912018-02-16 11:02:26 -07001262 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001263 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001264 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001265
Dave Houlton5fa47912018-02-16 11:02:26 -07001266 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1267 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001268
Dave Houlton5fa47912018-02-16 11:02:26 -07001269 // Query fine-grained feature support for this device.
1270 // If app has specific feature requirements it should check supported
1271 // features based on this query
1272 vk::PhysicalDeviceFeatures physDevFeatures;
1273 gpu.getFeatures(&physDevFeatures);
1274}
1275
Tony-LunarG6cebf142019-09-11 14:32:23 -06001276void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001277// Create a WSI surface for the window:
1278#if defined(VK_USE_PLATFORM_WIN32_KHR)
1279 {
1280 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1281
1282 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1283 VERIFY(result == vk::Result::eSuccess);
1284 }
1285#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1286 {
1287 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1288
1289 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1290 VERIFY(result == vk::Result::eSuccess);
1291 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001292#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1293 {
1294 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1295
1296 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1297 VERIFY(result == vk::Result::eSuccess);
1298 }
1299#elif defined(VK_USE_PLATFORM_XCB_KHR)
1300 {
1301 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1302
1303 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1304 VERIFY(result == vk::Result::eSuccess);
1305 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001306#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001307 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001308 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001309
Bill Hollings0a0625a2019-07-15 17:39:18 -04001310 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001311 VERIFY(result == vk::Result::eSuccess);
1312 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001313#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1314 {
1315 auto result = create_display_surface();
1316 VERIFY(result == vk::Result::eSuccess);
1317 }
1318#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001319}
1320
1321void Demo::init_vk_swapchain() {
1322 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001323 // Iterate over each queue to learn whether it supports presenting:
1324 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1325 for (uint32_t i = 0; i < queue_family_count; i++) {
1326 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1327 }
1328
1329 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1330 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1331 for (uint32_t i = 0; i < queue_family_count; i++) {
1332 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1333 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1334 graphicsQueueFamilyIndex = i;
1335 }
1336
1337 if (supportsPresent[i] == VK_TRUE) {
1338 graphicsQueueFamilyIndex = i;
1339 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001340 break;
1341 }
1342 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001343 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001344
Dave Houlton5fa47912018-02-16 11:02:26 -07001345 if (presentQueueFamilyIndex == UINT32_MAX) {
1346 // If didn't find a queue that supports both graphics and present,
1347 // then
1348 // find a separate present queue.
1349 for (uint32_t i = 0; i < queue_family_count; ++i) {
1350 if (supportsPresent[i] == VK_TRUE) {
1351 presentQueueFamilyIndex = i;
1352 break;
1353 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001354 }
1355 }
1356
Dave Houlton5fa47912018-02-16 11:02:26 -07001357 // Generate error if could not find both a graphics and a present queue
1358 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1359 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1360 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001361
Dave Houlton5fa47912018-02-16 11:02:26 -07001362 graphics_queue_family_index = graphicsQueueFamilyIndex;
1363 present_queue_family_index = presentQueueFamilyIndex;
1364 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001365
Dave Houlton5fa47912018-02-16 11:02:26 -07001366 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001367
Dave Houlton5fa47912018-02-16 11:02:26 -07001368 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1369 if (!separate_present_queue) {
1370 present_queue = graphics_queue;
1371 } else {
1372 device.getQueue(present_queue_family_index, 0, &present_queue);
1373 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001374
Dave Houlton5fa47912018-02-16 11:02:26 -07001375 // Get the list of VkFormat's that are supported:
1376 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001377 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001378 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001379
Dave Houlton5fa47912018-02-16 11:02:26 -07001380 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1381 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1382 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1385 // the surface has no preferred format. Otherwise, at least one
1386 // supported format will be returned.
1387 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1388 format = vk::Format::eB8G8R8A8Unorm;
1389 } else {
1390 assert(formatCount >= 1);
1391 format = surfFormats[0].format;
1392 }
1393 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001394
Dave Houlton5fa47912018-02-16 11:02:26 -07001395 quit = false;
1396 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001397
Dave Houlton5fa47912018-02-16 11:02:26 -07001398 // Create semaphores to synchronize acquiring presentable buffers before
1399 // rendering and waiting for drawing to be complete before presenting
1400 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001401
Dave Houlton5fa47912018-02-16 11:02:26 -07001402 // Create fences that we can use to throttle if we get too far
1403 // ahead of the image presents
1404 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1405 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1406 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1407 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001408
Dave Houlton5fa47912018-02-16 11:02:26 -07001409 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1410 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001411
Dave Houlton5fa47912018-02-16 11:02:26 -07001412 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1413 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001414
Dave Houlton5fa47912018-02-16 11:02:26 -07001415 if (separate_present_queue) {
1416 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001417 VERIFY(result == vk::Result::eSuccess);
1418 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001419 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001420 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001421
Dave Houlton5fa47912018-02-16 11:02:26 -07001422 // Get Memory information and properties
1423 gpu.getMemoryProperties(&memory_properties);
1424}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001425
Dave Houlton5fa47912018-02-16 11:02:26 -07001426void Demo::prepare() {
1427 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1428 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1429 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001430
Dave Houlton5fa47912018-02-16 11:02:26 -07001431 auto const cmd = vk::CommandBufferAllocateInfo()
1432 .setCommandPool(cmd_pool)
1433 .setLevel(vk::CommandBufferLevel::ePrimary)
1434 .setCommandBufferCount(1);
1435
1436 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1437 VERIFY(result == vk::Result::eSuccess);
1438
1439 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1440
1441 result = this->cmd.begin(&cmd_buf_info);
1442 VERIFY(result == vk::Result::eSuccess);
1443
1444 prepare_buffers();
1445 prepare_depth();
1446 prepare_textures();
1447 prepare_cube_data_buffers();
1448
1449 prepare_descriptor_layout();
1450 prepare_render_pass();
1451 prepare_pipeline();
1452
1453 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1454 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1455 VERIFY(result == vk::Result::eSuccess);
1456 }
1457
1458 if (separate_present_queue) {
1459 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1460
1461 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1462 VERIFY(result == vk::Result::eSuccess);
1463
1464 auto const present_cmd = vk::CommandBufferAllocateInfo()
1465 .setCommandPool(present_cmd_pool)
1466 .setLevel(vk::CommandBufferLevel::ePrimary)
1467 .setCommandBufferCount(1);
1468
1469 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1470 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1471 VERIFY(result == vk::Result::eSuccess);
1472
1473 build_image_ownership_cmd(i);
1474 }
1475 }
1476
1477 prepare_descriptor_pool();
1478 prepare_descriptor_set();
1479
1480 prepare_framebuffers();
1481
1482 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1483 current_buffer = i;
1484 draw_build_cmd(swapchain_image_resources[i].cmd);
1485 }
1486
1487 /*
1488 * Prepare functions above may generate pipeline commands
1489 * that need to be flushed before beginning the render loop.
1490 */
1491 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001492 if (staging_texture.buffer) {
1493 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001494 }
1495
1496 current_buffer = 0;
1497 prepared = true;
1498}
1499
1500void Demo::prepare_buffers() {
1501 vk::SwapchainKHR oldSwapchain = swapchain;
1502
1503 // Check the surface capabilities and formats
1504 vk::SurfaceCapabilitiesKHR surfCapabilities;
1505 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1506 VERIFY(result == vk::Result::eSuccess);
1507
1508 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001509 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001510 VERIFY(result == vk::Result::eSuccess);
1511
1512 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1513 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1514 VERIFY(result == vk::Result::eSuccess);
1515
1516 vk::Extent2D swapchainExtent;
1517 // width and height are either both -1, or both not -1.
1518 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1519 // If the surface size is undefined, the size is set to
1520 // the size of the images requested.
1521 swapchainExtent.width = width;
1522 swapchainExtent.height = height;
1523 } else {
1524 // If the surface size is defined, the swap chain size must match
1525 swapchainExtent = surfCapabilities.currentExtent;
1526 width = surfCapabilities.currentExtent.width;
1527 height = surfCapabilities.currentExtent.height;
1528 }
1529
1530 // The FIFO present mode is guaranteed by the spec to be supported
1531 // and to have no tearing. It's a great default present mode to use.
1532 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1533
1534 // There are times when you may wish to use another present mode. The
1535 // following code shows how to select them, and the comments provide some
1536 // reasons you may wish to use them.
1537 //
1538 // It should be noted that Vulkan 1.0 doesn't provide a method for
1539 // synchronizing rendering with the presentation engine's display. There
1540 // is a method provided for throttling rendering with the display, but
1541 // there are some presentation engines for which this method will not work.
1542 // If an application doesn't throttle its rendering, and if it renders much
1543 // faster than the refresh rate of the display, this can waste power on
1544 // mobile devices. That is because power is being spent rendering images
1545 // that may never be seen.
1546
1547 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1548 // about
1549 // tearing, or have some way of synchronizing their rendering with the
1550 // display.
1551 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1552 // generally render a new presentable image every refresh cycle, but are
1553 // occasionally early. In this case, the application wants the new
1554 // image
1555 // to be displayed instead of the previously-queued-for-presentation
1556 // image
1557 // that has not yet been displayed.
1558 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1559 // render a new presentable image every refresh cycle, but are
1560 // occasionally
1561 // late. In this case (perhaps because of stuttering/latency concerns),
1562 // the application wants the late image to be immediately displayed,
1563 // even
1564 // though that may mean some tearing.
1565
1566 if (presentMode != swapchainPresentMode) {
1567 for (size_t i = 0; i < presentModeCount; ++i) {
1568 if (presentModes[i] == presentMode) {
1569 swapchainPresentMode = presentMode;
1570 break;
1571 }
1572 }
1573 }
1574
1575 if (swapchainPresentMode != presentMode) {
1576 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1577 }
1578
1579 // Determine the number of VkImages to use in the swap chain.
1580 // Application desires to acquire 3 images at a time for triple
1581 // buffering
1582 uint32_t desiredNumOfSwapchainImages = 3;
1583 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1584 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1585 }
1586
1587 // If maxImageCount is 0, we can ask for as many images as we want,
1588 // otherwise
1589 // we're limited to maxImageCount
1590 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1591 // Application must settle for fewer images than desired:
1592 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1593 }
1594
1595 vk::SurfaceTransformFlagBitsKHR preTransform;
1596 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1597 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1598 } else {
1599 preTransform = surfCapabilities.currentTransform;
1600 }
1601
1602 // Find a supported composite alpha mode - one of these is guaranteed to be set
1603 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1604 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1605 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1606 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1607 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1608 vk::CompositeAlphaFlagBitsKHR::eInherit,
1609 };
1610 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1611 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1612 compositeAlpha = compositeAlphaFlags[i];
1613 break;
1614 }
1615 }
1616
1617 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1618 .setSurface(surface)
1619 .setMinImageCount(desiredNumOfSwapchainImages)
1620 .setImageFormat(format)
1621 .setImageColorSpace(color_space)
1622 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1623 .setImageArrayLayers(1)
1624 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1625 .setImageSharingMode(vk::SharingMode::eExclusive)
1626 .setQueueFamilyIndexCount(0)
1627 .setPQueueFamilyIndices(nullptr)
1628 .setPreTransform(preTransform)
1629 .setCompositeAlpha(compositeAlpha)
1630 .setPresentMode(swapchainPresentMode)
1631 .setClipped(true)
1632 .setOldSwapchain(oldSwapchain);
1633
1634 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1635 VERIFY(result == vk::Result::eSuccess);
1636
1637 // If we just re-created an existing swapchain, we should destroy the
1638 // old
1639 // swapchain at this point.
1640 // Note: destroying the swapchain also cleans up all its associated
1641 // presentable images once the platform is done with them.
1642 if (oldSwapchain) {
1643 device.destroySwapchainKHR(oldSwapchain, nullptr);
1644 }
1645
Mike Schuchardt7510c832018-10-29 13:23:08 -07001646 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001647 VERIFY(result == vk::Result::eSuccess);
1648
1649 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1650 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1651 VERIFY(result == vk::Result::eSuccess);
1652
1653 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1654
1655 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1656 auto color_image_view = vk::ImageViewCreateInfo()
1657 .setViewType(vk::ImageViewType::e2D)
1658 .setFormat(format)
1659 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1660
1661 swapchain_image_resources[i].image = swapchainImages[i];
1662
1663 color_image_view.image = swapchain_image_resources[i].image;
1664
1665 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1666 VERIFY(result == vk::Result::eSuccess);
1667 }
1668}
1669
1670void Demo::prepare_cube_data_buffers() {
1671 mat4x4 VP;
1672 mat4x4_mul(VP, projection_matrix, view_matrix);
1673
1674 mat4x4 MVP;
1675 mat4x4_mul(MVP, VP, model_matrix);
1676
1677 vktexcube_vs_uniform data;
1678 memcpy(data.mvp, MVP, sizeof(MVP));
1679 // dumpMatrix("MVP", MVP)
1680
1681 for (int32_t i = 0; i < 12 * 3; i++) {
1682 data.position[i][0] = g_vertex_buffer_data[i * 3];
1683 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1684 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1685 data.position[i][3] = 1.0f;
1686 data.attr[i][0] = g_uv_buffer_data[2 * i];
1687 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1688 data.attr[i][2] = 0;
1689 data.attr[i][3] = 0;
1690 }
1691
1692 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1693
1694 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1695 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001696 VERIFY(result == vk::Result::eSuccess);
1697
1698 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001699 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001700
Dave Houlton5fa47912018-02-16 11:02:26 -07001701 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001702
Dave Houlton5fa47912018-02-16 11:02:26 -07001703 bool const pass = memory_type_from_properties(
1704 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1705 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001706 VERIFY(pass);
1707
Dave Houlton5fa47912018-02-16 11:02:26 -07001708 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001709 VERIFY(result == vk::Result::eSuccess);
1710
Tony-LunarG37af49f2019-12-19 12:04:19 -07001711 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1712 &swapchain_image_resources[i].uniform_memory_ptr);
1713 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001714
Tony-LunarG37af49f2019-12-19 12:04:19 -07001715 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001716
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;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002066 layout.rowPitch = tex_width * 4;
2067 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2068 VERIFY(data.result == vk::Result::eSuccess);
2069
2070 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2071 fprintf(stderr, "Error loading texture: %s\n", filename);
2072 }
2073
2074 device.unmapMemory(tex_obj->mem);
2075}
2076
Dave Houlton5fa47912018-02-16 11:02:26 -07002077void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2078 vk::MemoryPropertyFlags required_props) {
2079 int32_t tex_width;
2080 int32_t tex_height;
2081 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2082 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002083 }
2084
Dave Houlton5fa47912018-02-16 11:02:26 -07002085 tex_obj->tex_width = tex_width;
2086 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002087
Dave Houlton5fa47912018-02-16 11:02:26 -07002088 auto const image_create_info = vk::ImageCreateInfo()
2089 .setImageType(vk::ImageType::e2D)
2090 .setFormat(vk::Format::eR8G8B8A8Unorm)
2091 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2092 .setMipLevels(1)
2093 .setArrayLayers(1)
2094 .setSamples(vk::SampleCountFlagBits::e1)
2095 .setTiling(tiling)
2096 .setUsage(usage)
2097 .setSharingMode(vk::SharingMode::eExclusive)
2098 .setQueueFamilyIndexCount(0)
2099 .setPQueueFamilyIndices(nullptr)
2100 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002101
Dave Houlton5fa47912018-02-16 11:02:26 -07002102 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2103 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002104
Dave Houlton5fa47912018-02-16 11:02:26 -07002105 vk::MemoryRequirements mem_reqs;
2106 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002107
Dave Houlton5fa47912018-02-16 11:02:26 -07002108 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2109 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002110
Dave Houlton5fa47912018-02-16 11:02:26 -07002111 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2112 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002113
Dave Houlton5fa47912018-02-16 11:02:26 -07002114 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2115 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002116
Dave Houlton5fa47912018-02-16 11:02:26 -07002117 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2118 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002119
Dave Houlton5fa47912018-02-16 11:02:26 -07002120 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2121 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2122 vk::SubresourceLayout layout;
2123 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002124
Dave Houlton5fa47912018-02-16 11:02:26 -07002125 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002126 VERIFY(data.result == vk::Result::eSuccess);
2127
Dave Houlton5fa47912018-02-16 11:02:26 -07002128 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2129 fprintf(stderr, "Error loading texture: %s\n", filename);
2130 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002131
Dave Houlton5fa47912018-02-16 11:02:26 -07002132 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002133 }
2134
Dave Houlton5fa47912018-02-16 11:02:26 -07002135 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2136}
2137
2138void Demo::prepare_textures() {
2139 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2140 vk::FormatProperties props;
2141 gpu.getFormatProperties(tex_format, &props);
2142
2143 for (uint32_t i = 0; i < texture_count; i++) {
2144 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2145 /* Device can texture using linear textures */
2146 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2147 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2148 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2149 // shader to run until layout transition completes
2150 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2151 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2152 vk::PipelineStageFlagBits::eFragmentShader);
2153 staging_texture.image = vk::Image();
2154 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2155 /* Must use staging buffer to copy linear texture to optimized */
2156
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002157 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002158
2159 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2160 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2161 vk::MemoryPropertyFlagBits::eDeviceLocal);
2162
Dave Houlton5fa47912018-02-16 11:02:26 -07002163 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2164 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2165 vk::PipelineStageFlagBits::eTransfer);
2166
2167 auto const subresource = vk::ImageSubresourceLayers()
2168 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2169 .setMipLevel(0)
2170 .setBaseArrayLayer(0)
2171 .setLayerCount(1);
2172
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002173 auto const copy_region =
2174 vk::BufferImageCopy()
2175 .setBufferOffset(0)
2176 .setBufferRowLength(staging_texture.tex_width)
2177 .setBufferImageHeight(staging_texture.tex_height)
2178 .setImageSubresource(subresource)
2179 .setImageOffset({0, 0, 0})
2180 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002181
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002182 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002183
2184 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2185 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2186 vk::PipelineStageFlagBits::eFragmentShader);
2187 } else {
2188 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002189 }
2190
Dave Houlton5fa47912018-02-16 11:02:26 -07002191 auto const samplerInfo = vk::SamplerCreateInfo()
2192 .setMagFilter(vk::Filter::eNearest)
2193 .setMinFilter(vk::Filter::eNearest)
2194 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2195 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2196 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2197 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2198 .setMipLodBias(0.0f)
2199 .setAnisotropyEnable(VK_FALSE)
2200 .setMaxAnisotropy(1)
2201 .setCompareEnable(VK_FALSE)
2202 .setCompareOp(vk::CompareOp::eNever)
2203 .setMinLod(0.0f)
2204 .setMaxLod(0.0f)
2205 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2206 .setUnnormalizedCoordinates(VK_FALSE);
2207
2208 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2209 VERIFY(result == vk::Result::eSuccess);
2210
2211 auto const viewInfo = vk::ImageViewCreateInfo()
2212 .setImage(textures[i].image)
2213 .setViewType(vk::ImageViewType::e2D)
2214 .setFormat(tex_format)
2215 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2216
2217 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2218 VERIFY(result == vk::Result::eSuccess);
2219 }
2220}
2221
2222vk::ShaderModule Demo::prepare_vs() {
2223 const uint32_t vertShaderCode[] = {
2224#include "cube.vert.inc"
2225 };
2226
2227 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2228
2229 return vert_shader_module;
2230}
2231
2232void Demo::resize() {
2233 uint32_t i;
2234
2235 // Don't react to resize until after first initialization.
2236 if (!prepared) {
2237 return;
2238 }
2239
2240 // In order to properly resize the window, we must re-create the
2241 // swapchain
2242 // AND redo the command buffers, etc.
2243 //
2244 // First, perform part of the cleanup() function:
2245 prepared = false;
2246 auto result = device.waitIdle();
2247 VERIFY(result == vk::Result::eSuccess);
2248
2249 for (i = 0; i < swapchainImageCount; i++) {
2250 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2251 }
2252
2253 device.destroyDescriptorPool(desc_pool, nullptr);
2254
2255 device.destroyPipeline(pipeline, nullptr);
2256 device.destroyPipelineCache(pipelineCache, nullptr);
2257 device.destroyRenderPass(render_pass, nullptr);
2258 device.destroyPipelineLayout(pipeline_layout, nullptr);
2259 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2260
2261 for (i = 0; i < texture_count; i++) {
2262 device.destroyImageView(textures[i].view, nullptr);
2263 device.destroyImage(textures[i].image, nullptr);
2264 device.freeMemory(textures[i].mem, nullptr);
2265 device.destroySampler(textures[i].sampler, nullptr);
2266 }
2267
2268 device.destroyImageView(depth.view, nullptr);
2269 device.destroyImage(depth.image, nullptr);
2270 device.freeMemory(depth.mem, nullptr);
2271
2272 for (i = 0; i < swapchainImageCount; i++) {
2273 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002274 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002275 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002276 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002277 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
Tony-LunarG37af49f2019-12-19 12:04:19 -07002351 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002352}
2353
Karl Schultzb7940402018-05-29 13:09:22 -06002354/* Convert ppm image data from header file into RGBA texture image */
2355#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002356bool 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 -06002357 (void)filename;
2358 char *cPtr;
2359 cPtr = (char *)lunarg_ppm;
2360 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002361 return false;
2362 }
Karl Schultzb7940402018-05-29 13:09:22 -06002363 while (strncmp(cPtr++, "\n", 1))
2364 ;
2365 sscanf(cPtr, "%u %u", width, height);
2366 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002367 return true;
2368 }
Karl Schultzb7940402018-05-29 13:09:22 -06002369 while (strncmp(cPtr++, "\n", 1))
2370 ;
2371 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002372 return false;
2373 }
Karl Schultzb7940402018-05-29 13:09:22 -06002374 while (strncmp(cPtr++, "\n", 1))
2375 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002376 for (int y = 0; y < *height; y++) {
2377 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002378 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002379 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002380 rowPtr[3] = 255; /* Alpha of 1 */
2381 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002382 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002383 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002384 rgba_data += layout->rowPitch;
2385 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002386 return true;
2387}
2388
2389bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2390 // Search memtypes to find first index with those properties
2391 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2392 if ((typeBits & 1) == 1) {
2393 // Type is available, does it match user properties?
2394 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2395 *typeIndex = i;
2396 return true;
2397 }
2398 }
2399 typeBits >>= 1;
2400 }
2401
2402 // No memory types matched, return failure
2403 return false;
2404}
2405
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002406#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002407void Demo::run() {
2408 if (!prepared) {
2409 return;
2410 }
2411
2412 draw();
2413 curFrame++;
2414
Petr Krausd88e4e52019-01-23 18:45:04 +01002415 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002416 PostQuitMessage(validation_error);
2417 }
2418}
2419
2420void Demo::create_window() {
2421 WNDCLASSEX win_class;
2422
2423 // Initialize the window class structure:
2424 win_class.cbSize = sizeof(WNDCLASSEX);
2425 win_class.style = CS_HREDRAW | CS_VREDRAW;
2426 win_class.lpfnWndProc = WndProc;
2427 win_class.cbClsExtra = 0;
2428 win_class.cbWndExtra = 0;
2429 win_class.hInstance = connection; // hInstance
2430 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2431 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2432 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2433 win_class.lpszMenuName = nullptr;
2434 win_class.lpszClassName = name;
2435 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2436
2437 // Register window class:
2438 if (!RegisterClassEx(&win_class)) {
2439 // It didn't work, so try to give a useful error:
2440 printf("Unexpected error trying to start the application!\n");
2441 fflush(stdout);
2442 exit(1);
2443 }
2444
2445 // Create window with the registered class:
2446 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2447 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2448 window = CreateWindowEx(0,
2449 name, // class name
2450 name, // app name
2451 WS_OVERLAPPEDWINDOW | // window style
2452 WS_VISIBLE | WS_SYSMENU,
2453 100, 100, // x/y coords
2454 wr.right - wr.left, // width
2455 wr.bottom - wr.top, // height
2456 nullptr, // handle to parent
2457 nullptr, // handle to menu
2458 connection, // hInstance
2459 nullptr); // no extra parameters
2460
2461 if (!window) {
2462 // It didn't work, so try to give a useful error:
2463 printf("Cannot create a window in which to draw!\n");
2464 fflush(stdout);
2465 exit(1);
2466 }
2467
2468 // Window client area size must be at least 1 pixel high, to prevent
2469 // crash.
2470 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2471 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2472}
2473#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2474
2475void Demo::create_xlib_window() {
2476 const char *display_envar = getenv("DISPLAY");
2477 if (display_envar == nullptr || display_envar[0] == '\0') {
2478 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2479 fflush(stdout);
2480 exit(1);
2481 }
2482
2483 XInitThreads();
2484 display = XOpenDisplay(nullptr);
2485 long visualMask = VisualScreenMask;
2486 int numberOfVisuals;
2487 XVisualInfo vInfoTemplate = {};
2488 vInfoTemplate.screen = DefaultScreen(display);
2489 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2490
2491 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2492
2493 XSetWindowAttributes windowAttributes = {};
2494 windowAttributes.colormap = colormap;
2495 windowAttributes.background_pixel = 0xFFFFFFFF;
2496 windowAttributes.border_pixel = 0;
2497 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2498
2499 xlib_window =
2500 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2501 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2502
2503 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2504 XMapWindow(display, xlib_window);
2505 XFlush(display);
2506 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2507}
2508
2509void Demo::handle_xlib_event(const XEvent *event) {
2510 switch (event->type) {
2511 case ClientMessage:
2512 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2513 quit = true;
2514 }
2515 break;
2516 case KeyPress:
2517 switch (event->xkey.keycode) {
2518 case 0x9: // Escape
2519 quit = true;
2520 break;
2521 case 0x71: // left arrow key
2522 spin_angle -= spin_increment;
2523 break;
2524 case 0x72: // right arrow key
2525 spin_angle += spin_increment;
2526 break;
2527 case 0x41: // space bar
2528 pause = !pause;
2529 break;
2530 }
2531 break;
2532 case ConfigureNotify:
2533 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2534 width = event->xconfigure.width;
2535 height = event->xconfigure.height;
2536 resize();
2537 }
2538 break;
2539 default:
2540 break;
2541 }
2542}
2543
2544void Demo::run_xlib() {
2545 while (!quit) {
2546 XEvent event;
2547
2548 if (pause) {
2549 XNextEvent(display, &event);
2550 handle_xlib_event(&event);
2551 }
2552 while (XPending(display) > 0) {
2553 XNextEvent(display, &event);
2554 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002555 }
2556
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002557 draw();
2558 curFrame++;
2559
Dave Houlton5fa47912018-02-16 11:02:26 -07002560 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2561 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002562 }
2563 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002564}
Tony Barbour153cb062016-12-07 13:43:36 -07002565#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002566
Dave Houlton5fa47912018-02-16 11:02:26 -07002567void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2568 uint8_t event_code = event->response_type & 0x7f;
2569 switch (event_code) {
2570 case XCB_EXPOSE:
2571 // TODO: Resize window
2572 break;
2573 case XCB_CLIENT_MESSAGE:
2574 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2575 quit = true;
2576 }
2577 break;
2578 case XCB_KEY_RELEASE: {
2579 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002580
Dave Houlton5fa47912018-02-16 11:02:26 -07002581 switch (key->detail) {
2582 case 0x9: // Escape
2583 quit = true;
2584 break;
2585 case 0x71: // left arrow key
2586 spin_angle -= spin_increment;
2587 break;
2588 case 0x72: // right arrow key
2589 spin_angle += spin_increment;
2590 break;
2591 case 0x41: // space bar
2592 pause = !pause;
2593 break;
2594 }
2595 } break;
2596 case XCB_CONFIGURE_NOTIFY: {
2597 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2598 if ((width != cfg->width) || (height != cfg->height)) {
2599 width = cfg->width;
2600 height = cfg->height;
2601 resize();
2602 }
2603 } break;
2604 default:
2605 break;
2606 }
2607}
2608
2609void Demo::run_xcb() {
2610 xcb_flush(connection);
2611
2612 while (!quit) {
2613 xcb_generic_event_t *event;
2614
2615 if (pause) {
2616 event = xcb_wait_for_event(connection);
2617 } else {
2618 event = xcb_poll_for_event(connection);
2619 }
2620 while (event) {
2621 handle_xcb_event(event);
2622 free(event);
2623 event = xcb_poll_for_event(connection);
2624 }
2625
2626 draw();
2627 curFrame++;
2628 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2629 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002630 }
2631 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002632}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002633
Dave Houlton5fa47912018-02-16 11:02:26 -07002634void Demo::create_xcb_window() {
2635 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002636
Dave Houlton5fa47912018-02-16 11:02:26 -07002637 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002638
Dave Houlton5fa47912018-02-16 11:02:26 -07002639 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2640 value_list[0] = screen->black_pixel;
2641 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002642
Dave Houlton5fa47912018-02-16 11:02:26 -07002643 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2644 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2645
2646 /* Magic code that will send notification when window is destroyed */
2647 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2648 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2649
2650 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2651 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2652
2653 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2654
2655 free(reply);
2656
2657 xcb_map_window(connection, xcb_window);
2658
2659 // Force the x/y coordinates to 100,100 results are identical in
2660 // consecutive
2661 // runs
2662 const uint32_t coords[] = {100, 100};
2663 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2664}
2665#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2666
2667void Demo::run() {
2668 while (!quit) {
2669 if (pause) {
2670 wl_display_dispatch(display);
2671 } else {
2672 wl_display_dispatch_pending(display);
2673 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002674 draw();
2675 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002676 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002677 quit = true;
2678 }
2679 }
2680 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002681}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002682
Dave Houlton5fa47912018-02-16 11:02:26 -07002683void Demo::create_window() {
2684 window = wl_compositor_create_surface(compositor);
2685 if (!window) {
2686 printf("Can not create wayland_surface from compositor!\n");
2687 fflush(stdout);
2688 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002689 }
2690
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002691 shell_surface = wl_shell_get_shell_surface(shell, window);
2692 if (!shell_surface) {
2693 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002694 fflush(stdout);
2695 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002696 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002697
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002698 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2699 wl_shell_surface_set_toplevel(shell_surface);
2700 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002701}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002702#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002703void Demo::run() {
2704 draw();
2705 curFrame++;
2706 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2707 quit = true;
2708 }
2709}
Damien Leone600c3052017-01-31 10:26:07 -07002710#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2711
Dave Houlton5fa47912018-02-16 11:02:26 -07002712vk::Result Demo::create_display_surface() {
2713 vk::Result result;
2714 uint32_t display_count;
2715 uint32_t mode_count;
2716 uint32_t plane_count;
2717 vk::DisplayPropertiesKHR display_props;
2718 vk::DisplayKHR display;
2719 vk::DisplayModePropertiesKHR mode_props;
2720 vk::DisplayPlanePropertiesKHR *plane_props;
2721 vk::Bool32 found_plane = VK_FALSE;
2722 uint32_t plane_index;
2723 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002724
Dave Houlton5fa47912018-02-16 11:02:26 -07002725 // Get the first display
2726 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2727 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002728
Dave Houlton5fa47912018-02-16 11:02:26 -07002729 if (display_count == 0) {
2730 printf("Cannot find any display!\n");
2731 fflush(stdout);
2732 exit(1);
2733 }
2734
2735 display_count = 1;
2736 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2737 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2738
2739 display = display_props.display;
2740
2741 // Get the first mode of the display
2742 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2743 VERIFY(result == vk::Result::eSuccess);
2744
2745 if (mode_count == 0) {
2746 printf("Cannot find any mode for the display!\n");
2747 fflush(stdout);
2748 exit(1);
2749 }
2750
2751 mode_count = 1;
2752 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2753 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2754
2755 // Get the list of planes
2756 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2757 VERIFY(result == vk::Result::eSuccess);
2758
2759 if (plane_count == 0) {
2760 printf("Cannot find any plane!\n");
2761 fflush(stdout);
2762 exit(1);
2763 }
2764
2765 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2766 VERIFY(plane_props != nullptr);
2767
2768 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2769 VERIFY(result == vk::Result::eSuccess);
2770
2771 // Find a plane compatible with the display
2772 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2773 uint32_t supported_count;
2774 vk::DisplayKHR *supported_displays;
2775
2776 // Disqualify planes that are bound to a different display
2777 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2778 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002779 }
2780
Dave Houlton5fa47912018-02-16 11:02:26 -07002781 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002782 VERIFY(result == vk::Result::eSuccess);
2783
Dave Houlton5fa47912018-02-16 11:02:26 -07002784 if (supported_count == 0) {
2785 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002786 }
2787
Dave Houlton5fa47912018-02-16 11:02:26 -07002788 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2789 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002790
Dave Houlton5fa47912018-02-16 11:02:26 -07002791 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002792 VERIFY(result == vk::Result::eSuccess);
2793
Dave Houlton5fa47912018-02-16 11:02:26 -07002794 for (uint32_t i = 0; i < supported_count; i++) {
2795 if (supported_displays[i] == display) {
2796 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002797 break;
2798 }
2799 }
2800
Dave Houlton5fa47912018-02-16 11:02:26 -07002801 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002802
Dave Houlton5fa47912018-02-16 11:02:26 -07002803 if (found_plane) {
2804 break;
Damien Leone600c3052017-01-31 10:26:07 -07002805 }
2806 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002807
2808 if (!found_plane) {
2809 printf("Cannot find a plane compatible with the display!\n");
2810 fflush(stdout);
2811 exit(1);
2812 }
2813
2814 free(plane_props);
2815
2816 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2817 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2818 // Find a supported alpha mode
2819 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2820 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2821 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2822 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2823 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2824 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2825 };
2826 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2827 if (planeCaps.supportedAlpha & alphaModes[i]) {
2828 alphaMode = alphaModes[i];
2829 break;
2830 }
2831 }
2832
2833 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2834 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2835
2836 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2837 .setDisplayMode(mode_props.displayMode)
2838 .setPlaneIndex(plane_index)
2839 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2840 .setGlobalAlpha(1.0f)
2841 .setAlphaMode(alphaMode)
2842 .setImageExtent(image_extent);
2843
2844 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2845}
2846
2847void Demo::run_display() {
2848 while (!quit) {
2849 draw();
2850 curFrame++;
2851
Petr Krausd88e4e52019-01-23 18:45:04 +01002852 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002853 quit = true;
2854 }
2855 }
2856}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002857#endif
2858
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002859#if _WIN32
2860// Include header required for parsing the command line options.
2861#include <shellapi.h>
2862
2863Demo demo;
2864
2865// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002866LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2867 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002868 case WM_CLOSE:
2869 PostQuitMessage(validation_error);
2870 break;
2871 case WM_PAINT:
2872 demo.run();
2873 break;
2874 case WM_GETMINMAXINFO: // set window's minimum size
2875 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2876 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002877 case WM_ERASEBKGND:
2878 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002879 case WM_SIZE:
2880 // Resize the application to the new window size, except when
2881 // it was minimized. Vulkan doesn't support images or swapchains
2882 // with width=0 and height=0.
2883 if (wParam != SIZE_MINIMIZED) {
2884 demo.width = lParam & 0xffff;
2885 demo.height = (lParam & 0xffff0000) >> 16;
2886 demo.resize();
2887 }
2888 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002889 case WM_KEYDOWN:
2890 switch (wParam) {
2891 case VK_ESCAPE:
2892 PostQuitMessage(validation_error);
2893 break;
2894 case VK_LEFT:
2895 demo.spin_angle -= demo.spin_increment;
2896 break;
2897 case VK_RIGHT:
2898 demo.spin_angle += demo.spin_increment;
2899 break;
2900 case VK_SPACE:
2901 demo.pause = !demo.pause;
2902 break;
2903 }
2904 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002905 default:
2906 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002907 }
2908
2909 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2910}
2911
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002912int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002913 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002914 MSG msg; // message
2915 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002916 int argc;
2917 char **argv;
2918
Jamie Madillb2ff6502017-03-15 16:17:46 -04002919 // Ensure wParam is initialized.
2920 msg.wParam = 0;
2921
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002922 // Use the CommandLine functions to get the command line arguments.
2923 // Unfortunately, Microsoft outputs
2924 // this information as wide characters for Unicode, and we simply want the
2925 // Ascii version to be compatible
2926 // with the non-Windows side. So, we have to convert the information to
2927 // Ascii character strings.
2928 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002929 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002930 argc = 0;
2931 }
2932
Jeremy Hayes9d304782016-10-09 11:48:12 -06002933 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002934 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002935 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002936 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002937 } else {
2938 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002939 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2940 size_t numConverted = 0;
2941
2942 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002943 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002944 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002945 }
2946 }
2947 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002948 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002949 argv = nullptr;
2950 }
2951
2952 demo.init(argc, argv);
2953
2954 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002955 if (argc > 0 && argv != nullptr) {
2956 for (int iii = 0; iii < argc; iii++) {
2957 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002958 free(argv[iii]);
2959 }
2960 }
2961 free(argv);
2962 }
2963
2964 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002965 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002966 demo.create_window();
2967 demo.init_vk_swapchain();
2968
2969 demo.prepare();
2970
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002971 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002972
2973 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002974 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002975 if (demo.pause) {
2976 const BOOL succ = WaitMessage();
2977
2978 if (!succ) {
2979 const auto &suppress_popups = demo.suppress_popups;
2980 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2981 }
2982 }
2983
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002984 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002985 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002986 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002987 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06002988 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002989 /* Translate and dispatch to event queue*/
2990 TranslateMessage(&msg);
2991 DispatchMessage(&msg);
2992 }
2993 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
2994 }
2995
2996 demo.cleanup();
2997
2998 return (int)msg.wParam;
2999}
3000
3001#elif __linux__
3002
Jeremy Hayes9d304782016-10-09 11:48:12 -06003003int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003004 Demo demo;
3005
3006 demo.init(argc, argv);
3007
Tony Barbour153cb062016-12-07 13:43:36 -07003008#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003009 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003010#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003011 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003012 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003013#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003014 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003015#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003016
3017 demo.init_vk_swapchain();
3018
3019 demo.prepare();
3020
Tony Barbour153cb062016-12-07 13:43:36 -07003021#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003022 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003023#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003024 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003025#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003026 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003027#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3028 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003029#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003030
3031 demo.cleanup();
3032
3033 return validation_error;
3034}
3035
Bill Hollings0a0625a2019-07-15 17:39:18 -04003036#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003037
3038// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003039static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003040 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003041 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003042 demo.init_vk_swapchain();
3043 demo.prepare();
3044 demo.spin_angle = 0.4f;
3045}
3046
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003047#else
3048#error "Platform not supported"
3049#endif