diff --git a/build.gradle b/build.gradle index b0dd3325..f4512f7a 100644 --- a/build.gradle +++ b/build.gradle @@ -124,6 +124,7 @@ android { '-DCMAKE_ANDROID_NDK_VERSION=' + ndkVersion, '-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', + '-DWIVRN_USE_SYSTEM_BOOST=OFF', '-DWIVRN_USE_SYSTEM_FREETYPE=OFF', '-DWIVRN_BUILD_CLIENT=ON', '-DWIVRN_BUILD_SERVER=OFF', diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index d2c1770e..8245a853 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -13,7 +13,7 @@ if (WIVRN_USE_LIBKTX) FetchContent_MakeAvailable(libktx) endif() -if (NOT BOOST_FOUND) +if (NOT WIVRN_USE_SYSTEM_BOOST) FetchContent_MakeAvailable(boost) endif() @@ -51,7 +51,7 @@ if(ANDROID) else() add_executable(wivrn) - if (OpenXR_FOUND) + if (WIVRN_USE_SYSTEM_OPENXR) target_link_libraries(wivrn OpenXR::openxr_loader OpenXR::headers) else() FetchContent_MakeAvailable(openxr_loader) @@ -91,7 +91,22 @@ file(GLOB_RECURSE VULKAN_SHADERS CONFIGURE_DEPENDS "*.glsl") target_sources(wivrn PRIVATE ${LOCAL_SOURCE} ${VULKAN_SHADERS}) wivrn_compile_glsl(wivrn SHADERS ${VULKAN_SHADERS}) -target_link_libraries(wivrn Vulkan::Vulkan spdlog::spdlog glm::glm fastgltf FreetypeHarfbuzz stb Boost::url Boost::locale) +target_link_libraries(wivrn + Boost::locale + Boost::url + EnTT::EnTT + fastgltf + FreetypeHarfbuzz + glm::glm + imspinner + simdjson + spdlog::spdlog + stb + uni-algo + Vulkan::Vulkan + wivrn-common + wivrn-external +) if (WIVRN_USE_LIBKTX) target_link_libraries(wivrn ktx_read) @@ -107,10 +122,6 @@ if(NOT ANDROID) install(TARGETS wivrn) endif() -target_link_libraries(wivrn simdjson uni-algo wivrn-common wivrn-external) - - - ############################################################################## # Dear ImGui # @@ -140,10 +151,6 @@ target_link_libraries(wivrn-imgui FreetypeHarfbuzz) target_link_libraries(wivrn wivrn-imgui) -############################################################################## -# EnTT -# -target_link_libraries(wivrn EnTT::EnTT) ############################################################################## # Vulkan Validation Layer @@ -230,7 +237,7 @@ add_custom_command(OUTPUT ${ASSETS_DIR}/wivrn.png DEPENDS ${IMG_SRC_DIR}/wivrn.svg ${WIVRN_CSS_ABS}) add_custom_target(assets ALL DEPENDS - ${ASSETS_DIR}/wivrn.png) + ${ASSETS_DIR}/wivrn.png) add_dependencies(wivrn assets) @@ -251,8 +258,8 @@ if(ANDROID) add_custom_target(assets-android ALL DEPENDS ${ASSETS_DIR}/wivrn.ktx2 ${ASSETS_DIR}/WoodFloor051_1K-JPG_Color.ktx2 - ${ASSETS_DIR}/vr_splash.png) - + ${ASSETS_DIR}/vr_splash.png + ) add_dependencies(assets-android assets) add_dependencies(wivrn assets-android) endif() diff --git a/client/application.cpp b/client/application.cpp index b0433274..24082765 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -18,7 +18,7 @@ */ #include "application.h" -#include "asset.h" + #include "hardware.h" #include "openxr/openxr.h" #include "scene.h" @@ -26,18 +26,23 @@ #include "spdlog/spdlog.h" #include "utils/contains.h" #include "utils/files.h" +#include "utils/i18n.h" #include "vk/check.h" #include "wifi_lock.h" +#include "wivrn_packets.h" #include "xr/actionset.h" #include "xr/check.h" +#include "xr/htc_exts.h" +#include "xr/htc_face_tracker.h" #include "xr/meta_body_tracking_fidelity.h" -#include "xr/xr.h" +#include "xr/to_string.h" #include #include #include #include #include #include +#include #include #include #include @@ -67,7 +72,6 @@ struct interaction_profile std::string profile_name; std::vector required_extensions; XrVersion min_version = XR_MAKE_VERSION(1, 0, 0); - XrVersion max_version = XR_MAKE_VERSION(2, 0, 0); // exclusive std::vector input_sources; bool available; }; @@ -134,8 +138,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/facebook/touch_controller_pro", - .required_extensions = {"XR_FB_touch_controller_pro"}, - .max_version = XR_MAKE_VERSION(1, 1, 0), + .required_extensions = {XR_FB_TOUCH_CONTROLLER_PRO_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/left/output/haptic_trigger_fb", @@ -247,8 +250,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/meta/touch_controller_plus", - .required_extensions = {"XR_META_touch_controller_plus"}, - .max_version = XR_MAKE_VERSION(1, 1, 0), + .required_extensions = {XR_META_TOUCH_CONTROLLER_PLUS_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -348,7 +350,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/bytedance/pico_neo3_controller", - .required_extensions = {"XR_BD_controller_interaction"}, + .required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -391,7 +393,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/bytedance/pico4_controller", - .required_extensions = {"XR_BD_controller_interaction"}, + .required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -434,7 +436,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/bytedance/pico4s_controller", - .required_extensions = {"XR_BD_controller_interaction"}, + .required_extensions = {XR_BD_CONTROLLER_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -477,7 +479,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/htc/vive_focus3_controller", - .required_extensions = {"XR_HTC_vive_focus3_controller_interaction"}, + .required_extensions = {XR_HTC_VIVE_FOCUS3_CONTROLLER_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/hand/left/output/haptic", "/user/hand/right/output/haptic", @@ -519,7 +521,7 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/ext/hand_interaction_ext", - .required_extensions = {"XR_EXT_hand_interaction"}, + .required_extensions = {XR_EXT_HAND_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/hand/left/input/aim/pose", "/user/hand/left/input/grip/pose", @@ -548,11 +550,14 @@ static std::vector interaction_profiles{ }, interaction_profile{ .profile_name = "/interaction_profiles/htc/vive_xr_tracker", - .required_extensions = {"XR_HTC_vive_xr_tracker_interaction", "XR_HTC_path_enumeration"}, + .required_extensions = { + XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME, + XR_HTC_PATH_ENUMERATION_EXTENSION_NAME, + }, }, interaction_profile{ .profile_name = "/interaction_profiles/ext/eye_gaze_interaction", - .required_extensions = {"XR_EXT_eye_gaze_interaction"}, + .required_extensions = {XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME}, .input_sources = { "/user/eyes_ext/input/gaze_ext/pose", }, @@ -649,6 +654,7 @@ VkBool32 application::vulkan_debug_report_callback( } #ifndef NDEBUG + bool my_error = true; if (level >= spdlog::level::warn) { bool validation_layer_found = false; @@ -659,10 +665,13 @@ VkBool32 application::vulkan_debug_report_callback( if (validation_layer_found && i.library != "libVkLayer_khronos_validation.so") spdlog::log(level, "{:#016x}: {} + {:#x}", i.pc, i.library, i.pc - i.library_base); + + if (i.library == "libopenxr_loader.so") + my_error = false; } } - if (level >= spdlog::level::err) + if (level >= spdlog::level::err and my_error) abort(); #endif @@ -717,15 +726,13 @@ void application::initialize_vulkan() spdlog::info("Using Vulkan validation layer"); layers.push_back("VK_LAYER_KHRONOS_validation"); } + bool debug_report_found = false; + bool debug_utils_found = false; #endif std::vector instance_extensions{}; std::unordered_set optional_device_extensions{}; -#ifndef NDEBUG - bool debug_report_found = false; - bool debug_utils_found = false; -#endif spdlog::info("Available Vulkan instance extensions:"); std::vector> extensions; for (vk::ExtensionProperties & i: vk_context.enumerateInstanceExtensionProperties(nullptr)) @@ -734,28 +741,27 @@ void application::initialize_vulkan() #ifndef NDEBUG if (!strcmp(i.extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME)) + { debug_report_found = true; + instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); + } - if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) + if (!strcmp(i.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) and + guess_model() != model::oculus_quest) // Quest 1 lies, the extension won't load + { debug_utils_found = true; + instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); + } #endif } std::ranges::sort(extensions); for (const auto & [extension_name, spec_version]: extensions) spdlog::info(" {} (version {})", extension_name, spec_version); -#ifndef NDEBUG - if (debug_utils_found && debug_report_found) - { - // debug_extensions_found = true; - // spdlog::info("Using debug extensions"); - instance_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); - // instance_extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); - } -#endif - vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); optional_device_extensions.emplace(VK_IMG_FILTER_CUBIC_EXTENSION_NAME); + optional_device_extensions.emplace(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); + optional_device_extensions.emplace(VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME); #ifdef __ANDROID__ vk_device_extensions.push_back(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME); @@ -874,6 +880,7 @@ void application::initialize_vulkan() .ppEnabledExtensionNames = vk_device_extensions.data(), .pEnabledFeatures = &device_features, }, + vk::PhysicalDeviceFragmentShadingRateFeaturesKHR{}, #ifdef __ANDROID__ vk::PhysicalDeviceSamplerYcbcrConversionFeaturesKHR{ .samplerYcbcrConversion = VK_TRUE, @@ -881,6 +888,22 @@ void application::initialize_vulkan() #endif }; + if (utils::contains(vk_device_extensions, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME) and + utils::contains(vk_device_extensions, VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME)) + { + auto [feat, fragment_feat] = vk_physical_device.getFeatures2(); + auto & create_feat = device_create_info.get(); + create_feat.primitiveFragmentShadingRate = fragment_feat.primitiveFragmentShadingRate; + create_feat.attachmentFragmentShadingRate = fragment_feat.attachmentFragmentShadingRate; + spdlog::info("Fragment shading rate features: primitive={} attachment={}", + create_feat.primitiveFragmentShadingRate, + create_feat.attachmentFragmentShadingRate); + } + else + { + device_create_info.unlink(); + } + vk_device = xr_system_id.create_device(vk_physical_device, device_create_info.get()); *vk_queue.lock() = vk_device.getQueue(vk_queue_family_index, 0); @@ -902,10 +925,16 @@ void application::initialize_vulkan() 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, + }, +#ifndef NDEBUG + debug_utils_found +#else + false +#endif + ); } void application::log_views() @@ -952,8 +981,6 @@ void application::initialize_actions() { spdlog::debug("Initializing actions"); - auto * htc_body = std::get_if(&body_tracker); - // Build an action set with all possible input sources std::vector action_sets; xr_actionset = xr::actionset(xr_instance, "all_actions", "All actions"); @@ -967,7 +994,8 @@ void application::initialize_actions() std::vector sources; for (auto & profile: interaction_profiles) { - profile.available = utils::contains_all(xr_extensions, profile.required_extensions) and profile.min_version <= api_version and profile.max_version > api_version; + profile.available = std::ranges::all_of(profile.required_extensions, [&](auto & ext) { return xr_instance.has_extension(ext); }) and + profile.min_version <= api_version; if (profile.profile_name.ends_with("khr/simple_controller")) { @@ -1008,15 +1036,15 @@ void application::initialize_actions() } if (add_palms) { - if ((api_version >= XR_MAKE_VERSION(1, 1, 0) or utils::contains(xr_extensions, XR_KHR_MAINTENANCE1_EXTENSION_NAME)) // - and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // + if ((api_version >= XR_MAKE_VERSION(1, 1, 0) or xr_instance.has_extension(XR_KHR_MAINTENANCE1_EXTENSION_NAME)) // + and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // and not utils::contains(profile.input_sources, "/user/hand/left/input/grip_surface/pose")) { spdlog::info("Adding grip_surface/pose for interaction profile {}", profile.profile_name); profile.input_sources.push_back("/user/hand/left/input/grip_surface/pose"); profile.input_sources.push_back("/user/hand/right/input/grip_surface/pose"); } - else if (utils::contains(xr_extensions, XR_EXT_PALM_POSE_EXTENSION_NAME) // + else if (xr_instance.has_extension(XR_EXT_PALM_POSE_EXTENSION_NAME) // and utils::contains(profile.input_sources, "/user/hand/left/input/grip/pose") // and not utils::contains(profile.input_sources, "/user/hand/left/input/palm_ext/pose")) { @@ -1027,14 +1055,15 @@ void application::initialize_actions() } // Dynamically add VIVE XR Trackers to the profile if available - if (htc_body && utils::contains(profile.required_extensions, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME)) + if (utils::contains(profile.required_extensions, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME) and + xr_instance.has_extension(XR_HTC_PATH_ENUMERATION_EXTENSION_NAME)) { - for (const auto & user_path: htc_body->get_paths()) + XrPath tracker_profile = xr_instance.string_to_path("/interaction_profiles/htc/vive_xr_tracker"); + for (const auto & user_path: xr_instance.enumerate_paths_for_interaction_profile(tracker_profile)) { - for (const auto & input_path: htc_body->get_paths(user_path)) - { - profile.input_sources.push_back(path_to_string(user_path) + path_to_string(input_path)); - } + generic_trackers.emplace_back(user_path, nullptr); + for (const auto & input_path: xr_instance.enumerate_paths_for_interaction_profile(tracker_profile, user_path)) + profile.input_sources.push_back(xr_instance.path_to_string(user_path) + xr_instance.path_to_string(input_path)); } } @@ -1082,8 +1111,14 @@ void application::initialize_actions() spaces[size_t(xr::spaces::poke_right)] = xr_session.create_action_space(a); else if (name == "/user/eyes_ext/input/gaze_ext/pose") spaces[size_t(xr::spaces::eye_gaze)] = xr_session.create_action_space(a); - else if (name.contains("/input/entity_htc/pose") && htc_body) - htc_body->add(xr_session.create_action_space(a)); + else if (name.contains("/input/entity_htc/pose")) + { + for (auto & [path, action]: generic_trackers) + { + if (name.starts_with(xr_instance.path_to_string(path))) + action = xr_session.create_action_space(a); + } + } } // Build an action set for each scene @@ -1120,7 +1155,7 @@ void application::initialize_actions() xr_bindings.push_back(XrActionSuggestedBinding{ .action = a, - .binding = string_to_path(k.input_source)}); + .binding = xr_instance.string_to_path(k.input_source)}); } } } @@ -1137,7 +1172,7 @@ void application::initialize_actions() for (const auto & name: profile.input_sources) { - xr_bindings.push_back({actions_by_name[name], string_to_path(name)}); + xr_bindings.push_back({actions_by_name[name], xr_instance.string_to_path(name)}); } try @@ -1157,7 +1192,7 @@ void application::initialize() { // LogLayersAndExtensions assert(!xr_instance); - xr_extensions.clear(); + std::vector xr_extensions; // Required extensions xr_extensions.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME); @@ -1230,21 +1265,16 @@ void application::initialize() spdlog::info(" Orientation tracking: {}", (bool)properties.trackingProperties.orientationTracking); spdlog::info(" Position tracking: {}", (bool)properties.trackingProperties.positionTracking); - if (utils::contains(xr_extensions, XR_EXT_HAND_TRACKING_EXTENSION_NAME)) - { - XrSystemHandTrackingPropertiesEXT hand_tracking_properties = xr_system_id.hand_tracking_properties(); - spdlog::info(" Hand tracking support: {}", (bool)hand_tracking_properties.supportsHandTracking); - hand_tracking_supported = hand_tracking_properties.supportsHandTracking; - } + spdlog::info(" Hand tracking support: {}", xr_system_id.hand_tracking_supported()); - if (utils::contains(xr_extensions, XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME)) + if (xr_instance.has_extension(XR_EXT_EYE_GAZE_INTERACTION_EXTENSION_NAME)) { XrSystemEyeGazeInteractionPropertiesEXT eye_gaze_properties = xr_system_id.eye_gaze_interaction_properties(); spdlog::info(" Eye gaze support: {}", (bool)eye_gaze_properties.supportsEyeGazeInteraction); eye_gaze_supported = eye_gaze_properties.supportsEyeGazeInteraction; } - if (utils::contains(xr_extensions, XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME)) + if (xr_instance.has_extension(XR_FB_COMPOSITION_LAYER_SETTINGS_EXTENSION_NAME)) { spdlog::info(" OpenXR post-processing extension support: true"); openxr_post_processing_supported = true; @@ -1252,93 +1282,45 @@ void application::initialize() switch (xr_system_id.passthrough_supported()) { - case xr::system::passthrough_type::no_passthrough: + case xr::passthrough_type::none: spdlog::info(" Passthrough: not supported"); break; - case xr::system::passthrough_type::bw: + case xr::passthrough_type::bw: spdlog::info(" Passthrough: black and white"); break; - case xr::system::passthrough_type::color: + case xr::passthrough_type::color: spdlog::info(" Passthrough: color"); break; } + spdlog::info(" Face tracker: {}", magic_enum::enum_name(xr_system_id.face_tracker_supported())); + spdlog::info(" Body tracker: {}", magic_enum::enum_name(xr_system_id.body_tracker_supported())); + // Log view configurations and blend modes log_views(); initialize_vulkan(); - xr_session = xr::session(xr_instance, xr_system_id, vk_instance, vk_physical_device, vk_device, vk_queue_family_index); - - { - auto spaces = xr_session.get_reference_spaces(); - spdlog::info("{} reference spaces", spaces.size()); - for (XrReferenceSpaceType i: spaces) - spdlog::info(" {}", xr::to_string(i)); - } + xr_session = xr::session(xr_instance, xr_system_id, vk_instance, vk_physical_device, vk_device, vk_queue, vk_queue_family_index); spaces[size_t(xr::spaces::view)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW); spaces[size_t(xr::spaces::world)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE); config.emplace(xr_system_id); - if (hand_tracking_supported) + // HTC face tracker fails if created later + // we can destroy it right away, it actually stores static handles + if (xr_system_id.face_tracker_supported() == xr::face_tracker_type::htc) { - left_hand = xr_session.create_hand_tracker(XR_HAND_LEFT_EXT); - right_hand = xr_session.create_hand_tracker(XR_HAND_RIGHT_EXT); + auto props = xr_system_id.htc_face_tracking_properties(); + xr::htc_face_tracker(xr_instance, xr_session, props.supportEyeFacialTracking, props.supportLipFacialTracking); } - if (utils::contains(xr_extensions, XR_FB_FACE_TRACKING2_EXTENSION_NAME)) { - XrSystemFaceTrackingProperties2FB fb_face2_properties = xr_system_id.fb_face_tracking2_properties(); - spdlog::info(" FB face tracking support: {}", (bool)fb_face2_properties.supportsVisualFaceTracking); - if (fb_face2_properties.supportsVisualFaceTracking) - face_tracker.emplace(xr_instance, xr_session); - } - - if (std::holds_alternative(face_tracker) && utils::contains(xr_extensions, XR_HTC_FACIAL_TRACKING_EXTENSION_NAME)) - { - XrSystemFacialTrackingPropertiesHTC htc_face_properties = xr_system_id.htc_face_tracking_properties(); - spdlog::info(" HTC eye tracking support: {}", (bool)htc_face_properties.supportEyeFacialTracking); - spdlog::info(" HTC lip tracking support: {}", (bool)htc_face_properties.supportLipFacialTracking); - if (htc_face_properties.supportEyeFacialTracking || htc_face_properties.supportLipFacialTracking) - face_tracker.emplace(xr_instance, xr_session, htc_face_properties.supportEyeFacialTracking, htc_face_properties.supportLipFacialTracking); - } - - if (std::holds_alternative(face_tracker) && eye_gaze_supported) - { - switch (guess_model()) - { - case model::pico_4_pro: - case model::pico_4_enterprise: - spdlog::info(" PICO face tracking support: true"); - face_tracker.emplace(xr_instance, xr_session); - break; - default: - break; - } - } - - if (utils::contains_all(xr_extensions, std::array{XR_FB_BODY_TRACKING_EXTENSION_NAME, XR_META_BODY_TRACKING_FULL_BODY_EXTENSION_NAME, XR_META_BODY_TRACKING_FIDELITY_EXTENSION_NAME})) - { - XrSystemBodyTrackingPropertiesFB fb_body_properties = xr_system_id.fb_body_tracking_properties(); - spdlog::info(" FB body tracking support: {}", (bool)fb_body_properties.supportsBodyTracking); - if (fb_body_properties.supportsBodyTracking) - body_tracker.emplace(xr_instance, xr_session); - } - - if (std::holds_alternative(body_tracker) && utils::contains_all(xr_extensions, std::array{XR_HTC_PATH_ENUMERATION_EXTENSION_NAME, XR_HTC_VIVE_XR_TRACKER_INTERACTION_EXTENSION_NAME})) - { - spdlog::info(" HTC body tracking support: true"); - body_tracker.emplace(xr_instance, xr_session); - } - - if (std::holds_alternative(body_tracker) && utils::contains(xr_extensions, XR_BD_BODY_TRACKING_EXTENSION_NAME)) - { - XrSystemBodyTrackingPropertiesBD bd_body_properties = xr_system_id.bd_body_tracking_properties(); - spdlog::info(" PICO body tracking support: {}", (bool)bd_body_properties.supportsBodyTracking); - if (bd_body_properties.supportsBodyTracking) - body_tracker.emplace(xr_instance, xr_session); + auto spaces = xr_session.get_reference_spaces(); + spdlog::info("{} reference spaces", spaces.size()); + for (XrReferenceSpaceType i: spaces) + spdlog::info(" {}", xr::to_string(i)); } vk::CommandPoolCreateInfo cmdpool_create_info; @@ -1348,50 +1330,47 @@ void application::initialize() vk_cmdpool = vk::raii::CommandPool{vk_device, cmdpool_create_info}; initialize_actions(); + load_locale(); +} +void application::load_locale() +{ gen.add_messages_domain("wivrn"); std::locale loc = gen(""); + messages_info.encoding = "UTF-8"; + if (config->locale.empty()) + { #ifdef __ANDROID__ - jni::klass java_util_Locale("java/util/Locale"); - auto default_locale = java_util_Locale.call>("getDefault"); + jni::klass java_util_Locale("java/util/Locale"); + auto default_locale = java_util_Locale.call>("getDefault"); - // if (auto language = default_locale.call("toString")) - if (auto language = default_locale.call("getLanguage")) - messages_info.language = language; - - if (auto country = default_locale.call("getCountry")) - messages_info.country = country; - - messages_info.encoding = "UTF-8"; + // if (auto language = default_locale.call("toString")) + if (auto language = default_locale.call("getLanguage")) + messages_info.language = language; + if (auto country = default_locale.call("getCountry")) + messages_info.country = country; #else - auto & facet = std::use_facet(loc); - messages_info.language = facet.language(); - messages_info.country = facet.country(); - messages_info.encoding = "UTF-8"; + auto & facet = std::use_facet(loc); + messages_info.language = facet.language(); + messages_info.country = facet.country(); #endif + } + else + { + auto pos = config->locale.find("_"); + messages_info.language = config->locale.substr(0, pos); + if (pos != std::string::npos) + messages_info.country = config->locale.substr(pos + 1); + } spdlog::info("Current locale: language {}, country {}, encoding {}", messages_info.language, messages_info.country, messages_info.encoding); messages_info.paths.push_back("locale"); messages_info.domains.push_back(boost::locale::gnu_gettext::messages_info::domain("wivrn")); - messages_info.callback = [](const std::string & file_name, const std::string & encoding) { - std::vector buffer; - try - { - asset file(file_name); - buffer.resize(file.size()); - memcpy(buffer.data(), file.data(), file.size()); - } - catch (...) - { - } - - return buffer; - }; - + messages_info.callback = open_locale_file; loc = std::locale(loc, boost::locale::gnu_gettext::create_messages_facet(messages_info)); std::locale::global(loc); @@ -1875,13 +1854,6 @@ void application::poll_events() exit_requested = true; } break; - case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: { - if (auto * htc_body = std::get_if(&body_tracker)) - { - htc_body->update_active(); - } - } - break; case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: break; case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: { diff --git a/client/application.h b/client/application.h index fc566520..365ebcf6 100644 --- a/client/application.h +++ b/client/application.h @@ -28,13 +28,11 @@ #include "utils/thread_safe.h" #include "vk/vk_allocator.h" #include "wifi_lock.h" -#include "xr/fb_body_tracker.h" -#include "xr/fb_face_tracker2.h" -#include "xr/hand_tracker.h" -#include "xr/htc_body_tracker.h" -#include "xr/htc_face_tracker.h" -#include "xr/pico_body_tracker.h" -#include "xr/pico_face_tracker.h" +#include "xr/actionset.h" +#include "xr/instance.h" +#include "xr/session.h" +#include "xr/swapchain.h" +#include "xr/system.h" #include #include #include @@ -125,12 +123,7 @@ class application : public singleton xr::actionset xr_actionset; std::vector> actions; - bool hand_tracking_supported = false; - xr::hand_tracker left_hand; - xr::hand_tracker right_hand; - - std::variant face_tracker; - std::variant body_tracker; + std::vector> generic_trackers; bool eye_gaze_supported = false; @@ -140,7 +133,6 @@ class application : public singleton bool session_focused = false; bool session_visible = false; bool debug_extensions_found = false; - std::vector xr_extensions; std::vector vk_device_extensions; std::atomic exit_requested = false; std::filesystem::path config_path; @@ -270,16 +262,6 @@ public: return std::make_pair(position, orientation); } - static XrPath string_to_path(const std::string & s) - { - return instance().xr_instance.string_to_path(s); - } - - static std::string path_to_string(XrPath p) - { - return instance().xr_instance.path_to_string(p); - } - void run(); static void push_scene(std::shared_ptr); @@ -350,16 +332,6 @@ public: // #endif } - static XrTime now() - { - return instance().xr_instance.now(); - } - - static uint32_t queue_family_index() - { - return instance().vk_queue_family_index; - } - static thread_safe & get_queue() { return instance().vk_queue; @@ -375,26 +347,21 @@ public: return intent; } - static vk::raii::PhysicalDevice & get_physical_device() - { - return instance().vk_physical_device; - } - static const vk::PhysicalDeviceProperties & get_physical_device_properties() { return instance().physical_device_properties; } - static vk::raii::Device & get_device() - { - return instance().vk_device; - } - static vk::raii::Instance & get_vulkan_instance() { return instance().vk_instance; } + static xr::system & get_system() + { + return instance().xr_system_id; + } + static vk::raii::PipelineCache & get_pipeline_cache() { return instance().pipeline_cache; @@ -415,21 +382,6 @@ public: return instance().last_scene_cpu_time; } - static bool get_hand_tracking_supported() - { - return instance().hand_tracking_supported; - } - - static bool get_face_tracking_supported() - { - return !std::holds_alternative(instance().face_tracker); - } - - static bool get_body_tracking_supported() - { - return !std::holds_alternative(instance().body_tracker); - } - static bool get_eye_gaze_supported() { return instance().eye_gaze_supported; @@ -440,29 +392,9 @@ public: return instance().openxr_post_processing_supported; } - static xr::hand_tracker & get_left_hand() + static auto & get_generic_trackers() { - return instance().left_hand; - } - - static xr::hand_tracker & get_right_hand() - { - return instance().right_hand; - } - - static auto & get_face_tracker() - { - return instance().face_tracker; - } - - static auto & get_body_tracker() - { - return instance().body_tracker; - } - - static const std::vector & get_xr_extensions() - { - return instance().xr_extensions; + return instance().generic_trackers; } static const std::vector & get_vk_device_extensions() diff --git a/client/configuration.cpp b/client/configuration.cpp index abe7f15e..dbea9cf2 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -82,6 +82,8 @@ bool configuration::check_feature(feature f) const { std::lock_guard lock(mutex); + auto & system = application::get_system(); + auto it = features.find(f); if (it == features.end()) return false; @@ -94,7 +96,7 @@ bool configuration::check_feature(feature f) const case feature::microphone: break; case feature::hand_tracking: - if (not application::get_hand_tracking_supported()) + if (not system.hand_tracking_supported()) return false; break; case feature::eye_gaze: @@ -102,50 +104,12 @@ bool configuration::check_feature(feature f) const return false; break; case feature::face_tracking: - switch (guess_model()) - { - case model::htc_vive_focus_3: - case model::htc_vive_focus_vision: - case model::htc_vive_xr_elite: - if (not std::holds_alternative(application::get_face_tracker())) - return false; - break; - case model::pico_4_pro: - case model::pico_4_enterprise: - if (not std::holds_alternative(application::get_face_tracker())) - return false; - break; - default: - if (not std::holds_alternative(application::get_face_tracker())) - return false; - break; - } + if (system.face_tracker_supported() == xr::face_tracker_type::none) + return false; break; case feature::body_tracking: - switch (guess_model()) - { - case model::meta_quest_3: - case model::meta_quest_3s: - if (not std::holds_alternative(application::get_body_tracker())) - return false; - break; - case model::htc_vive_focus_3: - case model::htc_vive_xr_elite: - case model::htc_vive_focus_vision: - if (not std::holds_alternative(application::get_body_tracker())) - return false; - break; - case model::pico_neo_3: - case model::pico_4: - case model::pico_4s: - case model::pico_4_pro: - case model::pico_4_enterprise: - if (not std::holds_alternative(application::get_body_tracker())) - return false; - break; - default: - break; - } + if (system.body_tracker_supported() == xr::body_tracker_type::none) + return false; break; } } @@ -181,8 +145,8 @@ void configuration::set_feature(feature f, bool state) configuration::configuration(xr::system & system) { - passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color; - features[feature::hand_tracking] = application::get_hand_tracking_supported(); + passthrough_enabled = system.passthrough_supported() == xr::passthrough_type::color; + features[feature::hand_tracking] = system.hand_tracking_supported(); try { simdjson::dom::parser parser; @@ -214,8 +178,8 @@ configuration::configuration(xr::system & system) if (auto val = root["resolution_scale"]; val.is_double()) resolution_scale = val.get_double(); - if (auto val = root["sgsr"]; val.is_object()) - parse_sgsr_options(val.get_object()); + if (auto val = root["enable_stream_gui"]; val.is_bool()) + enable_stream_gui = val.get_bool(); if (auto val = root["openxr_post_processing"]; val.is_object()) parse_openxr_post_processing_options(val.get_object()); @@ -240,7 +204,7 @@ configuration::configuration(xr::system & system) features[i] = val.get_bool(); } - if (system.passthrough_supported() == xr::system::passthrough_type::no_passthrough) + if (system.passthrough_supported() == xr::passthrough_type::none) passthrough_enabled = false; if (auto val = root["override_foveation_enable"]; val.is_bool()) @@ -254,6 +218,9 @@ configuration::configuration(xr::system & system) if (auto val = root["first_run"]; val.is_bool()) first_run = val.get_bool(); + + if (auto val = root["locale"]; val.is_string()) + locale = val.get_string().value(); } catch (std::exception & e) { @@ -264,31 +231,11 @@ configuration::configuration(xr::system & system) preferred_refresh_rate.reset(); minimum_refresh_rate.reset(); resolution_scale = 1.4; - sgsr = {}; openxr_post_processing = {}; - passthrough_enabled = system.passthrough_supported() == xr::system::passthrough_type::color; + passthrough_enabled = system.passthrough_supported() == xr::passthrough_type::color; } } -void configuration::parse_sgsr_options(simdjson::simdjson_result sgsr_root) -{ - sgsr = {}; - if (auto val = sgsr_root["enabled"]; val.is_bool()) - sgsr.enabled = val.get_bool(); - - if (auto val = sgsr_root["upscaling_factor"]; val.is_double()) - sgsr.upscaling_factor = val.get_double(); - - if (auto val = sgsr_root["use_edge_direction"]; val.is_bool()) - sgsr.use_edge_direction = val.get_bool(); - - if (auto val = sgsr_root["edge_threshold"]; val.is_double()) - sgsr.edge_threshold = val.get_double(); - - if (auto val = sgsr_root["edge_sharpness"]; val.is_double()) - sgsr.edge_sharpness = val.get_double(); -} - void configuration::parse_openxr_post_processing_options(simdjson::simdjson_result openxr_post_processing_root) { openxr_post_processing = {}; @@ -304,17 +251,6 @@ static std::ostream & operator<<(std::ostream & stream, feature f) return stream << "\"" << magic_enum::enum_name(f) << "\""; } -static std::ostream & write_sgsr(std::ofstream & stream, const configuration::sgsr_settings & sgsr) -{ - stream << "{\"enabled\":" << std::boolalpha << sgsr.enabled; - stream << ",\"upscaling_factor\":" << sgsr.upscaling_factor; - stream << ",\"use_edge_direction\":" << std::boolalpha << sgsr.use_edge_direction; - stream << ",\"edge_threshold\":" << sgsr.edge_threshold; - stream << ",\"edge_sharpness\":" << sgsr.edge_sharpness; - stream << "}"; - return stream; -} - static std::ostream & write_openxr_post_processing(std::ofstream & stream, const configuration::openxr_post_processing_settings & openxr_post_processing) { stream << "{\"super_sampling\":" << openxr_post_processing.super_sampling; @@ -357,14 +293,13 @@ void configuration::save() if (minimum_refresh_rate) json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate; json << ",\"resolution_scale\":" << resolution_scale; - json << ",\"sgsr\":"; - write_sgsr(json, sgsr); json << ",\"openxr_post_processing\":"; write_openxr_post_processing(json, openxr_post_processing); json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; json << ",\"mic_unprocessed_audio\":" << std::boolalpha << mic_unprocessed_audio; json << ",\"fb_lower_body\":" << std::boolalpha << fb_lower_body; json << ",\"fb_hip\":" << std::boolalpha << fb_hip; + json << ",\"enable_stream_gui\":" << std::boolalpha << enable_stream_gui; for (auto & [key, value]: features) json << "," << key << ":" << std::boolalpha << value; json << ",\"virtual_keyboard_layout\":" << json_string(virtual_keyboard_layout); @@ -372,5 +307,6 @@ void configuration::save() json << ",\"override_foveation_pitch\":" << override_foveation_pitch; json << ",\"override_foveation_distance\":" << override_foveation_distance; json << ",\"first_run\":" << std::boolalpha << first_run; + json << ",\"locale\":" << json_string(locale); json << "}"; } diff --git a/client/configuration.h b/client/configuration.h index 8d34faae..d8dfbf6f 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -56,16 +56,7 @@ public: bool fb_lower_body = false; bool fb_hip = true; - // Snapdragon Game Super Resolution - struct sgsr_settings - { - bool enabled = false; - float upscaling_factor = 1.5; - bool use_edge_direction = true; - float edge_threshold = 4.0; - float edge_sharpness = 2.0; - }; - sgsr_settings sgsr{}; + bool enable_stream_gui = true; // XR_FB_composition_layer_settings extension flags struct openxr_post_processing_settings @@ -83,6 +74,8 @@ public: bool first_run = true; + std::string locale; + bool check_feature(feature f) const; void set_feature(feature f, bool state); @@ -90,7 +83,6 @@ private: mutable std::mutex mutex; std::map features; - void parse_sgsr_options(simdjson::simdjson_result root); void parse_openxr_post_processing_options(simdjson::simdjson_result root); public: diff --git a/client/decoder/shard_accumulator.cpp b/client/decoder/shard_accumulator.cpp index c570fa93..a7ec0636 100644 --- a/client/decoder/shard_accumulator.cpp +++ b/client/decoder/shard_accumulator.cpp @@ -18,9 +18,9 @@ */ #include "shard_accumulator.h" -#include "application.h" -#include "scenes/stream.h" +#include "scenes/stream.h" // IWYU pragma: keep #include "spdlog/spdlog.h" +#include "xr/instance.h" namespace wivrn { @@ -63,10 +63,10 @@ static bool is_complete(const shard_set & shards) return true; } -std::optional shard_set::insert(data_shard && shard) +std::optional shard_set::insert(data_shard && shard, xr::instance & instance) { if (empty()) - feedback.received_first_packet = application::now(); + feedback.received_first_packet = instance.now(); auto idx = shard.shard_idx; if (idx >= data.size()) @@ -121,12 +121,12 @@ void shard_accumulator::push_shard(video_stream_data_shard && shard) } else if (frame_diff == 0) { - auto shard_idx = current.insert(std::move(shard)); + auto shard_idx = current.insert(std::move(shard), instance); try_submit_frame(shard_idx); } else if (frame_diff == 1) { - next.insert(std::move(shard)); + next.insert(std::move(shard), instance); if (is_complete(next)) { debug_why_not_sent(current); @@ -191,7 +191,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) if (not frame_complete) return; - current.feedback.received_last_packet = application::now(); + current.feedback.received_last_packet = instance.now(); current.feedback.sent_to_decoder = current.feedback.received_last_packet; data_shard::timing_info_t timing_info = data_shards.back()->timing_info.value_or(data_shard::timing_info_t{}); current.feedback.encode_begin = timing_info.encode_begin; @@ -216,7 +216,7 @@ void shard_accumulator::try_submit_frame(uint16_t shard_idx) void shard_accumulator::send_feedback(wivrn::from_headset::feedback & feedback) { if (not feedback.received_last_packet) - feedback.received_first_packet = application::now(); + feedback.received_first_packet = instance.now(); auto scene = weak_scene.lock(); if (scene) scene->send_feedback(feedback); diff --git a/client/decoder/shard_accumulator.h b/client/decoder/shard_accumulator.h index 4777de7f..a0145e22 100644 --- a/client/decoder/shard_accumulator.h +++ b/client/decoder/shard_accumulator.h @@ -19,27 +19,30 @@ #pragma once -#include -#include - -#ifdef __ANDROID__ -#include "decoder/android/android_decoder.h" -using decoder_impl = ::wivrn::android::decoder; -#else -#include "decoder/ffmpeg/ffmpeg_decoder.h" -using decoder_impl = ::wivrn::ffmpeg::decoder; -#endif - +#include "decoder.h" #include "wivrn_packets.h" + +#include #include #include +#include + +namespace xr +{ +class instance; +} + +namespace scenes +{ +class stream; +} namespace wivrn { class shard_accumulator { - std::shared_ptr decoder; + std::shared_ptr decoder_; public: using data_shard = wivrn::to_headset::video_stream_data_shard; @@ -50,7 +53,7 @@ public: void reset(uint64_t frame_index); bool empty() const; - std::optional insert(data_shard &&); + std::optional insert(data_shard &&, xr::instance & instance); wivrn::from_headset::feedback feedback{}; @@ -70,19 +73,22 @@ private: shard_set current; shard_set next; std::weak_ptr weak_scene; + xr::instance & instance; public: explicit shard_accumulator( vk::raii::Device & device, vk::raii::PhysicalDevice & physical_device, + xr::instance & instance, const wivrn::to_headset::video_stream_description::item & description, float fps, std::weak_ptr scene, uint8_t stream_index) : - decoder(std::make_shared(device, physical_device, description, fps, stream_index, scene, this)), + decoder_(decoder::make(device, physical_device, description, fps, stream_index, scene, this)), current(stream_index), next(stream_index), - weak_scene(scene) + weak_scene(scene), + instance(instance) { next.reset(1); } @@ -91,20 +97,20 @@ public: auto & desc() const { - return decoder->desc(); + return decoder_->description; } vk::Sampler sampler() { - return decoder->sampler(); + return decoder_->sampler(); } - vk::Extent2D image_size() + const vk::Extent2D extent() { - return decoder->image_size(); + return decoder_->extent(); } - using blit_handle = decoder_impl::blit_handle; + using blit_handle = decoder::blit_handle; private: void try_submit_frame(std::optional shard_idx); diff --git a/client/render/gpu_buffer.h b/client/render/gpu_buffer.h index 7f03c03e..892dc3fb 100644 --- a/client/render/gpu_buffer.h +++ b/client/render/gpu_buffer.h @@ -18,7 +18,6 @@ #pragma once -#include "application.h" #include "utils/alignment.h" #include "vk/allocation.h" #include @@ -115,10 +114,10 @@ public: } } - buffer_allocation copy_to_gpu() + buffer_allocation copy_to_gpu(vk::raii::Device & device) { buffer_allocation gpu_buffer{ - application::get_device(), + device, vk::BufferCreateInfo{ .size = bytes.size(), .usage = usage}, diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 7a2daabb..888e4865 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -345,9 +345,9 @@ imgui_context::imgui_context( ImGui_ImplVulkan_InitInfo init_info = { .Instance = *application::get_vulkan_instance(), - .PhysicalDevice = *application::get_physical_device(), - .Device = *application::get_device(), - .QueueFamily = application::queue_family_index(), + .PhysicalDevice = *physical_device, + .Device = *device, + .QueueFamily = queue_family_index, .Queue = *queue.get_unsafe(), .RenderPass = *renderpass, .MinImageCount = 2, @@ -718,7 +718,7 @@ void imgui_context::new_frame(XrTime display_time) ImPlot::SetCurrentContext(plot_context); if (last_display_time) - io.DeltaTime = std::min((display_time - last_display_time) * 1e-9f, 0.0166f); + io.DeltaTime = std::clamp((display_time - last_display_time) * 1e-9f, 0.001f, 0.0166f); last_display_time = display_time; // Uses the window list from last frame @@ -1099,6 +1099,13 @@ ImTextureID imgui_context::load_texture(const std::string & filename) void imgui_context::free_texture(ImTextureID texture) { + // Make sure we are done using the texture + std::vector fences; + for (auto & f: command_buffers) + fences.push_back(*f.fence); + if (auto result = device.waitForFences(fences, true, 1'000'000'000); result != vk::Result::eSuccess) + spdlog::error("vkWaitForfences: {}", vk::to_string(result)); + textures.erase(texture); } diff --git a/client/render/scene_loader.cpp b/client/render/scene_loader.cpp index 66ba86a4..07ceddfe 100644 --- a/client/render/scene_loader.cpp +++ b/client/render/scene_loader.cpp @@ -785,7 +785,7 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) // Copy the staging buffer to the GPU spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size()); - auto buffer = std::make_shared(staging_buffer.copy_to_gpu()); + auto buffer = std::make_shared(staging_buffer.copy_to_gpu(device)); for (auto & i: materials) i->buffer = buffer; diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index e67831ce..2074e5aa 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -28,6 +28,7 @@ #include "vk/allocation.h" #include "vk/pipeline.h" #include "vk/shader.h" +#include "vk/specialization_constants.h" #include #include #include @@ -532,34 +533,11 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) auto vertex_shader = load_shader(device, info.shader_name + ".vert"); 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, dithering), - .size = sizeof(VkBool32), - }, - vk::SpecializationMapEntry{ - .constantID = 2, - .offset = offsetof(pipeline_info, alpha_cutout), - .size = sizeof(VkBool32), - }, - vk::SpecializationMapEntry{ - .constantID = 3, - .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, - }; + auto specialization = make_specialization_constants( + int32_t(info.nb_texcoords), + VkBool32(info.dithering), + VkBool32(info.alpha_cutout), + VkBool32(info.skinning)); return vk::raii::Pipeline{ device, @@ -570,14 +548,14 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) .stage = vk::ShaderStageFlagBits::eVertex, .module = *vertex_shader, .pName = "main", - .pSpecializationInfo = &specialization, + .pSpecializationInfo = specialization, }, vk::PipelineShaderStageCreateInfo{ .stage = vk::ShaderStageFlagBits::eFragment, .module = *fragment_shader, .pName = "main", - .pSpecializationInfo = &specialization, + .pSpecializationInfo = specialization, }, }, @@ -794,7 +772,7 @@ void scene_renderer::update_material_descriptor_set(renderer::material & materia device.updateDescriptorSets(write_ds, {}); } -static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0) +[[maybe_unused]] static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0) { if (level == 0) spdlog::info("Node hierarchy:"); diff --git a/client/render/text_rasterizer.cpp b/client/render/text_rasterizer.cpp index d206aa15..ac0f7a83 100644 --- a/client/render/text_rasterizer.cpp +++ b/client/render/text_rasterizer.cpp @@ -139,46 +139,42 @@ text_rasterizer::text_rasterizer(vk::raii::Device & device, vk::raii::PhysicalDe image_allocation text_rasterizer::create_image(vk::Extent2D size) { - image_allocation alloc{device, - vk::ImageCreateInfo{ - .imageType = vk::ImageType::e2D, - .format = text::format, - .extent = { - .width = size.width, - .height = size.height, - .depth = 1, - }, - .mipLevels = 1, - .arrayLayers = 1, - .samples = vk::SampleCountFlagBits::e1, - .tiling = vk::ImageTiling::eOptimal, - .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, - .sharingMode = vk::SharingMode::eExclusive, - .initialLayout = vk::ImageLayout::eUndefined, - }, - VmaAllocationCreateInfo{ - .flags = 0, - .usage = VMA_MEMORY_USAGE_AUTO, - }}; - - application::set_debug_reports_name(alloc, "text_rasterizer image"); - return alloc; + return {device, + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = text::format, + .extent = { + .width = size.width, + .height = size.height, + .depth = 1, + }, + .mipLevels = 1, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst, + .sharingMode = vk::SharingMode::eExclusive, + .initialLayout = vk::ImageLayout::eUndefined, + }, + VmaAllocationCreateInfo{ + .flags = 0, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "text_rasterizer image"}; } buffer_allocation text_rasterizer::create_buffer(size_t size) { - buffer_allocation alloc{device, - vk::BufferCreateInfo{ - .size = size, - .usage = vk::BufferUsageFlagBits::eTransferSrc, - }, - VmaAllocationCreateInfo{ - .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, - .usage = VMA_MEMORY_USAGE_AUTO, - }}; - application::set_debug_reports_name(alloc, "text_rasterizer buffer"); - - return alloc; + return {device, + vk::BufferCreateInfo{ + .size = size, + .usage = vk::BufferUsageFlagBits::eTransferSrc, + }, + VmaAllocationCreateInfo{ + .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT, + .usage = VMA_MEMORY_USAGE_AUTO, + }, + "text_rasterizer buffer"}; } text_rasterizer::~text_rasterizer() diff --git a/client/scene.cpp b/client/scene.cpp index feeb29fe..684922ee 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -51,8 +51,6 @@ scene::scene(key, const meta & current_meta, std::span support queue_family_index(application::instance().vk_queue_family_index), current_meta(current_meta) { - passthrough_supported = system.passthrough_supported(); - swapchain_format = vk::Format::eUndefined; spdlog::info("Supported swapchain formats:"); @@ -443,7 +441,7 @@ std::pair scene::load_gltf(const std::filesyst node.layer_mask = layer_mask; assert(renderer); - scene_loader loader(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); + scene_loader loader(device, physical_device, queue, queue_family_index, renderer->get_default_material()); loader.add_prefab(world, loader(path), entity); diff --git a/client/scene.h b/client/scene.h index e84bbcea..9593100c 100644 --- a/client/scene.h +++ b/client/scene.h @@ -103,7 +103,6 @@ public: protected: vk::Format swapchain_format; vk::Format depth_format; - xr::system::passthrough_type passthrough_supported; bool composition_layer_depth_test_supported; bool composition_layer_color_scale_bias_supported; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index cd328c19..bf7666ca 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -383,9 +383,18 @@ void scenes::lobby::connect(const configuration::server_data & data) data.manual); } -std::optional scenes::lobby::check_recenter_gesture(const std::array & joints) +std::optional scenes::lobby::check_recenter_gesture(xr::spaces space, const std::optional> & joints) { - const auto & palm = joints[XR_HAND_JOINT_PALM_EXT].first; + if (recentering_context and std::get<0>(*recentering_context) != space) + return std::nullopt; + + if (not joints) + { + recentering_context.reset(); + return std::nullopt; + } + + const auto & palm = (*joints)[XR_HAND_JOINT_PALM_EXT].first; const auto & o = palm.pose.orientation; const auto & p = palm.pose.position; glm::quat q{o.w, o.x, o.y, o.z}; @@ -393,102 +402,130 @@ std::optional scenes::lobby::check_recenter_gesture(const std::array< if (glm::dot(q * glm::vec3(0, 1, 0), glm::vec3(0, -1, 0)) > constants::lobby::recenter_cosangle_min) { + recentering_context.emplace(space, glm::vec3{}, 0); return v + glm::vec3(0, constants::lobby::recenter_distance_up, 0) + q * glm::vec3(0, 0, -constants::lobby::recenter_distance_front); } + recentering_context.reset(); return std::nullopt; } std::optional scenes::lobby::check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position) { - std::optional> aim; - glm::vec3 offset_position; - glm::quat offset_orientation; + xr::spaces controller; + glm::vec3 recenter_position; + float recenter_distance; - if (application::read_action_bool(recenter_left_action).value_or(std::pair{0, false}).second) + if (recentering_context) { - aim = application::locate_controller(application::space(xr::spaces::aim_left), application::space(xr::spaces::world), predicted_display_time); - std::tie(offset_position, offset_orientation) = input->offset[xr::spaces::aim_left]; - } - - if (application::read_action_bool(recenter_right_action).value_or(std::pair{0, false}).second) - { - aim = application::locate_controller(application::space(xr::spaces::aim_right), application::space(xr::spaces::world), predicted_display_time); - std::tie(offset_position, offset_orientation) = input->offset[xr::spaces::aim_right]; - } - - if (aim) - { - // Handle controller offset - aim->first = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position; - aim->second = aim->second * offset_orientation; - - if (not gui_recenter_position or not gui_recenter_distance) + controller = std::get<0>(*recentering_context); + bool state; + switch (controller) { - // First frame where the recenter action is active - imgui_context::controller_state state{ - .active = true, - .aim_position = aim->first, - .aim_orientation = aim->second, - }; + case xr::spaces::aim_left: + state = application::read_action_bool(recenter_left_action).value_or(std::pair{0, false}).second; + break; - imgui_ctx->compute_pointer_position(state); + case xr::spaces::aim_right: + state = application::read_action_bool(recenter_right_action).value_or(std::pair{0, false}).second; + break; - if (state.pointer_position) // TODO: check that the pointer is inside an imgui window - { - auto M = glm::mat3_cast(imgui_ctx->layers()[0].orientation); + default: + return std::nullopt; + } - // Pointer position in world - glm::vec3 world_pointer_position = imgui_ctx->rw_from_vp(*state.pointer_position); + if (not state) + { + recentering_context.reset(); + return std::nullopt; + } + } + else if (auto state = application::read_action_bool(recenter_left_action); state and state->second) + controller = xr::spaces::aim_left; + else if (auto state = application::read_action_bool(recenter_right_action); state and state->second) + controller = xr::spaces::aim_right; + else + return std::nullopt; - // Pointer position in GUI - gui_recenter_position = glm::transpose(M) * (world_pointer_position - imgui_ctx->layers()[0].position); - gui_recenter_distance = glm::length(state.aim_position - world_pointer_position); - } - else - { - gui_recenter_position = glm::vec3(0, 0, 0); - gui_recenter_distance = constants::lobby::recenter_action_distance; - } + auto aim = application::locate_controller(application::space(controller), application::space(xr::spaces::world), predicted_display_time); + + if (not aim) + { + // The controller cannot be located + recentering_context.reset(); + return std::nullopt; + } + + // Handle controller offset + auto [offset_position, offset_orientation] = input->offset[controller]; + aim->first = aim->first + glm::mat3_cast(aim->second * offset_orientation) * offset_position; + aim->second = aim->second * offset_orientation; + + if (not recentering_context) + { + // First frame of recentering + imgui_context::controller_state state{ + .active = true, + .aim_position = aim->first, + .aim_orientation = aim->second, + }; + + imgui_ctx->compute_pointer_position(state); + + if (state.pointer_position) // TODO: check that the pointer is inside an imgui window + { + auto M = glm::mat3_cast(imgui_ctx->layers()[0].orientation); + + // Pointer position in world + glm::vec3 world_pointer_position = imgui_ctx->rw_from_vp(*state.pointer_position); + + // Pointer position in GUI + recenter_position = glm::transpose(M) * (world_pointer_position - imgui_ctx->layers()[0].position); + recenter_distance = glm::length(state.aim_position - world_pointer_position); } else { - // Subsequent frames: find the GUI position that gives the correct world pointer position - glm::vec3 controller_direction = -glm::column(glm::mat3_cast(aim->second), 2); - glm::vec3 wanted_world_pointer_position = aim->first + controller_direction * *gui_recenter_distance; - - // I'm sure there's an analytical solution but I can't be bothered to write it so - // let's use a gradient descent instead - auto f = [&](glm::vec3 new_gui_position) { - auto q = compute_gui_orientation(head_position, new_gui_position); - auto M = glm::mat3_cast(q); // plane-to-world transform - - glm::vec3 world_pointer_position = new_gui_position + M * *gui_recenter_position; - - return world_pointer_position - wanted_world_pointer_position; - }; - - // One step is usually enough, the solution will continuously improve in the next frames - glm::vec3 gui_position = imgui_ctx->layers()[0].position; - float eps = 0.01; - glm::vec3 obj = f(gui_position); - glm::vec3 obj_dx = (f(gui_position + glm::vec3(eps, 0, 0)) - obj) / eps; - glm::vec3 obj_dy = (f(gui_position + glm::vec3(0, eps, 0)) - obj) / eps; - glm::vec3 obj_dz = (f(gui_position + glm::vec3(0, 0, eps)) - obj) / eps; - - glm::mat3 jacobian{obj_dx, obj_dy, obj_dz}; - - gui_position -= glm::inverse(jacobian) * obj; - - return gui_position; + // Use the center of the GUI if the controller points outside of the GUI + recenter_position = glm::vec3(0, 0, 0); + recenter_distance = constants::lobby::recenter_action_distance; } + + recentering_context.emplace(controller, recenter_position, recenter_distance); + return std::nullopt; } else { - gui_recenter_position.reset(); - } + // Subsequent frames: find the GUI position that gives the correct world pointer position + std::tie(controller, recenter_position, recenter_distance) = *recentering_context; - return std::nullopt; + glm::vec3 controller_direction = -glm::column(glm::mat3_cast(aim->second), 2); + glm::vec3 wanted_world_pointer_position = aim->first + controller_direction * recenter_distance; + + // I'm sure there's an analytical solution but I can't be bothered to write it so + // let's use a gradient descent instead + auto f = [&](glm::vec3 new_gui_position) { + auto q = compute_gui_orientation(head_position, new_gui_position); + auto M = glm::mat3_cast(q); // plane-to-world transform + + glm::vec3 world_pointer_position = new_gui_position + M * recenter_position; + + return world_pointer_position - wanted_world_pointer_position; + }; + + // One step is usually enough, the solution will continuously improve in the next frames + glm::vec3 gui_position = imgui_ctx->layers()[0].position; + float eps = 0.01; + glm::vec3 obj = f(gui_position); + glm::vec3 obj_dx = (f(gui_position + glm::vec3(eps, 0, 0)) - obj) / eps; + glm::vec3 obj_dy = (f(gui_position + glm::vec3(0, eps, 0)) - obj) / eps; + glm::vec3 obj_dz = (f(gui_position + glm::vec3(0, 0, eps)) - obj) / eps; + + glm::mat3 jacobian{obj_dx, obj_dy, obj_dz}; + + gui_position -= glm::inverse(jacobian) * obj; + + return gui_position; + } } std::optional scenes::lobby::check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation) @@ -612,26 +649,24 @@ void scenes::lobby::render(const XrFrameState & frame_state) if (!new_gui_position and head_position) new_gui_position = check_recenter_action(frame_state.predictedDisplayTime, head_position->first); - if (application::get_hand_tracking_supported()) + if (left_hand and right_hand) { - auto left = application::get_left_hand().locate(world_space, frame_state.predictedDisplayTime); - auto right = application::get_right_hand().locate(world_space, frame_state.predictedDisplayTime); + auto left = left_hand->locate(world_space, frame_state.predictedDisplayTime); + auto right = right_hand->locate(world_space, frame_state.predictedDisplayTime); hand_model::apply(world, left, right); if (left and xr::hand_tracker::check_flags(*left, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) - { hide_left_controller = true; - if (!new_gui_position) - new_gui_position = check_recenter_gesture(*left); - } if (right and xr::hand_tracker::check_flags(*right, XR_SPACE_LOCATION_POSITION_TRACKED_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT, 0)) - { hide_right_controller = true; - if (!new_gui_position) - new_gui_position = check_recenter_gesture(*right); - } + + if (not new_gui_position) + new_gui_position = check_recenter_gesture(xr::spaces::palm_left, left); + + if (not new_gui_position) + new_gui_position = check_recenter_gesture(xr::spaces::palm_right, right); } if (head_position && new_gui_position) @@ -763,7 +798,7 @@ void scenes::lobby::on_focused() // assert(std::ranges::all_of(views, [height](const XrViewConfigurationView & view) { return view.recommendedImageRectHeight == height; })); renderer.emplace(device, physical_device, queue, commandpool); - loader.emplace(device, physical_device, queue, application::queue_family_index(), renderer->get_default_material()); + loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material()); lobby_entity = load_gltf("ground.gltf", layer_lobby).first; @@ -800,12 +835,6 @@ void scenes::lobby::on_focused() xyz_axes_right_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; #endif - if (application::get_hand_tracking_supported()) - { - hand_model::add_hand(*this, XR_HAND_LEFT_EXT, "left-hand.glb", layer_controllers); - hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, "right-hand.glb", layer_controllers); - } - recenter_left_action = get_action("recenter_left").first; recenter_right_action = get_action("recenter_right").first; @@ -827,21 +856,19 @@ void scenes::lobby::on_focused() .haptic_output = get_action("right_haptic").first, }, }; - if (auto & hand = application::get_left_hand()) + + if (system.hand_tracking_supported()) { - imgui_inputs.push_back( - { - .hand = &hand, - }); - } - if (auto & hand = application::get_right_hand()) - { - imgui_inputs.push_back( - { - .hand = &hand, - }); + left_hand = session.create_hand_tracker(XR_HAND_LEFT_EXT); + right_hand = session.create_hand_tracker(XR_HAND_RIGHT_EXT); + hand_model::add_hand(*this, XR_HAND_LEFT_EXT, "left-hand.glb", layer_controllers); + hand_model::add_hand(*this, XR_HAND_RIGHT_EXT, "right-hand.glb", layer_controllers); + imgui_inputs.push_back({.hand = &*left_hand}); + imgui_inputs.push_back({.hand = &*right_hand}); } + face_tracker = xr::make_face_tracker(instance, system, session); + // 0.4mm / pixel std::vector vps{ { @@ -882,21 +909,7 @@ void scenes::lobby::on_focused() swapchain_imgui = xr::swapchain(session, device, swapchain_format, 3000, 1300); - imgui_ctx.emplace(physical_device, device, queue_family_index, queue, imgui_inputs, swapchain_imgui, vps); - std::string image; - /* Could be used for more patriotics logos - - auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - auto tm = std::localtime(&t); - - switch (tm->tm_mon) - { - default: - image = "wivrn"; - break; - } - */ image = "wivrn"; try { @@ -942,6 +955,9 @@ void scenes::lobby::on_unfocused() world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools input.reset(); + left_hand.reset(); + right_hand.reset(); + face_tracker.emplace(); loader.reset(); renderer.reset(); diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 1ef69eae..d527ec9c 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -29,7 +29,9 @@ #include "wivrn_config.h" #include "wivrn_discover.h" #include "wivrn_packets.h" +#include "xr/face_tracker.h" #include +#include #include #include @@ -65,6 +67,11 @@ class lobby : public scene_impl std::optional imgui_ctx; + std::optional left_hand; + std::optional right_hand; + + xr::face_tracker face_tracker; + std::string selected_item; std::unique_ptr license; @@ -94,8 +101,10 @@ class lobby : public scene_impl XrAction recenter_left_action = XR_NULL_HANDLE; XrAction recenter_right_action = XR_NULL_HANDLE; - std::optional gui_recenter_position; - std::optional gui_recenter_distance; + // std::optional gui_recenter_position; + // std::optional gui_recenter_distance; + // Which controller is used for recentering, position of the pointed point in the GUI, in GUI axes, and distance between the controller and the pointed point during recentering + std::optional> recentering_context; bool recenter_gui = true; void move_gui(glm::vec3 head_position, glm::vec3 new_gui_position); @@ -120,6 +129,7 @@ class lobby : public scene_impl ImTextureID about_picture; ImTextureID default_icon; std::unordered_map app_icons; + std::optional timestamp_start_application; virtual_keyboard keyboard; @@ -136,7 +146,7 @@ class lobby : public scene_impl void draw_features_status(XrTime predicted_display_time); void gui_connecting(locked_notifiable & request); void gui_enter_pin(locked_notifiable & request); - void gui_connected(); + void gui_connected(XrTime predicted_display_time); void gui_server_list(); void gui_new_server(); void gui_settings(); @@ -152,7 +162,7 @@ class lobby : public scene_impl void connect(const configuration::server_data & data); std::unique_ptr connect_to_session(wivrn_discover::service service, bool manual_connection); - std::optional check_recenter_gesture(const std::array & joints); + std::optional check_recenter_gesture(xr::spaces space, const std::optional> & joints); std::optional check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position); std::optional check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 5ff2efa0..fa7222cc 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -35,11 +35,13 @@ #include "utils/overloaded.h" #include "utils/ranges.h" #include "version.h" +#include "xr/body_tracker.h" #include #include #include #include #include +#include #include #include #include @@ -246,6 +248,7 @@ void scenes::lobby::gui_connecting(locked_notifiable & pin_req if (next_scene) { current_tab = tab::connected; + timestamp_start_application.reset(); ImGui::CloseCurrentPopup(); return; } @@ -376,7 +379,7 @@ void scenes::lobby::gui_enter_pin(locked_notifiable & pin_requ imgui_ctx->vibrate_on_hover(); } -void scenes::lobby::gui_connected() +void scenes::lobby::gui_connected(XrTime predicted_display_time) { if (not next_scene) { @@ -401,14 +404,17 @@ void scenes::lobby::gui_connected() auto apps = next_scene->get_applications(); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20}); - if (apps->applications.empty()) + if (apps->empty()) { CenterTextHV(_("Start an application on the server to start streaming.")); } else { + bool app_starting = timestamp_start_application and (predicted_display_time - *timestamp_start_application < 10'000'000'000); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {20, 0}); - ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, disconnect_size.y + 80), 0); + ImGui::BeginDisabled(app_starting); + ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, disconnect_size.y + 80), 0, app_starting ? ImGuiWindowFlags_NoScrollWithMouse : 0); ImGui::Indent(20); if (server_name.empty()) @@ -427,7 +433,7 @@ void scenes::lobby::gui_connected() ImGui::Indent((usable_window_width - icon_line_width) / 2); auto t0 = std::chrono::steady_clock::now(); - for (const auto [index, app]: utils::enumerate(apps->applications)) + for (const auto [index, app]: utils::enumerate(*apps)) { ImTextureID texture = [&]() -> ImTextureID { if (app.image.empty()) @@ -458,8 +464,11 @@ void scenes::lobby::gui_connected() }(); ImGui::PushStyleColor(ImGuiCol_Button, 0); - if (icon(app.name + "##" + app.id, texture, {256, 256}, 0, {icon_width, 0})) + if (icon(app.name + "##" + app.id, texture, {256, 256}, ImGuiButtonFlags_PressedOnClickRelease, {icon_width, 0})) + { + timestamp_start_application = predicted_display_time; next_scene->start_application(app.id); + } imgui_ctx->vibrate_on_hover(); ImGui::PopStyleColor(); // ImGuiCol_Button @@ -471,7 +480,7 @@ void scenes::lobby::gui_connected() std::vector> to_be_removed; for (const auto & [app_id, app_icon]: app_icons) { - if (not std::ranges::contains(apps->applications, app_id, &to_headset::application_list::application::id)) + if (not std::ranges::contains(*apps, app_id, &scenes::stream::app::id)) to_be_removed.emplace_back(app_id, app_icon); } for (const auto & [app_id, app_icon]: to_be_removed) @@ -482,12 +491,26 @@ void scenes::lobby::gui_connected() ScrollWhenDragging(); ImGui::EndChild(); + ImGui::EndDisabled(); + + if (app_starting) + { + ImGui::SetCursorPos(ImGui::GetWindowSize() / 2 - ImVec2{200, 200} - ImGui::GetStyle().FramePadding); + ImSpinner::SpinnerAng("App starting spinner", + 200, // Radius + 40, // Thickness + ImColor{1.f, 1.f, 1.f, 1.f}, // Colour + ImColor{1.f, 1.f, 1.f, 0.f}, // Background + 6, // Velocity + 0.75f * 2 * M_PI // Angle + ); + } + ImGui::PopStyleVar(); // ImGuiStyleVar_WindowPadding } ImGui::PopStyleVar(); - ImGui::SetCursorPosX(ImGui::GetWindowSize().x - disconnect_size.x - 50); - ImGui::SetCursorPosY(ImGui::GetWindowSize().y - disconnect_size.y - 50); + ImGui::SetCursorPos(ImGui::GetWindowSize() - disconnect_size - ImVec2{50, 50}); 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)); @@ -905,7 +928,7 @@ void scenes::lobby::gui_settings() ImGui::EndDisabled(); } { - ImGui::BeginDisabled(not application::get_hand_tracking_supported()); + ImGui::BeginDisabled(not system.hand_tracking_supported()); bool enabled = config.check_feature(feature::hand_tracking); if (ImGui::Checkbox(_S("Enable hand tracking"), &enabled)) { @@ -929,7 +952,7 @@ void scenes::lobby::gui_settings() ImGui::EndDisabled(); } { - ImGui::BeginDisabled(not application::get_face_tracking_supported()); + ImGui::BeginDisabled(std::holds_alternative(face_tracker)); bool enabled = config.check_feature(feature::face_tracking); if (ImGui::Checkbox(_S("Enable face tracking"), &enabled)) { @@ -941,8 +964,9 @@ void scenes::lobby::gui_settings() imgui_ctx->vibrate_on_hover(); } + auto body_tracker = system.body_tracker_supported(); { - ImGui::BeginDisabled(not application::get_body_tracking_supported()); + ImGui::BeginDisabled(body_tracker == xr::body_tracker_type::none); bool enabled = config.check_feature(feature::body_tracking); if (ImGui::Checkbox(_S("Enable body tracking"), &enabled)) { @@ -957,19 +981,14 @@ void scenes::lobby::gui_settings() } else { - std::visit(utils::overloaded{ - [](auto &) {}, - [this](xr::fb_body_tracker &) { - imgui_ctx->tooltip(_("Requires 'Hand and body tracking' to be enabled in the Quest movement tracking settings,\notherwise body data will be guessed from controller and headset positions")); - }, - }, - application::get_body_tracker()); + if (body_tracker == xr::body_tracker_type::fb) + imgui_ctx->tooltip(_("Requires 'Hand and body tracking' to be enabled in the Quest movement tracking settings,\notherwise body data will be guessed from controller and headset positions")); } } imgui_ctx->vibrate_on_hover(); } - if (std::holds_alternative(application::get_body_tracker())) + if (body_tracker == xr::body_tracker_type::fb) { ImGui::BeginDisabled(not config.check_feature(feature::body_tracking)); ImGui::Indent(); @@ -995,7 +1014,7 @@ void scenes::lobby::gui_settings() ImGui::EndDisabled(); } - ImGui::BeginDisabled(passthrough_supported == xr::system::passthrough_type::no_passthrough); + ImGui::BeginDisabled(system.passthrough_supported() == xr::passthrough_type::none); if (ImGui::Checkbox(_S("Enable video passthrough in lobby"), &config.passthrough_enabled)) { setup_passthrough(); @@ -1006,6 +1025,13 @@ void scenes::lobby::gui_settings() imgui_ctx->tooltip(_("This feature is not supported by your headset")); ImGui::EndDisabled(); + { + ImGui::Checkbox(_S("Enable in-stream window"), &config.enable_stream_gui); + imgui_ctx->vibrate_on_hover(); + if (ImGui::IsItemHovered()) + imgui_ctx->tooltip(_("Enables the configuration window to be shown while the game is streaming.\nIf enabled, the window is activated by pressing both thumbsticks.")); + } + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing } @@ -1237,12 +1263,12 @@ void scenes::lobby::gui_first_run() item{ .f = feature::face_tracking, .text = _S("Enable face tracking?"), - .supported = application::get_face_tracking_supported(), + .supported = not std::holds_alternative(face_tracker), }, item{ .f = feature::body_tracking, .text = _S("Enable body tracking?"), - .supported = application::get_body_tracking_supported(), + .supported = system.body_tracker_supported() != xr::body_tracker_type::none, }, }; @@ -1572,11 +1598,22 @@ static auto face_weights() return res; } -static const char * get_face_icon(XrTime predicted_display_time) +static const char * get_face_icon(XrTime predicted_display_time, xr::face_tracker & face_tracker) { static const auto w = face_weights(); wivrn::from_headset::tracking::fb_face2 expression; - std::get(application::get_face_tracker()).get_weights(predicted_display_time, expression); + const char * result = nullptr; + std::visit(utils::overloaded{ + [](std::monostate &) {}, + [&](xr::htc_face_tracker &) { result = ICON_FA_FACE_SMILE_WINK; }, + [&](auto & ft) { + ft.get_weights(predicted_display_time, expression); + }, + }, + face_tracker); + + if (result) + return result; if (not expression.is_valid) return ICON_FA_FACE_MEH; @@ -1619,7 +1656,7 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) .icon_disabled = ICON_FA_MICROPHONE_SLASH, }); - if (application::get_hand_tracking_supported()) + if (system.hand_tracking_supported()) { items.push_back({ .f = feature::hand_tracking, @@ -1640,21 +1677,18 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) }); } - if (application::get_face_tracking_supported()) + if (not std::holds_alternative(face_tracker)) { - const char * icon_enabled = std::holds_alternative(application::get_face_tracker()) - ? get_face_icon(predicted_display_time) - : ICON_FA_FACE_KISS_WINK_HEART; items.push_back({ .f = feature::face_tracking, .tooltip_enabled = _("Face tracking is enabled"), .tooltip_disabled = _("Face tracking is disabled"), - .icon_enabled = icon_enabled, + .icon_enabled = get_face_icon(predicted_display_time, face_tracker), .icon_disabled = ICON_FA_FACE_MEH_BLANK, }); } - if (application::get_body_tracking_supported()) + if (system.body_tracker_supported() != xr::body_tracker_type::none) { items.push_back({ .f = feature::body_tracking, @@ -1728,7 +1762,7 @@ void scenes::lobby::draw_features_status(XrTime predicted_display_time) if (*status.charge > 0.995) icon_nr = 5; else - icon_nr = application::now() / 500'000'000 % 5; + icon_nr = instance.now() / 500'000'000 % 5; } else icon_nr = std::round((*status.charge) * 4); @@ -1845,7 +1879,7 @@ std::vector> scenes::lobby::draw_gui(XrTi ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 10); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10}); ImGui::Begin("WiVRn", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); - gui_connected(); + gui_connected(predicted_display_time); ImGui::End(); ImGui::PopStyleVar(3); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_FrameRounding, ImGuiStyleVar_FramePadding } @@ -1957,7 +1991,7 @@ std::vector> scenes::lobby::draw_gui(XrTi if (not is_gui_visible(*imgui_ctx, predicted_display_time)) { - if (application::get_hand_tracking_supported()) + if (system.hand_tracking_supported()) display_recentering_tip(*imgui_ctx, _("Press the grip button or put your palm up\nto move the main window")); else display_recentering_tip(*imgui_ctx, _("Press the grip button to move the main window")); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index dc20f14e..e79c1305 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -17,11 +17,9 @@ * along with this program. If not, see . */ #include "constants.h" -#include "utils/overloaded.h" -#include "xr/fb_body_tracker.h" +#include "xr/body_tracker.h" +#include "xr/face_tracker.h" #include "xr/fb_face_tracker2.h" -#include "xr/htc_body_tracker.h" -#include "xr/pico_body_tracker.h" #include "xr/space.h" #include #include @@ -40,8 +38,6 @@ #include "utils/contains.h" #include "utils/named_thread.h" #include "utils/ranges.h" -#include "vk/pipeline.h" -#include "vk/shader.h" #include "wivrn_packets.h" #include #include @@ -49,6 +45,11 @@ #include #include +#include "wivrn_config.h" +#if WIVRN_FEATURE_RENDERDOC +#include "vk/renderdoc.h" +#endif + using namespace wivrn; // clang-format off @@ -151,7 +152,8 @@ static const std::array supported_depth_formats{ }; scenes::stream::stream() : - scene_impl(supported_color_formats, supported_depth_formats) + scene_impl(supported_color_formats, supported_depth_formats), + blitters{blitter(device, 0), blitter(device, 1)} { } @@ -189,7 +191,11 @@ std::shared_ptr scenes::stream::create(std::unique_ptrnetwork_session = std::move(network_session); self->network_session->send_control([&]() { - from_headset::headset_info_packet info{}; + from_headset::headset_info_packet info{ + .language = application::get_messages_info().language, + .country = application::get_messages_info().country, + .variant = application::get_messages_info().variant, + }; auto view = self->system.view_configuration_views(self->viewconfig)[0]; view = override_view(view, guess_model()); @@ -251,46 +257,49 @@ std::shared_ptr scenes::stream::create(std::unique_ptrsystem.face_tracker_supported()) + { + case xr::face_tracker_type::none: + info.face_tracking = from_headset::face_type::none; + break; + case xr::face_tracker_type::fb: + case xr::face_tracker_type::pico: + info.face_tracking = from_headset::face_type::fb2; + break; + case xr::face_tracker_type::htc: + info.face_tracking = from_headset::face_type::htc; + break; + } } info.num_generic_trackers = 0; if (config.check_feature(feature::body_tracking)) { - info.num_generic_trackers = std::visit(utils::overloaded{ - [&](std::monostate &) { - return size_t(0); - }, - [&](auto & b) { - return b.count(); - }, - }, - application::get_body_tracker()); + switch (self->system.body_tracker_supported()) + { + case xr::body_tracker_type::none: + break; + case xr::body_tracker_type::fb: + info.num_generic_trackers = xr::fb_body_tracker::get_whitelisted_joints(config.fb_lower_body, config.fb_hip).size(); + break; + case xr::body_tracker_type::htc: + info.num_generic_trackers = application::get_generic_trackers().size(); + break; + case xr::body_tracker_type::pico: + info.num_generic_trackers = xr::pico_body_tracker::joint_whitelist.size(); + break; + } } info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right); - info.passthrough = self->system.passthrough_supported() != xr::system::passthrough_type::no_passthrough; + info.passthrough = self->system.passthrough_supported() != xr::passthrough_type::none; info.system_name = std::string(self->system.properties().systemName); audio::get_audio_description(info); if (not(config.check_feature(feature::microphone))) info.microphone = {}; - info.supported_codecs = decoder_impl::supported_codecs(); + info.supported_codecs = decoder::supported_codecs(); return info; }()); @@ -311,15 +320,6 @@ std::shared_ptr scenes::stream::create(std::unique_ptrnetwork_session->send_control(from_headset::get_application_list{ - .language = info.language, - .country = info.country, - .variant = info.variant, - }); - } - { const auto & config = application::get_config(); self->override_foveation_enable = config.override_foveation_enable; @@ -363,7 +363,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrhaptics_actions.emplace(id, haptics_action{ .action = action.first, - .path = application::string_to_path(path), + .path = self->instance.string_to_path(path), }); } } @@ -394,7 +394,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrget_default_material()); + loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material()); std::string profile = controller_name(); input.emplace( @@ -470,8 +470,11 @@ void scenes::stream::on_focused() swapchain_imgui, std::vector{vp}); - plots_toggle_1 = get_action("plots_toggle_1").first; - plots_toggle_2 = get_action("plots_toggle_2").first; + if (application::get_config().enable_stream_gui) + { + plots_toggle_1 = get_action("plots_toggle_1").first; + plots_toggle_2 = get_action("plots_toggle_2").first; + } recenter_left = get_action("recenter_left").first; recenter_right = get_action("recenter_right").first; foveation_pitch = get_action("foveation_pitch").first; @@ -494,6 +497,8 @@ void scenes::stream::on_unfocused() loader.reset(); renderer.reset(); clear_swapchains(); + left_hand.reset(); + right_hand.reset(); imgui_ctx.reset(); swapchain_imgui = xr::swapchain(); @@ -524,16 +529,16 @@ void scenes::stream::push_blit_handle(shard_accumulator * decoder, std::shared_p { if (decoder != decoders[stream].decoder.get()) return; - handle->feedback.received_from_decoder = application::now(); + handle->feedback.received_from_decoder = instance.now(); std::swap(handle, decoders[stream].latest_frames[handle->feedback.frame_index % decoders[stream].latest_frames.size()]); } if (state_ != state::streaming and std::ranges::all_of(decoders, [](accumulator_images & i) { - return i.alpha() or not i.frames().empty(); + return i.alpha() or not i.empty(); })) { state_ = state::streaming; - spdlog::info("Stream scene ready at t={}", application::now()); + spdlog::info("Stream scene ready at t={}", instance.now()); } } @@ -548,15 +553,14 @@ bool scenes::stream::accumulator_images::alpha() const return decoder->desc().channels == wivrn::to_headset::video_stream_description::channels_t::alpha; } -std::vector scenes::stream::accumulator_images::frames() const +bool scenes::stream::accumulator_images::empty() const { - std::vector result; for (const auto & frame: latest_frames) { if (frame) - result.push_back(frame->feedback.frame_index); + return false; } - return result; + return true; } std::vector> scenes::stream::common_frame(XrTime display_time) @@ -766,138 +770,17 @@ void scenes::stream::render(const XrFrameState & frame_state) } if (state_ == state::stalled) - application::pop_scene(); - - assert(swapchain); - for (auto & i: decoders) { - if (auto sampler = i.decoder->sampler(); sampler and not *i.blit_pipeline) - { - // Create blit pipeline - // Create VkDescriptorSetLayout with an immutable sampler - vk::DescriptorSetLayoutBinding sampler_layout_binding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - .pImmutableSamplers = &sampler, - }; + network_session->send_control(from_headset::get_application_list{ + .language = application::get_messages_info().language, + .country = application::get_messages_info().country, + .variant = application::get_messages_info().variant, + }); - vk::DescriptorSetLayoutCreateInfo layout_info{ - .bindingCount = 1, - .pBindings = &sampler_layout_binding, - }; - - i.descriptor_set_layout = vk::raii::DescriptorSetLayout(device, layout_info); - i.descriptor_set = device.allocateDescriptorSets( - vk::DescriptorSetAllocateInfo{ - .descriptorPool = *blit_descriptor_pool, - .descriptorSetCount = 1, - .pSetLayouts = &*i.descriptor_set_layout, - })[0] - .release(); - - const auto & description = i.decoder->desc(); - vk::Extent2D image_size = i.decoder->image_size(); - std::array useful_size{ - float(description.width) / image_size.width, - float(description.height) / image_size.height, - }; - spdlog::info("useful size: {}x{} with buffer {}x{}", - description.width, - description.height, - image_size.width, - image_size.height); - - std::array specialization_constants_desc{ - vk::SpecializationMapEntry{ - .constantID = 0, - .offset = 0, - .size = sizeof(float), - }, - vk::SpecializationMapEntry{ - .constantID = 1, - .offset = sizeof(float), - .size = sizeof(float), - }}; - - vk::SpecializationInfo vert_specialization_info; - vert_specialization_info.setMapEntries(specialization_constants_desc); - vert_specialization_info.setData(useful_size); - - std::array constants = { - need_srgb_conversion(guess_model()), - i.alpha(), - }; - std::array frag_specialization_constant_desc = { - vk::SpecializationMapEntry{ - .constantID = 0, - .offset = 0, - .size = sizeof(constants[0]), - }, - vk::SpecializationMapEntry{ - .constantID = 1, - .offset = sizeof(constants[0]), - .size = sizeof(constants[1]), - }, - }; - vk::SpecializationInfo frag_specialization_info; - frag_specialization_info.setMapEntries(frag_specialization_constant_desc); - frag_specialization_info.setData(constants); - - // Create graphics pipeline - vk::raii::ShaderModule vertex_shader = load_shader(device, "stream.vert"); - vk::raii::ShaderModule fragment_shader = load_shader(device, "stream.frag"); - - vk::PipelineLayoutCreateInfo pipeline_layout_info{ - .setLayoutCount = 1, - .pSetLayouts = &*i.descriptor_set_layout, - }; - - i.blit_pipeline_layout = vk::raii::PipelineLayout(device, pipeline_layout_info); - - vk::pipeline_builder pipeline_info{ - .Stages = {{ - .stage = vk::ShaderStageFlagBits::eVertex, - .module = *vertex_shader, - .pName = "main", - .pSpecializationInfo = &vert_specialization_info, - }, - { - .stage = vk::ShaderStageFlagBits::eFragment, - .module = *fragment_shader, - .pName = "main", - .pSpecializationInfo = &frag_specialization_info, - }}, - .VertexBindingDescriptions = {}, - .VertexAttributeDescriptions = {}, - .InputAssemblyState = {{ - .topology = vk::PrimitiveTopology::eTriangleStrip, - }}, - // With vk::DynamicState::eViewport, vk::DynamicState::eScissor the number of viewports - // and scissors is still used, put a vector with one element - .Viewports = {{}}, - .Scissors = {{}}, - .RasterizationState = {{ - .polygonMode = vk::PolygonMode::eFill, - .lineWidth = 1, - }}, - .MultisampleState = {{ - .rasterizationSamples = vk::SampleCountFlagBits::e1, - }}, - .ColorBlendAttachments = { - {.colorWriteMask = i.alpha() ? vk::ColorComponentFlagBits::eA - : vk::ColorComponentFlagBits::eA | vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB}}, - .DynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}, - .layout = *i.blit_pipeline_layout, - .renderPass = *blit_render_pass, - .subpass = 0, - }; - - i.blit_pipeline = vk::raii::Pipeline(device, application::get_pipeline_cache(), pipeline_info); - } + application::pop_scene(); } + assert(swapchain); if (device.waitForFences(*fence, VK_TRUE, UINT64_MAX) == vk::Result::eTimeout) throw std::runtime_error("Vulkan fence timeout"); @@ -928,11 +811,13 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array image_indices; +#if WIVRN_FEATURE_RENDERDOC + renderdoc_begin(*vk_instance); +#endif command_buffer.reset(); - - vk::CommandBufferBeginInfo begin_info; - begin_info.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; - command_buffer.begin(begin_info); + command_buffer.begin(vk::CommandBufferBeginInfo{ + .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit, + }); // Keep a reference to the resources needed to blit the images until vkWaitForFences @@ -947,13 +832,12 @@ void scenes::stream::render(const XrFrameState & frame_state) std::array foveation{}; bool use_alpha = false; - // Blit images from the decoders - for (auto [i, blit_handle]: std::views::zip(decoders, current_blit_handles)) + for (auto & blit_handle: current_blit_handles) { - if (not blit_handle or not *i.blit_pipeline) + if (not blit_handle) continue; - blit_handle->feedback.blitted = application::now(); + blit_handle->feedback.blitted = instance.now(); if (blit_handle->feedback.blitted - blit_handle->feedback.received_from_decoder > 1'000'000'000) state_ = stream::state::stalled; ++blit_handle->feedback.times_displayed; @@ -964,27 +848,12 @@ void scenes::stream::render(const XrFrameState & frame_state) foveation = blit_handle->view_info.foveation; use_alpha = blit_handle->view_info.alpha; - vk::DescriptorImageInfo image_info{ - .imageView = *blit_handle->image_view, - .imageLayout = vk::ImageLayout::eGeneral, - }; - - vk::WriteDescriptorSet descriptor_write{ - .dstSet = i.descriptor_set, - .dstBinding = 0, - .dstArrayElement = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = &image_info, - }; - - device.updateDescriptorSets(descriptor_write, {}); - if (*blit_handle->current_layout != vk::ImageLayout::eGeneral) + if (blit_handle->current_layout == vk::ImageLayout::eUndefined) { vk::ImageMemoryBarrier barrier{ .srcAccessMask = vk::AccessFlagBits::eNone, .dstAccessMask = vk::AccessFlagBits::eMemoryRead, - .oldLayout = *blit_handle->current_layout, + .oldLayout = vk::ImageLayout::eUndefined, .newLayout = vk::ImageLayout::eGeneral, .image = blit_handle->image, .subresourceRange = { @@ -995,72 +864,22 @@ void scenes::stream::render(const XrFrameState & frame_state) }; command_buffer.pipelineBarrier(vk::PipelineStageFlagBits::eAllCommands, vk::PipelineStageFlagBits::eAllCommands, {}, {}, {}, barrier); - *blit_handle->current_layout = vk::ImageLayout::eGeneral; + blit_handle->current_layout = vk::ImageLayout::eGeneral; } } - uint16_t x_offset = 0; - for (auto & out: decoder_output) + // Blit images from the decoders + std::array blitted; + for (auto [i, b]: utils::enumerate(blitters)) { - command_buffer.beginRenderPass( - { - .renderPass = *blit_render_pass, - .framebuffer = *out.frame_buffer, - .renderArea = { - .offset = {0, 0}, - .extent = decoder_out_size, - }, - .clearValueCount = 0, - }, - vk::SubpassContents::eInline); - - for (const auto & decoder: decoders) + b.begin(command_buffer); + for (auto [j, blit_handle]: utils::enumerate(current_blit_handles)) { - if (not *decoder.blit_pipeline) + if (not blit_handle) continue; - if (decoder.alpha() and not use_alpha) - continue; - - command_buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, *decoder.blit_pipeline); - - const auto & description = decoder.decoder->desc(); - int x0 = description.offset_x - x_offset; - int y0 = description.offset_y; - int x1 = x0 + description.width * description.subsampling; - int y1 = y0 + description.height * description.subsampling; - - vk::Viewport viewport{ - .x = (float)x0, - .y = (float)y0, - .width = float(description.width * description.subsampling), - .height = float(description.height * description.subsampling), - .minDepth = 0, - .maxDepth = 1, - }; - - x0 = std::clamp(x0, 0, decoder_out_size.width); - x1 = std::clamp(x1, 0, decoder_out_size.width); - y0 = std::clamp(y0, 0, decoder_out_size.height); - y1 = std::clamp(y1, 0, decoder_out_size.height); - - vk::Rect2D scissor{ - .offset = {.x = x0, .y = y0}, - .extent = {.width = (uint32_t)(x1 - x0), .height = (uint32_t)(y1 - y0)}, - }; - - command_buffer.setViewport(0, viewport); - command_buffer.setScissor(0, scissor); - - command_buffer.bindDescriptorSets( - vk::PipelineBindPoint::eGraphics, - *decoder.blit_pipeline_layout, - 0, - decoder.descriptor_set, - nullptr); - command_buffer.draw(3, 1, 0, 0); + b.push_image(command_buffer, j, decoders[j].decoder->sampler(), decoders[j].decoder->extent(), blit_handle->image_view, blit_handle->current_layout); } - command_buffer.endRenderPass(); - x_offset += decoder_out_size.width; + blitted[i] = b.end(command_buffer); } command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 1); @@ -1071,7 +890,7 @@ void scenes::stream::render(const XrFrameState & frame_state) int32_t max_height = 0; for (size_t i = 0; i < view_count; ++i) { - extents[i] = reprojector->defoveated_size(foveation[i]); + extents[i] = defoveator->defoveated_size(foveation[i]); max_width = std::max(max_width, extents[i].width); max_height = std::max(max_height, extents[i].height); } @@ -1101,7 +920,7 @@ void scenes::stream::render(const XrFrameState & frame_state) // defoveate the image int image_index = swapchain.acquire(); swapchain.wait(); - reprojector->reproject(command_buffer, foveation, image_index); + defoveator->defoveate(command_buffer, foveation, blitted, image_index); command_buffer.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, *query_pool, 2); @@ -1109,6 +928,9 @@ void scenes::stream::render(const XrFrameState & frame_state) vk::SubmitInfo submit_info; submit_info.setCommandBuffers(*command_buffer); queue.lock()->submit(submit_info, *fence); +#if WIVRN_FEATURE_RENDERDOC + renderdoc_end(*vk_instance); +#endif swapchain.release(); std::vector layer_view(view_count); @@ -1275,119 +1097,15 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript } video_stream_description = description; - - const uint32_t video_width = description.width / view_count; - const uint32_t video_height = description.height; - - // Create renderpass - { - vk::AttachmentDescription color_desc{ - .format = vk::Format::eA8B8G8R8SrgbPack32, - .samples = vk::SampleCountFlagBits::e1, - .loadOp = vk::AttachmentLoadOp::eDontCare, - .storeOp = vk::AttachmentStoreOp::eStore, - .initialLayout = vk::ImageLayout::eUndefined, - .finalLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - }; - - vk::AttachmentReference color_ref{ - .attachment = 0, - .layout = vk::ImageLayout::eColorAttachmentOptimal, - }; - - vk::SubpassDescription subpass{ - .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, - }; - subpass.setColorAttachments(color_ref); - - vk::RenderPassCreateInfo renderpass_info{ - .flags = {}, - }; - renderpass_info.setAttachments(color_desc); - renderpass_info.setSubpasses(subpass); - - blit_render_pass = vk::raii::RenderPass(device, renderpass_info); - } - - // Create outputs for the decoders - decoder_out_size = vk::Extent2D{video_width, video_height}; - { - decoder_out_format = vk::Format::eA8B8G8R8SrgbPack32; - - vk::ImageCreateInfo image_info{ - .flags = vk::ImageCreateFlags{}, - .imageType = vk::ImageType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .extent = {video_width, video_height, 1}, - .mipLevels = 1, - .arrayLayers = view_count, - .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, - }; - - decoder_out_image = image_allocation{device, image_info, alloc_info}; - - vk::ImageViewCreateInfo image_view_info{ - .image = vk::Image{decoder_out_image}, - .viewType = vk::ImageViewType::e2D, - .format = vk::Format::eA8B8G8R8SrgbPack32, - .components = {}, - .subresourceRange = { - .aspectMask = vk::ImageAspectFlagBits::eColor, - .baseMipLevel = 0, - .levelCount = 1, - .baseArrayLayer = 0, - .layerCount = 1, - }, - }; - - for (uint32_t view = 0; view < view_count; ++view) - { - auto & output = decoder_output[view]; - - image_view_info.subresourceRange.baseArrayLayer = view; - output.image_view = vk::raii::ImageView(device, image_view_info); - - output.frame_buffer = vk::raii::Framebuffer( - device, - vk::FramebufferCreateInfo{ - .renderPass = *blit_render_pass, - .attachmentCount = 1, - .pAttachments = &*output.image_view, - .width = decoder_out_size.width, - .height = decoder_out_size.height, - .layers = 1, - }); - } - } - - { - vk::DescriptorPoolSize pool_size{ - .type = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = uint32_t(2 * description.items.size()), - }; - blit_descriptor_pool = vk::raii::DescriptorPool( - device, - vk::DescriptorPoolCreateInfo{ - .maxSets = uint32_t(2 * description.items.size()), - .poolSizeCount = 1, - .pPoolSizes = &pool_size, - }); - } + for (auto & b: blitters) + b.reset(description); for (const auto & [stream_index, item]: utils::enumerate(description.items)) { spdlog::info("Creating decoder size {}x{} offset {},{}", item.width, item.height, item.offset_x, item.offset_y); decoders.push_back(accumulator_images{ - .decoder = std::make_unique(device, physical_device, item, description.fps, shared_from_this(), stream_index), + .decoder = std::make_unique(device, physical_device, instance, item, description.fps, shared_from_this(), stream_index), }); } } @@ -1400,15 +1118,6 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint const uint32_t video_width = video_stream_description->width / view_count; const uint32_t video_height = video_stream_description->height; - const configuration::sgsr_settings sgsr = application::get_config().sgsr; - if (sgsr.enabled) - { - const float upscaling_factor = sgsr.upscaling_factor; - spdlog::info("Using SGSR with an upscale factor of {}", upscaling_factor); - swapchain_width *= upscaling_factor; - swapchain_height *= upscaling_factor; - } - auto views = system.view_configuration_views(viewconfig); swapchain = xr::swapchain(session, device, swapchain_format, swapchain_width, swapchain_height, 1, views.size()); @@ -1425,12 +1134,9 @@ void scenes::stream::setup_reprojection_swapchain(uint32_t swapchain_width, uint for (auto & image: swapchain.images()) swapchain_images.push_back(image.image); - reprojector.emplace( + defoveator.emplace( device, physical_device, - decoder_out_image, - vk::Extent2D{.width = video_width, .height = video_height}, - 2, swapchain_images, extent, swapchain.format()); diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 6f506ab7..64cafea0 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -23,8 +23,9 @@ #include "decoder/shard_accumulator.h" #include "render/imgui_impl.h" #include "scene.h" +#include "scenes/blitter.h" #include "scenes/input_profile.h" -#include "stream_reprojection.h" +#include "stream_defoveator.h" #include "utils/thread_safe.h" #include "wifi_lock.h" #include "wivrn_client.h" @@ -48,6 +49,13 @@ public: }; static const size_t image_buffer_size = 3; + struct app + { + std::string id; + std::string name; + std::vector image; + }; + private: static const size_t view_count = 2; @@ -56,16 +64,12 @@ private: struct accumulator_images { std::unique_ptr decoder; - vk::raii::DescriptorSetLayout descriptor_set_layout = nullptr; - vk::DescriptorSet descriptor_set = nullptr; - vk::raii::PipelineLayout blit_pipeline_layout = nullptr; - vk::raii::Pipeline blit_pipeline = nullptr; - // latest frames from oldest to most recent + // latest frames, rolling buffer std::array, image_buffer_size> latest_frames; std::shared_ptr frame(uint64_t id) const; bool alpha() const; - std::vector frames() const; + bool empty() const; }; wifi_lock::wifi wifi; @@ -77,9 +81,9 @@ private: std::unique_ptr network_session; std::atomic exiting = false; std::thread network_thread; - std::mutex tracking_control_mutex; - to_headset::tracking_control tracking_control{}; + thread_safe tracking_control{}; std::array, 2> interaction_profiles; // left and right hand + std::atomic interaction_profile_changed = false; std::atomic recenter_requested = false; std::atomic display_time_phase = 0; std::atomic display_time_period = 0; @@ -90,21 +94,10 @@ private: std::shared_mutex decoder_mutex; std::optional video_stream_description; std::vector decoders; // Locked by decoder_mutex - vk::raii::DescriptorPool blit_descriptor_pool = nullptr; - vk::raii::RenderPass blit_render_pass = nullptr; - vk::Extent2D decoder_out_size; - vk::Format decoder_out_format; - image_allocation decoder_out_image; + std::array blitters; - struct renderpass_output - { - vk::raii::ImageView image_view = nullptr; - vk::raii::Framebuffer frame_buffer = nullptr; - }; - std::array decoder_output; - - std::optional reprojector; + std::optional defoveator; vk::raii::Fence fence = nullptr; vk::raii::CommandBuffer command_buffer = nullptr; @@ -125,6 +118,8 @@ private: std::optional