#include #include #include #ifdef __APPLE__ #define VK_ENABLE_BETA_EXTENSIONS #endif #define VULKAN_HPP_NO_CONSTRUCTORS #include #include "util/types.h" #include "vkfw.hpp" namespace vk { using DebugUtilsMessengerUnique = vk::UniqueHandle; } constexpr i32 WIDTH = 800; constexpr i32 HEIGHT = 600; constexpr std::array validationLayers = { "VK_LAYER_KHRONOS_validation" }; #ifdef NDEBUG constexpr bool enableValidationLayers = false; #else constexpr bool enableValidationLayers = true; #endif class VulkanApp { public: fn run() -> void { initWindow(); initVulkan(); mainLoop(); } private: vkfw::UniqueInstance mGLFWInstance; vkfw::UniqueWindow mWindow; vk::UniqueInstance mInstance; vk::DebugUtilsMessengerUnique mDebugMessenger; vk::DispatchLoaderDynamic mLoader; vk::PhysicalDevice mPhysicalDevice; vk::UniqueDevice mDevice; vk::Queue mGraphicsQueue; vk::Queue mPresentQueue; vk::UniqueSurfaceKHR mSurface; struct QueueFamilyIndices { std::optional graphics_family; std::optional present_family; fn isComplete() -> bool { return graphics_family.has_value() && present_family.has_value(); } }; fn initWindow() -> void { mGLFWInstance = vkfw::initUnique(); vkfw::WindowHints hints; hints.clientAPI = vkfw::ClientAPI::eNone; hints.resizable = vkfw::eFalse; mWindow = vkfw::createWindowUnique(WIDTH, HEIGHT, "Vulkan", hints); } fn initVulkan() -> void { createInstance(); setupDebugMessenger(); createSurface(); pickPhysicalDevice(); createLogicalDevice(); } fn mainLoop() -> void { while (!mWindow->shouldClose()) { vkfw::waitEvents(); } } fn createInstance() -> void { if (enableValidationLayers && !checkValidationLayerSupport()) throw std::runtime_error("Validation layers requested, but not available!"); vk::ApplicationInfo appInfo { .pApplicationName = "Hello Triangle", .applicationVersion = 1, .pEngineName = "No Engine", .engineVersion = 1, .apiVersion = vk::ApiVersion10 }; // Retrieve extensions using custom function std::vector extensions = getRequiredExtensions(); // Enable the portability extension and set flags extensions.push_back(vk::KHRPortabilityEnumerationExtensionName); #if VK_HEADER_VERSION < 110 extensions.push_back(vk::KHRGetPhysicalDeviceProperties2ExtensionName); #endif vk::InstanceCreateInfo createInfo { .flags = vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR, .pApplicationInfo = &appInfo, .enabledLayerCount = enableValidationLayers ? static_cast(validationLayers.size()) : 0, .ppEnabledLayerNames = enableValidationLayers ? validationLayers.data() : nullptr, .enabledExtensionCount = static_cast(extensions.size()), .ppEnabledExtensionNames = extensions.data() }; #ifndef NDEBUG fmt::println("Available extensions:"); for (const char* extension : extensions) fmt::println("\t{}", extension); #endif try { mInstance = vk::createInstanceUnique(createInfo); mLoader = vk::DispatchLoaderDynamic(mInstance.get(), vkGetInstanceProcAddr); } catch (const vk::SystemError& err) { throw std::runtime_error("Failed to create instance: " + std::string(err.what())); } } fn setupDebugMessenger() -> void { if (!enableValidationLayers) return; vk::DebugUtilsMessengerCreateInfoEXT messengerCreateInfo { .messageSeverity = vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose | vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning | vk::DebugUtilsMessageSeverityFlagBitsEXT::eError, .messageType = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral | vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation | vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance, .pfnUserCallback = debugCallback, }; mDebugMessenger = mInstance->createDebugUtilsMessengerEXTUnique(messengerCreateInfo, nullptr, mLoader); } fn createSurface() -> void { mSurface = vkfw::createWindowSurfaceUnique(mInstance.get(), mWindow.get()); } fn pickPhysicalDevice() -> void { std::vector devices = mInstance->enumeratePhysicalDevices(); if (devices.empty()) throw std::runtime_error("Failed to find GPUs with Vulkan support!"); #ifndef NDEBUG fmt::println("Available devices:"); #endif for (const auto& device : devices) { #ifndef NDEBUG vk::PhysicalDeviceProperties properties = device.getProperties(); fmt::println("\t{}", properties.deviceName.data()); #endif if (isDeviceSuitable(device)) { mPhysicalDevice = device; break; } } if (!mPhysicalDevice) throw std::runtime_error("Failed to find a suitable GPU!"); } fn createLogicalDevice() -> void { QueueFamilyIndices indices = findQueueFamilies(mPhysicalDevice); std::vector queueCreateInfos; std::set uniqueQueueFamilies = { indices.graphics_family.value(), indices.present_family.value() }; f32 queuePriority = 1.0F; for (u32 queueFamily : uniqueQueueFamilies) { vk::DeviceQueueCreateInfo queueCreateInfo { .queueFamilyIndex = queueFamily, .queueCount = 1, .pQueuePriorities = &queuePriority }; queueCreateInfos.push_back(queueCreateInfo); } vk::PhysicalDeviceFeatures deviceFeatures; #ifdef __APPLE__ vk::DeviceCreateInfo createInfo { .queueCreateInfoCount = static_cast(queueCreateInfos.size()), .pQueueCreateInfos = queueCreateInfos.data(), .enabledExtensionCount = 1, .ppEnabledExtensionNames = { vk::KHRPortabilitySubsetExtensionName }, .pEnabledFeatures = &deviceFeatures }; #else vk::DeviceCreateInfo createInfo { .queueCreateInfoCount = static_cast(queueCreateInfos.size()), .pQueueCreateInfos = queueCreateInfos.data(), .enabledExtensionCount = 0, .ppEnabledExtensionNames = nullptr, .pEnabledFeatures = &deviceFeatures }; #endif mDevice = mPhysicalDevice.createDeviceUnique(createInfo); mGraphicsQueue = mDevice->getQueue(indices.graphics_family.value(), 0); mPresentQueue = mDevice->getQueue(indices.present_family.value(), 0); } fn isDeviceSuitable(vk::PhysicalDevice device) -> bool { QueueFamilyIndices indices = findQueueFamilies(device); return indices.isComplete(); } fn findQueueFamilies(vk::PhysicalDevice device) -> QueueFamilyIndices { QueueFamilyIndices indices; std::vector queueFamilies = device.getQueueFamilyProperties(); for (u32 i = 0; i < queueFamilies.size(); i++) { if (queueFamilies[i].queueFlags & vk::QueueFlagBits::eGraphics) indices.graphics_family = i; vk::Bool32 presentSupport = device.getSurfaceSupportKHR(i, mSurface.get()); if (presentSupport) indices.present_family = i; if (indices.isComplete()) break; } return indices; } static fn getRequiredExtensions() -> std::vector { std::span extensionsSpan = vkfw::getRequiredInstanceExtensions(); std::vector extensions(extensionsSpan.begin(), extensionsSpan.end()); if (enableValidationLayers) extensions.push_back(vk::EXTDebugUtilsExtensionName); return extensions; } static fn checkValidationLayerSupport() -> bool { std::vector availableLayers = vk::enumerateInstanceLayerProperties(); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } if (!layerFound) return false; } return true; } static VKAPI_ATTR fn VKAPI_CALL debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT /*messageSeverity*/, VkDebugUtilsMessageTypeFlagsEXT /*messageType*/, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* /*pUserData*/ ) -> vk::Bool32 { fmt::println("Validation layer: {}", pCallbackData->pMessage); return vk::False; } }; fn main() -> i32 { VulkanApp app; try { app.run(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }