blob: 4af978569f9fdb88e9d62bd994622a29fcd4687f [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>
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -040025#include "xdg-shell-client-header.h"
26#include "xdg-decoration-client-header.h"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060027#endif
28
29#include <cassert>
Petr Krausbc0ab752017-12-09 00:22:39 +010030#include <cinttypes>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060031#include <cstdio>
32#include <cstdlib>
33#include <cstring>
34#include <csignal>
Tony-LunarGd74734f2019-06-04 14:11:43 -060035#include <iostream>
36#include <sstream>
Jeremy Hayesf56427a2016-09-07 15:55:11 -060037#include <memory>
38
Mark Lobodzinskidefadcf2017-10-23 09:23:06 -060039#define VULKAN_HPP_NO_SMART_HANDLE
Jeremy Hayesf56427a2016-09-07 15:55:11 -060040#define VULKAN_HPP_NO_EXCEPTIONS
Shannon McPherson2abb6992019-04-05 10:46:16 -060041#define VULKAN_HPP_TYPESAFE_CONVERSION
Jeremy Hayesf56427a2016-09-07 15:55:11 -060042#include <vulkan/vulkan.hpp>
43#include <vulkan/vk_sdk_platform.h>
44
45#include "linmath.h"
46
47#ifndef NDEBUG
48#define VERIFY(x) assert(x)
49#else
50#define VERIFY(x) ((void)(x))
51#endif
52
Lenny Komowffe446c2018-11-19 17:08:04 -070053#define APP_SHORT_NAME "vkcube"
Jeremy Hayesf56427a2016-09-07 15:55:11 -060054#ifdef _WIN32
55#define APP_NAME_STR_LEN 80
56#endif
57
58// Allow a maximum of two outstanding presentation operations.
59#define FRAME_LAG 2
60
61#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
62
63#ifdef _WIN32
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070064#define ERR_EXIT(err_msg, err_class) \
65 do { \
66 if (!suppress_popups) MessageBox(nullptr, err_msg, err_class, MB_OK); \
67 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060068 } while (0)
69#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070070#define ERR_EXIT(err_msg, err_class) \
71 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -080072 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070073 fflush(stdout); \
74 exit(1); \
Jeremy Hayesf56427a2016-09-07 15:55:11 -060075 } while (0)
76#endif
77
Jeremy Hayes9d304782016-10-09 11:48:12 -060078struct texture_object {
Jeremy Hayesf56427a2016-09-07 15:55:11 -060079 vk::Sampler sampler;
80
81 vk::Image image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -060082 vk::Buffer buffer;
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070083 vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060084
85 vk::MemoryAllocateInfo mem_alloc;
86 vk::DeviceMemory mem;
87 vk::ImageView view;
88
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -070089 int32_t tex_width{0};
90 int32_t tex_height{0};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060091};
92
Jeremy Hayes9d304782016-10-09 11:48:12 -060093static char const *const tex_files[] = {"lunarg.ppm"};
Jeremy Hayesf56427a2016-09-07 15:55:11 -060094
95static int validation_error = 0;
96
97struct vkcube_vs_uniform {
98 // Must start with MVP
99 float mvp[4][4];
100 float position[12 * 3][4];
101 float color[12 * 3][4];
102};
103
104struct vktexcube_vs_uniform {
105 // Must start with MVP
106 float mvp[4][4];
107 float position[12 * 3][4];
108 float attr[12 * 3][4];
109};
110
111//--------------------------------------------------------------------------------------
112// Mesh and VertexFormat Data
113//--------------------------------------------------------------------------------------
114// clang-format off
115static const float g_vertex_buffer_data[] = {
116 -1.0f,-1.0f,-1.0f, // -X side
117 -1.0f,-1.0f, 1.0f,
118 -1.0f, 1.0f, 1.0f,
119 -1.0f, 1.0f, 1.0f,
120 -1.0f, 1.0f,-1.0f,
121 -1.0f,-1.0f,-1.0f,
122
123 -1.0f,-1.0f,-1.0f, // -Z side
124 1.0f, 1.0f,-1.0f,
125 1.0f,-1.0f,-1.0f,
126 -1.0f,-1.0f,-1.0f,
127 -1.0f, 1.0f,-1.0f,
128 1.0f, 1.0f,-1.0f,
129
130 -1.0f,-1.0f,-1.0f, // -Y side
131 1.0f,-1.0f,-1.0f,
132 1.0f,-1.0f, 1.0f,
133 -1.0f,-1.0f,-1.0f,
134 1.0f,-1.0f, 1.0f,
135 -1.0f,-1.0f, 1.0f,
136
137 -1.0f, 1.0f,-1.0f, // +Y side
138 -1.0f, 1.0f, 1.0f,
139 1.0f, 1.0f, 1.0f,
140 -1.0f, 1.0f,-1.0f,
141 1.0f, 1.0f, 1.0f,
142 1.0f, 1.0f,-1.0f,
143
144 1.0f, 1.0f,-1.0f, // +X side
145 1.0f, 1.0f, 1.0f,
146 1.0f,-1.0f, 1.0f,
147 1.0f,-1.0f, 1.0f,
148 1.0f,-1.0f,-1.0f,
149 1.0f, 1.0f,-1.0f,
150
151 -1.0f, 1.0f, 1.0f, // +Z side
152 -1.0f,-1.0f, 1.0f,
153 1.0f, 1.0f, 1.0f,
154 -1.0f,-1.0f, 1.0f,
155 1.0f,-1.0f, 1.0f,
156 1.0f, 1.0f, 1.0f,
157};
158
159static const float g_uv_buffer_data[] = {
160 0.0f, 1.0f, // -X side
161 1.0f, 1.0f,
162 1.0f, 0.0f,
163 1.0f, 0.0f,
164 0.0f, 0.0f,
165 0.0f, 1.0f,
166
167 1.0f, 1.0f, // -Z side
168 0.0f, 0.0f,
169 0.0f, 1.0f,
170 1.0f, 1.0f,
171 1.0f, 0.0f,
172 0.0f, 0.0f,
173
174 1.0f, 0.0f, // -Y side
175 1.0f, 1.0f,
176 0.0f, 1.0f,
177 1.0f, 0.0f,
178 0.0f, 1.0f,
179 0.0f, 0.0f,
180
181 1.0f, 0.0f, // +Y side
182 0.0f, 0.0f,
183 0.0f, 1.0f,
184 1.0f, 0.0f,
185 0.0f, 1.0f,
186 1.0f, 1.0f,
187
188 1.0f, 0.0f, // +X side
189 0.0f, 0.0f,
190 0.0f, 1.0f,
191 0.0f, 1.0f,
192 1.0f, 1.0f,
193 1.0f, 0.0f,
194
195 0.0f, 0.0f, // +Z side
196 0.0f, 1.0f,
197 1.0f, 0.0f,
198 0.0f, 1.0f,
199 1.0f, 1.0f,
200 1.0f, 0.0f,
201};
Jeremy Hayes9d304782016-10-09 11:48:12 -0600202// clang-format on
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600203
Jeremy Hayes9d304782016-10-09 11:48:12 -0600204typedef struct {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600205 vk::Image image;
206 vk::CommandBuffer cmd;
207 vk::CommandBuffer graphics_to_present_cmd;
208 vk::ImageView view;
Jeremy Hayes00399e32017-06-14 15:07:32 -0600209 vk::Buffer uniform_buffer;
210 vk::DeviceMemory uniform_memory;
211 vk::Framebuffer framebuffer;
212 vk::DescriptorSet descriptor_set;
213} SwapchainImageResources;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600214
Joey Bzdekbaf66472017-06-07 09:37:37 -0600215struct Demo {
216 Demo();
217 void build_image_ownership_cmd(uint32_t const &);
218 vk::Bool32 check_layers(uint32_t, const char *const *, uint32_t, vk::LayerProperties *);
219 void cleanup();
220 void create_device();
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600221 void destroy_texture(texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600222 void draw();
223 void draw_build_cmd(vk::CommandBuffer);
224 void flush_init_cmd();
225 void init(int, char **);
226 void init_connection();
227 void init_vk();
228 void init_vk_swapchain();
229 void prepare();
230 void prepare_buffers();
231 void prepare_cube_data_buffers();
232 void prepare_depth();
233 void prepare_descriptor_layout();
234 void prepare_descriptor_pool();
235 void prepare_descriptor_set();
236 void prepare_framebuffers();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100237 vk::ShaderModule prepare_shader_module(const uint32_t *, size_t);
238 vk::ShaderModule prepare_vs();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600239 vk::ShaderModule prepare_fs();
240 void prepare_pipeline();
241 void prepare_render_pass();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600242 void prepare_texture_image(const char *, texture_object *, vk::ImageTiling, vk::ImageUsageFlags, vk::MemoryPropertyFlags);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600243 void prepare_texture_buffer(const char *, texture_object *);
Joey Bzdekbaf66472017-06-07 09:37:37 -0600244 void prepare_textures();
Petr Kraus9a4eb6a2017-11-30 14:49:20 +0100245
Joey Bzdekbaf66472017-06-07 09:37:37 -0600246 void resize();
Tony-LunarG6cebf142019-09-11 14:32:23 -0600247 void create_surface();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600248 void set_image_layout(vk::Image, vk::ImageAspectFlags, vk::ImageLayout, vk::ImageLayout, vk::AccessFlags,
249 vk::PipelineStageFlags, vk::PipelineStageFlags);
250 void update_data_buffer();
251 bool loadTexture(const char *, uint8_t *, vk::SubresourceLayout *, int32_t *, int32_t *);
252 bool memory_type_from_properties(uint32_t, vk::MemoryPropertyFlags, uint32_t *);
253
254#if defined(VK_USE_PLATFORM_WIN32_KHR)
255 void run();
256 void create_window();
257#elif defined(VK_USE_PLATFORM_XLIB_KHR)
258 void create_xlib_window();
259 void handle_xlib_event(const XEvent *);
260 void run_xlib();
261#elif defined(VK_USE_PLATFORM_XCB_KHR)
262 void handle_xcb_event(const xcb_generic_event_t *);
263 void run_xcb();
264 void create_xcb_window();
265#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
266 void run();
267 void create_window();
Karl Schultz206b1c52018-04-13 18:02:07 -0600268#elif defined(VK_USE_PLATFORM_MACOS_MVK)
269 void run();
Joey Bzdekbaf66472017-06-07 09:37:37 -0600270#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
271 vk::Result create_display_surface();
272 void run_display();
273#endif
274
275#if defined(VK_USE_PLATFORM_WIN32_KHR)
276 HINSTANCE connection; // hInstance - Windows Instance
277 HWND window; // hWnd - window handle
278 POINT minsize; // minimum window size
279 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
280#elif defined(VK_USE_PLATFORM_XLIB_KHR)
281 Window xlib_window;
282 Atom xlib_wm_delete_window;
283 Display *display;
284#elif defined(VK_USE_PLATFORM_XCB_KHR)
285 xcb_window_t xcb_window;
286 xcb_screen_t *screen;
287 xcb_connection_t *connection;
288 xcb_intern_atom_reply_t *atom_wm_delete_window;
289#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
290 wl_display *display;
291 wl_registry *registry;
292 wl_compositor *compositor;
293 wl_surface *window;
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400294 xdg_wm_base *wm_base;
295 zxdg_decoration_manager_v1 *xdg_decoration_mgr;
296 zxdg_toplevel_decoration_v1 *toplevel_decoration;
297 xdg_surface *window_surface;
298 bool xdg_surface_has_been_configured;
299 xdg_toplevel *window_toplevel;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600300 wl_seat *seat;
301 wl_pointer *pointer;
302 wl_keyboard *keyboard;
Karl Schultz9ceac062017-12-12 10:33:01 -0500303#elif (defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK))
304 void *window;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600305#endif
306
307 vk::SurfaceKHR surface;
308 bool prepared;
309 bool use_staging_buffer;
310 bool use_xlib;
311 bool separate_present_queue;
312
313 vk::Instance inst;
314 vk::PhysicalDevice gpu;
315 vk::Device device;
316 vk::Queue graphics_queue;
317 vk::Queue present_queue;
318 uint32_t graphics_queue_family_index;
319 uint32_t present_queue_family_index;
320 vk::Semaphore image_acquired_semaphores[FRAME_LAG];
321 vk::Semaphore draw_complete_semaphores[FRAME_LAG];
322 vk::Semaphore image_ownership_semaphores[FRAME_LAG];
323 vk::PhysicalDeviceProperties gpu_props;
324 std::unique_ptr<vk::QueueFamilyProperties[]> queue_props;
325 vk::PhysicalDeviceMemoryProperties memory_properties;
326
327 uint32_t enabled_extension_count;
328 uint32_t enabled_layer_count;
329 char const *extension_names[64];
330 char const *enabled_layers[64];
331
332 uint32_t width;
333 uint32_t height;
334 vk::Format format;
335 vk::ColorSpaceKHR color_space;
336
337 uint32_t swapchainImageCount;
338 vk::SwapchainKHR swapchain;
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600339 std::unique_ptr<SwapchainImageResources[]> swapchain_image_resources;
Joey Bzdekbaf66472017-06-07 09:37:37 -0600340 vk::PresentModeKHR presentMode;
341 vk::Fence fences[FRAME_LAG];
342 uint32_t frame_index;
343
344 vk::CommandPool cmd_pool;
345 vk::CommandPool present_cmd_pool;
346
347 struct {
348 vk::Format format;
349 vk::Image image;
350 vk::MemoryAllocateInfo mem_alloc;
351 vk::DeviceMemory mem;
352 vk::ImageView view;
353 } depth;
354
355 static int32_t const texture_count = 1;
356 texture_object textures[texture_count];
357 texture_object staging_texture;
358
359 struct {
360 vk::Buffer buf;
361 vk::MemoryAllocateInfo mem_alloc;
362 vk::DeviceMemory mem;
363 vk::DescriptorBufferInfo buffer_info;
364 } uniform_data;
365
366 vk::CommandBuffer cmd; // Buffer for initialization commands
367 vk::PipelineLayout pipeline_layout;
368 vk::DescriptorSetLayout desc_layout;
369 vk::PipelineCache pipelineCache;
370 vk::RenderPass render_pass;
371 vk::Pipeline pipeline;
372
373 mat4x4 projection_matrix;
374 mat4x4 view_matrix;
375 mat4x4 model_matrix;
376
377 float spin_angle;
378 float spin_increment;
379 bool pause;
380
381 vk::ShaderModule vert_shader_module;
382 vk::ShaderModule frag_shader_module;
383
384 vk::DescriptorPool desc_pool;
385 vk::DescriptorSet desc_set;
386
387 std::unique_ptr<vk::Framebuffer[]> framebuffers;
388
389 bool quit;
390 uint32_t curFrame;
391 uint32_t frameCount;
392 bool validate;
393 bool use_break;
394 bool suppress_popups;
395
396 uint32_t current_buffer;
397 uint32_t queue_family_count;
398};
399
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600400#ifdef _WIN32
401// MS-Windows event handling function:
402LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
403#endif
404
Karl Schultz23cc2182016-11-23 17:15:17 -0700405#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700406static void handle_ping(void *data, wl_shell_surface *shell_surface, uint32_t serial) {
Karl Schultz23cc2182016-11-23 17:15:17 -0700407 wl_shell_surface_pong(shell_surface, serial);
408}
409
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700410static 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 -0700411
412static void handle_popup_done(void *data, wl_shell_surface *shell_surface) {}
413
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700414static const wl_shell_surface_listener shell_surface_listener = {handle_ping, handle_configure, handle_popup_done};
Karl Schultz23cc2182016-11-23 17:15:17 -0700415
Joey Bzdek15eb0702017-06-07 09:40:36 -0600416static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
417 wl_fixed_t sy) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700418
Joey Bzdek15eb0702017-06-07 09:40:36 -0600419static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
Karl Schultz23cc2182016-11-23 17:15:17 -0700420
Joey Bzdek15eb0702017-06-07 09:40:36 -0600421static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
422
423static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
424 uint32_t state) {
Joey Bzdek33bc5c82017-06-14 10:33:36 -0600425 Demo *demo = (Demo *)data;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600426 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400427 xdg_toplevel_move(demo->window_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600428 }
429}
430
431static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
432
433static const struct wl_pointer_listener pointer_listener = {
434 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
435};
436
437static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
438
439static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
440 struct wl_array *keys) {}
441
442static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
443
444static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
445 uint32_t state) {
446 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
447 Demo *demo = (Demo *)data;
448 switch (key) {
449 case KEY_ESC: // Escape
450 demo->quit = true;
451 break;
452 case KEY_LEFT: // left arrow key
453 demo->spin_angle -= demo->spin_increment;
454 break;
455 case KEY_RIGHT: // right arrow key
456 demo->spin_angle += demo->spin_increment;
457 break;
458 case KEY_SPACE: // space bar
459 demo->pause = !demo->pause;
460 break;
461 }
462}
463
464static void keyboard_handle_modifiers(void *data, wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
465 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
466
467static const struct wl_keyboard_listener keyboard_listener = {
468 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
469};
470
471static void seat_handle_capabilities(void *data, wl_seat *seat, uint32_t caps) {
472 // Subscribe to pointer events
473 Demo *demo = (Demo *)data;
474 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
475 demo->pointer = wl_seat_get_pointer(seat);
476 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
477 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
478 wl_pointer_destroy(demo->pointer);
479 demo->pointer = NULL;
480 }
481 // Subscribe to keyboard events
482 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
483 demo->keyboard = wl_seat_get_keyboard(seat);
484 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
485 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
486 wl_keyboard_destroy(demo->keyboard);
487 demo->keyboard = NULL;
488 }
489}
490
491static const wl_seat_listener seat_listener = {
492 seat_handle_capabilities,
493};
494
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400495static void wm_base_ping(void *data, xdg_wm_base *xdg_wm_base, uint32_t serial) { xdg_wm_base_pong(xdg_wm_base, serial); }
496
497static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
498
Joey Bzdek15eb0702017-06-07 09:40:36 -0600499static void registry_handle_global(void *data, wl_registry *registry, uint32_t id, const char *interface, uint32_t version) {
500 Demo *demo = (Demo *)data;
501 // pickup wayland objects when they appear
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400502 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600503 demo->compositor = (wl_compositor *)wl_registry_bind(registry, id, &wl_compositor_interface, 1);
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400504 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
505 demo->wm_base = (xdg_wm_base *)wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
506 xdg_wm_base_add_listener(demo->wm_base, &wm_base_listener, nullptr);
507 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -0600508 demo->seat = (wl_seat *)wl_registry_bind(registry, id, &wl_seat_interface, 1);
509 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400510 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
511 demo->xdg_decoration_mgr =
512 (zxdg_decoration_manager_v1 *)wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Joey Bzdek15eb0702017-06-07 09:40:36 -0600513 }
514}
515
516static void registry_handle_global_remove(void *data, wl_registry *registry, uint32_t name) {}
517
518static const wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Karl Schultz23cc2182016-11-23 17:15:17 -0700519#endif
520
Joey Bzdekbaf66472017-06-07 09:37:37 -0600521Demo::Demo()
522 :
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600523#if defined(VK_USE_PLATFORM_WIN32_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600524 connection{nullptr},
525 window{nullptr},
526 minsize(POINT{0, 0}), // Use explicit construction to avoid MSVC error C2797.
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600527#endif
Tony Barbour153cb062016-12-07 13:43:36 -0700528
Tony Barbour78d6b572016-11-14 14:46:33 -0700529#if defined(VK_USE_PLATFORM_XLIB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600530 xlib_window{0},
531 xlib_wm_delete_window{0},
532 display{nullptr},
Tony Barbour153cb062016-12-07 13:43:36 -0700533#elif defined(VK_USE_PLATFORM_XCB_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600534 xcb_window{0},
535 screen{nullptr},
536 connection{nullptr},
Karl Schultz23cc2182016-11-23 17:15:17 -0700537#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdekbaf66472017-06-07 09:37:37 -0600538 display{nullptr},
539 registry{nullptr},
540 compositor{nullptr},
541 window{nullptr},
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400542 wm_base{nullptr},
543 xdg_decoration_mgr{nullptr},
544 toplevel_decoration{nullptr},
545 window_surface{nullptr},
546 xdg_surface_has_been_configured{false},
547 window_toplevel{nullptr},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600548 seat{nullptr},
549 pointer{nullptr},
550 keyboard{nullptr},
Tony Barbour78d6b572016-11-14 14:46:33 -0700551#endif
Joey Bzdekbaf66472017-06-07 09:37:37 -0600552 prepared{false},
553 use_staging_buffer{false},
554 use_xlib{false},
555 graphics_queue_family_index{0},
556 present_queue_family_index{0},
557 enabled_extension_count{0},
558 enabled_layer_count{0},
559 width{0},
560 height{0},
561 swapchainImageCount{0},
Dave Airliea4417182019-04-12 16:47:29 +1000562 presentMode{vk::PresentModeKHR::eFifo},
Joey Bzdekbaf66472017-06-07 09:37:37 -0600563 frame_index{0},
564 spin_angle{0.0f},
565 spin_increment{0.0f},
566 pause{false},
567 quit{false},
568 curFrame{0},
569 frameCount{0},
570 validate{false},
571 use_break{false},
572 suppress_popups{false},
573 current_buffer{0},
574 queue_family_count{0} {
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600575#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -0700576 memset(name, '\0', APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600577#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700578 memset(projection_matrix, 0, sizeof(projection_matrix));
579 memset(view_matrix, 0, sizeof(view_matrix));
580 memset(model_matrix, 0, sizeof(model_matrix));
581}
582
583void Demo::build_image_ownership_cmd(uint32_t const &i) {
584 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
585 auto result = swapchain_image_resources[i].graphics_to_present_cmd.begin(&cmd_buf_info);
586 VERIFY(result == vk::Result::eSuccess);
587
588 auto const image_ownership_barrier =
589 vk::ImageMemoryBarrier()
590 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600591 .setDstAccessMask(vk::AccessFlags())
Dave Houlton5fa47912018-02-16 11:02:26 -0700592 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
593 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
594 .setSrcQueueFamilyIndex(graphics_queue_family_index)
595 .setDstQueueFamilyIndex(present_queue_family_index)
596 .setImage(swapchain_image_resources[i].image)
597 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
598
599 swapchain_image_resources[i].graphics_to_present_cmd.pipelineBarrier(
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600600 vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlagBits(), 0, nullptr, 0,
601 nullptr, 1, &image_ownership_barrier);
Dave Houlton5fa47912018-02-16 11:02:26 -0700602
603 result = swapchain_image_resources[i].graphics_to_present_cmd.end();
604 VERIFY(result == vk::Result::eSuccess);
605}
606
607vk::Bool32 Demo::check_layers(uint32_t check_count, char const *const *const check_names, uint32_t layer_count,
608 vk::LayerProperties *layers) {
609 for (uint32_t i = 0; i < check_count; i++) {
610 vk::Bool32 found = VK_FALSE;
611 for (uint32_t j = 0; j < layer_count; j++) {
612 if (!strcmp(check_names[i], layers[j].layerName)) {
613 found = VK_TRUE;
614 break;
615 }
616 }
617 if (!found) {
618 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
619 return 0;
620 }
621 }
622 return VK_TRUE;
623}
624
625void Demo::cleanup() {
626 prepared = false;
627 device.waitIdle();
628
629 // Wait for fences from present operations
630 for (uint32_t i = 0; i < FRAME_LAG; i++) {
631 device.waitForFences(1, &fences[i], VK_TRUE, UINT64_MAX);
632 device.destroyFence(fences[i], nullptr);
633 device.destroySemaphore(image_acquired_semaphores[i], nullptr);
634 device.destroySemaphore(draw_complete_semaphores[i], nullptr);
635 if (separate_present_queue) {
636 device.destroySemaphore(image_ownership_semaphores[i], nullptr);
637 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600638 }
639
Dave Houlton5fa47912018-02-16 11:02:26 -0700640 for (uint32_t i = 0; i < swapchainImageCount; i++) {
641 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
642 }
643 device.destroyDescriptorPool(desc_pool, nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600644
Dave Houlton5fa47912018-02-16 11:02:26 -0700645 device.destroyPipeline(pipeline, nullptr);
646 device.destroyPipelineCache(pipelineCache, nullptr);
647 device.destroyRenderPass(render_pass, nullptr);
648 device.destroyPipelineLayout(pipeline_layout, nullptr);
649 device.destroyDescriptorSetLayout(desc_layout, nullptr);
650
651 for (uint32_t i = 0; i < texture_count; i++) {
652 device.destroyImageView(textures[i].view, nullptr);
653 device.destroyImage(textures[i].image, nullptr);
654 device.freeMemory(textures[i].mem, nullptr);
655 device.destroySampler(textures[i].sampler, nullptr);
656 }
657 device.destroySwapchainKHR(swapchain, nullptr);
658
659 device.destroyImageView(depth.view, nullptr);
660 device.destroyImage(depth.image, nullptr);
661 device.freeMemory(depth.mem, nullptr);
662
663 for (uint32_t i = 0; i < swapchainImageCount; i++) {
664 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
665 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
666 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
667 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
668 }
669
670 device.destroyCommandPool(cmd_pool, nullptr);
671
672 if (separate_present_queue) {
673 device.destroyCommandPool(present_cmd_pool, nullptr);
674 }
675 device.waitIdle();
676 device.destroy(nullptr);
677 inst.destroySurfaceKHR(surface, nullptr);
678
679#if defined(VK_USE_PLATFORM_XLIB_KHR)
680 XDestroyWindow(display, xlib_window);
681 XCloseDisplay(display);
682#elif defined(VK_USE_PLATFORM_XCB_KHR)
683 xcb_destroy_window(connection, xcb_window);
684 xcb_disconnect(connection);
685 free(atom_wm_delete_window);
686#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
687 wl_keyboard_destroy(keyboard);
688 wl_pointer_destroy(pointer);
689 wl_seat_destroy(seat);
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400690 xdg_toplevel_destroy(window_toplevel);
691 xdg_surface_destroy(window_surface);
Dave Houlton5fa47912018-02-16 11:02:26 -0700692 wl_surface_destroy(window);
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -0400693 xdg_wm_base_destroy(wm_base);
694 if (xdg_decoration_mgr) {
695 zxdg_toplevel_decoration_v1_destroy(toplevel_decoration);
696 zxdg_decoration_manager_v1_destroy(xdg_decoration_mgr);
697 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700698 wl_compositor_destroy(compositor);
699 wl_registry_destroy(registry);
700 wl_display_disconnect(display);
Dave Houlton5fa47912018-02-16 11:02:26 -0700701#endif
702
703 inst.destroy(nullptr);
704}
705
706void Demo::create_device() {
707 float const priorities[1] = {0.0};
708
709 vk::DeviceQueueCreateInfo queues[2];
710 queues[0].setQueueFamilyIndex(graphics_queue_family_index);
711 queues[0].setQueueCount(1);
712 queues[0].setPQueuePriorities(priorities);
713
714 auto deviceInfo = vk::DeviceCreateInfo()
715 .setQueueCreateInfoCount(1)
716 .setPQueueCreateInfos(queues)
717 .setEnabledLayerCount(0)
718 .setPpEnabledLayerNames(nullptr)
719 .setEnabledExtensionCount(enabled_extension_count)
720 .setPpEnabledExtensionNames((const char *const *)extension_names)
721 .setPEnabledFeatures(nullptr);
722
723 if (separate_present_queue) {
724 queues[1].setQueueFamilyIndex(present_queue_family_index);
725 queues[1].setQueueCount(1);
726 queues[1].setPQueuePriorities(priorities);
727 deviceInfo.setQueueCreateInfoCount(2);
728 }
729
730 auto result = gpu.createDevice(&deviceInfo, nullptr, &device);
731 VERIFY(result == vk::Result::eSuccess);
732}
733
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600734void Demo::destroy_texture(texture_object *tex_objs) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700735 // clean up staging resources
736 device.freeMemory(tex_objs->mem, nullptr);
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600737 if (tex_objs->image) device.destroyImage(tex_objs->image, nullptr);
738 if (tex_objs->buffer) device.destroyBuffer(tex_objs->buffer, nullptr);
Dave Houlton5fa47912018-02-16 11:02:26 -0700739}
740
741void Demo::draw() {
742 // Ensure no more than FRAME_LAG renderings are outstanding
743 device.waitForFences(1, &fences[frame_index], VK_TRUE, UINT64_MAX);
744 device.resetFences(1, &fences[frame_index]);
745
746 vk::Result result;
747 do {
748 result =
749 device.acquireNextImageKHR(swapchain, UINT64_MAX, image_acquired_semaphores[frame_index], vk::Fence(), &current_buffer);
750 if (result == vk::Result::eErrorOutOfDateKHR) {
751 // demo->swapchain is out of date (e.g. the window was resized) and
752 // must be recreated:
753 resize();
754 } else if (result == vk::Result::eSuboptimalKHR) {
755 // swapchain is not as optimal as it could be, but the platform's
756 // presentation engine will still present the image correctly.
757 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600758 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
759 inst.destroySurfaceKHR(surface, nullptr);
760 create_surface();
761 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700762 } else {
763 VERIFY(result == vk::Result::eSuccess);
764 }
765 } while (result != vk::Result::eSuccess);
766
767 update_data_buffer();
768
769 // Wait for the image acquired semaphore to be signaled to ensure
770 // that the image won't be rendered to until the presentation
771 // engine has fully released ownership to the application, and it is
772 // okay to render to the image.
773 vk::PipelineStageFlags const pipe_stage_flags = vk::PipelineStageFlagBits::eColorAttachmentOutput;
774 auto const submit_info = vk::SubmitInfo()
775 .setPWaitDstStageMask(&pipe_stage_flags)
776 .setWaitSemaphoreCount(1)
777 .setPWaitSemaphores(&image_acquired_semaphores[frame_index])
778 .setCommandBufferCount(1)
779 .setPCommandBuffers(&swapchain_image_resources[current_buffer].cmd)
780 .setSignalSemaphoreCount(1)
781 .setPSignalSemaphores(&draw_complete_semaphores[frame_index]);
782
783 result = graphics_queue.submit(1, &submit_info, fences[frame_index]);
784 VERIFY(result == vk::Result::eSuccess);
785
786 if (separate_present_queue) {
787 // If we are using separate queues, change image ownership to the
788 // present queue before presenting, waiting for the draw complete
789 // semaphore and signalling the ownership released semaphore when
790 // finished
791 auto const present_submit_info = vk::SubmitInfo()
792 .setPWaitDstStageMask(&pipe_stage_flags)
793 .setWaitSemaphoreCount(1)
794 .setPWaitSemaphores(&draw_complete_semaphores[frame_index])
795 .setCommandBufferCount(1)
796 .setPCommandBuffers(&swapchain_image_resources[current_buffer].graphics_to_present_cmd)
797 .setSignalSemaphoreCount(1)
798 .setPSignalSemaphores(&image_ownership_semaphores[frame_index]);
799
800 result = present_queue.submit(1, &present_submit_info, vk::Fence());
801 VERIFY(result == vk::Result::eSuccess);
802 }
803
804 // If we are using separate queues we have to wait for image ownership,
805 // otherwise wait for draw complete
806 auto const presentInfo = vk::PresentInfoKHR()
807 .setWaitSemaphoreCount(1)
808 .setPWaitSemaphores(separate_present_queue ? &image_ownership_semaphores[frame_index]
809 : &draw_complete_semaphores[frame_index])
810 .setSwapchainCount(1)
811 .setPSwapchains(&swapchain)
812 .setPImageIndices(&current_buffer);
813
814 result = present_queue.presentKHR(&presentInfo);
815 frame_index += 1;
816 frame_index %= FRAME_LAG;
817 if (result == vk::Result::eErrorOutOfDateKHR) {
818 // swapchain is out of date (e.g. the window was resized) and
819 // must be recreated:
820 resize();
821 } else if (result == vk::Result::eSuboptimalKHR) {
822 // swapchain is not as optimal as it could be, but the platform's
823 // presentation engine will still present the image correctly.
Tony-LunarG6cebf142019-09-11 14:32:23 -0600824 } else if (result == vk::Result::eErrorSurfaceLostKHR) {
825 inst.destroySurfaceKHR(surface, nullptr);
826 create_surface();
827 resize();
Dave Houlton5fa47912018-02-16 11:02:26 -0700828 } else {
829 VERIFY(result == vk::Result::eSuccess);
830 }
831}
832
833void Demo::draw_build_cmd(vk::CommandBuffer commandBuffer) {
834 auto const commandInfo = vk::CommandBufferBeginInfo().setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
835
836 vk::ClearValue const clearValues[2] = {vk::ClearColorValue(std::array<float, 4>({{0.2f, 0.2f, 0.2f, 0.2f}})),
837 vk::ClearDepthStencilValue(1.0f, 0u)};
838
839 auto const passInfo = vk::RenderPassBeginInfo()
840 .setRenderPass(render_pass)
841 .setFramebuffer(swapchain_image_resources[current_buffer].framebuffer)
842 .setRenderArea(vk::Rect2D(vk::Offset2D(0, 0), vk::Extent2D((uint32_t)width, (uint32_t)height)))
843 .setClearValueCount(2)
844 .setPClearValues(clearValues);
845
846 auto result = commandBuffer.begin(&commandInfo);
847 VERIFY(result == vk::Result::eSuccess);
848
849 commandBuffer.beginRenderPass(&passInfo, vk::SubpassContents::eInline);
850 commandBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
851 commandBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipeline_layout, 0, 1,
852 &swapchain_image_resources[current_buffer].descriptor_set, 0, nullptr);
Jeremy Kniager979b5312019-11-22 14:55:57 -0700853 float viewport_dimension;
854 float viewport_x = 0.0f;
855 float viewport_y = 0.0f;
856 if (width < height) {
857 viewport_dimension = (float)width;
858 viewport_y = (height - width) / 2.0f;
859 } else {
860 viewport_dimension = (float)height;
861 viewport_x = (width - height) / 2.0f;
862 }
863 auto const viewport = vk::Viewport()
864 .setX(viewport_x)
865 .setY(viewport_y)
866 .setWidth((float)viewport_dimension)
867 .setHeight((float)viewport_dimension)
868 .setMinDepth((float)0.0f)
869 .setMaxDepth((float)1.0f);
Dave Houlton5fa47912018-02-16 11:02:26 -0700870 commandBuffer.setViewport(0, 1, &viewport);
871
872 vk::Rect2D const scissor(vk::Offset2D(0, 0), vk::Extent2D(width, height));
873 commandBuffer.setScissor(0, 1, &scissor);
874 commandBuffer.draw(12 * 3, 1, 0, 0);
875 // Note that ending the renderpass changes the image's layout from
876 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
877 commandBuffer.endRenderPass();
878
879 if (separate_present_queue) {
880 // We have to transfer ownership from the graphics queue family to
881 // the
882 // present queue family to be able to present. Note that we don't
883 // have
884 // to transfer from present queue family back to graphics queue
885 // family at
886 // the start of the next frame because we don't care about the
887 // image's
888 // contents at that point.
Jeremy Hayes9d304782016-10-09 11:48:12 -0600889 auto const image_ownership_barrier =
890 vk::ImageMemoryBarrier()
891 .setSrcAccessMask(vk::AccessFlags())
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600892 .setDstAccessMask(vk::AccessFlags())
Jeremy Hayes9d304782016-10-09 11:48:12 -0600893 .setOldLayout(vk::ImageLayout::ePresentSrcKHR)
894 .setNewLayout(vk::ImageLayout::ePresentSrcKHR)
895 .setSrcQueueFamilyIndex(graphics_queue_family_index)
896 .setDstQueueFamilyIndex(present_queue_family_index)
Dave Houlton5fa47912018-02-16 11:02:26 -0700897 .setImage(swapchain_image_resources[current_buffer].image)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700898 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600899
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600900 commandBuffer.pipelineBarrier(vk::PipelineStageFlagBits::eBottomOfPipe, vk::PipelineStageFlagBits::eBottomOfPipe,
Dave Houlton5fa47912018-02-16 11:02:26 -0700901 vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &image_ownership_barrier);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600902 }
903
Dave Houlton5fa47912018-02-16 11:02:26 -0700904 result = commandBuffer.end();
905 VERIFY(result == vk::Result::eSuccess);
906}
907
908void Demo::flush_init_cmd() {
909 // TODO: hmm.
910 // This function could get called twice if the texture uses a staging
911 // buffer
912 // In that case the second call should be ignored
913 if (!cmd) {
914 return;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600915 }
916
Dave Houlton5fa47912018-02-16 11:02:26 -0700917 auto result = cmd.end();
918 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600919
Dave Houlton5fa47912018-02-16 11:02:26 -0700920 auto const fenceInfo = vk::FenceCreateInfo();
921 vk::Fence fence;
922 result = device.createFence(&fenceInfo, nullptr, &fence);
923 VERIFY(result == vk::Result::eSuccess);
924
925 vk::CommandBuffer const commandBuffers[] = {cmd};
926 auto const submitInfo = vk::SubmitInfo().setCommandBufferCount(1).setPCommandBuffers(commandBuffers);
927
928 result = graphics_queue.submit(1, &submitInfo, fence);
929 VERIFY(result == vk::Result::eSuccess);
930
931 result = device.waitForFences(1, &fence, VK_TRUE, UINT64_MAX);
932 VERIFY(result == vk::Result::eSuccess);
933
934 device.freeCommandBuffers(cmd_pool, 1, commandBuffers);
935 device.destroyFence(fence, nullptr);
936
937 cmd = vk::CommandBuffer();
938}
939
940void Demo::init(int argc, char **argv) {
941 vec3 eye = {0.0f, 3.0f, 5.0f};
942 vec3 origin = {0, 0, 0};
943 vec3 up = {0.0f, 1.0f, 0.0};
944
945 presentMode = vk::PresentModeKHR::eFifo;
946 frameCount = UINT32_MAX;
947 use_xlib = false;
Tony-LunarG6cebf142019-09-11 14:32:23 -0600948
Dave Houlton5fa47912018-02-16 11:02:26 -0700949 for (int i = 1; i < argc; i++) {
950 if (strcmp(argv[i], "--use_staging") == 0) {
951 use_staging_buffer = true;
952 continue;
953 }
954 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
955 presentMode = (vk::PresentModeKHR)atoi(argv[i + 1]);
956 i++;
957 continue;
958 }
959 if (strcmp(argv[i], "--break") == 0) {
960 use_break = true;
961 continue;
962 }
963 if (strcmp(argv[i], "--validate") == 0) {
964 validate = true;
965 continue;
966 }
967 if (strcmp(argv[i], "--xlib") == 0) {
968 fprintf(stderr, "--xlib is deprecated and no longer does anything");
969 continue;
970 }
971 if (strcmp(argv[i], "--c") == 0 && frameCount == UINT32_MAX && i < argc - 1 &&
972 sscanf(argv[i + 1], "%" SCNu32, &frameCount) == 1) {
973 i++;
974 continue;
975 }
976 if (strcmp(argv[i], "--suppress_popups") == 0) {
977 suppress_popups = true;
978 continue;
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600979 }
980
Tony-LunarGd74734f2019-06-04 14:11:43 -0600981 std::stringstream usage;
982 usage << "Usage:\n " << APP_SHORT_NAME << "\t[--use_staging] [--validate]\n"
983 << "\t[--break] [--c <framecount>] [--suppress_popups]\n"
984 << "\t[--present_mode <present mode enum>]\n"
985 << "\t<present_mode_enum>\n"
986 << "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = " << VK_PRESENT_MODE_IMMEDIATE_KHR << "\n"
987 << "\t\tVK_PRESENT_MODE_MAILBOX_KHR = " << VK_PRESENT_MODE_MAILBOX_KHR << "\n"
988 << "\t\tVK_PRESENT_MODE_FIFO_KHR = " << VK_PRESENT_MODE_FIFO_KHR << "\n"
989 << "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = " << VK_PRESENT_MODE_FIFO_RELAXED_KHR;
990
991#if defined(_WIN32)
992 if (!suppress_popups) MessageBox(NULL, usage.str().c_str(), "Usage Error", MB_OK);
993#else
994 std::cerr << usage.str();
995 std::cerr.flush();
996#endif
Dave Houlton5fa47912018-02-16 11:02:26 -0700997 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -0600998 }
999
Dave Houlton5fa47912018-02-16 11:02:26 -07001000 if (!use_xlib) {
1001 init_connection();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001002 }
1003
Dave Houlton5fa47912018-02-16 11:02:26 -07001004 init_vk();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001005
Dave Houlton5fa47912018-02-16 11:02:26 -07001006 width = 500;
1007 height = 500;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001008
Dave Houlton5fa47912018-02-16 11:02:26 -07001009 spin_angle = 4.0f;
1010 spin_increment = 0.2f;
1011 pause = false;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001012
Dave Houlton5fa47912018-02-16 11:02:26 -07001013 mat4x4_perspective(projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
1014 mat4x4_look_at(view_matrix, eye, origin, up);
1015 mat4x4_identity(model_matrix);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001016
Dave Houlton5fa47912018-02-16 11:02:26 -07001017 projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
1018}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001019
Dave Houlton5fa47912018-02-16 11:02:26 -07001020void Demo::init_connection() {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001021#if defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001022 const xcb_setup_t *setup;
1023 xcb_screen_iterator_t iter;
1024 int scr;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001025
Dave Houlton5fa47912018-02-16 11:02:26 -07001026 const char *display_envar = getenv("DISPLAY");
1027 if (display_envar == nullptr || display_envar[0] == '\0') {
1028 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
1029 fflush(stdout);
1030 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001031 }
1032
Dave Houlton5fa47912018-02-16 11:02:26 -07001033 connection = xcb_connect(nullptr, &scr);
1034 if (xcb_connection_has_error(connection) > 0) {
1035 printf(
1036 "Cannot find a compatible Vulkan installable client driver "
1037 "(ICD).\nExiting ...\n");
1038 fflush(stdout);
1039 exit(1);
1040 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001041
Dave Houlton5fa47912018-02-16 11:02:26 -07001042 setup = xcb_get_setup(connection);
1043 iter = xcb_setup_roots_iterator(setup);
1044 while (scr-- > 0) xcb_screen_next(&iter);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001045
Dave Houlton5fa47912018-02-16 11:02:26 -07001046 screen = iter.data;
1047#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1048 display = wl_display_connect(nullptr);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001049
Dave Houlton5fa47912018-02-16 11:02:26 -07001050 if (display == nullptr) {
1051 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
1052 fflush(stdout);
1053 exit(1);
1054 }
1055
1056 registry = wl_display_get_registry(display);
1057 wl_registry_add_listener(registry, &registry_listener, this);
1058 wl_display_dispatch(display);
Dave Houlton5fa47912018-02-16 11:02:26 -07001059#endif
1060}
1061
1062void Demo::init_vk() {
1063 uint32_t instance_extension_count = 0;
1064 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001065 char const *const instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Dave Houlton5fa47912018-02-16 11:02:26 -07001066 enabled_extension_count = 0;
1067 enabled_layer_count = 0;
1068
Dave Houlton5fa47912018-02-16 11:02:26 -07001069 // Look for validation layers
1070 vk::Bool32 validation_found = VK_FALSE;
1071 if (validate) {
Mike Schuchardt7510c832018-10-29 13:23:08 -07001072 auto result = vk::enumerateInstanceLayerProperties(&instance_layer_count, static_cast<vk::LayerProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001073 VERIFY(result == vk::Result::eSuccess);
1074
Dave Houlton5fa47912018-02-16 11:02:26 -07001075 if (instance_layer_count > 0) {
1076 std::unique_ptr<vk::LayerProperties[]> instance_layers(new vk::LayerProperties[instance_layer_count]);
1077 result = vk::enumerateInstanceLayerProperties(&instance_layer_count, instance_layers.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001078 VERIFY(result == vk::Result::eSuccess);
1079
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001080 validation_found = check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07001081 instance_layer_count, instance_layers.get());
1082 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06001083 enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
1084 enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001085 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001086 }
1087
Dave Houlton5fa47912018-02-16 11:02:26 -07001088 if (!validation_found) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001089 ERR_EXIT(
Dave Houlton5fa47912018-02-16 11:02:26 -07001090 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
1091 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07001092 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001093 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001094 }
1095
Dave Houlton5fa47912018-02-16 11:02:26 -07001096 /* Look for instance extensions */
1097 vk::Bool32 surfaceExtFound = VK_FALSE;
1098 vk::Bool32 platformSurfaceExtFound = VK_FALSE;
1099 memset(extension_names, 0, sizeof(extension_names));
1100
Mike Schuchardt7510c832018-10-29 13:23:08 -07001101 auto result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count,
1102 static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001103 VERIFY(result == vk::Result::eSuccess);
1104
1105 if (instance_extension_count > 0) {
1106 std::unique_ptr<vk::ExtensionProperties[]> instance_extensions(new vk::ExtensionProperties[instance_extension_count]);
1107 result = vk::enumerateInstanceExtensionProperties(nullptr, &instance_extension_count, instance_extensions.get());
1108 VERIFY(result == vk::Result::eSuccess);
1109
1110 for (uint32_t i = 0; i < instance_extension_count; i++) {
1111 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1112 surfaceExtFound = 1;
1113 extension_names[enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
1114 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001115#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001116 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1117 platformSurfaceExtFound = 1;
1118 extension_names[enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
1119 }
1120#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1121 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1122 platformSurfaceExtFound = 1;
1123 extension_names[enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
1124 }
1125#elif defined(VK_USE_PLATFORM_XCB_KHR)
1126 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1127 platformSurfaceExtFound = 1;
1128 extension_names[enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
1129 }
Tony Barbour153cb062016-12-07 13:43:36 -07001130#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001131 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1132 platformSurfaceExtFound = 1;
1133 extension_names[enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
1134 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001135#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1136 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1137 platformSurfaceExtFound = 1;
1138 extension_names[enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
1139 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001140#elif defined(VK_USE_PLATFORM_IOS_MVK)
1141 if (!strcmp(VK_MVK_IOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1142 platformSurfaceExtFound = 1;
1143 extension_names[enabled_extension_count++] = VK_MVK_IOS_SURFACE_EXTENSION_NAME;
1144 }
1145#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1146 if (!strcmp(VK_MVK_MACOS_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
1147 platformSurfaceExtFound = 1;
1148 extension_names[enabled_extension_count++] = VK_MVK_MACOS_SURFACE_EXTENSION_NAME;
1149 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001150
Dave Houlton5fa47912018-02-16 11:02:26 -07001151#endif
1152 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001153 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001154 }
1155
1156 if (!surfaceExtFound) {
1157 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1158 " extension.\n\n"
1159 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1160 "Please look at the Getting Started guide for additional information.\n",
1161 "vkCreateInstance Failure");
1162 }
1163
1164 if (!platformSurfaceExtFound) {
1165#if defined(VK_USE_PLATFORM_WIN32_KHR)
1166 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1167 " extension.\n\n"
1168 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1169 "Please look at the Getting Started guide for additional information.\n",
1170 "vkCreateInstance Failure");
1171#elif defined(VK_USE_PLATFORM_XCB_KHR)
1172 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1173 " extension.\n\n"
1174 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1175 "Please look at the Getting Started guide for additional information.\n",
1176 "vkCreateInstance Failure");
1177#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1178 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1179 " extension.\n\n"
1180 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1181 "Please look at the Getting Started guide for additional information.\n",
1182 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001183#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001184 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1185 " extension.\n\n"
1186 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1187 "Please look at the Getting Started guide for additional information.\n",
1188 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001189#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001190 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1191 " extension.\n\n"
1192 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1193 "Please look at the Getting Started guide for additional information.\n",
1194 "vkCreateInstance Failure");
Karl Schultz9ceac062017-12-12 10:33:01 -05001195#elif defined(VK_USE_PLATFORM_IOS_MVK)
1196 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_IOS_SURFACE_EXTENSION_NAME
1197 " extension.\n\nDo you have a compatible "
1198 "Vulkan installable client driver (ICD) installed?\nPlease "
1199 "look at the Getting Started guide for additional "
1200 "information.\n",
1201 "vkCreateInstance Failure");
1202#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1203 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_MVK_MACOS_SURFACE_EXTENSION_NAME
1204 " extension.\n\nDo you have a compatible "
1205 "Vulkan installable client driver (ICD) installed?\nPlease "
1206 "look at the Getting Started guide for additional "
1207 "information.\n",
1208 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001209#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001210 }
1211 auto const app = vk::ApplicationInfo()
1212 .setPApplicationName(APP_SHORT_NAME)
1213 .setApplicationVersion(0)
1214 .setPEngineName(APP_SHORT_NAME)
1215 .setEngineVersion(0)
1216 .setApiVersion(VK_API_VERSION_1_0);
1217 auto const inst_info = vk::InstanceCreateInfo()
1218 .setPApplicationInfo(&app)
1219 .setEnabledLayerCount(enabled_layer_count)
1220 .setPpEnabledLayerNames(instance_validation_layers)
1221 .setEnabledExtensionCount(enabled_extension_count)
1222 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001223
Dave Houlton5fa47912018-02-16 11:02:26 -07001224 result = vk::createInstance(&inst_info, nullptr, &inst);
1225 if (result == vk::Result::eErrorIncompatibleDriver) {
1226 ERR_EXIT(
1227 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1228 "Please look at the Getting Started guide for additional information.\n",
1229 "vkCreateInstance Failure");
1230 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1231 ERR_EXIT(
1232 "Cannot find a specified extension library.\n"
1233 "Make sure your layers path is set appropriately.\n",
1234 "vkCreateInstance Failure");
1235 } else if (result != vk::Result::eSuccess) {
1236 ERR_EXIT(
1237 "vkCreateInstance failed.\n\n"
1238 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1239 "Please look at the Getting Started guide for additional information.\n",
1240 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001241 }
1242
Dave Houlton5fa47912018-02-16 11:02:26 -07001243 /* Make initial call to query gpu_count, then second call for gpu info*/
1244 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001245 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001246 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001247
1248 if (gpu_count > 0) {
1249 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1250 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001251 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001252 /* For cube demo we just grab the first physical device */
1253 gpu = physical_devices[0];
1254 } else {
1255 ERR_EXIT(
1256 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1257 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1258 "Please look at the Getting Started guide for additional information.\n",
1259 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001260 }
1261
Dave Houlton5fa47912018-02-16 11:02:26 -07001262 /* Look for device extensions */
1263 uint32_t device_extension_count = 0;
1264 vk::Bool32 swapchainExtFound = VK_FALSE;
1265 enabled_extension_count = 0;
1266 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001267
Mike Schuchardt7510c832018-10-29 13:23:08 -07001268 result =
1269 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001270 VERIFY(result == vk::Result::eSuccess);
1271
1272 if (device_extension_count > 0) {
1273 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1274 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001275 VERIFY(result == vk::Result::eSuccess);
1276
Dave Houlton5fa47912018-02-16 11:02:26 -07001277 for (uint32_t i = 0; i < device_extension_count; i++) {
1278 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1279 swapchainExtFound = 1;
1280 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001281 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001282 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001283 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001284 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001285
Dave Houlton5fa47912018-02-16 11:02:26 -07001286 if (!swapchainExtFound) {
1287 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1288 " extension.\n\n"
1289 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1290 "Please look at the Getting Started guide for additional information.\n",
1291 "vkCreateInstance Failure");
1292 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001293
Dave Houlton5fa47912018-02-16 11:02:26 -07001294 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001295
Dave Houlton5fa47912018-02-16 11:02:26 -07001296 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001297 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001298 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001299
Dave Houlton5fa47912018-02-16 11:02:26 -07001300 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1301 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001302
Dave Houlton5fa47912018-02-16 11:02:26 -07001303 // Query fine-grained feature support for this device.
1304 // If app has specific feature requirements it should check supported
1305 // features based on this query
1306 vk::PhysicalDeviceFeatures physDevFeatures;
1307 gpu.getFeatures(&physDevFeatures);
1308}
1309
Tony-LunarG6cebf142019-09-11 14:32:23 -06001310void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001311// Create a WSI surface for the window:
1312#if defined(VK_USE_PLATFORM_WIN32_KHR)
1313 {
1314 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1315
1316 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1317 VERIFY(result == vk::Result::eSuccess);
1318 }
1319#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1320 {
1321 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1322
1323 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1324 VERIFY(result == vk::Result::eSuccess);
1325 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001326#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1327 {
1328 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1329
1330 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1331 VERIFY(result == vk::Result::eSuccess);
1332 }
1333#elif defined(VK_USE_PLATFORM_XCB_KHR)
1334 {
1335 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1336
1337 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1338 VERIFY(result == vk::Result::eSuccess);
1339 }
Karl Schultz9ceac062017-12-12 10:33:01 -05001340#elif defined(VK_USE_PLATFORM_IOS_MVK)
1341 {
1342 auto const createInfo = vk::IOSSurfaceCreateInfoMVK().setPView(nullptr);
1343
1344 auto result = inst.createIOSSurfaceMVK(&createInfo, nullptr, &surface);
1345 VERIFY(result == vk::Result::eSuccess);
1346 }
1347#elif defined(VK_USE_PLATFORM_MACOS_MVK)
1348 {
1349 auto const createInfo = vk::MacOSSurfaceCreateInfoMVK().setPView(window);
1350
1351 auto result = inst.createMacOSSurfaceMVK(&createInfo, nullptr, &surface);
1352 VERIFY(result == vk::Result::eSuccess);
1353 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001354#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1355 {
1356 auto result = create_display_surface();
1357 VERIFY(result == vk::Result::eSuccess);
1358 }
1359#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001360}
1361
1362void Demo::init_vk_swapchain() {
1363 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001364 // Iterate over each queue to learn whether it supports presenting:
1365 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1366 for (uint32_t i = 0; i < queue_family_count; i++) {
1367 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1368 }
1369
1370 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1371 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1372 for (uint32_t i = 0; i < queue_family_count; i++) {
1373 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1374 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1375 graphicsQueueFamilyIndex = i;
1376 }
1377
1378 if (supportsPresent[i] == VK_TRUE) {
1379 graphicsQueueFamilyIndex = i;
1380 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001381 break;
1382 }
1383 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001385
Dave Houlton5fa47912018-02-16 11:02:26 -07001386 if (presentQueueFamilyIndex == UINT32_MAX) {
1387 // If didn't find a queue that supports both graphics and present,
1388 // then
1389 // find a separate present queue.
1390 for (uint32_t i = 0; i < queue_family_count; ++i) {
1391 if (supportsPresent[i] == VK_TRUE) {
1392 presentQueueFamilyIndex = i;
1393 break;
1394 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001395 }
1396 }
1397
Dave Houlton5fa47912018-02-16 11:02:26 -07001398 // Generate error if could not find both a graphics and a present queue
1399 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1400 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1401 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001402
Dave Houlton5fa47912018-02-16 11:02:26 -07001403 graphics_queue_family_index = graphicsQueueFamilyIndex;
1404 present_queue_family_index = presentQueueFamilyIndex;
1405 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001406
Dave Houlton5fa47912018-02-16 11:02:26 -07001407 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001408
Dave Houlton5fa47912018-02-16 11:02:26 -07001409 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1410 if (!separate_present_queue) {
1411 present_queue = graphics_queue;
1412 } else {
1413 device.getQueue(present_queue_family_index, 0, &present_queue);
1414 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001415
Dave Houlton5fa47912018-02-16 11:02:26 -07001416 // Get the list of VkFormat's that are supported:
1417 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001418 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001419 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001420
Dave Houlton5fa47912018-02-16 11:02:26 -07001421 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1422 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1423 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001424
Dave Houlton5fa47912018-02-16 11:02:26 -07001425 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1426 // the surface has no preferred format. Otherwise, at least one
1427 // supported format will be returned.
1428 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1429 format = vk::Format::eB8G8R8A8Unorm;
1430 } else {
1431 assert(formatCount >= 1);
1432 format = surfFormats[0].format;
1433 }
1434 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001435
Dave Houlton5fa47912018-02-16 11:02:26 -07001436 quit = false;
1437 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001438
Dave Houlton5fa47912018-02-16 11:02:26 -07001439 // Create semaphores to synchronize acquiring presentable buffers before
1440 // rendering and waiting for drawing to be complete before presenting
1441 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001442
Dave Houlton5fa47912018-02-16 11:02:26 -07001443 // Create fences that we can use to throttle if we get too far
1444 // ahead of the image presents
1445 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1446 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1447 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1448 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001449
Dave Houlton5fa47912018-02-16 11:02:26 -07001450 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1451 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001452
Dave Houlton5fa47912018-02-16 11:02:26 -07001453 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1454 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001455
Dave Houlton5fa47912018-02-16 11:02:26 -07001456 if (separate_present_queue) {
1457 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001458 VERIFY(result == vk::Result::eSuccess);
1459 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001460 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001461 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001462
Dave Houlton5fa47912018-02-16 11:02:26 -07001463 // Get Memory information and properties
1464 gpu.getMemoryProperties(&memory_properties);
1465}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001466
Dave Houlton5fa47912018-02-16 11:02:26 -07001467void Demo::prepare() {
1468 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1469 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1470 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001471
Dave Houlton5fa47912018-02-16 11:02:26 -07001472 auto const cmd = vk::CommandBufferAllocateInfo()
1473 .setCommandPool(cmd_pool)
1474 .setLevel(vk::CommandBufferLevel::ePrimary)
1475 .setCommandBufferCount(1);
1476
1477 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1478 VERIFY(result == vk::Result::eSuccess);
1479
1480 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1481
1482 result = this->cmd.begin(&cmd_buf_info);
1483 VERIFY(result == vk::Result::eSuccess);
1484
1485 prepare_buffers();
1486 prepare_depth();
1487 prepare_textures();
1488 prepare_cube_data_buffers();
1489
1490 prepare_descriptor_layout();
1491 prepare_render_pass();
1492 prepare_pipeline();
1493
1494 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1495 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1496 VERIFY(result == vk::Result::eSuccess);
1497 }
1498
1499 if (separate_present_queue) {
1500 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1501
1502 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1503 VERIFY(result == vk::Result::eSuccess);
1504
1505 auto const present_cmd = vk::CommandBufferAllocateInfo()
1506 .setCommandPool(present_cmd_pool)
1507 .setLevel(vk::CommandBufferLevel::ePrimary)
1508 .setCommandBufferCount(1);
1509
1510 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1511 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1512 VERIFY(result == vk::Result::eSuccess);
1513
1514 build_image_ownership_cmd(i);
1515 }
1516 }
1517
1518 prepare_descriptor_pool();
1519 prepare_descriptor_set();
1520
1521 prepare_framebuffers();
1522
1523 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1524 current_buffer = i;
1525 draw_build_cmd(swapchain_image_resources[i].cmd);
1526 }
1527
1528 /*
1529 * Prepare functions above may generate pipeline commands
1530 * that need to be flushed before beginning the render loop.
1531 */
1532 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001533 if (staging_texture.buffer) {
1534 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001535 }
1536
1537 current_buffer = 0;
1538 prepared = true;
1539}
1540
1541void Demo::prepare_buffers() {
1542 vk::SwapchainKHR oldSwapchain = swapchain;
1543
1544 // Check the surface capabilities and formats
1545 vk::SurfaceCapabilitiesKHR surfCapabilities;
1546 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1547 VERIFY(result == vk::Result::eSuccess);
1548
1549 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001550 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001551 VERIFY(result == vk::Result::eSuccess);
1552
1553 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1554 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1555 VERIFY(result == vk::Result::eSuccess);
1556
1557 vk::Extent2D swapchainExtent;
1558 // width and height are either both -1, or both not -1.
1559 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1560 // If the surface size is undefined, the size is set to
1561 // the size of the images requested.
1562 swapchainExtent.width = width;
1563 swapchainExtent.height = height;
1564 } else {
1565 // If the surface size is defined, the swap chain size must match
1566 swapchainExtent = surfCapabilities.currentExtent;
1567 width = surfCapabilities.currentExtent.width;
1568 height = surfCapabilities.currentExtent.height;
1569 }
1570
1571 // The FIFO present mode is guaranteed by the spec to be supported
1572 // and to have no tearing. It's a great default present mode to use.
1573 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1574
1575 // There are times when you may wish to use another present mode. The
1576 // following code shows how to select them, and the comments provide some
1577 // reasons you may wish to use them.
1578 //
1579 // It should be noted that Vulkan 1.0 doesn't provide a method for
1580 // synchronizing rendering with the presentation engine's display. There
1581 // is a method provided for throttling rendering with the display, but
1582 // there are some presentation engines for which this method will not work.
1583 // If an application doesn't throttle its rendering, and if it renders much
1584 // faster than the refresh rate of the display, this can waste power on
1585 // mobile devices. That is because power is being spent rendering images
1586 // that may never be seen.
1587
1588 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1589 // about
1590 // tearing, or have some way of synchronizing their rendering with the
1591 // display.
1592 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1593 // generally render a new presentable image every refresh cycle, but are
1594 // occasionally early. In this case, the application wants the new
1595 // image
1596 // to be displayed instead of the previously-queued-for-presentation
1597 // image
1598 // that has not yet been displayed.
1599 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1600 // render a new presentable image every refresh cycle, but are
1601 // occasionally
1602 // late. In this case (perhaps because of stuttering/latency concerns),
1603 // the application wants the late image to be immediately displayed,
1604 // even
1605 // though that may mean some tearing.
1606
1607 if (presentMode != swapchainPresentMode) {
1608 for (size_t i = 0; i < presentModeCount; ++i) {
1609 if (presentModes[i] == presentMode) {
1610 swapchainPresentMode = presentMode;
1611 break;
1612 }
1613 }
1614 }
1615
1616 if (swapchainPresentMode != presentMode) {
1617 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1618 }
1619
1620 // Determine the number of VkImages to use in the swap chain.
1621 // Application desires to acquire 3 images at a time for triple
1622 // buffering
1623 uint32_t desiredNumOfSwapchainImages = 3;
1624 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1625 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1626 }
1627
1628 // If maxImageCount is 0, we can ask for as many images as we want,
1629 // otherwise
1630 // we're limited to maxImageCount
1631 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1632 // Application must settle for fewer images than desired:
1633 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1634 }
1635
1636 vk::SurfaceTransformFlagBitsKHR preTransform;
1637 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1638 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1639 } else {
1640 preTransform = surfCapabilities.currentTransform;
1641 }
1642
1643 // Find a supported composite alpha mode - one of these is guaranteed to be set
1644 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1645 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1646 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1647 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1648 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1649 vk::CompositeAlphaFlagBitsKHR::eInherit,
1650 };
1651 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1652 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1653 compositeAlpha = compositeAlphaFlags[i];
1654 break;
1655 }
1656 }
1657
1658 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1659 .setSurface(surface)
1660 .setMinImageCount(desiredNumOfSwapchainImages)
1661 .setImageFormat(format)
1662 .setImageColorSpace(color_space)
1663 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1664 .setImageArrayLayers(1)
1665 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1666 .setImageSharingMode(vk::SharingMode::eExclusive)
1667 .setQueueFamilyIndexCount(0)
1668 .setPQueueFamilyIndices(nullptr)
1669 .setPreTransform(preTransform)
1670 .setCompositeAlpha(compositeAlpha)
1671 .setPresentMode(swapchainPresentMode)
1672 .setClipped(true)
1673 .setOldSwapchain(oldSwapchain);
1674
1675 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1676 VERIFY(result == vk::Result::eSuccess);
1677
1678 // If we just re-created an existing swapchain, we should destroy the
1679 // old
1680 // swapchain at this point.
1681 // Note: destroying the swapchain also cleans up all its associated
1682 // presentable images once the platform is done with them.
1683 if (oldSwapchain) {
1684 device.destroySwapchainKHR(oldSwapchain, nullptr);
1685 }
1686
Mike Schuchardt7510c832018-10-29 13:23:08 -07001687 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001688 VERIFY(result == vk::Result::eSuccess);
1689
1690 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1691 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1692 VERIFY(result == vk::Result::eSuccess);
1693
1694 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1695
1696 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1697 auto color_image_view = vk::ImageViewCreateInfo()
1698 .setViewType(vk::ImageViewType::e2D)
1699 .setFormat(format)
1700 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1701
1702 swapchain_image_resources[i].image = swapchainImages[i];
1703
1704 color_image_view.image = swapchain_image_resources[i].image;
1705
1706 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1707 VERIFY(result == vk::Result::eSuccess);
1708 }
1709}
1710
1711void Demo::prepare_cube_data_buffers() {
1712 mat4x4 VP;
1713 mat4x4_mul(VP, projection_matrix, view_matrix);
1714
1715 mat4x4 MVP;
1716 mat4x4_mul(MVP, VP, model_matrix);
1717
1718 vktexcube_vs_uniform data;
1719 memcpy(data.mvp, MVP, sizeof(MVP));
1720 // dumpMatrix("MVP", MVP)
1721
1722 for (int32_t i = 0; i < 12 * 3; i++) {
1723 data.position[i][0] = g_vertex_buffer_data[i * 3];
1724 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1725 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1726 data.position[i][3] = 1.0f;
1727 data.attr[i][0] = g_uv_buffer_data[2 * i];
1728 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1729 data.attr[i][2] = 0;
1730 data.attr[i][3] = 0;
1731 }
1732
1733 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1734
1735 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1736 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001737 VERIFY(result == vk::Result::eSuccess);
1738
1739 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001740 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001741
Dave Houlton5fa47912018-02-16 11:02:26 -07001742 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001743
Dave Houlton5fa47912018-02-16 11:02:26 -07001744 bool const pass = memory_type_from_properties(
1745 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1746 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001747 VERIFY(pass);
1748
Dave Houlton5fa47912018-02-16 11:02:26 -07001749 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001750 VERIFY(result == vk::Result::eSuccess);
1751
Dave Houlton5fa47912018-02-16 11:02:26 -07001752 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1753 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001754
Dave Houlton5fa47912018-02-16 11:02:26 -07001755 memcpy(pData.value, &data, sizeof data);
1756
1757 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1758
1759 result =
1760 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001761 VERIFY(result == vk::Result::eSuccess);
1762 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001763}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001764
Dave Houlton5fa47912018-02-16 11:02:26 -07001765void Demo::prepare_depth() {
1766 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001767
Dave Houlton5fa47912018-02-16 11:02:26 -07001768 auto const image = vk::ImageCreateInfo()
1769 .setImageType(vk::ImageType::e2D)
1770 .setFormat(depth.format)
1771 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1772 .setMipLevels(1)
1773 .setArrayLayers(1)
1774 .setSamples(vk::SampleCountFlagBits::e1)
1775 .setTiling(vk::ImageTiling::eOptimal)
1776 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1777 .setSharingMode(vk::SharingMode::eExclusive)
1778 .setQueueFamilyIndexCount(0)
1779 .setPQueueFamilyIndices(nullptr)
1780 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001781
Dave Houlton5fa47912018-02-16 11:02:26 -07001782 auto result = device.createImage(&image, nullptr, &depth.image);
1783 VERIFY(result == vk::Result::eSuccess);
1784
1785 vk::MemoryRequirements mem_reqs;
1786 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1787
1788 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1789 depth.mem_alloc.setMemoryTypeIndex(0);
1790
1791 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1792 &depth.mem_alloc.memoryTypeIndex);
1793 VERIFY(pass);
1794
1795 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1796 VERIFY(result == vk::Result::eSuccess);
1797
1798 result = device.bindImageMemory(depth.image, depth.mem, 0);
1799 VERIFY(result == vk::Result::eSuccess);
1800
1801 auto const view = vk::ImageViewCreateInfo()
1802 .setImage(depth.image)
1803 .setViewType(vk::ImageViewType::e2D)
1804 .setFormat(depth.format)
1805 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1806 result = device.createImageView(&view, nullptr, &depth.view);
1807 VERIFY(result == vk::Result::eSuccess);
1808}
1809
1810void Demo::prepare_descriptor_layout() {
1811 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1812 .setBinding(0)
1813 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1814 .setDescriptorCount(1)
1815 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1816 .setPImmutableSamplers(nullptr),
1817 vk::DescriptorSetLayoutBinding()
1818 .setBinding(1)
1819 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1820 .setDescriptorCount(texture_count)
1821 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1822 .setPImmutableSamplers(nullptr)};
1823
1824 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1825
1826 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1827 VERIFY(result == vk::Result::eSuccess);
1828
1829 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1830
1831 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1832 VERIFY(result == vk::Result::eSuccess);
1833}
1834
1835void Demo::prepare_descriptor_pool() {
1836 vk::DescriptorPoolSize const poolSizes[2] = {
1837 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1838 vk::DescriptorPoolSize()
1839 .setType(vk::DescriptorType::eCombinedImageSampler)
1840 .setDescriptorCount(swapchainImageCount * texture_count)};
1841
1842 auto const descriptor_pool =
1843 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1844
1845 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1846 VERIFY(result == vk::Result::eSuccess);
1847}
1848
1849void Demo::prepare_descriptor_set() {
1850 auto const alloc_info =
1851 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1852
1853 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1854
1855 vk::DescriptorImageInfo tex_descs[texture_count];
1856 for (uint32_t i = 0; i < texture_count; i++) {
1857 tex_descs[i].setSampler(textures[i].sampler);
1858 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001859 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001860 }
1861
1862 vk::WriteDescriptorSet writes[2];
1863
1864 writes[0].setDescriptorCount(1);
1865 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1866 writes[0].setPBufferInfo(&buffer_info);
1867
1868 writes[1].setDstBinding(1);
1869 writes[1].setDescriptorCount(texture_count);
1870 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1871 writes[1].setPImageInfo(tex_descs);
1872
1873 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1874 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001875 VERIFY(result == vk::Result::eSuccess);
1876
Dave Houlton5fa47912018-02-16 11:02:26 -07001877 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1878 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1879 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1880 device.updateDescriptorSets(2, writes, 0, nullptr);
1881 }
1882}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001883
Dave Houlton5fa47912018-02-16 11:02:26 -07001884void Demo::prepare_framebuffers() {
1885 vk::ImageView attachments[2];
1886 attachments[1] = depth.view;
1887
1888 auto const fb_info = vk::FramebufferCreateInfo()
1889 .setRenderPass(render_pass)
1890 .setAttachmentCount(2)
1891 .setPAttachments(attachments)
1892 .setWidth((uint32_t)width)
1893 .setHeight((uint32_t)height)
1894 .setLayers(1);
1895
1896 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1897 attachments[0] = swapchain_image_resources[i].view;
1898 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001899 VERIFY(result == vk::Result::eSuccess);
1900 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001901}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001902
Dave Houlton5fa47912018-02-16 11:02:26 -07001903vk::ShaderModule Demo::prepare_fs() {
1904 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001905#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001906 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001907
Dave Houlton5fa47912018-02-16 11:02:26 -07001908 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001909
Dave Houlton5fa47912018-02-16 11:02:26 -07001910 return frag_shader_module;
1911}
1912
1913void Demo::prepare_pipeline() {
1914 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1915 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1916 VERIFY(result == vk::Result::eSuccess);
1917
1918 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1919 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1920 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1921
1922 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1923
1924 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1925
1926 // TODO: Where are pViewports and pScissors set?
1927 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1928
1929 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1930 .setDepthClampEnable(VK_FALSE)
1931 .setRasterizerDiscardEnable(VK_FALSE)
1932 .setPolygonMode(vk::PolygonMode::eFill)
1933 .setCullMode(vk::CullModeFlagBits::eBack)
1934 .setFrontFace(vk::FrontFace::eCounterClockwise)
1935 .setDepthBiasEnable(VK_FALSE)
1936 .setLineWidth(1.0f);
1937
1938 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1939
1940 auto const stencilOp =
1941 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1942
1943 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1944 .setDepthTestEnable(VK_TRUE)
1945 .setDepthWriteEnable(VK_TRUE)
1946 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1947 .setDepthBoundsTestEnable(VK_FALSE)
1948 .setStencilTestEnable(VK_FALSE)
1949 .setFront(stencilOp)
1950 .setBack(stencilOp);
1951
1952 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1953 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1954 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1955
1956 auto const colorBlendInfo =
1957 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1958
1959 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1960
1961 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1962
1963 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1964 .setStageCount(2)
1965 .setPStages(shaderStageInfo)
1966 .setPVertexInputState(&vertexInputInfo)
1967 .setPInputAssemblyState(&inputAssemblyInfo)
1968 .setPViewportState(&viewportInfo)
1969 .setPRasterizationState(&rasterizationInfo)
1970 .setPMultisampleState(&multisampleInfo)
1971 .setPDepthStencilState(&depthStencilInfo)
1972 .setPColorBlendState(&colorBlendInfo)
1973 .setPDynamicState(&dynamicStateInfo)
1974 .setLayout(pipeline_layout)
1975 .setRenderPass(render_pass);
1976
1977 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1978 VERIFY(result == vk::Result::eSuccess);
1979
1980 device.destroyShaderModule(frag_shader_module, nullptr);
1981 device.destroyShaderModule(vert_shader_module, nullptr);
1982}
1983
1984void Demo::prepare_render_pass() {
1985 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1986 // because at the start of the renderpass, we don't care about their contents.
1987 // At the start of the subpass, the color attachment's layout will be transitioned
1988 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1989 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1990 // the renderpass, the color attachment's layout will be transitioned to
1991 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1992 // the renderpass, no barriers are necessary.
1993 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1994 .setFormat(format)
1995 .setSamples(vk::SampleCountFlagBits::e1)
1996 .setLoadOp(vk::AttachmentLoadOp::eClear)
1997 .setStoreOp(vk::AttachmentStoreOp::eStore)
1998 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1999 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2000 .setInitialLayout(vk::ImageLayout::eUndefined)
2001 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
2002 vk::AttachmentDescription()
2003 .setFormat(depth.format)
2004 .setSamples(vk::SampleCountFlagBits::e1)
2005 .setLoadOp(vk::AttachmentLoadOp::eClear)
2006 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
2007 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
2008 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
2009 .setInitialLayout(vk::ImageLayout::eUndefined)
2010 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
2011
2012 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
2013
2014 auto const depth_reference =
2015 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
2016
2017 auto const subpass = vk::SubpassDescription()
2018 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2019 .setInputAttachmentCount(0)
2020 .setPInputAttachments(nullptr)
2021 .setColorAttachmentCount(1)
2022 .setPColorAttachments(&color_reference)
2023 .setPResolveAttachments(nullptr)
2024 .setPDepthStencilAttachment(&depth_reference)
2025 .setPreserveAttachmentCount(0)
2026 .setPPreserveAttachments(nullptr);
2027
Tony-LunarG495604b2019-06-13 15:32:05 -06002028 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2029 vk::SubpassDependency const dependencies[2] = {
2030 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2031 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2032 .setDstSubpass(0)
2033 .setSrcStageMask(stages)
2034 .setDstStageMask(stages)
2035 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2036 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2037 .setDependencyFlags(vk::DependencyFlags()),
2038 vk::SubpassDependency() // Image layout transition
2039 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2040 .setDstSubpass(0)
2041 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2042 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2043 .setSrcAccessMask(vk::AccessFlagBits())
2044 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2045 .setDependencyFlags(vk::DependencyFlags()),
2046 };
2047
Dave Houlton5fa47912018-02-16 11:02:26 -07002048 auto const rp_info = vk::RenderPassCreateInfo()
2049 .setAttachmentCount(2)
2050 .setPAttachments(attachments)
2051 .setSubpassCount(1)
2052 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002053 .setDependencyCount(2)
2054 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002055
2056 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2057 VERIFY(result == vk::Result::eSuccess);
2058}
2059
2060vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2061 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2062
2063 vk::ShaderModule module;
2064 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2065 VERIFY(result == vk::Result::eSuccess);
2066
2067 return module;
2068}
2069
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002070void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2071 int32_t tex_width;
2072 int32_t tex_height;
2073
2074 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2075 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2076 }
2077
2078 tex_obj->tex_width = tex_width;
2079 tex_obj->tex_height = tex_height;
2080
2081 auto const buffer_create_info = vk::BufferCreateInfo()
2082 .setSize(tex_width * tex_height * 4)
2083 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2084 .setSharingMode(vk::SharingMode::eExclusive)
2085 .setQueueFamilyIndexCount(0)
2086 .setPQueueFamilyIndices(nullptr);
2087
2088 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2089 VERIFY(result == vk::Result::eSuccess);
2090
2091 vk::MemoryRequirements mem_reqs;
2092 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2093
2094 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2095 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2096
2097 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2098 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2099 VERIFY(pass == true);
2100
2101 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2102 VERIFY(result == vk::Result::eSuccess);
2103
2104 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2105 VERIFY(result == vk::Result::eSuccess);
2106
2107 vk::SubresourceLayout layout;
2108 memset(&layout, 0, sizeof(layout));
2109 layout.rowPitch = tex_width * 4;
2110 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2111 VERIFY(data.result == vk::Result::eSuccess);
2112
2113 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2114 fprintf(stderr, "Error loading texture: %s\n", filename);
2115 }
2116
2117 device.unmapMemory(tex_obj->mem);
2118}
2119
Dave Houlton5fa47912018-02-16 11:02:26 -07002120void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2121 vk::MemoryPropertyFlags required_props) {
2122 int32_t tex_width;
2123 int32_t tex_height;
2124 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2125 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002126 }
2127
Dave Houlton5fa47912018-02-16 11:02:26 -07002128 tex_obj->tex_width = tex_width;
2129 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002130
Dave Houlton5fa47912018-02-16 11:02:26 -07002131 auto const image_create_info = vk::ImageCreateInfo()
2132 .setImageType(vk::ImageType::e2D)
2133 .setFormat(vk::Format::eR8G8B8A8Unorm)
2134 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2135 .setMipLevels(1)
2136 .setArrayLayers(1)
2137 .setSamples(vk::SampleCountFlagBits::e1)
2138 .setTiling(tiling)
2139 .setUsage(usage)
2140 .setSharingMode(vk::SharingMode::eExclusive)
2141 .setQueueFamilyIndexCount(0)
2142 .setPQueueFamilyIndices(nullptr)
2143 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002144
Dave Houlton5fa47912018-02-16 11:02:26 -07002145 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2146 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002147
Dave Houlton5fa47912018-02-16 11:02:26 -07002148 vk::MemoryRequirements mem_reqs;
2149 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002150
Dave Houlton5fa47912018-02-16 11:02:26 -07002151 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2152 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002153
Dave Houlton5fa47912018-02-16 11:02:26 -07002154 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2155 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002156
Dave Houlton5fa47912018-02-16 11:02:26 -07002157 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2158 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002159
Dave Houlton5fa47912018-02-16 11:02:26 -07002160 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2161 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002162
Dave Houlton5fa47912018-02-16 11:02:26 -07002163 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2164 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2165 vk::SubresourceLayout layout;
2166 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002167
Dave Houlton5fa47912018-02-16 11:02:26 -07002168 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002169 VERIFY(data.result == vk::Result::eSuccess);
2170
Dave Houlton5fa47912018-02-16 11:02:26 -07002171 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2172 fprintf(stderr, "Error loading texture: %s\n", filename);
2173 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002174
Dave Houlton5fa47912018-02-16 11:02:26 -07002175 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002176 }
2177
Dave Houlton5fa47912018-02-16 11:02:26 -07002178 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2179}
2180
2181void Demo::prepare_textures() {
2182 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2183 vk::FormatProperties props;
2184 gpu.getFormatProperties(tex_format, &props);
2185
2186 for (uint32_t i = 0; i < texture_count; i++) {
2187 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2188 /* Device can texture using linear textures */
2189 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2190 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2191 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2192 // shader to run until layout transition completes
2193 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2194 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2195 vk::PipelineStageFlagBits::eFragmentShader);
2196 staging_texture.image = vk::Image();
2197 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2198 /* Must use staging buffer to copy linear texture to optimized */
2199
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002200 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002201
2202 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2203 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2204 vk::MemoryPropertyFlagBits::eDeviceLocal);
2205
Dave Houlton5fa47912018-02-16 11:02:26 -07002206 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2207 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2208 vk::PipelineStageFlagBits::eTransfer);
2209
2210 auto const subresource = vk::ImageSubresourceLayers()
2211 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2212 .setMipLevel(0)
2213 .setBaseArrayLayer(0)
2214 .setLayerCount(1);
2215
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002216 auto const copy_region =
2217 vk::BufferImageCopy()
2218 .setBufferOffset(0)
2219 .setBufferRowLength(staging_texture.tex_width)
2220 .setBufferImageHeight(staging_texture.tex_height)
2221 .setImageSubresource(subresource)
2222 .setImageOffset({0, 0, 0})
2223 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002224
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002225 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002226
2227 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2228 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2229 vk::PipelineStageFlagBits::eFragmentShader);
2230 } else {
2231 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002232 }
2233
Dave Houlton5fa47912018-02-16 11:02:26 -07002234 auto const samplerInfo = vk::SamplerCreateInfo()
2235 .setMagFilter(vk::Filter::eNearest)
2236 .setMinFilter(vk::Filter::eNearest)
2237 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2238 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2239 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2240 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2241 .setMipLodBias(0.0f)
2242 .setAnisotropyEnable(VK_FALSE)
2243 .setMaxAnisotropy(1)
2244 .setCompareEnable(VK_FALSE)
2245 .setCompareOp(vk::CompareOp::eNever)
2246 .setMinLod(0.0f)
2247 .setMaxLod(0.0f)
2248 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2249 .setUnnormalizedCoordinates(VK_FALSE);
2250
2251 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2252 VERIFY(result == vk::Result::eSuccess);
2253
2254 auto const viewInfo = vk::ImageViewCreateInfo()
2255 .setImage(textures[i].image)
2256 .setViewType(vk::ImageViewType::e2D)
2257 .setFormat(tex_format)
2258 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2259
2260 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2261 VERIFY(result == vk::Result::eSuccess);
2262 }
2263}
2264
2265vk::ShaderModule Demo::prepare_vs() {
2266 const uint32_t vertShaderCode[] = {
2267#include "cube.vert.inc"
2268 };
2269
2270 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2271
2272 return vert_shader_module;
2273}
2274
2275void Demo::resize() {
2276 uint32_t i;
2277
2278 // Don't react to resize until after first initialization.
2279 if (!prepared) {
2280 return;
2281 }
2282
2283 // In order to properly resize the window, we must re-create the
2284 // swapchain
2285 // AND redo the command buffers, etc.
2286 //
2287 // First, perform part of the cleanup() function:
2288 prepared = false;
2289 auto result = device.waitIdle();
2290 VERIFY(result == vk::Result::eSuccess);
2291
2292 for (i = 0; i < swapchainImageCount; i++) {
2293 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2294 }
2295
2296 device.destroyDescriptorPool(desc_pool, nullptr);
2297
2298 device.destroyPipeline(pipeline, nullptr);
2299 device.destroyPipelineCache(pipelineCache, nullptr);
2300 device.destroyRenderPass(render_pass, nullptr);
2301 device.destroyPipelineLayout(pipeline_layout, nullptr);
2302 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2303
2304 for (i = 0; i < texture_count; i++) {
2305 device.destroyImageView(textures[i].view, nullptr);
2306 device.destroyImage(textures[i].image, nullptr);
2307 device.freeMemory(textures[i].mem, nullptr);
2308 device.destroySampler(textures[i].sampler, nullptr);
2309 }
2310
2311 device.destroyImageView(depth.view, nullptr);
2312 device.destroyImage(depth.image, nullptr);
2313 device.freeMemory(depth.mem, nullptr);
2314
2315 for (i = 0; i < swapchainImageCount; i++) {
2316 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2317 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2318 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2319 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2320 }
2321
2322 device.destroyCommandPool(cmd_pool, nullptr);
2323 if (separate_present_queue) {
2324 device.destroyCommandPool(present_cmd_pool, nullptr);
2325 }
2326
2327 // Second, re-perform the prepare() function, which will re-create the
2328 // swapchain.
2329 prepare();
2330}
2331
2332void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2333 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2334 assert(cmd);
2335
2336 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2337 vk::AccessFlags flags;
2338
2339 switch (layout) {
2340 case vk::ImageLayout::eTransferDstOptimal:
2341 // Make sure anything that was copying from this image has
2342 // completed
2343 flags = vk::AccessFlagBits::eTransferWrite;
2344 break;
2345 case vk::ImageLayout::eColorAttachmentOptimal:
2346 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2347 break;
2348 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2349 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2350 break;
2351 case vk::ImageLayout::eShaderReadOnlyOptimal:
2352 // Make sure any Copy or CPU writes to image are flushed
2353 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2354 break;
2355 case vk::ImageLayout::eTransferSrcOptimal:
2356 flags = vk::AccessFlagBits::eTransferRead;
2357 break;
2358 case vk::ImageLayout::ePresentSrcKHR:
2359 flags = vk::AccessFlagBits::eMemoryRead;
2360 break;
2361 default:
2362 break;
2363 }
2364
2365 return flags;
2366 };
2367
2368 auto const barrier = vk::ImageMemoryBarrier()
2369 .setSrcAccessMask(srcAccessMask)
2370 .setDstAccessMask(DstAccessMask(newLayout))
2371 .setOldLayout(oldLayout)
2372 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002373 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2374 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002375 .setImage(image)
2376 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2377
2378 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2379}
2380
2381void Demo::update_data_buffer() {
2382 mat4x4 VP;
2383 mat4x4_mul(VP, projection_matrix, view_matrix);
2384
2385 // Rotate around the Y axis
2386 mat4x4 Model;
2387 mat4x4_dup(Model, model_matrix);
2388 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2389
2390 mat4x4 MVP;
2391 mat4x4_mul(MVP, VP, model_matrix);
2392
2393 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2394 VERIFY(data.result == vk::Result::eSuccess);
2395
2396 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2397
2398 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2399}
2400
Karl Schultzb7940402018-05-29 13:09:22 -06002401/* Convert ppm image data from header file into RGBA texture image */
2402#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002403bool 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 -06002404 (void)filename;
2405 char *cPtr;
2406 cPtr = (char *)lunarg_ppm;
2407 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002408 return false;
2409 }
Karl Schultzb7940402018-05-29 13:09:22 -06002410 while (strncmp(cPtr++, "\n", 1))
2411 ;
2412 sscanf(cPtr, "%u %u", width, height);
2413 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002414 return true;
2415 }
Karl Schultzb7940402018-05-29 13:09:22 -06002416 while (strncmp(cPtr++, "\n", 1))
2417 ;
2418 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002419 return false;
2420 }
Karl Schultzb7940402018-05-29 13:09:22 -06002421 while (strncmp(cPtr++, "\n", 1))
2422 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002423 for (int y = 0; y < *height; y++) {
2424 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002425 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002426 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002427 rowPtr[3] = 255; /* Alpha of 1 */
2428 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002429 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002430 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002431 rgba_data += layout->rowPitch;
2432 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002433 return true;
2434}
2435
2436bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2437 // Search memtypes to find first index with those properties
2438 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2439 if ((typeBits & 1) == 1) {
2440 // Type is available, does it match user properties?
2441 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2442 *typeIndex = i;
2443 return true;
2444 }
2445 }
2446 typeBits >>= 1;
2447 }
2448
2449 // No memory types matched, return failure
2450 return false;
2451}
2452
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002453#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002454void Demo::run() {
2455 if (!prepared) {
2456 return;
2457 }
2458
2459 draw();
2460 curFrame++;
2461
Petr Krausd88e4e52019-01-23 18:45:04 +01002462 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002463 PostQuitMessage(validation_error);
2464 }
2465}
2466
2467void Demo::create_window() {
2468 WNDCLASSEX win_class;
2469
2470 // Initialize the window class structure:
2471 win_class.cbSize = sizeof(WNDCLASSEX);
2472 win_class.style = CS_HREDRAW | CS_VREDRAW;
2473 win_class.lpfnWndProc = WndProc;
2474 win_class.cbClsExtra = 0;
2475 win_class.cbWndExtra = 0;
2476 win_class.hInstance = connection; // hInstance
2477 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2478 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2479 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2480 win_class.lpszMenuName = nullptr;
2481 win_class.lpszClassName = name;
2482 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2483
2484 // Register window class:
2485 if (!RegisterClassEx(&win_class)) {
2486 // It didn't work, so try to give a useful error:
2487 printf("Unexpected error trying to start the application!\n");
2488 fflush(stdout);
2489 exit(1);
2490 }
2491
2492 // Create window with the registered class:
2493 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2494 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2495 window = CreateWindowEx(0,
2496 name, // class name
2497 name, // app name
2498 WS_OVERLAPPEDWINDOW | // window style
2499 WS_VISIBLE | WS_SYSMENU,
2500 100, 100, // x/y coords
2501 wr.right - wr.left, // width
2502 wr.bottom - wr.top, // height
2503 nullptr, // handle to parent
2504 nullptr, // handle to menu
2505 connection, // hInstance
2506 nullptr); // no extra parameters
2507
2508 if (!window) {
2509 // It didn't work, so try to give a useful error:
2510 printf("Cannot create a window in which to draw!\n");
2511 fflush(stdout);
2512 exit(1);
2513 }
2514
2515 // Window client area size must be at least 1 pixel high, to prevent
2516 // crash.
2517 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2518 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2519}
2520#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2521
2522void Demo::create_xlib_window() {
2523 const char *display_envar = getenv("DISPLAY");
2524 if (display_envar == nullptr || display_envar[0] == '\0') {
2525 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2526 fflush(stdout);
2527 exit(1);
2528 }
2529
2530 XInitThreads();
2531 display = XOpenDisplay(nullptr);
2532 long visualMask = VisualScreenMask;
2533 int numberOfVisuals;
2534 XVisualInfo vInfoTemplate = {};
2535 vInfoTemplate.screen = DefaultScreen(display);
2536 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2537
2538 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2539
2540 XSetWindowAttributes windowAttributes = {};
2541 windowAttributes.colormap = colormap;
2542 windowAttributes.background_pixel = 0xFFFFFFFF;
2543 windowAttributes.border_pixel = 0;
2544 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2545
2546 xlib_window =
2547 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2548 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2549
2550 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2551 XMapWindow(display, xlib_window);
2552 XFlush(display);
2553 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2554}
2555
2556void Demo::handle_xlib_event(const XEvent *event) {
2557 switch (event->type) {
2558 case ClientMessage:
2559 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2560 quit = true;
2561 }
2562 break;
2563 case KeyPress:
2564 switch (event->xkey.keycode) {
2565 case 0x9: // Escape
2566 quit = true;
2567 break;
2568 case 0x71: // left arrow key
2569 spin_angle -= spin_increment;
2570 break;
2571 case 0x72: // right arrow key
2572 spin_angle += spin_increment;
2573 break;
2574 case 0x41: // space bar
2575 pause = !pause;
2576 break;
2577 }
2578 break;
2579 case ConfigureNotify:
2580 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2581 width = event->xconfigure.width;
2582 height = event->xconfigure.height;
2583 resize();
2584 }
2585 break;
2586 default:
2587 break;
2588 }
2589}
2590
2591void Demo::run_xlib() {
2592 while (!quit) {
2593 XEvent event;
2594
2595 if (pause) {
2596 XNextEvent(display, &event);
2597 handle_xlib_event(&event);
2598 }
2599 while (XPending(display) > 0) {
2600 XNextEvent(display, &event);
2601 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002602 }
2603
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002604 draw();
2605 curFrame++;
2606
Dave Houlton5fa47912018-02-16 11:02:26 -07002607 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2608 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002609 }
2610 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002611}
Tony Barbour153cb062016-12-07 13:43:36 -07002612#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002613
Dave Houlton5fa47912018-02-16 11:02:26 -07002614void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2615 uint8_t event_code = event->response_type & 0x7f;
2616 switch (event_code) {
2617 case XCB_EXPOSE:
2618 // TODO: Resize window
2619 break;
2620 case XCB_CLIENT_MESSAGE:
2621 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2622 quit = true;
2623 }
2624 break;
2625 case XCB_KEY_RELEASE: {
2626 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002627
Dave Houlton5fa47912018-02-16 11:02:26 -07002628 switch (key->detail) {
2629 case 0x9: // Escape
2630 quit = true;
2631 break;
2632 case 0x71: // left arrow key
2633 spin_angle -= spin_increment;
2634 break;
2635 case 0x72: // right arrow key
2636 spin_angle += spin_increment;
2637 break;
2638 case 0x41: // space bar
2639 pause = !pause;
2640 break;
2641 }
2642 } break;
2643 case XCB_CONFIGURE_NOTIFY: {
2644 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2645 if ((width != cfg->width) || (height != cfg->height)) {
2646 width = cfg->width;
2647 height = cfg->height;
2648 resize();
2649 }
2650 } break;
2651 default:
2652 break;
2653 }
2654}
2655
2656void Demo::run_xcb() {
2657 xcb_flush(connection);
2658
2659 while (!quit) {
2660 xcb_generic_event_t *event;
2661
2662 if (pause) {
2663 event = xcb_wait_for_event(connection);
2664 } else {
2665 event = xcb_poll_for_event(connection);
2666 }
2667 while (event) {
2668 handle_xcb_event(event);
2669 free(event);
2670 event = xcb_poll_for_event(connection);
2671 }
2672
2673 draw();
2674 curFrame++;
2675 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2676 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002677 }
2678 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002679}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002680
Dave Houlton5fa47912018-02-16 11:02:26 -07002681void Demo::create_xcb_window() {
2682 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002683
Dave Houlton5fa47912018-02-16 11:02:26 -07002684 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002685
Dave Houlton5fa47912018-02-16 11:02:26 -07002686 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2687 value_list[0] = screen->black_pixel;
2688 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002689
Dave Houlton5fa47912018-02-16 11:02:26 -07002690 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2691 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2692
2693 /* Magic code that will send notification when window is destroyed */
2694 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2695 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2696
2697 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2698 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2699
2700 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2701
2702 free(reply);
2703
2704 xcb_map_window(connection, xcb_window);
2705
2706 // Force the x/y coordinates to 100,100 results are identical in
2707 // consecutive
2708 // runs
2709 const uint32_t coords[] = {100, 100};
2710 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2711}
2712#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2713
2714void Demo::run() {
2715 while (!quit) {
2716 if (pause) {
2717 wl_display_dispatch(display);
2718 } else {
2719 wl_display_dispatch_pending(display);
2720 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002721 draw();
2722 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002723 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002724 quit = true;
2725 }
2726 }
2727 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002728}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002729
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002730static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2731 Demo *demo = (Demo *)data;
2732 xdg_surface_ack_configure(xdg_surface, serial);
2733 if (demo->xdg_surface_has_been_configured) {
2734 demo->resize();
2735 }
2736 demo->xdg_surface_has_been_configured = true;
2737}
2738
2739static const xdg_surface_listener surface_listener = {handle_surface_configure};
2740
2741static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2742 struct wl_array *states) {
2743 Demo *demo = (Demo *)data;
2744 demo->width = width;
2745 demo->height = height;
2746 // This will be followed by a surface configure
2747}
2748
2749static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2750 Demo *demo = (Demo *)data;
2751 demo->quit = true;
2752}
2753
2754static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2755
Dave Houlton5fa47912018-02-16 11:02:26 -07002756void Demo::create_window() {
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002757 if (!wm_base) {
2758 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2759 fflush(stdout);
2760 exit(1);
2761 }
2762
Dave Houlton5fa47912018-02-16 11:02:26 -07002763 window = wl_compositor_create_surface(compositor);
2764 if (!window) {
2765 printf("Can not create wayland_surface from compositor!\n");
2766 fflush(stdout);
2767 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002768 }
2769
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002770 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2771 if (!window_surface) {
2772 printf("Can not get xdg_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002773 fflush(stdout);
2774 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002775 }
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002776 window_toplevel = xdg_surface_get_toplevel(window_surface);
2777 if (!window_toplevel) {
2778 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2779 fflush(stdout);
2780 exit(1);
2781 }
2782 xdg_surface_add_listener(window_surface, &surface_listener, this);
2783 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2784 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2785 if (xdg_decoration_mgr) {
2786 // if supported, let the compositor render titlebars for us
2787 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2788 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2789 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002790
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002791 wl_surface_commit(window);
Dave Houlton5fa47912018-02-16 11:02:26 -07002792}
Karl Schultz206b1c52018-04-13 18:02:07 -06002793#elif defined(VK_USE_PLATFORM_MACOS_MVK)
2794void Demo::run() {
2795 draw();
2796 curFrame++;
2797 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2798 quit = true;
2799 }
2800}
Damien Leone600c3052017-01-31 10:26:07 -07002801#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2802
Dave Houlton5fa47912018-02-16 11:02:26 -07002803vk::Result Demo::create_display_surface() {
2804 vk::Result result;
2805 uint32_t display_count;
2806 uint32_t mode_count;
2807 uint32_t plane_count;
2808 vk::DisplayPropertiesKHR display_props;
2809 vk::DisplayKHR display;
2810 vk::DisplayModePropertiesKHR mode_props;
2811 vk::DisplayPlanePropertiesKHR *plane_props;
2812 vk::Bool32 found_plane = VK_FALSE;
2813 uint32_t plane_index;
2814 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002815
Dave Houlton5fa47912018-02-16 11:02:26 -07002816 // Get the first display
2817 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2818 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002819
Dave Houlton5fa47912018-02-16 11:02:26 -07002820 if (display_count == 0) {
2821 printf("Cannot find any display!\n");
2822 fflush(stdout);
2823 exit(1);
2824 }
2825
2826 display_count = 1;
2827 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2828 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2829
2830 display = display_props.display;
2831
2832 // Get the first mode of the display
2833 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2834 VERIFY(result == vk::Result::eSuccess);
2835
2836 if (mode_count == 0) {
2837 printf("Cannot find any mode for the display!\n");
2838 fflush(stdout);
2839 exit(1);
2840 }
2841
2842 mode_count = 1;
2843 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2844 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2845
2846 // Get the list of planes
2847 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2848 VERIFY(result == vk::Result::eSuccess);
2849
2850 if (plane_count == 0) {
2851 printf("Cannot find any plane!\n");
2852 fflush(stdout);
2853 exit(1);
2854 }
2855
2856 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2857 VERIFY(plane_props != nullptr);
2858
2859 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2860 VERIFY(result == vk::Result::eSuccess);
2861
2862 // Find a plane compatible with the display
2863 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2864 uint32_t supported_count;
2865 vk::DisplayKHR *supported_displays;
2866
2867 // Disqualify planes that are bound to a different display
2868 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2869 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002870 }
2871
Dave Houlton5fa47912018-02-16 11:02:26 -07002872 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002873 VERIFY(result == vk::Result::eSuccess);
2874
Dave Houlton5fa47912018-02-16 11:02:26 -07002875 if (supported_count == 0) {
2876 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002877 }
2878
Dave Houlton5fa47912018-02-16 11:02:26 -07002879 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2880 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002881
Dave Houlton5fa47912018-02-16 11:02:26 -07002882 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002883 VERIFY(result == vk::Result::eSuccess);
2884
Dave Houlton5fa47912018-02-16 11:02:26 -07002885 for (uint32_t i = 0; i < supported_count; i++) {
2886 if (supported_displays[i] == display) {
2887 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002888 break;
2889 }
2890 }
2891
Dave Houlton5fa47912018-02-16 11:02:26 -07002892 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002893
Dave Houlton5fa47912018-02-16 11:02:26 -07002894 if (found_plane) {
2895 break;
Damien Leone600c3052017-01-31 10:26:07 -07002896 }
2897 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002898
2899 if (!found_plane) {
2900 printf("Cannot find a plane compatible with the display!\n");
2901 fflush(stdout);
2902 exit(1);
2903 }
2904
2905 free(plane_props);
2906
2907 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2908 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2909 // Find a supported alpha mode
2910 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2911 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2912 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2913 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2914 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2915 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2916 };
2917 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2918 if (planeCaps.supportedAlpha & alphaModes[i]) {
2919 alphaMode = alphaModes[i];
2920 break;
2921 }
2922 }
2923
2924 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2925 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2926
2927 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2928 .setDisplayMode(mode_props.displayMode)
2929 .setPlaneIndex(plane_index)
2930 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2931 .setGlobalAlpha(1.0f)
2932 .setAlphaMode(alphaMode)
2933 .setImageExtent(image_extent);
2934
2935 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2936}
2937
2938void Demo::run_display() {
2939 while (!quit) {
2940 draw();
2941 curFrame++;
2942
Petr Krausd88e4e52019-01-23 18:45:04 +01002943 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002944 quit = true;
2945 }
2946 }
2947}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002948#endif
2949
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002950#if _WIN32
2951// Include header required for parsing the command line options.
2952#include <shellapi.h>
2953
2954Demo demo;
2955
2956// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002957LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2958 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002959 case WM_CLOSE:
2960 PostQuitMessage(validation_error);
2961 break;
2962 case WM_PAINT:
2963 demo.run();
2964 break;
2965 case WM_GETMINMAXINFO: // set window's minimum size
2966 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2967 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002968 case WM_ERASEBKGND:
2969 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002970 case WM_SIZE:
2971 // Resize the application to the new window size, except when
2972 // it was minimized. Vulkan doesn't support images or swapchains
2973 // with width=0 and height=0.
2974 if (wParam != SIZE_MINIMIZED) {
2975 demo.width = lParam & 0xffff;
2976 demo.height = (lParam & 0xffff0000) >> 16;
2977 demo.resize();
2978 }
2979 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002980 case WM_KEYDOWN:
2981 switch (wParam) {
2982 case VK_ESCAPE:
2983 PostQuitMessage(validation_error);
2984 break;
2985 case VK_LEFT:
2986 demo.spin_angle -= demo.spin_increment;
2987 break;
2988 case VK_RIGHT:
2989 demo.spin_angle += demo.spin_increment;
2990 break;
2991 case VK_SPACE:
2992 demo.pause = !demo.pause;
2993 break;
2994 }
2995 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002996 default:
2997 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002998 }
2999
3000 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
3001}
3002
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003003int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003004 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003005 MSG msg; // message
3006 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003007 int argc;
3008 char **argv;
3009
Jamie Madillb2ff6502017-03-15 16:17:46 -04003010 // Ensure wParam is initialized.
3011 msg.wParam = 0;
3012
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003013 // Use the CommandLine functions to get the command line arguments.
3014 // Unfortunately, Microsoft outputs
3015 // this information as wide characters for Unicode, and we simply want the
3016 // Ascii version to be compatible
3017 // with the non-Windows side. So, we have to convert the information to
3018 // Ascii character strings.
3019 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003020 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003021 argc = 0;
3022 }
3023
Jeremy Hayes9d304782016-10-09 11:48:12 -06003024 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003025 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003026 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003027 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003028 } else {
3029 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003030 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3031 size_t numConverted = 0;
3032
3033 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003034 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003035 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003036 }
3037 }
3038 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003039 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003040 argv = nullptr;
3041 }
3042
3043 demo.init(argc, argv);
3044
3045 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003046 if (argc > 0 && argv != nullptr) {
3047 for (int iii = 0; iii < argc; iii++) {
3048 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003049 free(argv[iii]);
3050 }
3051 }
3052 free(argv);
3053 }
3054
3055 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003056 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003057 demo.create_window();
3058 demo.init_vk_swapchain();
3059
3060 demo.prepare();
3061
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003062 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003063
3064 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003065 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003066 if (demo.pause) {
3067 const BOOL succ = WaitMessage();
3068
3069 if (!succ) {
3070 const auto &suppress_popups = demo.suppress_popups;
3071 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3072 }
3073 }
3074
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003075 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003076 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003077 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003078 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003079 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003080 /* Translate and dispatch to event queue*/
3081 TranslateMessage(&msg);
3082 DispatchMessage(&msg);
3083 }
3084 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3085 }
3086
3087 demo.cleanup();
3088
3089 return (int)msg.wParam;
3090}
3091
3092#elif __linux__
3093
Jeremy Hayes9d304782016-10-09 11:48:12 -06003094int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003095 Demo demo;
3096
3097 demo.init(argc, argv);
3098
Tony Barbour153cb062016-12-07 13:43:36 -07003099#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003100 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003101#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003102 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003103 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003104#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003105 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003106#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003107
3108 demo.init_vk_swapchain();
3109
3110 demo.prepare();
3111
Tony Barbour153cb062016-12-07 13:43:36 -07003112#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003113 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003114#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003115 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003116#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003117 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003118#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3119 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003120#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003121
3122 demo.cleanup();
3123
3124 return validation_error;
3125}
3126
Karl Schultz9ceac062017-12-12 10:33:01 -05003127#elif defined(VK_USE_PLATFORM_IOS_MVK) || defined(VK_USE_PLATFORM_MACOS_MVK)
3128
3129// Global function invoked from NS or UI views and controllers to create demo
Karl Schultz206b1c52018-04-13 18:02:07 -06003130static void demo_main(struct Demo &demo, void *view, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003131 demo.init(argc, (char **)argv);
3132 demo.window = view;
3133 demo.init_vk_swapchain();
3134 demo.prepare();
3135 demo.spin_angle = 0.4f;
3136}
3137
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003138#else
3139#error "Platform not supported"
3140#endif