diff --git a/CMakeLists.txt b/CMakeLists.txt index de67ae79..aa8c5723 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -39,7 +39,12 @@ option(WIVRN_BUILD_WIVRNCTL "Build wivrnctl" ON) option(WIVRN_BUILD_DISSECTOR "Build Wireshark dissector" OFF) option(WIVRN_BUILD_TEST "Build test binaries" OFF) option(WIVRN_WERROR "Treat warnings as errors" OFF) -option(WIVRN_OPTIMIZE_SHADERS "Run siprv-opt on compiled shaders" ON) +option(WIVRN_OPTIMIZE_SHADERS "Run spirv-opt on compiled shaders" ON) +option(WIVRN_DEBUG_SHADERS "Compile shaders with debug information" OFF) + +if(WIVRN_OPTIMIZE_SHADERS AND WIVRN_DEBUG_SHADERS) + message(FATAL_ERROR "WIVRN_OPTIMIZE_SHADERS and WIVRN_DEBUG_SHADERS are incompatible") +endif() option(WIVRN_USE_NVENC "Enable nvenc (Nvidia) hardware encoder" ON) option(WIVRN_USE_VAAPI "Enable vaapi (AMD/Intel) hardware encoder" ON) @@ -97,9 +102,9 @@ include(VulkanVersion) if (WIVRN_USE_SYSTEM_BOOST AND NEED_COMMON) if (WIVRN_BUILD_DISSECTOR) - find_package(Boost 1.84.0 REQUIRED COMPONENTS locale url) + find_package(Boost 1.84.0 REQUIRED COMPONENTS locale url iostreams) else() - find_package(Boost 1.75.0 REQUIRED COMPONENTS locale url) + find_package(Boost 1.75.0 REQUIRED COMPONENTS locale url iostreams) endif() endif() diff --git a/assets/ray-htc.glb b/assets/ray-htc.glb index 3082b690..065a7aec 100644 Binary files a/assets/ray-htc.glb and b/assets/ray-htc.glb differ diff --git a/assets/ray.glb b/assets/ray.glb index 8433e1e7..bc6d26d6 100644 Binary files a/assets/ray.glb and b/assets/ray.glb differ diff --git a/client/constants.h b/client/constants.h index 1d39f73d..eb64fdf8 100644 --- a/client/constants.h +++ b/client/constants.h @@ -53,9 +53,8 @@ constexpr float fingertip_distance_stick_thd = -0.02; // Max distance wher constexpr float scroll_value_thd = 0.01; // Pointer radius -constexpr float pointer_radius_in = 10; -constexpr float pointer_radius_out = 12; -constexpr float pointer_thickness = 4; +constexpr float pointer_thickness = 2; +constexpr float pointer_radius_in = 6; // Pointer transparency constexpr float pointer_alpha = 0.8; @@ -63,8 +62,7 @@ constexpr float pointer_alpha_disabled = 0.25; constexpr float pointer_fading_distance = 40; // Pointer color -constexpr uint32_t pointer_color_pressed = 0xffff3300; -constexpr uint32_t pointer_color_unpressed = 0xffffffff; +constexpr uint32_t pointer_color = 0x40ffffff; constexpr uint32_t pointer_color_border = 0xff000000; } // namespace constants::gui @@ -110,7 +108,8 @@ constexpr int zindex_passthrough = -2; constexpr int zindex_lobby = -1; constexpr int zindex_gui = 0; constexpr int zindex_controllers = 1; -constexpr int zindex_recenter_tip = 2; +constexpr int zindex_tooltip = 2; +constexpr int zindex_recenter_tip = 3; } // namespace constants::lobby namespace constants::stream @@ -131,7 +130,7 @@ constexpr float window_rounding = 10; constexpr ImVec2 tooltip_padding = {5, 5}; constexpr float tooltip_rounding = 0; -constexpr float tooltip_distance = 10; +constexpr glm::vec3 tooltip_distance = {0, 0.004, 0.005}; constexpr ImVec2 button_size = {220, 80}; constexpr ImVec2 icon_button_size = {80, 80}; diff --git a/client/hardware.cpp b/client/hardware.cpp index c27fe30a..b51ba930 100644 --- a/client/hardware.cpp +++ b/client/hardware.cpp @@ -376,10 +376,10 @@ std::pair controller_offset(std::string_view profile, xr:: return {{0, -0.006, -0.025}, glm::angleAxis(glm::radians(-15.f), glm::vec3{1, 0, 0})}; case xr::spaces::aim_left: - return {{-0.010, 0, 0.025}, {1, 0, 0, 0}}; + return {{-0.010, 0, 0.02}, {1, 0, 0, 0}}; case xr::spaces::aim_right: - return {{0.010, 0, 0.025}, {1, 0, 0, 0}}; + return {{0.010, 0, 0.02}, {1, 0, 0, 0}}; default: break; @@ -392,6 +392,10 @@ std::pair controller_offset(std::string_view profile, xr:: case xr::spaces::grip_right: return {{0, -0.010, -0.025}, glm::angleAxis(glm::radians(-12.f), glm::vec3{1, 0, 0})}; + case xr::spaces::aim_left: + case xr::spaces::aim_right: + return {{0, 0, -0.03}, {1, 0, 0, 0}}; + default: break; } diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index e8f29f8e..97f5d752 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -214,7 +215,7 @@ std::vector> imgui_context::ray_plane_intersection(cons for (const auto & i: layers_) { - if (i.space != xr::spaces::world) + if (i.space != xr::spaces::world or i.tooltip_viewport) continue; auto M = glm::transpose(glm::mat3_cast(i.orientation)); // world-to-plane transform @@ -633,10 +634,6 @@ std::vector imgui_context::read_controllers_sta auto trigger = application::read_action_float(ctrl.trigger).value_or(std::pair{0, 0}); state.trigger_value = trigger.second; - // TODO tunable - /*if (new_state.trigger_value < 0.5) - new_state.trigger_clicked = false; - else */ if (state.trigger_value > constants::gui::trigger_click_thd) state.trigger_clicked = true; } @@ -920,15 +917,13 @@ std::vector> imgui_context::end_frame() else alpha *= constants::gui::pointer_alpha_disabled; - ImU32 color_pressed = ImGui::GetColorU32(constants::gui::pointer_color_pressed, alpha); - ImU32 color_unpressed = ImGui::GetColorU32(constants::gui::pointer_color_unpressed, alpha); - - bool pressed = controller.second.trigger_clicked || controller.second.fingertip_touching; + float radius_in = constants::gui::pointer_radius_in; + float radius_out = radius_in + constants::gui::pointer_thickness * 0.5; ImDrawList * draw_list = ImGui::GetForegroundDrawList(); draw_list->PushClipRect(clip_rect_min, clip_rect_max); - draw_list->AddCircleFilled(*position, constants::gui::pointer_radius_in, pressed ? color_pressed : color_unpressed); - draw_list->AddCircle(*position, constants::gui::pointer_radius_out, ImGui::GetColorU32(constants::gui::pointer_color_border, alpha), 0, constants::gui::pointer_thickness); + draw_list->AddCircleFilled(*position, radius_in, ImGui::GetColorU32(constants::gui::pointer_color, alpha)); + draw_list->AddCircle(*position, radius_out, ImGui::GetColorU32(constants::gui::pointer_color_border, alpha), 0, constants::gui::pointer_thickness); draw_list->PopClipRect(); } } @@ -983,15 +978,47 @@ std::vector> imgui_context::end_frame() for (auto & i: layers_) { bool visible = false; + + ImRect layer_rect( + i.vp_origin.x, + i.vp_origin.y, + i.vp_origin.x + i.vp_size.x, + i.vp_origin.y + i.vp_size.y); + + ImRect all_windows_rect{ + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::lowest(), + std::numeric_limits::lowest(), + }; + for (ImGuiWindow * window: context->Windows) { - if (window->Active and not window->Hidden and window_intersects_viewport(window, i)) + ImRect window_rect{ + window->Pos.x, + window->Pos.y, + window->Pos.x + window->Size.x, + window->Pos.y + window->Size.y}; + + if (window->Active and not window->Hidden and layer_rect.Overlaps(window_rect)) { visible = true; - break; + + // Take the union of all visible windows in this layer + all_windows_rect.Add(window_rect); } } + // Take the intersection with the layer + all_windows_rect.ClipWithFull(layer_rect); + + glm::vec2 pixel_size = i.size / glm::vec2(i.vp_size); + glm::vec2 all_windows_center(all_windows_rect.GetCenter().x, all_windows_rect.GetCenter().y); + glm::vec2 layer_center(layer_rect.GetCenter().x, layer_rect.GetCenter().y); + + glm::vec3 new_position = i.position + i.orientation * glm::vec3((all_windows_center - layer_center) * pixel_size, 0); + glm::vec2 new_size = glm::vec2(all_windows_rect.GetWidth(), all_windows_rect.GetHeight()) * pixel_size; + if (not visible) continue; @@ -1006,12 +1033,12 @@ std::vector> imgui_context::end_frame() .swapchain = swapchain, .imageRect = { .offset = { - .x = i.vp_origin.x, - .y = i.vp_origin.y, + .x = int(all_windows_rect.Min.x), + .y = int(all_windows_rect.Min.y), }, .extent = { - .width = i.vp_size.x, - .height = i.vp_size.y, + .width = int(all_windows_rect.Max.x - all_windows_rect.Min.x), + .height = int(all_windows_rect.Max.y - all_windows_rect.Min.y), }}, }, .pose = { @@ -1022,14 +1049,14 @@ std::vector> imgui_context::end_frame() .w = i.orientation.w, }, .position = { - .x = i.position.x, - .y = i.position.y, - .z = i.position.z, + .x = new_position.x, + .y = new_position.y, + .z = new_position.z, }, }, .size = { - .width = i.size.x, - .height = i.size.y, + .width = new_size.x, + .height = new_size.y, }, }); } @@ -1037,11 +1064,9 @@ std::vector> imgui_context::end_frame() return quads; } -std::vector imgui_context::windows() +std::vector imgui_context::windows() { - std::vector w; - - ImGuiWindow * modal_popup = ImGui::GetTopMostAndVisiblePopupModal(); + std::vector w; for (const imgui_context::viewport & layer: layers_) { @@ -1052,10 +1077,7 @@ std::vector imgui_context::windows() for (ImGuiWindow * window: context->Windows) { - if (not window->Active or window->Hidden /*or window->ParentWindowInBeginStack != nullptr*/) - continue; - - if (modal_popup != nullptr and window != modal_popup and not layer.always_show_cursor) + if (not window->Active or window->Hidden or (window->Flags & ImGuiWindowFlags_ChildWindow)) continue; if (not window_intersects_viewport(window, layer)) @@ -1066,7 +1088,7 @@ std::vector imgui_context::windows() ImVec2 min = ImMax(v.Min, window->Pos); ImVec2 center = (min + max) / 2; - w.push_back(viewport{ + w.push_back(window_viewport{ .space = layer.space, .position = layer.position + glm::mat3_cast(layer.orientation) * @@ -1079,9 +1101,6 @@ std::vector imgui_context::windows() (max.x - min.x) * layer.size.x / layer.vp_size.x, (max.y - min.y) * layer.size.y / layer.vp_size.y, }, - .vp_origin = {min.x, min.y}, - .vp_size = {max.x - min.x, max.y - min.y}, - .always_show_cursor = layer.always_show_cursor, }); } } @@ -1241,34 +1260,32 @@ void imgui_context::tooltip(std::string_view text) // FIXME: this is incorrect if we use the docking branch of imgui ImGuiViewport * viewport = ImGui::GetMainViewport(); auto & current_layer = layer(ImGui::GetMousePos()); - auto pos_backup = viewport->Pos; - auto size_backup = viewport->Size; - viewport->Pos = ImVec2(current_layer.vp_origin.x, current_layer.vp_origin.y); - viewport->Size = ImVec2(current_layer.vp_size.x, current_layer.vp_size.y); - ImVec2 pos{ + assert(std::ranges::contains(layers_, true, &viewport::tooltip_viewport)); + auto & tooltip_layer = *std::ranges::find(layers_, true, &viewport::tooltip_viewport); + + // Get the item position before drawing the tooltip (top center) + ImVec2 item_position{ (ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2, - ImGui::GetItemRectMin().y - constants::style::tooltip_distance, + ImGui::GetItemRectMin().y, }; + auto pos_backup = viewport->Pos; + auto size_backup = viewport->Size; + viewport->Pos = ImVec2(tooltip_layer.vp_origin.x, tooltip_layer.vp_origin.y); + viewport->Size = ImVec2(tooltip_layer.vp_size.x, tooltip_layer.vp_size.y); + + // Draw the tooltip in the tooltip layer + // Clamp position to avoid overflowing on the left or the right ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding); - // Clamp position to avoid overflowing on the left or the right auto & style = ImGui::GetStyle(); const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true); - const ImVec2 size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f}; - pos.x = std::clamp(pos.x, viewport->Pos.x + size.x / 2, viewport->Pos.x + viewport->Size.x - size.x / 2); - ImVec2 pivot = {0.5, 1}; + const ImVec2 tooltip_size = {text_size.x + style.WindowPadding.x * 2.0f, text_size.y + style.WindowPadding.y * 2.0f}; - // Move tooltip below the item if it overflows on the top - if (pos.y - size.y <= viewport->Pos.y) - { - pos.y = ImGui::GetItemRectMax().y + constants::style::tooltip_distance; - pivot.y = 0; - } - - ImGui::SetNextWindowPos(pos, ImGuiCond_Always, pivot); + ImGui::SetNextWindowPos(viewport->Pos + viewport->Size * 0.5, ImGuiCond_Always, {0.5, 0.5}); + ImGui::SetNextWindowSizeConstraints({0, 0}, viewport->Size); if (ImGui::BeginTooltip()) { ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff); @@ -1276,11 +1293,21 @@ void imgui_context::tooltip(std::string_view text) ImGui::PopStyleColor(); ImGui::EndTooltip(); } - ImGui::PopStyleVar(2); viewport->Pos = pos_backup; viewport->Size = size_backup; + + // Compute the tooltip position + glm::quat tooltip_orientation = current_layer.orientation; + auto M = glm::mat3_cast(tooltip_orientation); + + float pixel_size = current_layer.size.y / current_layer.vp_size.y; + glm::vec3 tooltip_position_centre = rw_from_vp(item_position) + M * (glm::vec3(0, tooltip_size.y / 2, 0) * pixel_size + constants::style::tooltip_distance); + + // Position the tooltip layer + tooltip_layer.position = tooltip_position_centre; + tooltip_layer.orientation = tooltip_orientation; } // https://github.com/ocornut/imgui/issues/3379#issuecomment-2943903877 diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 0f96b780..b659dd18 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -136,6 +136,7 @@ public: glm::ivec2 vp_size; bool always_show_cursor = false; // Show the cursor in this viewport even if there is a modal popup elsewhere (eg. this is a virtual keyboard) + bool tooltip_viewport = false; // Choose this viewport to display the tooltip, ignore mouse events int z_index = 0; @@ -145,6 +146,15 @@ public: } }; + struct window_viewport + { + // Position of this window in the world + xr::spaces space; + glm::vec3 position; + glm::quat orientation; + glm::vec2 size; + }; + private: uint32_t queue_family_index; @@ -215,7 +225,7 @@ public: return layers_; } - std::vector windows(); + std::vector windows(); viewport & layer(ImVec2 position); diff --git a/client/render/scene_components.h b/client/render/scene_components.h index 28b1b2a9..36188cb6 100644 --- a/client/render/scene_components.h +++ b/client/render/scene_components.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include #include @@ -100,7 +101,7 @@ struct material size_t offset; std::string name; - std::string fragment_shader_name = "lit.frag"; + std::string fragment_shader = "lit.frag"; }; struct primitive @@ -110,7 +111,7 @@ struct primitive uint32_t vertex_count; vk::IndexType index_type; vk::DeviceSize index_offset; - std::vector vertex_offset; // TODO: inplace_vector + beman::inplace_vector::inplace_vector vertex_offset; // See VkPhysicalDeviceLimits::maxVertexInputBindings vertex_layout layout; glm::vec3 obb_min; @@ -155,11 +156,24 @@ struct node bool visible = true; uint32_t layer_mask = -1; - std::array clipping_planes; - // TODO: separate component? std::vector> joints; // Node index, inverse bind matrix of each joint + std::vector extra_shader_data; + template + void set_extra_shader_data(const T & data) + { + extra_shader_data.resize(sizeof(std::decay_t)); + memcpy(extra_shader_data.data(), &data, sizeof(std::decay_t)); + } + + template + T & get_extra_shader_data() + { + assert(extra_shader_data.size() == sizeof(std::decay_t)); + return *reinterpret_cast(extra_shader_data.data()); + } + // For internal use by the renderer glm::mat4 transform_to_root; bool global_visible; diff --git a/client/render/scene_loader.cpp b/client/render/scene_loader.cpp index ef44967f..8dab64ec 100644 --- a/client/render/scene_loader.cpp +++ b/client/render/scene_loader.cpp @@ -45,6 +45,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -513,7 +516,7 @@ struct : std::error_category } fastgltf_error_category; // END -fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory) +fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::filesystem::path & directory, std::function extra_callback) { fastgltf::Parser parser( fastgltf::Extensions::KHR_texture_basisu | @@ -524,6 +527,12 @@ fastgltf::Asset load_gltf_asset(fastgltf::GltfDataBuffer & buffer, const std::fi fastgltf::Options::AllowDouble | fastgltf::Options::DecomposeNodeMatrices; + parser.setUserPointer(&extra_callback); + parser.setExtrasParseCallback([](simdjson::dom::object * extras, std::size_t object_index, fastgltf::Category category, void * user_pointer) { + auto f = reinterpret_cast *>(user_pointer); + (*f)(*extras, object_index, category); + }); + auto expected_asset = parser.loadGltf(buffer, directory, gltf_options); if (auto error = expected_asset.error(); error != fastgltf::Error::None) @@ -540,7 +549,8 @@ class loader_context vk::raii::PhysicalDevice physical_device; vk::raii::Device & device; thread_safe & queue; - image_loader & loader; + image_loader loader; + const std::map, std::string> & extras; std::vector loaded_assets; utils::mapped_file & load_from_asset(const std::filesystem::path & path) @@ -563,14 +573,16 @@ public: vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, thread_safe & queue, - image_loader & loader) : + uint32_t queue_family_index, + std::map, std::string> & extras) : base_directory(std::move(base_directory)), name(std::move(name)), gltf(gltf), physical_device(physical_device), device(device), queue(queue), - loader(loader) + loader(device, physical_device, queue, queue_family_index), + extras(extras) { } @@ -793,6 +805,8 @@ public: materials.reserve(gltf.materials.size()); for (const fastgltf::Material & gltf_material: gltf.materials) { + size_t material_id = materials.size(); + // Copy the default material, without references to its buffer or descriptor set auto & material = *materials.emplace_back(std::make_shared(default_material)); material.name = gltf_material.name; @@ -803,21 +817,24 @@ public: switch (gltf_material.alphaMode) { case fastgltf::AlphaMode::Opaque: - material.fragment_shader_name = "lit.frag"; + material.fragment_shader = "lit.frag"; material.blend_enable = false; break; case fastgltf::AlphaMode::Mask: - material.fragment_shader_name = "lit_mask.frag"; + material.fragment_shader = "lit_mask.frag"; material.blend_enable = false; break; case fastgltf::AlphaMode::Blend: - material.fragment_shader_name = "lit.frag"; + material.fragment_shader = "lit.frag"; material.blend_enable = true; break; } + if (auto it = extras.find({fastgltf::Category::Materials, material_id, "fragment_shader"}); it != extras.end()) + material.fragment_shader = it->second; + renderer::material::gpu_data & material_data = material.staging; material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); @@ -870,6 +887,7 @@ public: meshes.reserve(gltf.meshes.size()); for (const fastgltf::Mesh & gltf_mesh: gltf.meshes) { + size_t mesh_id = meshes.size(); std::shared_ptr & mesh_ref = meshes.emplace_back(); mesh_ref = std::make_shared(); @@ -892,7 +910,9 @@ public: renderer::vertex_layout & layout = primitive_ref.layout; - if (gltf_primitive.findAttribute("JOINTS_0") == gltf_primitive.attributes.cend()) + if (auto it = extras.find({fastgltf::Category::Meshes, mesh_id, "vertex_shader"}); it != extras.end()) + primitive_ref.vertex_shader = it->second; + else if (gltf_primitive.findAttribute("JOINTS_0") == gltf_primitive.attributes.cend()) primitive_ref.vertex_shader = "lit.vert"; else primitive_ref.vertex_shader = "lit_skinned.vert"; @@ -1007,7 +1027,6 @@ public: node.orientation = glm::make_quat(TRS.rotation.data()); node.scale = glm::make_vec3(TRS.scale.data()); node.visible = true; - std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1}); } return entities; @@ -1148,10 +1167,19 @@ std::shared_ptr scene_loader::operator()( if (auto error = data_buffer.error(); error != fastgltf::Error::None) throw std::system_error((int)error, fastgltf_error_category); - fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), parent_path); + std::map, std::string> gltf_extras; - image_loader loader{device, physical_device, queue, queue_family_index}; - loader_context ctx{parent_path, name, asset, physical_device, device, queue, loader}; + fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), parent_path, [&](simdjson::dom::object & extras, std::size_t object_index, fastgltf::Category category) { + std::string_view value; + + for (const auto & kv: extras) + { + if (kv.value.get_string().get(value) == simdjson::SUCCESS) + gltf_extras.emplace(std::tuple{category, object_index, kv.key}, value); + } + }); + + loader_context ctx{parent_path, name, asset, physical_device, device, queue, queue_family_index, gltf_extras}; #ifndef NDEBUG if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None) diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index 6b24dab1..d8542057 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -29,6 +29,7 @@ #include "vk/pipeline.h" #include "vk/shader.h" #include "vk/specialization_constants.h" +#include #include #include #include @@ -675,8 +676,8 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) { spdlog::debug("Creating pipeline"); - auto vertex_shader = shader_loader{device}(info.vertex_shader_name); - auto fragment_shader = shader_loader{device}(info.fragment_shader_name); + auto vertex_shader = load_shader(device, info.vertex_shader_name); + auto fragment_shader = load_shader(device, info.fragment_shader_name); auto specialization = make_specialization_constants( int32_t(info.nb_texcoords), @@ -732,7 +733,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ .blendEnable = info.blend_enable, - .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, + .srcColorBlendFactor = vk::BlendFactor::eOne, .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, .colorBlendOp = vk::BlendOp::eAdd, .srcAlphaBlendFactor = vk::BlendFactor::eOne, @@ -1106,8 +1107,12 @@ void scene_renderer::render( // TODO: reuse the UBO if another primitive of the same mesh has already been drawn vk::DeviceSize instance_ubo_offset = resources.uniform_buffer_offset; + vk::DeviceSize instance_ubo_size = sizeof(instance_gpu_data) + node.extra_shader_data.size(); + instance_gpu_data & object_ubo = *reinterpret_cast(ubo + resources.uniform_buffer_offset); - resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data)); + std::span extra_shader_data{reinterpret_cast(ubo + resources.uniform_buffer_offset + sizeof(instance_gpu_data)), node.extra_shader_data.size()}; + + resources.uniform_buffer_offset += utils::align_up(buffer_alignment, sizeof(instance_gpu_data) + node.extra_shader_data.size()); vk::DeviceSize joints_ubo_offset = 0; if (!node.joints.empty()) @@ -1130,7 +1135,7 @@ void scene_renderer::render( object_ubo.modelview[frame_index] = frame.view * transform; object_ubo.modelviewproj[frame_index] = viewproj[frame_index] * transform; } - object_ubo.clipping_planes = node.clipping_planes; + std::ranges::copy(node.extra_shader_data, extra_shader_data.begin()); // Get the material std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; @@ -1139,7 +1144,7 @@ void scene_renderer::render( pipeline_info info{ .renderpass = rp_info, .vertex_shader_name = primitive.vertex_shader, - .fragment_shader_name = material->fragment_shader_name, + .fragment_shader_name = material->fragment_shader, .vertex_layout = primitive.layout, .cull_mode = primitive.cull_mode, .front_face = primitive.front_face, @@ -1187,7 +1192,7 @@ void scene_renderer::render( vk::DescriptorBufferInfo buffer_info_2{ .buffer = resources.uniform_buffer, .offset = instance_ubo_offset, - .range = sizeof(instance_gpu_data), + .range = instance_ubo_size, }; vk::DescriptorBufferInfo buffer_info_3{ .buffer = resources.uniform_buffer, diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index 1b9f2561..f1b9b8d3 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -199,7 +199,6 @@ class scene_renderer glm::mat4 model; std::array modelview; std::array modelviewproj; - std::array clipping_planes; }; struct debug_draw_vertex diff --git a/client/scene.cpp b/client/scene.cpp index d2a0273e..4bfdf273 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -158,16 +158,10 @@ void scene::render_world( const std::optional & foveation, bool render_debug_draws) { - std::vector frames; - frames.reserve(views.size()); - - // TODO inplace vector - std::vector composition_layer_color; - std::vector composition_layer_depth; - - composition_layer_color.reserve(views.size()); - if (keep_depth_buffer) - composition_layer_depth.reserve(views.size()); + assert(views.size() <= layer::max_views); + beman::inplace_vector::inplace_vector frames; + beman::inplace_vector::inplace_vector composition_layer_color; + beman::inplace_vector::inplace_vector composition_layer_depth; auto [color_swapchain, color_image, foveation_image] = [&]() -> std::tuple { xr::swapchain & color_swapchain = get_swapchain(swapchain_format, width, height, 1, views.size(), foveation); @@ -253,8 +247,8 @@ void scene::render_world( add_projection_layer( XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, space, - std::move(composition_layer_color), - std::move(composition_layer_depth)); + composition_layer_color, + composition_layer_depth); } xr::swapchain & scene::get_swapchain(vk::Format format, int32_t width, int32_t height, int sample_count, uint32_t array_size, const std::optional & foveation) @@ -377,8 +371,8 @@ void scene::render_start(bool passthrough, XrTime predicted_display_time_) void scene::add_projection_layer( XrCompositionLayerFlags flags, XrSpace space, - std::vector && color_views, - std::vector && depth_views) + std::span color_views, + std::span depth_views) { layers.push_back(layer{ .composition_layer = XrCompositionLayerProjection{ @@ -389,8 +383,8 @@ void scene::add_projection_layer( .viewCount = (uint32_t)color_views.size(), .views = nullptr, }, - .color_views = std::move(color_views), - .depth_views = std::move(depth_views), + .color_views{color_views.begin(), color_views.end()}, + .depth_views{depth_views.begin(), depth_views.end()}, }); } diff --git a/client/scene.h b/client/scene.h index f13571c6..7027c225 100644 --- a/client/scene.h +++ b/client/scene.h @@ -29,6 +29,7 @@ #include "xr/session.h" #include "xr/swapchain.h" #include "xr/system.h" +#include #include #include @@ -132,11 +133,12 @@ protected: struct layer { + static const int max_views = 2; + std::variant composition_layer; - // TODO in place vectors - std::vector color_views; // Used by XrCompositionLayerProjection - std::vector depth_views; // Used by XrCompositionLayerProjection + beman::inplace_vector::inplace_vector color_views; // Used by XrCompositionLayerProjection + beman::inplace_vector::inplace_vector depth_views; // Used by XrCompositionLayerProjection std::optional color_scale_bias; std::optional depth_test; @@ -172,8 +174,8 @@ protected: void add_projection_layer( XrCompositionLayerFlags flags, XrSpace space, - std::vector && color_views, - std::vector && depth_views = {}); + std::span color_views, + std::span depth_views = {}); void add_quad_layer( XrCompositionLayerFlags flags, diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp index ddc65def..ff8bc6b3 100644 --- a/client/scenes/input_profile.cpp +++ b/client/scenes/input_profile.cpp @@ -23,6 +23,8 @@ #include "render/scene_components.h" #include "utils/mapped_file.h" #include "xr/space.h" +#include +#include #include #include #include @@ -33,6 +35,7 @@ #include #include #include +#include namespace components { @@ -62,17 +65,27 @@ struct visual_response details::node_state state; }; -} // namespace components - -namespace -{ // Component added to nodes bound to an action space struct bound_space { xr::spaces space; + XrDuration Δt; }; +// Component added to node clipped by the GUI +struct clipped_by_gui +{ +}; + +struct emissive_trigger +{ + XrAction action; +}; +} // namespace components + +namespace +{ // clang-format off const std::unordered_map input_mappings = { {"xr-standard-squeeze" , "/input/squeeze/value" }, @@ -171,9 +184,21 @@ struct json_visual_response // OpenXR component path std::string component_subpath; }; + +struct ray_extra_shader_data +{ + std::array window_to_world; + float emissive_factor; +}; + +void setup_ray_shader(entt::registry & scene, entt::entity entity, const ray_extra_shader_data & initial_data = {}) +{ + auto & node = scene.get(entity); + node.set_extra_shader_data(initial_data); +} } // namespace -input_profile::input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray) +input_profile::input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray, XrAction left_trigger, XrAction right_trigger) { utils::mapped_file json{json_profile}; @@ -266,7 +291,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p auto [e, node] = scene.add_gltf(model, layer_mask_controller); node.name = layout; entity = e; - scene.world.emplace(e, space); + scene.world.emplace(e, space, 0); spdlog::debug("Created entity {}", layout); } @@ -281,16 +306,32 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p else continue; - auto && [entity, node] = scene.add_gltf(controller_ray_model_name(), layer_mask_ray); - node.name = (std::string)layout.key + "_ray"; - spdlog::debug("Created entity {}", node.name); + auto && [ray_entity, ray_node] = scene.add_gltf(controller_ray_model_name(), layer_mask_ray); - scene.world.emplace(entity, space); + ray_node.name = (std::string)layout.key + "_ray"; + spdlog::debug("Created entity {}", ray_node.name); - if (layout.key == "left") - left_ray = entity; - else if (layout.key == "right") - right_ray = entity; + scene.world.emplace(find_node_by_name(scene.world, "Ray", ray_entity), space, 0); + scene.world.emplace(find_node_by_name(scene.world, "Ray", ray_entity)); + scene.world.emplace(find_node_by_name(scene.world, "Ray", ray_entity), layout.key == "left" ? left_trigger : right_trigger); + setup_ray_shader(scene.world, find_node_by_name(scene.world, "Ray", ray_entity)); + + try + { + // These nodes don't exist in the HTC version + scene.world.emplace(find_node_by_name(scene.world, "Trail", ray_entity), space, 0); + scene.world.emplace(find_node_by_name(scene.world, "Trail now", ray_entity), space, 0); + scene.world.emplace(find_node_by_name(scene.world, "Trail -10ms", ray_entity), space, -10'000'000); + scene.world.emplace(find_node_by_name(scene.world, "Trail -20ms", ray_entity), space, -20'000'000); + scene.world.emplace(find_node_by_name(scene.world, "Trail -30ms", ray_entity), space, -30'000'000); + scene.world.emplace(find_node_by_name(scene.world, "Trail -40ms", ray_entity), space, -40'000'000); + scene.world.emplace(find_node_by_name(scene.world, "Trail", ray_entity)); + scene.world.emplace(find_node_by_name(scene.world, "Trail", ray_entity), layout.key == "left" ? left_trigger : right_trigger); + setup_ray_shader(scene.world, find_node_by_name(scene.world, "Trail", ray_entity)); + } + catch (...) + { + } } for (auto & json_response: json_responses) @@ -362,41 +403,6 @@ static void apply_visual_response(components::node & node, components::details:: node.visible = value > 0.5; } -static void set_clipping_planes(entt::registry & scene, entt::entity entity, std::span clipping_planes) -{ - // If the ray starts on the wrong side of the GUI, hide it entirely - // This assumes the node is a child of the root node - components::node & node = scene.get(entity); - for (glm::vec4 & plane: clipping_planes) - { - if (glm::dot(plane, glm::vec4(node.position, 1)) < 0) - { - scene.get(entity).visible = false; - return; - } - } - - // Apply the clipping planes on direct children of the target entity - for (auto && [child_entity, child_node]: scene.view().each()) - { - if (child_node.parent == entity) - { - size_t nb_clipping_planes = std::min(child_node.clipping_planes.size(), clipping_planes.size()); - - auto copy_results = std::ranges::copy_n( - clipping_planes.begin(), - nb_clipping_planes, - child_node.clipping_planes.begin()); - - // Disable the remaining clipping planes - std::ranges::fill_n( - copy_results.out, - child_node.clipping_planes.size() - nb_clipping_planes, - glm::vec4(0, 0, 0, 1)); - } - } -} - void input_profile::apply( entt::registry & scene, XrSpace world_space, @@ -405,9 +411,9 @@ void input_profile::apply( bool hide_left_ray, bool hide_right_controller, bool hide_right_ray, - std::span pointer_limits) + std::span world_to_window) { - for (auto && [entity, node, space]: scene.view().each()) + for (auto && [entity, node, space]: scene.view().each()) { if ((space.space == xr::spaces::grip_left and hide_left_controller) or (space.space == xr::spaces::aim_left and hide_left_ray) or @@ -416,7 +422,7 @@ void input_profile::apply( { node.visible = false; } - else if (auto location = application::locate_controller(application::space(space.space), world_space, predicted_display_time); location) + else if (auto location = application::locate_controller(application::space(space.space), world_space, predicted_display_time + space.Δt); location) { node.visible = true; @@ -495,6 +501,32 @@ void input_profile::apply( } } - set_clipping_planes(scene, left_ray, pointer_limits); - set_clipping_planes(scene, right_ray, pointer_limits); + for (auto && [entity, node, response]: scene.view().each()) + { + if (not response.action) + continue; + + if (auto opt_value = application::read_action_float(response.action)) + { + float value = opt_value->second * 0.9 + 0.1; + node.set_extra_shader_data(ray_extra_shader_data{{}, value}); + } + } + + for (auto && [entity, node]: scene.view().each()) + { + auto & data = node.get_extra_shader_data(); + size_t nb_windows = std::min(data.window_to_world.size(), world_to_window.size()); + + auto copy_results = std::ranges::copy_n( + world_to_window.begin(), + nb_windows, + data.window_to_world.begin()); + + // Disable the remaining clipping planes + std::ranges::fill_n( + copy_results.out, + data.window_to_world.size() - nb_windows, + glm::mat4{/* TODO */}); + } } diff --git a/client/scenes/input_profile.h b/client/scenes/input_profile.h index d8f549d5..83f3b144 100644 --- a/client/scenes/input_profile.h +++ b/client/scenes/input_profile.h @@ -37,7 +37,7 @@ struct input_profile magic_enum::containers::array> offset; - input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray); + input_profile(scene & scene, const std::filesystem::path & json_profile, uint32_t layer_mask_controller, uint32_t layer_mask_ray, XrAction left_trigger = XR_NULL_HANDLE, XrAction right_trigger = XR_NULL_HANDLE); // application::poll_actions() must have been called before void apply( @@ -48,5 +48,5 @@ struct input_profile bool hide_left_ray, bool hide_right_controller, bool hide_right_ray, - std::span pointer_limits); + std::span world_to_window); }; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index 39e693d5..a99887cb 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -626,28 +626,7 @@ std::optional scenes::lobby::check_recenter_gui(glm::vec3 head_positi return std::nullopt; } -// Return the vector v such that dot(v, x) > 0 iff x is on the side where the composition layer is visible -static glm::vec4 compute_ray_limits(const XrPosef & pose, float margin = 0) -{ - glm::quat q{ - pose.orientation.w, - pose.orientation.x, - pose.orientation.y, - pose.orientation.z, - }; - - glm::vec3 p{ - pose.position.x, - pose.position.y, - pose.position.z, - }; - - glm::vec3 normal = glm::column(glm::mat3_cast(q), 2); - - return glm::vec4(normal, -glm::dot(p, normal) - margin); -} - -static void stick_finger_to_gui(std::array & hand, const std::vector & layers) +static void stick_finger_to_gui(std::array & hand, const std::vector & layers) { // Move XR_HAND_JOINT_INDEX_{TIP,DISTAL,INTERMEDIATE,PROXIMAL}_EXT so that: // - Only the X rotation changes for distal and intermediate (relative to the parent bone) @@ -667,7 +646,7 @@ static void stick_finger_to_gui(std::array> intersections; // Target position of the finger tip, distance to the GUI plane - for (const imgui_context::viewport & layer: layers) + for (const imgui_context::window_viewport & layer: layers) { // Ignore layers that are not absolutely positionned if (layer.space != xr::spaces::world) @@ -1054,11 +1033,11 @@ void scenes::lobby::render(const XrFrameState & frame_state) #endif // Get the planes that limit the ray size from the composition layers - std::vector ray_limits; - for (auto & [z_index, layer]: imgui_layers) + std::vector world_to_window; + for (auto & window: imgui_ctx->windows()) { - if (z_index != constants::lobby::zindex_recenter_tip) - ray_limits.push_back(compute_ray_limits(layer.pose)); + if (window.space == xr::spaces::world) + world_to_window.push_back(glm::inverse(glm::translate(window.position) * glm::mat4(glm::mat3_cast(window.orientation)) * glm::scale(glm::vec3(window.size, 1)))); } input->apply(world, @@ -1068,7 +1047,7 @@ void scenes::lobby::render(const XrFrameState & frame_state) not imgui_ctx->is_aim_interaction()[0], hide_right_controller, not imgui_ctx->is_aim_interaction()[1], - ray_limits); + world_to_window); renderer::animate(world, frame_state.predictedDisplayPeriod * 1.0e-9); @@ -1168,7 +1147,9 @@ void scenes::lobby::on_focused() *this, "assets://controllers/" + profile + "/profile.json", layer_controllers, - layer_rays); + layer_rays, + get_action("left_trigger").first, + get_action("right_trigger").first); spdlog::info("Loaded input profile {}", input->id); @@ -1264,7 +1245,17 @@ void scenes::lobby::on_focused() .vp_origin = {0, 1000}, .vp_size = {1500, 300}, .z_index = constants::lobby::zindex_recenter_tip, - }}; + }, + { + // Tooltip + .space = xr::spaces::world, + .size = {0.6, 0.08}, + .vp_origin = {0, 1300}, + .vp_size = {1500, 200}, + .tooltip_viewport = true, + .z_index = constants::lobby::zindex_tooltip, + }, + }; xr::swapchain swapchain_imgui(instance, session, device, swapchain_format, 3000, 1500); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 0985c53e..be01ec06 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -1034,7 +1034,7 @@ void scenes::lobby::gui_debug_node_hierarchy(entt::entity root) primitive.vertex_count, primitive.material_->name, primitive.vertex_shader, - primitive.material_->fragment_shader_name); + primitive.material_->fragment_shader); imgui_ctx->tooltip(tooltip); } diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 5168284b..0222ae67 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -34,6 +34,7 @@ #include "boost/pfr/core.hpp" #include "decoder/shard_accumulator.h" #include "hardware.h" +#include "inplace_vector.hpp" #include "spdlog/spdlog.h" #include "utils/contains.h" #include "utils/named_thread.h" @@ -51,6 +52,7 @@ #endif using namespace wivrn; +using namespace beman::inplace_vector; // clang-format off static const std::unordered_map device_ids = { @@ -428,7 +430,9 @@ void scenes::stream::on_focused() *this, "assets://controllers/" + profile + "/profile.json", layer_controllers, - layer_rays); + layer_rays, + get_action("left_trigger").first, + get_action("right_trigger").first); spdlog::info("Loaded input profile {}", input->id); @@ -472,14 +476,23 @@ void scenes::stream::on_focused() device, swapchain_format, 1800, - 1000); + 1200); - imgui_context::viewport vp{ - .space = xr::spaces::world, - // Position and orientation are set at each frame - .size = {1.2, 0.6666}, - .vp_origin = {0, 0}, - .vp_size = {1800, 1000}, + std::vector vps{ + { + .space = xr::spaces::world, + // Position and orientation are set at each frame + .size = {1.2, 0.6666}, + .vp_origin = {0, 0}, + .vp_size = {1800, 1000}, + }, + { + .space = xr::spaces::world, + .size = {1.2, 0.1333}, + .vp_origin = {0, 1000}, + .vp_size = {1800, 200}, + .tooltip_viewport = true, + }, }; imgui_ctx.emplace(physical_device, @@ -488,7 +501,7 @@ void scenes::stream::on_focused() queue, imgui_inputs, std::move(swapchain_imgui), - std::vector{vp}, + std::move(vps), image_cache); if (application::get_config().enable_stream_gui) @@ -588,8 +601,7 @@ std::array, 3> scenes::stream::c if (decoders.empty()) return {}; std::unique_lock lock(frames_mutex); - thread_local std::vector common_frames; - common_frames.clear(); + inplace_vector common_frames; const bool alpha = decoders[0].latest_frames[0] and decoders[0].latest_frames[0]->view_info.alpha; for (size_t i = 0; i < view_count + alpha; ++i) { @@ -602,7 +614,7 @@ std::array, 3> scenes::stream::c else { // clang-format off - std::erase_if(common_frames, + erase_if(common_frames, [this, i](auto & left) { return std::ranges::none_of( @@ -615,7 +627,7 @@ std::array, 3> scenes::stream::c // clang-format on } } - std::array, view_count + 1> result; + std::array, decoder_count> result; if (not common_frames.empty()) { auto min = std::ranges::min_element(common_frames, @@ -958,9 +970,9 @@ void scenes::stream::render(const XrFrameState & frame_state) vk::SubmitInfo submit_info; submit_info.setCommandBuffers(*command_buffer); - std::vector semaphores; - std::vector semaphore_vals; - std::vector wait_stages; + inplace_vector semaphores; + inplace_vector semaphore_vals; + inplace_vector wait_stages; for (auto b: current_blit_handles) { if (b and b->semaphore) @@ -985,8 +997,6 @@ void scenes::stream::render(const XrFrameState & frame_state) #endif swapchain.release(); - std::vector layer_view(view_count); - if (use_alpha) session.enable_passthrough(system); else @@ -995,6 +1005,7 @@ void scenes::stream::render(const XrFrameState & frame_state) render_start(use_alpha, frame_state.predictedDisplayTime); // Add the layer with the streamed content + std::array layer_view; for (uint32_t view = 0; view < view_count; view++) { layer_view[view] = @@ -1016,7 +1027,7 @@ void scenes::stream::render(const XrFrameState & frame_state) add_projection_layer( XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT, application::space(xr::spaces::world), - std::move(layer_view)); + layer_view); if (composition_layer_color_scale_bias_supported) { @@ -1069,8 +1080,8 @@ void scenes::stream::render(const XrFrameState & frame_state) // Network operations may be blocking, do them once everything was submitted { // Keep a copy of the feedback packets as they can be modified if they're encrypted - std::vector feedbacks; - std::vector packets; + inplace_vector feedbacks; + inplace_vector packets; feedbacks.reserve(current_blit_handles.size()); packets.reserve(current_blit_handles.size()); diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 2a526784..f9b37a58 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -53,6 +53,7 @@ public: private: static const size_t view_count = 2; + static const size_t decoder_count = view_count + 1; struct accumulator_images { @@ -68,7 +69,7 @@ private: // for frames inside accumulator images std::mutex frames_mutex; - std::array, view_count + 1> common_frame(XrTime display_time); + std::array, decoder_count> common_frame(XrTime display_time); std::unique_ptr network_session; std::atomic exiting = false; @@ -86,7 +87,7 @@ private: std::shared_mutex decoder_mutex; std::optional video_stream_description; - std::array decoders; // Locked by decoder_mutex + std::array decoders; // Locked by decoder_mutex std::optional defoveator; @@ -162,7 +163,7 @@ private: void update_gui_position(xr::spaces controller); // Keep a reference to the resources needed to blit the images until vkWaitForFences - std::array, view_count + 1> current_blit_handles; + std::array, decoder_count> current_blit_handles; XrTime running_application_req = 0; thread_safe running_applications; @@ -302,7 +303,7 @@ private: float compact_cpu_time = 0; float compact_gpu_time = 0; - void accumulate_metrics(XrTime predicted_display_time, const std::array, view_count + 1> & blit_handles, const gpu_timestamps & timestamps); + void accumulate_metrics(XrTime predicted_display_time, const std::array, decoder_count> & blit_handles, const gpu_timestamps & timestamps); void gui_performance_metrics(); void gui_compact_view(); void gui_settings(float predicted_display_period); diff --git a/client/scenes/stream_gui.cpp b/client/scenes/stream_gui.cpp index 9b1f0863..78d44f3a 100644 --- a/client/scenes/stream_gui.cpp +++ b/client/scenes/stream_gui.cpp @@ -32,6 +32,8 @@ #include #include #include +#include +#include #include #include #include @@ -729,27 +731,6 @@ void scenes::stream::gui_applications() ImGui::PopStyleVar(3); } -// Return the vector v such that dot(v, x) > 0 iff x is on the side where the composition layer is visible -static glm::vec4 compute_ray_limits(const XrPosef & pose, float margin = 0) -{ - glm::quat q{ - pose.orientation.w, - pose.orientation.x, - pose.orientation.y, - pose.orientation.z, - }; - - glm::vec3 p{ - pose.position.x, - pose.position.y, - pose.position.z, - }; - - glm::vec3 normal = glm::column(glm::mat3_cast(q), 2); - - return glm::vec4(normal, -glm::dot(p, normal) - margin); -} - void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicted_display_period) { if (not(plots_toggle_1 and plots_toggle_2)) @@ -854,7 +835,8 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte const ImGuiStyle & style = ImGui::GetStyle(); imgui_ctx->new_frame(predicted_display_time); - ImVec2 content_size{ImGui::GetMainViewport()->Size - ImVec2{tab_width, 0} - margin_around_window * 2}; + ImVec2 viewport_size(imgui_ctx->layers()[0].vp_size.x, imgui_ctx->layers()[0].vp_size.y); + ImVec2 content_size{viewport_size - ImVec2{tab_width, 0} - margin_around_window * 2}; ImVec2 content_center = margin_around_window + content_size / 2 + ImVec2{tab_width, 0}; bool display_tabs, always_auto_resize; @@ -870,7 +852,7 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte case gui_status::hidden: case gui_status::bitrate_settings: case gui_status::foveation_settings: - ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Size / 2, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowPos(viewport_size / 2, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); always_auto_resize = true; display_tabs = false; break; @@ -885,13 +867,13 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte case gui_status::settings: case gui_status::applications: ImGui::SetNextWindowPos(margin_around_window); - ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size - margin_around_window * 2); + ImGui::SetNextWindowSize(viewport_size - margin_around_window * 2); always_auto_resize = false; display_tabs = true; break; case gui_status::application_launcher: ImGui::SetNextWindowPos(margin_around_window); - ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size - margin_around_window * 2); + ImGui::SetNextWindowSize(viewport_size - margin_around_window * 2); always_auto_resize = false; display_tabs = false; break; @@ -1053,10 +1035,12 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte else recentering_context.reset(); - std::vector ray_limits; - - for (auto [_, layer]: layers) - ray_limits.push_back(compute_ray_limits(layer.pose)); + std::vector world_to_window; + for (auto & window: imgui_ctx->windows()) + { + if (window.space == xr::spaces::world) + world_to_window.push_back(glm::inverse(glm::translate(window.position) * glm::mat4(glm::mat3_cast(window.orientation)) * glm::scale(glm::vec3(window.size, 1)))); + } bool hide_left_controller = false; bool hide_right_controller = false; @@ -1080,7 +1064,7 @@ void scenes::stream::draw_gui(XrTime predicted_display_time, XrDuration predicte hide_left_controller, hide_right_controller, hide_right_controller, - ray_limits); + world_to_window); // Add the layer with the controllers if (composition_layer_depth_test_supported) diff --git a/client/shaders/common.glsl.inc b/client/shaders/common.glsl.inc index 7c4f52bf..a5c07d2d 100644 --- a/client/shaders/common.glsl.inc +++ b/client/shaders/common.glsl.inc @@ -1,7 +1,6 @@ // kate: hl glsl const int nb_views = 2; -const int nb_clipping = 4; const int nb_texcoords = 2; const bool use_pbr = false; @@ -20,7 +19,6 @@ layout(set = 0, binding = 1) uniform mesh_ubo mat4 model; mat4 modelview[nb_views]; mat4 modelviewproj[nb_views]; - vec4 clipping_plane[nb_clipping]; } mesh; layout(set = 0, binding = 2) uniform joints_ubo diff --git a/client/shaders/debug_draw.glsl b/client/shaders/debug_draw.glsl index 1b554151..4a5fbb86 100644 --- a/client/shaders/debug_draw.glsl +++ b/client/shaders/debug_draw.glsl @@ -27,7 +27,6 @@ layout (constant_id = 2) const bool alpha_cutout = false; layout (constant_id = 3) const bool skinning = false; const int nb_views = 2; -const int nb_clipping = 4; layout(set = 0, binding = 0) uniform scene_ubo { @@ -42,7 +41,6 @@ layout(set = 0, binding = 1) uniform mesh_ubo mat4 model; mat4 modelview[nb_views]; mat4 modelviewproj[nb_views]; - vec4 clipping_plane[nb_clipping]; } mesh; layout(set = 0, binding = 2) uniform joints_ubo diff --git a/client/shaders/lit.vert.glsl b/client/shaders/lit.vert.glsl index 7d638bc8..a83cb489 100644 --- a/client/shaders/lit.vert.glsl +++ b/client/shaders/lit.vert.glsl @@ -34,7 +34,6 @@ layout(location = 5) in vec4 in_color; out gl_PerVertex { vec4 gl_Position; - float gl_ClipDistance[nb_clipping]; }; void main() @@ -59,9 +58,4 @@ void main() frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0); light_pos = scene.view[gl_ViewIndex] * scene.light_position; vertex_color = in_color; - - for (int i = 0; i < nb_clipping; i++) - { - gl_ClipDistance[i] = dot(mesh.clipping_plane[i], mesh.model * vec4(in_position, 1.0)); - } } diff --git a/client/shaders/lit_skinned.vert.glsl b/client/shaders/lit_skinned.vert.glsl index 51bd6082..a4ce04e9 100644 --- a/client/shaders/lit_skinned.vert.glsl +++ b/client/shaders/lit_skinned.vert.glsl @@ -36,7 +36,6 @@ layout(location = 7) in vec4 in_weights; out gl_PerVertex { vec4 gl_Position; - float gl_ClipDistance[nb_clipping]; }; void main() @@ -53,8 +52,8 @@ void main() in_weights.z * joints.joint_matrices[int(in_joints.z)] + in_weights.w * joints.joint_matrices[int(in_joints.w)]; - // TODO on CPU? - mat3 mv = inverse(transpose(mat3(mesh.modelview[gl_ViewIndex]))); + + mat3 mv = inverse(transpose(mat3(mesh.modelview[gl_ViewIndex] * skinMatrix))); tangent = vec4(normalize(mv * in_tangent.xyz), in_tangent.w); if (any(isnan(tangent))) // avoid NaNs if no tangent data is provided @@ -62,15 +61,9 @@ void main() normal = normalize(mv * in_normal); - normal = vec3(mesh.modelview[gl_ViewIndex] * skinMatrix * vec4(in_normal, 0.0)); gl_Position = mesh.modelviewproj[gl_ViewIndex] * skinMatrix * vec4(in_position, 1.0); - frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0); + frag_pos = mesh.modelview[gl_ViewIndex] * skinMatrix * vec4(in_position, 1.0); light_pos = scene.view[gl_ViewIndex] * scene.light_position; vertex_color = in_color; - - for(int i = 0; i < nb_clipping; i++) - { - gl_ClipDistance[i] = dot(mesh.clipping_plane[i], mesh.model * vec4(in_position, 1.0)); - } } diff --git a/client/shaders/ray.frag.glsl b/client/shaders/ray.frag.glsl new file mode 100644 index 00000000..5f12e391 --- /dev/null +++ b/client/shaders/ray.frag.glsl @@ -0,0 +1,23 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 + +#extension GL_GOOGLE_include_directive : require + +#include "ray_common.glsl.inc" diff --git a/client/shaders/ray.vert.glsl b/client/shaders/ray.vert.glsl new file mode 100644 index 00000000..8e43d235 --- /dev/null +++ b/client/shaders/ray.vert.glsl @@ -0,0 +1,25 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 +#extension GL_EXT_multiview : require +#extension GL_GOOGLE_include_directive : require + +#define SKINNED 0 + +#include "ray_common.glsl.inc" diff --git a/client/shaders/ray_common.glsl.inc b/client/shaders/ray_common.glsl.inc new file mode 100644 index 00000000..ba1a55de --- /dev/null +++ b/client/shaders/ray_common.glsl.inc @@ -0,0 +1,140 @@ +// kate: hl glsl + +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +const int nb_views = 2; +const int nb_windows = 4; + +layout(set = 0, binding = 1) uniform mesh_ubo +{ + mat4 model; + mat4 modelview[nb_views]; + mat4 modelviewproj[nb_views]; + + // Extra data + mat4 world_to_window[nb_windows]; + float emissive_factor; +} mesh; + +layout(set = 0, binding = 2) uniform joints_ubo +{ + mat4 joint_matrices[32]; +} joints; + +layout(set = 0, binding = 6) uniform sampler2D emissive_texture; + + + +#ifdef VERT_SHADER +// Vertex input +layout(location = 0) in vec3 in_position; +layout(location = 1) in vec2 in_texcoord; + +#if SKINNED +layout(location = 2) in vec4 in_joints; +layout(location = 3) in vec4 in_weights; +#endif + +#endif + +#ifdef FRAG_SHADER +#define VS_TO_FS in +#else +#define VS_TO_FS out +#endif + +// Vertex-to-fragment +layout(location = 0) VS_TO_FS vec2 texcoord; +#ifndef HTC_WORKAROUND +layout(location = 1) VS_TO_FS vec4 position_wrt_window[nb_windows]; +layout(location = 1 + nb_windows) VS_TO_FS vec4 base_wrt_window[nb_windows]; +#endif // HTC_WORKAROUND + +#ifdef VERT_SHADER +out gl_PerVertex +{ + vec4 gl_Position; +#ifdef HTC_WORKAROUND + float gl_ClipDistance[nb_windows]; +#endif +}; + +void main() +{ + texcoord = in_texcoord; + +#if SKINNED + mat4 skinMatrix = + in_weights.x * joints.joint_matrices[int(in_joints.x)] + + in_weights.y * joints.joint_matrices[int(in_joints.y)] + + in_weights.z * joints.joint_matrices[int(in_joints.z)] + + in_weights.w * joints.joint_matrices[int(in_joints.w)]; + + gl_Position = mesh.modelviewproj[gl_ViewIndex] * skinMatrix * vec4(in_position, 1.0); + vec4 world_position = mesh.model * skinMatrix * vec4(in_position, 1.0); + vec4 base_position = mesh.model * skinMatrix * vec4(in_position.xy, 0.0, 1.0); +#else // SKINNED + gl_Position = mesh.modelviewproj[gl_ViewIndex] * vec4(in_position, 1.0); + vec4 world_position = mesh.model * vec4(in_position, 1.0); + vec4 base_position = mesh.model * vec4(in_position.xy, 0.0, 1.0); +#endif // SKINNED + + for(uint i = 0; i < nb_windows; i++) + { +#ifdef HTC_WORKAROUND + vec4 tmp = mesh.world_to_window[i] * world_position; + gl_ClipDistance[i] = tmp.z; +#else // HTC_WORKAROUND + position_wrt_window[i] = mesh.world_to_window[i] * world_position; + base_wrt_window[i] = mesh.world_to_window[i] * base_position; +#endif // HTC_WORKAROUND + } +} +#endif // VERT_SHADER + +#ifdef FRAG_SHADER +// Fragment output +layout(location = 0) out vec4 out_color; + +void main() +{ +#ifdef HTC_WORKAROUND + out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 1.0 / 255.0); +#else // HTC_WORKAROUND + for (uint i = 0; i < nb_windows; i++) + { + if (position_wrt_window[i].w < 0.5) + continue; + + // TODO check NaN + float lambda = -base_wrt_window[i].z / (position_wrt_window[i].z - base_wrt_window[i].z); + + if (lambda < 0 || lambda > 1) + continue; + + vec2 intersection = base_wrt_window[i].xy + lambda * (position_wrt_window[i].xy - base_wrt_window[i].xy); + if (abs(intersection.x) < 0.5 && abs(intersection.y) < 0.5) + discard; + } + + out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 0); +#endif // HTC_WORKAROUND + +} +#endif // FRAG_SHADER diff --git a/client/shaders/ray_htc.frag.glsl b/client/shaders/ray_htc.frag.glsl new file mode 100644 index 00000000..c9dcb242 --- /dev/null +++ b/client/shaders/ray_htc.frag.glsl @@ -0,0 +1,25 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 + +#extension GL_GOOGLE_include_directive : require + +#define HTC_WORKAROUND + +#include "ray_common.glsl.inc" diff --git a/client/shaders/ray_htc.vert.glsl b/client/shaders/ray_htc.vert.glsl new file mode 100644 index 00000000..0dd723dd --- /dev/null +++ b/client/shaders/ray_htc.vert.glsl @@ -0,0 +1,26 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 +#extension GL_EXT_multiview : require +#extension GL_GOOGLE_include_directive : require + +#define SKINNED 0 +#define HTC_WORKAROUND + +#include "ray_common.glsl.inc" diff --git a/client/shaders/ray_skinned.vert.glsl b/client/shaders/ray_skinned.vert.glsl new file mode 100644 index 00000000..55189385 --- /dev/null +++ b/client/shaders/ray_skinned.vert.glsl @@ -0,0 +1,25 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 +#extension GL_EXT_multiview : require +#extension GL_GOOGLE_include_directive : require + +#define SKINNED 1 + +#include "ray_common.glsl.inc" diff --git a/client/shaders/ray_skinned_htc.vert.glsl b/client/shaders/ray_skinned_htc.vert.glsl new file mode 100644 index 00000000..c0405ecb --- /dev/null +++ b/client/shaders/ray_skinned_htc.vert.glsl @@ -0,0 +1,26 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#version 450 +#extension GL_EXT_multiview : require +#extension GL_GOOGLE_include_directive : require + +#define SKINNED 1 +#define HTC_WORKAROUND + +#include "ray_common.glsl.inc" diff --git a/client/vk/shader.cpp b/client/vk/shader.cpp index 2fa2df98..e610c938 100644 --- a/client/vk/shader.cpp +++ b/client/vk/shader.cpp @@ -18,7 +18,6 @@ */ #include "shader.h" -#include "utils/cache.h" #include "wivrn_shaders.h" #include #include @@ -104,8 +103,3 @@ std::shared_ptr shader_loader::operator()(const std::string & name) return (*this)(shaders.at(name)); } - -std::shared_ptr load_shader(vk::raii::Device & device, const std::string & name) -{ - return shader_loader{device}(name); -} diff --git a/client/vk/shader.h b/client/vk/shader.h index d0da17d6..079e89de 100644 --- a/client/vk/shader.h +++ b/client/vk/shader.h @@ -64,4 +64,7 @@ struct shader_loader std::shared_ptr operator()(const std::string & name); }; -std::shared_ptr load_shader(vk::raii::Device & device, const std::string & name); +inline std::shared_ptr load_shader(vk::raii::Device & device, const std::string & name) +{ + return shader_loader{device}(name); +} diff --git a/cmake/CompileGLSL.cmake b/cmake/CompileGLSL.cmake index 003e00f1..f53c110a 100644 --- a/cmake/CompileGLSL.cmake +++ b/cmake/CompileGLSL.cmake @@ -13,13 +13,20 @@ function(compile_glsl_aux shader_stage shader_name glsl_filename output target_e }}, ") + if (WIVRN_DEBUG_SHADERS) + set(SHADER_FLAGS -gVS) + else() + set(SHADER_FLAGS ) + endif() + add_custom_command( OUTPUT "${SPV_FILE}-nopt" - COMMAND Vulkan::glslangValidator -V --target-env ${target_env} -S ${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} -o "${SPV_FILE}-nopt" --depfile "${SPV_FILE}.d" + COMMAND Vulkan::glslangValidator -V --target-env ${target_env} -S ${shader_stage} -D${shader_stage_upper}_SHADER ${in_file} ${SHADER_FLAGS} -o "${SPV_FILE}-nopt" --depfile "${SPV_FILE}.d" DEPENDS "${glsl_filename}" DEPFILE "${SPV_FILE}.d" VERBATIM ) + if (WIVRN_OPTIMIZE_SHADERS) add_custom_command( OUTPUT "${SPV_FILE}-opt" diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 7a86f39f..e4e85ae5 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -1,7 +1,7 @@ if (WIVRN_USE_SYSTEM_BOOST) add_library(Boost::pfr ALIAS Boost::headers) else() - set(BOOST_INCLUDE_LIBRARIES locale url pfr) + set(BOOST_INCLUDE_LIBRARIES locale url pfr iostreams) FetchContent_MakeAvailable(boost) endif() @@ -40,14 +40,17 @@ add_library(wivrn-common STATIC EXCLUDE_FROM_ALL if (WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_SERVER) add_library(wivrn-common-server STATIC EXCLUDE_FROM_ALL + application.cpp utils/flatpak.cpp - utils/xdg_icon_lookup.cpp - utils/steam_app_info.cpp utils/load_icon.cpp utils/ini.cpp - application.cpp + utils/steam_info.cpp + utils/vdf.cpp + utils/xdg_icon_lookup.cpp ) - target_link_libraries(wivrn-common-server PRIVATE nlohmann_json::nlohmann_json PNG::PNG PkgConfig::librsvg-2.0 LibArchive::LibArchive PUBLIC wivrn-common-base) + target_link_libraries(wivrn-common-server + PRIVATE nlohmann_json::nlohmann_json PNG::PNG PkgConfig::librsvg-2.0 LibArchive::LibArchive Boost::iostreams + PUBLIC wivrn-common-base) if (WIVRN_BUILD_TEST) add_executable(list-apps @@ -55,6 +58,10 @@ if (WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_SERVER) ) target_link_libraries(list-apps wivrn-common-server) + + add_executable(vdf utils/vdf.cpp) + target_compile_definitions(vdf PRIVATE WIVRN_BUILD_TEST) + target_link_libraries(vdf Boost::iostreams) endif() endif() diff --git a/common/application.cpp b/common/application.cpp index 49c506a6..065c7a0f 100644 --- a/common/application.cpp +++ b/common/application.cpp @@ -20,13 +20,12 @@ #include "application.h" #include "utils/flatpak.h" -#include "utils/steam_app_info.h" +#include "utils/steam_info.h" #include "utils/xdg_base_directory.h" #include "utils/xdg_icon_lookup.h" #include #include -#include #include namespace wivrn @@ -42,168 +41,6 @@ std::string read_file(const std::filesystem::path & path) return {begin, end}; } -std::filesystem::path home() -{ - auto home = std::getenv("HOME"); - return home ? home : ""; -} - -std::pair> find_steam() -{ - auto h = home(); - // Flatpak Steam - if (std::filesystem::exists(h / ".var/app/com.valvesoftware.Steam/.steam/steam")) - return {"flatpak run com.valvesoftware.Steam", h / ".var/app/com.valvesoftware.Steam/.steam/steam"}; - - // Debian Steam (accessed from flatpak) - if (std::filesystem::exists(h / ".steam/debian-installation")) - return {"steam", h / ".steam/debian-installation"}; - - // system Steam - if (std::filesystem::exists(xdg_data_home() / "Steam")) - return {"steam", xdg_data_home() / "Steam"}; - - // system Steam (accessed from flatpak) - if (std::filesystem::exists(h / ".local/share/Steam")) - return {"steam", h / ".local/share/Steam"}; - - return {}; -} - -std::string read_vr_manifest(const std::filesystem::path & root) -{ - return read_file(root / "config/steamapps.vrmanifest"); -} - -std::unordered_map safe_read_steam_icons(const std::filesystem::path & root) -{ - try - { - return read_steam_icons(root / "appcache/appinfo.vdf"); - } - catch (...) - {} - - return {}; -} - -std::optional find_steam_icon(const std::filesystem::path & root, int app_id, const std::unordered_map & info) -{ - auto icon = info.find(app_id); - if (icon == info.end()) - return std::nullopt; - - try - { - auto icon_path = root / "steam/games" / (icon->second.clienticon + ".ico"); - - if (std::filesystem::exists(icon_path)) - return icon_path; - } - catch (...) - { - } - - try - { - auto icon_path = root / "steam/games" / (icon->second.linuxclienticon + ".zip"); - if (std::filesystem::exists(icon_path)) - return icon_path; - } - catch (...) - { - } - - return std::nullopt; -} - -void read_steam_vr_apps(std::unordered_map & res) -{ - auto [command, root] = find_steam(); - if (not root) - return; - - auto manifest = read_vr_manifest(*root); - auto info = safe_read_steam_icons(*root); - - if (manifest.empty()) - return; - nlohmann::json json = nlohmann::json::parse(manifest); - - for (auto & i: json["applications"]) - { - try - { - application app; - - if (i["launch_type"] == "url") - app.exec = command + " " + (std::string)i["url"]; - else - continue; - - std::string app_key = i["app_key"]; - for (auto [locale, items]: i["strings"].items()) - { - if (auto it = items.find("name"); it != items.end()) - app.name[locale] = *it; - } - - if (not app.name.contains("")) - { - auto it = app.name.find("en_us"); - if (it == app.name.end()) - it = app.name.begin(); - if (it != app.name.end()) - app.name[""] = it->second; - } - - try - { - const char prefix[] = "steam.app."; - if (app_key.starts_with(prefix)) - { - uint32_t app_id = stoll(app_key.substr(strlen(prefix))); - app.icon_path = find_steam_icon(*root, app_id, info); - } - } - catch (...) - { - } - - if (not app.exec.empty()) - res[app_key] = std::move(app); - } - catch (std::exception & e) - { - std::cerr << "Failed to parse Steam VR manifest: " << e.what() << std::endl; - } - } - - for (auto const & entry: std::filesystem::directory_iterator{*root / "userdata"}) - { - auto shortcuts_vdf = entry.path() / "config/shortcuts.vdf"; - if (std::filesystem::exists(shortcuts_vdf)) - { - try - { - for (auto && item: read_steam_shortcuts(shortcuts_vdf)) - { - res[std::to_string(item.appid)] = { - .name = {{"", std::move(item.name)}}, - // ¯\_(ツ)_/¯ - .exec = command + " steam://rungameid/" + std::to_string((uint64_t(item.appid) << 32) + 0x2000000), - .icon_path = std::move(item.icon), - }; - } - } - catch (std::exception & e) - { - std::cerr << "Failed to parse Steam shortcuts file " << shortcuts_vdf << ": " << e.what() << std::endl; - } - } - } -} - std::string unescape(std::string_view in) { std::string out; @@ -391,8 +228,19 @@ std::unordered_map list_applications() { std::unordered_map res; - read_steam_vr_apps(res); - + for (auto & steam: steam::find_installations()) + { + auto cmd = steam.get_steam_command() + " "; + for (auto && app: steam.list_applications()) + { + res.emplace(std::to_string(app.appid), + application{ + .name = std::move(app.name), + .exec = cmd + app.url, + .icon_path = steam.get_icon(app.appid), + }); + } + } do_data_dir(xdg_data_home(), res); for (auto && dir: xdg_data_dirs()) diff --git a/common/utils/steam_app_info.cpp b/common/utils/steam_app_info.cpp deleted file mode 100644 index df1a68ed..00000000 --- a/common/utils/steam_app_info.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/* - * WiVRn VR streaming - * Copyright (C) 2025 Guillaume Meunier - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "steam_app_info.h" -#include -#include -#include -#include - -namespace -{ - -class binary_reader -{ - std::ifstream in; - -public: - binary_reader(std::ifstream && in) : in{std::move(in)} {} - - void discard(size_t bytes) - { - in.seekg(bytes, std::ios_base::cur); - } - - template - T read(); - - template - requires std::is_integral_v - T read() - { - T res; - in.read((char *)&res, sizeof(T)); - if (not in) - throw std::runtime_error{"File truncated"}; - - static_assert(std::endian::native == std::endian::big or std::endian::native == std::endian::little); - - if constexpr (std::endian::native == std::endian::big) - return std::byteswap(res); - else - return res; - } - - std::vector string_table(); - - auto tellg() - { - return in.tellg(); - } - void seekg(size_t pos) - { - in.seekg(pos); - } -}; - -template <> -std::string binary_reader::read() -{ - std::string res; - std::getline(in, res, '\0'); - if (not in) - throw std::runtime_error{"File truncated"}; - return res; -} - -std::vector binary_reader::string_table() -{ - std::vector res; - size_t string_offset = read(); - auto pos = in.tellg(); - - in.seekg(string_offset); - auto count = read(); - res.reserve(count); - for (size_t i = 0; i < count; ++i) - res.emplace_back(read()); - in.seekg(pos); - return res; -} - -template -void read_dict(binary_reader & in, T & visitor, const std::vector * string_table = nullptr) -{ - while (true) - { - auto type = in.read(); - if (type == 8) - { - visitor.end_dict(); - return; - } - - // Key - const std::string & key = string_table ? string_table->at(in.read()) : in.read(); - - // Value - switch (type) - { - case 0: // Dictionary - visitor.begin_dict(key); - read_dict(in, visitor, string_table); - break; - case 1: // UTF-8 string - visitor.on_string(key, in.read()); - break; - case 2: // uint32_t - visitor.on_uint32_t(key, in.read()); - break; - // case 3: // float - default: - throw std::runtime_error{"Unknown object type " + std::to_string(type)}; - } - } -} -} // namespace - -std::unordered_map wivrn::read_steam_icons(std::filesystem::path path) -{ - binary_reader in{std::ifstream{path}}; - - uint32_t magic = in.read(); - if ((magic & 0xff'ff'ff'00) != 0x07'56'44'00) - throw std::runtime_error{"Wrong magic number"}; - - auto universe = in.read(); - - int version = magic & 0xff; - - std::vector string_table; - std::vector * string_table_ptr = nullptr; - if (version >= 41) - { - string_table = in.string_table(); - string_table_ptr = &string_table; - } - - std::unordered_map res; - - struct V - { - wivrn::steam_icon current{}; - - void begin_dict(const std::string & key) - { - } - void end_dict() - { - } - void on_string(const std::string & key, std::string && val) - { - if (strcasecmp(key.c_str(), "clienticon") == 0) - current.clienticon = std::move(val); - else if (strcasecmp(key.c_str(), "linuxclienticon") == 0) - current.linuxclienticon = std::move(val); - } - void on_uint32_t(const std::string & key, uint32_t val) - { - } - }; - - while (true) - { - // See https://github.com/SteamDatabase/SteamAppInfo/blob/master/README.md#app-entry-repeated - auto app_id = in.read(); - if (app_id == 0) - break; - - size_t size_data = in.read(); - size_t pos = in.tellg(); - in.discard( - 4 // info_state - + 4 // last_updated - + 8 // pics_token - + 20 // SHA1 of the app info - + 4 // change number - + 20 // SHA1 of the bin data - + 4 // checksum - + 1 // type - ); - try - { - V v; - read_dict(in, v, string_table_ptr); - if (not(v.current.clienticon.empty() and v.current.linuxclienticon.empty())) - res.emplace(app_id, std::move(v.current)); - } - catch (...) - { - // Ignore errors - } - in.seekg(pos + size_data); - } - - return res; -} - -std::vector wivrn::read_steam_shortcuts(std::filesystem::path path) -{ - binary_reader in{std::ifstream{path}}; - auto type = in.read(); - auto name = in.read(); - - if (type != 0 or name != "shortcuts") - throw std::runtime_error{"Invalid type for shortcuts file"}; - - std::vector res; - struct V - { - std::vector & items; - - int depth = 0; - wivrn::steam_shortcut current{}; - bool VR = false; - - void begin_dict(const std::string & key) - { - ++depth; - if (depth == 1) - { - current = decltype(current){}; - VR = false; - } - } - void end_dict() - { - --depth; - if (depth == 0) - { - if (VR) - items.push_back(std::move(current)); - } - } - void on_string(const std::string & key, std::string && val) - { - if (depth == 1) - { - if (strcasecmp(key.c_str(), "AppName") == 0) - current.name = std::move(val); - else if (strcasecmp(key.c_str(), "icon") == 0 and not val.empty()) - current.icon = std::move(val); - } - } - void on_uint32_t(const std::string & key, uint32_t val) - { - if (depth == 1) - { - if (strcasecmp(key.c_str(), "appid") == 0) - current.appid = val; - else if (strcasecmp(key.c_str(), "OpenVR") == 0) - VR = val; - } - } - } v{res}; - - read_dict(in, v); - - return res; -} diff --git a/common/utils/steam_info.cpp b/common/utils/steam_info.cpp new file mode 100644 index 00000000..808db459 --- /dev/null +++ b/common/utils/steam_info.cpp @@ -0,0 +1,491 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "steam_info.h" +#include "vdf.h" +#include "xdg_base_directory.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +class binary_reader +{ + std::ifstream in; + +public: + binary_reader(std::ifstream && in) : in{std::move(in)} {} + + void discard(size_t bytes) + { + in.seekg(bytes, std::ios_base::cur); + } + + template + T read(); + + template + requires std::is_integral_v + T read() + { + T res; + in.read((char *)&res, sizeof(T)); + if (not in) + throw std::runtime_error{"File truncated"}; + + static_assert(std::endian::native == std::endian::big or std::endian::native == std::endian::little); + + if constexpr (std::endian::native == std::endian::big) + return std::byteswap(res); + else + return res; + } + + std::vector string_table(); + + auto tellg() + { + return in.tellg(); + } + void seekg(size_t pos) + { + in.seekg(pos); + } +}; + +template <> +std::string binary_reader::read() +{ + std::string res; + std::getline(in, res, '\0'); + if (not in) + throw std::runtime_error{"File truncated"}; + return res; +} + +std::vector binary_reader::string_table() +{ + std::vector res; + size_t string_offset = read(); + auto pos = in.tellg(); + + in.seekg(string_offset); + auto count = read(); + res.reserve(count); + for (size_t i = 0; i < count; ++i) + res.emplace_back(read()); + in.seekg(pos); + return res; +} + +template +void read_dict(binary_reader & in, T & visitor, const std::vector * string_table = nullptr) +{ + while (true) + { + auto type = in.read(); + if (type == 8) + { + visitor.end_dict(); + return; + } + + // Key + const std::string & key = string_table ? string_table->at(in.read()) : in.read(); + + // Value + switch (type) + { + case 0: // Dictionary + visitor.begin_dict(key); + read_dict(in, visitor, string_table); + break; + case 1: // UTF-8 string + visitor.on_string(key, in.read()); + break; + case 2: // uint32_t + visitor.on_uint32_t(key, in.read()); + break; + // case 3: // float + default: + throw std::runtime_error{"Unknown object type " + std::to_string(type)}; + } + } +} + +std::filesystem::path home() +{ + auto home = std::getenv("HOME"); + return home ? home : ""; +} + +std::optional guess_steam_userid(const std::filesystem::path & root) +{ + auto localconfig = root / "config/loginusers.vdf"; + if (not std::filesystem::exists(localconfig)) + return {}; + + try + { + wivrn::vdf::root loginusers(localconfig); + if (loginusers.key != "users") + return {}; + + std::optional res; + for (const auto & [userid, entries]: std::get>(loginusers.value)) + { + uint64_t v; + if (std::from_chars(userid.data.begin(), userid.data.end(), v).ec != std::errc{}) + continue; + res = v; // truncate to 32 bits + for (const auto & [key, value]: std::get>(entries)) + { + if (key == "MostRecent" and std::get(value) == "1") + return res; + } + } + return res; + } + catch (std::exception & e) + { + return {}; + } +} + +} // namespace + +void read_steam_icons(std::filesystem::path path, std::unordered_map & icons) +{ + binary_reader in{std::ifstream{path}}; + + uint32_t magic = in.read(); + if ((magic & 0xff'ff'ff'00) != 0x07'56'44'00) + throw std::runtime_error{"Wrong magic number"}; + + auto universe = in.read(); + + int version = magic & 0xff; + + std::vector string_table; + std::vector * string_table_ptr = nullptr; + if (version >= 41) + { + string_table = in.string_table(); + string_table_ptr = &string_table; + } + + struct V + { + wivrn::steam::icon current{}; + + void begin_dict(const std::string & key) + { + } + void end_dict() + { + } + void on_string(const std::string & key, std::string && val) + { + if (strcasecmp(key.c_str(), "clienticon") == 0) + current.clienticon = std::move(val); + else if (strcasecmp(key.c_str(), "linuxclienticon") == 0) + current.linuxclienticon = std::move(val); + } + void on_uint32_t(const std::string & key, uint32_t val) + { + } + }; + + while (true) + { + // See https://github.com/SteamDatabase/SteamAppInfo/blob/master/README.md#app-entry-repeated + auto app_id = in.read(); + if (app_id == 0) + break; + + size_t size_data = in.read(); + size_t pos = in.tellg(); + in.discard( + 4 // info_state + + 4 // last_updated + + 8 // pics_token + + 20 // SHA1 of the app info + + 4 // change number + + 20 // SHA1 of the bin data + + 4 // checksum + + 1 // type + ); + try + { + V v; + read_dict(in, v, string_table_ptr); + if (not(v.current.clienticon.empty() and v.current.linuxclienticon.empty())) + icons.emplace(app_id, std::move(v.current)); + } + catch (...) + { + // Ignore errors + } + in.seekg(pos + size_data); + } +} + +void read_steam_shortcuts( + const std::filesystem::path & path, + std::vector & apps, + std::unordered_map & icons) +{ + if (not std::filesystem::exists(path)) + return; + binary_reader in{std::ifstream{path}}; + auto type = in.read(); + auto name = in.read(); + + if (type != 0 or name != "shortcuts") + throw std::runtime_error{"Invalid type for shortcuts file"}; + + std::vector res; + struct V + { + std::vector & apps; + std::unordered_map & icons; + + int depth = 0; + wivrn::steam::application current{}; + std::filesystem::path icon; + bool VR = false; + + void begin_dict(const std::string & key) + { + ++depth; + if (depth == 1) + { + current = decltype(current){}; + icon.clear(); + VR = false; + } + } + void end_dict() + { + --depth; + if (depth == 0) + { + if (VR) + { + if (not icon.empty()) + icons[current.appid] = std::move(icon); + // ¯\_(ツ)_/¯ + current.appid = (current.appid << 32) | 0x02000000; + current.url = std::format("steam://rungameid/{}", current.appid); + apps.push_back(std::move(current)); + } + } + } + void on_string(const std::string & key, std::string && val) + { + if (depth == 1) + { + if (strcasecmp(key.c_str(), "AppName") == 0) + current.name[""] = std::move(val); + else if (strcasecmp(key.c_str(), "icon") == 0 and not val.empty()) + icon = std::move(val); + } + } + void on_uint32_t(const std::string & key, uint32_t val) + { + if (depth == 1) + { + if (strcasecmp(key.c_str(), "appid") == 0) + current.appid = val; + else if (strcasecmp(key.c_str(), "OpenVR") == 0) + VR = val; + } + } + } v{apps, icons}; + + read_dict(in, v); +} + +wivrn::steam::steam(std::filesystem::path root, bool flatpak) : + root(std::move(root)), + flatpak(flatpak), + default_userid(guess_steam_userid(this->root)) +{ +} + +std::vector wivrn::steam::find_installations() +{ + std::vector res; + auto h = home(); + + auto try_construct = [&res](std::filesystem::path root, bool flatpak = false) { + try + { + if (std::filesystem::exists(root)) + { + res.push_back(wivrn::steam(std::move(root), flatpak)); + return true; + } + } + catch (std::exception &) + { + } + return false; + }; + + // Flatpak Steam + try_construct(h / ".var/app/com.valvesoftware.Steam/.steam/steam", true); + + // Debian Steam (accessed from flatpak) + try_construct(h / ".steam/debian-installation") + // system Steam + or try_construct(xdg_data_home() / "Steam") + // system Steam (accessed from flatpak) + or try_construct(h / ".local/share/Steam"); + + return res; +} + +std::vector wivrn::steam::list_applications() +{ + std::vector res; + // Steam games, from VR manifest + { + std::ifstream manifest(root / "config/steamapps.vrmanifest"); + nlohmann::json json = nlohmann::json::parse(manifest); + for (auto & i: json["applications"]) + { + try + { + // Steam games have an url launch + // shortcuts may be in this file, or may not... + if (i["launch_type"] != "url") + continue; + + std::string app_key = i["app_key"]; + const char prefix[] = "steam.app."; + if (not app_key.starts_with(prefix)) + continue; + + application app{ + .appid = stoul(app_key.substr(strlen(prefix))), + .url = i["url"], + }; + + for (auto [locale, items]: i["strings"].items()) + { + if (auto it = items.find("name"); it != items.end()) + app.name[locale] = *it; + } + + if (not app.name.contains("")) + { + auto it = app.name.find("en_us"); + if (it == app.name.end()) + it = app.name.begin(); + if (it != app.name.end()) + app.name[""] = it->second; + else + continue; // skip unnamed app + } + res.push_back(std::move(app)); + } + catch (std::exception & e) + { + std::cerr << "Failed to parse Steam VR manifest: " << e.what() << std::endl; + } + } + } + + // Shortcuts + if (default_userid) + { + try + { + read_steam_shortcuts(root / "userdata" / std::to_string(*default_userid) / "config/shortcuts.vdf", res, shortcut_icons); + } + catch (std::exception & e) + { + } + } + else + { + // Is it a good idea to just iterate over all users? + for (auto const & entry: std::filesystem::directory_iterator{root / "userdata"}) + try + { + read_steam_shortcuts(entry.path() / "config/shortcuts.vdf", res, shortcut_icons); + } + catch (std::exception & e) + { + } + } + + return res; +} + +std::optional wivrn::steam::get_icon(uint64_t appid) +{ + if (appid & 0x02000000) + { + // Shortcut + auto it = shortcut_icons.find(appid >> 32); + if (it != shortcut_icons.end()) + return it->second; + return {}; + } + + if (not icons) + { + icons.emplace(); + try + { + read_steam_icons(root / "appcache/appinfo.vdf", *icons); + } + catch (...) + {} + } + auto it = icons->find(appid); + if (it == icons->end()) + return {}; + + auto icon_path = root / "steam/games" / (it->second.clienticon + ".ico"); + + if (std::filesystem::exists(icon_path)) + return icon_path; + + icon_path = root / "steam/games" / (it->second.linuxclienticon + ".zip"); + if (std::filesystem::exists(icon_path)) + return icon_path; + + return {}; +} + +std::string wivrn::steam::get_steam_command() const +{ + if (flatpak) + return "flatpak run com.valvesoftware.Steam"; + return "steam"; +} diff --git a/common/utils/steam_info.h b/common/utils/steam_info.h new file mode 100644 index 00000000..0b20c570 --- /dev/null +++ b/common/utils/steam_info.h @@ -0,0 +1,69 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2025 Guillaume Meunier + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +namespace wivrn +{ + +class steam +{ +public: + struct application + { + uint64_t appid; + // localised names, with empty locale for default + std::unordered_map name; + std::string url; + }; + struct icon + { + std::string clienticon; + std::string linuxclienticon; + }; + +private: + std::filesystem::path root; + bool flatpak; + std::optional default_userid; + std::optional> icons; + std::unordered_map shortcut_icons; + + steam(std::filesystem::path root, bool flatpak); + +public: + static std::vector find_installations(); + + std::vector list_applications(); + std::optional get_icon(uint64_t app_id); + std::string get_steam_command() const; +}; + +struct steam_shortcut +{ + uint32_t appid; + std::string name; + std::optional icon; +}; + +} // namespace wivrn diff --git a/common/utils/vdf.cpp b/common/utils/vdf.cpp new file mode 100644 index 00000000..b23c60d2 --- /dev/null +++ b/common/utils/vdf.cpp @@ -0,0 +1,191 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "vdf.h" + +#include +#include + +namespace +{ + +void consume_whitespace(const char *& pos, const char * end) +{ + for (; pos != end; ++pos) + { + if (not std::isspace(*pos)) + return; + } + throw std::runtime_error("malformed VDF file"); +} + +wivrn::vdf::string read_string(const char *& pos, const char * end) +{ + consume_whitespace(pos, end); + + const bool quoted = *pos == '"'; + if (quoted) + ++pos; + + const char * begin = pos; + + for (; pos != end; ++pos) + { + if (*pos == '\\') + { + ++pos; + if (pos == end) + break; + continue; + } + + if (quoted) + { + if (*pos == '"') + return {std::string_view(begin, pos++)}; + } + else + { + if (std::isspace(*pos) or *pos == '{' or *pos == '}') + return {std::string_view(begin, pos)}; + } + } + throw std::runtime_error("malformed string in VDF file"); +} + +std::variant> read_value(const char *& pos, const char * end); + +wivrn::vdf::keyvalue read_key_value(const char *& pos, const char * end) +{ + return wivrn::vdf::keyvalue{ + .key = read_string(pos, end), + .value = read_value(pos, end), + }; +} + +std::vector read_dict(const char *& pos, const char * end) +{ + consume_whitespace(pos, end); + if (*pos != '{') + throw std::runtime_error("malformed VDF file"); + ++pos; + + std::vector res; + while (true) + { + consume_whitespace(pos, end); + if (*pos == '}') + { + ++pos; + return res; + } + res.push_back(read_key_value(pos, end)); + } + + throw std::runtime_error("malformed dict in VDF file"); +} + +std::variant> read_value(const char *& pos, const char * end) +{ + consume_whitespace(pos, end); + + if (*pos == '{') + return read_dict(pos, end); + else + return read_string(pos, end); +} + +} // namespace + +bool wivrn::vdf::string::operator==(const char * b) const +{ + const char * a = data.begin(); + for (; a != data.end(); ++a, ++b) + { + if (*b == '\0') + return false; + if (*a == '\\') + { + ++a; + // This should be taken care of by the parser + assert(a != data.end()); + } + + if (std::tolower(*b) != std::tolower(*a)) + return false; + } + return *b == '\0'; +} + +wivrn::vdf::root::root(const std::filesystem::path & file) +{ + boost::iostreams::mapped_file in{file}; + opaque = in; + + const char * pos = in.begin(); + key = read_string(pos, in.end()); + value = read_value(pos, in.end()); +} + +void dump(const wivrn::vdf::keyvalue & kv, int depth) +{ + for (int i = 0; i < depth; ++i) + std::cout << '\t'; + std::cout << '"' << kv.key.data << "\": "; + struct V + { + int depth; + void operator()(const wivrn::vdf::string & s) + { + std::cout << '"' << s.data << '"'; + } + void operator()(const std::vector & kv) + { + std::cout << '{' << std::endl; + for (const auto & i: kv) + { + dump(i, depth + 1); + if (&i != &kv.back()) + std::cout << ','; + std::cout << std::endl; + } + for (int i = 0; i < depth; ++i) + std::cout << '\t'; + std::cout << "}"; + } + }; + std::visit(V{depth}, kv.value); +} + +#ifdef WIVRN_BUILD_TEST +void dump(const wivrn::vdf::root & kv) +{ + std::cout << '{'; + dump(kv, 0); + std::cout << '}'; +} + +int main(int argc, char ** argv) +{ + for (int i = 1; i < argc; ++i) + { + wivrn::vdf::root doc{argv[i]}; + dump(doc); + } +} +#endif diff --git a/common/utils/steam_app_info.h b/common/utils/vdf.h similarity index 63% rename from common/utils/steam_app_info.h rename to common/utils/vdf.h index 640dcc93..3be53223 100644 --- a/common/utils/steam_app_info.h +++ b/common/utils/vdf.h @@ -1,6 +1,6 @@ /* * WiVRn VR streaming - * Copyright (C) 2025 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,28 +18,37 @@ #pragma once +#include #include -#include -#include +#include +#include #include namespace wivrn { -struct steam_icon +namespace vdf { - std::string clienticon; - std::string linuxclienticon; +struct string +{ + std::string_view data; + + bool operator==(const char *) const; }; -struct steam_shortcut +struct keyvalue { - uint32_t appid; - std::string name; - std::optional icon; + string key; + std::variant> value; }; -std::unordered_map read_steam_icons(std::filesystem::path path); -std::vector read_steam_shortcuts(std::filesystem::path path); +struct root : public keyvalue +{ + root(const std::filesystem::path &); + +private: + std::any opaque; +}; +} // namespace vdf } // namespace wivrn diff --git a/dashboard/io.github.wivrn.wivrn.metainfo.xml b/dashboard/io.github.wivrn.wivrn.metainfo.xml index 60316677..d8ba8f62 100644 --- a/dashboard/io.github.wivrn.wivrn.metainfo.xml +++ b/dashboard/io.github.wivrn.wivrn.metainfo.xml @@ -28,7 +28,7 @@
  • Samsung Galaxy XR
  • -

    For desktop streaming, check out wlx-overlay-s.

    +

    For desktop streaming, check out WayVR.

    Guillaume Meunier, Patrick Nicolas et al diff --git a/external/inplace_vector.hpp b/external/inplace_vector.hpp new file mode 100644 index 00000000..82209b4e --- /dev/null +++ b/external/inplace_vector.hpp @@ -0,0 +1,956 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef BEMAN_INPLACE_VECTOR_INPLACE_VECTOR_HPP +#define BEMAN_INPLACE_VECTOR_INPLACE_VECTOR_HPP + +#if !defined(__has_include) || __has_include() +#include +#endif + +#include // for rotate... +#include +#include +#include // for lots... +#include // for size_t +#include // for fixed-width integer types +#include // for reverse_iterator and iterator traits +#include // for numeric_limits +#include // for destroy +#include +#include // for aligned_storage and all meta-functions + +// Artifact from previous implementation, can be used as hints for optimizer +#define IV_EXPECT(EXPR) + +#ifndef BEMAN_IV_THROW_OR_ABORT + +#ifndef BEMAN_INPLACE_VECTOR_NO_EXCEPTIONS +#define BEMAN_INPLACE_VECTOR_NO_EXCEPTIONS() 0 +#endif + +#if BEMAN_INPLACE_VECTOR_NO_EXCEPTIONS() +#include // for abort +#define BEMAN_IV_THROW_OR_ABORT(x) abort() +#else +#include // for length_error +#define BEMAN_IV_THROW_OR_ABORT(x) throw x +#endif +#endif + +// Private utilities +namespace beman::inplace_vector::details { + +struct from_range_t {}; +inline constexpr from_range_t from_range; + +// clang-format off +// Smallest unsigned integer that can represent values in [0, N]. +template +using smallest_size_t += std::conditional_t<(N < std::numeric_limits::max()), uint8_t, + std::conditional_t<(N < std::numeric_limits::max()), uint16_t, + std::conditional_t<(N < std::numeric_limits::max()), uint32_t, + std::conditional_t<(N < std::numeric_limits::max()), uint64_t, + size_t>>>>; +// clang-format on + +// Index a random-access and sized range doing bound checks in debug builds +template +static constexpr decltype(auto) index(Rng &&rng, Index i) noexcept + requires(std::ranges::sized_range) +{ + IV_EXPECT(static_cast(i) < std::ranges::size(rng)); + return std::begin(std::forward(rng))[std::forward(i)]; +} + +// http://eel.is/c++draft/container.requirements.general#container.intro.reqmts-2 +template +concept container_compatible_range = + std::ranges::input_range && + std::convertible_to, T>; + +template +concept satisfy_triviality = std::is_trivially_copyable_v && + std::is_trivially_default_constructible_v && + std::is_trivially_destructible_v; + +template +concept satisfy_constexpr = N == 0 || satisfy_triviality; + +template +concept lessthan_comparable = requires(const T &a, const T &b) { + { a < b } -> std::convertible_to; +}; + +// Types implementing the `inplace_vector`'s storage +namespace storage { + +// Storage for zero elements. +template struct zero_sized { +protected: + using size_type = uint8_t; + static constexpr T *storage_data() noexcept { return nullptr; } + static constexpr size_type storage_size() noexcept { return 0; } + static constexpr void + unsafe_set_size([[maybe_unused]] size_t new_size) noexcept { + IV_EXPECT(new_size == 0 && + "tried to change size of empty storage to non-zero value"); + } + +public: + constexpr zero_sized() = default; + constexpr zero_sized(zero_sized const &) = default; + constexpr zero_sized &operator=(zero_sized const &) = default; + constexpr zero_sized(zero_sized &&) = default; + constexpr zero_sized &operator=(zero_sized &&) = default; + constexpr ~zero_sized() = default; +}; + +// Storage for trivial types. +template struct trivial { + static_assert(satisfy_triviality, + "storage::trivial requires Trivial"); + static_assert(N != size_t{0}, "N == 0, use zero_sized"); + +protected: + using size_type = smallest_size_t; + +private: + using array_based_storage = std::array, N>; + alignas(alignof(T)) array_based_storage storage_data_{}; + size_type storage_size_ = 0; + +protected: + constexpr const T *storage_data() const noexcept { + return storage_data_.data(); + } + constexpr auto storage_data() noexcept { return storage_data_.data(); } + constexpr size_type storage_size() const noexcept { return storage_size_; } + constexpr void unsafe_set_size(size_t new_size) noexcept { + IV_EXPECT(size_type(new_size) <= N && "new_size out-of-bounds [0, N]"); + storage_size_ = size_type(new_size); + } + +public: + constexpr trivial() noexcept = default; + constexpr trivial(trivial const &) noexcept = default; + constexpr trivial &operator=(trivial const &) noexcept = default; + constexpr trivial(trivial &&) noexcept = default; + constexpr trivial &operator=(trivial &&) noexcept = default; + constexpr ~trivial() = default; +}; + +// This is the base storage for non-trivial types. +// In this storage solution, elements are stored in type-erased byte storage, +// thus, reinterpret_cast must be used, +// which makes inplace_vector of non-trivial types non-constexpr-friendly. +// +// Note: This is not used if trivial union is supported. +template struct raw_byte_based_storage { + alignas(T) std::byte _d[sizeof(T) * N]; + T *storage_data(size_t i) noexcept { + IV_EXPECT(i < N); + return reinterpret_cast(_d) + i; + } + const T *storage_data(size_t i) const noexcept { + IV_EXPECT(i < N); + return reinterpret_cast(_d) + i; + } +}; + +/// Storage for non-trivial elements. +template struct non_trivial { + static_assert(!satisfy_triviality, + "use storage::trivial for Trivial elements"); + static_assert(N != size_t{0}, "use storage::zero for N==0"); + +protected: + using size_type = smallest_size_t; + +private: + using byte_based_storage = raw_byte_based_storage, N>; + byte_based_storage storage_data_{}; // BUGBUG: test SIMD types + size_type storage_size_ = 0; + +protected: + constexpr const T *storage_data() const noexcept { + return storage_data_.storage_data(0); + } + constexpr auto storage_data() noexcept { + return storage_data_.storage_data(0); + } + constexpr size_type storage_size() const noexcept { return storage_size_; } + constexpr void unsafe_set_size(size_t new_size) noexcept { + IV_EXPECT(size_type(new_size) <= N && "new_size out-of-bounds [0, N)"); + storage_size_ = size_type(new_size); + } + +public: + constexpr non_trivial() noexcept = default; + constexpr non_trivial(non_trivial const &) noexcept = default; + constexpr non_trivial &operator=(non_trivial const &) noexcept = default; + constexpr non_trivial(non_trivial &&) noexcept = default; + constexpr non_trivial &operator=(non_trivial &&) noexcept = default; + + constexpr ~non_trivial() + requires(std::is_trivially_destructible_v) + = default; + constexpr ~non_trivial() { + std::destroy(storage_data(), storage_data() + storage_size()); + } +}; + +// Selects the vector storage. +template +using storage_for = std::conditional_t< + !satisfy_constexpr, non_trivial, + std::conditional_t, trivial>>; + +} // namespace storage + +template +struct inplace_vector_base : private storage::storage_for { +protected: + static_assert(std::is_nothrow_destructible_v, + "T must be nothrow destructible"); + + using base_t = storage::storage_for; + using base_t::storage_data; + using base_t::storage_size; + using base_t::unsafe_set_size; + +public: + using value_type = T; + using pointer = T *; + using const_pointer = const T *; + using reference = value_type &; + using const_reference = const value_type &; + using size_type = size_t; + using difference_type = std::ptrdiff_t; + using iterator = pointer; + using const_iterator = const_pointer; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + // iterators + + constexpr iterator begin() noexcept { return storage_data(); } + constexpr const_iterator begin() const noexcept { return storage_data(); } + constexpr iterator end() noexcept { return begin() + size(); } + constexpr const_iterator end() const noexcept { return begin() + size(); } + constexpr reverse_iterator rbegin() noexcept { + return reverse_iterator(end()); + } + constexpr const_reverse_iterator rbegin() const noexcept { + return const_reverse_iterator(end()); + } + constexpr reverse_iterator rend() noexcept { + return reverse_iterator(begin()); + } + constexpr const_reverse_iterator rend() const noexcept { + return const_reverse_iterator(begin()); + } + + constexpr const_iterator cbegin() const noexcept { return storage_data(); } + constexpr const_iterator cend() const noexcept { return cbegin() + size(); } + constexpr const_reverse_iterator crbegin() const noexcept { + return const_reverse_iterator(cend()); + } + constexpr const_reverse_iterator crend() const noexcept { + return const_reverse_iterator(cbegin()); + } + + // [inplace.vector.capacity], size/capacity + + [[nodiscard]] constexpr bool empty() const noexcept { + return storage_size() == 0; + }; + constexpr size_type size() const noexcept { return storage_size(); } + constexpr void shrink_to_fit() {} + static constexpr size_type max_size() noexcept { return N; } + static constexpr size_type capacity() noexcept { return N; } + + // element access + + constexpr reference operator[](size_type n) { + return details::index(*this, n); + } + constexpr const_reference operator[](size_type n) const { + return details::index(*this, n); + } + constexpr reference front() { return details::index(*this, size_type(0)); } + constexpr const_reference front() const { + return details::index(*this, size_type(0)); + } + constexpr reference back() { + return details::index(*this, size() - size_type(1)); + } + constexpr const_reference back() const { + return details::index(*this, size() - size_type(1)); + } + + // [containers.sequences.inplace_vector.data], data access + constexpr T *data() noexcept { return storage_data(); } + constexpr const T *data() const noexcept { return storage_data(); } + +protected: // Utilities + constexpr void + assert_iterator_in_range([[maybe_unused]] const_iterator it) noexcept { + IV_EXPECT(begin() <= it && "iterator not in range"); + IV_EXPECT(it <= end() && "iterator not in range"); + } + constexpr void + assert_valid_iterator_pair([[maybe_unused]] const_iterator first, + [[maybe_unused]] const_iterator last) noexcept { + IV_EXPECT(first <= last && "invalid iterator pair"); + } + constexpr void assert_iterator_pair_in_range(const_iterator first, + const_iterator last) noexcept { + assert_iterator_in_range(first); + assert_iterator_in_range(last); + assert_valid_iterator_pair(first, last); + } + constexpr void + unsafe_destroy(T *first, + T *last) noexcept(std::is_nothrow_destructible_v) { + assert_iterator_pair_in_range(first, last); + if constexpr (N > 0 && !std::is_trivially_destructible_v) { + for (; first != last; ++first) + first->~T(); + } + } + +public: + // [inplace.vector.modifiers], modifiers + + template + constexpr T &unchecked_emplace_back(Args &&...args) + requires(std::constructible_from) + { + IV_EXPECT(size() < capacity() && "inplace_vector out-of-memory"); + std::construct_at(storage_data() + size(), std::forward(args)...); + unsafe_set_size(size() + size_type(1)); + return this->back(); + } + + template constexpr T *try_emplace_back(Args &&...args) { + if (size() == capacity()) [[unlikely]] + return nullptr; + return &unchecked_emplace_back(std::forward(args)...); + } + + constexpr T *try_push_back(const T &x) + requires(std::constructible_from) + { + return try_emplace_back(x); + } + constexpr T *try_push_back(T &&x) + requires(std::constructible_from) + { + return try_emplace_back(std::forward(x)); + } + + constexpr T &unchecked_push_back(const T &x) + requires(std::constructible_from) + { + return unchecked_emplace_back(x); + } + constexpr T &unchecked_push_back(T &&x) + requires(std::constructible_from) + { + return unchecked_emplace_back(std::forward(x)); + } + + template R> + constexpr std::ranges::borrowed_iterator_t try_append_range(R &&rg) + requires(std::constructible_from>) + { + auto it = std::ranges::begin(rg); + const auto end = std::ranges::end(rg); + for (; size() != capacity() && it != end; ++it) { + unchecked_emplace_back(*it); + } + return it; + } + + constexpr iterator erase(const_iterator first, const_iterator last) + requires(std::movable) + { + assert_iterator_pair_in_range(first, last); + iterator f = begin() + (first - begin()); + if (first != last) { + unsafe_destroy(std::move(f + (last - first), end(), f), end()); + unsafe_set_size(size() - static_cast(last - first)); + } + return f; + } + + constexpr iterator erase(const_iterator position) + requires(std::movable) + { + return erase(position, position + 1); + } + + constexpr void clear() noexcept { + unsafe_destroy(begin(), end()); + unsafe_set_size(0); + } + + constexpr void pop_back() { + IV_EXPECT(size() > 0 && "pop_back from empty inplace_vector!"); + if (size() > 0) { // UB fail-safe + unsafe_destroy(end() - 1, end()); + unsafe_set_size(size() - 1); + } + } + + constexpr friend bool operator==(const inplace_vector_base &x, + const inplace_vector_base &y) { + return x.size() == y.size() && std::ranges::equal(x, y); + } + + constexpr void swap(inplace_vector_base &x) noexcept( + N == 0 || (std::is_nothrow_swappable_v && + std::is_nothrow_move_constructible_v)) + requires(std::movable) + { + auto tmp = std::move(x); + x = std::move(*this); + (*this) = std::move(tmp); + } + + constexpr friend void + swap(inplace_vector_base &x, inplace_vector_base &y) noexcept( + N == 0 || (std::is_nothrow_swappable_v && + std::is_nothrow_move_constructible_v)) { + x.swap(y); + } + + constexpr friend auto operator<=>(const inplace_vector_base &x, + const inplace_vector_base &y) + requires(details::lessthan_comparable) + { + if constexpr (std::three_way_comparable) { + return std::lexicographical_compare_three_way(x.begin(), x.end(), + y.begin(), y.end()); + } else { + const auto sz = std::min(x.size(), y.size()); + for (std::size_t i = 0; i < sz; ++i) { + if (x[i] < y[i]) + return std::strong_ordering::less; + if (y[i] < x[i]) + return std::strong_ordering::greater; + // [container.opt.reqmts] < must be total ordering relationship + } + + return x.size() <=> y.size(); + } + } + + // [containers.sequences.inplace_vector.cons], construct/copy/destroy + + constexpr inplace_vector_base() noexcept = default; + + constexpr inplace_vector_base(const inplace_vector_base &x) + requires(N == 0 || std::is_trivially_copy_constructible_v) + = default; + + constexpr inplace_vector_base(const inplace_vector_base &x) + requires(N != 0 && !std::is_trivially_copy_constructible_v && + std::copyable) + { + for (auto &&e : x) + unchecked_emplace_back(e); + } + + constexpr inplace_vector_base(inplace_vector_base &&x) + requires(N == 0 || std::is_trivially_move_constructible_v) + = default; + + constexpr inplace_vector_base(inplace_vector_base &&x) + requires(N != 0 && !std::is_trivially_move_constructible_v && + std::movable) + { + for (auto &&e : x) + unchecked_emplace_back(std::move(e)); + } + + constexpr inplace_vector_base &operator=(const inplace_vector_base &x) + requires(N == 0 || (std::is_trivially_destructible_v && + std::is_trivially_copy_constructible_v && + std::is_trivially_copy_assignable_v)) + = default; + + constexpr inplace_vector_base &operator=(const inplace_vector_base &x) + requires(N != 0 && + !(std::is_trivially_destructible_v && + std::is_trivially_copy_constructible_v && + std::is_trivially_copy_assignable_v) && + std::copyable) + { + clear(); + for (auto &&e : x) + unchecked_emplace_back(e); + return *this; + } + + constexpr inplace_vector_base &operator=(inplace_vector_base &&x) + requires(N == 0 || (std::is_trivially_destructible_v && + std::is_trivially_move_constructible_v && + std::is_trivially_move_assignable_v)) + = default; + + constexpr inplace_vector_base &operator=(inplace_vector_base &&x) + requires(N != 0 && + !(std::is_trivially_destructible_v && + std::is_trivially_move_constructible_v && + std::is_trivially_move_assignable_v) && + std::movable) + { + clear(); + for (auto &&e : x) + unchecked_emplace_back(std::move(e)); + return *this; + } +}; + +} // namespace beman::inplace_vector::details + +namespace beman::inplace_vector { + +template +concept has_constexpr_support = + details::satisfy_constexpr; + +/// Dynamically-resizable fixed-N vector with inplace storage. +template +struct inplace_vector : public details::inplace_vector_base { + using value_type = T; + using pointer = T *; + using const_pointer = const T *; + using reference = value_type &; + using const_reference = const value_type &; + using size_type = size_t; + using difference_type = std::ptrdiff_t; + using iterator = pointer; + using const_iterator = const_pointer; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + // [containers.sequences.inplace_vector.modifiers], modifiers + + template + constexpr T &emplace_back(Args &&...args) + requires(std::constructible_from) + { + if (!this->try_emplace_back(std::forward(args)...)) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } + return this->back(); + } + constexpr T &push_back(const T &x) + requires(std::constructible_from) + { + emplace_back(x); + return this->back(); + } + constexpr T &push_back(T &&x) + requires(std::constructible_from) + { + emplace_back(std::forward(x)); + return this->back(); + } + + template R> + constexpr void append_range(R &&rg) + requires(std::constructible_from>) + { + if constexpr (std::ranges::sized_range) { + if (this->size() + std::ranges::size(rg) > this->capacity()) + [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } + } + for (auto &&e : rg) { + if (this->size() == this->capacity()) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } + emplace_back(std::forward(e)); + } + } + + template + constexpr iterator emplace(const_iterator position, Args &&...args) + requires(std::constructible_from && std::movable) + { + this->assert_iterator_in_range(position); + auto b = this->end(); + emplace_back(std::forward(args)...); + auto pos = this->begin() + (position - this->begin()); + std::rotate(pos, b, this->end()); + return pos; + } + + template + constexpr iterator insert(const_iterator position, InputIterator first, + InputIterator last) + requires(std::constructible_from> && + std::movable) + { + this->assert_iterator_in_range(position); + if constexpr (std::random_access_iterator) { + if (this->size() + static_cast(std::distance(first, last)) > + this->capacity()) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } + } + auto b = this->end(); + for (; first != last; ++first) + emplace_back(*first); + auto pos = this->begin() + (position - this->begin()); + std::rotate(pos, b, this->end()); + return pos; + } + + template R> + constexpr iterator insert_range(const_iterator position, R &&rg) + requires(std::constructible_from> && + std::movable) + { + return insert(position, std::begin(rg), std::end(rg)); + } + + constexpr iterator insert(const_iterator position, + std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + { + return insert_range(position, il); + } + + constexpr iterator insert(const_iterator position, size_type n, const T &x) + requires(std::constructible_from && std::copyable) + { + this->assert_iterator_in_range(position); + auto b = this->end(); + for (size_type i = 0; i < n; ++i) + emplace_back(x); + auto pos = this->begin() + (position - this->begin()); + std::rotate(pos, b, this->end()); + return pos; + } + + constexpr iterator insert(const_iterator position, const T &x) + requires(std::constructible_from && std::copyable) + { + return insert(position, 1, x); + } + + constexpr iterator insert(const_iterator position, T &&x) + requires(std::constructible_from && std::movable) + { + return emplace(position, std::move(x)); + } + + constexpr inplace_vector &operator=(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + { + assign_range(il); + return *this; + } + + template + constexpr void assign(InputIterator first, InputIterator last) + requires(std::constructible_from> && + std::movable) + { + this->clear(); + insert(this->begin(), first, last); + } + template R> + constexpr void assign_range(R &&rg) + requires(std::constructible_from> && + std::movable) + { + assign(std::begin(rg), std::end(rg)); + } + constexpr void assign(size_type n, const T &u) + requires(std::constructible_from && std::movable) + { + this->clear(); + insert(this->begin(), n, u); + } + constexpr void assign(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + { + this->clear(); + insert_range(this->begin(), il); + } + + // [inplace.vector.capacity], size/capacity + + constexpr void reserve(size_type n) { + if (n > N) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } + } + + constexpr void resize(size_type sz, const T &c) + requires(std::constructible_from && std::copyable) + { + if (sz == this->size()) + return; + else if (sz > N) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } else if (sz > this->size()) + insert(this->end(), sz - this->size(), c); + else { + this->unsafe_destroy(this->begin() + sz, this->end()); + this->unsafe_set_size(sz); + } + } + constexpr void resize(size_type sz) + requires(std::constructible_from && std::default_initializable) + { + if (sz == this->size()) + return; + else if (sz > N) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::bad_alloc()); + } else if (sz > this->size()) { + while (this->size() != sz) + emplace_back(T{}); + } else { + this->unsafe_destroy(this->begin() + sz, this->end()); + this->unsafe_set_size(sz); + } + } + + // element access + + constexpr reference at(size_type pos) { + if (pos >= this->size()) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::out_of_range("inplace_vector::at")); + } + return details::index(*this, pos); + } + constexpr const_reference at(size_type pos) const { + if (pos >= this->size()) [[unlikely]] { + BEMAN_IV_THROW_OR_ABORT(std::out_of_range("inplace_vector::at")); + } + return details::index(*this, pos); + } + + // [containers.sequences.inplace_vector.cons], construct/copy/destroy + + constexpr inplace_vector() noexcept = default; + + constexpr inplace_vector(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + { + insert(this->begin(), il); + } + + constexpr inplace_vector(size_type n, const T &value) + requires(std::constructible_from && std::copyable) + { + insert(this->begin(), n, value); + } + + constexpr explicit inplace_vector(size_type n) + requires(std::constructible_from && std::default_initializable) + { + for (size_type i = 0; i < n; ++i) + emplace_back(T{}); + } + + template // BUGBUG: why not std::ranges::input_iterator? + constexpr inplace_vector(InputIterator first, InputIterator last) + requires(std::constructible_from> && + std::movable) + { + insert(this->begin(), first, last); + } + + template R> + constexpr inplace_vector(details::from_range_t, R &&rg) + requires(std::constructible_from> && + std::movable) + { + insert_range(this->begin(), std::forward(rg)); + } +}; + +namespace freestanding { +template +struct inplace_vector : public details::inplace_vector_base { + using value_type = T; + using pointer = T *; + using const_pointer = const T *; + using reference = value_type &; + using const_reference = const value_type &; + using size_type = size_t; + using difference_type = std::ptrdiff_t; + using iterator = pointer; + using const_iterator = const_pointer; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + // [containers.sequences.inplace_vector.modifiers], modifiers + + template + constexpr T &emplace_back(Args &&...args) + requires(std::constructible_from) + = delete; + constexpr T &push_back(const T &x) + requires(std::constructible_from) + = delete; + constexpr T &push_back(T &&x) + requires(std::constructible_from) + = delete; + + template R> + constexpr void append_range(R &&rg) + requires(std::constructible_from>) + = delete; + + template + constexpr iterator emplace(const_iterator position, Args &&...args) + requires(std::constructible_from && std::movable) + = delete; + + template + constexpr iterator insert(const_iterator position, InputIterator first, + InputIterator last) + requires(std::constructible_from> && + std::movable) + = delete; + + template R> + constexpr iterator insert_range(const_iterator position, R &&rg) + requires(std::constructible_from> && + std::movable) + = delete; + + constexpr iterator insert(const_iterator position, + std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + = delete; + + constexpr iterator insert(const_iterator position, size_type n, const T &x) + requires(std::constructible_from && std::copyable) + = delete; + + constexpr iterator insert(const_iterator position, const T &x) + requires(std::constructible_from && std::copyable) + = delete; + + constexpr iterator insert(const_iterator position, T &&x) + requires(std::constructible_from && std::movable) + = delete; + + constexpr inplace_vector &operator=(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + = delete; + + template + constexpr void assign(InputIterator first, InputIterator last) + requires(std::constructible_from> && + std::movable) + = delete; + template R> + constexpr void assign_range(R &&rg) + requires(std::constructible_from> && + std::movable) + = delete; + constexpr void assign(size_type n, const T &u) + requires(std::constructible_from && std::movable) + = delete; + constexpr void assign(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + = delete; + + // [inplace.vector.capacity], size/capacity + + constexpr void reserve(size_type n) = delete; + + constexpr void resize(size_type sz, const T &c) + requires(std::constructible_from && std::copyable) + = delete; + constexpr void resize(size_type sz) + requires(std::constructible_from && std::default_initializable) + = delete; + + // element access + + constexpr reference at(size_type pos) = delete; + constexpr const_reference at(size_type pos) const = delete; + + // [containers.sequences.inplace_vector.cons], construct/copy/destroy + + constexpr inplace_vector() noexcept = default; + + constexpr inplace_vector(std::initializer_list il) + requires(std::constructible_from< + T, std::ranges::range_reference_t>> && + std::movable) + = delete; + + constexpr inplace_vector(size_type n, const T &value) + requires(std::constructible_from && std::copyable) + = delete; + + constexpr explicit inplace_vector(size_type n) + requires(std::constructible_from && std::default_initializable) + = delete; + + template // BUGBUG: why not std::ranges::input_iterator? + constexpr inplace_vector(InputIterator first, InputIterator last) + requires(std::constructible_from> && + std::movable) + = delete; + + template R> + constexpr inplace_vector(beman::inplace_vector::details::from_range_t, R &&rg) + requires(std::constructible_from> && + std::movable) + = delete; +}; + +} // namespace freestanding + +template +constexpr std::size_t erase(details::inplace_vector_base &c, + const U &value) { + auto it = std::remove(c.begin(), c.end(), value); + auto r = std::distance(it, c.end()); + c.erase(it, c.end()); + return r; +} + +template +constexpr std::size_t erase_if(details::inplace_vector_base &c, + Predicate pred) { + auto it = std::remove_if(c.begin(), c.end(), pred); + auto r = std::distance(it, c.end()); + c.erase(it, c.end()); + return r; +} + +} // namespace beman::inplace_vector + +#undef IV_EXPECT + +#endif // BEMAN_INPLACE_VECTOR_INPLACE_VECTOR_HPP diff --git a/patches/monado/0009-don-t-verify-GL-stuff.patch b/patches/monado/0009-don-t-verify-GL-stuff.patch new file mode 100644 index 00000000..520c5430 --- /dev/null +++ b/patches/monado/0009-don-t-verify-GL-stuff.patch @@ -0,0 +1,33 @@ +From 6f17ee6c92b62a2418164f627775f267eb6d19fc Mon Sep 17 00:00:00 2001 +From: no name +Date: Sun, 25 Jan 2026 10:09:10 +0100 +Subject: [PATCH] don't verify GL stuff + +--- + src/xrt/state_trackers/oxr/oxr_verify.c | 10 ---------- + 1 file changed, 10 deletions(-) + +diff --git a/src/xrt/state_trackers/oxr/oxr_verify.c b/src/xrt/state_trackers/oxr/oxr_verify.c +index e9197d501..71f81c954 100644 +--- a/src/xrt/state_trackers/oxr/oxr_verify.c ++++ b/src/xrt/state_trackers/oxr/oxr_verify.c +@@ -608,16 +608,6 @@ oxr_verify_XrGraphicsBindingOpenGLXlibKHR(struct oxr_logger *log, const XrGraphi + "XrGraphicsBindingOpenGLXlibKHR::glxDrawable is NULL"); + } + +- if (next->glxFBConfig == NULL) { +- return oxr_error(log, XR_ERROR_GRAPHICS_DEVICE_INVALID, +- "XrGraphicsBindingOpenGLXlibKHR::glxFBConfig is NULL"); +- } +- +- if (next->visualid == 0) { +- return oxr_error(log, XR_ERROR_GRAPHICS_DEVICE_INVALID, +- "XrGraphicsBindingOpenGLXlibKHR::visualid is 0"); +- } +- + return XR_SUCCESS; + } + +-- +2.52.0 + diff --git a/server/driver/pose_list.cpp b/server/driver/pose_list.cpp index a091c261..b3dd7326 100644 --- a/server/driver/pose_list.cpp +++ b/server/driver/pose_list.cpp @@ -260,13 +260,19 @@ std::pair pose_list::get_at(XrTime at_timestamp_ns) if (orientation.y) { - flags(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); + if (auto norm2 = orientation.y->squaredNorm(); + norm2 > 0.9 and norm2 < 1.1) + { + flags(XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT); - ret.pose.orientation = { - .x = (*orientation.y)[1], - .y = (*orientation.y)[2], - .z = (*orientation.y)[3], - .w = (*orientation.y)[0]}; + orientation.y->normalize(); + + ret.pose.orientation = { + .x = (*orientation.y)[1], + .y = (*orientation.y)[2], + .z = (*orientation.y)[3], + .w = (*orientation.y)[0]}; + } if (orientation.dy) { diff --git a/server/driver/wivrn_foveation.cpp b/server/driver/wivrn_foveation.cpp index cde6b75e..50d4fbfe 100644 --- a/server/driver/wivrn_foveation.cpp +++ b/server/driver/wivrn_foveation.cpp @@ -27,7 +27,6 @@ #include "xrt/xrt_defines.h" #include -#include #include #include #include @@ -218,44 +217,6 @@ static void fill_param_2d( out.resize(count * 2 - 1); } -static float get_angle_offset() -{ - if (const char * cvar = std::getenv("WIVRN_FOVEATION_OFFSET")) - { - std::string_view var(cvar); - float res; - auto e = std::from_chars(var.begin(), var.end(), res); - if (e.ec == std::errc()) - { - // No clamping, we don’t know the range - // of actual values for all headsets for sure. - return -res * M_PI / 180; - } - else - U_LOG_W("Malformed WIVRN_FOVEATION_OFFSET, must be a number (angle in °)"); - } - // normal sight line is between 10° and 15° below horizontal - // https://apps.dtic.mil/sti/tr/pdf/AD0758339.pdf pages 393-394 - // testing shows 10° looks better - return 10 * M_PI / 180; -} - -static float get_convergence_distance() -{ - if (const char * cvar = std::getenv("WIVRN_FOVEATION_DISTANCE")) - { - std::string_view var(cvar); - float res; - auto e = std::from_chars(var.begin(), var.end(), res); - if (e.ec == std::errc()) - return std::max(res, 0.05f); - else - U_LOG_W("Malformed WIVRN_FOVEATION_DISTANCE, must be a number (distance in meters)"); - } - // 1m by default - return 1; -} - namespace wivrn { @@ -303,8 +264,11 @@ void wivrn_foveation::compute_params( wivrn_foveation::wivrn_foveation(wivrn_vk_bundle & bundle, const xrt_hmd_parts & hmd) : foveated_width(hmd.screens[0].w_pixels), foveated_height(hmd.screens[0].h_pixels), - angle_offset(get_angle_offset()), - convergence_distance(get_convergence_distance()), + // normal sight line is between 10° and 15° below horizontal + // https://apps.dtic.mil/sti/tr/pdf/AD0758339.pdf pages 393-394 + // testing shows 10° looks better + angle_offset(10 * M_PI / 180), + convergence_distance(1 /* meter*/), command_pool(bundle.device, vk::CommandPoolCreateInfo{.queueFamilyIndex = bundle.queue_family_index}), cmd(std::move(bundle.device.allocateCommandBuffers({ .commandPool = *command_pool, diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index 9ce0f626..cac0ddeb 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -228,33 +228,18 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr connection if (get_info().eye_gaze || is_forced_extension("EXT_eye_gaze_interaction")) { // The tracker space needs to be attached to the head pose once the space overseer is created - eye_tracker = std::make_unique(*this); - static_roles.eyes = eye_tracker.get(); - xdevs[xdev_count++] = eye_tracker.get(); + xdevs[xdev_count++] = static_roles.eyes = &eye_tracker.emplace(*this); } auto face = get_info().face_tracking; if (face == from_headset::face_type::android || is_forced_extension("ANDROID_face_tracking")) - { - android_face_tracker = std::make_unique(&hmd, *this); - static_roles.face = android_face_tracker.get(); - xdevs[xdev_count++] = android_face_tracker.get(); - } - if (face == from_headset::face_type::fb2 || is_forced_extension("FB_face_tracking2")) - { - fb_face2_tracker = std::make_unique(&hmd, *this); - static_roles.face = fb_face2_tracker.get(); - xdevs[xdev_count++] = fb_face2_tracker.get(); - } - if (face == wivrn::from_headset::face_type::htc || is_forced_extension("HTC_facial_tracking")) - { - htc_face_tracker = std::make_unique(&hmd, *this); - static_roles.face = htc_face_tracker.get(); - xdevs[xdev_count++] = htc_face_tracker.get(); - } + xdevs[xdev_count++] = static_roles.face = &android_face_tracker.emplace(&hmd, *this); + else if (face == from_headset::face_type::fb2 || is_forced_extension("FB_face_tracking2")) + xdevs[xdev_count++] = static_roles.face = &fb_face2_tracker.emplace(&hmd, *this); + else if (face == wivrn::from_headset::face_type::htc || is_forced_extension("HTC_facial_tracking")) + xdevs[xdev_count++] = static_roles.face = &htc_face_tracker.emplace(&hmd, *this); auto num_generic_trackers = get_info().num_generic_trackers; - generic_trackers.reserve(num_generic_trackers); if (num_generic_trackers > 0) { if (num_generic_trackers > from_headset::body_tracking::max_tracked_poses) @@ -274,11 +259,7 @@ wivrn::wivrn_session::wivrn_session(std::unique_ptr connection U_LOG_I("Creating %d generic trackers", num_generic_trackers); for (int i = 0; i < num_generic_trackers; ++i) - { - auto dev = std::make_unique(i, &hmd, *this); - xdevs[xdev_count++] = dev.get(); - generic_trackers.push_back(std::move(dev)); - } + xdevs[xdev_count++] = &generic_trackers.emplace_back(i, &hmd, *this); } #if WIVRN_FEATURE_SOLARXR @@ -368,7 +349,7 @@ xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptrxrt_system.broadcast, &self->hmd, - self->eye_tracker.get(), + self->static_roles.eyes, &self->left_controller, &self->right_controller, nullptr, @@ -385,13 +366,14 @@ xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptrspace_overseer, &self->hmd, XRT_INPUT_GENERIC_HEAD_POSE, &head_space); if (res == XRT_SUCCESS) { - res = xrt_space_overseer_attach_device(self->space_overseer, self->eye_tracker.get(), head_space); + res = xrt_space_overseer_attach_device(self->space_overseer, self->static_roles.eyes, head_space); xrt_space_reference(&head_space, NULL); } if (res != XRT_SUCCESS) { U_LOG_W("failed to initialize eye tracker: %s", xrt_result_to_string(res).c_str()); - self->eye_tracker = nullptr; + self->static_roles.eyes = nullptr; + self->eye_tracker.reset(); } } @@ -651,12 +633,8 @@ void wivrn_session::operator()(from_headset::body_tracking && body_tracking) { auto offset = offset_est.get_offset(); - assert(generic_trackers.size() <= from_headset::body_tracking::max_tracked_poses); - for (int i = 0; i < generic_trackers.size(); i++) - { - auto pose = body_tracking.poses ? (*body_tracking.poses)[i] : from_headset::body_tracking::pose{}; - generic_trackers[i]->update_tracking(body_tracking, pose, offset); - } + for (auto [tracker, pose]: std::ranges::zip_view(generic_trackers, *body_tracking.poses)) + tracker.update_tracking(body_tracking, pose, offset); } void wivrn_session::operator()(from_headset::inputs && inputs) { diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index f943a1ae..993e82a5 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -19,13 +19,19 @@ #pragma once +#include "app_pacer.h" #include "clock_offset.h" -#include "driver/app_pacer.h" +#include "inplace_vector.hpp" #include "tracking_control.h" #include "utils/thread_safe.h" +#include "wivrn_android_face_tracker.h" #include "wivrn_connection.h" #include "wivrn_controller.h" +#include "wivrn_eye_tracker.h" +#include "wivrn_fb_face2_tracker.h" +#include "wivrn_generic_tracker.h" #include "wivrn_hmd.h" +#include "wivrn_htc_face_tracker.h" #include "wivrn_ipc.h" #include "wivrn_packets.h" #include "wivrn_uinput.h" @@ -35,6 +41,7 @@ #include #include #include +#include #include #include @@ -85,11 +92,11 @@ class wivrn_session : public xrt_system_devices int32_t left_hand_interaction_index; wivrn_controller right_hand_interaction; int32_t right_hand_interaction_index; - std::unique_ptr eye_tracker; - std::unique_ptr android_face_tracker; - std::unique_ptr fb_face2_tracker; - std::unique_ptr htc_face_tracker; - std::vector> generic_trackers; + std::optional eye_tracker; + std::optional android_face_tracker; + std::optional fb_face2_tracker; + std::optional htc_face_tracker; + beman::inplace_vector::inplace_vector generic_trackers; std::optional uinput_handler; std::shared_mutex comp_target_mutex;