/* 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 #include // for usleep(), sleep() #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 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_vkCmdSetEvent vkCmdSetEvent; PFN_vkCmdWaitEvents vkCmdWaitEvents; PFN_vkCreateSemaphore vkCreateSemaphore; PFN_vkDestroySemaphore vkDestroySemaphore; PFN_vkCreateFence vkCreateFence; PFN_vkDestroyFence vkDestroyFence; PFN_vkCreateEvent vkCreateEvent; PFN_vkDestroyEvent vkDestroyEvent; PFN_vkGetFenceStatus vkGetFenceStatus; PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; PFN_vkWaitForFences vkWaitForFences; PFN_vkResetFences vkResetFences; PFN_vkQueueSubmit vkQueueSubmit; PFN_vkQueuePresentKHR vkQueuePresentKHR; PFN_vkSetEvent vkSetEvent; PFN_vkGetEventStatus vkGetEventStatus; }; /** Application-specific swapchain behavior */ struct SwapchainVulkan { VkSwapchainKHR rawSwapchain; VkSurfaceFormatKHR surfaceFormat; uint32_t nImages; VkExtent2D extent; VkImage *images; VkImageView *imageViews; }; struct SemaphoreVulkan { VkSemaphore dummyFinished; VkSemaphore presentComplete; VkSemaphore renderFinished; }; struct FenceVulkan { VkFence *swapchain; // Fences for each swapchain image }; struct EventVulkan { VkEvent dummy; VkEvent normal; }; struct SyncVulkan { struct SemaphoreVulkan semaphore; struct FenceVulkan fence; struct EventVulkan event; }; /** 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; 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; VkCommandBuffer *commandBuffers; VkCommandBuffer dummyBuffer; 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()); 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 _vkCmdSetEvent = "vkCmdSetEvent"; vk->dev->vkCmdSetEvent = (PFN_vkCmdSetEvent)vk->api->vkGetDeviceProcAddr(device, _vkCmdSetEvent); if (!vk->dev->vkCmdSetEvent) { rvkSetErrMsg(vk, strErrLd, _vkCmdSetEvent); return -1; } static const char *const _vkCmdWaitEvents = "vkCmdWaitEvents"; vk->dev->vkCmdWaitEvents = (PFN_vkCmdWaitEvents)vk->api->vkGetDeviceProcAddr(device, _vkCmdWaitEvents); if (!vk->dev->vkCmdWaitEvents) { rvkSetErrMsg(vk, strErrLd, _vkCmdWaitEvents); 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 _vkCreateEvent = "vkCreateEvent"; vk->dev->vkCreateEvent = (PFN_vkCreateEvent)vk->api->vkGetDeviceProcAddr(device, _vkCreateEvent); if (!vk->dev->vkCreateEvent) { rvkSetErrMsg(vk, strErrLd, _vkCreateEvent); return -1; } static const char *const _vkDestroyEvent = "vkDestroyEvent"; vk->dev->vkDestroyEvent = (PFN_vkDestroyEvent)vk->api->vkGetDeviceProcAddr(device, _vkDestroyEvent); if (!vk->dev->vkDestroyEvent) { rvkSetErrMsg(vk, strErrLd, _vkDestroyEvent); 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; } static const char *const _vkSetEvent = "vkSetEvent"; vk->dev->vkSetEvent = (PFN_vkSetEvent)vk->api->vkGetDeviceProcAddr(device, _vkSetEvent); if (!vk->dev->vkSetEvent) { rvkSetErrMsg(vk, strErrLd, _vkSetEvent); return -1; } static const char *const _vkGetEventStatus = "vkGetEventStatus"; vk->dev->vkGetEventStatus = (PFN_vkGetEventStatus)vk->api->vkGetDeviceProcAddr(device, _vkGetEventStatus); if (!vk->dev->vkGetEventStatus) { rvkSetErrMsg(vk, strErrLd, _vkGetEventStatus); 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; } static int rvkCreateRawSwapchain(struct RenderVulkan *vk, int width, int height) { VkSurfaceCapabilitiesKHR surfaceCapabilities; VkSurfaceFormatKHR *surfaceFormats; VkPresentModeKHR *presentModes; VkResult result; if ((result = vk->api->vkGetPhysicalDeviceSurfaceCapabilitiesKHR( vk->physicalDevice, vk->surface, &surfaceCapabilities))) { rvkSetErrMsg(vk, "Could not get surface capabilities: %d", result); return -1; } 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->swapchain.surfaceFormat = want; break; } if (surfaceFormats[i].format == want.format && surfaceFormats[i].colorSpace == want.colorSpace) { vk->swapchain.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; } presentMode = VK_PRESENT_MODE_FIFO_KHR; free(presentModes); printf("Using present mode:\t\t`%s`\t(%d)\n", strPresentMode(presentMode), presentMode); // TODO: Clamp vk->swapchain.extent.width = width; vk->swapchain.extent.height = height; vk->swapchain.nImages = surfaceCapabilities.minImageCount + 6; //vk->swapchain.nImages = surfaceCapabilities.maxImageCount; printf("Using %d swapchain images\n", vk->swapchain.nImages); VkSwapchainCreateInfoKHR createInfo = { 0 }; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = vk->surface; createInfo.minImageCount = vk->swapchain.nImages; createInfo.imageFormat = vk->swapchain.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 = presentMode; createInfo.clipped = VK_TRUE; createInfo.oldSwapchain = VK_NULL_HANDLE; // TODO 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) { if (vk->swapchain.rawSwapchain) { vk->dev->vkDestroySwapchainKHR(vk->device, vk->swapchain.rawSwapchain, ALLOC_VK); memset(&vk->swapchain, 0, sizeof(vk->swapchain)); } } 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->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 = 1; vk->dev->vkAllocateCommandBuffers(vk->device, &allocInfo, &vk->dummyBuffer); allocInfo.commandBufferCount = vk->swapchain.nImages; vk->commandBuffers = malloc(vk->swapchain.nImages * sizeof(vk->commandBuffers)); return vk->dev->vkAllocateCommandBuffers(vk->device, &allocInfo, vk->commandBuffers); } static void freeCommandBuffers(struct RenderVulkan *vk) { if (vk->commandBuffers) { vk->dev->vkFreeCommandBuffers(vk->device, vk->commandPool, vk->swapchain.nImages, vk->commandBuffers); free(vk->commandBuffers); vk->commandBuffers = NULL; } } 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) { vk->dev->vkBeginCommandBuffer(vk->commandBuffers[i], &beginInfo); vk->dev->vkCmdSetEvent(vk->commandBuffers[i], vk->sync.event.normal, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT); 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->vkCmdPipelineBarrier(vk->commandBuffers[i], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &toClearBarrier); vk->dev->vkCmdClearColorImage(vk->commandBuffers[i], vk->swapchain.images[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &clearValue, 1, &range); vk->dev->vkCmdPipelineBarrier(vk->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->commandBuffers[i]); } return 0; } static int recordDummyBuffer(struct RenderVulkan *vk) { VkCommandBufferBeginInfo beginInfo = { 0 }; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; vk->dev->vkBeginCommandBuffer(vk->dummyBuffer, &beginInfo); vk->dev->vkCmdWaitEvents(vk->dummyBuffer, 1, &vk->sync.event.dummy, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, NULL, 0, NULL, 0, NULL ); vk->dev->vkEndCommandBuffer(vk->dummyBuffer); return 0; } int rvkCreateSwapchain(struct RenderVulkan *vk, const int width, const int height) { 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; } return 0; } void rvkDestroySwapchain(struct RenderVulkan *vk) { freeCommandBuffers(vk); destroySwapchainImageViews(vk->device, vk->dev, &vk->swapchain); rvkDestroyRawSwapchain(vk); } /** 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.dummyFinished); vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.presentComplete); vk->dev->vkCreateSemaphore(vk->device, &semaphoreInfo, ALLOC_VK, &vk->sync.semaphore.renderFinished); VkFenceCreateInfo fenceInfo = { 0 }; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; vk->sync.fence.swapchain = calloc(vk->swapchain.nImages, sizeof(*vk->sync.fence.swapchain)); VkResult result; for (uint32_t i = 0; i < vk->swapchain.nImages; ++i) { if ((result = vk->dev->vkCreateFence(vk->device, &fenceInfo, ALLOC_VK, &vk->sync.fence.swapchain[i]))) { rvkSetErrMsg(vk, "Could not create render finished fence: %d", result); return -1; } } VkEventCreateInfo eventInfo = { 0 }; eventInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO; if ((result = vk->dev->vkCreateEvent(vk->device, &eventInfo, ALLOC_VK, &vk->sync.event.dummy))) { rvkSetErrMsg(vk, "Could not create dummy event\n"); return -1; } if ((result = vk->dev->vkCreateEvent(vk->device, &eventInfo, ALLOC_VK, &vk->sync.event.normal))) { rvkSetErrMsg(vk, "Could not create normal event\n"); return -1; } if (recordDummyBuffer(vk)) { return -1; } if (recordCommandBuffers(vk)) { return -1; } return 0; } void rvkDestroySyncObjects(struct RenderVulkan *vk) { if (vk->sync.fence.swapchain) { for (uint32_t i = 0; i < vk->swapchain.nImages; ++i) { if (vk->sync.fence.swapchain[i]) { vk->dev->vkDestroyFence(vk->device, vk->sync.fence.swapchain[i], ALLOC_VK); } } free(vk->sync.fence.swapchain); vk->sync.fence.swapchain = NULL; } 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; } if (vk->sync.semaphore.dummyFinished) { vk->dev->vkDestroySemaphore(vk->device, vk->sync.semaphore.dummyFinished, ALLOC_VK); vk->sync.semaphore.dummyFinished = VK_NULL_HANDLE; } if (vk->sync.event.dummy) { vk->dev->vkDestroyEvent(vk->device, vk->sync.event.dummy, ALLOC_VK); } if (vk->sync.event.normal) { vk->dev->vkDestroyEvent(vk->device, vk->sync.event.normal, ALLOC_VK); } } static void rvkCloseDevice(struct RenderVulkan *vk) { if (vk->device) { if (vk->dev->vkDeviceWaitIdle) vk->dev->vkDeviceWaitIdle(vk->device); rvkDestroySyncObjects(vk); rvkDestroySwapchain(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; VkResult hackSemaphore(struct RenderVulkan *vk, VkSemaphore *pSemaphore) { VkSemaphoreCreateInfo createInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; return vk->dev->vkCreateSemaphore(vk->device, &createInfo, ALLOC_VK, pSemaphore); } PuglStatus onDisplay(PuglView *view) { struct RenderVulkan *vk = puglGetHandle(view); VkResult result; const VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT }; const VkPipelineStageFlags dummyStage = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_HOST_BIT; VkSubmitInfo dummyInfo = { 0 }; dummyInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; //dummyInfo.waitSemaphoreCount = 1; //dummyInfo.pWaitSemaphores = &vk->sync.semaphore.presentComplete; dummyInfo.pWaitDstStageMask = &dummyStage; dummyInfo.commandBufferCount = 1; dummyInfo.pCommandBuffers = &vk->dummyBuffer; dummyInfo.signalSemaphoreCount = 1; dummyInfo.pSignalSemaphores = &vk->sync.semaphore.dummyFinished; static uint32_t dummy = 0; if (!dummy) { printf("%d: Submitting dummy buffer...\n", dummy); if ((result = vk->dev->vkQueueSubmit(vk->graphicsQueue, 1, &dummyInfo, VK_NULL_HANDLE ))) { rvkSetErrMsg(vk, "Could not submit dummy to queue: %d", result); running = 0; return PUGL_FAILURE; } printf("%d: Dummy buffer submitted\n", dummy); } else if (dummy == vk->swapchain.nImages-1) { usleep(500000); // TODO: set breakpoint result = vk->dev->vkGetEventStatus(vk->device, vk->sync.event.normal); if (result == VK_EVENT_SET) { printf("%d: ERROR: Queue already executed\n", dummy); } else if (result == VK_EVENT_RESET) { printf("%d: Success: queue not yet executed\n", dummy); } else { printf("%d: ERROR: %d\n", dummy, result); } printf("%d: Setting event\n", dummy); vk->dev->vkSetEvent(vk->device, vk->sync.event.dummy); } #if 0 VkSemaphore freshSemaphore; if ((result = hackSemaphore(vk, &freshSemaphore))) { fprintf(stderr, "Could not make fresh semaphore\n"); running = 0; return PUGL_FAILURE; } #else VkSemaphore freshSemaphore = vk->sync.semaphore.presentComplete; #endif const VkSemaphore waits[] = { //vk->sync.semaphore.presentComplete, freshSemaphore, vk->sync.semaphore.dummyFinished }; uint32_t imageIndex; // TODO: Swapchain recreation when rezing, minimizing, etc. // TODO: Possibly use unique semaphores per in-flight image? if (dummy < vk->swapchain.nImages-1) { printf("%d: Acquiring swapchain image...\n", dummy); } if ((result = vk->dev->vkAcquireNextImageKHR( vk->device, vk->swapchain.rawSwapchain, UINT64_MAX, //vk->sync.semaphore.presentComplete, freshSemaphore, VK_NULL_HANDLE, &imageIndex))) { rvkSetErrMsg(vk, "Could not acquire swapchain image: %d", result); running = 0; return PUGL_FAILURE; } if (dummy < vk->swapchain.nImages-1) { printf("%d: Swapchain image acquired\n", dummy); } /* 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->sync.fence.swapchain[imageIndex], VK_TRUE, UINT64_MAX); vk->dev->vkResetFences(vk->device, 1, &vk->sync.fence.swapchain[imageIndex]); VkSubmitInfo submitInfo = { 0 }; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = !dummy ? 2 : 1; submitInfo.pWaitSemaphores = waits; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &vk->commandBuffers[imageIndex]; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &vk->sync.semaphore.renderFinished; if (dummy < vk->swapchain.nImages-1) { printf("%d: Submitting queue...\n", dummy); } if ((result = vk->dev->vkQueueSubmit(vk->graphicsQueue, 1, &submitInfo, vk->sync.fence.swapchain[imageIndex] ))) { //rvkSetErrMsg(vk, "Could not submit to queue: %d", result); fprintf(stderr, "Could not submit to queue: %d", result); running = 0; return PUGL_FAILURE; } if (dummy < vk->swapchain.nImages-1) { printf("%d: Queue submitted\n", dummy); } 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; if (dummy < vk->swapchain.nImages-1) { printf("%d: Submitting present...\n", dummy); } vk->dev->vkQueuePresentKHR(vk->graphicsQueue, &presentInfo); if (dummy < vk->swapchain.nImages-1) { printf("%d: Present submitted\n", dummy); fflush(stdout); } if (args.continuous) ++framesDrawn; ++dummy; return PUGL_SUCCESS; } PuglStatus onEvent(PuglView *view, const PuglEvent *e) { printEvent(e, "Event:\t", args.verbose); switch (e->type) { case PUGL_EXPOSE: onDisplay(view); break; case PUGL_CLOSE: running = 0; break; case PUGL_KEY_PRESS: if (e->key.key == PUGL_KEY_ESCAPE) { running = 0; } 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, 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 */