/* Copyright (c) 2019, Jordan Halase Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Note: Due to the length of many function and variable names in the * Vulkan API, the line width of any Vulkan-related code here may be * extended from 80 columns to 120 colums to improve readability. */ /* The goal of this project is to create an entirely self-contained, embeddable * Vulkan renderer. While dynamic linking directly against the system Vulkan * loader is safe, it will crash if attempting to run on a system without it * installed. By loading the Vulkan library dynamically, the application may * gracefully close or even fall back to a different rendering API. * Furthermore, Vulkan specifies that using functions retrieved via * `vkGetDeviceProcAddr` may actually run faster than if the application were * using the Vulkan loader directly due to bypassing the loader terminator. * * https://vulkan.lunarg.com/doc/sdk/1.0.61.1/windows/LoaderAndLayerInterface.html */ #include #include #include #include #if defined(_WIN32) #include #include // XXX Pugl: to implement puglCreateVulkanSurface() on Win32 #else #include // XXX Pugl: to implement puglCreateVulkanSurface() on X11 #include // XXX Pugl: to implement puglCreateVulkanSurface() on X11 #endif #include "test/test_utils.h" // for printEvent() #include "pugl/pugl.h" #include "pugl/pugl_stub_backend.h" #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" // a better, cross-platform sprintf() for error formatting /* Thread-local storage for ad-hoc dlerr() on Windows */ #if defined(__GNUC__) #define APP_THREAD_LOCAL __thread #else #define APP_THREAD_LOCAL __declspec(thread) #endif #define MIN(a, b) ((a) <= (b) ? (a) : (b)) #define MAX(a, b) ((a) >= (b) ? (a) : (b)) #define CLAMP(x, l, h) ((x) <= (l) ? (l) : (x) >= (h) ? (h) : (x)) struct Arguments { bool validation; bool verbose; bool continuous; }; static void printUsage(const char *cmd, const struct Arguments *args, const bool error) { FILE *fp = error ? stderr : stdout; const char *const defaultStr = "\t[default]\n"; const char *const newline = "\n"; fprintf(fp, "Usage: %s [OPTION...]\n", cmd); fprintf(fp, " -h, --help\t\tShow this help message\n"); fprintf(fp, " --validation\t\tRun with Vulkan validation layers and debug callback%s", args->validation ? defaultStr : newline); fprintf(fp, " --no-validation\tRun without Vulkan validation layers or debug callback%s", !args->validation ? defaultStr : newline); fprintf(fp, " -c, --continuous\tDraw continuously as fast as possible%s", args->continuous ? defaultStr : newline); fprintf(fp, " -v, --verbose\t\tPrint verbose window system events%s", args->verbose ? defaultStr : newline); exit(error); } static void parseArgs(const int argc, char *const *const argv, struct Arguments *const args) { if (argc < 2) { return; } const struct Arguments immutable = *args; int i; for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { printUsage(argv[0], &immutable, false); } else if (!strcmp(argv[i], "--validation")) { args->validation = true; } else if (!strcmp(argv[i], "--no-validation")) { args->validation = false; } else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--continuous")) { args->continuous = true; } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")) { args->verbose = true; } else { fprintf(stderr, "Unknown option `%s`\n", argv[1]); printUsage(argv[0], &immutable, true); } } } static void printArgs(int argc, char **argv) { int i; for (i = 0; i < argc-1; ++i) { printf("%s ", argv[i]); } printf("%s\n", argv[i]); } /** Vulkan allocation callbacks if we ever decide to use them when debugging. * * This is put in a macro so we don't have to look for every Vulkan function * that uses it. */ #define ALLOC_VK NULL /** Instance-level Vulkan functions and handle */ struct VulkanAPI { void *handle; PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; PFN_vkEnumerateInstanceVersion vkEnumerateInstanceVersion; PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; PFN_vkCreateInstance vkCreateInstance; PFN_vkDestroyInstance vkDestroyInstance; PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; PFN_vkCreateDevice vkCreateDevice; PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; }; /** Device-level Vulkan functions */ struct VulkanDev { PFN_vkDestroyDevice vkDestroyDevice; PFN_vkDeviceWaitIdle vkDeviceWaitIdle; PFN_vkGetDeviceQueue vkGetDeviceQueue; PFN_vkQueueWaitIdle vkQueueWaitIdle; PFN_vkCreateCommandPool vkCreateCommandPool; PFN_vkDestroyCommandPool vkDestroyCommandPool; PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; PFN_vkCreateImageView vkCreateImageView; PFN_vkDestroyImageView vkDestroyImageView; PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; PFN_vkFreeCommandBuffers vkFreeCommandBuffers; PFN_vkBeginCommandBuffer vkBeginCommandBuffer; PFN_vkEndCommandBuffer vkEndCommandBuffer; PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; PFN_vkCmdClearColorImage vkCmdClearColorImage; PFN_vkCreateSemaphore vkCreateSemaphore; PFN_vkDestroySemaphore vkDestroySemaphore; PFN_vkCreateFence vkCreateFence; PFN_vkDestroyFence vkDestroyFence; PFN_vkGetFenceStatus vkGetFenceStatus; PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; PFN_vkWaitForFences vkWaitForFences; PFN_vkResetFences vkResetFences; PFN_vkQueueSubmit vkQueueSubmit; PFN_vkQueuePresentKHR vkQueuePresentKHR; }; /** Application-specific swapchain behavior */ struct SwapchainVulkan { struct SwapchainVulkan *old; // Linked list of retired swapchains VkSwapchainKHR rawSwapchain; uint32_t nImages; VkExtent2D extent; VkImage *images; VkImageView *imageViews; VkFence *fences; VkCommandBuffer *commandBuffers; }; struct SemaphoreVulkan { VkSemaphore presentComplete; VkSemaphore renderFinished; }; struct FenceVulkan { VkFence *swapchain; // Fences for each swapchain image }; struct SyncVulkan { struct SemaphoreVulkan semaphore; }; /** Vulkan application that uses Pugl for windows and events * * TODO: Separate Instance from rest of application. */ struct RenderVulkan { struct VulkanAPI *api; struct VulkanDev *dev; char *errMsg; PuglWorld *world; PuglView *view; VkInstance instance; VkDebugReportCallbackEXT debugCallback; VkSurfaceKHR surface; VkSurfaceFormatKHR surfaceFormat; VkPresentModeKHR presentMode; VkPhysicalDeviceProperties deviceProperties; // TODO: Make this a pointer. It's really big. VkPhysicalDevice physicalDevice; uint32_t graphicsIndex; VkDevice device; VkQueue graphicsQueue; VkCommandPool commandPool; struct SwapchainVulkan *swapchain; struct SyncVulkan sync; }; #define RVK_ERRMSG_LEN 4096 void rvkSetErrMsg(struct RenderVulkan *vk, const char *fmt, ...) { vk->errMsg = realloc(vk->errMsg, RVK_ERRMSG_LEN); va_list args; va_start(args, fmt); stbsp_vsnprintf(vk->errMsg, RVK_ERRMSG_LEN, fmt, args); va_end(args); } void rvkClearErrMsg(struct RenderVulkan *vk) { if (vk->errMsg) { free(vk->errMsg); vk->errMsg = NULL; } } const char *rvkGetErrMsg(struct RenderVulkan *vk) { return vk->errMsg; } #if defined(_WIN32) #define VULKAN_SONAME_LATEST "vulkan-1.dll" static inline void *appDlopen(const char *soname) { return LoadLibraryA(soname); } static inline char *appDlerror() { // TODO: Print a more informative string. Error codes are annoying. DWORD errCode = GetLastError(); static APP_THREAD_LOCAL char errStr[64]; stbsp_snprintf(errStr, sizeof(errStr), "Dynamic Library Error: %d", errCode); return errStr; } static inline void *appDlsym(void *handle, const char *symbol) { const uintptr_t ulAddr = (uintptr_t)GetProcAddress(handle, symbol); return (void*)ulAddr; } static inline int appDlclose(void *handle) { return FreeLibrary(handle); } /* XXX: puglGetRequiredInstanceExtensions() implementation for Win32 * "Get the platform-specific names of the required instance-level * extensions if you want to display your images to the screen." * Reminder that Vulkan is off-screen by default. */ void getRequiredInstanceExtensions( uint32_t *pExtensionCount, const char **const ppExtensionNames) { static const char *const required[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME }; static const uint32_t num = sizeof(required) / sizeof(required[0]); if (ppExtensionNames) { for (uint32_t i = 0; i < num; ++i) { ppExtensionNames[i] = required[i]; } } else { *pExtensionCount = num; } } /* XXX: puglCreateVulkanSurface() implementation for Win32 * * Creating a surface is platform-specific and should be handled by Pugl * with this function exposed publicly. * * No need to wrap vkFreeSurfaceKHR(). Creating a surface is platform * specific, but freeing it is not. */ VkResult createVulkanSurface(PuglView *view, VkInstance instance, PFN_vkGetInstanceProcAddr getInstanceProcAddrFunc, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) { VkWin32SurfaceCreateInfoKHR createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; //createInfo.hinstance = GetModuleHandle(0); // FIXME (?) createInfo.hinstance = puglGetNativeWorld(puglGetWorld(view)); createInfo.hwnd = puglGetNativeWindow(view); PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)getInstanceProcAddrFunc( instance, "vkCreateWin32SurfaceKHR"); return vkCreateWin32SurfaceKHR(instance, &createInfo, pAllocator, pSurface); } #else #define VULKAN_SONAME_LATEST "libvulkan.so.1" #include static inline void *appDlopen(const char *soname) { return dlopen(soname, RTLD_NOW); } static inline char *appDlerror() { return dlerror(); } static inline void *appDlsym(void *handle, const char *symbol) { return dlsym(handle, symbol); } static inline int appDlclose(void *handle) { return dlclose(handle); } /* XXX: puglGetRequiredInstanceExtensions() implementation for Xlib * "Get the platform-specific names of the required instance-level * extensions if you want to display your images to the screen." * Reminder that Vulkan is off-screen by default. */ void getRequiredInstanceExtensions( uint32_t *pExtensionCount, const char **const ppExtensionNames) { static const char *const required[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_XLIB_SURFACE_EXTENSION_NAME }; static const uint32_t num = sizeof(required) / sizeof(required[0]); if (ppExtensionNames) { for (uint32_t i = 0; i < num; ++i) { ppExtensionNames[i] = required[i]; } } else { *pExtensionCount = num; } } /* XXX: puglCreateVulkanSurface() implementation for Xlib * * Creating a surface is platform-specific and should be handled by Pugl * with this function exposed publicly. * * No need to wrap vkFreeSurfaceKHR(). Creating a surface is platform * specific, but freeing it is not. */ VkResult createVulkanSurface(PuglView *view, VkInstance instance, PFN_vkGetInstanceProcAddr getInstanceProcAddrFunc, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) { VkXlibSurfaceCreateInfoKHR createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR; //createInfo.dpy = ((struct PuglWorldImpl*)world)->impl->display; createInfo.dpy = puglGetNativeWorld(puglGetWorld(view)); createInfo.window = puglGetNativeWindow(view); PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR = (PFN_vkCreateXlibSurfaceKHR)getInstanceProcAddrFunc( instance, "vkCreateXlibSurfaceKHR"); return vkCreateXlibSurfaceKHR(instance, &createInfo, pAllocator, pSurface); } #endif static void *loadVulkanLibrary() { void *handle = appDlopen(VULKAN_SONAME_LATEST); return handle; } static void loadVulkanGetInstanceProcAddrFunc(void *handle, PFN_vkGetInstanceProcAddr *getInstanceProcAddrFunc) { *getInstanceProcAddrFunc = (PFN_vkGetInstanceProcAddr)appDlsym( handle, "vkGetInstanceProcAddr"); } static int unloadVulkanLibrary(void *handle) { if (handle) { return appDlclose(handle); } return 0; } static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char *layerPrefix, const char *msg, void *userData ) { fprintf(stderr, "\nValidation layer:\n%s\n\n", msg); return VK_FALSE; } static VkResult rvkCreateInternalInstance( struct RenderVulkan *vk, const uint32_t nLayers, const char *const *const layers, const uint32_t nAdditional, const char *const *const additionalExtensions) { VkApplicationInfo appInfo = { 0 }; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Pugl Vulkan Test"; appInfo.applicationVersion = VK_MAKE_VERSION(0, 1, 0); appInfo.pEngineName = "Pugl Vulkan Test Engine"; appInfo.engineVersion = VK_MAKE_VERSION(0, 1, 0); /* MoltenVK for macOS currently only supports Vulkan 1.0 */ appInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0); uint32_t i, j, nRequired; getRequiredInstanceExtensions(&nRequired, NULL); const uint32_t nExtensions = nRequired + nAdditional; const char **const extensions = malloc(sizeof(const char*) * nExtensions); getRequiredInstanceExtensions(NULL, extensions); for (i = nRequired, j = 0; i < nExtensions; ++i, ++j) { extensions[i] = additionalExtensions[j]; } for (i = 0; i < nExtensions; ++i) { printf("Using instance extension:\t%s\n", extensions[i]); } for (i = 0; i < nLayers; ++i) { printf("Using instance layer:\t\t%s\n", layers[i]); } VkInstanceCreateInfo createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; createInfo.enabledLayerCount = nLayers; createInfo.ppEnabledLayerNames = layers; createInfo.enabledExtensionCount = nExtensions; createInfo.ppEnabledExtensionNames = extensions; VkResult result = VK_SUCCESS; if ((result = vk->api->vkCreateInstance(&createInfo, ALLOC_VK, &vk->instance))) { rvkSetErrMsg(vk, "Could not create Vulkan Instance: %d\n", result); } free(extensions); return result; } static void rvkDestroyInternalInstance(struct RenderVulkan *vk) { vk->api->vkDestroyInstance(vk->instance, ALLOC_VK); vk->instance = VK_NULL_HANDLE; } /** Create a self-contained Vulkan instance and set up a debug reporter * * If errors occurred, the struct will be returned in an unusable state. * It MUST then be destroyed via `rvkDestroyWorld`. * */ int rvkCreateWorld(struct RenderVulkan **vkOut, bool validation) { struct RenderVulkan *vk = calloc(1, sizeof(*vk)); *vkOut = vk; vk->world = puglNewWorld(); if (!vk->world) { rvkSetErrMsg(vk, "Could not create Pugl world"); return -1; } vk->api = calloc(1, sizeof(*vk->api)); vk->api->handle = loadVulkanLibrary(); if (!vk->api->handle) { rvkSetErrMsg(vk, "Error loading Vulkan shared library:\n%s\n", appDlerror()); return -1; } loadVulkanGetInstanceProcAddrFunc(vk->api->handle, &vk->api->vkGetInstanceProcAddr); if (!vk->api->vkGetInstanceProcAddr) { rvkSetErrMsg(vk, "Error loading `vkGetInstanceProcAddr`:\n%s", appDlerror()); return -1; } vk->api->vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion"); if (!vk->api->vkEnumerateInstanceVersion) { rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceVersion`"); return -1; } vk->api->vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties"); if (!vk->api->vkEnumerateInstanceExtensionProperties) { rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceExtensionProperties`"); return -1; } vk->api->vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vk->api->vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties"); if (!vk->api->vkEnumerateInstanceLayerProperties) { rvkSetErrMsg(vk, "Error loading `vkEnumerateInstanceLayerProperties`"); return -1; } vk->api->vkCreateInstance = (PFN_vkCreateInstance)vk->api->vkGetInstanceProcAddr(NULL, "vkCreateInstance"); if (!vk->api->vkCreateInstance) { rvkSetErrMsg(vk, "Error loading `vkCreateInstance`"); return -1; } VkResult result; // FIXME: Use `vkEnumerateInstanceExtensionProperties` to query for // debug & validation support or it will fail if not found. if (validation) { static const char *const instanceLayers[] = { "VK_LAYER_KHRONOS_validation" }; const uint32_t nInstanceLayers = sizeof(instanceLayers) / sizeof(instanceLayers[0]); static const char *const instanceExtensions[] = { VK_EXT_DEBUG_REPORT_EXTENSION_NAME }; const uint32_t nInstanceExtensions = sizeof(instanceExtensions) / sizeof(instanceExtensions[0]); if ((result = rvkCreateInternalInstance(vk, nInstanceLayers, instanceLayers, nInstanceExtensions, instanceExtensions))) { return -1; } } else { if ((result = rvkCreateInternalInstance(vk, 0, NULL, 0, NULL))) { return -1; } } static const char *const strErrLd = "Error loading instance function %s"; static const char *const _vkDestroyInstance = "vkDestroyInstance"; vk->api->vkDestroyInstance = (PFN_vkDestroyInstance)vk->api->vkGetInstanceProcAddr(vk->instance, _vkDestroyInstance); if (!vk->api->vkDestroyInstance) { rvkSetErrMsg(vk, strErrLd, _vkDestroyInstance); return -1; } /* It is okay if debug reporter functions are not resolved (for now) */ vk->api->vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)vk->api->vkGetInstanceProcAddr(vk->instance, "vkCreateDebugReportCallbackEXT"); vk->api->vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)vk->api->vkGetInstanceProcAddr(vk->instance, "vkDestroyDebugReportCallbackEXT"); /* But not if we are unable to destroy a created debug reporter */ if (vk->api->vkCreateDebugReportCallbackEXT && !vk->api->vkDestroyDebugReportCallbackEXT) { rvkSetErrMsg(vk, "No debug reporter destroy function loaded for corresponding create function\n"); return -1; } /* Dynamically load instance-level Vulkan function pointers via `vkGetInstanceProcAddr` * * TODO: This could perhaps be generated by a script and put into a separate "loader" file */ static const char *const _vkDestroySurfaceKHR = "vkDestroySurfaceKHR"; vk->api->vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkDestroySurfaceKHR); if (!vk->api->vkDestroySurfaceKHR) { rvkSetErrMsg(vk, strErrLd, _vkDestroySurfaceKHR); return -1; } static const char *const _vkEnumeratePhysicalDevices = "vkEnumeratePhysicalDevices"; vk->api->vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)vk->api->vkGetInstanceProcAddr(vk->instance, _vkEnumeratePhysicalDevices); if (!vk->api->vkEnumeratePhysicalDevices) { rvkSetErrMsg(vk, strErrLd, _vkEnumeratePhysicalDevices); return -1; } static const char *const _vkGetPhysicalDeviceProperties = "vkGetPhysicalDeviceProperties"; vk->api->vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceProperties); if (!vk->api->vkGetPhysicalDeviceProperties) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceProperties); return -1; } static const char *const _vkGetPhysicalDeviceQueueFamilyProperties = "vkGetPhysicalDeviceQueueFamilyProperties"; vk->api->vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceQueueFamilyProperties); if (!vk->api->vkGetPhysicalDeviceQueueFamilyProperties) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceQueueFamilyProperties); return -1; } static const char *const _vkGetPhysicalDeviceSurfaceSupportKHR = "vkGetPhysicalDeviceSurfaceSupportKHR"; vk->api->vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceSupportKHR); if (!vk->api->vkGetPhysicalDeviceSurfaceSupportKHR) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceSupportKHR); return -1; } static const char *const _vkGetPhysicalDeviceMemoryProperties = "vkGetPhysicalDeviceMemoryProperties"; vk->api->vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceMemoryProperties); if (!vk->api->vkGetPhysicalDeviceMemoryProperties) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceMemoryProperties); return -1; } static const char *const _vkEnumerateDeviceExtensionProperties = "vkEnumerateDeviceExtensionProperties"; vk->api->vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)vk->api->vkGetInstanceProcAddr(vk->instance, _vkEnumerateDeviceExtensionProperties); if (!vk->api->vkEnumerateDeviceExtensionProperties) { rvkSetErrMsg(vk, strErrLd, _vkEnumerateDeviceExtensionProperties); return -1; } static const char *const _vkCreateDevice = "vkCreateDevice"; vk->api->vkCreateDevice = (PFN_vkCreateDevice)vk->api->vkGetInstanceProcAddr(vk->instance, _vkCreateDevice); if (!vk->api->vkCreateDevice) { rvkSetErrMsg(vk, strErrLd, _vkCreateDevice); return -1; } static const char *const _vkGetDeviceProcAddr = "vkGetDeviceProcAddr"; vk->api->vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetDeviceProcAddr); if (!vk->api->vkGetDeviceProcAddr) { rvkSetErrMsg(vk, strErrLd, _vkGetDeviceProcAddr); return -1; } static const char *const _vkGetPhysicalDeviceSurfaceCapabilitiesKHR = "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"; vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceCapabilitiesKHR); if (!vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceCapabilitiesKHR); return -1; } static const char *const _vkGetPhysicalDeviceSurfaceFormatsKHR = "vkGetPhysicalDeviceSurfaceFormatsKHR"; vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfaceFormatsKHR); if (!vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfaceFormatsKHR); return -1; } static const char *const _vkGetPhysicalDeviceSurfacePresentModesKHR = "vkGetPhysicalDeviceSurfacePresentModesKHR"; vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vk->api->vkGetInstanceProcAddr(vk->instance, _vkGetPhysicalDeviceSurfacePresentModesKHR); if (!vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR) { rvkSetErrMsg(vk, strErrLd, _vkGetPhysicalDeviceSurfacePresentModesKHR); return -1; } /* End loading function pointers */ if (vk->api->vkCreateDebugReportCallbackEXT) { printf("Creating debug reporter\n"); VkDebugReportCallbackCreateInfoEXT debugInfo = { 0 }; debugInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; debugInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; debugInfo.pfnCallback = debugCallback; if ((result = vk->api->vkCreateDebugReportCallbackEXT(vk->instance, &debugInfo, ALLOC_VK, &vk->debugCallback))) { rvkSetErrMsg(vk, "Could not create debug reporter: %d", result); return -1; } } return 0; } /** Create the view, window, and surface for this application */ int rvkCreateSurface(struct RenderVulkan *vk, const PuglRect frame) { vk->view = puglNewView(vk->world); if (!vk->view) { rvkSetErrMsg(vk, "Could not create Pugl view"); return -1; } puglSetFrame(vk->view, frame); puglSetHandle(vk->view, vk); puglSetBackend(vk->view, puglStubBackend()); puglSetViewHint(vk->view, PUGL_RESIZABLE, true); PuglStatus status; if ((status = puglCreateWindow(vk->view, "Vulkan Application Using Pugl"))) { rvkSetErrMsg(vk, "Could not create window: %s\n", puglStrerror(status)); return -1; } VkResult result; if ((result = createVulkanSurface(vk->view, vk->instance, vk->api->vkGetInstanceProcAddr, ALLOC_VK, &vk->surface))) { rvkSetErrMsg(vk, "Could not create window surface: %d\n", result); return -1; } return 0; } static void printQueueFamilyCapabilities(const VkQueueFlagBits queueFlags) { const char *maybeOr = ""; const char *const or = " | "; if (queueFlags & VK_QUEUE_GRAPHICS_BIT) { printf("%sGRAPHICS", maybeOr); maybeOr = or; } if (queueFlags & VK_QUEUE_COMPUTE_BIT) { printf("%sCOMPUTE", maybeOr); maybeOr = or; } if (queueFlags & VK_QUEUE_TRANSFER_BIT) { printf("%sTRANSFER", maybeOr); maybeOr = or; } if (queueFlags & VK_QUEUE_SPARSE_BINDING_BIT) { printf("%sSPARSE_BINDING", maybeOr); maybeOr = or; } if (queueFlags & VK_QUEUE_PROTECTED_BIT) { printf("%sPROTECTED", maybeOr); maybeOr = or; } printf("\n"); } /** Checks if a particular physical device is suitable for this application. * * This function is referentially transparent (aside from printing to stdout). * * Choosing a physical device is an *extremely* application-specific procedure. * * All rendering in Vulkan is done off-screen by default. To get rendered * results on-screen they must be "presented" to a surface. * The Vulkan spec allows devices to have presentation done on a separate queue * family than GRAPHICS, or no present support at all. However, every graphics * card today that is capable of connecting to a display has at least one queue * family capable of both GRAPHICS and present. * * This single-threaded application will use only one queue for all operations. * More specifically, it will make use of GRAPHICS and TRANSFER operations on * a single queue retrieved from a GRAPHICS queue family that supports present. * * In my experience, most cards follow this format: * * INTEGRATED: Typically have one queue family for all operations. * May retrieve only one queue from this single queue family. * DEDICATED: Older cards typically have one queue family for GRAPHICS and one * for TRANSFER. Newer cards typically have a separate queue family * for COMPUTE. Remember that all GRAPHICS queue families * implicitly allow both COMPUTE and TRANSFER operations on it as * well. Programmers making use of separate queue families may allow * devices to work more efficiently. * * May typically retrieve up to a few queues from either queue * family. The maximum number of available queues is specific to * that device's queue families. Programmers making use of separate * queues for highly independent workloads may allow devices to work * more efficiently. Queues must be submitted to from a single * thread at a time, so programmers wanting to make use of * multithreaded queue submission must retrieve queues per-thread. * * GOTCHA: Some devices may have multiple GRAPHICS queue families * with only one of them able to present. Do not assume a * device is unsuitable until ALL queue families have been * checked. * * Because this application will load all resources before any rendering begins, * and the amount of resources are small enough to be loaded almost instantly, * it will not make use of a separate TRANSFER queue family. * * Information for many devices is available online at * https://vulkan.gpuinfo.org/ */ static bool rvkIsDeviceSuitable(const struct RenderVulkan *const vk, const VkPhysicalDevice physicalDevice, uint32_t *const graphicsIndex) { uint32_t nQueueFamilies; vk->api->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &nQueueFamilies, NULL); VkQueueFamilyProperties *queueProperties = malloc(nQueueFamilies * sizeof(*queueProperties)); vk->api->vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &nQueueFamilies, queueProperties); for (uint32_t i = 0; i < nQueueFamilies; ++i) { printf("Queue family %d queueCount:\t%d\n", i, queueProperties[i].queueCount); } for (uint32_t i = 0; i < nQueueFamilies; ++i) { printf("Queue family %d queueFlags:\t", i); printQueueFamilyCapabilities(queueProperties[i].queueFlags); } uint32_t g; for (g = 0; g < nQueueFamilies; ++g) { if (queueProperties[g].queueFlags & VK_QUEUE_GRAPHICS_BIT) { VkBool32 canSurface; vk->api->vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, g, vk->surface, &canSurface); if (canSurface) break; } } free(queueProperties); if (g >= nQueueFamilies) { /* We only support graphics and present on the same queue family. */ printf("No graphics+support queue families found on this device\n"); return false; } VkBool32 canSwapchain = VK_FALSE; uint32_t nExtensions; vk->api->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &nExtensions, NULL); VkExtensionProperties *availableExtensions = malloc(nExtensions * sizeof(*availableExtensions)); vk->api->vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &nExtensions, availableExtensions); for (uint32_t i = 0; i < nExtensions; ++i) { if (!strcmp(availableExtensions[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) { canSwapchain = VK_TRUE; break; } } free(availableExtensions); if (!canSwapchain) { printf("Cannot use a swapchain on this device\n"); return false; } *graphicsIndex = g; return true; } const char *strDeviceType(const VkPhysicalDeviceType deviceType) { switch (deviceType) { case VK_PHYSICAL_DEVICE_TYPE_OTHER: return "Other"; case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "Integrated GPU"; case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "Discrete GPU"; case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "Virtual GPU"; case VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU"; default: return "Unknown"; } } /** Selects a physical device * * This application will not attempt to find the "most powerful" device on the * system, and will choose the first suitable device it finds. */ int rvkSelectPhysicalDevice(struct RenderVulkan *vk) { int ret = 0; if (!vk->surface) { rvkSetErrMsg(vk, "Cannot select a physical device without a surface"); return -1; } static const char *const strErrEnum = "Could not enumerate physical devices: %s"; static const char *const strWarnEnum = "Warn: Incomplete enumeration of physical devices"; uint32_t nDevices; VkResult result; if ((result = vk->api->vkEnumeratePhysicalDevices(vk->instance, &nDevices, NULL))) { if (result != VK_INCOMPLETE) { rvkSetErrMsg(vk, strErrEnum, result); return -1; } else { fprintf(stderr, "%s\n", strWarnEnum); } } if (!nDevices) { rvkSetErrMsg(vk, "No physical devices found"); return -1; } VkPhysicalDevice *devices = malloc(nDevices * sizeof(*devices)); VkPhysicalDeviceProperties *deviceProperties = malloc(nDevices * sizeof(*deviceProperties)); if ((result = vk->api->vkEnumeratePhysicalDevices(vk->instance, &nDevices, devices))) { if (result != VK_INCOMPLETE) { rvkSetErrMsg(vk, strErrEnum, result); ret = -1; goto done; } else { fprintf(stderr, "%s\n", strWarnEnum); } } const char *strType; uint32_t i; for (i = 0; i < nDevices; ++i) { vk->api->vkGetPhysicalDeviceProperties(devices[i], &deviceProperties[i]); strType = strDeviceType(deviceProperties[i].deviceType); printf("Found physical device %d/%d:\t`%s`\t(%s)\n", i+1, nDevices, deviceProperties[i].deviceName, strType); } for (i = 0; i < nDevices; ++i) { strType = strDeviceType(deviceProperties[i].deviceType); printf("Checking suitability for\t`%s`...\t(%s)\n", deviceProperties[i].deviceName, strType); uint32_t graphicsIndex; if (rvkIsDeviceSuitable(vk, devices[i], &graphicsIndex)) { printf("Using physical device:\t\t`%s`\t(%s)\n", deviceProperties[i].deviceName, strDeviceType(deviceProperties[i].deviceType)); vk->deviceProperties = deviceProperties[i]; vk->physicalDevice = devices[i]; vk->graphicsIndex = graphicsIndex; printf("Using queue family index:\t%d\tfor\tGRAPHICS\n", vk->graphicsIndex); goto done; } printf("Device `%s` (%s) not suitable\n", deviceProperties[i].deviceName, strType); } if (i >= nDevices) { rvkSetErrMsg(vk, "No suitable devices found"); ret = -1; } done: free(deviceProperties); free(devices); return ret; } static int rvkLoadDeviceFunctions(struct RenderVulkan *vk, VkDevice device) { const char *const strErrLd = "Error loading device function %s"; static const char *const _vkDestroyDevice = "vkDestroyDevice"; vk->dev->vkDestroyDevice = (PFN_vkDestroyDevice)vk->api->vkGetDeviceProcAddr(device, _vkDestroyDevice); if (!vk->dev->vkDestroyDevice) { rvkSetErrMsg(vk, strErrLd, _vkDestroyDevice); return -1; } static const char *const _vkDeviceWaitIdle = "vkDeviceWaitIdle"; vk->dev->vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)vk->api->vkGetDeviceProcAddr(device, _vkDeviceWaitIdle); if (!vk->dev->vkDeviceWaitIdle) { rvkSetErrMsg(vk, strErrLd, _vkDeviceWaitIdle); return -1; } static const char *const _vkGetDeviceQueue = "vkGetDeviceQueue"; vk->dev->vkGetDeviceQueue = (PFN_vkGetDeviceQueue)vk->api->vkGetDeviceProcAddr(device, _vkGetDeviceQueue); if (!vk->dev->vkGetDeviceQueue) { rvkSetErrMsg(vk, strErrLd, _vkGetDeviceQueue); return -1; } static const char *const _vkQueueWaitIdle = "vkQueueWaitIdle"; vk->dev->vkQueueWaitIdle = (PFN_vkQueueWaitIdle)vk->api->vkGetDeviceProcAddr(device, _vkQueueWaitIdle); if (!vk->dev->vkQueueWaitIdle) { rvkSetErrMsg(vk, strErrLd, _vkQueueWaitIdle); return -1; } static const char *const _vkCreateCommandPool = "vkCreateCommandPool"; vk->dev->vkCreateCommandPool = (PFN_vkCreateCommandPool)vk->api->vkGetDeviceProcAddr(device, _vkCreateCommandPool); if (!vk->dev->vkCreateCommandPool) { rvkSetErrMsg(vk, strErrLd, _vkCreateCommandPool); return -1; } static const char *const _vkDestroyCommandPool = "vkDestroyCommandPool"; vk->dev->vkDestroyCommandPool = (PFN_vkDestroyCommandPool)vk->api->vkGetDeviceProcAddr(device, _vkDestroyCommandPool); if (!vk->dev->vkDestroyCommandPool) { rvkSetErrMsg(vk, strErrLd, _vkDestroyCommandPool); return -1; } static const char *const _vkCreateSwapchainKHR = "vkCreateSwapchainKHR"; vk->dev->vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vk->api->vkGetDeviceProcAddr(device, _vkCreateSwapchainKHR); if (!vk->dev->vkCreateSwapchainKHR) { rvkSetErrMsg(vk, strErrLd, _vkCreateSwapchainKHR); return -1; } static const char *const _vkDestroySwapchainKHR = "vkDestroySwapchainKHR"; vk->dev->vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vk->api->vkGetDeviceProcAddr(device, _vkDestroySwapchainKHR); if (!vk->dev->vkDestroySwapchainKHR) { rvkSetErrMsg(vk, strErrLd, _vkDestroySwapchainKHR); return -1; } static const char *const _vkGetSwapchainImagesKHR = "vkGetSwapchainImagesKHR"; vk->dev->vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vk->api->vkGetDeviceProcAddr(device, _vkGetSwapchainImagesKHR); if (!vk->dev->vkGetSwapchainImagesKHR) { rvkSetErrMsg(vk, strErrLd, _vkGetSwapchainImagesKHR); return -1; } static const char *const _vkCreateImageView = "vkCreateImageView"; vk->dev->vkCreateImageView = (PFN_vkCreateImageView)vk->api->vkGetDeviceProcAddr(device, _vkCreateImageView); if (!vk->dev->vkCreateImageView) { rvkSetErrMsg(vk, strErrLd, _vkCreateImageView); return -1; } static const char *const _vkDestroyImageView = "vkDestroyImageView"; vk->dev->vkDestroyImageView = (PFN_vkDestroyImageView)vk->api->vkGetDeviceProcAddr(device, _vkDestroyImageView); if (!vk->dev->vkDestroyImageView) { rvkSetErrMsg(vk, strErrLd, _vkDestroyImageView); return -1; } static const char *const _vkAllocateCommandBuffers = "vkAllocateCommandBuffers"; vk->dev->vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)vk->api->vkGetDeviceProcAddr(device, _vkAllocateCommandBuffers); if (!vk->dev->vkAllocateCommandBuffers) { rvkSetErrMsg(vk, strErrLd, _vkAllocateCommandBuffers); return -1; } static const char *const _vkFreeCommandBuffers = "vkFreeCommandBuffers"; vk->dev->vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)vk->api->vkGetDeviceProcAddr(device, _vkFreeCommandBuffers); if (!vk->dev->vkFreeCommandBuffers) { rvkSetErrMsg(vk, strErrLd, _vkFreeCommandBuffers); return -1; } static const char *const _vkBeginCommandBuffer = "vkBeginCommandBuffer"; vk->dev->vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)vk->api->vkGetDeviceProcAddr(device, _vkBeginCommandBuffer); if (!vk->dev->vkBeginCommandBuffer) { rvkSetErrMsg(vk, strErrLd, _vkBeginCommandBuffer); return -1; } static const char *const _vkEndCommandBuffer = "vkEndCommandBuffer"; vk->dev->vkEndCommandBuffer = (PFN_vkEndCommandBuffer)vk->api->vkGetDeviceProcAddr(device, _vkEndCommandBuffer); if (!vk->dev->vkEndCommandBuffer) { rvkSetErrMsg(vk, strErrLd, _vkEndCommandBuffer); return -1; } static const char *const _vkCmdPipelineBarrier = "vkCmdPipelineBarrier"; vk->dev->vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)vk->api->vkGetDeviceProcAddr(device, _vkCmdPipelineBarrier); if (!vk->dev->vkCmdPipelineBarrier) { rvkSetErrMsg(vk, strErrLd, _vkCmdPipelineBarrier); return -1; } static const char *const _vkCmdClearColorImage = "vkCmdClearColorImage"; vk->dev->vkCmdClearColorImage = (PFN_vkCmdClearColorImage)vk->api->vkGetDeviceProcAddr(device, _vkCmdClearColorImage); if (!vk->dev->vkCmdClearColorImage) { rvkSetErrMsg(vk, strErrLd, _vkCmdClearColorImage); return -1; } static const char *const _vkCreateSemaphore = "vkCreateSemaphore"; vk->dev->vkCreateSemaphore = (PFN_vkCreateSemaphore)vk->api->vkGetDeviceProcAddr(device, _vkCreateSemaphore); if (!vk->dev->vkCreateSemaphore) { rvkSetErrMsg(vk, strErrLd, _vkCreateSemaphore); return -1; } static const char *const _vkCreateFence = "vkCreateFence"; vk->dev->vkCreateFence = (PFN_vkCreateFence)vk->api->vkGetDeviceProcAddr(device, _vkCreateFence); if (!vk->dev->vkCreateFence) { rvkSetErrMsg(vk, strErrLd, _vkCreateFence); return -1; } static const char *const _vkDestroyFence = "vkDestroyFence"; vk->dev->vkDestroyFence = (PFN_vkDestroyFence)vk->api->vkGetDeviceProcAddr(device, _vkDestroyFence); if (!vk->dev->vkDestroyFence) { rvkSetErrMsg(vk, strErrLd, _vkDestroyFence); return -1; } static const char *const _vkGetFenceStatus = "vkGetFenceStatus"; vk->dev->vkGetFenceStatus = (PFN_vkGetFenceStatus)vk->api->vkGetDeviceProcAddr(device, _vkGetFenceStatus); if (!vk->dev->vkGetFenceStatus) { rvkSetErrMsg(vk, strErrLd, _vkGetFenceStatus); return -1; } static const char *const _vkDestroySemaphore = "vkDestroySemaphore"; vk->dev->vkDestroySemaphore = (PFN_vkDestroySemaphore)vk->api->vkGetDeviceProcAddr(device, _vkDestroySemaphore); if (!vk->dev->vkDestroySemaphore) { rvkSetErrMsg(vk, strErrLd, _vkDestroySemaphore); return -1; } static const char *const _vkAcquireNextImageKHR = "vkAcquireNextImageKHR"; vk->dev->vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vk->api->vkGetDeviceProcAddr(device, _vkAcquireNextImageKHR); if (!vk->dev->vkAcquireNextImageKHR) { rvkSetErrMsg(vk, strErrLd, _vkAcquireNextImageKHR); return -1; } static const char *const _vkWaitForFences = "vkWaitForFences"; vk->dev->vkWaitForFences = (PFN_vkWaitForFences)vk->api->vkGetDeviceProcAddr(device, _vkWaitForFences); if (!vk->dev->vkWaitForFences) { rvkSetErrMsg(vk, strErrLd, _vkWaitForFences); return -1; } static const char *const _vkResetFences = "vkResetFences"; vk->dev->vkResetFences = (PFN_vkResetFences)vk->api->vkGetDeviceProcAddr(device, _vkResetFences); if (!vk->dev->vkResetFences) { rvkSetErrMsg(vk, strErrLd, _vkResetFences); return -1; } static const char *const _vkQueueSubmit = "vkQueueSubmit"; vk->dev->vkQueueSubmit = (PFN_vkQueueSubmit)vk->api->vkGetDeviceProcAddr(device, _vkQueueSubmit); if (!vk->dev->vkQueueSubmit) { rvkSetErrMsg(vk, strErrLd, _vkQueueSubmit); return -1; } static const char *const _vkQueuePresentKHR = "vkQueuePresentKHR"; vk->dev->vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vk->api->vkGetDeviceProcAddr(device, _vkQueuePresentKHR); if (!vk->dev->vkQueuePresentKHR) { rvkSetErrMsg(vk, strErrLd, _vkQueuePresentKHR); return -1; } return 0; } /** Opens the logical device, retrieves queue(s), and creates the command pool * for this application. */ int rvkOpenDevice(struct RenderVulkan *vk) { if (vk->device) { rvkSetErrMsg(vk, "Renderer already has an opened device"); return -1; } const float graphicsQueuePriority = 1.0f; const char *const swapchainName = VK_KHR_SWAPCHAIN_EXTENSION_NAME; VkDeviceQueueCreateInfo queueCreateInfo = { 0 }; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = vk->graphicsIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &graphicsQueuePriority; VkDeviceCreateInfo createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = 1; createInfo.pQueueCreateInfos = &queueCreateInfo; /* `enabledLayerCount` and `ppEnabledLayerNames` are ignored by modern * Vulkan implementations. * TODO: But maybe we should support the older implementations. */ createInfo.enabledExtensionCount = 1; createInfo.ppEnabledExtensionNames = &swapchainName; /* This application uses no device features. */ createInfo.pEnabledFeatures = NULL; VkDevice device; VkResult result; if ((result = vk->api->vkCreateDevice(vk->physicalDevice, &createInfo, ALLOC_VK, &device))) { rvkSetErrMsg(vk, "Could not open device `%s`: %d\n", vk->deviceProperties.deviceName, result); return -1; } vk->dev = calloc(1, sizeof(*vk->dev)); vk->device = device; if (rvkLoadDeviceFunctions(vk, device)) { return -1; } vk->dev->vkGetDeviceQueue(vk->device, vk->graphicsIndex, 0, &vk->graphicsQueue); VkCommandPoolCreateInfo commandInfo = { 0 }; commandInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandInfo.queueFamilyIndex = vk->graphicsIndex; VkCommandPool commandPool; if ((result = vk->dev->vkCreateCommandPool(vk->device, &commandInfo, ALLOC_VK, &commandPool))) { rvkSetErrMsg(vk, "Could not create command pool: %d\n", result); return -1; } vk->commandPool = commandPool; return 0; } static char *strPresentMode(const VkPresentModeKHR presentMode) { switch (presentMode) { case VK_PRESENT_MODE_IMMEDIATE_KHR: return "Immediate"; case VK_PRESENT_MODE_MAILBOX_KHR: return "Mailbox"; case VK_PRESENT_MODE_FIFO_KHR: return "FIFO"; case VK_PRESENT_MODE_FIFO_RELAXED_KHR: return "FIFO relaxed"; default: return "Other"; } } static bool isPresentModeSupported(const VkPresentModeKHR *const presentModes, const uint32_t nPresentModes, const VkPresentModeKHR want) { const char *const strWant = strPresentMode(want); printf("Checking for present mode:\t`%s`...\n", strWant); for (uint32_t i = 0; i < nPresentModes; ++i) { if (presentModes[i] == want) { return true; } } /* The same device on different platforms may not have the same present modes */ printf("Present mode `%s` not available for this device or platform\n", strWant); return false; } /** Configure the surface for the currently opened device. */ int rvkConfigureSurface(struct RenderVulkan *vk) { VkSurfaceFormatKHR *surfaceFormats; VkPresentModeKHR *presentModes; VkResult result; uint32_t nFormats; vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physicalDevice, vk->surface, &nFormats, NULL); if (!nFormats) { rvkSetErrMsg(vk, "No surface formats available"); return -1; } surfaceFormats = malloc(nFormats * sizeof(*surfaceFormats)); vk->api->vkGetPhysicalDeviceSurfaceFormatsKHR(vk->physicalDevice, vk->surface, &nFormats, surfaceFormats); uint32_t i; for (i = 0; i < nFormats; ++i) { const VkSurfaceFormatKHR want = { /* UNORM is *NOT* recommended for color blending, but is * useful for getting simple "HTML" colors to the screen * without manually converting to a linear color space. * * See: * MinutePhysics (Henry Reich). * "Computer Color Is Broken" * YouTube video, 4:13. March 20, 2015. * https://www.youtube.com/watch?v=LKnqECcg6Gw */ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR }; if (surfaceFormats[i].format == VK_FORMAT_UNDEFINED) { vk->surfaceFormat = want; break; } if (surfaceFormats[i].format == want.format && surfaceFormats[i].colorSpace == want.colorSpace) { vk->surfaceFormat = want; break; } } free(surfaceFormats); if (i >= nFormats) { rvkSetErrMsg(vk, "Could not find a suitable surface format"); return -1; } uint32_t nPresentModes; vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physicalDevice, vk->surface, &nPresentModes, NULL); if (!nPresentModes) { rvkSetErrMsg(vk, "No present modes available"); return -1; } presentModes = malloc(nPresentModes * sizeof(*presentModes)); vk->api->vkGetPhysicalDeviceSurfacePresentModesKHR(vk->physicalDevice, vk->surface, &nPresentModes, presentModes); VkPresentModeKHR presentMode; for (i = 0; i < nPresentModes; ++i) { presentMode = presentModes[i]; printf("Found present mode:\t\t`%s`\t(%d)\n", strPresentMode(presentMode), presentMode); } if (isPresentModeSupported(presentModes, nPresentModes, VK_PRESENT_MODE_MAILBOX_KHR)) { presentMode = VK_PRESENT_MODE_MAILBOX_KHR; } else if (isPresentModeSupported(presentModes, nPresentModes, VK_PRESENT_MODE_IMMEDIATE_KHR)) { presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; } else { presentMode = VK_PRESENT_MODE_FIFO_KHR; } free(presentModes); vk->presentMode = presentMode; printf("Using present mode:\t\t`%s`\t(%d)\n", strPresentMode(presentMode), presentMode); return 0; } static int rvkCreateRawSwapchain(struct RenderVulkan *vk, uint32_t width, uint32_t height) { /* We must retrieve the surface capabilities every time we make a new * swapchain because it can change every frame. For example, the * minimum and maximum extents can change per-frame as the user drag- * resizes the window. */ VkSurfaceCapabilitiesKHR surfaceCapabilities; VkResult result; if ((result = vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR( vk->physicalDevice, vk->surface, &surfaceCapabilities))) { rvkSetErrMsg(vk, "Could not get surface capabilities: %d", result); return -1; } /* The current window size isn't always equivalent to the Vulkan surface * drawable size, which can be observed when resizing the window on the * fly with some devices and drivers. I suspect this is the result of a * race condition between the window size and the drawable size, with * the reported window size lagging behind the drawable size, or that * the surface is proactively resized internally by the Vulkan driver * before the window system finalizes this new size. * * This has been observed on multiple platforms and seems inherent to * the window system. * * Nonetheless, clamping the returned window size to the minimum and * maximum surface capabilities seems to fix the problem completely. * * The `currentExtent` may hold a special value `UINT32_MAX` to mean * that the extent will be chosen by the swapchain, instead of the * usual other way around. This is why we pass our own width and height * instead of just querying the `currentExtent`. */ width = CLAMP(width, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width); height = CLAMP(height, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height); vk->swapchain->extent.width = width; vk->swapchain->extent.height = height; vk->swapchain->nImages = surfaceCapabilities.minImageCount; //vk->swapchain->nImages = surfaceCapabilities.maxImageCount; VkSwapchainCreateInfoKHR createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = vk->surface; createInfo.minImageCount = vk->swapchain->nImages; createInfo.imageFormat = vk->surfaceFormat.format; createInfo.imageExtent = vk->swapchain->extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; createInfo.preTransform = surfaceCapabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = vk->presentMode; createInfo.clipped = VK_TRUE; if (vk->swapchain->old) { createInfo.oldSwapchain = vk->swapchain->old->rawSwapchain; } if ((result = vk->dev->vkCreateSwapchainKHR(vk->device, &createInfo, ALLOC_VK, &vk->swapchain->rawSwapchain))) { rvkSetErrMsg(vk, "Could not create swapchain: %d", result); return -1; } return 0; } static void rvkDestroyRawSwapchain(struct RenderVulkan *vk, struct SwapchainVulkan *swapchain) { if (swapchain && swapchain->rawSwapchain) { vk->dev->vkDestroySwapchainKHR(vk->device, swapchain->rawSwapchain, ALLOC_VK); } } static VkResult createSwapchainImageViews(VkDevice device, const struct VulkanDev *const dev, struct SwapchainVulkan *const swapchain) { VkResult result; if ((result = dev->vkGetSwapchainImagesKHR(device, swapchain->rawSwapchain, &swapchain->nImages, NULL))) { return result; } swapchain->images = calloc(swapchain->nImages, sizeof(*swapchain->images)); if ((result = dev->vkGetSwapchainImagesKHR(device, swapchain->rawSwapchain, &swapchain->nImages, swapchain->images))) { return result; } #if 0 /* We don't need this yet until we start using as a render target. */ swapchain->imageViews = calloc(swapchain->nImages, sizeof(*swapchain->imageViews)); for (uint32_t i = 0; i < swapchain->nImages; ++i) { VkImageViewCreateInfo createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapchain->images[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapchain->surfaceFormat.format; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; if ((result = dev->vkCreateImageView(device, &createInfo, ALLOC_VK, &swapchain->imageViews[i]))) { return result; } } #endif return VK_SUCCESS; } static void destroySwapchainImageViews(VkDevice device, const struct VulkanDev *const dev, struct SwapchainVulkan *const swapchain) { if (!swapchain) return; if (swapchain->imageViews) { for (uint32_t i = 0; i < swapchain->nImages; ++i) { if (swapchain->imageViews[i]) { dev->vkDestroyImageView(device, swapchain->imageViews[i], ALLOC_VK); } } free(swapchain->imageViews); swapchain->imageViews = NULL; } if (swapchain->images) { free(swapchain->images); swapchain->images = NULL; swapchain->nImages = 0; } } static VkResult allocateCommandBuffers(struct RenderVulkan *vk) { VkCommandBufferAllocateInfo allocInfo = { 0 }; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = vk->commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = vk->swapchain->nImages; vk->swapchain->commandBuffers = malloc(vk->swapchain->nImages * sizeof(vk->swapchain->commandBuffers)); return vk->dev->vkAllocateCommandBuffers(vk->device, &allocInfo, vk->swapchain->commandBuffers); } static void freeCommandBuffers(struct RenderVulkan *vk, struct SwapchainVulkan *swapchain) { if (swapchain && swapchain->commandBuffers) { vk->dev->vkFreeCommandBuffers(vk->device, vk->commandPool, swapchain->nImages, swapchain->commandBuffers); free(swapchain->commandBuffers); } } static int recordCommandBuffers(struct RenderVulkan *vk) { VkClearColorValue clearValue = { 0 }; clearValue.float32[0] = (float)0xa4/0x100; // R clearValue.float32[1] = (float)0x1e/0x100; // G clearValue.float32[2] = (float)0x22/0x100; // B clearValue.float32[3] = (float)0xff/0x100; // A VkImageSubresourceRange range = { 0 }; range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; range.baseMipLevel = 0; range.levelCount = 1; range.baseArrayLayer = 0; range.layerCount = 1; VkCommandBufferBeginInfo beginInfo = { 0 }; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) { VkImageMemoryBarrier toClearBarrier = { 0 }; toClearBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; toClearBarrier.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; toClearBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; toClearBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; toClearBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; toClearBarrier.srcQueueFamilyIndex = vk->graphicsIndex; toClearBarrier.dstQueueFamilyIndex = vk->graphicsIndex; toClearBarrier.image = vk->swapchain->images[i]; toClearBarrier.subresourceRange = range; VkImageMemoryBarrier toPresentBarrier = { 0 }; toPresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; toPresentBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; toPresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; toPresentBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; toPresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; toPresentBarrier.srcQueueFamilyIndex = vk->graphicsIndex; toPresentBarrier.dstQueueFamilyIndex = vk->graphicsIndex; toPresentBarrier.image = vk->swapchain->images[i]; toPresentBarrier.subresourceRange = range; vk->dev->vkBeginCommandBuffer(vk->swapchain->commandBuffers[i], &beginInfo); vk->dev->vkCmdPipelineBarrier(vk->swapchain->commandBuffers[i], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &toClearBarrier); vk->dev->vkCmdClearColorImage(vk->swapchain->commandBuffers[i], vk->swapchain->images[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearValue, 1, &range); vk->dev->vkCmdPipelineBarrier(vk->swapchain->commandBuffers[i], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &toPresentBarrier); vk->dev->vkEndCommandBuffer(vk->swapchain->commandBuffers[i]); } return 0; } int rvkCreateSwapchain(struct RenderVulkan *vk, const uint32_t width, const uint32_t height) { struct SwapchainVulkan *oldSwapchain = vk->swapchain; vk->swapchain = calloc(1, sizeof(*vk->swapchain)); vk->swapchain->old = oldSwapchain; if (rvkCreateRawSwapchain(vk, width, height)) { return -1; } VkResult result; if ((result = createSwapchainImageViews(vk->device, vk->dev, vk->swapchain))) { rvkSetErrMsg(vk, "Could not create swapchain image views: %d", result); return -1; } if ((result = allocateCommandBuffers(vk))) { rvkSetErrMsg(vk, "Could not allocate command buffers: %d", result); return -1; } VkFenceCreateInfo fenceInfo = { 0 }; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; vk->swapchain->fences = calloc(vk->swapchain->nImages, sizeof(*vk->swapchain->fences)); for (uint32_t i = 0; i < vk->swapchain->nImages; ++i) { if ((result = vk->dev->vkCreateFence(vk->device, &fenceInfo, ALLOC_VK, &vk->swapchain->fences[i]))) { rvkSetErrMsg(vk, "Could not create render finished fence: %d", result); return -1; } } if (recordCommandBuffers(vk)) { return -1; } return 0; } // TODO: Move device into RenderDev to limit scope static void rvkDestroySwapchain(struct RenderVulkan *vk, struct SwapchainVulkan *swapchain) { if (swapchain && swapchain->fences) { for (uint32_t i = 0; i < swapchain->nImages; ++i) { if (swapchain->fences[i]) { vk->dev->vkDestroyFence(vk->device, swapchain->fences[i], ALLOC_VK); } } free(swapchain->fences); } freeCommandBuffers(vk, swapchain); destroySwapchainImageViews(vk->device, vk->dev, swapchain); rvkDestroyRawSwapchain(vk, swapchain); free(swapchain); } static bool canDestroySwapchain(const struct RenderVulkan *vk, const struct SwapchainVulkan *swapchain) { uint32_t notReady = 0; for (uint32_t i = 0; i < swapchain->nImages; ++i) { VkResult result; result = vk->dev->vkGetFenceStatus(vk->device, swapchain->fences[i]); if (result == VK_NOT_READY) { ++notReady; } } return !notReady; } /* FIXME: Race condition! Swapchains cannot be destroyed until they are done * being rendered to. */ void rvkCollectSwapchainGarbage(struct RenderVulkan *vk) { struct SwapchainVulkan *old, *pp = vk->swapchain; uint32_t count = 0; if (pp && (pp)->old) { for(pp = (pp)->old; pp; pp = old) { old = (pp)->old; rvkDestroySwapchain(vk, pp); ++count; } vk->swapchain->old = NULL; } printf("Collected %d retired swapchains\n", count); } void rvkDestroyAllSwapchains(struct RenderVulkan *vk) { struct SwapchainVulkan *swapchain, *old; for (swapchain = vk->swapchain; swapchain; swapchain = old) { old = swapchain->old; rvkDestroySwapchain(vk, swapchain); } } /** Creates any semaphores or fences for this application. */ int rvkCreateSyncObjects(struct RenderVulkan *vk) { VkSemaphoreCreateInfo semaphoreInfo = { 0 }; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.presentComplete); vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.renderFinished); return 0; } void rvkDestroySyncObjects(struct RenderVulkan *vk) { if (vk->sync.semaphore.renderFinished) { vk->dev->vkDestroySemaphore(vk->device, vk->sync.semaphore.renderFinished, ALLOC_VK); vk->sync.semaphore.renderFinished = VK_NULL_HANDLE; } if (vk->sync.semaphore.presentComplete) { vk->dev->vkDestroySemaphore(vk->device, vk->sync.semaphore.presentComplete, ALLOC_VK); vk->sync.semaphore.presentComplete = VK_NULL_HANDLE; } } static void rvkCloseDevice(struct RenderVulkan *vk) { if (vk->device) { if (vk->dev->vkDeviceWaitIdle) vk->dev->vkDeviceWaitIdle(vk->device); rvkDestroySyncObjects(vk); rvkDestroyAllSwapchains(vk); if (vk->commandPool) { vk->dev->vkDestroyCommandPool(vk->device, vk->commandPool, ALLOC_VK); vk->commandPool = VK_NULL_HANDLE; } vk->graphicsQueue = VK_NULL_HANDLE; /* `vk->device` implies `vk->dev` but device functions MAY not * be loaded. * However, all subobjects of `vk->device` imply functions loaded */ if (vk->dev->vkDestroyDevice) { vk->dev->vkDestroyDevice(vk->device, ALLOC_VK); } else { /* This is only theoretical, because we must load the "destroy" * function AFTER we create the device */ fprintf(stderr, "Fatal: Unable to destroy logical device (missing function pointer)\n"); } free(vk->dev); vk->dev = NULL; vk->device = VK_NULL_HANDLE; } } /** This must work no matter the current state of `vk` */ void rvkDestroyApplication(struct RenderVulkan *vk) { if (vk) { rvkCloseDevice(vk); if (vk->surface) { vk->api->vkDestroySurfaceKHR(vk->instance, vk->surface, ALLOC_VK); vk->surface = VK_NULL_HANDLE; } if (vk->view) { /* PuglView must be freed AFTER surface but BEFORE instance destroy */ puglFreeView(vk->view); vk->view = NULL; } } } /** This must be called AFTER `rvkDestroyApplication` if it was created */ void rvkDestroyWorld(struct RenderVulkan *vk) { if (vk) { if (vk->world) { /* PuglWorld must be unloaded AFTER PuglView but BEFORE instance destroy */ puglFreeWorld(vk->world); vk->world = NULL; } if (vk->debugCallback) { /* `vk->debugCallback` implies `vk->api` and all instance functions loaded */ vk->api->vkDestroyDebugReportCallbackEXT(vk->instance, vk->debugCallback, ALLOC_VK); vk->debugCallback = VK_NULL_HANDLE; } if (vk->instance) { rvkDestroyInternalInstance(vk); vk->instance = VK_NULL_HANDLE; } if (vk->api) { if (vk->api->handle) unloadVulkanLibrary(vk->api->handle); free(vk->api); vk->api = NULL; } if (vk->errMsg) { free(vk->errMsg); vk->errMsg = NULL; } free(vk); } } /* Normally, we would NOT exit the entire process on errors when running as * part of a larger process, but since we own this process, there isn't anything * else to do. As a plugin, we would destroy the window and all memory * associated with it, leaving the larger process intact. */ static void rvkFatal(struct RenderVulkan *vk) { fprintf(stderr, "%s\n", rvkGetErrMsg(vk)); rvkDestroyApplication(vk); rvkDestroyWorld(vk); printf("Aborting gracefully\n"); exit(1); } #define CHECK_RVK(rvk, expr) do { if ((expr)) { rvkFatal(rvk); } } while (0) int running = 1; struct Arguments args; uint32_t framesDrawn; PuglStatus onDisplay(PuglView *view) { struct RenderVulkan *vk = puglGetHandle(view); uint32_t imageIndex; PuglRect frame; VkResult result; // TODO: Swapchain recreation when resizing, minimizing, etc. while ((result = vk->dev->vkAcquireNextImageKHR( vk->device, vk->swapchain->rawSwapchain, UINT64_MAX, vk->sync.semaphore.presentComplete, VK_NULL_HANDLE, &imageIndex))) { switch (result) { case VK_SUCCESS: break; case VK_SUBOPTIMAL_KHR: case VK_ERROR_OUT_OF_DATE_KHR: printf("Reactive resize!\n"); frame = puglGetFrame(vk->view); CHECK_RVK(vk, rvkCreateSwapchain(vk, frame.width, frame.height)); continue; default: rvkSetErrMsg(vk, "Could not acquire swapchain image: %d", result); rvkFatal(vk); } } /* If running continuously and with an asynchronous presentation engine, * Vulkan can blast the queue with rendering work faster than the GPU * can execute it, causing RAM usage to grow indefinitely. We use fences * to limit the number of submitted frames to the number of swapchain * images. These fences will be required later anyway when flushing * persistently mapped uniform buffer ranges. */ vk->dev->vkWaitForFences(vk->device, 1, &vk->swapchain->fences[imageIndex], VK_TRUE, UINT64_MAX); vk->dev->vkResetFences(vk->device, 1, &vk->swapchain->fences[imageIndex]); const VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submitInfo = { 0 }; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &vk->sync.semaphore.presentComplete; submitInfo.pWaitDstStageMask = &waitStage; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &vk->swapchain->commandBuffers[imageIndex]; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &vk->sync.semaphore.renderFinished; if ((result = vk->dev->vkQueueSubmit(vk->graphicsQueue, 1, &submitInfo, vk->swapchain->fences[imageIndex] ))) { rvkSetErrMsg(vk, "Could not submit to queue: %d", result); return PUGL_FAILURE; } VkPresentInfoKHR presentInfo = { 0 }; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &vk->sync.semaphore.renderFinished; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &vk->swapchain->rawSwapchain; presentInfo.pImageIndices = &imageIndex; presentInfo.pResults = NULL; vk->dev->vkQueuePresentKHR(vk->graphicsQueue, &presentInfo); if (args.continuous) ++framesDrawn; return PUGL_SUCCESS; } static bool shouldResize(const struct RenderVulkan *vk, const PuglEvent *e) { const struct SwapchainVulkan *swapchain = vk->swapchain; return (swapchain->extent.width != e->configure.width) || (swapchain->extent.height != e->configure.height); } static PuglStatus onResize(struct RenderVulkan *vk, uint32_t width, uint32_t height) { CHECK_RVK(vk, rvkCreateSwapchain(vk, width, height)); return onDisplay(vk->view); } PuglStatus onEvent(PuglView *view, const PuglEvent *e) { printEvent(e, "Event:\t", args.verbose); struct RenderVulkan *vk = puglGetHandle(view); switch (e->type) { case PUGL_EXPOSE: return onDisplay(view); break; case PUGL_CONFIGURE: // Proactive resize if (shouldResize(vk, e)) { return onResize(vk, e->configure.width, e->configure.height); } break; case PUGL_CLOSE: running = 0; break; case PUGL_KEY_PRESS: switch (e->key.key) { case PUGL_KEY_ESCAPE: running = 0; break; case 'c': // Manually collect swapchain garbage vk->dev->vkDeviceWaitIdle(vk->device); rvkCollectSwapchainGarbage(vk); break; } break; default: break; } return PUGL_SUCCESS; } int main(int argc, char **argv) { #if defined(__linux__) /* The Mesa Vulkan drivers require this to be called */ XInitThreads(); #endif args.validation = true; args.verbose = false; args.continuous = false; parseArgs(argc, argv, &args); printArgs(argc, argv); /* Vulkan application that uses Pugl for windows and events */ struct RenderVulkan *vk; CHECK_RVK(vk, rvkCreateWorld(&vk, args.validation)); printf("Created Vulkan Instance Successfully\n"); const PuglRect frame = { 0, 0, 800, 600 }; CHECK_RVK(vk, rvkCreateSurface(vk, frame)); CHECK_RVK(vk, rvkSelectPhysicalDevice(vk)); CHECK_RVK(vk, rvkOpenDevice(vk)); CHECK_RVK(vk, rvkConfigureSurface(vk)); CHECK_RVK(vk, rvkCreateSwapchain(vk, frame.width, frame.height)); CHECK_RVK(vk, rvkCreateSyncObjects(vk)); printf("Opened Vulkan Device Successfully\n"); puglSetEventFunc(vk->view, onEvent); PuglFpsPrinter fpsPrinter = { puglGetTime(vk->world) }; puglShowWindow(vk->view); while (running) { if (args.continuous) { puglPostRedisplay(vk->view); } else { puglPollEvents(vk->world, -1); } puglDispatchEvents(vk->world); if (args.continuous) { puglPrintFps(vk->world, &fpsPrinter, &framesDrawn); } } rvkDestroyApplication(vk); rvkDestroyWorld(vk); printf("Exiting gracefully\n"); return 0; } #if 0 #if defined(_WIN32) int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { (void)hInstance; (void)hPrevInstance; (void)lpCmdLine; (void)nCmdShow; return main(); } #endif /* _WIN32 */ #endif /* 0 */