diff --git a/client/application.cpp b/client/application.cpp index f59f2599..93e4aa9f 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -22,27 +22,22 @@ #include "scene.h" #include "spdlog/common.h" #include "spdlog/spdlog.h" +#include "utils/contains.h" #include "utils/files.h" #include "utils/named_thread.h" +#include "vk/check.h" #include "xr/actionset.h" +#include "xr/check.h" #include "xr/xr.h" #include -#include "utils/contains.h" -#include #include #include -#include #include +#include #include #include #include -#include "vk/check.h" -#include "xr/check.h" -#include -#include -#include #include -#include #include #ifndef NDEBUG @@ -55,13 +50,12 @@ #include "jnipp.h" #else -#include #include "utils/xdg_base_directory.h" +#include #endif using namespace std::chrono_literals; - struct interaction_profile { std::string profile_name; @@ -132,7 +126,7 @@ static std::vector interaction_profiles{ }}, interaction_profile{ "/interaction_profiles/bytedance/pico_neo3_controller", - { "XR_BD_controller_interaction" }, + {"XR_BD_controller_interaction"}, { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -174,7 +168,7 @@ static std::vector interaction_profiles{ }}, interaction_profile{ "/interaction_profiles/bytedance/pico4_controller", - { "XR_BD_controller_interaction" }, + {"XR_BD_controller_interaction"}, { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -214,7 +208,7 @@ static std::vector interaction_profiles{ }}, interaction_profile{ "/interaction_profiles/htc/vive_focus3_controller", - { "XR_HTC_vive_focus3_controller_interaction" }, + {"XR_HTC_vive_focus3_controller_interaction"}, { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -257,7 +251,7 @@ static std::vector interaction_profiles{ static const std::pair action_suffixes[] = { - // clang-format off + // clang-format off // From OpenXR spec 1.0.33, §6.3.2 Input subpaths // Standard components @@ -278,12 +272,12 @@ static const std::pair action_suffixes[] = // Output paths {"/haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, - // clang-format on + // clang-format on }; static XrActionType guess_action_type(const std::string & name) { - for(const auto & [suffix, type]: action_suffixes) + for (const auto & [suffix, type]: action_suffixes) { if (name.ends_with(suffix)) return type; @@ -368,7 +362,7 @@ void application::initialize_vulkan() spdlog::info("Available Vulkan layers:"); [[maybe_unused]] bool validation_layer_found = false; - for(vk::LayerProperties& i: vk_context.enumerateInstanceLayerProperties()) + for (vk::LayerProperties & i: vk_context.enumerateInstanceLayerProperties()) { spdlog::info(" {}", i.layerName); if (!strcmp(i.layerName, "VK_LAYER_KHRONOS_validation")) @@ -392,7 +386,7 @@ void application::initialize_vulkan() bool debug_utils_found = false; #endif spdlog::info("Available Vulkan instance extensions:"); - for(vk::ExtensionProperties& i: vk_context.enumerateInstanceExtensionProperties(nullptr)) + for (vk::ExtensionProperties & i: vk_context.enumerateInstanceExtensionProperties(nullptr)) { spdlog::info(" {} (version {})", i.extensionName, i.specVersion); @@ -431,26 +425,26 @@ void application::initialize_vulkan() #endif vk::ApplicationInfo application_info{ - .pApplicationName = app_info.name.c_str(), - .applicationVersion = (uint32_t)app_info.version, - .pEngineName = engine_name, - .engineVersion = engine_version, - .apiVersion = VK_MAKE_API_VERSION(0, XR_VERSION_MAJOR(vulkan_version), XR_VERSION_MINOR(vulkan_version), 0), + .pApplicationName = app_info.name.c_str(), + .applicationVersion = (uint32_t)app_info.version, + .pEngineName = engine_name, + .engineVersion = engine_version, + .apiVersion = VK_MAKE_API_VERSION(0, XR_VERSION_MAJOR(vulkan_version), XR_VERSION_MINOR(vulkan_version), 0), }; vk::InstanceCreateInfo instance_create_info{ - .pApplicationInfo = &application_info, + .pApplicationInfo = &application_info, }; instance_create_info.setPEnabledLayerNames(layers); instance_create_info.setPEnabledExtensionNames(instance_extensions); XrVulkanInstanceCreateInfoKHR create_info{ - .type = XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR, - .systemId = xr_system_id, - .createFlags = 0, - .pfnGetInstanceProcAddr = vkGetInstanceProcAddr, - .vulkanCreateInfo = &(VkInstanceCreateInfo&)instance_create_info, - .vulkanAllocator = nullptr, + .type = XR_TYPE_VULKAN_INSTANCE_CREATE_INFO_KHR, + .systemId = xr_system_id, + .createFlags = 0, + .pfnGetInstanceProcAddr = vkGetInstanceProcAddr, + .vulkanCreateInfo = &(VkInstanceCreateInfo &)instance_create_info, + .vulkanAllocator = nullptr, }; auto xrCreateVulkanInstanceKHR = @@ -468,10 +462,10 @@ void application::initialize_vulkan() { vk::DebugReportCallbackCreateInfoEXT debug_report_info{ .flags = vk::DebugReportFlagBitsEXT::eInformation | - vk::DebugReportFlagBitsEXT::eWarning| - vk::DebugReportFlagBitsEXT::ePerformanceWarning | - vk::DebugReportFlagBitsEXT::eError | - vk::DebugReportFlagBitsEXT::eDebug, + vk::DebugReportFlagBitsEXT::eWarning | + vk::DebugReportFlagBitsEXT::ePerformanceWarning | + vk::DebugReportFlagBitsEXT::eError | + vk::DebugReportFlagBitsEXT::eDebug, .pfnCallback = vulkan_debug_report_callback, }; debug_report_callback = vk::raii::DebugReportCallbackEXT(vk_instance, debug_report_info); @@ -482,7 +476,7 @@ void application::initialize_vulkan() physical_device_properties = vk_physical_device.getProperties(); spdlog::info("Available Vulkan device extensions:"); - for(vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties()) + for (vk::ExtensionProperties & i: vk_physical_device.enumerateDeviceExtensionProperties()) { spdlog::info(" {}", i.extensionName); } @@ -508,26 +502,26 @@ void application::initialize_vulkan() float queuePriority = 0.0f; vk::DeviceQueueCreateInfo queueCreateInfo{ - .queueFamilyIndex = vk_queue_family_index, - .queueCount = 1, - .pQueuePriorities = &queuePriority + .queueFamilyIndex = vk_queue_family_index, + .queueCount = 1, + .pQueuePriorities = &queuePriority, }; vk::PhysicalDeviceFeatures device_features{ - // .samplerAnisotropy = true, + // .samplerAnisotropy = true, }; 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 - } + vk::DeviceCreateInfo{ + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queueCreateInfo, + .enabledExtensionCount = (uint32_t)device_extensions.size(), + .ppEnabledExtensionNames = device_extensions.data(), + .pEnabledFeatures = &device_features, + }, + vk::PhysicalDeviceSamplerYcbcrConversionFeaturesKHR{ + .samplerYcbcrConversion = VK_TRUE, + }, }; vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get()); @@ -537,21 +531,24 @@ void application::initialize_vulkan() vk::PipelineCacheCreateInfo pipeline_cache_info; std::vector pipeline_cache_bytes; - try { + try + { // TODO Robust pipeline cache serialization // https://zeux.io/2019/07/17/serializing-pipeline-cache/ pipeline_cache_bytes = utils::read_whole_file(cache_path / "pipeline_cache"); pipeline_cache_info.setInitialData(pipeline_cache_bytes); - } catch (...) { + } + catch (...) + { } pipeline_cache = vk::raii::PipelineCache(vk_device, pipeline_cache_info); allocator.emplace(VmaAllocatorCreateInfo{ - .physicalDevice = *vk_physical_device, - .device = *vk_device, - .instance = *vk_instance, + .physicalDevice = *vk_physical_device, + .device = *vk_device, + .instance = *vk_instance, }); } @@ -582,7 +579,7 @@ void application::log_views() static std::string make_xr_name(std::string name) { // Generate a name suitable for a path component (see OpenXR spec §6.2) - for(char& c: name) + for (char & c: name) { if (!isalnum(c) && c != '-' && c != '_' && c != '.') c = '_'; @@ -609,7 +606,7 @@ void application::initialize_actions() // Build the list of all possible input sources, without duplicates, // checking which profiles are supported by the runtime std::vector sources; - for(auto & profile: interaction_profiles) + for (auto & profile: interaction_profiles) { profile.available = utils::contains_all(xr_extensions, profile.required_extensions); @@ -618,7 +615,7 @@ void application::initialize_actions() suggested_bindings.emplace(profile.profile_name, std::vector{}); - for(const std::string& source: profile.input_sources) + for (const std::string & source: profile.input_sources) { if (!utils::contains(sources, source)) sources.push_back(source); @@ -628,7 +625,7 @@ void application::initialize_actions() // For each possible input source, create a XrAction and add it to the suggested binding std::unordered_map actions_by_name; - for(std::string& name: sources) + for (std::string & name: sources) { std::string name_without_slashes = make_xr_name(name); @@ -649,14 +646,14 @@ void application::initialize_actions() } // Build an action set for each scene - for(scene::meta* i: scene::scene_registry) + for (scene::meta * i: scene::scene_registry) { std::string actionset_name = make_xr_name(i->name); i->actionset = xr::actionset(xr_instance, actionset_name, i->name); action_sets.push_back(i->actionset); - for(auto& [action_name, action_type] : i->actions) + for (auto & [action_name, action_type]: i->actions) { XrAction a = i->actionset.create_action(action_type, action_name); i->actions_by_name[action_name] = std::make_pair(a, action_type); @@ -665,23 +662,22 @@ void application::initialize_actions() i->spaces_by_name[action_name] = xr_session.create_action_space(a); } - for(const scene::suggested_binding& j: i->bindings) + for (const scene::suggested_binding & j: i->bindings) { // Skip unsupported profiles if (!suggested_bindings.contains(j.profile_name)) continue; - std::vector& xr_bindings = suggested_bindings[j.profile_name]; + std::vector & xr_bindings = suggested_bindings[j.profile_name]; - for(const scene::action_binding& k: j.paths) + for (const scene::action_binding & k: j.paths) { XrAction a = i->actions_by_name[k.action_name].first; assert(a != XR_NULL_HANDLE); xr_bindings.push_back(XrActionSuggestedBinding{ - .action = a, - .binding = string_to_path(k.input_source) - }); + .action = a, + .binding = string_to_path(k.input_source)}); } } } @@ -693,7 +689,7 @@ void application::initialize_actions() if (!profile.available) continue; - std::vector& xr_bindings = suggested_bindings[profile.profile_name]; + std::vector & xr_bindings = suggested_bindings[profile.profile_name]; for (const auto & name: profile.input_sources) { @@ -704,7 +700,7 @@ void application::initialize_actions() { xr_instance.suggest_bindings(profile.profile_name, xr_bindings); } - catch(...) + catch (...) { // Ignore errors } @@ -730,22 +726,22 @@ void application::initialize() opt_extensions.push_back(XR_FB_PASSTHROUGH_EXTENSION_NAME); opt_extensions.push_back(XR_HTC_PASSTHROUGH_EXTENSION_NAME); - for(const auto& i: interaction_profiles) + for (const auto & i: interaction_profiles) { - for(const auto& j: i.required_extensions) + for (const auto & j: i.required_extensions) { opt_extensions.push_back(j); } } - for(const auto& i: xr::instance::extensions()) + for (const auto & i: xr::instance::extensions()) { if (utils::contains(opt_extensions, i.extensionName)) xr_extensions.push_back(i.extensionName); } std::vector extensions; - for(const auto& i: xr_extensions) + for (const auto & i: xr_extensions) { extensions.push_back(i.c_str()); } @@ -781,7 +777,7 @@ void application::initialize() hand_tracking_supported = hand_tracking_properties.supportsHandTracking; } - switch(xr_system_id.passthrough_supported()) + switch (xr_system_id.passthrough_supported()) { case xr::system::passthrough_type::no_passthrough: spdlog::info(" Passthrough: not supported"); @@ -829,8 +825,6 @@ void application::initialize() interaction_profile_changed(); } - - std::pair application::get_action(const std::string & requested_name) { for (const auto & [action, type, name]: instance().actions) @@ -909,10 +903,10 @@ application::application(application_info info) : if (XR_SUCCEEDED(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", (PFN_xrVoidFunction *)(&initializeLoader)))) { XrLoaderInitInfoAndroidKHR loaderInitInfoAndroid{ - .type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR, - .next = nullptr, - .applicationVM = app_info.native_app->activity->vm, - .applicationContext = app_info.native_app->activity->clazz, + .type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR, + .next = nullptr, + .applicationVM = app_info.native_app->activity->vm, + .applicationContext = app_info.native_app->activity->clazz, }; initializeLoader((const XrLoaderInitInfoBaseHeaderKHR *)&loaderInitInfoAndroid); } @@ -931,7 +925,7 @@ application::application(application_info info) : { initialize(); } - catch (std::exception& e) + catch (std::exception & e) { spdlog::error("Error during initialization: {}", e.what()); cleanup(); @@ -992,7 +986,7 @@ void application::cleanup() scene_stack.clear(); // Empty the meta objects while the OpenXR instance still exists - for(auto i: scene::scene_registry) + for (auto i: scene::scene_registry) { xr::actionset tmp = std::move(i->actionset); i->actions_by_name.clear(); // Not strictly necessary @@ -1044,8 +1038,6 @@ void application::loop() scene->render(framestate.predictedDisplayTime, framestate.shouldRender); last_scene_cpu_time = std::chrono::steady_clock::now() - t1; - - } else { @@ -1104,8 +1096,9 @@ void application::run() #else void application::run() { - struct sigaction act{}; - act.sa_handler = [](int){ + struct sigaction act + {}; + act.sa_handler = [](int) { instance().exit_requested = true; }; sigaction(SIGINT, &act, nullptr); @@ -1142,9 +1135,8 @@ void application::push_scene(std::shared_ptr s) void application::poll_actions() { std::array action_sets{ - instance().xr_actionset, - instance().current_scene()->current_meta.actionset - }; + instance().xr_actionset, + instance().current_scene()->current_meta.actionset}; instance().xr_session.sync_actions(action_sets); } diff --git a/client/application.h b/client/application.h index c94c3367..92db7de1 100644 --- a/client/application.h +++ b/client/application.h @@ -148,7 +148,6 @@ class application : public singleton std::unordered_set debug_report_ignored_objects; std::unordered_map debug_report_object_name; - #ifndef NDEBUG vk::raii::DebugReportCallbackEXT debug_report_callback = nullptr; #endif @@ -164,12 +163,12 @@ public: void set_wifi_locks(bool enabled); - static AAssetManager* asset_manager() + static AAssetManager * asset_manager() { return instance().app_info.native_app->activity->assetManager; } - static android_app* native_app() + static android_app * native_app() { return instance().app_info.native_app; } @@ -222,16 +221,16 @@ public: return {}; glm::vec3 position{ - location.pose.position.x, - location.pose.position.y, - location.pose.position.z, + location.pose.position.x, + location.pose.position.y, + location.pose.position.z, }; glm::quat orientation{ - location.pose.orientation.w, - location.pose.orientation.x, - location.pose.orientation.y, - location.pose.orientation.z, + location.pose.orientation.w, + location.pose.orientation.x, + location.pose.orientation.y, + location.pose.orientation.z, }; return std::make_pair(position, orientation); @@ -309,22 +308,22 @@ public: #endif } - template - static void set_debug_reports_name(const T& object, std::string name) + template + static void set_debug_reports_name(const T & object, std::string name) { -// #ifndef NDEBUG + // #ifndef NDEBUG // if (instance().debug_utils_found) - const vk::DebugUtilsObjectNameInfoEXT name_info { - .objectType = T::objectType, - .objectHandle = (uint64_t)(typename T::NativeType)object, - .pObjectName = name.c_str(), - }; + const vk::DebugUtilsObjectNameInfoEXT name_info{ + .objectType = T::objectType, + .objectHandle = (uint64_t)(typename T::NativeType)object, + .pObjectName = name.c_str(), + }; - instance().vk_device.setDebugUtilsObjectNameEXT(name_info); + instance().vk_device.setDebugUtilsObjectNameEXT(name_info); // 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() @@ -337,47 +336,47 @@ public: return instance().vk_queue_family_index; } - static vk::raii::Queue& get_queue() + static vk::raii::Queue & get_queue() { - return instance().vk_queue; + return instance().vk_queue; } - const std::string& get_server_address() const + const std::string & get_server_address() const { return server_address; } - static vk::raii::PhysicalDevice& get_physical_device() + static vk::raii::PhysicalDevice & get_physical_device() { return instance().vk_physical_device; } - static const vk::PhysicalDeviceProperties& get_physical_device_properties() + static const vk::PhysicalDeviceProperties & get_physical_device_properties() { return instance().physical_device_properties; } - static vk::raii::Device& get_device() + static vk::raii::Device & get_device() { return instance().vk_device; } - static vk::raii::Instance& get_vulkan_instance() + static vk::raii::Instance & get_vulkan_instance() { - return instance().vk_instance; + return instance().vk_instance; } - static vk::raii::PipelineCache& get_pipeline_cache() + static vk::raii::PipelineCache & get_pipeline_cache() { - return instance().pipeline_cache; + return instance().pipeline_cache; } - static const std::filesystem::path& get_config_path() + static const std::filesystem::path & get_config_path() { return instance().config_path; } - static const std::filesystem::path& get_cache_path() + static const std::filesystem::path & get_cache_path() { return instance().cache_path; } @@ -392,17 +391,17 @@ public: return instance().hand_tracking_supported; } - static xr::hand_tracker& get_left_hand() + static xr::hand_tracker & get_left_hand() { return instance().left_hand; } - static xr::hand_tracker& get_right_hand() + static xr::hand_tracker & get_right_hand() { return instance().right_hand; } - static const std::vector& get_xr_extensions() + static const std::vector & get_xr_extensions() { return instance().xr_extensions; } diff --git a/client/asset.cpp b/client/asset.cpp index 7bce1c56..fd94baa4 100644 --- a/client/asset.cpp +++ b/client/asset.cpp @@ -27,7 +27,7 @@ #ifdef __ANDROID__ #include -asset::asset(const std::filesystem::path& path) +asset::asset(const std::filesystem::path & path) { spdlog::debug("Loading Android asset {}", path.string()); android_asset = AAssetManager_open(application::asset_manager(), path.c_str(), AASSET_MODE_BUFFER); @@ -39,7 +39,7 @@ asset::asset(const std::filesystem::path& path) } asset::asset(asset && other) : - android_asset(other.android_asset) + android_asset(other.android_asset) { other.android_asset = nullptr; } @@ -76,7 +76,7 @@ std::filesystem::path asset::asset_root() return root; } -asset::asset(const std::filesystem::path& path) +asset::asset(const std::filesystem::path & path) { assert(path.is_relative()); diff --git a/client/asset.h b/client/asset.h index 4b87e0a0..ed4c7432 100644 --- a/client/asset.h +++ b/client/asset.h @@ -28,7 +28,6 @@ struct AAsset; #endif - class asset { #ifdef __ANDROID__ @@ -41,7 +40,7 @@ class asset public: asset() = default; - asset(const std::filesystem::path& path); + asset(const std::filesystem::path & path); #ifdef __ANDROID__ asset(asset && other); @@ -72,6 +71,6 @@ public: operator std::string() const { - return std::string(reinterpret_cast(data()), size()); + return std::string(reinterpret_cast(data()), size()); } }; diff --git a/client/audio/android/audio.cpp b/client/audio/android/audio.cpp index 8880e13b..acb4e885 100644 --- a/client/audio/android/audio.cpp +++ b/client/audio/android/audio.cpp @@ -23,14 +23,6 @@ #include "spdlog/spdlog.h" #include -#include -#include -#include -#include -#include -#include -#include -#include void wivrn::android::audio::exit() { @@ -96,7 +88,7 @@ int32_t wivrn::android::audio::microphone_data_cb(AAudioStream * stream, void * if (self->exiting) { - self->microphone_stop_ack= true; + self->microphone_stop_ack = true; self->microphone_stop_ack.notify_all(); return AAUDIO_CALLBACK_RESULT_STOP; } @@ -119,9 +111,7 @@ wivrn::android::audio::audio(const xrt::drivers::wivrn::to_headset::audio_stream AAudioStreamBuilder * builder; aaudio_result_t result = AAudio_createStreamBuilder(&builder); if (result != AAUDIO_OK) - { throw std::runtime_error(std::string("Cannot create stream builder: ") + AAudio_convertResultToText(result)); - } if (desc.microphone) { @@ -182,9 +172,7 @@ wivrn::android::audio::~audio() for (auto stream: {speaker, microphone}) { if (stream) - { AAudioStream_close(stream); - } } } diff --git a/client/audio/android/audio.h b/client/audio/android/audio.h index da2e7c0d..fd6efbdd 100644 --- a/client/audio/android/audio.h +++ b/client/audio/android/audio.h @@ -35,8 +35,8 @@ namespace wivrn::android { class audio { - static int32_t speaker_data_cb(AAudioStreamStruct*, void*, void*, int32_t); - static int32_t microphone_data_cb(AAudioStreamStruct*, void*, void*, int32_t); + static int32_t speaker_data_cb(AAudioStreamStruct *, void *, void *, int32_t); + static int32_t microphone_data_cb(AAudioStreamStruct *, void *, void *, int32_t); utils::ring_buffer output_buffer; @@ -52,6 +52,7 @@ class audio std::atomic exiting = false; void exit(); + public: audio(const audio &) = delete; audio & operator=(const audio &) = delete; diff --git a/client/audio/audio.h b/client/audio/audio.h index 3b0a0c81..a6476e16 100644 --- a/client/audio/audio.h +++ b/client/audio/audio.h @@ -19,7 +19,9 @@ #pragma once +#include "wivrn_client.h" #include "wivrn_packets.h" +#include "xr/instance.h" #ifdef __ANDROID__ #include "android/audio.h" @@ -29,15 +31,14 @@ using audio = ::wivrn::android::audio; class audio { public: - - audio(const audio&) = delete; - audio& operator=(const audio&) = delete; + audio(const audio &) = delete; + audio & operator=(const audio &) = delete; audio(const xrt::drivers::wivrn::to_headset::audio_stream_description &, wivrn_session &, xr::instance &) {} ~audio() = default; void operator()(xrt::drivers::wivrn::audio_data &&) {} - static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet& info) {} + static void get_audio_description(xrt::drivers::wivrn::from_headset::headset_info_packet & info) {} }; #endif diff --git a/client/decoder/android/android_decoder.cpp b/client/decoder/android/android_decoder.cpp index 46e5188c..707b6234 100644 --- a/client/decoder/android/android_decoder.cpp +++ b/client/decoder/android/android_decoder.cpp @@ -20,12 +20,10 @@ #include "android_decoder.h" #include "application.h" #include "scenes/stream.h" -#include "vk/shader.h" -#include "vk/pipeline.h" +#include "utils/named_thread.h" #include #include #include -#include #include #include #include @@ -218,8 +216,8 @@ void decoder::push_nals(std::span> data, int64_t timest } decoder::decoder( - vk::raii::Device& device, - vk::raii::PhysicalDevice& physical_device, + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, float fps, uint8_t stream_index, @@ -227,10 +225,16 @@ decoder::decoder( shard_accumulator * accumulator) : description(description), fps(fps), device(device), weak_scene(weak_scene), accumulator(accumulator) { - spdlog::info("hbm_mutex.native_handle() = {}", (void*)hbm_mutex.native_handle()); + spdlog::info("hbm_mutex.native_handle() = {}", (void *)hbm_mutex.native_handle()); AImageReader * ir; - check(AImageReader_newWithUsage(description.width, description.height, AIMAGE_FORMAT_PRIVATE, AHARDWAREBUFFER_USAGE_CPU_READ_NEVER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, 5 /* maxImages */, &ir), + check(AImageReader_newWithUsage( + description.width, + description.height, + AIMAGE_FORMAT_PRIVATE, + AHARDWAREBUFFER_USAGE_CPU_READ_NEVER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, + 5 /* maxImages */, + &ir), "AImageReader_newWithUsage"); image_reader.reset(ir); @@ -241,28 +245,30 @@ decoder::decoder( application::get_vulkan_proc( "vkGetAndroidHardwareBufferPropertiesANDROID"); - output_releaser = utils::named_thread("decoder-" + std::to_string(stream_index), [this]() { - while (true) - { - try - { - auto index = output_buffers.pop(); - auto status = AMediaCodec_releaseOutputBuffer(media_codec.get(), index, true); - // will trigger on_image_available through ImageReader - if (status != AMEDIA_OK) - spdlog::error("AMediaCodec_releaseOutputBuffer: MediaCodec error {}", - (int)status); - } - catch (const utils::sync_queue_closed & e) - { - return; - } - catch (const std::exception & e) - { - spdlog::error("error in output releaser thread: {}", e.what()); - } - } - }); + output_releaser = utils::named_thread( + "decoder-" + std::to_string(stream_index), + [this]() { + while (true) + { + try + { + auto index = output_buffers.pop(); + auto status = AMediaCodec_releaseOutputBuffer(media_codec.get(), index, true); + // will trigger on_image_available through ImageReader + if (status != AMEDIA_OK) + spdlog::error("AMediaCodec_releaseOutputBuffer: MediaCodec error {}", + (int)status); + } + catch (const utils::sync_queue_closed & e) + { + return; + } + catch (const std::exception & e) + { + spdlog::error("error in output releaser thread: {}", e.what()); + } + } + }); } decoder::~decoder() @@ -281,7 +287,7 @@ void decoder::push_data(std::span> data, uint64_t frame if (!media_codec) { std::vector contiguous_data; - for (const auto& d: data) + for (const auto & d: data) contiguous_data.insert(contiguous_data.end(), d.begin(), d.end()); auto [csd, not_csd] = filter_csd(contiguous_data, description.codec); if (csd.empty()) @@ -335,19 +341,16 @@ void decoder::frame_completed(xrt::drivers::wivrn::from_headset::feedback & feed if (not media_codec) { // If media_codec is not initialized, frame processing ends here - auto scene = weak_scene.lock(); - if (scene) - { + if (auto scene = weak_scene.lock()) scene->send_feedback(feedback); - } } // nothing required for decoder, mediacodec will callback when done feedback.sent_to_decoder = application::now(); frame_infos.push(frame_info{ - .feedback = feedback, - .timing_info = timing_info, - .view_info = view_info, + .feedback = feedback, + .timing_info = timing_info, + .view_info = view_info, }); } @@ -394,14 +397,14 @@ void decoder::on_image_available(AImageReader * reader) auto vk_data = map_hardware_buffer(image); auto handle = std::make_shared( - info->feedback, - info->timing_info, - info->view_info, - vk_data->image_view, - *vk_data->vimage, - &vk_data->layout, - vk_data, - image); + info->feedback, + info->timing_info, + info->view_info, + vk_data->image_view, + *vk_data->vimage, + &vk_data->layout, + vk_data, + image); if (auto scene = weak_scene.lock()) scene->push_blit_handle(accumulator, std::move(handle)); @@ -413,7 +416,7 @@ void decoder::on_image_available(AImageReader * reader) } } -void decoder::create_sampler(const AHardwareBuffer_Desc& buffer_desc, vk::AndroidHardwareBufferFormatPropertiesANDROID & ahb_format) +void decoder::create_sampler(const AHardwareBuffer_Desc & buffer_desc, vk::AndroidHardwareBufferFormatPropertiesANDROID & ahb_format) { assert(ahb_format.externalFormat != 0); spdlog::info("AndroidHardwareBufferProperties"); @@ -421,10 +424,10 @@ void decoder::create_sampler(const AHardwareBuffer_Desc& buffer_desc, vk::Androi spdlog::info(" External format: {:#x}", ahb_format.externalFormat); spdlog::info(" Format features: {}", vk::to_string(ahb_format.formatFeatures)); spdlog::info(" samplerYcbcrConversionComponents: ({}, {}, {}, {})", - vk::to_string(ahb_format.samplerYcbcrConversionComponents.r), - vk::to_string(ahb_format.samplerYcbcrConversionComponents.g), - vk::to_string(ahb_format.samplerYcbcrConversionComponents.b), - vk::to_string(ahb_format.samplerYcbcrConversionComponents.a)); + vk::to_string(ahb_format.samplerYcbcrConversionComponents.r), + vk::to_string(ahb_format.samplerYcbcrConversionComponents.g), + vk::to_string(ahb_format.samplerYcbcrConversionComponents.b), + vk::to_string(ahb_format.samplerYcbcrConversionComponents.a)); spdlog::info(" Suggested YCbCr model: {}", vk::to_string(ahb_format.suggestedYcbcrModel)); spdlog::info(" Suggested YCbCr range: {}", vk::to_string(ahb_format.suggestedYcbcrRange)); spdlog::info(" Suggested X chroma offset: {}", vk::to_string(ahb_format.suggestedXChromaOffset)); @@ -437,20 +440,19 @@ void decoder::create_sampler(const AHardwareBuffer_Desc& buffer_desc, vk::Androi yuv_filter = vk::Filter::eNearest; // Create VkSamplerYcbcrConversion - vk::StructureChain ycbcr_create_info - { - vk::SamplerYcbcrConversionCreateInfo{ - .format = vk::Format::eUndefined, - .ycbcrModel = ahb_format.suggestedYcbcrModel, - .ycbcrRange = ahb_format.suggestedYcbcrRange, - .components = ahb_format.samplerYcbcrConversionComponents, - .xChromaOffset = ahb_format.suggestedXChromaOffset, - .yChromaOffset = ahb_format.suggestedYChromaOffset, - .chromaFilter = yuv_filter, - }, - vk::ExternalFormatANDROID{ - .externalFormat = ahb_format.externalFormat, - }, + vk::StructureChain ycbcr_create_info{ + vk::SamplerYcbcrConversionCreateInfo{ + .format = vk::Format::eUndefined, + .ycbcrModel = ahb_format.suggestedYcbcrModel, + .ycbcrRange = ahb_format.suggestedYcbcrRange, + .components = ahb_format.samplerYcbcrConversionComponents, + .xChromaOffset = ahb_format.suggestedXChromaOffset, + .yChromaOffset = ahb_format.suggestedYChromaOffset, + .chromaFilter = yuv_filter, + }, + vk::ExternalFormatANDROID{ + .externalFormat = ahb_format.externalFormat, + }, }; // suggested values from decoder don't actually read the metadata, so it's garbage @@ -464,29 +466,28 @@ void decoder::create_sampler(const AHardwareBuffer_Desc& buffer_desc, vk::Androi // Create VkSampler vk::StructureChain sampler_info{ - vk::SamplerCreateInfo{ - .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, - } + vk::SamplerCreateInfo{ + .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, + }, }; - ycbcr_sampler = vk::raii::Sampler(device, sampler_info.get()); } @@ -516,65 +517,63 @@ std::shared_ptr decoder::map_hardware_buffer(AI return it->second; vk::StructureChain img_info{ - 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 - } + 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, + }, }; vk::raii::Image vimage(device, img_info.get()); assert(properties.memoryTypeBits != 0); vk::StructureChain mem_info{ - vk::MemoryAllocateInfo{ - .allocationSize = properties.allocationSize, - .memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1) - }, - vk::MemoryDedicatedAllocateInfo{ - .image = *vimage - }, - vk::ImportAndroidHardwareBufferInfoANDROID{ - .buffer = hardware_buffer - } + vk::MemoryAllocateInfo{ + .allocationSize = properties.allocationSize, + .memoryTypeIndex = (uint32_t)(ffs(properties.memoryTypeBits) - 1), + }, + vk::MemoryDedicatedAllocateInfo{ + .image = *vimage, + }, + vk::ImportAndroidHardwareBufferInfoANDROID{ + .buffer = hardware_buffer, + }, }; - 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 = *ycbcr_conversion - } + 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 = *ycbcr_conversion, + }, }; application::ignore_debug_reports_for(*vimage); diff --git a/client/decoder/android/android_decoder.h b/client/decoder/android/android_decoder.h index 7e02b57b..63ecb086 100644 --- a/client/decoder/android/android_decoder.h +++ b/client/decoder/android/android_decoder.h @@ -19,16 +19,12 @@ #pragma once -#include "utils/named_thread.h" #include "utils/sync_queue.h" #include "wivrn_packets.h" #include -#include #include -#include #include #include -#include #include #include @@ -68,7 +64,7 @@ public: xrt::drivers::wivrn::from_headset::feedback feedback; xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t timing_info; xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info; - vk::raii::ImageView& image_view; + vk::raii::ImageView & image_view; vk::Image image = nullptr; vk::ImageLayout * current_layout = nullptr; @@ -83,7 +79,7 @@ private: xrt::drivers::wivrn::to_headset::video_stream_description::item description; float fps; - vk::raii::Device& device; + vk::raii::Device & device; vk::AndroidHardwareBufferFormatPropertiesANDROID ahb_format; vk::raii::SamplerYcbcrConversion ycbcr_conversion = nullptr; @@ -124,12 +120,12 @@ private: std::unordered_map> hardware_buffer_map; vk::raii::RenderPass renderpass = nullptr; - void create_sampler(const AHardwareBuffer_Desc& buffer_desc, vk::AndroidHardwareBufferFormatPropertiesANDROID & ahb_format); + void create_sampler(const AHardwareBuffer_Desc & buffer_desc, vk::AndroidHardwareBufferFormatPropertiesANDROID & ahb_format); std::shared_ptr map_hardware_buffer(AImage *); public: - decoder(vk::raii::Device& device, - vk::raii::PhysicalDevice& physical_device, + decoder(vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, float fps, uint8_t stream_index, @@ -142,7 +138,10 @@ public: void push_data(std::span> data, uint64_t frame_index, bool partial); - void frame_completed(xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t & timing_info, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); + void frame_completed( + xrt::drivers::wivrn::from_headset::feedback & feedback, + const xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t & timing_info, + const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); const auto & desc() const { diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.cpp b/client/decoder/ffmpeg/ffmpeg_decoder.cpp index 04eb9bbb..dbd4634f 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.cpp +++ b/client/decoder/ffmpeg/ffmpeg_decoder.cpp @@ -69,8 +69,8 @@ decoder::blit_handle::~blit_handle() } decoder::decoder( - vk::raii::Device& device, - vk::raii::PhysicalDevice& physical_device, + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, float fps, uint8_t stream_index, @@ -85,24 +85,23 @@ decoder::decoder( free_images[i] = i; vk::ImageCreateInfo image_info{ - .imageType = vk::ImageType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .extent = { - .width = description.width, - .height = description.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e1, - .tiling = vk::ImageTiling::eLinear, - .usage = vk::ImageUsageFlagBits::eSampled, - .initialLayout = vk::ImageLayout::eUndefined, + .imageType = vk::ImageType::e2D, + .format = vk::Format::eA8B8G8R8SrgbPack32, + .extent = { + .width = description.width, + .height = description.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eLinear, + .usage = vk::ImageUsageFlagBits::eSampled, + .initialLayout = vk::ImageLayout::eUndefined, }; VmaAllocationCreateInfo alloc_info{ - .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT - }; + .requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT}; decoded_images[i].image = image_allocation(device, image_info, alloc_info); @@ -114,18 +113,20 @@ decoder::decoder( decoded_images[i].layout = decoded_images[i].image->getSubresourceLayout(resource); - decoded_images[i].image_view = vk::raii::ImageView(device, { - .image = (vk::Image)decoded_images[i].image, - .viewType = vk::ImageViewType::e2D, - .format = image_info.format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } - }); + decoded_images[i].image_view = vk::raii::ImageView( + device, + { + .image = (vk::Image)decoded_images[i].image, + .viewType = vk::ImageViewType::e2D, + .format = image_info.format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); decoded_images[i].current_layout = vk::ImageLayout::eUndefined; } @@ -142,21 +143,23 @@ decoder::decoder( if (ret < 0) throw std::runtime_error{"avcodec_open2 failed"}; - rgb_sampler = vk::raii::Sampler(device, { - .flags = {}, - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eNearest, - .addressModeU = vk::SamplerAddressMode::eClampToEdge, - .addressModeV = vk::SamplerAddressMode::eClampToEdge, - .addressModeW = vk::SamplerAddressMode::eClampToEdge, - .unnormalizedCoordinates = false, - }); + rgb_sampler = vk::raii::Sampler( + device, + { + .flags = {}, + .magFilter = vk::Filter::eLinear, + .minFilter = vk::Filter::eLinear, + .mipmapMode = vk::SamplerMipmapMode::eNearest, + .addressModeU = vk::SamplerAddressMode::eClampToEdge, + .addressModeV = vk::SamplerAddressMode::eClampToEdge, + .addressModeW = vk::SamplerAddressMode::eClampToEdge, + .unnormalizedCoordinates = false, + }); } void decoder::push_data(std::span> data, uint64_t frame_index, bool partial) { - for (const auto& d: data) + for (const auto & d: data) packet.insert(packet.end(), d.begin(), d.end()); this->frame_index = frame_index; } @@ -217,15 +220,14 @@ void decoder::frame_completed(const xrt::drivers::wivrn::from_headset::feedback throw std::runtime_error{"sws_scale failed"}; auto handle = std::make_shared( - feedback, - timing_info, - view_info, - decoded_images[index].image_view, - (vk::Image)decoded_images[index].image, - &decoded_images[index].current_layout, - index, - this - ); + feedback, + timing_info, + view_info, + decoded_images[index].image_view, + (vk::Image)decoded_images[index].image, + &decoded_images[index].current_layout, + index, + this); if (auto scene = weak_scene.lock()) scene->push_blit_handle(accumulator, std::move(handle)); diff --git a/client/decoder/ffmpeg/ffmpeg_decoder.h b/client/decoder/ffmpeg/ffmpeg_decoder.h index d03c92c3..a9d90242 100644 --- a/client/decoder/ffmpeg/ffmpeg_decoder.h +++ b/client/decoder/ffmpeg/ffmpeg_decoder.h @@ -19,15 +19,13 @@ #pragma once +#include "vk/allocation.h" #include "wivrn_packets.h" -#include #include #include #include -#include #include #include -#include "vk/allocation.h" class shard_accumulator; @@ -53,7 +51,7 @@ public: xrt::drivers::wivrn::from_headset::feedback feedback; xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t timing_info; xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t view_info; - vk::raii::ImageView& image_view; + vk::raii::ImageView & image_view; vk::Image image = nullptr; vk::ImageLayout * current_layout = nullptr; @@ -74,7 +72,7 @@ private: vk::ImageLayout current_layout = vk::ImageLayout::eUndefined; }; - vk::raii::Device& device; + vk::raii::Device & device; vk::raii::Sampler rgb_sampler = nullptr; std::array decoded_images; @@ -93,8 +91,8 @@ private: std::mutex mutex; public: - decoder(vk::raii::Device& device, - vk::raii::PhysicalDevice& physical_device, + decoder(vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, float fps, uint8_t stream_index, @@ -106,7 +104,10 @@ public: void push_data(std::span> data, uint64_t frame_index, bool partial); - void frame_completed(const xrt::drivers::wivrn::from_headset::feedback & feedback, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t & timing_info, const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); + void frame_completed( + const xrt::drivers::wivrn::from_headset::feedback & feedback, + const xrt::drivers::wivrn::to_headset::video_stream_data_shard::timing_info_t & timing_info, + const xrt::drivers::wivrn::to_headset::video_stream_data_shard::view_info_t & view_info); const auto & desc() const { diff --git a/client/decoder/shard_accumulator.cpp b/client/decoder/shard_accumulator.cpp index 6621fc76..240c80c3 100644 --- a/client/decoder/shard_accumulator.cpp +++ b/client/decoder/shard_accumulator.cpp @@ -21,7 +21,6 @@ #include "application.h" #include "scenes/stream.h" #include "spdlog/spdlog.h" -#include "wivrn_serialization.h" using namespace xrt::drivers::wivrn::to_headset; using shard_set = shard_accumulator::shard_set; @@ -106,7 +105,7 @@ void shard_accumulator::advance() next.reset(current.frame_index() + 1); } -void shard_accumulator::push_shard(video_stream_data_shard&& shard) +void shard_accumulator::push_shard(video_stream_data_shard && shard) { assert(current.frame_index() + 1 == next.frame_index()); diff --git a/client/decoder/shard_accumulator.h b/client/decoder/shard_accumulator.h index c9ca323f..aa5c8091 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -19,7 +19,6 @@ #pragma once -#include "xr/instance.h" #include #include @@ -72,8 +71,8 @@ private: public: explicit shard_accumulator( - vk::raii::Device& device, - vk::raii::PhysicalDevice& physical_device, + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, const xrt::drivers::wivrn::to_headset::video_stream_description::item & description, float fps, std::weak_ptr scene, @@ -86,7 +85,7 @@ public: next.reset(1); } - void push_shard(xrt::drivers::wivrn::to_headset::video_stream_data_shard&&); + void push_shard(xrt::drivers::wivrn::to_headset::video_stream_data_shard &&); auto & desc() const { diff --git a/client/hardware.cpp b/client/hardware.cpp index f91600a0..67118eae 100644 --- a/client/hardware.cpp +++ b/client/hardware.cpp @@ -54,7 +54,6 @@ model guess_model() spdlog::info(" ro.product.manufacturer = \"{}\":", manufacturer); spdlog::info(" ro.product.model = \"{}\":", model); - if (device == "monterey") return model::oculus_quest; if (device == "hollywood") diff --git a/client/jnipp.h b/client/jnipp.h index 8d0090ea..6416388c 100644 --- a/client/jnipp.h +++ b/client/jnipp.h @@ -303,7 +303,7 @@ struct array return self.get(); } - array(T& element) + array(T & element) { auto & env = jni_thread::env(); self.reset(env.NewObjectArray(1, element.klass(), element)); diff --git a/client/main.cpp b/client/main.cpp index 8c3d2204..ac9a2302 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -23,9 +23,9 @@ #include "spdlog/spdlog.h" #include -#include -#include #include +#include +#include #ifdef __ANDROID__ #include "spdlog/sinks/android_sink.h" @@ -63,11 +63,14 @@ void real_main() if (colon == std::string::npos) { port = xrt::drivers::wivrn::default_port; - } else { + } + else + { port = std::stoi(server_address.substr(colon + 1)); server_address = server_address.substr(0, colon); } - struct addrinfo hint{ + struct addrinfo hint + { .ai_flags = AI_ADDRCONFIG, .ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM, @@ -77,25 +80,26 @@ void real_main() { throw std::runtime_error("Unable to resolve address for " + server_address + ":" + gai_strerror(err)); } - for (addrinfo *addr = addresses ; addr and not session; addr = addr->ai_next) + for (addrinfo * addr = addresses; addr and not session; addr = addr->ai_next) { - try { + try + { char buf[100]; switch (addr->ai_family) { case AF_INET: - inet_ntop(addr->ai_family, &((sockaddr_in*)addr->ai_addr)->sin_addr, buf, sizeof(buf)); + inet_ntop(addr->ai_family, &((sockaddr_in *)addr->ai_addr)->sin_addr, buf, sizeof(buf)); spdlog::info("Trying to connect to {} port {}", buf, port); - session = std::make_unique(((sockaddr_in*)addr->ai_addr)->sin_addr, port); + session = std::make_unique(((sockaddr_in *)addr->ai_addr)->sin_addr, port); break; case AF_INET6: - inet_ntop(addr->ai_family, &((sockaddr_in6*)addr->ai_addr)->sin6_addr, buf, sizeof(buf)); + inet_ntop(addr->ai_family, &((sockaddr_in6 *)addr->ai_addr)->sin6_addr, buf, sizeof(buf)); spdlog::info("Trying to connect to {} port {}", buf, port); - session = std::make_unique(((sockaddr_in6*)addr->ai_addr)->sin6_addr, port); + session = std::make_unique(((sockaddr_in6 *)addr->ai_addr)->sin6_addr, port); break; } } - catch(std::exception& e) + catch (std::exception & e) { spdlog::warn("Cannot connect to {}: {}", server_address, e.what()); } diff --git a/client/render/gpu_buffer.h b/client/render/gpu_buffer.h index a536dba4..7f03c03e 100644 --- a/client/render/gpu_buffer.h +++ b/client/render/gpu_buffer.h @@ -18,13 +18,13 @@ #pragma once +#include "application.h" +#include "utils/alignment.h" +#include "vk/allocation.h" +#include +#include #include #include -#include -#include -#include "application.h" -#include "vk/allocation.h" -#include "utils/alignment.h" class gpu_buffer { @@ -125,8 +125,7 @@ public: VmaAllocationCreateInfo{ .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, .usage = VMA_MEMORY_USAGE_AUTO}, - "gpu_buffer::copy_to_gpu" - }; + "gpu_buffer::copy_to_gpu"}; memcpy(gpu_buffer.map(), bytes.data(), bytes.size()); gpu_buffer.unmap(); diff --git a/client/render/growable_descriptor_pool.cpp b/client/render/growable_descriptor_pool.cpp index 8a68a597..2cccd9d5 100644 --- a/client/render/growable_descriptor_pool.cpp +++ b/client/render/growable_descriptor_pool.cpp @@ -18,18 +18,18 @@ #include "growable_descriptor_pool.h" -#include #include +#include struct descriptor_set { - growable_descriptor_pool& growable_pool; + growable_descriptor_pool & growable_pool; vk::DescriptorPool pool; vk::raii::DescriptorSet ds; ~descriptor_set() { - for(auto& i: growable_pool.pools) + for (auto & i: growable_pool.pools) { if (*i.descriptor_pool == pool) { @@ -40,25 +40,31 @@ struct descriptor_set } }; -growable_descriptor_pool::growable_descriptor_pool(vk::raii::Device & device, vk::raii::DescriptorSetLayout& layout, std::span bindings, int descriptorsets_per_pool) : - device(device), layout_(nullptr), descriptorsets_per_pool(descriptorsets_per_pool) +growable_descriptor_pool::growable_descriptor_pool( + vk::raii::Device & device, + vk::raii::DescriptorSetLayout & layout, + std::span bindings, + int descriptorsets_per_pool) : + device(device), + layout_(nullptr), + descriptorsets_per_pool(descriptorsets_per_pool) { if (descriptorsets_per_pool <= 0) throw std::invalid_argument("descriptorsets_per_pool"); - for(vk::DescriptorSetLayoutBinding binding: bindings) + for (vk::DescriptorSetLayoutBinding binding: bindings) { - if (auto it = std::find_if(size.begin(), size.end(), [&binding](vk::DescriptorPoolSize& x){return x.type == binding.descriptorType;}); it != size.end()) - { - it->descriptorCount += binding.descriptorCount * descriptorsets_per_pool; - } - else if (binding.descriptorCount > 0) - { - size.push_back(vk::DescriptorPoolSize{ - .type = binding.descriptorType, - .descriptorCount = binding.descriptorCount * descriptorsets_per_pool, - }); - } + if (auto it = std::find_if(size.begin(), size.end(), [&binding](vk::DescriptorPoolSize & x) { return x.type == binding.descriptorType; }); it != size.end()) + { + it->descriptorCount += binding.descriptorCount * descriptorsets_per_pool; + } + else if (binding.descriptorCount > 0) + { + size.push_back(vk::DescriptorPoolSize{ + .type = binding.descriptorType, + .descriptorCount = binding.descriptorCount * descriptorsets_per_pool, + }); + } } layout_ = *layout; @@ -91,8 +97,8 @@ std::shared_ptr growable_descriptor_pool::allocate() pool_info.setPoolSizes(size); pools.push_back(pool{ - .free_count = descriptorsets_per_pool - 1, - .descriptor_pool = vk::raii::DescriptorPool(device, pool_info), + .free_count = descriptorsets_per_pool - 1, + .descriptor_pool = vk::raii::DescriptorPool(device, pool_info), }); alloc_info.descriptorPool = *pools.back().descriptor_pool; diff --git a/client/render/growable_descriptor_pool.h b/client/render/growable_descriptor_pool.h index be2c8598..56a93412 100644 --- a/client/render/growable_descriptor_pool.h +++ b/client/render/growable_descriptor_pool.h @@ -18,8 +18,8 @@ #pragma once -#include #include +#include #include class growable_descriptor_pool @@ -28,8 +28,8 @@ class growable_descriptor_pool struct pool { - int free_count; - vk::raii::DescriptorPool descriptor_pool; + int free_count; + vk::raii::DescriptorPool descriptor_pool; }; vk::raii::Device & device; @@ -40,7 +40,7 @@ class growable_descriptor_pool std::vector pools; public: - growable_descriptor_pool(vk::raii::Device & device, vk::raii::DescriptorSetLayout& layout, std::span bindings, int descriptorsets_per_pool = 100); + growable_descriptor_pool(vk::raii::Device & device, vk::raii::DescriptorSetLayout & layout, std::span bindings, int descriptorsets_per_pool = 100); std::shared_ptr allocate(); }; diff --git a/client/render/image_loader.cpp b/client/render/image_loader.cpp index ceb0069e..d43f370b 100644 --- a/client/render/image_loader.cpp +++ b/client/render/image_loader.cpp @@ -20,13 +20,12 @@ #include "image_loader.h" #include +#include #include #include #include #include -#include #include -#include #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_JPEG @@ -42,28 +41,28 @@ using stbi_ptr = std::unique_ptr constexpr vk::Format formats[4] = {vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined, vk::Format::eUndefined}; @@ -156,10 +155,10 @@ int bytes_per_pixel(vk::Format format) } } // namespace -image_loader::image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, vk::raii::Queue& queue, vk::raii::CommandPool & cb_pool) : - device(device), - queue(queue), - cb_pool(cb_pool) +image_loader::image_loader(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool) : + device(device), + queue(queue), + cb_pool(cb_pool) { vdi = ktxVulkanDeviceInfo_Create(*physical_device, *device, *queue, *cb_pool, nullptr); } @@ -173,10 +172,10 @@ image_loader::~image_loader() void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format) { auto cb = std::move(device.allocateCommandBuffers({ - .commandPool = *cb_pool, - .level = vk::CommandBufferLevel::ePrimary, - .commandBufferCount = 1, - })[0]); + .commandPool = *cb_pool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = 1, + })[0]); cb.begin(vk::CommandBufferBeginInfo{.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); @@ -211,7 +210,7 @@ void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::For // Allocate image auto r = std::make_shared(); r->allocation = image_allocation{ - device, + device, vk::ImageCreateInfo{ .imageType = vk::ImageType::e2D, .format = format, @@ -225,40 +224,51 @@ void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::For VmaAllocationCreateInfo{ .flags = 0, .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, - }, "image_loader::do_load"}; + }, + "image_loader::do_load"}; r->image = (vk::Image)r->allocation; // Transition all mipmap levels layout to eTransferDstOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eNone, - .dstAccessMask = vk::AccessFlagBits::eTransferWrite, - .oldLayout = vk::ImageLayout::eUndefined, - .newLayout = vk::ImageLayout::eTransferDstOptimal, - .image = r->image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = num_mipmaps, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); + cb.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eTransfer, + vk::DependencyFlags{}, + {}, + {}, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eNone, + .dstAccessMask = vk::AccessFlagBits::eTransferWrite, + .oldLayout = vk::ImageLayout::eUndefined, + .newLayout = vk::ImageLayout::eTransferDstOptimal, + .image = r->image, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = num_mipmaps, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); // Copy image data - cb.copyBufferToImage(staging_buffer, r->image, vk::ImageLayout::eTransferDstOptimal, vk::BufferImageCopy{ - .bufferOffset = 0, - .bufferRowLength = 0, - .bufferImageHeight = 0, - .imageSubresource = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .mipLevel = 0, - .baseArrayLayer = 0, - .layerCount = 1, - }, - .imageOffset = {0, 0, 0}, - .imageExtent = extent, - }); + cb.copyBufferToImage( + staging_buffer, + r->image, + vk::ImageLayout::eTransferDstOptimal, + vk::BufferImageCopy{ + .bufferOffset = 0, + .bufferRowLength = 0, + .bufferImageHeight = 0, + .imageSubresource = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .mipLevel = 0, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .imageOffset = {0, 0, 0}, + .imageExtent = extent, + }); // Create mipmaps int width = extent.width; @@ -269,71 +279,94 @@ void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::For int next_height = height > 1 ? height / 2 : 1; // Transition source image layout to eTransferSrcOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferWrite, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = vk::ImageLayout::eTransferDstOptimal, - .newLayout = vk::ImageLayout::eTransferSrcOptimal, - .image = r->image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = level - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); + cb.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader, + vk::DependencyFlags{}, + {}, + {}, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + .oldLayout = vk::ImageLayout::eTransferDstOptimal, + .newLayout = vk::ImageLayout::eTransferSrcOptimal, + .image = r->image, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = level - 1, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); // Blit level n-1 to level n - cb.blitImage(r->image, vk::ImageLayout::eTransferSrcOptimal, r->image, vk::ImageLayout::eTransferDstOptimal, vk::ImageBlit{ - .srcSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level - 1, .baseArrayLayer = 0, .layerCount = 1}, - .srcOffsets = std::array{ - vk::Offset3D{0, 0, 0}, - vk::Offset3D{width, height, 1}, - }, - .dstSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level, .baseArrayLayer = 0, .layerCount = 1}, - .dstOffsets = std::array{ - vk::Offset3D{0, 0, 0}, - vk::Offset3D{next_width, next_height, 1}, - }, - }, - vk::Filter::eLinear); + cb.blitImage( + r->image, + vk::ImageLayout::eTransferSrcOptimal, + r->image, + vk::ImageLayout::eTransferDstOptimal, + vk::ImageBlit{ + .srcSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level - 1, .baseArrayLayer = 0, .layerCount = 1}, + .srcOffsets = std::array{ + vk::Offset3D{0, 0, 0}, + vk::Offset3D{width, height, 1}, + }, + .dstSubresource = {.aspectMask = vk::ImageAspectFlagBits::eColor, .mipLevel = level, .baseArrayLayer = 0, .layerCount = 1}, + .dstOffsets = std::array{ + vk::Offset3D{0, 0, 0}, + vk::Offset3D{next_width, next_height, 1}, + }, + }, + vk::Filter::eLinear); // Transition source image layout to eShaderReadOnlyOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferRead, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = vk::ImageLayout::eTransferSrcOptimal, - .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - .image = r->image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = level - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); + cb.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader, + vk::DependencyFlags{}, + {}, + {}, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferRead, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + .oldLayout = vk::ImageLayout::eTransferSrcOptimal, + .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .image = r->image, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = level - 1, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); width = next_width; height = next_height; } // Transition the last level to eShaderReadOnlyOptimal - cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader, vk::DependencyFlags{}, {}, {}, vk::ImageMemoryBarrier{ - .srcAccessMask = vk::AccessFlagBits::eTransferWrite, - .dstAccessMask = vk::AccessFlagBits::eShaderRead, - .oldLayout = vk::ImageLayout::eTransferDstOptimal, - .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - .image = r->image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = num_mipmaps - 1, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }); + cb.pipelineBarrier( + vk::PipelineStageFlagBits::eTransfer, + vk::PipelineStageFlagBits::eFragmentShader, + vk::DependencyFlags{}, + {}, + {}, + vk::ImageMemoryBarrier{ + .srcAccessMask = vk::AccessFlagBits::eTransferWrite, + .dstAccessMask = vk::AccessFlagBits::eShaderRead, + .oldLayout = vk::ImageLayout::eTransferDstOptimal, + .newLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .image = r->image, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = num_mipmaps - 1, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); cb.end(); vk::SubmitInfo info; @@ -343,28 +376,31 @@ void image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::For if (auto result = device.waitForFences(*fence, true, 1'000'000'000); result != vk::Result::eSuccess) throw std::runtime_error("vkWaitForfences: " + vk::to_string(result)); - r->image_view = vk::raii::ImageView{device, vk::ImageViewCreateInfo{ - .image = r->image, - .viewType = image_view_type, - .format = format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = num_mipmaps, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }}; + r->image_view = vk::raii::ImageView{ + device, + vk::ImageViewCreateInfo{ + .image = r->image, + .viewType = image_view_type, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = num_mipmaps, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }, + }; image_view = std::shared_ptr(r, &r->image_view); } void image_loader::do_load_ktx(std::span bytes) { - ktxTexture* texture; + ktxTexture * texture; ktxVulkanTexture vk_texture; - ktxResult err = ktxTexture_CreateFromMemory(reinterpret_cast(bytes.data()), bytes.size(), /*KTX_TEXTURE_CREATE_CHECK_GLTF_BASISU_BIT*/0, &texture); + ktxResult err = ktxTexture_CreateFromMemory(reinterpret_cast(bytes.data()), bytes.size(), /*KTX_TEXTURE_CREATE_CHECK_GLTF_BASISU_BIT*/ 0, &texture); if (err != KTX_SUCCESS) { @@ -377,10 +413,7 @@ void image_loader::do_load_ktx(std::span bytes) // TODO } - err = ktxTexture_VkUploadEx(texture, vdi, &vk_texture, - VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_SAMPLED_BIT, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); + err = ktxTexture_VkUploadEx(texture, vdi, &vk_texture, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); if (err != KTX_SUCCESS) { // TODO try uncompressing the texture @@ -401,18 +434,21 @@ void image_loader::do_load_ktx(std::span bytes) r->ktx_texture = vk_texture; r->device = *device; r->image = vk::Image(vk_texture.image); - r->image_view = vk::raii::ImageView{device, vk::ImageViewCreateInfo{ - .image = r->image, - .viewType = image_view_type, - .format = format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = num_mipmaps, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }}; + r->image_view = vk::raii::ImageView{ + device, + vk::ImageViewCreateInfo{ + .image = r->image, + .viewType = image_view_type, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = num_mipmaps, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }, + }; image_view = std::shared_ptr(r, &r->image_view); } diff --git a/client/render/image_loader.h b/client/render/image_loader.h index 17939c3d..6db3dd38 100644 --- a/client/render/image_loader.h +++ b/client/render/image_loader.h @@ -20,15 +20,14 @@ #pragma once #include "vk/allocation.h" +#include "vk/fwd.h" #include #include #include #include #include #include -#include #include -#include "vk/fwd.h" struct ktxVulkanDeviceInfo; @@ -51,20 +50,19 @@ struct image_loader // Load raw pixel data void load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format); - - template + template void load(std::span pixels, vk::Extent3D extent, vk::Format format) { load(pixels.data(), pixels.size() * sizeof(T), extent, format); } - template + template void load(const std::array & pixels, vk::Extent3D extent, vk::Format format) { load(pixels.data(), pixels.size() * sizeof(T), extent, format); } - template + template void load(const std::vector & pixels, vk::Extent3D extent, vk::Format format) { load(pixels.data(), pixels.size() * sizeof(T), extent, format); diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 4c2f3881..5dc0b443 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -21,21 +21,21 @@ #include "application.h" #include "asset.h" +#include "image_loader.h" #include "openxr/openxr.h" #include "utils/ranges.h" #include "vulkan/vulkan_enums.hpp" #include "vulkan/vulkan_handles.hpp" #include "vulkan/vulkan_to_string.hpp" -#include -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include #include -#include "image_loader.h" +#include #include "IconsFontAwesome6.h" @@ -51,47 +51,48 @@ * struct ImGui_ImplVulkanH_Window */ -static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Format format, bool clear) +static vk::raii::RenderPass create_renderpass(vk::raii::Device & device, vk::Format format, bool clear) { - vk::AttachmentDescription attachment{ - .format = format, - .samples = vk::SampleCountFlagBits::e1, - .loadOp = clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare, - .storeOp = vk::AttachmentStoreOp::eStore, - .stencilLoadOp = vk::AttachmentLoadOp::eDontCare, - .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, - .initialLayout = vk::ImageLayout::eUndefined, - .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, + vk::AttachmentDescription attachment{ + .format = format, + .samples = vk::SampleCountFlagBits::e1, + .loadOp = clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare, + .storeOp = vk::AttachmentStoreOp::eStore, + .stencilLoadOp = vk::AttachmentLoadOp::eDontCare, + .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, + .initialLayout = vk::ImageLayout::eUndefined, + .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, }; vk::AttachmentReference color_attachment{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, + .attachment = 0, + .layout = vk::ImageLayout::eColorAttachmentOptimal, }; vk::SubpassDescription subpass = { - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment, + .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment, }; vk::SubpassDependency dependency = { - .srcSubpass = VK_SUBPASS_EXTERNAL, - .dstSubpass = 0, - .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, - .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, - .srcAccessMask = {}, - .dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite, + .srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .srcAccessMask = {}, + .dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite, }; - return vk::raii::RenderPass(device, vk::RenderPassCreateInfo{ - .attachmentCount = 1, - .pAttachments = &attachment, - .subpassCount = 1, - .pSubpasses = &subpass, - .dependencyCount = 1, - .pDependencies = &dependency, - }); + return vk::raii::RenderPass( + device, vk::RenderPassCreateInfo{ + .attachmentCount = 1, + .pAttachments = &attachment, + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = 1, + .pDependencies = &dependency, + }); } static void check_vk_result(VkResult result) @@ -103,7 +104,7 @@ static void check_vk_result(VkResult result) } } -std::optional> imgui_context::ray_plane_intersection(const imgui_context::controller_state& in) +std::optional> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) { if (!in.active) return {}; @@ -131,133 +132,129 @@ std::optional> imgui_context::ray_plane_intersection(co coord = coord / scale_; if (fabs(coord.x) <= 0.5 && fabs(coord.y) <= 0.5) - return std::make_pair(ImVec2 - ( - (0.5 + coord.x) * size.width, - (0.5 - coord.y) * size.height - ), - -lambda); + return std::make_pair(ImVec2( + (0.5 + coord.x) * size.width, + (0.5 - coord.y) * size.height), + -lambda); } return {}; } -imgui_context::imgui_frame& imgui_context::get_frame(vk::Image destination) +imgui_context::imgui_frame & imgui_context::get_frame(vk::Image destination) { - for(auto& i: frames) + for (auto & i: frames) { if (i.destination == destination) return i; } - auto& frame = frames.emplace_back(); + auto & frame = frames.emplace_back(); frame.destination = destination; // Only 1 mipmap level for the framebuffer view - frame.image_view_framebuffer = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = destination, - .viewType = vk::ImageViewType::e2D, - .format = format, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } - }); - - frame.framebuffer = vk::raii::Framebuffer(device, vk::FramebufferCreateInfo{ - .renderPass = *renderpass, - .attachmentCount = 1, - .pAttachments = &*frame.image_view_framebuffer, - .width = size.width, - .height = size.height, - .layers = 1, - }); + frame.image_view_framebuffer = vk::raii::ImageView( + device, + vk::ImageViewCreateInfo{ + .image = destination, + .viewType = vk::ImageViewType::e2D, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); + frame.framebuffer = vk::raii::Framebuffer( + device, + vk::FramebufferCreateInfo{ + .renderPass = *renderpass, + .attachmentCount = 1, + .pAttachments = &*frame.image_view_framebuffer, + .width = size.width, + .height = size.height, + .layers = 1, + }); return frame; } static const std::array pool_sizes = -{ - vk::DescriptorPoolSize{ - .type = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 100, - } -}; + { + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 100, + }}; static const vk::DescriptorSetLayoutBinding layout_bindings{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment -}; + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment}; -imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span controllers_, xr::swapchain& swapchain, glm::vec2 size) : - physical_device(physical_device), - device(device), - queue_family_index(queue_family_index), - queue(queue), - descriptor_pool(device, vk::DescriptorPoolCreateInfo - { - .flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, - .maxSets = pool_sizes[0].descriptorCount, - .poolSizeCount = pool_sizes.size(), - .pPoolSizes = pool_sizes.data(), - }), - ds_layout(device, vk::DescriptorSetLayoutCreateInfo - { - .bindingCount = 1, - .pBindings = &layout_bindings - }), - renderpass(create_renderpass(device, swapchain.format(), true)), - command_pool(device, vk::CommandPoolCreateInfo{ - .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, - .queueFamilyIndex = queue_family_index, - }), - command_buffers(swapchain.images().size()), - size(swapchain.extent().width, swapchain.extent().height), - format(swapchain.format()), - scale_(size.x, size.y), - swapchain(swapchain), - context(ImGui::CreateContext()), - plot_context(ImPlot::CreateContext()), - io((ImGui::SetCurrentContext(context), ImGui::GetIO())), - world(world) +imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, uint32_t queue_family_index, vk::raii::Queue & queue, XrSpace world, std::span controllers_, xr::swapchain & swapchain, glm::vec2 size) : + physical_device(physical_device), + device(device), + queue_family_index(queue_family_index), + queue(queue), + descriptor_pool(device, + vk::DescriptorPoolCreateInfo{ + .flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, + .maxSets = pool_sizes[0].descriptorCount, + .poolSizeCount = pool_sizes.size(), + .pPoolSizes = pool_sizes.data(), + }), + ds_layout(device, vk::DescriptorSetLayoutCreateInfo{.bindingCount = 1, .pBindings = &layout_bindings}), + renderpass(create_renderpass(device, swapchain.format(), true)), + command_pool(device, + vk::CommandPoolCreateInfo{ + .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, + .queueFamilyIndex = queue_family_index, + }), + command_buffers(swapchain.images().size()), + size(swapchain.extent().width, swapchain.extent().height), + format(swapchain.format()), + scale_(size.x, size.y), + swapchain(swapchain), + context(ImGui::CreateContext()), + plot_context(ImPlot::CreateContext()), + io((ImGui::SetCurrentContext(context), ImGui::GetIO())), + world(world) { controllers.reserve(controllers_.size()); - for(const auto& i:controllers_) + for (const auto & i: controllers_) controllers.emplace_back(i, controller_state{}); io.IniFilename = nullptr; - for(command_buffer& cb: command_buffers) + for (command_buffer & cb: command_buffers) { cb.command_buffer = std::move(device.allocateCommandBuffers({ - .commandPool = *command_pool, - .commandBufferCount = 1, + .commandPool = *command_pool, + .commandBufferCount = 1, })[0]); cb.fence = device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}); } ImGui_ImplVulkan_InitInfo init_info = { - .Instance = *application::get_vulkan_instance(), - .PhysicalDevice = *application::get_physical_device(), - .Device = *application::get_device(), - .QueueFamily = application::queue_family_index(), - .Queue = *application::get_queue(), - .PipelineCache = *application::get_pipeline_cache(), - .DescriptorPool = *descriptor_pool, - .Subpass = 0, - .MinImageCount = 2, - .ImageCount = (uint32_t)swapchain.images().size(), // used to cycle between VkBuffers in ImGui_ImplVulkan_RenderDrawData - .MSAASamples = VK_SAMPLE_COUNT_1_BIT, - .Allocator = nullptr, - .CheckVkResultFn = check_vk_result, + .Instance = *application::get_vulkan_instance(), + .PhysicalDevice = *application::get_physical_device(), + .Device = *application::get_device(), + .QueueFamily = application::queue_family_index(), + .Queue = *application::get_queue(), + .PipelineCache = *application::get_pipeline_cache(), + .DescriptorPool = *descriptor_pool, + .Subpass = 0, + .MinImageCount = 2, + .ImageCount = (uint32_t)swapchain.images().size(), // used to cycle between VkBuffers in ImGui_ImplVulkan_RenderDrawData + .MSAASamples = VK_SAMPLE_COUNT_1_BIT, + .Allocator = nullptr, + .CheckVkResultFn = check_vk_result, }; ImGui::SetCurrentContext(context); @@ -271,29 +268,27 @@ imgui_context::imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii: { ImFontConfig config; config.FontDataOwnedByAtlas = false; - io.Fonts->AddFontFromMemoryTTF(const_cast(roboto.data()), roboto.size(), 30, &config); + io.Fonts->AddFontFromMemoryTTF(const_cast(roboto.data()), roboto.size(), 30, &config); config.MergeMode = true; config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced - static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_regular.data()), font_awesome_regular.size(), 30, &config, icon_ranges); - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_solid.data()), font_awesome_solid.size(), 30, &config, icon_ranges); + static const ImWchar icon_ranges[] = {ICON_MIN_FA, ICON_MAX_FA, 0}; + io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_regular.data()), font_awesome_regular.size(), 30, &config, icon_ranges); + io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_solid.data()), font_awesome_solid.size(), 30, &config, icon_ranges); } { ImFontConfig config; config.FontDataOwnedByAtlas = false; - large_font = io.Fonts->AddFontFromMemoryTTF(const_cast(roboto.data()), roboto.size(), 75, &config); - + large_font = io.Fonts->AddFontFromMemoryTTF(const_cast(roboto.data()), roboto.size(), 75, &config); } - // Setup Dear ImGui style ImGui::StyleColorsDark(); // ImGui::StyleColorsClassic(); - //ImGui::StyleColorsLight(); + // ImGui::StyleColorsLight(); - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle & style = ImGui::GetStyle(); style.WindowBorderSize = 0; } @@ -313,22 +308,21 @@ void imgui_context::new_frame(XrTime display_time) std::vector new_states; - for(auto&& [index, controller]: utils::enumerate(controllers)) + for (auto && [index, controller]: utils::enumerate(controllers)) { - auto& [ctrl, state] = controller; + auto & [ctrl, state] = controller; - controller_state& new_state = new_states.emplace_back(); + controller_state & new_state = new_states.emplace_back(); if (auto joints = ctrl.hand.locate(world, display_time)) { - XrHandJointLocationEXT& index_tip = (*joints)[XR_HAND_JOINT_INDEX_TIP_EXT].first; + XrHandJointLocationEXT & index_tip = (*joints)[XR_HAND_JOINT_INDEX_TIP_EXT].first; if (index_tip.locationFlags & XR_SPACE_LOCATION_POSITION_TRACKED_BIT) { new_state.aim_position = { - index_tip.pose.position.x, - index_tip.pose.position.y, - index_tip.pose.position.z - }; + index_tip.pose.position.x, + index_tip.pose.position.y, + index_tip.pose.position.z}; new_state.aim_orientation = orientation_; @@ -340,7 +334,7 @@ void imgui_context::new_frame(XrTime display_time) new_state.hover_distance = std::abs(position_distance->second); if (std::abs(position_distance->second) < 0.1f) - new_state.fingertip_hovered = true; + new_state.fingertip_hovered = true; else new_state.active = false; @@ -363,7 +357,7 @@ void imgui_context::new_frame(XrTime display_time) if (ctrl.squeeze) { - auto squeeze = application::read_action_float(ctrl.squeeze).value_or(std::pair{0,0}); + auto squeeze = application::read_action_float(ctrl.squeeze).value_or(std::pair{0, 0}); new_state.squeeze_value = squeeze.second; // TODO tunable @@ -375,7 +369,7 @@ void imgui_context::new_frame(XrTime display_time) if (ctrl.trigger) { - auto trigger = application::read_action_float(ctrl.trigger).value_or(std::pair{0,0}); + auto trigger = application::read_action_float(ctrl.trigger).value_or(std::pair{0, 0}); new_state.trigger_value = trigger.second; // TODO tunable @@ -388,20 +382,20 @@ void imgui_context::new_frame(XrTime display_time) if (ctrl.scroll) { if (auto act = application::read_action_vec2(ctrl.scroll); act) - new_state.scroll_value = { -act->second.x * scroll_scale, act->second.y * scroll_scale }; + new_state.scroll_value = {-act->second.x * scroll_scale, act->second.y * scroll_scale}; else new_state.scroll_value = {0, 0}; } } - for(auto [new_state, controller]: utils::zip(new_states, controllers)) + for (auto [new_state, controller]: utils::zip(new_states, controllers)) { if (new_state.hover_distance < 0.02 && controller.second.hover_distance >= 0.02) new_state.fingertip_touched = true; } float closest_hover_distance = 1e10; - for(auto&& [index, new_state]: utils::enumerate(new_states)) + for (auto && [index, new_state]: utils::enumerate(new_states)) { if (new_state.hover_distance < closest_hover_distance && new_state.fingertip_hovered) { @@ -434,7 +428,7 @@ void imgui_context::new_frame(XrTime display_time) bool last_trigger = controllers[new_focused_controller].second.trigger_clicked || controllers[new_focused_controller].second.fingertip_touched; button_pressed = new_states[new_focused_controller].trigger_clicked || - (new_states[new_focused_controller].fingertip_touched && !controllers[new_focused_controller].second.fingertip_touched); + (new_states[new_focused_controller].fingertip_touched && !controllers[new_focused_controller].second.fingertip_touched); if (position_distance) { @@ -462,7 +456,7 @@ void imgui_context::new_frame(XrTime display_time) } focused_controller = new_focused_controller; - for(auto&& [controller, next_state]: utils::zip(controllers, new_states)) + for (auto && [controller, next_state]: utils::zip(controllers, new_states)) { controller.second = next_state; } @@ -477,18 +471,16 @@ void imgui_context::new_frame(XrTime display_time) ImGui::NewFrame(); - ImDrawList* draw_list = ImGui::GetForegroundDrawList(); + ImDrawList * draw_list = ImGui::GetForegroundDrawList(); if (position_distance) { - float distance_to_border = std::min({ - position_distance->first.x, - size.width - position_distance->first.x, - position_distance->first.y, - size.height - position_distance->first.y - }); + float distance_to_border = std::min({position_distance->first.x, + size.width - position_distance->first.x, + position_distance->first.y, + size.height - position_distance->first.y}); - float radius = 10; //std::clamp(distance_to_border / 4, 0, 10); + float radius = 10; // std::clamp(distance_to_border / 4, 0, 10); float alpha = std::clamp((distance_to_border - 10) / 50, 0, 0.8); ImU32 color_pressed = ImGui::GetColorU32(ImVec4(0, 0.2, 1, alpha)); @@ -497,7 +489,7 @@ void imgui_context::new_frame(XrTime display_time) bool pressed = button_pressed || new_states[new_focused_controller].fingertip_touched; draw_list->AddCircleFilled(position_distance->first, radius, pressed ? color_pressed : color_unpressed); - draw_list->AddCircle(position_distance->first, radius*1.2, ImGui::GetColorU32(ImVec4(0, 0, 0, alpha)), 0, radius * 0.4); + draw_list->AddCircle(position_distance->first, radius * 1.2, ImGui::GetColorU32(ImVec4(0, 0, 0, alpha)), 0, radius * 0.4); } image_index = swapchain.acquire(); @@ -515,9 +507,9 @@ XrCompositionLayerQuad imgui_context::end_frame() current_command_buffer = (current_command_buffer + 1) % command_buffers.size(); - auto& f = get_frame(destination); - auto& cb = get_command_buffer().command_buffer; - auto& fence = get_command_buffer().fence; + auto & f = get_frame(destination); + auto & cb = get_command_buffer().command_buffer; + auto & fence = get_command_buffer().fence; if (auto result = device.waitForFences(*fence, true, 1'000'000'000); result != vk::Result::eSuccess) throw std::runtime_error("vkWaitForfences: " + vk::to_string(result)); @@ -528,14 +520,14 @@ XrCompositionLayerQuad imgui_context::end_frame() vk::ClearValue clear{vk::ClearColorValue(0, 0, 0, 0)}; cb.beginRenderPass(vk::RenderPassBeginInfo{ - .renderPass = *renderpass, - .framebuffer = *f.framebuffer, - .renderArea = { - .extent = size, - }, - .clearValueCount = 1, - .pClearValues = &clear - }, vk::SubpassContents::eInline); + .renderPass = *renderpass, + .framebuffer = *f.framebuffer, + .renderArea = { + .extent = size, + }, + .clearValueCount = 1, + .pClearValues = &clear}, + vk::SubpassContents::eInline); ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), *cb); @@ -544,25 +536,26 @@ XrCompositionLayerQuad imgui_context::end_frame() cb.end(); queue.submit(vk::SubmitInfo{ - .commandBufferCount = 1, - .pCommandBuffers = &*cb, - }, *fence); + .commandBufferCount = 1, + .pCommandBuffers = &*cb, + }, + *fence); swapchain.release(); return XrCompositionLayerQuad{ - .type = XR_TYPE_COMPOSITION_LAYER_QUAD, - .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, - .space = world, - .eyeVisibility = XrEyeVisibility::XR_EYE_VISIBILITY_BOTH, - .subImage = { - .swapchain = swapchain, - .imageRect = { - .offset = {0, 0}, - .extent = {(int32_t)size.width, (int32_t)size.height}}, - }, - .pose = pose(), - .size = scale(), + .type = XR_TYPE_COMPOSITION_LAYER_QUAD, + .layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, + .space = world, + .eyeVisibility = XrEyeVisibility::XR_EYE_VISIBILITY_BOTH, + .subImage = { + .swapchain = swapchain, + .imageRect = { + .offset = {0, 0}, + .extent = {(int32_t)size.width, (int32_t)size.height}}, + }, + .pose = pose(), + .size = scale(), }; } @@ -574,7 +567,7 @@ imgui_context::~imgui_context() std::vector fences; // Release the command buffers without freing them, they will be destroyed with the command pool - for(auto& f: command_buffers) + for (auto & f: command_buffers) { f.command_buffer.release(); fences.push_back(*f.fence); @@ -589,54 +582,59 @@ imgui_context::~imgui_context() ImGui::DestroyContext(context); } - -ImTextureID imgui_context::load_texture(const std::string& filename, vk::raii::Sampler&& sampler) +ImTextureID imgui_context::load_texture(const std::string & filename, vk::raii::Sampler && sampler) { bool srgb = true; image_loader loader(physical_device, device, queue, command_pool); loader.load(asset{filename}, srgb); vk::raii::DescriptorSet ds = std::move(device.allocateDescriptorSets({ - .descriptorPool = *descriptor_pool, - .descriptorSetCount = 1, - .pSetLayouts = &*ds_layout + .descriptorPool = *descriptor_pool, + .descriptorSetCount = 1, + .pSetLayouts = &*ds_layout, })[0]); vk::DescriptorImageInfo image_info{ - .sampler = *sampler, - .imageView = **loader.image_view, - .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .sampler = *sampler, + .imageView = **loader.image_view, + .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; vk::WriteDescriptorSet ds_write{ - .dstSet = *ds, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info - }; + .dstSet = *ds, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &image_info}; device.updateDescriptorSets(ds_write, nullptr); ImTextureID id = *ds; - textures.emplace(id, texture_data{ - .sampler = std::move(sampler), - // .image = std::move(loader.image), - .image_view = std::move(loader.image_view), - .descriptor_set = std::move(ds), - }); + textures.emplace( + id, + texture_data{ + .sampler = std::move(sampler), + // .image = std::move(loader.image), + .image_view = std::move(loader.image_view), + .descriptor_set = std::move(ds), + }); return id; } -ImTextureID imgui_context::load_texture(const std::string& filename) +ImTextureID imgui_context::load_texture(const std::string & filename) { - return load_texture(filename, vk::raii::Sampler(device, vk::SamplerCreateInfo{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eLinear, - .borderColor = vk::BorderColor::eFloatTransparentBlack, - })); + return load_texture( + filename, + vk::raii::Sampler{ + device, + vk::SamplerCreateInfo{ + .magFilter = vk::Filter::eLinear, + .minFilter = vk::Filter::eLinear, + .mipmapMode = vk::SamplerMipmapMode::eLinear, + .borderColor = vk::BorderColor::eFloatTransparentBlack, + }, + }); } void imgui_context::free_texture(ImTextureID texture) diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index f8e9c6ae..736b3153 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -18,19 +18,19 @@ #pragma once -#include "xr/swapchain.h" #include "xr/hand_tracker.h" -#include -#include -#include +#include "xr/swapchain.h" #include #include -#include +#include +#include #include -#include #include -#include #include +#include +#include +#include +#include class imgui_context { @@ -63,7 +63,7 @@ public: XrAction scroll; // XR_ACTION_TYPE_VECTOR2F_INPUT // TODO: thresholds? - xr::hand_tracker& hand; + xr::hand_tracker & hand; }; struct controller_state @@ -87,9 +87,9 @@ public: private: vk::raii::PhysicalDevice physical_device; - vk::raii::Device& device; + vk::raii::Device & device; uint32_t queue_family_index; - vk::raii::Queue& queue; + vk::raii::Queue & queue; vk::raii::Pipeline pipeline = nullptr; vk::raii::DescriptorPool descriptor_pool; @@ -100,29 +100,29 @@ private: std::unordered_map textures; std::vector frames; - imgui_frame& get_frame(vk::Image destination); + imgui_frame & get_frame(vk::Image destination); std::vector command_buffers; size_t current_command_buffer = 0; - command_buffer& get_command_buffer() + command_buffer & get_command_buffer() { return command_buffers[current_command_buffer]; } vk::Extent2D size; vk::Format format; - vk::ClearValue clear_value = {vk::ClearColorValue{0,0,0,0}}; + vk::ClearValue clear_value = {vk::ClearColorValue{0, 0, 0, 0}}; glm::vec3 position_ = {0, 1, -1.5}; glm::quat orientation_ = {1, 0, 0, 0}; glm::vec2 scale_; - xr::swapchain& swapchain; + xr::swapchain & swapchain; int image_index; ImGuiContext * context; ImPlotContext * plot_context; - ImGuiIO& io; + ImGuiIO & io; std::vector> controllers; XrSpace world; @@ -131,10 +131,19 @@ private: bool button_pressed = false; - std::optional> ray_plane_intersection(const imgui_context::controller_state& in); + std::optional> ray_plane_intersection(const imgui_context::controller_state & in); public: - imgui_context(vk::raii::PhysicalDevice physical_device, vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue, XrSpace world, std::span controllers, xr::swapchain& swapchain, glm::vec2 size); + imgui_context( + vk::raii::PhysicalDevice physical_device, + vk::raii::Device & device, + uint32_t queue_family_index, + vk::raii::Queue & queue, + XrSpace world, + std::span controllers, + xr::swapchain & swapchain, + glm::vec2 size); + ~imgui_context(); void set_position(glm::vec3 position, glm::quat orientation) @@ -146,26 +155,26 @@ public: XrPosef pose() const { return XrPosef{ - .orientation = { - .x = orientation_.x, - .y = orientation_.y, - .z = orientation_.z, - .w = orientation_.w, - }, - .position = { - .x = position_.x, - .y = position_.y, - .z = position_.z, - } + .orientation = { + .x = orientation_.x, + .y = orientation_.y, + .z = orientation_.z, + .w = orientation_.w, + }, + .position = { + .x = position_.x, + .y = position_.y, + .z = position_.z, + }, }; } - glm::vec3& position() + glm::vec3 & position() { return position_; } - glm::quat& orientation() + glm::quat & orientation() { return orientation_; } @@ -182,7 +191,10 @@ public: XrExtent2Df scale() const { - return { scale_.x, scale_.y }; + return { + scale_.x, + scale_.y, + }; } void new_frame(XrTime display_time); @@ -194,8 +206,8 @@ public: return focused_controller; } - ImTextureID load_texture(const std::string& filename, vk::raii::Sampler&& sampler); - ImTextureID load_texture(const std::string& filename); + ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler); + ImTextureID load_texture(const std::string & filename); void free_texture(ImTextureID); void set_current(); }; diff --git a/client/render/scene_data.cpp b/client/render/scene_data.cpp index fe6fabc5..d163b6c1 100644 --- a/client/render/scene_data.cpp +++ b/client/render/scene_data.cpp @@ -140,8 +140,6 @@ fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::fi fastgltf::Options::DontRequireValidAssetMember | fastgltf::Options::AllowDouble | fastgltf::Options::LoadGLBBuffers | - // fastgltf::Options::LoadExternalBuffers | - // fastgltf::Options::LoadExternalImages | fastgltf::Options::DecomposeNodeMatrices; fastgltf::Expected expected_asset{fastgltf::Error::None}; @@ -322,8 +320,8 @@ constexpr bool starts_with(std::span data, std::span image_data) { - const uint8_t png_magic[] = {0xFF, 0xD8, 0xFF}; - const uint8_t jpeg_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; + const uint8_t jpeg_magic[] = {0xFF, 0xD8, 0xFF}; + const uint8_t png_magic[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}; const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; @@ -342,7 +340,7 @@ fastgltf::MimeType guess_mime_type(std::span image_data) std::shared_ptr do_load_image( vk::raii::PhysicalDevice & physical_device, vk::raii::Device & device, - vk::raii::Queue & queue, + vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, std::span image_data, bool srgb) @@ -352,7 +350,6 @@ std::shared_ptr do_load_image( case fastgltf::MimeType::JPEG: case fastgltf::MimeType::PNG: case fastgltf::MimeType::KTX2: { - try { image_loader loader(physical_device, device, queue, cb_pool); @@ -361,7 +358,7 @@ std::shared_ptr do_load_image( spdlog::debug("Loaded image {}x{}, format {}, {} mipmaps", loader.extent.width, loader.extent.height, vk::to_string(loader.format), loader.num_mipmaps); return loader.image_view; } - catch(std::exception& e) + catch (std::exception & e) { spdlog::info("Cannot load image: {}", e.what()); return {}; @@ -372,7 +369,6 @@ std::shared_ptr do_load_image( spdlog::error("Unsupported image MIME type"); return {}; } - } class loader_context @@ -406,7 +402,7 @@ public: { } - fastgltf::span load(const fastgltf::URI& uri) + fastgltf::span load(const fastgltf::URI & uri) { auto path = base_directory.empty() ? std::filesystem::path(uri.path()) : base_directory / std::filesystem::path(uri.path()); std::span bytes; @@ -416,12 +412,12 @@ public: return fastgltf::span(bytes.data(), bytes.size()); } - fastgltf::span load(const fastgltf::sources::URI& uri) + fastgltf::span load(const fastgltf::sources::URI & uri) { return load(uri.uri); } - template + template fastgltf::span subspan(fastgltf::span span, size_t offset, size_t count = fastgltf::dynamic_extent) { assert(offset < span.size()); @@ -449,7 +445,7 @@ public: fastgltf::Buffer & buffer = gltf.buffers.at(view.bufferIndex); - auto buffer2 = visit_source(buffer.data); + auto buffer2 = visit_source(buffer.data); return {subspan(buffer2.bytes, view.byteOffset, view.byteLength), buffer_view.mimeType}; }, @@ -457,7 +453,7 @@ public: if (!uri.uri.isLocalPath()) throw std::runtime_error("Non local paths are not supported"); // TODO ? - fastgltf::span data = load(uri); + fastgltf::span data = load(uri); // Don't use the MIME type from fastgltf, it's not initialized for URIs return {subspan(data, uri.fileByteOffset), fastgltf::MimeType::None}; @@ -504,7 +500,6 @@ public: srgb_array.at(gltf_material.emissiveTexture->textureIndex) = true; } - std::vector> textures; textures.reserve(gltf.textures.size()); for (auto && [srgb, gltf_texture]: utils::zip(srgb_array, gltf.textures)) @@ -683,8 +678,8 @@ public: primitive_ref.vertex_offset = staging_buffer.add_vertices(vertices); primitive_ref.vertex_count = vertices.size(); - primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC - primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC + primitive_ref.cull_mode = vk::CullModeFlagBits::eBack; // TBC + primitive_ref.front_face = vk::FrontFace::eCounterClockwise; // TBC primitive_ref.topology = convert(gltf_primitive.type); if (gltf_primitive.materialIndex) @@ -698,7 +693,7 @@ public: std::vector load_all_nodes() { std::vector unsorted_objects; - unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::node::root_id }); + unsorted_objects.resize(gltf.nodes.size(), {.parent_id = scene_data::node::root_id}); for (const auto & [index, gltf_node]: utils::enumerate(gltf.nodes)) { @@ -707,18 +702,18 @@ public: if (gltf_node.skinIndex) { - auto& skin = gltf.skins.at(*gltf_node.skinIndex); + auto & skin = gltf.skins.at(*gltf_node.skinIndex); unsorted_objects[index].joints.resize(skin.joints.size()); - for(auto [i, joint_index]: utils::enumerate(skin.joints)) + for (auto [i, joint_index]: utils::enumerate(skin.joints)) unsorted_objects[index].joints.at(i).first = joint_index; if (skin.inverseBindMatrices) { const fastgltf::Accessor & accessor = gltf.accessors.at(*skin.inverseBindMatrices); - fastgltf::iterateAccessorWithIndex(gltf, accessor, [&](const glm::mat4& value, std::size_t idx) { + fastgltf::iterateAccessorWithIndex(gltf, accessor, [&](const glm::mat4 & value, std::size_t idx) { unsorted_objects[index].joints.at(idx).second = value; }); } @@ -780,16 +775,16 @@ public: } // renumber joint indices - for(auto& node: sorted_nodes) + for (auto & node: sorted_nodes) { - for(auto& joint: node.joints) + for (auto & joint: node.joints) { joint.first = new_index[joint.first]; } } assert(sorted_nodes.size() == unsorted_nodes.size()); - for(size_t i = 0; i < sorted_nodes.size(); i++) + for (size_t i = 0; i < sorted_nodes.size(); i++) { assert(sorted_nodes[i].parent_id == scene_data::node::root_id || sorted_nodes[i].parent_id < i); } @@ -812,7 +807,7 @@ scene_data scene_loader::operator()(const std::filesystem::path & gltf_path) asset asset_file(gltf_path); fastgltf::GltfDataBuffer data_buffer; - data_buffer.copyBytes(reinterpret_cast(asset_file.data()), asset_file.size()); + data_buffer.copyBytes(reinterpret_cast(asset_file.data()), asset_file.size()); fastgltf::Asset asset = load_gltf_asset(data_buffer, gltf_path.parent_path()); loader_context ctx(gltf_path.parent_path(), asset, physical_device, device, queue, cb_pool); @@ -868,7 +863,7 @@ scene_data & scene_data::import(scene_data && other, node_handle parent) if (node.mesh_id) *node.mesh_id += mesh_offset; - for(auto& joint: node.joints) + for (auto & joint: node.joints) { joint.first += nodes_offset; } @@ -892,7 +887,6 @@ scene_data & scene_data::import(scene_data && other, node_handle parent) return *this; } - scene_data & scene_data::import(scene_data && other) { return import(std::move(other), {}); @@ -903,19 +897,18 @@ node_handle scene_data::new_node() size_t id = scene_nodes.size(); scene_nodes.push_back(node{ - .parent_id = node::root_id, - .position = {0, 0, 0}, - .orientation = {1, 0, 0, 0}, - .scale = {1, 1, 1}, - .visible = true - }); + .parent_id = node::root_id, + .position = {0, 0, 0}, + .orientation = {1, 0, 0, 0}, + .scale = {1, 1, 1}, + .visible = true}); return {id, this}; } node_handle scene_data::find_node(std::string_view name) { - for(auto&& [index, node]: utils::enumerate(scene_nodes)) + for (auto && [index, node]: utils::enumerate(scene_nodes)) { if (node.name == name) { @@ -936,7 +929,7 @@ node_handle scene_data::find_node(node_handle root, std::string_view name) flag[root.id] = true; - for(size_t index = root.id; index < scene_nodes.size(); index++) + for (size_t index = root.id; index < scene_nodes.size(); index++) { size_t parent = scene_nodes[index].parent_id; @@ -958,9 +951,9 @@ node_handle scene_data::find_node(node_handle root, std::string_view name) std::shared_ptr scene_data::find_material(std::string_view name) { - for(auto& mesh:meshes) + for (auto & mesh: meshes) { - for(auto& primitive: mesh.primitives) + for (auto & primitive: mesh.primitives) { if (primitive.material_ && primitive.material_->name == name) return primitive.material_; diff --git a/client/render/scene_data.h b/client/render/scene_data.h index 12df449a..73871b88 100644 --- a/client/render/scene_data.h +++ b/client/render/scene_data.h @@ -28,14 +28,13 @@ #include #include #include +#include #include #include #include -#include #include #include #include -#include struct sampler_info { @@ -193,8 +192,8 @@ struct scene_data scene_data & operator=(const scene_data &) = delete; scene_data & operator=(scene_data &&) = default; - scene_data& import(scene_data && other, node_handle parent); - scene_data& import(scene_data && other); + scene_data & import(scene_data && other, node_handle parent); + scene_data & import(scene_data && other); node_handle new_node(); node_handle find_node(std::string_view name); @@ -214,11 +213,11 @@ class scene_loader public: scene_loader(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, uint32_t queue_family_index, std::shared_ptr default_material) : - device(device), - physical_device(physical_device), - queue(queue), - queue_family_index(queue_family_index), - default_material(default_material) + device(device), + physical_device(physical_device), + queue(queue), + queue_family_index(queue_family_index), + default_material(default_material) {} scene_data operator()(const std::filesystem::path & gltf_path); @@ -232,32 +231,33 @@ class node_handle public: node_handle() = default; - node_handle(size_t id, scene_data * scene) : id(id), scene(scene) {} - node_handle(const node_handle&) = default; - node_handle& operator=(const node_handle&) = default; + node_handle(size_t id, scene_data * scene) : + id(id), scene(scene) {} + node_handle(const node_handle &) = default; + node_handle & operator=(const node_handle &) = default; - scene_data::node& operator*() + scene_data::node & operator*() { assert(scene != nullptr); assert(id < scene->scene_nodes.size()); return scene->scene_nodes[id]; } - const scene_data::node& operator*() const + const scene_data::node & operator*() const { assert(scene != nullptr); assert(id < scene->scene_nodes.size()); return scene->scene_nodes[id]; } - scene_data::node* operator->() + scene_data::node * operator->() { assert(scene != nullptr); assert(id < scene->scene_nodes.size()); return &scene->scene_nodes[id]; } - const scene_data::node* operator->() const + const scene_data::node * operator->() const { assert(scene != nullptr); assert(id < scene->scene_nodes.size()); diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index fc190e91..2a42c0e0 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -23,19 +23,18 @@ #include "render/image_loader.h" #include "render/scene_data.h" #include "utils/alignment.h" +#include "utils/fmt_glm.h" #include "utils/ranges.h" #include "vk/allocation.h" #include "vk/pipeline.h" #include "vk/shader.h" #include -#include +#include #include #include -#include #include #include #include -#include "utils/fmt_glm.h" #include extern const std::map> shaders; @@ -113,16 +112,13 @@ std::shared_ptr scene_renderer::create_default_material(vk default_material->normal_texture = create_default_texture(cb_pool, {128, 128, 255, 255}); default_material->buffer = std::make_shared( - device, - vk::BufferCreateInfo{ - .size = sizeof(default_material->staging), - .usage = vk::BufferUsageFlagBits::eUniformBuffer - }, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO - } - ); + device, + vk::BufferCreateInfo{ + .size = sizeof(default_material->staging), + .usage = vk::BufferUsageFlagBits::eUniformBuffer}, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO}); memcpy(default_material->buffer->map(), &default_material->staging, sizeof(default_material->staging)); default_material->buffer->unmap(); @@ -137,47 +133,67 @@ static vk::FrontFace reverse(vk::FrontFace face) return vk::FrontFace::eCounterClockwise; } -static std::array layout_bindings_0 -{ - vk::DescriptorSetLayoutBinding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, - vk::DescriptorSetLayoutBinding{ - .binding = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment}, - vk::DescriptorSetLayoutBinding{ - .binding = 2, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment} +static std::array layout_bindings_0{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 2, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, + }, }; -static std::array layout_bindings_1 -{ - vk::DescriptorSetLayoutBinding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 5, - .stageFlags = vk::ShaderStageFlagBits::eFragment}, - vk::DescriptorSetLayoutBinding{ - .binding = 5, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment} +static std::array layout_bindings_1{ + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 5, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + .binding = 5, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + }, }; -scene_renderer::scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, vk::Extent2D output_size, vk::Format output_format, std::span depth_formats, int frames_in_flight) : +scene_renderer::scene_renderer( + vk::raii::Device & device, + vk::raii::PhysicalDevice physical_device, + vk::raii::Queue & queue, + vk::raii::CommandPool & cb_pool, + vk::Extent2D output_size, + vk::Format output_format, + std::span depth_formats, + int frames_in_flight) : physical_device(physical_device), device(device), physical_device_properties(physical_device.getProperties()), queue(queue), output_size(output_size), output_format(output_format), - depth_format(find_usable_image_format(physical_device, depth_formats, {output_size.width, output_size.height, 1}, vk::ImageUsageFlagBits::eDepthStencilAttachment)), + depth_format( + find_usable_image_format( + physical_device, + depth_formats, + { + output_size.width, + output_size.height, + 1, + }, + vk::ImageUsageFlagBits::eDepthStencilAttachment)), layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)), layout_1(create_descriptor_set_layout(layout_bindings_1)), ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable @@ -188,11 +204,12 @@ scene_renderer::scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevi // Create Vulkan resources frame_resources.resize(frames_in_flight); - std::vector command_buffers = device.allocateCommandBuffers({ - .commandPool = *cb_pool, - .level = vk::CommandBufferLevel::ePrimary, - .commandBufferCount = (uint32_t)frame_resources.size(), - }); + std::vector command_buffers = device.allocateCommandBuffers( + { + .commandPool = *cb_pool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = (uint32_t)frame_resources.size(), + }); for (auto && [res, cb]: utils::zip(frame_resources, command_buffers)) { @@ -220,7 +237,7 @@ scene_renderer::~scene_renderer() void scene_renderer::wait_idle() { std::vector fences(frame_resources.size()); - for(auto&& [i, f]: utils::enumerate(frame_resources)) + for (auto && [i, f]: utils::enumerate(frame_resources)) fences[i] = *f.fence; if (auto result = device.waitForFences(fences, true, 1'000'000'000); result != vk::Result::eSuccess) @@ -294,10 +311,10 @@ vk::raii::RenderPass scene_renderer::create_renderpass() vk::SubpassDescription subpasses{ .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - .colorAttachmentCount = 1, - .pColorAttachments = &color_attachment, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment, #ifdef MSAA_4x - .pResolveAttachments = &resolve_attachment, + .pResolveAttachments = &resolve_attachment, #endif .pDepthStencilAttachment = &depth_attachment, }; @@ -339,73 +356,92 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image output_image out; // TODO: use image view from xr::swapchain - out.image_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = output, - .viewType = vk::ImageViewType::e2D, - .format = output_format, - .components{}, - .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, - }); + out.image_view = vk::raii::ImageView( + device, vk::ImageViewCreateInfo{ + .image = output, + .viewType = vk::ImageViewType::e2D, + .format = output_format, + .components{}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); - out.depth_buffer = image_allocation{device, - vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = depth_format, - .extent = { - .width = output_size.width, - .height = output_size.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .samples = MSAA_SAMPLES, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment + out.depth_buffer = image_allocation{ + device, + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = depth_format, + .extent = { + .width = output_size.width, + .height = output_size.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = MSAA_SAMPLES, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eTransientAttachment}, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check + }}; - }, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check - }}; - - out.depth_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = out.depth_buffer, - .viewType = vk::ImageViewType::e2D, - .format = depth_format, - .components{}, - .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eDepth, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, - }); + out.depth_view = vk::raii::ImageView( + device, + vk::ImageViewCreateInfo{ + .image = out.depth_buffer, + .viewType = vk::ImageViewType::e2D, + .format = depth_format, + .components{}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eDepth, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); #ifdef MSAA_4x out.multisample_image = image_allocation{vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = output_format, - .extent = { - .width = output_size.width, - .height = output_size.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .samples = MSAA_SAMPLES, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment + .imageType = vk::ImageType::e2D, + .format = output_format, + .extent = { + .width = output_size.width, + .height = output_size.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = MSAA_SAMPLES, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransientAttachment, + }, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check + .preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, + }}; - }, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, // TODO: check - .preferredFlags = VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT, - }}; out.multisample_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ - .image = out.multisample_image, - .viewType = vk::ImageViewType::e2D, - .format = output_format, - .components{}, - .subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}, - }); + .image = out.multisample_image, + .viewType = vk::ImageViewType::e2D, + .format = output_format, + .components{}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }); #endif vk::FramebufferCreateInfo fb_info{ @@ -417,7 +453,7 @@ scene_renderer::output_image scene_renderer::create_output_image_data(vk::Image #ifdef MSAA_4x std::array attachments{ - vk::ImageView{*out.multisample_view}, + vk::ImageView{*out.multisample_view}, vk::ImageView{*out.depth_view}, vk::ImageView{*out.image_view}, }; @@ -444,7 +480,7 @@ vk::raii::Pipeline & scene_renderer::get_pipeline(const pipeline_info & info) vk::raii::DescriptorSetLayout scene_renderer::create_descriptor_set_layout(std::span bindings, vk::DescriptorSetLayoutCreateFlags flags) { - vk::DescriptorSetLayoutCreateInfo dsl_info{.flags = flags}; + vk::DescriptorSetLayoutCreateInfo dsl_info{.flags = flags}; dsl_info.setBindings(bindings); return vk::raii::DescriptorSetLayout{device, dsl_info}; } @@ -467,116 +503,109 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) auto fragment_shader = load_shader(device, info.shader_name + ".frag"); std::array specialization_constants_desc{ - vk::SpecializationMapEntry - { - .constantID = 0, - .offset = offsetof(pipeline_info, nb_texcoords), - .size = sizeof(int32_t), - }, - vk::SpecializationMapEntry - { - .constantID = 1, - .offset = offsetof(pipeline_info, nb_clipping), - .size = sizeof(int32_t), - }, - vk::SpecializationMapEntry - { - .constantID = 2, - .offset = offsetof(pipeline_info, dithering), - .size = sizeof(VkBool32), - }, - vk::SpecializationMapEntry - { - .constantID = 3, - .offset = offsetof(pipeline_info, alpha_cutout), - .size = sizeof(VkBool32), - }, - vk::SpecializationMapEntry - { - .constantID = 4, - .offset = offsetof(pipeline_info, skinning), - .size = sizeof(VkBool32), - } - }; + vk::SpecializationMapEntry{ + .constantID = 0, + .offset = offsetof(pipeline_info, nb_texcoords), + .size = sizeof(int32_t), + }, + vk::SpecializationMapEntry{ + .constantID = 1, + .offset = offsetof(pipeline_info, nb_clipping), + .size = sizeof(int32_t), + }, + vk::SpecializationMapEntry{ + .constantID = 2, + .offset = offsetof(pipeline_info, dithering), + .size = sizeof(VkBool32), + }, + vk::SpecializationMapEntry{ + .constantID = 3, + .offset = offsetof(pipeline_info, alpha_cutout), + .size = sizeof(VkBool32), + }, + vk::SpecializationMapEntry{ + .constantID = 4, + .offset = offsetof(pipeline_info, skinning), + .size = sizeof(VkBool32), + }}; vk::SpecializationInfo specialization{ - .mapEntryCount = specialization_constants_desc.size(), - .pMapEntries = specialization_constants_desc.data(), - .dataSize = sizeof(pipeline_info), - .pData = &info, + .mapEntryCount = specialization_constants_desc.size(), + .pMapEntries = specialization_constants_desc.data(), + .dataSize = sizeof(pipeline_info), + .pData = &info, }; return vk::raii::Pipeline{ - device, - application::get_pipeline_cache(), - vk::pipeline_builder{ - .Stages{ - vk::PipelineShaderStageCreateInfo{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - .pSpecializationInfo = &specialization, + device, + application::get_pipeline_cache(), + vk::pipeline_builder{ + .Stages{ + vk::PipelineShaderStageCreateInfo{ + .stage = vk::ShaderStageFlagBits::eVertex, + .module = *vertex_shader, + .pName = "main", + .pSpecializationInfo = &specialization, - }, - vk::PipelineShaderStageCreateInfo{ - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - .pSpecializationInfo = &specialization, + }, + vk::PipelineShaderStageCreateInfo{ + .stage = vk::ShaderStageFlagBits::eFragment, + .module = *fragment_shader, + .pName = "main", + .pSpecializationInfo = &specialization, - }, - }, - .VertexBindingDescriptions = {vertex_description.binding}, - .VertexAttributeDescriptions = vertex_description.attributes, - .InputAssemblyState = {{ - .topology = info.topology, - .primitiveRestartEnable = false, - }}, - .Viewports = {vk::Viewport{ - .x = 0, - .y = 0, - .width = (float)output_size.width, - .height = (float)output_size.height, - .minDepth = 0, - .maxDepth = 1, - }}, - .Scissors = {vk::Rect2D{ - .offset = {0, 0}, - .extent = output_size, - }}, - .RasterizationState = {vk::PipelineRasterizationStateCreateInfo{ - .polygonMode = vk::PolygonMode::eFill, - .cullMode = info.cull_mode, - .frontFace = info.front_face, - .lineWidth = 1.0, - }}, - .MultisampleState = {vk::PipelineMultisampleStateCreateInfo{ - .rasterizationSamples = MSAA_SAMPLES, - }}, - .DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{ - .depthTestEnable = true, - .depthWriteEnable = true, - .depthCompareOp = vk::CompareOp::eLess, - .depthBoundsTestEnable = false, - .minDepthBounds = 0.0f, - .maxDepthBounds = 1.0f, - }}, - .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, - .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ - .blendEnable = info.blend_enable, - .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, - .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, - .colorBlendOp = vk::BlendOp::eAdd, - .srcAlphaBlendFactor = vk::BlendFactor::eSrcAlpha, - .dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, - .alphaBlendOp = vk::BlendOp::eAdd, - .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA - }}, - .DynamicState = {}, - .layout = *pipeline_layout, - .renderPass = *renderpass, - .subpass = 0, - }}; + }, + }, + .VertexBindingDescriptions = {vertex_description.binding}, + .VertexAttributeDescriptions = vertex_description.attributes, + .InputAssemblyState = {{ + .topology = info.topology, + .primitiveRestartEnable = false, + }}, + .Viewports = {vk::Viewport{ + .x = 0, + .y = 0, + .width = (float)output_size.width, + .height = (float)output_size.height, + .minDepth = 0, + .maxDepth = 1, + }}, + .Scissors = {vk::Rect2D{ + .offset = {0, 0}, + .extent = output_size, + }}, + .RasterizationState = {vk::PipelineRasterizationStateCreateInfo{ + .polygonMode = vk::PolygonMode::eFill, + .cullMode = info.cull_mode, + .frontFace = info.front_face, + .lineWidth = 1.0, + }}, + .MultisampleState = {vk::PipelineMultisampleStateCreateInfo{ + .rasterizationSamples = MSAA_SAMPLES, + }}, + .DepthStencilState = {vk::PipelineDepthStencilStateCreateInfo{ + .depthTestEnable = true, + .depthWriteEnable = true, + .depthCompareOp = vk::CompareOp::eLess, + .depthBoundsTestEnable = false, + .minDepthBounds = 0.0f, + .maxDepthBounds = 1.0f, + }}, + .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, + .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ + .blendEnable = info.blend_enable, + .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, + .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, + .colorBlendOp = vk::BlendOp::eAdd, + .srcAlphaBlendFactor = vk::BlendFactor::eSrcAlpha, + .dstAlphaBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, + .alphaBlendOp = vk::BlendOp::eAdd, + .colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA}}, + .DynamicState = {}, + .layout = *pipeline_layout, + .renderPass = *renderpass, + .subpass = 0, + }}; } vk::Sampler scene_renderer::get_sampler(const sampler_info & info) @@ -585,15 +614,17 @@ vk::Sampler scene_renderer::get_sampler(const sampler_info & info) if (it != samplers.end()) return **it->second; - auto out = std::make_shared(device, vk::SamplerCreateInfo{ - .magFilter = info.mag_filter, - .minFilter = info.min_filter, - .mipmapMode = info.min_filter_mipmap, - .addressModeU = info.wrapS, - .addressModeV = info.wrapT, - // .anisotropyEnable = true, - // .maxAnisotropy = 4, - }); + auto out = std::make_shared( + device, + vk::SamplerCreateInfo{ + .magFilter = info.mag_filter, + .minFilter = info.min_filter, + .mipmapMode = info.min_filter_mipmap, + .addressModeU = info.wrapS, + .addressModeV = info.wrapT, + // .anisotropyEnable = true, + // .maxAnisotropy = 4, + }); samplers.emplace(info, out); return **out; @@ -603,7 +634,7 @@ void scene_renderer::start_frame() { current_frame_index = (current_frame_index + 1) % frame_resources.size(); - auto& f = current_frame(); + auto & f = current_frame(); if (auto result = device.waitForFences(*f.fence, true, 1'000'000'000); result != vk::Result::eSuccess) throw std::runtime_error("vkWaitForfences: " + vk::to_string(result)); device.resetFences(*f.fence); @@ -611,11 +642,11 @@ void scene_renderer::start_frame() if (f.query_pool_filled) { auto [res, timestamps] = query_pool.getResults( - current_frame_index * 2, - 2, - 2 * sizeof(uint64_t), - sizeof(uint64_t), - vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); + current_frame_index * 2, + 2, + 2 * sizeof(uint64_t), + sizeof(uint64_t), + vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); if (res == vk::Result::eSuccess) { @@ -634,29 +665,31 @@ void scene_renderer::start_frame() { // TODO multiple UBOs if it does not fit f.uniform_buffer = buffer_allocation{ - device, - vk::BufferCreateInfo{ - .size = 1048576, - .usage = vk::BufferUsageFlagBits::eUniformBuffer}, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE}, - "scene_renderer::render (UBO)" - }; + device, + vk::BufferCreateInfo{ + .size = 1048576, + .usage = vk::BufferUsageFlagBits::eUniformBuffer, + }, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE, + }, + "scene_renderer::render (UBO)"}; } } void scene_renderer::end_frame() { - auto& f = current_frame(); + auto & f = current_frame(); f.cb.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, *query_pool, current_frame_index * 2 + 1); f.cb.end(); queue.submit(vk::SubmitInfo{ - .commandBufferCount = 1, - .pCommandBuffers = &*f.cb, - }, *f.fence); + .commandBufferCount = 1, + .pCommandBuffers = &*f.cb, + }, + *f.fence); f.query_pool_filled = true; } @@ -665,50 +698,50 @@ scene_renderer::per_frame_resources & scene_renderer::current_frame() return frame_resources[current_frame_index]; } -void scene_renderer::update_material_descriptor_set(scene_data::material& material) +void scene_renderer::update_material_descriptor_set(scene_data::material & material) { if (!material.ds || !material.ds.unique()) material.ds = ds_pool_material.allocate(); vk::DescriptorSet ds = **material.ds; - auto f = [&](std::shared_ptr& texture){ + auto f = [&](std::shared_ptr & texture) { return vk::DescriptorImageInfo{ - .sampler = get_sampler(texture->sampler), - .imageView = **texture->image_view, - .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + .sampler = get_sampler(texture->sampler), + .imageView = **texture->image_view, + .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; }; std::array write_ds_image{ - f(material.base_color_texture), - f(material.metallic_roughness_texture), - f(material.occlusion_texture), - f(material.emissive_texture), - f(material.normal_texture), + f(material.base_color_texture), + f(material.metallic_roughness_texture), + f(material.occlusion_texture), + f(material.emissive_texture), + f(material.normal_texture), }; vk::DescriptorBufferInfo write_ds_buffer{ - .buffer = *material.buffer, - .offset = material.offset, - .range = sizeof(scene_data::material::gpu_data) + .buffer = *material.buffer, + .offset = material.offset, + .range = sizeof(scene_data::material::gpu_data), }; std::array write_ds{ - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 0, - .descriptorCount = (uint32_t)write_ds_image.size(), - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data() - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = (uint32_t)write_ds_image.size(), - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &write_ds_buffer - }, + vk::WriteDescriptorSet{ + .dstSet = ds, + .dstBinding = 0, + .descriptorCount = (uint32_t)write_ds_image.size(), + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data(), + }, + vk::WriteDescriptorSet{ + .dstSet = ds, + .dstBinding = (uint32_t)write_ds_image.size(), + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &write_ds_buffer, + }, }; device.updateDescriptorSets(write_ds, {}); @@ -731,7 +764,7 @@ void scene_renderer::update_material_descriptor_set(scene_data::material& materi // } // } -void scene_renderer::render(scene_data & scene, const std::array& clear_color, std::span frames) +void scene_renderer::render(scene_data & scene, const std::array & clear_color, std::span frames) { per_frame_resources & resources = current_frame(); @@ -753,7 +786,7 @@ void scene_renderer::render(scene_data & scene, const std::array& clea std::vector reverse_side(scene.scene_nodes.size()); std::vector visible(scene.scene_nodes.size()); - for(const auto& [index, object]: utils::enumerate(scene.scene_nodes)) + for (const auto & [index, object]: utils::enumerate(scene.scene_nodes)) { glm::mat4 transform_to_parent = glm::translate(glm::mat4(1), object.position) * (glm::mat4)object.orientation * glm::scale(glm::mat4(1), object.scale); float det = object.scale.x * object.scale.y * object.scale.z; @@ -785,7 +818,7 @@ void scene_renderer::render(scene_data & scene, const std::array& clea glm::mat4 viewproj = frame.projection * frame.view; vk::DeviceSize frame_ubo_offset = resources.uniform_buffer_offset; - frame_gpu_data& frame_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); + frame_gpu_data & frame_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data)); // frame_ubo.ambient_color = glm::vec4(0.5,0.5,0.5,0); // TODO @@ -794,26 +827,27 @@ void scene_renderer::render(scene_data & scene, const std::array& clea // frame_ubo.ambient_color = glm::vec4(0.2,0.2,0.2,0); // TODO // frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO - frame_ubo.ambient_color = glm::vec4(0,0,0,0); // TODO - frame_ubo.light_color = glm::vec4(0.8,0.8,0.8,0); // TODO + frame_ubo.ambient_color = glm::vec4(0, 0, 0, 0); // TODO + frame_ubo.light_color = glm::vec4(0.8, 0.8, 0.8, 0); // TODO - frame_ubo.light_position = glm::vec4(1,1,1,0); // TODO + frame_ubo.light_position = glm::vec4(1, 1, 1, 0); // TODO frame_ubo.proj = frame.projection; frame_ubo.view = frame.view; - cb.beginRenderPass(vk::RenderPassBeginInfo{ - .renderPass = *renderpass, - .framebuffer = *output.framebuffer, - .renderArea = { - .offset = {0, 0}, - .extent = output_size, - }, - .clearValueCount = clear_values.size(), - .pClearValues = clear_values.data(), - }, - vk::SubpassContents::eInline); + cb.beginRenderPass( + vk::RenderPassBeginInfo{ + .renderPass = *renderpass, + .framebuffer = *output.framebuffer, + .renderArea = { + .offset = {0, 0}, + .extent = output_size, + }, + .clearValueCount = clear_values.size(), + .pClearValues = clear_values.data(), + }, + vk::SubpassContents::eInline); - for(const auto& [index, node]: utils::enumerate(scene.scene_nodes)) + for (const auto & [index, node]: utils::enumerate(scene.scene_nodes)) { if (!node.mesh_id) continue; @@ -821,11 +855,11 @@ void scene_renderer::render(scene_data & scene, const std::array& clea if (!visible[index]) continue; - scene_data::mesh& mesh = scene.meshes.at(*node.mesh_id); - glm::mat4& transform = transform_to_root[index]; + scene_data::mesh & mesh = scene.meshes.at(*node.mesh_id); + glm::mat4 & transform = transform_to_root[index]; vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset; - instance_gpu_data& object_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); + instance_gpu_data & object_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(frame_gpu_data)); vk::DeviceSize joints_ubo_offset = 0; @@ -836,7 +870,7 @@ void scene_renderer::render(scene_data & scene, const std::array& clea resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(glm::mat4) * 32); assert(node.joints.size() <= 32); - for(auto&& [idx, joint]: utils::enumerate(node.joints)) + for (auto && [idx, joint]: utils::enumerate(node.joints)) { joint_matrices[idx] = glm::inverse(transform) * transform_to_root[joint.first] * joint.second; } @@ -846,7 +880,7 @@ void scene_renderer::render(scene_data & scene, const std::array& clea object_ubo.modelview = frame.view * transform; object_ubo.modelviewproj = viewproj * transform; - for(scene_data::primitive& primitive: mesh.primitives) + for (scene_data::primitive & primitive: mesh.primitives) { // Get the material std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; @@ -856,14 +890,14 @@ void scene_renderer::render(scene_data & scene, const std::array& clea // Get the pipeline pipeline_info info{ - .shader_name = material->shader_name, - .cull_mode = primitive.cull_mode, - .front_face = primitive.front_face, - .topology = primitive.topology, - .blend_enable = material->blend_enable, + .shader_name = material->shader_name, + .cull_mode = primitive.cull_mode, + .front_face = primitive.front_face, + .topology = primitive.topology, + .blend_enable = material->blend_enable, - .nb_texcoords = 2, // TODO - .skinning = !node.joints.empty() + .nb_texcoords = 2, // TODO + .skinning = !node.joints.empty(), }; if (material->double_sided) @@ -880,41 +914,39 @@ void scene_renderer::render(scene_data & scene, const std::array& clea cb.bindVertexBuffers(0, (vk::Buffer)*mesh.buffer, primitive.vertex_offset); vk::DescriptorBufferInfo buffer_info_1{ - .buffer = resources.uniform_buffer, - .offset = frame_ubo_offset, - .range = sizeof(frame_gpu_data) + .buffer = resources.uniform_buffer, + .offset = frame_ubo_offset, + .range = sizeof(frame_gpu_data) }; vk::DescriptorBufferInfo buffer_info_2{ - .buffer = resources.uniform_buffer, - .offset = instance_ubo_offset, - .range = sizeof(instance_gpu_data) - }; + .buffer = resources.uniform_buffer, + .offset = instance_ubo_offset, + .range = sizeof(instance_gpu_data)}; vk::DescriptorBufferInfo buffer_info_3{ - .buffer = resources.uniform_buffer, - .offset = joints_ubo_offset, - .range = sizeof(glm::mat4) * 32 - }; + .buffer = resources.uniform_buffer, + .offset = joints_ubo_offset, + .range = sizeof(glm::mat4) * 32}; std::array descriptors{ - vk::WriteDescriptorSet{ - .dstBinding = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_1 - }, - vk::WriteDescriptorSet{ - .dstBinding = 1, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_2 - }, - vk::WriteDescriptorSet{ - .dstBinding = 2, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info_3 - }, + vk::WriteDescriptorSet{ + .dstBinding = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_1, + }, + vk::WriteDescriptorSet{ + .dstBinding = 1, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_2, + }, + vk::WriteDescriptorSet{ + .dstBinding = 2, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_3, + }, }; cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors); @@ -929,7 +961,6 @@ void scene_renderer::render(scene_data & scene, const std::array& clea resources.resources.push_back(material->ds); } - } cb.endRenderPass(); } diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index f3aef7cd..0a7b4983 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -18,10 +18,7 @@ #pragma once -#include -#include #include -#include #include #include #include @@ -30,6 +27,8 @@ #include #include #include +#include +#include #include "vk/allocation.h" @@ -158,10 +157,10 @@ class scene_renderer std::vector> resources; bool query_pool_filled = false; - // Buffer for per-view and per-instance data - // device local, host visible, host coherent + // Buffer for per-view and per-instance data + // device local, host visible, host coherent size_t uniform_buffer_offset; - buffer_allocation uniform_buffer; + buffer_allocation uniform_buffer; }; std::vector frame_resources; @@ -169,12 +168,20 @@ class scene_renderer vk::raii::QueryPool query_pool = nullptr; double gpu_time_s = 0; - per_frame_resources& current_frame(); + per_frame_resources & current_frame(); - void update_material_descriptor_set(scene_data::material& material); + void update_material_descriptor_set(scene_data::material & material); public: - scene_renderer(vk::raii::Device & device, vk::raii::PhysicalDevice physical_device, vk::raii::Queue & queue, vk::raii::CommandPool & cb_pool, vk::Extent2D output_size, vk::Format output_format, std::span depth_formats, int frames_in_flight = 2); + scene_renderer( + vk::raii::Device & device, + vk::raii::PhysicalDevice physical_device, + vk::raii::Queue & queue, + vk::raii::CommandPool & cb_pool, + vk::Extent2D output_size, + vk::Format output_format, + std::span depth_formats, + int frames_in_flight = 2); ~scene_renderer(); @@ -186,7 +193,7 @@ public: }; void start_frame(); - void render(scene_data & scene, const std::array& clear_color, std::span info); + void render(scene_data & scene, const std::array & clear_color, std::span info); void end_frame(); double get_gpu_time() const diff --git a/client/scene.cpp b/client/scene.cpp index fa7bc34f..89207274 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -19,7 +19,6 @@ #include "scene.h" #include "application.h" -#include #include #include @@ -27,21 +26,21 @@ std::vector scene::scene_registry; scene::~scene() {} -scene::scene(key, const meta& current_meta) : - instance(application::instance().xr_instance), - system(application::instance().xr_system_id), - session(application::instance().xr_session), - world_space(application::instance().world_space), - view_space(application::instance().view_space), - viewconfig(application::instance().app_info.viewconfig), +scene::scene(key, const meta & current_meta) : + instance(application::instance().xr_instance), + system(application::instance().xr_system_id), + session(application::instance().xr_session), + world_space(application::instance().world_space), + view_space(application::instance().view_space), + viewconfig(application::instance().app_info.viewconfig), - 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), - queue_family_index(application::instance().vk_queue_family_index), - current_meta(current_meta) + 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), + queue_family_index(application::instance().vk_queue_family_index), + current_meta(current_meta) { } diff --git a/client/scene.h b/client/scene.h index 5db4c449..7935a3e4 100644 --- a/client/scene.h +++ b/client/scene.h @@ -25,8 +25,8 @@ #include #include -#include #include +#include // See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/ // for automatic registration of scenes @@ -61,13 +61,14 @@ public: private: // Force derived classes to inherit from scene_impl instead of scene - class key {}; - template + class key + {}; + template friend class scene_impl; friend class application; protected: - static std::vector scene_registry; + static std::vector scene_registry; xr::instance & instance; xr::system & system; @@ -76,14 +77,14 @@ protected: xr::space & view_space; XrViewConfigurationType viewconfig; - vk::raii::Instance& vk_instance; - vk::raii::Device& device; - vk::raii::PhysicalDevice& physical_device; - vk::raii::Queue& queue; - vk::raii::CommandPool& commandpool; + vk::raii::Instance & vk_instance; + vk::raii::Device & device; + vk::raii::PhysicalDevice & physical_device; + vk::raii::Queue & queue; + vk::raii::CommandPool & commandpool; uint32_t queue_family_index; - const meta& current_meta; + const meta & current_meta; std::pair get_action(const std::string & name) { @@ -96,7 +97,7 @@ protected: } public: - scene(key, const meta&); + scene(key, const meta &); virtual ~scene(); @@ -108,7 +109,7 @@ public: virtual void on_session_state_changed(XrSessionState state); }; -template +template class scene_impl : public scene { friend T; @@ -123,7 +124,8 @@ class scene_impl : public scene static inline bool registered = scene_impl::register_scene(); - scene_impl() : scene(key{}, T::get_meta_scene()) + scene_impl() : + scene(key{}, T::get_meta_scene()) { (void)registered; } diff --git a/client/scenes/hand_model.cpp b/client/scenes/hand_model.cpp index 057bb9f8..1438217a 100644 --- a/client/scenes/hand_model.cpp +++ b/client/scenes/hand_model.cpp @@ -59,29 +59,27 @@ hand_model::hand_model(const std::filesystem::path & gltf_path, scene_loader & l // clang-format on } -void hand_model::apply(const std::optional>& joints_location) +void hand_model::apply(const std::optional> & joints_location) { if (joints_location) { root_node->visible = true; - for(auto&& [joint, loc]: utils::zip(joints, *joints_location)) + for (auto && [joint, loc]: utils::zip(joints, *joints_location)) { if (!joint) continue; joint->position = { - loc.first.pose.position.x, - loc.first.pose.position.y, - loc.first.pose.position.z - }; + loc.first.pose.position.x, + loc.first.pose.position.y, + loc.first.pose.position.z}; joint->orientation = { - loc.first.pose.orientation.w, - loc.first.pose.orientation.x, - loc.first.pose.orientation.y, - loc.first.pose.orientation.z - }; + loc.first.pose.orientation.w, + loc.first.pose.orientation.x, + loc.first.pose.orientation.y, + loc.first.pose.orientation.z}; } } else diff --git a/client/scenes/hand_model.h b/client/scenes/hand_model.h index f91109a5..40645fe7 100644 --- a/client/scenes/hand_model.h +++ b/client/scenes/hand_model.h @@ -27,7 +27,7 @@ struct hand_model node_handle root_node; std::vector joints; - hand_model(const std::filesystem::path & gltf_path, scene_loader& loader, scene_data& scene); + hand_model(const std::filesystem::path & gltf_path, scene_loader & loader, scene_data & scene); - void apply(const std::optional>& joints); + void apply(const std::optional> & joints); }; diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp index 012cf905..034d8f3d 100644 --- a/client/scenes/input_profile.cpp +++ b/client/scenes/input_profile.cpp @@ -20,13 +20,13 @@ #include "application.h" #include "asset.h" +#include #include #include #include #include #include #include -#include namespace { @@ -204,7 +204,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l } } - for(auto&& [layout, model]: models) + for (auto && [layout, model]: models) { node_handle root_node = scene.new_node(); root_node->name = layout; @@ -222,7 +222,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l scene.import(std::move(model), root_node); } - for(auto& json_response: json_responses) + for (auto & json_response: json_responses) { std::string action_path = "/user/hand/" + json_response.layout + json_response.component_subpath; @@ -236,11 +236,11 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l continue; } - auto& response = responses.emplace_back(); + auto & response = responses.emplace_back(); response.action = action.first; response.type = action.second; - switch(json_response.property) + switch (json_response.property) { case component_property::button: case component_property::state: @@ -262,7 +262,7 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l } node_handle controller_root_node; - for(auto&& [i, j]: model_handles) + for (auto && [i, j]: model_handles) { if (j->name == json_response.layout) { @@ -366,11 +366,11 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo { float scaled_value = *value * response.scale + response.bias; - if ((scaled_value < 0) || (scaled_value > 1)) + if ((scaled_value < 0) || (scaled_value > 1)) { std::string full_name = response.target.node->name; - for(auto i = response.target.node; i; i = i.parent()) + for (auto i = response.target.node; i; i = i.parent()) { full_name = i->name + "/" + full_name; } @@ -378,11 +378,10 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time, bo spdlog::warn("Out of range value {} (scaled to {}) for node {}", *value, scaled_value, full_name); } - - std::visit([&](auto& transform) - { + std::visit([&](auto & transform) { apply_visual_response(response.target.node, transform, scaled_value); - }, response.target.state); + }, + response.target.state); } } } diff --git a/client/scenes/input_profile.h b/client/scenes/input_profile.h index 357131d1..a528504d 100644 --- a/client/scenes/input_profile.h +++ b/client/scenes/input_profile.h @@ -19,10 +19,10 @@ #pragma once #include -#include -#include -#include #include +#include +#include +#include struct input_profile { @@ -60,7 +60,7 @@ struct input_profile std::vector responses; std::vector> model_handles; - input_profile(const std::filesystem::path& json_profile, scene_loader& loader, scene_data& scene); + input_profile(const std::filesystem::path & json_profile, scene_loader & loader, scene_data & scene); // application::poll_actions() must have been called before void apply(XrSpace world_space, XrTime predicted_display_time, bool hide_left, bool hide_right); diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index ce32fe6e..fb44839d 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -18,38 +18,38 @@ */ #include "lobby.h" -#include "version.h" #include "application.h" #include "glm/geometric.hpp" +#include "hardware.h" #include "imgui.h" #include "input_profile.h" #include "openxr/openxr.h" #include "render/scene_data.h" #include "render/scene_renderer.h" #include "stream.h" -#include "hardware.h" #include "utils/contains.h" +#include "version.h" #include "wivrn_client.h" #include "xr/passthrough.h" #include #include "wivrn_discover.h" #include +#include #include #include #include +#include #include #include #include #include #include -#include -#include -#include -#include -#include #include +#include +#include +#include static const std::string discover_service = "_wivrn._tcp.local."; static bool force_autoconnect = false; @@ -68,7 +68,7 @@ static std::string choose_webxr_profile() return controller; #endif - switch(guess_model()) + switch (guess_model()) { case model::oculus_quest: return "oculus-touch-v2"; @@ -92,16 +92,16 @@ static std::string choose_webxr_profile() __builtin_unreachable(); } -static std::string json_string(const std::string& in) +static std::string json_string(const std::string & in) { std::string out; out.reserve(in.size() + 2); out += '"'; - for(char c: in) + for (char c: in) { - switch(c) + switch (c) { case '\b': out += "\\b"; @@ -143,10 +143,9 @@ static std::string json_string(const std::string& in) } static const std::array supported_formats = -{ - vk::Format::eR8G8B8A8Srgb, - vk::Format::eB8G8R8A8Srgb -}; + { + vk::Format::eR8G8B8A8Srgb, + vk::Format::eB8G8R8A8Srgb}; void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime predicted_display_time) { @@ -175,7 +174,7 @@ void scenes::lobby::move_gui(glm::vec3 position, glm::quat orientation, XrTime p gui_yaw += gui_yaw_error; imgui_ctx->position() += gui_position_error; - imgui_ctx->orientation() = glm::quat(cos(gui_yaw/2), 0, sin(gui_yaw/2), 0) * glm::quat(cos(gui_target_pitch/2), sin(gui_target_pitch/2), 0, 0); + imgui_ctx->orientation() = glm::quat(cos(gui_yaw / 2), 0, sin(gui_yaw / 2), 0) * glm::quat(cos(gui_target_pitch / 2), sin(gui_target_pitch / 2), 0, 0); } } @@ -191,21 +190,20 @@ scenes::lobby::lobby() { simdjson::dom::parser parser; simdjson::dom::element root = parser.load(application::get_config_path() / "client.json"); - for(simdjson::dom::object i: simdjson::dom::array(root["servers"])) + for (simdjson::dom::object i: simdjson::dom::array(root["servers"])) { server_data data{ - .autoconnect = i["autoconnect"].get_bool(), - .manual = i["manual"].get_bool(), - .visible = false, - .compatible = true, - .service = { - .name = (std::string)i["pretty_name"], - .hostname = (std::string)i["hostname"], - .port = (int)i["port"].get_int64(), - .txt = {{"cookie", (std::string)i["cookie"]}} + .autoconnect = i["autoconnect"].get_bool(), + .manual = i["manual"].get_bool(), + .visible = false, + .compatible = true, + .service = { + .name = (std::string)i["pretty_name"], + .hostname = (std::string)i["hostname"], + .port = (int)i["port"].get_int64(), + .txt = {{"cookie", (std::string)i["cookie"]}} - } - }; + }}; servers.emplace(data.service.txt["cookie"], data); } @@ -228,7 +226,7 @@ scenes::lobby::lobby() if (passthrough.is_bool()) passthrough_enabled = passthrough.get_bool(); } - catch(std::exception& e) + catch (std::exception & e) { spdlog::warn("Cannot read configuration: {}", e.what()); servers.clear(); @@ -236,7 +234,7 @@ scenes::lobby::lobby() } spdlog::info("{} known server(s):", servers.size()); - for(auto& i: servers) + for (auto & i: servers) { spdlog::info(" {}", i.second.service.name); } @@ -270,7 +268,7 @@ void scenes::lobby::save_config() { std::stringstream ss; - for (auto& [cookie, server_data]: servers) + for (auto & [cookie, server_data]: servers) { if (server_data.autoconnect || server_data.manual) { @@ -294,20 +292,20 @@ void scenes::lobby::save_config() json << "{\"servers\":[" << servers_str << "]," << "\"show_performance_metrics\":" << std::boolalpha << show_performance_metrics; if (preferred_refresh_rate != 0.) - json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate ; + json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate; json << ",\"microphone\":" << std::boolalpha << microphone; json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; json << "}"; } -static std::string ip_address_to_string(const in_addr& addr) +static std::string ip_address_to_string(const in_addr & addr) { char buf[100]; inet_ntop(AF_INET, &addr, buf, sizeof(buf)); return buf; } -static std::string ip_address_to_string(const in6_addr& addr) +static std::string ip_address_to_string(const in6_addr & addr) { char buf[100]; inet_ntop(AF_INET6, &addr, buf, sizeof(buf)); @@ -323,7 +321,7 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic spdlog::debug("Client protocol version: {}", protocol_string); spdlog::debug("Server TXT:"); - for(auto& [i,j]: service.txt) + for (auto & [i, j]: service.txt) { spdlog::debug(" {}=\"{}\"", i, j); } @@ -339,11 +337,10 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic // Only the automatically discovered servers already have their IP addresses available if (manual_connection) { - addrinfo hint - { - .ai_flags = AI_ADDRCONFIG, - .ai_family = AF_UNSPEC, - .ai_socktype = SOCK_STREAM, + addrinfo hint{ + .ai_flags = AI_ADDRCONFIG, + .ai_family = AF_UNSPEC, + .ai_socktype = SOCK_STREAM, }; addrinfo * addresses; if (int err = getaddrinfo(service.hostname.c_str(), nullptr, &hint, &addresses)) @@ -352,15 +349,15 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic throw std::runtime_error("Cannot resolve hostname: " + std::string(gai_strerror(err))); } - for(auto i = addresses; i; i = i->ai_next) + for (auto i = addresses; i; i = i->ai_next) { switch (i->ai_family) { case AF_INET: - service.addresses.push_back(((sockaddr_in*)i->ai_addr)->sin_addr); + service.addresses.push_back(((sockaddr_in *)i->ai_addr)->sin_addr); break; case AF_INET6: - service.addresses.push_back(((sockaddr_in6*)i->ai_addr)->sin6_addr); + service.addresses.push_back(((sockaddr_in6 *)i->ai_addr)->sin6_addr); break; } } @@ -372,7 +369,8 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic { std::string address_string = std::visit([](auto & address) { return ip_address_to_string(address); - }, address); + }, + address); try { @@ -381,7 +379,7 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic return std::visit([port = service.port](auto & address) { return std::make_unique(address, port); }, - address); + address); } catch (std::exception & e) { @@ -434,7 +432,7 @@ void scenes::lobby::update_server_list() std::vector discovered_services = discover->get_services(); // TODO: only if discovered_services changed - for(auto& [cookie, data]: servers) + for (auto & [cookie, data]: servers) { data.visible = false; } @@ -442,7 +440,7 @@ void scenes::lobby::update_server_list() char protocol_string[17]; sprintf(protocol_string, "%016lx", xrt::drivers::wivrn::protocol_version); - for(auto& service: discovered_services) + for (auto & service: discovered_services) { std::string cookie; bool compatible = true; @@ -467,13 +465,15 @@ void scenes::lobby::update_server_list() if (server == servers.end()) { // Newly discovered server: add it to the list - servers.emplace(cookie, server_data{ - .autoconnect = false, - .manual = false, - .visible = true, - .compatible = compatible, - .service = service - }); + servers.emplace( + cookie, + server_data{ + .autoconnect = false, + .manual = false, + .visible = true, + .compatible = compatible, + .service = service, + }); } else { @@ -484,19 +484,21 @@ void scenes::lobby::update_server_list() } } -void scenes::lobby::connect(server_data& data) +void scenes::lobby::connect(server_data & data) { server_name = data.service.name; async_error.reset(); - async_session = utils::async, std::string>([](auto token, wivrn_discover::service service, bool manual) - { - token.set_progress("Waiting for connection"); - return connect_to_session(service, manual); - }, data.service, data.manual); + async_session = utils::async, std::string>( + [](auto token, wivrn_discover::service service, bool manual) { + token.set_progress("Waiting for connection"); + return connect_to_session(service, manual); + }, + data.service, + data.manual); } -static std::vector render_layer(std::vector& views, std::vector& swapchains, scene_renderer& renderer, scene_data& data, const std::array& clear_color) +static std::vector render_layer(std::vector & views, std::vector & swapchains, scene_renderer & renderer, scene_data & data, const std::array & clear_color) { std::vector frames; frames.reserve(views.size()); @@ -509,19 +511,23 @@ static std::vector render_layer(std::vectorset_current(); if (!async_session.valid() && !next_scene && !ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopup)) { - for(auto&& [cookie, data]: servers) + for (auto && [cookie, data]: servers) { if (data.visible && (data.autoconnect || force_autoconnect) && data.compatible) - { connect(data); - } } } @@ -591,7 +595,7 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render) { if (left_hand) { - auto& hand = application::get_left_hand(); + auto & hand = application::get_left_hand(); auto joints = hand.locate(world_space, predicted_display_time); left_hand->apply(joints); @@ -601,7 +605,7 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render) if (right_hand) { - auto& hand = application::get_right_hand(); + auto & hand = application::get_right_hand(); auto joints = hand.locate(world_space, predicted_display_time); right_hand->apply(joints); @@ -653,9 +657,11 @@ void scenes::lobby::render(XrTime predicted_display_time, bool should_render) if (passthrough_enabled) { - std::visit([&](auto& p){ - layers_base.push_back(p.layer()); - }, passthrough); + std::visit( + [&](auto & p) { + layers_base.push_back(p.layer()); + }, + passthrough); } else { @@ -708,25 +714,25 @@ void scenes::lobby::on_focused() if (application::get_hand_tracking_supported()) { - left_hand.emplace( "left-hand.glb", loader, *controllers_scene); + left_hand.emplace("left-hand.glb", loader, *controllers_scene); right_hand.emplace("right-hand.glb", loader, *controllers_scene); } std::array imgui_inputs{ - imgui_context::controller{ - .aim = get_action_space("left_aim"), - .trigger = get_action("left_trigger").first, - .squeeze = get_action("left_squeeze").first, - .scroll = get_action("left_scroll").first, - .hand = application::get_left_hand(), - }, - imgui_context::controller{ - .aim = get_action_space("right_aim"), - .trigger = get_action("right_trigger").first, - .squeeze = get_action("right_squeeze").first, - .scroll = get_action("right_scroll").first, - .hand = application::get_right_hand(), - }, + imgui_context::controller{ + .aim = get_action_space("left_aim"), + .trigger = get_action("left_trigger").first, + .squeeze = get_action("left_squeeze").first, + .scroll = get_action("left_scroll").first, + .hand = application::get_left_hand(), + }, + imgui_context::controller{ + .aim = get_action_space("right_aim"), + .trigger = get_action("right_trigger").first, + .squeeze = get_action("right_squeeze").first, + .scroll = get_action("right_scroll").first, + .hand = application::get_right_hand(), + }, }; swapchain_imgui = xr::swapchain(session, device, swapchain_format, 1500, 1000); @@ -736,7 +742,7 @@ void scenes::lobby::on_focused() { about_picture = imgui_ctx->load_texture("wivrn.ktx2"); } - catch(...) + catch (...) { about_picture = imgui_ctx->load_texture("wivrn.png"); } @@ -752,7 +758,7 @@ void scenes::lobby::on_focused() passthrough.emplace(instance, session); } - std::visit([](auto& p) {p.start();}, passthrough); + std::visit([](auto & p) { p.start(); }, passthrough); } } @@ -784,96 +790,95 @@ void scenes::lobby::on_session_state_changed(XrSessionState state) discover.reset(); } -scene::meta& scenes::lobby::get_meta_scene() +scene::meta & scenes::lobby::get_meta_scene() { static meta m{ - .name = "Lobby", - .actions = { - {"left_aim", XR_ACTION_TYPE_POSE_INPUT}, - {"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, - {"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, - {"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, - {"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, - {"right_aim", XR_ACTION_TYPE_POSE_INPUT}, - {"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, - {"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, - {"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, - {"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, - }, - .bindings = { - suggested_binding{ - "/interaction_profiles/oculus/touch_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - } - }, - suggested_binding{ - "/interaction_profiles/bytedance/pico_neo3_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - } - }, - suggested_binding{ - "/interaction_profiles/bytedance/pico4_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - } - }, - suggested_binding{ - "/interaction_profiles/htc/vive_focus3_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/trigger/value"}, - {"left_squeeze", "/user/hand/left/input/squeeze/value"}, - {"left_scroll", "/user/hand/left/input/thumbstick"}, - {"left_haptic", "/user/hand/left/output/haptic"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/trigger/value"}, - {"right_squeeze", "/user/hand/right/input/squeeze/value"}, - {"right_scroll", "/user/hand/right/input/thumbstick"}, - {"right_haptic", "/user/hand/right/output/haptic"}, - } - }, - suggested_binding{ - "/interaction_profiles/khr/simple_controller", - { - {"left_aim", "/user/hand/left/input/aim/pose"}, - {"left_trigger", "/user/hand/left/input/select/click"}, - {"left_squeeze", "/user/hand/left/input/menu/click"}, - {"right_aim", "/user/hand/right/input/aim/pose"}, - {"right_trigger", "/user/hand/right/input/select/click"}, - {"right_squeeze", "/user/hand/right/input/menu/click"}, - } - }, - } - }; + .name = "Lobby", + .actions = { + {"left_aim", XR_ACTION_TYPE_POSE_INPUT}, + {"left_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, + {"left_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, + {"left_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, + {"left_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, + {"right_aim", XR_ACTION_TYPE_POSE_INPUT}, + {"right_trigger", XR_ACTION_TYPE_FLOAT_INPUT}, + {"right_squeeze", XR_ACTION_TYPE_FLOAT_INPUT}, + {"right_scroll", XR_ACTION_TYPE_VECTOR2F_INPUT}, + {"right_haptic", XR_ACTION_TYPE_VIBRATION_OUTPUT}, + }, + .bindings = { + suggested_binding{ + "/interaction_profiles/oculus/touch_controller", + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/trigger/value"}, + {"left_squeeze", "/user/hand/left/input/squeeze/value"}, + {"left_scroll", "/user/hand/left/input/thumbstick"}, + {"left_haptic", "/user/hand/left/output/haptic"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/trigger/value"}, + {"right_squeeze", "/user/hand/right/input/squeeze/value"}, + {"right_scroll", "/user/hand/right/input/thumbstick"}, + {"right_haptic", "/user/hand/right/output/haptic"}, + }, + }, + suggested_binding{ + "/interaction_profiles/bytedance/pico_neo3_controller", + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/trigger/value"}, + {"left_squeeze", "/user/hand/left/input/squeeze/value"}, + {"left_scroll", "/user/hand/left/input/thumbstick"}, + {"left_haptic", "/user/hand/left/output/haptic"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/trigger/value"}, + {"right_squeeze", "/user/hand/right/input/squeeze/value"}, + {"right_scroll", "/user/hand/right/input/thumbstick"}, + {"right_haptic", "/user/hand/right/output/haptic"}, + }, + }, + suggested_binding{ + "/interaction_profiles/bytedance/pico4_controller", + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/trigger/value"}, + {"left_squeeze", "/user/hand/left/input/squeeze/value"}, + {"left_scroll", "/user/hand/left/input/thumbstick"}, + {"left_haptic", "/user/hand/left/output/haptic"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/trigger/value"}, + {"right_squeeze", "/user/hand/right/input/squeeze/value"}, + {"right_scroll", "/user/hand/right/input/thumbstick"}, + {"right_haptic", "/user/hand/right/output/haptic"}, + }, + }, + suggested_binding{ + "/interaction_profiles/htc/vive_focus3_controller", + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/trigger/value"}, + {"left_squeeze", "/user/hand/left/input/squeeze/value"}, + {"left_scroll", "/user/hand/left/input/thumbstick"}, + {"left_haptic", "/user/hand/left/output/haptic"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/trigger/value"}, + {"right_squeeze", "/user/hand/right/input/squeeze/value"}, + {"right_scroll", "/user/hand/right/input/thumbstick"}, + {"right_haptic", "/user/hand/right/output/haptic"}, + }, + }, + suggested_binding{ + "/interaction_profiles/khr/simple_controller", + { + {"left_aim", "/user/hand/left/input/aim/pose"}, + {"left_trigger", "/user/hand/left/input/select/click"}, + {"left_squeeze", "/user/hand/left/input/menu/click"}, + {"right_aim", "/user/hand/right/input/aim/pose"}, + {"right_trigger", "/user/hand/right/input/select/click"}, + {"right_squeeze", "/user/hand/right/input/menu/click"}, + }, + }, + }}; return m; } diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index b1ed1e43..65450911 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -21,18 +21,18 @@ #include "render/scene_data.h" #include "scene.h" -#include #include "scenes/hand_model.h" #include "wivrn_discover.h" +#include #include "xr/passthrough.h" +#include #include #include -#include -#include "render/scene_renderer.h" -#include "render/imgui_impl.h" #include "input_profile.h" +#include "render/imgui_impl.h" +#include "render/scene_renderer.h" #include "utils/async.h" class wivrn_session; @@ -73,7 +73,6 @@ class lobby : public scene_impl std::shared_ptr next_scene; std::string server_name; - std::optional renderer; std::optional lobby_scene; std::optional controllers_scene; @@ -130,7 +129,7 @@ class lobby : public scene_impl void vibrate_on_hover(); - void connect(server_data& data); + void connect(server_data & data); public: virtual ~lobby(); @@ -141,6 +140,6 @@ public: void on_focused() override; void on_session_state_changed(XrSessionState state) override; - static meta& get_meta_scene(); + static meta & get_meta_scene(); }; } // namespace scenes diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 4251fcb8..6a77c556 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -21,11 +21,11 @@ #include "application.h" #include "imgui.h" -#include "implot.h" #include "imgui_internal.h" +#include "implot.h" #include "lobby.h" -#include "version.h" #include "stream.h" +#include "version.h" #include #include @@ -35,7 +35,7 @@ #include "IconsFontAwesome6.h" -static void CenterTextH(const std::string& text) +static void CenterTextH(const std::string & text) { float win_width = ImGui::GetWindowSize().x; float text_width = ImGui::CalcTextSize(text.c_str()).x; @@ -44,20 +44,20 @@ static void CenterTextH(const std::string& text) ImGui::Text("%s", text.c_str()); } -static void CenterTextHV(const std::string& text) +static void CenterTextHV(const std::string & text) { ImVec2 size = ImGui::GetWindowSize(); std::vector lines = utils::split(text); float text_height = 0; - for(const auto& i: lines) + for (const auto & i: lines) text_height += ImGui::CalcTextSize(i.c_str()).y; ImGui::SetCursorPosY((size.y - text_height) / 2); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); - for(const auto& i: lines) + for (const auto & i: lines) { float text_width = ImGui::CalcTextSize(i.c_str()).x; ImGui::SetCursorPosX((size.x - text_width) / 2); @@ -98,7 +98,6 @@ void scenes::lobby::gui_connecting() ImGui::Dummy({1000, 1}); - ImGui::PushFont(imgui_ctx->large_font); CenterTextH(fmt::format("Connection to {}", server_name)); ImGui::PopFont(); @@ -175,19 +174,17 @@ void scenes::lobby::gui_add_server() if (ImGui::Button("Save", button_size)) { current_tab = tab::server_list; - server_data data - { - .manual = true, - .service = { - .name = add_server_window_prettyname, - .hostname = add_server_window_hostname, - .port = add_server_window_port, - }, + server_data data{ + .manual = true, + .service = { + .name = add_server_window_prettyname, + .hostname = add_server_window_hostname, + .port = add_server_window_port, + }, }; servers.emplace("manual-" + data.service.name, data); save_config(); - } vibrate_on_hover(); } @@ -196,14 +193,14 @@ void scenes::lobby::gui_server_list() { // Build an index of the cookies sorted by server name std::multimap sorted_cookies; - for(auto&& [cookie, data]: servers) + for (auto && [cookie, data]: servers) { sorted_cookies.emplace(data.service.name, cookie); } const ImVec2 button_size(220, 80); const float list_item_height = 100; - auto& style = ImGui::GetStyle(); + auto & style = ImGui::GetStyle(); std::string cookie_to_remove; if (sorted_cookies.empty()) @@ -220,9 +217,9 @@ void scenes::lobby::gui_server_list() ImGui::PushStyleColor(ImGuiCol_Header, 0); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, 0); ImGui::PushStyleColor(ImGuiCol_HeaderActive, 0); - for(const auto& [name, cookie]: sorted_cookies) + for (const auto & [name, cookie]: sorted_cookies) { - server_data& data = servers.at(cookie); + server_data & data = servers.at(cookie); bool is_selected = (cookie == selected_item); ImGui::SetCursorPos(pos); @@ -247,7 +244,7 @@ void scenes::lobby::gui_server_list() // TODO // if (ImGui::IsItemHovered()) // { - // ImGui::SetTooltip("Tooltip"); + // ImGui::SetTooltip("Tooltip"); // } ImVec2 button_position(ImGui::GetWindowContentRegionMax().x - style.WindowPadding.x - 20, pos.y + (list_item_height - button_size.y) / 2); @@ -259,15 +256,15 @@ void scenes::lobby::gui_server_list() ImGui::BeginDisabled(!enable_connect_button); if (enable_connect_button) { - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.8f, 0.3f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.8f, 0.3f, 0.40f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.8f, 0.3f, 1.00f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 1.0f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 1.0f, 0.2f, 1.00f)); } else { - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.4f, 0.3f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.4f, 0.3f, 0.40f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.2f, 0.4f, 0.3f, 1.00f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.5f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.1f, 0.5f, 0.2f, 1.00f)); } if (ImGui::Button(("Connect##" + cookie).c_str(), button_size)) { @@ -291,9 +288,9 @@ void scenes::lobby::gui_server_list() if (data.manual) { ImGui::SetCursorPos(button_position); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); if (ImGui::Button(("Remove##" + cookie).c_str(), button_size)) cookie_to_remove = cookie; @@ -316,13 +313,10 @@ void scenes::lobby::gui_server_list() if ((async_session.valid() || next_scene) && !ImGui::IsPopupOpen("connecting")) ImGui::OpenPopup("connecting"); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20,20)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20, 20)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 10); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 2); - if (ImGui::BeginPopupModal("connecting", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove)) + if (ImGui::BeginPopupModal("connecting", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove)) { gui_connecting(); ImGui::EndPopup(); @@ -404,11 +398,9 @@ void scenes::lobby::gui_settings() float win_width = ImGui::GetWindowSize().x; float win_height = ImGui::GetWindowSize().y; - ImVec2 plot_size{ - win_width / 2 - style.ItemSpacing.x / 2, - win_height / 2 - }; + win_width / 2 - style.ItemSpacing.x / 2, + win_height / 2}; static std::array cpu_time; static std::array gpu_time; @@ -417,7 +409,6 @@ void scenes::lobby::gui_settings() float min_v = 0; float max_v = 20; - cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6; gpu_time[offset] = renderer->get_gpu_time() * 1'000; offset = (offset + 1) % cpu_time.size(); @@ -428,7 +419,7 @@ void scenes::lobby::gui_settings() ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0)); ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); - if (ImPlot::BeginPlot("CPU time", plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) + if (ImPlot::BeginPlot("CPU time", plot_size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild)) { auto col = ImPlot::GetColormapColor(0); @@ -442,11 +433,11 @@ void scenes::lobby::gui_settings() ImGui::SameLine(); - if (ImPlot::BeginPlot("GPU time", plot_size, ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) + if (ImPlot::BeginPlot("GPU time", plot_size, ImPlotFlags_CanvasOnly | ImPlotFlags_NoChild)) { auto col = ImPlot::GetColormapColor(1); - ImPlot::SetupAxes(nullptr,"GPU time [ms]", ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxes(nullptr, "GPU time [ms]", ImPlotAxisFlags_NoDecorations, 0); ImPlot::SetupAxesLimits(0, gpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); ImPlot::SetNextLineStyle(col); ImPlot::SetNextFillStyle(col, 0.25); @@ -512,7 +503,7 @@ static bool RadioButtonWithoutCheckBox(const char * label, bool active, ImVec2 s return pressed; } -template +template static bool RadioButtonWithoutCheckBox(const char * label, T * v, T v_button, ImVec2 size_arg) { const bool pressed = RadioButtonWithoutCheckBox(label, *v == v_button, size_arg); @@ -524,8 +515,8 @@ static bool RadioButtonWithoutCheckBox(const char * label, T * v, T v_button, Im static void ScrollWhenDraggingOnVoid(ImVec2 delta) { // https://github.com/ocornut/imgui/issues/3379#issuecomment-1678718752 - ImGuiContext& g = *ImGui::GetCurrentContext(); - ImGuiWindow* window = g.CurrentWindow; + ImGuiContext & g = *ImGui::GetCurrentContext(); + ImGuiWindow * window = g.CurrentWindow; bool hovered = false; bool held = false; ImGuiID id = window->GetID("##scrolldraggingoverlay"); @@ -567,10 +558,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) // ImGui::SetNextWindowPos({0, 0}); // ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); - ImGui::Begin("WiVRn", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove); + ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); ImGui::SetCursorPos({MinTabWidth + 20, 0}); @@ -579,7 +567,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) ImGui::BeginChild("Main", ImVec2(ImGui::GetWindowSize().x - ImGui::GetCursorPosX(), 0)); ImGui::SetCursorPosY(20); - switch(current_tab) + switch (current_tab) { case tab::server_list: gui_server_list(); @@ -607,7 +595,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) ImGui::SetScrollY(0); } - ImGui::Dummy(ImVec2(0,20)); + ImGui::Dummy(ImVec2(0, 20)); ImVec2 mouse_delta = ImGui::GetIO().MouseDelta; ScrollWhenDraggingOnVoid(ImVec2(0.0f, -mouse_delta.y)); @@ -622,21 +610,20 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) static float TabWidth = MinTabWidth; ImGui::BeginChild("Tabs", {TabWidth, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y}); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10,10)); - RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " Server list", ¤t_tab, tab::server_list, {TabWidth, 0}); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10)); + RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " Server list", ¤t_tab, tab::server_list, {TabWidth, 0}); vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_GEARS " Settings", ¤t_tab, tab::settings, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_GEARS " Settings", ¤t_tab, tab::settings, {TabWidth, 0}); vibrate_on_hover(); - ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 2*ImGui::GetCurrentContext()->FontSize - 4*style.FramePadding.y - style.ItemSpacing.y - style.WindowPadding.y); + ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 2 * ImGui::GetCurrentContext()->FontSize - 4 * style.FramePadding.y - style.ItemSpacing.y - style.WindowPadding.y); RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " About", ¤t_tab, tab::about, {TabWidth, 0}); vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " Exit", ¤t_tab, tab::exit, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " Exit", ¤t_tab, tab::exit, {TabWidth, 0}); vibrate_on_hover(); - if (!ImGui::IsMouseDown(ImGuiMouseButton_Left)) { if (ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows)) @@ -651,7 +638,7 @@ XrCompositionLayerQuad scenes::lobby::draw_gui(XrTime predicted_display_time) ImGui::PopStyleColor(); // ImGuiCol_ChildBg ImGui::End(); ImGui::PopStyleColor(); // ImGuiCol_WindowBg - ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize + ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_ScrollbarSize if (hovered_item != last_hovered && hovered_item != 0) { diff --git a/client/scenes/lobby_keyboard.cpp b/client/scenes/lobby_keyboard.cpp index c90141d0..42313af5 100644 --- a/client/scenes/lobby_keyboard.cpp +++ b/client/scenes/lobby_keyboard.cpp @@ -38,84 +38,82 @@ struct key using keyboard_layout = std::vector>; keyboard_layout azerty = { - { - { 1, U"aàâæ" }, - { 1, U"z" }, - { 1, U"eéèêë" }, - { 1, U"r" }, - { 1, U"t" }, - { 1, U"yÿ" }, - { 1, U"uùûü" }, - { 1, U"iîï" }, - { 1, U"oôœ" }, - { 1, U"p" }, - { 2, U"", ImGuiKey_Backslash }, - }, - { - { 1, U"q" }, - { 1, U"s" }, - { 1, U"d" }, - { 1, U"f" }, - { 1, U"g" }, - { 1, U"h" }, - { 1, U"j" }, - { 1, U"k" }, - { 1, U"l" }, - { 1, U"m" }, - }, - { - { 2, U"", ImGuiKey_LeftShift }, - { 1, U"w" }, - { 1, U"x" }, - { 1, U"cç" }, - { 1, U"v" }, - { 1, U"b" }, - { 1, U"n" }, - { 1, U",?" }, - { 1, U";." }, - { 1, U":/" }, - { 1, U"!§" }, - } -}; + { + {1, U"aàâæ"}, + {1, U"z"}, + {1, U"eéèêë"}, + {1, U"r"}, + {1, U"t"}, + {1, U"yÿ"}, + {1, U"uùûü"}, + {1, U"iîï"}, + {1, U"oôœ"}, + {1, U"p"}, + {2, U"", ImGuiKey_Backslash}, + }, + { + {1, U"q"}, + {1, U"s"}, + {1, U"d"}, + {1, U"f"}, + {1, U"g"}, + {1, U"h"}, + {1, U"j"}, + {1, U"k"}, + {1, U"l"}, + {1, U"m"}, + }, + { + {2, U"", ImGuiKey_LeftShift}, + {1, U"w"}, + {1, U"x"}, + {1, U"cç"}, + {1, U"v"}, + {1, U"b"}, + {1, U"n"}, + {1, U",?"}, + {1, U";."}, + {1, U":/"}, + {1, U"!§"}, + }}; keyboard_layout symbols = { - { - { 1, U"1" }, - { 1, U"2" }, - { 1, U"3" }, - { 1, U"4" }, - { 1, U"5" }, - { 1, U"6" }, - { 1, U"7" }, - { 1, U"8" }, - { 1, U"9" }, - { 1, U"0" }, - }, - { - { 1, U"@" }, - { 1, U"#" }, - { 1, U"%" }, - { 1, U"&" }, - { 1, U"*" }, - { 1, U"_" }, - { 1, U"-" }, - { 1, U"+" }, - { 1, U"(" }, - { 1, U")" }, - }, - { - { 1, U"\"" }, - { 1, U"<" }, - { 1, U">" }, - { 1, U"'" }, - { 1, U"*" }, - { 1, U":" }, - { 1, U"/" }, - { 1, U"!" }, - { 1, U"?" }, - { 1, U"" }, - } -}; + { + {1, U"1"}, + {1, U"2"}, + {1, U"3"}, + {1, U"4"}, + {1, U"5"}, + {1, U"6"}, + {1, U"7"}, + {1, U"8"}, + {1, U"9"}, + {1, U"0"}, + }, + { + {1, U"@"}, + {1, U"#"}, + {1, U"%"}, + {1, U"&"}, + {1, U"*"}, + {1, U"_"}, + {1, U"-"}, + {1, U"+"}, + {1, U"("}, + {1, U")"}, + }, + { + {1, U"\""}, + {1, U"<"}, + {1, U">"}, + {1, U"'"}, + {1, U"*"}, + {1, U":"}, + {1, U"/"}, + {1, U"!"}, + {1, U"?"}, + {1, U""}, + }}; static std::string to_utf8(char32_t c) { @@ -147,144 +145,152 @@ static std::string to_utf8(char32_t c) return s; } -static bool button_behavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) +static bool button_behavior(const ImRect & bb, ImGuiID id, bool * out_hovered, bool * out_held, ImGuiButtonFlags flags) { - ImGuiContext& g = *GImGui; - ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImGuiContext & g = *GImGui; + ImGuiWindow * window = ImGui::GetCurrentWindow(); - // Default behavior inherited from item flags - // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that. - ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags); - if (flags & ImGuiButtonFlags_AllowOverlap) - item_flags |= ImGuiItemFlags_AllowOverlap; - if (flags & ImGuiButtonFlags_Repeat) - item_flags |= ImGuiItemFlags_ButtonRepeat; + // Default behavior inherited from item flags + // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that. + ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags); + if (flags & ImGuiButtonFlags_AllowOverlap) + item_flags |= ImGuiItemFlags_AllowOverlap; + if (flags & ImGuiButtonFlags_Repeat) + item_flags |= ImGuiItemFlags_ButtonRepeat; - bool pressed = false; - bool hovered = ImGui::ItemHoverable(bb, id, item_flags); + bool pressed = false; + bool hovered = ImGui::ItemHoverable(bb, id, item_flags); - // Mouse handling - const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id; - if (hovered) - { - // Poll mouse buttons - // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. - // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. - int mouse_button_clicked = -1; - int mouse_button_released = -1; - for (int button = 0; button < 3; button++) - if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here. - { - if (ImGui::IsMouseClicked(button, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; } - if (ImGui::IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; } - } + // Mouse handling + const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id; + if (hovered) + { + // Poll mouse buttons + // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. + // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. + int mouse_button_clicked = -1; + int mouse_button_released = -1; + for (int button = 0; button < 3; button++) + if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here. + { + if (ImGui::IsMouseClicked(button, test_owner_id) && mouse_button_clicked == -1) + { + mouse_button_clicked = button; + } + if (ImGui::IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) + { + mouse_button_released = button; + } + } - // Process initial action - if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) - { - if (mouse_button_clicked != -1 && g.ActiveId != id) - { - if (!(flags & ImGuiButtonFlags_NoSetKeyOwner)) - ImGui::SetKeyOwner(ImGui::MouseButtonToKey(mouse_button_clicked), id); - if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere)) - { - // ImGui::SetActiveID(id, window); - g.ActiveIdMouseButton = mouse_button_clicked; - if (!(flags & ImGuiButtonFlags_NoNavFocus)) - ImGui::SetFocusID(id, window); - ImGui::FocusWindow(window); - } - if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2)) - { - pressed = true; - // if (flags & ImGuiButtonFlags_NoHoldingActiveId) - // ImGui::ClearActiveID(); - // else - // ImGui::SetActiveID(id, window); // Hold on ID - if (!(flags & ImGuiButtonFlags_NoNavFocus)) - ImGui::SetFocusID(id, window); - g.ActiveIdMouseButton = mouse_button_clicked; - ImGui::FocusWindow(window); - } - } - if (flags & ImGuiButtonFlags_PressedOnRelease) - { - if (mouse_button_released != -1) - { - const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior - if (!has_repeated_at_least_once) - pressed = true; - if (!(flags & ImGuiButtonFlags_NoNavFocus)) - ImGui::SetFocusID(id, window); - // ImGui::ClearActiveID(); - } - } + // Process initial action + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + { + if (mouse_button_clicked != -1 && g.ActiveId != id) + { + if (!(flags & ImGuiButtonFlags_NoSetKeyOwner)) + ImGui::SetKeyOwner(ImGui::MouseButtonToKey(mouse_button_clicked), id); + if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere)) + { + // ImGui::SetActiveID(id, window); + g.ActiveIdMouseButton = mouse_button_clicked; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + ImGui::SetFocusID(id, window); + ImGui::FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2)) + { + pressed = true; + // if (flags & ImGuiButtonFlags_NoHoldingActiveId) + // ImGui::ClearActiveID(); + // else + // ImGui::SetActiveID(id, window); // Hold on ID + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + ImGui::SetFocusID(id, window); + g.ActiveIdMouseButton = mouse_button_clicked; + ImGui::FocusWindow(window); + } + } + if (flags & ImGuiButtonFlags_PressedOnRelease) + { + if (mouse_button_released != -1) + { + const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior + if (!has_repeated_at_least_once) + pressed = true; + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + ImGui::SetFocusID(id, window); + // ImGui::ClearActiveID(); + } + } - // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). - // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. - if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat)) - if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && ImGui::IsMouseClicked(g.ActiveIdMouseButton, test_owner_id, ImGuiInputFlags_Repeat)) - pressed = true; - } + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat)) + if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && ImGui::IsMouseClicked(g.ActiveIdMouseButton, test_owner_id, ImGuiInputFlags_Repeat)) + pressed = true; + } - if (pressed) - g.NavDisableHighlight = true; - } + if (pressed) + g.NavDisableHighlight = true; + } - // Process while held - bool held = false; - if (g.ActiveId == id) - { - if (g.ActiveIdSource == ImGuiInputSource_Mouse) - { - if (g.ActiveIdIsJustActivated) - g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; + // Process while held + bool held = false; + if (g.ActiveId == id) + { + if (g.ActiveIdSource == ImGuiInputSource_Mouse) + { + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; - const int mouse_button = g.ActiveIdMouseButton; - if (mouse_button == -1) - { - // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304). - // ImGui::ClearActiveID(); - } - else if (ImGui::IsMouseDown(mouse_button, test_owner_id)) - { - held = true; - } - else - { - bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0; - bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; - if ((release_in || release_anywhere) && !g.DragDropActive) - { - // Report as pressed when releasing the mouse (this is the most common path) - bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2; - bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps - bool is_button_avail_or_owned = ImGui::TestKeyOwner(ImGui::MouseButtonToKey(mouse_button), test_owner_id); - if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned) - pressed = true; - } - // ImGui::ClearActiveID(); - } - if (!(flags & ImGuiButtonFlags_NoNavFocus)) - g.NavDisableHighlight = true; - } - else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) - { - // When activated using Nav, we hold on the ActiveID until activation button is released - // if (g.NavActivateDownId != id) - // ImGui::ClearActiveID(); - } - if (pressed) - g.ActiveIdHasBeenPressedBefore = true; - } + const int mouse_button = g.ActiveIdMouseButton; + if (mouse_button == -1) + { + // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304). + // ImGui::ClearActiveID(); + } + else if (ImGui::IsMouseDown(mouse_button, test_owner_id)) + { + held = true; + } + else + { + bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0; + bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0; + if ((release_in || release_anywhere) && !g.DragDropActive) + { + // Report as pressed when releasing the mouse (this is the most common path) + bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2; + bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps + bool is_button_avail_or_owned = ImGui::TestKeyOwner(ImGui::MouseButtonToKey(mouse_button), test_owner_id); + if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned) + pressed = true; + } + // ImGui::ClearActiveID(); + } + if (!(flags & ImGuiButtonFlags_NoNavFocus)) + g.NavDisableHighlight = true; + } + else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) + { + // When activated using Nav, we hold on the ActiveID until activation button is released + // if (g.NavActivateDownId != id) + // ImGui::ClearActiveID(); + } + if (pressed) + g.ActiveIdHasBeenPressedBefore = true; + } - if (out_hovered) *out_hovered = hovered; - if (out_held) *out_held = held; + if (out_hovered) + *out_hovered = hovered; + if (out_held) + *out_held = held; - return pressed; + return pressed; } -static void draw_single_key(const key& k, int key_id, ImVec2 size_arg) +static void draw_single_key(const key & k, int key_id, ImVec2 size_arg) { std::string label = k.characters == U"" ? "" : to_utf8(k.characters[0]); label += "##virtual_keyboard_key_" + std::to_string(key_id); @@ -293,12 +299,12 @@ static void draw_single_key(const key& k, int key_id, ImVec2 size_arg) int flags = (int)ImGuiButtonFlags_PressedOnClickRelease | (int)ImGuiButtonFlags_MouseButtonLeft | (int)ImGuiButtonFlags_NoNavFocus; - ImGuiWindow* window = ImGui::GetCurrentWindow(); + ImGuiWindow * window = ImGui::GetCurrentWindow(); if (window->SkipItems) return /*false*/; - ImGuiContext& g = *GImGui; - const ImGuiStyle& style = g.Style; + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; const ImGuiID id = window->GetID(label.c_str()); const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true); @@ -316,46 +322,40 @@ static void draw_single_key(const key& k, int key_id, ImVec2 size_arg) [[maybe_unused]] bool pressed = button_behavior(bb, id, &hovered, &held, flags); // Render - const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 col = ImGui::GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered + : ImGuiCol_Button); ImGui::RenderNavHighlight(bb, id); ImGui::RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); // if (g.LogEnabled) - // LogSetNextTextDecoration("[", "]"); + // LogSetNextTextDecoration("[", "]"); ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups - //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); // IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags); // return pressed; - - - - - - - } void scenes::lobby::gui_keyboard(ImVec2 size) { - const keyboard_layout& layout = azerty; + const keyboard_layout & layout = azerty; int nb_rows = layout.size(); ImVec2 position = ImGui::GetCursorPos(); - ImGuiStyle& style = ImGui::GetStyle(); + ImGuiStyle & style = ImGui::GetStyle(); std::vector keys_width; // Size of a key including margin, scaled by the key width later ImVec2 key_size{FLT_MAX, (size.y + style.FramePadding.y) / nb_rows}; - for(const auto& row: layout) + for (const auto & row: layout) { float total_width = 0; - for(auto& key: row) + for (auto & key: row) total_width += key.width; keys_width.push_back(total_width); @@ -364,11 +364,11 @@ void scenes::lobby::gui_keyboard(ImVec2 size) } int id = 0; - for(const auto& [row, width]: utils::zip(layout, keys_width)) + for (const auto & [row, width]: utils::zip(layout, keys_width)) { ImVec2 key_position = position; - for(const auto& key: row) + for (const auto & key: row) { if (key.visible) { diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index f3ff37ea..c1f49a36 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -21,11 +21,14 @@ #include "stream.h" #include "application.h" +#include "audio/audio.h" +#include "boost/pfr/core.hpp" #include "decoder/shard_accumulator.h" +#include "hardware.h" #include "spdlog/spdlog.h" +#include "utils/named_thread.h" #include "utils/ranges.h" #include "utils/sync_queue.h" -#include "utils/named_thread.h" #include "vk/pipeline.h" #include "vk/shader.h" #include "wivrn_packets.h" @@ -33,9 +36,6 @@ #include #include #include -#include "boost/pfr/core.hpp" -#include "audio/audio.h" -#include "hardware.h" using namespace xrt::drivers::wivrn; @@ -69,15 +69,14 @@ static const std::unordered_map device_ids = { // clang-format on static const std::array supported_formats = -{ - vk::Format::eR8G8B8A8Srgb, - vk::Format::eB8G8R8A8Srgb -}; + { + vk::Format::eR8G8B8A8Srgb, + vk::Format::eB8G8R8A8Srgb}; std::shared_ptr scenes::stream::create(std::unique_ptr network_session, bool show_performance_metrics, bool enable_microphone) { std::shared_ptr self{new stream}; - spdlog::info("decoder_mutex.native_handle() = {}", (void*)self->decoder_mutex.native_handle()); + spdlog::info("decoder_mutex.native_handle() = {}", (void *)self->decoder_mutex.native_handle()); self->network_session = std::move(network_session); self->show_performance_metrics = show_performance_metrics; @@ -94,7 +93,9 @@ std::shared_ptr scenes::stream::create(std::unique_ptrinstance.now(), application::view()); + assert(views.size() == info.fov.size()); + for (auto [i, j]: utils::zip(views, info.fov)) { j = i.fov; @@ -122,9 +123,11 @@ std::shared_ptr scenes::stream::create(std::unique_ptrvideo_thread = utils::named_thread("video_thread", &stream::video, self.get()); self->command_buffer = std::move(self->device.allocateCommandBuffers({ - .commandPool = *self->commandpool, - .level = vk::CommandBufferLevel::ePrimary, - .commandBufferCount = 1})[0]); + .commandPool = *self->commandpool, + .level = vk::CommandBufferLevel::ePrimary, + .commandBufferCount = 1, + })[0]); + self->fence = self->device.createFence({.flags = vk::FenceCreateFlagBits::eSignaled}); // Look up the XrActions for haptics @@ -166,7 +169,12 @@ std::shared_ptr scenes::stream::create(std::unique_ptrswapchain_format)); - self->query_pool = vk::raii::QueryPool(self->device, vk::QueryPoolCreateInfo{.queryType = vk::QueryType::eTimestamp, .queryCount = size_gpu_timestamps}); + self->query_pool = vk::raii::QueryPool( + self->device, + vk::QueryPoolCreateInfo{ + .queryType = vk::QueryType::eTimestamp, + .queryCount = size_gpu_timestamps, + }); return self; } @@ -176,21 +184,22 @@ void scenes::stream::on_focused() if (show_performance_metrics) { swapchain_imgui = xr::swapchain( - session, - device, - swapchain_format, - 1500, 1000); + session, + device, + swapchain_format, + 1500, + 1000); imgui_ctx.emplace(physical_device, - device, - queue_family_index, - queue, - view_space, - std::span{}, - swapchain_imgui, - glm::vec2{1.0, 0.6666}); + device, + queue_family_index, + queue, + view_space, + std::span{}, + swapchain_imgui, + glm::vec2{1.0, 0.6666}); - imgui_ctx->set_position({0,0,-1}, {1,0,0,0}); + imgui_ctx->set_position({0, 0, -1}, {1, 0, 0, 0}); } assert(video_stream_description); @@ -231,9 +240,9 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p if (i.decoder.get() == decoder) { std::swap(removed, i.latest_frames[0]); - for (size_t j = 1 ; j < i.latest_frames.size() ; ++j) + for (size_t j = 1; j < i.latest_frames.size(); ++j) { - std::swap(i.latest_frames[j-1], i.latest_frames[j]); + std::swap(i.latest_frames[j - 1], i.latest_frames[j]); } std::swap(i.latest_frames.back(), handle); break; @@ -276,8 +285,7 @@ std::optional scenes::stream::accumulator_images::common_frame(const s { std::vector tmp; auto x = set.frames(); - std::set_intersection( - x.begin(), x.end(), common_frames.begin(), common_frames.end(), std::back_inserter(tmp)); + std::ranges::set_intersection(x, common_frames, std::back_inserter(tmp)); common_frames = tmp; if (common_frames.empty()) return {}; @@ -294,8 +302,10 @@ std::shared_ptr scenes::stream::accumulator_imag { if (not *it) continue; + if (id and (*it)->feedback.frame_index != *id) continue; + return *it; } return nullptr; @@ -357,7 +367,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) })[0] .release(); - const auto& description = i.decoder->desc(); + const auto & description = i.decoder->desc(); vk::Extent2D image_size = i.decoder->image_size(); std::array useful_size{ float(description.width) / image_size.width, @@ -416,8 +426,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) .topology = vk::PrimitiveTopology::eTriangleStrip, }}, .ViewportState = {.flags = {}}, - .Viewports = {{}}, - .Scissors = {{}}, + .Viewports = {{}}, + .Scissors = {{}}, .RasterizationState = {{ .polygonMode = vk::PolygonMode::eFill, .lineWidth = 1, @@ -440,6 +450,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) throw std::runtime_error("Vulkan fence timeout"); + device.resetFences(*fence); // We don't need those after vkWaitForFences @@ -449,15 +460,15 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) if (query_pool_filled) { auto [res, timestamps2] = query_pool.getResults( - 0, - size_gpu_timestamps, - size_gpu_timestamps * sizeof(uint64_t), - sizeof(uint64_t), - vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); + 0, + size_gpu_timestamps, + size_gpu_timestamps * sizeof(uint64_t), + sizeof(uint64_t), + vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait); if (res == vk::Result::eSuccess) { - boost::pfr::for_each_field(timestamps, [n = 1, ×tamps2](float& t) mutable { + boost::pfr::for_each_field(timestamps, [n = 1, ×tamps2](float & t) mutable { t = (timestamps2[n++] - timestamps2[0]) * application::get_physical_device_properties().limits.timestampPeriod / 1e9; }); } @@ -497,8 +508,10 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) // Search for the most recent frame available on all decoders. // If no such frame exists, use the latest frame for each decoder auto common_frame = accumulator_images::common_frame(decoders, next_frame); + if (common_frame) next_frame = *common_frame + 1; + // Blit images from the decoders for (auto & i: decoders) { @@ -541,19 +554,19 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) .oldLayout = *blit_handle->current_layout, .newLayout = vk::ImageLayout::eGeneral, .image = blit_handle->image, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .levelCount = 1, - .layerCount = 1, - }, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .levelCount = 1, + .layerCount = 1, + }, }; + command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, barrier); *blit_handle->current_layout = vk::ImageLayout::eGeneral; } } } - uint16_t x_offset = 0; for (auto & out: decoder_output) { @@ -588,7 +601,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) .width = (float)description.width, .height = (float)description.height, .minDepth = 0, - .maxDepth = 1}; + .maxDepth = 1, + }; x0 = std::clamp(x0, 0, out.size.width); x1 = std::clamp(x1, 0, out.size.width); @@ -639,15 +653,23 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) { swapchains[swapchain_index].release(); - layer_view[swapchain_index].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW; + layer_view[swapchain_index] = + { + .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, + .pose = views[swapchain_index].pose, + .fov = views[swapchain_index].fov, - layer_view[swapchain_index].pose = views[swapchain_index].pose; - layer_view[swapchain_index].fov = views[swapchain_index].fov; - - layer_view[swapchain_index].subImage.swapchain = swapchains[swapchain_index]; - layer_view[swapchain_index].subImage.imageRect.offset = {0, 0}; - layer_view[swapchain_index].subImage.imageRect.extent.width = swapchains[swapchain_index].width(); - layer_view[swapchain_index].subImage.imageRect.extent.height = swapchains[swapchain_index].height(); + .subImage = { + .swapchain = swapchains[swapchain_index], + .imageRect = { + .offset = {0, 0}, + .extent = { + swapchains[swapchain_index].width(), + swapchains[swapchain_index].height(), + }, + }, + }, + }; } float brightness = std::clamp(dbrightness * (predicted_display_time - first_frame_time) / 1.e9, 0, 1); @@ -655,7 +677,8 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) XrCompositionLayerColorScaleBiasKHR color_scale_bias{ .type = XR_TYPE_COMPOSITION_LAYER_COLOR_SCALE_BIAS_KHR, .colorScale = {brightness, brightness, brightness, 1}, - .colorBias = {}}; + .colorBias = {}, + }; XrCompositionLayerProjection layer{ .type = XR_TYPE_COMPOSITION_LAYER_PROJECTION, @@ -683,7 +706,7 @@ void scenes::stream::render(XrTime predicted_display_time, bool should_render) session.end_frame(/*timestamp*/ predicted_display_time, layers_base); // Network operations may be blocking, do them once everything was submitted - for (const auto& handle: current_blit_handles) + for (const auto & handle: current_blit_handles) send_feedback(handle->feedback); read_actions(); @@ -753,37 +776,37 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript decoder_output[i].size.height = video_height; vk::ImageCreateInfo image_info{ - .flags = vk::ImageCreateFlags{}, - .imageType = vk::ImageType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .extent = decoder_out_size, - .mipLevels = 1, - .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e1, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, - .sharingMode = vk::SharingMode::eExclusive, - .initialLayout = vk::ImageLayout::eUndefined, + .flags = vk::ImageCreateFlags{}, + .imageType = vk::ImageType::e2D, + .format = vk::Format::eA8B8G8R8SrgbPack32, + .extent = decoder_out_size, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment, + .sharingMode = vk::SharingMode::eExclusive, + .initialLayout = vk::ImageLayout::eUndefined, }; VmaAllocationCreateInfo alloc_info{ - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, }; decoder_output[i].image = image_allocation{device, image_info, alloc_info}; vk::ImageViewCreateInfo image_view_info{ - .image = vk::Image{decoder_output[i].image}, - .viewType = vk::ImageViewType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .components = {}, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .image = vk::Image{decoder_output[i].image}, + .viewType = vk::ImageViewType::e2D, + .format = vk::Format::eA8B8G8R8SrgbPack32, + .components = {}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; decoder_output[i].image_view = vk::raii::ImageView(device, image_view_info); @@ -912,12 +935,11 @@ void scenes::stream::video() } } -scene::meta& scenes::stream::get_meta_scene() +scene::meta & scenes::stream::get_meta_scene() { static meta m{ - "Stream", - {} - }; + "Stream", + {}}; return m; } diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 22e842c1..7ca2dd5e 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -19,7 +19,9 @@ #pragma once +#include "audio/audio.h" #include "decoder/shard_accumulator.h" +#include "render/imgui_impl.h" #include "scene.h" #include "stream_reprojection.h" #include "utils/sync_queue.h" @@ -28,8 +30,6 @@ #include #include #include -#include "audio/audio.h" -#include "render/imgui_impl.h" namespace scenes { @@ -82,7 +82,7 @@ private: std::mutex decoder_mutex; std::optional video_stream_description; - uint64_t next_frame; // Preferred index for next frame + uint64_t next_frame; // Preferred index for next frame std::vector decoders; // Locked by decoder_mutex vk::raii::DescriptorPool blit_descriptor_pool = nullptr; vk::raii::RenderPass blit_render_pass = nullptr; @@ -124,13 +124,13 @@ public: void on_focused() override; void on_unfocused() override; - void operator()(to_headset::handshake&&) {}; + void operator()(to_headset::handshake &&){}; void operator()(to_headset::video_stream_data_shard &&); void operator()(to_headset::haptics &&); void operator()(to_headset::timesync_query &&); void operator()(to_headset::audio_stream_description &&); void operator()(to_headset::video_stream_description &&); - void operator()(audio_data&&); + void operator()(audio_data &&); void push_blit_handle(shard_accumulator * decoder, std::shared_ptr handle); @@ -138,7 +138,7 @@ public: state current_state() const { - return state_ ; + return state_; } bool alive() const @@ -146,7 +146,7 @@ public: return !exiting; } - static meta& get_meta_scene(); + static meta & get_meta_scene(); private: void process_packets(); @@ -179,7 +179,6 @@ private: float cpu_time = 0; float bandwidth_rx = 0; float bandwidth_tx = 0; - }; struct plot @@ -215,7 +214,7 @@ private: XrTime last_metric_time = 0; int metrics_offset = 0; - void accumulate_metrics(XrTime predicted_display_time, const std::vector>& blit_handles, const gpu_timestamps& timestamps); + void accumulate_metrics(XrTime predicted_display_time, const std::vector> & blit_handles, const gpu_timestamps & timestamps); XrCompositionLayerQuad plot_performance_metrics(XrTime predicted_display_time); }; } // namespace scenes diff --git a/client/scenes/stream_actions.cpp b/client/scenes/stream_actions.cpp index 0ccfcd40..2889c0d3 100644 --- a/client/scenes/stream_actions.cpp +++ b/client/scenes/stream_actions.cpp @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "stream.h" #include "application.h" +#include "stream.h" #include void scenes::stream::read_actions() diff --git a/client/scenes/stream_network.cpp b/client/scenes/stream_network.cpp index 54b98977..6a374d51 100644 --- a/client/scenes/stream_network.cpp +++ b/client/scenes/stream_network.cpp @@ -65,7 +65,7 @@ void scenes::stream::operator()(to_headset::timesync_query && query) network_session->send_stream(response); } -void scenes::stream::operator()(audio_data&& data) +void scenes::stream::operator()(audio_data && data) { if (audio_handle) (*audio_handle)(std::move(data)); diff --git a/client/scenes/stream_reprojection.cpp b/client/scenes/stream_reprojection.cpp index eb3993de..53e02ef3 100644 --- a/client/scenes/stream_reprojection.cpp +++ b/client/scenes/stream_reprojection.cpp @@ -20,12 +20,12 @@ #include "stream_reprojection.h" #include "application.h" #include "vk/allocation.h" -#include "vk/shader.h" #include "vk/pipeline.h" -#include +#include "vk/shader.h" #include #include #include +#include #include #include #include @@ -43,31 +43,38 @@ struct stream_reprojection::uniform const int nb_reprojection_vertices = 64; -stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector input_images_, std::vector 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) +stream_reprojection::stream_reprojection( + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, + std::vector input_images_, + std::vector 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) { foveation_parameters = description.foveation; vk::PhysicalDeviceProperties properties = physical_device.getProperties(); vk::SamplerCreateInfo sampler_info{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eNearest, - .addressModeU = vk::SamplerAddressMode::eClampToBorder, - .addressModeV = vk::SamplerAddressMode::eClampToBorder, - .addressModeW = vk::SamplerAddressMode::eClampToBorder, - .mipLodBias = 0.0f, - .anisotropyEnable = VK_FALSE, - .maxAnisotropy = 1, - .compareEnable = VK_FALSE, - .compareOp = vk::CompareOp::eNever, - .minLod = 0.0f, - .maxLod = 0.0f, - .borderColor = vk::BorderColor::eFloatOpaqueBlack, - .unnormalizedCoordinates = VK_FALSE, + .magFilter = vk::Filter::eLinear, + .minFilter = vk::Filter::eLinear, + .mipmapMode = vk::SamplerMipmapMode::eNearest, + .addressModeU = vk::SamplerAddressMode::eClampToBorder, + .addressModeV = vk::SamplerAddressMode::eClampToBorder, + .addressModeW = vk::SamplerAddressMode::eClampToBorder, + .mipLodBias = 0.0f, + .anisotropyEnable = VK_FALSE, + .maxAnisotropy = 1, + .compareEnable = VK_FALSE, + .compareOp = vk::CompareOp::eNever, + .minLod = 0.0f, + .maxLod = 0.0f, + .borderColor = vk::BorderColor::eFloatOpaqueBlack, + .unnormalizedCoordinates = VK_FALSE, }; sampler = vk::raii::Sampler(device, sampler_info); @@ -76,13 +83,13 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy uniform_size = uniform_size - uniform_size % properties.limits.minUniformBufferOffsetAlignment; vk::BufferCreateInfo create_info{ - .size = uniform_size * input_images.size(), - .usage = vk::BufferUsageFlagBits::eUniformBuffer, - .sharingMode = vk::SharingMode::eExclusive, + .size = uniform_size * input_images.size(), + .usage = vk::BufferUsageFlagBits::eUniformBuffer, + .sharingMode = vk::SharingMode::eExclusive, }; VmaAllocationCreateInfo alloc_info{ - .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + .requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, }; buffer = buffer_allocation(device, create_info, alloc_info); @@ -92,18 +99,18 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy // Create VkDescriptorSetLayout std::array layout_binding{ - vk::DescriptorSetLayoutBinding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - }, - vk::DescriptorSetLayoutBinding{ - .binding = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, - } + vk::DescriptorSetLayoutBinding{ + .binding = 0, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .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; @@ -119,7 +126,7 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy vk::DescriptorPoolSize{ .type = vk::DescriptorType::eUniformBuffer, .descriptorCount = (uint32_t)input_images.size(), - } + }, }; vk::DescriptorPoolCreateInfo pool_info; @@ -136,87 +143,86 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy for (vk::Image image: input_images) { vk::ImageViewCreateInfo iv_info{ - .image = image, - .viewType = vk::ImageViewType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .components = { - .r = vk::ComponentSwizzle::eIdentity, - .g = vk::ComponentSwizzle::eIdentity, - .b = vk::ComponentSwizzle::eIdentity, - .a = vk::ComponentSwizzle::eIdentity, - }, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } + .image = image, + .viewType = vk::ImageViewType::e2D, + .format = vk::Format::eA8B8G8R8SrgbPack32, + .components = { + .r = vk::ComponentSwizzle::eIdentity, + .g = vk::ComponentSwizzle::eIdentity, + .b = vk::ComponentSwizzle::eIdentity, + .a = vk::ComponentSwizzle::eIdentity, + }, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; input_image_views.emplace_back(device, iv_info); vk::DescriptorSetAllocateInfo ds_info{ - .descriptorPool = *descriptor_pool, - .descriptorSetCount = 1, - .pSetLayouts = &*descriptor_set_layout, + .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, + .sampler = *sampler, + .imageView = *input_image_views.back(), + .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; vk::DescriptorBufferInfo buffer_info{ - .buffer = buffer, - .offset = offset, - .range = sizeof(uniform), + .buffer = buffer, + .offset = offset, + .range = sizeof(uniform), }; offset += uniform_size; std::array write{ - vk::WriteDescriptorSet{ - .dstSet = descriptor_sets.back(), - .dstBinding = 0, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info, - }, - vk::WriteDescriptorSet{ - .dstSet = descriptor_sets.back(), - .dstBinding = 1, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &buffer_info, - } + vk::WriteDescriptorSet{ + .dstSet = descriptor_sets.back(), + .dstBinding = 0, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = &image_info, + }, + vk::WriteDescriptorSet{ + .dstSet = descriptor_sets.back(), + .dstBinding = 1, + .dstArrayElement = 0, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info, + }, }; - device.updateDescriptorSets(write, {}); } // Create renderpass vk::AttachmentReference color_ref{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, + .attachment = 0, + .layout = vk::ImageLayout::eColorAttachmentOptimal, }; vk::AttachmentDescription attachment{ - .format = format, - .samples = vk::SampleCountFlagBits::e1, - .loadOp = vk::AttachmentLoadOp::eDontCare, - .storeOp = vk::AttachmentStoreOp::eStore, - .initialLayout = vk::ImageLayout::eColorAttachmentOptimal, - .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, + .format = format, + .samples = vk::SampleCountFlagBits::e1, + .loadOp = vk::AttachmentLoadOp::eDontCare, + .storeOp = vk::AttachmentStoreOp::eStore, + .initialLayout = vk::ImageLayout::eColorAttachmentOptimal, + .finalLayout = vk::ImageLayout::eColorAttachmentOptimal, }; vk::SubpassDescription subpass{ - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, + .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, }; subpass.setColorAttachments(color_ref); @@ -226,45 +232,42 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy renderpass = vk::raii::RenderPass(device, renderpass_info); - // Create graphics pipeline vk::raii::ShaderModule vertex_shader = load_shader(device, "reprojection.vert"); vk::raii::ShaderModule fragment_shader = load_shader(device, "reprojection.frag"); - vk::PipelineLayoutCreateInfo pipeline_layout_info; pipeline_layout_info.setSetLayouts(*descriptor_set_layout); layout = vk::raii::PipelineLayout(device, pipeline_layout_info); int use_foveation[] = { - foveation_parameters[0].x.scale < 1, - foveation_parameters[0].y.scale < 1, - nb_reprojection_vertices, - nb_reprojection_vertices - }; + foveation_parameters[0].x.scale < 1, + foveation_parameters[0].y.scale < 1, + nb_reprojection_vertices, + nb_reprojection_vertices}; std::array specialization_constants_desc{ - vk::SpecializationMapEntry{ - .constantID = 0, - .offset = 0, - .size = sizeof(int), - }, - vk::SpecializationMapEntry{ - .constantID = 1, - .offset = sizeof(int), - .size = sizeof(int), - }, - vk::SpecializationMapEntry{ - .constantID = 2, - .offset = 2 * sizeof(int), - .size = sizeof(int), - }, - vk::SpecializationMapEntry{ - .constantID = 3, - .offset = 3 * sizeof(int), - .size = sizeof(int), - } + vk::SpecializationMapEntry{ + .constantID = 0, + .offset = 0, + .size = sizeof(int), + }, + vk::SpecializationMapEntry{ + .constantID = 1, + .offset = sizeof(int), + .size = sizeof(int), + }, + vk::SpecializationMapEntry{ + .constantID = 2, + .offset = 2 * sizeof(int), + .size = sizeof(int), + }, + vk::SpecializationMapEntry{ + .constantID = 3, + .offset = 3 * sizeof(int), + .size = sizeof(int), + }, }; vk::SpecializationInfo specialization_info; @@ -272,53 +275,59 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy specialization_info.setMapEntries(specialization_constants_desc); specialization_info.setData(use_foveation); - vk::pipeline_builder pipeline_info - { - .flags = {}, - .Stages = {{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - .pSpecializationInfo = &specialization_info, - },{ - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - .pSpecializationInfo = &specialization_info, - }}, - .VertexInputState = {.flags = {}}, - .VertexBindingDescriptions = {}, - .VertexAttributeDescriptions = {}, - .InputAssemblyState = {{ - .topology = vk::PrimitiveTopology::eTriangleList, - }}, - .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 | vk::ColorComponentFlagBits::eA - }}, - .layout = *layout, - .renderPass = *renderpass, - .subpass = 0, + vk::pipeline_builder pipeline_info{ + .flags = {}, + .Stages = { + { + .stage = vk::ShaderStageFlagBits::eVertex, + .module = *vertex_shader, + .pName = "main", + .pSpecializationInfo = &specialization_info, + }, + { + .stage = vk::ShaderStageFlagBits::eFragment, + .module = *fragment_shader, + .pName = "main", + .pSpecializationInfo = &specialization_info, + }, + }, + .VertexInputState = { + .flags = {}, + }, + .VertexBindingDescriptions = {}, + .VertexAttributeDescriptions = {}, + .InputAssemblyState = {{ + .topology = vk::PrimitiveTopology::eTriangleList, + }}, + .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 | vk::ColorComponentFlagBits::eA, + }}, + .layout = *layout, + .renderPass = *renderpass, + .subpass = 0, }; pipeline = vk::raii::Pipeline(device, application::get_pipeline_cache(), pipeline_info); @@ -329,31 +338,31 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy for (vk::Image image: output_images) { vk::ImageViewCreateInfo iv_info{ - .image = image, - .viewType = vk::ImageViewType::e2D, - .format = format, - .components = { - .r = vk::ComponentSwizzle::eIdentity, - .g = vk::ComponentSwizzle::eIdentity, - .b = vk::ComponentSwizzle::eIdentity, - .a = vk::ComponentSwizzle::eIdentity, - }, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, + .image = image, + .viewType = vk::ImageViewType::e2D, + .format = format, + .components = { + .r = vk::ComponentSwizzle::eIdentity, + .g = vk::ComponentSwizzle::eIdentity, + .b = vk::ComponentSwizzle::eIdentity, + .a = vk::ComponentSwizzle::eIdentity, + }, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, }; output_image_views.emplace_back(device, iv_info); vk::FramebufferCreateInfo fb_create_info{ - .renderPass = *renderpass, - .width = extent.width, - .height = extent.height, - .layers = 1, + .renderPass = *renderpass, + .width = extent.width, + .height = extent.height, + .layers = 1, }; fb_create_info.setAttachments(*output_image_views.back()); @@ -361,7 +370,7 @@ stream_reprojection::stream_reprojection(vk::raii::Device& device, vk::raii::Phy } } -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) +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()) throw std::runtime_error("Invalid source image index"); @@ -382,31 +391,33 @@ void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int { (l+r)/(r-l), (t+b)/(b-t), -1, -1 }, { 0, 0, -2*zn, 0 } }; + // clang-format on glm::mat4 hmd_unview = glm::mat4_cast(glm::quat( - dest_pose.w, - dest_pose.x, - dest_pose.y, - dest_pose.z)); + dest_pose.w, + dest_pose.x, + dest_pose.y, + dest_pose.z)); r = tan(source_fov.angleRight); l = tan(source_fov.angleLeft); t = tan(source_fov.angleUp); b = tan(source_fov.angleDown); + // clang-format off glm::mat4 video_proj{ { 2/(r-l), 0, 0, 0 }, { 0, 2/(b-t), 0, 0 }, { (l+r)/(r-l), (t+b)/(b-t), -1, -1 }, { 0, 0, -2*zn, 0 } }; + // clang-format on glm::mat4 video_view = glm::mat4_cast(glm::quat( - -source_pose.w, - source_pose.x, - source_pose.y, - source_pose.z)); - // clang-format on + -source_pose.w, + source_pose.x, + source_pose.y, + source_pose.z)); ubo[source]->reprojection = video_proj * video_view * hmd_unview * glm::inverse(hmd_proj); @@ -421,12 +432,12 @@ void stream_reprojection::reproject(vk::raii::CommandBuffer& command_buffer, int ubo[source]->xc.y = foveation_parameters[source].y.center; vk::RenderPassBeginInfo begin_info{ - .renderPass = *renderpass, - .framebuffer = *framebuffers[destination], - .renderArea = { - .offset = {0, 0}, - .extent = extent, - }, + .renderPass = *renderpass, + .framebuffer = *framebuffers[destination], + .renderArea = { + .offset = {0, 0}, + .extent = extent, + }, }; command_buffer.pipelineBarrier( diff --git a/client/scenes/stream_reprojection.h b/client/scenes/stream_reprojection.h index 72610234..989bef3d 100644 --- a/client/scenes/stream_reprojection.h +++ b/client/scenes/stream_reprojection.h @@ -21,9 +21,8 @@ #include "vk/allocation.h" #include "wivrn_packets.h" -#include -#include #include +#include class stream_reprojection { @@ -56,8 +55,23 @@ class stream_reprojection std::array foveation_parameters; public: - stream_reprojection(vk::raii::Device& device, vk::raii::PhysicalDevice& physical_device, std::vector input_images, std::vector output_images, vk::Extent2D extent, vk::Format format, const xrt::drivers::wivrn::to_headset::video_stream_description & description); + stream_reprojection( + vk::raii::Device & device, + vk::raii::PhysicalDevice & physical_device, + std::vector input_images, + std::vector output_images, + vk::Extent2D extent, + vk::Format format, + const xrt::drivers::wivrn::to_headset::video_stream_description & description); + stream_reprojection(const stream_reprojection &) = delete; - 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( + vk::raii::CommandBuffer & command_buffer, + int source, + int destination, + XrQuaternionf source_pose, + XrFovf source_fov, + XrQuaternionf destination_pose, + XrFovf destination_fov); }; diff --git a/client/scenes/stream_stats.cpp b/client/scenes/stream_stats.cpp index 07a8d259..f2afb379 100644 --- a/client/scenes/stream_stats.cpp +++ b/client/scenes/stream_stats.cpp @@ -25,8 +25,8 @@ #include "implot.h" #include "utils/ranges.h" #include -#include #include +#include namespace { @@ -34,9 +34,9 @@ float compute_plot_max_value(float * data, int count, ptrdiff_t stride) { float max = 0; uintptr_t ptr = (uintptr_t)data; - for(int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { - max = std::max(max, *(float*)(ptr + i * stride)); + max = std::max(max, *(float *)(ptr + i * stride)); } // First power of 10 less than the max @@ -47,18 +47,18 @@ float compute_plot_max_value(float * data, int count, ptrdiff_t stride) std::pair compute_plot_unit(float max_value) { if (max_value > 1e9) - return { 1e-9, "G" }; + return {1e-9, "G"}; if (max_value > 1e6) - return { 1e-6, "M" }; + return {1e-6, "M"}; if (max_value > 1e3) - return { 1e-3, "k" }; + return {1e-3, "k"}; if (max_value > 1) - return { 1, "" }; + return {1, ""}; if (max_value > 1e-3) - return { 1e3, "m" }; + return {1e3, "m"}; if (max_value > 1e-6) - return { 1e6, "u" }; - return { 1e9, "n" }; + return {1e6, "u"}; + return {1e9, "n"}; } struct getter_data @@ -72,15 +72,15 @@ struct getter_data ImPlotPoint getter(int index, void * data_) { - getter_data& data = *(getter_data*)data_; + getter_data & data = *(getter_data *)data_; int offset_index = (index + data.offset) % data.count; - return ImPlotPoint(index, *(float*)(data.data + offset_index * data.stride) * data.multiplier); -} + return ImPlotPoint(index, *(float *)(data.data + offset_index * data.stride) * data.multiplier); } +} // namespace -void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector>& blit_handles, const gpu_timestamps& timestamps) +void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std::vector> & blit_handles, const gpu_timestamps & timestamps) { uint64_t rx = network_session->bytes_received(); uint64_t tx = network_session->bytes_sent(); @@ -88,13 +88,13 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std float dt = (predicted_display_time - last_metric_time) * 1e-9f; bandwidth_rx = 0.8 * bandwidth_rx + 0.2 * float(rx - bytes_received) / dt; - bandwidth_tx = 0.8 * bandwidth_tx + 0.2 * float(tx - bytes_sent ) /dt; + bandwidth_tx = 0.8 * bandwidth_tx + 0.2 * float(tx - bytes_sent) / dt; last_metric_time = predicted_display_time; bytes_received = rx; bytes_sent = tx; - *(gpu_timestamps*)&global_metrics[metrics_offset] = timestamps; + *(gpu_timestamps *)&global_metrics[metrics_offset] = timestamps; global_metrics[metrics_offset].cpu_time = application::get_cpu_time().count() * 1e-9f; global_metrics[metrics_offset].bandwidth_rx = bandwidth_rx * 8; global_metrics[metrics_offset].bandwidth_tx = bandwidth_tx * 8; @@ -103,15 +103,16 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std decoder_metrics.resize(blit_handles.size()); auto min_encode_begin = std::numeric_limitstiming_info.encode_begin)>::max(); - for(const auto& bh: blit_handles) + for (const auto & bh: blit_handles) min_encode_begin = std::min(min_encode_begin, bh->timing_info.encode_begin); - for(auto&& [metrics, bh]: utils::zip(decoder_metrics, blit_handles)) + for (auto && [metrics, bh]: utils::zip(decoder_metrics, blit_handles)) { if (metrics.size() != global_metrics.size()) metrics.resize(global_metrics.size()); metrics[metrics_offset] = decoder_metric{ + // clang-format off .send_begin = (bh->timing_info.send_begin - min_encode_begin) * 1e-9f, .send_end = (bh->timing_info.send_end - min_encode_begin) * 1e-9f, .received_first_packet = (bh->feedback.received_first_packet - min_encode_begin) * 1e-9f, @@ -120,6 +121,7 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std .received_from_decoder = (bh->feedback.received_from_decoder - min_encode_begin) * 1e-9f, .blitted = (bh->feedback.blitted - min_encode_begin) * 1e-9f, .displayed = (bh->feedback.displayed - min_encode_begin) * 1e-9f, + // clang-format on }; } @@ -133,28 +135,20 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted ImGui::SetNextWindowPos({0, 0}); ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size); - ImGui::Begin("Performance metrics", nullptr, - ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove); + ImGui::Begin("Performance metrics", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); - ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2,2) * style.WindowPadding; + ImVec2 window_size = ImGui::GetWindowSize() - ImVec2(2, 2) * style.WindowPadding; static const std::array plots = { - plot("CPU time", { - {"", &global_metric::cpu_time}, - }, - "s"), - plot("GPU time", { - {"Reproject", &global_metric::gpu_time}, - {"Blit", &global_metric::gpu_barrier}, - }, - "s"), - plot("Network", { - {"Download", &global_metric::bandwidth_rx}, - {"Upload", &global_metric::bandwidth_tx}, - }, - "bit/s"), + // clang-format off + plot("CPU time", {{"", &global_metric::cpu_time}}, "s"), + + plot("GPU time", {{"Reproject", &global_metric::gpu_time}, + {"Blit", &global_metric::gpu_barrier}}, "s"), + + plot("Network", {{"Download", &global_metric::bandwidth_rx}, + {"Upload", &global_metric::bandwidth_tx}}, "bit/s"), + // clang-format on }; int n_plots = plots.size() + decoders.size(); @@ -164,8 +158,8 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted int n_rows = ceil((float)n_plots / n_cols); ImVec2 plot_size = ImVec2( - window_size.x / n_cols - style.ItemSpacing.x * (n_cols-1) / n_cols, - window_size.y / n_rows - style.ItemSpacing.y * (n_rows-1) / n_rows); + window_size.x / n_cols - style.ItemSpacing.x * (n_cols - 1) / n_cols, + window_size.y / n_rows - style.ItemSpacing.y * (n_rows - 1) / n_rows); ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64)); ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0)); @@ -174,17 +168,17 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); int n = 0; - for(const auto& [title, subplots, unit]: plots) + for (const auto & [title, subplots, unit]: plots) { if (ImPlot::BeginPlot(title, plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild)) { float min_v = 0; float max_v = 0; - for (const auto& [subtitle, data]: subplots) + for (const auto & [subtitle, data]: subplots) { max_v = std::max(max_v, compute_plot_max_value(&(global_metrics.data()->*data), global_metrics.size(), sizeof(global_metric))); } - auto [ multiplier, prefix ] = compute_plot_unit(max_v); + auto [multiplier, prefix] = compute_plot_unit(max_v); if (axis_scale[n] == 0 || std::isnan(axis_scale[n])) axis_scale[n] = max_v; @@ -199,7 +193,7 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted ImPlot::SetNextLineStyle(color); ImPlot::SetNextFillStyle(color, 0.25); - for (const auto& [subtitle, data]: subplots) + for (const auto & [subtitle, data]: subplots) { getter_data gdata{ .data = (uintptr_t) & (global_metrics.data()->*data), @@ -217,7 +211,7 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted ImGui::SameLine(); } - for(auto&& [index, metrics]: utils::enumerate(decoder_metrics)) + for (auto && [index, metrics]: utils::enumerate(decoder_metrics)) { std::string title = "Decoder " + std::to_string(index); if (ImPlot::BeginPlot(title.c_str(), plot_size, ImPlotFlags_NoTitle | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText | ImPlotFlags_NoChild)) @@ -235,83 +229,75 @@ XrCompositionLayerQuad scenes::stream::plot_performance_metrics(XrTime predicted ImPlot::SetupAxes(nullptr, title_with_units, ImPlotAxisFlags_NoDecorations, 0); ImPlot::SetupAxesLimits(0, metrics.size() - 1, min_v * 1e3f, axis_scale[n] * 1e3f, ImGuiCond_Always); - getter_data getter_send_begin{ - .data = (uintptr_t)&(metrics.data()->send_begin), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->send_begin), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_send_end{ - .data = (uintptr_t)&(metrics.data()->send_end), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->send_end), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_received_first_packet{ - .data = (uintptr_t)&(metrics.data()->received_first_packet), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->received_first_packet), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_received_last_packet{ - .data = (uintptr_t)&(metrics.data()->received_last_packet), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->received_last_packet), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_sent_to_decoder{ - .data = (uintptr_t)&(metrics.data()->sent_to_decoder), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->sent_to_decoder), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_received_from_decoder{ - .data = (uintptr_t)&(metrics.data()->received_from_decoder), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->received_from_decoder), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_blitted{ - .data = (uintptr_t)&(metrics.data()->blitted), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->blitted), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; getter_data getter_displayed{ - .data = (uintptr_t)&(metrics.data()->displayed), - .stride = sizeof(decoder_metric), - .offset = metrics_offset, - .count = (int)metrics.size(), - .multiplier = 1e3f - }; + .data = (uintptr_t) & (metrics.data()->displayed), + .stride = sizeof(decoder_metric), + .offset = metrics_offset, + .count = (int)metrics.size(), + .multiplier = 1e3f}; + // clang-format off ImPlot::PlotShadedG("Send", getter, &getter_send_begin, getter, &getter_send_end, metrics.size()); ImPlot::PlotShadedG("Receive", getter, &getter_received_first_packet, getter, &getter_received_last_packet, metrics.size()); ImPlot::PlotShadedG("Decode", getter, &getter_sent_to_decoder, getter, &getter_received_from_decoder, metrics.size()); ImPlot::PlotLineG("Blitted", getter, &getter_blitted, metrics.size()); ImPlot::PlotLineG("Displayed", getter, &getter_displayed, metrics.size()); + // clang-format on ImPlot::EndPlot(); } if (++n % n_cols != 0) ImGui::SameLine(); - } ImPlot::PopStyleColor(5); diff --git a/client/scenes/stream_tracking.cpp b/client/scenes/stream_tracking.cpp index dff75251..ea9a9f42 100644 --- a/client/scenes/stream_tracking.cpp +++ b/client/scenes/stream_tracking.cpp @@ -17,20 +17,22 @@ * along with this program. If not, see . */ +#include "application.h" #include "stream.h" #include "utils/ranges.h" -#include "application.h" -#include #include +#include static from_headset::tracking::pose locate_space(device_id device, XrSpace space, XrSpace reference, XrTime time) { XrSpaceVelocity velocity{ - .type = XR_TYPE_SPACE_VELOCITY}; + .type = XR_TYPE_SPACE_VELOCITY, + }; XrSpaceLocation location{ .type = XR_TYPE_SPACE_LOCATION, - .next = &velocity}; + .next = &velocity, + }; xrLocateSpace(space, reference, time, &location); @@ -63,20 +65,20 @@ static from_headset::tracking::pose locate_space(device_id device, XrSpace space return res; } -static std::optional> locate_hands(xr::hand_tracker& hand, XrSpace space, XrTime time) +static std::optional> locate_hands(xr::hand_tracker & hand, XrSpace space, XrTime time) { auto joints = hand.locate(space, time); if (joints) { std::array poses; - for(int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { poses[i] = { - .pose = (*joints)[i].first.pose, - .linear_velocity = (*joints)[i].second.linearVelocity, - .angular_velocity = (*joints)[i].second.angularVelocity, - .radius = (*joints)[i].first.radius, + .pose = (*joints)[i].first.pose, + .linear_velocity = (*joints)[i].second.linearVelocity, + .angular_velocity = (*joints)[i].second.angularVelocity, + .radius = (*joints)[i].first.radius, }; if ((*joints)[i].first.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) @@ -115,8 +117,8 @@ void scenes::stream::tracking() XrSpace view_space = application::view(); const XrDuration tracking_period = 1'000'000; // Send tracking data every 1ms - const XrDuration dt = 100'000; // Wake up 0.1ms before measuring the position - const XrDuration extrapolation_horizon = 1; // 50'000'000; + const XrDuration dt = 100'000; // Wake up 0.1ms before measuring the position + const XrDuration extrapolation_horizon = 1; // 50'000'000; XrTime t0 = instance.now(); t0 = t0 - t0 % tracking_period; diff --git a/client/utils/alignment.h b/client/utils/alignment.h index d2727360..e0514265 100644 --- a/client/utils/alignment.h +++ b/client/utils/alignment.h @@ -23,10 +23,10 @@ namespace utils { - template - requires std::integral - T align_up(T alignment, T value) - { - return ((value + alignment - 1) / alignment) * alignment; - } +template + requires std::integral +T align_up(T alignment, T value) +{ + return ((value + alignment - 1) / alignment) * alignment; } +} // namespace utils diff --git a/client/utils/async.h b/client/utils/async.h index 1f0353e1..e40e0851 100644 --- a/client/utils/async.h +++ b/client/utils/async.h @@ -19,213 +19,215 @@ #pragma once #include -#include +// #include +#include #include #include #include -#include #include -#include +#include #include namespace utils { - enum class future_status +enum class future_status +{ + ready, + timeout +}; + +template +struct async_token; + +template +struct future; + +template +future async(F && f, Args &&... args); + +template +struct future +{ + friend struct async_token; + + template + friend future async(F && f, Args &&... args); + + struct state { - ready, - timeout - }; + std::mutex lock; + std::condition_variable cv; - template - struct async_token; + std::optional result; + Progress progress; + std::exception_ptr exception; + std::atomic cancelled = false; - template - struct future; + std::thread thread; - template - future async(F&& f, Args&&...args); - - - template - struct future - { - friend struct async_token; - - template friend future async(F&& f, Args&&...args); - - struct state + ~state() { - std::mutex lock; - std::condition_variable cv; - - std::optional result; - Progress progress; - std::exception_ptr exception; - std::atomic cancelled = false; - - std::thread thread; - - ~state() + if (thread.joinable()) { - if (thread.joinable()) - { - if (thread.get_id() == std::this_thread::get_id()) - thread.detach(); - else - thread.join(); - } + if (thread.get_id() == std::this_thread::get_id()) + thread.detach(); + else + thread.join(); } - }; - - std::shared_ptr shared_state; - - public: - bool valid() const - { - return (bool)shared_state; - } - - future_status poll() const - { - assert(valid()); - - std::unique_lock _{shared_state->lock}; - - if (shared_state->result || shared_state->exception) - return future_status::ready; - else - return future_status::timeout; - } - - // future_status wait_until(std::chrono::steady_clock::time_point deadline) const - // { - // assert(valid()); - // - // std::unique_lock _{shared_state->lock}; - // auto now = std::chrono::steady_clock::now(); - // while(now < deadline) - // { - // if (shared_state->result || shared_state->exception) - // return future_status::ready; - // - // shared_state->cv.wait_until(_, deadline); - // } - // return future_status::timeout; - // } - // - // future_status wait_for(std::chrono::steady_clock::duration duration) const - // { - // return wait_until(std::chrono::steady_clock::now() + duration); - // } - - Result get() - { - assert(valid()); - - std::unique_lock _{shared_state->lock}; - shared_state->cv.wait(_, [&]{ - return shared_state->result || shared_state->exception; - }); - - if (shared_state->thread.joinable()) - shared_state->thread.join(); - - if (shared_state->result) - return std::move(*shared_state->result); - - std::rethrow_exception(shared_state->exception); - } - - Progress get_progress() - { - assert(valid()); - std::unique_lock _{shared_state->lock}; - return shared_state->progress; - } - - void cancel() - { - if (!valid()) - return; - - shared_state->cancelled = true; - - shared_state.reset(); - } - - void reset() - { - shared_state.reset(); } }; - template - struct async_token + std::shared_ptr shared_state; + +public: + bool valid() const { - template friend future async(F&& f, Args&&...args); - - using state = typename future::state; - std::shared_ptr shared_state; - - async_token(std::shared_ptr shared_state) : shared_state(shared_state) - { - } - - async_token(const async_token&) = default; - async_token(async_token&&) = default; - async_token& operator=(const async_token&) = default; - async_token& operator=(async_token&&) = default; - - void set_result(Result&& r) - { - assert(shared_state); - std::unique_lock _{shared_state->lock}; - shared_state->result = std::move(r); - shared_state->cv.notify_all(); - } - - void set_exception(std::exception_ptr&& e) - { - assert(shared_state); - std::unique_lock _{shared_state->lock}; - shared_state->exception = std::move(e); - shared_state->cv.notify_all(); - } - - public: - void set_progress(Progress&& p) - { - assert(shared_state); - std::unique_lock _{shared_state->lock}; - shared_state->progress = std::move(p); - shared_state->cv.notify_all(); - } - - bool is_cancelled() - { - return shared_state->cancelled; - } - }; - - template - future async(F&& f, Args&&...args) - { - future fut; - - fut.shared_state = std::make_shared::state>(); - - fut.shared_state->thread = std::thread([f, args...](auto token) - { - try - { - token.set_result(std::invoke(f, token, args...)); - } - catch(...) - { - token.set_exception(std::current_exception()); - } - }, async_token(fut.shared_state)); - - return fut; + return (bool)shared_state; } + + future_status poll() const + { + assert(valid()); + + std::unique_lock _{shared_state->lock}; + + if (shared_state->result || shared_state->exception) + return future_status::ready; + else + return future_status::timeout; + } + + // future_status wait_until(std::chrono::steady_clock::time_point deadline) const + // { + // assert(valid()); + // + // std::unique_lock _{shared_state->lock}; + // auto now = std::chrono::steady_clock::now(); + // while(now < deadline) + // { + // if (shared_state->result || shared_state->exception) + // return future_status::ready; + // + // shared_state->cv.wait_until(_, deadline); + // } + // return future_status::timeout; + // } + // + // future_status wait_for(std::chrono::steady_clock::duration duration) const + // { + // return wait_until(std::chrono::steady_clock::now() + duration); + // } + + Result get() + { + assert(valid()); + + std::unique_lock _{shared_state->lock}; + shared_state->cv.wait(_, [&] { + return shared_state->result || shared_state->exception; + }); + + if (shared_state->thread.joinable()) + shared_state->thread.join(); + + if (shared_state->result) + return std::move(*shared_state->result); + + std::rethrow_exception(shared_state->exception); + } + + Progress get_progress() + { + assert(valid()); + std::unique_lock _{shared_state->lock}; + return shared_state->progress; + } + + void cancel() + { + if (!valid()) + return; + + shared_state->cancelled = true; + + shared_state.reset(); + } + + void reset() + { + shared_state.reset(); + } +}; + +template +struct async_token +{ + template + friend future async(F && f, Args &&... args); + + using state = typename future::state; + std::shared_ptr shared_state; + + async_token(std::shared_ptr shared_state) : + shared_state(shared_state) + { + } + + async_token(const async_token &) = default; + async_token(async_token &&) = default; + async_token & operator=(const async_token &) = default; + async_token & operator=(async_token &&) = default; + + void set_result(Result && r) + { + assert(shared_state); + std::unique_lock _{shared_state->lock}; + shared_state->result = std::move(r); + shared_state->cv.notify_all(); + } + + void set_exception(std::exception_ptr && e) + { + assert(shared_state); + std::unique_lock _{shared_state->lock}; + shared_state->exception = std::move(e); + shared_state->cv.notify_all(); + } + +public: + void set_progress(Progress && p) + { + assert(shared_state); + std::unique_lock _{shared_state->lock}; + shared_state->progress = std::move(p); + shared_state->cv.notify_all(); + } + + bool is_cancelled() + { + return shared_state->cancelled; + } +}; + +template +future async(F && f, Args &&... args) +{ + future fut; + + fut.shared_state = std::make_shared::state>(); + + fut.shared_state->thread = std::thread([f, args...](auto token) { + try + { + token.set_result(std::invoke(f, token, args...)); + } + catch (...) + { + token.set_exception(std::current_exception()); + } + }, + async_token(fut.shared_state)); + + return fut; } +} // namespace utils diff --git a/client/utils/backtrace.h b/client/utils/backtrace.h index 88ab0faf..39ba2940 100644 --- a/client/utils/backtrace.h +++ b/client/utils/backtrace.h @@ -19,9 +19,9 @@ #pragma once +#include #include #include -#include namespace utils { diff --git a/client/utils/contains.h b/client/utils/contains.h index 982b8d4c..362c99b9 100644 --- a/client/utils/contains.h +++ b/client/utils/contains.h @@ -23,8 +23,8 @@ namespace utils { -template -bool contains(Rng&& range, const T& value) +template +bool contains(Rng && range, const T & value) { auto it = std::find(range.begin(), range.end(), value); @@ -32,10 +32,10 @@ bool contains(Rng&& range, const T& value) } // Check if all values of range2 are in range1 -template -bool contains_all(Rng1&& range1, Rng2&& range2) +template +bool contains_all(Rng1 && range1, Rng2 && range2) { - for(const auto& i: range2) + for (const auto & i: range2) { if (!contains(range1, i)) return false; @@ -44,4 +44,4 @@ bool contains_all(Rng1&& range1, Rng2&& range2) return true; } -} +} // namespace utils diff --git a/client/utils/files.h b/client/utils/files.h index 14a0cfdb..7fef9e61 100644 --- a/client/utils/files.h +++ b/client/utils/files.h @@ -20,12 +20,10 @@ #include #include -#include -#include namespace utils { -template +template static std::vector read_whole_file(std::filesystem::path filename) { std::ifstream file(filename, std::ios::binary | std::ios::ate); @@ -34,7 +32,7 @@ static std::vector read_whole_file(std::filesystem::path filename) size_t size = file.tellg(); file.seekg(0); - if constexpr(sizeof(T) > 1) + if constexpr (sizeof(T) > 1) size = size - size % sizeof(T); std::vector bytes(size / sizeof(T)); @@ -44,8 +42,8 @@ static std::vector read_whole_file(std::filesystem::path filename) return bytes; } -template -requires std::contiguous_iterator +template + requires std::contiguous_iterator static void write_whole_file(std::filesystem::path filename, T bytes) { std::ofstream file(filename, std::ios::binary); @@ -53,4 +51,4 @@ static void write_whole_file(std::filesystem::path filename, T bytes) file.write(reinterpret_cast(bytes.data()), bytes.size() * sizeof(typename T::value_type)); } -} +} // namespace utils diff --git a/client/utils/fmt_glm.h b/client/utils/fmt_glm.h index c066b003..e81a7e5b 100644 --- a/client/utils/fmt_glm.h +++ b/client/utils/fmt_glm.h @@ -18,13 +18,12 @@ #pragma once -#include #include - +#include // /usr/include/fmt/chrono.h:2017 -template +template struct fmt::formatter, Char> //: fmt::formatter { // auto parse(basic_format_parse_context& ctx) const -> decltype(ctx.begin()) @@ -37,14 +36,13 @@ struct fmt::formatter, Char> //: fmt::formatter // return begin; // } - auto parse(basic_format_parse_context& ctx) const // -> decltype(ctx.begin()) + auto parse(basic_format_parse_context & ctx) const // -> decltype(ctx.begin()) { return ctx.begin(); } - template - auto format(const glm::vec& v, FormatContext& ctx) const -> decltype(ctx.out()) + auto format(const glm::vec & v, FormatContext & ctx) const -> decltype(ctx.out()) { if constexpr (L == 1) { @@ -66,11 +64,8 @@ struct fmt::formatter, Char> //: fmt::formatter return fmt::format_to(ctx.out(), "[ {}, {}, {}, {} ]", v.x, v.y, v.z, v.w); } - - // return formatter( - // auto time = std::tm(); // time.tm_wday = static_cast(wd.c_encoding()); // detail::get_locale loc(localized, ctx.locale()); @@ -78,25 +73,21 @@ struct fmt::formatter, Char> //: fmt::formatter // w.on_abbr_weekday(); // return w.out(); } - }; - -template +template struct fmt::formatter, Char> { - - auto parse(basic_format_parse_context& ctx) const // -> decltype(ctx.begin()) + auto parse(basic_format_parse_context & ctx) const // -> decltype(ctx.begin()) { return ctx.begin(); } template - auto format(const glm::qua& q, FormatContext& ctx) const -> decltype(ctx.out()) + auto format(const glm::qua & q, FormatContext & ctx) const -> decltype(ctx.out()) { return fmt::format_to(ctx.out(), "[ {}, {}, {}, {} ]", q.w, q.x, q.y, q.z); } - }; /* diff --git a/client/utils/magic_hash.h b/client/utils/magic_hash.h index b6bd0424..73b2799b 100644 --- a/client/utils/magic_hash.h +++ b/client/utils/magic_hash.h @@ -19,22 +19,23 @@ #pragma once +#include #include #include #include -#include namespace utils { -template -struct is_vk_flags : std::false_type {}; +template +struct is_vk_flags : std::false_type +{}; -template -struct is_vk_flags> : std::true_type {}; +template +struct is_vk_flags> : std::true_type +{}; - -template +template struct magic_hash { std::size_t operator()(const T & info) const noexcept @@ -42,7 +43,6 @@ struct magic_hash size_t h = 0; boost::pfr::for_each_field(info, [&](const auto & member) { - using U = std::remove_cvref_t; if constexpr (is_vk_flags::value) @@ -61,4 +61,4 @@ struct magic_hash return h; } }; -} +} // namespace utils diff --git a/client/utils/ranges.h b/client/utils/ranges.h index c7e149aa..3d260d92 100644 --- a/client/utils/ranges.h +++ b/client/utils/ranges.h @@ -26,33 +26,35 @@ namespace utils { - template - concept has_const_iterator = requires { - std::declval(); - }; +template +concept has_const_iterator = requires { + std::declval(); +}; - template struct get_const_iterator_aux; +template +struct get_const_iterator_aux; - template struct get_const_iterator_aux - { - using const_iterator = T::const_iterator; - }; +template +struct get_const_iterator_aux +{ + using const_iterator = T::const_iterator; +}; - template struct get_const_iterator_aux - { - using const_iterator = T::iterator; - }; - - template - using get_const_iterator = get_const_iterator_aux>::const_iterator; +template +struct get_const_iterator_aux +{ + using const_iterator = T::iterator; +}; +template +using get_const_iterator = get_const_iterator_aux>::const_iterator; template struct enumerate_range { struct iterator { - using underlying_iterator = std::conditional_t, get_const_iterator, typename T::iterator>; + using underlying_iterator = std::conditional_t, get_const_iterator, typename T::iterator>; using underlying_value_type = std::conditional_t, const typename T::value_type, typename T::value_type>; size_t index; diff --git a/client/vk/fwd.h b/client/vk/fwd.h index 61c0a246..7b579b6d 100644 --- a/client/vk/fwd.h +++ b/client/vk/fwd.h @@ -21,9 +21,9 @@ namespace vk::raii { - class ImageView; - class PhysicalDevice; - class Device; - class Queue; - class CommandPool; -} +class ImageView; +class PhysicalDevice; +class Device; +class Queue; +class CommandPool; +} // namespace vk::raii diff --git a/client/vk/pipeline.h b/client/vk/pipeline.h index a793db94..d346aded 100644 --- a/client/vk/pipeline.h +++ b/client/vk/pipeline.h @@ -73,23 +73,23 @@ public: 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 + .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, }; } }; diff --git a/client/vk/shader.cpp b/client/vk/shader.cpp index 1c5ea73d..b7d5d89d 100644 --- a/client/vk/shader.cpp +++ b/client/vk/shader.cpp @@ -19,17 +19,17 @@ #include "shader.h" -vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector & spirv) +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector & spirv) { vk::ShaderModuleCreateInfo create_info{ - .codeSize = spirv.size() * sizeof(uint32_t), - .pCode = data(spirv), + .codeSize = spirv.size() * sizeof(uint32_t), + .pCode = data(spirv), }; return vk::raii::ShaderModule{device, create_info}; } -vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::string & name) +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name) { return load_shader(device, shaders.at(name)); } diff --git a/client/vk/shader.h b/client/vk/shader.h index ec95fe49..ad0fe78b 100644 --- a/client/vk/shader.h +++ b/client/vk/shader.h @@ -26,5 +26,5 @@ extern const std::map> shaders; -vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::vector & spirv); -vk::raii::ShaderModule load_shader(vk::raii::Device& device, const std::string & name); +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::vector & spirv); +vk::raii::ShaderModule load_shader(vk::raii::Device & device, const std::string & name); diff --git a/client/wivrn_client.cpp b/client/wivrn_client.cpp index 33141ba0..6e8ebc9a 100644 --- a/client/wivrn_client.cpp +++ b/client/wivrn_client.cpp @@ -35,7 +35,7 @@ using namespace std::chrono_literals; void wivrn_session::handshake() { - //Wait for handshake on control socket, then send ours on stream socket + // Wait for handshake on control socket, then send ours on stream socket pollfd fds{}; fds.events = POLLIN; fds.fd = control.get_fd(); @@ -69,7 +69,6 @@ void wivrn_session::handshake() wivrn_session::wivrn_session(in6_addr address, int port) : control(address, port), stream(), address(address) { - char buffer[100]; spdlog::info("Connection to {}:{}", inet_ntop(AF_INET6, &address, buffer, sizeof(buffer)), port); handshake(); @@ -82,7 +81,6 @@ wivrn_session::wivrn_session(in6_addr address, int port) : wivrn_session::wivrn_session(in_addr address, int port) : control(address, port), stream(), address(address) { - char buffer[100]; spdlog::info("Connection to {}:{}", inet_ntop(AF_INET, &address, buffer, sizeof(buffer)), port); handshake(); diff --git a/client/wivrn_discover.cpp b/client/wivrn_discover.cpp index b34dccfe..a36e63fc 100644 --- a/client/wivrn_discover.cpp +++ b/client/wivrn_discover.cpp @@ -298,7 +298,22 @@ private: } } - static int query_callback(int sock, const sockaddr * from, size_t addrlen, mdns_entry_type_t entry, uint16_t query_id, uint16_t rtype, uint16_t rclass, uint32_t ttl, const void * data, size_t size, size_t name_offset, size_t name_length, size_t record_offset, size_t record_length, void * user_data) + static int query_callback( + int sock, + const sockaddr * from, + size_t addrlen, + mdns_entry_type_t entry, + uint16_t query_id, + uint16_t rtype, + uint16_t rclass, + uint32_t ttl, + const void * data, + size_t size, + size_t name_offset, + size_t name_length, + size_t record_offset, + size_t record_length, + void * user_data) { dnssd_cache * self = (dnssd_cache *)user_data; @@ -338,7 +353,7 @@ private: std::array txt_buffer; size_t nb_records = mdns_record_parse_txt(data, size, record_offset, record_length, txt_buffer.data(), txt_buffer.size()); - for(size_t i = 0; i < nb_records; ++i) + for (size_t i = 0; i < nb_records; ++i) { std::string key{txt_buffer[i].key.str, txt_buffer[i].key.length}; std::string value{txt_buffer[i].value.str, txt_buffer[i].value.length}; @@ -592,7 +607,7 @@ int main() j); } - for (auto& [key, value]: i.txt) + for (auto & [key, value]: i.txt) { spdlog::info(" {} = {}", key, value); } diff --git a/client/xr/check.h b/client/xr/check.h index 21d2a733..96617c58 100644 --- a/client/xr/check.h +++ b/client/xr/check.h @@ -19,8 +19,8 @@ #pragma once -#include #include +#include namespace xr { diff --git a/client/xr/error_category.cpp b/client/xr/error_category.cpp index 2f28ebe2..c5945f24 100644 --- a/client/xr/error_category.cpp +++ b/client/xr/error_category.cpp @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include "xr/check.h" #include "xr.h" +#include "xr/check.h" #include namespace diff --git a/client/xr/hand_tracker.cpp b/client/xr/hand_tracker.cpp index d0fa0697..2e4e658b 100644 --- a/client/xr/hand_tracker.cpp +++ b/client/xr/hand_tracker.cpp @@ -19,34 +19,33 @@ #include "hand_tracker.h" - std::optional> xr::hand_tracker::locate(XrSpace space, XrTime time) { if (!id || !xrLocateHandJointsEXT) return std::nullopt; XrHandJointsLocateInfoEXT info{ - .type = XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT, - .next = nullptr, - .baseSpace = space, - .time = time, + .type = XR_TYPE_HAND_JOINTS_LOCATE_INFO_EXT, + .next = nullptr, + .baseSpace = space, + .time = time, }; std::array joints_pos; std::array joints_vel; XrHandJointVelocitiesEXT velocities{ - .type = XR_TYPE_HAND_JOINT_VELOCITIES_EXT, - .next = nullptr, - .jointCount = joints_vel.size(), - .jointVelocities = joints_vel.data(), + .type = XR_TYPE_HAND_JOINT_VELOCITIES_EXT, + .next = nullptr, + .jointCount = joints_vel.size(), + .jointVelocities = joints_vel.data(), }; XrHandJointLocationsEXT locations{ - .type = XR_TYPE_HAND_JOINT_LOCATIONS_EXT, - .next = &velocities, - .jointCount = joints_pos.size(), - .jointLocations = joints_pos.data(), + .type = XR_TYPE_HAND_JOINT_LOCATIONS_EXT, + .next = &velocities, + .jointCount = joints_pos.size(), + .jointLocations = joints_pos.data(), }; CHECK_XR(xrLocateHandJointsEXT(id, &info, &locations)); @@ -55,9 +54,9 @@ std::optional> xr:: return std::nullopt; std::array joints; - for(int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) + for (int i = 0; i < XR_HAND_JOINT_COUNT_EXT; i++) { - joints[i] = { joints_pos[i], joints_vel[i] }; + joints[i] = {joints_pos[i], joints_vel[i]}; } return joints; diff --git a/client/xr/hand_tracker.h b/client/xr/hand_tracker.h index dda9636d..9d74d92b 100644 --- a/client/xr/hand_tracker.h +++ b/client/xr/hand_tracker.h @@ -20,10 +20,10 @@ #pragma once #include "utils/handle.h" -#include #include -#include #include +#include +#include #include "instance.h" diff --git a/client/xr/instance.cpp b/client/xr/instance.cpp index f137e131..240e8229 100644 --- a/client/xr/instance.cpp +++ b/client/xr/instance.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -66,15 +65,15 @@ xr::instance::instance(std::string_view application_name, std::vector layers; @@ -111,7 +110,7 @@ xr::instance::instance(std::string_view application_name, std::vector & bindings) { - XrInteractionProfileSuggestedBinding suggested_binding{}; - suggested_binding.type = XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING; - suggested_binding.interactionProfile = string_to_path(interaction_profile); - suggested_binding.countSuggestedBindings = bindings.size(); - suggested_binding.suggestedBindings = bindings.data(); + XrInteractionProfileSuggestedBinding suggested_binding{ + .type = XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, + .interactionProfile = string_to_path(interaction_profile), + .countSuggestedBindings = (uint32_t)bindings.size(), + .suggestedBindings = bindings.data(), + }; + CHECK_XR(xrSuggestInteractionProfileBindings(id, &suggested_binding)); } diff --git a/client/xr/passthrough.cpp b/client/xr/passthrough.cpp index ea854394..b785bd28 100644 --- a/client/xr/passthrough.cpp +++ b/client/xr/passthrough.cpp @@ -18,10 +18,10 @@ */ #include "passthrough.h" -#include "session.h" #include "openxr/openxr.h" +#include "session.h" -xr::passthrough_layer_fb::passthrough_layer_fb(instance& inst, session& s, const XrPassthroughLayerCreateInfoFB& info) +xr::passthrough_layer_fb::passthrough_layer_fb(instance & inst, session & s, const XrPassthroughLayerCreateInfoFB & info) { xrDestroyPassthroughLayerFB = inst.get_proc("xrDestroyPassthroughLayerFB"); @@ -35,7 +35,6 @@ xr::passthrough_layer_fb::~passthrough_layer_fb() xrDestroyPassthroughLayerFB(id); } - xr::passthrough_fb::passthrough_fb(instance & inst, session & s) { PFN_xrCreatePassthroughFB xrCreatePassthroughFB = inst.get_proc("xrCreatePassthroughFB"); @@ -47,26 +46,26 @@ xr::passthrough_fb::passthrough_fb(instance & inst, session & s) xrPassthroughLayerResumeFB = inst.get_proc("xrPassthroughLayerResumeFB"); XrPassthroughCreateInfoFB info{ - .type = XR_TYPE_PASSTHROUGH_CREATE_INFO_FB, - .flags = 0 + .type = XR_TYPE_PASSTHROUGH_CREATE_INFO_FB, + .flags = 0, }; CHECK_XR(xrCreatePassthroughFB(s, &info, &id)); XrPassthroughLayerCreateInfoFB layer_info{ - .type = XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB, - .passthrough = id, - .flags = 0, - .purpose = XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB + .type = XR_TYPE_PASSTHROUGH_LAYER_CREATE_INFO_FB, + .passthrough = id, + .flags = 0, + .purpose = XR_PASSTHROUGH_LAYER_PURPOSE_RECONSTRUCTION_FB, }; passthrough_layer.emplace(inst, s, layer_info); composition_layer = XrCompositionLayerPassthroughFB{ - .type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB, - .flags = 0, - .space = XR_NULL_HANDLE, - .layerHandle = *passthrough_layer + .type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_FB, + .flags = 0, + .space = XR_NULL_HANDLE, + .layerHandle = *passthrough_layer, }; } @@ -95,21 +94,21 @@ xr::passthrough_htc::passthrough_htc(instance & inst, session & s) xrDestroyPassthroughHTC = inst.get_proc("xrDestroyPassthroughHTC"); XrPassthroughCreateInfoHTC info{ - .type = XR_TYPE_PASSTHROUGH_CREATE_INFO_HTC, - .form = XR_PASSTHROUGH_FORM_PLANAR_HTC + .type = XR_TYPE_PASSTHROUGH_CREATE_INFO_HTC, + .form = XR_PASSTHROUGH_FORM_PLANAR_HTC, }; CHECK_XR(xrCreatePassthroughHTC(s, &info, &id)); composition_layer = XrCompositionLayerPassthroughHTC{ - .type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_HTC, - .layerFlags = 0, - .space = XR_NULL_HANDLE, - .passthrough = id, - .color = { - .type = XR_TYPE_PASSTHROUGH_COLOR_HTC, - .alpha = 1 - } + .type = XR_TYPE_COMPOSITION_LAYER_PASSTHROUGH_HTC, + .layerFlags = 0, + .space = XR_NULL_HANDLE, + .passthrough = id, + .color = { + .type = XR_TYPE_PASSTHROUGH_COLOR_HTC, + .alpha = 1, + }, }; } @@ -118,4 +117,3 @@ xr::passthrough_htc::~passthrough_htc() if (id != XR_NULL_HANDLE && xrDestroyPassthroughHTC) xrDestroyPassthroughHTC(id); } - diff --git a/client/xr/passthrough.h b/client/xr/passthrough.h index 5a435ef8..8b9682b5 100644 --- a/client/xr/passthrough.h +++ b/client/xr/passthrough.h @@ -31,11 +31,12 @@ class session; class passthrough_layer_fb : public utils::handle { PFN_xrDestroyPassthroughLayerFB xrDestroyPassthroughLayerFB{}; + public: passthrough_layer_fb() = default; - passthrough_layer_fb(instance&, session&, const XrPassthroughLayerCreateInfoFB&); - passthrough_layer_fb(passthrough_layer_fb&&) = delete; - passthrough_layer_fb& operator=(passthrough_layer_fb&&) = delete; + passthrough_layer_fb(instance &, session &, const XrPassthroughLayerCreateInfoFB &); + passthrough_layer_fb(passthrough_layer_fb &&) = delete; + passthrough_layer_fb & operator=(passthrough_layer_fb &&) = delete; ~passthrough_layer_fb(); }; @@ -61,15 +62,18 @@ public: void start(); void pause(); - XrCompositionLayerBaseHeader * layer() { return (XrCompositionLayerBaseHeader*)&composition_layer; } + XrCompositionLayerBaseHeader * layer() + { + return (XrCompositionLayerBaseHeader *)&composition_layer; + } }; - class passthrough_htc : public utils::handle { PFN_xrDestroyPassthroughHTC xrDestroyPassthroughHTC{}; XrCompositionLayerPassthroughHTC composition_layer; + public: passthrough_htc() = default; passthrough_htc(instance &, session &); @@ -81,7 +85,10 @@ public: void start() {} void pause() {} - XrCompositionLayerBaseHeader * layer() { return (XrCompositionLayerBaseHeader*)&composition_layer; } + XrCompositionLayerBaseHeader * layer() + { + return (XrCompositionLayerBaseHeader *)&composition_layer; + } }; using passthrough = std::variant; diff --git a/client/xr/session.cpp b/client/xr/session.cpp index b0150dfd..2f6b899f 100644 --- a/client/xr/session.cpp +++ b/client/xr/session.cpp @@ -20,27 +20,30 @@ #include "session.h" #include "details/enumerate.h" +#include "utils/ranges.h" #include "xr.h" #include #include -#include "utils/ranges.h" -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) : +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) { - XrGraphicsBindingVulkan2KHR vulkan_binding{}; - vulkan_binding.type = XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR; + XrGraphicsBindingVulkan2KHR vulkan_binding{ + .type = XR_TYPE_GRAPHICS_BINDING_VULKAN2_KHR, - vulkan_binding.instance = *vk_inst; - vulkan_binding.physicalDevice = *pdev; - vulkan_binding.device = *dev; - vulkan_binding.queueFamilyIndex = queue_family_index; - vulkan_binding.queueIndex = 0; + .instance = *vk_inst, + .physicalDevice = *pdev, + .device = *dev, + .queueFamilyIndex = (uint32_t)queue_family_index, + .queueIndex = 0, + }; + + XrSessionCreateInfo session_info{ + .type = XR_TYPE_SESSION_CREATE_INFO, + .next = &vulkan_binding, + .systemId = sys, + }; - XrSessionCreateInfo session_info{}; - session_info.type = XR_TYPE_SESSION_CREATE_INFO; - session_info.next = &vulkan_binding; - session_info.systemId = sys; CHECK_XR(xrCreateSession(inst, &session_info, &id)); } @@ -51,10 +54,11 @@ std::vector xr::session::get_reference_spaces() const xr::space xr::session::create_reference_space(XrReferenceSpaceType ref, const XrPosef & pose) { - XrReferenceSpaceCreateInfo create_info{}; - create_info.type = XR_TYPE_REFERENCE_SPACE_CREATE_INFO; - create_info.referenceSpaceType = ref; - create_info.poseInReferenceSpace = pose; + XrReferenceSpaceCreateInfo create_info{ + .type = XR_TYPE_REFERENCE_SPACE_CREATE_INFO, + .referenceSpaceType = ref, + .poseInReferenceSpace = pose, + }; XrSpace s; CHECK_XR(xrCreateReferenceSpace(id, &create_info, &s)); @@ -64,11 +68,12 @@ xr::space xr::session::create_reference_space(XrReferenceSpaceType ref, const Xr xr::space xr::session::create_action_space(XrAction action, const XrPosef & pose) { - XrActionSpaceCreateInfo create_info{}; - create_info.type = XR_TYPE_ACTION_SPACE_CREATE_INFO; - create_info.action = action; - create_info.poseInActionSpace = pose; - create_info.subactionPath = XR_NULL_PATH; + XrActionSpaceCreateInfo create_info{ + .type = XR_TYPE_ACTION_SPACE_CREATE_INFO, + .action = action, + .subactionPath = XR_NULL_PATH, + .poseInActionSpace = pose, + }; XrSpace s; CHECK_XR(xrCreateActionSpace(id, &create_info, &s)); @@ -76,15 +81,13 @@ xr::space xr::session::create_action_space(XrAction action, const XrPosef & pose return s; } - xr::hand_tracker xr::session::create_hand_tracker(XrHandEXT hand, XrHandJointSetEXT hand_joint_set) { - XrHandTrackerCreateInfoEXT create_info - { - .type = XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT, - .next = nullptr, - .hand = hand, - .handJointSet = hand_joint_set, + XrHandTrackerCreateInfoEXT create_info{ + .type = XR_TYPE_HAND_TRACKER_CREATE_INFO_EXT, + .next = nullptr, + .hand = hand, + .handJointSet = hand_joint_set, }; XrHandTrackerEXT ht; @@ -106,11 +109,13 @@ std::vector xr::session::get_swapchain_formats() const XrFrameState xr::session::wait_frame() { - XrFrameWaitInfo wait_info{}; - wait_info.type = XR_TYPE_FRAME_WAIT_INFO; + XrFrameWaitInfo wait_info{ + .type = XR_TYPE_FRAME_WAIT_INFO, + }; - XrFrameState state{}; - state.type = XR_TYPE_FRAME_STATE; + XrFrameState state{ + .type = XR_TYPE_FRAME_STATE, + }; CHECK_XR(xrWaitFrame(id, &wait_info, &state)); @@ -119,29 +124,32 @@ XrFrameState xr::session::wait_frame() void xr::session::begin_frame() { - XrFrameBeginInfo begin_info{}; - begin_info.type = XR_TYPE_FRAME_BEGIN_INFO; + XrFrameBeginInfo begin_info{ + .type = XR_TYPE_FRAME_BEGIN_INFO, + }; CHECK_XR(xrBeginFrame(id, &begin_info)); } void xr::session::end_frame(XrTime display_time, const std::vector & layers, XrEnvironmentBlendMode blend_mode) { - XrFrameEndInfo end_info{}; - end_info.type = XR_TYPE_FRAME_END_INFO; - end_info.displayTime = display_time; - end_info.environmentBlendMode = blend_mode; - end_info.layerCount = layers.size(); - end_info.layers = layers.data(); + XrFrameEndInfo end_info{ + .type = XR_TYPE_FRAME_END_INFO, + .displayTime = display_time, + .environmentBlendMode = blend_mode, + .layerCount = (uint32_t)layers.size(), + .layers = layers.data(), + }; CHECK_XR(xrEndFrame(id, &end_info)); } void xr::session::begin_session(XrViewConfigurationType view_config) { - XrSessionBeginInfo begin_info{}; - begin_info.type = XR_TYPE_SESSION_BEGIN_INFO; - begin_info.primaryViewConfigurationType = view_config; + XrSessionBeginInfo begin_info{ + .type = XR_TYPE_SESSION_BEGIN_INFO, + .primaryViewConfigurationType = view_config, + }; CHECK_XR(xrBeginSession(id, &begin_info)); } @@ -155,14 +163,16 @@ std::pair> xr::session::locate_views(XrVie XrTime display_time, XrSpace space) { - XrViewLocateInfo view_locate_info{}; - view_locate_info.type = XR_TYPE_VIEW_LOCATE_INFO; - view_locate_info.viewConfigurationType = view_config_type; - view_locate_info.displayTime = display_time; - view_locate_info.space = space; + XrViewLocateInfo view_locate_info{ + .type = XR_TYPE_VIEW_LOCATE_INFO, + .viewConfigurationType = view_config_type, + .displayTime = display_time, + .space = space, + }; - XrViewState view_state{}; - view_state.type = XR_TYPE_VIEW_STATE; + XrViewState view_state{ + .type = XR_TYPE_VIEW_STATE, + }; auto views = details::enumerate(xrLocateViews, id, &view_locate_info, &view_state); @@ -171,8 +181,10 @@ std::pair> xr::session::locate_views(XrVie std::string xr::session::get_current_interaction_profile(const std::string & path) { - XrInteractionProfileState state{}; - state.type = XR_TYPE_INTERACTION_PROFILE_STATE; + XrInteractionProfileState state{ + .type = XR_TYPE_INTERACTION_PROFILE_STATE, + }; + CHECK_XR(xrGetCurrentInteractionProfile(id, inst->string_to_path(path), &state)); return inst->path_to_string(state.interactionProfile); @@ -180,10 +192,11 @@ std::string xr::session::get_current_interaction_profile(const std::string & pat void xr::session::attach_actionsets(const std::vector & actionsets) { - XrSessionActionSetsAttachInfo attach_info{}; - attach_info.type = XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO; - attach_info.countActionSets = actionsets.size(); - attach_info.actionSets = actionsets.data(); + XrSessionActionSetsAttachInfo attach_info{ + .type = XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, + .countActionSets = (uint32_t)actionsets.size(), + .actionSets = actionsets.data(), + }; CHECK_XR(xrAttachSessionActionSets(id, &attach_info)); } @@ -265,7 +278,7 @@ void xr::session::sync_actions(std::span action_sets) { std::vector active_action_sets(action_sets.size()); - for(auto&& [i, j]: utils::zip(active_action_sets, action_sets)) + for (auto && [i, j]: utils::zip(active_action_sets, action_sets)) { i.actionSet = j; i.subactionPath = XR_NULL_PATH; diff --git a/client/xr/session.h b/client/xr/session.h index 036aaa5d..c7902833 100644 --- a/client/xr/session.h +++ b/client/xr/session.h @@ -20,14 +20,14 @@ #pragma once #include "utils/handle.h" +#include #include #include -#include #include #include -#include "space.h" #include "hand_tracker.h" +#include "space.h" namespace xr { @@ -40,7 +40,7 @@ class session : public utils::handle public: session() = default; - session(instance &, system &, vk::raii::Instance&, vk::raii::PhysicalDevice&, vk::raii::Device&, int queue_family_index); + session(instance &, system &, vk::raii::Instance &, vk::raii::PhysicalDevice &, vk::raii::Device &, int queue_family_index); session(session &&) = default; session & operator=(session &&) = default; @@ -67,7 +67,9 @@ public: std::string get_current_interaction_profile(const std::string & path); void attach_actionsets(const std::vector & actionsets); std::vector sources_for_action(XrAction a); - std::vector localized_sources_for_action(XrAction action, XrInputSourceLocalizedNameFlags components = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT); + std::vector localized_sources_for_action( + XrAction action, + XrInputSourceLocalizedNameFlags components = XR_INPUT_SOURCE_LOCALIZED_NAME_USER_PATH_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_INTERACTION_PROFILE_BIT | XR_INPUT_SOURCE_LOCALIZED_NAME_COMPONENT_BIT); float get_current_refresh_rate(); std::vector get_refresh_rates(); diff --git a/client/xr/swapchain.cpp b/client/xr/swapchain.cpp index 47497e97..d36f0067 100644 --- a/client/xr/swapchain.cpp +++ b/client/xr/swapchain.cpp @@ -21,21 +21,22 @@ #include "details/enumerate.h" #include "session.h" -xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count) +xr::swapchain::swapchain(xr::session & s, vk::raii::Device & device, vk::Format format, int32_t width, int32_t height, int sample_count) { assert(sample_count == 1); - XrSwapchainCreateInfo create_info{}; - create_info.type = XR_TYPE_SWAPCHAIN_CREATE_INFO; - create_info.createFlags = 0; - create_info.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; - create_info.format = static_cast(format); - create_info.sampleCount = sample_count; - create_info.width = width; - create_info.height = height; - create_info.faceCount = 1; - create_info.arraySize = 1; - create_info.mipCount = 1; + XrSwapchainCreateInfo create_info{ + .type = XR_TYPE_SWAPCHAIN_CREATE_INFO, + .createFlags = 0, + .usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, + .format = static_cast(format), + .sampleCount = (uint32_t)sample_count, + .width = (uint32_t)width, + .height = (uint32_t)height, + .faceCount = 1, + .arraySize = 1, + .mipCount = 1, + }; width_ = width; height_ = height; @@ -53,18 +54,17 @@ xr::swapchain::swapchain(xr::session & s, vk::raii::Device& device, vk::Format f images_[i].image = array[i].image; vk::ImageViewCreateInfo iv_create_info{ - .image = array[i].image, - .viewType = vk::ImageViewType::e2D, - .format = format, - .components = {}, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - } - }; + .image = array[i].image, + .viewType = vk::ImageViewType::e2D, + .format = format, + .components = {}, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }}; images_[i].view = vk::raii::ImageView(device, iv_create_info); } @@ -80,8 +80,9 @@ int xr::swapchain::acquire() { uint32_t index; - XrSwapchainImageAcquireInfo acquire_info{}; - acquire_info.type = XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO; + XrSwapchainImageAcquireInfo acquire_info{ + .type = XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, + }; CHECK_XR(xrAcquireSwapchainImage(id, &acquire_info, &index)); @@ -90,9 +91,10 @@ int xr::swapchain::acquire() bool xr::swapchain::wait(XrDuration timeout) { - XrSwapchainImageWaitInfo wait_info{}; - wait_info.type = XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO; - wait_info.timeout = timeout; + XrSwapchainImageWaitInfo wait_info{ + .type = XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, + .timeout = timeout, + }; XrResult result = xrWaitSwapchainImage(id, &wait_info); CHECK_XR(result, "xrWaitSwapchainImage"); @@ -101,8 +103,9 @@ bool xr::swapchain::wait(XrDuration timeout) void xr::swapchain::release() { - XrSwapchainImageReleaseInfo release_info{}; - release_info.type = XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO; + XrSwapchainImageReleaseInfo release_info{ + .type = XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, + }; CHECK_XR(xrReleaseSwapchainImage(id, &release_info)); } diff --git a/client/xr/swapchain.h b/client/xr/swapchain.h index c30d2cdc..3163d9c1 100644 --- a/client/xr/swapchain.h +++ b/client/xr/swapchain.h @@ -52,7 +52,7 @@ private: public: swapchain() = default; - swapchain(session &, vk::raii::Device& device, vk::Format format, int32_t width, int32_t height, int sample_count = 1); + swapchain(session &, vk::raii::Device & device, vk::Format format, int32_t width, int32_t height, int sample_count = 1); swapchain(swapchain &&) = default; swapchain(const swapchain &) = delete; swapchain & operator=(swapchain &&) = default; @@ -69,7 +69,7 @@ public: } XrExtent2Di extent() const { - return { width_, height_ }; + return {width_, height_}; } int sample_count() const { diff --git a/client/xr/system.cpp b/client/xr/system.cpp index 35c285b6..72c1192a 100644 --- a/client/xr/system.cpp +++ b/client/xr/system.cpp @@ -48,8 +48,9 @@ XrGraphicsRequirementsVulkan2KHR xr::system::graphics_requirements() const auto xrGetVulkanGraphicsRequirements2KHR = inst->get_proc("xrGetVulkanGraphicsRequirements2KHR"); - XrGraphicsRequirementsVulkan2KHR requirements{}; - requirements.type = XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR; + XrGraphicsRequirementsVulkan2KHR requirements{ + .type = XR_TYPE_GRAPHICS_REQUIREMENTS_VULKAN2_KHR, + }; CHECK_XR(xrGetVulkanGraphicsRequirements2KHR(*inst, id, &requirements)); return requirements; @@ -60,7 +61,9 @@ XrSystemProperties xr::system::properties() const if (!id) throw std::invalid_argument("this"); - XrSystemProperties prop{.type = XR_TYPE_SYSTEM_PROPERTIES}; + XrSystemProperties prop{ + .type = XR_TYPE_SYSTEM_PROPERTIES, + }; CHECK_XR(xrGetSystemProperties(*inst, id, &prop)); return prop; @@ -71,14 +74,13 @@ XrSystemHandTrackingPropertiesEXT xr::system::hand_tracking_properties() const if (!id) throw std::invalid_argument("this"); - XrSystemHandTrackingPropertiesEXT hand_tracking_prop - { - .type = XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, + XrSystemHandTrackingPropertiesEXT hand_tracking_prop{ + .type = XR_TYPE_SYSTEM_HAND_TRACKING_PROPERTIES_EXT, }; XrSystemProperties prop{ - .type = XR_TYPE_SYSTEM_PROPERTIES, - .next = &hand_tracking_prop, + .type = XR_TYPE_SYSTEM_PROPERTIES, + .next = &hand_tracking_prop, }; CHECK_XR(xrGetSystemProperties(*inst, id, &prop)); @@ -87,25 +89,24 @@ XrSystemHandTrackingPropertiesEXT xr::system::hand_tracking_properties() const xr::system::passthrough_type xr::system::passthrough_supported() const { - const std::vector& xr_extensions = application::get_xr_extensions(); + const std::vector & xr_extensions = application::get_xr_extensions(); if (utils::contains(xr_extensions, XR_HTC_PASSTHROUGH_EXTENSION_NAME)) return passthrough_type::color; if (utils::contains(xr_extensions, XR_FB_PASSTHROUGH_EXTENSION_NAME)) { XrSystemPassthroughProperties2FB passthrough_prop2{ - .type = XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES2_FB, + .type = XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES2_FB, }; - XrSystemPassthroughPropertiesFB passthrough_prop - { - .type = XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB, - .next = &passthrough_prop2, + XrSystemPassthroughPropertiesFB passthrough_prop{ + .type = XR_TYPE_SYSTEM_PASSTHROUGH_PROPERTIES_FB, + .next = &passthrough_prop2, }; XrSystemProperties prop{ - .type = XR_TYPE_SYSTEM_PROPERTIES, - .next = &passthrough_prop, + .type = XR_TYPE_SYSTEM_PROPERTIES, + .next = &passthrough_prop, }; CHECK_XR(xrGetSystemProperties(*inst, id, &prop)); @@ -124,15 +125,16 @@ xr::system::passthrough_type xr::system::passthrough_supported() const return passthrough_type::no_passthrough; } -vk::raii::PhysicalDevice xr::system::physical_device(vk::raii::Instance& vulkan) const +vk::raii::PhysicalDevice xr::system::physical_device(vk::raii::Instance & vulkan) const { auto xrGetVulkanGraphicsDevice2KHR = inst->get_proc("xrGetVulkanGraphicsDevice2KHR"); - XrVulkanGraphicsDeviceGetInfoKHR get_info{}; - get_info.type = XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR; - get_info.systemId = id; - get_info.vulkanInstance = *vulkan; + XrVulkanGraphicsDeviceGetInfoKHR get_info{ + .type = XR_TYPE_VULKAN_GRAPHICS_DEVICE_GET_INFO_KHR, + .systemId = id, + .vulkanInstance = *vulkan, + }; VkPhysicalDevice dev; CHECK_XR(xrGetVulkanGraphicsDevice2KHR(*inst, &get_info, &dev)); @@ -140,15 +142,15 @@ vk::raii::PhysicalDevice xr::system::physical_device(vk::raii::Instance& vulkan) return vk::raii::PhysicalDevice{vulkan, dev}; } -vk::raii::Device xr::system::create_device(vk::raii::PhysicalDevice& pdev, vk::DeviceCreateInfo & create_info) const +vk::raii::Device xr::system::create_device(vk::raii::PhysicalDevice & pdev, vk::DeviceCreateInfo & create_info) const { - XrVulkanDeviceCreateInfoKHR xr_create_info{}; - - xr_create_info.type = XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR; - xr_create_info.pfnGetInstanceProcAddr = vkGetInstanceProcAddr; - xr_create_info.systemId = id; - xr_create_info.vulkanPhysicalDevice = *pdev; - xr_create_info.vulkanCreateInfo = &(VkDeviceCreateInfo&)create_info; + XrVulkanDeviceCreateInfoKHR xr_create_info{ + .type = XR_TYPE_VULKAN_DEVICE_CREATE_INFO_KHR, + .systemId = id, + .pfnGetInstanceProcAddr = vkGetInstanceProcAddr, + .vulkanPhysicalDevice = *pdev, + .vulkanCreateInfo = &(VkDeviceCreateInfo &)create_info, + }; VkDevice dev; VkResult vresult; @@ -167,8 +169,9 @@ std::vector xr::system::view_configurations() const XrViewConfigurationProperties xr::system::view_configuration_properties(XrViewConfigurationType type) const { - XrViewConfigurationProperties prop{}; - prop.type = XR_TYPE_VIEW_CONFIGURATION_PROPERTIES; + XrViewConfigurationProperties prop{ + .type = XR_TYPE_VIEW_CONFIGURATION_PROPERTIES, + }; CHECK_XR(xrGetViewConfigurationProperties(*inst, id, type, &prop)); return prop; diff --git a/client/xr/system.h b/client/xr/system.h index 8f4abbdf..5d4974bb 100644 --- a/client/xr/system.h +++ b/client/xr/system.h @@ -65,8 +65,8 @@ public: passthrough_type passthrough_supported() const; XrGraphicsRequirementsVulkan2KHR graphics_requirements() const; - vk::raii::PhysicalDevice physical_device(vk::raii::Instance& vulkan) const; - vk::raii::Device create_device(vk::raii::PhysicalDevice& pdev, vk::DeviceCreateInfo & create_info) const; + vk::raii::PhysicalDevice physical_device(vk::raii::Instance & vulkan) const; + vk::raii::Device create_device(vk::raii::PhysicalDevice & pdev, vk::DeviceCreateInfo & create_info) const; std::vector view_configurations() const; XrViewConfigurationProperties view_configuration_properties(XrViewConfigurationType) const; diff --git a/common/utils/named_thread.h b/common/utils/named_thread.h index a123daf8..7acd470c 100644 --- a/common/utils/named_thread.h +++ b/common/utils/named_thread.h @@ -19,18 +19,17 @@ #pragma once -#include +#include #include #include -#include namespace utils { -template -std::thread named_thread(const std::string& name, Args&&... args) +template +std::thread named_thread(const std::string & name, Args &&... args) { std::thread t{std::forward(args)...}; pthread_setname_np(t.native_handle(), name.substr(0, 15).c_str()); return t; } -} +} // namespace utils diff --git a/common/utils/ring_buffer.h b/common/utils/ring_buffer.h index 4a2d088a..b1dbb67e 100644 --- a/common/utils/ring_buffer.h +++ b/common/utils/ring_buffer.h @@ -56,7 +56,6 @@ public: read_index.store(next_read); return std::move(res); } - }; } // namespace utils diff --git a/common/utils/singleton.h b/common/utils/singleton.h index 6890fca7..8ef85cc0 100644 --- a/common/utils/singleton.h +++ b/common/utils/singleton.h @@ -21,7 +21,7 @@ #include -template +template class singleton { // static_assert(std::derived_from>); @@ -32,7 +32,7 @@ protected: singleton() { assert(instance_ == nullptr); - instance_ = reinterpret_cast(this); + instance_ = reinterpret_cast(this); } ~singleton() @@ -41,15 +41,16 @@ protected: instance_ = nullptr; } - singleton(const singleton&) = delete; - singleton& operator=(const singleton&) = delete; + singleton(const singleton &) = delete; + singleton & operator=(const singleton &) = delete; public: static T & instance() { assert(instance_ != nullptr); - return *reinterpret_cast(instance_); + return *reinterpret_cast(instance_); } }; -template T * singleton::instance_; +template +T * singleton::instance_; diff --git a/common/utils/wrap_lambda.h b/common/utils/wrap_lambda.h index 3851946d..02e157da 100644 --- a/common/utils/wrap_lambda.h +++ b/common/utils/wrap_lambda.h @@ -57,13 +57,13 @@ public: auto userdata_first() { using F = decltype(std::function(impl)); - return details::add_void::template fn_0; + return ::details::add_void::template fn_0; } operator auto() { using F = decltype(std::function(impl)); - return details::add_void::template fn; + return ::details::add_void::template fn; } operator void *() diff --git a/common/utils/xdg_base_directory.cpp b/common/utils/xdg_base_directory.cpp index 3d070d86..addad42a 100644 --- a/common/utils/xdg_base_directory.cpp +++ b/common/utils/xdg_base_directory.cpp @@ -17,8 +17,8 @@ * along with this program. If not, see . */ -#include #include +#include std::filesystem::path xdg_config_home() { diff --git a/common/version.h b/common/version.h index f10a4165..e6a1935f 100644 --- a/common/version.h +++ b/common/version.h @@ -1,13 +1,12 @@ #pragma once -#include "wivrn_serialization.h" #include "wivrn_packets.h" - +#include "wivrn_serialization.h" namespace xrt::drivers::wivrn { - using protocol = std::variant; +using protocol = std::variant; - extern const char git_version[]; - static inline const constinit auto protocol_version = serialization_type_hash(); -} +extern const char git_version[]; +static inline const constinit auto protocol_version = serialization_type_hash(); +} // namespace xrt::drivers::wivrn diff --git a/common/vk/allocation.h b/common/vk/allocation.h index d66158b6..164b6b22 100644 --- a/common/vk/allocation.h +++ b/common/vk/allocation.h @@ -21,8 +21,8 @@ #include "vk_allocator.h" #include "vk_mem_alloc.h" -#include #include +#include template struct basic_allocation_traits diff --git a/common/vk/vk_mem_alloc.cpp b/common/vk/vk_mem_alloc.cpp index fcd63844..e0150246 100644 --- a/common/vk/vk_mem_alloc.cpp +++ b/common/vk/vk_mem_alloc.cpp @@ -7,5 +7,4 @@ // printf("\n"); \ // } while(false) - #include "vk_mem_alloc.h" diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index 065a8911..27539583 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -27,8 +27,8 @@ #include #include #include -#include #include +#include #include "wivrn_serialization_types.h" diff --git a/common/wivrn_serialization_types.h b/common/wivrn_serialization_types.h index 5a6f9a4d..ea9d733c 100644 --- a/common/wivrn_serialization_types.h +++ b/common/wivrn_serialization_types.h @@ -29,12 +29,12 @@ namespace xrt::drivers::wivrn struct data_holder { data_holder() = default; - data_holder(const data_holder&) = delete; - data_holder(data_holder&&) = default; - data_holder& operator=(const data_holder&) = delete; - data_holder& operator=(data_holder&&) = default; + data_holder(const data_holder &) = delete; + data_holder(data_holder &&) = default; + data_holder & operator=(const data_holder &) = delete; + data_holder & operator=(data_holder &&) = default; std::vector c; }; -} +} // namespace xrt::drivers::wivrn diff --git a/common/wivrn_serialization_ut.cpp b/common/wivrn_serialization_ut.cpp index ddf04ff1..1c96651d 100644 --- a/common/wivrn_serialization_ut.cpp +++ b/common/wivrn_serialization_ut.cpp @@ -51,4 +51,4 @@ struct test float y; }; static_assert(serialization_type_hash() == hash("structure{int32,float32}")); -} // namespace unit_tests +} // namespace diff --git a/common/wivrn_sockets.h b/common/wivrn_sockets.h index 011dcccf..87c40009 100644 --- a/common/wivrn_sockets.h +++ b/common/wivrn_sockets.h @@ -23,10 +23,10 @@ #include #include +#include #include #include #include -#include #include #include #include @@ -71,9 +71,10 @@ protected: public: fd_base() = default; - fd_base(int fd): fd{fd} {} + fd_base(int fd) : + fd{fd} {} fd_base(fd_base &&); - fd_base& operator=(fd_base &&); + fd_base & operator=(fd_base &&); ~fd_base(); int get_fd() const @@ -162,17 +163,19 @@ template struct Index; template -struct Index> { - static const std::size_t value = 0; +struct Index> +{ + static const std::size_t value = 0; }; template -struct Index> { - static const std::size_t value = 1 + Index>::value; +struct Index> +{ + static const std::size_t value = 1 + Index>::value; }; -} +} // namespace details -template +template class typed_socket> : public Socket { public: diff --git a/server/active_runtime.cpp b/server/active_runtime.cpp index b42e4964..8667cf39 100644 --- a/server/active_runtime.cpp +++ b/server/active_runtime.cpp @@ -22,7 +22,8 @@ #include #include -active_runtime::active_runtime() : pid(getpid()), active_runtime_json(xdg_config_home() / "openxr" / "1" / "active_runtime.json") +active_runtime::active_runtime() : + pid(getpid()), active_runtime_json(xdg_config_home() / "openxr" / "1" / "active_runtime.json") { try { @@ -40,7 +41,7 @@ active_runtime::active_runtime() : pid(getpid()), active_runtime_json(xdg_config to_be_deleted = true; } - catch(std::exception& e) + catch (std::exception & e) { std::cerr << "Cannot set active OpenXR runtime: " << e.what() << std::endl; } @@ -55,7 +56,7 @@ active_runtime::~active_runtime() std::filesystem::remove(active_runtime_json); } } - catch(std::exception& e) + catch (std::exception & e) { std::cerr << "Cannot unset active OpenXR runtime: " << e.what() << std::endl; } diff --git a/server/active_runtime.h b/server/active_runtime.h index 79e4d928..04b408b9 100644 --- a/server/active_runtime.h +++ b/server/active_runtime.h @@ -18,8 +18,8 @@ #pragma once -#include #include +#include class active_runtime { @@ -29,7 +29,7 @@ class active_runtime public: active_runtime(); - active_runtime(const active_runtime&) = delete; - active_runtime& operator=(const active_runtime&) = delete; + active_runtime(const active_runtime &) = delete; + active_runtime & operator=(const active_runtime &) = delete; ~active_runtime(); }; diff --git a/server/audio/audio_pipewire.cpp b/server/audio/audio_pipewire.cpp index 576cf2d8..256e8385 100644 --- a/server/audio/audio_pipewire.cpp +++ b/server/audio/audio_pipewire.cpp @@ -200,13 +200,13 @@ void pipewire_device::mic_process(void * self_v) } const auto & data = buffer->buffer->datas[0]; - uint8_t* data_ptr = (uint8_t*)data.data; + uint8_t * data_ptr = (uint8_t *)data.data; if (not data.data) return; const size_t frame_size = self->desc.microphone->num_channels * sizeof(int16_t); -#if PW_CHECK_VERSION(0,3,49) +#if PW_CHECK_VERSION(0, 3, 49) size_t num_frames = buffer->requested; #else size_t num_frames = 0; @@ -222,7 +222,7 @@ void pipewire_device::mic_process(void * self_v) while (num_frames != 0) { // remaining bytes in existing buffer - auto& current = self->mic_current; + auto & current = self->mic_current; ptrdiff_t tmp_remain = current.payload.size_bytes(); // limit to requested frames tmp_remain = std::min(tmp_remain, num_frames * frame_size); @@ -265,10 +265,11 @@ void pipewire_device::speaker_process(void * self_v) (uint8_t *)data.data + data.chunk->offset, data.chunk->size), }; - try { + try + { self->session.send_control(packet); } - catch (std::exception& e) + catch (std::exception & e) { U_LOG_W("Failed to send audio data: %s", e.what()); } diff --git a/server/audio/audio_pipewire.h b/server/audio/audio_pipewire.h index 0316e5ac..7e3662cf 100644 --- a/server/audio/audio_pipewire.h +++ b/server/audio/audio_pipewire.h @@ -26,4 +26,4 @@ std::shared_ptr create_pipewire_handle( const std::string & sink_name, const std::string & sink_description, const xrt::drivers::wivrn::from_headset::headset_info_packet & info, - xrt::drivers::wivrn::wivrn_session& session); + xrt::drivers::wivrn::wivrn_session & session); diff --git a/server/audio/audio_pulse.cpp b/server/audio/audio_pulse.cpp index c8d2cb83..729749ff 100644 --- a/server/audio/audio_pulse.cpp +++ b/server/audio/audio_pulse.cpp @@ -1,11 +1,11 @@ #include "audio_pulse.h" #include "../wivrn_ipc.h" +#include "driver/wivrn_session.h" #include "os/os_time.h" #include "util/u_logging.h" #include "utils/sync_queue.h" #include "utils/wrap_lambda.h" -#include "driver/wivrn_session.h" #include #include diff --git a/server/audio/audio_pulse.h b/server/audio/audio_pulse.h index 73bd6a15..0b968970 100644 --- a/server/audio/audio_pulse.h +++ b/server/audio/audio_pulse.h @@ -26,4 +26,4 @@ std::shared_ptr create_pulse_handle( const std::string & sink_name, const std::string & sink_description, const xrt::drivers::wivrn::from_headset::headset_info_packet & info, - xrt::drivers::wivrn::wivrn_session& session); + xrt::drivers::wivrn::wivrn_session & session); diff --git a/server/audio/audio_setup.cpp b/server/audio/audio_setup.cpp index 3c15c546..4aa8fc74 100644 --- a/server/audio/audio_setup.cpp +++ b/server/audio/audio_setup.cpp @@ -45,7 +45,7 @@ std::shared_ptr audio_device::create( #ifdef WIVRN_USE_PULSEAUDIO if (auto res = create_pulse_handle(source_name, source_description, sink_name, sink_description, info, session)) - return res; + return res; #endif U_LOG_W("No audio backend available"); return nullptr; diff --git a/server/avahi_publisher.h b/server/avahi_publisher.h index babe3e4c..a5b52a1b 100644 --- a/server/avahi_publisher.h +++ b/server/avahi_publisher.h @@ -32,7 +32,7 @@ class avahi_publisher void * userdata /**< The user data that was passed to avahi_client_new() */); public: - avahi_publisher(const char * name, std::string type, int port, const std::map& txt = {}); + avahi_publisher(const char * name, std::string type, int port, const std::map & txt = {}); ~avahi_publisher(); diff --git a/server/driver/clock_offset.cpp b/server/driver/clock_offset.cpp index 4c017683..0b62ee28 100644 --- a/server/driver/clock_offset.cpp +++ b/server/driver/clock_offset.cpp @@ -50,13 +50,13 @@ void clock_offset_estimator::add_sample(const xrt::drivers::wivrn::from_headset: { sample_interval = std::chrono::seconds(1); int64_t latency = 0; - for (const auto& s: samples) + for (const auto & s: samples) latency += s.received - s.query; latency /= samples.size(); // packets with too high latency are likely to be retransmitted if (sample.received - sample.query > 3 * latency) { - U_LOG_D("drop packet for latency %ldµs > %ldµs", (sample.received - sample.query) /1000, latency/1000); + U_LOG_D("drop packet for latency %ldµs > %ldµs", (sample.received - sample.query) / 1000, latency / 1000); return; } @@ -96,7 +96,7 @@ void clock_offset_estimator::add_sample(const xrt::drivers::wivrn::from_headset: { #if 1 // assume symmetrical latency - double x = (s.query + s.received)* 0.5 - x0; + double x = (s.query + s.received) * 0.5 - x0; #else // assume latency is only on server -> headset link double x = s.received - x0; diff --git a/server/driver/clock_offset.h b/server/driver/clock_offset.h index 3a49fc46..8604e147 100644 --- a/server/driver/clock_offset.h +++ b/server/driver/clock_offset.h @@ -36,7 +36,10 @@ struct clock_offset int64_t b = 0; double a = 1; - operator bool() { return b != 0;} + operator bool() + { + return b != 0; + } XrTime from_headset(XrTime) const; @@ -45,7 +48,7 @@ struct clock_offset class clock_offset_estimator { - struct sample: public xrt::drivers::wivrn::from_headset::timesync_response + struct sample : public xrt::drivers::wivrn::from_headset::timesync_response { XrTime received; }; @@ -58,9 +61,9 @@ class clock_offset_estimator std::chrono::steady_clock::time_point next_sample{}; std::atomic sample_interval = std::chrono::milliseconds(10); - public: - void request_sample(wivrn_connection& connection); - void add_sample(const xrt::drivers::wivrn::from_headset::timesync_response& sample); +public: + void request_sample(wivrn_connection & connection); + void add_sample(const xrt::drivers::wivrn::from_headset::timesync_response & sample); clock_offset get_offset(); }; diff --git a/server/driver/configuration.cpp b/server/driver/configuration.cpp index 021da82c..2f8cae2e 100644 --- a/server/driver/configuration.cpp +++ b/server/driver/configuration.cpp @@ -25,8 +25,8 @@ #endif #define JSON_DIAGNOSTICS 1 #include -#include #include +#include #include "util/u_logging.h" @@ -45,14 +45,15 @@ static std::filesystem::path get_cookie_file() namespace xrt::drivers::wivrn { - -NLOHMANN_JSON_SERIALIZE_ENUM(video_codec, { - {video_codec(-1), ""}, - {h264, "h264"}, - {h264, "avc"}, - {h265, "h265"}, - {h265, "hevc"}, - }) +NLOHMANN_JSON_SERIALIZE_ENUM( + video_codec, + { + {video_codec(-1), ""}, + {h264, "h264"}, + {h264, "avc"}, + {h265, "h265"}, + {h265, "hevc"}, + }) } configuration configuration::read_user_configuration() @@ -110,7 +111,7 @@ configuration configuration::read_user_configuration() result.application.push_back(json["application"]); else { - for(const auto& i: json["application"]) + for (const auto & i: json["application"]) { result.application.push_back(i); } @@ -146,7 +147,7 @@ std::string server_cookie() std::uniform_int_distribution dist(0, 61); char buffer[33]; - for(int i = 0; i < 32; i++) + for (int i = 0; i < 32; i++) { int c = dist(engine); diff --git a/server/driver/hand_joints_list.cpp b/server/driver/hand_joints_list.cpp index 3e6eaa7a..250f3b48 100644 --- a/server/driver/hand_joints_list.cpp +++ b/server/driver/hand_joints_list.cpp @@ -28,19 +28,18 @@ static_assert(XRT_HAND_JOINT_COUNT == XR_HAND_JOINT_COUNT_EXT); namespace { - xrt_hand_joint_value interpolate(const xrt_hand_joint_value & a, const xrt_hand_joint_value & b, float t) - { - return { - .relation = pose_list::interpolate(a.relation, b.relation, t), - .radius = a.radius * (1-t) + b.radius * t - }; - } +xrt_hand_joint_value interpolate(const xrt_hand_joint_value & a, const xrt_hand_joint_value & b, float t) +{ + return { + .relation = pose_list::interpolate(a.relation, b.relation, t), + .radius = a.radius * (1 - t) + b.radius * t}; } +} // namespace xrt_hand_joint_set hand_joints_list::interpolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, float t) { xrt_hand_joint_set j = a; - for(int i = 0; i < XRT_HAND_JOINT_COUNT; i++) + for (int i = 0; i < XRT_HAND_JOINT_COUNT; i++) { j.values.hand_joint_set_default[i] = ::interpolate(a.values.hand_joint_set_default[i], b.values.hand_joint_set_default[i], t); } @@ -49,7 +48,7 @@ xrt_hand_joint_set hand_joints_list::interpolate(const xrt_hand_joint_set & a, c xrt_hand_joint_set hand_joints_list::extrapolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, uint64_t ta, uint64_t tb, uint64_t t) { - xrt_hand_joint_set j = t <= ta ? a : b; + xrt_hand_joint_set j = t <= ta ? a : b; // Only extrapolate the hand pose, individual joints are too noisy j.hand_pose = pose_list::extrapolate(a.hand_pose, b.hand_pose, ta, tb, t); return j; @@ -78,17 +77,17 @@ static xrt_space_relation_flags cast_flags(uint8_t in_flags) return xrt_space_relation_flags(flags); } -static xrt_space_relation to_relation(const from_headset::hand_tracking::pose& pose) +static xrt_space_relation to_relation(const from_headset::hand_tracking::pose & pose) { return { - .relation_flags = cast_flags(pose.flags), - .pose = xrt_cast(pose.pose), - .linear_velocity = xrt_cast(pose.linear_velocity), - .angular_velocity = xrt_cast(pose.angular_velocity), + .relation_flags = cast_flags(pose.flags), + .pose = xrt_cast(pose.pose), + .linear_velocity = xrt_cast(pose.linear_velocity), + .angular_velocity = xrt_cast(pose.angular_velocity), }; } -static xrt_hand_joint_set convert_joints(const std::optional>& input_joints) +static xrt_hand_joint_set convert_joints(const std::optional> & input_joints) { xrt_hand_joint_set output_joints{}; @@ -101,9 +100,9 @@ static xrt_hand_joint_set convert_joints(const std::optional { int hand_id; @@ -31,7 +30,8 @@ public: static xrt_hand_joint_set interpolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, float t); static xrt_hand_joint_set extrapolate(const xrt_hand_joint_set & a, const xrt_hand_joint_set & b, uint64_t ta, uint64_t tb, uint64_t t); - hand_joints_list(int hand_id) : hand_id(hand_id) {} + hand_joints_list(int hand_id) : + hand_id(hand_id) {} void update_tracking(const xrt::drivers::wivrn::from_headset::hand_tracking & tracking, const clock_offset & offset); }; diff --git a/server/driver/history.h b/server/driver/history.h index 8a902d32..7a74ecb4 100644 --- a/server/driver/history.h +++ b/server/driver/history.h @@ -19,12 +19,12 @@ #pragma once +#include "clock_offset.h" +#include #include #include #include #include -#include -#include "clock_offset.h" template class history @@ -97,7 +97,8 @@ public: const auto & d1 = data.back(); return Derived::extrapolate(d0, d1, d0.at_timestamp_ns, d1.at_timestamp_ns, at_timestamp_ns); } - else { + else + { return data.back(); } } diff --git a/server/driver/pose_list.cpp b/server/driver/pose_list.cpp index 29430815..588bdcc4 100644 --- a/server/driver/pose_list.cpp +++ b/server/driver/pose_list.cpp @@ -41,7 +41,7 @@ xrt_space_relation pose_list::extrapolate(const xrt_space_relation & a, const xr xrt_space_relation res = t < ta ? a : b; - xrt_vec3 lin_vel = res.relation_flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT ? res.linear_velocity : (b.pose.position - a.pose.position ) / h; + xrt_vec3 lin_vel = res.relation_flags & XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT ? res.linear_velocity : (b.pose.position - a.pose.position) / h; float dt = (t - tb) / 1.e9; diff --git a/server/driver/pose_list.h b/server/driver/pose_list.h index eb5c175a..40cc75f0 100644 --- a/server/driver/pose_list.h +++ b/server/driver/pose_list.h @@ -19,12 +19,11 @@ #pragma once -#include "wivrn_packets.h" #include "clock_offset.h" #include "history.h" +#include "wivrn_packets.h" #include "xrt/xrt_defines.h" - class pose_list : public history { xrt::drivers::wivrn::device_id device; diff --git a/server/driver/view_list.h b/server/driver/view_list.h index f98a90d2..49aeee90 100644 --- a/server/driver/view_list.h +++ b/server/driver/view_list.h @@ -30,7 +30,6 @@ struct tracked_views std::array fovs; }; - class view_list : public history { public: diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index 020dd862..c2ddce6b 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -21,7 +21,6 @@ #include "encoder/video_encoder.h" #include "main/comp_compositor.h" #include "math/m_space.h" -#include "encoder/video_encoder.h" #include "xrt_cast.h" #include #include @@ -540,12 +539,12 @@ static VkResult comp_wivrn_present(struct comp_target * ct, view_info.display_time = cn->cnx->get_offset().to_headset(desired_present_time_ns); for (int eye = 0; eye < 2; ++eye) { - const auto &slot = cn->c->base.slot; + const auto & slot = cn->c->base.slot; view_info.fov[eye] = xrt_cast(slot.fovs[eye]); view_info.pose[eye] = xrt_cast(slot.poses[eye]); if (cn->c->debug.atw_off) { - const auto &stereo = slot.layers[0].data.stereo; + const auto & stereo = slot.layers[0].data.stereo; view_info.pose[eye] = xrt_cast(eye ? stereo.r.pose : stereo.l.pose); } else diff --git a/server/driver/wivrn_comp_target.h b/server/driver/wivrn_comp_target.h index d88d2992..42b28e17 100644 --- a/server/driver/wivrn_comp_target.h +++ b/server/driver/wivrn_comp_target.h @@ -28,12 +28,12 @@ #include "utils/wivrn_vk_bundle.h" #include "vk/allocation.h" +#include "driver/wivrn_pacer.h" #include #include #include #include #include -#include "driver/wivrn_pacer.h" #include namespace xrt::drivers::wivrn @@ -74,8 +74,8 @@ struct wivrn_comp_target : public comp_target VkColorSpaceKHR color_space; - static std::vector wanted_instance_extensions; - static std::vector wanted_device_extensions; + static std::vector wanted_instance_extensions; + static std::vector wanted_device_extensions; struct encoder_thread { diff --git a/server/driver/wivrn_connection.cpp b/server/driver/wivrn_connection.cpp index 083a5159..cff0b99d 100644 --- a/server/driver/wivrn_connection.cpp +++ b/server/driver/wivrn_connection.cpp @@ -29,11 +29,11 @@ wivrn_connection::wivrn_connection(TCP && tcp) : { sockaddr_in6 server_address; socklen_t len = sizeof(server_address); - if (getsockname(control.get_fd(), (sockaddr*)&server_address, &len) < 0) + if (getsockname(control.get_fd(), (sockaddr *)&server_address, &len) < 0) { throw std::system_error(errno, std::system_category(), "Cannot get socket port"); } - int port = ntohs(((struct sockaddr_in6*)&server_address)->sin6_port); + int port = ntohs(((struct sockaddr_in6 *)&server_address)->sin6_port); sockaddr_in6 client_address; len = sizeof(client_address); @@ -78,7 +78,6 @@ wivrn_connection::wivrn_connection(TCP && tcp) : stream.set_send_buffer_size(1024 * 1024 * 5); break; } - } if (std::chrono::steady_clock::now() > timeout) @@ -92,7 +91,7 @@ wivrn_connection::wivrn_connection(TCP && tcp) : // Set Expedited forwarding https://datatracker.ietf.org/doc/html/rfc3246 stream.set_tos(IPTOS_DSCP_EF); } - catch (std::exception& e) + catch (std::exception & e) { U_LOG_I("Failed to set IP ToS to Expedited Forwarding: %s", e.what()); } diff --git a/server/driver/wivrn_controller.cpp b/server/driver/wivrn_controller.cpp index 12220c32..35a0f9d3 100644 --- a/server/driver/wivrn_controller.cpp +++ b/server/driver/wivrn_controller.cpp @@ -111,24 +111,24 @@ static const size_t left_hand_bindings_count = ARRAY_SIZE(left_hand_bindings); static const size_t right_hand_bindings_count = ARRAY_SIZE(right_hand_bindings); static xrt_binding_input_pair simple_input_binding[] = { - {XRT_INPUT_SIMPLE_SELECT_CLICK, XRT_INPUT_TOUCH_TRIGGER_VALUE}, - {XRT_INPUT_SIMPLE_MENU_CLICK, XRT_INPUT_TOUCH_MENU_CLICK}, - {XRT_INPUT_SIMPLE_GRIP_POSE, XRT_INPUT_TOUCH_GRIP_POSE}, - {XRT_INPUT_SIMPLE_AIM_POSE, XRT_INPUT_TOUCH_AIM_POSE}, + {XRT_INPUT_SIMPLE_SELECT_CLICK, XRT_INPUT_TOUCH_TRIGGER_VALUE}, + {XRT_INPUT_SIMPLE_MENU_CLICK, XRT_INPUT_TOUCH_MENU_CLICK}, + {XRT_INPUT_SIMPLE_GRIP_POSE, XRT_INPUT_TOUCH_GRIP_POSE}, + {XRT_INPUT_SIMPLE_AIM_POSE, XRT_INPUT_TOUCH_AIM_POSE}, }; static xrt_binding_output_pair simple_output_binding[] = { - {XRT_OUTPUT_NAME_SIMPLE_VIBRATION, XRT_OUTPUT_NAME_TOUCH_HAPTIC}, + {XRT_OUTPUT_NAME_SIMPLE_VIBRATION, XRT_OUTPUT_NAME_TOUCH_HAPTIC}, }; static xrt_binding_profile wivrn_binding_profiles[] = { - { - .name = XRT_DEVICE_SIMPLE_CONTROLLER, - .inputs = simple_input_binding, - .input_count = std::size(simple_input_binding), - .outputs = simple_output_binding, - .output_count = std::size(simple_output_binding), - }, + { + .name = XRT_DEVICE_SIMPLE_CONTROLLER, + .inputs = simple_input_binding, + .input_count = std::size(simple_input_binding), + .outputs = simple_output_binding, + .output_count = std::size(simple_output_binding), + }, }; static void wivrn_controller_destroy(xrt_device * xdev); @@ -139,10 +139,10 @@ static void wivrn_controller_get_tracked_pose(xrt_device * xdev, xrt_space_relation * out_relation); static void wivrn_controller_get_hand_tracking(xrt_device * xdev, - xrt_input_name name, - uint64_t desired_timestamp_ns, - xrt_hand_joint_set * out_value, - uint64_t *out_timestamp_ns); + xrt_input_name name, + uint64_t desired_timestamp_ns, + xrt_hand_joint_set * out_value, + uint64_t * out_timestamp_ns); static void wivrn_controller_set_output(struct xrt_device * xdev, enum xrt_output_name name, const union xrt_output_value * value); @@ -152,10 +152,10 @@ wivrn_controller::wivrn_controller(int hand_id, xrt_device * hmd, std::shared_ptr cnx) : xrt_device{}, - grip(hand_id == 0 ? device_id::LEFT_GRIP : device_id::RIGHT_GRIP), - aim(hand_id == 0 ? device_id::LEFT_AIM : device_id::RIGHT_AIM), - joints(hand_id), - cnx(cnx) + grip(hand_id == 0 ? device_id::LEFT_GRIP : device_id::RIGHT_GRIP), + aim(hand_id == 0 ? device_id::LEFT_AIM : device_id::RIGHT_AIM), + joints(hand_id), + cnx(cnx) { xrt_device * base = this; @@ -252,7 +252,7 @@ void wivrn_controller::update_inputs() inputs_array = inputs_staging; } -void wivrn_controller::set_inputs(const from_headset::inputs & inputs, const clock_offset& clock_offset) +void wivrn_controller::set_inputs(const from_headset::inputs & inputs, const clock_offset & clock_offset) { std::lock_guard lock{mutex}; for (const auto & input: inputs.values) @@ -325,11 +325,11 @@ xrt_space_relation wivrn_controller::get_tracked_pose(xrt_input_name name, uint6 std::pair wivrn_controller::get_hand_tracking(xrt_input_name name, uint64_t desired_timestamp_ns) { - switch(name) + switch (name) { case XRT_INPUT_GENERIC_HAND_TRACKING_LEFT: case XRT_INPUT_GENERIC_HAND_TRACKING_RIGHT: - return { joints.get_at(desired_timestamp_ns), desired_timestamp_ns }; + return {joints.get_at(desired_timestamp_ns), desired_timestamp_ns}; default: U_LOG_W("Unknown input name requested"); @@ -392,10 +392,10 @@ static void wivrn_controller_get_tracked_pose(xrt_device * xdev, } static void wivrn_controller_get_hand_tracking(xrt_device * xdev, - xrt_input_name name, - uint64_t desired_timestamp_ns, - xrt_hand_joint_set * out_value, - uint64_t *out_timestamp_ns) + xrt_input_name name, + uint64_t desired_timestamp_ns, + xrt_hand_joint_set * out_value, + uint64_t * out_timestamp_ns) { std::tie(*out_value, *out_timestamp_ns) = static_cast(xdev)->get_hand_tracking(name, desired_timestamp_ns); } diff --git a/server/driver/wivrn_controller.h b/server/driver/wivrn_controller.h index afa5e676..fe3cd329 100644 --- a/server/driver/wivrn_controller.h +++ b/server/driver/wivrn_controller.h @@ -21,8 +21,8 @@ #include "xrt/xrt_device.h" -#include "pose_list.h" #include "hand_joints_list.h" +#include "pose_list.h" #include "wivrn_session.h" #include diff --git a/server/driver/wivrn_hmd.cpp b/server/driver/wivrn_hmd.cpp index d3a5324a..65c4dc57 100644 --- a/server/driver/wivrn_hmd.cpp +++ b/server/driver/wivrn_hmd.cpp @@ -91,7 +91,7 @@ static std::tuple solve_foveation(float λ, float c) // // Use eq. 2 to express a as function of b, then replace in eq. 1 // equation that needs to be null is: - auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a;}; + auto b = [λ, c](double a) { return atan(a * (1 - c) / λ) - a; }; auto eq = [λ, c](double a) { return atan(a * (1 - c) / λ) + atan(a * (1 + c) / λ) - 2 * a; }; // (eq. 3) // function starts positive, reaches a maximum then decreases to -∞ diff --git a/server/driver/wivrn_pacer.h b/server/driver/wivrn_pacer.h index 032cb5ba..2446054d 100644 --- a/server/driver/wivrn_pacer.h +++ b/server/driver/wivrn_pacer.h @@ -41,7 +41,8 @@ class wivrn_pacer uint64_t last_wake_up_ns = 0; // Client wait time for each decoder - struct stream_data{ + struct stream_data + { // Last feedback for each encoder xrt::drivers::wivrn::from_headset::feedback last_feedback; std::vector times; @@ -49,7 +50,8 @@ class wivrn_pacer }; std::vector streams; - struct frame_history{ + struct frame_history + { uint64_t frame_id; uint64_t present_ns; }; @@ -69,7 +71,7 @@ public: uint64_t & out_present_slop_ns, uint64_t & out_predicted_display_time_ns); - void on_feedback(const xrt::drivers::wivrn::from_headset::feedback &, const clock_offset&); + void on_feedback(const xrt::drivers::wivrn::from_headset::feedback &, const clock_offset &); void mark_timing_point( comp_target_timing_point point, diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index d1f30e42..cc4ba66c 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -74,7 +74,7 @@ public: clock_offset get_offset(); - void operator()(from_headset::handshake&&) {} + void operator()(from_headset::handshake &&) {} void operator()(from_headset::headset_info_packet &&); void operator()(from_headset::tracking &&); void operator()(from_headset::hand_tracking &&); @@ -97,7 +97,7 @@ public: std::array get_foveation_parameters(); - void dump_time(const std::string & event, uint64_t frame, uint64_t time, uint8_t stream = -1, const char* extra = ""); + void dump_time(const std::string & event, uint64_t frame, uint64_t time, uint8_t stream = -1, const char * extra = ""); private: static void run(std::weak_ptr); diff --git a/server/encoder/encoder_settings.cpp b/server/encoder/encoder_settings.cpp index 79ca4640..2a75f1b0 100644 --- a/server/encoder/encoder_settings.cpp +++ b/server/encoder/encoder_settings.cpp @@ -43,10 +43,10 @@ static bool is_nvidia(vk::PhysicalDevice physical_device) return props.vendorID == 0x10DE; } -static void split_bitrate(std::vector &encoders, uint64_t bitrate) +static void split_bitrate(std::vector & encoders, uint64_t bitrate) { double total_weight = 0; - for (auto& encoder: encoders) + for (auto & encoder: encoders) { double w = encoder.width * encoder.height; switch (encoder.codec) @@ -61,7 +61,7 @@ static void split_bitrate(std::vector &en total_weight += w; } - for (auto& encoder: encoders) + for (auto & encoder: encoders) { encoder.bitrate = encoder.bitrate * bitrate / total_weight; } @@ -94,21 +94,21 @@ static std::vector get_encoder_default_se else { #ifdef WIVRN_USE_VAAPI -/* Split in 3 parts: - * +--------+--------+ - * | | | - * | | | - * +--------+ | - * | | | - * | | | - * | | | - * | | | - * | | | - * +--------+--------+ - * All 3 are encoded sequentially, so that the smallest is ready earlier. - * Decoder can start work as fast as possible, reducing idle time. - * - */ + /* Split in 3 parts: + * +--------+--------+ + * | | | + * | | | + * +--------+ | + * | | | + * | | | + * | | | + * | | | + * | | | + * +--------+--------+ + * All 3 are encoded sequentially, so that the smallest is ready earlier. + * Decoder can start work as fast as possible, reducing idle time. + * + */ settings.encoder_name = encoder_vaapi; settings.width = std::ceil(width * 0.5); std::vector encoders(3, settings); @@ -133,9 +133,9 @@ static std::vector get_encoder_default_se return {settings}; } -static void make_even(uint16_t& value, uint16_t max) +static void make_even(uint16_t & value, uint16_t max) { - value += value %2; + value += value % 2; value = std::min(value, max); } diff --git a/server/encoder/ffmpeg/video_encoder_va.cpp b/server/encoder/ffmpeg/video_encoder_va.cpp index a3c6883f..117f712e 100644 --- a/server/encoder/ffmpeg/video_encoder_va.cpp +++ b/server/encoder/ffmpeg/video_encoder_va.cpp @@ -94,7 +94,7 @@ get_render_device(vk::raii::PhysicalDevice & physical_device) return path; } -av_buffer_ptr make_drm_hw_ctx(vk::raii::PhysicalDevice & physical_device, const std::optional& device) +av_buffer_ptr make_drm_hw_ctx(vk::raii::PhysicalDevice & physical_device, const std::optional & device) { const auto render_device = device ? *device : get_render_device(physical_device); AVBufferRef * hw_ctx; diff --git a/server/encoder/ffmpeg/video_encoder_va.h b/server/encoder/ffmpeg/video_encoder_va.h index bbf9bf52..213d9d02 100644 --- a/server/encoder/ffmpeg/video_encoder_va.h +++ b/server/encoder/ffmpeg/video_encoder_va.h @@ -19,9 +19,9 @@ #pragma once -#include "video_encoder_ffmpeg.h" #include "ffmpeg_helper.h" #include "utils/wivrn_vk_bundle.h" +#include "video_encoder_ffmpeg.h" #include namespace xrt::drivers::wivrn @@ -40,7 +40,7 @@ class video_encoder_va : public VideoEncoderFFMPEG std::vector mem; public: - video_encoder_va(wivrn_vk_bundle&, xrt::drivers::wivrn::encoder_settings & settings, float fps); + video_encoder_va(wivrn_vk_bundle &, xrt::drivers::wivrn::encoder_settings & settings, float fps); void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index 725bca75..6b00c53e 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -72,7 +72,7 @@ std::unique_ptr VideoEncoder::Create( throw std::runtime_error("Failed to create encoder " + settings.encoder_name); res->stream_idx = stream_idx; - auto wivrn_dump_video= std::getenv("WIVRN_DUMP_VIDEO"); + auto wivrn_dump_video = std::getenv("WIVRN_DUMP_VIDEO"); if (wivrn_dump_video) { std::string file(wivrn_dump_video); @@ -124,7 +124,7 @@ void VideoEncoder::SendData(std::span data, bool end_of_frame) if (end_of_frame) timing_info.send_end = clock.to_headset(os_monotonic_get_ns()); if (video_dump) - video_dump.write((char*)data.data(), data.size()); + video_dump.write((char *)data.data(), data.size()); if (shard.shard_idx == 0) { cnx->dump_time("send_begin", shard.frame_idx, os_monotonic_get_ns(), stream_idx); diff --git a/server/encoder/video_encoder_nvenc.cpp b/server/encoder/video_encoder_nvenc.cpp index e9c43c34..95348859 100644 --- a/server/encoder/video_encoder_nvenc.cpp +++ b/server/encoder/video_encoder_nvenc.cpp @@ -287,7 +287,7 @@ void VideoEncoderNvenc::PresentImage(yuv_converter & src_yuv, vk::raii::CommandB *yuv_buffer, vk::BufferImageCopy{ .bufferOffset = pitch * rect.extent.height, - .bufferRowLength = uint32_t(pitch/2), + .bufferRowLength = uint32_t(pitch / 2), .imageSubresource = { .aspectMask = vk::ImageAspectFlagBits::eColor, .layerCount = 1, diff --git a/server/encoder/video_encoder_nvenc.h b/server/encoder/video_encoder_nvenc.h index db783678..5bf36742 100644 --- a/server/encoder/video_encoder_nvenc.h +++ b/server/encoder/video_encoder_nvenc.h @@ -29,7 +29,7 @@ namespace xrt::drivers::wivrn class VideoEncoderNvenc : public VideoEncoder { - wivrn_vk_bundle& vk; + wivrn_vk_bundle & vk; // relevant part of the input image to encode vk::Rect2D rect; @@ -51,10 +51,10 @@ class VideoEncoderNvenc : public VideoEncoder int bitrate; public: - VideoEncoderNvenc(wivrn_vk_bundle& vk, const encoder_settings & settings, float fps); + VideoEncoderNvenc(wivrn_vk_bundle & vk, const encoder_settings & settings, float fps); void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; - void Encode( bool idr, std::chrono::steady_clock::time_point pts) override; + void Encode(bool idr, std::chrono::steady_clock::time_point pts) override; }; } // namespace xrt::drivers::wivrn diff --git a/server/encoder/video_encoder_x264.h b/server/encoder/video_encoder_x264.h index 557409a7..13ed9c6f 100644 --- a/server/encoder/video_encoder_x264.h +++ b/server/encoder/video_encoder_x264.h @@ -57,7 +57,7 @@ class VideoEncoderX264 : public VideoEncoder std::list pending_nals; public: - VideoEncoderX264(wivrn_vk_bundle& vk, encoder_settings & settings, float fps); + VideoEncoderX264(wivrn_vk_bundle & vk, encoder_settings & settings, float fps); void PresentImage(yuv_converter & src_yuv, vk::raii::CommandBuffer & cmd_buf) override; diff --git a/server/encoder/yuv_converter.h b/server/encoder/yuv_converter.h index 9d38d35d..b26bd3fe 100644 --- a/server/encoder/yuv_converter.h +++ b/server/encoder/yuv_converter.h @@ -28,9 +28,11 @@ class yuv_converter vk::Extent2D extent; vk::Image rgb; + public: image_allocation luma; image_allocation chroma; + private: vk::raii::ImageView view_rgb = nullptr; vk::raii::ImageView view_luma = nullptr; @@ -44,13 +46,13 @@ private: std::vector mem; - public: +public: yuv_converter(); - yuv_converter(vk::PhysicalDevice, vk::raii::Device& device, vk::Image rgb, vk::Format format, vk::Extent2D extent); + yuv_converter(vk::PhysicalDevice, vk::raii::Device & device, vk::Image rgb, vk::Format format, vk::Extent2D extent); // Converts the given image to yuv, stored in luma and chroma images. // The output images will be in transfer src optimal layout - void record_draw_commands(vk::raii::CommandBuffer& cmd_buf); + void record_draw_commands(vk::raii::CommandBuffer & cmd_buf); - void assemble_planes(vk::Rect2D, vk::raii::CommandBuffer&, vk::Image target); + void assemble_planes(vk::Rect2D, vk::raii::CommandBuffer &, vk::Image target); }; diff --git a/server/hostname.cpp b/server/hostname.cpp index faff0de0..e39cf06b 100644 --- a/server/hostname.cpp +++ b/server/hostname.cpp @@ -11,7 +11,6 @@ std::string hostname() { - #ifdef WIVRN_USE_SYSTEMD sd_bus * bus; if (sd_bus_default_system(&bus) < 0) diff --git a/server/main.cpp b/server/main.cpp index fa9657b9..7a029dd2 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -25,11 +25,11 @@ #include "version.h" #include "wivrn_config.h" +#include "active_runtime.h" #include "avahi_publisher.h" #include "hostname.h" #include #include -#include "active_runtime.h" // Insert the on load constructor to init trace marker. U_TRACE_TARGET_SETUP(U_TRACE_WHICH_SERVICE) @@ -265,7 +265,7 @@ int inner_main(int argc, char * argv[]) setenv("LISTEN_PID", std::to_string(getpid()).c_str(), true); - //FIXME: synchronization fails on gfx pipeline + // FIXME: synchronization fails on gfx pipeline setenv("XRT_COMPOSITOR_COMPUTE", "1", true); try diff --git a/server/pidfd.h b/server/pidfd.h index c9b7148d..afca46c4 100644 --- a/server/pidfd.h +++ b/server/pidfd.h @@ -28,12 +28,11 @@ extern "C" #else #include -#include -#include #include +#include +#include #include - #ifndef __NR_pidfd_open #define __NR_pidfd_open 434 #endif @@ -45,7 +44,7 @@ static int pidfd_open(pid_t pid, unsigned int flags) #ifndef __NR_pidfd_send_signal #define __NR_pidfd_send_signal 424 #endif -static int pidfd_send_signal(int pidfd, int sig, siginfo_t *info, unsigned int flags) +static int pidfd_send_signal(int pidfd, int sig, siginfo_t * info, unsigned int flags) { return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags); } diff --git a/server/utils/wivrn_vk_bundle.h b/server/utils/wivrn_vk_bundle.h index 584594e4..e740f4d7 100644 --- a/server/utils/wivrn_vk_bundle.h +++ b/server/utils/wivrn_vk_bundle.h @@ -31,7 +31,7 @@ struct vk_bundle; // however we don't own it, so deactivate the destructor struct raii_instance : public vk::raii::Instance { - raii_instance(vk::raii::Context &ctx, VkInstance i) : + raii_instance(vk::raii::Context & ctx, VkInstance i) : vk::raii::Instance(ctx, i) {} raii_instance & operator=(raii_instance &&) noexcept = default; ~raii_instance() @@ -60,10 +60,10 @@ struct wivrn_vk_bundle vk::raii::Queue queue; uint32_t queue_family_index; - std::vector instance_extensions; - std::vector device_extensions; + std::vector instance_extensions; + std::vector device_extensions; - wivrn_vk_bundle(vk_bundle& vk, std::span requested_instance_extensions, std::span requested_device_extensions); + wivrn_vk_bundle(vk_bundle & vk, std::span requested_instance_extensions, std::span requested_device_extensions); uint32_t get_memory_type(uint32_t type_bits, vk::MemoryPropertyFlags memory_props); }; diff --git a/server/wivrn_ipc.cpp b/server/wivrn_ipc.cpp index 1819b75c..b5e074cd 100644 --- a/server/wivrn_ipc.cpp +++ b/server/wivrn_ipc.cpp @@ -42,7 +42,7 @@ void init_cleanup_functions() void add_cleanup_function(void (*callback)(uintptr_t), uintptr_t userdata) { - for(auto& i: *cleanup_functions) + for (auto & i: *cleanup_functions) { if (i.callback == nullptr) { @@ -54,7 +54,7 @@ void add_cleanup_function(void (*callback)(uintptr_t), uintptr_t userdata) void remove_cleanup_function(void (*callback)(uintptr_t), uintptr_t userdata) { - for(auto& i: *cleanup_functions) + for (auto & i: *cleanup_functions) { if (i.callback == callback && i.userdata == userdata) { @@ -67,7 +67,7 @@ void remove_cleanup_function(void (*callback)(uintptr_t), uintptr_t userdata) void run_cleanup_functions() { // Don't fork if cleanup_functions is empty - if (std::ranges::all_of(*cleanup_functions, [](auto& i){ return i.callback == nullptr; })) + if (std::ranges::all_of(*cleanup_functions, [](auto & i) { return i.callback == nullptr; })) return; // Fork because pulseaudio doesn't like being initialized in the parent and the child @@ -80,7 +80,7 @@ void run_cleanup_functions() } else if (child == 0) { - for(auto& i: *cleanup_functions) + for (auto & i: *cleanup_functions) { if (i.callback) {