blob: fc32c74f9db4a06af12407c1ad11b35101313457 [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;
Tony-LunarG50e737c2020-07-16 14:26:03 -0600306 uint32_t gpu_number;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600307
308 vk::Instance inst;
309 vk::PhysicalDevice gpu;
310 vk::Device device;
311 vk::Queue graphics_queue;
312 vk::Queue present_queue;
313 uint32_t graphics_queue_family_index;
314 uint32_t present_queue_family_index;
315 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
316 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
317 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
318 vk::PhysicalDeviceProperties gpu_props;
319 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
320 vk::PhysicalDeviceMemoryProperties memory_properties;
321
322 uint32_t enabled_extension_count;
323 uint32_t enabled_layer_count;
324 char const *extension_names[64];
325 char const *enabled_layers[64];
326
327 uint32_t width;
328 uint32_t height;
329 vk::Format format;
330 vk::ColorSpaceKHR color_space;
331
332 uint32_t swapchainImageCount;
333 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600334 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600335 vk::PresentModeKHR presentMode;
336 vk::Fence fences[FRAME_LAG];
337 uint32_t frame_index;
338
339 vk::CommandPool cmd_pool;
340 vk::CommandPool present_cmd_pool;
341
342 struct {
343 vk::Format format;
344 vk::Image image;
345 vk::MemoryAllocateInfo mem_alloc;
346 vk::DeviceMemory mem;
347 vk::ImageView view;
348 } depth;
349
350 static int32_t const texture_count = 1;
351 texture_object textures[texture_count];
352 texture_object staging_texture;
353
354 struct {
355 vk::Buffer buf;
356 vk::MemoryAllocateInfo mem_alloc;
357 vk::DeviceMemory mem;
358 vk::DescriptorBufferInfo buffer_info;
359 } uniform_data;
360
361 vk::CommandBuffer cmd; // Buffer for initialization commands
362 vk::PipelineLayout pipeline_layout;
363 vk::DescriptorSetLayout desc_layout;
364 vk::PipelineCache pipelineCache;
365 vk::RenderPass render_pass;
366 vk::Pipeline pipeline;
367
368 mat4x4 projection_matrix;
369 mat4x4 view_matrix;
370 mat4x4 model_matrix;
371
372 float spin_angle;
373 float spin_increment;
374 bool pause;
375
376 vk::ShaderModule vert_shader_module;
377 vk::ShaderModule frag_shader_module;
378
379 vk::DescriptorPool desc_pool;
380 vk::DescriptorSet desc_set;
381
382 std::unique_ptr<vk::Framebuffer[]> framebuffers;
383
384 bool quit;
385 uint32_t curFrame;
386 uint32_t frameCount;
387 bool validate;
388 bool use_break;
389 bool suppress_popups;
390
391 uint32_t current_buffer;
392 uint32_t queue_family_count;
393};
394
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600395#ifdef _WIN32
396// MS-Windows event handling function:
397LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
398#endif
399
Karl Schultz23cc2182016-11-23 17:15:17 -0700400#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700401static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700402 wl_shell_surface_pong(shell_surface, serial);
403}
404
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700405static 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 -0700406
407static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
408
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700409static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700410
Joey Bzdek15eb0702017-06-07 09:40:36 -0600411static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
412 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700413
Joey Bzdek15eb0702017-06-07 09:40:36 -0600414static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700415
Joey Bzdek15eb0702017-06-07 09:40:36 -0600416static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
417
418static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
419 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600420 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700422 wl_shell_surface_move(demo->shell_surface, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600423 }
424}
425
426static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
427
428static const struct wl_pointer_listener pointer_listener = {
429 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
430};
431
432static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
433
434static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
435 struct wl_array *keys) {}
436
437static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
438
439static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
440 uint32_t state) {
441 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
442 Demo *demo = (Demo *)data;
443 switch (key) {
444 case KEY_ESC: // Escape
445 demo->quit = true;
446 break;
447 case KEY_LEFT: // left arrow key
448 demo->spin_angle -= demo->spin_increment;
449 break;
450 case KEY_RIGHT: // right arrow key
451 demo->spin_angle += demo->spin_increment;
452 break;
453 case KEY_SPACE: // space bar
454 demo->pause = !demo->pause;
455 break;
456 }
457}
458
459static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
460 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
461
462static const struct wl_keyboard_listener keyboard_listener = {
463 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
464};
465
466static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
467 // Subscribe to pointer events
468 Demo *demo = (Demo *)data;
469 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
470 demo->pointer = wl_seat_get_pointer(seat);
471 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
472 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
473 wl_pointer_destroy(demo->pointer);
474 demo->pointer = NULL;
475 }
476 // Subscribe to keyboard events
477 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
478 demo->keyboard = wl_seat_get_keyboard(seat);
479 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
480 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
481 wl_keyboard_destroy(demo->keyboard);
482 demo->keyboard = NULL;
483 }
484}
485
486static const wl_seat_listener seat_listener = {
487 seat_handle_capabilities,
488};
489
490static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
491 Demo *demo = (Demo *)data;
492 // pickup wayland objects when they appear
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700493 if (strcmp(interface, "wl_compositor") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600494 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700495 } else if (strcmp(interface, "wl_shell") == 0) {
496 demo->shell = (wl_shell *)wl_registry_bind(registry, id, &wl_shell_interface, 1);
497 } else if (strcmp(interface, "wl_seat") == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600498 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
499 wl_seat_add_listener(demo->seat, &seat_listener, demo);
500 }
501}
502
503static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
504
505static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700506#endif
507
Joey Bzdekbaf66472017-06-07 09:37:37 -0600508Demo::Demo()
509 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600510#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600511 connection{nullptr},
512 window{nullptr},
513 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600514#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700515
Tony Barbour78d6b572016-11-14 14:46:33 -0700516#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600517 xlib_window{0},
518 xlib_wm_delete_window{0},
519 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700520#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521 xcb_window{0},
522 screen{nullptr},
523 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700524#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600525 display{nullptr},
526 registry{nullptr},
527 compositor{nullptr},
528 window{nullptr},
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700529 shell{nullptr},
530 shell_surface{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600531 seat{nullptr},
532 pointer{nullptr},
533 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700534#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600535 prepared{false},
536 use_staging_buffer{false},
537 use_xlib{false},
538 graphics_queue_family_index{0},
539 present_queue_family_index{0},
540 enabled_extension_count{0},
541 enabled_layer_count{0},
542 width{0},
543 height{0},
544 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000545 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600546 frame_index{0},
547 spin_angle{0.0f},
548 spin_increment{0.0f},
549 pause{false},
550 quit{false},
551 curFrame{0},
552 frameCount{0},
553 validate{false},
554 use_break{false},
555 suppress_popups{false},
556 current_buffer{0},
557 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600558#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700559 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600560#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700561 memset(projection_matrix, 0, sizeof(projection_matrix));
562 memset(view_matrix, 0, sizeof(view_matrix));
563 memset(model_matrix, 0, sizeof(model_matrix));
564}
565
566void Demo::build_image_ownership_cmd(uint32_t const &i) {
567 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
568 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
569 VERIFY(result == vk::Result::eSuccess);
570
571 auto const image_ownership_barrier =
572 vk::ImageMemoryBarrier()
573 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600574 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700575 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
576 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
577 .setSrcQueueFamilyIndex(graphics_queue_family_index)
578 .setDstQueueFamilyIndex(present_queue_family_index)
579 .setImage(swapchain_image_resources[i].image)
580 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
581
582 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600583 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
584 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700585
586 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
587 VERIFY(result == vk::Result::eSuccess);
588}
589
590vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
591 vk::LayerProperties *layers) {
592 for (uint32_t i = 0; i < check_count; i++) {
593 vk::Bool32 found = VK_FALSE;
594 for (uint32_t j = 0; j < layer_count; j++) {
595 if (!strcmp(check_names[i], layers[j].layerName)) {
596 found = VK_TRUE;
597 break;
598 }
599 }
600 if (!found) {
601 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
602 return 0;
603 }
604 }
605 return VK_TRUE;
606}
607
608void Demo::cleanup() {
609 prepared = false;
610 device.waitIdle();
611
612 // Wait for fences from present operations
613 for (uint32_t i = 0; i < FRAME_LAG; i++) {
614 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
615 device.destroyFence(fences[i], nullptr);
616 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
617 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
618 if (separate_present_queue) {
619 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
620 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600621 }
622
Dave Houlton5fa47912018-02-16 11:02:26 -0700623 for (uint32_t i = 0; i < swapchainImageCount; i++) {
624 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
625 }
626 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600627
Dave Houlton5fa47912018-02-16 11:02:26 -0700628 device.destroyPipeline(pipeline, nullptr);
629 device.destroyPipelineCache(pipelineCache, nullptr);
630 device.destroyRenderPass(render_pass, nullptr);
631 device.destroyPipelineLayout(pipeline_layout, nullptr);
632 device.destroyDescriptorSetLayout(desc_layout, nullptr);
633
634 for (uint32_t i = 0; i < texture_count; i++) {
635 device.destroyImageView(textures[i].view, nullptr);
636 device.destroyImage(textures[i].image, nullptr);
637 device.freeMemory(textures[i].mem, nullptr);
638 device.destroySampler(textures[i].sampler, nullptr);
639 }
640 device.destroySwapchainKHR(swapchain, nullptr);
641
642 device.destroyImageView(depth.view, nullptr);
643 device.destroyImage(depth.image, nullptr);
644 device.freeMemory(depth.mem, nullptr);
645
646 for (uint32_t i = 0; i < swapchainImageCount; i++) {
647 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700648 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -0700649 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -0700650 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -0700651 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
652 }
653
654 device.destroyCommandPool(cmd_pool, nullptr);
655
656 if (separate_present_queue) {
657 device.destroyCommandPool(present_cmd_pool, nullptr);
658 }
659 device.waitIdle();
660 device.destroy(nullptr);
661 inst.destroySurfaceKHR(surface, nullptr);
662
663#if defined(VK_USE_PLATFORM_XLIB_KHR)
664 XDestroyWindow(display, xlib_window);
665 XCloseDisplay(display);
666#elif defined(VK_USE_PLATFORM_XCB_KHR)
667 xcb_destroy_window(connection, xcb_window);
668 xcb_disconnect(connection);
669 free(atom_wm_delete_window);
670#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
671 wl_keyboard_destroy(keyboard);
672 wl_pointer_destroy(pointer);
673 wl_seat_destroy(seat);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700674 wl_shell_surface_destroy(shell_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700675 wl_surface_destroy(window);
Tony-LunarG5ceb7be2019-12-05 16:05:40 -0700676 wl_shell_destroy(shell);
Dave Houlton5fa47912018-02-16 11:02:26 -0700677 wl_compositor_destroy(compositor);
678 wl_registry_destroy(registry);
679 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700680#endif
681
682 inst.destroy(nullptr);
683}
684
685void Demo::create_device() {
686 float const priorities[1] = {0.0};
687
688 vk::DeviceQueueCreateInfo queues[2];
689 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
690 queues[0].setQueueCount(1);
691 queues[0].setPQueuePriorities(priorities);
692
693 auto deviceInfo = vk::DeviceCreateInfo()
694 .setQueueCreateInfoCount(1)
695 .setPQueueCreateInfos(queues)
696 .setEnabledLayerCount(0)
697 .setPpEnabledLayerNames(nullptr)
698 .setEnabledExtensionCount(enabled_extension_count)
699 .setPpEnabledExtensionNames((const char *const *)extension_names)
700 .setPEnabledFeatures(nullptr);
701
702 if (separate_present_queue) {
703 queues[1].setQueueFamilyIndex(present_queue_family_index);
704 queues[1].setQueueCount(1);
705 queues[1].setPQueuePriorities(priorities);
706 deviceInfo.setQueueCreateInfoCount(2);
707 }
708
709 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
710 VERIFY(result == vk::Result::eSuccess);
711}
712
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600713void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700714 // clean up staging resources
715 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600716 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
717 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700718}
719
720void Demo::draw() {
721 // Ensure no more than FRAME_LAG renderings are outstanding
722 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -0700723 device.resetFences({fences[frame_index]});
Dave Houlton5fa47912018-02-16 11:02:26 -0700724
725 vk::Result result;
726 do {
727 result =
728 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
729 if (result == vk::Result::eErrorOutOfDateKHR) {
730 // demo->swapchain is out of date (e.g. the window was resized) and
731 // must be recreated:
732 resize();
733 } else if (result == vk::Result::eSuboptimalKHR) {
734 // swapchain is not as optimal as it could be, but the platform's
735 // presentation engine will still present the image correctly.
736 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600737 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
738 inst.destroySurfaceKHR(surface, nullptr);
739 create_surface();
740 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700741 } else {
742 VERIFY(result == vk::Result::eSuccess);
743 }
744 } while (result != vk::Result::eSuccess);
745
746 update_data_buffer();
747
748 // Wait for the image acquired semaphore to be signaled to ensure
749 // that the image won't be rendered to until the presentation
750 // engine has fully released ownership to the application, and it is
751 // okay to render to the image.
752 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
753 auto const submit_info = vk::SubmitInfo()
754 .setPWaitDstStageMask(&pipe_stage_flags)
755 .setWaitSemaphoreCount(1)
756 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
757 .setCommandBufferCount(1)
758 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
759 .setSignalSemaphoreCount(1)
760 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
761
762 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
763 VERIFY(result == vk::Result::eSuccess);
764
765 if (separate_present_queue) {
766 // If we are using separate queues, change image ownership to the
767 // present queue before presenting, waiting for the draw complete
768 // semaphore and signalling the ownership released semaphore when
769 // finished
770 auto const present_submit_info = vk::SubmitInfo()
771 .setPWaitDstStageMask(&pipe_stage_flags)
772 .setWaitSemaphoreCount(1)
773 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
774 .setCommandBufferCount(1)
775 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
776 .setSignalSemaphoreCount(1)
777 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
778
779 result = present_queue.submit(1, &present_submit_info, vk::Fence());
780 VERIFY(result == vk::Result::eSuccess);
781 }
782
783 // If we are using separate queues we have to wait for image ownership,
784 // otherwise wait for draw complete
785 auto const presentInfo = vk::PresentInfoKHR()
786 .setWaitSemaphoreCount(1)
787 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
788 : &draw_complete_semaphores[frame_index])
789 .setSwapchainCount(1)
790 .setPSwapchains(&swapchain)
791 .setPImageIndices(&current_buffer);
792
793 result = present_queue.presentKHR(&presentInfo);
794 frame_index += 1;
795 frame_index %= FRAME_LAG;
796 if (result == vk::Result::eErrorOutOfDateKHR) {
797 // swapchain is out of date (e.g. the window was resized) and
798 // must be recreated:
799 resize();
800 } else if (result == vk::Result::eSuboptimalKHR) {
801 // swapchain is not as optimal as it could be, but the platform's
802 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600803 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
804 inst.destroySurfaceKHR(surface, nullptr);
805 create_surface();
806 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700807 } else {
808 VERIFY(result == vk::Result::eSuccess);
809 }
810}
811
812void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
813 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
814
815 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
816 vk::ClearDepthStencilValue(1.0f, 0u)};
817
818 auto const passInfo = vk::RenderPassBeginInfo()
819 .setRenderPass(render_pass)
820 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
821 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
822 .setClearValueCount(2)
823 .setPClearValues(clearValues);
824
825 auto result = commandBuffer.begin(&commandInfo);
826 VERIFY(result == vk::Result::eSuccess);
827
828 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
829 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
830 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
831 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700832 float viewport_dimension;
833 float viewport_x = 0.0f;
834 float viewport_y = 0.0f;
835 if (width < height) {
836 viewport_dimension = (float)width;
837 viewport_y = (height - width) / 2.0f;
838 } else {
839 viewport_dimension = (float)height;
840 viewport_x = (width - height) / 2.0f;
841 }
842 auto const viewport = vk::Viewport()
843 .setX(viewport_x)
844 .setY(viewport_y)
845 .setWidth((float)viewport_dimension)
846 .setHeight((float)viewport_dimension)
847 .setMinDepth((float)0.0f)
848 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700849 commandBuffer.setViewport(0, 1, &viewport);
850
851 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
852 commandBuffer.setScissor(0, 1, &scissor);
853 commandBuffer.draw(12 * 3, 1, 0, 0);
854 // Note that ending the renderpass changes the image's layout from
855 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
856 commandBuffer.endRenderPass();
857
858 if (separate_present_queue) {
859 // We have to transfer ownership from the graphics queue family to
860 // the
861 // present queue family to be able to present. Note that we don't
862 // have
863 // to transfer from present queue family back to graphics queue
864 // family at
865 // the start of the next frame because we don't care about the
866 // image's
867 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600868 auto const image_ownership_barrier =
869 vk::ImageMemoryBarrier()
870 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600871 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600872 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
873 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
874 .setSrcQueueFamilyIndex(graphics_queue_family_index)
875 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700876 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700877 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600878
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600879 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700880 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600881 }
882
Dave Houlton5fa47912018-02-16 11:02:26 -0700883 result = commandBuffer.end();
884 VERIFY(result == vk::Result::eSuccess);
885}
886
887void Demo::flush_init_cmd() {
888 // TODO: hmm.
889 // This function could get called twice if the texture uses a staging
890 // buffer
891 // In that case the second call should be ignored
892 if (!cmd) {
893 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600894 }
895
Dave Houlton5fa47912018-02-16 11:02:26 -0700896 auto result = cmd.end();
897 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600898
Dave Houlton5fa47912018-02-16 11:02:26 -0700899 auto const fenceInfo = vk::FenceCreateInfo();
900 vk::Fence fence;
901 result = device.createFence(&fenceInfo, nullptr, &fence);
902 VERIFY(result == vk::Result::eSuccess);
903
904 vk::CommandBuffer const commandBuffers[] = {cmd};
905 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
906
907 result = graphics_queue.submit(1, &submitInfo, fence);
908 VERIFY(result == vk::Result::eSuccess);
909
910 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
911 VERIFY(result == vk::Result::eSuccess);
912
913 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
914 device.destroyFence(fence, nullptr);
915
916 cmd = vk::CommandBuffer();
917}
918
919void Demo::init(int argc, char **argv) {
920 vec3 eye = {0.0f, 3.0f, 5.0f};
921 vec3 origin = {0, 0, 0};
922 vec3 up = {0.0f, 1.0f, 0.0};
923
924 presentMode = vk::PresentModeKHR::eFifo;
925 frameCount = UINT32_MAX;
926 use_xlib = false;
Tony-LunarG50e737c2020-07-16 14:26:03 -0600927 /* For cube demo we just grab the first physical device by default */
928 gpu_number = 0;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600929
Dave Houlton5fa47912018-02-16 11:02:26 -0700930 for (int i = 1; i < argc; i++) {
931 if (strcmp(argv[i], "--use_staging") == 0) {
932 use_staging_buffer = true;
933 continue;
934 }
935 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
936 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
937 i++;
938 continue;
939 }
940 if (strcmp(argv[i], "--break") == 0) {
941 use_break = true;
942 continue;
943 }
944 if (strcmp(argv[i], "--validate") == 0) {
945 validate = true;
946 continue;
947 }
948 if (strcmp(argv[i], "--xlib") == 0) {
949 fprintf(stderr, "--xlib is deprecated and no longer does anything");
950 continue;
951 }
952 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
953 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
954 i++;
955 continue;
956 }
957 if (strcmp(argv[i], "--suppress_popups") == 0) {
958 suppress_popups = true;
959 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600960 }
Tony-LunarG50e737c2020-07-16 14:26:03 -0600961 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
962 gpu_number = atoi(argv[i + 1]);
963 i++;
964 continue;
965 }
Tony-LunarGd74734f2019-06-04 14:11:43 -0600966 std::stringstream usage;
967 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
968 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -0600969 << "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -0600970 << "\t[--present_mode <present mode enum>]\n"
971 << "\t<present_mode_enum>\n"
972 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
973 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
974 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
975 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
976
977#if defined(_WIN32)
978 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
979#else
980 std::cerr << usage.str();
981 std::cerr.flush();
982#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700983 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600984 }
985
Dave Houlton5fa47912018-02-16 11:02:26 -0700986 if (!use_xlib) {
987 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600988 }
989
Dave Houlton5fa47912018-02-16 11:02:26 -0700990 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600991
Dave Houlton5fa47912018-02-16 11:02:26 -0700992 width = 500;
993 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600994
Dave Houlton5fa47912018-02-16 11:02:26 -0700995 spin_angle = 4.0f;
996 spin_increment = 0.2f;
997 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600998
Dave Houlton5fa47912018-02-16 11:02:26 -0700999 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1000 mat4x4_look_at(view_matrix, eye, origin, up);
1001 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001002
Dave Houlton5fa47912018-02-16 11:02:26 -07001003 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1004}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001005
Dave Houlton5fa47912018-02-16 11:02:26 -07001006void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001007#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001008 const xcb_setup_t *setup;
1009 xcb_screen_iterator_t iter;
1010 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001011
Dave Houlton5fa47912018-02-16 11:02:26 -07001012 const char *display_envar = getenv("DISPLAY");
1013 if (display_envar == nullptr || display_envar[0] == '\0') {
1014 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1015 fflush(stdout);
1016 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001017 }
1018
Dave Houlton5fa47912018-02-16 11:02:26 -07001019 connection = xcb_connect(nullptr, &scr);
1020 if (xcb_connection_has_error(connection) > 0) {
1021 printf(
1022 "Cannot find a compatible Vulkan installable client driver "
1023 "(ICD).\nExiting ...\n");
1024 fflush(stdout);
1025 exit(1);
1026 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001027
Dave Houlton5fa47912018-02-16 11:02:26 -07001028 setup = xcb_get_setup(connection);
1029 iter = xcb_setup_roots_iterator(setup);
1030 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001031
Dave Houlton5fa47912018-02-16 11:02:26 -07001032 screen = iter.data;
1033#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1034 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001035
Dave Houlton5fa47912018-02-16 11:02:26 -07001036 if (display == nullptr) {
1037 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1038 fflush(stdout);
1039 exit(1);
1040 }
1041
1042 registry = wl_display_get_registry(display);
1043 wl_registry_add_listener(registry, &registry_listener, this);
1044 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001045#endif
1046}
1047
1048void Demo::init_vk() {
1049 uint32_t instance_extension_count = 0;
1050 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001051 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001052 enabled_extension_count = 0;
1053 enabled_layer_count = 0;
1054
Dave Houlton5fa47912018-02-16 11:02:26 -07001055 // Look for validation layers
1056 vk::Bool32 validation_found = VK_FALSE;
1057 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001058 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001059 VERIFY(result == vk::Result::eSuccess);
1060
Dave Houlton5fa47912018-02-16 11:02:26 -07001061 if (instance_layer_count > 0) {
1062 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1063 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001064 VERIFY(result == vk::Result::eSuccess);
1065
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001066 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001067 instance_layer_count, instance_layers.get());
1068 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001069 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1070 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
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 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001075 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001076 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1077 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001078 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001079 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001080 }
1081
Dave Houlton5fa47912018-02-16 11:02:26 -07001082 /* Look for instance extensions */
1083 vk::Bool32 surfaceExtFound = VK_FALSE;
1084 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1085 memset(extension_names, 0, sizeof(extension_names));
1086
Mike Schuchardt7510c832018-10-29 13:23:08 -07001087 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1088 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001089 VERIFY(result == vk::Result::eSuccess);
1090
1091 if (instance_extension_count > 0) {
1092 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1093 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1094 VERIFY(result == vk::Result::eSuccess);
1095
1096 for (uint32_t i = 0; i < instance_extension_count; i++) {
1097 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1098 surfaceExtFound = 1;
1099 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1100 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001101#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001102 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1103 platformSurfaceExtFound = 1;
1104 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1105 }
1106#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1107 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1108 platformSurfaceExtFound = 1;
1109 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1110 }
1111#elif defined(VK_USE_PLATFORM_XCB_KHR)
1112 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1113 platformSurfaceExtFound = 1;
1114 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1115 }
Tony Barbour153cb062016-12-07 13:43:36 -07001116#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001117 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1118 platformSurfaceExtFound = 1;
1119 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1120 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001121#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1122 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1123 platformSurfaceExtFound = 1;
1124 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1125 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001126#elif defined(VK_USE_PLATFORM_METAL_EXT)
1127 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001128 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001129 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001130 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001131
Dave Houlton5fa47912018-02-16 11:02:26 -07001132#endif
1133 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001134 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001135 }
1136
1137 if (!surfaceExtFound) {
1138 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1139 " extension.\n\n"
1140 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1141 "Please look at the Getting Started guide for additional information.\n",
1142 "vkCreateInstance Failure");
1143 }
1144
1145 if (!platformSurfaceExtFound) {
1146#if defined(VK_USE_PLATFORM_WIN32_KHR)
1147 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1148 " extension.\n\n"
1149 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1150 "Please look at the Getting Started guide for additional information.\n",
1151 "vkCreateInstance Failure");
1152#elif defined(VK_USE_PLATFORM_XCB_KHR)
1153 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1154 " extension.\n\n"
1155 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1156 "Please look at the Getting Started guide for additional information.\n",
1157 "vkCreateInstance Failure");
1158#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1159 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1160 " extension.\n\n"
1161 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1162 "Please look at the Getting Started guide for additional information.\n",
1163 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001164#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001165 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1166 " extension.\n\n"
1167 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1168 "Please look at the Getting Started guide for additional information.\n",
1169 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001170#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001171 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1172 " extension.\n\n"
1173 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1174 "Please look at the Getting Started guide for additional information.\n",
1175 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001176#elif defined(VK_USE_PLATFORM_METAL_EXT)
1177 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001178 " extension.\n\nDo you have a compatible "
1179 "Vulkan installable client driver (ICD) installed?\nPlease "
1180 "look at the Getting Started guide for additional "
1181 "information.\n",
1182 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001183#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001184 }
1185 auto const app = vk::ApplicationInfo()
1186 .setPApplicationName(APP_SHORT_NAME)
1187 .setApplicationVersion(0)
1188 .setPEngineName(APP_SHORT_NAME)
1189 .setEngineVersion(0)
1190 .setApiVersion(VK_API_VERSION_1_0);
1191 auto const inst_info = vk::InstanceCreateInfo()
1192 .setPApplicationInfo(&app)
1193 .setEnabledLayerCount(enabled_layer_count)
1194 .setPpEnabledLayerNames(instance_validation_layers)
1195 .setEnabledExtensionCount(enabled_extension_count)
1196 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001197
Dave Houlton5fa47912018-02-16 11:02:26 -07001198 result = vk::createInstance(&inst_info, nullptr, &inst);
1199 if (result == vk::Result::eErrorIncompatibleDriver) {
1200 ERR_EXIT(
1201 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1202 "Please look at the Getting Started guide for additional information.\n",
1203 "vkCreateInstance Failure");
1204 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1205 ERR_EXIT(
1206 "Cannot find a specified extension library.\n"
1207 "Make sure your layers path is set appropriately.\n",
1208 "vkCreateInstance Failure");
1209 } else if (result != vk::Result::eSuccess) {
1210 ERR_EXIT(
1211 "vkCreateInstance failed.\n\n"
1212 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1213 "Please look at the Getting Started guide for additional information.\n",
1214 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001215 }
1216
Dave Houlton5fa47912018-02-16 11:02:26 -07001217 /* Make initial call to query gpu_count, then second call for gpu info*/
1218 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001219 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001220 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001221
1222 if (gpu_count > 0) {
1223 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1224 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001225 VERIFY(result == vk::Result::eSuccess);
Tony-LunarG50e737c2020-07-16 14:26:03 -06001226 if (gpu_number > gpu_count - 1) {
1227 fprintf(stderr, "Gpu %u specified is not present, gpu count = %u\n", gpu_number, gpu_count);
1228 fprintf(stderr, "Continuing with gpu 0\n");
1229 gpu_number = 0;
1230 }
1231 gpu = physical_devices[gpu_number];
Dave Houlton5fa47912018-02-16 11:02:26 -07001232 } else {
1233 ERR_EXIT(
1234 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1235 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1236 "Please look at the Getting Started guide for additional information.\n",
1237 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001238 }
1239
Dave Houlton5fa47912018-02-16 11:02:26 -07001240 /* Look for device extensions */
1241 uint32_t device_extension_count = 0;
1242 vk::Bool32 swapchainExtFound = VK_FALSE;
1243 enabled_extension_count = 0;
1244 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001245
Mike Schuchardt7510c832018-10-29 13:23:08 -07001246 result =
1247 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001248 VERIFY(result == vk::Result::eSuccess);
1249
1250 if (device_extension_count > 0) {
1251 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1252 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001253 VERIFY(result == vk::Result::eSuccess);
1254
Dave Houlton5fa47912018-02-16 11:02:26 -07001255 for (uint32_t i = 0; i < device_extension_count; i++) {
1256 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1257 swapchainExtFound = 1;
1258 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001259 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001260 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001261 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001262 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001263
Dave Houlton5fa47912018-02-16 11:02:26 -07001264 if (!swapchainExtFound) {
1265 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1266 " extension.\n\n"
1267 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1268 "Please look at the Getting Started guide for additional information.\n",
1269 "vkCreateInstance Failure");
1270 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001271
Dave Houlton5fa47912018-02-16 11:02:26 -07001272 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001273
Dave Houlton5fa47912018-02-16 11:02:26 -07001274 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001275 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001276 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001277
Dave Houlton5fa47912018-02-16 11:02:26 -07001278 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1279 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001280
Dave Houlton5fa47912018-02-16 11:02:26 -07001281 // Query fine-grained feature support for this device.
1282 // If app has specific feature requirements it should check supported
1283 // features based on this query
1284 vk::PhysicalDeviceFeatures physDevFeatures;
1285 gpu.getFeatures(&physDevFeatures);
1286}
1287
Tony-LunarG6cebf142019-09-11 14:32:23 -06001288void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001289// Create a WSI surface for the window:
1290#if defined(VK_USE_PLATFORM_WIN32_KHR)
1291 {
1292 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1293
1294 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1295 VERIFY(result == vk::Result::eSuccess);
1296 }
1297#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1298 {
1299 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1300
1301 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1302 VERIFY(result == vk::Result::eSuccess);
1303 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001304#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1305 {
1306 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1307
1308 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1309 VERIFY(result == vk::Result::eSuccess);
1310 }
1311#elif defined(VK_USE_PLATFORM_XCB_KHR)
1312 {
1313 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1314
1315 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1316 VERIFY(result == vk::Result::eSuccess);
1317 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001318#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001319 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001320 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001321
Bill Hollings0a0625a2019-07-15 17:39:18 -04001322 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001323 VERIFY(result == vk::Result::eSuccess);
1324 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001325#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1326 {
1327 auto result = create_display_surface();
1328 VERIFY(result == vk::Result::eSuccess);
1329 }
1330#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001331}
1332
1333void Demo::init_vk_swapchain() {
1334 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001335 // Iterate over each queue to learn whether it supports presenting:
1336 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1337 for (uint32_t i = 0; i < queue_family_count; i++) {
1338 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1339 }
1340
1341 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1342 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1343 for (uint32_t i = 0; i < queue_family_count; i++) {
1344 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1345 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1346 graphicsQueueFamilyIndex = i;
1347 }
1348
1349 if (supportsPresent[i] == VK_TRUE) {
1350 graphicsQueueFamilyIndex = i;
1351 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001352 break;
1353 }
1354 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001355 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001356
Dave Houlton5fa47912018-02-16 11:02:26 -07001357 if (presentQueueFamilyIndex == UINT32_MAX) {
1358 // If didn't find a queue that supports both graphics and present,
1359 // then
1360 // find a separate present queue.
1361 for (uint32_t i = 0; i < queue_family_count; ++i) {
1362 if (supportsPresent[i] == VK_TRUE) {
1363 presentQueueFamilyIndex = i;
1364 break;
1365 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001366 }
1367 }
1368
Dave Houlton5fa47912018-02-16 11:02:26 -07001369 // Generate error if could not find both a graphics and a present queue
1370 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1371 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1372 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001373
Dave Houlton5fa47912018-02-16 11:02:26 -07001374 graphics_queue_family_index = graphicsQueueFamilyIndex;
1375 present_queue_family_index = presentQueueFamilyIndex;
1376 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001377
Dave Houlton5fa47912018-02-16 11:02:26 -07001378 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001379
Dave Houlton5fa47912018-02-16 11:02:26 -07001380 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1381 if (!separate_present_queue) {
1382 present_queue = graphics_queue;
1383 } else {
1384 device.getQueue(present_queue_family_index, 0, &present_queue);
1385 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001386
Dave Houlton5fa47912018-02-16 11:02:26 -07001387 // Get the list of VkFormat's that are supported:
1388 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001389 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001390 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001391
Dave Houlton5fa47912018-02-16 11:02:26 -07001392 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1393 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1394 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001395
Dave Houlton5fa47912018-02-16 11:02:26 -07001396 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1397 // the surface has no preferred format. Otherwise, at least one
1398 // supported format will be returned.
1399 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1400 format = vk::Format::eB8G8R8A8Unorm;
1401 } else {
1402 assert(formatCount >= 1);
1403 format = surfFormats[0].format;
1404 }
1405 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001406
Dave Houlton5fa47912018-02-16 11:02:26 -07001407 quit = false;
1408 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001409
Dave Houlton5fa47912018-02-16 11:02:26 -07001410 // Create semaphores to synchronize acquiring presentable buffers before
1411 // rendering and waiting for drawing to be complete before presenting
1412 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001413
Dave Houlton5fa47912018-02-16 11:02:26 -07001414 // Create fences that we can use to throttle if we get too far
1415 // ahead of the image presents
1416 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1417 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1418 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1419 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001420
Dave Houlton5fa47912018-02-16 11:02:26 -07001421 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1422 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001423
Dave Houlton5fa47912018-02-16 11:02:26 -07001424 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1425 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001426
Dave Houlton5fa47912018-02-16 11:02:26 -07001427 if (separate_present_queue) {
1428 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001429 VERIFY(result == vk::Result::eSuccess);
1430 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001431 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001432 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001433
Dave Houlton5fa47912018-02-16 11:02:26 -07001434 // Get Memory information and properties
1435 gpu.getMemoryProperties(&memory_properties);
1436}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001437
Dave Houlton5fa47912018-02-16 11:02:26 -07001438void Demo::prepare() {
1439 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1440 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1441 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001442
Dave Houlton5fa47912018-02-16 11:02:26 -07001443 auto const cmd = vk::CommandBufferAllocateInfo()
1444 .setCommandPool(cmd_pool)
1445 .setLevel(vk::CommandBufferLevel::ePrimary)
1446 .setCommandBufferCount(1);
1447
1448 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1449 VERIFY(result == vk::Result::eSuccess);
1450
1451 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1452
1453 result = this->cmd.begin(&cmd_buf_info);
1454 VERIFY(result == vk::Result::eSuccess);
1455
1456 prepare_buffers();
1457 prepare_depth();
1458 prepare_textures();
1459 prepare_cube_data_buffers();
1460
1461 prepare_descriptor_layout();
1462 prepare_render_pass();
1463 prepare_pipeline();
1464
1465 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1466 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1467 VERIFY(result == vk::Result::eSuccess);
1468 }
1469
1470 if (separate_present_queue) {
1471 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1472
1473 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1474 VERIFY(result == vk::Result::eSuccess);
1475
1476 auto const present_cmd = vk::CommandBufferAllocateInfo()
1477 .setCommandPool(present_cmd_pool)
1478 .setLevel(vk::CommandBufferLevel::ePrimary)
1479 .setCommandBufferCount(1);
1480
1481 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1482 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1483 VERIFY(result == vk::Result::eSuccess);
1484
1485 build_image_ownership_cmd(i);
1486 }
1487 }
1488
1489 prepare_descriptor_pool();
1490 prepare_descriptor_set();
1491
1492 prepare_framebuffers();
1493
1494 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1495 current_buffer = i;
1496 draw_build_cmd(swapchain_image_resources[i].cmd);
1497 }
1498
1499 /*
1500 * Prepare functions above may generate pipeline commands
1501 * that need to be flushed before beginning the render loop.
1502 */
1503 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001504 if (staging_texture.buffer) {
1505 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001506 }
1507
1508 current_buffer = 0;
1509 prepared = true;
1510}
1511
1512void Demo::prepare_buffers() {
1513 vk::SwapchainKHR oldSwapchain = swapchain;
1514
1515 // Check the surface capabilities and formats
1516 vk::SurfaceCapabilitiesKHR surfCapabilities;
1517 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1518 VERIFY(result == vk::Result::eSuccess);
1519
1520 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001521 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001522 VERIFY(result == vk::Result::eSuccess);
1523
1524 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1525 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1526 VERIFY(result == vk::Result::eSuccess);
1527
1528 vk::Extent2D swapchainExtent;
1529 // width and height are either both -1, or both not -1.
1530 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1531 // If the surface size is undefined, the size is set to
1532 // the size of the images requested.
1533 swapchainExtent.width = width;
1534 swapchainExtent.height = height;
1535 } else {
1536 // If the surface size is defined, the swap chain size must match
1537 swapchainExtent = surfCapabilities.currentExtent;
1538 width = surfCapabilities.currentExtent.width;
1539 height = surfCapabilities.currentExtent.height;
1540 }
1541
1542 // The FIFO present mode is guaranteed by the spec to be supported
1543 // and to have no tearing. It's a great default present mode to use.
1544 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1545
1546 // There are times when you may wish to use another present mode. The
1547 // following code shows how to select them, and the comments provide some
1548 // reasons you may wish to use them.
1549 //
1550 // It should be noted that Vulkan 1.0 doesn't provide a method for
1551 // synchronizing rendering with the presentation engine's display. There
1552 // is a method provided for throttling rendering with the display, but
1553 // there are some presentation engines for which this method will not work.
1554 // If an application doesn't throttle its rendering, and if it renders much
1555 // faster than the refresh rate of the display, this can waste power on
1556 // mobile devices. That is because power is being spent rendering images
1557 // that may never be seen.
1558
1559 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1560 // about
1561 // tearing, or have some way of synchronizing their rendering with the
1562 // display.
1563 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1564 // generally render a new presentable image every refresh cycle, but are
1565 // occasionally early. In this case, the application wants the new
1566 // image
1567 // to be displayed instead of the previously-queued-for-presentation
1568 // image
1569 // that has not yet been displayed.
1570 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1571 // render a new presentable image every refresh cycle, but are
1572 // occasionally
1573 // late. In this case (perhaps because of stuttering/latency concerns),
1574 // the application wants the late image to be immediately displayed,
1575 // even
1576 // though that may mean some tearing.
1577
1578 if (presentMode != swapchainPresentMode) {
1579 for (size_t i = 0; i < presentModeCount; ++i) {
1580 if (presentModes[i] == presentMode) {
1581 swapchainPresentMode = presentMode;
1582 break;
1583 }
1584 }
1585 }
1586
1587 if (swapchainPresentMode != presentMode) {
1588 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1589 }
1590
1591 // Determine the number of VkImages to use in the swap chain.
1592 // Application desires to acquire 3 images at a time for triple
1593 // buffering
1594 uint32_t desiredNumOfSwapchainImages = 3;
1595 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1596 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1597 }
1598
1599 // If maxImageCount is 0, we can ask for as many images as we want,
1600 // otherwise
1601 // we're limited to maxImageCount
1602 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1603 // Application must settle for fewer images than desired:
1604 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1605 }
1606
1607 vk::SurfaceTransformFlagBitsKHR preTransform;
1608 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1609 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1610 } else {
1611 preTransform = surfCapabilities.currentTransform;
1612 }
1613
1614 // Find a supported composite alpha mode - one of these is guaranteed to be set
1615 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1616 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1617 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1618 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1619 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1620 vk::CompositeAlphaFlagBitsKHR::eInherit,
1621 };
1622 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1623 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1624 compositeAlpha = compositeAlphaFlags[i];
1625 break;
1626 }
1627 }
1628
1629 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1630 .setSurface(surface)
1631 .setMinImageCount(desiredNumOfSwapchainImages)
1632 .setImageFormat(format)
1633 .setImageColorSpace(color_space)
1634 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1635 .setImageArrayLayers(1)
1636 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1637 .setImageSharingMode(vk::SharingMode::eExclusive)
1638 .setQueueFamilyIndexCount(0)
1639 .setPQueueFamilyIndices(nullptr)
1640 .setPreTransform(preTransform)
1641 .setCompositeAlpha(compositeAlpha)
1642 .setPresentMode(swapchainPresentMode)
1643 .setClipped(true)
1644 .setOldSwapchain(oldSwapchain);
1645
1646 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1647 VERIFY(result == vk::Result::eSuccess);
1648
1649 // If we just re-created an existing swapchain, we should destroy the
1650 // old
1651 // swapchain at this point.
1652 // Note: destroying the swapchain also cleans up all its associated
1653 // presentable images once the platform is done with them.
1654 if (oldSwapchain) {
1655 device.destroySwapchainKHR(oldSwapchain, nullptr);
1656 }
1657
Mike Schuchardt7510c832018-10-29 13:23:08 -07001658 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001659 VERIFY(result == vk::Result::eSuccess);
1660
1661 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1662 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1663 VERIFY(result == vk::Result::eSuccess);
1664
1665 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1666
1667 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1668 auto color_image_view = vk::ImageViewCreateInfo()
1669 .setViewType(vk::ImageViewType::e2D)
1670 .setFormat(format)
1671 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1672
1673 swapchain_image_resources[i].image = swapchainImages[i];
1674
1675 color_image_view.image = swapchain_image_resources[i].image;
1676
1677 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1678 VERIFY(result == vk::Result::eSuccess);
1679 }
1680}
1681
1682void Demo::prepare_cube_data_buffers() {
1683 mat4x4 VP;
1684 mat4x4_mul(VP, projection_matrix, view_matrix);
1685
1686 mat4x4 MVP;
1687 mat4x4_mul(MVP, VP, model_matrix);
1688
1689 vktexcube_vs_uniform data;
1690 memcpy(data.mvp, MVP, sizeof(MVP));
1691 // dumpMatrix("MVP", MVP)
1692
1693 for (int32_t i = 0; i < 12 * 3; i++) {
1694 data.position[i][0] = g_vertex_buffer_data[i * 3];
1695 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1696 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1697 data.position[i][3] = 1.0f;
1698 data.attr[i][0] = g_uv_buffer_data[2 * i];
1699 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1700 data.attr[i][2] = 0;
1701 data.attr[i][3] = 0;
1702 }
1703
1704 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1705
1706 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1707 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001708 VERIFY(result == vk::Result::eSuccess);
1709
1710 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001711 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001712
Dave Houlton5fa47912018-02-16 11:02:26 -07001713 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001714
Dave Houlton5fa47912018-02-16 11:02:26 -07001715 bool const pass = memory_type_from_properties(
1716 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1717 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001718 VERIFY(pass);
1719
Dave Houlton5fa47912018-02-16 11:02:26 -07001720 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001721 VERIFY(result == vk::Result::eSuccess);
1722
Tony-LunarG37af49f2019-12-19 12:04:19 -07001723 result = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags(),
1724 &swapchain_image_resources[i].uniform_memory_ptr);
1725 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001726
Tony-LunarG37af49f2019-12-19 12:04:19 -07001727 memcpy(swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Dave Houlton5fa47912018-02-16 11:02:26 -07001728
1729 result =
1730 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001731 VERIFY(result == vk::Result::eSuccess);
1732 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001733}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001734
Dave Houlton5fa47912018-02-16 11:02:26 -07001735void Demo::prepare_depth() {
1736 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001737
Dave Houlton5fa47912018-02-16 11:02:26 -07001738 auto const image = vk::ImageCreateInfo()
1739 .setImageType(vk::ImageType::e2D)
1740 .setFormat(depth.format)
1741 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1742 .setMipLevels(1)
1743 .setArrayLayers(1)
1744 .setSamples(vk::SampleCountFlagBits::e1)
1745 .setTiling(vk::ImageTiling::eOptimal)
1746 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1747 .setSharingMode(vk::SharingMode::eExclusive)
1748 .setQueueFamilyIndexCount(0)
1749 .setPQueueFamilyIndices(nullptr)
1750 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001751
Dave Houlton5fa47912018-02-16 11:02:26 -07001752 auto result = device.createImage(&image, nullptr, &depth.image);
1753 VERIFY(result == vk::Result::eSuccess);
1754
1755 vk::MemoryRequirements mem_reqs;
1756 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1757
1758 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1759 depth.mem_alloc.setMemoryTypeIndex(0);
1760
1761 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1762 &depth.mem_alloc.memoryTypeIndex);
1763 VERIFY(pass);
1764
1765 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1766 VERIFY(result == vk::Result::eSuccess);
1767
1768 result = device.bindImageMemory(depth.image, depth.mem, 0);
1769 VERIFY(result == vk::Result::eSuccess);
1770
1771 auto const view = vk::ImageViewCreateInfo()
1772 .setImage(depth.image)
1773 .setViewType(vk::ImageViewType::e2D)
1774 .setFormat(depth.format)
1775 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1776 result = device.createImageView(&view, nullptr, &depth.view);
1777 VERIFY(result == vk::Result::eSuccess);
1778}
1779
1780void Demo::prepare_descriptor_layout() {
1781 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1782 .setBinding(0)
1783 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1784 .setDescriptorCount(1)
1785 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1786 .setPImmutableSamplers(nullptr),
1787 vk::DescriptorSetLayoutBinding()
1788 .setBinding(1)
1789 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1790 .setDescriptorCount(texture_count)
1791 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1792 .setPImmutableSamplers(nullptr)};
1793
1794 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1795
1796 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1797 VERIFY(result == vk::Result::eSuccess);
1798
1799 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1800
1801 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1802 VERIFY(result == vk::Result::eSuccess);
1803}
1804
1805void Demo::prepare_descriptor_pool() {
1806 vk::DescriptorPoolSize const poolSizes[2] = {
1807 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1808 vk::DescriptorPoolSize()
1809 .setType(vk::DescriptorType::eCombinedImageSampler)
1810 .setDescriptorCount(swapchainImageCount * texture_count)};
1811
1812 auto const descriptor_pool =
1813 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1814
1815 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1816 VERIFY(result == vk::Result::eSuccess);
1817}
1818
1819void Demo::prepare_descriptor_set() {
1820 auto const alloc_info =
1821 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1822
1823 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1824
1825 vk::DescriptorImageInfo tex_descs[texture_count];
1826 for (uint32_t i = 0; i < texture_count; i++) {
1827 tex_descs[i].setSampler(textures[i].sampler);
1828 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001829 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001830 }
1831
1832 vk::WriteDescriptorSet writes[2];
1833
1834 writes[0].setDescriptorCount(1);
1835 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1836 writes[0].setPBufferInfo(&buffer_info);
1837
1838 writes[1].setDstBinding(1);
1839 writes[1].setDescriptorCount(texture_count);
1840 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1841 writes[1].setPImageInfo(tex_descs);
1842
1843 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1844 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001845 VERIFY(result == vk::Result::eSuccess);
1846
Dave Houlton5fa47912018-02-16 11:02:26 -07001847 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1848 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1849 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1850 device.updateDescriptorSets(2, writes, 0, nullptr);
1851 }
1852}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001853
Dave Houlton5fa47912018-02-16 11:02:26 -07001854void Demo::prepare_framebuffers() {
1855 vk::ImageView attachments[2];
1856 attachments[1] = depth.view;
1857
1858 auto const fb_info = vk::FramebufferCreateInfo()
1859 .setRenderPass(render_pass)
1860 .setAttachmentCount(2)
1861 .setPAttachments(attachments)
1862 .setWidth((uint32_t)width)
1863 .setHeight((uint32_t)height)
1864 .setLayers(1);
1865
1866 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1867 attachments[0] = swapchain_image_resources[i].view;
1868 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001869 VERIFY(result == vk::Result::eSuccess);
1870 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001871}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001872
Dave Houlton5fa47912018-02-16 11:02:26 -07001873vk::ShaderModule Demo::prepare_fs() {
1874 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001875#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001876 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001877
Dave Houlton5fa47912018-02-16 11:02:26 -07001878 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001879
Dave Houlton5fa47912018-02-16 11:02:26 -07001880 return frag_shader_module;
1881}
1882
1883void Demo::prepare_pipeline() {
1884 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1885 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1886 VERIFY(result == vk::Result::eSuccess);
1887
1888 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1889 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1890 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1891
1892 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1893
1894 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1895
1896 // TODO: Where are pViewports and pScissors set?
1897 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1898
1899 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1900 .setDepthClampEnable(VK_FALSE)
1901 .setRasterizerDiscardEnable(VK_FALSE)
1902 .setPolygonMode(vk::PolygonMode::eFill)
1903 .setCullMode(vk::CullModeFlagBits::eBack)
1904 .setFrontFace(vk::FrontFace::eCounterClockwise)
1905 .setDepthBiasEnable(VK_FALSE)
1906 .setLineWidth(1.0f);
1907
1908 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1909
1910 auto const stencilOp =
1911 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1912
1913 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1914 .setDepthTestEnable(VK_TRUE)
1915 .setDepthWriteEnable(VK_TRUE)
1916 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1917 .setDepthBoundsTestEnable(VK_FALSE)
1918 .setStencilTestEnable(VK_FALSE)
1919 .setFront(stencilOp)
1920 .setBack(stencilOp);
1921
1922 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1923 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1924 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1925
1926 auto const colorBlendInfo =
1927 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1928
1929 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1930
1931 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1932
1933 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1934 .setStageCount(2)
1935 .setPStages(shaderStageInfo)
1936 .setPVertexInputState(&vertexInputInfo)
1937 .setPInputAssemblyState(&inputAssemblyInfo)
1938 .setPViewportState(&viewportInfo)
1939 .setPRasterizationState(&rasterizationInfo)
1940 .setPMultisampleState(&multisampleInfo)
1941 .setPDepthStencilState(&depthStencilInfo)
1942 .setPColorBlendState(&colorBlendInfo)
1943 .setPDynamicState(&dynamicStateInfo)
1944 .setLayout(pipeline_layout)
1945 .setRenderPass(render_pass);
1946
1947 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1948 VERIFY(result == vk::Result::eSuccess);
1949
1950 device.destroyShaderModule(frag_shader_module, nullptr);
1951 device.destroyShaderModule(vert_shader_module, nullptr);
1952}
1953
1954void Demo::prepare_render_pass() {
1955 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1956 // because at the start of the renderpass, we don't care about their contents.
1957 // At the start of the subpass, the color attachment's layout will be transitioned
1958 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1959 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1960 // the renderpass, the color attachment's layout will be transitioned to
1961 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1962 // the renderpass, no barriers are necessary.
1963 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1964 .setFormat(format)
1965 .setSamples(vk::SampleCountFlagBits::e1)
1966 .setLoadOp(vk::AttachmentLoadOp::eClear)
1967 .setStoreOp(vk::AttachmentStoreOp::eStore)
1968 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1969 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1970 .setInitialLayout(vk::ImageLayout::eUndefined)
1971 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1972 vk::AttachmentDescription()
1973 .setFormat(depth.format)
1974 .setSamples(vk::SampleCountFlagBits::e1)
1975 .setLoadOp(vk::AttachmentLoadOp::eClear)
1976 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1977 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1978 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1979 .setInitialLayout(vk::ImageLayout::eUndefined)
1980 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1981
1982 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1983
1984 auto const depth_reference =
1985 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1986
1987 auto const subpass = vk::SubpassDescription()
1988 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1989 .setInputAttachmentCount(0)
1990 .setPInputAttachments(nullptr)
1991 .setColorAttachmentCount(1)
1992 .setPColorAttachments(&color_reference)
1993 .setPResolveAttachments(nullptr)
1994 .setPDepthStencilAttachment(&depth_reference)
1995 .setPreserveAttachmentCount(0)
1996 .setPPreserveAttachments(nullptr);
1997
Tony-LunarG495604b2019-06-13 15:32:05 -06001998 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
1999 vk::SubpassDependency const dependencies[2] = {
2000 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2001 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2002 .setDstSubpass(0)
2003 .setSrcStageMask(stages)
2004 .setDstStageMask(stages)
2005 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2006 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2007 .setDependencyFlags(vk::DependencyFlags()),
2008 vk::SubpassDependency() // Image layout transition
2009 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2010 .setDstSubpass(0)
2011 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2012 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2013 .setSrcAccessMask(vk::AccessFlagBits())
2014 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2015 .setDependencyFlags(vk::DependencyFlags()),
2016 };
2017
Dave Houlton5fa47912018-02-16 11:02:26 -07002018 auto const rp_info = vk::RenderPassCreateInfo()
2019 .setAttachmentCount(2)
2020 .setPAttachments(attachments)
2021 .setSubpassCount(1)
2022 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002023 .setDependencyCount(2)
2024 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002025
2026 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2027 VERIFY(result == vk::Result::eSuccess);
2028}
2029
2030vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2031 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2032
2033 vk::ShaderModule module;
2034 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2035 VERIFY(result == vk::Result::eSuccess);
2036
2037 return module;
2038}
2039
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002040void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2041 int32_t tex_width;
2042 int32_t tex_height;
2043
2044 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2045 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2046 }
2047
2048 tex_obj->tex_width = tex_width;
2049 tex_obj->tex_height = tex_height;
2050
2051 auto const buffer_create_info = vk::BufferCreateInfo()
2052 .setSize(tex_width * tex_height * 4)
2053 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2054 .setSharingMode(vk::SharingMode::eExclusive)
2055 .setQueueFamilyIndexCount(0)
2056 .setPQueueFamilyIndices(nullptr);
2057
2058 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2059 VERIFY(result == vk::Result::eSuccess);
2060
2061 vk::MemoryRequirements mem_reqs;
2062 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2063
2064 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2065 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2066
2067 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2068 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2069 VERIFY(pass == true);
2070
2071 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2072 VERIFY(result == vk::Result::eSuccess);
2073
2074 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2075 VERIFY(result == vk::Result::eSuccess);
2076
2077 vk::SubresourceLayout layout;
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002078 layout.rowPitch = tex_width * 4;
2079 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2080 VERIFY(data.result == vk::Result::eSuccess);
2081
2082 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2083 fprintf(stderr, "Error loading texture: %s\n", filename);
2084 }
2085
2086 device.unmapMemory(tex_obj->mem);
2087}
2088
Dave Houlton5fa47912018-02-16 11:02:26 -07002089void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2090 vk::MemoryPropertyFlags required_props) {
2091 int32_t tex_width;
2092 int32_t tex_height;
2093 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2094 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002095 }
2096
Dave Houlton5fa47912018-02-16 11:02:26 -07002097 tex_obj->tex_width = tex_width;
2098 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002099
Dave Houlton5fa47912018-02-16 11:02:26 -07002100 auto const image_create_info = vk::ImageCreateInfo()
2101 .setImageType(vk::ImageType::e2D)
2102 .setFormat(vk::Format::eR8G8B8A8Unorm)
2103 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2104 .setMipLevels(1)
2105 .setArrayLayers(1)
2106 .setSamples(vk::SampleCountFlagBits::e1)
2107 .setTiling(tiling)
2108 .setUsage(usage)
2109 .setSharingMode(vk::SharingMode::eExclusive)
2110 .setQueueFamilyIndexCount(0)
2111 .setPQueueFamilyIndices(nullptr)
2112 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002113
Dave Houlton5fa47912018-02-16 11:02:26 -07002114 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2115 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002116
Dave Houlton5fa47912018-02-16 11:02:26 -07002117 vk::MemoryRequirements mem_reqs;
2118 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002119
Dave Houlton5fa47912018-02-16 11:02:26 -07002120 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2121 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002122
Dave Houlton5fa47912018-02-16 11:02:26 -07002123 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2124 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002125
Dave Houlton5fa47912018-02-16 11:02:26 -07002126 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2127 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002128
Dave Houlton5fa47912018-02-16 11:02:26 -07002129 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2130 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002131
Dave Houlton5fa47912018-02-16 11:02:26 -07002132 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2133 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2134 vk::SubresourceLayout layout;
2135 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002136
Dave Houlton5fa47912018-02-16 11:02:26 -07002137 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002138 VERIFY(data.result == vk::Result::eSuccess);
2139
Dave Houlton5fa47912018-02-16 11:02:26 -07002140 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2141 fprintf(stderr, "Error loading texture: %s\n", filename);
2142 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002143
Dave Houlton5fa47912018-02-16 11:02:26 -07002144 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002145 }
2146
Dave Houlton5fa47912018-02-16 11:02:26 -07002147 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2148}
2149
2150void Demo::prepare_textures() {
2151 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2152 vk::FormatProperties props;
2153 gpu.getFormatProperties(tex_format, &props);
2154
2155 for (uint32_t i = 0; i < texture_count; i++) {
2156 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2157 /* Device can texture using linear textures */
2158 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2159 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2160 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2161 // shader to run until layout transition completes
2162 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2163 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2164 vk::PipelineStageFlagBits::eFragmentShader);
2165 staging_texture.image = vk::Image();
2166 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2167 /* Must use staging buffer to copy linear texture to optimized */
2168
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002169 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002170
2171 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2172 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2173 vk::MemoryPropertyFlagBits::eDeviceLocal);
2174
Dave Houlton5fa47912018-02-16 11:02:26 -07002175 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2176 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2177 vk::PipelineStageFlagBits::eTransfer);
2178
2179 auto const subresource = vk::ImageSubresourceLayers()
2180 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2181 .setMipLevel(0)
2182 .setBaseArrayLayer(0)
2183 .setLayerCount(1);
2184
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002185 auto const copy_region =
2186 vk::BufferImageCopy()
2187 .setBufferOffset(0)
2188 .setBufferRowLength(staging_texture.tex_width)
2189 .setBufferImageHeight(staging_texture.tex_height)
2190 .setImageSubresource(subresource)
2191 .setImageOffset({0, 0, 0})
2192 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002193
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002194 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002195
2196 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2197 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2198 vk::PipelineStageFlagBits::eFragmentShader);
2199 } else {
2200 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002201 }
2202
Dave Houlton5fa47912018-02-16 11:02:26 -07002203 auto const samplerInfo = vk::SamplerCreateInfo()
2204 .setMagFilter(vk::Filter::eNearest)
2205 .setMinFilter(vk::Filter::eNearest)
2206 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2207 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2208 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2209 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2210 .setMipLodBias(0.0f)
2211 .setAnisotropyEnable(VK_FALSE)
2212 .setMaxAnisotropy(1)
2213 .setCompareEnable(VK_FALSE)
2214 .setCompareOp(vk::CompareOp::eNever)
2215 .setMinLod(0.0f)
2216 .setMaxLod(0.0f)
2217 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2218 .setUnnormalizedCoordinates(VK_FALSE);
2219
2220 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2221 VERIFY(result == vk::Result::eSuccess);
2222
2223 auto const viewInfo = vk::ImageViewCreateInfo()
2224 .setImage(textures[i].image)
2225 .setViewType(vk::ImageViewType::e2D)
2226 .setFormat(tex_format)
2227 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2228
2229 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2230 VERIFY(result == vk::Result::eSuccess);
2231 }
2232}
2233
2234vk::ShaderModule Demo::prepare_vs() {
2235 const uint32_t vertShaderCode[] = {
2236#include "cube.vert.inc"
2237 };
2238
2239 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2240
2241 return vert_shader_module;
2242}
2243
2244void Demo::resize() {
2245 uint32_t i;
2246
2247 // Don't react to resize until after first initialization.
2248 if (!prepared) {
2249 return;
2250 }
2251
2252 // In order to properly resize the window, we must re-create the
2253 // swapchain
2254 // AND redo the command buffers, etc.
2255 //
2256 // First, perform part of the cleanup() function:
2257 prepared = false;
2258 auto result = device.waitIdle();
2259 VERIFY(result == vk::Result::eSuccess);
2260
2261 for (i = 0; i < swapchainImageCount; i++) {
2262 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2263 }
2264
2265 device.destroyDescriptorPool(desc_pool, nullptr);
2266
2267 device.destroyPipeline(pipeline, nullptr);
2268 device.destroyPipelineCache(pipelineCache, nullptr);
2269 device.destroyRenderPass(render_pass, nullptr);
2270 device.destroyPipelineLayout(pipeline_layout, nullptr);
2271 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2272
2273 for (i = 0; i < texture_count; i++) {
2274 device.destroyImageView(textures[i].view, nullptr);
2275 device.destroyImage(textures[i].image, nullptr);
2276 device.freeMemory(textures[i].mem, nullptr);
2277 device.destroySampler(textures[i].sampler, nullptr);
2278 }
2279
2280 device.destroyImageView(depth.view, nullptr);
2281 device.destroyImage(depth.image, nullptr);
2282 device.freeMemory(depth.mem, nullptr);
2283
2284 for (i = 0; i < swapchainImageCount; i++) {
2285 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
Mike Schuchardt7bcbfd32020-05-07 15:33:52 -07002286 device.freeCommandBuffers(cmd_pool, {swapchain_image_resources[i].cmd});
Dave Houlton5fa47912018-02-16 11:02:26 -07002287 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002288 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
Dave Houlton5fa47912018-02-16 11:02:26 -07002289 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2290 }
2291
2292 device.destroyCommandPool(cmd_pool, nullptr);
2293 if (separate_present_queue) {
2294 device.destroyCommandPool(present_cmd_pool, nullptr);
2295 }
2296
2297 // Second, re-perform the prepare() function, which will re-create the
2298 // swapchain.
2299 prepare();
2300}
2301
2302void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2303 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2304 assert(cmd);
2305
2306 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2307 vk::AccessFlags flags;
2308
2309 switch (layout) {
2310 case vk::ImageLayout::eTransferDstOptimal:
2311 // Make sure anything that was copying from this image has
2312 // completed
2313 flags = vk::AccessFlagBits::eTransferWrite;
2314 break;
2315 case vk::ImageLayout::eColorAttachmentOptimal:
2316 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2317 break;
2318 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2319 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2320 break;
2321 case vk::ImageLayout::eShaderReadOnlyOptimal:
2322 // Make sure any Copy or CPU writes to image are flushed
2323 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2324 break;
2325 case vk::ImageLayout::eTransferSrcOptimal:
2326 flags = vk::AccessFlagBits::eTransferRead;
2327 break;
2328 case vk::ImageLayout::ePresentSrcKHR:
2329 flags = vk::AccessFlagBits::eMemoryRead;
2330 break;
2331 default:
2332 break;
2333 }
2334
2335 return flags;
2336 };
2337
2338 auto const barrier = vk::ImageMemoryBarrier()
2339 .setSrcAccessMask(srcAccessMask)
2340 .setDstAccessMask(DstAccessMask(newLayout))
2341 .setOldLayout(oldLayout)
2342 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002343 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2344 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002345 .setImage(image)
2346 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2347
2348 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2349}
2350
2351void Demo::update_data_buffer() {
2352 mat4x4 VP;
2353 mat4x4_mul(VP, projection_matrix, view_matrix);
2354
2355 // Rotate around the Y axis
2356 mat4x4 Model;
2357 mat4x4_dup(Model, model_matrix);
2358 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2359
2360 mat4x4 MVP;
2361 mat4x4_mul(MVP, VP, model_matrix);
2362
Tony-LunarG37af49f2019-12-19 12:04:19 -07002363 memcpy(swapchain_image_resources[current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], sizeof(MVP));
Dave Houlton5fa47912018-02-16 11:02:26 -07002364}
2365
Karl Schultzb7940402018-05-29 13:09:22 -06002366/* Convert ppm image data from header file into RGBA texture image */
2367#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002368bool 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 -06002369 (void)filename;
2370 char *cPtr;
2371 cPtr = (char *)lunarg_ppm;
2372 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002373 return false;
2374 }
Karl Schultzb7940402018-05-29 13:09:22 -06002375 while (strncmp(cPtr++, "\n", 1))
2376 ;
2377 sscanf(cPtr, "%u %u", width, height);
2378 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002379 return true;
2380 }
Karl Schultzb7940402018-05-29 13:09:22 -06002381 while (strncmp(cPtr++, "\n", 1))
2382 ;
2383 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002384 return false;
2385 }
Karl Schultzb7940402018-05-29 13:09:22 -06002386 while (strncmp(cPtr++, "\n", 1))
2387 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002388 for (int y = 0; y < *height; y++) {
2389 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002390 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002391 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002392 rowPtr[3] = 255; /* Alpha of 1 */
2393 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002394 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002395 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002396 rgba_data += layout->rowPitch;
2397 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002398 return true;
2399}
2400
2401bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2402 // Search memtypes to find first index with those properties
2403 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2404 if ((typeBits & 1) == 1) {
2405 // Type is available, does it match user properties?
2406 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2407 *typeIndex = i;
2408 return true;
2409 }
2410 }
2411 typeBits >>= 1;
2412 }
2413
2414 // No memory types matched, return failure
2415 return false;
2416}
2417
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002418#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002419void Demo::run() {
2420 if (!prepared) {
2421 return;
2422 }
2423
2424 draw();
2425 curFrame++;
2426
Petr Krausd88e4e52019-01-23 18:45:04 +01002427 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002428 PostQuitMessage(validation_error);
2429 }
2430}
2431
2432void Demo::create_window() {
2433 WNDCLASSEX win_class;
2434
2435 // Initialize the window class structure:
2436 win_class.cbSize = sizeof(WNDCLASSEX);
2437 win_class.style = CS_HREDRAW | CS_VREDRAW;
2438 win_class.lpfnWndProc = WndProc;
2439 win_class.cbClsExtra = 0;
2440 win_class.cbWndExtra = 0;
2441 win_class.hInstance = connection; // hInstance
2442 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2443 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2444 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2445 win_class.lpszMenuName = nullptr;
2446 win_class.lpszClassName = name;
2447 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2448
2449 // Register window class:
2450 if (!RegisterClassEx(&win_class)) {
2451 // It didn't work, so try to give a useful error:
2452 printf("Unexpected error trying to start the application!\n");
2453 fflush(stdout);
2454 exit(1);
2455 }
2456
2457 // Create window with the registered class:
2458 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2459 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2460 window = CreateWindowEx(0,
2461 name, // class name
2462 name, // app name
2463 WS_OVERLAPPEDWINDOW | // window style
2464 WS_VISIBLE | WS_SYSMENU,
2465 100, 100, // x/y coords
2466 wr.right - wr.left, // width
2467 wr.bottom - wr.top, // height
2468 nullptr, // handle to parent
2469 nullptr, // handle to menu
2470 connection, // hInstance
2471 nullptr); // no extra parameters
2472
2473 if (!window) {
2474 // It didn't work, so try to give a useful error:
2475 printf("Cannot create a window in which to draw!\n");
2476 fflush(stdout);
2477 exit(1);
2478 }
2479
2480 // Window client area size must be at least 1 pixel high, to prevent
2481 // crash.
2482 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2483 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2484}
2485#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2486
2487void Demo::create_xlib_window() {
2488 const char *display_envar = getenv("DISPLAY");
2489 if (display_envar == nullptr || display_envar[0] == '\0') {
2490 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2491 fflush(stdout);
2492 exit(1);
2493 }
2494
2495 XInitThreads();
2496 display = XOpenDisplay(nullptr);
2497 long visualMask = VisualScreenMask;
2498 int numberOfVisuals;
2499 XVisualInfo vInfoTemplate = {};
2500 vInfoTemplate.screen = DefaultScreen(display);
2501 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2502
2503 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2504
2505 XSetWindowAttributes windowAttributes = {};
2506 windowAttributes.colormap = colormap;
2507 windowAttributes.background_pixel = 0xFFFFFFFF;
2508 windowAttributes.border_pixel = 0;
2509 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2510
2511 xlib_window =
2512 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2513 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2514
2515 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2516 XMapWindow(display, xlib_window);
2517 XFlush(display);
2518 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2519}
2520
2521void Demo::handle_xlib_event(const XEvent *event) {
2522 switch (event->type) {
2523 case ClientMessage:
2524 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2525 quit = true;
2526 }
2527 break;
2528 case KeyPress:
2529 switch (event->xkey.keycode) {
2530 case 0x9: // Escape
2531 quit = true;
2532 break;
2533 case 0x71: // left arrow key
2534 spin_angle -= spin_increment;
2535 break;
2536 case 0x72: // right arrow key
2537 spin_angle += spin_increment;
2538 break;
2539 case 0x41: // space bar
2540 pause = !pause;
2541 break;
2542 }
2543 break;
2544 case ConfigureNotify:
2545 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2546 width = event->xconfigure.width;
2547 height = event->xconfigure.height;
2548 resize();
2549 }
2550 break;
2551 default:
2552 break;
2553 }
2554}
2555
2556void Demo::run_xlib() {
2557 while (!quit) {
2558 XEvent event;
2559
2560 if (pause) {
2561 XNextEvent(display, &event);
2562 handle_xlib_event(&event);
2563 }
2564 while (XPending(display) > 0) {
2565 XNextEvent(display, &event);
2566 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002567 }
2568
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002569 draw();
2570 curFrame++;
2571
Dave Houlton5fa47912018-02-16 11:02:26 -07002572 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2573 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002574 }
2575 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002576}
Tony Barbour153cb062016-12-07 13:43:36 -07002577#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002578
Dave Houlton5fa47912018-02-16 11:02:26 -07002579void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2580 uint8_t event_code = event->response_type & 0x7f;
2581 switch (event_code) {
2582 case XCB_EXPOSE:
2583 // TODO: Resize window
2584 break;
2585 case XCB_CLIENT_MESSAGE:
2586 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2587 quit = true;
2588 }
2589 break;
2590 case XCB_KEY_RELEASE: {
2591 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002592
Dave Houlton5fa47912018-02-16 11:02:26 -07002593 switch (key->detail) {
2594 case 0x9: // Escape
2595 quit = true;
2596 break;
2597 case 0x71: // left arrow key
2598 spin_angle -= spin_increment;
2599 break;
2600 case 0x72: // right arrow key
2601 spin_angle += spin_increment;
2602 break;
2603 case 0x41: // space bar
2604 pause = !pause;
2605 break;
2606 }
2607 } break;
2608 case XCB_CONFIGURE_NOTIFY: {
2609 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2610 if ((width != cfg->width) || (height != cfg->height)) {
2611 width = cfg->width;
2612 height = cfg->height;
2613 resize();
2614 }
2615 } break;
2616 default:
2617 break;
2618 }
2619}
2620
2621void Demo::run_xcb() {
2622 xcb_flush(connection);
2623
2624 while (!quit) {
2625 xcb_generic_event_t *event;
2626
2627 if (pause) {
2628 event = xcb_wait_for_event(connection);
2629 } else {
2630 event = xcb_poll_for_event(connection);
2631 }
2632 while (event) {
2633 handle_xcb_event(event);
2634 free(event);
2635 event = xcb_poll_for_event(connection);
2636 }
2637
2638 draw();
2639 curFrame++;
2640 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2641 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002642 }
2643 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002644}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002645
Dave Houlton5fa47912018-02-16 11:02:26 -07002646void Demo::create_xcb_window() {
2647 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002648
Dave Houlton5fa47912018-02-16 11:02:26 -07002649 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002650
Dave Houlton5fa47912018-02-16 11:02:26 -07002651 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2652 value_list[0] = screen->black_pixel;
2653 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002654
Dave Houlton5fa47912018-02-16 11:02:26 -07002655 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2656 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2657
2658 /* Magic code that will send notification when window is destroyed */
2659 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2660 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2661
2662 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2663 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2664
2665 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2666
2667 free(reply);
2668
2669 xcb_map_window(connection, xcb_window);
2670
2671 // Force the x/y coordinates to 100,100 results are identical in
2672 // consecutive
2673 // runs
2674 const uint32_t coords[] = {100, 100};
2675 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2676}
2677#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2678
2679void Demo::run() {
2680 while (!quit) {
2681 if (pause) {
2682 wl_display_dispatch(display);
2683 } else {
2684 wl_display_dispatch_pending(display);
2685 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002686 draw();
2687 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002688 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002689 quit = true;
2690 }
2691 }
2692 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002693}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002694
Dave Houlton5fa47912018-02-16 11:02:26 -07002695void Demo::create_window() {
2696 window = wl_compositor_create_surface(compositor);
2697 if (!window) {
2698 printf("Can not create wayland_surface from compositor!\n");
2699 fflush(stdout);
2700 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002701 }
2702
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002703 shell_surface = wl_shell_get_shell_surface(shell, window);
2704 if (!shell_surface) {
2705 printf("Can not get shell_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002706 fflush(stdout);
2707 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002708 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002709
Tony-LunarG5ceb7be2019-12-05 16:05:40 -07002710 wl_shell_surface_add_listener(shell_surface, &shell_surface_listener, this);
2711 wl_shell_surface_set_toplevel(shell_surface);
2712 wl_shell_surface_set_title(shell_surface, APP_SHORT_NAME);
Dave Houlton5fa47912018-02-16 11:02:26 -07002713}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002714#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002715void Demo::run() {
2716 draw();
2717 curFrame++;
2718 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2719 quit = true;
2720 }
2721}
Damien Leone600c3052017-01-31 10:26:07 -07002722#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2723
Dave Houlton5fa47912018-02-16 11:02:26 -07002724vk::Result Demo::create_display_surface() {
2725 vk::Result result;
2726 uint32_t display_count;
2727 uint32_t mode_count;
2728 uint32_t plane_count;
2729 vk::DisplayPropertiesKHR display_props;
2730 vk::DisplayKHR display;
2731 vk::DisplayModePropertiesKHR mode_props;
2732 vk::DisplayPlanePropertiesKHR *plane_props;
2733 vk::Bool32 found_plane = VK_FALSE;
2734 uint32_t plane_index;
2735 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002736
Dave Houlton5fa47912018-02-16 11:02:26 -07002737 // Get the first display
2738 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2739 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002740
Dave Houlton5fa47912018-02-16 11:02:26 -07002741 if (display_count == 0) {
2742 printf("Cannot find any display!\n");
2743 fflush(stdout);
2744 exit(1);
2745 }
2746
2747 display_count = 1;
2748 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2749 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2750
2751 display = display_props.display;
2752
2753 // Get the first mode of the display
2754 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2755 VERIFY(result == vk::Result::eSuccess);
2756
2757 if (mode_count == 0) {
2758 printf("Cannot find any mode for the display!\n");
2759 fflush(stdout);
2760 exit(1);
2761 }
2762
2763 mode_count = 1;
2764 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2765 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2766
2767 // Get the list of planes
2768 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2769 VERIFY(result == vk::Result::eSuccess);
2770
2771 if (plane_count == 0) {
2772 printf("Cannot find any plane!\n");
2773 fflush(stdout);
2774 exit(1);
2775 }
2776
2777 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2778 VERIFY(plane_props != nullptr);
2779
2780 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2781 VERIFY(result == vk::Result::eSuccess);
2782
2783 // Find a plane compatible with the display
2784 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2785 uint32_t supported_count;
2786 vk::DisplayKHR *supported_displays;
2787
2788 // Disqualify planes that are bound to a different display
2789 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2790 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002791 }
2792
Dave Houlton5fa47912018-02-16 11:02:26 -07002793 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002794 VERIFY(result == vk::Result::eSuccess);
2795
Dave Houlton5fa47912018-02-16 11:02:26 -07002796 if (supported_count == 0) {
2797 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002798 }
2799
Dave Houlton5fa47912018-02-16 11:02:26 -07002800 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2801 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002802
Dave Houlton5fa47912018-02-16 11:02:26 -07002803 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002804 VERIFY(result == vk::Result::eSuccess);
2805
Dave Houlton5fa47912018-02-16 11:02:26 -07002806 for (uint32_t i = 0; i < supported_count; i++) {
2807 if (supported_displays[i] == display) {
2808 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002809 break;
2810 }
2811 }
2812
Dave Houlton5fa47912018-02-16 11:02:26 -07002813 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002814
Dave Houlton5fa47912018-02-16 11:02:26 -07002815 if (found_plane) {
2816 break;
Damien Leone600c3052017-01-31 10:26:07 -07002817 }
2818 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002819
2820 if (!found_plane) {
2821 printf("Cannot find a plane compatible with the display!\n");
2822 fflush(stdout);
2823 exit(1);
2824 }
2825
2826 free(plane_props);
2827
2828 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2829 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2830 // Find a supported alpha mode
2831 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2832 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2833 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2834 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2835 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2836 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2837 };
2838 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2839 if (planeCaps.supportedAlpha & alphaModes[i]) {
2840 alphaMode = alphaModes[i];
2841 break;
2842 }
2843 }
2844
2845 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2846 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2847
2848 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2849 .setDisplayMode(mode_props.displayMode)
2850 .setPlaneIndex(plane_index)
2851 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2852 .setGlobalAlpha(1.0f)
2853 .setAlphaMode(alphaMode)
2854 .setImageExtent(image_extent);
2855
2856 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2857}
2858
2859void Demo::run_display() {
2860 while (!quit) {
2861 draw();
2862 curFrame++;
2863
Petr Krausd88e4e52019-01-23 18:45:04 +01002864 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002865 quit = true;
2866 }
2867 }
2868}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002869#endif
2870
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002871#if _WIN32
2872// Include header required for parsing the command line options.
2873#include <shellapi.h>
2874
2875Demo demo;
2876
2877// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002878LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2879 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002880 case WM_CLOSE:
2881 PostQuitMessage(validation_error);
2882 break;
2883 case WM_PAINT:
2884 demo.run();
2885 break;
2886 case WM_GETMINMAXINFO: // set window's minimum size
2887 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2888 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002889 case WM_ERASEBKGND:
2890 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002891 case WM_SIZE:
2892 // Resize the application to the new window size, except when
2893 // it was minimized. Vulkan doesn't support images or swapchains
2894 // with width=0 and height=0.
2895 if (wParam != SIZE_MINIMIZED) {
2896 demo.width = lParam & 0xffff;
2897 demo.height = (lParam & 0xffff0000) >> 16;
2898 demo.resize();
2899 }
2900 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002901 case WM_KEYDOWN:
2902 switch (wParam) {
2903 case VK_ESCAPE:
2904 PostQuitMessage(validation_error);
2905 break;
2906 case VK_LEFT:
2907 demo.spin_angle -= demo.spin_increment;
2908 break;
2909 case VK_RIGHT:
2910 demo.spin_angle += demo.spin_increment;
2911 break;
2912 case VK_SPACE:
2913 demo.pause = !demo.pause;
2914 break;
2915 }
2916 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002917 default:
2918 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002919 }
2920
2921 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2922}
2923
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002924int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002925 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002926 MSG msg; // message
2927 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002928 int argc;
2929 char **argv;
2930
Jamie Madillb2ff6502017-03-15 16:17:46 -04002931 // Ensure wParam is initialized.
2932 msg.wParam = 0;
2933
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002934 // Use the CommandLine functions to get the command line arguments.
2935 // Unfortunately, Microsoft outputs
2936 // this information as wide characters for Unicode, and we simply want the
2937 // Ascii version to be compatible
2938 // with the non-Windows side. So, we have to convert the information to
2939 // Ascii character strings.
2940 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002941 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002942 argc = 0;
2943 }
2944
Jeremy Hayes9d304782016-10-09 11:48:12 -06002945 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002946 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06002947 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002948 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002949 } else {
2950 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002951 size_t wideCharLen = wcslen(commandLineArgs[iii]);
2952 size_t numConverted = 0;
2953
2954 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06002955 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002956 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002957 }
2958 }
2959 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06002960 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002961 argv = nullptr;
2962 }
2963
2964 demo.init(argc, argv);
2965
2966 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06002967 if (argc > 0 && argv != nullptr) {
2968 for (int iii = 0; iii < argc; iii++) {
2969 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002970 free(argv[iii]);
2971 }
2972 }
2973 free(argv);
2974 }
2975
2976 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07002977 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002978 demo.create_window();
2979 demo.init_vk_swapchain();
2980
2981 demo.prepare();
2982
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002983 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002984
2985 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06002986 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01002987 if (demo.pause) {
2988 const BOOL succ = WaitMessage();
2989
2990 if (!succ) {
2991 const auto &suppress_popups = demo.suppress_popups;
2992 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
2993 }
2994 }
2995
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002996 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002997 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002998 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002999 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003000 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003001 /* Translate and dispatch to event queue*/
3002 TranslateMessage(&msg);
3003 DispatchMessage(&msg);
3004 }
3005 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3006 }
3007
3008 demo.cleanup();
3009
3010 return (int)msg.wParam;
3011}
3012
3013#elif __linux__
3014
Jeremy Hayes9d304782016-10-09 11:48:12 -06003015int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003016 Demo demo;
3017
3018 demo.init(argc, argv);
3019
Tony Barbour153cb062016-12-07 13:43:36 -07003020#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003021 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003022#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003023 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003024 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003025#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003026 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003027#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003028
3029 demo.init_vk_swapchain();
3030
3031 demo.prepare();
3032
Tony Barbour153cb062016-12-07 13:43:36 -07003033#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003034 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003035#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003036 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003037#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003038 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003039#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3040 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003041#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003042
3043 demo.cleanup();
3044
3045 return validation_error;
3046}
3047
Bill Hollings0a0625a2019-07-15 17:39:18 -04003048#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003049
3050// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003051static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003052 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003053 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003054 demo.init_vk_swapchain();
3055 demo.prepare();
3056 demo.spin_angle = 0.4f;
3057}
3058
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003059#else
3060#error "Platform not supported"
3061#endif