vulkaninfo.c revision bc9caa57c5583dfdf05198e78b78a7cb361da16c
1/*
2 * Copyright (c) 2015-2016 The Khronos Group Inc.
3 * Copyright (c) 2015-2016 Valve Corporation
4 * Copyright (c) 2015-2016 LunarG, Inc.
5 *
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: Courtney Goeltzenleuchter <courtney@LunarG.com>
19 * Author: David Pinedo <david@lunarg.com>
20 * Author: Mark Lobodzinski <mark@lunarg.com>
21 * Author: Rene Lindsay <rene@lunarg.com>
22 */
23#include <assert.h>
24#include <inttypes.h>
25#include <stdbool.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29
30#ifdef _WIN32
31#include <fcntl.h>
32#include <io.h>
33#endif // _WIN32
34
35#if defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_XCB_KHR)
36#include <X11/Xutil.h>
37#endif
38
39#if defined(VK_USE_PLATFORM_MIR_KHR)
40#warning "Vulkaninfo does not have code for Mir at this time"
41#endif
42
43#include <vulkan/vulkan.h>
44
45#define ERR(err) printf("%s:%d: failed with %s\n", __FILE__, __LINE__, VkResultString(err));
46
47#ifdef _WIN32
48
49#define snprintf _snprintf
50
51// Returns nonzero if the console is used only for this process. Will return
52// zero if another process (such as cmd.exe) is also attached.
53static int ConsoleIsExclusive(void) {
54    DWORD pids[2];
55    DWORD num_pids = GetConsoleProcessList(pids, ARRAYSIZE(pids));
56    return num_pids <= 1;
57}
58
59#define WAIT_FOR_CONSOLE_DESTROY                                                                                                   \
60    do {                                                                                                                           \
61        if (ConsoleIsExclusive())                                                                                                  \
62            Sleep(INFINITE);                                                                                                       \
63    } while (0)
64#else
65#define WAIT_FOR_CONSOLE_DESTROY
66#endif
67
68#define ERR_EXIT(err)                                                                                                              \
69    do {                                                                                                                           \
70        ERR(err);                                                                                                                  \
71        fflush(stdout);                                                                                                            \
72        WAIT_FOR_CONSOLE_DESTROY;                                                                                                  \
73        exit(-1);                                                                                                                  \
74    } while (0)
75
76#if defined(NDEBUG) && defined(__GNUC__)
77#define U_ASSERT_ONLY __attribute__((unused))
78#else
79#define U_ASSERT_ONLY
80#endif
81
82#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
83
84#define MAX_QUEUE_TYPES 5
85#define APP_SHORT_NAME "vulkaninfo"
86
87struct AppGpu;
88
89struct AppDev {
90    struct AppGpu *gpu; /* point back to the GPU */
91
92    VkDevice obj;
93
94    VkFormatProperties format_props[VK_FORMAT_RANGE_SIZE];
95};
96
97struct LayerExtensionList {
98    VkLayerProperties layer_properties;
99    uint32_t extension_count;
100    VkExtensionProperties *extension_properties;
101};
102
103struct AppInstance {
104    VkInstance instance;
105    uint32_t global_layer_count;
106    struct LayerExtensionList *global_layers;
107    uint32_t global_extension_count;
108    VkExtensionProperties *global_extensions; // Instance Extensions
109
110    PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR;
111    PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
112    PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR;
113    PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR;
114
115    VkSurfaceKHR surface;
116    int width, height;
117
118#ifdef VK_USE_PLATFORM_WIN32_KHR
119    HINSTANCE h_instance; // Windows Instance
120    HWND h_wnd;           // window handle
121#elif VK_USE_PLATFORM_XCB_KHR
122    xcb_connection_t *xcb_connection;
123    xcb_screen_t *xcb_screen;
124    xcb_window_t xcb_window;
125#elif VK_USE_PLATFORM_XLIB_KHR
126    Display *xlib_display;
127    Window xlib_window;
128#elif VK_USE_PLATFORM_ANDROID_KHR // TODO
129    ANativeWindow *window;
130#endif
131};
132
133struct AppGpu {
134    uint32_t id;
135    VkPhysicalDevice obj;
136
137    VkPhysicalDeviceProperties props;
138
139    uint32_t queue_count;
140    VkQueueFamilyProperties *queue_props;
141    VkDeviceQueueCreateInfo *queue_reqs;
142
143    VkPhysicalDeviceMemoryProperties memory_props;
144    VkPhysicalDeviceFeatures features;
145    VkPhysicalDevice limits;
146
147    uint32_t device_extension_count;
148    VkExtensionProperties *device_extensions;
149
150    struct AppDev dev;
151};
152
153static VKAPI_ATTR VkBool32 VKAPI_CALL DbgCallback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, uint64_t srcObject,
154                                                  size_t location, int32_t msgCode, const char *pLayerPrefix, const char *pMsg,
155                                                  void *pUserData) {
156    char *message = (char *)malloc(strlen(pMsg) + 100);
157
158    assert(message);
159
160    if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
161        sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg);
162    } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
163        sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg);
164    } else if (msgFlags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
165        sprintf(message, "INFO: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg);
166    } else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
167        sprintf(message, "DEBUG: [%s] Code %d : %s", pLayerPrefix, msgCode, pMsg);
168    }
169
170    printf("%s\n", message);
171    fflush(stdout);
172    free(message);
173
174    /*
175     * false indicates that layer should not bail-out of an
176     * API call that had validation failures. This may mean that the
177     * app dies inside the driver due to invalid parameter(s).
178     * That's what would happen without validation layers, so we'll
179     * keep that behavior here.
180     */
181    return false;
182}
183
184static const char *VkResultString(VkResult err) {
185    switch (err) {
186#define STR(r)                                                                                                                     \
187    case r:                                                                                                                        \
188        return #r
189        STR(VK_SUCCESS);
190        STR(VK_NOT_READY);
191        STR(VK_TIMEOUT);
192        STR(VK_EVENT_SET);
193        STR(VK_EVENT_RESET);
194        STR(VK_ERROR_INITIALIZATION_FAILED);
195        STR(VK_ERROR_OUT_OF_HOST_MEMORY);
196        STR(VK_ERROR_OUT_OF_DEVICE_MEMORY);
197        STR(VK_ERROR_DEVICE_LOST);
198        STR(VK_ERROR_LAYER_NOT_PRESENT);
199        STR(VK_ERROR_EXTENSION_NOT_PRESENT);
200        STR(VK_ERROR_MEMORY_MAP_FAILED);
201        STR(VK_ERROR_INCOMPATIBLE_DRIVER);
202#undef STR
203    default:
204        return "UNKNOWN_RESULT";
205    }
206}
207
208static const char *VkPhysicalDeviceTypeString(VkPhysicalDeviceType type) {
209    switch (type) {
210#define STR(r)                                                                                                                     \
211    case VK_PHYSICAL_DEVICE_TYPE_##r:                                                                                              \
212        return #r
213        STR(OTHER);
214        STR(INTEGRATED_GPU);
215        STR(DISCRETE_GPU);
216        STR(VIRTUAL_GPU);
217#undef STR
218    default:
219        return "UNKNOWN_DEVICE";
220    }
221}
222
223static const char *VkFormatString(VkFormat fmt) {
224    switch (fmt) {
225#define STR(r)                                                                                                                     \
226    case VK_FORMAT_##r:                                                                                                            \
227        return #r
228        STR(UNDEFINED);
229        STR(R4G4_UNORM_PACK8);
230        STR(R4G4B4A4_UNORM_PACK16);
231        STR(B4G4R4A4_UNORM_PACK16);
232        STR(R5G6B5_UNORM_PACK16);
233        STR(B5G6R5_UNORM_PACK16);
234        STR(R5G5B5A1_UNORM_PACK16);
235        STR(B5G5R5A1_UNORM_PACK16);
236        STR(A1R5G5B5_UNORM_PACK16);
237        STR(R8_UNORM);
238        STR(R8_SNORM);
239        STR(R8_USCALED);
240        STR(R8_SSCALED);
241        STR(R8_UINT);
242        STR(R8_SINT);
243        STR(R8_SRGB);
244        STR(R8G8_UNORM);
245        STR(R8G8_SNORM);
246        STR(R8G8_USCALED);
247        STR(R8G8_SSCALED);
248        STR(R8G8_UINT);
249        STR(R8G8_SINT);
250        STR(R8G8_SRGB);
251        STR(R8G8B8_UNORM);
252        STR(R8G8B8_SNORM);
253        STR(R8G8B8_USCALED);
254        STR(R8G8B8_SSCALED);
255        STR(R8G8B8_UINT);
256        STR(R8G8B8_SINT);
257        STR(R8G8B8_SRGB);
258        STR(B8G8R8_UNORM);
259        STR(B8G8R8_SNORM);
260        STR(B8G8R8_USCALED);
261        STR(B8G8R8_SSCALED);
262        STR(B8G8R8_UINT);
263        STR(B8G8R8_SINT);
264        STR(B8G8R8_SRGB);
265        STR(R8G8B8A8_UNORM);
266        STR(R8G8B8A8_SNORM);
267        STR(R8G8B8A8_USCALED);
268        STR(R8G8B8A8_SSCALED);
269        STR(R8G8B8A8_UINT);
270        STR(R8G8B8A8_SINT);
271        STR(R8G8B8A8_SRGB);
272        STR(B8G8R8A8_UNORM);
273        STR(B8G8R8A8_SNORM);
274        STR(B8G8R8A8_USCALED);
275        STR(B8G8R8A8_SSCALED);
276        STR(B8G8R8A8_UINT);
277        STR(B8G8R8A8_SINT);
278        STR(B8G8R8A8_SRGB);
279        STR(A8B8G8R8_UNORM_PACK32);
280        STR(A8B8G8R8_SNORM_PACK32);
281        STR(A8B8G8R8_USCALED_PACK32);
282        STR(A8B8G8R8_SSCALED_PACK32);
283        STR(A8B8G8R8_UINT_PACK32);
284        STR(A8B8G8R8_SINT_PACK32);
285        STR(A8B8G8R8_SRGB_PACK32);
286        STR(A2R10G10B10_UNORM_PACK32);
287        STR(A2R10G10B10_SNORM_PACK32);
288        STR(A2R10G10B10_USCALED_PACK32);
289        STR(A2R10G10B10_SSCALED_PACK32);
290        STR(A2R10G10B10_UINT_PACK32);
291        STR(A2R10G10B10_SINT_PACK32);
292        STR(A2B10G10R10_UNORM_PACK32);
293        STR(A2B10G10R10_SNORM_PACK32);
294        STR(A2B10G10R10_USCALED_PACK32);
295        STR(A2B10G10R10_SSCALED_PACK32);
296        STR(A2B10G10R10_UINT_PACK32);
297        STR(A2B10G10R10_SINT_PACK32);
298        STR(R16_UNORM);
299        STR(R16_SNORM);
300        STR(R16_USCALED);
301        STR(R16_SSCALED);
302        STR(R16_UINT);
303        STR(R16_SINT);
304        STR(R16_SFLOAT);
305        STR(R16G16_UNORM);
306        STR(R16G16_SNORM);
307        STR(R16G16_USCALED);
308        STR(R16G16_SSCALED);
309        STR(R16G16_UINT);
310        STR(R16G16_SINT);
311        STR(R16G16_SFLOAT);
312        STR(R16G16B16_UNORM);
313        STR(R16G16B16_SNORM);
314        STR(R16G16B16_USCALED);
315        STR(R16G16B16_SSCALED);
316        STR(R16G16B16_UINT);
317        STR(R16G16B16_SINT);
318        STR(R16G16B16_SFLOAT);
319        STR(R16G16B16A16_UNORM);
320        STR(R16G16B16A16_SNORM);
321        STR(R16G16B16A16_USCALED);
322        STR(R16G16B16A16_SSCALED);
323        STR(R16G16B16A16_UINT);
324        STR(R16G16B16A16_SINT);
325        STR(R16G16B16A16_SFLOAT);
326        STR(R32_UINT);
327        STR(R32_SINT);
328        STR(R32_SFLOAT);
329        STR(R32G32_UINT);
330        STR(R32G32_SINT);
331        STR(R32G32_SFLOAT);
332        STR(R32G32B32_UINT);
333        STR(R32G32B32_SINT);
334        STR(R32G32B32_SFLOAT);
335        STR(R32G32B32A32_UINT);
336        STR(R32G32B32A32_SINT);
337        STR(R32G32B32A32_SFLOAT);
338        STR(R64_UINT);
339        STR(R64_SINT);
340        STR(R64_SFLOAT);
341        STR(R64G64_UINT);
342        STR(R64G64_SINT);
343        STR(R64G64_SFLOAT);
344        STR(R64G64B64_UINT);
345        STR(R64G64B64_SINT);
346        STR(R64G64B64_SFLOAT);
347        STR(R64G64B64A64_UINT);
348        STR(R64G64B64A64_SINT);
349        STR(R64G64B64A64_SFLOAT);
350        STR(B10G11R11_UFLOAT_PACK32);
351        STR(E5B9G9R9_UFLOAT_PACK32);
352        STR(D16_UNORM);
353        STR(X8_D24_UNORM_PACK32);
354        STR(D32_SFLOAT);
355        STR(S8_UINT);
356        STR(D16_UNORM_S8_UINT);
357        STR(D24_UNORM_S8_UINT);
358        STR(D32_SFLOAT_S8_UINT);
359        STR(BC1_RGB_UNORM_BLOCK);
360        STR(BC1_RGB_SRGB_BLOCK);
361        STR(BC2_UNORM_BLOCK);
362        STR(BC2_SRGB_BLOCK);
363        STR(BC3_UNORM_BLOCK);
364        STR(BC3_SRGB_BLOCK);
365        STR(BC4_UNORM_BLOCK);
366        STR(BC4_SNORM_BLOCK);
367        STR(BC5_UNORM_BLOCK);
368        STR(BC5_SNORM_BLOCK);
369        STR(BC6H_UFLOAT_BLOCK);
370        STR(BC6H_SFLOAT_BLOCK);
371        STR(BC7_UNORM_BLOCK);
372        STR(BC7_SRGB_BLOCK);
373        STR(ETC2_R8G8B8_UNORM_BLOCK);
374        STR(ETC2_R8G8B8A1_UNORM_BLOCK);
375        STR(ETC2_R8G8B8A8_UNORM_BLOCK);
376        STR(EAC_R11_UNORM_BLOCK);
377        STR(EAC_R11_SNORM_BLOCK);
378        STR(EAC_R11G11_UNORM_BLOCK);
379        STR(EAC_R11G11_SNORM_BLOCK);
380        STR(ASTC_4x4_UNORM_BLOCK);
381        STR(ASTC_4x4_SRGB_BLOCK);
382        STR(ASTC_5x4_UNORM_BLOCK);
383        STR(ASTC_5x4_SRGB_BLOCK);
384        STR(ASTC_5x5_UNORM_BLOCK);
385        STR(ASTC_5x5_SRGB_BLOCK);
386        STR(ASTC_6x5_UNORM_BLOCK);
387        STR(ASTC_6x5_SRGB_BLOCK);
388        STR(ASTC_6x6_UNORM_BLOCK);
389        STR(ASTC_6x6_SRGB_BLOCK);
390        STR(ASTC_8x5_UNORM_BLOCK);
391        STR(ASTC_8x5_SRGB_BLOCK);
392        STR(ASTC_8x6_UNORM_BLOCK);
393        STR(ASTC_8x6_SRGB_BLOCK);
394        STR(ASTC_8x8_UNORM_BLOCK);
395        STR(ASTC_8x8_SRGB_BLOCK);
396        STR(ASTC_10x5_UNORM_BLOCK);
397        STR(ASTC_10x5_SRGB_BLOCK);
398        STR(ASTC_10x6_UNORM_BLOCK);
399        STR(ASTC_10x6_SRGB_BLOCK);
400        STR(ASTC_10x8_UNORM_BLOCK);
401        STR(ASTC_10x8_SRGB_BLOCK);
402        STR(ASTC_10x10_UNORM_BLOCK);
403        STR(ASTC_10x10_SRGB_BLOCK);
404        STR(ASTC_12x10_UNORM_BLOCK);
405        STR(ASTC_12x10_SRGB_BLOCK);
406        STR(ASTC_12x12_UNORM_BLOCK);
407        STR(ASTC_12x12_SRGB_BLOCK);
408#undef STR
409    default:
410        return "UNKNOWN_FORMAT";
411    }
412}
413#if defined(VK_USE_PLATFORM_XCB_KHR) || defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_WIN32_KHR)
414static const char *VkPresentModeString(VkPresentModeKHR mode) {
415    switch (mode) {
416#define STR(r)                                                                                                                     \
417    case VK_PRESENT_MODE_##r:                                                                                                      \
418        return #r
419        STR(IMMEDIATE_KHR);
420        STR(MAILBOX_KHR);
421        STR(FIFO_KHR);
422        STR(FIFO_RELAXED_KHR);
423#undef STR
424    default:
425        return "UNKNOWN_FORMAT";
426    }
427}
428#endif
429
430static void AppDevInitFormats(struct AppDev *dev) {
431    VkFormat f;
432
433    for (f = 0; f < VK_FORMAT_RANGE_SIZE; f++) {
434        const VkFormat fmt = f;
435
436        vkGetPhysicalDeviceFormatProperties(dev->gpu->obj, fmt, &dev->format_props[f]);
437    }
438}
439
440static void ExtractVersion(uint32_t version, uint32_t *major, uint32_t *minor, uint32_t *patch) {
441    *major = version >> 22;
442    *minor = (version >> 12) & 0x3ff;
443    *patch = version & 0xfff;
444}
445
446static void AppGetPhysicalDeviceLayerExtensions(struct AppGpu *gpu, char *layer_name, uint32_t *extension_count,
447                                                VkExtensionProperties **extension_properties) {
448    VkResult err;
449    uint32_t ext_count = 0;
450    VkExtensionProperties *ext_ptr = NULL;
451
452    /* repeat get until VK_INCOMPLETE goes away */
453    do {
454        err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, &ext_count, NULL);
455        assert(!err);
456
457        if (ext_ptr) {
458            free(ext_ptr);
459        }
460        ext_ptr = malloc(ext_count * sizeof(VkExtensionProperties));
461        err = vkEnumerateDeviceExtensionProperties(gpu->obj, layer_name, &ext_count, ext_ptr);
462    } while (err == VK_INCOMPLETE);
463    assert(!err);
464
465    *extension_count = ext_count;
466    *extension_properties = ext_ptr;
467}
468
469static void AppDevInit(struct AppDev *dev, struct AppGpu *gpu) {
470    VkDeviceCreateInfo info = {
471        .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
472        .pNext = NULL,
473        .flags = 0,
474        .queueCreateInfoCount = 0,
475        .pQueueCreateInfos = NULL,
476        .enabledLayerCount = 0,
477        .ppEnabledLayerNames = NULL,
478        .enabledExtensionCount = 0,
479        .ppEnabledExtensionNames = NULL,
480    };
481    VkResult U_ASSERT_ONLY err;
482
483    // Device extensions
484    AppGetPhysicalDeviceLayerExtensions(gpu, NULL, &gpu->device_extension_count, &gpu->device_extensions);
485
486    fflush(stdout);
487
488    /* request all queues */
489    info.queueCreateInfoCount = gpu->queue_count;
490    info.pQueueCreateInfos = gpu->queue_reqs;
491
492    info.enabledLayerCount = 0;
493    info.ppEnabledLayerNames = NULL;
494    info.enabledExtensionCount = 0;
495    info.ppEnabledExtensionNames = NULL;
496    dev->gpu = gpu;
497    err = vkCreateDevice(gpu->obj, &info, NULL, &dev->obj);
498    if (err)
499        ERR_EXIT(err);
500}
501
502static void AppDevDestroy(struct AppDev *dev) {
503    vkDeviceWaitIdle(dev->obj);
504    vkDestroyDevice(dev->obj, NULL);
505}
506
507static void AppGetGlobalLayerExtensions(char *layer_name, uint32_t *extension_count, VkExtensionProperties **extension_properties) {
508    VkResult err;
509    uint32_t ext_count = 0;
510    VkExtensionProperties *ext_ptr = NULL;
511
512    /* repeat get until VK_INCOMPLETE goes away */
513    do {
514        // gets the extension count if the last parameter is NULL
515        err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, NULL);
516        assert(!err);
517
518        if (ext_ptr) {
519            free(ext_ptr);
520        }
521        ext_ptr = malloc(ext_count * sizeof(VkExtensionProperties));
522        // gets the extension properties if the last parameter is not NULL
523        err = vkEnumerateInstanceExtensionProperties(layer_name, &ext_count, ext_ptr);
524    } while (err == VK_INCOMPLETE);
525    assert(!err);
526    *extension_count = ext_count;
527    *extension_properties = ext_ptr;
528}
529
530/* Gets a list of layer and instance extensions */
531static void AppGetInstanceExtensions(struct AppInstance *inst) {
532    VkResult U_ASSERT_ONLY err;
533
534    uint32_t count = 0;
535
536    /* Scan layers */
537    VkLayerProperties *global_layer_properties = NULL;
538    struct LayerExtensionList *global_layers = NULL;
539
540    do {
541        err = vkEnumerateInstanceLayerProperties(&count, NULL);
542        assert(!err);
543
544        if (global_layer_properties) {
545            free(global_layer_properties);
546        }
547        global_layer_properties = malloc(sizeof(VkLayerProperties) * count);
548        assert(global_layer_properties);
549
550        if (global_layers) {
551            free(global_layers);
552        }
553        global_layers = malloc(sizeof(struct LayerExtensionList) * count);
554        assert(global_layers);
555
556        err = vkEnumerateInstanceLayerProperties(&count, global_layer_properties);
557    } while (err == VK_INCOMPLETE);
558    assert(!err);
559
560    inst->global_layer_count = count;
561    inst->global_layers = global_layers;
562
563    for (uint32_t i = 0; i < inst->global_layer_count; i++) {
564        VkLayerProperties *src_info = &global_layer_properties[i];
565        struct LayerExtensionList *dst_info = &inst->global_layers[i];
566        memcpy(&dst_info->layer_properties, src_info, sizeof(VkLayerProperties));
567
568        // Save away layer extension info for report
569        // Gets layer extensions, if first parameter is not NULL
570        AppGetGlobalLayerExtensions(src_info->layerName, &dst_info->extension_count, &dst_info->extension_properties);
571    }
572    free(global_layer_properties);
573
574    // Collect global extensions
575    inst->global_extension_count = 0;
576    // Gets instance extensions, if no layer was specified in the first
577    // paramteter
578    AppGetGlobalLayerExtensions(NULL, &inst->global_extension_count, &inst->global_extensions);
579}
580
581static void AppCreateInstance(struct AppInstance *inst) {
582    AppGetInstanceExtensions(inst);
583
584//---Build a list of extensions to load---
585#define MAX_EXTENSIONS 4
586    uint32_t i = 0;
587    uint32_t ext_count = 0;
588    const char *ext_names[MAX_EXTENSIONS]; // array of string pointers to
589                                           // extension names
590    for (i = 0; (i < inst->global_extension_count); i++) {
591        const char *found_name = inst->global_extensions[i].extensionName;
592        if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, found_name)) {
593            ext_names[ext_count++] = VK_KHR_SURFACE_EXTENSION_NAME;
594        }
595    }
596
597#if defined(VK_USE_PLATFORM_XCB_KHR) || defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_WAYLAND_KHR) ||               \
598    defined(VK_USE_PLATFORM_WIN32_KHR) || defined(VK_USE_PLATFORM_ANDROID_KHR)
599    if (ext_count)
600        for (i = 0; ((i < inst->global_extension_count) && (ext_count < MAX_EXTENSIONS)); i++) {
601            const char *found_name = inst->global_extensions[i].extensionName;
602#ifdef VK_USE_PLATFORM_WIN32_KHR
603            if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, found_name)) {
604                ext_names[ext_count++] = VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
605            }
606#elif VK_USE_PLATFORM_XCB_KHR
607            if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, found_name)) {
608                ext_names[ext_count++] = VK_KHR_XCB_SURFACE_EXTENSION_NAME;
609            }
610#elif VK_USE_PLATFORM_XLIB_KHR
611            if (!strcmp(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, found_name)) {
612                ext_names[ext_count++] = VK_KHR_XLIB_SURFACE_EXTENSION_NAME;
613            }
614#elif VK_USE_PLATFORM_WAYLAND_KHR
615            if (!strcmp(VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME, found_name)) {
616                ext_names[ext_count++] = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME;
617            }
618#elif VK_USE_PLATFORM_ANDROID_KHR
619            if (!strcmp(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, found_name)) {
620                ext_names[ext_count++] = VK_KHR_ANDROID_SURFACE_EXTENSION_NAME;
621            }
622#endif
623        }
624#endif
625    // If we don't find the KHR_SURFACE extension and at least one other
626    // device-specific extension,
627    // then give up on reporting presentable surface formats."
628    if (ext_count < 2)
629        ext_count = 0;
630    //----------------------------------------
631
632    const VkApplicationInfo app_info = {
633        .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
634        .pNext = NULL,
635        .pApplicationName = APP_SHORT_NAME,
636        .applicationVersion = 1,
637        .pEngineName = APP_SHORT_NAME,
638        .engineVersion = 1,
639        .apiVersion = VK_API_VERSION_1_0,
640    };
641
642    VkInstanceCreateInfo inst_info = {
643        .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
644        .pNext = NULL,
645        .pApplicationInfo = &app_info,
646        .enabledLayerCount = 0,
647        .ppEnabledLayerNames = NULL,
648        .enabledExtensionCount = ext_count,
649        .ppEnabledExtensionNames = ext_names,
650    };
651
652    VkDebugReportCallbackCreateInfoEXT dbg_info;
653    memset(&dbg_info, 0, sizeof(dbg_info));
654    dbg_info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
655    dbg_info.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_INFORMATION_BIT_EXT;
656    dbg_info.pfnCallback = DbgCallback;
657    inst_info.pNext = &dbg_info;
658
659    VkResult U_ASSERT_ONLY err;
660    err = vkCreateInstance(&inst_info, NULL, &inst->instance);
661    if (err == VK_ERROR_INCOMPATIBLE_DRIVER) {
662        printf("Cannot create Vulkan instance.\n");
663        ERR_EXIT(err);
664    } else if (err) {
665        ERR_EXIT(err);
666    }
667
668    if (ext_count > 0) {
669//--Load Extensions--
670#define GET_INSTANCE_PROC_ADDR(ENTRYPOINT)                                                                                         \
671    { inst->ENTRYPOINT = (void *)vkGetInstanceProcAddr(inst->instance, #ENTRYPOINT); }
672        GET_INSTANCE_PROC_ADDR(vkGetPhysicalDeviceSurfaceSupportKHR)
673        GET_INSTANCE_PROC_ADDR(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)
674        GET_INSTANCE_PROC_ADDR(vkGetPhysicalDeviceSurfaceFormatsKHR)
675        GET_INSTANCE_PROC_ADDR(vkGetPhysicalDeviceSurfacePresentModesKHR)
676#undef GET_INSTANCE_PROC_ADDR
677    }
678}
679
680//-----------------------------------------------------------
681
682static void AppDestroyInstance(struct AppInstance *inst) {
683    free(inst->global_extensions);
684    vkDestroyInstance(inst->instance, NULL);
685}
686
687static void AppGpuInit(struct AppGpu *gpu, uint32_t id, VkPhysicalDevice obj) {
688    uint32_t i;
689
690    memset(gpu, 0, sizeof(*gpu));
691
692    gpu->id = id;
693    gpu->obj = obj;
694
695    vkGetPhysicalDeviceProperties(gpu->obj, &gpu->props);
696
697    /* get queue count */
698    vkGetPhysicalDeviceQueueFamilyProperties(gpu->obj, &gpu->queue_count, NULL);
699
700    gpu->queue_props = malloc(sizeof(gpu->queue_props[0]) * gpu->queue_count);
701
702    if (!gpu->queue_props)
703        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
704    vkGetPhysicalDeviceQueueFamilyProperties(gpu->obj, &gpu->queue_count, gpu->queue_props);
705
706    /* set up queue requests */
707    gpu->queue_reqs = malloc(sizeof(*gpu->queue_reqs) * gpu->queue_count);
708    if (!gpu->queue_reqs)
709        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
710    for (i = 0; i < gpu->queue_count; i++) {
711        float *queue_priorities = malloc(gpu->queue_props[i].queueCount * sizeof(float));
712        if (!queue_priorities)
713            ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
714        memset(queue_priorities, 0, gpu->queue_props[i].queueCount * sizeof(float));
715        gpu->queue_reqs[i].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
716        gpu->queue_reqs[i].pNext = NULL;
717        gpu->queue_reqs[i].flags = 0;
718        gpu->queue_reqs[i].queueFamilyIndex = i;
719        gpu->queue_reqs[i].queueCount = gpu->queue_props[i].queueCount;
720        gpu->queue_reqs[i].pQueuePriorities = queue_priorities;
721    }
722
723    vkGetPhysicalDeviceMemoryProperties(gpu->obj, &gpu->memory_props);
724
725    vkGetPhysicalDeviceFeatures(gpu->obj, &gpu->features);
726
727    AppDevInit(&gpu->dev, gpu);
728    AppDevInitFormats(&gpu->dev);
729}
730
731static void AppGpuDestroy(struct AppGpu *gpu) {
732    AppDevDestroy(&gpu->dev);
733    free(gpu->device_extensions);
734
735    for (uint32_t i = 0; i < gpu->queue_count; i++) {
736        free((void *)gpu->queue_reqs[i].pQueuePriorities);
737    }
738    free(gpu->queue_reqs);
739    free(gpu->queue_props);
740}
741
742// clang-format off
743
744//-----------------------------------------------------------
745
746//---------------------------Win32---------------------------
747#ifdef VK_USE_PLATFORM_WIN32_KHR
748
749// MS-Windows event handling function:
750LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
751    return (DefWindowProc(hWnd, uMsg, wParam, lParam));
752}
753
754static void AppCreateWin32Window(struct AppInstance *inst) {
755    inst->h_instance = GetModuleHandle(NULL);
756
757    WNDCLASSEX win_class;
758
759    // Initialize the window class structure:
760    win_class.cbSize = sizeof(WNDCLASSEX);
761    win_class.style = CS_HREDRAW | CS_VREDRAW;
762    win_class.lpfnWndProc = WndProc;
763    win_class.cbClsExtra = 0;
764    win_class.cbWndExtra = 0;
765    win_class.hInstance = inst->h_instance;
766    win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
767    win_class.hCursor = LoadCursor(NULL, IDC_ARROW);
768    win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
769    win_class.lpszMenuName = NULL;
770    win_class.lpszClassName = APP_SHORT_NAME;
771    win_class.hInstance = inst->h_instance;
772    win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO);
773    // Register window class:
774    if (!RegisterClassEx(&win_class)) {
775        // It didn't work, so try to give a useful error:
776        printf("Failed to register the window class!\n");
777        fflush(stdout);
778        exit(1);
779    }
780    // Create window with the registered class:
781    RECT wr = { 0, 0, inst->width, inst->height };
782    AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);
783    inst->h_wnd = CreateWindowEx(0,
784        APP_SHORT_NAME,       // class name
785        APP_SHORT_NAME,       // app name
786        //WS_VISIBLE | WS_SYSMENU |
787        WS_OVERLAPPEDWINDOW,  // window style
788        100, 100,             // x/y coords
789        wr.right - wr.left,   // width
790        wr.bottom - wr.top,   // height
791        NULL,                 // handle to parent
792        NULL,                 // handle to menu
793        inst->h_instance,      // hInstance
794        NULL);                // no extra parameters
795    if (!inst->h_wnd) {
796        // It didn't work, so try to give a useful error:
797        printf("Failed to create a window!\n");
798        fflush(stdout);
799        exit(1);
800    }
801}
802
803static void AppCreateWin32Surface(struct AppInstance *inst) {
804    VkResult U_ASSERT_ONLY err;
805    VkWin32SurfaceCreateInfoKHR createInfo;
806    createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
807    createInfo.pNext = NULL;
808    createInfo.flags = 0;
809    createInfo.hinstance = inst->h_instance;
810    createInfo.hwnd = inst->h_wnd;
811    err = vkCreateWin32SurfaceKHR(inst->instance, &createInfo, NULL, &inst->surface);
812    assert(!err);
813}
814
815static void AppDestroyWin32Window(struct AppInstance *inst) {
816    DestroyWindow(inst->h_wnd);
817}
818#endif //VK_USE_PLATFORM_WIN32_KHR
819//-----------------------------------------------------------
820
821#if defined(VK_USE_PLATFORM_XCB_KHR)     || \
822    defined(VK_USE_PLATFORM_XLIB_KHR)    || \
823    defined(VK_USE_PLATFORM_WIN32_KHR)
824static void AppDestroySurface(struct AppInstance *inst) { //same for all platforms
825    vkDestroySurfaceKHR(inst->instance, inst->surface, NULL);
826}
827#endif
828
829//----------------------------XCB----------------------------
830
831#ifdef VK_USE_PLATFORM_XCB_KHR
832static void AppCreateXcbWindow(struct AppInstance *inst) {
833    //--Init Connection--
834    const xcb_setup_t *setup;
835    xcb_screen_iterator_t iter;
836    int scr;
837
838    inst->xcb_connection = xcb_connect(NULL, &scr);
839    if (inst->xcb_connection == NULL) {
840        printf("XCB failed to connect to the X server.\nExiting ...\n");
841        fflush(stdout);
842        exit(1);
843    }
844
845    int conn_error = xcb_connection_has_error(inst->xcb_connection);
846    if (conn_error) {
847        printf("XCB failed to connect to the X server due to error:%d.\nExiting ...\n", conn_error);
848        fflush(stdout);
849        exit(1);
850    }
851
852    setup = xcb_get_setup(inst->xcb_connection);
853    iter = xcb_setup_roots_iterator(setup);
854    while (scr-- > 0) {
855        xcb_screen_next(&iter);
856    }
857
858    inst->xcb_screen = iter.data;
859    //-------------------
860
861    inst->xcb_window = xcb_generate_id(inst->xcb_connection);
862    xcb_create_window(inst->xcb_connection, XCB_COPY_FROM_PARENT, inst->xcb_window,
863                      inst->xcb_screen->root, 0, 0, inst->width, inst->height, 0,
864                      XCB_WINDOW_CLASS_INPUT_OUTPUT, inst->xcb_screen->root_visual,
865                      0, NULL);
866
867    xcb_intern_atom_cookie_t cookie = xcb_intern_atom(inst->xcb_connection, 1, 12, "WM_PROTOCOLS");
868    xcb_intern_atom_reply_t *reply =  xcb_intern_atom_reply(inst->xcb_connection, cookie, 0);
869    free(reply);
870}
871
872static void AppCreateXcbSurface(struct AppInstance *inst) {
873    VkResult U_ASSERT_ONLY err;
874    VkXcbSurfaceCreateInfoKHR xcb_createInfo;
875    xcb_createInfo.sType      = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
876    xcb_createInfo.pNext      = NULL;
877    xcb_createInfo.flags      = 0;
878    xcb_createInfo.connection = inst->xcb_connection;
879    xcb_createInfo.window     = inst->xcb_window;
880    err = vkCreateXcbSurfaceKHR(inst->instance, &xcb_createInfo, NULL, &inst->surface);
881    assert(!err);
882}
883
884static void AppDestroyXcbWindow(struct AppInstance *inst) {
885    xcb_destroy_window(inst->xcb_connection, inst->xcb_window);
886    xcb_disconnect(inst->xcb_connection);
887}
888//VK_USE_PLATFORM_XCB_KHR
889//-----------------------------------------------------------
890
891//----------------------------XLib---------------------------
892#elif VK_USE_PLATFORM_XLIB_KHR
893static void AppCreateXlibWindow(struct AppInstance *inst) {
894    long visualMask = VisualScreenMask;
895    int numberOfVisuals;
896
897    inst->xlib_display = XOpenDisplay(NULL);
898    if (inst->xlib_display == NULL) {
899        printf("XLib failed to connect to the X server.\nExiting ...\n");
900        fflush(stdout);
901        exit(1);
902    }
903
904    XVisualInfo vInfoTemplate={};
905    vInfoTemplate.screen = DefaultScreen(inst->xlib_display);
906    XVisualInfo *visualInfo = XGetVisualInfo(inst->xlib_display, visualMask,
907                                             &vInfoTemplate, &numberOfVisuals);
908    inst->xlib_window = XCreateWindow(
909                inst->xlib_display, RootWindow(inst->xlib_display, vInfoTemplate.screen), 0, 0,
910                inst->width, inst->height, 0, visualInfo->depth, InputOutput,
911                visualInfo->visual, 0, NULL);
912
913    XSync(inst->xlib_display,false);
914}
915
916static void AppCreateXlibSurface(struct AppInstance *inst) {
917    VkResult U_ASSERT_ONLY err;
918    VkXlibSurfaceCreateInfoKHR createInfo;
919    createInfo.sType  = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
920    createInfo.pNext  = NULL;
921    createInfo.flags  = 0;
922    createInfo.dpy    = inst->xlib_display;
923    createInfo.window = inst->xlib_window;
924    err = vkCreateXlibSurfaceKHR(inst->instance, &createInfo, NULL, &inst->surface);
925    assert(!err);
926}
927
928static void AppDestroyXlibWindow(struct AppInstance *inst) {
929    XDestroyWindow(inst->xlib_display, inst->xlib_window);
930    XCloseDisplay(inst->xlib_display);
931}
932#endif //VK_USE_PLATFORM_XLIB_KHR
933//-----------------------------------------------------------
934
935#if defined(VK_USE_PLATFORM_XCB_KHR)     || \
936    defined(VK_USE_PLATFORM_XLIB_KHR)    || \
937    defined(VK_USE_PLATFORM_WIN32_KHR)
938static int AppDumpSurfaceFormats(struct AppInstance *inst, struct AppGpu *gpu){
939    // Get the list of VkFormat's that are supported:
940    VkResult U_ASSERT_ONLY err;
941    uint32_t format_count = 0;
942    err = inst->vkGetPhysicalDeviceSurfaceFormatsKHR(gpu->obj, inst->surface, &format_count, NULL);
943    assert(!err);
944
945    VkSurfaceFormatKHR *surf_formats = (VkSurfaceFormatKHR *)malloc(format_count * sizeof(VkSurfaceFormatKHR));
946    if (!surf_formats)
947        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
948    err = inst->vkGetPhysicalDeviceSurfaceFormatsKHR(gpu->obj, inst->surface, &format_count, surf_formats);
949    assert(!err);
950    printf("Formats:\t\tcount = %d\n", format_count);
951
952    for (uint32_t i = 0; i < format_count; i++) {
953        printf("\t%s\n", VkFormatString(surf_formats[i].format));
954    }
955    fflush(stdout);
956    return format_count;
957}
958
959static int AppDumpSurfacePresentModes(struct AppInstance *inst, struct AppGpu *gpu) {
960    // Get the list of VkPresentMode's that are supported:
961    VkResult U_ASSERT_ONLY err;
962    uint32_t present_mode_count = 0;
963    err = inst->vkGetPhysicalDeviceSurfacePresentModesKHR(gpu->obj, inst->surface, &present_mode_count, NULL);
964    assert(!err);
965
966    VkPresentModeKHR *surf_present_modes = (VkPresentModeKHR *)malloc(present_mode_count * sizeof(VkPresentInfoKHR));
967    if (!surf_present_modes)
968        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
969    err = inst->vkGetPhysicalDeviceSurfacePresentModesKHR(gpu->obj, inst->surface, &present_mode_count, surf_present_modes);
970    assert(!err);
971    printf("Present Modes:\t\tcount = %d\n", present_mode_count);
972
973    for (uint32_t i = 0; i < present_mode_count; i++) {
974        printf("\t%s\n", VkPresentModeString(surf_present_modes[i]));
975    }
976    printf("\n");
977    fflush(stdout);
978    return present_mode_count;
979}
980#endif
981
982static void AppDevDumpFormatProps(const struct AppDev *dev, VkFormat fmt)
983{
984    const VkFormatProperties *props = &dev->format_props[fmt];
985    struct {
986        const char *name;
987        VkFlags flags;
988    } features[3];
989
990    features[0].name  = "linearTiling   FormatFeatureFlags";
991    features[0].flags = props->linearTilingFeatures;
992    features[1].name  = "optimalTiling  FormatFeatureFlags";
993    features[1].flags = props->optimalTilingFeatures;
994    features[2].name  = "bufferFeatures FormatFeatureFlags";
995    features[2].flags = props->bufferFeatures;
996
997    printf("\nFORMAT_%s:", VkFormatString(fmt));
998    for (uint32_t i = 0; i < ARRAY_SIZE(features); i++) {
999        printf("\n\t%s:", features[i].name);
1000        if (features[i].flags == 0) {
1001            printf("\n\t\tNone");
1002        } else {
1003            printf("%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1004               ((features[i].flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)                  ? "\n\t\tVK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT"                  : ""),  //0x0001
1005               ((features[i].flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)                  ? "\n\t\tVK_FORMAT_FEATURE_STORAGE_IMAGE_BIT"                  : ""),  //0x0002
1006               ((features[i].flags & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)           ? "\n\t\tVK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT"           : ""),  //0x0004
1007               ((features[i].flags & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT)           ? "\n\t\tVK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT"           : ""),  //0x0008
1008               ((features[i].flags & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT)           ? "\n\t\tVK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT"           : ""),  //0x0010
1009               ((features[i].flags & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT)    ? "\n\t\tVK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT"    : ""),  //0x0020
1010               ((features[i].flags & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT)                  ? "\n\t\tVK_FORMAT_FEATURE_VERTEX_BUFFER_BIT"                  : ""),  //0x0040
1011               ((features[i].flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)               ? "\n\t\tVK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT"               : ""),  //0x0080
1012               ((features[i].flags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT)         ? "\n\t\tVK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT"         : ""),  //0x0100
1013               ((features[i].flags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)       ? "\n\t\tVK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT"       : ""),  //0x0200
1014               ((features[i].flags & VK_FORMAT_FEATURE_BLIT_SRC_BIT)                       ? "\n\t\tVK_FORMAT_FEATURE_BLIT_SRC_BIT"                       : ""),  //0x0400
1015               ((features[i].flags & VK_FORMAT_FEATURE_BLIT_DST_BIT)                       ? "\n\t\tVK_FORMAT_FEATURE_BLIT_DST_BIT"                       : ""),  //0x0800
1016               ((features[i].flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)    ? "\n\t\tVK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT"    : ""),  //0x1000
1017               ((features[i].flags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG) ? "\n\t\tVK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG" : "")); //0x2000
1018        }
1019    }
1020    printf("\n");
1021}
1022
1023
1024static void
1025AppDevDump(const struct AppDev *dev)
1026{
1027    printf("Format Properties:\n");
1028    printf("==================");
1029    VkFormat fmt;
1030
1031    for (fmt = 0; fmt < VK_FORMAT_RANGE_SIZE; fmt++) {
1032        AppDevDumpFormatProps(dev, fmt);
1033    }
1034}
1035
1036#ifdef _WIN32
1037#define PRINTF_SIZE_T_SPECIFIER    "%Iu"
1038#else
1039#define PRINTF_SIZE_T_SPECIFIER    "%zu"
1040#endif
1041
1042static void AppGpuDumpFeatures(const struct AppGpu *gpu)
1043{
1044    const VkPhysicalDeviceFeatures *features = &gpu->features;
1045
1046    printf("VkPhysicalDeviceFeatures:\n");
1047    printf("=========================\n");
1048
1049    printf("\trobustBufferAccess                      = %u\n", features->robustBufferAccess                     );
1050    printf("\tfullDrawIndexUint32                     = %u\n", features->fullDrawIndexUint32                    );
1051    printf("\timageCubeArray                          = %u\n", features->imageCubeArray                         );
1052    printf("\tindependentBlend                        = %u\n", features->independentBlend                       );
1053    printf("\tgeometryShader                          = %u\n", features->geometryShader                         );
1054    printf("\ttessellationShader                      = %u\n", features->tessellationShader                     );
1055    printf("\tsampleRateShading                       = %u\n", features->sampleRateShading                      );
1056    printf("\tdualSrcBlend                            = %u\n", features->dualSrcBlend                           );
1057    printf("\tlogicOp                                 = %u\n", features->logicOp                                );
1058    printf("\tmultiDrawIndirect                       = %u\n", features->multiDrawIndirect                      );
1059    printf("\tdrawIndirectFirstInstance               = %u\n", features->drawIndirectFirstInstance              );
1060    printf("\tdepthClamp                              = %u\n", features->depthClamp                             );
1061    printf("\tdepthBiasClamp                          = %u\n", features->depthBiasClamp                         );
1062    printf("\tfillModeNonSolid                        = %u\n", features->fillModeNonSolid                       );
1063    printf("\tdepthBounds                             = %u\n", features->depthBounds                            );
1064    printf("\twideLines                               = %u\n", features->wideLines                              );
1065    printf("\tlargePoints                             = %u\n", features->largePoints                            );
1066    printf("\ttextureCompressionETC2                  = %u\n", features->textureCompressionETC2                 );
1067    printf("\ttextureCompressionASTC_LDR              = %u\n", features->textureCompressionASTC_LDR             );
1068    printf("\ttextureCompressionBC                    = %u\n", features->textureCompressionBC                   );
1069    printf("\tocclusionQueryPrecise                   = %u\n", features->occlusionQueryPrecise                  );
1070    printf("\tpipelineStatisticsQuery                 = %u\n", features->pipelineStatisticsQuery                );
1071    printf("\tvertexSideEffects                       = %u\n", features->vertexPipelineStoresAndAtomics         );
1072    printf("\ttessellationSideEffects                 = %u\n", features->fragmentStoresAndAtomics               );
1073    printf("\tgeometrySideEffects                     = %u\n", features->shaderTessellationAndGeometryPointSize );
1074    printf("\tshaderImageGatherExtended               = %u\n", features->shaderImageGatherExtended              );
1075    printf("\tshaderStorageImageExtendedFormats       = %u\n", features->shaderStorageImageExtendedFormats      );
1076    printf("\tshaderStorageImageMultisample           = %u\n", features->shaderStorageImageMultisample          );
1077    printf("\tshaderStorageImageReadWithoutFormat     = %u\n", features->shaderStorageImageReadWithoutFormat    );
1078    printf("\tshaderStorageImageWriteWithoutFormat    = %u\n", features->shaderStorageImageWriteWithoutFormat   );
1079    printf("\tshaderUniformBufferArrayDynamicIndexing = %u\n", features->shaderUniformBufferArrayDynamicIndexing);
1080    printf("\tshaderSampledImageArrayDynamicIndexing  = %u\n", features->shaderSampledImageArrayDynamicIndexing );
1081    printf("\tshaderStorageBufferArrayDynamicIndexing = %u\n", features->shaderStorageBufferArrayDynamicIndexing);
1082    printf("\tshaderStorageImageArrayDynamicIndexing  = %u\n", features->shaderStorageImageArrayDynamicIndexing );
1083    printf("\tshaderClipDistance                      = %u\n", features->shaderClipDistance                     );
1084    printf("\tshaderCullDistance                      = %u\n", features->shaderCullDistance                     );
1085    printf("\tshaderFloat64                           = %u\n", features->shaderFloat64                          );
1086    printf("\tshaderInt64                             = %u\n", features->shaderInt64                            );
1087    printf("\tshaderInt16                             = %u\n", features->shaderInt16                            );
1088    printf("\tshaderResourceResidency                 = %u\n", features->shaderResourceResidency                );
1089    printf("\tshaderResourceMinLod                    = %u\n", features->shaderResourceMinLod                   );
1090    printf("\talphaToOne                              = %u\n", features->alphaToOne                             );
1091    printf("\tsparseBinding                           = %u\n", features->sparseBinding                          );
1092    printf("\tsparseResidencyBuffer                   = %u\n", features->sparseResidencyBuffer                  );
1093    printf("\tsparseResidencyImage2D                  = %u\n", features->sparseResidencyImage2D                 );
1094    printf("\tsparseResidencyImage3D                  = %u\n", features->sparseResidencyImage3D                 );
1095    printf("\tsparseResidency2Samples                 = %u\n", features->sparseResidency2Samples                );
1096    printf("\tsparseResidency4Samples                 = %u\n", features->sparseResidency4Samples                );
1097    printf("\tsparseResidency8Samples                 = %u\n", features->sparseResidency8Samples                );
1098    printf("\tsparseResidency16Samples                = %u\n", features->sparseResidency16Samples               );
1099    printf("\tsparseResidencyAliased                  = %u\n", features->sparseResidencyAliased                 );
1100    printf("\tvariableMultisampleRate                 = %u\n", features->variableMultisampleRate                );
1101    printf("\tinheritedQueries                        = %u\n", features->inheritedQueries                       );
1102}
1103
1104static void AppDumpSparseProps(const VkPhysicalDeviceSparseProperties *sparse_props)
1105{
1106
1107    printf("\tVkPhysicalDeviceSparseProperties:\n");
1108    printf("\t---------------------------------\n");
1109
1110    printf("\t\tresidencyStandard2DBlockShape            = %u\n", sparse_props->residencyStandard2DBlockShape           );
1111    printf("\t\tresidencyStandard2DMultisampleBlockShape = %u\n", sparse_props->residencyStandard2DMultisampleBlockShape);
1112    printf("\t\tresidencyStandard3DBlockShape            = %u\n", sparse_props->residencyStandard3DBlockShape           );
1113    printf("\t\tresidencyAlignedMipSize                  = %u\n", sparse_props->residencyAlignedMipSize                 );
1114    printf("\t\tresidencyNonResidentStrict               = %u\n", sparse_props->residencyNonResidentStrict              );
1115}
1116
1117static void AppDumpLimits(const VkPhysicalDeviceLimits *limits)
1118{
1119    printf("\tVkPhysicalDeviceLimits:\n");
1120    printf("\t-----------------------\n");
1121    printf("\t\tmaxImageDimension1D                     = %u\n",                 limits->maxImageDimension1D                    );
1122    printf("\t\tmaxImageDimension2D                     = %u\n",                 limits->maxImageDimension2D                    );
1123    printf("\t\tmaxImageDimension3D                     = %u\n",                 limits->maxImageDimension3D                    );
1124    printf("\t\tmaxImageDimensionCube                   = %u\n",                 limits->maxImageDimensionCube                  );
1125    printf("\t\tmaxImageArrayLayers                     = %u\n",                 limits->maxImageArrayLayers                    );
1126    printf("\t\tmaxTexelBufferElements                  = 0x%" PRIxLEAST32 "\n", limits->maxTexelBufferElements                 );
1127    printf("\t\tmaxUniformBufferRange                   = 0x%" PRIxLEAST32 "\n", limits->maxUniformBufferRange                  );
1128    printf("\t\tmaxStorageBufferRange                   = 0x%" PRIxLEAST32 "\n", limits->maxStorageBufferRange                  );
1129    printf("\t\tmaxPushConstantsSize                    = %u\n",                 limits->maxPushConstantsSize                   );
1130    printf("\t\tmaxMemoryAllocationCount                = %u\n",                 limits->maxMemoryAllocationCount               );
1131    printf("\t\tmaxSamplerAllocationCount               = %u\n",                 limits->maxSamplerAllocationCount              );
1132    printf("\t\tbufferImageGranularity                  = 0x%" PRIxLEAST64 "\n", limits->bufferImageGranularity                 );
1133    printf("\t\tsparseAddressSpaceSize                  = 0x%" PRIxLEAST64 "\n", limits->sparseAddressSpaceSize                 );
1134    printf("\t\tmaxBoundDescriptorSets                  = %u\n",                 limits->maxBoundDescriptorSets                 );
1135    printf("\t\tmaxPerStageDescriptorSamplers           = %u\n",                 limits->maxPerStageDescriptorSamplers          );
1136    printf("\t\tmaxPerStageDescriptorUniformBuffers     = %u\n",                 limits->maxPerStageDescriptorUniformBuffers    );
1137    printf("\t\tmaxPerStageDescriptorStorageBuffers     = %u\n",                 limits->maxPerStageDescriptorStorageBuffers    );
1138    printf("\t\tmaxPerStageDescriptorSampledImages      = %u\n",                 limits->maxPerStageDescriptorSampledImages     );
1139    printf("\t\tmaxPerStageDescriptorStorageImages      = %u\n",                 limits->maxPerStageDescriptorStorageImages     );
1140    printf("\t\tmaxPerStageDescriptorInputAttachments   = %u\n",                 limits->maxPerStageDescriptorInputAttachments  );
1141    printf("\t\tmaxPerStageResources                    = %u\n",                 limits->maxPerStageResources                   );
1142    printf("\t\tmaxDescriptorSetSamplers                = %u\n",                 limits->maxDescriptorSetSamplers               );
1143    printf("\t\tmaxDescriptorSetUniformBuffers          = %u\n",                 limits->maxDescriptorSetUniformBuffers         );
1144    printf("\t\tmaxDescriptorSetUniformBuffersDynamic   = %u\n",                 limits->maxDescriptorSetUniformBuffersDynamic  );
1145    printf("\t\tmaxDescriptorSetStorageBuffers          = %u\n",                 limits->maxDescriptorSetStorageBuffers         );
1146    printf("\t\tmaxDescriptorSetStorageBuffersDynamic   = %u\n",                 limits->maxDescriptorSetStorageBuffersDynamic  );
1147    printf("\t\tmaxDescriptorSetSampledImages           = %u\n",                 limits->maxDescriptorSetSampledImages          );
1148    printf("\t\tmaxDescriptorSetStorageImages           = %u\n",                 limits->maxDescriptorSetStorageImages          );
1149    printf("\t\tmaxDescriptorSetInputAttachments        = %u\n",                 limits->maxDescriptorSetInputAttachments       );
1150    printf("\t\tmaxVertexInputAttributes                = %u\n",                 limits->maxVertexInputAttributes               );
1151    printf("\t\tmaxVertexInputBindings                  = %u\n",                 limits->maxVertexInputBindings                 );
1152    printf("\t\tmaxVertexInputAttributeOffset           = 0x%" PRIxLEAST32 "\n", limits->maxVertexInputAttributeOffset          );
1153    printf("\t\tmaxVertexInputBindingStride             = 0x%" PRIxLEAST32 "\n", limits->maxVertexInputBindingStride            );
1154    printf("\t\tmaxVertexOutputComponents               = %u\n",                 limits->maxVertexOutputComponents              );
1155    printf("\t\tmaxTessellationGenerationLevel          = %u\n",                 limits->maxTessellationGenerationLevel         );
1156    printf("\t\tmaxTessellationPatchSize                        = %u\n",                 limits->maxTessellationPatchSize                       );
1157    printf("\t\tmaxTessellationControlPerVertexInputComponents  = %u\n",                 limits->maxTessellationControlPerVertexInputComponents );
1158    printf("\t\tmaxTessellationControlPerVertexOutputComponents = %u\n",                 limits->maxTessellationControlPerVertexOutputComponents);
1159    printf("\t\tmaxTessellationControlPerPatchOutputComponents  = %u\n",                 limits->maxTessellationControlPerPatchOutputComponents );
1160    printf("\t\tmaxTessellationControlTotalOutputComponents     = %u\n",                 limits->maxTessellationControlTotalOutputComponents    );
1161    printf("\t\tmaxTessellationEvaluationInputComponents        = %u\n",                 limits->maxTessellationEvaluationInputComponents       );
1162    printf("\t\tmaxTessellationEvaluationOutputComponents       = %u\n",                 limits->maxTessellationEvaluationOutputComponents      );
1163    printf("\t\tmaxGeometryShaderInvocations            = %u\n",                 limits->maxGeometryShaderInvocations           );
1164    printf("\t\tmaxGeometryInputComponents              = %u\n",                 limits->maxGeometryInputComponents             );
1165    printf("\t\tmaxGeometryOutputComponents             = %u\n",                 limits->maxGeometryOutputComponents            );
1166    printf("\t\tmaxGeometryOutputVertices               = %u\n",                 limits->maxGeometryOutputVertices              );
1167    printf("\t\tmaxGeometryTotalOutputComponents        = %u\n",                 limits->maxGeometryTotalOutputComponents       );
1168    printf("\t\tmaxFragmentInputComponents              = %u\n",                 limits->maxFragmentInputComponents             );
1169    printf("\t\tmaxFragmentOutputAttachments            = %u\n",                 limits->maxFragmentOutputAttachments           );
1170    printf("\t\tmaxFragmentDualSrcAttachments           = %u\n",                 limits->maxFragmentDualSrcAttachments          );
1171    printf("\t\tmaxFragmentCombinedOutputResources      = %u\n",                 limits->maxFragmentCombinedOutputResources     );
1172    printf("\t\tmaxComputeSharedMemorySize              = 0x%" PRIxLEAST32 "\n", limits->maxComputeSharedMemorySize             );
1173    printf("\t\tmaxComputeWorkGroupCount[0]             = %u\n",                 limits->maxComputeWorkGroupCount[0]            );
1174    printf("\t\tmaxComputeWorkGroupCount[1]             = %u\n",                 limits->maxComputeWorkGroupCount[1]            );
1175    printf("\t\tmaxComputeWorkGroupCount[2]             = %u\n",                 limits->maxComputeWorkGroupCount[2]            );
1176    printf("\t\tmaxComputeWorkGroupInvocations          = %u\n",                 limits->maxComputeWorkGroupInvocations         );
1177    printf("\t\tmaxComputeWorkGroupSize[0]              = %u\n",                 limits->maxComputeWorkGroupSize[0]             );
1178    printf("\t\tmaxComputeWorkGroupSize[1]              = %u\n",                 limits->maxComputeWorkGroupSize[1]             );
1179    printf("\t\tmaxComputeWorkGroupSize[2]              = %u\n",                 limits->maxComputeWorkGroupSize[2]             );
1180    printf("\t\tsubPixelPrecisionBits                   = %u\n",                 limits->subPixelPrecisionBits                  );
1181    printf("\t\tsubTexelPrecisionBits                   = %u\n",                 limits->subTexelPrecisionBits                  );
1182    printf("\t\tmipmapPrecisionBits                     = %u\n",                 limits->mipmapPrecisionBits                    );
1183    printf("\t\tmaxDrawIndexedIndexValue                = %u\n",                 limits->maxDrawIndexedIndexValue               );
1184    printf("\t\tmaxDrawIndirectCount                    = %u\n",                 limits->maxDrawIndirectCount                   );
1185    printf("\t\tmaxSamplerLodBias                       = %f\n",                 limits->maxSamplerLodBias                      );
1186    printf("\t\tmaxSamplerAnisotropy                    = %f\n",                 limits->maxSamplerAnisotropy                   );
1187    printf("\t\tmaxViewports                            = %u\n",                 limits->maxViewports                           );
1188    printf("\t\tmaxViewportDimensions[0]                = %u\n",                 limits->maxViewportDimensions[0]               );
1189    printf("\t\tmaxViewportDimensions[1]                = %u\n",                 limits->maxViewportDimensions[1]               );
1190    printf("\t\tviewportBoundsRange[0]                  =%13f\n",                 limits->viewportBoundsRange[0]                 );
1191    printf("\t\tviewportBoundsRange[1]                  =%13f\n",                 limits->viewportBoundsRange[1]                 );
1192    printf("\t\tviewportSubPixelBits                    = %u\n",                 limits->viewportSubPixelBits                   );
1193    printf("\t\tminMemoryMapAlignment                   = " PRINTF_SIZE_T_SPECIFIER "\n", limits->minMemoryMapAlignment         );
1194    printf("\t\tminTexelBufferOffsetAlignment           = 0x%" PRIxLEAST64 "\n", limits->minTexelBufferOffsetAlignment          );
1195    printf("\t\tminUniformBufferOffsetAlignment         = 0x%" PRIxLEAST64 "\n", limits->minUniformBufferOffsetAlignment        );
1196    printf("\t\tminStorageBufferOffsetAlignment         = 0x%" PRIxLEAST64 "\n", limits->minStorageBufferOffsetAlignment        );
1197    printf("\t\tminTexelOffset                          =%3d\n",                 limits->minTexelOffset                         );
1198    printf("\t\tmaxTexelOffset                          =%3d\n",                 limits->maxTexelOffset                         );
1199    printf("\t\tminTexelGatherOffset                    =%3d\n",                 limits->minTexelGatherOffset                   );
1200    printf("\t\tmaxTexelGatherOffset                    =%3d\n",                 limits->maxTexelGatherOffset                   );
1201    printf("\t\tminInterpolationOffset                  =%9f\n",                 limits->minInterpolationOffset                 );
1202    printf("\t\tmaxInterpolationOffset                  =%9f\n",                 limits->maxInterpolationOffset                 );
1203    printf("\t\tsubPixelInterpolationOffsetBits         = %u\n",                 limits->subPixelInterpolationOffsetBits        );
1204    printf("\t\tmaxFramebufferWidth                     = %u\n",                 limits->maxFramebufferWidth                    );
1205    printf("\t\tmaxFramebufferHeight                    = %u\n",                 limits->maxFramebufferHeight                   );
1206    printf("\t\tmaxFramebufferLayers                    = %u\n",                 limits->maxFramebufferLayers                   );
1207    printf("\t\tframebufferColorSampleCounts            = %u\n",                 limits->framebufferColorSampleCounts           );
1208    printf("\t\tframebufferDepthSampleCounts            = %u\n",                 limits->framebufferDepthSampleCounts           );
1209    printf("\t\tframebufferStencilSampleCounts          = %u\n",                 limits->framebufferStencilSampleCounts         );
1210    printf("\t\tframebufferNoAttachmentsSampleCounts    = %u\n",                 limits->framebufferNoAttachmentsSampleCounts   );
1211    printf("\t\tmaxColorAttachments                     = %u\n",                 limits->maxColorAttachments                    );
1212    printf("\t\tsampledImageColorSampleCounts           = %u\n",                 limits->sampledImageColorSampleCounts          );
1213    printf("\t\tsampledImageDepthSampleCounts           = %u\n",                 limits->sampledImageDepthSampleCounts          );
1214    printf("\t\tsampledImageStencilSampleCounts         = %u\n",                 limits->sampledImageStencilSampleCounts        );
1215    printf("\t\tsampledImageIntegerSampleCounts         = %u\n",                 limits->sampledImageIntegerSampleCounts        );
1216    printf("\t\tstorageImageSampleCounts                = %u\n",                 limits->storageImageSampleCounts               );
1217    printf("\t\tmaxSampleMaskWords                      = %u\n",                 limits->maxSampleMaskWords                     );
1218    printf("\t\ttimestampComputeAndGraphics             = %u\n",                 limits->timestampComputeAndGraphics            );
1219    printf("\t\ttimestampPeriod                         = %f\n",                 limits->timestampPeriod                        );
1220    printf("\t\tmaxClipDistances                        = %u\n",                 limits->maxClipDistances                       );
1221    printf("\t\tmaxCullDistances                        = %u\n",                 limits->maxCullDistances                       );
1222    printf("\t\tmaxCombinedClipAndCullDistances         = %u\n",                 limits->maxCombinedClipAndCullDistances        );
1223    printf("\t\tdiscreteQueuePriorities                 = %u\n",                 limits->discreteQueuePriorities                );
1224    printf("\t\tpointSizeRange[0]                       = %f\n",                 limits->pointSizeRange[0]                      );
1225    printf("\t\tpointSizeRange[1]                       = %f\n",                 limits->pointSizeRange[1]                      );
1226    printf("\t\tlineWidthRange[0]                       = %f\n",                 limits->lineWidthRange[0]                      );
1227    printf("\t\tlineWidthRange[1]                       = %f\n",                 limits->lineWidthRange[1]                      );
1228    printf("\t\tpointSizeGranularity                    = %f\n",                 limits->pointSizeGranularity                   );
1229    printf("\t\tlineWidthGranularity                    = %f\n",                 limits->lineWidthGranularity                   );
1230    printf("\t\tstrictLines                             = %u\n",                 limits->strictLines                            );
1231    printf("\t\tstandardSampleLocations                 = %u\n",                 limits->standardSampleLocations                );
1232    printf("\t\toptimalBufferCopyOffsetAlignment        = 0x%" PRIxLEAST64 "\n", limits->optimalBufferCopyOffsetAlignment       );
1233    printf("\t\toptimalBufferCopyRowPitchAlignment      = 0x%" PRIxLEAST64 "\n", limits->optimalBufferCopyRowPitchAlignment     );
1234    printf("\t\tnonCoherentAtomSize                     = 0x%" PRIxLEAST64 "\n", limits->nonCoherentAtomSize                    );
1235}
1236
1237static void AppGpuDumpProps(const struct AppGpu *gpu)
1238{
1239    const VkPhysicalDeviceProperties *props = &gpu->props;
1240    const uint32_t apiVersion=props->apiVersion;
1241    const uint32_t major = VK_VERSION_MAJOR(apiVersion);
1242    const uint32_t minor = VK_VERSION_MINOR(apiVersion);
1243    const uint32_t patch = VK_VERSION_PATCH(apiVersion);
1244
1245    printf("VkPhysicalDeviceProperties:\n");
1246    printf("===========================\n");
1247    printf("\tapiVersion     = 0x%" PRIxLEAST32 "  (%d.%d.%d)\n", apiVersion, major, minor, patch);
1248    printf("\tdriverVersion  = %u (0x%" PRIxLEAST32 ")\n",props->driverVersion, props->driverVersion);
1249    printf("\tvendorID       = 0x%04x\n",                 props->vendorID);
1250    printf("\tdeviceID       = 0x%04x\n",                 props->deviceID);
1251    printf("\tdeviceType     = %s\n",                     VkPhysicalDeviceTypeString(props->deviceType));
1252    printf("\tdeviceName     = %s\n",                     props->deviceName);
1253
1254    AppDumpLimits(&gpu->props.limits);
1255    AppDumpSparseProps(&gpu->props.sparseProperties);
1256
1257    fflush(stdout);
1258}
1259// clang-format on
1260
1261static void AppDumpExtensions(const char *indent, const char *layer_name, const uint32_t extension_count,
1262                              const VkExtensionProperties *extension_properties) {
1263    uint32_t i;
1264    if (layer_name && (strlen(layer_name) > 0)) {
1265        printf("%s%s Extensions", indent, layer_name);
1266    } else {
1267        printf("%sExtensions", indent);
1268    }
1269    printf("\tcount = %d\n", extension_count);
1270    for (i = 0; i < extension_count; i++) {
1271        VkExtensionProperties const *ext_prop = &extension_properties[i];
1272
1273        printf("%s\t", indent);
1274        printf("%-36s: extension revision %2d\n", ext_prop->extensionName, ext_prop->specVersion);
1275    }
1276    fflush(stdout);
1277}
1278
1279#if defined(VK_USE_PLATFORM_XCB_KHR) || defined(VK_USE_PLATFORM_XLIB_KHR) || defined(VK_USE_PLATFORM_WIN32_KHR)
1280// Returns true if the named extension is in the list of extensions.
1281static bool HasExtension(const char *extension_name, const uint32_t extension_count,
1282                         const VkExtensionProperties *extension_properties) {
1283    for (uint32_t i = 0; i < extension_count; i++) {
1284        if (!strcmp(extension_name, extension_properties[i].extensionName))
1285            return true;
1286    }
1287    return false;
1288}
1289#endif
1290
1291static void AppGpuDumpQueueProps(const struct AppGpu *gpu, uint32_t id) {
1292    const VkQueueFamilyProperties *props = &gpu->queue_props[id];
1293
1294    printf("VkQueueFamilyProperties[%d]:\n", id);
1295    printf("===========================\n");
1296    char *sep = ""; // separator character
1297    printf("\tqueueFlags         = ");
1298    if (props->queueFlags & VK_QUEUE_GRAPHICS_BIT) {
1299        printf("GRAPHICS");
1300        sep = " | ";
1301    }
1302    if (props->queueFlags & VK_QUEUE_COMPUTE_BIT) {
1303        printf("%sCOMPUTE", sep);
1304        sep = " | ";
1305    }
1306    if (props->queueFlags & VK_QUEUE_TRANSFER_BIT) {
1307        printf("%sTRANSFER", sep);
1308        sep = " | ";
1309    }
1310    if (props->queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) {
1311        printf("%sSPARSE", sep);
1312    }
1313    printf("\n");
1314
1315    printf("\tqueueCount         = %u\n", props->queueCount);
1316    printf("\ttimestampValidBits = %u\n", props->timestampValidBits);
1317    printf("\tminImageTransferGranularity = (%d, %d, %d)\n", props->minImageTransferGranularity.width,
1318           props->minImageTransferGranularity.height, props->minImageTransferGranularity.depth);
1319    fflush(stdout);
1320}
1321
1322static void AppGpuDumpMemoryProps(const struct AppGpu *gpu) {
1323    const VkPhysicalDeviceMemoryProperties *props = &gpu->memory_props;
1324
1325    printf("VkPhysicalDeviceMemoryProperties:\n");
1326    printf("=================================\n");
1327    printf("\tmemoryTypeCount       = %u\n", props->memoryTypeCount);
1328    for (uint32_t i = 0; i < props->memoryTypeCount; i++) {
1329        printf("\tmemoryTypes[%u] : \n", i);
1330        printf("\t\theapIndex     = %u\n", props->memoryTypes[i].heapIndex);
1331        printf("\t\tpropertyFlags = 0x%" PRIxLEAST32 ":\n", props->memoryTypes[i].propertyFlags);
1332
1333        // Print each named flag, if it is set.
1334        VkFlags flags = props->memoryTypes[i].propertyFlags;
1335#define PRINT_FLAG(FLAG)                                                                                                           \
1336    if (flags & FLAG)                                                                                                              \
1337        printf("\t\t\t" #FLAG "\n");
1338        PRINT_FLAG(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)
1339        PRINT_FLAG(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)
1340        PRINT_FLAG(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)
1341        PRINT_FLAG(VK_MEMORY_PROPERTY_HOST_CACHED_BIT)
1342        PRINT_FLAG(VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT)
1343#undef PRINT_FLAG
1344    }
1345    printf("\n");
1346    printf("\tmemoryHeapCount       = %u\n", props->memoryHeapCount);
1347    for (uint32_t i = 0; i < props->memoryHeapCount; i++) {
1348        printf("\tmemoryHeaps[%u] : \n", i);
1349        const VkDeviceSize memSize = props->memoryHeaps[i].size;
1350        printf("\t\tsize          = " PRINTF_SIZE_T_SPECIFIER " (0x%" PRIxLEAST64 ")\n", (size_t)memSize, memSize);
1351
1352        VkMemoryHeapFlags heap_flags = props->memoryHeaps[i].flags;
1353        printf("\t\tflags: \n\t\t\t");
1354        printf((heap_flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) ? "VK_MEMORY_HEAP_DEVICE_LOCAL_BIT\n" : "None\n");
1355    }
1356    fflush(stdout);
1357}
1358
1359static void AppGpuDump(const struct AppGpu *gpu) {
1360    uint32_t i;
1361
1362    printf("\nDevice Properties and Extensions :\n");
1363    printf("==================================\n");
1364    printf("GPU%u\n", gpu->id);
1365    AppGpuDumpProps(gpu);
1366    printf("\n");
1367    AppDumpExtensions("", "Device", gpu->device_extension_count, gpu->device_extensions);
1368    printf("\n");
1369    for (i = 0; i < gpu->queue_count; i++) {
1370        AppGpuDumpQueueProps(gpu, i);
1371        printf("\n");
1372    }
1373    AppGpuDumpMemoryProps(gpu);
1374    printf("\n");
1375    AppGpuDumpFeatures(gpu);
1376    printf("\n");
1377    AppDevDump(&gpu->dev);
1378}
1379
1380#ifdef _WIN32
1381// Enlarges the console window to have a large scrollback size.
1382static void ConsoleEnlarge() {
1383    HANDLE console_handle = GetStdHandle(STD_OUTPUT_HANDLE);
1384
1385    // make the console window bigger
1386    CONSOLE_SCREEN_BUFFER_INFO csbi;
1387    COORD buffer_size;
1388    if (GetConsoleScreenBufferInfo(console_handle, &csbi)) {
1389        buffer_size.X = csbi.dwSize.X + 30;
1390        buffer_size.Y = 20000;
1391        SetConsoleScreenBufferSize(console_handle, buffer_size);
1392    }
1393
1394    SMALL_RECT r;
1395    r.Left = r.Top = 0;
1396    r.Right = csbi.dwSize.X - 1 + 30;
1397    r.Bottom = 50;
1398    SetConsoleWindowInfo(console_handle, true, &r);
1399
1400    // change the console window title
1401    SetConsoleTitle(TEXT(APP_SHORT_NAME));
1402}
1403#endif
1404
1405int main(int argc, char **argv) {
1406    unsigned int major, minor, patch;
1407    struct AppGpu *gpus;
1408    VkPhysicalDevice *objs;
1409    uint32_t gpu_count, i;
1410    VkResult err;
1411    struct AppInstance inst;
1412
1413#ifdef _WIN32
1414    if (ConsoleIsExclusive())
1415        ConsoleEnlarge();
1416#endif
1417
1418    major = VK_VERSION_MAJOR(VK_API_VERSION_1_0);
1419    minor = VK_VERSION_MINOR(VK_API_VERSION_1_0);
1420    patch = VK_VERSION_PATCH(VK_HEADER_VERSION);
1421
1422    printf("===========\n");
1423    printf("VULKAN INFO\n");
1424    printf("===========\n\n");
1425    printf("Vulkan API Version: %d.%d.%d\n\n", major, minor, patch);
1426
1427    AppCreateInstance(&inst);
1428
1429    printf("\nInstance Extensions:\n");
1430    printf("====================\n");
1431    AppDumpExtensions("", "Instance", inst.global_extension_count, inst.global_extensions);
1432
1433    err = vkEnumeratePhysicalDevices(inst.instance, &gpu_count, NULL);
1434    if (err)
1435        ERR_EXIT(err);
1436    objs = malloc(sizeof(objs[0]) * gpu_count);
1437    if (!objs)
1438        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
1439    err = vkEnumeratePhysicalDevices(inst.instance, &gpu_count, objs);
1440    if (err)
1441        ERR_EXIT(err);
1442
1443    gpus = malloc(sizeof(gpus[0]) * gpu_count);
1444    if (!gpus)
1445        ERR_EXIT(VK_ERROR_OUT_OF_HOST_MEMORY);
1446    for (i = 0; i < gpu_count; i++) {
1447        AppGpuInit(&gpus[i], i, objs[i]);
1448        printf("\n\n");
1449    }
1450
1451    //---Layer-Device-Extensions---
1452    printf("Layers: count = %d\n", inst.global_layer_count);
1453    printf("=======\n");
1454    for (uint32_t i = 0; i < inst.global_layer_count; i++) {
1455        uint32_t major, minor, patch;
1456        char spec_version[64], layer_version[64];
1457        VkLayerProperties const *layer_prop = &inst.global_layers[i].layer_properties;
1458
1459        ExtractVersion(layer_prop->specVersion, &major, &minor, &patch);
1460        snprintf(spec_version, sizeof(spec_version), "%d.%d.%d", major, minor, patch);
1461        snprintf(layer_version, sizeof(layer_version), "%d", layer_prop->implementationVersion);
1462        printf("%s (%s) Vulkan version %s, layer version %s\n", layer_prop->layerName, (char *)layer_prop->description,
1463               spec_version, layer_version);
1464
1465        AppDumpExtensions("\t", "Layer", inst.global_layers[i].extension_count, inst.global_layers[i].extension_properties);
1466
1467        char *layer_name = inst.global_layers[i].layer_properties.layerName;
1468        printf("\tDevices \tcount = %d\n", gpu_count);
1469        for (uint32_t j = 0; j < gpu_count; j++) {
1470            printf("\t\tGPU id       : %u (%s)\n", j, gpus[j].props.deviceName);
1471            uint32_t count = 0;
1472            VkExtensionProperties *props;
1473            AppGetPhysicalDeviceLayerExtensions(&gpus[j], layer_name, &count, &props);
1474            AppDumpExtensions("\t\t", "Layer-Device", count, props);
1475            free(props);
1476        }
1477        printf("\n");
1478    }
1479    fflush(stdout);
1480    //-----------------------------
1481
1482    printf("Presentable Surfaces:\n");
1483    printf("=====================\n");
1484    inst.width = 256;
1485    inst.height = 256;
1486    int format_count = 0;
1487    int present_mode_count = 0;
1488
1489#if defined(VK_USE_PLATFORM_XCB_KHR) || defined(VK_USE_PLATFORM_XLIB_KHR)
1490    if (getenv("DISPLAY") == NULL) {
1491        printf("'DISPLAY' environment variable not set... Exiting!\n");
1492        fflush(stdout);
1493        exit(1);
1494    }
1495#endif
1496//--WIN32--
1497#ifdef VK_USE_PLATFORM_WIN32_KHR
1498    if (HasExtension(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, inst.global_extension_count, inst.global_extensions)) {
1499        AppCreateWin32Window(&inst);
1500        for (i = 0; i < gpu_count; i++) {
1501            AppCreateWin32Surface(&inst);
1502            printf("GPU id       : %u (%s)\n", i, gpus[i].props.deviceName);
1503            printf("Surface type : %s\n", VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1504            format_count += AppDumpSurfaceFormats(&inst, &gpus[i]);
1505            present_mode_count += AppDumpSurfacePresentModes(&inst, &gpus[i]);
1506            AppDestroySurface(&inst);
1507        }
1508        AppDestroyWin32Window(&inst);
1509    }
1510//--XCB--
1511#elif VK_USE_PLATFORM_XCB_KHR
1512    if (HasExtension(VK_KHR_XCB_SURFACE_EXTENSION_NAME, inst.global_extension_count, inst.global_extensions)) {
1513        AppCreateXcbWindow(&inst);
1514        for (i = 0; i < gpu_count; i++) {
1515            AppCreateXcbSurface(&inst);
1516            printf("GPU id       : %u (%s)\n", i, gpus[i].props.deviceName);
1517            printf("Surface type : %s\n", VK_KHR_XCB_SURFACE_EXTENSION_NAME);
1518            format_count += AppDumpSurfaceFormats(&inst, &gpus[i]);
1519            present_mode_count += AppDumpSurfacePresentModes(&inst, &gpus[i]);
1520            AppDestroySurface(&inst);
1521        }
1522        AppDestroyXcbWindow(&inst);
1523    }
1524//--XLIB--
1525#elif VK_USE_PLATFORM_XLIB_KHR
1526    if (HasExtension(VK_KHR_XLIB_SURFACE_EXTENSION_NAME, inst.global_extension_count, inst.global_extensions)) {
1527        AppCreateXlibWindow(&inst);
1528        for (i = 0; i < gpu_count; i++) {
1529            AppCreateXlibSurface(&inst);
1530            printf("GPU id       : %u (%s)\n", i, gpus[i].props.deviceName);
1531            printf("Surface type : %s\n", VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
1532            format_count += AppDumpSurfaceFormats(&inst, &gpus[i]);
1533            present_mode_count += AppDumpSurfacePresentModes(&inst, &gpus[i]);
1534            AppDestroySurface(&inst);
1535        }
1536        AppDestroyXlibWindow(&inst);
1537    }
1538#endif
1539    // TODO: Android / Wayland / MIR
1540    if (!format_count && !present_mode_count)
1541        printf("None found\n");
1542    //---------
1543
1544    for (i = 0; i < gpu_count; i++) {
1545        AppGpuDump(&gpus[i]);
1546        printf("\n\n");
1547    }
1548
1549    for (i = 0; i < gpu_count; i++)
1550        AppGpuDestroy(&gpus[i]);
1551    free(gpus);
1552    free(objs);
1553
1554    AppDestroyInstance(&inst);
1555
1556    fflush(stdout);
1557#ifdef _WIN32
1558    if (ConsoleIsExclusive())
1559        Sleep(INFINITE);
1560#endif
1561
1562    return 0;
1563}
1564