blob: 373b08ff566e087980f06c25c72c25f83b9fbba9 [file] [log] [blame]
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09001/*
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.
Ian Elliottd940ca22017-03-22 08:31:27 -06005 *
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: Chia-I Wu <olv@lunarg.com>
19 * Author: Courtney Goeltzenleuchter <courtney@LunarG.com>
20 * Author: Ian Elliott <ian@LunarG.com>
21 * Author: Ian Elliott <ianelliott@google.com>
22 * Author: Jon Ashburn <jon@lunarg.com>
23 * Author: Gwan-gyeong Mun <elongbug@gmail.com>
24 * Author: Tony Barbour <tony@LunarG.com>
25 * Author: Bill Hollings <bill.hollings@brenwill.com>
26 */
Karl Schultze4dc75c2016-02-02 15:37:51 -070027
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -060028#define _GNU_SOURCE
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060029#include <stdio.h>
Ian Elliottd940ca22017-03-22 08:31:27 -060030#include <stdarg.h>
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060031#include <stdlib.h>
32#include <string.h>
33#include <stdbool.h>
34#include <assert.h>
Courtney Goeltzenleuchteraf1951c2015-12-01 14:11:38 -070035#include <signal.h>
Mun Gwan-gyeong22533892016-08-20 14:46:22 +090036#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour2593b182016-04-19 10:57:58 -060037#include <X11/Xutil.h>
Joey Bzdek15eb0702017-06-07 09:40:36 -060038#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
39#include <linux/input.h>
Manuel Stoecklac939332019-06-26 20:55:53 -040040#include "xdg-shell-client-header.h"
41#include "xdg-decoration-client-header.h"
Tony Barbour2593b182016-04-19 10:57:58 -060042#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060043
Ian Elliott639ca472015-04-16 15:23:05 -060044#ifdef _WIN32
Biswapriyo Nathffe404f2020-08-25 01:47:41 +053045#ifdef _MSC_VER
Ian Elliott639ca472015-04-16 15:23:05 -060046#pragma comment(linker, "/subsystem:windows")
Biswapriyo Nathc472fa22020-08-25 23:49:34 +053047#endif // MSVC
Ian Elliott639ca472015-04-16 15:23:05 -060048#define APP_NAME_STR_LEN 80
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070049#endif // _WIN32
Ian Elliott639ca472015-04-16 15:23:05 -060050
Cody Northrop8707a6e2016-04-26 19:59:19 -060051#ifdef ANDROID
52#include "vulkan_wrapper.h"
53#else
David Pinedoc5193c12015-11-06 12:54:48 -070054#include <vulkan/vulkan.h>
Cody Northrop8707a6e2016-04-26 19:59:19 -060055#endif
Ian Elliottb08e0d92015-11-20 11:55:46 -070056
David Pinedo541526f2015-11-24 09:00:24 -070057#include <vulkan/vk_sdk_platform.h>
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -060058#include "linmath.h"
Mark Lobodzinski0edf1382018-04-10 15:40:04 -060059#include "object_type_string_helper.h"
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -060060
Ian Elliottd940ca22017-03-22 08:31:27 -060061#include "gettime.h"
62#include "inttypes.h"
63#define MILLION 1000000L
64#define BILLION 1000000000L
65
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060066#define DEMO_TEXTURE_COUNT 1
Lenny Komowffe446c2018-11-19 17:08:04 -070067#define APP_SHORT_NAME "vkcube"
68#define APP_LONG_NAME "Vulkan Cube"
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -060069
Tony Barbour66a56c32016-09-21 13:10:56 -060070// Allow a maximum of two outstanding presentation operations.
71#define FRAME_LAG 2
72
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -060073#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
74
Tony Barbourfdc2d352015-04-22 09:02:32 -060075#if defined(NDEBUG) && defined(__GNUC__)
76#define U_ASSERT_ONLY __attribute__((unused))
77#else
78#define U_ASSERT_ONLY
79#endif
80
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +090081#if defined(__GNUC__)
82#define UNUSED __attribute__((unused))
83#else
84#define UNUSED
85#endif
86
Ian Elliott07264132015-04-28 11:35:02 -060087#ifdef _WIN32
Tony Barbour602ca4f2016-09-12 14:02:43 -060088bool in_callback = false;
Mark Lobodzinski85dbd822017-01-26 13:34:13 -070089#define ERR_EXIT(err_msg, err_class) \
90 do { \
91 if (!demo->suppress_popups) MessageBox(NULL, err_msg, err_class, MB_OK); \
92 exit(1); \
Karl Schultze4dc75c2016-02-02 15:37:51 -070093 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -060094void DbgMsg(char *fmt, ...) {
95 va_list va;
96 va_start(va, fmt);
Mike Weiblene9847ff2019-06-27 15:18:32 -060097 vprintf(fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -060098 va_end(va);
Mike Weiblene9847ff2019-06-27 15:18:32 -060099 fflush(stdout);
Ian Elliottd940ca22017-03-22 08:31:27 -0600100}
Ian Elliott07264132015-04-28 11:35:02 -0600101
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500102#elif defined __ANDROID__
103#include <android/log.h>
Jeremy Kniager979b5312019-11-22 14:55:57 -0700104#define ERR_EXIT(err_msg, err_class) \
105 do { \
Lenny Komowffe446c2018-11-19 17:08:04 -0700106 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", err_msg)); \
Jeremy Kniager979b5312019-11-22 14:55:57 -0700107 exit(1); \
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500108 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -0600109#ifdef VARARGS_WORKS_ON_ANDROID
110void DbgMsg(const char *fmt, ...) {
111 va_list va;
112 va_start(va, fmt);
Lenny Komowffe446c2018-11-19 17:08:04 -0700113 __android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -0600114 va_end(va);
115}
116#else // VARARGS_WORKS_ON_ANDROID
Jeremy Kniager979b5312019-11-22 14:55:57 -0700117#define DbgMsg(fmt, ...) \
118 do { \
Lenny Komowffe446c2018-11-19 17:08:04 -0700119 ((void)__android_log_print(ANDROID_LOG_INFO, "Vulkan Cube", fmt, ##__VA_ARGS__)); \
Ian Elliottd940ca22017-03-22 08:31:27 -0600120 } while (0)
121#endif // VARARGS_WORKS_ON_ANDROID
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500122#else
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700123#define ERR_EXIT(err_msg, err_class) \
124 do { \
Robert Morell4ccc6522017-02-01 14:51:00 -0800125 printf("%s\n", err_msg); \
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700126 fflush(stdout); \
127 exit(1); \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700128 } while (0)
Ian Elliottd940ca22017-03-22 08:31:27 -0600129void DbgMsg(char *fmt, ...) {
130 va_list va;
131 va_start(va, fmt);
Mike Weiblene9847ff2019-06-27 15:18:32 -0600132 vprintf(fmt, va);
Ian Elliottd940ca22017-03-22 08:31:27 -0600133 va_end(va);
Mike Weiblene9847ff2019-06-27 15:18:32 -0600134 fflush(stdout);
Ian Elliottd940ca22017-03-22 08:31:27 -0600135}
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500136#endif
Ian Elliott07264132015-04-28 11:35:02 -0600137
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700138#define GET_INSTANCE_PROC_ADDR(inst, entrypoint) \
139 { \
140 demo->fp##entrypoint = (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \
141 if (demo->fp##entrypoint == NULL) { \
142 ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint, "vkGetInstanceProcAddr Failure"); \
143 } \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700144 }
Ian Elliottaaae5352015-07-06 14:27:58 -0600145
Jon Ashburn7d8342c2015-10-08 15:58:23 -0600146static PFN_vkGetDeviceProcAddr g_gdpa = NULL;
147
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700148#define GET_DEVICE_PROC_ADDR(dev, entrypoint) \
149 { \
150 if (!g_gdpa) g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(demo->inst, "vkGetDeviceProcAddr"); \
151 demo->fp##entrypoint = (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint); \
152 if (demo->fp##entrypoint == NULL) { \
153 ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint, "vkGetDeviceProcAddr Failure"); \
154 } \
Karl Schultze4dc75c2016-02-02 15:37:51 -0700155 }
Ian Elliott673898b2015-06-22 15:07:49 -0600156
Courtney Goeltzenleuchter97db1c12014-10-30 15:14:16 -0600157/*
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700158 * structure to track all objects related to a texture.
159 */
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600160struct texture_object {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600161 VkSampler sampler;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700162
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600163 VkImage image;
Tony-LunarGbc9fc052018-09-21 13:47:06 -0600164 VkBuffer buffer;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600165 VkImageLayout imageLayout;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600166
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800167 VkMemoryAllocateInfo mem_alloc;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -0500168 VkDeviceMemory mem;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600169 VkImageView view;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700170 int32_t tex_width, tex_height;
171};
172
Karl Schultze4dc75c2016-02-02 15:37:51 -0700173static char *tex_files[] = {"lunarg.ppm"};
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600174
Karl Schultz0218c002016-03-22 17:06:13 -0600175static int validation_error = 0;
176
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600177struct vktexcube_vs_uniform {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600178 // Must start with MVP
Karl Schultze4dc75c2016-02-02 15:37:51 -0700179 float mvp[4][4];
180 float position[12 * 3][4];
181 float attr[12 * 3][4];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600182};
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600183
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600184//--------------------------------------------------------------------------------------
185// Mesh and VertexFormat Data
186//--------------------------------------------------------------------------------------
Karl Schultze4dc75c2016-02-02 15:37:51 -0700187// clang-format off
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600188static const float g_vertex_buffer_data[] = {
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800189 -1.0f,-1.0f,-1.0f, // -X side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600190 -1.0f,-1.0f, 1.0f,
191 -1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800192 -1.0f, 1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600193 -1.0f, 1.0f,-1.0f,
194 -1.0f,-1.0f,-1.0f,
195
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800196 -1.0f,-1.0f,-1.0f, // -Z side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600197 1.0f, 1.0f,-1.0f,
198 1.0f,-1.0f,-1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800199 -1.0f,-1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600200 -1.0f, 1.0f,-1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600201 1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600202
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800203 -1.0f,-1.0f,-1.0f, // -Y side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600204 1.0f,-1.0f,-1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600205 1.0f,-1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800206 -1.0f,-1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600207 1.0f,-1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600208 -1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600209
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800210 -1.0f, 1.0f,-1.0f, // +Y side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600211 -1.0f, 1.0f, 1.0f,
212 1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800213 -1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600214 1.0f, 1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600215 1.0f, 1.0f,-1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600216
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800217 1.0f, 1.0f,-1.0f, // +X side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600218 1.0f, 1.0f, 1.0f,
219 1.0f,-1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800220 1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600221 1.0f,-1.0f,-1.0f,
222 1.0f, 1.0f,-1.0f,
223
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800224 -1.0f, 1.0f, 1.0f, // +Z side
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600225 -1.0f,-1.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600226 1.0f, 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800227 -1.0f,-1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600228 1.0f,-1.0f, 1.0f,
229 1.0f, 1.0f, 1.0f,
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600230};
231
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600232static const float g_uv_buffer_data[] = {
Rene Lindsay76867e82016-07-29 10:49:11 -0700233 0.0f, 1.0f, // -X side
234 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800235 1.0f, 0.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800236 1.0f, 0.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600237 0.0f, 0.0f,
238 0.0f, 1.0f,
239
Rene Lindsay76867e82016-07-29 10:49:11 -0700240 1.0f, 1.0f, // -Z side
241 0.0f, 0.0f,
242 0.0f, 1.0f,
243 1.0f, 1.0f,
244 1.0f, 0.0f,
245 0.0f, 0.0f,
246
247 1.0f, 0.0f, // -Y side
248 1.0f, 1.0f,
249 0.0f, 1.0f,
250 1.0f, 0.0f,
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -0600251 0.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800252 0.0f, 0.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600253
Rene Lindsay76867e82016-07-29 10:49:11 -0700254 1.0f, 0.0f, // +Y side
255 0.0f, 0.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800256 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600257 1.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700258 0.0f, 1.0f,
Mike Stroyan16b3d982015-03-19 14:29:04 -0600259 1.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600260
Rene Lindsay76867e82016-07-29 10:49:11 -0700261 1.0f, 0.0f, // +X side
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800262 0.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700263 0.0f, 1.0f,
264 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600265 1.0f, 1.0f,
Chia-I Wuae3b55d2015-04-22 14:56:17 +0800266 1.0f, 0.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700267
268 0.0f, 0.0f, // +Z side
269 0.0f, 1.0f,
270 1.0f, 0.0f,
271 0.0f, 1.0f,
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -0600272 1.0f, 1.0f,
Rene Lindsay76867e82016-07-29 10:49:11 -0700273 1.0f, 0.0f,
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600274};
Karl Schultze4dc75c2016-02-02 15:37:51 -0700275// clang-format on
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600276
Karl Schultze4dc75c2016-02-02 15:37:51 -0700277void dumpMatrix(const char *note, mat4x4 MVP) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600278 int i;
279
280 printf("%s: \n", note);
Karl Schultze4dc75c2016-02-02 15:37:51 -0700281 for (i = 0; i < 4; i++) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600282 printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]);
283 }
284 printf("\n");
285 fflush(stdout);
286}
287
Karl Schultze4dc75c2016-02-02 15:37:51 -0700288void dumpVec4(const char *note, vec4 vector) {
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600289 printf("%s: \n", note);
Karl Schultze4dc75c2016-02-02 15:37:51 -0700290 printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600291 printf("\n");
292 fflush(stdout);
293}
294
Mark Lobodzinski4c62d002016-05-19 17:22:25 -0600295typedef struct {
Ian Elliottaaae5352015-07-06 14:27:58 -0600296 VkImage image;
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800297 VkCommandBuffer cmd;
Tony Barbour22e06272016-09-07 16:07:56 -0600298 VkCommandBuffer graphics_to_present_cmd;
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -0600299 VkImageView view;
Tony Barboura72d9492017-01-11 13:35:09 -0700300 VkBuffer uniform_buffer;
301 VkDeviceMemory uniform_memory;
Tony-LunarG37af49f2019-12-19 12:04:19 -0700302 void *uniform_memory_ptr;
Tony Barboura72d9492017-01-11 13:35:09 -0700303 VkFramebuffer framebuffer;
304 VkDescriptorSet descriptor_set;
Tony Barboura72d9492017-01-11 13:35:09 -0700305} SwapchainImageResources;
Ian Elliottaaae5352015-07-06 14:27:58 -0600306
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600307struct demo {
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500308#if defined(VK_USE_PLATFORM_WIN32_KHR)
Ian Elliott639ca472015-04-16 15:23:05 -0600309#define APP_NAME_STR_LEN 80
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700310 HINSTANCE connection; // hInstance - Windows Instance
311 char name[APP_NAME_STR_LEN]; // Name to put on the window/icon
312 HWND window; // hWnd - window handle
313 POINT minsize; // minimum window size
Tony Barbour153cb062016-12-07 13:43:36 -0700314#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700315 Display *display;
Tony Barbour2593b182016-04-19 10:57:58 -0600316 Window xlib_window;
317 Atom xlib_wm_delete_window;
Tony Barbour153cb062016-12-07 13:43:36 -0700318#elif defined(VK_USE_PLATFORM_XCB_KHR)
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700319 Display *display;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600320 xcb_connection_t *connection;
321 xcb_screen_t *screen;
Tony Barbour2593b182016-04-19 10:57:58 -0600322 xcb_window_t xcb_window;
Chia-I Wucbb564e2015-04-16 22:02:10 +0800323 xcb_intern_atom_reply_t *atom_wm_delete_window;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +0900324#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
325 struct wl_display *display;
326 struct wl_registry *registry;
327 struct wl_compositor *compositor;
328 struct wl_surface *window;
Manuel Stoecklac939332019-06-26 20:55:53 -0400329 struct xdg_wm_base *xdg_wm_base;
330 struct zxdg_decoration_manager_v1 *xdg_decoration_mgr;
331 struct zxdg_toplevel_decoration_v1 *toplevel_decoration;
332 struct xdg_surface *xdg_surface;
333 int xdg_surface_has_been_configured;
334 struct xdg_toplevel *xdg_toplevel;
Joey Bzdek15eb0702017-06-07 09:40:36 -0600335 struct wl_seat *seat;
336 struct wl_pointer *pointer;
337 struct wl_keyboard *keyboard;
Nicolas Caramellic8be8c82020-07-13 17:22:09 +0200338#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
339 IDirectFB *dfb;
340 IDirectFBSurface *window;
341 IDirectFBEventBuffer *event_buffer;
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500342#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Mike Schuchardt837d5162018-03-08 12:57:02 -0700343 struct ANativeWindow *window;
Bill Hollings0a0625a2019-07-15 17:39:18 -0400344#elif defined(VK_USE_PLATFORM_METAL_EXT)
345 void *caMetalLayer;
Michael Lentinec6cde4b2016-04-18 13:20:45 -0500346#endif
Ian Elliottb08e0d92015-11-20 11:55:46 -0700347 VkSurfaceKHR surface;
Cody Northrop1fedb212015-05-28 11:27:16 -0600348 bool prepared;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -0700349 bool use_staging_buffer;
Tony Barbour22e06272016-09-07 16:07:56 -0600350 bool separate_present_queue;
Jeremy Kniager602e4182018-01-19 10:52:34 -0700351 bool is_minimized;
Witold Baryluka3b988f2021-01-07 19:03:02 +0000352 int32_t gpu_number;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600353
Ian Elliott53622a72017-03-28 11:06:33 -0600354 bool VK_KHR_incremental_present_enabled;
355
Ian Elliottd940ca22017-03-22 08:31:27 -0600356 bool VK_GOOGLE_display_timing_enabled;
357 bool syncd_with_actual_presents;
358 uint64_t refresh_duration;
359 uint64_t refresh_duration_multiplier;
360 uint64_t target_IPD; // image present duration (inverse of frame rate)
361 uint64_t prev_desired_present_time;
362 uint32_t next_present_id;
363 uint32_t last_early_id; // 0 if no early images
364 uint32_t last_late_id; // 0 if no late images
365
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600366 VkInstance inst;
Tony Barbour72304ef2015-04-16 15:59:00 -0600367 VkPhysicalDevice gpu;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600368 VkDevice device;
Tony Barboura2a67812016-07-18 13:21:06 -0600369 VkQueue graphics_queue;
370 VkQueue present_queue;
371 uint32_t graphics_queue_family_index;
372 uint32_t present_queue_family_index;
Tony Barbour66a56c32016-09-21 13:10:56 -0600373 VkSemaphore image_acquired_semaphores[FRAME_LAG];
374 VkSemaphore draw_complete_semaphores[FRAME_LAG];
375 VkSemaphore image_ownership_semaphores[FRAME_LAG];
Tony Barbourecf1b2b2015-06-24 16:06:58 -0600376 VkPhysicalDeviceProperties gpu_props;
Cody Northrop4d3c11d2015-08-03 17:04:53 -0600377 VkQueueFamilyProperties *queue_props;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -0600378 VkPhysicalDeviceMemoryProperties memory_properties;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600379
Tony Barbourda2bad52016-01-22 14:36:40 -0700380 uint32_t enabled_extension_count;
381 uint32_t enabled_layer_count;
382 char *extension_names[64];
Karl Schultz5b423ea2016-06-20 19:08:43 -0600383 char *enabled_layers[64];
Tony Barbourda2bad52016-01-22 14:36:40 -0700384
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600385 int width, height;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600386 VkFormat format;
Ian Elliotta0781972015-08-21 15:09:33 -0600387 VkColorSpaceKHR color_space;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600388
Mark Lobodzinski2dbc2662017-01-26 12:16:30 -0700389 PFN_vkGetPhysicalDeviceSurfaceSupportKHR fpGetPhysicalDeviceSurfaceSupportKHR;
390 PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR fpGetPhysicalDeviceSurfaceCapabilitiesKHR;
391 PFN_vkGetPhysicalDeviceSurfaceFormatsKHR fpGetPhysicalDeviceSurfaceFormatsKHR;
392 PFN_vkGetPhysicalDeviceSurfacePresentModesKHR fpGetPhysicalDeviceSurfacePresentModesKHR;
Ian Elliotta0781972015-08-21 15:09:33 -0600393 PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR;
394 PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR;
395 PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR;
396 PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR;
397 PFN_vkQueuePresentKHR fpQueuePresentKHR;
Ian Elliottd940ca22017-03-22 08:31:27 -0600398 PFN_vkGetRefreshCycleDurationGOOGLE fpGetRefreshCycleDurationGOOGLE;
399 PFN_vkGetPastPresentationTimingGOOGLE fpGetPastPresentationTimingGOOGLE;
Ian Elliotta0781972015-08-21 15:09:33 -0600400 uint32_t swapchainImageCount;
Ian Elliottcf074d32015-10-16 18:02:43 -0600401 VkSwapchainKHR swapchain;
Tony Barboura72d9492017-01-11 13:35:09 -0700402 SwapchainImageResources *swapchain_image_resources;
Tony Barbour291d57b2016-10-21 14:47:07 -0600403 VkPresentModeKHR presentMode;
Tony Barbour66a56c32016-09-21 13:10:56 -0600404 VkFence fences[FRAME_LAG];
Tony Barbour66a56c32016-09-21 13:10:56 -0600405 int frame_index;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600406
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800407 VkCommandPool cmd_pool;
Tony Barbour22e06272016-09-07 16:07:56 -0600408 VkCommandPool present_cmd_pool;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600409
410 struct {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600411 VkFormat format;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600412
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600413 VkImage image;
Chia-I Wua8fe78a2015-10-27 18:04:07 +0800414 VkMemoryAllocateInfo mem_alloc;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -0500415 VkDeviceMemory mem;
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -0600416 VkImageView view;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600417 } depth;
418
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600419 struct texture_object textures[DEMO_TEXTURE_COUNT];
Tony Barbour16156cb2016-10-19 14:15:49 -0600420 struct texture_object staging_texture;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600421
Mark Lobodzinski85dbd822017-01-26 13:34:13 -0700422 VkCommandBuffer cmd; // Buffer for initialization commands
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -0500423 VkPipelineLayout pipeline_layout;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600424 VkDescriptorSetLayout desc_layout;
Jon Ashburnc4ab7af2015-07-09 15:02:25 -0600425 VkPipelineCache pipelineCache;
Chia-I Wuf973e322015-07-08 13:34:24 +0800426 VkRenderPass render_pass;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600427 VkPipeline pipeline;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600428
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600429 mat4x4 projection_matrix;
430 mat4x4 view_matrix;
431 mat4x4 model_matrix;
432
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600433 float spin_angle;
434 float spin_increment;
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -0600435 bool pause;
436
Tony Barbourb6dba5c2015-07-21 09:04:41 -0600437 VkShaderModule vert_shader_module;
438 VkShaderModule frag_shader_module;
439
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600440 VkDescriptorPool desc_pool;
Chia-I Wuf973e322015-07-08 13:34:24 +0800441
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600442 bool quit;
David Pinedo2bb7c932015-06-18 17:03:14 -0600443 int32_t curFrame;
444 int32_t frameCount;
Tony Barbour3dddd5d2015-04-29 16:19:20 -0600445 bool validate;
Tobin Ehlis4eb29d62017-03-14 11:29:01 -0600446 bool validate_checks_disabled;
Courtney Goeltzenleuchter03f4b772015-07-22 11:03:51 -0600447 bool use_break;
lenny-lunargfbe22392016-06-06 11:07:53 -0600448 bool suppress_popups;
Mark Young66510e52017-11-10 10:05:14 -0700449
450 PFN_vkCreateDebugUtilsMessengerEXT CreateDebugUtilsMessengerEXT;
451 PFN_vkDestroyDebugUtilsMessengerEXT DestroyDebugUtilsMessengerEXT;
452 PFN_vkSubmitDebugUtilsMessageEXT SubmitDebugUtilsMessageEXT;
453 PFN_vkCmdBeginDebugUtilsLabelEXT CmdBeginDebugUtilsLabelEXT;
454 PFN_vkCmdEndDebugUtilsLabelEXT CmdEndDebugUtilsLabelEXT;
455 PFN_vkCmdInsertDebugUtilsLabelEXT CmdInsertDebugUtilsLabelEXT;
456 PFN_vkSetDebugUtilsObjectNameEXT SetDebugUtilsObjectNameEXT;
457 VkDebugUtilsMessengerEXT dbg_messenger;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -0600458
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -0600459 uint32_t current_buffer;
Tony Barbourab2a0362016-09-06 11:40:12 -0600460 uint32_t queue_family_count;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600461};
462
Mark Young66510e52017-11-10 10:05:14 -0700463VKAPI_ATTR VkBool32 VKAPI_CALL debug_messenger_callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
464 VkDebugUtilsMessageTypeFlagsEXT messageType,
465 const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData,
466 void *pUserData) {
467 char prefix[64] = "";
468 char *message = (char *)malloc(strlen(pCallbackData->pMessage) + 5000);
lenny-lunargfbe22392016-06-06 11:07:53 -0600469 assert(message);
Mark Young66510e52017-11-10 10:05:14 -0700470 struct demo *demo = (struct demo *)pUserData;
lenny-lunargfbe22392016-06-06 11:07:53 -0600471
Mark Young66510e52017-11-10 10:05:14 -0700472 if (demo->use_break) {
473#ifndef WIN32
474 raise(SIGTRAP);
475#else
476 DebugBreak();
477#endif
478 }
479
480 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
481 strcat(prefix, "VERBOSE : ");
482 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
483 strcat(prefix, "INFO : ");
484 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
485 strcat(prefix, "WARNING : ");
486 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
487 strcat(prefix, "ERROR : ");
488 }
489
490 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) {
491 strcat(prefix, "GENERAL");
lenny-lunargfbe22392016-06-06 11:07:53 -0600492 } else {
Mark Young66510e52017-11-10 10:05:14 -0700493 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
494 strcat(prefix, "VALIDATION");
495 validation_error = 1;
496 }
497 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) {
498 if (messageType & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) {
499 strcat(prefix, "|");
500 }
501 strcat(prefix, "PERFORMANCE");
502 }
503 }
504
505 sprintf(message, "%s - Message Id Number: %d | Message Id Name: %s\n\t%s\n", prefix, pCallbackData->messageIdNumber,
506 pCallbackData->pMessageIdName, pCallbackData->pMessage);
507 if (pCallbackData->objectCount > 0) {
508 char tmp_message[500];
509 sprintf(tmp_message, "\n\tObjects - %d\n", pCallbackData->objectCount);
510 strcat(message, tmp_message);
511 for (uint32_t object = 0; object < pCallbackData->objectCount; ++object) {
512 if (NULL != pCallbackData->pObjects[object].pObjectName && strlen(pCallbackData->pObjects[object].pObjectName) > 0) {
513 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p, Name \"%s\"\n", object,
Mark Young44212682018-02-21 15:29:41 -0700514 string_VkObjectType(pCallbackData->pObjects[object].objectType),
Mark Young66510e52017-11-10 10:05:14 -0700515 (void *)(pCallbackData->pObjects[object].objectHandle), pCallbackData->pObjects[object].pObjectName);
516 } else {
517 sprintf(tmp_message, "\t\tObject[%d] - %s, Handle %p\n", object,
Mark Young44212682018-02-21 15:29:41 -0700518 string_VkObjectType(pCallbackData->pObjects[object].objectType),
Mark Young66510e52017-11-10 10:05:14 -0700519 (void *)(pCallbackData->pObjects[object].objectHandle));
520 }
521 strcat(message, tmp_message);
522 }
523 }
524 if (pCallbackData->cmdBufLabelCount > 0) {
525 char tmp_message[500];
526 sprintf(tmp_message, "\n\tCommand Buffer Labels - %d\n", pCallbackData->cmdBufLabelCount);
527 strcat(message, tmp_message);
528 for (uint32_t cmd_buf_label = 0; cmd_buf_label < pCallbackData->cmdBufLabelCount; ++cmd_buf_label) {
529 sprintf(tmp_message, "\t\tLabel[%d] - %s { %f, %f, %f, %f}\n", cmd_buf_label,
530 pCallbackData->pCmdBufLabels[cmd_buf_label].pLabelName, pCallbackData->pCmdBufLabels[cmd_buf_label].color[0],
531 pCallbackData->pCmdBufLabels[cmd_buf_label].color[1], pCallbackData->pCmdBufLabels[cmd_buf_label].color[2],
532 pCallbackData->pCmdBufLabels[cmd_buf_label].color[3]);
533 strcat(message, tmp_message);
534 }
lenny-lunargfbe22392016-06-06 11:07:53 -0600535 }
536
537#ifdef _WIN32
Cody Northropaf28a532016-09-27 10:50:57 -0600538
Tony Barbour602ca4f2016-09-12 14:02:43 -0600539 in_callback = true;
Jeremy Kniager979b5312019-11-22 14:55:57 -0700540 if (!demo->suppress_popups) MessageBox(NULL, message, "Alert", MB_OK);
Tony Barbour602ca4f2016-09-12 14:02:43 -0600541 in_callback = false;
Cody Northropaf28a532016-09-27 10:50:57 -0600542
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600543#elif defined(ANDROID)
Cody Northropaf28a532016-09-27 10:50:57 -0600544
Mike Schuchardt837d5162018-03-08 12:57:02 -0700545 if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700546 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700547 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700548 __android_log_print(ANDROID_LOG_WARN, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700549 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) {
Cody Northropaf28a532016-09-27 10:50:57 -0600550 __android_log_print(ANDROID_LOG_ERROR, APP_SHORT_NAME, "%s", message);
Mike Schuchardt837d5162018-03-08 12:57:02 -0700551 } else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) {
552 __android_log_print(ANDROID_LOG_VERBOSE, APP_SHORT_NAME, "%s", message);
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600553 } else {
Jeremy Kniager979b5312019-11-22 14:55:57 -0700554 __android_log_print(ANDROID_LOG_INFO, APP_SHORT_NAME, "%s", message);
Cody Northropc5e5a8c2016-09-26 21:05:00 -0600555 }
Cody Northropaf28a532016-09-27 10:50:57 -0600556
lenny-lunargfbe22392016-06-06 11:07:53 -0600557#else
Cody Northropaf28a532016-09-27 10:50:57 -0600558
lenny-lunargfbe22392016-06-06 11:07:53 -0600559 printf("%s\n", message);
560 fflush(stdout);
Cody Northropaf28a532016-09-27 10:50:57 -0600561
lenny-lunargfbe22392016-06-06 11:07:53 -0600562#endif
Cody Northropaf28a532016-09-27 10:50:57 -0600563
lenny-lunargfbe22392016-06-06 11:07:53 -0600564 free(message);
565
Mark Young66510e52017-11-10 10:05:14 -0700566 // Don't bail out, but keep going.
lenny-lunargfbe22392016-06-06 11:07:53 -0600567 return false;
568}
569
Ian Elliottd940ca22017-03-22 08:31:27 -0600570bool ActualTimeLate(uint64_t desired, uint64_t actual, uint64_t rdur) {
571 // The desired time was the earliest time that the present should have
572 // occured. In almost every case, the actual time should be later than the
573 // desired time. We should only consider the actual time "late" if it is
574 // after "desired + rdur".
575 if (actual <= desired) {
576 // The actual time was before or equal to the desired time. This will
577 // probably never happen, but in case it does, return false since the
578 // present was obviously NOT late.
579 return false;
580 }
Liam Middlebrook881fe392018-05-03 15:52:32 -0700581 uint64_t deadline = desired + rdur;
Ian Elliottd940ca22017-03-22 08:31:27 -0600582 if (actual > deadline) {
583 return true;
584 } else {
585 return false;
586 }
587}
Dave Houlton5fa47912018-02-16 11:02:26 -0700588bool CanPresentEarlier(uint64_t earliest, uint64_t actual, uint64_t margin, uint64_t rdur) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600589 if (earliest < actual) {
590 // Consider whether this present could have occured earlier. Make sure
591 // that earliest time was at least 2msec earlier than actual time, and
592 // that the margin was at least 2msec:
593 uint64_t diff = actual - earliest;
594 if ((diff >= (2 * MILLION)) && (margin >= (2 * MILLION))) {
595 // This present could have occured earlier because both: 1) the
596 // earliest time was at least 2 msec before actual time, and 2) the
597 // margin was at least 2msec.
598 return true;
599 }
600 }
601 return false;
602}
603
Tony-LunarG6cebf142019-09-11 14:32:23 -0600604// Forward declarations:
Ian Elliottcf074d32015-10-16 18:02:43 -0600605static void demo_resize(struct demo *demo);
Tony-LunarG6cebf142019-09-11 14:32:23 -0600606static void demo_create_surface(struct demo *demo);
Ian Elliottcf074d32015-10-16 18:02:43 -0600607
Dave Houlton5fa47912018-02-16 11:02:26 -0700608static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, VkFlags requirements_mask, uint32_t *typeIndex) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700609 // Search memtypes to find first index with those properties
Alexandre BACQUART89eb8df2016-04-28 14:25:09 -0600610 for (uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700611 if ((typeBits & 1) == 1) {
612 // Type is available, does it match user properties?
Dave Houlton5fa47912018-02-16 11:02:26 -0700613 if ((demo->memory_properties.memoryTypes[i].propertyFlags & requirements_mask) == requirements_mask) {
Karl Schultze4dc75c2016-02-02 15:37:51 -0700614 *typeIndex = i;
615 return true;
616 }
617 }
618 typeBits >>= 1;
619 }
620 // No memory types matched, return failure
621 return false;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -0600622}
623
Karl Schultze4dc75c2016-02-02 15:37:51 -0700624static void demo_flush_init_cmd(struct demo *demo) {
Tony Barbourfdc2d352015-04-22 09:02:32 -0600625 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600626
Tony Barbource7524e2016-07-28 12:01:45 -0600627 // This function could get called twice if the texture uses a staging buffer
628 // In that case the second call should be ignored
Dave Houlton5fa47912018-02-16 11:02:26 -0700629 if (demo->cmd == VK_NULL_HANDLE) return;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600630
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600631 err = vkEndCommandBuffer(demo->cmd);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600632 assert(!err);
633
Tony Barbource7524e2016-07-28 12:01:45 -0600634 VkFence fence;
Dave Houlton5fa47912018-02-16 11:02:26 -0700635 VkFenceCreateInfo fence_ci = {.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = 0};
Tony Barboura72d9492017-01-11 13:35:09 -0700636 err = vkCreateFence(demo->device, &fence_ci, NULL, &fence);
637 assert(!err);
638
Karl Schultze4dc75c2016-02-02 15:37:51 -0700639 const VkCommandBuffer cmd_bufs[] = {demo->cmd};
Karl Schultze4dc75c2016-02-02 15:37:51 -0700640 VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
641 .pNext = NULL,
642 .waitSemaphoreCount = 0,
643 .pWaitSemaphores = NULL,
644 .pWaitDstStageMask = NULL,
645 .commandBufferCount = 1,
646 .pCommandBuffers = cmd_bufs,
647 .signalSemaphoreCount = 0,
648 .pSignalSemaphores = NULL};
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600649
Tony Barbource7524e2016-07-28 12:01:45 -0600650 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, fence);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600651 assert(!err);
652
Tony Barbource7524e2016-07-28 12:01:45 -0600653 err = vkWaitForFences(demo->device, 1, &fence, VK_TRUE, UINT64_MAX);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600654 assert(!err);
655
Courtney Goeltzenleuchter014ded82015-10-23 14:21:05 -0600656 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs);
Tony Barbource7524e2016-07-28 12:01:45 -0600657 vkDestroyFence(demo->device, fence, NULL);
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600658 demo->cmd = VK_NULL_HANDLE;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600659}
660
Dave Houlton5fa47912018-02-16 11:02:26 -0700661static void demo_set_image_layout(struct demo *demo, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout old_image_layout,
662 VkImageLayout new_image_layout, VkAccessFlagBits srcAccessMask, VkPipelineStageFlags src_stages,
Tony Barbour5ff13182016-10-19 13:58:29 -0600663 VkPipelineStageFlags dest_stages) {
Tony Barbour6db4fcb2016-10-19 13:41:16 -0600664 assert(demo->cmd);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600665
Dave Houlton5fa47912018-02-16 11:02:26 -0700666 VkImageMemoryBarrier image_memory_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
667 .pNext = NULL,
668 .srcAccessMask = srcAccessMask,
669 .dstAccessMask = 0,
Tony-LunarGa141b962018-05-30 11:33:19 -0600670 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
671 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
Dave Houlton5fa47912018-02-16 11:02:26 -0700672 .oldLayout = old_image_layout,
673 .newLayout = new_image_layout,
674 .image = image,
675 .subresourceRange = {aspectMask, 0, 1, 0, 1}};
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600676
Tony Barboureb5077b2016-10-19 15:23:36 -0600677 switch (new_image_layout) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700678 case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
679 /* Make sure anything that was copying from this image has completed */
680 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
681 break;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600682
Dave Houlton5fa47912018-02-16 11:02:26 -0700683 case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
684 image_memory_barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
685 break;
Mark Lobodzinski9e0be702015-11-04 13:49:48 -0700686
Dave Houlton5fa47912018-02-16 11:02:26 -0700687 case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
688 image_memory_barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
689 break;
Mark Lobodzinski9e0be702015-11-04 13:49:48 -0700690
Dave Houlton5fa47912018-02-16 11:02:26 -0700691 case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
692 image_memory_barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
693 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600694
Dave Houlton5fa47912018-02-16 11:02:26 -0700695 case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
696 image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
697 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600698
Dave Houlton5fa47912018-02-16 11:02:26 -0700699 case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
700 image_memory_barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
701 break;
Tony Barboureb5077b2016-10-19 15:23:36 -0600702
Dave Houlton5fa47912018-02-16 11:02:26 -0700703 default:
704 image_memory_barrier.dstAccessMask = 0;
705 break;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600706 }
707
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -0600708 VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier;
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600709
Dave Houlton5fa47912018-02-16 11:02:26 -0700710 vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, NULL, 1, pmemory_barrier);
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -0600711}
712
Karl Schultze4dc75c2016-02-02 15:37:51 -0700713static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) {
Lenny Komowe830b592018-02-23 16:18:36 -0700714 VkDebugUtilsLabelEXT label;
715 memset(&label, 0, sizeof(label));
Jon Ashburn0bec67e2016-01-11 13:12:43 -0700716 const VkCommandBufferBeginInfo cmd_buf_info = {
717 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
718 .pNext = NULL,
Tony Barbource7524e2016-07-28 12:01:45 -0600719 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
Rene Lindsayd787e3a2016-07-07 16:00:14 -0700720 .pInheritanceInfo = NULL,
Jon Ashburn0bec67e2016-01-11 13:12:43 -0700721 };
Chia-I Wua74c5b22015-07-07 11:50:03 +0800722 const VkClearValue clear_values[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -0700723 [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}},
724 [1] = {.depthStencil = {1.0f, 0}},
Chia-I Wua74c5b22015-07-07 11:50:03 +0800725 };
726 const VkRenderPassBeginInfo rp_begin = {
727 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
728 .pNext = NULL,
Chia-I Wuf973e322015-07-08 13:34:24 +0800729 .renderPass = demo->render_pass,
Tony Barboura72d9492017-01-11 13:35:09 -0700730 .framebuffer = demo->swapchain_image_resources[demo->current_buffer].framebuffer,
Chia-I Wua74c5b22015-07-07 11:50:03 +0800731 .renderArea.offset.x = 0,
732 .renderArea.offset.y = 0,
733 .renderArea.extent.width = demo->width,
734 .renderArea.extent.height = demo->height,
Cody Northrop372bbae2015-08-04 11:51:03 -0600735 .clearValueCount = 2,
736 .pClearValues = clear_values,
Jon Ashburn08f6eb92015-01-02 18:24:05 -0700737 };
Chia-I Wuf973e322015-07-08 13:34:24 +0800738 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600739
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600740 err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info);
Mark Young66510e52017-11-10 10:05:14 -0700741
742 if (demo->validate) {
743 // Set a name for the command buffer
744 VkDebugUtilsObjectNameInfoEXT cmd_buf_name = {
745 .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT,
746 .pNext = NULL,
747 .objectType = VK_OBJECT_TYPE_COMMAND_BUFFER,
748 .objectHandle = (uint64_t)cmd_buf,
749 .pObjectName = "CubeDrawCommandBuf",
750 };
751 demo->SetDebugUtilsObjectNameEXT(demo->device, &cmd_buf_name);
752
753 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
754 label.pNext = NULL;
755 label.pLabelName = "DrawBegin";
756 label.color[0] = 0.4f;
757 label.color[1] = 0.3f;
758 label.color[2] = 0.2f;
759 label.color[3] = 0.1f;
760 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
761 }
762
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600763 assert(!err);
Chia-I Wuf051d262015-10-27 19:25:11 +0800764 vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
Mark Young66510e52017-11-10 10:05:14 -0700765
766 if (demo->validate) {
767 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
768 label.pNext = NULL;
769 label.pLabelName = "InsideRenderPass";
770 label.color[0] = 8.4f;
771 label.color[1] = 7.3f;
772 label.color[2] = 6.2f;
773 label.color[3] = 7.1f;
774 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
775 }
776
Karl Schultze4dc75c2016-02-02 15:37:51 -0700777 vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline);
Dave Houlton5fa47912018-02-16 11:02:26 -0700778 vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline_layout, 0, 1,
779 &demo->swapchain_image_resources[demo->current_buffer].descriptor_set, 0, NULL);
Courtney Goeltzenleuchter4cbf78b2015-09-17 15:06:17 -0600780 VkViewport viewport;
781 memset(&viewport, 0, sizeof(viewport));
Jeremy Kniager979b5312019-11-22 14:55:57 -0700782 float viewport_dimension;
783 if (demo->width < demo->height) {
784 viewport_dimension = (float)demo->width;
785 viewport.y = (demo->height - demo->width) / 2.0f;
786 } else {
787 viewport_dimension = (float)demo->height;
788 viewport.x = (demo->width - demo->height) / 2.0f;
789 }
790 viewport.height = viewport_dimension;
791 viewport.width = viewport_dimension;
Karl Schultze4dc75c2016-02-02 15:37:51 -0700792 viewport.minDepth = (float)0.0f;
793 viewport.maxDepth = (float)1.0f;
Jon Ashburn19255f82015-12-30 14:06:55 -0700794 vkCmdSetViewport(cmd_buf, 0, 1, &viewport);
Courtney Goeltzenleuchter4cbf78b2015-09-17 15:06:17 -0600795
796 VkRect2D scissor;
797 memset(&scissor, 0, sizeof(scissor));
798 scissor.extent.width = demo->width;
799 scissor.extent.height = demo->height;
800 scissor.offset.x = 0;
801 scissor.offset.y = 0;
Jon Ashburn19255f82015-12-30 14:06:55 -0700802 vkCmdSetScissor(cmd_buf, 0, 1, &scissor);
Mark Young66510e52017-11-10 10:05:14 -0700803
804 if (demo->validate) {
805 label.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT;
806 label.pNext = NULL;
807 label.pLabelName = "ActualDraw";
Mike Schuchardt4cf3aa42018-02-23 12:44:05 -0700808 label.color[0] = -0.4f;
809 label.color[1] = -0.3f;
810 label.color[2] = -0.2f;
811 label.color[3] = -0.1f;
Mark Young66510e52017-11-10 10:05:14 -0700812 demo->CmdBeginDebugUtilsLabelEXT(cmd_buf, &label);
813 }
814
Courtney Goeltzenleuchter332a3672015-09-23 12:31:50 -0600815 vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0);
Mark Young66510e52017-11-10 10:05:14 -0700816 if (demo->validate) {
817 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
818 }
819
Tony Barbour98390392016-07-28 10:50:13 -0600820 // Note that ending the renderpass changes the image's layout from
Tony Barbour22e06272016-09-07 16:07:56 -0600821 // COLOR_ATTACHMENT_OPTIMAL to PRESENT_SRC_KHR
Chia-I Wu57b23b42015-06-26 15:34:39 +0800822 vkCmdEndRenderPass(cmd_buf);
Mark Young66510e52017-11-10 10:05:14 -0700823 if (demo->validate) {
824 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
825 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600826
Tony Barbour22e06272016-09-07 16:07:56 -0600827 if (demo->separate_present_queue) {
828 // We have to transfer ownership from the graphics queue family to the
829 // present queue family to be able to present. Note that we don't have
830 // to transfer from present queue family back to graphics queue family at
831 // the start of the next frame because we don't care about the image's
832 // contents at that point.
Dave Houlton5fa47912018-02-16 11:02:26 -0700833 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
834 .pNext = NULL,
835 .srcAccessMask = 0,
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600836 .dstAccessMask = 0,
Dave Houlton5fa47912018-02-16 11:02:26 -0700837 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
838 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
839 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
840 .dstQueueFamilyIndex = demo->present_queue_family_index,
841 .image = demo->swapchain_image_resources[demo->current_buffer].image,
842 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
Tony Barbour22e06272016-09-07 16:07:56 -0600843
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600844 vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0,
845 NULL, 1, &image_ownership_barrier);
Tony Barbour22e06272016-09-07 16:07:56 -0600846 }
Mark Young66510e52017-11-10 10:05:14 -0700847 if (demo->validate) {
848 demo->CmdEndDebugUtilsLabelEXT(cmd_buf);
849 }
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -0600850 err = vkEndCommandBuffer(cmd_buf);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600851 assert(!err);
852}
853
Tony Barbour22e06272016-09-07 16:07:56 -0600854void demo_build_image_ownership_cmd(struct demo *demo, int i) {
855 VkResult U_ASSERT_ONLY err;
856
857 const VkCommandBufferBeginInfo cmd_buf_info = {
858 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
859 .pNext = NULL,
860 .flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT,
861 .pInheritanceInfo = NULL,
862 };
Dave Houlton5fa47912018-02-16 11:02:26 -0700863 err = vkBeginCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd, &cmd_buf_info);
Tony Barbour22e06272016-09-07 16:07:56 -0600864 assert(!err);
865
Dave Houlton5fa47912018-02-16 11:02:26 -0700866 VkImageMemoryBarrier image_ownership_barrier = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
867 .pNext = NULL,
868 .srcAccessMask = 0,
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600869 .dstAccessMask = 0,
Dave Houlton5fa47912018-02-16 11:02:26 -0700870 .oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
871 .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
872 .srcQueueFamilyIndex = demo->graphics_queue_family_index,
873 .dstQueueFamilyIndex = demo->present_queue_family_index,
874 .image = demo->swapchain_image_resources[i].image,
875 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
Tony Barbour22e06272016-09-07 16:07:56 -0600876
Tony-LunarG4ba65cd2018-05-30 14:53:14 -0600877 vkCmdPipelineBarrier(demo->swapchain_image_resources[i].graphics_to_present_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
878 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &image_ownership_barrier);
Tony Barboura72d9492017-01-11 13:35:09 -0700879 err = vkEndCommandBuffer(demo->swapchain_image_resources[i].graphics_to_present_cmd);
Tony Barbour22e06272016-09-07 16:07:56 -0600880 assert(!err);
881}
882
Karl Schultze4dc75c2016-02-02 15:37:51 -0700883void demo_update_data_buffer(struct demo *demo) {
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600884 mat4x4 MVP, Model, VP;
885 int matrixSize = sizeof(MVP);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600886
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600887 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600888
Karl Schultz6ddf1e02017-01-04 10:31:20 -0700889 // Rotate around the Y axis
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600890 mat4x4_dup(Model, demo->model_matrix);
Arman Uguray3ae08892021-05-25 00:07:24 -0700891 mat4x4_rotate_Y(demo->model_matrix, Model, (float)degreesToRadians(demo->spin_angle));
892 mat4x4_orthonormalize(demo->model_matrix, demo->model_matrix);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -0600893 mat4x4_mul(MVP, VP, demo->model_matrix);
Courtney Goeltzenleuchterfc3b9532014-10-28 10:32:57 -0600894
Tony-LunarG37af49f2019-12-19 12:04:19 -0700895 memcpy(demo->swapchain_image_resources[demo->current_buffer].uniform_memory_ptr, (const void *)&MVP[0][0], matrixSize);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -0600896}
897
Ian Elliottd940ca22017-03-22 08:31:27 -0600898void DemoUpdateTargetIPD(struct demo *demo) {
899 // Look at what happened to previous presents, and make appropriate
900 // adjustments in timing:
901 VkResult U_ASSERT_ONLY err;
Dave Houlton5fa47912018-02-16 11:02:26 -0700902 VkPastPresentationTimingGOOGLE *past = NULL;
Ian Elliottd940ca22017-03-22 08:31:27 -0600903 uint32_t count = 0;
Ian Elliottd940ca22017-03-22 08:31:27 -0600904
Dave Houlton5fa47912018-02-16 11:02:26 -0700905 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, NULL);
Ian Elliottd940ca22017-03-22 08:31:27 -0600906 assert(!err);
Ian Elliottd940ca22017-03-22 08:31:27 -0600907 if (count) {
Dave Houlton5fa47912018-02-16 11:02:26 -0700908 past = (VkPastPresentationTimingGOOGLE *)malloc(sizeof(VkPastPresentationTimingGOOGLE) * count);
Ian Elliottd940ca22017-03-22 08:31:27 -0600909 assert(past);
Dave Houlton5fa47912018-02-16 11:02:26 -0700910 err = demo->fpGetPastPresentationTimingGOOGLE(demo->device, demo->swapchain, &count, past);
Ian Elliottd940ca22017-03-22 08:31:27 -0600911 assert(!err);
912
913 bool early = false;
914 bool late = false;
915 bool calibrate_next = false;
Dave Houlton5fa47912018-02-16 11:02:26 -0700916 for (uint32_t i = 0; i < count; i++) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600917 if (!demo->syncd_with_actual_presents) {
918 // This is the first time that we've received an
919 // actualPresentTime for this swapchain. In order to not
920 // perceive these early frames as "late", we need to sync-up
921 // our future desiredPresentTime's with the
922 // actualPresentTime(s) that we're receiving now.
923 calibrate_next = true;
Ian Elliottd940ca22017-03-22 08:31:27 -0600924
Ian Elliottd940ca22017-03-22 08:31:27 -0600925 // So that we don't suspect any pending presents as late,
926 // record them all as suspected-late presents:
927 demo->last_late_id = demo->next_present_id - 1;
928 demo->last_early_id = 0;
Ian Elliottd940ca22017-03-22 08:31:27 -0600929 demo->syncd_with_actual_presents = true;
930 break;
Dave Houlton5fa47912018-02-16 11:02:26 -0700931 } else if (CanPresentEarlier(past[i].earliestPresentTime, past[i].actualPresentTime, past[i].presentMargin,
Ian Elliottd940ca22017-03-22 08:31:27 -0600932 demo->refresh_duration)) {
933 // This image could have been presented earlier. We don't want
934 // to decrease the target_IPD until we've seen early presents
935 // for at least two seconds.
936 if (demo->last_early_id == past[i].presentID) {
937 // We've now seen two seconds worth of early presents.
938 // Flag it as such, and reset the counter:
939 early = true;
940 demo->last_early_id = 0;
941 } else if (demo->last_early_id == 0) {
942 // This is the first early present we've seen.
943 // Calculate the presentID for two seconds from now.
Dave Houlton5fa47912018-02-16 11:02:26 -0700944 uint64_t lastEarlyTime = past[i].actualPresentTime + (2 * BILLION);
945 uint32_t howManyPresents = (uint32_t)((lastEarlyTime - past[i].actualPresentTime) / demo->target_IPD);
Ian Elliottd940ca22017-03-22 08:31:27 -0600946 demo->last_early_id = past[i].presentID + howManyPresents;
947 } else {
948 // We are in the midst of a set of early images,
949 // and so we won't do anything.
950 }
951 late = false;
952 demo->last_late_id = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -0700953 } else if (ActualTimeLate(past[i].desiredPresentTime, past[i].actualPresentTime, demo->refresh_duration)) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600954 // This image was presented after its desired time. Since
955 // there's a delay between calling vkQueuePresentKHR and when
956 // we get the timing data, several presents may have been late.
957 // Thus, we need to threat all of the outstanding presents as
958 // being likely late, so that we only increase the target_IPD
959 // once for all of those presents.
Dave Houlton5fa47912018-02-16 11:02:26 -0700960 if ((demo->last_late_id == 0) || (demo->last_late_id < past[i].presentID)) {
Ian Elliottd940ca22017-03-22 08:31:27 -0600961 late = true;
962 // Record the last suspected-late present:
963 demo->last_late_id = demo->next_present_id - 1;
964 } else {
965 // We are in the midst of a set of likely-late images,
966 // and so we won't do anything.
967 }
968 early = false;
969 demo->last_early_id = 0;
970 } else {
971 // Since this image was not presented early or late, reset
972 // any sets of early or late presentIDs:
973 early = false;
974 late = false;
975 calibrate_next = true;
976 demo->last_early_id = 0;
977 demo->last_late_id = 0;
978 }
979 }
980
981 if (early) {
982 // Since we've seen at least two-seconds worth of presnts that
983 // could have occured earlier than desired, let's decrease the
984 // target_IPD (i.e. increase the frame rate):
985 //
986 // TODO(ianelliott): Try to calculate a better target_IPD based
987 // on the most recently-seen present (this is overly-simplistic).
988 demo->refresh_duration_multiplier--;
989 if (demo->refresh_duration_multiplier == 0) {
990 // This should never happen, but in case it does, don't
991 // try to go faster.
992 demo->refresh_duration_multiplier = 1;
993 }
Dave Houlton5fa47912018-02-16 11:02:26 -0700994 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
Ian Elliottd940ca22017-03-22 08:31:27 -0600995 }
996 if (late) {
997 // Since we found a new instance of a late present, we want to
998 // increase the target_IPD (i.e. decrease the frame rate):
999 //
1000 // TODO(ianelliott): Try to calculate a better target_IPD based
1001 // on the most recently-seen present (this is overly-simplistic).
1002 demo->refresh_duration_multiplier++;
Dave Houlton5fa47912018-02-16 11:02:26 -07001003 demo->target_IPD = demo->refresh_duration * demo->refresh_duration_multiplier;
Ian Elliottd940ca22017-03-22 08:31:27 -06001004 }
1005
1006 if (calibrate_next) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001007 int64_t multiple = demo->next_present_id - past[count - 1].presentID;
1008 demo->prev_desired_present_time = (past[count - 1].actualPresentTime + (multiple * demo->target_IPD));
Ian Elliottd940ca22017-03-22 08:31:27 -06001009 }
Karl Schultza33771f2018-05-28 16:16:47 -06001010 free(past);
Ian Elliottd940ca22017-03-22 08:31:27 -06001011 }
Ian Elliottd940ca22017-03-22 08:31:27 -06001012}
1013
Karl Schultze4dc75c2016-02-02 15:37:51 -07001014static void demo_draw(struct demo *demo) {
Tony Barbourfdc2d352015-04-22 09:02:32 -06001015 VkResult U_ASSERT_ONLY err;
Tony Barboure35e8aa2016-06-20 10:44:08 -06001016
Damien Leonec336d822017-04-14 16:10:14 -07001017 // Ensure no more than FRAME_LAG renderings are outstanding
szdarkhackd322ff02016-10-08 09:51:22 +03001018 vkWaitForFences(demo->device, 1, &demo->fences[demo->frame_index], VK_TRUE, UINT64_MAX);
1019 vkResetFences(demo->device, 1, &demo->fences[demo->frame_index]);
Tony Barbour66a56c32016-09-21 13:10:56 -06001020
Tony Barbour8b7c9112017-06-29 13:34:41 -06001021 do {
Tony Barbour6914e6d2017-06-02 12:11:29 -06001022 // Get the index of the next available swapchain image:
Dave Houlton5fa47912018-02-16 11:02:26 -07001023 err =
1024 demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX,
1025 demo->image_acquired_semaphores[demo->frame_index], VK_NULL_HANDLE, &demo->current_buffer);
Tony Barbour66a56c32016-09-21 13:10:56 -06001026
Tony Barbour6914e6d2017-06-02 12:11:29 -06001027 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1028 // demo->swapchain is out of date (e.g. the window was resized) and
1029 // must be recreated:
1030 demo_resize(demo);
1031 } else if (err == VK_SUBOPTIMAL_KHR) {
1032 // demo->swapchain is not as optimal as it could be, but the platform's
1033 // presentation engine will still present the image correctly.
1034 break;
Tony-LunarG6cebf142019-09-11 14:32:23 -06001035 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1036 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1037 demo_create_surface(demo);
1038 demo_resize(demo);
Tony Barbour6914e6d2017-06-02 12:11:29 -06001039 } else {
1040 assert(!err);
1041 }
Tony Barbour8b7c9112017-06-29 13:34:41 -06001042 } while (err != VK_SUCCESS);
Tony Barbour6914e6d2017-06-02 12:11:29 -06001043
Tony Barbour3eafe1f2017-06-14 11:59:55 -06001044 demo_update_data_buffer(demo);
1045
Ian Elliottd940ca22017-03-22 08:31:27 -06001046 if (demo->VK_GOOGLE_display_timing_enabled) {
1047 // Look at what happened to previous presents, and make appropriate
1048 // adjustments in timing:
1049 DemoUpdateTargetIPD(demo);
1050
1051 // Note: a real application would position its geometry to that it's in
1052 // the correct locatoin for when the next image is presented. It might
1053 // also wait, so that there's less latency between any input and when
1054 // the next image is rendered/presented. This demo program is so
1055 // simple that it doesn't do either of those.
1056 }
1057
Tony Barbource7524e2016-07-28 12:01:45 -06001058 // Wait for the image acquired semaphore to be signaled to ensure
Courtney Goeltzenleuchter5fa898d2015-10-20 18:04:07 -06001059 // that the image won't be rendered to until the presentation
1060 // engine has fully released ownership to the application, and it is
1061 // okay to render to the image.
Tony Barbour22e06272016-09-07 16:07:56 -06001062 VkPipelineStageFlags pipe_stage_flags;
1063 VkSubmitInfo submit_info;
1064 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1065 submit_info.pNext = NULL;
1066 submit_info.pWaitDstStageMask = &pipe_stage_flags;
1067 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1068 submit_info.waitSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001069 submit_info.pWaitSemaphores = &demo->image_acquired_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001070 submit_info.commandBufferCount = 1;
Tony Barboura72d9492017-01-11 13:35:09 -07001071 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].cmd;
Tony Barbour22e06272016-09-07 16:07:56 -06001072 submit_info.signalSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001073 submit_info.pSignalSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
Dave Houlton5fa47912018-02-16 11:02:26 -07001074 err = vkQueueSubmit(demo->graphics_queue, 1, &submit_info, demo->fences[demo->frame_index]);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001075 assert(!err);
1076
Tony Barbour22e06272016-09-07 16:07:56 -06001077 if (demo->separate_present_queue) {
1078 // If we are using separate queues, change image ownership to the
1079 // present queue before presenting, waiting for the draw complete
1080 // semaphore and signalling the ownership released semaphore when finished
Tony Barboura72d9492017-01-11 13:35:09 -07001081 VkFence nullFence = VK_NULL_HANDLE;
Tony Barbour22e06272016-09-07 16:07:56 -06001082 pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1083 submit_info.waitSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001084 submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001085 submit_info.commandBufferCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07001086 submit_info.pCommandBuffers = &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd;
Tony Barbour22e06272016-09-07 16:07:56 -06001087 submit_info.signalSemaphoreCount = 1;
Tony Barbour66a56c32016-09-21 13:10:56 -06001088 submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index];
Tony Barbour22e06272016-09-07 16:07:56 -06001089 err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence);
1090 assert(!err);
1091 }
1092
1093 // If we are using separate queues we have to wait for image ownership,
1094 // otherwise wait for draw complete
Ian Elliotta0781972015-08-21 15:09:33 -06001095 VkPresentInfoKHR present = {
1096 .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
Ian Elliottaaae5352015-07-06 14:27:58 -06001097 .pNext = NULL,
Ian Elliottcf7f7482016-08-19 03:46:58 -06001098 .waitSemaphoreCount = 1,
Dave Houlton5fa47912018-02-16 11:02:26 -07001099 .pWaitSemaphores = (demo->separate_present_queue) ? &demo->image_ownership_semaphores[demo->frame_index]
1100 : &demo->draw_complete_semaphores[demo->frame_index],
Ian Elliotta0781972015-08-21 15:09:33 -06001101 .swapchainCount = 1,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001102 .pSwapchains = &demo->swapchain,
1103 .pImageIndices = &demo->current_buffer,
Ian Elliottaaae5352015-07-06 14:27:58 -06001104 };
1105
Dave Airlie48a68f92019-04-12 17:04:48 +10001106 VkRectLayerKHR rect;
1107 VkPresentRegionKHR region;
1108 VkPresentRegionsKHR regions;
Ian Elliott53622a72017-03-28 11:06:33 -06001109 if (demo->VK_KHR_incremental_present_enabled) {
1110 // If using VK_KHR_incremental_present, we provide a hint of the region
1111 // that contains changed content relative to the previously-presented
1112 // image. The implementation can use this hint in order to save
1113 // work/power (by only copying the region in the hint). The
1114 // implementation is free to ignore the hint though, and so we must
1115 // ensure that the entire image has the correctly-drawn content.
1116 uint32_t eighthOfWidth = demo->width / 8;
1117 uint32_t eighthOfHeight = demo->height / 8;
Dave Airlie48a68f92019-04-12 17:04:48 +10001118
1119 rect.offset.x = eighthOfWidth;
1120 rect.offset.y = eighthOfHeight;
1121 rect.extent.width = eighthOfWidth * 6;
1122 rect.extent.height = eighthOfHeight * 6;
1123 rect.layer = 0;
1124
1125 region.rectangleCount = 1;
1126 region.pRectangles = &rect;
1127
1128 regions.sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR;
1129 regions.pNext = present.pNext;
1130 regions.swapchainCount = present.swapchainCount;
1131 regions.pRegions = &region;
Ian Elliott53622a72017-03-28 11:06:33 -06001132 present.pNext = &regions;
Ian Elliott53622a72017-03-28 11:06:33 -06001133 }
1134
Ian Elliottd940ca22017-03-22 08:31:27 -06001135 if (demo->VK_GOOGLE_display_timing_enabled) {
1136 VkPresentTimeGOOGLE ptime;
1137 if (demo->prev_desired_present_time == 0) {
1138 // This must be the first present for this swapchain.
1139 //
1140 // We don't know where we are relative to the presentation engine's
1141 // display's refresh cycle. We also don't know how long rendering
1142 // takes. Let's make a grossly-simplified assumption that the
1143 // desiredPresentTime should be half way between now and
1144 // now+target_IPD. We will adjust over time.
1145 uint64_t curtime = getTimeInNanoseconds();
1146 if (curtime == 0) {
1147 // Since we didn't find out the current time, don't give a
1148 // desiredPresentTime:
1149 ptime.desiredPresentTime = 0;
1150 } else {
Ian Elliottd940ca22017-03-22 08:31:27 -06001151 ptime.desiredPresentTime = curtime + (demo->target_IPD >> 1);
1152 }
1153 } else {
Dave Houlton5fa47912018-02-16 11:02:26 -07001154 ptime.desiredPresentTime = (demo->prev_desired_present_time + demo->target_IPD);
Ian Elliottd940ca22017-03-22 08:31:27 -06001155 }
1156 ptime.presentID = demo->next_present_id++;
1157 demo->prev_desired_present_time = ptime.desiredPresentTime;
Ian Elliottd940ca22017-03-22 08:31:27 -06001158
1159 VkPresentTimesInfoGOOGLE present_time = {
1160 .sType = VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,
1161 .pNext = present.pNext,
1162 .swapchainCount = present.swapchainCount,
1163 .pTimes = &ptime,
1164 };
1165 if (demo->VK_GOOGLE_display_timing_enabled) {
1166 present.pNext = &present_time;
Ian Elliottd940ca22017-03-22 08:31:27 -06001167 }
1168 }
1169
Tony Barboura2a67812016-07-18 13:21:06 -06001170 err = demo->fpQueuePresentKHR(demo->present_queue, &present);
Tony Barbour66a56c32016-09-21 13:10:56 -06001171 demo->frame_index += 1;
1172 demo->frame_index %= FRAME_LAG;
1173
Ian Elliottcf074d32015-10-16 18:02:43 -06001174 if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1175 // demo->swapchain is out of date (e.g. the window was resized) and
1176 // must be recreated:
1177 demo_resize(demo);
1178 } else if (err == VK_SUBOPTIMAL_KHR) {
Tony-LunarGa8e96342021-06-04 15:12:55 -06001179 // SUBOPTIMAL could be due to a resize
1180 VkSurfaceCapabilitiesKHR surfCapabilities;
1181 err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
1182 assert(!err);
Tony-LunarGbbdf5842021-06-11 12:00:30 -06001183 if (surfCapabilities.currentExtent.width != (uint32_t)demo->width ||
1184 surfCapabilities.currentExtent.height != (uint32_t)demo->height) {
Tony-LunarGa8e96342021-06-04 15:12:55 -06001185 demo_resize(demo);
1186 }
Tony-LunarG6cebf142019-09-11 14:32:23 -06001187 } else if (err == VK_ERROR_SURFACE_LOST_KHR) {
1188 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
1189 demo_create_surface(demo);
1190 demo_resize(demo);
Ian Elliottcf074d32015-10-16 18:02:43 -06001191 } else {
1192 assert(!err);
1193 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001194}
1195
Karl Schultze4dc75c2016-02-02 15:37:51 -07001196static void demo_prepare_buffers(struct demo *demo) {
Ian Elliottaaae5352015-07-06 14:27:58 -06001197 VkResult U_ASSERT_ONLY err;
Ian Elliottcf074d32015-10-16 18:02:43 -06001198 VkSwapchainKHR oldSwapchain = demo->swapchain;
Ian Elliottaaae5352015-07-06 14:27:58 -06001199
Ian Elliottb08e0d92015-11-20 11:55:46 -07001200 // Check the surface capabilities and formats
1201 VkSurfaceCapabilitiesKHR surfCapabilities;
Dave Houlton5fa47912018-02-16 11:02:26 -07001202 err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR(demo->gpu, demo->surface, &surfCapabilities);
Ian Elliottaaae5352015-07-06 14:27:58 -06001203 assert(!err);
1204
Ian Elliott8528eff2015-08-07 15:56:59 -06001205 uint32_t presentModeCount;
Dave Houlton5fa47912018-02-16 11:02:26 -07001206 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06001207 assert(!err);
Dave Houlton5fa47912018-02-16 11:02:26 -07001208 VkPresentModeKHR *presentModes = (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR));
Ian Elliott8528eff2015-08-07 15:56:59 -06001209 assert(presentModes);
Dave Houlton5fa47912018-02-16 11:02:26 -07001210 err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR(demo->gpu, demo->surface, &presentModeCount, presentModes);
Ian Elliottaaae5352015-07-06 14:27:58 -06001211 assert(!err);
1212
Ian Elliotta0781972015-08-21 15:09:33 -06001213 VkExtent2D swapchainExtent;
Ian Elliottcf7f7482016-08-19 03:46:58 -06001214 // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
1215 if (surfCapabilities.currentExtent.width == 0xFFFFFFFF) {
1216 // If the surface size is undefined, the size is set to the size
1217 // of the images requested, which must fit within the minimum and
1218 // maximum values.
Ian Elliotta0781972015-08-21 15:09:33 -06001219 swapchainExtent.width = demo->width;
1220 swapchainExtent.height = demo->height;
Ian Elliottcf7f7482016-08-19 03:46:58 -06001221
1222 if (swapchainExtent.width < surfCapabilities.minImageExtent.width) {
1223 swapchainExtent.width = surfCapabilities.minImageExtent.width;
1224 } else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width) {
1225 swapchainExtent.width = surfCapabilities.maxImageExtent.width;
1226 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001227
Ian Elliottcf7f7482016-08-19 03:46:58 -06001228 if (swapchainExtent.height < surfCapabilities.minImageExtent.height) {
1229 swapchainExtent.height = surfCapabilities.minImageExtent.height;
1230 } else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height) {
1231 swapchainExtent.height = surfCapabilities.maxImageExtent.height;
1232 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07001233 } else {
Ian Elliottaaae5352015-07-06 14:27:58 -06001234 // If the surface size is defined, the swap chain size must match
Ian Elliottb08e0d92015-11-20 11:55:46 -07001235 swapchainExtent = surfCapabilities.currentExtent;
1236 demo->width = surfCapabilities.currentExtent.width;
1237 demo->height = surfCapabilities.currentExtent.height;
Ian Elliottaaae5352015-07-06 14:27:58 -06001238 }
1239
Jeremy Kniager602e4182018-01-19 10:52:34 -07001240 if (demo->width == 0 || demo->height == 0) {
1241 demo->is_minimized = true;
1242 return;
1243 } else {
1244 demo->is_minimized = false;
1245 }
1246
Tony Barbour66a56c32016-09-21 13:10:56 -06001247 // The FIFO present mode is guaranteed by the spec to be supported
Ian Elliottb18fdde2016-10-03 12:11:12 -06001248 // and to have no tearing. It's a great default present mode to use.
Ian Elliotta0781972015-08-21 15:09:33 -06001249 VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
Tony Barbour291d57b2016-10-21 14:47:07 -06001250
Ian Elliottb18fdde2016-10-03 12:11:12 -06001251 // There are times when you may wish to use another present mode. The
1252 // following code shows how to select them, and the comments provide some
1253 // reasons you may wish to use them.
1254 //
1255 // It should be noted that Vulkan 1.0 doesn't provide a method for
1256 // synchronizing rendering with the presentation engine's display. There
1257 // is a method provided for throttling rendering with the display, but
1258 // there are some presentation engines for which this method will not work.
1259 // If an application doesn't throttle its rendering, and if it renders much
1260 // faster than the refresh rate of the display, this can waste power on
1261 // mobile devices. That is because power is being spent rendering images
1262 // that may never be seen.
Tony Barbour291d57b2016-10-21 14:47:07 -06001263
Ian Elliottb18fdde2016-10-03 12:11:12 -06001264 // VK_PRESENT_MODE_IMMEDIATE_KHR is for applications that don't care about
1265 // tearing, or have some way of synchronizing their rendering with the
1266 // display.
Ian Elliottb18fdde2016-10-03 12:11:12 -06001267 // VK_PRESENT_MODE_MAILBOX_KHR may be useful for applications that
1268 // generally render a new presentable image every refresh cycle, but are
1269 // occasionally early. In this case, the application wants the new image
1270 // to be displayed instead of the previously-queued-for-presentation image
1271 // that has not yet been displayed.
Ian Elliottb18fdde2016-10-03 12:11:12 -06001272 // VK_PRESENT_MODE_FIFO_RELAXED_KHR is for applications that generally
1273 // render a new presentable image every refresh cycle, but are occasionally
1274 // late. In this case (perhaps because of stuttering/latency concerns),
1275 // the application wants the late image to be immediately displayed, even
1276 // though that may mean some tearing.
Tony Barbour291d57b2016-10-21 14:47:07 -06001277
Dave Houlton5fa47912018-02-16 11:02:26 -07001278 if (demo->presentMode != swapchainPresentMode) {
Tony Barbour291d57b2016-10-21 14:47:07 -06001279 for (size_t i = 0; i < presentModeCount; ++i) {
1280 if (presentModes[i] == demo->presentMode) {
1281 swapchainPresentMode = demo->presentMode;
1282 break;
1283 }
Ian Elliottb18fdde2016-10-03 12:11:12 -06001284 }
1285 }
Tony Barbour291d57b2016-10-21 14:47:07 -06001286 if (swapchainPresentMode != demo->presentMode) {
1287 ERR_EXIT("Present mode specified is not supported\n", "Present mode unsupported");
1288 }
Ian Elliottaaae5352015-07-06 14:27:58 -06001289
Tony Barbour84376fe2017-01-06 15:54:22 -07001290 // Determine the number of VkImages to use in the swap chain.
1291 // Application desires to acquire 3 images at a time for triple
1292 // buffering
1293 uint32_t desiredNumOfSwapchainImages = 3;
1294 if (desiredNumOfSwapchainImages < surfCapabilities.minImageCount) {
1295 desiredNumOfSwapchainImages = surfCapabilities.minImageCount;
1296 }
Ian Elliottcf7f7482016-08-19 03:46:58 -06001297 // If maxImageCount is 0, we can ask for as many images as we want;
1298 // otherwise we're limited to maxImageCount
Dave Houlton5fa47912018-02-16 11:02:26 -07001299 if ((surfCapabilities.maxImageCount > 0) && (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount)) {
Ian Elliottaaae5352015-07-06 14:27:58 -06001300 // Application must settle for fewer images than desired:
Ian Elliottcf7f7482016-08-19 03:46:58 -06001301 desiredNumOfSwapchainImages = surfCapabilities.maxImageCount;
Ian Elliottaaae5352015-07-06 14:27:58 -06001302 }
1303
Tony Barbour9fd6d352015-09-16 15:01:32 -06001304 VkSurfaceTransformFlagsKHR preTransform;
Dave Houlton5fa47912018-02-16 11:02:26 -07001305 if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
Ian Elliotta7a731c2015-12-11 15:52:12 -07001306 preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Ian Elliottaaae5352015-07-06 14:27:58 -06001307 } else {
Ian Elliottb08e0d92015-11-20 11:55:46 -07001308 preTransform = surfCapabilities.currentTransform;
Ian Elliottaaae5352015-07-06 14:27:58 -06001309 }
1310
Tony Barbour820b55b2017-03-14 08:55:46 -06001311 // Find a supported composite alpha mode - one of these is guaranteed to be set
1312 VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
1313 VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = {
1314 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
1315 VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR,
1316 VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR,
1317 VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR,
1318 };
Tony Barbour34ea9cf2017-08-14 12:02:30 -06001319 for (uint32_t i = 0; i < ARRAY_SIZE(compositeAlphaFlags); i++) {
Tony Barbour820b55b2017-03-14 08:55:46 -06001320 if (surfCapabilities.supportedCompositeAlpha & compositeAlphaFlags[i]) {
1321 compositeAlpha = compositeAlphaFlags[i];
1322 break;
1323 }
1324 }
1325
Tony Barboura2a67812016-07-18 13:21:06 -06001326 VkSwapchainCreateInfoKHR swapchain_ci = {
Ian Elliott5b97eae2015-09-22 10:20:23 -06001327 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
Chia-I Wucbb564e2015-04-16 22:02:10 +08001328 .pNext = NULL,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001329 .surface = demo->surface,
Ian Elliottcf7f7482016-08-19 03:46:58 -06001330 .minImageCount = desiredNumOfSwapchainImages,
Chia-I Wucbb564e2015-04-16 22:02:10 +08001331 .imageFormat = demo->format,
Ian Elliott8528eff2015-08-07 15:56:59 -06001332 .imageColorSpace = demo->color_space,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001333 .imageExtent =
1334 {
Dave Houlton5fa47912018-02-16 11:02:26 -07001335 .width = swapchainExtent.width,
1336 .height = swapchainExtent.height,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001337 },
Ian Elliottb08e0d92015-11-20 11:55:46 -07001338 .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
Ian Elliottaaae5352015-07-06 14:27:58 -06001339 .preTransform = preTransform,
Tony Barbour820b55b2017-03-14 08:55:46 -06001340 .compositeAlpha = compositeAlpha,
Ian Elliottb08e0d92015-11-20 11:55:46 -07001341 .imageArrayLayers = 1,
1342 .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
1343 .queueFamilyIndexCount = 0,
Ian Elliott8528eff2015-08-07 15:56:59 -06001344 .pQueueFamilyIndices = NULL,
Ian Elliotta0781972015-08-21 15:09:33 -06001345 .presentMode = swapchainPresentMode,
Ian Elliottcf074d32015-10-16 18:02:43 -06001346 .oldSwapchain = oldSwapchain,
Ian Elliottaaae5352015-07-06 14:27:58 -06001347 .clipped = true,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001348 };
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001349 uint32_t i;
Dave Houlton5fa47912018-02-16 11:02:26 -07001350 err = demo->fpCreateSwapchainKHR(demo->device, &swapchain_ci, NULL, &demo->swapchain);
Chia-I Wucbb564e2015-04-16 22:02:10 +08001351 assert(!err);
1352
Ian Elliottcf074d32015-10-16 18:02:43 -06001353 // If we just re-created an existing swapchain, we should destroy the old
1354 // swapchain at this point.
1355 // Note: destroying the swapchain also cleans up all its associated
1356 // presentable images once the platform is done with them.
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001357 if (oldSwapchain != VK_NULL_HANDLE) {
Ian Elliottb08e0d92015-11-20 11:55:46 -07001358 demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06001359 }
1360
Dave Houlton5fa47912018-02-16 11:02:26 -07001361 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06001362 assert(!err);
Chia-I Wucbb564e2015-04-16 22:02:10 +08001363
Dave Houlton5fa47912018-02-16 11:02:26 -07001364 VkImage *swapchainImages = (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage));
Ian Elliotta0781972015-08-21 15:09:33 -06001365 assert(swapchainImages);
Dave Houlton5fa47912018-02-16 11:02:26 -07001366 err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, &demo->swapchainImageCount, swapchainImages);
Ian Elliottaaae5352015-07-06 14:27:58 -06001367 assert(!err);
Ian Elliottaaae5352015-07-06 14:27:58 -06001368
Dave Houlton5fa47912018-02-16 11:02:26 -07001369 demo->swapchain_image_resources =
1370 (SwapchainImageResources *)malloc(sizeof(SwapchainImageResources) * demo->swapchainImageCount);
Tony Barboura72d9492017-01-11 13:35:09 -07001371 assert(demo->swapchain_image_resources);
1372
Ian Elliotta0781972015-08-21 15:09:33 -06001373 for (i = 0; i < demo->swapchainImageCount; i++) {
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001374 VkImageViewCreateInfo color_image_view = {
1375 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001376 .pNext = NULL,
1377 .format = demo->format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001378 .components =
1379 {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001380 .r = VK_COMPONENT_SWIZZLE_IDENTITY,
1381 .g = VK_COMPONENT_SWIZZLE_IDENTITY,
1382 .b = VK_COMPONENT_SWIZZLE_IDENTITY,
1383 .a = VK_COMPONENT_SWIZZLE_IDENTITY,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001384 },
Dave Houlton5fa47912018-02-16 11:02:26 -07001385 .subresourceRange =
1386 {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001387 .viewType = VK_IMAGE_VIEW_TYPE_2D,
1388 .flags = 0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001389 };
1390
Tony Barboura72d9492017-01-11 13:35:09 -07001391 demo->swapchain_image_resources[i].image = swapchainImages[i];
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001392
Tony Barboura72d9492017-01-11 13:35:09 -07001393 color_image_view.image = demo->swapchain_image_resources[i].image;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001394
Dave Houlton5fa47912018-02-16 11:02:26 -07001395 err = vkCreateImageView(demo->device, &color_image_view, NULL, &demo->swapchain_image_resources[i].view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001396 assert(!err);
1397 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07001398
Ian Elliottd940ca22017-03-22 08:31:27 -06001399 if (demo->VK_GOOGLE_display_timing_enabled) {
1400 VkRefreshCycleDurationGOOGLE rc_dur;
Dave Houlton5fa47912018-02-16 11:02:26 -07001401 err = demo->fpGetRefreshCycleDurationGOOGLE(demo->device, demo->swapchain, &rc_dur);
Ian Elliottd940ca22017-03-22 08:31:27 -06001402 assert(!err);
1403 demo->refresh_duration = rc_dur.refreshDuration;
1404
1405 demo->syncd_with_actual_presents = false;
1406 // Initially target 1X the refresh duration:
1407 demo->target_IPD = demo->refresh_duration;
1408 demo->refresh_duration_multiplier = 1;
1409 demo->prev_desired_present_time = 0;
1410 demo->next_present_id = 1;
Ian Elliottd940ca22017-03-22 08:31:27 -06001411 }
1412
Jason Chen5d4fee92019-04-04 12:45:29 +08001413 if (NULL != swapchainImages) {
1414 free(swapchainImages);
1415 }
1416
Mark Young04fd3d82016-01-25 14:43:50 -07001417 if (NULL != presentModes) {
1418 free(presentModes);
1419 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001420}
1421
Karl Schultze4dc75c2016-02-02 15:37:51 -07001422static void demo_prepare_depth(struct demo *demo) {
Tony Barbour72304ef2015-04-16 15:59:00 -06001423 const VkFormat depth_format = VK_FORMAT_D16_UNORM;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001424 const VkImageCreateInfo image = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001425 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001426 .pNext = NULL,
Tony Barbour72304ef2015-04-16 15:59:00 -06001427 .imageType = VK_IMAGE_TYPE_2D,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001428 .format = depth_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001429 .extent = {demo->width, demo->height, 1},
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001430 .mipLevels = 1,
Courtney Goeltzenleuchterdff021f2015-10-21 17:57:31 -06001431 .arrayLayers = 1,
Chia-I Wu3ede9462015-10-31 00:31:16 +08001432 .samples = VK_SAMPLE_COUNT_1_BIT,
Tony Barbour72304ef2015-04-16 15:59:00 -06001433 .tiling = VK_IMAGE_TILING_OPTIMAL,
Courtney Goeltzenleuchter4e368ee2015-09-10 14:14:11 -06001434 .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001435 .flags = 0,
1436 };
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001437
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001438 VkImageViewCreateInfo view = {
1439 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001440 .pNext = NULL,
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001441 .image = VK_NULL_HANDLE,
Courtney Goeltzenleuchter556ee322015-07-15 17:41:38 -06001442 .format = depth_format,
Dave Houlton5fa47912018-02-16 11:02:26 -07001443 .subresourceRange =
1444 {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1},
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001445 .flags = 0,
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001446 .viewType = VK_IMAGE_VIEW_TYPE_2D,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001447 };
Mike Stroyanebae8322015-04-17 12:36:38 -06001448
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001449 VkMemoryRequirements mem_reqs;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001450 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001451 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001452
1453 demo->depth.format = depth_format;
1454
1455 /* create image */
Karl Schultze4dc75c2016-02-02 15:37:51 -07001456 err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001457 assert(!err);
1458
Karl Schultze4dc75c2016-02-02 15:37:51 -07001459 vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs);
Tony Barbourcb59a5d2015-10-23 10:53:30 -06001460 assert(!err);
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06001461
Chia-I Wuf48700b2015-11-10 16:21:09 +08001462 demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001463 demo->depth.mem_alloc.pNext = NULL;
1464 demo->depth.mem_alloc.allocationSize = mem_reqs.size;
1465 demo->depth.mem_alloc.memoryTypeIndex = 0;
1466
Dave Houlton5fa47912018-02-16 11:02:26 -07001467 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001468 &demo->depth.mem_alloc.memoryTypeIndex);
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001469 assert(pass);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001470
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001471 /* allocate memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001472 err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, &demo->depth.mem);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001473 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001474
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001475 /* bind memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001476 err = vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001477 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001478
1479 /* create image view */
1480 view.image = demo->depth.image;
Chia-I Wu63636062015-10-26 21:10:41 +08001481 err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001482 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001483}
1484
Karl Schultzb7940402018-05-29 13:09:22 -06001485/* Convert ppm image data from header file into RGBA texture image */
1486#include "lunarg.ppm.h"
Dave Houlton5fa47912018-02-16 11:02:26 -07001487bool loadTexture(const char *filename, uint8_t *rgba_data, VkSubresourceLayout *layout, int32_t *width, int32_t *height) {
Karl Schultzb7940402018-05-29 13:09:22 -06001488 (void)filename;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001489 char *cPtr;
Dave Houlton5fa47912018-02-16 11:02:26 -07001490 cPtr = (char *)lunarg_ppm;
1491 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "P6\n", 3)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001492 return false;
1493 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001494 while (strncmp(cPtr++, "\n", 1))
1495 ;
Alexandre BACQUART9063e2a2016-06-17 11:30:32 -06001496 sscanf(cPtr, "%u %u", width, height);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001497 if (rgba_data == NULL) {
1498 return true;
1499 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001500 while (strncmp(cPtr++, "\n", 1))
1501 ;
1502 if ((unsigned char *)cPtr >= (lunarg_ppm + lunarg_ppm_len) || strncmp(cPtr, "255\n", 4)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001503 return false;
1504 }
Dave Houlton5fa47912018-02-16 11:02:26 -07001505 while (strncmp(cPtr++, "\n", 1))
1506 ;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001507 for (int y = 0; y < *height; y++) {
1508 uint8_t *rowPtr = rgba_data;
1509 for (int x = 0; x < *width; x++) {
1510 memcpy(rowPtr, cPtr, 3);
1511 rowPtr[3] = 255; /* Alpha of 1 */
1512 rowPtr += 4;
1513 cPtr += 3;
1514 }
1515 rgba_data += layout->rowPitch;
1516 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001517 return true;
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001518}
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001519
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001520static void demo_prepare_texture_buffer(struct demo *demo, const char *filename, struct texture_object *tex_obj) {
1521 int32_t tex_width;
1522 int32_t tex_height;
1523 VkResult U_ASSERT_ONLY err;
1524 bool U_ASSERT_ONLY pass;
1525
1526 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
1527 ERR_EXIT("Failed to load textures", "Load Texture Failure");
1528 }
1529
1530 tex_obj->tex_width = tex_width;
1531 tex_obj->tex_height = tex_height;
1532
1533 const VkBufferCreateInfo buffer_create_info = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
1534 .pNext = NULL,
1535 .flags = 0,
1536 .size = tex_width * tex_height * 4,
1537 .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
1538 .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
1539 .queueFamilyIndexCount = 0,
1540 .pQueueFamilyIndices = NULL};
1541
1542 err = vkCreateBuffer(demo->device, &buffer_create_info, NULL, &tex_obj->buffer);
1543 assert(!err);
1544
1545 VkMemoryRequirements mem_reqs;
1546 vkGetBufferMemoryRequirements(demo->device, tex_obj->buffer, &mem_reqs);
1547
1548 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1549 tex_obj->mem_alloc.pNext = NULL;
1550 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1551 tex_obj->mem_alloc.memoryTypeIndex = 0;
1552
1553 VkFlags requirements = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
1554 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, requirements, &tex_obj->mem_alloc.memoryTypeIndex);
1555 assert(pass);
1556
1557 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
1558 assert(!err);
1559
1560 /* bind memory */
1561 err = vkBindBufferMemory(demo->device, tex_obj->buffer, tex_obj->mem, 0);
1562 assert(!err);
1563
1564 VkSubresourceLayout layout;
1565 memset(&layout, 0, sizeof(layout));
1566 layout.rowPitch = tex_width * 4;
1567
1568 void *data;
1569 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
1570 assert(!err);
1571
1572 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1573 fprintf(stderr, "Error loading texture: %s\n", filename);
1574 }
1575
1576 vkUnmapMemory(demo->device, tex_obj->mem);
1577}
1578
Dave Houlton5fa47912018-02-16 11:02:26 -07001579static void demo_prepare_texture_image(struct demo *demo, const char *filename, struct texture_object *tex_obj,
1580 VkImageTiling tiling, VkImageUsageFlags usage, VkFlags required_props) {
Mike Stroyan8b89e072015-06-15 14:21:03 -06001581 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001582 int32_t tex_width;
1583 int32_t tex_height;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001584 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001585 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001586
Karl Schultze4dc75c2016-02-02 15:37:51 -07001587 if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05001588 ERR_EXIT("Failed to load textures", "Load Texture Failure");
David Pinedo30bd71d2015-04-23 08:16:57 -06001589 }
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001590
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06001591 tex_obj->tex_width = tex_width;
1592 tex_obj->tex_height = tex_height;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001593
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001594 const VkImageCreateInfo image_create_info = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001595 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001596 .pNext = NULL,
Tony Barbour72304ef2015-04-16 15:59:00 -06001597 .imageType = VK_IMAGE_TYPE_2D,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001598 .format = tex_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001599 .extent = {tex_width, tex_height, 1},
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001600 .mipLevels = 1,
Courtney Goeltzenleuchterdff021f2015-10-21 17:57:31 -06001601 .arrayLayers = 1,
Chia-I Wu3ede9462015-10-31 00:31:16 +08001602 .samples = VK_SAMPLE_COUNT_1_BIT,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001603 .tiling = tiling,
Courtney Goeltzenleuchterc56c36a2015-04-21 09:31:23 -06001604 .usage = usage,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001605 .flags = 0,
Tobin Ehlisf07d9552016-02-11 17:49:23 -07001606 .initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001607 };
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001608
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001609 VkMemoryRequirements mem_reqs;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001610
Dave Houlton5fa47912018-02-16 11:02:26 -07001611 err = vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001612 assert(!err);
1613
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001614 vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs);
Piers Daniell735ee532015-02-23 16:23:13 -07001615
Chia-I Wuf48700b2015-11-10 16:21:09 +08001616 tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001617 tex_obj->mem_alloc.pNext = NULL;
1618 tex_obj->mem_alloc.allocationSize = mem_reqs.size;
1619 tex_obj->mem_alloc.memoryTypeIndex = 0;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001620
Dave Houlton5fa47912018-02-16 11:02:26 -07001621 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, required_props, &tex_obj->mem_alloc.memoryTypeIndex);
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001622 assert(pass);
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06001623
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001624 /* allocate memory */
Dave Houlton5fa47912018-02-16 11:02:26 -07001625 err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, &(tex_obj->mem));
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001626 assert(!err);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001627
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001628 /* bind memory */
Karl Schultze4dc75c2016-02-02 15:37:51 -07001629 err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001630 assert(!err);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001631
Tony Barbour8a9f62a2015-10-15 12:42:56 -06001632 if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001633 const VkImageSubresource subres = {
Chia-I Wua0141432015-10-27 19:55:05 +08001634 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001635 .mipLevel = 0,
Courtney Goeltzenleuchterfc465b82015-09-10 16:38:41 -06001636 .arrayLayer = 0,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001637 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001638 VkSubresourceLayout layout;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001639 void *data;
1640
Dave Houlton5fa47912018-02-16 11:02:26 -07001641 vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, &layout);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001642
Dave Houlton5fa47912018-02-16 11:02:26 -07001643 err = vkMapMemory(demo->device, tex_obj->mem, 0, tex_obj->mem_alloc.allocationSize, 0, &data);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001644 assert(!err);
1645
1646 if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) {
1647 fprintf(stderr, "Error loading texture: %s\n", filename);
1648 }
1649
Mark Lobodzinskie4c92a62015-09-07 13:59:43 -06001650 vkUnmapMemory(demo->device, tex_obj->mem);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001651 }
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06001652
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001653 tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001654}
1655
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001656static void demo_destroy_texture(struct demo *demo, struct texture_object *tex_objs) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001657 /* clean up staging resources */
Chia-I Wu63636062015-10-26 21:10:41 +08001658 vkFreeMemory(demo->device, tex_objs->mem, NULL);
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001659 if (tex_objs->image) vkDestroyImage(demo->device, tex_objs->image, NULL);
1660 if (tex_objs->buffer) vkDestroyBuffer(demo->device, tex_objs->buffer, NULL);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001661}
1662
Karl Schultze4dc75c2016-02-02 15:37:51 -07001663static void demo_prepare_textures(struct demo *demo) {
Tony Barbour72304ef2015-04-16 15:59:00 -06001664 const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM;
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001665 VkFormatProperties props;
Mark Lobodzinskic4fffc72015-01-29 08:55:56 -06001666 uint32_t i;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001667
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001668 vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001669
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001670 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06001671 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001672
Dave Houlton5fa47912018-02-16 11:02:26 -07001673 if ((props.linearTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !demo->use_staging_buffer) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001674 /* Device can texture using linear textures */
Dave Houlton5fa47912018-02-16 11:02:26 -07001675 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_SAMPLED_BIT,
1676 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
Tony Barbour5ff13182016-10-19 13:58:29 -06001677 // Nothing in the pipeline needs to be complete to start, and don't allow fragment
1678 // shader to run until layout transition completes
Dave Houlton5fa47912018-02-16 11:02:26 -07001679 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1680 demo->textures[i].imageLayout, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001681 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
Tony Barbour16156cb2016-10-19 14:15:49 -06001682 demo->staging_texture.image = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07001683 } else if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001684 /* Must use staging buffer to copy linear texture to optimized */
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001685
Tony Barbour16156cb2016-10-19 14:15:49 -06001686 memset(&demo->staging_texture, 0, sizeof(demo->staging_texture));
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001687 demo_prepare_texture_buffer(demo, tex_files[i], &demo->staging_texture);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001688
Dave Houlton5fa47912018-02-16 11:02:26 -07001689 demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL,
1690 (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1691 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001692
Dave Houlton5fa47912018-02-16 11:02:26 -07001693 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED,
1694 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001695 VK_PIPELINE_STAGE_TRANSFER_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001696
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001697 VkBufferImageCopy copy_region = {
1698 .bufferOffset = 0,
1699 .bufferRowLength = demo->staging_texture.tex_width,
1700 .bufferImageHeight = demo->staging_texture.tex_height,
1701 .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
1702 .imageOffset = {0, 0, 0},
1703 .imageExtent = {demo->staging_texture.tex_width, demo->staging_texture.tex_height, 1},
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001704 };
Tony-LunarGbc9fc052018-09-21 13:47:06 -06001705
1706 vkCmdCopyBufferToImage(demo->cmd, demo->staging_texture.buffer, demo->textures[i].image,
1707 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_region);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001708
Dave Houlton5fa47912018-02-16 11:02:26 -07001709 demo_set_image_layout(demo, demo->textures[i].image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1710 demo->textures[i].imageLayout, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
Tony Barbour5ff13182016-10-19 13:58:29 -06001711 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001712
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001713 } else {
Mike Stroyan8b89e072015-06-15 14:21:03 -06001714 /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */
1715 assert(!"No support for R8G8B8A8_UNORM as texture image format");
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001716 }
1717
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001718 const VkSamplerCreateInfo sampler = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001719 .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001720 .pNext = NULL,
Chia-I Wu6ef8c3b2015-10-26 16:49:32 +08001721 .magFilter = VK_FILTER_NEAREST,
1722 .minFilter = VK_FILTER_NEAREST,
Jon Ashburn0bec67e2016-01-11 13:12:43 -07001723 .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001724 .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1725 .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
1726 .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001727 .mipLodBias = 0.0f,
Jon Ashburn55e3fb02015-12-14 14:59:20 -07001728 .anisotropyEnable = VK_FALSE,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001729 .maxAnisotropy = 1,
Tony Barbour72304ef2015-04-16 15:59:00 -06001730 .compareOp = VK_COMPARE_OP_NEVER,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001731 .minLod = 0.0f,
1732 .maxLod = 0.0f,
Tony Barbourcb530c72015-06-25 16:56:44 -06001733 .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE,
Mark Lobodzinski644dc492015-09-01 15:42:56 -06001734 .unnormalizedCoordinates = VK_FALSE,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001735 };
Courtney Goeltzenleuchter68369392014-10-29 15:59:49 -06001736
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001737 VkImageViewCreateInfo view = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001738 .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001739 .pNext = NULL,
Chia-I Wu1c4086a2015-10-26 20:04:44 +08001740 .image = VK_NULL_HANDLE,
Tony Barbour72304ef2015-04-16 15:59:00 -06001741 .viewType = VK_IMAGE_VIEW_TYPE_2D,
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07001742 .format = tex_format,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001743 .components =
1744 {
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05001745 VK_COMPONENT_SWIZZLE_IDENTITY,
1746 VK_COMPONENT_SWIZZLE_IDENTITY,
1747 VK_COMPONENT_SWIZZLE_IDENTITY,
1748 VK_COMPONENT_SWIZZLE_IDENTITY,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001749 },
1750 .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06001751 .flags = 0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001752 };
Jon Ashburnb2a66652015-01-16 09:37:43 -07001753
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001754 /* create sampler */
Dave Houlton5fa47912018-02-16 11:02:26 -07001755 err = vkCreateSampler(demo->device, &sampler, NULL, &demo->textures[i].sampler);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001756 assert(!err);
1757
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001758 /* create image view */
1759 view.image = demo->textures[i].image;
Dave Houlton5fa47912018-02-16 11:02:26 -07001760 err = vkCreateImageView(demo->device, &view, NULL, &demo->textures[i].view);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001761 assert(!err);
1762 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001763}
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001764
Tony Barboura72d9492017-01-11 13:35:09 -07001765void demo_prepare_cube_data_buffers(struct demo *demo) {
Courtney Goeltzenleuchter28c4d5f2015-04-14 18:48:46 -06001766 VkBufferCreateInfo buf_info;
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001767 VkMemoryRequirements mem_reqs;
Tony Barboura72d9492017-01-11 13:35:09 -07001768 VkMemoryAllocateInfo mem_alloc;
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001769 mat4x4 MVP, VP;
Tony Barbourfdc2d352015-04-22 09:02:32 -06001770 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter87a0ef02015-10-22 11:03:31 -06001771 bool U_ASSERT_ONLY pass;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001772 struct vktexcube_vs_uniform data;
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001773
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001774 mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001775 mat4x4_mul(MVP, VP, demo->model_matrix);
1776 memcpy(data.mvp, MVP, sizeof(MVP));
Karl Schultze4dc75c2016-02-02 15:37:51 -07001777 // dumpMatrix("MVP", MVP);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001778
Karl Schultza2615462017-01-20 13:19:20 -07001779 for (unsigned int i = 0; i < 12 * 3; i++) {
Karl Schultze4dc75c2016-02-02 15:37:51 -07001780 data.position[i][0] = g_vertex_buffer_data[i * 3];
1781 data.position[i][1] = g_vertex_buffer_data[i * 3 + 1];
1782 data.position[i][2] = g_vertex_buffer_data[i * 3 + 2];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001783 data.position[i][3] = 1.0f;
Karl Schultze4dc75c2016-02-02 15:37:51 -07001784 data.attr[i][0] = g_uv_buffer_data[2 * i];
1785 data.attr[i][1] = g_uv_buffer_data[2 * i + 1];
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001786 data.attr[i][2] = 0;
1787 data.attr[i][3] = 0;
1788 }
1789
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001790 memset(&buf_info, 0, sizeof(buf_info));
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001791 buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
Courtney Goeltzenleuchter42a078d2015-04-15 15:29:59 -06001792 buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
Cody Northrop91807302015-07-16 10:29:32 -06001793 buf_info.size = sizeof(data);
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001794
Tony Barboura72d9492017-01-11 13:35:09 -07001795 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07001796 err = vkCreateBuffer(demo->device, &buf_info, NULL, &demo->swapchain_image_resources[i].uniform_buffer);
Tony Barboura72d9492017-01-11 13:35:09 -07001797 assert(!err);
Chia-I Wu8ea21c72015-01-01 07:55:04 +08001798
Dave Houlton5fa47912018-02-16 11:02:26 -07001799 vkGetBufferMemoryRequirements(demo->device, demo->swapchain_image_resources[i].uniform_buffer, &mem_reqs);
Dominik Witczak2fe1c702015-09-22 18:25:33 +02001800
Tony Barboura72d9492017-01-11 13:35:09 -07001801 mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1802 mem_alloc.pNext = NULL;
1803 mem_alloc.allocationSize = mem_reqs.size;
1804 mem_alloc.memoryTypeIndex = 0;
1805
Dave Houlton5fa47912018-02-16 11:02:26 -07001806 pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits,
1807 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
1808 &mem_alloc.memoryTypeIndex);
Tony Barboura72d9492017-01-11 13:35:09 -07001809 assert(pass);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001810
Dave Houlton5fa47912018-02-16 11:02:26 -07001811 err = vkAllocateMemory(demo->device, &mem_alloc, NULL, &demo->swapchain_image_resources[i].uniform_memory);
Tony Barboura72d9492017-01-11 13:35:09 -07001812 assert(!err);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001813
Tony-LunarG37af49f2019-12-19 12:04:19 -07001814 err = vkMapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, 0, VK_WHOLE_SIZE, 0,
1815 &demo->swapchain_image_resources[i].uniform_memory_ptr);
Tony Barboura72d9492017-01-11 13:35:09 -07001816 assert(!err);
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001817
Tony-LunarG37af49f2019-12-19 12:04:19 -07001818 memcpy(demo->swapchain_image_resources[i].uniform_memory_ptr, &data, sizeof data);
Mark Lobodzinski2dcdfd72015-05-29 09:32:35 -05001819
Tony Barboura72d9492017-01-11 13:35:09 -07001820 err = vkBindBufferMemory(demo->device, demo->swapchain_image_resources[i].uniform_buffer,
Dave Houlton5fa47912018-02-16 11:02:26 -07001821 demo->swapchain_image_resources[i].uniform_memory, 0);
Tony Barboura72d9492017-01-11 13:35:09 -07001822 assert(!err);
1823 }
Courtney Goeltzenleuchter4984d152014-10-28 14:50:30 -06001824}
1825
Karl Schultze4dc75c2016-02-02 15:37:51 -07001826static void demo_prepare_descriptor_layout(struct demo *demo) {
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001827 const VkDescriptorSetLayoutBinding layout_bindings[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001828 [0] =
1829 {
1830 .binding = 0,
1831 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
1832 .descriptorCount = 1,
1833 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
1834 .pImmutableSamplers = NULL,
1835 },
1836 [1] =
1837 {
1838 .binding = 1,
1839 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1840 .descriptorCount = DEMO_TEXTURE_COUNT,
1841 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT,
1842 .pImmutableSamplers = NULL,
1843 },
Chia-I Wua2aa8632015-03-26 15:04:41 +08001844 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001845 const VkDescriptorSetLayoutCreateInfo descriptor_layout = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06001846 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08001847 .pNext = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001848 .bindingCount = 2,
Jon Ashburn238f3432015-12-30 18:01:16 -07001849 .pBindings = layout_bindings,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08001850 };
Tony Barbourfdc2d352015-04-22 09:02:32 -06001851 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001852
Dave Houlton5fa47912018-02-16 11:02:26 -07001853 err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, &demo->desc_layout);
Chia-I Wub58c24a2015-03-26 15:27:55 +08001854 assert(!err);
1855
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05001856 const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = {
Karl Schultze4dc75c2016-02-02 15:37:51 -07001857 .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
1858 .pNext = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001859 .setLayoutCount = 1,
Karl Schultze4dc75c2016-02-02 15:37:51 -07001860 .pSetLayouts = &demo->desc_layout,
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05001861 };
1862
Dave Houlton5fa47912018-02-16 11:02:26 -07001863 err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, &demo->pipeline_layout);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001864 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001865}
1866
Karl Schultze4dc75c2016-02-02 15:37:51 -07001867static void demo_prepare_render_pass(struct demo *demo) {
Tony Barbourdb30e4b2016-10-11 11:41:05 -06001868 // The initial layout for the color and depth attachments will be LAYOUT_UNDEFINED
1869 // because at the start of the renderpass, we don't care about their contents.
1870 // At the start of the subpass, the color attachment's layout will be transitioned
1871 // to LAYOUT_COLOR_ATTACHMENT_OPTIMAL and the depth stencil attachment's layout
1872 // will be transitioned to LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL. At the end of
1873 // the renderpass, the color attachment's layout will be transitioned to
1874 // LAYOUT_PRESENT_SRC_KHR to be ready to present. This is all done as part of
1875 // the renderpass, no barriers are necessary.
Chia-I Wua74c5b22015-07-07 11:50:03 +08001876 const VkAttachmentDescription attachments[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001877 [0] =
1878 {
1879 .format = demo->format,
1880 .flags = 0,
1881 .samples = VK_SAMPLE_COUNT_1_BIT,
1882 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1883 .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
1884 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1885 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1886 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1887 .finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
1888 },
1889 [1] =
1890 {
1891 .format = demo->depth.format,
1892 .flags = 0,
1893 .samples = VK_SAMPLE_COUNT_1_BIT,
1894 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
1895 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1896 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
1897 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
1898 .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
1899 .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1900 },
Chia-I Wuf973e322015-07-08 13:34:24 +08001901 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001902 const VkAttachmentReference color_reference = {
Dave Houlton5fa47912018-02-16 11:02:26 -07001903 .attachment = 0,
1904 .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001905 };
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001906 const VkAttachmentReference depth_reference = {
1907 .attachment = 1,
1908 .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
1909 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001910 const VkSubpassDescription subpass = {
Chia-I Wua74c5b22015-07-07 11:50:03 +08001911 .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
1912 .flags = 0,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001913 .inputAttachmentCount = 0,
Cody Northrop945bb832015-08-04 11:16:41 -06001914 .pInputAttachments = NULL,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001915 .colorAttachmentCount = 1,
Cody Northrop945bb832015-08-04 11:16:41 -06001916 .pColorAttachments = &color_reference,
1917 .pResolveAttachments = NULL,
Chia-I Wu6555f3f2015-10-26 17:32:47 +08001918 .pDepthStencilAttachment = &depth_reference,
Chia-I Wu3dfc1342015-10-26 20:48:51 +08001919 .preserveAttachmentCount = 0,
Cody Northrop945bb832015-08-04 11:16:41 -06001920 .pPreserveAttachments = NULL,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001921 };
Tony-LunarG495604b2019-06-13 15:32:05 -06001922
1923 VkSubpassDependency attachmentDependencies[2] = {
1924 [0] =
1925 {
1926 // Depth buffer is shared between swapchain images
1927 .srcSubpass = VK_SUBPASS_EXTERNAL,
1928 .dstSubpass = 0,
1929 .srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1930 .dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
1931 .srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1932 .dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
1933 .dependencyFlags = 0,
1934 },
1935 [1] =
1936 {
1937 // Image Layout Transition
1938 .srcSubpass = VK_SUBPASS_EXTERNAL,
1939 .dstSubpass = 0,
1940 .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1941 .dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
1942 .srcAccessMask = 0,
1943 .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT,
1944 .dependencyFlags = 0,
1945 },
1946 };
1947
Chia-I Wuf973e322015-07-08 13:34:24 +08001948 const VkRenderPassCreateInfo rp_info = {
1949 .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
1950 .pNext = NULL,
Tony Barboura860ce12016-11-21 12:56:25 -07001951 .flags = 0,
Chia-I Wua74c5b22015-07-07 11:50:03 +08001952 .attachmentCount = 2,
1953 .pAttachments = attachments,
1954 .subpassCount = 1,
1955 .pSubpasses = &subpass,
Tony-LunarG495604b2019-06-13 15:32:05 -06001956 .dependencyCount = 2,
1957 .pDependencies = attachmentDependencies,
Chia-I Wuf973e322015-07-08 13:34:24 +08001958 };
Chia-I Wua74c5b22015-07-07 11:50:03 +08001959 VkResult U_ASSERT_ONLY err;
Chia-I Wuf973e322015-07-08 13:34:24 +08001960
Chia-I Wu63636062015-10-26 21:10:41 +08001961 err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass);
Chia-I Wuf973e322015-07-08 13:34:24 +08001962 assert(!err);
1963}
1964
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001965static VkShaderModule demo_prepare_shader_module(struct demo *demo, const uint32_t *code, size_t size) {
Chia-I Wu46176f12015-10-31 00:31:16 +08001966 VkShaderModule module;
Courtney Goeltzenleuchtera80a1a92015-06-24 18:24:19 -06001967 VkShaderModuleCreateInfo moduleCreateInfo;
Courtney Goeltzenleuchterd3cdaaf2015-12-17 09:53:29 -07001968 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001969
Courtney Goeltzenleuchtera80a1a92015-06-24 18:24:19 -06001970 moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1971 moduleCreateInfo.pNext = NULL;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001972 moduleCreateInfo.flags = 0;
Courtney Goeltzenleuchtera95e3052015-10-30 15:19:27 -06001973 moduleCreateInfo.codeSize = size;
1974 moduleCreateInfo.pCode = code;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001975
Courtney Goeltzenleuchtera95e3052015-10-30 15:19:27 -06001976 err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module);
1977 assert(!err);
Chia-I Wu46176f12015-10-31 00:31:16 +08001978
1979 return module;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001980}
1981
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001982static void demo_prepare_vs(struct demo *demo) {
1983 const uint32_t vs_code[] = {
1984#include "cube.vert.inc"
1985 };
1986 demo->vert_shader_module = demo_prepare_shader_module(demo, vs_code, sizeof(vs_code));
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001987}
1988
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01001989static void demo_prepare_fs(struct demo *demo) {
1990 const uint32_t fs_code[] = {
1991#include "cube.frag.inc"
1992 };
1993 demo->frag_shader_module = demo_prepare_shader_module(demo, fs_code, sizeof(fs_code));
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06001994}
1995
Karl Schultze4dc75c2016-02-02 15:37:51 -07001996static void demo_prepare_pipeline(struct demo *demo) {
Tony-LunarG8ee48dc2020-05-07 10:02:58 -06001997#define NUM_DYNAMIC_STATES 2 /*Viewport + Scissor*/
1998
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06001999 VkGraphicsPipelineCreateInfo pipeline;
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002000 VkPipelineCacheCreateInfo pipelineCache;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002001 VkPipelineVertexInputStateCreateInfo vi;
Tony Barbour194bf282015-07-10 15:29:03 -06002002 VkPipelineInputAssemblyStateCreateInfo ia;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002003 VkPipelineRasterizationStateCreateInfo rs;
2004 VkPipelineColorBlendStateCreateInfo cb;
2005 VkPipelineDepthStencilStateCreateInfo ds;
2006 VkPipelineViewportStateCreateInfo vp;
2007 VkPipelineMultisampleStateCreateInfo ms;
Tony-LunarG8ee48dc2020-05-07 10:02:58 -06002008 VkDynamicState dynamicStateEnables[NUM_DYNAMIC_STATES];
Karl Schultze4dc75c2016-02-02 15:37:51 -07002009 VkPipelineDynamicStateCreateInfo dynamicState;
Tony Barbourfdc2d352015-04-22 09:02:32 -06002010 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002011
Piers Daniellba839d12015-09-29 13:01:09 -06002012 memset(dynamicStateEnables, 0, sizeof dynamicStateEnables);
2013 memset(&dynamicState, 0, sizeof dynamicState);
2014 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
2015 dynamicState.pDynamicStates = dynamicStateEnables;
2016
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002017 memset(&pipeline, 0, sizeof(pipeline));
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002018 pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
Mark Lobodzinski1cfc7722015-04-17 14:11:39 -05002019 pipeline.layout = demo->pipeline_layout;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002020
Jason Ekstrand515b7ae2015-10-15 17:15:25 -07002021 memset(&vi, 0, sizeof(vi));
2022 vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
2023
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002024 memset(&ia, 0, sizeof(ia));
Tony Barbour194bf282015-07-10 15:29:03 -06002025 ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
Tony Barbour72304ef2015-04-16 15:59:00 -06002026 ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002027
2028 memset(&rs, 0, sizeof(rs));
Chia-I Wuf051d262015-10-27 19:25:11 +08002029 rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
2030 rs.polygonMode = VK_POLYGON_MODE_FILL;
Chia-I Wu6555f3f2015-10-26 17:32:47 +08002031 rs.cullMode = VK_CULL_MODE_BACK_BIT;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002032 rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
Courtney Goeltzenleuchter0db2c912015-10-15 12:57:38 -06002033 rs.depthClampEnable = VK_FALSE;
Cody Northrop709c1742015-08-17 11:10:49 -06002034 rs.rasterizerDiscardEnable = VK_FALSE;
2035 rs.depthBiasEnable = VK_FALSE;
Mark Young8749e2e2016-03-31 14:56:43 -06002036 rs.lineWidth = 1.0f;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002037
2038 memset(&cb, 0, sizeof(cb));
Tony Barbour194bf282015-07-10 15:29:03 -06002039 cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
2040 VkPipelineColorBlendAttachmentState att_state[1];
Tony Barbour29645d02015-01-16 14:27:35 -07002041 memset(att_state, 0, sizeof(att_state));
Chia-I Wuf051d262015-10-27 19:25:11 +08002042 att_state[0].colorWriteMask = 0xf;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002043 att_state[0].blendEnable = VK_FALSE;
Tony Barbour29645d02015-01-16 14:27:35 -07002044 cb.attachmentCount = 1;
2045 cb.pAttachments = att_state;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002046
Tony Barbour29645d02015-01-16 14:27:35 -07002047 memset(&vp, 0, sizeof(vp));
Tony Barbour194bf282015-07-10 15:29:03 -06002048 vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
Tony Barbour72304ef2015-04-16 15:59:00 -06002049 vp.viewportCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002050 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_VIEWPORT;
Piers Daniellba839d12015-09-29 13:01:09 -06002051 vp.scissorCount = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002052 dynamicStateEnables[dynamicState.dynamicStateCount++] = VK_DYNAMIC_STATE_SCISSOR;
Tony Barbour29645d02015-01-16 14:27:35 -07002053
2054 memset(&ds, 0, sizeof(ds));
Tony Barbour194bf282015-07-10 15:29:03 -06002055 ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002056 ds.depthTestEnable = VK_TRUE;
2057 ds.depthWriteEnable = VK_TRUE;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002058 ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
Cody Northrop5e4125d2015-08-26 10:01:32 -06002059 ds.depthBoundsTestEnable = VK_FALSE;
Chia-I Wuf051d262015-10-27 19:25:11 +08002060 ds.back.failOp = VK_STENCIL_OP_KEEP;
2061 ds.back.passOp = VK_STENCIL_OP_KEEP;
2062 ds.back.compareOp = VK_COMPARE_OP_ALWAYS;
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002063 ds.stencilTestEnable = VK_FALSE;
Tony Barbour29645d02015-01-16 14:27:35 -07002064 ds.front = ds.back;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002065
Tony Barbour29645d02015-01-16 14:27:35 -07002066 memset(&ms, 0, sizeof(ms));
Tony Barbour194bf282015-07-10 15:29:03 -06002067 ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
Cody Northrop011546b2015-08-04 14:34:54 -06002068 ms.pSampleMask = NULL;
Chia-I Wu3ede9462015-10-31 00:31:16 +08002069 ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002070
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002071 demo_prepare_vs(demo);
2072 demo_prepare_fs(demo);
2073
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002074 // Two stages: vs and fs
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002075 VkPipelineShaderStageCreateInfo shaderStages[2];
2076 memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo));
2077
Karl Schultze4dc75c2016-02-02 15:37:51 -07002078 shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2079 shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002080 shaderStages[0].module = demo->vert_shader_module;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002081 shaderStages[0].pName = "main";
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002082
Karl Schultze4dc75c2016-02-02 15:37:51 -07002083 shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
2084 shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002085 shaderStages[1].module = demo->frag_shader_module;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002086 shaderStages[1].pName = "main";
Mark Lobodzinski521d7762015-06-23 15:11:57 -06002087
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002088 memset(&pipelineCache, 0, sizeof(pipelineCache));
2089 pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002090
Dave Houlton5fa47912018-02-16 11:02:26 -07002091 err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, &demo->pipelineCache);
Jon Ashburnc4ab7af2015-07-09 15:02:25 -06002092 assert(!err);
Tony Barbour194bf282015-07-10 15:29:03 -06002093
Karl Schultze4dc75c2016-02-02 15:37:51 -07002094 pipeline.pVertexInputState = &vi;
Tony Barbour194bf282015-07-10 15:29:03 -06002095 pipeline.pInputAssemblyState = &ia;
Karl Schultze4dc75c2016-02-02 15:37:51 -07002096 pipeline.pRasterizationState = &rs;
2097 pipeline.pColorBlendState = &cb;
2098 pipeline.pMultisampleState = &ms;
2099 pipeline.pViewportState = &vp;
2100 pipeline.pDepthStencilState = &ds;
Petr Kraus9a4eb6a2017-11-30 14:49:20 +01002101 pipeline.stageCount = ARRAY_SIZE(shaderStages);
Karl Schultze4dc75c2016-02-02 15:37:51 -07002102 pipeline.pStages = shaderStages;
2103 pipeline.renderPass = demo->render_pass;
2104 pipeline.pDynamicState = &dynamicState;
Tony Barbour194bf282015-07-10 15:29:03 -06002105
Courtney Goeltzenleuchterd311fd02015-08-13 16:55:04 -06002106 pipeline.renderPass = demo->render_pass;
2107
Dave Houlton5fa47912018-02-16 11:02:26 -07002108 err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, &pipeline, NULL, &demo->pipeline);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002109 assert(!err);
2110
Chia-I Wu63636062015-10-26 21:10:41 +08002111 vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL);
2112 vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002113}
2114
Karl Schultze4dc75c2016-02-02 15:37:51 -07002115static void demo_prepare_descriptor_pool(struct demo *demo) {
Chia-I Wuf051d262015-10-27 19:25:11 +08002116 const VkDescriptorPoolSize type_counts[2] = {
Dave Houlton5fa47912018-02-16 11:02:26 -07002117 [0] =
2118 {
2119 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
2120 .descriptorCount = demo->swapchainImageCount,
2121 },
2122 [1] =
2123 {
2124 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2125 .descriptorCount = demo->swapchainImageCount * DEMO_TEXTURE_COUNT,
2126 },
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002127 };
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06002128 const VkDescriptorPoolCreateInfo descriptor_pool = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06002129 .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002130 .pNext = NULL,
Tony Barboura72d9492017-01-11 13:35:09 -07002131 .maxSets = demo->swapchainImageCount,
Chia-I Wuf051d262015-10-27 19:25:11 +08002132 .poolSizeCount = 2,
2133 .pPoolSizes = type_counts,
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002134 };
Tony Barbourfdc2d352015-04-22 09:02:32 -06002135 VkResult U_ASSERT_ONLY err;
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002136
Dave Houlton5fa47912018-02-16 11:02:26 -07002137 err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, &demo->desc_pool);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002138 assert(!err);
2139}
2140
Karl Schultze4dc75c2016-02-02 15:37:51 -07002141static void demo_prepare_descriptor_set(struct demo *demo) {
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002142 VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT];
Chia-I Wuae721ba2015-05-25 16:27:55 +08002143 VkWriteDescriptorSet writes[2];
Tony Barbourfdc2d352015-04-22 09:02:32 -06002144 VkResult U_ASSERT_ONLY err;
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002145
Dave Houlton5fa47912018-02-16 11:02:26 -07002146 VkDescriptorSetAllocateInfo alloc_info = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
2147 .pNext = NULL,
2148 .descriptorPool = demo->desc_pool,
2149 .descriptorSetCount = 1,
2150 .pSetLayouts = &demo->desc_layout};
Tony Barboura72d9492017-01-11 13:35:09 -07002151
2152 VkDescriptorBufferInfo buffer_info;
2153 buffer_info.offset = 0;
2154 buffer_info.range = sizeof(struct vktexcube_vs_uniform);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002155
Chia-I Wuae721ba2015-05-25 16:27:55 +08002156 memset(&tex_descs, 0, sizeof(tex_descs));
Karl Schultza2615462017-01-20 13:19:20 -07002157 for (unsigned int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002158 tex_descs[i].sampler = demo->textures[i].sampler;
2159 tex_descs[i].imageView = demo->textures[i].view;
Karl Schultze88bc842018-09-11 16:23:14 -06002160 tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002161 }
2162
2163 memset(&writes, 0, sizeof(writes));
2164
2165 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
Chia-I Wu3dfc1342015-10-26 20:48:51 +08002166 writes[0].descriptorCount = 1;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002167 writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
Tony Barboura72d9492017-01-11 13:35:09 -07002168 writes[0].pBufferInfo = &buffer_info;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002169
2170 writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002171 writes[1].dstBinding = 1;
Chia-I Wu3dfc1342015-10-26 20:48:51 +08002172 writes[1].descriptorCount = DEMO_TEXTURE_COUNT;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002173 writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
Courtney Goeltzenleuchterc3ad65e2015-10-23 13:38:14 -06002174 writes[1].pImageInfo = tex_descs;
Chia-I Wuae721ba2015-05-25 16:27:55 +08002175
Tony Barboura72d9492017-01-11 13:35:09 -07002176 for (unsigned int i = 0; i < demo->swapchainImageCount; i++) {
2177 err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->swapchain_image_resources[i].descriptor_set);
2178 assert(!err);
2179 buffer_info.buffer = demo->swapchain_image_resources[i].uniform_buffer;
2180 writes[0].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2181 writes[1].dstSet = demo->swapchain_image_resources[i].descriptor_set;
2182 vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL);
2183 }
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002184}
2185
Karl Schultze4dc75c2016-02-02 15:37:51 -07002186static void demo_prepare_framebuffers(struct demo *demo) {
Courtney Goeltzenleuchter41866db2015-09-01 17:30:39 -06002187 VkImageView attachments[2];
Cody Northrop2e11cad2015-08-04 10:47:08 -06002188 attachments[1] = demo->depth.view;
2189
Chia-I Wuf973e322015-07-08 13:34:24 +08002190 const VkFramebufferCreateInfo fb_info = {
Karl Schultze4dc75c2016-02-02 15:37:51 -07002191 .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
2192 .pNext = NULL,
2193 .renderPass = demo->render_pass,
2194 .attachmentCount = 2,
2195 .pAttachments = attachments,
2196 .width = demo->width,
2197 .height = demo->height,
2198 .layers = 1,
Chia-I Wuf973e322015-07-08 13:34:24 +08002199 };
2200 VkResult U_ASSERT_ONLY err;
2201 uint32_t i;
2202
Tony Barbourd8e504f2015-10-08 14:26:24 -06002203 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002204 attachments[0] = demo->swapchain_image_resources[i].view;
Dave Houlton5fa47912018-02-16 11:02:26 -07002205 err = vkCreateFramebuffer(demo->device, &fb_info, NULL, &demo->swapchain_image_resources[i].framebuffer);
Chia-I Wuf973e322015-07-08 13:34:24 +08002206 assert(!err);
2207 }
2208}
2209
Karl Schultze4dc75c2016-02-02 15:37:51 -07002210static void demo_prepare(struct demo *demo) {
Cody Northrop91e221b2015-07-09 18:08:32 -06002211 VkResult U_ASSERT_ONLY err;
Jeremy Kniager602e4182018-01-19 10:52:34 -07002212 if (demo->cmd_pool == VK_NULL_HANDLE) {
2213 const VkCommandPoolCreateInfo cmd_pool_info = {
2214 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2215 .pNext = NULL,
2216 .queueFamilyIndex = demo->graphics_queue_family_index,
2217 .flags = 0,
2218 };
2219 err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, &demo->cmd_pool);
2220 assert(!err);
2221 }
Cody Northrop91e221b2015-07-09 18:08:32 -06002222
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002223 const VkCommandBufferAllocateInfo cmd = {
Chia-I Wuf48700b2015-11-10 16:21:09 +08002224 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002225 .pNext = NULL,
Chia-I Wua8fe78a2015-10-27 18:04:07 +08002226 .commandPool = demo->cmd_pool,
2227 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
Jon Ashburn0bec67e2016-01-11 13:12:43 -07002228 .commandBufferCount = 1,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002229 };
Tony Barbour6db4fcb2016-10-19 13:41:16 -06002230 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd);
2231 assert(!err);
2232 VkCommandBufferBeginInfo cmd_buf_info = {
2233 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
2234 .pNext = NULL,
2235 .flags = 0,
2236 .pInheritanceInfo = NULL,
2237 };
2238 err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info);
2239 assert(!err);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002240
2241 demo_prepare_buffers(demo);
Jeremy Kniager602e4182018-01-19 10:52:34 -07002242
2243 if (demo->is_minimized) {
2244 demo->prepared = false;
2245 return;
2246 }
2247
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002248 demo_prepare_depth(demo);
2249 demo_prepare_textures(demo);
Tony Barboura72d9492017-01-11 13:35:09 -07002250 demo_prepare_cube_data_buffers(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002251
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002252 demo_prepare_descriptor_layout(demo);
Chia-I Wuf973e322015-07-08 13:34:24 +08002253 demo_prepare_render_pass(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002254 demo_prepare_pipeline(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002255
Ian Elliotta0781972015-08-21 15:09:33 -06002256 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002257 err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->swapchain_image_resources[i].cmd);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002258 assert(!err);
2259 }
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002260
Tony Barbour22e06272016-09-07 16:07:56 -06002261 if (demo->separate_present_queue) {
Karl Schultza2615462017-01-20 13:19:20 -07002262 const VkCommandPoolCreateInfo present_cmd_pool_info = {
Tony Barbour22e06272016-09-07 16:07:56 -06002263 .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
2264 .pNext = NULL,
2265 .queueFamilyIndex = demo->present_queue_family_index,
2266 .flags = 0,
2267 };
Dave Houlton5fa47912018-02-16 11:02:26 -07002268 err = vkCreateCommandPool(demo->device, &present_cmd_pool_info, NULL, &demo->present_cmd_pool);
Tony Barbour22e06272016-09-07 16:07:56 -06002269 assert(!err);
Karl Schultza2615462017-01-20 13:19:20 -07002270 const VkCommandBufferAllocateInfo present_cmd_info = {
Tony Barbour22e06272016-09-07 16:07:56 -06002271 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
2272 .pNext = NULL,
2273 .commandPool = demo->present_cmd_pool,
2274 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
2275 .commandBufferCount = 1,
2276 };
2277 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002278 err = vkAllocateCommandBuffers(demo->device, &present_cmd_info,
2279 &demo->swapchain_image_resources[i].graphics_to_present_cmd);
Tony Barbour22e06272016-09-07 16:07:56 -06002280 assert(!err);
2281 demo_build_image_ownership_cmd(demo, i);
2282 }
2283 }
2284
Chia-I Wu63ea9262015-03-26 13:14:16 +08002285 demo_prepare_descriptor_pool(demo);
Chia-I Wu6a3c8972015-01-04 16:27:24 +08002286 demo_prepare_descriptor_set(demo);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002287
Chia-I Wuf973e322015-07-08 13:34:24 +08002288 demo_prepare_framebuffers(demo);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002289
Ian Elliotta0781972015-08-21 15:09:33 -06002290 for (uint32_t i = 0; i < demo->swapchainImageCount; i++) {
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002291 demo->current_buffer = i;
Tony Barboura72d9492017-01-11 13:35:09 -07002292 demo_draw_build_cmd(demo, demo->swapchain_image_resources[i].cmd);
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002293 }
2294
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06002295 /*
2296 * Prepare functions above may generate pipeline commands
2297 * that need to be flushed before beginning the render loop.
2298 */
2299 demo_flush_init_cmd(demo);
Tony-LunarGbc9fc052018-09-21 13:47:06 -06002300 if (demo->staging_texture.buffer) {
2301 demo_destroy_texture(demo, &demo->staging_texture);
Tony Barbour16156cb2016-10-19 14:15:49 -06002302 }
Courtney Goeltzenleuchter752eb8e2015-03-25 13:36:41 -06002303
Courtney Goeltzenleuchterefc58ae2015-02-17 09:48:44 -07002304 demo->current_buffer = 0;
Mike Stroyanbb60b382015-10-28 09:46:57 -06002305 demo->prepared = true;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002306}
2307
Karl Schultze4dc75c2016-02-02 15:37:51 -07002308static void demo_cleanup(struct demo *demo) {
David Pinedo2bb7c932015-06-18 17:03:14 -06002309 uint32_t i;
2310
2311 demo->prepared = false;
Tony Barbource7524e2016-07-28 12:01:45 -06002312 vkDeviceWaitIdle(demo->device);
David Pinedo2bb7c932015-06-18 17:03:14 -06002313
Tony Barbour66a56c32016-09-21 13:10:56 -06002314 // Wait for fences from present operations
2315 for (i = 0; i < FRAME_LAG; i++) {
szdarkhackd322ff02016-10-08 09:51:22 +03002316 vkWaitForFences(demo->device, 1, &demo->fences[i], VK_TRUE, UINT64_MAX);
Tony Barbour66a56c32016-09-21 13:10:56 -06002317 vkDestroyFence(demo->device, demo->fences[i], NULL);
2318 vkDestroySemaphore(demo->device, demo->image_acquired_semaphores[i], NULL);
2319 vkDestroySemaphore(demo->device, demo->draw_complete_semaphores[i], NULL);
2320 if (demo->separate_present_queue) {
2321 vkDestroySemaphore(demo->device, demo->image_ownership_semaphores[i], NULL);
2322 }
2323 }
2324
Jeremy Kniager602e4182018-01-19 10:52:34 -07002325 // If the window is currently minimized, demo_resize has already done some cleanup for us.
2326 if (!demo->is_minimized) {
2327 for (i = 0; i < demo->swapchainImageCount; i++) {
2328 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
2329 }
2330 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
Chia-I Wuf973e322015-07-08 13:34:24 +08002331
Jeremy Kniager602e4182018-01-19 10:52:34 -07002332 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2333 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2334 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2335 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2336 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002337
Jeremy Kniager602e4182018-01-19 10:52:34 -07002338 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
2339 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2340 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2341 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2342 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
2343 }
2344 demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002345
Jeremy Kniager602e4182018-01-19 10:52:34 -07002346 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2347 vkDestroyImage(demo->device, demo->depth.image, NULL);
2348 vkFreeMemory(demo->device, demo->depth.mem, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002349
Jeremy Kniager602e4182018-01-19 10:52:34 -07002350 for (i = 0; i < demo->swapchainImageCount; i++) {
2351 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
2352 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
2353 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002354 vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
Jeremy Kniager602e4182018-01-19 10:52:34 -07002355 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
2356 }
2357 free(demo->swapchain_image_resources);
2358 free(demo->queue_props);
2359 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
Tony Barbour66a56c32016-09-21 13:10:56 -06002360
Jeremy Kniager602e4182018-01-19 10:52:34 -07002361 if (demo->separate_present_queue) {
2362 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2363 }
Tony Barbour22e06272016-09-07 16:07:56 -06002364 }
Tony Barbourffa9a422016-11-10 16:45:15 -07002365 vkDeviceWaitIdle(demo->device);
Chia-I Wu63636062015-10-26 21:10:41 +08002366 vkDestroyDevice(demo->device, NULL);
Tony Barbourd70b42c2015-06-30 14:14:19 -06002367 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07002368 demo->DestroyDebugUtilsMessengerEXT(demo->inst, demo->dbg_messenger, NULL);
Tony Barbourd70b42c2015-06-30 14:14:19 -06002369 }
Ian Elliottb08e0d92015-11-20 11:55:46 -07002370 vkDestroySurfaceKHR(demo->inst, demo->surface, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002371
Tony Barbour153cb062016-12-07 13:43:36 -07002372#if defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour78d6b572016-11-14 14:46:33 -07002373 XDestroyWindow(demo->display, demo->xlib_window);
2374 XCloseDisplay(demo->display);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002375#elif defined(VK_USE_PLATFORM_XCB_KHR)
Pavol Klacansky573a19d2016-05-10 03:08:19 -06002376 xcb_destroy_window(demo->connection, demo->xcb_window);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002377 xcb_disconnect(demo->connection);
2378 free(demo->atom_wm_delete_window);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002379#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdek15eb0702017-06-07 09:40:36 -06002380 wl_keyboard_destroy(demo->keyboard);
2381 wl_pointer_destroy(demo->pointer);
2382 wl_seat_destroy(demo->seat);
Manuel Stoecklac939332019-06-26 20:55:53 -04002383 xdg_toplevel_destroy(demo->xdg_toplevel);
2384 xdg_surface_destroy(demo->xdg_surface);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002385 wl_surface_destroy(demo->window);
Manuel Stoecklac939332019-06-26 20:55:53 -04002386 xdg_wm_base_destroy(demo->xdg_wm_base);
2387 if (demo->xdg_decoration_mgr) {
2388 zxdg_toplevel_decoration_v1_destroy(demo->toplevel_decoration);
2389 zxdg_decoration_manager_v1_destroy(demo->xdg_decoration_mgr);
2390 }
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002391 wl_compositor_destroy(demo->compositor);
2392 wl_registry_destroy(demo->registry);
2393 wl_display_disconnect(demo->display);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002394#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2395 demo->event_buffer->Release(demo->event_buffer);
2396 demo->window->Release(demo->window);
2397 demo->dfb->Release(demo->dfb);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002398#endif
Karl Schultz86429112017-06-20 11:27:59 -06002399
2400 vkDestroyInstance(demo->inst, NULL);
David Pinedo2bb7c932015-06-18 17:03:14 -06002401}
2402
Karl Schultze4dc75c2016-02-02 15:37:51 -07002403static void demo_resize(struct demo *demo) {
Ian Elliottcf074d32015-10-16 18:02:43 -06002404 uint32_t i;
2405
Mike Stroyanbb60b382015-10-28 09:46:57 -06002406 // Don't react to resize until after first initialization.
2407 if (!demo->prepared) {
Jeremy Kniager602e4182018-01-19 10:52:34 -07002408 if (demo->is_minimized) {
2409 demo_prepare(demo);
2410 }
Mike Stroyanbb60b382015-10-28 09:46:57 -06002411 return;
2412 }
Ian Elliottcf074d32015-10-16 18:02:43 -06002413 // In order to properly resize the window, we must re-create the swapchain
2414 // AND redo the command buffers, etc.
2415 //
2416 // First, perform part of the demo_cleanup() function:
2417 demo->prepared = false;
Tony Barbource7524e2016-07-28 12:01:45 -06002418 vkDeviceWaitIdle(demo->device);
Ian Elliottcf074d32015-10-16 18:02:43 -06002419
2420 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002421 vkDestroyFramebuffer(demo->device, demo->swapchain_image_resources[i].framebuffer, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002422 }
Chia-I Wu63636062015-10-26 21:10:41 +08002423 vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002424
Chia-I Wu63636062015-10-26 21:10:41 +08002425 vkDestroyPipeline(demo->device, demo->pipeline, NULL);
2426 vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL);
2427 vkDestroyRenderPass(demo->device, demo->render_pass, NULL);
2428 vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL);
2429 vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002430
2431 for (i = 0; i < DEMO_TEXTURE_COUNT; i++) {
Chia-I Wu63636062015-10-26 21:10:41 +08002432 vkDestroyImageView(demo->device, demo->textures[i].view, NULL);
2433 vkDestroyImage(demo->device, demo->textures[i].image, NULL);
2434 vkFreeMemory(demo->device, demo->textures[i].mem, NULL);
2435 vkDestroySampler(demo->device, demo->textures[i].sampler, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002436 }
Ian Elliottcf074d32015-10-16 18:02:43 -06002437
Chia-I Wu63636062015-10-26 21:10:41 +08002438 vkDestroyImageView(demo->device, demo->depth.view, NULL);
2439 vkDestroyImage(demo->device, demo->depth.image, NULL);
2440 vkFreeMemory(demo->device, demo->depth.mem, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002441
Ian Elliottcf074d32015-10-16 18:02:43 -06002442 for (i = 0; i < demo->swapchainImageCount; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07002443 vkDestroyImageView(demo->device, demo->swapchain_image_resources[i].view, NULL);
Dave Houlton5fa47912018-02-16 11:02:26 -07002444 vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, &demo->swapchain_image_resources[i].cmd);
Tony Barboura72d9492017-01-11 13:35:09 -07002445 vkDestroyBuffer(demo->device, demo->swapchain_image_resources[i].uniform_buffer, NULL);
Tony-LunarG37af49f2019-12-19 12:04:19 -07002446 vkUnmapMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory);
Tony Barboura72d9492017-01-11 13:35:09 -07002447 vkFreeMemory(demo->device, demo->swapchain_image_resources[i].uniform_memory, NULL);
Ian Elliottcf074d32015-10-16 18:02:43 -06002448 }
Chia-I Wu63636062015-10-26 21:10:41 +08002449 vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL);
Jeremy Kniager602e4182018-01-19 10:52:34 -07002450 demo->cmd_pool = VK_NULL_HANDLE;
Tony Barbour22e06272016-09-07 16:07:56 -06002451 if (demo->separate_present_queue) {
2452 vkDestroyCommandPool(demo->device, demo->present_cmd_pool, NULL);
2453 }
Tony Barboura72d9492017-01-11 13:35:09 -07002454 free(demo->swapchain_image_resources);
Ian Elliottcf074d32015-10-16 18:02:43 -06002455
Ian Elliottcf074d32015-10-16 18:02:43 -06002456 // Second, re-perform the demo_prepare() function, which will re-create the
2457 // swapchain:
2458 demo_prepare(demo);
2459}
2460
David Pinedo2bb7c932015-06-18 17:03:14 -06002461// On MS-Windows, make this a global, so it's available to WndProc()
2462struct demo demo;
2463
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002464#if defined(VK_USE_PLATFORM_WIN32_KHR)
Karl Schultze4dc75c2016-02-02 15:37:51 -07002465static void demo_run(struct demo *demo) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002466 if (!demo->prepared) return;
Tony Barbource7524e2016-07-28 12:01:45 -06002467
Ian Elliott639ca472015-04-16 15:23:05 -06002468 demo_draw(demo);
David Pinedo2bb7c932015-06-18 17:03:14 -06002469 demo->curFrame++;
Petr Krausd88e4e52019-01-23 18:45:04 +01002470 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
Karl Schultz8a663912016-03-24 18:43:41 -06002471 PostQuitMessage(validation_error);
David Pinedo2bb7c932015-06-18 17:03:14 -06002472 }
David Pinedo2bb7c932015-06-18 17:03:14 -06002473}
Ian Elliott639ca472015-04-16 15:23:05 -06002474
2475// MS-Windows event handling function:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002476LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
2477 switch (uMsg) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002478 case WM_CLOSE:
2479 PostQuitMessage(validation_error);
2480 break;
2481 case WM_PAINT:
2482 // The validation callback calls MessageBox which can generate paint
2483 // events - don't make more Vulkan calls if we got here from the
2484 // callback
2485 if (!in_callback) {
2486 demo_run(&demo);
2487 }
2488 break;
2489 case WM_GETMINMAXINFO: // set window's minimum size
2490 ((MINMAXINFO *)lParam)->ptMinTrackSize = demo.minsize;
2491 return 0;
Aaron Hagan500b9c32018-10-03 21:56:29 -04002492 case WM_ERASEBKGND:
2493 return 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07002494 case WM_SIZE:
2495 // Resize the application to the new window size, except when
2496 // it was minimized. Vulkan doesn't support images or swapchains
2497 // with width=0 and height=0.
2498 if (wParam != SIZE_MINIMIZED) {
2499 demo.width = lParam & 0xffff;
2500 demo.height = (lParam & 0xffff0000) >> 16;
2501 demo_resize(&demo);
2502 }
2503 break;
Petr Krausd88e4e52019-01-23 18:45:04 +01002504 case WM_KEYDOWN:
2505 switch (wParam) {
2506 case VK_ESCAPE:
2507 PostQuitMessage(validation_error);
2508 break;
2509 case VK_LEFT:
2510 demo.spin_angle -= demo.spin_increment;
2511 break;
2512 case VK_RIGHT:
2513 demo.spin_angle += demo.spin_increment;
2514 break;
2515 case VK_SPACE:
2516 demo.pause = !demo.pause;
2517 break;
2518 }
2519 return 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002520 default:
2521 break;
Ian Elliott639ca472015-04-16 15:23:05 -06002522 }
2523 return (DefWindowProc(hWnd, uMsg, wParam, lParam));
2524}
2525
Karl Schultze4dc75c2016-02-02 15:37:51 -07002526static void demo_create_window(struct demo *demo) {
2527 WNDCLASSEX win_class;
Ian Elliott639ca472015-04-16 15:23:05 -06002528
2529 // Initialize the window class structure:
2530 win_class.cbSize = sizeof(WNDCLASSEX);
2531 win_class.style = CS_HREDRAW | CS_VREDRAW;
2532 win_class.lpfnWndProc = WndProc;
2533 win_class.cbClsExtra = 0;
2534 win_class.cbWndExtra = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002535 win_class.hInstance = demo->connection; // hInstance
Ian Elliott639ca472015-04-16 15:23:05 -06002536 win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
2537 win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
2538 win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
2539 win_class.lpszMenuName = NULL;
2540 win_class.lpszClassName = demo->name;
2541 win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
2542 // Register window class:
2543 if (!RegisterClassEx(&win_class)) {
2544 // It didn't work, so try to give a useful error:
2545 printf("Unexpected error trying to start the application!\n");
2546 fflush(stdout);
2547 exit(1);
2548 }
2549 // Create window with the registered class:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002550 RECT wr = {0, 0, demo->width, demo->height};
Mike Stroyanb46779e2015-06-15 14:20:13 -06002551 AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
Ian Elliott639ca472015-04-16 15:23:05 -06002552 demo->window = CreateWindowEx(0,
Dave Houlton5fa47912018-02-16 11:02:26 -07002553 demo->name, // class name
2554 demo->name, // app name
2555 WS_OVERLAPPEDWINDOW | // window style
Karl Schultze4dc75c2016-02-02 15:37:51 -07002556 WS_VISIBLE | WS_SYSMENU,
Dave Houlton5fa47912018-02-16 11:02:26 -07002557 100, 100, // x/y coords
2558 wr.right - wr.left, // width
2559 wr.bottom - wr.top, // height
2560 NULL, // handle to parent
2561 NULL, // handle to menu
2562 demo->connection, // hInstance
2563 NULL); // no extra parameters
Ian Elliott639ca472015-04-16 15:23:05 -06002564 if (!demo->window) {
2565 // It didn't work, so try to give a useful error:
2566 printf("Cannot create a window in which to draw!\n");
2567 fflush(stdout);
2568 exit(1);
2569 }
Rene Lindsayb9403da2016-07-01 18:00:30 -06002570 // Window client area size must be at least 1 pixel high, to prevent crash.
2571 demo->minsize.x = GetSystemMetrics(SM_CXMINTRACK);
Dave Houlton5fa47912018-02-16 11:02:26 -07002572 demo->minsize.y = GetSystemMetrics(SM_CYMINTRACK) + 1;
Ian Elliott639ca472015-04-16 15:23:05 -06002573}
Tony Barbour8295ac42016-08-08 11:04:17 -06002574#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Tony Barbour2593b182016-04-19 10:57:58 -06002575static void demo_create_xlib_window(struct demo *demo) {
Mike Weiblen5d2ad542018-02-13 13:56:13 -07002576 const char *display_envar = getenv("DISPLAY");
2577 if (display_envar == NULL || display_envar[0] == '\0') {
2578 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
2579 fflush(stdout);
2580 exit(1);
2581 }
Tony Barbour2593b182016-04-19 10:57:58 -06002582
Tony Barbouree9cd372017-01-31 16:09:58 -07002583 XInitThreads();
Tony Barbour2593b182016-04-19 10:57:58 -06002584 demo->display = XOpenDisplay(NULL);
2585 long visualMask = VisualScreenMask;
2586 int numberOfVisuals;
Dave Houlton5fa47912018-02-16 11:02:26 -07002587 XVisualInfo vInfoTemplate = {};
Tony Barbour2593b182016-04-19 10:57:58 -06002588 vInfoTemplate.screen = DefaultScreen(demo->display);
Dave Houlton5fa47912018-02-16 11:02:26 -07002589 XVisualInfo *visualInfo = XGetVisualInfo(demo->display, visualMask, &vInfoTemplate, &numberOfVisuals);
Tony Barbour2593b182016-04-19 10:57:58 -06002590
Dave Houlton5fa47912018-02-16 11:02:26 -07002591 Colormap colormap =
2592 XCreateColormap(demo->display, RootWindow(demo->display, vInfoTemplate.screen), visualInfo->visual, AllocNone);
Tony Barbour2593b182016-04-19 10:57:58 -06002593
Dave Houlton5fa47912018-02-16 11:02:26 -07002594 XSetWindowAttributes windowAttributes = {};
Tony Barbour2593b182016-04-19 10:57:58 -06002595 windowAttributes.colormap = colormap;
2596 windowAttributes.background_pixel = 0xFFFFFFFF;
2597 windowAttributes.border_pixel = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07002598 windowAttributes.event_mask = KeyPressMask | KeyReleaseMask | StructureNotifyMask | ExposureMask;
Tony Barbour2593b182016-04-19 10:57:58 -06002599
Dave Houlton5fa47912018-02-16 11:02:26 -07002600 demo->xlib_window = XCreateWindow(demo->display, RootWindow(demo->display, vInfoTemplate.screen), 0, 0, demo->width,
2601 demo->height, 0, visualInfo->depth, InputOutput, visualInfo->visual,
2602 CWBackPixel | CWBorderPixel | CWEventMask | CWColormap, &windowAttributes);
Tony Barbour2593b182016-04-19 10:57:58 -06002603
2604 XSelectInput(demo->display, demo->xlib_window, ExposureMask | KeyPressMask);
2605 XMapWindow(demo->display, demo->xlib_window);
2606 XFlush(demo->display);
Dave Houlton5fa47912018-02-16 11:02:26 -07002607 demo->xlib_wm_delete_window = XInternAtom(demo->display, "WM_DELETE_WINDOW", False);
Tony Barbour2593b182016-04-19 10:57:58 -06002608}
2609static void demo_handle_xlib_event(struct demo *demo, const XEvent *event) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002610 switch (event->type) {
2611 case ClientMessage:
2612 if ((Atom)event->xclient.data.l[0] == demo->xlib_wm_delete_window) demo->quit = true;
Tony Barbour2593b182016-04-19 10:57:58 -06002613 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002614 case KeyPress:
2615 switch (event->xkey.keycode) {
2616 case 0x9: // Escape
2617 demo->quit = true;
2618 break;
2619 case 0x71: // left arrow key
2620 demo->spin_angle -= demo->spin_increment;
2621 break;
2622 case 0x72: // right arrow key
2623 demo->spin_angle += demo->spin_increment;
2624 break;
2625 case 0x41: // space bar
2626 demo->pause = !demo->pause;
2627 break;
2628 }
Tony Barbour2593b182016-04-19 10:57:58 -06002629 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002630 case ConfigureNotify:
2631 if ((demo->width != event->xconfigure.width) || (demo->height != event->xconfigure.height)) {
2632 demo->width = event->xconfigure.width;
2633 demo->height = event->xconfigure.height;
2634 demo_resize(demo);
2635 }
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002636 break;
Dave Houlton5fa47912018-02-16 11:02:26 -07002637 default:
Tony Barbour2593b182016-04-19 10:57:58 -06002638 break;
Tony Barbour2593b182016-04-19 10:57:58 -06002639 }
Tony Barbour2593b182016-04-19 10:57:58 -06002640}
2641
2642static void demo_run_xlib(struct demo *demo) {
Tony Barbour2593b182016-04-19 10:57:58 -06002643 while (!demo->quit) {
2644 XEvent event;
2645
2646 if (demo->pause) {
2647 XNextEvent(demo->display, &event);
2648 demo_handle_xlib_event(demo, &event);
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002649 }
2650 while (XPending(demo->display) > 0) {
2651 XNextEvent(demo->display, &event);
2652 demo_handle_xlib_event(demo, &event);
Tony Barbour2593b182016-04-19 10:57:58 -06002653 }
2654
Tony Barbour2593b182016-04-19 10:57:58 -06002655 demo_draw(demo);
Tony Barbour2593b182016-04-19 10:57:58 -06002656 demo->curFrame++;
Dave Houlton5fa47912018-02-16 11:02:26 -07002657 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
Tony Barbour2593b182016-04-19 10:57:58 -06002658 }
2659}
Tony Barbour153cb062016-12-07 13:43:36 -07002660#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07002661static void demo_handle_xcb_event(struct demo *demo, const xcb_generic_event_t *event) {
Piers Daniell735ee532015-02-23 16:23:13 -07002662 uint8_t event_code = event->response_type & 0x7f;
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002663 switch (event_code) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002664 case XCB_EXPOSE:
2665 // TODO: Resize window
2666 break;
2667 case XCB_CLIENT_MESSAGE:
2668 if ((*(xcb_client_message_event_t *)event).data.data32[0] == (*demo->atom_wm_delete_window).atom) {
2669 demo->quit = true;
2670 }
2671 break;
2672 case XCB_KEY_RELEASE: {
2673 const xcb_key_release_event_t *key = (const xcb_key_release_event_t *)event;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002674
Dave Houlton5fa47912018-02-16 11:02:26 -07002675 switch (key->detail) {
2676 case 0x9: // Escape
2677 demo->quit = true;
2678 break;
2679 case 0x71: // left arrow key
2680 demo->spin_angle -= demo->spin_increment;
2681 break;
2682 case 0x72: // right arrow key
2683 demo->spin_angle += demo->spin_increment;
2684 break;
2685 case 0x41: // space bar
2686 demo->pause = !demo->pause;
2687 break;
2688 }
2689 } break;
2690 case XCB_CONFIGURE_NOTIFY: {
2691 const xcb_configure_notify_event_t *cfg = (const xcb_configure_notify_event_t *)event;
2692 if ((demo->width != cfg->width) || (demo->height != cfg->height)) {
2693 demo->width = cfg->width;
2694 demo->height = cfg->height;
2695 demo_resize(demo);
2696 }
2697 } break;
2698 default:
Karl Schultze4dc75c2016-02-02 15:37:51 -07002699 break;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002700 }
2701}
2702
Tony Barbour2593b182016-04-19 10:57:58 -06002703static void demo_run_xcb(struct demo *demo) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002704 xcb_flush(demo->connection);
2705
2706 while (!demo->quit) {
2707 xcb_generic_event_t *event;
2708
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002709 if (demo->pause) {
2710 event = xcb_wait_for_event(demo->connection);
Dave Houlton5fa47912018-02-16 11:02:26 -07002711 } else {
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002712 event = xcb_poll_for_event(demo->connection);
Karl Schultz6ddf1e02017-01-04 10:31:20 -07002713 }
2714 while (event) {
2715 demo_handle_xcb_event(demo, event);
2716 free(event);
2717 event = xcb_poll_for_event(demo->connection);
Courtney Goeltzenleuchter98085552014-11-10 11:13:13 -07002718 }
Courtney Goeltzenleuchterc465d6c2014-11-18 11:28:09 -07002719
Courtney Goeltzenleuchter98085552014-11-10 11:13:13 -07002720 demo_draw(demo);
David Pinedo2bb7c932015-06-18 17:03:14 -06002721 demo->curFrame++;
Dave Houlton5fa47912018-02-16 11:02:26 -07002722 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002723 }
2724}
2725
Tony Barbour2593b182016-04-19 10:57:58 -06002726static void demo_create_xcb_window(struct demo *demo) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002727 uint32_t value_mask, value_list[32];
2728
Tony Barbour2593b182016-04-19 10:57:58 -06002729 demo->xcb_window = xcb_generate_id(demo->connection);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002730
2731 value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK;
2732 value_list[0] = demo->screen->black_pixel;
Dave Houlton5fa47912018-02-16 11:02:26 -07002733 value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002734
Dave Houlton5fa47912018-02-16 11:02:26 -07002735 xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->xcb_window, demo->screen->root, 0, 0, demo->width, demo->height,
2736 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, value_mask, value_list);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002737
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002738 /* Magic code that will send notification when window is destroyed */
Dave Houlton5fa47912018-02-16 11:02:26 -07002739 xcb_intern_atom_cookie_t cookie = xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS");
2740 xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(demo->connection, cookie, 0);
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002741
Dave Houlton5fa47912018-02-16 11:02:26 -07002742 xcb_intern_atom_cookie_t cookie2 = xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW");
2743 demo->atom_wm_delete_window = xcb_intern_atom_reply(demo->connection, cookie2, 0);
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002744
Dave Houlton5fa47912018-02-16 11:02:26 -07002745 xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->xcb_window, (*reply).atom, 4, 32, 1,
Courtney Goeltzenleuchter98cb2cb2014-11-06 14:27:52 -07002746 &(*demo->atom_wm_delete_window).atom);
2747 free(reply);
2748
Tony Barbour2593b182016-04-19 10:57:58 -06002749 xcb_map_window(demo->connection, demo->xcb_window);
David Pinedo2bb7c932015-06-18 17:03:14 -06002750
Karl Schultze4dc75c2016-02-02 15:37:51 -07002751 // Force the x/y coordinates to 100,100 results are identical in consecutive
2752 // runs
2753 const uint32_t coords[] = {100, 100};
Dave Houlton5fa47912018-02-16 11:02:26 -07002754 xcb_configure_window(demo->connection, demo->xcb_window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06002755}
Tony Barbour6b131662016-08-25 13:14:45 -06002756// VK_USE_PLATFORM_XCB_KHR
2757#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002758static void demo_run(struct demo *demo) {
2759 while (!demo->quit) {
Joey Bzdek15eb0702017-06-07 09:40:36 -06002760 if (demo->pause) {
2761 wl_display_dispatch(demo->display); // block and wait for input
Joey Bzdek33bc5c82017-06-14 10:33:36 -06002762 } else {
Joey Bzdek15eb0702017-06-07 09:40:36 -06002763 wl_display_dispatch_pending(demo->display); // don't block
2764 demo_draw(demo);
2765 demo->curFrame++;
2766 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2767 }
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002768 }
2769}
2770
Manuel Stoecklac939332019-06-26 20:55:53 -04002771static void handle_surface_configure(void *data, struct xdg_surface *xdg_surface, uint32_t serial) {
2772 struct demo *demo = (struct demo *)data;
2773 xdg_surface_ack_configure(xdg_surface, serial);
2774 if (demo->xdg_surface_has_been_configured) {
2775 demo_resize(demo);
2776 }
2777 demo->xdg_surface_has_been_configured = 1;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002778}
2779
Manuel Stoecklac939332019-06-26 20:55:53 -04002780static const struct xdg_surface_listener xdg_surface_listener = {handle_surface_configure};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002781
Manuel Stoecklac939332019-06-26 20:55:53 -04002782static void handle_toplevel_configure(void *data, struct xdg_toplevel *xdg_toplevel UNUSED, int32_t width, int32_t height,
2783 struct wl_array *states UNUSED) {
2784 struct demo *demo = (struct demo *)data;
2785 /* zero values imply the program may choose its own size, so in that case
2786 * stay with the existing value (which on startup is the default) */
2787 if (width > 0) {
2788 demo->width = width;
2789 }
2790 if (height > 0) {
2791 demo->height = height;
2792 }
2793 /* This should be followed by a surface configure */
2794}
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002795
Manuel Stoecklac939332019-06-26 20:55:53 -04002796static void handle_toplevel_close(void *data, struct xdg_toplevel *xdg_toplevel UNUSED) {
2797 struct demo *demo = (struct demo *)data;
2798 demo->quit = true;
2799}
2800
2801static const struct xdg_toplevel_listener xdg_toplevel_listener = {handle_toplevel_configure, handle_toplevel_close};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002802
2803static void demo_create_window(struct demo *demo) {
Manuel Stoecklac939332019-06-26 20:55:53 -04002804 if (!demo->xdg_wm_base) {
2805 printf("Compositor did not provide the standard protocol xdg-wm-base\n");
2806 fflush(stdout);
2807 exit(1);
2808 }
2809
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002810 demo->window = wl_compositor_create_surface(demo->compositor);
2811 if (!demo->window) {
2812 printf("Can not create wayland_surface from compositor!\n");
2813 fflush(stdout);
2814 exit(1);
2815 }
2816
Manuel Stoecklac939332019-06-26 20:55:53 -04002817 demo->xdg_surface = xdg_wm_base_get_xdg_surface(demo->xdg_wm_base, demo->window);
2818 if (!demo->xdg_surface) {
2819 printf("Can not get xdg_surface from wayland_surface!\n");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002820 fflush(stdout);
2821 exit(1);
2822 }
Manuel Stoecklac939332019-06-26 20:55:53 -04002823 demo->xdg_toplevel = xdg_surface_get_toplevel(demo->xdg_surface);
2824 if (!demo->xdg_toplevel) {
2825 printf("Can not allocate xdg_toplevel for xdg_surface!\n");
2826 fflush(stdout);
2827 exit(1);
2828 }
2829 xdg_surface_add_listener(demo->xdg_surface, &xdg_surface_listener, demo);
2830 xdg_toplevel_add_listener(demo->xdg_toplevel, &xdg_toplevel_listener, demo);
2831 xdg_toplevel_set_title(demo->xdg_toplevel, APP_SHORT_NAME);
2832 if (demo->xdg_decoration_mgr) {
2833 // if supported, let the compositor render titlebars for us
2834 demo->toplevel_decoration =
2835 zxdg_decoration_manager_v1_get_toplevel_decoration(demo->xdg_decoration_mgr, demo->xdg_toplevel);
2836 zxdg_toplevel_decoration_v1_set_mode(demo->toplevel_decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE);
2837 }
2838
2839 wl_surface_commit(demo->window);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09002840}
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002841#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
2842static void demo_create_directfb_window(struct demo *demo) {
2843 DFBResult ret;
2844
2845 ret = DirectFBInit(NULL, NULL);
2846 if (ret) {
2847 printf("DirectFBInit failed to initialize DirectFB!\n");
2848 fflush(stdout);
2849 exit(1);
2850 }
2851
2852 ret = DirectFBCreate(&demo->dfb);
2853 if (ret) {
2854 printf("DirectFBCreate failed to create main interface of DirectFB!\n");
2855 fflush(stdout);
2856 exit(1);
2857 }
2858
2859 DFBSurfaceDescription desc;
2860 desc.flags = DSDESC_CAPS | DSDESC_WIDTH | DSDESC_HEIGHT;
2861 desc.caps = DSCAPS_PRIMARY;
2862 desc.width = demo->width;
2863 desc.height = demo->height;
2864 ret = demo->dfb->CreateSurface(demo->dfb, &desc, &demo->window);
2865 if (ret) {
2866 printf("CreateSurface failed to create DirectFB surface interface!\n");
2867 fflush(stdout);
2868 exit(1);
2869 }
2870
2871 ret = demo->dfb->CreateInputEventBuffer(demo->dfb, DICAPS_KEYS, DFB_FALSE, &demo->event_buffer);
2872 if (ret) {
2873 printf("CreateInputEventBuffer failed to create DirectFB event buffer interface!\n");
2874 fflush(stdout);
2875 exit(1);
2876 }
2877}
2878
2879static void demo_handle_directfb_event(struct demo *demo, const DFBInputEvent *event) {
2880 if (event->type != DIET_KEYPRESS) return;
2881 switch (event->key_symbol) {
2882 case DIKS_ESCAPE: // Escape
2883 demo->quit = true;
2884 break;
2885 case DIKS_CURSOR_LEFT: // left arrow key
2886 demo->spin_angle -= demo->spin_increment;
2887 break;
2888 case DIKS_CURSOR_RIGHT: // right arrow key
2889 demo->spin_angle += demo->spin_increment;
2890 break;
2891 case DIKS_SPACE: // space bar
2892 demo->pause = !demo->pause;
2893 break;
2894 default:
2895 break;
2896 }
2897}
2898
2899static void demo_run_directfb(struct demo *demo) {
2900 while (!demo->quit) {
2901 DFBInputEvent event;
2902
2903 if (demo->pause) {
2904 demo->event_buffer->WaitForEvent(demo->event_buffer);
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002905 if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002906 } else {
Nicolas Caramelli6d4f1c62020-07-13 18:10:07 +02002907 if (!demo->event_buffer->GetEvent(demo->event_buffer, DFB_EVENT(&event))) demo_handle_directfb_event(demo, &event);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02002908
2909 demo_draw(demo);
2910 demo->curFrame++;
2911 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) demo->quit = true;
2912 }
2913 }
2914}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002915#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
2916static void demo_run(struct demo *demo) {
Dave Houlton5fa47912018-02-16 11:02:26 -07002917 if (!demo->prepared) return;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002918
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002919 demo_draw(demo);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05002920 demo->curFrame++;
2921}
Bill Hollings0a0625a2019-07-15 17:39:18 -04002922#elif defined(VK_USE_PLATFORM_METAL_EXT)
Karl Schultz206b1c52018-04-13 18:02:07 -06002923static void demo_run(struct demo *demo) {
2924 demo_draw(demo);
2925 demo->curFrame++;
2926 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
2927 demo->quit = TRUE;
2928 }
2929}
Damien Leone600c3052017-01-31 10:26:07 -07002930#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
2931static VkResult demo_create_display_surface(struct demo *demo) {
2932 VkResult U_ASSERT_ONLY err;
2933 uint32_t display_count;
2934 uint32_t mode_count;
2935 uint32_t plane_count;
2936 VkDisplayPropertiesKHR display_props;
2937 VkDisplayKHR display;
2938 VkDisplayModePropertiesKHR mode_props;
2939 VkDisplayPlanePropertiesKHR *plane_props;
2940 VkBool32 found_plane = VK_FALSE;
2941 uint32_t plane_index;
2942 VkExtent2D image_extent;
2943 VkDisplaySurfaceCreateInfoKHR create_info;
2944
2945 // Get the first display
Damien Leone600c3052017-01-31 10:26:07 -07002946 display_count = 1;
2947 err = vkGetPhysicalDeviceDisplayPropertiesKHR(demo->gpu, &display_count, &display_props);
2948 assert(!err || (err == VK_INCOMPLETE));
2949
2950 display = display_props.display;
2951
2952 // Get the first mode of the display
2953 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, NULL);
2954 assert(!err);
2955
2956 if (mode_count == 0) {
2957 printf("Cannot find any mode for the display!\n");
2958 fflush(stdout);
2959 exit(1);
2960 }
2961
2962 mode_count = 1;
2963 err = vkGetDisplayModePropertiesKHR(demo->gpu, display, &mode_count, &mode_props);
2964 assert(!err || (err == VK_INCOMPLETE));
2965
2966 // Get the list of planes
2967 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, NULL);
2968 assert(!err);
2969
2970 if (plane_count == 0) {
2971 printf("Cannot find any plane!\n");
2972 fflush(stdout);
2973 exit(1);
2974 }
2975
2976 plane_props = malloc(sizeof(VkDisplayPlanePropertiesKHR) * plane_count);
2977 assert(plane_props);
2978
2979 err = vkGetPhysicalDeviceDisplayPlanePropertiesKHR(demo->gpu, &plane_count, plane_props);
2980 assert(!err);
2981
2982 // Find a plane compatible with the display
2983 for (plane_index = 0; plane_index < plane_count; plane_index++) {
2984 uint32_t supported_count;
2985 VkDisplayKHR *supported_displays;
2986
2987 // Disqualify planes that are bound to a different display
Dave Houlton5fa47912018-02-16 11:02:26 -07002988 if ((plane_props[plane_index].currentDisplay != VK_NULL_HANDLE) && (plane_props[plane_index].currentDisplay != display)) {
Damien Leone600c3052017-01-31 10:26:07 -07002989 continue;
2990 }
2991
2992 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, NULL);
2993 assert(!err);
2994
2995 if (supported_count == 0) {
2996 continue;
2997 }
2998
2999 supported_displays = malloc(sizeof(VkDisplayKHR) * supported_count);
3000 assert(supported_displays);
3001
3002 err = vkGetDisplayPlaneSupportedDisplaysKHR(demo->gpu, plane_index, &supported_count, supported_displays);
3003 assert(!err);
3004
3005 for (uint32_t i = 0; i < supported_count; i++) {
3006 if (supported_displays[i] == display) {
3007 found_plane = VK_TRUE;
3008 break;
3009 }
3010 }
3011
3012 free(supported_displays);
3013
3014 if (found_plane) {
3015 break;
3016 }
3017 }
3018
3019 if (!found_plane) {
3020 printf("Cannot find a plane compatible with the display!\n");
3021 fflush(stdout);
3022 exit(1);
3023 }
3024
3025 free(plane_props);
3026
Tony Barbour820b55b2017-03-14 08:55:46 -06003027 VkDisplayPlaneCapabilitiesKHR planeCaps;
3028 vkGetDisplayPlaneCapabilitiesKHR(demo->gpu, mode_props.displayMode, plane_index, &planeCaps);
3029 // Find a supported alpha mode
Tony-LunarGa6e40812021-06-15 13:14:06 -06003030 VkDisplayPlaneAlphaFlagBitsKHR alphaMode = VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR;
3031 VkDisplayPlaneAlphaFlagBitsKHR alphaModes[4] = {
Tony Barbour820b55b2017-03-14 08:55:46 -06003032 VK_DISPLAY_PLANE_ALPHA_OPAQUE_BIT_KHR,
3033 VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR,
3034 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_BIT_KHR,
3035 VK_DISPLAY_PLANE_ALPHA_PER_PIXEL_PREMULTIPLIED_BIT_KHR,
3036 };
3037 for (uint32_t i = 0; i < sizeof(alphaModes); i++) {
3038 if (planeCaps.supportedAlpha & alphaModes[i]) {
3039 alphaMode = alphaModes[i];
3040 break;
3041 }
3042 }
Damien Leone600c3052017-01-31 10:26:07 -07003043 image_extent.width = mode_props.parameters.visibleRegion.width;
3044 image_extent.height = mode_props.parameters.visibleRegion.height;
3045
3046 create_info.sType = VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR;
3047 create_info.pNext = NULL;
3048 create_info.flags = 0;
3049 create_info.displayMode = mode_props.displayMode;
3050 create_info.planeIndex = plane_index;
3051 create_info.planeStackIndex = plane_props[plane_index].currentStackIndex;
3052 create_info.transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Tony Barbour820b55b2017-03-14 08:55:46 -06003053 create_info.alphaMode = alphaMode;
Damien Leone600c3052017-01-31 10:26:07 -07003054 create_info.globalAlpha = 1.0f;
3055 create_info.imageExtent = image_extent;
3056
3057 return vkCreateDisplayPlaneSurfaceKHR(demo->inst, &create_info, NULL, &demo->surface);
3058}
3059
Dave Houlton5fa47912018-02-16 11:02:26 -07003060static void demo_run_display(struct demo *demo) {
Damien Leone600c3052017-01-31 10:26:07 -07003061 while (!demo->quit) {
3062 demo_draw(demo);
3063 demo->curFrame++;
3064
3065 if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) {
3066 demo->quit = true;
3067 }
3068 }
3069}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003070#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003071
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003072/*
3073 * Return 1 (true) if all layer names specified in check_names
3074 * can be found in given layer properties.
3075 */
Dave Houlton5fa47912018-02-16 11:02:26 -07003076static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, uint32_t layer_count, VkLayerProperties *layers) {
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003077 for (uint32_t i = 0; i < check_count; i++) {
Courtney Goeltzenleuchterc88ce512015-07-09 11:44:38 -06003078 VkBool32 found = 0;
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003079 for (uint32_t j = 0; j < layer_count; j++) {
3080 if (!strcmp(check_names[i], layers[j].layerName)) {
3081 found = 1;
Dustin Graves7c287352016-01-27 13:48:06 -07003082 break;
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003083 }
3084 }
3085 if (!found) {
3086 fprintf(stderr, "Cannot find layer: %s\n", check_names[i]);
3087 return 0;
3088 }
3089 }
3090 return 1;
3091}
Tony-LunarG27c21242021-03-11 16:28:19 -07003092#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
3093int find_display_gpu(int gpu_number, uint32_t gpu_count, VkPhysicalDevice *physical_devices) {
3094 uint32_t display_count = 0;
3095 VkResult result;
3096 int gpu_return = gpu_number;
3097 if (gpu_number >= 0) {
3098 result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[gpu_number], &display_count, NULL);
3099 assert(!result);
3100 } else {
3101 for (uint32_t i = 0; i < gpu_count; i++) {
3102 result = vkGetPhysicalDeviceDisplayPropertiesKHR(physical_devices[i], &display_count, NULL);
3103 assert(!result);
3104 if (display_count) {
3105 gpu_return = i;
3106 break;
3107 }
3108 }
3109 }
3110 if (display_count > 0)
3111 return gpu_return;
3112 else
3113 return -1;
3114}
3115#endif
Karl Schultze4dc75c2016-02-02 15:37:51 -07003116static void demo_init_vk(struct demo *demo) {
Tobin Ehlis99239dc2015-04-16 18:04:57 -06003117 VkResult err;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003118 uint32_t instance_extension_count = 0;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003119 uint32_t instance_layer_count = 0;
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003120 char *instance_validation_layers[] = {"VK_LAYER_KHRONOS_validation"};
Karl Schultz7c50ad62016-04-01 12:07:03 -06003121 demo->enabled_extension_count = 0;
3122 demo->enabled_layer_count = 0;
Jeremy Kniager602e4182018-01-19 10:52:34 -07003123 demo->is_minimized = false;
3124 demo->cmd_pool = VK_NULL_HANDLE;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003125
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003126 // Look for validation layers
Courtney Goeltzenleuchterc88ce512015-07-09 11:44:38 -06003127 VkBool32 validation_found = 0;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003128 if (demo->validate) {
Karl Schultz7c50ad62016-04-01 12:07:03 -06003129 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL);
Dustin Graves7c287352016-01-27 13:48:06 -07003130 assert(!err);
Courtney Goeltzenleuchter886f76c2015-07-06 17:46:11 -06003131
Karl Schultz7c50ad62016-04-01 12:07:03 -06003132 if (instance_layer_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003133 VkLayerProperties *instance_layers = malloc(sizeof(VkLayerProperties) * instance_layer_count);
3134 err = vkEnumerateInstanceLayerProperties(&instance_layer_count, instance_layers);
Karl Schultz7c50ad62016-04-01 12:07:03 -06003135 assert(!err);
Dustin Graves7c287352016-01-27 13:48:06 -07003136
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003137 validation_found = demo_check_layers(ARRAY_SIZE(instance_validation_layers), instance_validation_layers,
Dave Houlton5fa47912018-02-16 11:02:26 -07003138 instance_layer_count, instance_layers);
Karl Schultz7c50ad62016-04-01 12:07:03 -06003139 if (validation_found) {
Mark Lobodzinski96f2ff32019-03-27 12:37:30 -06003140 demo->enabled_layer_count = ARRAY_SIZE(instance_validation_layers);
3141 demo->enabled_layers[0] = "VK_LAYER_KHRONOS_validation";
Karl Schultz7c50ad62016-04-01 12:07:03 -06003142 }
3143 free(instance_layers);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003144 }
Dustin Graves7c287352016-01-27 13:48:06 -07003145
Karl Schultz7c50ad62016-04-01 12:07:03 -06003146 if (!validation_found) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003147 ERR_EXIT(
3148 "vkEnumerateInstanceLayerProperties failed to find required validation layer.\n\n"
3149 "Please look at the Getting Started guide for additional information.\n",
3150 "vkCreateInstance Failure");
Karl Schultz7c50ad62016-04-01 12:07:03 -06003151 }
Dustin Graves7c287352016-01-27 13:48:06 -07003152 }
3153
3154 /* Look for instance extensions */
3155 VkBool32 surfaceExtFound = 0;
3156 VkBool32 platformSurfaceExtFound = 0;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003157 memset(demo->extension_names, 0, sizeof(demo->extension_names));
Dustin Graves7c287352016-01-27 13:48:06 -07003158
Dave Houlton5fa47912018-02-16 11:02:26 -07003159 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003160 assert(!err);
3161
Dustin Graves7c287352016-01-27 13:48:06 -07003162 if (instance_extension_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003163 VkExtensionProperties *instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
3164 err = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
Dustin Graves7c287352016-01-27 13:48:06 -07003165 assert(!err);
3166 for (uint32_t i = 0; i < instance_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003167 if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003168 surfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003169 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003170 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003171#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003172 if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003173 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003174 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003175 }
Tony Barbour153cb062016-12-07 13:43:36 -07003176#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003177 if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Tony Barbour2593b182016-04-19 10:57:58 -06003178 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003179 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
Tony Barbour2593b182016-04-19 10:57:58 -06003180 }
Tony Barbour153cb062016-12-07 13:43:36 -07003181#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003182 if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003183 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003184 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003185 }
Tony Barbour153cb062016-12-07 13:43:36 -07003186#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003187 if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003188 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003189 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003190 }
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003191#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3192 if (!strcmp(VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3193 platformSurfaceExtFound = 1;
3194 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME;
3195 }
Damien Leone600c3052017-01-31 10:26:07 -07003196#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003197 if (!strcmp(VK_KHR_DISPLAY_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Damien Leone600c3052017-01-31 10:26:07 -07003198 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003199 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_DISPLAY_EXTENSION_NAME;
Damien Leone600c3052017-01-31 10:26:07 -07003200 }
Tony Barbour153cb062016-12-07 13:43:36 -07003201#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003202 if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003203 platformSurfaceExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003204 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003205 }
Bill Hollings0a0625a2019-07-15 17:39:18 -04003206#elif defined(VK_USE_PLATFORM_METAL_EXT)
3207 if (!strcmp(VK_EXT_METAL_SURFACE_EXTENSION_NAME, instance_extensions[i].extensionName)) {
Bill Hollingsf4352142017-02-14 22:58:56 -05003208 platformSurfaceExtFound = 1;
Bill Hollings0a0625a2019-07-15 17:39:18 -04003209 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_METAL_SURFACE_EXTENSION_NAME;
Bill Hollingsf4352142017-02-14 22:58:56 -05003210 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003211#endif
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05003212 if (!strcmp(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3213 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME;
3214 }
Mark Young66510e52017-11-10 10:05:14 -07003215 if (!strcmp(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instance_extensions[i].extensionName)) {
3216 if (demo->validate) {
3217 demo->extension_names[demo->enabled_extension_count++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME;
3218 }
3219 }
Karl Schultz7c50ad62016-04-01 12:07:03 -06003220 assert(demo->enabled_extension_count < 64);
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003221 }
Dustin Graves7c287352016-01-27 13:48:06 -07003222
3223 free(instance_extensions);
Tobin Ehlis99239dc2015-04-16 18:04:57 -06003224 }
Dustin Graves7c287352016-01-27 13:48:06 -07003225
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003226 if (!surfaceExtFound) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003227 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_SURFACE_EXTENSION_NAME
3228 " extension.\n\n"
3229 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3230 "Please look at the Getting Started guide for additional information.\n",
Ian Elliott65152912015-04-28 13:22:33 -06003231 "vkCreateInstance Failure");
3232 }
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003233 if (!platformSurfaceExtFound) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003234#if defined(VK_USE_PLATFORM_WIN32_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003235 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME
3236 " extension.\n\n"
3237 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3238 "Please look at the Getting Started guide for additional information.\n",
Ian Elliottd3f7dcc2015-11-20 13:08:34 -07003239 "vkCreateInstance Failure");
Bill Hollings0a0625a2019-07-15 17:39:18 -04003240#elif defined(VK_USE_PLATFORM_METAL_EXT)
3241 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_METAL_SURFACE_EXTENSION_NAME
Dave Houlton5fa47912018-02-16 11:02:26 -07003242 " extension.\n\n"
3243 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3244 "Please look at the Getting Started guide for additional information.\n",
Tony Barbourc65cd752017-03-13 15:29:35 -06003245 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003246#elif defined(VK_USE_PLATFORM_XCB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003247 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XCB_SURFACE_EXTENSION_NAME
3248 " extension.\n\n"
3249 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3250 "Please look at the Getting Started guide for additional information.\n",
Mark Lobodzinski6f7a6032015-11-24 12:04:15 -07003251 "vkCreateInstance Failure");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003252#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003253 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME
3254 " extension.\n\n"
3255 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3256 "Please look at the Getting Started guide for additional information.\n",
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003257 "vkCreateInstance Failure");
Damien Leone600c3052017-01-31 10:26:07 -07003258#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003259 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_DISPLAY_EXTENSION_NAME
3260 " extension.\n\n"
3261 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3262 "Please look at the Getting Started guide for additional information.\n",
Damien Leone600c3052017-01-31 10:26:07 -07003263 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003264#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003265 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_ANDROID_SURFACE_EXTENSION_NAME
3266 " extension.\n\n"
3267 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3268 "Please look at the Getting Started guide for additional information.\n",
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003269 "vkCreateInstance Failure");
Tony Barbour153cb062016-12-07 13:43:36 -07003270#elif defined(VK_USE_PLATFORM_XLIB_KHR)
Dave Houlton5fa47912018-02-16 11:02:26 -07003271 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_KHR_XLIB_SURFACE_EXTENSION_NAME
3272 " extension.\n\n"
3273 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3274 "Please look at the Getting Started guide for additional information.\n",
Tony Barbour2593b182016-04-19 10:57:58 -06003275 "vkCreateInstance Failure");
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003276#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3277 ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find the " VK_EXT_DIRECTFB_SURFACE_EXTENSION_NAME
3278 " extension.\n\n"
3279 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3280 "Please look at the Getting Started guide for additional information.\n",
3281 "vkCreateInstance Failure");
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003282#endif
Tony Barbour153cb062016-12-07 13:43:36 -07003283 }
Courtney Goeltzenleuchter78351a62015-04-10 08:34:15 -06003284 const VkApplicationInfo app = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06003285 .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003286 .pNext = NULL,
Chia-I Wua8fe78a2015-10-27 18:04:07 +08003287 .pApplicationName = APP_SHORT_NAME,
3288 .applicationVersion = 0,
Ian Elliott44e33f72015-04-28 10:52:52 -06003289 .pEngineName = APP_SHORT_NAME,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003290 .engineVersion = 0,
Jon Ashburn7f4bc2c2016-03-22 13:57:46 -06003291 .apiVersion = VK_API_VERSION_1_0,
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003292 };
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003293 VkInstanceCreateInfo inst_info = {
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06003294 .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
Jon Ashburnab46b362015-04-04 14:52:07 -06003295 .pNext = NULL,
Chia-I Wua8fe78a2015-10-27 18:04:07 +08003296 .pApplicationInfo = &app,
Karl Schultz7c50ad62016-04-01 12:07:03 -06003297 .enabledLayerCount = demo->enabled_layer_count,
3298 .ppEnabledLayerNames = (const char *const *)instance_validation_layers,
3299 .enabledExtensionCount = demo->enabled_extension_count,
3300 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
Jon Ashburnab46b362015-04-04 14:52:07 -06003301 };
Karl Schultzcd9887d2016-03-25 14:25:16 -06003302
3303 /*
3304 * This is info for a temp callback to use during CreateInstance.
3305 * After the instance is created, we use the instance-based
3306 * function to register the final callback.
3307 */
Mark Young66510e52017-11-10 10:05:14 -07003308 VkDebugUtilsMessengerCreateInfoEXT dbg_messenger_create_info;
Ian Elliott5959bbd2016-03-25 09:07:19 -06003309 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07003310 // VK_EXT_debug_utils style
3311 dbg_messenger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
3312 dbg_messenger_create_info.pNext = NULL;
3313 dbg_messenger_create_info.flags = 0;
3314 dbg_messenger_create_info.messageSeverity =
3315 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
3316 dbg_messenger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
3317 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
3318 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
3319 dbg_messenger_create_info.pfnUserCallback = debug_messenger_callback;
3320 dbg_messenger_create_info.pUserData = demo;
3321 inst_info.pNext = &dbg_messenger_create_info;
Ian Elliott5959bbd2016-03-25 09:07:19 -06003322 }
Ian Elliott097d9f32015-04-28 11:35:02 -06003323
Chia-I Wu63636062015-10-26 21:10:41 +08003324 err = vkCreateInstance(&inst_info, NULL, &demo->inst);
Ian Elliott07264132015-04-28 11:35:02 -06003325 if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003326 ERR_EXIT(
3327 "Cannot find a compatible Vulkan installable client driver (ICD).\n\n"
3328 "Please look at the Getting Started guide for additional information.\n",
3329 "vkCreateInstance Failure");
Courtney Goeltzenleuchter1e47e4b2015-09-14 18:01:17 -06003330 } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003331 ERR_EXIT(
3332 "Cannot find a specified extension library.\n"
3333 "Make sure your layers path is set appropriately.\n",
3334 "vkCreateInstance Failure");
Ian Elliott07264132015-04-28 11:35:02 -06003335 } else if (err) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003336 ERR_EXIT(
3337 "vkCreateInstance failed.\n\n"
3338 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3339 "Please look at the Getting Started guide for additional information.\n",
3340 "vkCreateInstance Failure");
Ian Elliott3979e282015-04-03 15:24:55 -06003341 }
Jon Ashburnab46b362015-04-04 14:52:07 -06003342
Witold Baryluka3b988f2021-01-07 19:03:02 +00003343 /* Make initial call to query gpu_count, then second call for gpu info */
3344 uint32_t gpu_count = 0;
Tobin Ehlis8a724d82015-09-07 15:16:39 -06003345 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL);
Petr Kraus2f1dbdb2018-04-14 14:45:17 +02003346 assert(!err);
Dustin Graves7c287352016-01-27 13:48:06 -07003347
Witold Baryluka3b988f2021-01-07 19:03:02 +00003348 if (gpu_count <= 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003349 ERR_EXIT(
3350 "vkEnumeratePhysicalDevices reported zero accessible devices.\n\n"
3351 "Do you have a compatible Vulkan installable client driver (ICD) installed?\n"
3352 "Please look at the Getting Started guide for additional information.\n",
3353 "vkEnumeratePhysicalDevices Failure");
Dustin Graves7c287352016-01-27 13:48:06 -07003354 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003355
Witold Baryluka3b988f2021-01-07 19:03:02 +00003356 VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count);
3357 err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices);
3358 assert(!err);
3359 if (demo->gpu_number >= 0 && !((uint32_t)demo->gpu_number < gpu_count)) {
3360 fprintf(stderr, "GPU %d specified is not present, GPU count = %u\n", demo->gpu_number, gpu_count);
3361 ERR_EXIT("Specified GPU number is not present", "User Error");
3362 }
3363
Tony-LunarG27c21242021-03-11 16:28:19 -07003364#if defined(VK_USE_PLATFORM_DISPLAY_KHR)
3365 demo->gpu_number = find_display_gpu(demo->gpu_number, gpu_count, physical_devices);
3366 if (demo->gpu_number < 0) {
3367 printf("Cannot find any display!\n");
3368 fflush(stdout);
3369 exit(1);
3370 }
3371#else
Witold Baryluka3b988f2021-01-07 19:03:02 +00003372 /* Try to auto select most suitable device */
3373 if (demo->gpu_number == -1) {
3374 uint32_t count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU + 1];
3375 memset(count_device_type, 0, sizeof(count_device_type));
3376
3377 VkPhysicalDeviceProperties physicalDeviceProperties;
3378 for (uint32_t i = 0; i < gpu_count; i++) {
3379 vkGetPhysicalDeviceProperties(physical_devices[i], &physicalDeviceProperties);
3380 assert(physicalDeviceProperties.deviceType <= VK_PHYSICAL_DEVICE_TYPE_CPU);
3381 count_device_type[physicalDeviceProperties.deviceType]++;
3382 }
3383
3384 VkPhysicalDeviceType search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
3385 if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU]) {
3386 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU;
3387 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU]) {
3388 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
3389 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU]) {
3390 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU;
3391 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_CPU]) {
3392 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_CPU;
3393 } else if (count_device_type[VK_PHYSICAL_DEVICE_TYPE_OTHER]) {
3394 search_for_device_type = VK_PHYSICAL_DEVICE_TYPE_OTHER;
3395 }
3396
3397 for (uint32_t i = 0; i < gpu_count; i++) {
3398 vkGetPhysicalDeviceProperties(physical_devices[i], &physicalDeviceProperties);
3399 if (physicalDeviceProperties.deviceType == search_for_device_type) {
3400 demo->gpu_number = i;
3401 break;
3402 }
3403 }
3404 }
Tony-LunarG27c21242021-03-11 16:28:19 -07003405#endif
Witold Baryluka3b988f2021-01-07 19:03:02 +00003406 assert(demo->gpu_number >= 0);
3407 demo->gpu = physical_devices[demo->gpu_number];
3408 {
3409 VkPhysicalDeviceProperties physicalDeviceProperties;
3410 vkGetPhysicalDeviceProperties(demo->gpu, &physicalDeviceProperties);
3411 fprintf(stderr, "Selected GPU %d: %s, type: %u\n", demo->gpu_number, physicalDeviceProperties.deviceName,
3412 physicalDeviceProperties.deviceType);
3413 }
3414 free(physical_devices);
3415
Dustin Graves7c287352016-01-27 13:48:06 -07003416 /* Look for device extensions */
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003417 uint32_t device_extension_count = 0;
Dustin Graves7c287352016-01-27 13:48:06 -07003418 VkBool32 swapchainExtFound = 0;
3419 demo->enabled_extension_count = 0;
Karl Schultz7c50ad62016-04-01 12:07:03 -06003420 memset(demo->extension_names, 0, sizeof(demo->extension_names));
Dustin Graves7c287352016-01-27 13:48:06 -07003421
Dave Houlton5fa47912018-02-16 11:02:26 -07003422 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, NULL);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003423 assert(!err);
3424
Dustin Graves7c287352016-01-27 13:48:06 -07003425 if (device_extension_count > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003426 VkExtensionProperties *device_extensions = malloc(sizeof(VkExtensionProperties) * device_extension_count);
3427 err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, &device_extension_count, device_extensions);
Dustin Graves7c287352016-01-27 13:48:06 -07003428 assert(!err);
Ian Elliottaaae5352015-07-06 14:27:58 -06003429
Dustin Graves7c287352016-01-27 13:48:06 -07003430 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003431 if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, device_extensions[i].extensionName)) {
Dustin Graves7c287352016-01-27 13:48:06 -07003432 swapchainExtFound = 1;
Dave Houlton5fa47912018-02-16 11:02:26 -07003433 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_SWAPCHAIN_EXTENSION_NAME;
Dustin Graves7c287352016-01-27 13:48:06 -07003434 }
Richard S. Wright Jra7825742021-01-06 16:02:12 -05003435 if (!strcmp("VK_KHR_portability_subset", device_extensions[i].extensionName)) {
3436 demo->extension_names[demo->enabled_extension_count++] = "VK_KHR_portability_subset";
Richard S. Wright Jrca51bc72021-01-06 13:03:18 -05003437 }
Dustin Graves7c287352016-01-27 13:48:06 -07003438 assert(demo->enabled_extension_count < 64);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003439 }
Dustin Graves7c287352016-01-27 13:48:06 -07003440
Ian Elliott53622a72017-03-28 11:06:33 -06003441 if (demo->VK_KHR_incremental_present_enabled) {
3442 // Even though the user "enabled" the extension via the command
3443 // line, we must make sure that it's enumerated for use with the
3444 // device. Therefore, disable it here, and re-enable it again if
3445 // enumerated.
3446 demo->VK_KHR_incremental_present_enabled = false;
3447 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003448 if (!strcmp(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, device_extensions[i].extensionName)) {
3449 demo->extension_names[demo->enabled_extension_count++] = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME;
Ian Elliott53622a72017-03-28 11:06:33 -06003450 demo->VK_KHR_incremental_present_enabled = true;
3451 DbgMsg("VK_KHR_incremental_present extension enabled\n");
3452 }
3453 assert(demo->enabled_extension_count < 64);
3454 }
3455 if (!demo->VK_KHR_incremental_present_enabled) {
3456 DbgMsg("VK_KHR_incremental_present extension NOT AVAILABLE\n");
3457 }
3458 }
3459
Ian Elliottd940ca22017-03-22 08:31:27 -06003460 if (demo->VK_GOOGLE_display_timing_enabled) {
3461 // Even though the user "enabled" the extension via the command
3462 // line, we must make sure that it's enumerated for use with the
3463 // device. Therefore, disable it here, and re-enable it again if
3464 // enumerated.
3465 demo->VK_GOOGLE_display_timing_enabled = false;
3466 for (uint32_t i = 0; i < device_extension_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003467 if (!strcmp(VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME, device_extensions[i].extensionName)) {
3468 demo->extension_names[demo->enabled_extension_count++] = VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
Ian Elliottd940ca22017-03-22 08:31:27 -06003469 demo->VK_GOOGLE_display_timing_enabled = true;
Ian Elliott0c7b3c92017-03-27 14:38:52 -06003470 DbgMsg("VK_GOOGLE_display_timing extension enabled\n");
Ian Elliottd940ca22017-03-22 08:31:27 -06003471 }
3472 assert(demo->enabled_extension_count < 64);
3473 }
3474 if (!demo->VK_GOOGLE_display_timing_enabled) {
Ian Elliott0c7b3c92017-03-27 14:38:52 -06003475 DbgMsg("VK_GOOGLE_display_timing extension NOT AVAILABLE\n");
Ian Elliottd940ca22017-03-22 08:31:27 -06003476 }
3477 }
3478
Dustin Graves7c287352016-01-27 13:48:06 -07003479 free(device_extensions);
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003480 }
Dustin Graves7c287352016-01-27 13:48:06 -07003481
Tony Barbourcc69f452015-10-08 13:59:42 -06003482 if (!swapchainExtFound) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003483 ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find the " VK_KHR_SWAPCHAIN_EXTENSION_NAME
3484 " extension.\n\nDo you have a compatible Vulkan installable client driver (ICD) installed?\n"
3485 "Please look at the Getting Started guide for additional information.\n",
Courtney Goeltzenleuchterbe103362015-06-29 15:39:26 -06003486 "vkCreateInstance Failure");
3487 }
3488
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003489 if (demo->validate) {
Mark Young66510e52017-11-10 10:05:14 -07003490 // Setup VK_EXT_debug_utils function pointers always (we use them for
3491 // debug labels and names).
3492 demo->CreateDebugUtilsMessengerEXT =
3493 (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkCreateDebugUtilsMessengerEXT");
3494 demo->DestroyDebugUtilsMessengerEXT =
3495 (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(demo->inst, "vkDestroyDebugUtilsMessengerEXT");
3496 demo->SubmitDebugUtilsMessageEXT =
3497 (PFN_vkSubmitDebugUtilsMessageEXT)vkGetInstanceProcAddr(demo->inst, "vkSubmitDebugUtilsMessageEXT");
3498 demo->CmdBeginDebugUtilsLabelEXT =
3499 (PFN_vkCmdBeginDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdBeginDebugUtilsLabelEXT");
3500 demo->CmdEndDebugUtilsLabelEXT =
3501 (PFN_vkCmdEndDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdEndDebugUtilsLabelEXT");
3502 demo->CmdInsertDebugUtilsLabelEXT =
3503 (PFN_vkCmdInsertDebugUtilsLabelEXT)vkGetInstanceProcAddr(demo->inst, "vkCmdInsertDebugUtilsLabelEXT");
3504 demo->SetDebugUtilsObjectNameEXT =
3505 (PFN_vkSetDebugUtilsObjectNameEXT)vkGetInstanceProcAddr(demo->inst, "vkSetDebugUtilsObjectNameEXT");
3506 if (NULL == demo->CreateDebugUtilsMessengerEXT || NULL == demo->DestroyDebugUtilsMessengerEXT ||
3507 NULL == demo->SubmitDebugUtilsMessageEXT || NULL == demo->CmdBeginDebugUtilsLabelEXT ||
3508 NULL == demo->CmdEndDebugUtilsLabelEXT || NULL == demo->CmdInsertDebugUtilsLabelEXT ||
3509 NULL == demo->SetDebugUtilsObjectNameEXT) {
3510 ERR_EXIT("GetProcAddr: Failed to init VK_EXT_debug_utils\n", "GetProcAddr: Failure");
Courtney Goeltzenleuchteraf1951c2015-12-01 14:11:38 -07003511 }
Jon Ashburn9549c8e2015-12-15 08:47:46 -07003512
Mark Young66510e52017-11-10 10:05:14 -07003513 err = demo->CreateDebugUtilsMessengerEXT(demo->inst, &dbg_messenger_create_info, NULL, &demo->dbg_messenger);
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003514 switch (err) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003515 case VK_SUCCESS:
3516 break;
3517 case VK_ERROR_OUT_OF_HOST_MEMORY:
Mark Young66510e52017-11-10 10:05:14 -07003518 ERR_EXIT("CreateDebugUtilsMessengerEXT: out of host memory\n", "CreateDebugUtilsMessengerEXT Failure");
Dave Houlton5fa47912018-02-16 11:02:26 -07003519 break;
3520 default:
Mark Young66510e52017-11-10 10:05:14 -07003521 ERR_EXIT("CreateDebugUtilsMessengerEXT: unknown failure\n", "CreateDebugUtilsMessengerEXT Failure");
Dave Houlton5fa47912018-02-16 11:02:26 -07003522 break;
Courtney Goeltzenleuchter922a0fa2015-06-10 17:39:03 -06003523 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003524 }
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003525 vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props);
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003526
3527 /* Call with NULL data to get count */
Dave Houlton5fa47912018-02-16 11:02:26 -07003528 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, NULL);
Tony Barbourab2a0362016-09-06 11:40:12 -06003529 assert(demo->queue_family_count >= 1);
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003530
Dave Houlton5fa47912018-02-16 11:02:26 -07003531 demo->queue_props = (VkQueueFamilyProperties *)malloc(demo->queue_family_count * sizeof(VkQueueFamilyProperties));
3532 vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_family_count, demo->queue_props);
Tony Barbourab2a0362016-09-06 11:40:12 -06003533
Tobin Ehlisbf3020e2015-09-24 15:18:22 -06003534 // Query fine-grained feature support for this device.
Karl Schultze4dc75c2016-02-02 15:37:51 -07003535 // If app has specific feature requirements it should check supported
3536 // features based on this query
Tobin Ehlis8d03b7c2015-09-29 11:22:37 -06003537 VkPhysicalDeviceFeatures physDevFeatures;
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003538 vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures);
Tobin Ehlisbf3020e2015-09-24 15:18:22 -06003539
Tony Barbourda2bad52016-01-22 14:36:40 -07003540 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR);
3541 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR);
3542 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR);
3543 GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR);
3544 GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR);
3545}
3546
Karl Schultze4dc75c2016-02-02 15:37:51 -07003547static void demo_create_device(struct demo *demo) {
Tony Barbourda2bad52016-01-22 14:36:40 -07003548 VkResult U_ASSERT_ONLY err;
Karl Schultze4dc75c2016-02-02 15:37:51 -07003549 float queue_priorities[1] = {0.0};
Tony Barbour22e06272016-09-07 16:07:56 -06003550 VkDeviceQueueCreateInfo queues[2];
3551 queues[0].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3552 queues[0].pNext = NULL;
3553 queues[0].queueFamilyIndex = demo->graphics_queue_family_index;
3554 queues[0].queueCount = 1;
3555 queues[0].pQueuePriorities = queue_priorities;
3556 queues[0].flags = 0;
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003557
3558 VkDeviceCreateInfo device = {
3559 .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
3560 .pNext = NULL,
Chia-I Wu8b497442015-11-06 06:42:02 +08003561 .queueCreateInfoCount = 1,
Tony Barbour22e06272016-09-07 16:07:56 -06003562 .pQueueCreateInfos = queues,
Karl Schultz5b423ea2016-06-20 19:08:43 -06003563 .enabledLayerCount = 0,
3564 .ppEnabledLayerNames = NULL,
Tony Barbourda2bad52016-01-22 14:36:40 -07003565 .enabledExtensionCount = demo->enabled_extension_count,
Karl Schultze4dc75c2016-02-02 15:37:51 -07003566 .ppEnabledExtensionNames = (const char *const *)demo->extension_names,
Dave Houlton5fa47912018-02-16 11:02:26 -07003567 .pEnabledFeatures = NULL, // If specific features are required, pass them in here
Tobin Ehlis9626ba62015-09-22 13:52:37 -06003568 };
Tony Barbour22e06272016-09-07 16:07:56 -06003569 if (demo->separate_present_queue) {
3570 queues[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
3571 queues[1].pNext = NULL;
3572 queues[1].queueFamilyIndex = demo->present_queue_family_index;
3573 queues[1].queueCount = 1;
3574 queues[1].pQueuePriorities = queue_priorities;
3575 queues[1].flags = 0;
3576 device.queueCreateInfoCount = 2;
3577 }
Chia-I Wu63636062015-10-26 21:10:41 +08003578 err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003579 assert(!err);
Courtney Goeltzenleuchter3a35c822015-07-15 17:45:38 -06003580}
3581
Tony-LunarG6cebf142019-09-11 14:32:23 -06003582static void demo_create_surface(struct demo *demo) {
Courtney Goeltzenleuchterd3cdaaf2015-12-17 09:53:29 -07003583 VkResult U_ASSERT_ONLY err;
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003584
Karl Schultze4dc75c2016-02-02 15:37:51 -07003585// Create a WSI surface for the window:
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003586#if defined(VK_USE_PLATFORM_WIN32_KHR)
Ian Elliotta7a731c2015-12-11 15:52:12 -07003587 VkWin32SurfaceCreateInfoKHR createInfo;
3588 createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
3589 createInfo.pNext = NULL;
3590 createInfo.flags = 0;
Jon Ashburnb90f50d2015-12-24 17:08:01 -07003591 createInfo.hinstance = demo->connection;
3592 createInfo.hwnd = demo->window;
Ian Elliotta7a731c2015-12-11 15:52:12 -07003593
Dave Houlton5fa47912018-02-16 11:02:26 -07003594 err = vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003595#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003596 VkWaylandSurfaceCreateInfoKHR createInfo;
3597 createInfo.sType = VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR;
3598 createInfo.pNext = NULL;
3599 createInfo.flags = 0;
3600 createInfo.display = demo->display;
3601 createInfo.surface = demo->window;
3602
Dave Houlton5fa47912018-02-16 11:02:26 -07003603 err = vkCreateWaylandSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003604#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
3605 VkAndroidSurfaceCreateInfoKHR createInfo;
3606 createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
3607 createInfo.pNext = NULL;
3608 createInfo.flags = 0;
Mike Schuchardt837d5162018-03-08 12:57:02 -07003609 createInfo.window = (struct ANativeWindow *)(demo->window);
Ian Elliottb08e0d92015-11-20 11:55:46 -07003610
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003611 err = vkCreateAndroidSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003612#elif defined(VK_USE_PLATFORM_XLIB_KHR)
3613 VkXlibSurfaceCreateInfoKHR createInfo;
3614 createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
3615 createInfo.pNext = NULL;
3616 createInfo.flags = 0;
3617 createInfo.dpy = demo->display;
3618 createInfo.window = demo->xlib_window;
Ian Elliotta7a731c2015-12-11 15:52:12 -07003619
Dave Houlton5fa47912018-02-16 11:02:26 -07003620 err = vkCreateXlibSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Tony Barbour153cb062016-12-07 13:43:36 -07003621#elif defined(VK_USE_PLATFORM_XCB_KHR)
3622 VkXcbSurfaceCreateInfoKHR createInfo;
3623 createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
3624 createInfo.pNext = NULL;
3625 createInfo.flags = 0;
3626 createInfo.connection = demo->connection;
3627 createInfo.window = demo->xcb_window;
Tony Barbour2593b182016-04-19 10:57:58 -06003628
Tony Barbour153cb062016-12-07 13:43:36 -07003629 err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02003630#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
3631 VkDirectFBSurfaceCreateInfoEXT createInfo;
3632 createInfo.sType = VK_STRUCTURE_TYPE_DIRECTFB_SURFACE_CREATE_INFO_EXT;
3633 createInfo.pNext = NULL;
3634 createInfo.flags = 0;
3635 createInfo.dfb = demo->dfb;
3636 createInfo.surface = demo->window;
3637
3638 err = vkCreateDirectFBSurfaceEXT(demo->inst, &createInfo, NULL, &demo->surface);
Damien Leone600c3052017-01-31 10:26:07 -07003639#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
3640 err = demo_create_display_surface(demo);
Bill Hollings0a0625a2019-07-15 17:39:18 -04003641#elif defined(VK_USE_PLATFORM_METAL_EXT)
3642 VkMetalSurfaceCreateInfoEXT surface;
3643 surface.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
Bill Hollingsf4352142017-02-14 22:58:56 -05003644 surface.pNext = NULL;
3645 surface.flags = 0;
Bill Hollings0a0625a2019-07-15 17:39:18 -04003646 surface.pLayer = demo->caMetalLayer;
Bill Hollingsf4352142017-02-14 22:58:56 -05003647
Bill Hollings0a0625a2019-07-15 17:39:18 -04003648 err = vkCreateMetalSurfaceEXT(demo->inst, &surface, NULL, &demo->surface);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003649#endif
Tony Barbour2593b182016-04-19 10:57:58 -06003650 assert(!err);
Tony-LunarG6cebf142019-09-11 14:32:23 -06003651}
3652
Joshua Ashton1fbefe02020-04-02 06:45:48 +01003653static VkSurfaceFormatKHR pick_surface_format(const VkSurfaceFormatKHR *surfaceFormats, uint32_t count) {
3654 // Prefer non-SRGB formats...
3655 for (uint32_t i = 0; i < count; i++) {
3656 const VkFormat format = surfaceFormats[i].format;
3657
3658 if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_B8G8R8A8_UNORM ||
3659 format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || format == VK_FORMAT_A2R10G10B10_UNORM_PACK32 ||
3660 format == VK_FORMAT_R16G16B16A16_SFLOAT) {
3661 return surfaceFormats[i];
3662 }
3663 }
3664
3665 printf("Can't find our preferred formats... Falling back to first exposed format. Rendering may be incorrect.\n");
3666
3667 assert(count >= 1);
3668 return surfaceFormats[0];
3669}
3670
Tony-LunarG6cebf142019-09-11 14:32:23 -06003671static void demo_init_vk_swapchain(struct demo *demo) {
3672 VkResult U_ASSERT_ONLY err;
3673
3674 demo_create_surface(demo);
Ian Elliottaaae5352015-07-06 14:27:58 -06003675
Tony Barbourcc69f452015-10-08 13:59:42 -06003676 // Iterate over each queue to learn whether it supports presenting:
Dave Houlton5fa47912018-02-16 11:02:26 -07003677 VkBool32 *supportsPresent = (VkBool32 *)malloc(demo->queue_family_count * sizeof(VkBool32));
Karl Schultza2615462017-01-20 13:19:20 -07003678 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003679 demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, &supportsPresent[i]);
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003680 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003681
3682 // Search for a graphics and a present queue in the array of queue
3683 // families, try to find one that supports both
Tony Barbourab2a0362016-09-06 11:40:12 -06003684 uint32_t graphicsQueueFamilyIndex = UINT32_MAX;
3685 uint32_t presentQueueFamilyIndex = UINT32_MAX;
Karl Schultza2615462017-01-20 13:19:20 -07003686 for (uint32_t i = 0; i < demo->queue_family_count; i++) {
Tony Barbourab2a0362016-09-06 11:40:12 -06003687 if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) {
3688 if (graphicsQueueFamilyIndex == UINT32_MAX) {
3689 graphicsQueueFamilyIndex = i;
3690 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07003691
Tony Barbourab2a0362016-09-06 11:40:12 -06003692 if (supportsPresent[i] == VK_TRUE) {
3693 graphicsQueueFamilyIndex = i;
3694 presentQueueFamilyIndex = i;
3695 break;
3696 }
3697 }
3698 }
3699
3700 if (presentQueueFamilyIndex == UINT32_MAX) {
3701 // If didn't find a queue that supports both graphics and present, then
3702 // find a separate present queue.
Karl Schultza2615462017-01-20 13:19:20 -07003703 for (uint32_t i = 0; i < demo->queue_family_count; ++i) {
Tony Barbourab2a0362016-09-06 11:40:12 -06003704 if (supportsPresent[i] == VK_TRUE) {
3705 presentQueueFamilyIndex = i;
3706 break;
3707 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003708 }
3709 }
Ian Elliottaaae5352015-07-06 14:27:58 -06003710
3711 // Generate error if could not find both a graphics and a present queue
Dave Houlton5fa47912018-02-16 11:02:26 -07003712 if (graphicsQueueFamilyIndex == UINT32_MAX || presentQueueFamilyIndex == UINT32_MAX) {
3713 ERR_EXIT("Could not find both graphics and present queues\n", "Swapchain Initialization Failure");
Ian Elliottaaae5352015-07-06 14:27:58 -06003714 }
3715
Tony Barbourab2a0362016-09-06 11:40:12 -06003716 demo->graphics_queue_family_index = graphicsQueueFamilyIndex;
3717 demo->present_queue_family_index = presentQueueFamilyIndex;
Dave Houlton5fa47912018-02-16 11:02:26 -07003718 demo->separate_present_queue = (demo->graphics_queue_family_index != demo->present_queue_family_index);
Tony Barbourab2a0362016-09-06 11:40:12 -06003719 free(supportsPresent);
Courtney Goeltzenleuchtered667a52015-03-05 18:09:39 -07003720
Tony Barbourda2bad52016-01-22 14:36:40 -07003721 demo_create_device(demo);
3722
3723 GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR);
3724 GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR);
3725 GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR);
3726 GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR);
3727 GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR);
Ian Elliottd940ca22017-03-22 08:31:27 -06003728 if (demo->VK_GOOGLE_display_timing_enabled) {
3729 GET_DEVICE_PROC_ADDR(demo->device, GetRefreshCycleDurationGOOGLE);
3730 GET_DEVICE_PROC_ADDR(demo->device, GetPastPresentationTimingGOOGLE);
3731 }
Tony Barbourda2bad52016-01-22 14:36:40 -07003732
Dave Houlton5fa47912018-02-16 11:02:26 -07003733 vkGetDeviceQueue(demo->device, demo->graphics_queue_family_index, 0, &demo->graphics_queue);
Tony Barboura2a67812016-07-18 13:21:06 -06003734
Tony Barbour22e06272016-09-07 16:07:56 -06003735 if (!demo->separate_present_queue) {
Tony Barboura2a67812016-07-18 13:21:06 -06003736 demo->present_queue = demo->graphics_queue;
3737 } else {
Dave Houlton5fa47912018-02-16 11:02:26 -07003738 vkGetDeviceQueue(demo->device, demo->present_queue_family_index, 0, &demo->present_queue);
Tony Barboura2a67812016-07-18 13:21:06 -06003739 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003740
Ian Elliottaaae5352015-07-06 14:27:58 -06003741 // Get the list of VkFormat's that are supported:
Ian Elliott8528eff2015-08-07 15:56:59 -06003742 uint32_t formatCount;
Dave Houlton5fa47912018-02-16 11:02:26 -07003743 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, NULL);
Ian Elliottaaae5352015-07-06 14:27:58 -06003744 assert(!err);
Dave Houlton5fa47912018-02-16 11:02:26 -07003745 VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
3746 err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, &formatCount, surfFormats);
Ian Elliottaaae5352015-07-06 14:27:58 -06003747 assert(!err);
Joshua Ashton1fbefe02020-04-02 06:45:48 +01003748 VkSurfaceFormatKHR surfaceFormat = pick_surface_format(surfFormats, formatCount);
3749 demo->format = surfaceFormat.format;
3750 demo->color_space = surfaceFormat.colorSpace;
Jason Chen5d4fee92019-04-04 12:45:29 +08003751 free(surfFormats);
Ian Elliotte4602cd2015-04-21 16:41:02 -06003752
David Pinedo2bb7c932015-06-18 17:03:14 -06003753 demo->quit = false;
3754 demo->curFrame = 0;
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06003755
Tony Barbource7524e2016-07-28 12:01:45 -06003756 // Create semaphores to synchronize acquiring presentable buffers before
3757 // rendering and waiting for drawing to be complete before presenting
3758 VkSemaphoreCreateInfo semaphoreCreateInfo = {
3759 .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
3760 .pNext = NULL,
3761 .flags = 0,
3762 };
Tony Barbource7524e2016-07-28 12:01:45 -06003763
Tony Barbour66a56c32016-09-21 13:10:56 -06003764 // Create fences that we can use to throttle if we get too far
3765 // ahead of the image presents
3766 VkFenceCreateInfo fence_ci = {
Dave Houlton5fa47912018-02-16 11:02:26 -07003767 .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = NULL, .flags = VK_FENCE_CREATE_SIGNALED_BIT};
Tony Barbour66a56c32016-09-21 13:10:56 -06003768 for (uint32_t i = 0; i < FRAME_LAG; i++) {
Tony Barboura72d9492017-01-11 13:35:09 -07003769 err = vkCreateFence(demo->device, &fence_ci, NULL, &demo->fences[i]);
3770 assert(!err);
3771
Dave Houlton5fa47912018-02-16 11:02:26 -07003772 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_acquired_semaphores[i]);
Tony Barbour22e06272016-09-07 16:07:56 -06003773 assert(!err);
Tony Barbour66a56c32016-09-21 13:10:56 -06003774
Dave Houlton5fa47912018-02-16 11:02:26 -07003775 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->draw_complete_semaphores[i]);
Tony Barbour66a56c32016-09-21 13:10:56 -06003776 assert(!err);
3777
3778 if (demo->separate_present_queue) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003779 err = vkCreateSemaphore(demo->device, &semaphoreCreateInfo, NULL, &demo->image_ownership_semaphores[i]);
Tony Barbour66a56c32016-09-21 13:10:56 -06003780 assert(!err);
3781 }
Tony Barbour22e06272016-09-07 16:07:56 -06003782 }
Tony Barbour66a56c32016-09-21 13:10:56 -06003783 demo->frame_index = 0;
Tony Barbour22e06272016-09-07 16:07:56 -06003784
Mark Lobodzinskieadf9982015-07-02 16:49:40 -06003785 // Get Memory information and properties
Courtney Goeltzenleuchterbd5c1742015-10-20 16:40:38 -06003786 vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003787}
3788
Tony Barbour153cb062016-12-07 13:43:36 -07003789#if defined(VK_USE_PLATFORM_WAYLAND_KHR)
Joey Bzdek15eb0702017-06-07 09:40:36 -06003790static void pointer_handle_enter(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface, wl_fixed_t sx,
3791 wl_fixed_t sy) {}
3792
3793static void pointer_handle_leave(void *data, struct wl_pointer *pointer, uint32_t serial, struct wl_surface *surface) {}
3794
3795static void pointer_handle_motion(void *data, struct wl_pointer *pointer, uint32_t time, wl_fixed_t sx, wl_fixed_t sy) {}
3796
3797static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, uint32_t serial, uint32_t time, uint32_t button,
3798 uint32_t state) {
3799 struct demo *demo = data;
3800 if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
Manuel Stoecklac939332019-06-26 20:55:53 -04003801 xdg_toplevel_move(demo->xdg_toplevel, demo->seat, serial);
Joey Bzdek15eb0702017-06-07 09:40:36 -06003802 }
3803}
3804
3805static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, uint32_t time, uint32_t axis, wl_fixed_t value) {}
3806
3807static const struct wl_pointer_listener pointer_listener = {
3808 pointer_handle_enter, pointer_handle_leave, pointer_handle_motion, pointer_handle_button, pointer_handle_axis,
3809};
3810
3811static void keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int fd, uint32_t size) {}
3812
3813static void keyboard_handle_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface,
3814 struct wl_array *keys) {}
3815
3816static void keyboard_handle_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, struct wl_surface *surface) {}
3817
3818static void keyboard_handle_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, uint32_t key,
3819 uint32_t state) {
3820 if (state != WL_KEYBOARD_KEY_STATE_RELEASED) return;
3821 struct demo *demo = data;
3822 switch (key) {
3823 case KEY_ESC: // Escape
3824 demo->quit = true;
3825 break;
3826 case KEY_LEFT: // left arrow key
3827 demo->spin_angle -= demo->spin_increment;
3828 break;
3829 case KEY_RIGHT: // right arrow key
3830 demo->spin_angle += demo->spin_increment;
3831 break;
3832 case KEY_SPACE: // space bar
3833 demo->pause = !demo->pause;
3834 break;
3835 }
3836}
3837
3838static void keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t mods_depressed,
3839 uint32_t mods_latched, uint32_t mods_locked, uint32_t group) {}
3840
3841static const struct wl_keyboard_listener keyboard_listener = {
3842 keyboard_handle_keymap, keyboard_handle_enter, keyboard_handle_leave, keyboard_handle_key, keyboard_handle_modifiers,
3843};
3844
3845static void seat_handle_capabilities(void *data, struct wl_seat *seat, enum wl_seat_capability caps) {
3846 // Subscribe to pointer events
3847 struct demo *demo = data;
3848 if ((caps & WL_SEAT_CAPABILITY_POINTER) && !demo->pointer) {
3849 demo->pointer = wl_seat_get_pointer(seat);
3850 wl_pointer_add_listener(demo->pointer, &pointer_listener, demo);
3851 } else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && demo->pointer) {
3852 wl_pointer_destroy(demo->pointer);
3853 demo->pointer = NULL;
3854 }
3855 // Subscribe to keyboard events
3856 if (caps & WL_SEAT_CAPABILITY_KEYBOARD) {
3857 demo->keyboard = wl_seat_get_keyboard(seat);
3858 wl_keyboard_add_listener(demo->keyboard, &keyboard_listener, demo);
3859 } else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD)) {
3860 wl_keyboard_destroy(demo->keyboard);
3861 demo->keyboard = NULL;
3862 }
3863}
3864
3865static const struct wl_seat_listener seat_listener = {
3866 seat_handle_capabilities,
3867};
3868
Manuel Stoecklac939332019-06-26 20:55:53 -04003869static void wm_base_ping(void *data UNUSED, struct xdg_wm_base *xdg_wm_base, uint32_t serial) {
3870 xdg_wm_base_pong(xdg_wm_base, serial);
3871}
3872
3873static const struct xdg_wm_base_listener wm_base_listener = {wm_base_ping};
3874
3875static void registry_handle_global(void *data, struct wl_registry *registry, uint32_t id, const char *interface,
3876 uint32_t version UNUSED) {
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003877 struct demo *demo = data;
Joey Bzdek15eb0702017-06-07 09:40:36 -06003878 // pickup wayland objects when they appear
Manuel Stoecklac939332019-06-26 20:55:53 -04003879 if (strcmp(interface, wl_compositor_interface.name) == 0) {
Georges Basile Stavracas Neto7da3ea72019-10-05 11:53:39 -03003880 uint32_t minVersion = version < 4 ? version : 4;
3881 demo->compositor = wl_registry_bind(registry, id, &wl_compositor_interface, minVersion);
3882 if (demo->VK_KHR_incremental_present_enabled && minVersion < 4) {
3883 fprintf(stderr, "Wayland compositor doesn't support VK_KHR_incremental_present, disabling.\n");
3884 demo->VK_KHR_incremental_present_enabled = false;
3885 }
Manuel Stoecklac939332019-06-26 20:55:53 -04003886 } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) {
3887 demo->xdg_wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, 1);
3888 xdg_wm_base_add_listener(demo->xdg_wm_base, &wm_base_listener, NULL);
3889 } else if (strcmp(interface, wl_seat_interface.name) == 0) {
Joey Bzdek15eb0702017-06-07 09:40:36 -06003890 demo->seat = wl_registry_bind(registry, id, &wl_seat_interface, 1);
3891 wl_seat_add_listener(demo->seat, &seat_listener, demo);
Manuel Stoecklac939332019-06-26 20:55:53 -04003892 } else if (strcmp(interface, zxdg_decoration_manager_v1_interface.name) == 0) {
3893 demo->xdg_decoration_mgr = wl_registry_bind(registry, id, &zxdg_decoration_manager_v1_interface, 1);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003894 }
3895}
3896
Dave Houlton5fa47912018-02-16 11:02:26 -07003897static void registry_handle_global_remove(void *data UNUSED, struct wl_registry *registry UNUSED, uint32_t name UNUSED) {}
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003898
Dave Houlton5fa47912018-02-16 11:02:26 -07003899static const struct wl_registry_listener registry_listener = {registry_handle_global, registry_handle_global_remove};
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003900#endif
3901
Karl Schultze4dc75c2016-02-02 15:37:51 -07003902static void demo_init_connection(struct demo *demo) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003903#if defined(VK_USE_PLATFORM_XCB_KHR)
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003904 const xcb_setup_t *setup;
3905 xcb_screen_iterator_t iter;
3906 int scr;
3907
Mike Weiblen5d2ad542018-02-13 13:56:13 -07003908 const char *display_envar = getenv("DISPLAY");
3909 if (display_envar == NULL || display_envar[0] == '\0') {
3910 printf("Environment variable DISPLAY requires a valid value.\nExiting ...\n");
3911 fflush(stdout);
3912 exit(1);
3913 }
3914
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003915 demo->connection = xcb_connect(NULL, &scr);
Lenny Komow022bc2a2016-08-11 10:57:38 -06003916 if (xcb_connection_has_error(demo->connection) > 0) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003917 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
Ian Elliott3979e282015-04-03 15:24:55 -06003918 fflush(stdout);
3919 exit(1);
3920 }
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003921
3922 setup = xcb_get_setup(demo->connection);
3923 iter = xcb_setup_roots_iterator(setup);
Dave Houlton5fa47912018-02-16 11:02:26 -07003924 while (scr-- > 0) xcb_screen_next(&iter);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003925
3926 demo->screen = iter.data;
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003927#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
3928 demo->display = wl_display_connect(NULL);
3929
3930 if (demo->display == NULL) {
Dave Houlton5fa47912018-02-16 11:02:26 -07003931 printf("Cannot find a compatible Vulkan installable client driver (ICD).\nExiting ...\n");
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09003932 fflush(stdout);
3933 exit(1);
3934 }
3935
3936 demo->registry = wl_display_get_registry(demo->display);
3937 wl_registry_add_listener(demo->registry, &registry_listener, demo);
3938 wl_display_dispatch(demo->display);
Michael Lentinec6cde4b2016-04-18 13:20:45 -05003939#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003940}
3941
Karl Schultze4dc75c2016-02-02 15:37:51 -07003942static void demo_init(struct demo *demo, int argc, char **argv) {
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06003943 vec3 eye = {0.0f, 3.0f, 5.0f};
3944 vec3 origin = {0, 0, 0};
Chia-I Wuae3b55d2015-04-22 14:56:17 +08003945 vec3 up = {0.0f, 1.0f, 0.0};
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06003946
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06003947 memset(demo, 0, sizeof(*demo));
Tony Barbour291d57b2016-10-21 14:47:07 -06003948 demo->presentMode = VK_PRESENT_MODE_FIFO_KHR;
Tony Barbour1a86d032015-09-21 15:17:33 -06003949 demo->frameCount = INT32_MAX;
Witold Baryluka3b988f2021-01-07 19:03:02 +00003950 /* Autodetect suitable / best GPU by default */
3951 demo->gpu_number = -1;
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01003952 demo->width = 500;
3953 demo->height = 500;
Jeremy Kniager979b5312019-11-22 14:55:57 -07003954
Piers Daniell735ee532015-02-23 16:23:13 -07003955 for (int i = 1; i < argc; i++) {
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003956 if (strcmp(argv[i], "--use_staging") == 0) {
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07003957 demo->use_staging_buffer = true;
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003958 continue;
Ian Elliott639ca472015-04-16 15:23:05 -06003959 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003960 if ((strcmp(argv[i], "--present_mode") == 0) && (i < argc - 1)) {
3961 demo->presentMode = atoi(argv[i + 1]);
Tony Barbour291d57b2016-10-21 14:47:07 -06003962 i++;
3963 continue;
3964 }
Courtney Goeltzenleuchter03f4b772015-07-22 11:03:51 -06003965 if (strcmp(argv[i], "--break") == 0) {
3966 demo->use_break = true;
3967 continue;
3968 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06003969 if (strcmp(argv[i], "--validate") == 0) {
3970 demo->validate = true;
3971 continue;
3972 }
Tobin Ehlis4eb29d62017-03-14 11:29:01 -06003973 if (strcmp(argv[i], "--validate-checks-disabled") == 0) {
3974 demo->validate = true;
3975 demo->validate_checks_disabled = true;
3976 continue;
3977 }
Tony Barbour2593b182016-04-19 10:57:58 -06003978 if (strcmp(argv[i], "--xlib") == 0) {
Tony Barbour153cb062016-12-07 13:43:36 -07003979 fprintf(stderr, "--xlib is deprecated and no longer does anything");
Tony Barbour2593b182016-04-19 10:57:58 -06003980 continue;
3981 }
Dave Houlton5fa47912018-02-16 11:02:26 -07003982 if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && i < argc - 1 &&
3983 sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && demo->frameCount >= 0) {
David Pinedo2bb7c932015-06-18 17:03:14 -06003984 i++;
3985 continue;
3986 }
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01003987 if (strcmp(argv[i], "--width") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->width) == 1 && demo->width > 0) {
3988 i++;
3989 continue;
3990 }
3991 if (strcmp(argv[i], "--height") == 0 && i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->height) == 1 && demo->height > 0) {
3992 i++;
3993 continue;
3994 }
lenny-lunargfbe22392016-06-06 11:07:53 -06003995 if (strcmp(argv[i], "--suppress_popups") == 0) {
3996 demo->suppress_popups = true;
3997 continue;
3998 }
Ian Elliottd940ca22017-03-22 08:31:27 -06003999 if (strcmp(argv[i], "--display_timing") == 0) {
4000 demo->VK_GOOGLE_display_timing_enabled = true;
4001 continue;
4002 }
Ian Elliott53622a72017-03-28 11:06:33 -06004003 if (strcmp(argv[i], "--incremental_present") == 0) {
4004 demo->VK_KHR_incremental_present_enabled = true;
4005 continue;
4006 }
Tony-LunarG50e737c2020-07-16 14:26:03 -06004007 if ((strcmp(argv[i], "--gpu_number") == 0) && (i < argc - 1)) {
4008 demo->gpu_number = atoi(argv[i + 1]);
Witold Baryluka3b988f2021-01-07 19:03:02 +00004009 assert(demo->gpu_number >= 0);
Tony-LunarG50e737c2020-07-16 14:26:03 -06004010 i++;
4011 continue;
4012 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004013
Cody Northropaf28a532016-09-27 10:50:57 -06004014#if defined(ANDROID)
Lenny Komowffe446c2018-11-19 17:08:04 -07004015 ERR_EXIT("Usage: vkcube [--validate]\n", "Usage");
Cody Northropaf28a532016-09-27 10:50:57 -06004016#else
Tony-LunarGd74734f2019-06-04 14:11:43 -06004017 char *message =
4018 "Usage:\n %s\t[--use_staging] [--validate] [--validate-checks-disabled]\n"
4019 "\t[--break] [--c <framecount>] [--suppress_popups]\n"
4020 "\t[--incremental_present] [--display_timing]\n"
Tony-LunarG50e737c2020-07-16 14:26:03 -06004021 "\t[--gpu_number <index of physical device>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06004022 "\t[--present_mode <present mode enum>]\n"
Nicolas Caramelli7c25ce92021-01-08 17:46:07 +01004023 "\t[--width <width>] [--height <height>]\n"
Tony-LunarGd74734f2019-06-04 14:11:43 -06004024 "\t<present_mode_enum>\n"
4025 "\t\tVK_PRESENT_MODE_IMMEDIATE_KHR = %d\n"
4026 "\t\tVK_PRESENT_MODE_MAILBOX_KHR = %d\n"
4027 "\t\tVK_PRESENT_MODE_FIFO_KHR = %d\n"
4028 "\t\tVK_PRESENT_MODE_FIFO_RELAXED_KHR = %d\n";
4029 int length = snprintf(NULL, 0, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
4030 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
4031 char *usage = (char *)malloc(length + 1);
4032 if (!usage) {
4033 exit(1);
4034 }
4035 snprintf(usage, length + 1, message, APP_SHORT_NAME, VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
4036 VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR);
4037#if defined(_WIN32)
4038 if (!demo->suppress_popups) MessageBox(NULL, usage, "Usage Error", MB_OK);
4039#else
Tony-LunarG122ac062019-06-13 16:21:57 -06004040 fprintf(stderr, "%s", usage);
Ian Elliott639ca472015-04-16 15:23:05 -06004041 fflush(stderr);
Tony-LunarGd74734f2019-06-04 14:11:43 -06004042#endif
4043 free(usage);
Ian Elliott639ca472015-04-16 15:23:05 -06004044 exit(1);
Cody Northropaf28a532016-09-27 10:50:57 -06004045#endif
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07004046 }
4047
Tony Barbour153cb062016-12-07 13:43:36 -07004048 demo_init_connection(demo);
Tony Barbour2593b182016-04-19 10:57:58 -06004049
Courtney Goeltzenleuchtera4131c42015-04-08 15:36:08 -06004050 demo_init_vk(demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004051
Tony Barbour66a56c32016-09-21 13:10:56 -06004052 demo->spin_angle = 4.0f;
4053 demo->spin_increment = 0.2f;
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06004054 demo->pause = false;
4055
Dave Houlton5fa47912018-02-16 11:02:26 -07004056 mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 1.0f, 0.1f, 100.0f);
Courtney Goeltzenleuchter8879d3a2014-10-29 08:29:35 -06004057 mat4x4_look_at(demo->view_matrix, eye, origin, up);
4058 mat4x4_identity(demo->model_matrix);
Rene Lindsaybcccdea2016-08-12 17:56:09 -06004059
Dave Houlton5fa47912018-02-16 11:02:26 -07004060 demo->projection_matrix[1][1] *= -1; // Flip projection matrix from GL to Vulkan orientation.
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004061}
4062
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004063#if defined(VK_USE_PLATFORM_WIN32_KHR)
Mark Young418b9d12016-01-06 14:26:04 -07004064// Include header required for parsing the command line options.
4065#include <shellapi.h>
Ian Elliottf9cf78c2015-04-28 10:33:11 -06004066
Dave Houlton5fa47912018-02-16 11:02:26 -07004067int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) {
4068 MSG msg; // message
4069 bool done; // flag saying when app is complete
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004070 int argc;
Karl Schultze4dc75c2016-02-02 15:37:51 -07004071 char **argv;
Ian Elliott639ca472015-04-16 15:23:05 -06004072
Jamie Madillb2ff6502017-03-15 16:17:46 -04004073 // Ensure wParam is initialized.
4074 msg.wParam = 0;
4075
Karl Schultze4dc75c2016-02-02 15:37:51 -07004076 // Use the CommandLine functions to get the command line arguments.
4077 // Unfortunately, Microsoft outputs
4078 // this information as wide characters for Unicode, and we simply want the
4079 // Ascii version to be compatible
4080 // with the non-Windows side. So, we have to convert the information to
4081 // Ascii character strings.
4082 LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc);
4083 if (NULL == commandLineArgs) {
Mark Young418b9d12016-01-06 14:26:04 -07004084 argc = 0;
4085 }
4086
Karl Schultze4dc75c2016-02-02 15:37:51 -07004087 if (argc > 0) {
4088 argv = (char **)malloc(sizeof(char *) * argc);
4089 if (argv == NULL) {
Mark Young418b9d12016-01-06 14:26:04 -07004090 argc = 0;
Karl Schultze4dc75c2016-02-02 15:37:51 -07004091 } else {
4092 for (int iii = 0; iii < argc; iii++) {
4093 size_t wideCharLen = wcslen(commandLineArgs[iii]);
Mark Young418b9d12016-01-06 14:26:04 -07004094 size_t numConverted = 0;
4095
Karl Schultze4dc75c2016-02-02 15:37:51 -07004096 argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1));
4097 if (argv[iii] != NULL) {
Dave Houlton5fa47912018-02-16 11:02:26 -07004098 wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, commandLineArgs[iii], wideCharLen + 1);
Mark Young418b9d12016-01-06 14:26:04 -07004099 }
4100 }
4101 }
Karl Schultze4dc75c2016-02-02 15:37:51 -07004102 } else {
Mark Young418b9d12016-01-06 14:26:04 -07004103 argv = NULL;
4104 }
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004105
4106 demo_init(&demo, argc, argv);
Mark Young418b9d12016-01-06 14:26:04 -07004107
4108 // Free up the items we had to allocate for the command line arguments.
Karl Schultze4dc75c2016-02-02 15:37:51 -07004109 if (argc > 0 && argv != NULL) {
4110 for (int iii = 0; iii < argc; iii++) {
4111 if (argv[iii] != NULL) {
Mark Young418b9d12016-01-06 14:26:04 -07004112 free(argv[iii]);
4113 }
4114 }
4115 free(argv);
4116 }
4117
Tony Barbour3dddd5d2015-04-29 16:19:20 -06004118 demo.connection = hInstance;
Lenny Komowffe446c2018-11-19 17:08:04 -07004119 strncpy(demo.name, "Vulkan Cube", APP_NAME_STR_LEN);
Ian Elliott639ca472015-04-16 15:23:05 -06004120 demo_create_window(&demo);
Tony Barbourcc69f452015-10-08 13:59:42 -06004121 demo_init_vk_swapchain(&demo);
Ian Elliott639ca472015-04-16 15:23:05 -06004122
4123 demo_prepare(&demo);
4124
Dave Houlton5fa47912018-02-16 11:02:26 -07004125 done = false; // initialize loop condition variable
Mark Young418b9d12016-01-06 14:26:04 -07004126
4127 // main message loop
Karl Schultze4dc75c2016-02-02 15:37:51 -07004128 while (!done) {
Petr Krausd88e4e52019-01-23 18:45:04 +01004129 if (demo.pause) {
4130 const BOOL succ = WaitMessage();
4131
4132 if (!succ) {
4133 struct demo *tmp = &demo;
4134 struct demo *demo = tmp;
4135 ERR_EXIT("WaitMessage() failed on paused demo", "event loop error");
4136 }
4137 }
Ian Elliotta748eaf2015-04-28 15:50:36 -06004138 PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
Dave Houlton5fa47912018-02-16 11:02:26 -07004139 if (msg.message == WM_QUIT) // check for a quit message
Ian Elliott639ca472015-04-16 15:23:05 -06004140 {
Dave Houlton5fa47912018-02-16 11:02:26 -07004141 done = true; // if found, quit app
Karl Schultze4dc75c2016-02-02 15:37:51 -07004142 } else {
Ian Elliott639ca472015-04-16 15:23:05 -06004143 /* Translate and dispatch to event queue*/
Karl Schultze4dc75c2016-02-02 15:37:51 -07004144 TranslateMessage(&msg);
Ian Elliott639ca472015-04-16 15:23:05 -06004145 DispatchMessage(&msg);
4146 }
Tony Barbourc8a59892015-10-20 12:49:46 -06004147 RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT);
Ian Elliott639ca472015-04-16 15:23:05 -06004148 }
4149
4150 demo_cleanup(&demo);
4151
Karl Schultze4dc75c2016-02-02 15:37:51 -07004152 return (int)msg.wParam;
Ian Elliott639ca472015-04-16 15:23:05 -06004153}
Bill Hollingsf4352142017-02-14 22:58:56 -05004154
Bill Hollings0a0625a2019-07-15 17:39:18 -04004155#elif defined(VK_USE_PLATFORM_METAL_EXT)
4156static void demo_main(struct demo *demo, void *caMetalLayer, int argc, const char *argv[]) {
Dave Houlton5fa47912018-02-16 11:02:26 -07004157 demo_init(demo, argc, (char **)argv);
Bill Hollings0a0625a2019-07-15 17:39:18 -04004158 demo->caMetalLayer = caMetalLayer;
Tony Barbourc65cd752017-03-13 15:29:35 -06004159 demo_init_vk_swapchain(demo);
4160 demo_prepare(demo);
4161 demo->spin_angle = 0.4f;
Bill Hollingsf4352142017-02-14 22:58:56 -05004162}
4163
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004164#elif defined(VK_USE_PLATFORM_ANDROID_KHR)
4165#include <android/log.h>
4166#include <android_native_app_glue.h>
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004167#include "android_util.h"
4168
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004169static bool initialized = false;
4170static bool active = false;
4171struct demo demo;
4172
Dave Houlton5fa47912018-02-16 11:02:26 -07004173static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004174
Dave Houlton5fa47912018-02-16 11:02:26 -07004175static void processCommand(struct android_app *app, int32_t cmd) {
4176 switch (cmd) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004177 case APP_CMD_INIT_WINDOW: {
4178 if (app->window) {
Ian Elliottf05d5d12016-05-17 12:03:35 -06004179 // We're getting a new window. If the app is starting up, we
4180 // need to initialize. If the app has already been
4181 // initialized, that means that we lost our previous window,
4182 // which means that we have a lot of work to do. At a minimum,
4183 // we need to destroy the swapchain and surface associated with
4184 // the old window, and create a new surface and swapchain.
4185 // However, since there are a lot of other objects/state that
4186 // is tied to the swapchain, it's easiest to simply cleanup and
4187 // start over (i.e. use a brute-force approach of re-starting
4188 // the app)
4189 if (demo.prepared) {
4190 demo_cleanup(&demo);
4191 }
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004192
4193 // Parse Intents into argc, argv
4194 // Use the following key to send arguments, i.e.
4195 // --es args "--validate"
4196 const char key[] = "args";
Dave Houlton5fa47912018-02-16 11:02:26 -07004197 char *appTag = (char *)APP_SHORT_NAME;
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004198 int argc = 0;
Dave Houlton5fa47912018-02-16 11:02:26 -07004199 char **argv = get_args(app, key, appTag, &argc);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004200
4201 __android_log_print(ANDROID_LOG_INFO, appTag, "argc = %i", argc);
Dave Houlton5fa47912018-02-16 11:02:26 -07004202 for (int i = 0; i < argc; i++) __android_log_print(ANDROID_LOG_INFO, appTag, "argv[%i] = %s", i, argv[i]);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004203
4204 demo_init(&demo, argc, argv);
4205
4206 // Free the argv malloc'd by get_args
Dave Houlton5fa47912018-02-16 11:02:26 -07004207 for (int i = 0; i < argc; i++) free(argv[i]);
Cody Northropc5e5a8c2016-09-26 21:05:00 -06004208
Dave Houlton5fa47912018-02-16 11:02:26 -07004209 demo.window = (void *)app->window;
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004210 demo_init_vk_swapchain(&demo);
4211 demo_prepare(&demo);
4212 initialized = true;
4213 }
4214 break;
4215 }
4216 case APP_CMD_GAINED_FOCUS: {
4217 active = true;
4218 break;
4219 }
4220 case APP_CMD_LOST_FOCUS: {
4221 active = false;
4222 break;
4223 }
4224 }
4225}
4226
Dave Houlton5fa47912018-02-16 11:02:26 -07004227void android_main(struct android_app *app) {
Cody Northrop8707a6e2016-04-26 19:59:19 -06004228#ifdef ANDROID
4229 int vulkanSupport = InitVulkan();
Dave Houlton5fa47912018-02-16 11:02:26 -07004230 if (vulkanSupport == 0) return;
Cody Northrop8707a6e2016-04-26 19:59:19 -06004231#endif
4232
Ian Elliottf05d5d12016-05-17 12:03:35 -06004233 demo.prepared = false;
4234
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004235 app->onAppCmd = processCommand;
4236 app->onInputEvent = processInput;
4237
Dave Houlton5fa47912018-02-16 11:02:26 -07004238 while (1) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004239 int events;
Dave Houlton5fa47912018-02-16 11:02:26 -07004240 struct android_poll_source *source;
4241 while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004242 if (source) {
4243 source->process(app, source);
4244 }
4245
4246 if (app->destroyRequested != 0) {
4247 demo_cleanup(&demo);
4248 return;
4249 }
4250 }
4251 if (initialized && active) {
4252 demo_run(&demo);
4253 }
4254 }
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004255}
Tobin Ehlis43ed2982016-04-28 10:17:33 -06004256#else
Karl Schultze4dc75c2016-02-02 15:37:51 -07004257int main(int argc, char **argv) {
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004258 struct demo demo;
4259
Courtney Goeltzenleuchterb4fc0072015-02-17 12:54:31 -07004260 demo_init(&demo, argc, argv);
Tony Barbour153cb062016-12-07 13:43:36 -07004261#if defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour8295ac42016-08-08 11:04:17 -06004262 demo_create_xcb_window(&demo);
4263#elif defined(VK_USE_PLATFORM_XLIB_KHR)
4264 demo_create_xlib_window(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004265#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4266 demo_create_window(&demo);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02004267#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
4268 demo_create_directfb_window(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004269#endif
Tony Barbour2593b182016-04-19 10:57:58 -06004270
Tony Barbourcc69f452015-10-08 13:59:42 -06004271 demo_init_vk_swapchain(&demo);
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004272
4273 demo_prepare(&demo);
Tony Barbour2593b182016-04-19 10:57:58 -06004274
Tony Barbour153cb062016-12-07 13:43:36 -07004275#if defined(VK_USE_PLATFORM_XCB_KHR)
Tony Barbour8295ac42016-08-08 11:04:17 -06004276 demo_run_xcb(&demo);
4277#elif defined(VK_USE_PLATFORM_XLIB_KHR)
4278 demo_run_xlib(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004279#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
4280 demo_run(&demo);
Nicolas Caramellic8be8c82020-07-13 17:22:09 +02004281#elif defined(VK_USE_PLATFORM_DIRECTFB_EXT)
4282 demo_run_directfb(&demo);
Damien Leone600c3052017-01-31 10:26:07 -07004283#elif defined(VK_USE_PLATFORM_DISPLAY_KHR)
4284 demo_run_display(&demo);
Mun Gwan-gyeong6f01c552016-06-27 05:34:44 +09004285#endif
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004286
4287 demo_cleanup(&demo);
4288
Karl Schultz0218c002016-03-22 17:06:13 -06004289 return validation_error;
Courtney Goeltzenleuchter7be88a82014-10-23 13:16:59 -06004290}
Michael Lentinec6cde4b2016-04-18 13:20:45 -05004291#endif