blob: 5e875a15a3033cf99ac4aedc6f813d70b5f33466 [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();
Bill Hollings0a0625a2019-07-15 17:39:18 -0400268#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -0600269 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;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400303#elif defined(VK_USE_PLATFORM_METAL_EXT)
304 void *caMetalLayer;
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 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001140#elif defined(VK_USE_PLATFORM_METAL_EXT)
1141 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Karl Schultz9ceac062017-12-12 10:33:01 -05001142 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04001143 extension_names[enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Karl Schultz9ceac062017-12-12 10:33:01 -05001144 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001145
Dave Houlton5fa47912018-02-16 11:02:26 -07001146#endif
1147 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001148 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001149 }
1150
1151 if (!surfaceExtFound) {
1152 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
1153 " extension.\n\n"
1154 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1155 "Please look at the Getting Started guide for additional information.\n",
1156 "vkCreateInstance Failure");
1157 }
1158
1159 if (!platformSurfaceExtFound) {
1160#if defined(VK_USE_PLATFORM_WIN32_KHR)
1161 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
1162 " extension.\n\n"
1163 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1164 "Please look at the Getting Started guide for additional information.\n",
1165 "vkCreateInstance Failure");
1166#elif defined(VK_USE_PLATFORM_XCB_KHR)
1167 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
1168 " extension.\n\n"
1169 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1170 "Please look at the Getting Started guide for additional information.\n",
1171 "vkCreateInstance Failure");
1172#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1173 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
1174 " extension.\n\n"
1175 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1176 "Please look at the Getting Started guide for additional information.\n",
1177 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001178#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001179 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
1180 " extension.\n\n"
1181 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1182 "Please look at the Getting Started guide for additional information.\n",
1183 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07001184#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07001185 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
1186 " extension.\n\n"
1187 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1188 "Please look at the Getting Started guide for additional information.\n",
1189 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04001190#elif defined(VK_USE_PLATFORM_METAL_EXT)
1191 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Karl Schultz9ceac062017-12-12 10:33:01 -05001192 " extension.\n\nDo you have a compatible "
1193 "Vulkan installable client driver (ICD) installed?\nPlease "
1194 "look at the Getting Started guide for additional "
1195 "information.\n",
1196 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07001197#endif
Dave Houlton5fa47912018-02-16 11:02:26 -07001198 }
1199 auto const app = vk::ApplicationInfo()
1200 .setPApplicationName(APP_SHORT_NAME)
1201 .setApplicationVersion(0)
1202 .setPEngineName(APP_SHORT_NAME)
1203 .setEngineVersion(0)
1204 .setApiVersion(VK_API_VERSION_1_0);
1205 auto const inst_info = vk::InstanceCreateInfo()
1206 .setPApplicationInfo(&app)
1207 .setEnabledLayerCount(enabled_layer_count)
1208 .setPpEnabledLayerNames(instance_validation_layers)
1209 .setEnabledExtensionCount(enabled_extension_count)
1210 .setPpEnabledExtensionNames(extension_names);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001211
Dave Houlton5fa47912018-02-16 11:02:26 -07001212 result = vk::createInstance(&inst_info, nullptr, &inst);
1213 if (result == vk::Result::eErrorIncompatibleDriver) {
1214 ERR_EXIT(
1215 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
1216 "Please look at the Getting Started guide for additional information.\n",
1217 "vkCreateInstance Failure");
1218 } else if (result == vk::Result::eErrorExtensionNotPresent) {
1219 ERR_EXIT(
1220 "Cannot find a specified extension library.\n"
1221 "Make sure your layers path is set appropriately.\n",
1222 "vkCreateInstance Failure");
1223 } else if (result != vk::Result::eSuccess) {
1224 ERR_EXIT(
1225 "vkCreateInstance failed.\n\n"
1226 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1227 "Please look at the Getting Started guide for additional information.\n",
1228 "vkCreateInstance Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001229 }
1230
Dave Houlton5fa47912018-02-16 11:02:26 -07001231 /* Make initial call to query gpu_count, then second call for gpu info*/
1232 uint32_t gpu_count;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001233 result = inst.enumeratePhysicalDevices(&gpu_count, static_cast<vk::PhysicalDevice *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001234 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001235
1236 if (gpu_count > 0) {
1237 std::unique_ptr<vk::PhysicalDevice[]> physical_devices(new vk::PhysicalDevice[gpu_count]);
1238 result = inst.enumeratePhysicalDevices(&gpu_count, physical_devices.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001239 VERIFY(result == vk::Result::eSuccess);
Dave Houlton5fa47912018-02-16 11:02:26 -07001240 /* For cube demo we just grab the first physical device */
1241 gpu = physical_devices[0];
1242 } else {
1243 ERR_EXIT(
1244 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
1245 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1246 "Please look at the Getting Started guide for additional information.\n",
1247 "vkEnumeratePhysicalDevices Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001248 }
1249
Dave Houlton5fa47912018-02-16 11:02:26 -07001250 /* Look for device extensions */
1251 uint32_t device_extension_count = 0;
1252 vk::Bool32 swapchainExtFound = VK_FALSE;
1253 enabled_extension_count = 0;
1254 memset(extension_names, 0, sizeof(extension_names));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001255
Mike Schuchardt7510c832018-10-29 13:23:08 -07001256 result =
1257 gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, static_cast<vk::ExtensionProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001258 VERIFY(result == vk::Result::eSuccess);
1259
1260 if (device_extension_count > 0) {
1261 std::unique_ptr<vk::ExtensionProperties[]> device_extensions(new vk::ExtensionProperties[device_extension_count]);
1262 result = gpu.enumerateDeviceExtensionProperties(nullptr, &device_extension_count, device_extensions.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001263 VERIFY(result == vk::Result::eSuccess);
1264
Dave Houlton5fa47912018-02-16 11:02:26 -07001265 for (uint32_t i = 0; i < device_extension_count; i++) {
1266 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
1267 swapchainExtFound = 1;
1268 extension_names[enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001269 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001270 assert(enabled_extension_count < 64);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001271 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001272 }
Jeremy Hayes6ae1f8a2016-11-16 14:47:13 -07001273
Dave Houlton5fa47912018-02-16 11:02:26 -07001274 if (!swapchainExtFound) {
1275 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
1276 " extension.\n\n"
1277 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
1278 "Please look at the Getting Started guide for additional information.\n",
1279 "vkCreateInstance Failure");
1280 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001281
Dave Houlton5fa47912018-02-16 11:02:26 -07001282 gpu.getProperties(&gpu_props);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001283
Dave Houlton5fa47912018-02-16 11:02:26 -07001284 /* Call with nullptr data to get count */
Mike Schuchardt7510c832018-10-29 13:23:08 -07001285 gpu.getQueueFamilyProperties(&queue_family_count, static_cast<vk::QueueFamilyProperties *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001286 assert(queue_family_count >= 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001287
Dave Houlton5fa47912018-02-16 11:02:26 -07001288 queue_props.reset(new vk::QueueFamilyProperties[queue_family_count]);
1289 gpu.getQueueFamilyProperties(&queue_family_count, queue_props.get());
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001290
Dave Houlton5fa47912018-02-16 11:02:26 -07001291 // Query fine-grained feature support for this device.
1292 // If app has specific feature requirements it should check supported
1293 // features based on this query
1294 vk::PhysicalDeviceFeatures physDevFeatures;
1295 gpu.getFeatures(&physDevFeatures);
1296}
1297
Tony-LunarG6cebf142019-09-11 14:32:23 -06001298void Demo::create_surface() {
Dave Houlton5fa47912018-02-16 11:02:26 -07001299// Create a WSI surface for the window:
1300#if defined(VK_USE_PLATFORM_WIN32_KHR)
1301 {
1302 auto const createInfo = vk::Win32SurfaceCreateInfoKHR().setHinstance(connection).setHwnd(window);
1303
1304 auto result = inst.createWin32SurfaceKHR(&createInfo, nullptr, &surface);
1305 VERIFY(result == vk::Result::eSuccess);
1306 }
1307#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
1308 {
1309 auto const createInfo = vk::WaylandSurfaceCreateInfoKHR().setDisplay(display).setSurface(window);
1310
1311 auto result = inst.createWaylandSurfaceKHR(&createInfo, nullptr, &surface);
1312 VERIFY(result == vk::Result::eSuccess);
1313 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001314#elif defined(VK_USE_PLATFORM_XLIB_KHR)
1315 {
1316 auto const createInfo = vk::XlibSurfaceCreateInfoKHR().setDpy(display).setWindow(xlib_window);
1317
1318 auto result = inst.createXlibSurfaceKHR(&createInfo, nullptr, &surface);
1319 VERIFY(result == vk::Result::eSuccess);
1320 }
1321#elif defined(VK_USE_PLATFORM_XCB_KHR)
1322 {
1323 auto const createInfo = vk::XcbSurfaceCreateInfoKHR().setConnection(connection).setWindow(xcb_window);
1324
1325 auto result = inst.createXcbSurfaceKHR(&createInfo, nullptr, &surface);
1326 VERIFY(result == vk::Result::eSuccess);
1327 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04001328#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05001329 {
Bill Hollings0a0625a2019-07-15 17:39:18 -04001330 auto const createInfo = vk::MetalSurfaceCreateInfoEXT().setPLayer(static_cast<CAMetalLayer *>(caMetalLayer));
Karl Schultz9ceac062017-12-12 10:33:01 -05001331
Bill Hollings0a0625a2019-07-15 17:39:18 -04001332 auto result = inst.createMetalSurfaceEXT(&createInfo, nullptr, &surface);
Karl Schultz9ceac062017-12-12 10:33:01 -05001333 VERIFY(result == vk::Result::eSuccess);
1334 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001335#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
1336 {
1337 auto result = create_display_surface();
1338 VERIFY(result == vk::Result::eSuccess);
1339 }
1340#endif
Tony-LunarG6cebf142019-09-11 14:32:23 -06001341}
1342
1343void Demo::init_vk_swapchain() {
1344 create_surface();
Dave Houlton5fa47912018-02-16 11:02:26 -07001345 // Iterate over each queue to learn whether it supports presenting:
1346 std::unique_ptr<vk::Bool32[]> supportsPresent(new vk::Bool32[queue_family_count]);
1347 for (uint32_t i = 0; i < queue_family_count; i++) {
1348 gpu.getSurfaceSupportKHR(i, surface, &supportsPresent[i]);
1349 }
1350
1351 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
1352 uint32_t presentQueueFamilyIndex = UINT32_MAX;
1353 for (uint32_t i = 0; i < queue_family_count; i++) {
1354 if (queue_props[i].queueFlags & vk::QueueFlagBits::eGraphics) {
1355 if (graphicsQueueFamilyIndex == UINT32_MAX) {
1356 graphicsQueueFamilyIndex = i;
1357 }
1358
1359 if (supportsPresent[i] == VK_TRUE) {
1360 graphicsQueueFamilyIndex = i;
1361 presentQueueFamilyIndex = i;
Jeremy Hayes00399e32017-06-14 15:07:32 -06001362 break;
1363 }
1364 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001365 }
Jeremy Hayes00399e32017-06-14 15:07:32 -06001366
Dave Houlton5fa47912018-02-16 11:02:26 -07001367 if (presentQueueFamilyIndex == UINT32_MAX) {
1368 // If didn't find a queue that supports both graphics and present,
1369 // then
1370 // find a separate present queue.
1371 for (uint32_t i = 0; i < queue_family_count; ++i) {
1372 if (supportsPresent[i] == VK_TRUE) {
1373 presentQueueFamilyIndex = i;
1374 break;
1375 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001376 }
1377 }
1378
Dave Houlton5fa47912018-02-16 11:02:26 -07001379 // Generate error if could not find both a graphics and a present queue
1380 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
1381 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
1382 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001383
Dave Houlton5fa47912018-02-16 11:02:26 -07001384 graphics_queue_family_index = graphicsQueueFamilyIndex;
1385 present_queue_family_index = presentQueueFamilyIndex;
1386 separate_present_queue = (graphics_queue_family_index != present_queue_family_index);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001387
Dave Houlton5fa47912018-02-16 11:02:26 -07001388 create_device();
Jeremy Hayes00399e32017-06-14 15:07:32 -06001389
Dave Houlton5fa47912018-02-16 11:02:26 -07001390 device.getQueue(graphics_queue_family_index, 0, &graphics_queue);
1391 if (!separate_present_queue) {
1392 present_queue = graphics_queue;
1393 } else {
1394 device.getQueue(present_queue_family_index, 0, &present_queue);
1395 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001396
Dave Houlton5fa47912018-02-16 11:02:26 -07001397 // Get the list of VkFormat's that are supported:
1398 uint32_t formatCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001399 auto result = gpu.getSurfaceFormatsKHR(surface, &formatCount, static_cast<vk::SurfaceFormatKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001400 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001401
Dave Houlton5fa47912018-02-16 11:02:26 -07001402 std::unique_ptr<vk::SurfaceFormatKHR[]> surfFormats(new vk::SurfaceFormatKHR[formatCount]);
1403 result = gpu.getSurfaceFormatsKHR(surface, &formatCount, surfFormats.get());
1404 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001405
Dave Houlton5fa47912018-02-16 11:02:26 -07001406 // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
1407 // the surface has no preferred format. Otherwise, at least one
1408 // supported format will be returned.
1409 if (formatCount == 1 && surfFormats[0].format == vk::Format::eUndefined) {
1410 format = vk::Format::eB8G8R8A8Unorm;
1411 } else {
1412 assert(formatCount >= 1);
1413 format = surfFormats[0].format;
1414 }
1415 color_space = surfFormats[0].colorSpace;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001416
Dave Houlton5fa47912018-02-16 11:02:26 -07001417 quit = false;
1418 curFrame = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001419
Dave Houlton5fa47912018-02-16 11:02:26 -07001420 // Create semaphores to synchronize acquiring presentable buffers before
1421 // rendering and waiting for drawing to be complete before presenting
1422 auto const semaphoreCreateInfo = vk::SemaphoreCreateInfo();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001423
Dave Houlton5fa47912018-02-16 11:02:26 -07001424 // Create fences that we can use to throttle if we get too far
1425 // ahead of the image presents
1426 auto const fence_ci = vk::FenceCreateInfo().setFlags(vk::FenceCreateFlagBits::eSignaled);
1427 for (uint32_t i = 0; i < FRAME_LAG; i++) {
1428 result = device.createFence(&fence_ci, nullptr, &fences[i]);
1429 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001430
Dave Houlton5fa47912018-02-16 11:02:26 -07001431 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_acquired_semaphores[i]);
1432 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001433
Dave Houlton5fa47912018-02-16 11:02:26 -07001434 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &draw_complete_semaphores[i]);
1435 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001436
Dave Houlton5fa47912018-02-16 11:02:26 -07001437 if (separate_present_queue) {
1438 result = device.createSemaphore(&semaphoreCreateInfo, nullptr, &image_ownership_semaphores[i]);
Jeremy Hayes00399e32017-06-14 15:07:32 -06001439 VERIFY(result == vk::Result::eSuccess);
1440 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001441 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001442 frame_index = 0;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001443
Dave Houlton5fa47912018-02-16 11:02:26 -07001444 // Get Memory information and properties
1445 gpu.getMemoryProperties(&memory_properties);
1446}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001447
Dave Houlton5fa47912018-02-16 11:02:26 -07001448void Demo::prepare() {
1449 auto const cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(graphics_queue_family_index);
1450 auto result = device.createCommandPool(&cmd_pool_info, nullptr, &cmd_pool);
1451 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001452
Dave Houlton5fa47912018-02-16 11:02:26 -07001453 auto const cmd = vk::CommandBufferAllocateInfo()
1454 .setCommandPool(cmd_pool)
1455 .setLevel(vk::CommandBufferLevel::ePrimary)
1456 .setCommandBufferCount(1);
1457
1458 result = device.allocateCommandBuffers(&cmd, &this->cmd);
1459 VERIFY(result == vk::Result::eSuccess);
1460
1461 auto const cmd_buf_info = vk::CommandBufferBeginInfo().setPInheritanceInfo(nullptr);
1462
1463 result = this->cmd.begin(&cmd_buf_info);
1464 VERIFY(result == vk::Result::eSuccess);
1465
1466 prepare_buffers();
1467 prepare_depth();
1468 prepare_textures();
1469 prepare_cube_data_buffers();
1470
1471 prepare_descriptor_layout();
1472 prepare_render_pass();
1473 prepare_pipeline();
1474
1475 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1476 result = device.allocateCommandBuffers(&cmd, &swapchain_image_resources[i].cmd);
1477 VERIFY(result == vk::Result::eSuccess);
1478 }
1479
1480 if (separate_present_queue) {
1481 auto const present_cmd_pool_info = vk::CommandPoolCreateInfo().setQueueFamilyIndex(present_queue_family_index);
1482
1483 result = device.createCommandPool(&present_cmd_pool_info, nullptr, &present_cmd_pool);
1484 VERIFY(result == vk::Result::eSuccess);
1485
1486 auto const present_cmd = vk::CommandBufferAllocateInfo()
1487 .setCommandPool(present_cmd_pool)
1488 .setLevel(vk::CommandBufferLevel::ePrimary)
1489 .setCommandBufferCount(1);
1490
1491 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1492 result = device.allocateCommandBuffers(&present_cmd, &swapchain_image_resources[i].graphics_to_present_cmd);
1493 VERIFY(result == vk::Result::eSuccess);
1494
1495 build_image_ownership_cmd(i);
1496 }
1497 }
1498
1499 prepare_descriptor_pool();
1500 prepare_descriptor_set();
1501
1502 prepare_framebuffers();
1503
1504 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1505 current_buffer = i;
1506 draw_build_cmd(swapchain_image_resources[i].cmd);
1507 }
1508
1509 /*
1510 * Prepare functions above may generate pipeline commands
1511 * that need to be flushed before beginning the render loop.
1512 */
1513 flush_init_cmd();
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001514 if (staging_texture.buffer) {
1515 destroy_texture(&staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07001516 }
1517
1518 current_buffer = 0;
1519 prepared = true;
1520}
1521
1522void Demo::prepare_buffers() {
1523 vk::SwapchainKHR oldSwapchain = swapchain;
1524
1525 // Check the surface capabilities and formats
1526 vk::SurfaceCapabilitiesKHR surfCapabilities;
1527 auto result = gpu.getSurfaceCapabilitiesKHR(surface, &surfCapabilities);
1528 VERIFY(result == vk::Result::eSuccess);
1529
1530 uint32_t presentModeCount;
Mike Schuchardt7510c832018-10-29 13:23:08 -07001531 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, static_cast<vk::PresentModeKHR *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001532 VERIFY(result == vk::Result::eSuccess);
1533
1534 std::unique_ptr<vk::PresentModeKHR[]> presentModes(new vk::PresentModeKHR[presentModeCount]);
1535 result = gpu.getSurfacePresentModesKHR(surface, &presentModeCount, presentModes.get());
1536 VERIFY(result == vk::Result::eSuccess);
1537
1538 vk::Extent2D swapchainExtent;
1539 // width and height are either both -1, or both not -1.
1540 if (surfCapabilities.currentExtent.width == (uint32_t)-1) {
1541 // If the surface size is undefined, the size is set to
1542 // the size of the images requested.
1543 swapchainExtent.width = width;
1544 swapchainExtent.height = height;
1545 } else {
1546 // If the surface size is defined, the swap chain size must match
1547 swapchainExtent = surfCapabilities.currentExtent;
1548 width = surfCapabilities.currentExtent.width;
1549 height = surfCapabilities.currentExtent.height;
1550 }
1551
1552 // The FIFO present mode is guaranteed by the spec to be supported
1553 // and to have no tearing. It's a great default present mode to use.
1554 vk::PresentModeKHR swapchainPresentMode = vk::PresentModeKHR::eFifo;
1555
1556 // There are times when you may wish to use another present mode. The
1557 // following code shows how to select them, and the comments provide some
1558 // reasons you may wish to use them.
1559 //
1560 // It should be noted that Vulkan 1.0 doesn't provide a method for
1561 // synchronizing rendering with the presentation engine's display. There
1562 // is a method provided for throttling rendering with the display, but
1563 // there are some presentation engines for which this method will not work.
1564 // If an application doesn't throttle its rendering, and if it renders much
1565 // faster than the refresh rate of the display, this can waste power on
1566 // mobile devices. That is because power is being spent rendering images
1567 // that may never be seen.
1568
1569 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care
1570 // about
1571 // tearing, or have some way of synchronizing their rendering with the
1572 // display.
1573 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1574 // generally render a new presentable image every refresh cycle, but are
1575 // occasionally early. In this case, the application wants the new
1576 // image
1577 // to be displayed instead of the previously-queued-for-presentation
1578 // image
1579 // that has not yet been displayed.
1580 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1581 // render a new presentable image every refresh cycle, but are
1582 // occasionally
1583 // late. In this case (perhaps because of stuttering/latency concerns),
1584 // the application wants the late image to be immediately displayed,
1585 // even
1586 // though that may mean some tearing.
1587
1588 if (presentMode != swapchainPresentMode) {
1589 for (size_t i = 0; i < presentModeCount; ++i) {
1590 if (presentModes[i] == presentMode) {
1591 swapchainPresentMode = presentMode;
1592 break;
1593 }
1594 }
1595 }
1596
1597 if (swapchainPresentMode != presentMode) {
1598 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1599 }
1600
1601 // Determine the number of VkImages to use in the swap chain.
1602 // Application desires to acquire 3 images at a time for triple
1603 // buffering
1604 uint32_t desiredNumOfSwapchainImages = 3;
1605 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1606 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1607 }
1608
1609 // If maxImageCount is 0, we can ask for as many images as we want,
1610 // otherwise
1611 // we're limited to maxImageCount
1612 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
1613 // Application must settle for fewer images than desired:
1614 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
1615 }
1616
1617 vk::SurfaceTransformFlagBitsKHR preTransform;
1618 if (surfCapabilities.supportedTransforms & vk::SurfaceTransformFlagBitsKHR::eIdentity) {
1619 preTransform = vk::SurfaceTransformFlagBitsKHR::eIdentity;
1620 } else {
1621 preTransform = surfCapabilities.currentTransform;
1622 }
1623
1624 // Find a supported composite alpha mode - one of these is guaranteed to be set
1625 vk::CompositeAlphaFlagBitsKHR compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque;
1626 vk::CompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1627 vk::CompositeAlphaFlagBitsKHR::eOpaque,
1628 vk::CompositeAlphaFlagBitsKHR::ePreMultiplied,
1629 vk::CompositeAlphaFlagBitsKHR::ePostMultiplied,
1630 vk::CompositeAlphaFlagBitsKHR::eInherit,
1631 };
1632 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
1633 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1634 compositeAlpha = compositeAlphaFlags[i];
1635 break;
1636 }
1637 }
1638
1639 auto const swapchain_ci = vk::SwapchainCreateInfoKHR()
1640 .setSurface(surface)
1641 .setMinImageCount(desiredNumOfSwapchainImages)
1642 .setImageFormat(format)
1643 .setImageColorSpace(color_space)
1644 .setImageExtent({swapchainExtent.width, swapchainExtent.height})
1645 .setImageArrayLayers(1)
1646 .setImageUsage(vk::ImageUsageFlagBits::eColorAttachment)
1647 .setImageSharingMode(vk::SharingMode::eExclusive)
1648 .setQueueFamilyIndexCount(0)
1649 .setPQueueFamilyIndices(nullptr)
1650 .setPreTransform(preTransform)
1651 .setCompositeAlpha(compositeAlpha)
1652 .setPresentMode(swapchainPresentMode)
1653 .setClipped(true)
1654 .setOldSwapchain(oldSwapchain);
1655
1656 result = device.createSwapchainKHR(&swapchain_ci, nullptr, &swapchain);
1657 VERIFY(result == vk::Result::eSuccess);
1658
1659 // If we just re-created an existing swapchain, we should destroy the
1660 // old
1661 // swapchain at this point.
1662 // Note: destroying the swapchain also cleans up all its associated
1663 // presentable images once the platform is done with them.
1664 if (oldSwapchain) {
1665 device.destroySwapchainKHR(oldSwapchain, nullptr);
1666 }
1667
Mike Schuchardt7510c832018-10-29 13:23:08 -07001668 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, static_cast<vk::Image *>(nullptr));
Dave Houlton5fa47912018-02-16 11:02:26 -07001669 VERIFY(result == vk::Result::eSuccess);
1670
1671 std::unique_ptr<vk::Image[]> swapchainImages(new vk::Image[swapchainImageCount]);
1672 result = device.getSwapchainImagesKHR(swapchain, &swapchainImageCount, swapchainImages.get());
1673 VERIFY(result == vk::Result::eSuccess);
1674
1675 swapchain_image_resources.reset(new SwapchainImageResources[swapchainImageCount]);
1676
1677 for (uint32_t i = 0; i < swapchainImageCount; ++i) {
1678 auto color_image_view = vk::ImageViewCreateInfo()
1679 .setViewType(vk::ImageViewType::e2D)
1680 .setFormat(format)
1681 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
1682
1683 swapchain_image_resources[i].image = swapchainImages[i];
1684
1685 color_image_view.image = swapchain_image_resources[i].image;
1686
1687 result = device.createImageView(&color_image_view, nullptr, &swapchain_image_resources[i].view);
1688 VERIFY(result == vk::Result::eSuccess);
1689 }
1690}
1691
1692void Demo::prepare_cube_data_buffers() {
1693 mat4x4 VP;
1694 mat4x4_mul(VP, projection_matrix, view_matrix);
1695
1696 mat4x4 MVP;
1697 mat4x4_mul(MVP, VP, model_matrix);
1698
1699 vktexcube_vs_uniform data;
1700 memcpy(data.mvp, MVP, sizeof(MVP));
1701 // dumpMatrix("MVP", MVP)
1702
1703 for (int32_t i = 0; i < 12 * 3; i++) {
1704 data.position[i][0] = g_vertex_buffer_data[i * 3];
1705 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1706 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
1707 data.position[i][3] = 1.0f;
1708 data.attr[i][0] = g_uv_buffer_data[2 * i];
1709 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
1710 data.attr[i][2] = 0;
1711 data.attr[i][3] = 0;
1712 }
1713
1714 auto const buf_info = vk::BufferCreateInfo().setSize(sizeof(data)).setUsage(vk::BufferUsageFlagBits::eUniformBuffer);
1715
1716 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1717 auto result = device.createBuffer(&buf_info, nullptr, &swapchain_image_resources[i].uniform_buffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001718 VERIFY(result == vk::Result::eSuccess);
1719
1720 vk::MemoryRequirements mem_reqs;
Dave Houlton5fa47912018-02-16 11:02:26 -07001721 device.getBufferMemoryRequirements(swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001722
Dave Houlton5fa47912018-02-16 11:02:26 -07001723 auto mem_alloc = vk::MemoryAllocateInfo().setAllocationSize(mem_reqs.size).setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001724
Dave Houlton5fa47912018-02-16 11:02:26 -07001725 bool const pass = memory_type_from_properties(
1726 mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent,
1727 &mem_alloc.memoryTypeIndex);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001728 VERIFY(pass);
1729
Dave Houlton5fa47912018-02-16 11:02:26 -07001730 result = device.allocateMemory(&mem_alloc, nullptr, &swapchain_image_resources[i].uniform_memory);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001731 VERIFY(result == vk::Result::eSuccess);
1732
Dave Houlton5fa47912018-02-16 11:02:26 -07001733 auto pData = device.mapMemory(swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
1734 VERIFY(pData.result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001735
Dave Houlton5fa47912018-02-16 11:02:26 -07001736 memcpy(pData.value, &data, sizeof data);
1737
1738 device.unmapMemory(swapchain_image_resources[i].uniform_memory);
1739
1740 result =
1741 device.bindBufferMemory(swapchain_image_resources[i].uniform_buffer, swapchain_image_resources[i].uniform_memory, 0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001742 VERIFY(result == vk::Result::eSuccess);
1743 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001744}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001745
Dave Houlton5fa47912018-02-16 11:02:26 -07001746void Demo::prepare_depth() {
1747 depth.format = vk::Format::eD16Unorm;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001748
Dave Houlton5fa47912018-02-16 11:02:26 -07001749 auto const image = vk::ImageCreateInfo()
1750 .setImageType(vk::ImageType::e2D)
1751 .setFormat(depth.format)
1752 .setExtent({(uint32_t)width, (uint32_t)height, 1})
1753 .setMipLevels(1)
1754 .setArrayLayers(1)
1755 .setSamples(vk::SampleCountFlagBits::e1)
1756 .setTiling(vk::ImageTiling::eOptimal)
1757 .setUsage(vk::ImageUsageFlagBits::eDepthStencilAttachment)
1758 .setSharingMode(vk::SharingMode::eExclusive)
1759 .setQueueFamilyIndexCount(0)
1760 .setPQueueFamilyIndices(nullptr)
1761 .setInitialLayout(vk::ImageLayout::eUndefined);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001762
Dave Houlton5fa47912018-02-16 11:02:26 -07001763 auto result = device.createImage(&image, nullptr, &depth.image);
1764 VERIFY(result == vk::Result::eSuccess);
1765
1766 vk::MemoryRequirements mem_reqs;
1767 device.getImageMemoryRequirements(depth.image, &mem_reqs);
1768
1769 depth.mem_alloc.setAllocationSize(mem_reqs.size);
1770 depth.mem_alloc.setMemoryTypeIndex(0);
1771
1772 auto const pass = memory_type_from_properties(mem_reqs.memoryTypeBits, vk::MemoryPropertyFlagBits::eDeviceLocal,
1773 &depth.mem_alloc.memoryTypeIndex);
1774 VERIFY(pass);
1775
1776 result = device.allocateMemory(&depth.mem_alloc, nullptr, &depth.mem);
1777 VERIFY(result == vk::Result::eSuccess);
1778
1779 result = device.bindImageMemory(depth.image, depth.mem, 0);
1780 VERIFY(result == vk::Result::eSuccess);
1781
1782 auto const view = vk::ImageViewCreateInfo()
1783 .setImage(depth.image)
1784 .setViewType(vk::ImageViewType::e2D)
1785 .setFormat(depth.format)
1786 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
1787 result = device.createImageView(&view, nullptr, &depth.view);
1788 VERIFY(result == vk::Result::eSuccess);
1789}
1790
1791void Demo::prepare_descriptor_layout() {
1792 vk::DescriptorSetLayoutBinding const layout_bindings[2] = {vk::DescriptorSetLayoutBinding()
1793 .setBinding(0)
1794 .setDescriptorType(vk::DescriptorType::eUniformBuffer)
1795 .setDescriptorCount(1)
1796 .setStageFlags(vk::ShaderStageFlagBits::eVertex)
1797 .setPImmutableSamplers(nullptr),
1798 vk::DescriptorSetLayoutBinding()
1799 .setBinding(1)
1800 .setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
1801 .setDescriptorCount(texture_count)
1802 .setStageFlags(vk::ShaderStageFlagBits::eFragment)
1803 .setPImmutableSamplers(nullptr)};
1804
1805 auto const descriptor_layout = vk::DescriptorSetLayoutCreateInfo().setBindingCount(2).setPBindings(layout_bindings);
1806
1807 auto result = device.createDescriptorSetLayout(&descriptor_layout, nullptr, &desc_layout);
1808 VERIFY(result == vk::Result::eSuccess);
1809
1810 auto const pPipelineLayoutCreateInfo = vk::PipelineLayoutCreateInfo().setSetLayoutCount(1).setPSetLayouts(&desc_layout);
1811
1812 result = device.createPipelineLayout(&pPipelineLayoutCreateInfo, nullptr, &pipeline_layout);
1813 VERIFY(result == vk::Result::eSuccess);
1814}
1815
1816void Demo::prepare_descriptor_pool() {
1817 vk::DescriptorPoolSize const poolSizes[2] = {
1818 vk::DescriptorPoolSize().setType(vk::DescriptorType::eUniformBuffer).setDescriptorCount(swapchainImageCount),
1819 vk::DescriptorPoolSize()
1820 .setType(vk::DescriptorType::eCombinedImageSampler)
1821 .setDescriptorCount(swapchainImageCount * texture_count)};
1822
1823 auto const descriptor_pool =
1824 vk::DescriptorPoolCreateInfo().setMaxSets(swapchainImageCount).setPoolSizeCount(2).setPPoolSizes(poolSizes);
1825
1826 auto result = device.createDescriptorPool(&descriptor_pool, nullptr, &desc_pool);
1827 VERIFY(result == vk::Result::eSuccess);
1828}
1829
1830void Demo::prepare_descriptor_set() {
1831 auto const alloc_info =
1832 vk::DescriptorSetAllocateInfo().setDescriptorPool(desc_pool).setDescriptorSetCount(1).setPSetLayouts(&desc_layout);
1833
1834 auto buffer_info = vk::DescriptorBufferInfo().setOffset(0).setRange(sizeof(struct vktexcube_vs_uniform));
1835
1836 vk::DescriptorImageInfo tex_descs[texture_count];
1837 for (uint32_t i = 0; i < texture_count; i++) {
1838 tex_descs[i].setSampler(textures[i].sampler);
1839 tex_descs[i].setImageView(textures[i].view);
Karl Schultze88bc842018-09-11 16:23:14 -06001840 tex_descs[i].setImageLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
Dave Houlton5fa47912018-02-16 11:02:26 -07001841 }
1842
1843 vk::WriteDescriptorSet writes[2];
1844
1845 writes[0].setDescriptorCount(1);
1846 writes[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
1847 writes[0].setPBufferInfo(&buffer_info);
1848
1849 writes[1].setDstBinding(1);
1850 writes[1].setDescriptorCount(texture_count);
1851 writes[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
1852 writes[1].setPImageInfo(tex_descs);
1853
1854 for (unsigned int i = 0; i < swapchainImageCount; i++) {
1855 auto result = device.allocateDescriptorSets(&alloc_info, &swapchain_image_resources[i].descriptor_set);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001856 VERIFY(result == vk::Result::eSuccess);
1857
Dave Houlton5fa47912018-02-16 11:02:26 -07001858 buffer_info.setBuffer(swapchain_image_resources[i].uniform_buffer);
1859 writes[0].setDstSet(swapchain_image_resources[i].descriptor_set);
1860 writes[1].setDstSet(swapchain_image_resources[i].descriptor_set);
1861 device.updateDescriptorSets(2, writes, 0, nullptr);
1862 }
1863}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001864
Dave Houlton5fa47912018-02-16 11:02:26 -07001865void Demo::prepare_framebuffers() {
1866 vk::ImageView attachments[2];
1867 attachments[1] = depth.view;
1868
1869 auto const fb_info = vk::FramebufferCreateInfo()
1870 .setRenderPass(render_pass)
1871 .setAttachmentCount(2)
1872 .setPAttachments(attachments)
1873 .setWidth((uint32_t)width)
1874 .setHeight((uint32_t)height)
1875 .setLayers(1);
1876
1877 for (uint32_t i = 0; i < swapchainImageCount; i++) {
1878 attachments[0] = swapchain_image_resources[i].view;
1879 auto const result = device.createFramebuffer(&fb_info, nullptr, &swapchain_image_resources[i].framebuffer);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001880 VERIFY(result == vk::Result::eSuccess);
1881 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001882}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001883
Dave Houlton5fa47912018-02-16 11:02:26 -07001884vk::ShaderModule Demo::prepare_fs() {
1885 const uint32_t fragShaderCode[] = {
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001886#include "cube.frag.inc"
Dave Houlton5fa47912018-02-16 11:02:26 -07001887 };
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001888
Dave Houlton5fa47912018-02-16 11:02:26 -07001889 frag_shader_module = prepare_shader_module(fragShaderCode, sizeof(fragShaderCode));
Jeremy Hayesf56427a2016-09-07 15:55:11 -06001890
Dave Houlton5fa47912018-02-16 11:02:26 -07001891 return frag_shader_module;
1892}
1893
1894void Demo::prepare_pipeline() {
1895 vk::PipelineCacheCreateInfo const pipelineCacheInfo;
1896 auto result = device.createPipelineCache(&pipelineCacheInfo, nullptr, &pipelineCache);
1897 VERIFY(result == vk::Result::eSuccess);
1898
1899 vk::PipelineShaderStageCreateInfo const shaderStageInfo[2] = {
1900 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eVertex).setModule(prepare_vs()).setPName("main"),
1901 vk::PipelineShaderStageCreateInfo().setStage(vk::ShaderStageFlagBits::eFragment).setModule(prepare_fs()).setPName("main")};
1902
1903 vk::PipelineVertexInputStateCreateInfo const vertexInputInfo;
1904
1905 auto const inputAssemblyInfo = vk::PipelineInputAssemblyStateCreateInfo().setTopology(vk::PrimitiveTopology::eTriangleList);
1906
1907 // TODO: Where are pViewports and pScissors set?
1908 auto const viewportInfo = vk::PipelineViewportStateCreateInfo().setViewportCount(1).setScissorCount(1);
1909
1910 auto const rasterizationInfo = vk::PipelineRasterizationStateCreateInfo()
1911 .setDepthClampEnable(VK_FALSE)
1912 .setRasterizerDiscardEnable(VK_FALSE)
1913 .setPolygonMode(vk::PolygonMode::eFill)
1914 .setCullMode(vk::CullModeFlagBits::eBack)
1915 .setFrontFace(vk::FrontFace::eCounterClockwise)
1916 .setDepthBiasEnable(VK_FALSE)
1917 .setLineWidth(1.0f);
1918
1919 auto const multisampleInfo = vk::PipelineMultisampleStateCreateInfo();
1920
1921 auto const stencilOp =
1922 vk::StencilOpState().setFailOp(vk::StencilOp::eKeep).setPassOp(vk::StencilOp::eKeep).setCompareOp(vk::CompareOp::eAlways);
1923
1924 auto const depthStencilInfo = vk::PipelineDepthStencilStateCreateInfo()
1925 .setDepthTestEnable(VK_TRUE)
1926 .setDepthWriteEnable(VK_TRUE)
1927 .setDepthCompareOp(vk::CompareOp::eLessOrEqual)
1928 .setDepthBoundsTestEnable(VK_FALSE)
1929 .setStencilTestEnable(VK_FALSE)
1930 .setFront(stencilOp)
1931 .setBack(stencilOp);
1932
1933 vk::PipelineColorBlendAttachmentState const colorBlendAttachments[1] = {
1934 vk::PipelineColorBlendAttachmentState().setColorWriteMask(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1935 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA)};
1936
1937 auto const colorBlendInfo =
1938 vk::PipelineColorBlendStateCreateInfo().setAttachmentCount(1).setPAttachments(colorBlendAttachments);
1939
1940 vk::DynamicState const dynamicStates[2] = {vk::DynamicState::eViewport, vk::DynamicState::eScissor};
1941
1942 auto const dynamicStateInfo = vk::PipelineDynamicStateCreateInfo().setPDynamicStates(dynamicStates).setDynamicStateCount(2);
1943
1944 auto const pipeline = vk::GraphicsPipelineCreateInfo()
1945 .setStageCount(2)
1946 .setPStages(shaderStageInfo)
1947 .setPVertexInputState(&vertexInputInfo)
1948 .setPInputAssemblyState(&inputAssemblyInfo)
1949 .setPViewportState(&viewportInfo)
1950 .setPRasterizationState(&rasterizationInfo)
1951 .setPMultisampleState(&multisampleInfo)
1952 .setPDepthStencilState(&depthStencilInfo)
1953 .setPColorBlendState(&colorBlendInfo)
1954 .setPDynamicState(&dynamicStateInfo)
1955 .setLayout(pipeline_layout)
1956 .setRenderPass(render_pass);
1957
1958 result = device.createGraphicsPipelines(pipelineCache, 1, &pipeline, nullptr, &this->pipeline);
1959 VERIFY(result == vk::Result::eSuccess);
1960
1961 device.destroyShaderModule(frag_shader_module, nullptr);
1962 device.destroyShaderModule(vert_shader_module, nullptr);
1963}
1964
1965void Demo::prepare_render_pass() {
1966 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1967 // because at the start of the renderpass, we don't care about their contents.
1968 // At the start of the subpass, the color attachment's layout will be transitioned
1969 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1970 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1971 // the renderpass, the color attachment's layout will be transitioned to
1972 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1973 // the renderpass, no barriers are necessary.
1974 const vk::AttachmentDescription attachments[2] = {vk::AttachmentDescription()
1975 .setFormat(format)
1976 .setSamples(vk::SampleCountFlagBits::e1)
1977 .setLoadOp(vk::AttachmentLoadOp::eClear)
1978 .setStoreOp(vk::AttachmentStoreOp::eStore)
1979 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1980 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1981 .setInitialLayout(vk::ImageLayout::eUndefined)
1982 .setFinalLayout(vk::ImageLayout::ePresentSrcKHR),
1983 vk::AttachmentDescription()
1984 .setFormat(depth.format)
1985 .setSamples(vk::SampleCountFlagBits::e1)
1986 .setLoadOp(vk::AttachmentLoadOp::eClear)
1987 .setStoreOp(vk::AttachmentStoreOp::eDontCare)
1988 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1989 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1990 .setInitialLayout(vk::ImageLayout::eUndefined)
1991 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)};
1992
1993 auto const color_reference = vk::AttachmentReference().setAttachment(0).setLayout(vk::ImageLayout::eColorAttachmentOptimal);
1994
1995 auto const depth_reference =
1996 vk::AttachmentReference().setAttachment(1).setLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1997
1998 auto const subpass = vk::SubpassDescription()
1999 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
2000 .setInputAttachmentCount(0)
2001 .setPInputAttachments(nullptr)
2002 .setColorAttachmentCount(1)
2003 .setPColorAttachments(&color_reference)
2004 .setPResolveAttachments(nullptr)
2005 .setPDepthStencilAttachment(&depth_reference)
2006 .setPreserveAttachmentCount(0)
2007 .setPPreserveAttachments(nullptr);
2008
Tony-LunarG495604b2019-06-13 15:32:05 -06002009 vk::PipelineStageFlags stages = vk::PipelineStageFlagBits::eEarlyFragmentTests | vk::PipelineStageFlagBits::eLateFragmentTests;
2010 vk::SubpassDependency const dependencies[2] = {
2011 vk::SubpassDependency() // Depth buffer is shared between swapchain images
2012 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2013 .setDstSubpass(0)
2014 .setSrcStageMask(stages)
2015 .setDstStageMask(stages)
2016 .setSrcAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2017 .setDstAccessMask(vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite)
2018 .setDependencyFlags(vk::DependencyFlags()),
2019 vk::SubpassDependency() // Image layout transition
2020 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
2021 .setDstSubpass(0)
2022 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2023 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput)
2024 .setSrcAccessMask(vk::AccessFlagBits())
2025 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eColorAttachmentRead)
2026 .setDependencyFlags(vk::DependencyFlags()),
2027 };
2028
Dave Houlton5fa47912018-02-16 11:02:26 -07002029 auto const rp_info = vk::RenderPassCreateInfo()
2030 .setAttachmentCount(2)
2031 .setPAttachments(attachments)
2032 .setSubpassCount(1)
2033 .setPSubpasses(&subpass)
Tony-LunarG495604b2019-06-13 15:32:05 -06002034 .setDependencyCount(2)
2035 .setPDependencies(dependencies);
Dave Houlton5fa47912018-02-16 11:02:26 -07002036
2037 auto result = device.createRenderPass(&rp_info, nullptr, &render_pass);
2038 VERIFY(result == vk::Result::eSuccess);
2039}
2040
2041vk::ShaderModule Demo::prepare_shader_module(const uint32_t *code, size_t size) {
2042 const auto moduleCreateInfo = vk::ShaderModuleCreateInfo().setCodeSize(size).setPCode(code);
2043
2044 vk::ShaderModule module;
2045 auto result = device.createShaderModule(&moduleCreateInfo, nullptr, &module);
2046 VERIFY(result == vk::Result::eSuccess);
2047
2048 return module;
2049}
2050
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002051void Demo::prepare_texture_buffer(const char *filename, texture_object *tex_obj) {
2052 int32_t tex_width;
2053 int32_t tex_height;
2054
2055 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
2056 ERR_EXIT("Failed to load textures", "Load Texture Failure");
2057 }
2058
2059 tex_obj->tex_width = tex_width;
2060 tex_obj->tex_height = tex_height;
2061
2062 auto const buffer_create_info = vk::BufferCreateInfo()
2063 .setSize(tex_width * tex_height * 4)
2064 .setUsage(vk::BufferUsageFlagBits::eTransferSrc)
2065 .setSharingMode(vk::SharingMode::eExclusive)
2066 .setQueueFamilyIndexCount(0)
2067 .setPQueueFamilyIndices(nullptr);
2068
2069 auto result = device.createBuffer(&buffer_create_info, nullptr, &tex_obj->buffer);
2070 VERIFY(result == vk::Result::eSuccess);
2071
2072 vk::MemoryRequirements mem_reqs;
2073 device.getBufferMemoryRequirements(tex_obj->buffer, &mem_reqs);
2074
2075 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2076 tex_obj->mem_alloc.setMemoryTypeIndex(0);
2077
2078 vk::MemoryPropertyFlags requirements = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent;
2079 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
2080 VERIFY(pass == true);
2081
2082 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2083 VERIFY(result == vk::Result::eSuccess);
2084
2085 result = device.bindBufferMemory(tex_obj->buffer, tex_obj->mem, 0);
2086 VERIFY(result == vk::Result::eSuccess);
2087
2088 vk::SubresourceLayout layout;
2089 memset(&layout, 0, sizeof(layout));
2090 layout.rowPitch = tex_width * 4;
2091 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
2092 VERIFY(data.result == vk::Result::eSuccess);
2093
2094 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2095 fprintf(stderr, "Error loading texture: %s\n", filename);
2096 }
2097
2098 device.unmapMemory(tex_obj->mem);
2099}
2100
Dave Houlton5fa47912018-02-16 11:02:26 -07002101void Demo::prepare_texture_image(const char *filename, texture_object *tex_obj, vk::ImageTiling tiling, vk::ImageUsageFlags usage,
2102 vk::MemoryPropertyFlags required_props) {
2103 int32_t tex_width;
2104 int32_t tex_height;
2105 if (!loadTexture(filename, nullptr, nullptr, &tex_width, &tex_height)) {
2106 ERR_EXIT("Failed to load textures", "Load Texture Failure");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002107 }
2108
Dave Houlton5fa47912018-02-16 11:02:26 -07002109 tex_obj->tex_width = tex_width;
2110 tex_obj->tex_height = tex_height;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002111
Dave Houlton5fa47912018-02-16 11:02:26 -07002112 auto const image_create_info = vk::ImageCreateInfo()
2113 .setImageType(vk::ImageType::e2D)
2114 .setFormat(vk::Format::eR8G8B8A8Unorm)
2115 .setExtent({(uint32_t)tex_width, (uint32_t)tex_height, 1})
2116 .setMipLevels(1)
2117 .setArrayLayers(1)
2118 .setSamples(vk::SampleCountFlagBits::e1)
2119 .setTiling(tiling)
2120 .setUsage(usage)
2121 .setSharingMode(vk::SharingMode::eExclusive)
2122 .setQueueFamilyIndexCount(0)
2123 .setPQueueFamilyIndices(nullptr)
2124 .setInitialLayout(vk::ImageLayout::ePreinitialized);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002125
Dave Houlton5fa47912018-02-16 11:02:26 -07002126 auto result = device.createImage(&image_create_info, nullptr, &tex_obj->image);
2127 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002128
Dave Houlton5fa47912018-02-16 11:02:26 -07002129 vk::MemoryRequirements mem_reqs;
2130 device.getImageMemoryRequirements(tex_obj->image, &mem_reqs);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002131
Dave Houlton5fa47912018-02-16 11:02:26 -07002132 tex_obj->mem_alloc.setAllocationSize(mem_reqs.size);
2133 tex_obj->mem_alloc.setMemoryTypeIndex(0);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002134
Dave Houlton5fa47912018-02-16 11:02:26 -07002135 auto pass = memory_type_from_properties(mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
2136 VERIFY(pass == true);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002137
Dave Houlton5fa47912018-02-16 11:02:26 -07002138 result = device.allocateMemory(&tex_obj->mem_alloc, nullptr, &(tex_obj->mem));
2139 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002140
Dave Houlton5fa47912018-02-16 11:02:26 -07002141 result = device.bindImageMemory(tex_obj->image, tex_obj->mem, 0);
2142 VERIFY(result == vk::Result::eSuccess);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002143
Dave Houlton5fa47912018-02-16 11:02:26 -07002144 if (required_props & vk::MemoryPropertyFlagBits::eHostVisible) {
2145 auto const subres = vk::ImageSubresource().setAspectMask(vk::ImageAspectFlagBits::eColor).setMipLevel(0).setArrayLayer(0);
2146 vk::SubresourceLayout layout;
2147 device.getImageSubresourceLayout(tex_obj->image, &subres, &layout);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002148
Dave Houlton5fa47912018-02-16 11:02:26 -07002149 auto data = device.mapMemory(tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002150 VERIFY(data.result == vk::Result::eSuccess);
2151
Dave Houlton5fa47912018-02-16 11:02:26 -07002152 if (!loadTexture(filename, (uint8_t *)data.value, &layout, &tex_width, &tex_height)) {
2153 fprintf(stderr, "Error loading texture: %s\n", filename);
2154 }
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002155
Dave Houlton5fa47912018-02-16 11:02:26 -07002156 device.unmapMemory(tex_obj->mem);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002157 }
2158
Dave Houlton5fa47912018-02-16 11:02:26 -07002159 tex_obj->imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
2160}
2161
2162void Demo::prepare_textures() {
2163 vk::Format const tex_format = vk::Format::eR8G8B8A8Unorm;
2164 vk::FormatProperties props;
2165 gpu.getFormatProperties(tex_format, &props);
2166
2167 for (uint32_t i = 0; i < texture_count; i++) {
2168 if ((props.linearTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) && !use_staging_buffer) {
2169 /* Device can texture using linear textures */
2170 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eLinear, vk::ImageUsageFlagBits::eSampled,
2171 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
2172 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
2173 // shader to run until layout transition completes
2174 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2175 textures[i].imageLayout, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2176 vk::PipelineStageFlagBits::eFragmentShader);
2177 staging_texture.image = vk::Image();
2178 } else if (props.optimalTilingFeatures & vk::FormatFeatureFlagBits::eSampledImage) {
2179 /* Must use staging buffer to copy linear texture to optimized */
2180
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002181 prepare_texture_buffer(tex_files[i], &staging_texture);
Dave Houlton5fa47912018-02-16 11:02:26 -07002182
2183 prepare_texture_image(tex_files[i], &textures[i], vk::ImageTiling::eOptimal,
2184 vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
2185 vk::MemoryPropertyFlagBits::eDeviceLocal);
2186
Dave Houlton5fa47912018-02-16 11:02:26 -07002187 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::ePreinitialized,
2188 vk::ImageLayout::eTransferDstOptimal, vk::AccessFlagBits(), vk::PipelineStageFlagBits::eTopOfPipe,
2189 vk::PipelineStageFlagBits::eTransfer);
2190
2191 auto const subresource = vk::ImageSubresourceLayers()
2192 .setAspectMask(vk::ImageAspectFlagBits::eColor)
2193 .setMipLevel(0)
2194 .setBaseArrayLayer(0)
2195 .setLayerCount(1);
2196
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002197 auto const copy_region =
2198 vk::BufferImageCopy()
2199 .setBufferOffset(0)
2200 .setBufferRowLength(staging_texture.tex_width)
2201 .setBufferImageHeight(staging_texture.tex_height)
2202 .setImageSubresource(subresource)
2203 .setImageOffset({0, 0, 0})
2204 .setImageExtent({(uint32_t)staging_texture.tex_width, (uint32_t)staging_texture.tex_height, 1});
Dave Houlton5fa47912018-02-16 11:02:26 -07002205
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002206 cmd.copyBufferToImage(staging_texture.buffer, textures[i].image, vk::ImageLayout::eTransferDstOptimal, 1, &copy_region);
Dave Houlton5fa47912018-02-16 11:02:26 -07002207
2208 set_image_layout(textures[i].image, vk::ImageAspectFlagBits::eColor, vk::ImageLayout::eTransferDstOptimal,
2209 textures[i].imageLayout, vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer,
2210 vk::PipelineStageFlagBits::eFragmentShader);
2211 } else {
2212 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002213 }
2214
Dave Houlton5fa47912018-02-16 11:02:26 -07002215 auto const samplerInfo = vk::SamplerCreateInfo()
2216 .setMagFilter(vk::Filter::eNearest)
2217 .setMinFilter(vk::Filter::eNearest)
2218 .setMipmapMode(vk::SamplerMipmapMode::eNearest)
2219 .setAddressModeU(vk::SamplerAddressMode::eClampToEdge)
2220 .setAddressModeV(vk::SamplerAddressMode::eClampToEdge)
2221 .setAddressModeW(vk::SamplerAddressMode::eClampToEdge)
2222 .setMipLodBias(0.0f)
2223 .setAnisotropyEnable(VK_FALSE)
2224 .setMaxAnisotropy(1)
2225 .setCompareEnable(VK_FALSE)
2226 .setCompareOp(vk::CompareOp::eNever)
2227 .setMinLod(0.0f)
2228 .setMaxLod(0.0f)
2229 .setBorderColor(vk::BorderColor::eFloatOpaqueWhite)
2230 .setUnnormalizedCoordinates(VK_FALSE);
2231
2232 auto result = device.createSampler(&samplerInfo, nullptr, &textures[i].sampler);
2233 VERIFY(result == vk::Result::eSuccess);
2234
2235 auto const viewInfo = vk::ImageViewCreateInfo()
2236 .setImage(textures[i].image)
2237 .setViewType(vk::ImageViewType::e2D)
2238 .setFormat(tex_format)
2239 .setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
2240
2241 result = device.createImageView(&viewInfo, nullptr, &textures[i].view);
2242 VERIFY(result == vk::Result::eSuccess);
2243 }
2244}
2245
2246vk::ShaderModule Demo::prepare_vs() {
2247 const uint32_t vertShaderCode[] = {
2248#include "cube.vert.inc"
2249 };
2250
2251 vert_shader_module = prepare_shader_module(vertShaderCode, sizeof(vertShaderCode));
2252
2253 return vert_shader_module;
2254}
2255
2256void Demo::resize() {
2257 uint32_t i;
2258
2259 // Don't react to resize until after first initialization.
2260 if (!prepared) {
2261 return;
2262 }
2263
2264 // In order to properly resize the window, we must re-create the
2265 // swapchain
2266 // AND redo the command buffers, etc.
2267 //
2268 // First, perform part of the cleanup() function:
2269 prepared = false;
2270 auto result = device.waitIdle();
2271 VERIFY(result == vk::Result::eSuccess);
2272
2273 for (i = 0; i < swapchainImageCount; i++) {
2274 device.destroyFramebuffer(swapchain_image_resources[i].framebuffer, nullptr);
2275 }
2276
2277 device.destroyDescriptorPool(desc_pool, nullptr);
2278
2279 device.destroyPipeline(pipeline, nullptr);
2280 device.destroyPipelineCache(pipelineCache, nullptr);
2281 device.destroyRenderPass(render_pass, nullptr);
2282 device.destroyPipelineLayout(pipeline_layout, nullptr);
2283 device.destroyDescriptorSetLayout(desc_layout, nullptr);
2284
2285 for (i = 0; i < texture_count; i++) {
2286 device.destroyImageView(textures[i].view, nullptr);
2287 device.destroyImage(textures[i].image, nullptr);
2288 device.freeMemory(textures[i].mem, nullptr);
2289 device.destroySampler(textures[i].sampler, nullptr);
2290 }
2291
2292 device.destroyImageView(depth.view, nullptr);
2293 device.destroyImage(depth.image, nullptr);
2294 device.freeMemory(depth.mem, nullptr);
2295
2296 for (i = 0; i < swapchainImageCount; i++) {
2297 device.destroyImageView(swapchain_image_resources[i].view, nullptr);
2298 device.freeCommandBuffers(cmd_pool, 1, &swapchain_image_resources[i].cmd);
2299 device.destroyBuffer(swapchain_image_resources[i].uniform_buffer, nullptr);
2300 device.freeMemory(swapchain_image_resources[i].uniform_memory, nullptr);
2301 }
2302
2303 device.destroyCommandPool(cmd_pool, nullptr);
2304 if (separate_present_queue) {
2305 device.destroyCommandPool(present_cmd_pool, nullptr);
2306 }
2307
2308 // Second, re-perform the prepare() function, which will re-create the
2309 // swapchain.
2310 prepare();
2311}
2312
2313void Demo::set_image_layout(vk::Image image, vk::ImageAspectFlags aspectMask, vk::ImageLayout oldLayout, vk::ImageLayout newLayout,
2314 vk::AccessFlags srcAccessMask, vk::PipelineStageFlags src_stages, vk::PipelineStageFlags dest_stages) {
2315 assert(cmd);
2316
2317 auto DstAccessMask = [](vk::ImageLayout const &layout) {
2318 vk::AccessFlags flags;
2319
2320 switch (layout) {
2321 case vk::ImageLayout::eTransferDstOptimal:
2322 // Make sure anything that was copying from this image has
2323 // completed
2324 flags = vk::AccessFlagBits::eTransferWrite;
2325 break;
2326 case vk::ImageLayout::eColorAttachmentOptimal:
2327 flags = vk::AccessFlagBits::eColorAttachmentWrite;
2328 break;
2329 case vk::ImageLayout::eDepthStencilAttachmentOptimal:
2330 flags = vk::AccessFlagBits::eDepthStencilAttachmentWrite;
2331 break;
2332 case vk::ImageLayout::eShaderReadOnlyOptimal:
2333 // Make sure any Copy or CPU writes to image are flushed
2334 flags = vk::AccessFlagBits::eShaderRead | vk::AccessFlagBits::eInputAttachmentRead;
2335 break;
2336 case vk::ImageLayout::eTransferSrcOptimal:
2337 flags = vk::AccessFlagBits::eTransferRead;
2338 break;
2339 case vk::ImageLayout::ePresentSrcKHR:
2340 flags = vk::AccessFlagBits::eMemoryRead;
2341 break;
2342 default:
2343 break;
2344 }
2345
2346 return flags;
2347 };
2348
2349 auto const barrier = vk::ImageMemoryBarrier()
2350 .setSrcAccessMask(srcAccessMask)
2351 .setDstAccessMask(DstAccessMask(newLayout))
2352 .setOldLayout(oldLayout)
2353 .setNewLayout(newLayout)
Tony-LunarGa141b962018-05-30 11:33:19 -06002354 .setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
2355 .setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
Dave Houlton5fa47912018-02-16 11:02:26 -07002356 .setImage(image)
2357 .setSubresourceRange(vk::ImageSubresourceRange(aspectMask, 0, 1, 0, 1));
2358
2359 cmd.pipelineBarrier(src_stages, dest_stages, vk::DependencyFlagBits(), 0, nullptr, 0, nullptr, 1, &barrier);
2360}
2361
2362void Demo::update_data_buffer() {
2363 mat4x4 VP;
2364 mat4x4_mul(VP, projection_matrix, view_matrix);
2365
2366 // Rotate around the Y axis
2367 mat4x4 Model;
2368 mat4x4_dup(Model, model_matrix);
2369 mat4x4_rotate(model_matrix, Model, 0.0f, 1.0f, 0.0f, (float)degreesToRadians(spin_angle));
2370
2371 mat4x4 MVP;
2372 mat4x4_mul(MVP, VP, model_matrix);
2373
2374 auto data = device.mapMemory(swapchain_image_resources[current_buffer].uniform_memory, 0, VK_WHOLE_SIZE, vk::MemoryMapFlags());
2375 VERIFY(data.result == vk::Result::eSuccess);
2376
2377 memcpy(data.value, (const void *)&MVP[0][0], sizeof(MVP));
2378
2379 device.unmapMemory(swapchain_image_resources[current_buffer].uniform_memory);
2380}
2381
Karl Schultzb7940402018-05-29 13:09:22 -06002382/* Convert ppm image data from header file into RGBA texture image */
2383#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07002384bool 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 -06002385 (void)filename;
2386 char *cPtr;
2387 cPtr = (char *)lunarg_ppm;
2388 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002389 return false;
2390 }
Karl Schultzb7940402018-05-29 13:09:22 -06002391 while (strncmp(cPtr++, "\n", 1))
2392 ;
2393 sscanf(cPtr, "%u %u", width, height);
2394 if (rgba_data == NULL) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002395 return true;
2396 }
Karl Schultzb7940402018-05-29 13:09:22 -06002397 while (strncmp(cPtr++, "\n", 1))
2398 ;
2399 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002400 return false;
2401 }
Karl Schultzb7940402018-05-29 13:09:22 -06002402 while (strncmp(cPtr++, "\n", 1))
2403 ;
Dave Houlton5fa47912018-02-16 11:02:26 -07002404 for (int y = 0; y < *height; y++) {
2405 uint8_t *rowPtr = rgba_data;
Dave Houlton5fa47912018-02-16 11:02:26 -07002406 for (int x = 0; x < *width; x++) {
Karl Schultzb7940402018-05-29 13:09:22 -06002407 memcpy(rowPtr, cPtr, 3);
Dave Houlton5fa47912018-02-16 11:02:26 -07002408 rowPtr[3] = 255; /* Alpha of 1 */
2409 rowPtr += 4;
Karl Schultzb7940402018-05-29 13:09:22 -06002410 cPtr += 3;
Dave Houlton5fa47912018-02-16 11:02:26 -07002411 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002412 rgba_data += layout->rowPitch;
2413 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002414 return true;
2415}
2416
2417bool Demo::memory_type_from_properties(uint32_t typeBits, vk::MemoryPropertyFlags requirements_mask, uint32_t *typeIndex) {
2418 // Search memtypes to find first index with those properties
2419 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
2420 if ((typeBits & 1) == 1) {
2421 // Type is available, does it match user properties?
2422 if ((memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
2423 *typeIndex = i;
2424 return true;
2425 }
2426 }
2427 typeBits >>= 1;
2428 }
2429
2430 // No memory types matched, return failure
2431 return false;
2432}
2433
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002434#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002435void Demo::run() {
2436 if (!prepared) {
2437 return;
2438 }
2439
2440 draw();
2441 curFrame++;
2442
Petr Krausd88e4e52019-01-23 18:45:04 +01002443 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002444 PostQuitMessage(validation_error);
2445 }
2446}
2447
2448void Demo::create_window() {
2449 WNDCLASSEX win_class;
2450
2451 // Initialize the window class structure:
2452 win_class.cbSize = sizeof(WNDCLASSEX);
2453 win_class.style = CS_HREDRAW | CS_VREDRAW;
2454 win_class.lpfnWndProc = WndProc;
2455 win_class.cbClsExtra = 0;
2456 win_class.cbWndExtra = 0;
2457 win_class.hInstance = connection; // hInstance
2458 win_class.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
2459 win_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
2460 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2461 win_class.lpszMenuName = nullptr;
2462 win_class.lpszClassName = name;
2463 win_class.hIconSm = LoadIcon(nullptr, IDI_WINLOGO);
2464
2465 // Register window class:
2466 if (!RegisterClassEx(&win_class)) {
2467 // It didn't work, so try to give a useful error:
2468 printf("Unexpected error trying to start the application!\n");
2469 fflush(stdout);
2470 exit(1);
2471 }
2472
2473 // Create window with the registered class:
2474 RECT wr = {0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
2475 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
2476 window = CreateWindowEx(0,
2477 name, // class name
2478 name, // app name
2479 WS_OVERLAPPEDWINDOW | // window style
2480 WS_VISIBLE | WS_SYSMENU,
2481 100, 100, // x/y coords
2482 wr.right - wr.left, // width
2483 wr.bottom - wr.top, // height
2484 nullptr, // handle to parent
2485 nullptr, // handle to menu
2486 connection, // hInstance
2487 nullptr); // no extra parameters
2488
2489 if (!window) {
2490 // It didn't work, so try to give a useful error:
2491 printf("Cannot create a window in which to draw!\n");
2492 fflush(stdout);
2493 exit(1);
2494 }
2495
2496 // Window client area size must be at least 1 pixel high, to prevent
2497 // crash.
2498 minsize.x = GetSystemMetrics(SM_CXMINTRACK);
2499 minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
2500}
2501#elif defined(VK_USE_PLATFORM_XLIB_KHR)
2502
2503void Demo::create_xlib_window() {
2504 const char *display_envar = getenv("DISPLAY");
2505 if (display_envar == nullptr || display_envar[0] == '\0') {
2506 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2507 fflush(stdout);
2508 exit(1);
2509 }
2510
2511 XInitThreads();
2512 display = XOpenDisplay(nullptr);
2513 long visualMask = VisualScreenMask;
2514 int numberOfVisuals;
2515 XVisualInfo vInfoTemplate = {};
2516 vInfoTemplate.screen = DefaultScreen(display);
2517 XVisualInfo *visualInfo = XGetVisualInfo(display, visualMask, &vInfoTemplate, &numberOfVisuals);
2518
2519 Colormap colormap = XCreateColormap(display, RootWindow(display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
2520
2521 XSetWindowAttributes windowAttributes = {};
2522 windowAttributes.colormap = colormap;
2523 windowAttributes.background_pixel = 0xFFFFFFFF;
2524 windowAttributes.border_pixel = 0;
2525 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
2526
2527 xlib_window =
2528 XCreateWindow(display, RootWindow(display, vInfoTemplate.screen), 0, 0, width, height, 0, visualInfo->depth, InputOutput,
2529 visualInfo->visual, CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
2530
2531 XSelectInput(display, xlib_window, ExposureMask | KeyPressMask);
2532 XMapWindow(display, xlib_window);
2533 XFlush(display);
2534 xlib_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
2535}
2536
2537void Demo::handle_xlib_event(const XEvent *event) {
2538 switch (event->type) {
2539 case ClientMessage:
2540 if ((Atom)event->xclient.data.l[0] == xlib_wm_delete_window) {
2541 quit = true;
2542 }
2543 break;
2544 case KeyPress:
2545 switch (event->xkey.keycode) {
2546 case 0x9: // Escape
2547 quit = true;
2548 break;
2549 case 0x71: // left arrow key
2550 spin_angle -= spin_increment;
2551 break;
2552 case 0x72: // right arrow key
2553 spin_angle += spin_increment;
2554 break;
2555 case 0x41: // space bar
2556 pause = !pause;
2557 break;
2558 }
2559 break;
2560 case ConfigureNotify:
2561 if (((int32_t)width != event->xconfigure.width) || ((int32_t)height != event->xconfigure.height)) {
2562 width = event->xconfigure.width;
2563 height = event->xconfigure.height;
2564 resize();
2565 }
2566 break;
2567 default:
2568 break;
2569 }
2570}
2571
2572void Demo::run_xlib() {
2573 while (!quit) {
2574 XEvent event;
2575
2576 if (pause) {
2577 XNextEvent(display, &event);
2578 handle_xlib_event(&event);
2579 }
2580 while (XPending(display) > 0) {
2581 XNextEvent(display, &event);
2582 handle_xlib_event(&event);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002583 }
2584
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002585 draw();
2586 curFrame++;
2587
Dave Houlton5fa47912018-02-16 11:02:26 -07002588 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2589 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002590 }
2591 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002592}
Tony Barbour153cb062016-12-07 13:43:36 -07002593#elif defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002594
Dave Houlton5fa47912018-02-16 11:02:26 -07002595void Demo::handle_xcb_event(const xcb_generic_event_t *event) {
2596 uint8_t event_code = event->response_type & 0x7f;
2597 switch (event_code) {
2598 case XCB_EXPOSE:
2599 // TODO: Resize window
2600 break;
2601 case XCB_CLIENT_MESSAGE:
2602 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*atom_wm_delete_window).atom) {
2603 quit = true;
2604 }
2605 break;
2606 case XCB_KEY_RELEASE: {
2607 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002608
Dave Houlton5fa47912018-02-16 11:02:26 -07002609 switch (key->detail) {
2610 case 0x9: // Escape
2611 quit = true;
2612 break;
2613 case 0x71: // left arrow key
2614 spin_angle -= spin_increment;
2615 break;
2616 case 0x72: // right arrow key
2617 spin_angle += spin_increment;
2618 break;
2619 case 0x41: // space bar
2620 pause = !pause;
2621 break;
2622 }
2623 } break;
2624 case XCB_CONFIGURE_NOTIFY: {
2625 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2626 if ((width != cfg->width) || (height != cfg->height)) {
2627 width = cfg->width;
2628 height = cfg->height;
2629 resize();
2630 }
2631 } break;
2632 default:
2633 break;
2634 }
2635}
2636
2637void Demo::run_xcb() {
2638 xcb_flush(connection);
2639
2640 while (!quit) {
2641 xcb_generic_event_t *event;
2642
2643 if (pause) {
2644 event = xcb_wait_for_event(connection);
2645 } else {
2646 event = xcb_poll_for_event(connection);
2647 }
2648 while (event) {
2649 handle_xcb_event(event);
2650 free(event);
2651 event = xcb_poll_for_event(connection);
2652 }
2653
2654 draw();
2655 curFrame++;
2656 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2657 quit = true;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002658 }
2659 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002660}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002661
Dave Houlton5fa47912018-02-16 11:02:26 -07002662void Demo::create_xcb_window() {
2663 uint32_t value_mask, value_list[32];
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002664
Dave Houlton5fa47912018-02-16 11:02:26 -07002665 xcb_window = xcb_generate_id(connection);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002666
Dave Houlton5fa47912018-02-16 11:02:26 -07002667 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2668 value_list[0] = screen->black_pixel;
2669 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002670
Dave Houlton5fa47912018-02-16 11:02:26 -07002671 xcb_create_window(connection, XCB_COPY_FROM_PARENT, xcb_window, screen->root, 0, 0, width, height, 0,
2672 XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, value_mask, value_list);
2673
2674 /* Magic code that will send notification when window is destroyed */
2675 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, 1, 12, "WM_PROTOCOLS");
2676 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0);
2677
2678 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(connection, 0, 16, "WM_DELETE_WINDOW");
2679 atom_wm_delete_window = xcb_intern_atom_reply(connection, cookie2, 0);
2680
2681 xcb_change_property(connection, XCB_PROP_MODE_REPLACE, xcb_window, (*reply).atom, 4, 32, 1, &(*atom_wm_delete_window).atom);
2682
2683 free(reply);
2684
2685 xcb_map_window(connection, xcb_window);
2686
2687 // Force the x/y coordinates to 100,100 results are identical in
2688 // consecutive
2689 // runs
2690 const uint32_t coords[] = {100, 100};
2691 xcb_configure_window(connection, xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
2692}
2693#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
2694
2695void Demo::run() {
2696 while (!quit) {
2697 if (pause) {
2698 wl_display_dispatch(display);
2699 } else {
2700 wl_display_dispatch_pending(display);
2701 update_data_buffer();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002702 draw();
2703 curFrame++;
Jeremy Hayes9d304782016-10-09 11:48:12 -06002704 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002705 quit = true;
2706 }
2707 }
2708 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002709}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002710
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002711static void handle_surface_configure(void *data, xdg_surface *xdg_surface, uint32_t serial) {
2712 Demo *demo = (Demo *)data;
2713 xdg_surface_ack_configure(xdg_surface, serial);
2714 if (demo->xdg_surface_has_been_configured) {
2715 demo->resize();
2716 }
2717 demo->xdg_surface_has_been_configured = true;
2718}
2719
2720static const xdg_surface_listener surface_listener = {handle_surface_configure};
2721
2722static void handle_toplevel_configure(void *data, xdg_toplevel *xdg_toplevel, int32_t width, int32_t height,
2723 struct wl_array *states) {
2724 Demo *demo = (Demo *)data;
2725 demo->width = width;
2726 demo->height = height;
2727 // This will be followed by a surface configure
2728}
2729
2730static void handle_toplevel_close(void *data, xdg_toplevel *xdg_toplevel) {
2731 Demo *demo = (Demo *)data;
2732 demo->quit = true;
2733}
2734
2735static const xdg_toplevel_listener toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
2736
Dave Houlton5fa47912018-02-16 11:02:26 -07002737void Demo::create_window() {
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002738 if (!wm_base) {
2739 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2740 fflush(stdout);
2741 exit(1);
2742 }
2743
Dave Houlton5fa47912018-02-16 11:02:26 -07002744 window = wl_compositor_create_surface(compositor);
2745 if (!window) {
2746 printf("Can not create wayland_surface from compositor!\n");
2747 fflush(stdout);
2748 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002749 }
2750
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002751 window_surface = xdg_wm_base_get_xdg_surface(wm_base, window);
2752 if (!window_surface) {
2753 printf("Can not get xdg_surface from wayland_surface!\n");
Dave Houlton5fa47912018-02-16 11:02:26 -07002754 fflush(stdout);
2755 exit(1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002756 }
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002757 window_toplevel = xdg_surface_get_toplevel(window_surface);
2758 if (!window_toplevel) {
2759 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2760 fflush(stdout);
2761 exit(1);
2762 }
2763 xdg_surface_add_listener(window_surface, &surface_listener, this);
2764 xdg_toplevel_add_listener(window_toplevel, &toplevel_listener, this);
2765 xdg_toplevel_set_title(window_toplevel, APP_SHORT_NAME);
2766 if (xdg_decoration_mgr) {
2767 // if supported, let the compositor render titlebars for us
2768 toplevel_decoration = zxdg_decoration_manager_v1_get_toplevel_decoration(xdg_decoration_mgr, window_toplevel);
2769 zxdg_toplevel_decoration_v1_set_mode(toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2770 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002771
Manuel Stoeckl6f6e3372019-06-26 20:55:53 -04002772 wl_surface_commit(window);
Dave Houlton5fa47912018-02-16 11:02:26 -07002773}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002774#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002775void Demo::run() {
2776 draw();
2777 curFrame++;
2778 if (frameCount != UINT32_MAX && curFrame == frameCount) {
2779 quit = true;
2780 }
2781}
Damien Leone600c3052017-01-31 10:26:07 -07002782#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2783
Dave Houlton5fa47912018-02-16 11:02:26 -07002784vk::Result Demo::create_display_surface() {
2785 vk::Result result;
2786 uint32_t display_count;
2787 uint32_t mode_count;
2788 uint32_t plane_count;
2789 vk::DisplayPropertiesKHR display_props;
2790 vk::DisplayKHR display;
2791 vk::DisplayModePropertiesKHR mode_props;
2792 vk::DisplayPlanePropertiesKHR *plane_props;
2793 vk::Bool32 found_plane = VK_FALSE;
2794 uint32_t plane_index;
2795 vk::Extent2D image_extent;
Damien Leone600c3052017-01-31 10:26:07 -07002796
Dave Houlton5fa47912018-02-16 11:02:26 -07002797 // Get the first display
2798 result = gpu.getDisplayPropertiesKHR(&display_count, nullptr);
2799 VERIFY(result == vk::Result::eSuccess);
Damien Leone600c3052017-01-31 10:26:07 -07002800
Dave Houlton5fa47912018-02-16 11:02:26 -07002801 if (display_count == 0) {
2802 printf("Cannot find any display!\n");
2803 fflush(stdout);
2804 exit(1);
2805 }
2806
2807 display_count = 1;
2808 result = gpu.getDisplayPropertiesKHR(&display_count, &display_props);
2809 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2810
2811 display = display_props.display;
2812
2813 // Get the first mode of the display
2814 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, nullptr);
2815 VERIFY(result == vk::Result::eSuccess);
2816
2817 if (mode_count == 0) {
2818 printf("Cannot find any mode for the display!\n");
2819 fflush(stdout);
2820 exit(1);
2821 }
2822
2823 mode_count = 1;
2824 result = gpu.getDisplayModePropertiesKHR(display, &mode_count, &mode_props);
2825 VERIFY((result == vk::Result::eSuccess) || (result == vk::Result::eIncomplete));
2826
2827 // Get the list of planes
2828 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, nullptr);
2829 VERIFY(result == vk::Result::eSuccess);
2830
2831 if (plane_count == 0) {
2832 printf("Cannot find any plane!\n");
2833 fflush(stdout);
2834 exit(1);
2835 }
2836
2837 plane_props = (vk::DisplayPlanePropertiesKHR *)malloc(sizeof(vk::DisplayPlanePropertiesKHR) * plane_count);
2838 VERIFY(plane_props != nullptr);
2839
2840 result = gpu.getDisplayPlanePropertiesKHR(&plane_count, plane_props);
2841 VERIFY(result == vk::Result::eSuccess);
2842
2843 // Find a plane compatible with the display
2844 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2845 uint32_t supported_count;
2846 vk::DisplayKHR *supported_displays;
2847
2848 // Disqualify planes that are bound to a different display
2849 if (plane_props[plane_index].currentDisplay && (plane_props[plane_index].currentDisplay != display)) {
2850 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002851 }
2852
Dave Houlton5fa47912018-02-16 11:02:26 -07002853 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002854 VERIFY(result == vk::Result::eSuccess);
2855
Dave Houlton5fa47912018-02-16 11:02:26 -07002856 if (supported_count == 0) {
2857 continue;
Damien Leone600c3052017-01-31 10:26:07 -07002858 }
2859
Dave Houlton5fa47912018-02-16 11:02:26 -07002860 supported_displays = (vk::DisplayKHR *)malloc(sizeof(vk::DisplayKHR) * supported_count);
2861 VERIFY(supported_displays != nullptr);
Damien Leone600c3052017-01-31 10:26:07 -07002862
Dave Houlton5fa47912018-02-16 11:02:26 -07002863 result = gpu.getDisplayPlaneSupportedDisplaysKHR(plane_index, &supported_count, supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002864 VERIFY(result == vk::Result::eSuccess);
2865
Dave Houlton5fa47912018-02-16 11:02:26 -07002866 for (uint32_t i = 0; i < supported_count; i++) {
2867 if (supported_displays[i] == display) {
2868 found_plane = VK_TRUE;
Damien Leone600c3052017-01-31 10:26:07 -07002869 break;
2870 }
2871 }
2872
Dave Houlton5fa47912018-02-16 11:02:26 -07002873 free(supported_displays);
Damien Leone600c3052017-01-31 10:26:07 -07002874
Dave Houlton5fa47912018-02-16 11:02:26 -07002875 if (found_plane) {
2876 break;
Damien Leone600c3052017-01-31 10:26:07 -07002877 }
2878 }
Dave Houlton5fa47912018-02-16 11:02:26 -07002879
2880 if (!found_plane) {
2881 printf("Cannot find a plane compatible with the display!\n");
2882 fflush(stdout);
2883 exit(1);
2884 }
2885
2886 free(plane_props);
2887
2888 vk::DisplayPlaneCapabilitiesKHR planeCaps;
2889 gpu.getDisplayPlaneCapabilitiesKHR(mode_props.displayMode, plane_index, &planeCaps);
2890 // Find a supported alpha mode
2891 vk::DisplayPlaneAlphaFlagBitsKHR alphaMode = vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque;
2892 vk::DisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
2893 vk::DisplayPlaneAlphaFlagBitsKHR::eOpaque,
2894 vk::DisplayPlaneAlphaFlagBitsKHR::eGlobal,
2895 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixel,
2896 vk::DisplayPlaneAlphaFlagBitsKHR::ePerPixelPremultiplied,
2897 };
2898 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
2899 if (planeCaps.supportedAlpha & alphaModes[i]) {
2900 alphaMode = alphaModes[i];
2901 break;
2902 }
2903 }
2904
2905 image_extent.setWidth(mode_props.parameters.visibleRegion.width);
2906 image_extent.setHeight(mode_props.parameters.visibleRegion.height);
2907
2908 auto const createInfo = vk::DisplaySurfaceCreateInfoKHR()
2909 .setDisplayMode(mode_props.displayMode)
2910 .setPlaneIndex(plane_index)
2911 .setPlaneStackIndex(plane_props[plane_index].currentStackIndex)
2912 .setGlobalAlpha(1.0f)
2913 .setAlphaMode(alphaMode)
2914 .setImageExtent(image_extent);
2915
2916 return inst.createDisplayPlaneSurfaceKHR(&createInfo, nullptr, &surface);
2917}
2918
2919void Demo::run_display() {
2920 while (!quit) {
2921 draw();
2922 curFrame++;
2923
Petr Krausd88e4e52019-01-23 18:45:04 +01002924 if (frameCount != UINT32_MAX && curFrame == frameCount) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002925 quit = true;
2926 }
2927 }
2928}
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002929#endif
2930
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002931#if _WIN32
2932// Include header required for parsing the command line options.
2933#include <shellapi.h>
2934
2935Demo demo;
2936
2937// MS-Windows event handling function:
Jeremy Hayes9d304782016-10-09 11:48:12 -06002938LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2939 switch (uMsg) {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002940 case WM_CLOSE:
2941 PostQuitMessage(validation_error);
2942 break;
2943 case WM_PAINT:
2944 demo.run();
2945 break;
2946 case WM_GETMINMAXINFO: // set window's minimum size
2947 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2948 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002949 case WM_ERASEBKGND:
2950 return 1;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002951 case WM_SIZE:
2952 // Resize the application to the new window size, except when
2953 // it was minimized. Vulkan doesn't support images or swapchains
2954 // with width=0 and height=0.
2955 if (wParam != SIZE_MINIMIZED) {
2956 demo.width = lParam & 0xffff;
2957 demo.height = (lParam & 0xffff0000) >> 16;
2958 demo.resize();
2959 }
2960 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002961 case WM_KEYDOWN:
2962 switch (wParam) {
2963 case VK_ESCAPE:
2964 PostQuitMessage(validation_error);
2965 break;
2966 case VK_LEFT:
2967 demo.spin_angle -= demo.spin_increment;
2968 break;
2969 case VK_RIGHT:
2970 demo.spin_angle += demo.spin_increment;
2971 break;
2972 case VK_SPACE:
2973 demo.pause = !demo.pause;
2974 break;
2975 }
2976 return 0;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002977 default:
2978 break;
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002979 }
2980
2981 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2982}
2983
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07002984int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002985 // TODO: Gah.. refactor. This isn't 1989.
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07002986 MSG msg; // message
2987 bool done; // flag saying when app is complete
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002988 int argc;
2989 char **argv;
2990
Jamie Madillb2ff6502017-03-15 16:17:46 -04002991 // Ensure wParam is initialized.
2992 msg.wParam = 0;
2993
Jeremy Hayesf56427a2016-09-07 15:55:11 -06002994 // Use the CommandLine functions to get the command line arguments.
2995 // Unfortunately, Microsoft outputs
2996 // this information as wide characters for Unicode, and we simply want the
2997 // Ascii version to be compatible
2998 // with the non-Windows side. So, we have to convert the information to
2999 // Ascii character strings.
3000 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003001 if (nullptr == commandLineArgs) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003002 argc = 0;
3003 }
3004
Jeremy Hayes9d304782016-10-09 11:48:12 -06003005 if (argc > 0) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003006 argv = (char **)malloc(sizeof(char *) * argc);
Jeremy Hayes9d304782016-10-09 11:48:12 -06003007 if (argv == nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003008 argc = 0;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003009 } else {
3010 for (int iii = 0; iii < argc; iii++) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003011 size_t wideCharLen = wcslen(commandLineArgs[iii]);
3012 size_t numConverted = 0;
3013
3014 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
Jeremy Hayes9d304782016-10-09 11:48:12 -06003015 if (argv[iii] != nullptr) {
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003016 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003017 }
3018 }
3019 }
Jeremy Hayes9d304782016-10-09 11:48:12 -06003020 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003021 argv = nullptr;
3022 }
3023
3024 demo.init(argc, argv);
3025
3026 // Free up the items we had to allocate for the command line arguments.
Jeremy Hayes9d304782016-10-09 11:48:12 -06003027 if (argc > 0 && argv != nullptr) {
3028 for (int iii = 0; iii < argc; iii++) {
3029 if (argv[iii] != nullptr) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003030 free(argv[iii]);
3031 }
3032 }
3033 free(argv);
3034 }
3035
3036 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07003037 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003038 demo.create_window();
3039 demo.init_vk_swapchain();
3040
3041 demo.prepare();
3042
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003043 done = false; // initialize loop condition variable
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003044
3045 // main message loop
Jeremy Hayes9d304782016-10-09 11:48:12 -06003046 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01003047 if (demo.pause) {
3048 const BOOL succ = WaitMessage();
3049
3050 if (!succ) {
3051 const auto &suppress_popups = demo.suppress_popups;
3052 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
3053 }
3054 }
3055
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003056 PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003057 if (msg.message == WM_QUIT) // check for a quit message
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003058 {
Mark Lobodzinski85dbd822017-01-26 13:34:13 -07003059 done = true; // if found, quit app
Jeremy Hayes9d304782016-10-09 11:48:12 -06003060 } else {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003061 /* Translate and dispatch to event queue*/
3062 TranslateMessage(&msg);
3063 DispatchMessage(&msg);
3064 }
3065 RedrawWindow(demo.window, nullptr, nullptr, RDW_INTERNALPAINT);
3066 }
3067
3068 demo.cleanup();
3069
3070 return (int)msg.wParam;
3071}
3072
3073#elif __linux__
3074
Jeremy Hayes9d304782016-10-09 11:48:12 -06003075int main(int argc, char **argv) {
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003076 Demo demo;
3077
3078 demo.init(argc, argv);
3079
Tony Barbour153cb062016-12-07 13:43:36 -07003080#if defined(VK_USE_PLATFORM_XCB_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003081 demo.create_xcb_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003082#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07003083 demo.use_xlib = true;
Jeremy Hayes9d304782016-10-09 11:48:12 -06003084 demo.create_xlib_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003085#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Jeremy Hayes9d304782016-10-09 11:48:12 -06003086 demo.create_window();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003087#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003088
3089 demo.init_vk_swapchain();
3090
3091 demo.prepare();
3092
Tony Barbour153cb062016-12-07 13:43:36 -07003093#if defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003094 demo.run_xcb();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003095#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003096 demo.run_xlib();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003097#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -07003098 demo.run();
Damien Leone600c3052017-01-31 10:26:07 -07003099#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3100 demo.run_display();
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003101#endif
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003102
3103 demo.cleanup();
3104
3105 return validation_error;
3106}
3107
Bill Hollings0a0625a2019-07-15 17:39:18 -04003108#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz9ceac062017-12-12 10:33:01 -05003109
3110// Global function invoked from NS or UI views and controllers to create demo
Bill Hollings0a0625a2019-07-15 17:39:18 -04003111static void demo_main(struct Demo &demo, void *caMetalLayer, int argc, const char *argv[]) {
Karl Schultz9ceac062017-12-12 10:33:01 -05003112 demo.init(argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003113 demo.caMetalLayer = caMetalLayer;
Karl Schultz9ceac062017-12-12 10:33:01 -05003114 demo.init_vk_swapchain();
3115 demo.prepare();
3116 demo.spin_angle = 0.4f;
3117}
3118
Jeremy Hayesf56427a2016-09-07 15:55:11 -06003119#else
3120#error "Platform not supported"
3121#endif