RAIIfy vulkan

This commit is contained in:
Guillaume Meunier
2024-01-07 11:45:07 +01:00
parent 54fe51b21f
commit cf14f9bd8b
44 changed files with 2711 additions and 2793 deletions
+1
View File
@@ -90,6 +90,7 @@ endif()
target_compile_features(wivrn PRIVATE cxx_std_20) target_compile_features(wivrn PRIVATE cxx_std_20)
target_compile_definitions(wivrn PRIVATE "XR_USE_TIMESPEC=1") target_compile_definitions(wivrn PRIVATE "XR_USE_TIMESPEC=1")
target_compile_definitions(wivrn PRIVATE VULKAN_HPP_NO_STRUCT_CONSTRUCTORS VMA_VULKAN_VERSION=1001000)
set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden) set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden)
file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS
+99 -95
View File
@@ -24,14 +24,17 @@
#include "spdlog/common.h" #include "spdlog/common.h"
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include "utils/ranges.h" #include "utils/ranges.h"
#include "vk/details/enumerate.h"
#include "vk/vk.h" #include "vk/vk.h"
#include "xr/xr.h" #include "xr/xr.h"
#include <algorithm> #include <algorithm>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_handles.hpp>
#include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#include <openxr/openxr_platform.h> #include <openxr/openxr_platform.h>
#ifndef NDEBUG #ifndef NDEBUG
@@ -47,8 +50,6 @@
using namespace std::chrono_literals; using namespace std::chrono_literals;
application * application::instance_ = nullptr;
VkBool32 application::vulkan_debug_report_callback( VkBool32 application::vulkan_debug_report_callback(
VkDebugReportFlagsEXT flags, VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objectType, VkDebugReportObjectTypeEXT objectType,
@@ -59,7 +60,7 @@ VkBool32 application::vulkan_debug_report_callback(
const char * pMessage, const char * pMessage,
void * pUserData) void * pUserData)
{ {
if (instance_->debug_report_ignored_objects.contains(object)) if (instance().debug_report_ignored_objects.contains(object))
return VK_FALSE; return VK_FALSE;
spdlog::level::level_enum level = spdlog::level::info; spdlog::level::level_enum level = spdlog::level::info;
@@ -85,8 +86,8 @@ VkBool32 application::vulkan_debug_report_callback(
// spdlog::log(level, s); // spdlog::log(level, s);
spdlog::log(level, pMessage); spdlog::log(level, pMessage);
auto it = instance_->debug_report_object_name.find(object); auto it = instance().debug_report_object_name.find(object);
if (it != instance_->debug_report_object_name.end()) if (it != instance().debug_report_object_name.end())
{ {
spdlog::log(level, "{:#016x}: {}", object, it->second); spdlog::log(level, "{:#016x}: {}", object, it->second);
} }
@@ -123,7 +124,8 @@ void application::initialize_vulkan()
spdlog::info("Available Vulkan layers:"); spdlog::info("Available Vulkan layers:");
[[maybe_unused]] bool validation_layer_found = false; [[maybe_unused]] bool validation_layer_found = false;
for (VkLayerProperties & i: vk::details::enumerate<VkLayerProperties>(vkEnumerateInstanceLayerProperties))
for(vk::LayerProperties& i: vk_context.enumerateInstanceLayerProperties())
{ {
spdlog::info(" {}", i.layerName); spdlog::info(" {}", i.layerName);
if (!strcmp(i.layerName, "VK_LAYER_KHRONOS_validation")) if (!strcmp(i.layerName, "VK_LAYER_KHRONOS_validation"))
@@ -147,7 +149,7 @@ void application::initialize_vulkan()
bool debug_utils_found = false; bool debug_utils_found = false;
#endif #endif
spdlog::info("Available Vulkan instance extensions:"); spdlog::info("Available Vulkan instance extensions:");
for (VkExtensionProperties & i: vk::details::enumerate<VkExtensionProperties>(vkEnumerateInstanceExtensionProperties, nullptr)) for(vk::ExtensionProperties& i: vk_context.enumerateInstanceExtensionProperties(nullptr))
{ {
spdlog::info(" {}", i.extensionName); spdlog::info(" {}", i.extensionName);
@@ -183,78 +185,72 @@ void application::initialize_vulkan()
instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME); instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME);
#endif #endif
VkApplicationInfo applicationInfo{}; vk::ApplicationInfo application_info{
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; .pApplicationName = app_info.name.c_str(),
applicationInfo.apiVersion = VK_MAKE_API_VERSION(0, XR_VERSION_MAJOR(vulkan_version), XR_VERSION_MINOR(vulkan_version), 0); .applicationVersion = (uint32_t)app_info.version,
applicationInfo.pApplicationName = app_info.name.c_str(); .pEngineName = engine_name,
applicationInfo.applicationVersion = app_info.version; .engineVersion = engine_version,
applicationInfo.pEngineName = engine_name; .apiVersion = VK_MAKE_API_VERSION(0, XR_VERSION_MAJOR(vulkan_version), XR_VERSION_MINOR(vulkan_version), 0),
applicationInfo.engineVersion = engine_version; };
VkInstanceCreateInfo instanceCreateInfo{}; vk::InstanceCreateInfo instance_create_info{
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; .pApplicationInfo = &application_info,
instanceCreateInfo.pApplicationInfo = &applicationInfo; };
instanceCreateInfo.enabledLayerCount = layers.size(); instance_create_info.setPEnabledLayerNames(layers);
instanceCreateInfo.ppEnabledLayerNames = layers.data(); instance_create_info.setPEnabledExtensionNames(instance_extensions);
instanceCreateInfo.enabledExtensionCount = instance_extensions.size();
instanceCreateInfo.ppEnabledExtensionNames = instance_extensions.data();
XrVulkanInstanceCreateInfoKHR create_info{}; XrVulkanInstanceCreateInfoKHR create_info{
create_info.type = XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR; .type = XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR,
create_info.systemId = xr_system_id; .systemId = xr_system_id,
create_info.createFlags = 0; .createFlags = 0,
create_info.pfnGetInstanceProcAddr = vkGetInstanceProcAddr; .pfnGetInstanceProcAddr = vkGetInstanceProcAddr,
create_info.vulkanCreateInfo = &instanceCreateInfo; .vulkanCreateInfo = &(VkInstanceCreateInfo&)instance_create_info,
create_info.vulkanAllocator = nullptr; .vulkanAllocator = nullptr,
};
auto xrCreateVulkanInstanceKHR = auto xrCreateVulkanInstanceKHR =
xr_instance.get_proc<PFN_xrCreateVulkanInstanceKHR>("xrCreateVulkanInstanceKHR"); xr_instance.get_proc<PFN_xrCreateVulkanInstanceKHR>("xrCreateVulkanInstanceKHR");
VkResult vresult; VkResult vresult;
XrResult xresult = xrCreateVulkanInstanceKHR(xr_instance, &create_info, &vk_instance, &vresult); VkInstance tmp;
XrResult xresult = xrCreateVulkanInstanceKHR(xr_instance, &create_info, &tmp, &vresult);
CHECK_VK(vresult, "xrCreateVulkanInstanceKHR"); CHECK_VK(vresult, "xrCreateVulkanInstanceKHR");
CHECK_XR(xresult, "xrCreateVulkanInstanceKHR"); CHECK_XR(xresult, "xrCreateVulkanInstanceKHR");
vk_instance = vk::raii::Instance(vk_context, tmp);
#ifndef NDEBUG #ifndef NDEBUG
if (debug_report_found) if (debug_report_found)
{ {
VkDebugReportCallbackCreateInfoEXT debug_report_info{ vk::DebugReportCallbackCreateInfoEXT debug_report_info{
.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, .flags = vk::DebugReportFlagBitsEXT::eInformation |
.flags = VK_DEBUG_REPORT_INFORMATION_BIT_EXT | vk::DebugReportFlagBitsEXT::eWarning|
VK_DEBUG_REPORT_WARNING_BIT_EXT | vk::DebugReportFlagBitsEXT::ePerformanceWarning |
VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | vk::DebugReportFlagBitsEXT::eError |
VK_DEBUG_REPORT_ERROR_BIT_EXT | vk::DebugReportFlagBitsEXT::eDebug,
VK_DEBUG_REPORT_DEBUG_BIT_EXT,
.pfnCallback = vulkan_debug_report_callback, .pfnCallback = vulkan_debug_report_callback,
}; };
VkDebugReportCallbackEXT debug_report_callback; debug_report_callback = vk::raii::DebugReportCallbackEXT(vk_instance, debug_report_info);
auto vkCreateDebugReportCallbackEXT = get_vulkan_proc<PFN_vkCreateDebugReportCallbackEXT>("vkCreateDebugReportCallbackEXT");
CHECK_VK(vkCreateDebugReportCallbackEXT(vk_instance, &debug_report_info, nullptr, &debug_report_callback));
} }
#endif #endif
vk_physical_device = xr_system_id.physical_device(vk_instance); vk_physical_device = xr_system_id.physical_device(vk_instance);
spdlog::info("Available Vulkan device extensions:"); spdlog::info("Available Vulkan device extensions:");
for (VkExtensionProperties & i: vk::details::enumerate<VkExtensionProperties>(vkEnumerateDeviceExtensionProperties, vk_physical_device, nullptr)) for(vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties())
{ {
spdlog::info(" {}", i.extensionName); spdlog::info(" {}", i.extensionName);
} }
VkPhysicalDeviceProperties prop; vk::PhysicalDeviceProperties prop = vk_physical_device.getProperties();
vkGetPhysicalDeviceProperties(vk_physical_device, &prop);
spdlog::info("Initializing Vulkan with device {}", prop.deviceName); spdlog::info("Initializing Vulkan with device {}", prop.deviceName);
uint32_t count; std::vector<vk::QueueFamilyProperties> queue_properties = vk_physical_device.getQueueFamilyProperties();
vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &count, nullptr);
std::vector<VkQueueFamilyProperties> queue_properties(count);
vkGetPhysicalDeviceQueueFamilyProperties(vk_physical_device, &count, queue_properties.data());
vk_queue_family_index = -1; vk_queue_family_index = -1;
[[maybe_unused]] bool vk_queue_found = false; [[maybe_unused]] bool vk_queue_found = false;
for (size_t i = 0; i < queue_properties.size(); i++) for (size_t i = 0; i < queue_properties.size(); i++)
{ {
if (queue_properties[i].queueFlags & VkQueueFlagBits::VK_QUEUE_GRAPHICS_BIT) if (queue_properties[i].queueFlags & vk::QueueFlagBits::eGraphics)
{ {
vk_queue_found = true; vk_queue_found = true;
vk_queue_family_index = i; vk_queue_family_index = i;
@@ -266,30 +262,38 @@ void application::initialize_vulkan()
float queuePriority = 0.0f; float queuePriority = 0.0f;
VkDeviceQueueCreateInfo queueCreateInfo{}; vk::DeviceQueueCreateInfo queueCreateInfo{
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; .queueFamilyIndex = vk_queue_family_index,
queueCreateInfo.queueFamilyIndex = vk_queue_family_index; .queueCount = 1,
queueCreateInfo.queueCount = 1; .pQueuePriorities = &queuePriority
queueCreateInfo.pQueuePriorities = &queuePriority; };
VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR ycbcr_feature{ vk::PhysicalDeviceFeatures device_features;
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR,
.samplerYcbcrConversion = VK_TRUE};
VkPhysicalDeviceFeatures deviceFeatures{}; vk::StructureChain device_create_info{
vk::DeviceCreateInfo{
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &queueCreateInfo,
.enabledExtensionCount = (uint32_t)device_extensions.size(),
.ppEnabledExtensionNames = device_extensions.data(),
.pEnabledFeatures = &device_features,
},
vk::PhysicalDeviceSamplerYcbcrConversionFeaturesKHR{
.samplerYcbcrConversion = VK_TRUE
}
};
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.pNext = &ycbcr_feature;
createInfo.pQueueCreateInfos = &queueCreateInfo;
createInfo.queueCreateInfoCount = 1;
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = device_extensions.size();
createInfo.ppEnabledExtensionNames = device_extensions.data();
vk_device = xr_system_id.create_device(vk_physical_device, createInfo); vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get());
vkGetDeviceQueue(vk_device, vk_queue_family_index, 0, &vk_queue); vk_queue = vk_device.getQueue(vk_queue_family_index, 0);
VmaAllocatorCreateInfo info{
.physicalDevice = *vk_physical_device,
.device = *vk_device,
.instance = *vk_instance,
};
CHECK_VK(vmaCreateAllocator(&info, &allocator));
} }
void application::log_views() void application::log_views()
@@ -359,7 +363,7 @@ void application::initialize()
view_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW); view_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW);
world_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE); world_space = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE);
swapchain_format = VK_FORMAT_UNDEFINED; swapchain_format = vk::Format::eUndefined;
for (auto i: xr_session.get_swapchain_formats()) for (auto i: xr_session.get_swapchain_formats())
{ {
if (std::find(supported_formats.begin(), supported_formats.end(), i) != supported_formats.end()) if (std::find(supported_formats.begin(), supported_formats.end(), i) != supported_formats.end())
@@ -369,7 +373,7 @@ void application::initialize()
} }
} }
if (swapchain_format == VK_FORMAT_UNDEFINED) if (swapchain_format == vk::Format::eUndefined)
throw std::runtime_error("No supported swapchain format"); throw std::runtime_error("No supported swapchain format");
spdlog::info("Using format {}", string_VkFormat(swapchain_format)); spdlog::info("Using format {}", string_VkFormat(swapchain_format));
@@ -387,7 +391,11 @@ void application::initialize()
spdlog::info("Created swapchain {}: {}x{}", xr_swapchains.size(), xr_swapchains.back().width(), xr_swapchains.back().height()); spdlog::info("Created swapchain {}: {}x{}", xr_swapchains.size(), xr_swapchains.back().width(), xr_swapchains.back().height());
} }
vk_cmdpool = vk::command_pool{vk_device, vk_queue_family_index}; vk::CommandPoolCreateInfo cmdpool_create_info;
cmdpool_create_info.queueFamilyIndex = vk_queue_family_index;
cmdpool_create_info.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
vk_cmdpool = vk::raii::CommandPool{vk_device, cmdpool_create_info};
// TODO get it from application info // TODO get it from application info
xr_actionset = xr::actionset(xr_instance, "actions", "Actions"); xr_actionset = xr::actionset(xr_instance, "actions", "Actions");
@@ -472,7 +480,7 @@ void application::process_binding_action(std::vector<XrActionSuggestedBinding> &
std::pair<XrAction, XrActionType> application::get_action(const std::string & requested_name) std::pair<XrAction, XrActionType> application::get_action(const std::string & requested_name)
{ {
for (const auto & [action, type, name]: instance_->actions) for (const auto & [action, type, name]: instance().actions)
{ {
if (name == requested_name) if (name == requested_name)
return {action, type}; return {action, type};
@@ -538,18 +546,16 @@ application::application(application_info info) :
PFN_xrInitializeLoaderKHR initializeLoader = nullptr; PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
if (XR_SUCCEEDED(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&initializeLoader)))) if (XR_SUCCEEDED(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&initializeLoader))))
{ {
XrLoaderInitInfoAndroidKHR loaderInitInfoAndroid{}; XrLoaderInitInfoAndroidKHR loaderInitInfoAndroid{
loaderInitInfoAndroid.type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR; .type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR,
loaderInitInfoAndroid.next = nullptr; .next = nullptr,
loaderInitInfoAndroid.applicationVM = app_info.native_app->activity->vm; .applicationVM = app_info.native_app->activity->vm,
loaderInitInfoAndroid.applicationContext = app_info.native_app->activity->clazz; .applicationContext = app_info.native_app->activity->clazz,
};
initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid); initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid);
} }
#endif #endif
assert(instance_ == nullptr);
instance_ = this;
try try
{ {
initialize(); initialize();
@@ -610,8 +616,6 @@ void application::cleanup()
#ifdef XR_USE_PLATFORM_ANDROID #ifdef XR_USE_PLATFORM_ANDROID
jni::jni_thread::detach(); jni::jni_thread::detach();
#endif #endif
assert(instance_ == this);
instance_ = nullptr;
} }
application::~application() application::~application()
@@ -713,29 +717,29 @@ void application::run()
std::shared_ptr<scene> application::current_scene() std::shared_ptr<scene> application::current_scene()
{ {
std::unique_lock _{instance_->scene_stack_lock}; std::unique_lock _{instance().scene_stack_lock};
if (!instance_->scene_stack.empty()) if (!instance().scene_stack.empty())
return instance_->scene_stack.back(); return instance().scene_stack.back();
else else
return {}; return {};
} }
void application::pop_scene() void application::pop_scene()
{ {
std::unique_lock _{instance_->scene_stack_lock}; std::unique_lock _{instance().scene_stack_lock};
if (!instance_->scene_stack.empty()) if (!instance().scene_stack.empty())
instance_->scene_stack.pop_back(); instance().scene_stack.pop_back();
} }
void application::push_scene(std::shared_ptr<scene> s) void application::push_scene(std::shared_ptr<scene> s)
{ {
std::unique_lock _{instance_->scene_stack_lock}; std::unique_lock _{instance().scene_stack_lock};
instance_->scene_stack.push_back(std::move(s)); instance().scene_stack.push_back(std::move(s));
} }
void application::poll_actions() void application::poll_actions()
{ {
instance_->xr_session.sync_actions(instance_->xr_actionset); instance().xr_session.sync_actions(instance().xr_actionset);
} }
bool application::read_action(XrAction action, bool & value, XrTime & last_change_time) bool application::read_action(XrAction action, bool & value, XrTime & last_change_time)
@@ -749,7 +753,7 @@ bool application::read_action(XrAction action, bool & value, XrTime & last_chang
}; };
XrActionStateBoolean state{XR_TYPE_ACTION_STATE_BOOLEAN}; XrActionStateBoolean state{XR_TYPE_ACTION_STATE_BOOLEAN};
CHECK_XR(xrGetActionStateBoolean(instance_->xr_session, &get_info, &state)); CHECK_XR(xrGetActionStateBoolean(instance().xr_session, &get_info, &state));
if (!state.isActive) if (!state.isActive)
return false; return false;
@@ -770,7 +774,7 @@ bool application::read_action(XrAction action, float & value, XrTime & last_chan
}; };
XrActionStateFloat state{XR_TYPE_ACTION_STATE_FLOAT}; XrActionStateFloat state{XR_TYPE_ACTION_STATE_FLOAT};
CHECK_XR(xrGetActionStateFloat(instance_->xr_session, &get_info, &state)); CHECK_XR(xrGetActionStateFloat(instance().xr_session, &get_info, &state));
if (!state.isActive) if (!state.isActive)
return false; return false;
@@ -791,7 +795,7 @@ bool application::read_action(XrAction action, XrVector2f & value, XrTime & last
}; };
XrActionStateVector2f state{XR_TYPE_ACTION_STATE_VECTOR2F}; XrActionStateVector2f state{XR_TYPE_ACTION_STATE_VECTOR2F};
CHECK_XR(xrGetActionStateVector2f(instance_->xr_session, &get_info, &state)); CHECK_XR(xrGetActionStateVector2f(instance().xr_session, &get_info, &state));
if (!state.isActive) if (!state.isActive)
return false; return false;
@@ -818,7 +822,7 @@ void application::haptic_start(XrAction action, XrPath subpath, int64_t duration
.frequency = frequency, .frequency = frequency,
.amplitude = amplitude}; .amplitude = amplitude};
xrApplyHapticFeedback(application::instance_->xr_session, &action_info, (XrHapticBaseHeader *)&vibration); xrApplyHapticFeedback(application::instance().xr_session, &action_info, (XrHapticBaseHeader *)&vibration);
} }
void application::haptic_stop(XrAction action, XrPath subpath) void application::haptic_stop(XrAction action, XrPath subpath)
@@ -832,7 +836,7 @@ void application::haptic_stop(XrAction action, XrPath subpath)
.subactionPath = subpath, .subactionPath = subpath,
}; };
xrStopHapticFeedback(application::instance_->xr_session, &action_info); xrStopHapticFeedback(application::instance().xr_session, &action_info);
} }
void application::session_state_changed(XrSessionState new_state, XrTime timestamp) void application::session_state_changed(XrSessionState new_state, XrTime timestamp)
+53 -41
View File
@@ -29,10 +29,12 @@
#include <array> #include <array>
#include <mutex> #include <mutex>
#include <unordered_set> #include <unordered_set>
#include <vulkan/vulkan.h> #include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
#include <openxr/openxr_platform.h> #include <openxr/openxr_platform.h>
#include <openxr/openxr_reflection.h> #include <openxr/openxr_reflection.h>
#include "vk_mem_alloc.h"
#include "singleton.h"
class scene; class scene;
@@ -49,7 +51,7 @@ struct application_info
#endif #endif
}; };
class application class application : public singleton<application>
{ {
friend class scene; friend class scene;
@@ -62,8 +64,8 @@ class application
static inline const char engine_name[] = "No engine"; static inline const char engine_name[] = "No engine";
static inline const int engine_version = VK_MAKE_VERSION(1, 0, 0); static inline const int engine_version = VK_MAKE_VERSION(1, 0, 0);
static inline const std::array<VkFormat, 2> supported_formats = {VK_FORMAT_R8G8B8A8_SRGB, static inline const std::array<vk::Format, 2> supported_formats = {vk::Format::eR8G8B8A8Srgb,
VK_FORMAT_B8G8R8A8_SRGB}; vk::Format::eB8G8R8A8Srgb};
void initialize_vulkan(); void initialize_vulkan();
@@ -77,8 +79,6 @@ class application
void session_state_changed(XrSessionState new_state, XrTime timestamp); void session_state_changed(XrSessionState new_state, XrTime timestamp);
void interaction_profile_changed(); void interaction_profile_changed();
static application * instance_;
// OpenXR stuff // OpenXR stuff
xr::instance xr_instance; xr::instance xr_instance;
xr::system xr_system_id; xr::system xr_system_id;
@@ -93,17 +93,19 @@ class application
std::vector<xr::space> action_spaces; std::vector<xr::space> action_spaces;
// Vulkan stuff // Vulkan stuff
VkInstance vk_instance{}; vk::raii::Context vk_context;
VkPhysicalDevice vk_physical_device{}; vk::raii::Instance vk_instance = nullptr;
VkDevice vk_device{}; vk::raii::PhysicalDevice vk_physical_device = nullptr;
vk::raii::Device vk_device = nullptr;
uint32_t vk_queue_family_index; uint32_t vk_queue_family_index;
VkQueue vk_queue{}; vk::raii::Queue vk_queue = nullptr;
vk::renderpass vk_renderpass; vk::raii::CommandPool vk_cmdpool = nullptr;
vk::pipeline vk_pipeline;
vk::command_pool vk_cmdpool;
VkFormat swapchain_format; vk::Format swapchain_format;
// Vulkan memory allocator stuff
VmaAllocator allocator;
static inline const std::pair<const char *, XrActionType> oculus_touch[] = { static inline const std::pair<const char *, XrActionType> oculus_touch[] = {
{"/user/hand/left/output/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, {"/user/hand/left/output/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT},
@@ -233,7 +235,6 @@ class application
{"/user/hand/left/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT}, {"/user/hand/left/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT},
{"/user/hand/right/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT}, {"/user/hand/right/input/aim/pose", XR_ACTION_TYPE_POSE_INPUT},
}; };
bool session_running = false; bool session_running = false;
@@ -261,7 +262,13 @@ class application
std::unordered_set<uint64_t> debug_report_ignored_objects; std::unordered_set<uint64_t> debug_report_ignored_objects;
std::unordered_map<uint64_t, std::string> debug_report_object_name; std::unordered_map<uint64_t, std::string> debug_report_object_name;
#ifndef NDEBUG
vk::raii::DebugReportCallbackEXT debug_report_callback = nullptr;
#endif
public: public:
using singleton<application>::instance;
application(application_info info); application(application_info info);
application(const application &) = delete; application(const application &) = delete;
@@ -274,22 +281,22 @@ public:
static bool is_session_running() static bool is_session_running()
{ {
return instance_->session_running; return instance().session_running;
} }
static bool is_focused() static bool is_focused()
{ {
return instance_->session_focused; return instance().session_focused;
} }
static bool is_visible() static bool is_visible()
{ {
return instance_->session_visible; return instance().session_visible;
} }
static bool is_exit_requested() static bool is_exit_requested()
{ {
return instance_->exit_requested; return instance().exit_requested;
}; };
static void poll_actions(); static void poll_actions();
@@ -301,18 +308,18 @@ public:
static const std::vector<std::tuple<XrAction, XrActionType, std::string>> & inputs() static const std::vector<std::tuple<XrAction, XrActionType, std::string>> & inputs()
{ {
return instance_->actions; return instance().actions;
} }
static std::pair<XrAction, XrActionType> get_action(const std::string & name); static std::pair<XrAction, XrActionType> get_action(const std::string & name);
static XrPath string_to_path(const std::string & s) static XrPath string_to_path(const std::string & s)
{ {
return instance_->xr_instance.string_to_path(s); return instance().xr_instance.string_to_path(s);
} }
static std::string path_to_string(XrPath p) static std::string path_to_string(XrPath p)
{ {
return instance_->xr_instance.path_to_string(p); return instance().xr_instance.path_to_string(p);
} }
void run(); void run();
@@ -326,25 +333,19 @@ public:
template <typename T, typename... Args> template <typename T, typename... Args>
static void push_scene(Args &&... args) static void push_scene(Args &&... args)
{ {
std::unique_lock _{instance_->scene_stack_lock}; std::unique_lock _{instance().scene_stack_lock};
instance_->scene_stack.push_back(std::make_shared<T>(std::forward<Args>(args)...)); instance().scene_stack.push_back(std::make_shared<T>(std::forward<Args>(args)...));
} }
static void pop_scene(); static void pop_scene();
static std::shared_ptr<scene> current_scene(); static std::shared_ptr<scene> current_scene();
static application & instance()
{
assert(instance_ != nullptr);
return *instance_;
}
template <typename T> template <typename T>
static T get_vulkan_proc(const char * proc_name) static T get_vulkan_proc(const char * proc_name)
{ {
auto proc = vkGetInstanceProcAddr(instance_->vk_instance, proc_name); auto proc = instance().vk_instance.getProcAddr(proc_name);
if (!proc) if (!proc)
throw std::runtime_error(std::string("Cannot find Vulkan function ") + proc_name); throw std::runtime_error(std::string("Cannot find Vulkan function ") + proc_name);
return (T)proc; return (T)proc;
@@ -352,58 +353,69 @@ public:
static XrSpace view() static XrSpace view()
{ {
return instance_->view_space; return instance().view_space;
}; };
static XrSpace left_grip() static XrSpace left_grip()
{ {
return instance_->action_spaces[0]; return instance().action_spaces[0];
}; };
static XrSpace left_aim() static XrSpace left_aim()
{ {
return instance_->action_spaces[1]; return instance().action_spaces[1];
}; };
static XrSpace right_grip() static XrSpace right_grip()
{ {
return instance_->action_spaces[2]; return instance().action_spaces[2];
}; };
static XrSpace right_aim() static XrSpace right_aim()
{ {
return instance_->action_spaces[3]; return instance().action_spaces[3];
}; };
static void ignore_debug_reports_for(void * object) static void ignore_debug_reports_for(void * object)
{ {
#ifndef NDEBUG #ifndef NDEBUG
instance_->debug_report_ignored_objects.emplace((uint64_t)object); instance().debug_report_ignored_objects.emplace((uint64_t)object);
#endif #endif
} }
static void unignore_debug_reports_for(void * object) static void unignore_debug_reports_for(void * object)
{ {
#ifndef NDEBUG #ifndef NDEBUG
instance_->debug_report_ignored_objects.erase((uint64_t)object); instance().debug_report_ignored_objects.erase((uint64_t)object);
#endif #endif
} }
static void set_debug_reports_name(void * object, std::string name) static void set_debug_reports_name(void * object, std::string name)
{ {
#ifndef NDEBUG #ifndef NDEBUG
instance_->debug_report_object_name[(uint64_t)object] = std::move(name); printf("set_debug_reports_name %p, %s\n", object, name.c_str());
instance().debug_report_object_name[(uint64_t)object] = std::move(name);
#endif #endif
} }
static XrTime now() static XrTime now()
{ {
return instance_->xr_instance.now(); return instance().xr_instance.now();
} }
static uint32_t queue_family_index() static uint32_t queue_family_index()
{ {
return instance_->vk_queue_family_index; return instance().vk_queue_family_index;
} }
const std::string& get_server_address() const const std::string& get_server_address() const
{ {
return server_address; return server_address;
} }
static VmaAllocator get_allocator()
{
return instance().allocator;
}
static vk::raii::Device& get_device()
{
return instance().vk_device;
}
}; };
+324 -307
View File
@@ -20,8 +20,8 @@
#include "android_decoder.h" #include "android_decoder.h"
#include "application.h" #include "application.h"
#include "scenes/stream.h" #include "scenes/stream.h"
#include "utils/check.h" #include "vk/shader.h"
#include "vk/device_memory.h" #include "vk/pipeline.h"
#include <algorithm> #include <algorithm>
#include <android/hardware_buffer.h> #include <android/hardware_buffer.h>
#include <cassert> #include <cassert>
@@ -33,140 +33,133 @@
#include <mutex> #include <mutex>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <thread> #include <thread>
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_android.h> #include <vulkan/vulkan_android.h>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_raii.hpp>
#include "magic_enum.hpp"
DEUGLIFY(AMediaFormat) DEUGLIFY(AMediaFormat)
struct wivrn::android::decoder::pipeline_context struct wivrn::android::decoder::pipeline_context
{ {
VkDevice device; vk::raii::Device& device;
VkAndroidHardwareBufferFormatPropertiesANDROID ahb_format; vk::AndroidHardwareBufferFormatPropertiesANDROID ahb_format;
VkSamplerYcbcrConversion ycbcr_conversion; vk::raii::SamplerYcbcrConversion ycbcr_conversion = nullptr;
VkSampler sampler; vk::raii::Sampler sampler = nullptr;
std::vector<VkFramebuffer> framebuffers; vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr;
VkDescriptorSetLayout descriptor_set_layout; vk::raii::DescriptorPool descriptor_pool = nullptr;
VkDescriptorPool descriptor_pool;
std::mutex descriptor_pool_mutex; std::mutex descriptor_pool_mutex;
vk::pipeline_layout layout; vk::raii::PipelineLayout layout = nullptr;
vk::pipeline pipeline; vk::raii::Pipeline pipeline = nullptr;
~pipeline_context() pipeline_context(vk::raii::Device& device, const AHardwareBuffer_Desc& buffer_desc, vk::AndroidHardwareBufferFormatPropertiesANDROID & ahb_format, vk::raii::RenderPass& renderpass, const to_headset::video_stream_description::item& description) :
{
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
vkDestroySampler(device, sampler, nullptr);
vkDestroySamplerYcbcrConversion(device, ycbcr_conversion, nullptr);
}
pipeline_context(VkDevice device, const AHardwareBuffer_Desc& buffer_desc, VkAndroidHardwareBufferFormatPropertiesANDROID & ahb_format, VkRenderPass renderpass, const to_headset::video_stream_description::item& description) :
device(device), ahb_format(ahb_format) device(device), ahb_format(ahb_format)
{ {
assert(ahb_format.externalFormat != 0); assert(ahb_format.externalFormat != 0);
spdlog::info("AndroidHardwareBufferProperties"); spdlog::info("AndroidHardwareBufferProperties");
spdlog::info(" Vulkan format: {}", magic_enum::enum_name(ahb_format.format)); spdlog::info(" Vulkan format: {}", vk::to_string(ahb_format.format));
spdlog::info(" External format: {:#x}", ahb_format.externalFormat); spdlog::info(" External format: {:#x}", ahb_format.externalFormat);
spdlog::info(" Format features: {:#x}", ahb_format.formatFeatures); spdlog::info(" Format features: {}", vk::to_string(ahb_format.formatFeatures));
spdlog::info(" samplerYcbcrConversionComponents: ({}, {}, {}, {})", spdlog::info(" samplerYcbcrConversionComponents: ({}, {}, {}, {})",
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.r), vk::to_string(ahb_format.samplerYcbcrConversionComponents.r),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.g), vk::to_string(ahb_format.samplerYcbcrConversionComponents.g),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.b), vk::to_string(ahb_format.samplerYcbcrConversionComponents.b),
magic_enum::enum_name(ahb_format.samplerYcbcrConversionComponents.a)); vk::to_string(ahb_format.samplerYcbcrConversionComponents.a));
spdlog::info(" Suggested YCbCr model: {}", magic_enum::enum_name(ahb_format.suggestedYcbcrModel)); spdlog::info(" Suggested YCbCr model: {}", vk::to_string(ahb_format.suggestedYcbcrModel));
spdlog::info(" Suggested YCbCr range: {}", magic_enum::enum_name(ahb_format.suggestedYcbcrRange)); spdlog::info(" Suggested YCbCr range: {}", vk::to_string(ahb_format.suggestedYcbcrRange));
spdlog::info(" Suggested X chroma offset: {}", magic_enum::enum_name(ahb_format.suggestedXChromaOffset)); spdlog::info(" Suggested X chroma offset: {}", vk::to_string(ahb_format.suggestedXChromaOffset));
spdlog::info(" Suggested Y chroma offset: {}", magic_enum::enum_name(ahb_format.suggestedYChromaOffset)); spdlog::info(" Suggested Y chroma offset: {}", vk::to_string(ahb_format.suggestedYChromaOffset));
VkFilter yuv_filter; vk::Filter yuv_filter;
if (ahb_format.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT) if (ahb_format.formatFeatures & vk::FormatFeatureFlagBits::eSampledImageYcbcrConversionLinearFilter)
yuv_filter = VK_FILTER_LINEAR; yuv_filter = vk::Filter::eLinear;
else else
yuv_filter = VK_FILTER_NEAREST; yuv_filter = vk::Filter::eNearest;
// Create VkSamplerYcbcrConversion // Create VkSamplerYcbcrConversion
VkExternalFormatANDROID ycbcr_create_info2{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID, vk::StructureChain ycbcr_create_info
.externalFormat = ahb_format.externalFormat}; {
vk::SamplerYcbcrConversionCreateInfo{
VkSamplerYcbcrConversionCreateInfo ycbcr_create_info{ .format = vk::Format::eUndefined,
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO, .ycbcrModel = ahb_format.suggestedYcbcrModel,
.pNext = &ycbcr_create_info2, .ycbcrRange = ahb_format.suggestedYcbcrRange,
.format = VK_FORMAT_UNDEFINED, .components = ahb_format.samplerYcbcrConversionComponents,
.ycbcrModel = ahb_format.suggestedYcbcrModel, .xChromaOffset = ahb_format.suggestedXChromaOffset,
.ycbcrRange = ahb_format.suggestedYcbcrRange, .yChromaOffset = ahb_format.suggestedYChromaOffset,
.components = ahb_format.samplerYcbcrConversionComponents, .chromaFilter = yuv_filter,
.xChromaOffset = ahb_format.suggestedXChromaOffset, },
.yChromaOffset = ahb_format.suggestedYChromaOffset, vk::ExternalFormatANDROID{
.chromaFilter = yuv_filter, .externalFormat = ahb_format.externalFormat,
},
}; };
// suggested values from decoder don't actually read the metadata, so it's garbage // suggested values from decoder don't actually read the metadata, so it's garbage
if (description.range) if (description.range)
ycbcr_create_info.ycbcrRange = VkSamplerYcbcrRange(*description.range); ycbcr_create_info.get<vk::SamplerYcbcrConversionCreateInfo>().ycbcrRange = vk::SamplerYcbcrRange(*description.range);
if (description.color_model)
ycbcr_create_info.ycbcrModel = VkSamplerYcbcrModelConversion(*description.color_model);
CHECK_VK(vkCreateSamplerYcbcrConversion(device, &ycbcr_create_info, nullptr, &ycbcr_conversion)); if (description.color_model)
ycbcr_create_info.get<vk::SamplerYcbcrConversionCreateInfo>().ycbcrModel = vk::SamplerYcbcrModelConversion(*description.color_model);
ycbcr_conversion = vk::raii::SamplerYcbcrConversion(device, ycbcr_create_info.get<vk::SamplerYcbcrConversionCreateInfo>());
// Create VkSampler // Create VkSampler
VkSamplerYcbcrConversionInfo sampler_info2{ vk::StructureChain sampler_info{
.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, vk::SamplerCreateInfo{
.conversion = ycbcr_conversion, .magFilter = yuv_filter,
.minFilter = yuv_filter,
.mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeU = vk::SamplerAddressMode::eClampToEdge,
.addressModeV = vk::SamplerAddressMode::eClampToEdge,
.addressModeW = vk::SamplerAddressMode::eClampToEdge,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eNever,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = vk::BorderColor::eFloatOpaqueWhite, // TODO TBC
.unnormalizedCoordinates = VK_FALSE,
},
vk::SamplerYcbcrConversionInfo{
.conversion = *ycbcr_conversion,
}
}; };
VkSamplerCreateInfo sampler_info{
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.pNext = &sampler_info2,
.magFilter = yuv_filter,
.minFilter = yuv_filter,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_FALSE,
.maxAnisotropy = 1,
.compareEnable = VK_FALSE,
.compareOp = VK_COMPARE_OP_NEVER,
.minLod = 0.0f,
.maxLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, // TODO TBC
.unnormalizedCoordinates = VK_FALSE,
}; sampler = vk::raii::Sampler(device, sampler_info.get<vk::SamplerCreateInfo>());
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler));
// Create VkDescriptorSetLayout with an immutable sampler // Create VkDescriptorSetLayout with an immutable sampler
VkDescriptorSetLayoutBinding samplerLayoutBinding{ vk::DescriptorSetLayoutBinding sampler_layout_binding{
.binding = 0, .binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, .stageFlags = vk::ShaderStageFlagBits::eFragment,
.pImmutableSamplers = &sampler, };
sampler_layout_binding.setImmutableSamplers(*sampler);
vk::DescriptorSetLayoutCreateInfo layout_info;
layout_info.setBindings(sampler_layout_binding);
descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info);
vk::DescriptorPoolSize pool_size{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 100,
}; };
VkDescriptorSetLayoutCreateInfo layoutInfo{ vk::DescriptorPoolCreateInfo pool_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet,
.bindingCount = 1, .maxSets = pool_size.descriptorCount,
.pBindings = &samplerLayoutBinding,
}; };
pool_info.setPoolSizes(pool_size);
CHECK_VK(vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptor_set_layout)); descriptor_pool = vk::raii::DescriptorPool(device, pool_info);
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
poolSize.descriptorCount = 100;
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
poolInfo.poolSizeCount = 1;
poolInfo.pPoolSizes = &poolSize;
poolInfo.maxSets = poolSize.descriptorCount;
CHECK_VK(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptor_pool));
float useful_size[] = float useful_size[] =
{ {
@@ -174,67 +167,91 @@ struct wivrn::android::decoder::pipeline_context
float(description.height) / buffer_desc.height float(description.height) / buffer_desc.height
}; };
std::vector<VkSpecializationMapEntry> specialization_constants_desc{ std::array specialization_constants_desc{
{.constantID = 0, .offset = 0, .size = sizeof(float)}, vk::SpecializationMapEntry{
{.constantID = 1, .offset = sizeof(float), .size = sizeof(float)}}; .constantID = 0,
.offset = 0,
VkSpecializationInfo specialization_info{ .size = sizeof(float),
.mapEntryCount = (uint32_t)specialization_constants_desc.size(), },
.pMapEntries = specialization_constants_desc.data(), vk::SpecializationMapEntry{
.dataSize = sizeof(useful_size), .constantID = 1,
.pData = &useful_size}; .offset = sizeof(float),
.size = sizeof(float),
// Create graphics pipeline }
vk::shader vertex_shader(device, "stream.vert");
vk::shader fragment_shader(device, "stream.frag");
VkPipelineColorBlendAttachmentState pcbas{};
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
layout = vk::pipeline_layout(
device, {.descriptor_set_layouts = {descriptor_set_layout}});
vk::pipeline::graphics_info pipeline_info{
.shader_stages =
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main", .pSpecializationInfo = &specialization_info},
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main"}},
.vertex_input_bindings = {},
.vertex_input_attributes = {},
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP},
.viewports = {{}},
.scissors = {{}},
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
.dynamic_states = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR},
.renderPass = renderpass,
.subpass = 0,
}; };
pipeline = vk::pipeline(device, pipeline_info, layout); vk::SpecializationInfo specialization_info;
specialization_info.setMapEntries(specialization_constants_desc);
specialization_info.setData<float>(useful_size);
// Create graphics pipeline
vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert");
vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag");
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*descriptor_set_layout);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
vk::pipeline_builder pipeline_info
{
.flags = {},
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
},{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
.pSpecializationInfo = &specialization_info,
}},
.VertexInputState = {.flags = {}},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleStrip,
}},
.ViewportState = {.flags = {}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB
}},
.DynamicState = {.flags={}},
.DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
};
pipeline = vk::raii::Pipeline(device, nullptr, pipeline_info);
} }
}; };
struct wivrn::android::decoder::mapped_hardware_buffer struct wivrn::android::decoder::mapped_hardware_buffer
{ {
std::shared_ptr<pipeline_context> pipeline; std::shared_ptr<pipeline_context> pipeline;
VkImageView image_view{}; vk::raii::DeviceMemory memory = nullptr;
VkImage vimage{}; vk::raii::Image vimage = nullptr;
VkDeviceMemory memory{}; vk::raii::ImageView image_view = nullptr;
VkDescriptorSet descriptor_set{}; vk::raii::DescriptorSet descriptor_set = nullptr;
VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED; vk::ImageLayout layout = vk::ImageLayout::eUndefined;
~mapped_hardware_buffer() ~mapped_hardware_buffer()
{ {
assert(pipeline); assert(pipeline);
auto device = pipeline->device;
{ {
std::unique_lock lock(pipeline->descriptor_pool_mutex); std::unique_lock lock(pipeline->descriptor_pool_mutex);
vkFreeDescriptorSets(device, pipeline->descriptor_pool, 1, &descriptor_set); descriptor_set = nullptr;
} }
vkDestroyImageView(device, image_view, nullptr);
vkFreeMemory(device, memory, nullptr);
vkDestroyImage(device, vimage, nullptr);
} }
}; };
@@ -409,8 +426,8 @@ void decoder::push_nals(std::span<std::span<const uint8_t>> data, int64_t timest
} }
decoder::decoder( decoder::decoder(
VkDevice device, vk::raii::Device& device,
VkPhysicalDevice physical_device, vk::raii::PhysicalDevice& physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps, float fps,
uint8_t stream_index, uint8_t stream_index,
@@ -460,49 +477,53 @@ decoder::~decoder()
input_buffers.close(); input_buffers.close();
output_buffers.close(); output_buffers.close();
output_releaser.join(); output_releaser.join();
for (auto & i: blit_targets)
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
} }
void decoder::set_blit_targets(std::vector<decoder::blit_target> targets, VkFormat format) void decoder::set_blit_targets(std::vector<decoder::blit_target> targets, vk::Format format)
{ {
// Create renderpass // Create renderpass
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; vk::AttachmentDescription color_desc{
.format = format,
.samples = vk::SampleCountFlagBits::e1,
.loadOp = vk::AttachmentLoadOp::eLoad,
.storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = vk::ImageLayout::eColorAttachmentOptimal,
.finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{ vk::AttachmentReference color_ref{
.format = format, .attachment = 0,
.samples = VK_SAMPLE_COUNT_1_BIT, .layout = vk::ImageLayout::eColorAttachmentOptimal,
.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, };
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
}},
.subpasses = {VkSubpassDescription{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
}},
.dependencies = {}};
renderpass = vk::renderpass(device, renderpass_info); vk::SubpassDescription subpass{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
};
subpass.setColorAttachments(color_ref);
// Remove old blit targets first vk::RenderPassCreateInfo renderpass_info{
for (auto & i: blit_targets) .flags = {},
vkDestroyFramebuffer(device, i.framebuffer, nullptr);
};
renderpass_info.setAttachments(color_desc);
renderpass_info.setSubpasses(subpass);
renderpass = vk::raii::RenderPass(device, renderpass_info);
blit_targets = std::move(targets); blit_targets = std::move(targets);
for (auto & i: blit_targets) for (auto & i: blit_targets)
{ {
VkFramebufferCreateInfo fb_create_info{}; vk::FramebufferCreateInfo fb_create_info{
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; .renderPass = *renderpass,
fb_create_info.renderPass = renderpass; .attachmentCount = 1,
fb_create_info.attachmentCount = 1; .pAttachments = &i.image_view,
fb_create_info.pAttachments = &i.image_view; .width = i.extent.width,
fb_create_info.width = i.extent.width; .height = i.extent.height,
fb_create_info.height = i.extent.height; .layers = 1
fb_create_info.layers = 1; };
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &i.framebuffer));
i.framebuffer = std::make_shared<vk::raii::Framebuffer>(device, fb_create_info);
} }
} }
@@ -636,13 +657,7 @@ std::shared_ptr<decoder::mapped_hardware_buffer> decoder::map_hardware_buffer(AI
AHardwareBuffer_Desc buffer_desc{}; AHardwareBuffer_Desc buffer_desc{};
AHardwareBuffer_describe(hardware_buffer, &buffer_desc); AHardwareBuffer_describe(hardware_buffer, &buffer_desc);
VkAndroidHardwareBufferFormatPropertiesANDROID format_properties{}; auto [properties, format_properties] = device.getAndroidHardwareBufferPropertiesANDROID<vk::AndroidHardwareBufferPropertiesANDROID, vk::AndroidHardwareBufferFormatPropertiesANDROID>(*hardware_buffer);
format_properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
VkAndroidHardwareBufferPropertiesANDROID properties{};
properties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
properties.pNext = &format_properties;
CHECK_VK(vkGetAndroidHardwareBufferPropertiesANDROID(device, hardware_buffer, &properties));
if (!pipeline || memcmp(&pipeline->ahb_format, &format_properties, sizeof(format_properties))) if (!pipeline || memcmp(&pipeline->ahb_format, &format_properties, sizeof(format_properties)))
{ {
@@ -655,106 +670,107 @@ std::shared_ptr<decoder::mapped_hardware_buffer> decoder::map_hardware_buffer(AI
if (it != hardware_buffer_map.end()) if (it != hardware_buffer_map.end())
return it->second; return it->second;
VkExternalFormatANDROID img_info3{.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID, vk::StructureChain img_info{
.externalFormat = format_properties.externalFormat}; vk::ImageCreateInfo{
.flags = {},
.imageType = vk::ImageType::e2D,
.format = vk::Format::eUndefined,
.extent = {buffer_desc.width, buffer_desc.height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = vk::SampleCountFlagBits::e1,
.tiling = vk::ImageTiling::eOptimal,
.usage = vk::ImageUsageFlagBits::eSampled,
.sharingMode = vk::SharingMode::eExclusive,
.initialLayout = vk::ImageLayout::eUndefined
},
vk::ExternalMemoryImageCreateInfo{
.handleTypes = vk::ExternalMemoryHandleTypeFlagBits::eAndroidHardwareBufferANDROID
},
vk::ExternalFormatANDROID{
.externalFormat = format_properties.externalFormat
}
};
VkExternalMemoryImageCreateInfo img_info2{ vk::raii::Image vimage(device, img_info.get());
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.pNext = &img_info3,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo img_info{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.pNext = &img_info2,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = VK_FORMAT_UNDEFINED,
.extent = {buffer_desc.width, buffer_desc.height, 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
vk::image vimage(device, img_info);
VkImportAndroidHardwareBufferInfoANDROID mem_info3{
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID,
.buffer = hardware_buffer};
VkMemoryDedicatedAllocateInfo mem_info2{.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &mem_info3,
.image = vimage};
assert(properties.memoryTypeBits != 0); assert(properties.memoryTypeBits != 0);
VkMemoryAllocateInfo mem_info{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, vk::StructureChain mem_info{
.pNext = &mem_info2, vk::MemoryAllocateInfo{
.allocationSize = properties.allocationSize, .allocationSize = properties.allocationSize,
.memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1)}; .memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1)
},
vk::device_memory memory(device, mem_info); vk::MemoryDedicatedAllocateInfo{
CHECK_VK(vkBindImageMemory(device, vimage, memory, 0)); .image = *vimage
},
VkSamplerYcbcrConversionInfo ycbcr_info{.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, vk::ImportAndroidHardwareBufferInfoANDROID{
.conversion = pipeline->ycbcr_conversion}; .buffer = hardware_buffer
}
VkImageViewCreateInfo iv_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.pNext = &ycbcr_info,
.image = vimage,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_UNDEFINED,
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1}};
// TODO: vk::image_view
VkImageView image_view;
application::ignore_debug_reports_for(vimage);
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view));
application::unignore_debug_reports_for(vimage);
// TODO: vk::descriptor_set
VkDescriptorSet descriptor_set;
VkDescriptorSetAllocateInfo descriptor_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = pipeline->descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &pipeline->descriptor_set_layout,
}; };
{
vk::raii::DeviceMemory memory(device, mem_info.get());
vimage.bindMemory(*memory, 0);
vk::StructureChain iv_info{
vk::ImageViewCreateInfo{
.image = *vimage,
.viewType = vk::ImageViewType::e2D,
.format = vk::Format::eUndefined,
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1
}
},
vk::SamplerYcbcrConversionInfo{
.conversion = *pipeline->ycbcr_conversion
}
};
application::ignore_debug_reports_for(*vimage);
vk::raii::ImageView image_view(device, iv_info.get());
application::unignore_debug_reports_for(*vimage);
vk::raii::DescriptorSet descriptor_set = [&]{
std::unique_lock lock(pipeline->descriptor_pool_mutex); std::unique_lock lock(pipeline->descriptor_pool_mutex);
CHECK_VK(vkAllocateDescriptorSets(device, &descriptor_info, &descriptor_set));
}
VkDescriptorImageInfo image_info{ vk::raii::DescriptorSets descriptor_sets(device, {
.imageView = image_view, .descriptorPool = *pipeline->descriptor_pool,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .descriptorSetCount = 1,
.pSetLayouts = &*pipeline->descriptor_set_layout,
});
return std::move(descriptor_sets[0]);
}();
vk::DescriptorImageInfo image_info{
.imageView = *image_view,
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
}; };
VkWriteDescriptorSet descriptor_write{ vk::WriteDescriptorSet descriptor_write{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = *descriptor_set,
.dstSet = descriptor_set,
.dstBinding = 0, .dstBinding = 0,
.dstArrayElement = 0, .dstArrayElement = 0,
.descriptorCount = 1, .descriptorCount = 1,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info, .pImageInfo = &image_info,
}; };
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr); device.updateDescriptorSets(descriptor_write, {});
auto handle = std::make_shared<mapped_hardware_buffer>(); auto handle = std::make_shared<mapped_hardware_buffer>();
handle->pipeline = pipeline; handle->pipeline = pipeline;
handle->vimage = vimage.release(); handle->vimage = std::move(vimage);
handle->image_view = image_view; handle->image_view = std::move(image_view);
handle->memory = memory.release(); handle->memory = std::move(memory);
handle->descriptor_set = descriptor_set; handle->descriptor_set = std::move(descriptor_set);
hardware_buffer_map[hardware_buffer] = handle; hardware_buffer_map[hardware_buffer] = handle;
return handle; return handle;
@@ -780,29 +796,30 @@ void decoder::on_media_output_available(AMediaCodec * media_codec, void * userda
// will be consumed by dedicated thread // will be consumed by dedicated thread
} }
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices) void decoder::blit(vk::raii::CommandBuffer& command_buffer, blit_handle & handle, std::span<int> target_indices)
{ {
if (handle.vk_data->layout != VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) if (handle.vk_data->layout != vk::ImageLayout::eShaderReadOnlyOptimal)
{ {
VkImageMemoryBarrier memory_barrier{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, vk::ImageMemoryBarrier memory_barrier{
.srcAccessMask = 0, .srcAccessMask = {},
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, .dstAccessMask = vk::AccessFlagBits::eShaderRead,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, .oldLayout = vk::ImageLayout::eUndefined,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = vk::QueueFamilyIgnored,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = vk::QueueFamilyIgnored,
.image = handle.vk_data->vimage, .image = *handle.vk_data->vimage,
.subresourceRange = { .subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0, .baseMipLevel = 0,
.levelCount = 1, .levelCount = 1,
.baseArrayLayer = 0, .baseArrayLayer = 0,
.layerCount = 1, .layerCount = 1,
}}; }
};
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &memory_barrier); command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, memory_barrier);
handle.vk_data->layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; handle.vk_data->layout = vk::ImageLayout::eShaderReadOnlyOptimal;
} }
for (size_t target_index: target_indices) for (size_t target_index: target_indices)
@@ -820,45 +837,45 @@ void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::sp
int x1 = x0 + description.width; int x1 = x0 + description.width;
int y1 = y0 + description.height; int y1 = y0 + description.height;
VkRenderPassBeginInfo begin_info{ vk::RenderPassBeginInfo begin_info{
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = *renderpass,
.renderPass = renderpass, .framebuffer = **target.framebuffer,
.framebuffer = target.framebuffer, .renderArea = {
.renderArea =
{
.offset = {0, 0}, .offset = {0, 0},
.extent = target.extent, .extent = target.extent,
}, },
.clearValueCount = 0, .clearValueCount = 0,
}; };
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE); command_buffer.beginRenderPass(begin_info, vk::SubpassContents::eInline);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->pipeline); command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *handle.vk_data->pipeline->pipeline);
VkViewport viewport{.x = (float)x0, vk::Viewport viewport{
.y = (float)y0, .x = (float)x0,
.width = (float)description.width, .y = (float)y0,
.height = (float)description.height, .width = (float)description.width,
.minDepth = 0, .height = (float)description.height,
.maxDepth = 1}; .minDepth = 0,
.maxDepth = 1
};
x0 = std::clamp<int>(x0, 0, target.extent.width); x0 = std::clamp<int>(x0, 0, target.extent.width);
x1 = std::clamp<int>(x1, 0, target.extent.width); x1 = std::clamp<int>(x1, 0, target.extent.width);
y0 = std::clamp<int>(y0, 0, target.extent.height); y0 = std::clamp<int>(y0, 0, target.extent.height);
y1 = std::clamp<int>(y1, 0, target.extent.height); y1 = std::clamp<int>(y1, 0, target.extent.height);
VkRect2D scissor{ vk::Rect2D scissor{
.offset = {.x = x0, .y = y0}, .offset = {.x = x0, .y = y0},
.extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)}, .extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)},
}; };
vkCmdSetViewport(command_buffer, 0, 1, &viewport); command_buffer.setViewport(0, viewport);
vkCmdSetScissor(command_buffer, 0, 1, &scissor); command_buffer.setScissor(0, scissor);
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, handle.vk_data->pipeline->layout, 0, 1, &handle.vk_data->descriptor_set, 0, nullptr); command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *handle.vk_data->pipeline->layout, 0, *handle.vk_data->descriptor_set, {});
vkCmdDraw(command_buffer, 3, 1, 0, 0); command_buffer.draw(3, 1, 0, 0);
vkCmdEndRenderPass(command_buffer); command_buffer.endRenderPass();
} }
} }
+14 -18
View File
@@ -20,9 +20,6 @@
#pragma once #pragma once
#include "utils/sync_queue.h" #include "utils/sync_queue.h"
#include "vk/device_memory.h"
#include "vk/image.h"
#include "vk/renderpass.h"
#include "wivrn_packets.h" #include "wivrn_packets.h"
#include <memory> #include <memory>
#include <optional> #include <optional>
@@ -36,7 +33,7 @@
#include <media/NdkImageReader.h> #include <media/NdkImageReader.h>
#include <media/NdkMediaCodec.h> #include <media/NdkMediaCodec.h>
#include <media/NdkMediaFormat.h> #include <media/NdkMediaFormat.h>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_raii.hpp>
#define DEUGLIFY(x) \ #define DEUGLIFY(x) \
struct x##_deleter \ struct x##_deleter \
@@ -67,12 +64,12 @@ public:
struct blit_target struct blit_target
{ {
VkImage image; vk::Image image;
VkImageView image_view; vk::ImageView image_view;
VkOffset2D offset; vk::Offset2D offset;
VkExtent2D extent; vk::Extent2D extent;
VkFramebuffer framebuffer; std::shared_ptr<vk::raii::Framebuffer> framebuffer;
std::shared_ptr<pipeline_context> pipeline; std::shared_ptr<pipeline_context> pipeline;
}; };
@@ -94,7 +91,7 @@ private:
xrt::drivers::wivrn::to_headset::video_stream_description::item description; xrt::drivers::wivrn::to_headset::video_stream_description::item description;
float fps; float fps;
VkDevice device; vk::raii::Device& device;
AImageReader_ptr image_reader; AImageReader_ptr image_reader;
@@ -124,14 +121,13 @@ private:
std::shared_ptr<pipeline_context> pipeline; std::shared_ptr<pipeline_context> pipeline;
std::mutex hbm_mutex; std::mutex hbm_mutex;
std::unordered_map<AHardwareBuffer *, std::shared_ptr<mapped_hardware_buffer>> hardware_buffer_map; std::unordered_map<AHardwareBuffer *, std::shared_ptr<mapped_hardware_buffer>> hardware_buffer_map;
vk::renderpass renderpass; vk::raii::RenderPass renderpass = nullptr;
std::shared_ptr<mapped_hardware_buffer> map_hardware_buffer(AImage *); std::shared_ptr<mapped_hardware_buffer> map_hardware_buffer(AImage *);
public: public:
decoder( decoder(vk::raii::Device& device,
VkDevice device, vk::raii::PhysicalDevice& physical_device,
VkPhysicalDevice physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps, float fps,
uint8_t stream_index, uint8_t stream_index,
@@ -151,11 +147,11 @@ public:
return description; return description;
} }
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; static const vk::ImageLayout framebuffer_expected_layout = vk::ImageLayout::eColorAttachmentOptimal;
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; static const vk::ImageUsageFlagBits framebuffer_usage = vk::ImageUsageFlagBits::eColorAttachment;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format); void set_blit_targets(std::vector<blit_target> targets, vk::Format format);
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices); void blit(vk::raii::CommandBuffer& command_buffer, blit_handle & handle, std::span<int> target_indices);
void blit_finished(blit_handle & handle); void blit_finished(blit_handle & handle);
}; };
+36 -35
View File
@@ -23,6 +23,7 @@
#include "spdlog/spdlog.h" #include "spdlog/spdlog.h"
#include "utils/check.h" #include "utils/check.h"
#include <cassert> #include <cassert>
#include <vulkan/vulkan.hpp>
extern "C" extern "C"
{ {
@@ -69,8 +70,8 @@ decoder::blit_handle::~blit_handle()
} }
decoder::decoder( decoder::decoder(
VkDevice device, vk::raii::Device& device,
VkPhysicalDevice physical_device, vk::raii::PhysicalDevice& physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps, float fps,
uint8_t stream_index, uint8_t stream_index,
@@ -84,32 +85,33 @@ decoder::decoder(
{ {
free_images[i] = i; free_images[i] = i;
VkImageCreateInfo image_info{}; vk::ImageCreateInfo image_info;
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = vk::ImageType::e2D;
image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = vk::Format::eA8B8G8R8SrgbPack32;
image_info.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32;
image_info.extent.width = description.width; image_info.extent.width = description.width;
image_info.extent.height = description.height; image_info.extent.height = description.height;
image_info.extent.depth = 1; image_info.extent.depth = 1;
image_info.mipLevels = 1; image_info.mipLevels = 1;
image_info.arrayLayers = 1; image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.samples = vk::SampleCountFlagBits::e1;
image_info.tiling = VK_IMAGE_TILING_LINEAR; image_info.tiling = vk::ImageTiling::eLinear;
image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image_info.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.sharingMode = vk::SharingMode::eExclusive;
image_info.queueFamilyIndexCount = 0; image_info.queueFamilyIndexCount = 0;
image_info.pQueueFamilyIndices = NULL; image_info.pQueueFamilyIndices = nullptr;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; image_info.initialLayout = vk::ImageLayout::eUndefined;
decoded_images[i].image = vk::image(device, image_info); VmaAllocationCreateInfo alloc_info{};
decoded_images[i].memory = vk::device_memory(device, physical_device, decoded_images[i].image, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); alloc_info.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
decoded_images[i].memory.map_memory(); decoded_images[i].image = image_allocation(image_info, alloc_info);
VkImageSubresource resource{}; decoded_images[i].image.map();
resource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
vkGetImageSubresourceLayout(device, decoded_images[i].image, &resource, &decoded_images[i].layout); vk::ImageSubresource resource;
resource.aspectMask = vk::ImageAspectFlagBits::eColor;
decoded_images[i].layout = decoded_images[i].image->getSubresourceLayout(resource);
} }
auto avcodec = avcodec_find_decoder(codec_id(description.codec)); auto avcodec = avcodec_find_decoder(codec_id(description.codec));
@@ -125,31 +127,30 @@ decoder::decoder(
throw std::runtime_error{"avcodec_open2 failed"}; throw std::runtime_error{"avcodec_open2 failed"};
} }
void decoder::set_blit_targets(std::vector<blit_target> targets, VkFormat format) void decoder::set_blit_targets(std::vector<blit_target> targets, vk::Format format)
{ {
blit_targets = std::move(targets); blit_targets = std::move(targets);
} }
void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_indices) void decoder::blit(vk::raii::CommandBuffer& command_buffer, blit_handle & handle, std::span<int> blit_indices)
{ {
std::unique_lock lock(mutex); std::unique_lock lock(mutex);
// Transition layout to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL // Transition layout to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL
// TODO: transition only if needed // TODO: transition only if needed
VkImageMemoryBarrier barrier{}; vk::ImageMemoryBarrier barrier;
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.image = handle.image; barrier.image = handle.image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
barrier.subresourceRange.levelCount = 1; barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.layerCount = 1;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.srcQueueFamilyIndex = vk::QueueFamilyIgnored;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = vk::QueueFamilyIgnored;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barrier.oldLayout = vk::ImageLayout::eUndefined;
barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.newLayout = vk::ImageLayout::eTransferSrcOptimal;
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags{}, {}, {}, barrier);
for (int blit_index: blit_indices) for (int blit_index: blit_indices)
{ {
@@ -163,9 +164,9 @@ void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::sp
if (description.offset_x >= right or description.offset_x + description.width <= left) if (description.offset_x >= right or description.offset_x + description.width <= left)
continue; continue;
VkImageBlit blit{}; vk::ImageBlit blit;
blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit.srcSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
blit.srcSubresource.layerCount = 1; blit.srcSubresource.layerCount = 1;
blit.srcOffsets[0].x = std::max<int32_t>(0, left - description.offset_x); blit.srcOffsets[0].x = std::max<int32_t>(0, left - description.offset_x);
blit.srcOffsets[0].y = 0; blit.srcOffsets[0].y = 0;
@@ -173,14 +174,14 @@ void decoder::blit(VkCommandBuffer command_buffer, blit_handle & handle, std::sp
blit.srcOffsets[1].y = std::min<int32_t>(description.height, height - description.offset_y); blit.srcOffsets[1].y = std::min<int32_t>(description.height, height - description.offset_y);
blit.srcOffsets[1].z = 1; blit.srcOffsets[1].z = 1;
blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; blit.dstSubresource.aspectMask = vk::ImageAspectFlagBits::eColor;
blit.dstSubresource.layerCount = 1; blit.dstSubresource.layerCount = 1;
blit.dstOffsets[0].x = std::max<int32_t>(0, description.offset_x - left); blit.dstOffsets[0].x = std::max<int32_t>(0, description.offset_x - left);
blit.dstOffsets[0].y = description.offset_y; blit.dstOffsets[0].y = description.offset_y;
blit.dstOffsets[1].x = std::min<int32_t>(width, description.offset_x + description.width - left); blit.dstOffsets[1].x = std::min<int32_t>(width, description.offset_x + description.width - left);
blit.dstOffsets[1].y = std::min<int32_t>(height, description.offset_y + description.height); blit.dstOffsets[1].y = std::min<int32_t>(height, description.offset_y + description.height);
blit.dstOffsets[1].z = 1; blit.dstOffsets[1].z = 1;
vkCmdBlitImage(command_buffer, handle.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, blit_targets[blit_index].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR); command_buffer.blitImage(handle.image, vk::ImageLayout::eTransferSrcOptimal, blit_targets[blit_index].image, vk::ImageLayout::eTransferDstOptimal, blit, vk::Filter::eLinear);
} }
} }
@@ -241,7 +242,7 @@ void decoder::frame_completed(const xrt::drivers::wivrn::from_headset::feedback
decoded_images[index].frame_index = frame_index; decoded_images[index].frame_index = frame_index;
int dstStride = decoded_images[index].layout.rowPitch; int dstStride = decoded_images[index].layout.rowPitch;
uint8_t * out = (uint8_t *)decoded_images[index].memory.data(); uint8_t * out = (uint8_t *)decoded_images[index].image.map();
res = sws_scale(sws.get(), frame->data, frame->linesize, 0, frame->height, &out, &dstStride); res = sws_scale(sws.get(), frame->data, frame->linesize, 0, frame->height, &out, &dstStride);
if (res == 0) if (res == 0)
throw std::runtime_error{"sws_scale failed"}; throw std::runtime_error{"sws_scale failed"};
+15 -17
View File
@@ -19,8 +19,6 @@
#pragma once #pragma once
#include "vk/device_memory.h"
#include "vk/image.h"
#include "wivrn_packets.h" #include "wivrn_packets.h"
#include <deque> #include <deque>
#include <memory> #include <memory>
@@ -28,7 +26,8 @@
#include <span> #include <span>
#include <string> #include <string>
#include <vector> #include <vector>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_raii.hpp>
#include "vk/allocation.h"
class shard_accumulator; class shard_accumulator;
@@ -51,23 +50,22 @@ class decoder
public: public:
struct blit_target struct blit_target
{ {
VkImage image; vk::Image image;
VkImageView image_view; vk::ImageView image_view;
VkOffset2D offset; vk::Offset2D offset;
VkExtent2D extent; vk::Extent2D extent;
}; };
private: private:
static const int image_count = 3; static const int image_count = 3;
struct image struct image
{ {
vk::image image; image_allocation image;
vk::device_memory memory; vk::SubresourceLayout layout;
VkSubresourceLayout layout;
uint64_t frame_index; uint64_t frame_index;
}; };
VkDevice device; vk::raii::Device& device;
std::array<image, image_count> decoded_images; std::array<image, image_count> decoded_images;
std::vector<int> free_images; std::vector<int> free_images;
@@ -85,8 +83,8 @@ private:
public: public:
decoder( decoder(
VkDevice device, vk::raii::Device& device,
VkPhysicalDevice physical_device, vk::raii::PhysicalDevice& physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps, float fps,
uint8_t stream_index, uint8_t stream_index,
@@ -113,10 +111,10 @@ public:
~blit_handle(); ~blit_handle();
}; };
static const VkImageLayout framebuffer_expected_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; static const vk::ImageLayout framebuffer_expected_layout = vk::ImageLayout::eTransferDstOptimal;
static const VkImageUsageFlagBits framebuffer_usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; static const vk::ImageUsageFlagBits framebuffer_usage = vk::ImageUsageFlagBits::eTransferDst;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format); void set_blit_targets(std::vector<blit_target> targets, vk::Format format);
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> target_indices); void blit(vk::raii::CommandBuffer& command_buffer, blit_handle & handle, std::span<int> target_indices);
}; };
} // namespace ffmpeg } // namespace ffmpeg
+10 -6
View File
@@ -21,6 +21,8 @@
#include "xr/instance.h" #include "xr/instance.h"
#include <memory> #include <memory>
#include <vulkan/vulkan.hpp>
#ifdef XR_USE_PLATFORM_ANDROID #ifdef XR_USE_PLATFORM_ANDROID
#include "decoder/android/android_decoder.h" #include "decoder/android/android_decoder.h"
using decoder_impl = ::wivrn::android::decoder; using decoder_impl = ::wivrn::android::decoder;
@@ -70,8 +72,8 @@ private:
public: public:
explicit shard_accumulator( explicit shard_accumulator(
VkDevice device, vk::raii::Device& device,
VkPhysicalDevice physical_device, vk::raii::PhysicalDevice& physical_device,
const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description,
float fps, float fps,
std::weak_ptr<scenes::stream> scene, std::weak_ptr<scenes::stream> scene,
@@ -94,15 +96,17 @@ public:
using blit_handle = decoder_impl::blit_handle; using blit_handle = decoder_impl::blit_handle;
using blit_target = decoder_impl::blit_target; using blit_target = decoder_impl::blit_target;
static const VkImageLayout framebuffer_expected_layout = decoder_impl::framebuffer_expected_layout;
static const VkImageUsageFlagBits framebuffer_usage = decoder_impl::framebuffer_usage;
void set_blit_targets(std::vector<blit_target> targets, VkFormat format) static const vk::ImageLayout framebuffer_expected_layout = decoder_impl::framebuffer_expected_layout;
static const vk::ImageUsageFlagBits framebuffer_usage = decoder_impl::framebuffer_usage;
void set_blit_targets(std::vector<blit_target> targets, vk::Format format)
{ {
static_assert(std::copy_constructible<blit_target>);
decoder->set_blit_targets(std::move(targets), format); decoder->set_blit_targets(std::move(targets), format);
} }
void blit(VkCommandBuffer command_buffer, blit_handle & handle, std::span<int> blit_target_indices) void blit(vk::raii::CommandBuffer& command_buffer, blit_handle & handle, std::span<int> blit_target_indices)
{ {
return decoder->blit(command_buffer, handle, blit_target_indices); return decoder->blit(command_buffer, handle, blit_target_indices);
} }
File diff suppressed because it is too large Load Diff
+187 -187
View File
@@ -1,187 +1,187 @@
#pragma once // #pragma once
//
#include <memory> // #include <memory>
#include <span> // #include <span>
#include <vector> // #include <vector>
#include <vulkan/vulkan.h> // #include <vulkan/vulkan.h>
//
#include "glm/vec2.hpp" // #include "glm/vec2.hpp"
#include "glm/vec3.hpp" // #include "glm/vec3.hpp"
#include "tiny_gltf.h" // #include "tiny_gltf.h"
#include "vk/buffer.h" // #include "vk/buffer.h"
#include "vk/command_pool.h" // #include "vk/command_pool.h"
#include "vk/device_memory.h" // #include "vk/device_memory.h"
#include "vk/image.h" // #include "vk/image.h"
#include "vk/pipeline.h" // #include "vk/pipeline.h"
#include "vk/renderpass.h" // #include "vk/renderpass.h"
//
class scene_renderer // class scene_renderer
//
{ // {
public: // public:
class shader // class shader
{ // {
friend class scene_renderer; // friend class scene_renderer;
//
std::vector<VkDescriptorSetLayout> descriptor_set_layouts; // std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
std::vector<VkDescriptorPool> descriptor_pools; // std::vector<VkDescriptorPool> descriptor_pools;
VkShaderModule vertex_shader{}; // VkShaderModule vertex_shader{};
VkShaderModule fragment_shader{}; // VkShaderModule fragment_shader{};
VkPipelineLayout pipeline_layout{}; // VkPipelineLayout pipeline_layout{};
//
struct pipeline_info // struct pipeline_info
{ // {
VkPrimitiveTopology topology; // VkPrimitiveTopology topology;
std::vector<VkVertexInputBindingDescription> vertex_bindings; // std::vector<VkVertexInputBindingDescription> vertex_bindings;
std::vector<VkVertexInputAttributeDescription> vertex_attributes; // std::vector<VkVertexInputAttributeDescription> vertex_attributes;
}; // };
//
std::vector<std::pair<pipeline_info, VkPipeline>> pipelines; // std::vector<std::pair<pipeline_info, VkPipeline>> pipelines;
//
shader() = default; // shader() = default;
shader(const shader &) = delete; // shader(const shader &) = delete;
shader(shader &&) = delete; // shader(shader &&) = delete;
}; // };
//
class image // class image
{ // {
friend class scene_renderer; // friend class scene_renderer;
//
VkDeviceMemory memory{}; // VkDeviceMemory memory{};
VkSampler sampler{}; // VkSampler sampler{};
VkImage vk_image{}; // VkImage vk_image{};
VkImageView image_view{}; // VkImageView image_view{};
VkDescriptorSet descriptor_set{}; // VkDescriptorSet descriptor_set{};
//
image() = default; // image() = default;
image(const image &) = delete; // image(const image &) = delete;
image(image &&) = delete; // image(image &&) = delete;
}; // };
//
class buffer // class buffer
{ // {
friend class scene_renderer; // friend class scene_renderer;
//
VkDeviceMemory memory{}; // VkDeviceMemory memory{};
VkBuffer vk_buffer{}; // VkBuffer vk_buffer{};
//
buffer() = default; // buffer() = default;
buffer(const buffer &) = delete; // buffer(const buffer &) = delete;
buffer(buffer &&) = delete; // buffer(buffer &&) = delete;
}; // };
//
struct mesh_primitive // struct mesh_primitive
{ // {
struct vertex // struct vertex
{ // {
glm::vec3 position; // glm::vec3 position;
glm::vec3 normal; // glm::vec3 normal;
glm::vec2 texcoord; // glm::vec2 texcoord;
}; // };
//
VkPrimitiveTopology topology; // VkPrimitiveTopology topology;
//
VkPipeline pipeline; // VkPipeline pipeline;
//
std::weak_ptr<buffer> indices; // std::weak_ptr<buffer> indices;
size_t indices_offset; // size_t indices_offset;
size_t indices_count; // size_t indices_count;
//
std::weak_ptr<buffer> vertices; // std::weak_ptr<buffer> vertices;
size_t vertices_offset; // size_t vertices_offset;
}; // };
//
class model // class model
{ // {
friend class scene_renderer; // friend class scene_renderer;
//
tinygltf::Model gltf_model; // tinygltf::Model gltf_model;
std::vector<std::weak_ptr<image>> images; // std::vector<std::weak_ptr<image>> images;
std::vector<std::weak_ptr<buffer>> buffers; // std::vector<std::weak_ptr<buffer>> buffers;
}; // };
//
class model_instance // class model_instance
{ // {
friend class scene_renderer; // friend class scene_renderer;
//
model * gltf_model; // model * gltf_model;
//
void * ubo; // void * ubo;
}; // };
//
private: // private:
VkDevice device; // VkDevice device;
VkPhysicalDevice physical_device; // VkPhysicalDevice physical_device;
VkPhysicalDeviceProperties physical_device_properties; // VkPhysicalDeviceProperties physical_device_properties;
VkQueue queue; // VkQueue queue;
vk::command_pool command_pool; // vk::command_pool command_pool;
//
tinygltf::TinyGLTF gltf_loader; // tinygltf::TinyGLTF gltf_loader;
//
// Staging buffer // // Staging buffer
size_t staging_buffer_size = 0; // size_t staging_buffer_size = 0;
vk::buffer staging_buffer; // vk::buffer staging_buffer;
vk::device_memory staging_memory; // vk::device_memory staging_memory;
VkFence staging_fence{}; // VkFence staging_fence{};
void reserve(size_t size); // void reserve(size_t size);
//
void load_buffer(VkBuffer b, const void * data, size_t size); // void load_buffer(VkBuffer b, const void * data, size_t size);
//
template <typename T> // template <typename T>
void load_buffer(VkBuffer b, std::span<T> data) // void load_buffer(VkBuffer b, std::span<T> data)
{ // {
load_buffer(b, data.data(), data.size() * sizeof(T)); // load_buffer(b, data.data(), data.size() * sizeof(T));
} // }
//
void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); // void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
//
// Scene data // // Scene data
std::vector<std::shared_ptr<shader>> shaders; // std::vector<std::shared_ptr<shader>> shaders;
std::vector<std::shared_ptr<image>> images; // std::vector<std::shared_ptr<image>> images;
std::vector<std::shared_ptr<buffer>> buffers; // std::vector<std::shared_ptr<buffer>> buffers;
std::vector<std::shared_ptr<mesh_primitive>> primitives; // std::vector<std::shared_ptr<mesh_primitive>> primitives;
std::vector<std::shared_ptr<model>> models; // std::vector<std::shared_ptr<model>> models;
std::vector<model_instance> instances; // std::vector<model_instance> instances;
//
// Destination images // // Destination images
std::vector<VkImage> output_images; // std::vector<VkImage> output_images;
std::vector<VkImageView> output_image_views; // std::vector<VkImageView> output_image_views;
std::vector<VkFramebuffer> output_framebuffers; // std::vector<VkFramebuffer> output_framebuffers;
VkExtent2D output_size{}; // VkExtent2D output_size{};
VkFormat output_format{}; // VkFormat output_format{};
//
// Render pass // // Render pass
vk::renderpass renderpass; // vk::renderpass renderpass;
//
void cleanup(); // void cleanup();
void cleanup_output_images(); // void cleanup_output_images();
void cleanup_shader(shader *); // void cleanup_shader(shader *);
void cleanup_buffer(buffer *); // void cleanup_buffer(buffer *);
void cleanup_image(image *); // void cleanup_image(image *);
//
public: // public:
scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue); // scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue);
~scene_renderer(); // ~scene_renderer();
scene_renderer(const scene_renderer &) = delete; // scene_renderer(const scene_renderer &) = delete;
scene_renderer(scene_renderer &&) = delete; // scene_renderer(scene_renderer &&) = delete;
//
void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format); // void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format);
//
std::weak_ptr<shader> create_shader(std::string name, // std::weak_ptr<shader> create_shader(std::string name,
std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings); // std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings);
//
VkPipeline get_shader_pipeline(std::weak_ptr<shader> shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes); // VkPipeline get_shader_pipeline(std::weak_ptr<shader> shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes);
//
std::weak_ptr<image> create_image(void * data, VkExtent2D size, VkFormat format); // std::weak_ptr<image> create_image(void * data, VkExtent2D size, VkFormat format);
//
std::weak_ptr<buffer> create_buffer(const void * data, size_t size, VkBufferUsageFlags usage); // std::weak_ptr<buffer> create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
//
template <typename T> // template <typename T>
// requires(std::contiguous_iterator<typename T::iterator>) // // requires(std::contiguous_iterator<typename T::iterator>)
std::weak_ptr<buffer> create_buffer(const T & data, VkBufferUsageFlags usage) // std::weak_ptr<buffer> create_buffer(const T & data, VkBufferUsageFlags usage)
{ // {
return create_buffer(data.data(), data.size() * sizeof(T), usage); // return create_buffer(data.data(), data.size() * sizeof(T), usage);
} // }
//
model * load_gltf(const std::string & filename); // model * load_gltf(const std::string & filename);
}; // };
+114 -97
View File
@@ -18,6 +18,8 @@
*/ */
#include "text_rasterizer.h" #include "text_rasterizer.h"
#include "application.h"
#include "vk/allocation.h"
#include <cassert> #include <cassert>
#include <limits> #include <limits>
#include <system_error> #include <system_error>
@@ -27,7 +29,11 @@
#include <hb.h> #include <hb.h>
#include "utils/check.h" #include "utils/check.h"
#include "vk/buffer.h" #include <vk_mem_alloc.h>
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_handles.hpp>
#include <vulkan/vulkan_raii.hpp>
#ifdef XR_USE_PLATFORM_ANDROID #ifdef XR_USE_PLATFORM_ANDROID
#include <android/font.h> #include <android/font.h>
@@ -69,8 +75,13 @@ std::error_category & freetype_error_category()
// static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits<unsigned int>::max() }; // static hb_feature_t CligOn = { CligTag, 1, 0, std::numeric_limits<unsigned int>::max() };
// } // }
text_rasterizer::text_rasterizer(VkDevice device, VkPhysicalDevice physical_device, VkCommandPool command_pool, VkQueue queue) :
device(device), physical_device(physical_device), command_pool(command_pool), queue(queue) text_rasterizer::text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue) :
device(device),
physical_device(physical_device),
command_pool(command_pool),
queue(queue),
fence(device, vk::FenceCreateInfo{})
{ {
std::string font_filename; std::string font_filename;
@@ -127,16 +138,45 @@ text_rasterizer::text_rasterizer(VkDevice device, VkPhysicalDevice physical_devi
throw; throw;
} }
}
VkFenceCreateInfo fence_info{.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; image_allocation text_rasterizer::create_image(vk::Extent2D size, VmaMemoryUsage usage)
CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &fence)); {
vk::ImageCreateInfo image_info;
image_info.imageType = vk::ImageType::e2D;
image_info.format = text::format;
image_info.extent.width = size.width;
image_info.extent.height = size.height;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = vk::SampleCountFlagBits::e1;
image_info.tiling = vk::ImageTiling::eOptimal;
image_info.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst;
image_info.sharingMode = vk::SharingMode::eExclusive;
image_info.initialLayout = vk::ImageLayout::eUndefined;
VmaAllocationCreateInfo alloc_info{};
alloc_info.usage = VMA_MEMORY_USAGE_GPU_ONLY;
return image_allocation{image_info, alloc_info};
}
buffer_allocation text_rasterizer::create_buffer(size_t size, VmaMemoryUsage usage)
{
vk::BufferCreateInfo buffer_info;
buffer_info.size = size;
buffer_info.usage = vk::BufferUsageFlagBits::eTransferSrc;
buffer_info.sharingMode = vk::SharingMode::eExclusive;
VmaAllocationCreateInfo alloc_info{};
alloc_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
return buffer_allocation{buffer_info, alloc_info};
} }
text_rasterizer::~text_rasterizer() text_rasterizer::~text_rasterizer()
{ {
if (device && fence)
vkDestroyFence(device, fence, nullptr);
hb_buffer_destroy(buffer); hb_buffer_destroy(buffer);
hb_font_destroy(font); hb_font_destroy(font);
FT_Done_FreeType(freetype); FT_Done_FreeType(freetype);
@@ -241,106 +281,83 @@ text text_rasterizer::render(std::string_view s)
}}; }};
#else #else
VkImageCreateInfo image_info{ text return_value;
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.imageType = VK_IMAGE_TYPE_2D,
.format = text::format,
.extent = {
.width = uint32_t(x_max - x_min),
.height = uint32_t(y_max - y_min),
.depth = 1},
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
vk::image image(device, image_info);
vk::device_memory memory(device, physical_device, image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
VkBufferCreateInfo buffer_info{ return_value.size.width = x_max - x_min;
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, return_value.size.height = y_max - y_min;
.size = rendered_text.size(), return_value.image = create_image(return_value.size, VMA_MEMORY_USAGE_GPU_ONLY);
.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, buffer_allocation staging_buffer = create_buffer(rendered_text.size(), VMA_MEMORY_USAGE_CPU_TO_GPU);
void * mapped = staging_buffer.map();
memcpy(mapped, rendered_text.data(), rendered_text.size());
vk::raii::CommandBuffers cmdbufs(device, {
.commandPool = *command_pool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1,
});
vk::raii::CommandBuffer& cmdbuf = cmdbufs[0];
application::set_debug_reports_name((VkCommandBuffer)*cmdbuf, "text_rasterizer command buffer");
cmdbuf.begin({});
vk::ImageMemoryBarrier barrier{
.srcAccessMask = vk::AccessFlagBits::eNone,
.dstAccessMask = vk::AccessFlagBits::eTransferWrite,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eTransferDstOptimal,
.srcQueueFamilyIndex = vk::QueueFamilyIgnored,
.dstQueueFamilyIndex = vk::QueueFamilyIgnored,
.image = vk::Image{return_value.image},
.subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
}; };
vk::buffer staging_buffer(device, buffer_info); cmdbuf.pipelineBarrier(vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, barrier);
vk::device_memory staging_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
staging_memory.map_memory();
memcpy(staging_memory.data(), rendered_text.data(), rendered_text.size());
VkCommandBufferAllocateInfo cmdbufinfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, vk::BufferImageCopy copy_info{
.commandPool = command_pool, .bufferOffset = 0,
.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .bufferRowLength = 0,
.commandBufferCount = 1, .bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = {
.width = uint32_t(x_max - x_min),
.height = uint32_t(y_max - y_min),
.depth = 1,
},
}; };
VkCommandBuffer cmdbuf; cmdbuf.copyBufferToImage(staging_buffer, return_value.image, vk::ImageLayout::eTransferDstOptimal, copy_info);
CHECK_VK(vkAllocateCommandBuffers(device, &cmdbufinfo, &cmdbuf));
VkCommandBufferBeginInfo cmdbufbegininfo{
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
};
vkBeginCommandBuffer(cmdbuf, &cmdbufbegininfo);
VkImageMemoryBarrier barrier{ barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, barrier.dstAccessMask = vk::AccessFlagBits::eMemoryRead;
.srcAccessMask = 0, barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image,
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
VkBufferImageCopy copy_info{.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource =
VkImageSubresourceLayers{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = image_info.extent};
vkCmdCopyBufferToImage(cmdbuf, staging_buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_info);
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
barrier.newLayout = text::layout; barrier.newLayout = text::layout;
barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.baseMipLevel = 0;
vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); cmdbuf.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eBottomOfPipe, vk::DependencyFlags{}, {}, {}, barrier);
CHECK_VK(vkEndCommandBuffer(cmdbuf)); cmdbuf.end();
VkSubmitInfo submit_info{}; vk::SubmitInfo submit_info;
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.setCommandBuffers(*cmdbuf);
submit_info.commandBufferCount = 1; queue.submit(submit_info, *fence);
submit_info.pCommandBuffers = &cmdbuf; device.waitForFences(*fence, VK_TRUE, UINT64_MAX);
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence)); device.resetFences(*fence);
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, -1)); return return_value;
CHECK_VK(vkResetFences(device, 1, &fence));
return {
.image = std::move(image),
.memory = std::move(memory),
.size = {image_info.extent.width, image_info.extent.height}};
#endif #endif
} }
+19 -19
View File
@@ -19,41 +19,37 @@
#pragma once #pragma once
#ifndef TEST #include <vulkan/vulkan_raii.hpp>
#include "vk/device_memory.h"
#include "vk/image.h"
#endif
#include <vulkan/vulkan.h>
#include <freetype/freetype.h> #include <freetype/freetype.h>
#include <ft2build.h> #include <ft2build.h>
#include <hb.h> #include <hb.h>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include "vk/allocation.h"
struct text struct text
{ {
vk::Extent2D size;
#ifndef TEST #ifndef TEST
static inline const VkFormat format = VK_FORMAT_R8_UNORM; static inline const vk::Format format = vk::Format::eR8Unorm;
static inline const VkImageLayout layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; static inline const vk::ImageLayout layout = vk::ImageLayout::eShaderReadOnlyOptimal;
static inline const VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL; static inline const vk::ImageTiling tiling = vk::ImageTiling::eOptimal;
vk::image image; image_allocation image;
vk::device_memory memory;
#else #else
std::vector<uint8_t> bitmap; std::vector<uint8_t> bitmap;
#endif #endif
VkExtent2D size;
}; };
class text_rasterizer class text_rasterizer
{ {
VkDevice device{}; vk::raii::Device& device;
VkPhysicalDevice physical_device{}; vk::raii::PhysicalDevice& physical_device;
VkCommandPool command_pool{}; vk::raii::CommandPool& command_pool;
VkQueue queue{}; vk::raii::Queue& queue;
VkFence fence{}; vk::raii::Fence fence;
FT_Library freetype{}; FT_Library freetype{};
FT_Face face{}; FT_Face face{};
@@ -61,8 +57,12 @@ class text_rasterizer
hb_font_t * font{}; hb_font_t * font{};
hb_buffer_t * buffer{}; hb_buffer_t * buffer{};
image_allocation create_image(vk::Extent2D size, VmaMemoryUsage usage);
buffer_allocation create_buffer(size_t size, VmaMemoryUsage usage);
vk::raii::DeviceMemory allocate_memory(vk::Buffer buffer, vk::MemoryPropertyFlags flags);
public: public:
text_rasterizer(VkDevice device, VkPhysicalDevice physical_device, VkCommandPool command_pool, VkQueue queue); text_rasterizer(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, vk::raii::CommandPool& command_pool, vk::raii::Queue& queue);
~text_rasterizer(); ~text_rasterizer();
text render(std::string_view s); text render(std::string_view s);
+18 -27
View File
@@ -21,22 +21,23 @@
#include "application.h" #include "application.h"
#include <cassert> #include <cassert>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
#include <vulkan/vulkan_raii.hpp>
scene::~scene() {} scene::~scene() {}
scene::scene() : scene::scene() :
instance(application::instance_->xr_instance), instance(application::instance().xr_instance),
session(application::instance_->xr_session), session(application::instance().xr_session),
world_space(application::instance_->world_space), world_space(application::instance().world_space),
viewconfig(application::instance_->app_info.viewconfig), viewconfig(application::instance().app_info.viewconfig),
swapchains(application::instance_->xr_swapchains), swapchains(application::instance().xr_swapchains),
commandpool(application::instance_->vk_cmdpool) vk_instance(application::instance().vk_instance),
device(application::instance().vk_device),
physical_device(application::instance().vk_physical_device),
queue(application::instance().vk_queue),
commandpool(application::instance().vk_cmdpool)
{ {
vk_instance = application::instance_->vk_instance;
device = application::instance_->vk_device;
physical_device = application::instance_->vk_physical_device;
queue = application::instance_->vk_queue;
} }
void scene::render() void scene::render()
@@ -95,27 +96,17 @@ void scene::render_view(XrViewStateFlags flags, XrTime display_time, XrView & vi
void scene::on_unfocused() {} void scene::on_unfocused() {}
void scene::on_focused() {} void scene::on_focused() {}
VkFence scene::create_fence(bool signaled) vk::raii::Fence scene::create_fence(bool signaled)
{ {
// TODO: RAII vk::FenceCreateFlags flags{0};
VkFenceCreateInfo fence_info{};
fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fence_info.flags = signaled ? VK_FENCE_CREATE_SIGNALED_BIT : 0;
VkFence fence; if (signaled)
CHECK_VK(vkCreateFence(device, &fence_info, nullptr, &fence)); flags = vk::FenceCreateFlagBits::eSignaled;
return fence; return vk::raii::Fence(device, vk::FenceCreateInfo{.flags = flags});
} }
VkSemaphore scene::create_semaphore() vk::raii::Semaphore scene::create_semaphore()
{ {
// TODO: RAII return vk::raii::Semaphore(device, {});
VkSemaphoreCreateInfo sem_info{};
sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkSemaphore semaphore;
CHECK_VK(vkCreateSemaphore(device, &sem_info, nullptr, &semaphore));
return semaphore;
} }
+7 -8
View File
@@ -21,7 +21,6 @@
#include <cstdint> #include <cstdint>
#include "application.h"
#include "xr/session.h" #include "xr/session.h"
#include "xr/swapchain.h" #include "xr/swapchain.h"
@@ -34,14 +33,14 @@ protected:
XrViewConfigurationType viewconfig; XrViewConfigurationType viewconfig;
std::vector<xr::swapchain> & swapchains; std::vector<xr::swapchain> & swapchains;
VkInstance vk_instance; vk::raii::Instance& vk_instance;
VkDevice device; vk::raii::Device& device;
VkPhysicalDevice physical_device; vk::raii::PhysicalDevice& physical_device;
VkQueue queue; vk::raii::Queue& queue;
vk::command_pool & commandpool; vk::raii::CommandPool& commandpool;
VkFence create_fence(bool signaled = true); vk::raii::Fence create_fence(bool signaled = true);
VkSemaphore create_semaphore(); vk::raii::Semaphore create_semaphore();
public: public:
scene(); scene();
+210 -176
View File
@@ -21,209 +21,248 @@
#include "render/text_rasterizer.h" #include "render/text_rasterizer.h"
#include "stream.h" #include "stream.h"
#include "../common/version.h" #include "../common/version.h"
#include "application.h"
#include "vk/pipeline_layout.h"
#include "vk/shader.h"
#include "vk/pipeline.h"
#include <cstdint> #include <cstdint>
#include <glm/gtc/quaternion.hpp> #include <glm/gtc/quaternion.hpp>
#include <string> #include <string>
#include <tiny_gltf.h> #include <tiny_gltf.h>
#include <spdlog/spdlog.h>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_raii.hpp>
static const std::string discover_service = "_wivrn._tcp.local."; static const std::string discover_service = "_wivrn._tcp.local.";
scenes::lobby::~lobby() {} scenes::lobby::~lobby() {}
scenes::lobby::lobby() : scenes::lobby::lobby() :
status_string_rasterizer(device, physical_device, commandpool, queue), renderer(device, physical_device, queue) status_string_rasterizer(device, physical_device, commandpool, queue)//, renderer(device, physical_device, queue)
{ {
// renderer.load_gltf("Lobby.gltf");
uint32_t width = swapchains[0].width(); uint32_t width = swapchains[0].width();
uint32_t height = swapchains[0].height(); uint32_t height = swapchains[0].height();
// Create renderpass // Create renderpass
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; vk::RenderPassCreateInfo renderpass_info;
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{ vk::AttachmentDescription attachment_desc{
.format = swapchains[0].format(), .format = swapchains[0].format(),
.samples = VK_SAMPLE_COUNT_1_BIT, .samples = vk::SampleCountFlagBits::e1,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE, .storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .initialLayout = vk::ImageLayout::eUndefined,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
}}, };
.subpasses = {VkSubpassDescription{ renderpass_info.setAttachments(attachment_desc);
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
}},
.dependencies = {}};
renderpass = vk::renderpass(device, renderpass_info); vk::SubpassDescription subpass_desc{
.pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
};
vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
subpass_desc.setColorAttachments(color_ref);
renderpass_info.setSubpasses(subpass_desc);
VkSamplerCreateInfo sampler_info{ renderpass = vk::raii::RenderPass(device, renderpass_info);
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter = VK_FILTER_LINEAR, vk::SamplerCreateInfo sampler_info{
.minFilter = VK_FILTER_LINEAR, .magFilter = vk::Filter::eLinear,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, .minFilter = vk::Filter::eLinear,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .mipmapMode = vk::SamplerMipmapMode::eNearest,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .addressModeV = vk::SamplerAddressMode::eClampToBorder,
.mipLodBias = 0.0f, .addressModeW = vk::SamplerAddressMode::eClampToBorder,
.anisotropyEnable = VK_FALSE, .mipLodBias = 0.0f,
.maxAnisotropy = 1, .anisotropyEnable = VK_FALSE,
.compareEnable = VK_FALSE, .maxAnisotropy = 1,
.compareOp = VK_COMPARE_OP_NEVER, .compareEnable = VK_FALSE,
.minLod = 0.0f, .compareOp = vk::CompareOp::eNever,
.maxLod = 0.0f, .minLod = 0.0f,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, .maxLod = 0.0f,
.unnormalizedCoordinates = VK_FALSE, .borderColor = vk::BorderColor::eFloatOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE,
}; };
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &status_string_sampler)); status_string_sampler = vk::raii::Sampler(device, sampler_info);
// Create VkDescriptorSetLayout // Create descriptor set layout
VkDescriptorSetLayoutBinding layout_binding{ vk::DescriptorSetLayoutBinding layout_binding{
.binding = 0, .binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, .stageFlags = vk::ShaderStageFlagBits::eFragment,
}; };
VkDescriptorSetLayoutCreateInfo layout_info{ vk::DescriptorSetLayoutCreateInfo layout_info;
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, layout_info.setBindings(layout_binding);
.bindingCount = 1,
.pBindings = &layout_binding, status_string_image_descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info);
vk::DescriptorPoolSize status_string_image_descriptor_set_pool_size{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1,
}; };
CHECK_VK( vk::DescriptorPoolCreateInfo pool_info{
vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &status_string_image_descriptor_set_layout)); .maxSets = 1,
VkDescriptorPoolSize status_string_image_descriptor_set_pool_size{
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = 1,
}; };
pool_info.setPoolSizes(status_string_image_descriptor_set_pool_size);
VkDescriptorPoolCreateInfo pool_info{ status_string_descriptor_pool = vk::raii::DescriptorPool(device, pool_info);
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.flags = 0,
.maxSets = 1,
.poolSizeCount = 1,
.pPoolSizes = &status_string_image_descriptor_set_pool_size,
};
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &status_string_descriptor_pool));
VkDescriptorSetAllocateInfo ds_info{ vk::DescriptorSetAllocateInfo ds_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = *status_string_descriptor_pool,
.descriptorPool = status_string_descriptor_pool, .descriptorSetCount = 1,
.descriptorSetCount = 1,
.pSetLayouts = &status_string_image_descriptor_set_layout,
}; };
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &status_string_image_descriptor_set)); ds_info.setSetLayouts(*status_string_image_descriptor_set_layout);
status_string_image_descriptor_set = device.allocateDescriptorSets(ds_info)[0].release();
vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*status_string_image_descriptor_set_layout);
vk::PushConstantRange push_constant_range{
.stageFlags = vk::ShaderStageFlagBits::eVertex,
.offset = 0,
.size = sizeof(glm::mat4),
};
pipeline_layout_info.setPushConstantRanges(push_constant_range);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
// Create graphics pipeline // Create graphics pipeline
vk::shader vertex_shader(device, "text.vert"); vk::raii::ShaderModule vertex_shader = load_shader(device, "text.vert");
vk::shader fragment_shader(device, "text.frag"); vk::raii::ShaderModule fragment_shader = load_shader(device, "text.frag");
vk::pipeline::graphics_info pipeline_info; vk::pipeline_builder pipeline_info
{
.flags = {},
.Stages = {{
.stage = vk::ShaderStageFlagBits::eVertex,
.module = *vertex_shader,
.pName = "main",
},{
.stage = vk::ShaderStageFlagBits::eFragment,
.module = *fragment_shader,
.pName = "main",
}},
.VertexInputState = {.flags = {}},
.VertexBindingDescriptions = {},
.VertexAttributeDescriptions = {},
.InputAssemblyState = {{
.topology = vk::PrimitiveTopology::eTriangleList,
}},
.ViewportState = {.flags = {}},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)width,
.height = (float)height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = { .x = 0, .y = 0 },
.extent= { .width = width, .height = height },
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
};
pipeline_info.shader_stages.resize(2); pipeline = vk::raii::Pipeline(device, nullptr, pipeline_info);
pipeline_info.shader_stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
pipeline_info.shader_stages[0].module = vertex_shader;
pipeline_info.shader_stages[0].pName = "main";
pipeline_info.shader_stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
pipeline_info.shader_stages[1].module = fragment_shader;
pipeline_info.shader_stages[1].pName = "main";
pipeline_info.InputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipeline_info.viewports.push_back(VkViewport{0, 0, (float)width, (float)height, 0.0f, 1.0f});
pipeline_info.scissors.push_back(VkRect2D{{0, 0}, {width, height}});
pipeline_info.RasterizationState.polygonMode = VK_POLYGON_MODE_FILL;
pipeline_info.RasterizationState.lineWidth = 1;
pipeline_info.MultisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState pcbas{};
pcbas.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT;
pipeline_info.ColorBlendState.attachmentCount = 1;
pipeline_info.ColorBlendState.pAttachments = &pcbas;
pipeline_info.renderPass = renderpass;
pipeline_info.subpass = 0;
layout = vk::pipeline_layout(
device, {.descriptor_set_layouts = {status_string_image_descriptor_set_layout}, .push_constant_ranges = {VkPushConstantRange{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(glm::mat4)}}});
pipeline = vk::pipeline(device, pipeline_info, layout);
images_data.resize(swapchains.size()); images_data.resize(swapchains.size());
for (size_t i = 0; i < swapchains.size(); i++) for (size_t i = 0; i < swapchains.size(); i++)
{ {
auto & images = swapchains[i].images(); auto & images = swapchains[i].images();
images_data[i].resize(images.size()); images_data[i].reserve(images.size());
for (size_t j = 0; j < images.size(); j++) for (size_t j = 0; j < images.size(); j++)
{ {
VkFramebufferCreateInfo fb_create_info{}; vk::FramebufferCreateInfo fb_create_info{
fb_create_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; .renderPass = *renderpass,
fb_create_info.renderPass = renderpass; .attachmentCount = 1,
fb_create_info.attachmentCount = 1; .pAttachments = &*images[j].view,
fb_create_info.pAttachments = &images[j].view; .width = swapchains[i].width(),
fb_create_info.width = swapchains[i].width(); .height = swapchains[i].height(),
fb_create_info.height = swapchains[i].height(); .layers = 1,
fb_create_info.layers = 1; };
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &images_data[i][j].framebuffer));
images_data[i][j].render_finished = create_semaphore(); images_data[i].emplace_back(image_data{
.framebuffer = vk::raii::Framebuffer(device, fb_create_info),
.render_finished = create_semaphore()
});
} }
} }
command_buffer = commandpool.allocate_command_buffer(); vk::CommandBufferAllocateInfo alloc_info;
alloc_info.commandBufferCount = 1;
alloc_info.level = vk::CommandBufferLevel::ePrimary;
alloc_info.commandPool = *commandpool;
command_buffer = std::move(device.allocateCommandBuffers(alloc_info)[0]);
application::set_debug_reports_name((VkCommandBuffer)*command_buffer, "lobby command buffer");
fence = create_fence(false); fence = create_fence(false);
} }
void scenes::lobby::rasterize_status_string() void scenes::lobby::rasterize_status_string()
{ {
if (status_string_image_view)
vkDestroyImageView(device, status_string_image_view, nullptr);
status_string_rasterized_text = status_string_rasterizer.render(status_string); status_string_rasterized_text = status_string_rasterizer.render(status_string);
assert(status_string_rasterized_text.image != VK_NULL_HANDLE); vk::ImageViewCreateInfo iv_info{
assert(status_string_rasterized_text.memory != VK_NULL_HANDLE); .image = (VkImage)status_string_rasterized_text.image,
.viewType = vk::ImageViewType::e2D,
VkImageViewCreateInfo iv_info{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .format = status_string_rasterized_text.format,
.image = status_string_rasterized_text.image, .components = {
.viewType = VK_IMAGE_VIEW_TYPE_2D, .r = vk::ComponentSwizzle::eIdentity,
.format = status_string_rasterized_text.format, .g = vk::ComponentSwizzle::eIdentity,
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, .b = vk::ComponentSwizzle::eIdentity,
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .a = vk::ComponentSwizzle::eIdentity,
.baseMipLevel = 0, },
.levelCount = 1, .subresourceRange = {
.baseArrayLayer = 0, .aspectMask = vk::ImageAspectFlagBits::eColor,
.layerCount = 1}}; .baseMipLevel = 0,
.levelCount = 1,
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &status_string_image_view)); .baseArrayLayer = 0,
.layerCount = 1,
VkDescriptorImageInfo image_info{ },
.sampler = status_string_sampler,
.imageView = status_string_image_view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
}; };
VkWriteDescriptorSet descriptor_write{ status_string_image_view = vk::raii::ImageView(device, iv_info);
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet = status_string_image_descriptor_set, vk::DescriptorImageInfo image_info{
.dstBinding = 0, .sampler = *status_string_sampler,
.dstArrayElement = 0, .imageView = *status_string_image_view,
.descriptorCount = 1, .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.pImageInfo = &image_info,
}; };
vkUpdateDescriptorSets(device, 1, &descriptor_write, 0, nullptr); vk::WriteDescriptorSet descriptor_write{
.dstSet = status_string_image_descriptor_set,
.dstBinding = 0,
.dstArrayElement = 0,
.descriptorCount = 1,
.descriptorType = vk::DescriptorType::eCombinedImageSampler,
.pImageInfo = &image_info,
};
device.updateDescriptorSets(descriptor_write, {});
last_status_string = status_string; last_status_string = status_string;
} }
@@ -315,11 +354,9 @@ void scenes::lobby::render()
session.begin_frame(); session.begin_frame();
CHECK_VK(vkResetCommandBuffer(command_buffer, 0)); command_buffer.reset();
VkCommandBufferBeginInfo beginInfo{}; command_buffer.begin(vk::CommandBufferBeginInfo{});
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
CHECK_VK(vkBeginCommandBuffer(command_buffer, &beginInfo));
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space); auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
assert(views.size() == swapchains.size()); assert(views.size() == swapchains.size());
@@ -343,14 +380,12 @@ void scenes::lobby::render()
layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height(); layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height();
} }
CHECK_VK(vkEndCommandBuffer(command_buffer)); command_buffer.end();
VkSubmitInfo submitInfo{}; vk::SubmitInfo submit_info;
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.setCommandBuffers(*command_buffer);
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &command_buffer;
CHECK_VK(vkQueueSubmit(queue, 1, &submitInfo, fence)); queue.submit(submit_info, *fence);
XrCompositionLayerProjection layer{ XrCompositionLayerProjection layer{
.type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION,
@@ -365,8 +400,8 @@ void scenes::lobby::render()
session.end_frame(framestate.predictedDisplayTime, layers_base); session.end_frame(framestate.predictedDisplayTime, layers_base);
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX)); device.waitForFences(*fence, VK_TRUE, UINT64_MAX);
CHECK_VK(vkResetFences(device, 1, &fence)); device.resetFences(*fence);
} }
void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index) void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index)
@@ -374,22 +409,22 @@ void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrV
xr::swapchain & swapchain = swapchains[swapchain_index]; xr::swapchain & swapchain = swapchains[swapchain_index];
image_data & data = images_data[swapchain_index][image_index]; image_data & data = images_data[swapchain_index][image_index];
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}}; vk::ClearValue clear_color;
clear_color.color = {0.0f, 0.0f, 0.0f, 1.0f};
VkRenderPassBeginInfo renderPassInfo{}; vk::RenderPassBeginInfo renderpass_info{
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; .renderPass = *renderpass,
renderPassInfo.renderPass = renderpass; .framebuffer = *data.framebuffer,
renderPassInfo.framebuffer = data.framebuffer; .renderArea = {
renderPassInfo.renderArea.offset = {0, 0}; .offset = {0, 0},
renderPassInfo.renderArea.extent = {swapchain.width(), swapchain.height()}; .extent = {swapchain.width(), swapchain.height()},
renderPassInfo.clearValueCount = 1; }
renderPassInfo.pClearValues = &clearColor; };
renderpass_info.setClearValues(clear_color);
vkCmdBeginRenderPass(command_buffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); command_buffer.beginRenderPass(renderpass_info, vk::SubpassContents::eInline);
command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *layout, 0, status_string_image_descriptor_set, {});
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &status_string_image_descriptor_set, 0, nullptr);
float zn = 0.1; float zn = 0.1;
float r = tan(view.fov.angleRight); float r = tan(view.fov.angleRight);
@@ -420,11 +455,10 @@ void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrV
{-0.5 * aspect_ratio, -0.5, -10, 1}}; {-0.5 * aspect_ratio, -0.5, -10, 1}};
glm::mat4 mvp = proj * glm::inverse(view_matrix) * model_matrix; glm::mat4 mvp = proj * glm::inverse(view_matrix) * model_matrix;
vkCmdPushConstants(command_buffer, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(glm::mat4), &mvp);
vkCmdDraw(command_buffer, 6, 1, 0, 0); command_buffer.pushConstants<glm::mat4>(*layout, vk::ShaderStageFlagBits::eVertex, 0, mvp);
command_buffer.draw(6, 1, 0, 0);
vkCmdEndRenderPass(command_buffer); command_buffer.endRenderPass();
} }
void scenes::lobby::on_focused() void scenes::lobby::on_focused()
+17 -19
View File
@@ -20,9 +20,7 @@
#pragma once #pragma once
#include "scene.h" #include "scene.h"
#include "vk/buffer.h" #include <vulkan/vulkan_raii.hpp>
#include "vk/image.h"
#include "vk/renderpass.h"
#include "wivrn_discover.h" #include "wivrn_discover.h"
#include <tiny_gltf.h> #include <tiny_gltf.h>
@@ -39,25 +37,25 @@ class lobby : public scene
{ {
std::string status_string; std::string status_string;
std::string last_status_string; std::string last_status_string;
VkSampler status_string_sampler{}; vk::raii::Sampler status_string_sampler = nullptr;
text status_string_rasterized_text; text status_string_rasterized_text;
VkImageView status_string_image_view{}; vk::raii::ImageView status_string_image_view = nullptr;
VkDescriptorPool status_string_descriptor_pool{}; vk::raii::DescriptorPool status_string_descriptor_pool = nullptr;
VkDescriptorSetLayout status_string_image_descriptor_set_layout{}; vk::raii::DescriptorSetLayout status_string_image_descriptor_set_layout = nullptr;
VkDescriptorSet status_string_image_descriptor_set{}; vk::DescriptorSet status_string_image_descriptor_set;
text_rasterizer status_string_rasterizer; text_rasterizer status_string_rasterizer;
vk::renderpass renderpass; vk::raii::RenderPass renderpass = nullptr;
vk::pipeline_layout layout; vk::raii::PipelineLayout layout = nullptr;
vk::pipeline pipeline; vk::raii::Pipeline pipeline = nullptr;
VkFence fence{}; vk::raii::Fence fence = nullptr;
VkCommandBuffer command_buffer{}; vk::raii::CommandBuffer command_buffer = nullptr;
struct image_data struct image_data
{ {
VkFramebuffer framebuffer{}; vk::raii::Framebuffer framebuffer;
VkSemaphore render_finished{}; vk::raii::Semaphore render_finished;
}; };
std::vector<std::vector<image_data>> images_data; std::vector<std::vector<image_data>> images_data;
@@ -65,15 +63,15 @@ class lobby : public scene
std::optional<wivrn_discover> discover; std::optional<wivrn_discover> discover;
tinygltf::Model model; tinygltf::Model model;
std::vector<vk::device_memory> model_memory; std::vector<vk::DeviceMemory> model_memory;
std::vector<vk::buffer> model_buffers; std::vector<vk::Buffer> model_buffers;
std::vector<vk::image> model_images; std::vector<vk::Image> model_images;
void load_model(const std::string & filename); void load_model(const std::string & filename);
std::shared_ptr<stream> next_scene; std::shared_ptr<stream> next_scene;
scene_renderer renderer; // scene_renderer renderer;
void rasterize_status_string(); void rasterize_status_string();
+96 -115
View File
@@ -17,6 +17,9 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include <vulkan/vulkan.hpp>
#include <vulkan/vulkan_enums.hpp>
#include <vulkan/vulkan_raii.hpp>
#define GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS
#include "stream.h" #include "stream.h"
@@ -30,7 +33,6 @@
#include "utils/ranges.h" #include "utils/ranges.h"
#include "utils/sync_queue.h" #include "utils/sync_queue.h"
#include "vk/device_memory.h" #include "vk/device_memory.h"
#include "vk/image.h"
#include "wivrn_packets.h" #include "wivrn_packets.h"
#include "xr/details/enumerate.h" #include "xr/details/enumerate.h"
#include <algorithm> #include <algorithm>
@@ -111,7 +113,10 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
self->video_thread = std::thread(&stream::video, self.get()); self->video_thread = std::thread(&stream::video, self.get());
pthread_setname_np(self->video_thread.native_handle(), "video_thread"); pthread_setname_np(self->video_thread.native_handle(), "video_thread");
self->command_buffer = self->commandpool.allocate_command_buffer(); self->command_buffer = std::move(self->device.allocateCommandBuffers({
.commandPool = *self->commandpool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1})[0]);
self->fence = self->create_fence(false); self->fence = self->create_fence(false);
// Look up the XrActions for haptics // Look up the XrActions for haptics
@@ -258,38 +263,33 @@ void scenes::stream::render()
image_indices[swapchain_index] = image_index; image_indices[swapchain_index] = image_index;
} }
CHECK_VK(vkResetCommandBuffer(command_buffer, 0)); command_buffer.reset();
VkCommandBufferBeginInfo begin_info{ vk::CommandBufferBeginInfo begin_info;
.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit;
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, command_buffer.begin(begin_info);
};
CHECK_VK(vkBeginCommandBuffer(command_buffer, &begin_info));
// Transition the layout of the decoder framebuffer to the one the decoders expect // Transition the layout of the decoder framebuffer to the one the decoders expect
std::vector<VkImageMemoryBarrier> image_barriers; std::vector<vk::ImageMemoryBarrier> image_barriers;
for (size_t i = 0; i < decoder_output.size(); i++) for (size_t i = 0; i < decoder_output.size(); i++)
{ {
image_barriers.push_back(VkImageMemoryBarrier{ vk::ImageMemoryBarrier barrier;
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, barrier.srcAccessMask = vk::AccessFlagBits::eNone;
.srcAccessMask = 0, barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, barrier.oldLayout = vk::ImageLayout::eUndefined;
.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, barrier.newLayout = shard_accumulator::framebuffer_expected_layout;
.newLayout = shard_accumulator::framebuffer_expected_layout, barrier.srcQueueFamilyIndex = vk::QueueFamilyIgnored;
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, barrier.dstQueueFamilyIndex = vk::QueueFamilyIgnored;
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, barrier.image = (vk::Image)decoder_output[i].image;
.image = decoder_output[i].image, barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
.subresourceRange = { barrier.subresourceRange.baseMipLevel = 0;
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, barrier.subresourceRange.levelCount = 1;
.baseMipLevel = 0, barrier.subresourceRange.baseArrayLayer = 0;
.levelCount = 1, barrier.subresourceRange.layerCount = 1;
.baseArrayLayer = 0,
.layerCount = 1,
},
});
}
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data()); image_barriers.push_back(barrier);
}
command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, vk::DependencyFlags{}, {}, {}, image_barriers);
// Keep a reference to the resources needed to blit the images until vkWaitForFences // Keep a reference to the resources needed to blit the images until vkWaitForFences
std::vector<std::shared_ptr<shard_accumulator::blit_handle>> current_blit_handles; std::vector<std::shared_ptr<shard_accumulator::blit_handle>> current_blit_handles;
@@ -330,40 +330,35 @@ void scenes::stream::render()
image_barriers.clear(); image_barriers.clear();
for (size_t i = 0; i < decoder_output.size(); i++) for (size_t i = 0; i < decoder_output.size(); i++)
{ {
image_barriers.push_back(VkImageMemoryBarrier{ vk::ImageMemoryBarrier barrier;
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, barrier.srcAccessMask = vk::AccessFlagBits::eNone;
.srcAccessMask = 0, barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT, barrier.oldLayout = shard_accumulator::framebuffer_expected_layout;
.oldLayout = shard_accumulator::framebuffer_expected_layout, barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, barrier.srcQueueFamilyIndex = vk::QueueFamilyIgnored;
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, barrier.dstQueueFamilyIndex = vk::QueueFamilyIgnored;
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, barrier.image = (vk::Image)decoder_output[i].image;
.image = decoder_output[i].image, barrier.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
.subresourceRange = { barrier.subresourceRange.baseMipLevel = 0;
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, barrier.subresourceRange.levelCount = 1;
.baseMipLevel = 0, barrier.subresourceRange.baseArrayLayer = 0;
.levelCount = 1, barrier.subresourceRange.layerCount = 1;
.baseArrayLayer = 0,
.layerCount = 1, image_barriers.push_back(barrier);
},
});
} }
vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, image_barriers.size(), image_barriers.data()); command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, image_barriers);
// Reproject the image to the real pose // Reproject the image to the real pose
for (size_t view = 0; view < view_count; view++) for (size_t view = 0; view < view_count; view++)
{ {
size_t destination_index = view * swapchains[0].images().size() + image_indices[view]; size_t destination_index = view * swapchains[0].images().size() + image_indices[view];
reprojector.reproject(command_buffer, view, destination_index, pose[view].orientation, fov[view], views[view].pose.orientation, views[view].fov); reprojector->reproject(command_buffer, view, destination_index, pose[view].orientation, fov[view], views[view].pose.orientation, views[view].fov);
} }
CHECK_VK(vkEndCommandBuffer(command_buffer)); command_buffer.end();
VkSubmitInfo submit_info{ vk::SubmitInfo submit_info;
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, submit_info.setCommandBuffers(*command_buffer);
.commandBufferCount = 1, queue.submit(submit_info, *fence);
.pCommandBuffers = &command_buffer,
};
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence));
std::vector<XrCompositionLayerBaseHeader *> layers_base; std::vector<XrCompositionLayerBaseHeader *> layers_base;
std::vector<XrCompositionLayerProjectionView> layer_view; std::vector<XrCompositionLayerProjectionView> layer_view;
@@ -405,8 +400,8 @@ void scenes::stream::render()
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer)); layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base); session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base);
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX)); device.waitForFences(*fence, VK_TRUE, UINT64_MAX);
CHECK_VK(vkResetFences(device, 1, &fence)); device.resetFences(*fence);
// We don't need those after vkWaitForFences // We don't need those after vkWaitForFences
current_blit_handles.clear(); current_blit_handles.clear();
@@ -426,22 +421,6 @@ void scenes::stream::cleanup()
// Assumes decoder_mutex is locked // Assumes decoder_mutex is locked
ready_ = false; ready_ = false;
decoders.clear(); decoders.clear();
for (auto & output: decoder_output)
{
if (output.image)
vkDestroyImage(device, output.image, nullptr);
if (output.image_view)
vkDestroyImageView(device, output.image_view, nullptr);
if (output.memory)
vkFreeMemory(device, output.memory, nullptr);
output.image = VK_NULL_HANDLE;
output.image_view = VK_NULL_HANDLE;
output.memory = VK_NULL_HANDLE;
}
} }
void scenes::stream::setup(const to_headset::video_stream_description & description) void scenes::stream::setup(const to_headset::video_stream_description & description)
@@ -463,44 +442,44 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
VkExtent3D decoder_out_size{width, height, 1}; VkExtent3D decoder_out_size{width, height, 1};
for (size_t i = 0; i < view_count; i++) for (size_t i = 0; i < view_count; i++)
{ {
decoder_output[i].format = VK_FORMAT_A8B8G8R8_SRGB_PACK32; decoder_output[i].format = vk::Format::eA8B8G8R8SrgbPack32;
decoder_output[i].size = { decoder_output[i].size.width = width;
.width = width, decoder_output[i].size.height = height;
.height = height};
VkImageCreateInfo image_info{ vk::ImageCreateInfo image_info;
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, image_info.flags = vk::ImageCreateFlags{};
.flags = 0, image_info.imageType = vk::ImageType::e2D;
.imageType = VK_IMAGE_TYPE_2D, image_info.format = vk::Format::eA8B8G8R8SrgbPack32;
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32, image_info.extent = decoder_out_size;
.extent = decoder_out_size, image_info.mipLevels = 1;
.mipLevels = 1, image_info.arrayLayers = 1;
.arrayLayers = 1, image_info.samples = vk::SampleCountFlagBits::e1;
.samples = VK_SAMPLE_COUNT_1_BIT, image_info.tiling = vk::ImageTiling::eOptimal;
.tiling = VK_IMAGE_TILING_OPTIMAL, image_info.usage = vk::ImageUsageFlagBits::eSampled | shard_accumulator::framebuffer_usage;
.usage = VK_IMAGE_USAGE_SAMPLED_BIT | shard_accumulator::framebuffer_usage, image_info.sharingMode = vk::SharingMode::eExclusive;
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, image_info.initialLayout = vk::ImageLayout::eUndefined;
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
decoder_output[i].image = vk::image{device, image_info}.release(); VmaAllocationCreateInfo alloc_info{};
alloc_info.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
decoder_output[i].memory = vk::device_memory{device, physical_device, decoder_output[i].image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT}.release(); decoder_output[i].image = image_allocation{image_info, alloc_info};
VkImageViewCreateInfo image_view_info{ vk::ImageViewCreateInfo image_view_info;
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.image = decoder_output[i].image,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32,
.components = {}, // IDENTITY by default
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1}};
CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &decoder_output[i].image_view)); image_view_info.image = (VkImage)decoder_output[i].image;
image_view_info.viewType = vk::ImageViewType::e2D;
image_view_info.format = vk::Format::eA8B8G8R8SrgbPack32;
image_view_info.components.r = vk::ComponentSwizzle::eIdentity;
image_view_info.components.g = vk::ComponentSwizzle::eIdentity;
image_view_info.components.b = vk::ComponentSwizzle::eIdentity;
image_view_info.components.a = vk::ComponentSwizzle::eIdentity;
image_view_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
image_view_info.subresourceRange.baseMipLevel = 0;
image_view_info.subresourceRange.levelCount = 1;
image_view_info.subresourceRange.baseArrayLayer = 0;
image_view_info.subresourceRange.layerCount = 1;
decoder_output[i].image_view = vk::raii::ImageView(device, image_view_info);
} }
std::vector<shard_accumulator::blit_target> blit_targets; std::vector<shard_accumulator::blit_target> blit_targets;
@@ -508,10 +487,12 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
for (size_t i = 0; i < view_count; i++) for (size_t i = 0; i < view_count; i++)
{ {
blit_targets[i].image = decoder_output[i].image; blit_targets[i].image = (VkImage)decoder_output[i].image;
blit_targets[i].image_view = decoder_output[i].image_view; blit_targets[i].image_view = *decoder_output[i].image_view;
blit_targets[i].extent = {width, height}; blit_targets[i].extent.width = width;
blit_targets[i].offset = {static_cast<int>(width * i), 0}; blit_targets[i].extent.height = height;
blit_targets[i].offset.x = width * i;
blit_targets[i].offset.y = 0;
} }
for (const auto & [stream_index, item]: utils::enumerate(description.items)) for (const auto & [stream_index, item]: utils::enumerate(description.items))
@@ -520,27 +501,27 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
accumulator_images dec; accumulator_images dec;
dec.decoder = std::make_unique<shard_accumulator>(device, physical_device, item, description.fps, shared_from_this(), stream_index); dec.decoder = std::make_unique<shard_accumulator>(device, physical_device, item, description.fps, shared_from_this(), stream_index);
dec.decoder->set_blit_targets(blit_targets, VK_FORMAT_A8B8G8R8_SRGB_PACK32); dec.decoder->set_blit_targets(blit_targets, vk::Format::eA8B8G8R8SrgbPack32);
decoders.push_back(std::move(dec)); decoders.push_back(std::move(dec));
} }
spdlog::info("Initializing reprojector"); spdlog::info("Initializing reprojector");
VkExtent2D extent = {swapchains[0].width(), swapchains[0].height()}; vk::Extent2D extent = {swapchains[0].width(), swapchains[0].height()};
std::vector<VkImage> swapchain_images; std::vector<vk::Image> swapchain_images;
for (auto & swapchain: swapchains) for (auto & swapchain: swapchains)
{ {
for (auto & image: swapchain.images()) for (auto & image: swapchain.images())
swapchain_images.push_back(image.image); swapchain_images.push_back(image.image);
} }
std::vector<VkImage> images; std::vector<vk::Image> images;
for (renderpass_output & i: decoder_output) for (renderpass_output & i: decoder_output)
{ {
images.push_back(i.image); images.push_back((vk::Image)i.image);
} }
reprojector.init(device, physical_device, images, swapchain_images, extent, swapchains[0].format(), description); reprojector.emplace(device, physical_device, images, swapchain_images, extent, swapchains[0].format(), description);
} }
void scenes::stream::video() void scenes::stream::video()
+8 -9
View File
@@ -51,11 +51,10 @@ class stream : public scene, public std::enable_shared_from_this<stream>
struct renderpass_output struct renderpass_output
{ {
VkExtent2D size; vk::Extent2D size;
VkFormat format; vk::Format format;
VkImage image; image_allocation image;
VkDeviceMemory memory; vk::raii::ImageView image_view = nullptr;
VkImageView image_view;
}; };
std::unique_ptr<wivrn_session> network_session; std::unique_ptr<wivrn_session> network_session;
@@ -71,10 +70,10 @@ class stream : public scene, public std::enable_shared_from_this<stream>
std::array<renderpass_output, view_count> decoder_output{}; std::array<renderpass_output, view_count> decoder_output{};
stream_reprojection reprojector; std::optional<stream_reprojection> reprojector;
VkFence fence; vk::raii::Fence fence = nullptr;
VkCommandBuffer command_buffer; vk::raii::CommandBuffer command_buffer = nullptr;
std::array<std::pair<XrAction, XrPath>, 2> haptics_actions; std::array<std::pair<XrAction, XrPath>, 2> haptics_actions;
std::vector<std::tuple<device_id, XrAction, XrActionType>> input_actions; std::vector<std::tuple<device_id, XrAction, XrActionType>> input_actions;
@@ -103,7 +102,7 @@ public:
void operator()(to_headset::video_stream_description &&); void operator()(to_headset::video_stream_description &&);
void operator()(audio_data&&); void operator()(audio_data&&);
VkFormat swapchain_format() vk::Format swapchain_format()
{ {
return swapchains[0].format(); return swapchains[0].format();
} }
+1
View File
@@ -18,6 +18,7 @@
*/ */
#include "stream.h" #include "stream.h"
#include "application.h"
void scenes::stream::read_actions() void scenes::stream::read_actions()
{ {
+1
View File
@@ -18,6 +18,7 @@
*/ */
#include "stream.h" #include "stream.h"
#include <spdlog/spdlog.h>
void scenes::stream::process_packets() void scenes::stream::process_packets()
{ {
+266 -266
View File
@@ -18,12 +18,16 @@
*/ */
#include "stream_reprojection.h" #include "stream_reprojection.h"
#include "spdlog/spdlog.h" #include "vk/allocation.h"
#include "utils/check.h" #include "vk/shader.h"
#include "vk/pipeline.h"
#include <spdlog/spdlog.h>
#include <array> #include <array>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <glm/gtx/quaternion.hpp> #include <glm/gtx/quaternion.hpp>
#include <vk_mem_alloc.h>
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_raii.hpp>
struct stream_reprojection::uniform struct stream_reprojection::uniform
{ {
@@ -36,311 +40,312 @@ struct stream_reprojection::uniform
alignas(8) glm::vec2 xc; alignas(8) glm::vec2 xc;
}; };
stream_reprojection::~stream_reprojection() stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector<vk::Image> input_images_, std::vector<vk::Image> output_images_, vk::Extent2D extent, vk::Format format, const xrt::drivers::wivrn::to_headset::video_stream_description & description) :
input_images(std::move(input_images_)),
output_images(std::move(output_images_)),
extent(extent)
{ {
cleanup();
}
void stream_reprojection::cleanup()
{
if (device)
{
if (descriptor_pool)
vkDestroyDescriptorPool(device, descriptor_pool, nullptr);
if (descriptor_set_layout)
vkDestroyDescriptorSetLayout(device, descriptor_set_layout, nullptr);
for (VkFramebuffer framebuffer: framebuffers)
vkDestroyFramebuffer(device, framebuffer, nullptr);
for (VkImageView image_view: output_image_views)
vkDestroyImageView(device, image_view, nullptr);
for (VkImageView image_view: input_image_views)
vkDestroyImageView(device, image_view, nullptr);
if (sampler)
vkDestroySampler(device, sampler, nullptr);
descriptor_pool = VK_NULL_HANDLE;
descriptor_set_layout = VK_NULL_HANDLE;
sampler = VK_NULL_HANDLE;
framebuffers.clear();
output_image_views.clear();
input_image_views.clear();
ubo.clear();
}
}
void stream_reprojection::init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images_, std::vector<VkImage> output_images_, VkExtent2D extent, VkFormat format, const xrt::drivers::wivrn::to_headset::video_stream_description & description)
{
cleanup();
this->device = device;
this->physical_device = physical_device,
this->input_images = std::move(input_images_);
this->output_images = std::move(output_images_);
this->extent = extent;
this->format = format;
foveation_parameters = description.foveation; foveation_parameters = description.foveation;
VkPhysicalDeviceProperties properties; vk::PhysicalDeviceProperties properties = physical_device.getProperties();
vkGetPhysicalDeviceProperties(physical_device, &properties);
VkSamplerCreateInfo sampler_info{ vk::SamplerCreateInfo sampler_info{
.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = vk::Filter::eLinear,
.magFilter = VK_FILTER_LINEAR, .minFilter = vk::Filter::eLinear,
.minFilter = VK_FILTER_LINEAR, .mipmapMode = vk::SamplerMipmapMode::eNearest,
.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, .addressModeU = vk::SamplerAddressMode::eClampToBorder,
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .addressModeV = vk::SamplerAddressMode::eClampToBorder,
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .addressModeW = vk::SamplerAddressMode::eClampToBorder,
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER, .mipLodBias = 0.0f,
.mipLodBias = 0.0f, .anisotropyEnable = VK_FALSE,
.anisotropyEnable = VK_FALSE, .maxAnisotropy = 1,
.maxAnisotropy = 1, .compareEnable = VK_FALSE,
.compareEnable = VK_FALSE, .compareOp = vk::CompareOp::eNever,
.compareOp = VK_COMPARE_OP_NEVER, .minLod = 0.0f,
.minLod = 0.0f, .maxLod = 0.0f,
.maxLod = 0.0f, .borderColor = vk::BorderColor::eFloatOpaqueBlack,
.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK, .unnormalizedCoordinates = VK_FALSE,
.unnormalizedCoordinates = VK_FALSE,
}; };
CHECK_VK(vkCreateSampler(device, &sampler_info, nullptr, &sampler)); sampler = vk::raii::Sampler(device, sampler_info);
size_t uniform_size = sizeof(uniform) + properties.limits.minUniformBufferOffsetAlignment - 1; size_t uniform_size = sizeof(uniform) + properties.limits.minUniformBufferOffsetAlignment - 1;
uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment; uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment;
VkBufferCreateInfo create_info{ vk::BufferCreateInfo create_info{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = uniform_size * input_images.size(),
.size = uniform_size * input_images.size(), .usage = vk::BufferUsageFlagBits::eUniformBuffer,
.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, .sharingMode = vk::SharingMode::eExclusive,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
}; };
buffer = vk::buffer(device, create_info);
memory = vk::device_memory(device, physical_device, buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VmaAllocationCreateInfo alloc_info{
memory.map_memory(); .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
};
buffer = buffer_allocation(create_info, alloc_info);
void * data = buffer.map();
for (size_t i = 0; i < input_images.size(); i++) for (size_t i = 0; i < input_images.size(); i++)
ubo.push_back(reinterpret_cast<uniform *>(reinterpret_cast<uintptr_t>(memory.data()) + i * uniform_size)); ubo.push_back(reinterpret_cast<uniform *>(reinterpret_cast<uintptr_t>(data) + i * uniform_size));
// Create VkDescriptorSetLayout // Create VkDescriptorSetLayout
std::array<VkDescriptorSetLayoutBinding, 2> layout_binding{ std::array layout_binding{
VkDescriptorSetLayoutBinding{ vk::DescriptorSetLayoutBinding{
.binding = 0, .binding = 0,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = 1, .descriptorCount = 1,
.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, .stageFlags = vk::ShaderStageFlagBits::eFragment,
},
vk::DescriptorSetLayoutBinding{
.binding = 1,
.descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1,
.stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
}
};
vk::DescriptorSetLayoutCreateInfo layout_info;
layout_info.setBindings(layout_binding);
descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info);
std::array pool_size{
vk::DescriptorPoolSize{
.type = vk::DescriptorType::eCombinedImageSampler,
.descriptorCount = (uint32_t)input_images.size(),
}, },
{ vk::DescriptorPoolSize{
.binding = 1, .type = vk::DescriptorType::eUniformBuffer,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorCount = (uint32_t)input_images.size(),
.descriptorCount = 1, }
.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
}};
VkDescriptorSetLayoutCreateInfo layout_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = layout_binding.size(),
.pBindings = layout_binding.data(),
}; };
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout)); vk::DescriptorPoolCreateInfo pool_info;
pool_info.flags = vk::DescriptorPoolCreateFlags{};
pool_info.maxSets = input_images.size();
pool_info.setPoolSizes(pool_size);
std::array<VkDescriptorPoolSize, 2> pool_size{VkDescriptorPoolSize{ descriptor_pool = vk::raii::DescriptorPool(device, pool_info);
.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
.descriptorCount = (uint32_t)input_images.size(),
},
VkDescriptorPoolSize{
.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
.descriptorCount = (uint32_t)input_images.size(),
}};
VkDescriptorPoolCreateInfo pool_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.flags = 0,
.maxSets = (uint32_t)input_images.size(),
.poolSizeCount = pool_size.size(),
.pPoolSizes = pool_size.data(),
};
CHECK_VK(vkCreateDescriptorPool(device, &pool_info, nullptr, &descriptor_pool));
// Create image views and descriptor sets // Create image views and descriptor sets
input_image_views.reserve(input_images.size()); input_image_views.reserve(input_images.size());
descriptor_sets.reserve(input_images.size()); descriptor_sets.reserve(input_images.size());
VkDeviceSize offset = 0; VkDeviceSize offset = 0;
for (VkImage image: input_images) for (vk::Image image: input_images)
{ {
VkImageViewCreateInfo iv_info{ vk::ImageViewCreateInfo iv_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = image,
.image = image, .viewType = vk::ImageViewType::e2D,
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = vk::Format::eA8B8G8R8SrgbPack32,
.format = VK_FORMAT_A8B8G8R8_SRGB_PACK32, .components = {
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, .r = vk::ComponentSwizzle::eIdentity,
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .g = vk::ComponentSwizzle::eIdentity,
.baseMipLevel = 0, .b = vk::ComponentSwizzle::eIdentity,
.levelCount = 1, .a = vk::ComponentSwizzle::eIdentity,
.baseArrayLayer = 0, },
.layerCount = 1}}; .subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
VkImageView image_view; .baseMipLevel = 0,
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view)); .levelCount = 1,
input_image_views.push_back(image_view); .baseArrayLayer = 0,
.layerCount = 1,
VkDescriptorSetAllocateInfo ds_info{ }
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
.descriptorPool = descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &descriptor_set_layout,
};
VkDescriptorSet ds;
CHECK_VK(vkAllocateDescriptorSets(device, &ds_info, &ds));
descriptor_sets.push_back(ds);
VkDescriptorImageInfo image_info{
.sampler = sampler,
.imageView = image_view,
.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
}; };
VkDescriptorBufferInfo buffer_info{ input_image_views.emplace_back(device, iv_info);
.buffer = buffer, .offset = offset, .range = sizeof(uniform)};
vk::DescriptorSetAllocateInfo ds_info{
.descriptorPool = *descriptor_pool,
.descriptorSetCount = 1,
.pSetLayouts = &*descriptor_set_layout,
};
descriptor_sets.push_back(device.allocateDescriptorSets(ds_info)[0].release());
vk::DescriptorImageInfo image_info{
.sampler = *sampler,
.imageView = *input_image_views.back(),
.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
};
vk::DescriptorBufferInfo buffer_info{
.buffer = (vk::Buffer)buffer,
.offset = offset,
.range = sizeof(uniform),
};
offset += uniform_size; offset += uniform_size;
std::array<VkWriteDescriptorSet, 2> write{ std::array write{
VkWriteDescriptorSet{ vk::WriteDescriptorSet{
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = descriptor_sets.back(),
.dstSet = ds, .dstBinding = 0,
.dstBinding = 0, .dstArrayElement = 0,
.dstArrayElement = 0, .descriptorCount = 1,
.descriptorCount = 1, .descriptorType = vk::DescriptorType::eCombinedImageSampler,
.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &image_info,
.pImageInfo = &image_info, },
}, vk::WriteDescriptorSet{
VkWriteDescriptorSet{ .dstSet = descriptor_sets.back(),
.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstBinding = 1,
.dstSet = ds, .dstArrayElement = 0,
.dstBinding = 1, .descriptorCount = 1,
.dstArrayElement = 0, .descriptorType = vk::DescriptorType::eUniformBuffer,
.descriptorCount = 1, .pBufferInfo = &buffer_info,
.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, }
.pBufferInfo = &buffer_info},
}; };
vkUpdateDescriptorSets(device, write.size(), write.data(), 0, nullptr);
device.updateDescriptorSets(write, {});
} }
// Create renderpass // Create renderpass
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; vk::AttachmentReference color_ref{
.attachment = 0,
.layout = vk::ImageLayout::eColorAttachmentOptimal,
};
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{ vk::AttachmentDescription attachment{
.format = format, .format = format,
.samples = VK_SAMPLE_COUNT_1_BIT, .samples = vk::SampleCountFlagBits::e1,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE, .storeOp = vk::AttachmentStoreOp::eStore,
.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .initialLayout = vk::ImageLayout::eColorAttachmentOptimal,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .finalLayout = vk::ImageLayout::eColorAttachmentOptimal,
}}, };
.subpasses = {VkSubpassDescription{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, vk::SubpassDescription subpass{
.colorAttachmentCount = 1, .pipelineBindPoint = vk::PipelineBindPoint::eGraphics,
.pColorAttachments = &color_ref, };
}}, subpass.setColorAttachments(color_ref);
.dependencies = {}};
vk::RenderPassCreateInfo renderpass_info;
renderpass_info.setAttachments(attachment);
renderpass_info.setSubpasses(subpass);
renderpass = vk::raii::RenderPass(device, renderpass_info);
renderpass = vk::renderpass(device, renderpass_info);
// Create graphics pipeline // Create graphics pipeline
vk::shader vertex_shader(device, "reprojection.vert"); vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert");
vk::shader fragment_shader(device, "reprojection.frag"); vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag");
VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT};
layout = vk::pipeline_layout(device, {.descriptor_set_layouts = {descriptor_set_layout}}); vk::PipelineLayoutCreateInfo pipeline_layout_info;
pipeline_layout_info.setSetLayouts(*descriptor_set_layout);
layout = vk::raii::PipelineLayout(device, pipeline_layout_info);
VkBool32 use_foveation[] = { VkBool32 use_foveation[] = {
foveation_parameters[0].x.scale < 1, foveation_parameters[0].x.scale < 1,
foveation_parameters[0].y.scale < 1 foveation_parameters[0].y.scale < 1
}; };
std::vector<VkSpecializationMapEntry> specialization_constants_desc = { std::array specialization_constants_desc{
{.constantID = 0, .offset = 0, .size = sizeof(VkBool32)}, vk::SpecializationMapEntry{
{.constantID = 1, .offset = sizeof(VkBool32), .size = sizeof(VkBool32)} .constantID = 0,
.offset = 0,
.size = sizeof(VkBool32),
},
vk::SpecializationMapEntry{
.constantID = 1,
.offset = sizeof(VkBool32),
.size = sizeof(VkBool32),
}
}; };
VkSpecializationInfo specialization_info{ vk::SpecializationInfo specialization_info;
.mapEntryCount = (uint32_t)specialization_constants_desc.size(),
.pMapEntries = specialization_constants_desc.data(),
.dataSize = sizeof(use_foveation),
.pData = use_foveation};
vk::pipeline::graphics_info pipeline_info{ specialization_info.setMapEntries(specialization_constants_desc);
.shader_stages = specialization_info.setData<VkBool32>(use_foveation);
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vertex_shader, .pName = "main"},
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fragment_shader, .pName = "main", .pSpecializationInfo = &specialization_info}}, vk::pipeline_builder pipeline_info
.vertex_input_bindings = {}, {
.vertex_input_attributes = {}, .flags = {},
.InputAssemblyState = {.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP}, .Stages = {{
.viewports = {VkViewport{.x = 0, .stage = vk::ShaderStageFlagBits::eVertex,
.y = 0, .module = *vertex_shader,
.width = (float)extent.width, .pName = "main",
.height = (float)extent.height, },{
.minDepth = 0, .stage = vk::ShaderStageFlagBits::eFragment,
.maxDepth = 1}}, .module = *fragment_shader,
.scissors = {VkRect2D{ .pName = "main",
.offset = {0, 0}, .pSpecializationInfo = &specialization_info,
.extent = extent, }},
}}, .VertexInputState = {.flags = {}},
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1}, .VertexBindingDescriptions = {},
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}, .VertexAttributeDescriptions = {},
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas}, .InputAssemblyState = {{
.dynamic_states = {}, .topology = vk::PrimitiveTopology::eTriangleStrip,
.renderPass = renderpass, }},
.subpass = 0, .ViewportState = {.flags = {}},
.Viewports = {{
.x = 0,
.y = 0,
.width = (float)extent.width,
.height = (float)extent.height,
.minDepth = 0,
.maxDepth = 1,
}},
.Scissors = {{
.offset = { .x = 0, .y = 0 },
.extent= extent,
}},
.RasterizationState = {{
.polygonMode = vk::PolygonMode::eFill,
.lineWidth = 1,
}},
.MultisampleState = {{
.rasterizationSamples = vk::SampleCountFlagBits::e1,
}},
.ColorBlendState = {.flags = {}},
.ColorBlendAttachments = {{
.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB
}},
.layout = *layout,
.renderPass = *renderpass,
.subpass = 0,
}; };
pipeline = vk::pipeline(device, pipeline_info, layout); pipeline = vk::raii::Pipeline(device, nullptr, pipeline_info);
// Create image views and framebuffers // Create image views and framebuffers
output_image_views.reserve(output_images.size()); output_image_views.reserve(output_images.size());
framebuffers.reserve(output_images.size()); framebuffers.reserve(output_images.size());
for (VkImage image: output_images) for (vk::Image image: output_images)
{ {
VkImageViewCreateInfo iv_info{ vk::ImageViewCreateInfo iv_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = image,
.image = image, .viewType = vk::ImageViewType::e2D,
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = format,
.format = format, .components = {
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, .r = vk::ComponentSwizzle::eIdentity,
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .g = vk::ComponentSwizzle::eIdentity,
.baseMipLevel = 0, .b = vk::ComponentSwizzle::eIdentity,
.levelCount = 1, .a = vk::ComponentSwizzle::eIdentity,
.baseArrayLayer = 0, },
.layerCount = 1}}; .subresourceRange = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
VkImageView image_view; .baseMipLevel = 0,
CHECK_VK(vkCreateImageView(device, &iv_info, nullptr, &image_view)); .levelCount = 1,
output_image_views.push_back(image_view); .baseArrayLayer = 0,
.layerCount = 1,
VkFramebufferCreateInfo fb_create_info{ },
.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,
.renderPass = renderpass,
.attachmentCount = 1,
.pAttachments = &image_view,
.width = extent.width,
.height = extent.height,
.layers = 1,
}; };
VkFramebuffer framebuffer; output_image_views.emplace_back(device, iv_info);
CHECK_VK(vkCreateFramebuffer(device, &fb_create_info, nullptr, &framebuffer));
framebuffers.push_back(framebuffer); vk::FramebufferCreateInfo fb_create_info{
.renderPass = *renderpass,
.width = extent.width,
.height = extent.height,
.layers = 1,
};
fb_create_info.setAttachments(*output_image_views.back());
framebuffers.emplace_back(device, fb_create_info);
} }
} }
void stream_reprojection::reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov) void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf dest_pose, XrFovf dest_fov)
{ {
if (source < 0 || source >= (int)input_images.size()) if (source < 0 || source >= (int)input_images.size())
throw std::runtime_error("Invalid source image index"); throw std::runtime_error("Invalid source image index");
@@ -399,26 +404,21 @@ void stream_reprojection::reproject(VkCommandBuffer command_buffer, int source,
ubo[source]->lambda.y = foveation_parameters[source].y.a / foveation_parameters[source].y.scale; ubo[source]->lambda.y = foveation_parameters[source].y.a / foveation_parameters[source].y.scale;
ubo[source]->xc.y = foveation_parameters[source].y.center; ubo[source]->xc.y = foveation_parameters[source].y.center;
VkClearValue clear_color{}; vk::ClearValue clear_color;
VkRenderPassBeginInfo begin_info{ vk::RenderPassBeginInfo begin_info{
.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = *renderpass,
.renderPass = renderpass, .framebuffer = *framebuffers[destination],
.framebuffer = framebuffers[destination], .renderArea = {
.renderArea = .offset = {0, 0},
{ .extent = extent,
.offset = {0, 0}, },
.extent = extent,
},
.clearValueCount = 1,
.pClearValues = &clear_color,
}; };
begin_info.setClearValues(clear_color);
vkCmdBeginRenderPass(command_buffer, &begin_info, VK_SUBPASS_CONTENTS_INLINE); command_buffer.beginRenderPass(begin_info, vk::SubpassContents::eInline);
vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *pipeline);
command_buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *layout, 0, descriptor_sets[source], {});
vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &descriptor_sets[source], 0, nullptr); command_buffer.draw(3, 1, 0, 0);
vkCmdDraw(command_buffer, 3, 1, 0, 0); command_buffer.endRenderPass();
vkCmdEndRenderPass(command_buffer);
} }
+23 -37
View File
@@ -19,59 +19,45 @@
#pragma once #pragma once
#include "vk/buffer.h" #include "vk/allocation.h"
#include "vk/device_memory.h"
#include "vk/pipeline.h"
#include "vk/pipeline_layout.h"
#include "vk/renderpass.h"
#include "vk/shader.h"
#include "wivrn_packets.h" #include "wivrn_packets.h"
#include <vulkan/vulkan_core.h> #include <vulkan/vulkan_core.h>
#include <openxr/openxr.h> #include <openxr/openxr.h>
#include <vulkan/vulkan_raii.hpp>
class stream_reprojection class stream_reprojection
{ {
struct uniform; struct uniform;
VkDevice device;
VkPhysicalDevice physical_device;
// Uniform buffer // Uniform buffer
vk::buffer buffer; buffer_allocation buffer;
vk::device_memory memory; std::vector<uniform *> ubo;
std::vector<uniform *> ubo{};
// Source images
VkSampler sampler{};
std::vector<VkImage> input_images;
std::vector<VkImageView> input_image_views;
std::vector<VkDescriptorSet> descriptor_sets;
// Destination images
std::vector<VkImage> output_images;
std::vector<VkImageView> output_image_views;
std::vector<VkFramebuffer> framebuffers;
VkExtent2D extent{};
VkFormat format{};
// Graphic pipeline // Graphic pipeline
VkDescriptorSetLayout descriptor_set_layout{}; vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr;
VkDescriptorPool descriptor_pool{}; vk::raii::DescriptorPool descriptor_pool = nullptr;
vk::pipeline_layout layout; vk::raii::PipelineLayout layout = nullptr;
vk::pipeline pipeline; vk::raii::RenderPass renderpass = nullptr;
vk::renderpass renderpass; vk::raii::Pipeline pipeline = nullptr;
// Source images
vk::raii::Sampler sampler = nullptr;
std::vector<vk::Image> input_images;
std::vector<vk::raii::ImageView> input_image_views;
std::vector<vk::DescriptorSet> descriptor_sets;
// Destination images
std::vector<vk::Image> output_images;
std::vector<vk::raii::ImageView> output_image_views;
std::vector<vk::raii::Framebuffer> framebuffers;
vk::Extent2D extent;
// Foveation // Foveation
std::array<xrt::drivers::wivrn::to_headset::video_stream_description::foveation_parameter, 2> foveation_parameters; std::array<xrt::drivers::wivrn::to_headset::video_stream_description::foveation_parameter, 2> foveation_parameters;
void cleanup();
public: public:
stream_reprojection() = default; stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector<vk::Image> input_images, std::vector<vk::Image> output_images, vk::Extent2D extent, vk::Format format, const xrt::drivers::wivrn::to_headset::video_stream_description & description);
stream_reprojection(const stream_reprojection &) = delete; stream_reprojection(const stream_reprojection &) = delete;
void init(VkDevice device, VkPhysicalDevice physical_device, std::vector<VkImage> input_images, std::vector<VkImage> output_images, VkExtent2D extent, VkFormat format, const xrt::drivers::wivrn::to_headset::video_stream_description & description);
~stream_reprojection(); void reproject(vk::raii::CommandBuffer& command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf destination_pose, XrFovf destination_fov);
void reproject(VkCommandBuffer command_buffer, int source, int destination, XrQuaternionf source_pose, XrFovf source_fov, XrQuaternionf destination_pose, XrFovf destination_fov);
}; };
+1
View File
@@ -19,6 +19,7 @@
#include "stream.h" #include "stream.h"
#include "utils/ranges.h" #include "utils/ranges.h"
#include "application.h"
#include <thread> #include <thread>
static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time) static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time)
+29 -16
View File
@@ -1,7 +1,7 @@
/* /*
* WiVRn VR streaming * WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net> * Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net> * Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
@@ -19,22 +19,35 @@
#pragma once #pragma once
#include "utils/handle.h" #include <cassert>
#include <vulkan/vulkan.h> #include <concepts>
namespace vk template<typename T>
class singleton
{ {
class image : public utils::handle<VkImage> // static_assert(std::derived_from<T, singleton<T>>);
{
VkDevice device{}; static T * instance_;
protected:
singleton()
{
assert(instance_ == nullptr);
instance_ = reinterpret_cast<T*>(this);
}
~singleton()
{
assert(instance_ == this);
instance_ = nullptr;
}
public: public:
image() = default; static T & instance()
image(VkDevice device, const VkImageCreateInfo & create_info); {
image(const image &) = delete; assert(instance_ != nullptr);
image(image &&) = default; return *reinterpret_cast<T*>(instance_);
image & operator=(const image &) = delete; }
image & operator=(image &&) = default;
~image();
}; };
} // namespace vk
template<typename T> T * singleton<T>::instance_;
+116
View File
@@ -0,0 +1,116 @@
/*
* WiVRn VR streaming
* Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "allocation.h"
#include "application.h"
#include "utils/check.h"
#include <utility>
#include <vk_mem_alloc.h>
buffer_allocation::buffer_allocation(const vk::BufferCreateInfo & buffer_info, const VmaAllocationCreateInfo & alloc_info)
{
VmaAllocator allocator = application::get_allocator();
VkBuffer tmp;
CHECK_VK(vmaCreateBuffer(allocator, &static_cast<const VkBufferCreateInfo&>(buffer_info), &alloc_info, &tmp, &allocation, nullptr));
buffer = vk::raii::Buffer(application::get_device(), tmp);
}
buffer_allocation::~buffer_allocation()
{
VmaAllocator allocator = application::get_allocator();
if (data)
vmaUnmapMemory(allocator, allocation);
vmaDestroyBuffer(allocator, buffer.release(), allocation);
}
buffer_allocation::buffer_allocation(buffer_allocation && other) :
allocation(other.allocation),
buffer(std::move(other.buffer)),
data(other.data)
{
other.allocation = nullptr;
other.data = nullptr;
}
void * buffer_allocation::map()
{
if (data)
return data;
VmaAllocator allocator = application::get_allocator();
CHECK_VK(vmaMapMemory(allocator, allocation, &data));
return data;
}
const buffer_allocation & buffer_allocation::operator=(buffer_allocation && other)
{
std::swap(allocation, other.allocation);
std::swap(buffer, other.buffer);
return *this;
}
image_allocation::image_allocation(const vk::ImageCreateInfo & image_info, const VmaAllocationCreateInfo & alloc_info)
{
VmaAllocator allocator = application::get_allocator();
VkImage tmp;
CHECK_VK(vmaCreateImage(allocator, &static_cast<const VkImageCreateInfo&>(image_info), &alloc_info, &tmp, &allocation, nullptr));
image = vk::raii::Image(application::get_device(), tmp);
}
image_allocation::~image_allocation()
{
VmaAllocator allocator = application::get_allocator();
if (data)
vmaUnmapMemory(allocator, allocation);
vmaDestroyImage(allocator, image.release(), allocation);
}
image_allocation::image_allocation(image_allocation && other) :
allocation(other.allocation),
image(std::move(other.image)),
data(other.data)
{
other.allocation = nullptr;
other.data = nullptr;
}
void * image_allocation::map()
{
if (data)
return data;
VmaAllocator allocator = application::get_allocator();
CHECK_VK(vmaMapMemory(allocator, allocation, &data));
return data;
}
const image_allocation & image_allocation::operator=(image_allocation && other)
{
std::swap(allocation, other.allocation);
std::swap(image, other.image);
return *this;
}
+129
View File
@@ -0,0 +1,129 @@
/*
* WiVRn VR streaming
* Copyright (C) 2023 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2023 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "vk_mem_alloc.h"
#include <vulkan/vulkan_raii.hpp>
class buffer_allocation
{
VmaAllocation allocation = nullptr;
vk::raii::Buffer buffer = nullptr;
void * data = nullptr;
public:
operator VkBuffer() const
{
return *buffer;
}
operator vk::Buffer() const
{
return *buffer;
}
operator const vk::raii::Buffer&() const
{
return buffer;
}
operator vk::raii::Buffer&()
{
return buffer;
}
operator VmaAllocation() const
{
return allocation;
}
vk::raii::Buffer* operator->()
{
return &buffer;
}
const vk::raii::Buffer* operator->() const
{
return &buffer;
}
buffer_allocation() = default;
buffer_allocation(const vk::BufferCreateInfo& buffer_info, const VmaAllocationCreateInfo& alloc_info);
buffer_allocation(const buffer_allocation&) = delete;
buffer_allocation(buffer_allocation&&);
const buffer_allocation& operator=(const buffer_allocation&) = delete;
const buffer_allocation& operator=(buffer_allocation&&);
~buffer_allocation();
void * map();
};
class image_allocation
{
VmaAllocation allocation = nullptr;
vk::raii::Image image = nullptr;
void * data = nullptr;
public:
operator VkImage() const
{
return *image;
}
operator vk::Image() const
{
return *image;
}
operator const vk::raii::Image&() const
{
return image;
}
operator vk::raii::Image&()
{
return image;
}
operator VmaAllocation() const
{
return allocation;
}
vk::raii::Image* operator->()
{
return &image;
}
const vk::raii::Image* operator->() const
{
return &image;
}
image_allocation() = default;
image_allocation(const vk::ImageCreateInfo& image_info, const VmaAllocationCreateInfo& alloc_info);
image_allocation(const image_allocation&) = delete;
image_allocation(image_allocation&&);
const image_allocation& operator=(const image_allocation&) = delete;
const image_allocation& operator=(image_allocation&&);
~image_allocation();
void * map();
};
-33
View File
@@ -1,33 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "buffer.h"
#include "utils/check.h"
vk::buffer::buffer(VkDevice device, const VkBufferCreateInfo & create_info) :
device(device)
{
CHECK_VK(vkCreateBuffer(device, &create_info, nullptr, &id));
}
vk::buffer::~buffer()
{
if (device)
vkDestroyBuffer(device, id, nullptr);
}
-40
View File
@@ -1,40 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "utils/handle.h"
#include <vulkan/vulkan.h>
namespace vk
{
class buffer : public utils::handle<VkBuffer>
{
VkDevice device{};
public:
buffer() = default;
buffer(VkDevice device, const VkBufferCreateInfo & create_info);
buffer(const buffer &) = delete;
buffer(buffer &&) = default;
buffer & operator=(const buffer &) = delete;
buffer & operator=(buffer &&) = default;
~buffer();
};
} // namespace vk
-33
View File
@@ -1,33 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "buffer_view.h"
#include "utils/check.h"
vk::buffer_view::buffer_view(VkDevice device, const VkBufferViewCreateInfo & create_info) :
device(device)
{
CHECK_VK(vkCreateBufferView(device, &create_info, nullptr, &id));
}
vk::buffer_view::~buffer_view()
{
if (device)
vkDestroyBufferView(device, id, nullptr);
}
-40
View File
@@ -1,40 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "utils/handle.h"
#include <vulkan/vulkan.h>
namespace vk
{
class buffer_view : public utils::handle<VkBufferView>
{
VkDevice device{};
public:
buffer_view() = default;
buffer_view(VkDevice device, const VkBufferViewCreateInfo & create_info);
buffer_view(const buffer_view &) = delete;
buffer_view(buffer_view &&) = default;
buffer_view & operator=(const buffer_view &) = delete;
buffer_view & operator=(buffer_view &&) = default;
~buffer_view();
};
} // namespace vk
-84
View File
@@ -1,84 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "command_pool.h"
#include "vk.h"
vk::command_pool::command_pool(VkDevice device, uint32_t queueFamilyIndex) :
device(device), lock(std::make_unique<std::mutex>())
{
VkCommandPoolCreateInfo cmdpool_create_info{};
cmdpool_create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmdpool_create_info.queueFamilyIndex = queueFamilyIndex;
cmdpool_create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
CHECK_VK(vkCreateCommandPool(device, &cmdpool_create_info, nullptr, &id));
}
vk::command_pool::~command_pool()
{
if (device)
vkDestroyCommandPool(device, id, nullptr);
}
std::vector<VkCommandBuffer> vk::command_pool::allocate_command_buffers(uint32_t count, VkCommandBufferLevel level)
{
std::unique_lock _{*lock};
VkCommandBufferAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.commandPool = id;
alloc_info.level = level;
alloc_info.commandBufferCount = count;
std::vector<VkCommandBuffer> command_buffers{count};
CHECK_VK(vkAllocateCommandBuffers(device, &alloc_info, command_buffers.data()));
return command_buffers;
}
VkCommandBuffer vk::command_pool::allocate_command_buffer(VkCommandBufferLevel level)
{
std::unique_lock _{*lock};
VkCommandBufferAllocateInfo alloc_info{};
alloc_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
alloc_info.commandPool = id;
alloc_info.level = level;
alloc_info.commandBufferCount = 1;
VkCommandBuffer command_buffer;
CHECK_VK(vkAllocateCommandBuffers(device, &alloc_info, &command_buffer));
return command_buffer;
}
void vk::command_pool::free_command_buffers(const std::vector<VkCommandBuffer> & command_buffers)
{
std::unique_lock _{*lock};
vkFreeCommandBuffers(device, id, command_buffers.size(), command_buffers.data());
}
void vk::command_pool::free_command_buffer(VkCommandBuffer command_buffer)
{
if (command_buffer)
{
std::unique_lock _{*lock};
vkFreeCommandBuffers(device, id, 1, &command_buffer);
}
}
-51
View File
@@ -1,51 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "utils/handle.h"
#include <memory>
#include <mutex>
#include <vector>
#include <vulkan/vulkan.h>
namespace vk
{
class command_pool : public utils::handle<VkCommandPool>
{
VkDevice device{};
std::unique_ptr<std::mutex> lock;
public:
command_pool() = default;
command_pool(VkDevice device, uint32_t queueFamilyIndex);
command_pool(const command_pool &) = delete;
command_pool(command_pool &&) = default;
command_pool & operator=(const command_pool &) = delete;
command_pool & operator=(command_pool &&) = default;
~command_pool();
std::vector<VkCommandBuffer> allocate_command_buffers(uint32_t count, VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY);
VkCommandBuffer allocate_command_buffer(VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY);
void free_command_buffers(const std::vector<VkCommandBuffer> & command_buffers);
void free_command_buffer(VkCommandBuffer command_buffer);
};
} // namespace vk
-33
View File
@@ -1,33 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "image.h"
#include "utils/check.h"
vk::image::image(VkDevice device, const VkImageCreateInfo & create_info) :
device(device)
{
CHECK_VK(vkCreateImage(device, &create_info, nullptr, &id));
}
vk::image::~image()
{
if (device)
vkDestroyImage(device, id, nullptr);
}
-63
View File
@@ -18,66 +18,3 @@
*/ */
#include "pipeline.h" #include "pipeline.h"
#include "vk.h"
vk::pipeline::pipeline(VkDevice device, vk::pipeline::graphics_info & create_info, const VkPipelineLayout layout) :
device(device)
{
for (VkPipelineShaderStageCreateInfo & i: create_info.shader_stages)
{
i.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
}
create_info.InputAssemblyState.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
create_info.RasterizationState.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
create_info.MultisampleState.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
create_info.DepthStencilState.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
create_info.ColorBlendState.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
VkPipelineVertexInputStateCreateInfo VertexInputState{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.vertexBindingDescriptionCount = (uint32_t)create_info.vertex_input_bindings.size(),
.pVertexBindingDescriptions = create_info.vertex_input_bindings.data(),
.vertexAttributeDescriptionCount = (uint32_t)create_info.vertex_input_attributes.size(),
.pVertexAttributeDescriptions = create_info.vertex_input_attributes.data(),
};
VkPipelineDynamicStateCreateInfo DynamicState{
.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
.dynamicStateCount = (uint32_t)create_info.dynamic_states.size(),
.pDynamicStates = create_info.dynamic_states.data()};
VkPipelineViewportStateCreateInfo ViewportState{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
.viewportCount = (uint32_t)create_info.viewports.size(),
.pViewports = create_info.viewports.data(),
.scissorCount = (uint32_t)create_info.scissors.size(),
.pScissors = create_info.scissors.data(),
};
VkGraphicsPipelineCreateInfo info{};
info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
info.stageCount = create_info.shader_stages.size();
info.pStages = create_info.shader_stages.data();
info.pVertexInputState = &VertexInputState;
info.pInputAssemblyState = &create_info.InputAssemblyState;
info.pViewportState = &ViewportState;
info.pRasterizationState = &create_info.RasterizationState;
info.pMultisampleState = &create_info.MultisampleState;
info.pColorBlendState = &create_info.ColorBlendState;
info.layout = layout;
info.renderPass = create_info.renderPass;
info.subpass = create_info.subpass;
if (DynamicState.dynamicStateCount > 0)
info.pDynamicState = &DynamicState;
CHECK_VK(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, nullptr, &id));
}
vk::pipeline::~pipeline()
{
if (device)
vkDestroyPipeline(device, id, nullptr);
}
+66 -30
View File
@@ -19,42 +19,78 @@
#pragma once #pragma once
#include "pipeline_layout.h" #include <optional>
#include "utils/handle.h"
#include <vector> #include <vector>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan.hpp>
namespace vk namespace vk
{ {
class pipeline : public utils::handle<VkPipeline> class pipeline_builder
{ {
VkDevice device{};
public: public:
struct graphics_info vk::PipelineCreateFlags flags = {};
{
std::vector<VkPipelineShaderStageCreateInfo> shader_stages;
std::vector<VkVertexInputBindingDescription> vertex_input_bindings;
std::vector<VkVertexInputAttributeDescription> vertex_input_attributes;
VkPipelineInputAssemblyStateCreateInfo InputAssemblyState{};
// VkPipelineTessellationStateCreateInfo TessellationState;
std::vector<VkViewport> viewports;
std::vector<VkRect2D> scissors;
VkPipelineRasterizationStateCreateInfo RasterizationState{};
VkPipelineMultisampleStateCreateInfo MultisampleState{};
VkPipelineDepthStencilStateCreateInfo DepthStencilState{};
VkPipelineColorBlendStateCreateInfo ColorBlendState{};
std::vector<VkDynamicState> dynamic_states;
VkRenderPass renderPass{};
uint32_t subpass{};
};
pipeline() = default; std::vector<vk::PipelineShaderStageCreateInfo> Stages;
pipeline(VkDevice device, graphics_info & create_info, VkPipelineLayout layout);
pipeline(const pipeline &) = delete; vk::PipelineVertexInputStateCreateInfo VertexInputState;
pipeline(pipeline &&) = default; std::vector<vk::VertexInputBindingDescription> VertexBindingDescriptions;
pipeline & operator=(const pipeline &) = delete; std::vector<vk::VertexInputAttributeDescription> VertexAttributeDescriptions;
pipeline & operator=(pipeline &&) = default;
~pipeline(); std::optional<vk::PipelineInputAssemblyStateCreateInfo> InputAssemblyState;
std::optional<vk::PipelineTessellationStateCreateInfo> TessellationState;
vk::PipelineViewportStateCreateInfo ViewportState;
std::vector<vk::Viewport> Viewports = {};
std::vector<vk::Rect2D> Scissors = {};
std::optional<vk::PipelineRasterizationStateCreateInfo> RasterizationState;
std::optional<vk::PipelineMultisampleStateCreateInfo> MultisampleState;
std::optional<vk::PipelineDepthStencilStateCreateInfo> DepthStencilState;
vk::PipelineColorBlendStateCreateInfo ColorBlendState;
std::vector<vk::PipelineColorBlendAttachmentState> ColorBlendAttachments;
vk::PipelineDynamicStateCreateInfo DynamicState;
std::vector<vk::DynamicState> DynamicStates;
vk::PipelineLayout layout;
vk::RenderPass renderPass = {};
uint32_t subpass = {};
vk::Pipeline basePipelineHandle;
int32_t basePipelineIndex = {};
operator vk::GraphicsPipelineCreateInfo()
{
VertexInputState.setVertexBindingDescriptions(VertexBindingDescriptions);
VertexInputState.setVertexAttributeDescriptions(VertexAttributeDescriptions);
ViewportState.setViewports(Viewports);
ViewportState.setScissors(Scissors);
ColorBlendState.setAttachments(ColorBlendAttachments);
DynamicState.setDynamicStates(DynamicStates);
return GraphicsPipelineCreateInfo{
.flags = flags,
.stageCount = (uint32_t)Stages.size(),
.pStages = Stages.data(),
.pVertexInputState = &VertexInputState,
.pInputAssemblyState = InputAssemblyState ? &*InputAssemblyState : nullptr,
.pTessellationState = TessellationState ? &*TessellationState : nullptr,
.pViewportState = &ViewportState,
.pRasterizationState = RasterizationState ? &*RasterizationState : nullptr,
.pMultisampleState = MultisampleState ? &*MultisampleState : nullptr,
.pDepthStencilState = DepthStencilState ? &*DepthStencilState : nullptr,
.pColorBlendState = &ColorBlendState,
.pDynamicState = &DynamicState,
.layout = layout,
.renderPass = renderPass,
.subpass = subpass,
.basePipelineHandle = basePipelineHandle,
.basePipelineIndex = basePipelineIndex
};
}
}; };
} // namespace vk } // namespace vk
+5 -13
View File
@@ -19,24 +19,16 @@
#include "shader.h" #include "shader.h"
#include "vk.h" vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector<uint32_t> & spirv)
vk::shader::shader(VkDevice device, const std::vector<uint32_t> & spirv) :
device(device)
{ {
VkShaderModuleCreateInfo create_info{}; vk::ShaderModuleCreateInfo create_info{};
create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
create_info.pCode = data(spirv); create_info.pCode = data(spirv);
create_info.codeSize = spirv.size() * sizeof(uint32_t); create_info.codeSize = spirv.size() * sizeof(uint32_t);
CHECK_VK(vkCreateShaderModule(device, &create_info, nullptr, &id)); return vk::raii::ShaderModule{device, create_info};
} }
vk::shader::shader(VkDevice device, const std::string & name) : vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::string & name)
shader(device, shaders.at(name)) {}
vk::shader::~shader()
{ {
if (device) return load_shader(device, shaders.at(name));
vkDestroyShaderModule(device, id, nullptr);
} }
+3 -18
View File
@@ -19,27 +19,12 @@
#pragma once #pragma once
#include "utils/handle.h"
#include <map> #include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <vulkan/vulkan.h> #include <vulkan/vulkan_raii.hpp>
extern const std::map<std::string, std::vector<uint32_t>> shaders; extern const std::map<std::string, std::vector<uint32_t>> shaders;
namespace vk vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector<uint32_t> & spirv);
{ vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::string & name);
class shader : public utils::handle<VkShaderModule>
{
VkDevice device;
public:
shader(VkDevice device, const std::vector<uint32_t> & spirv);
shader(VkDevice device, const std::string & name);
shader(shader &&) = default;
shader & operator=(shader &&) = default;
shader(const shader &) = delete;
shader operator=(const shader &) = delete;
~shader();
};
} // namespace vk
-8
View File
@@ -21,14 +21,6 @@
#include "magic_enum.hpp" #include "magic_enum.hpp"
#include "utils/check.h" #include "utils/check.h"
#include "vk/buffer.h"
#include "vk/buffer_view.h"
#include "vk/command_pool.h"
#include "vk/device_memory.h"
#include "vk/image.h"
#include "vk/pipeline.h"
#include "vk/renderpass.h"
#include "vk/shader.h"
#include <string> #include <string>
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
+7 -7
View File
@@ -24,15 +24,15 @@
#include <vulkan/vulkan.h> #include <vulkan/vulkan.h>
#include <openxr/openxr_platform.h> #include <openxr/openxr_platform.h>
xr::session::session(xr::instance & inst, xr::system & sys, VkInstance vk_inst, VkPhysicalDevice pdev, VkDevice dev, int queue_family_index) : xr::session::session(xr::instance & inst, xr::system & sys, vk::raii::Instance& vk_inst, vk::raii::PhysicalDevice& pdev, vk::raii::Device& dev, int queue_family_index) :
inst(&inst) inst(&inst)
{ {
XrGraphicsBindingVulkan2KHR vulkan_binding{}; XrGraphicsBindingVulkan2KHR vulkan_binding{};
vulkan_binding.type = XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR; vulkan_binding.type = XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR;
vulkan_binding.instance = vk_inst; vulkan_binding.instance = *vk_inst;
vulkan_binding.physicalDevice = pdev; vulkan_binding.physicalDevice = *pdev;
vulkan_binding.device = dev; vulkan_binding.device = *dev;
vulkan_binding.queueFamilyIndex = queue_family_index; vulkan_binding.queueFamilyIndex = queue_family_index;
vulkan_binding.queueIndex = 0; vulkan_binding.queueIndex = 0;
@@ -75,11 +75,11 @@ xr::space xr::session::create_action_space(XrAction action, const XrPosef & pose
return s; return s;
} }
std::vector<VkFormat> xr::session::get_swapchain_formats() const std::vector<vk::Format> xr::session::get_swapchain_formats() const
{ {
std::vector<VkFormat> formats; std::vector<vk::Format> formats;
for (auto i: details::enumerate<int64_t>(xrEnumerateSwapchainFormats, id)) for (auto i: details::enumerate<int64_t>(xrEnumerateSwapchainFormats, id))
formats.push_back(static_cast<VkFormat>(i)); formats.push_back(static_cast<vk::Format>(i));
return formats; return formats;
} }
+3 -3
View File
@@ -22,7 +22,7 @@
#include "utils/handle.h" #include "utils/handle.h"
#include <string> #include <string>
#include <vector> #include <vector>
#include <vulkan/vulkan.h> #include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
#include "space.h" #include "space.h"
@@ -38,7 +38,7 @@ class session : public utils::handle<XrSession>
public: public:
session() = default; session() = default;
session(instance &, system &, VkInstance, VkPhysicalDevice, VkDevice, int queue_family_index); session(instance &, system &, vk::raii::Instance&, vk::raii::PhysicalDevice&, vk::raii::Device&, int queue_family_index);
session(session &&) = default; session(session &&) = default;
session & operator=(session &&) = default; session & operator=(session &&) = default;
@@ -48,7 +48,7 @@ public:
space create_reference_space(XrReferenceSpaceType ref, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}}); space create_reference_space(XrReferenceSpaceType ref, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}});
space create_action_space(XrAction action, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}}); space create_action_space(XrAction action, const XrPosef & pose = {{0, 0, 0, 1}, {0, 0, 0}});
std::vector<VkFormat> get_swapchain_formats() const; std::vector<vk::Format> get_swapchain_formats() const;
XrFrameState wait_frame(); XrFrameState wait_frame();
void begin_frame(); void begin_frame();
+11 -19
View File
@@ -21,11 +21,9 @@
#include "details/enumerate.h" #include "details/enumerate.h"
#include "error.h" #include "error.h"
#include "session.h" #include "session.h"
#include "vk/vk.h"
#include "xr.h" #include "xr.h"
xr::swapchain::swapchain(xr::session & s, VkDevice device, VkFormat format, uint32_t width, uint32_t height, int sample_count) : xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count)
device(device)
{ {
assert(sample_count == 1); assert(sample_count == 1);
@@ -33,7 +31,7 @@ xr::swapchain::swapchain(xr::session & s, VkDevice device, VkFormat format, uint
create_info.type = XR_TYPE_SWAPCHAIN_CREATE_INFO; create_info.type = XR_TYPE_SWAPCHAIN_CREATE_INFO;
create_info.createFlags = 0; create_info.createFlags = 0;
create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT;
create_info.format = format; create_info.format = static_cast<VkFormat>(format);
create_info.sampleCount = sample_count; create_info.sampleCount = sample_count;
create_info.width = width; create_info.width = width;
create_info.height = height; create_info.height = height;
@@ -56,32 +54,26 @@ xr::swapchain::swapchain(xr::session & s, VkDevice device, VkFormat format, uint
{ {
images_[i].image = array[i].image; images_[i].image = array[i].image;
VkImageViewCreateInfo iv_create_info{}; vk::ImageViewCreateInfo iv_create_info;
iv_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
iv_create_info.image = array[i].image; iv_create_info.image = array[i].image;
iv_create_info.viewType = VkImageViewType::VK_IMAGE_VIEW_TYPE_2D; iv_create_info.viewType = vk::ImageViewType::e2D;
iv_create_info.format = format; iv_create_info.format = format;
iv_create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; iv_create_info.components.r = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; iv_create_info.components.g = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; iv_create_info.components.b = vk::ComponentSwizzle::eIdentity;
iv_create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; iv_create_info.components.a = vk::ComponentSwizzle::eIdentity;
iv_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; iv_create_info.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;
iv_create_info.subresourceRange.baseMipLevel = 0; iv_create_info.subresourceRange.baseMipLevel = 0;
iv_create_info.subresourceRange.levelCount = 1; iv_create_info.subresourceRange.levelCount = 1;
iv_create_info.subresourceRange.baseArrayLayer = 0; iv_create_info.subresourceRange.baseArrayLayer = 0;
iv_create_info.subresourceRange.layerCount = 1; iv_create_info.subresourceRange.layerCount = 1;
CHECK_VK(vkCreateImageView(device, &iv_create_info, nullptr, &images_[i].view));
images_[i].view = vk::raii::ImageView(device, iv_create_info);
} }
} }
xr::swapchain::~swapchain() xr::swapchain::~swapchain()
{ {
for (auto & i: images_)
{
if (i.view)
vkDestroyImageView(device, i.view, nullptr);
}
if (id != XR_NULL_HANDLE) if (id != XR_NULL_HANDLE)
xrDestroySwapchain(id); xrDestroySwapchain(id);
} }
+6 -7
View File
@@ -25,7 +25,7 @@
#include "utils/handle.h" #include "utils/handle.h"
#include <vector> #include <vector>
#include <vulkan/vulkan.h> #include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
#include <openxr/openxr_platform.h> #include <openxr/openxr_platform.h>
@@ -38,22 +38,21 @@ class swapchain : public utils::handle<XrSwapchain>
public: public:
struct image struct image
{ {
VkImage image{}; vk::Image image{};
VkImageView view{}; vk::raii::ImageView view = nullptr;
}; };
private: private:
VkDevice device;
uint32_t width_; uint32_t width_;
uint32_t height_; uint32_t height_;
int sample_count_; int sample_count_;
VkFormat format_; vk::Format format_;
std::vector<image> images_; std::vector<image> images_;
public: public:
swapchain() = default; swapchain() = default;
swapchain(session &, VkDevice device, VkFormat format, uint32_t width, uint32_t height, int sample_count = 1); swapchain(session &, vk::raii::Device& device, vk::Format format, uint32_t width, uint32_t height, int sample_count = 1);
swapchain(swapchain &&) = default; swapchain(swapchain &&) = default;
swapchain(const swapchain &) = delete; swapchain(const swapchain &) = delete;
swapchain & operator=(swapchain &&) = default; swapchain & operator=(swapchain &&) = default;
@@ -80,7 +79,7 @@ public:
{ {
return images_; return images_;
} }
VkFormat format() const vk::Format format() const
{ {
return format_; return format_;
} }
+7 -7
View File
@@ -62,7 +62,7 @@ XrSystemProperties xr::system::properties() const
return prop; return prop;
} }
VkPhysicalDevice xr::system::physical_device(VkInstance vulkan) const vk::raii::PhysicalDevice xr::system::physical_device(vk::raii::Instance& vulkan) const
{ {
auto xrGetVulkanGraphicsDevice2KHR = auto xrGetVulkanGraphicsDevice2KHR =
inst->get_proc<PFN_xrGetVulkanGraphicsDevice2KHR>("xrGetVulkanGraphicsDevice2KHR"); inst->get_proc<PFN_xrGetVulkanGraphicsDevice2KHR>("xrGetVulkanGraphicsDevice2KHR");
@@ -70,23 +70,23 @@ VkPhysicalDevice xr::system::physical_device(VkInstance vulkan) const
XrVulkanGraphicsDeviceGetInfoKHR get_info{}; XrVulkanGraphicsDeviceGetInfoKHR get_info{};
get_info.type = XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR; get_info.type = XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR;
get_info.systemId = id; get_info.systemId = id;
get_info.vulkanInstance = vulkan; get_info.vulkanInstance = *vulkan;
VkPhysicalDevice dev; VkPhysicalDevice dev;
CHECK_XR(xrGetVulkanGraphicsDevice2KHR(*inst, &get_info, &dev)); CHECK_XR(xrGetVulkanGraphicsDevice2KHR(*inst, &get_info, &dev));
return dev; return vk::raii::PhysicalDevice{vulkan, dev};
} }
VkDevice xr::system::create_device(VkPhysicalDevice pdev, VkDeviceCreateInfo & create_info) const vk::raii::Device xr::system::create_device(vk::raii::PhysicalDevice& pdev, vk::DeviceCreateInfo & create_info) const
{ {
XrVulkanDeviceCreateInfoKHR xr_create_info{}; XrVulkanDeviceCreateInfoKHR xr_create_info{};
xr_create_info.type = XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR; xr_create_info.type = XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR;
xr_create_info.pfnGetInstanceProcAddr = vkGetInstanceProcAddr; xr_create_info.pfnGetInstanceProcAddr = vkGetInstanceProcAddr;
xr_create_info.systemId = id; xr_create_info.systemId = id;
xr_create_info.vulkanPhysicalDevice = pdev; xr_create_info.vulkanPhysicalDevice = *pdev;
xr_create_info.vulkanCreateInfo = &create_info; xr_create_info.vulkanCreateInfo = &(VkDeviceCreateInfo&)create_info;
VkDevice dev; VkDevice dev;
VkResult vresult; VkResult vresult;
@@ -95,7 +95,7 @@ VkDevice xr::system::create_device(VkPhysicalDevice pdev, VkDeviceCreateInfo & c
CHECK_XR(xrCreateVulkanDeviceKHR(*inst, &xr_create_info, &dev, &vresult)); CHECK_XR(xrCreateVulkanDeviceKHR(*inst, &xr_create_info, &dev, &vresult));
CHECK_VK(vresult, "xrCreateVulkanDeviceKHR"); CHECK_VK(vresult, "xrCreateVulkanDeviceKHR");
return dev; return vk::raii::Device{pdev, dev};
} }
std::vector<XrViewConfigurationType> xr::system::view_configurations() const std::vector<XrViewConfigurationType> xr::system::view_configurations() const
+3 -3
View File
@@ -25,7 +25,7 @@
#include "xr.h" #include "xr.h"
#include <vector> #include <vector>
#include <vulkan/vulkan.h> #include <vulkan/vulkan_raii.hpp>
#include <openxr/openxr.h> #include <openxr/openxr.h>
#include <openxr/openxr_platform.h> #include <openxr/openxr_platform.h>
@@ -55,8 +55,8 @@ public:
XrSystemProperties properties() const; XrSystemProperties properties() const;
XrGraphicsRequirementsVulkan2KHR graphics_requirements() const; XrGraphicsRequirementsVulkan2KHR graphics_requirements() const;
VkPhysicalDevice physical_device(VkInstance vulkan) const; vk::raii::PhysicalDevice physical_device(vk::raii::Instance& vulkan) const;
VkDevice create_device(VkPhysicalDevice pdev, VkDeviceCreateInfo & create_info) const; vk::raii::Device create_device(vk::raii::PhysicalDevice& pdev, vk::DeviceCreateInfo & create_info) const;
std::vector<XrViewConfigurationType> view_configurations() const; std::vector<XrViewConfigurationType> view_configurations() const;
XrViewConfigurationProperties view_configuration_properties(XrViewConfigurationType) const; XrViewConfigurationProperties view_configuration_properties(XrViewConfigurationType) const;