From cb1d0d7c2c640f68e54212cd94402bc3135653fb Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Sat, 27 Sep 2025 17:56:38 +0200 Subject: [PATCH] Add a screen to download gltf models --- CMakeLists.txt | 2 + assets-source/default-environment.svg | 47 ++ assets-source/passthrough.svg | 39 ++ client/CMakeLists.txt | 8 +- client/application.cpp | 8 +- client/configuration.cpp | 55 +- client/configuration.h | 2 + client/file_picker.cpp | 85 +++ client/file_picker.h | 35 ++ client/render/imgui_impl.cpp | 73 ++- client/render/imgui_impl.h | 15 + client/render/scene_loader.cpp | 165 +++--- client/scene.cpp | 1 - client/scene.h | 10 +- client/scenes/lobby.cpp | 91 ++- client/scenes/lobby.h | 77 +++ client/scenes/lobby_gui.cpp | 446 ++++++++------ client/scenes/lobby_gui_customize.cpp | 813 ++++++++++++++++++++++++++ client/scenes/stream.h | 2 +- client/scenes/stream_gui.cpp | 51 -- client/shaders/lit.vert.glsl | 10 +- client/shaders/lit_skinned.vert.glsl | 7 +- client/utils/async.h | 31 +- client/utils/cache.h | 18 +- common/utils/thread_safe.h | 2 +- common/wivrn_config.h.in | 2 + tools/check_po.py | 1 + tools/update_messages.sh | 1 + 28 files changed, 1698 insertions(+), 399 deletions(-) create mode 100644 assets-source/default-environment.svg create mode 100644 assets-source/passthrough.svg create mode 100644 client/file_picker.cpp create mode 100644 client/file_picker.h create mode 100644 client/scenes/lobby_gui_customize.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b866bb81..347ce0e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,6 +69,8 @@ endif() option(ENABLE_COLOURED_OUTPUT "Always produce ANSI-coloured output (GNU/Clang only)." ON) +set(WIVRN_ENVIRONMENTS_URL "https://wivrn.github.io/environments/index.json" CACHE STRING "URL hosting the custom environments json file") + if (WIVRN_BUILD_CLIENT OR WIVRN_BUILD_SERVER OR WIVRN_BUILD_DASHBOARD OR WIVRN_BUILD_DISSECTOR) set(NEED_COMMON TRUE) else() diff --git a/assets-source/default-environment.svg b/assets-source/default-environment.svg new file mode 100644 index 00000000..e33004c5 --- /dev/null +++ b/assets-source/default-environment.svg @@ -0,0 +1,47 @@ + + + + + + + + + + diff --git a/assets-source/passthrough.svg b/assets-source/passthrough.svg new file mode 100644 index 00000000..69efd2fb --- /dev/null +++ b/assets-source/passthrough.svg @@ -0,0 +1,39 @@ + + + + + + + + + diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index be600bd8..ed9ba742 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -235,12 +235,16 @@ file(REAL_PATH ${WIVRN_CSS} WIVRN_CSS_ABS BASE_DIRECTORY "${CMAKE_SOURCE_DIR}") set(IMAGES_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../images) set(ASSETS_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../assets-source) -wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS}) -wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn-pride.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn-pride.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS}) +wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS}) +wivrn_rasterize_svg(SOURCE ${IMAGES_SRC_DIR}/wivrn-pride.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/wivrn-pride.png WIDTH 540 HEIGHT 540 CSS ${WIVRN_CSS_ABS}) +wivrn_rasterize_svg(SOURCE ${ASSETS_SRC_DIR}/passthrough.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/passthrough.png WIDTH 256 HEIGHT 256) +wivrn_rasterize_svg(SOURCE ${ASSETS_SRC_DIR}/default-environment.svg DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/default-environment.png WIDTH 256 HEIGHT 256) wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/wivrn.png DESTINATION ${ASSETS_DIR}/wivrn.ktx2 TARGET wivrn) wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/wivrn-pride.png DESTINATION ${ASSETS_DIR}/wivrn-pride.ktx2 TARGET wivrn) wivrn_generate_ktx( SOURCE ${ASSETS_SRC_DIR}/default_icon.png DESTINATION ${ASSETS_DIR}/default_icon.ktx2 TARGET wivrn) +wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/passthrough.png DESTINATION ${ASSETS_DIR}/passthrough.ktx2 TARGET wivrn) +wivrn_generate_ktx( SOURCE ${CMAKE_CURRENT_BINARY_DIR}/default-environment.png DESTINATION ${ASSETS_DIR}/default-environment.ktx2 TARGET wivrn) wivrn_gltf_transform_uastc(SOURCE ${ASSETS_SRC_DIR}/ground.glb DESTINATION ${ASSETS_DIR}/ground.glb TARGET wivrn ZSTD 20) wivrn_webxr_controller( SOURCE ${ASSETS_SRC_DIR}/controllers/generic-trigger-squeeze DESTINATION ${ASSETS_DIR}/controllers/generic-trigger-squeeze TARGET wivrn) wivrn_webxr_controller( SOURCE ${ASSETS_SRC_DIR}/controllers/htc-vive-focus-3 DESTINATION ${ASSETS_DIR}/controllers/htc-vive-focus-3 TARGET wivrn) diff --git a/client/application.cpp b/client/application.cpp index e9a6fa1c..3e62a085 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -28,8 +28,8 @@ #include "utils/files.h" #include "utils/i18n.h" #include "vk/check.h" -#include "vk/shader.h" #include "wifi_lock.h" +#include "wivrn_config.h" #include "xr/actionset.h" #include "xr/check.h" #include "xr/htc_exts.h" @@ -1614,6 +1614,7 @@ void application::loop() } else { + spdlog::info("Last scene was popped"); exit_requested = true; } } @@ -1642,6 +1643,7 @@ void application::run() exit_requested = true; } } + spdlog::info("Exiting application_thread"); }); // Read all pending events. @@ -1660,10 +1662,13 @@ void application::run() if (app_info.native_app->destroyRequested) { + spdlog::info("app_info.native_app->destroyRequested is true"); exit_requested = true; } } + spdlog::info("Exiting normally"); + application_thread.join(); } #else @@ -1860,6 +1865,7 @@ void application::poll_events() switch (e.header.type) { case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: { + spdlog::info("Received XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING"); exit_requested = true; } break; diff --git a/client/configuration.cpp b/client/configuration.cpp index dbea9cf2..9709fd17 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -19,6 +19,7 @@ #include "configuration.h" #include "application.h" +#include "utils/json_string.h" #include #include @@ -27,56 +28,6 @@ #include "android/permissions.h" #endif -static std::string json_string(const std::string & in) -{ - std::string out; - out.reserve(in.size() + 2); - - out += '"'; - - for (char c: in) - { - switch (c) - { - case '\b': - out += "\\b"; - break; - - case '\f': - out += "\\f"; - break; - - case '\n': - out += "\\n"; - break; - - case '\r': - out += "\\r"; - break; - - case '\t': - out += "\\t"; - break; - - case '"': - out += "\\\""; - break; - - case '\\': - out += "\\\\"; - break; - - default: - out += c; - break; - } - } - - out += '"'; - - return out; -} - bool configuration::check_feature(feature f) const { { @@ -221,6 +172,9 @@ configuration::configuration(xr::system & system) if (auto val = root["locale"]; val.is_string()) locale = val.get_string().value(); + + if (auto val = root["environment_model"]; val.is_string()) + environment_model = (std::string_view)val.get_string(); } catch (std::exception & e) { @@ -308,5 +262,6 @@ void configuration::save() json << ",\"override_foveation_distance\":" << override_foveation_distance; json << ",\"first_run\":" << std::boolalpha << first_run; json << ",\"locale\":" << json_string(locale); + json << ",\"environment_model\":" << json_string(environment_model); json << "}"; } diff --git a/client/configuration.h b/client/configuration.h index d8dfbf6f..f5e6f3a6 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -68,6 +68,8 @@ public: std::string virtual_keyboard_layout = "QWERTY"; + std::string environment_model = "assets://ground.glb"; + bool override_foveation_enable = false; float override_foveation_pitch = 10 * M_PI / 180; float override_foveation_distance = 3; diff --git a/client/file_picker.cpp b/client/file_picker.cpp new file mode 100644 index 00000000..3a335d0e --- /dev/null +++ b/client/file_picker.cpp @@ -0,0 +1,85 @@ +/* + * 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 "file_picker.h" + +#include "application.h" +#include "utils/mapped_file.h" +#include + +#ifdef __ANDROID__ +#include "android/intent.h" +#endif + +std::future file_picker::open() +{ + // Put it in a shared_ptr because clang does not support std::move_only_function + auto promise = std::make_shared>(); + auto future = promise->get_future(); + +#ifdef __ANDROID__ + // https://developer.android.com/training/data-storage/shared/documents-files#open + // https://developer.android.com/reference/android/content/Intent#ACTION_OPEN_DOCUMENT + // https://developer.android.com/guide/components/intents-common#OpenFile + + intent open_doc{"android.intent.action.OPEN_DOCUMENT"}; // Intent.ACTION_OPEN_DOCUMENT + open_doc.set_type("*/*"); + open_doc.add_category("android.intent.category.OPENABLE"); // Intent.CATEGORY_OPENABLE + open_doc.start([promise](int result_code, intent && data) mutable { + try + { + if (result_code != -1 /* Activity.RESULT_OK */) + return; + + auto uri = data.get_uri(); + auto uri_string = (std::string)uri.call("toString"); + + jni::object<""> activity(application::native_app()->activity->clazz); + auto content_resolver = activity.call>("getContentResolver"); + + content_resolver.call("takePersistableUriPermission", uri, jni::Int{1} /* Intent.FLAG_GRANT_READ_URI_PERMISSION */); + + auto pfd = content_resolver.call>("openFileDescriptor", uri, jni::string{"r"}); + int fd = pfd.call("getFd"); + + // The file descriptor is owned by the ParcelFileDescriptor, dup it before + // passing it to mapped_file to ensure the original fd is not closed + promise->set_value(file_picker_result{ + .path = uri_string, + .file = utils::mapped_file{fd}, + }); + } + catch (...) + { + promise->set_exception(std::current_exception()); + } + }); +#else + // TODO +#endif + return future; +} + +void file_picker::display() +{ +#ifdef __ANDROID__ + // No-op on Android, the file picker is displayed by the OS +#else + // TODO +#endif +} diff --git a/client/file_picker.h b/client/file_picker.h new file mode 100644 index 00000000..42ba8ca6 --- /dev/null +++ b/client/file_picker.h @@ -0,0 +1,35 @@ +/* + * 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 "utils/mapped_file.h" +#include + +struct file_picker_result +{ + std::filesystem::path path; + utils::mapped_file file; +}; + +class file_picker +{ +public: + [[nodiscard]] std::future open(); + void display(); +}; diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 9eed781d..dabb7c56 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -1246,10 +1246,18 @@ void ScrollWhenDragging() void CenterTextH(const std::string & text) { float win_width = ImGui::GetWindowSize().x; - float text_width = ImGui::CalcTextSize(text.c_str()).x; - ImGui::SetCursorPosX((win_width - text_width) / 2); - ImGui::Text("%s", text.c_str()); + std::vector lines = utils::split(text); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 0}); + for (const auto & i: lines) + { + float text_width = ImGui::CalcTextSize(i.c_str()).x; + ImGui::SetCursorPosX((win_width - text_width) / 2); + ImGui::Text("%s", i.c_str()); + } + ImGui::PopStyleVar(); + ImGui::Dummy({}); // Make sure the original vertical ItemSpacing is respected } void CenterTextHV(const std::string & text) @@ -1273,3 +1281,62 @@ void CenterTextHV(const std::string & text) } ImGui::PopStyleVar(); } + +void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags) +{ + auto callback = [](ImGuiInputTextCallbackData * data) -> int { + std::string & text = *reinterpret_cast(data->UserData); + + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + assert(text.data() == data->Buf); + text.resize(data->BufTextLen); + data->Buf = text.data(); + } + + return 0; + }; + + ImGui::InputTextEx(label, nullptr, text.data(), text.size() + 1, size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text); +} + +bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; + const ImGuiID id = window->GetID(label.c_str()); + const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true); + + const ImVec2 pos = window->DC.CursorPos; + + ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, style.FramePadding.y); + if (!ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); + + ImGuiCol_ col; + if ((held && hovered) || active) + col = ImGuiCol_ButtonActive; + else if (hovered) + col = ImGuiCol_ButtonHovered; + else + col = ImGuiCol_Button; + + ImGui::RenderNavHighlight(bb, id); + ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding); + + ImVec2 TextAlign{0, 0.5f}; + ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb); + + IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags); + return pressed; +} diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 636dbd85..0e9df0db 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -243,5 +243,20 @@ public: }; void ScrollWhenDragging(); + void CenterTextH(const std::string & text); + void CenterTextHV(const std::string & text); + +void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags); + +bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg); + +template +static bool RadioButtonWithoutCheckBox(const std::string & label, T & v, U v_button, ImVec2 size_arg) +{ + const bool pressed = RadioButtonWithoutCheckBox(label, v == v_button, size_arg); + if (pressed) + v = v_button; + return pressed; +} diff --git a/client/render/scene_loader.cpp b/client/render/scene_loader.cpp index a3892811..60b3d739 100644 --- a/client/render/scene_loader.cpp +++ b/client/render/scene_loader.cpp @@ -1139,6 +1139,81 @@ std::shared_ptr scene_loader::operator()( return loaded_scene; } +struct cache_entry +{ + std::string filename; + int64_t timestamp = 0; + int64_t size = 0; +}; + +static cache_entry read_cache_entry(const std::filesystem::path & path) +{ + cache_entry entry; + std::string json = utils::read_whole_file(path / "index.json"); + simdjson::dom::parser parser; + simdjson::dom::element root = parser.parse(json); + + if (auto val = root["filename"]; val.is_string()) + entry.filename = val.get_string().value(); + + if (auto val = root["size"]; val.is_int64()) + entry.size = val.get_int64(); + + if (auto val = root["timestamp"]; val.is_int64()) + entry.timestamp = val.get_int64(); + + return entry; +} + +static void write_cache_entry(const std::filesystem::path & path, const cache_entry & entry) +{ + std::ofstream json{path / "index.json"}; + json << "{\"filename\":" << json_string(entry.filename); + json << ",\"size\":" << entry.size; + + // TODO get a timestamp for assets + if (not entry.filename.starts_with("assets://")) + { + auto mtime = std::chrono::file_clock::to_sys(std::filesystem::last_write_time(entry.filename)); + auto timestamp = std::chrono::duration_cast(mtime.time_since_epoch()).count(); + auto size = entry.size; + + json << ",\"timestamp\":" << timestamp; + } + json << "}"; +} + +// Returns false if the cache is out of date and must be deleted +static bool check_cache_entry(const std::filesystem::path & path) +{ + try + { + cache_entry entry = read_cache_entry(path); + + utils::mapped_file file{entry.filename}; + int64_t real_size = file.size(); + + if (real_size != entry.size) + return false; + + // TODO get a timestamp for assets + if (not entry.filename.starts_with("assets://")) + { + auto mtime = std::chrono::file_clock::to_sys(std::filesystem::last_write_time(entry.filename)); + auto timestamp = std::chrono::duration_cast(mtime.time_since_epoch()).count(); + + if (timestamp != entry.timestamp) + return false; + } + } + catch (...) + { + return false; + } + + return true; +} + std::shared_ptr scene_loader::operator()( const std::filesystem::path & gltf_path, std::function progress_cb) @@ -1169,6 +1244,14 @@ std::shared_ptr scene_loader::operator()( spdlog::debug("\"{}\" is not a directory: creating cache", gltf_texture_cache.native()); create_cache = true; } + else if (not check_cache_entry(gltf_texture_cache)) + { + std::error_code ec; + std::filesystem::remove_all(gltf_texture_cache, ec); + std::filesystem::create_directories(gltf_texture_cache); + spdlog::debug("\"{}\" is out of date: recreating cache", gltf_texture_cache.native()); + create_cache = true; + } } else { @@ -1186,20 +1269,12 @@ std::shared_ptr scene_loader::operator()( if (create_cache) { - std::ofstream json{gltf_texture_cache / "index.json"}; - json << "{\"filename\":" << json_string(gltf_path.native()); - json << ",\"size\":" << gltf_file.size(); - - // TODO get a timestamp for assets - if (not gltf_path.native().starts_with("assets://")) - { - auto mtime = std::chrono::file_clock::to_sys(std::filesystem::last_write_time(gltf_path)); - auto timestamp = std::chrono::duration_cast(mtime.time_since_epoch()).count(); - auto size = gltf_file.size(); - - json << ",\"timestamp\":" << timestamp; - } - json << "}"; + write_cache_entry( + gltf_texture_cache, + cache_entry{ + .filename = gltf_path.native(), + .size = (int64_t)gltf_file.size(), + }); } } @@ -1215,69 +1290,11 @@ void scene_loader::clear_texture_cache() if (not entry.is_directory()) continue; - std::string saved_filename; - int64_t saved_timestamp = 0; - int64_t saved_size = 0; - - try + if (not check_cache_entry(entry)) { - std::string json = utils::read_whole_file(entry.path() / "index.json"); - simdjson::dom::parser parser; - simdjson::dom::element root = parser.parse(json); - - if (auto val = root["filename"]; val.is_string()) - saved_filename = val.get_string().value(); - - if (auto val = root["size"]; val.is_int64()) - saved_size = val.get_int64(); - - if (auto val = root["timestamp"]; val.is_int64()) - saved_timestamp = val.get_int64(); - } - catch (std::exception & e) - { - // If the index file is not found, remove the cache - spdlog::info("{}: cannot open index.json ({}), removing cache directory", entry.path().native(), e.what()); + spdlog::info("{}: removing cache directory", entry.path().native()); std::error_code ec; std::filesystem::remove_all(entry.path(), ec); - continue; - } - - int64_t real_size = 0; - try - { - utils::mapped_file file{saved_filename}; - real_size = file.size(); - } - catch (std::exception & e) - { - spdlog::info("{}: cannot open {} ({}), removing cache directory", entry.path().native(), saved_filename, e.what()); - std::error_code ec; - std::filesystem::remove_all(entry.path(), ec); - continue; - } - - if (real_size != saved_size) - { - spdlog::info("{}: wrong size for {} (cache: {}, current: {}), removing cache directory", entry.path().native(), saved_filename, saved_size, real_size); - std::error_code ec; - std::filesystem::remove_all(entry.path(), ec); - continue; - } - - // TODO get a timestamp for assets - if (not saved_filename.starts_with("assets://")) - { - auto mtime = std::chrono::file_clock::to_sys(std::filesystem::last_write_time(saved_filename)); - auto timestamp = std::chrono::duration_cast(mtime.time_since_epoch()).count(); - - if (timestamp != saved_timestamp) - { - spdlog::info("{}: wrong timestamp for {} (cache: {}, current: {}), removing cache directory", entry.path().native(), saved_filename, saved_timestamp, timestamp); - std::error_code ec; - std::filesystem::remove_all(entry.path(), ec); - continue; - } } } } diff --git a/client/scene.cpp b/client/scene.cpp index ca5236a8..658aaa4f 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -577,7 +577,6 @@ std::pair scene::add_gltf(const std::filesyste return add_gltf(load_gltf(path), layer_mask); } - void scene::remove(entt::entity entity) { std::vector to_be_removed{entity}; diff --git a/client/scene.h b/client/scene.h index a610fe0b..05fd1bb3 100644 --- a/client/scene.h +++ b/client/scene.h @@ -20,7 +20,6 @@ #pragma once #include "render/image_loader.h" -#include "render/imgui_impl.h" #include "render/scene_loader.h" #include "render/scene_renderer.h" #include "utils/cache.h" @@ -220,6 +219,15 @@ public: void unload_gltf(const std::filesystem::path & path); std::pair add_gltf(std::shared_ptr gltf, uint32_t layer_mask = -1); std::pair add_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1); + void clear_texture_cache() + { + gltf_cache->loader().clear_texture_cache(); + } + + void clear_gltf_cache() + { + gltf_cache->clear(); + } void remove(entt::entity entity); }; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index d6087c78..3a1ad51e 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -19,6 +19,7 @@ #include "lobby.h" #include "application.h" +#include "configuration.h" #include "constants.h" #include "glm/geometric.hpp" #include "hand_model.h" @@ -27,18 +28,22 @@ #include "openxr/openxr.h" #include "protocol_version.h" #include "render/animation.h" +#include "render/scene_components.h" #include "stream.h" -#include "utils/contains.h" +#include "utils/files.h" #include "utils/i18n.h" #include "wivrn_client.h" #include "wivrn_discover.h" #include "wivrn_sockets.h" #include "xr/passthrough.h" #include "xr/space.h" -#include -#include // IWYU pragma: keep +#include +#include #include +#include +#include +#include #include #include #include @@ -731,8 +736,21 @@ void scenes::lobby::render(const XrFrameState & frame_state) } #endif + renderer->debug_draw_clear(); std::vector> imgui_layers = draw_gui(frame_state.predictedDisplayTime); +#if WIVRN_CLIENT_DEBUG_MENU + if (auto * node = world.try_get(debug_primitive_to_highlight.first); + node and + node->mesh and + debug_primitive_to_highlight.second < node->mesh->primitives.size()) + { + const auto & primitive = node->mesh->primitives[debug_primitive_to_highlight.second]; + // FIXME: transform_to_root is 1 frame late + renderer->debug_draw_box(node->transform_to_root, primitive.obb_min, primitive.obb_max, glm::vec4(1, 1, 1, 1)); + } +#endif + // Get the planes that limit the ray size from the composition layers std::vector ray_limits; for (auto & [z_index, layer]: imgui_layers) @@ -761,7 +779,8 @@ void scenes::lobby::render(const XrFrameState & frame_state) composition_layer_depth_test_supported, composition_layer_depth_test_supported ? layer_lobby | layer_controllers : layer_lobby, clear_color, - foveation); + foveation, + true); if (composition_layer_depth_test_supported) set_depth_test(true, XR_COMPARE_OP_ALWAYS_FB); @@ -823,7 +842,19 @@ void scenes::lobby::on_focused() // assert(std::ranges::all_of(views, [width](const XrViewConfigurationView & view) { return view.recommendedImageRectWidth == width; })); // assert(std::ranges::all_of(views, [height](const XrViewConfigurationView & view) { return view.recommendedImageRectHeight == height; })); - lobby_entity = add_gltf("assets://ground.glb", layer_lobby).first; + auto & config = application::get_config(); + + try + { + lobby_entity = add_gltf(config.environment_model, layer_lobby).first; + } + catch (std::exception & e) + { + spdlog::warn("Cannot load environment from {}: {}, reverting to default", config.environment_model, e.what()); + config.environment_model = configuration{}.environment_model; + lobby_entity = add_gltf(config.environment_model, layer_lobby).first; + config.save(); + } std::string profile = controller_name(); input.emplace( @@ -905,16 +936,16 @@ void scenes::lobby::on_focused() { // Pop up window .space = xr::spaces::world, - .size = {0.6, 0.28}, + .size = {0.6, 0.4}, .vp_origin = {1500, 0}, - .vp_size = {1500, 700}, + .vp_size = {1500, 1000}, .z_index = constants::lobby::zindex_gui, }, { // Virtual keyboard .space = xr::spaces::world, .size = {0.6, 0.2}, - .vp_origin = {1500, 700}, + .vp_origin = {1500, 1000}, .vp_size = {1500, 500}, .always_show_cursor = true, .z_index = constants::lobby::zindex_gui, @@ -930,7 +961,7 @@ void scenes::lobby::on_focused() .z_index = constants::lobby::zindex_recenter_tip, }}; - xr::swapchain swapchain_imgui(instance, session, device, swapchain_format, 3000, 1300); + xr::swapchain swapchain_imgui(instance, session, device, swapchain_format, 3000, 1500); imgui_ctx.emplace( physical_device, @@ -948,6 +979,46 @@ void scenes::lobby::on_focused() about_picture = imgui_ctx->load_texture("assets://" + image + ".ktx2"); + try + { + local_environments = load_environment_json(utils::read_whole_file(application::get_config_path() / "environments.json")); + + // Remove environments if the model file is deleted + std::erase_if(local_environments, [&](const environment_model & model) { + std::filesystem::path path = model.local_gltf_path; + return not std::filesystem::exists(path); + }); + } + catch (...) + { + } + + local_environments.push_back( + environment_model{ + .name = gettext_noop("Passthrough"), + .author = "", + .description = "", + .screenshot_url = "", + .gltf_url = "passthrough", // This needs to be unique because it is used as a key, even if there is no actual URL + .builtin = true, + .override_order = -2, + .local_gltf_path = "", + .screenshot = imgui_ctx->load_texture("assets://passthrough.ktx2")}); + + local_environments.push_back( + environment_model{ + .name = gettext_noop("Default environment"), + .author = "", + .description = "", + .screenshot_url = "", + .gltf_url = "default", + .builtin = true, + .override_order = -1, + .local_gltf_path = configuration{}.environment_model, + .screenshot = imgui_ctx->load_texture("assets://default-environment.ktx2")}); + + std::ranges::sort(local_environments, std::less{}); + setup_passthrough(); session.set_refresh_rate(application::get_config().preferred_refresh_rate.value_or(0)); multicast = application::get_wifi_lock().get_multicast_lock(); @@ -968,6 +1039,8 @@ void scenes::lobby::on_unfocused() renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets about_picture = 0; + local_environments.clear(); + imgui_ctx.reset(); world = entt::registry{}; diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index eb003964..c4f7def7 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -21,6 +21,8 @@ #include "configuration.h" #include "crypto.h" +#include "file_picker.h" +#include "libcurl.h" #include "scene.h" #include "scenes/lobby_keyboard.h" #include "utils/mapped_file.h" @@ -33,7 +35,9 @@ #include #include +#include #include +#include #include #include "input_profile.h" @@ -65,6 +69,9 @@ class lobby : public scene_impl std::optional input; entt::entity lobby_entity; + file_picker lobby_file_picker; + std::future lobby_file_picker_future; + std::optional imgui_ctx; std::optional left_hand; @@ -114,6 +121,7 @@ class lobby : public scene_impl server_list, settings, post_processing, + customize, #if WIVRN_CLIENT_DEBUG_MENU debug, #endif @@ -140,6 +148,73 @@ class lobby : public scene_impl thread_safe_notifyable pin_request; std::string pin_buffer; + struct environment_model + { + // Data from the JSON + std::string name; + std::string author; + std::string description; + std::string screenshot_url; + std::string gltf_url; + size_t size{}; + + bool builtin = false; + int override_order = 0; + std::filesystem::path local_screenshot_path; + std::filesystem::path local_gltf_path; + std::vector screenshot_png; + ImTextureID screenshot{}; + + std::strong_ordering operator<=>(const environment_model & other) const + { + // Reverse order for the builtin member: we want the built-in models first + if (auto cmp = override_order <=> other.override_order; cmp != std::strong_ordering::equal) + return cmp; + + return una::casesens::collate_utf8(name, other.name) <=> 0; + } + }; + + std::vector downloadable_environments; + std::vector local_environments; + environment_model * environment_to_be_deleted = nullptr; + + std::map>> current_transfers; + libcurl curl; // needs to be after current_transfers + + void update_file_picker(); + void update_transfers(); + void download(const std::string & url, const std::filesystem::path & path, std::function = {}); + void download(const std::string & url, std::function = {}); + libcurl::curl_handle * try_get_download_handle(const std::string & url); + + std::string downloadable_environment_list_status; + + std::vector load_environment_json(const std::string & json); + void save_environment_json(); + void download_environment(const environment_model & model, bool use_after_downloading); + void delete_environment(const environment_model & model); + enum class environment_item_action + { + none, + delete_model, + download_model, + use_model, + }; + environment_item_action environment_item(environment_model & model, bool download_screenshot); + void environment_list(std::vector & model, bool download_screenshot); + void use_environment(const environment_model & model); + void popup_load_environment(); + utils::future>, float> future_environment; + std::string load_environment_status; + + void download_environment_list(); + libcurl::curl_handle * parse_environment_list(); + +#if WIVRN_CLIENT_DEBUG_MENU + std::pair debug_primitive_to_highlight = {entt::null, 0}; +#endif + void draw_features_status(XrTime predicted_display_time); void gui_connecting(locked_notifiable & request); void gui_enter_pin(locked_notifiable & request); @@ -148,6 +223,8 @@ class lobby : public scene_impl void gui_new_server(); void gui_settings(); void gui_post_processing(); + void gui_customize(); + void gui_debug_node_hierarchy(entt::entity root = entt::null); void gui_debug(); void gui_about(); void gui_licenses(); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index 89a1e0d7..6b4c85b0 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -17,7 +17,6 @@ * along with this program. If not, see . */ -#include #define IMGUI_DEFINE_MATH_OPERATORS #ifdef __ANDROID__ @@ -27,47 +26,40 @@ #include "configuration.h" #include "constants.h" #include "imgui.h" -#include "imgui_internal.h" #include "lobby.h" -#include "scenes/stream.h" +#include "scenes/stream.h" // IWYU pragma: keep +#include "utils/async.h" #include "utils/i18n.h" #include "utils/mapped_file.h" #include "utils/overloaded.h" +#include "utils/ranges.h" #include "version.h" #include "xr/body_tracker.h" #include #include +#include +#include +#include +#include #include +#include +#include #include #include +#include +#include #include #include #include +#include #include #include +#include #include "IconsFontAwesome6.h" using namespace std::chrono_literals; -static void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags) -{ - auto callback = [](ImGuiInputTextCallbackData * data) -> int { - std::string & text = *reinterpret_cast(data->UserData); - - if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) - { - assert(text.data() == data->Buf); - text.resize(data->BufTextLen); - data->Buf = text.data(); - } - - return 0; - }; - - ImGui::InputTextEx(label, nullptr, text.data(), text.size() + 1, size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text); -} - static void display_recentering_tip(imgui_context & ctx, const std::string & tip) { ImGui::PushFont(nullptr, constants::gui::font_size_large); @@ -783,17 +775,6 @@ void scenes::lobby::gui_settings() ImGui::EndDisabled(); } - ImGui::BeginDisabled(system.passthrough_supported() == xr::passthrough_type::none); - if (ImGui::Checkbox(_S("Enable video passthrough in lobby"), &config.passthrough_enabled)) - { - setup_passthrough(); - config.save(); - } - imgui_ctx->vibrate_on_hover(); - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) - imgui_ctx->tooltip(_("This feature is not supported by your headset")); - ImGui::EndDisabled(); - { ImGui::Checkbox(_S("Enable in-stream window"), &config.enable_stream_gui); imgui_ctx->vibrate_on_hover(); @@ -871,120 +852,229 @@ void scenes::lobby::gui_post_processing() } #if WIVRN_CLIENT_DEBUG_MENU +void scenes::lobby::gui_debug_node_hierarchy(entt::entity root) +{ + for (auto && [entity, node]: world.view().each()) + { + if (node.parent != root) + continue; + + std::string id = "entity-" + std::to_string((int)entity); + const std::string & name = node.name == "" ? id : node.name; + + // See ImGui::StyleColorsDark + if (node.global_visible) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.00f, 1.00f, 1.00f, 1.00f)); + else + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.50f, 0.50f, 0.50f, 1.00f)); + + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + if (ImGui::TreeNodeEx(id.c_str(), ImGuiTreeNodeFlags_None, "%s", name.c_str())) + { + glm::vec3 scale{ + glm::length(glm::column(node.transform_to_root, 0)), + glm::length(glm::column(node.transform_to_root, 1)), + glm::length(glm::column(node.transform_to_root, 2)), + }; + + gui_debug_node_hierarchy(entity); + + if (node.mesh) + for (auto [index, primitive]: utils::enumerate(node.mesh->primitives)) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + std::string name = "Primitive " + std::to_string(index + 1); + + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf; + if (debug_primitive_to_highlight == std::pair{entity, index}) + flags |= ImGuiTreeNodeFlags_Selected; + + if (ImGui::TreeNodeEx(name.c_str(), flags)) + { + if (ImGui::IsItemClicked()) + debug_primitive_to_highlight = {entity, index}; + + if (ImGui::IsItemHovered()) + { + std::string tooltip = fmt::format( + "Name: {}\n" + "Topology: {}\n" + "Vertices: {}\n" + "Material: {}\n" + "vertex shader: {}\n" + "Fragment shader: {}\n", + name, + vk::to_string(primitive.topology), + primitive.vertex_count, + primitive.material_->name, + primitive.vertex_shader, + primitive.material_->fragment_shader_name); + + imgui_ctx->tooltip(tooltip); + } + + ImGui::TreePop(); + } + + ImGui::TableNextColumn(); + + glm::vec3 size = scale * (primitive.obb_max - primitive.obb_min); + ImGui::Text("%s", fmt::format("{} vertices, {:.3f} x {:.3f} x {:.3f} m", primitive.vertex_count, size.x, size.y, size.z).c_str()); + } + + ImGui::TreePop(); + } + ImGui::TableNextRow(); + ImGui::PopStyleColor(); // ImGuiCol_Text + } +} + void scenes::lobby::gui_debug() { ImGui::GetIO().ConfigDragClickToInputText = true; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(20, 20)); - ImGui::Checkbox("Display debug axes", &display_debug_axes); - imgui_ctx->vibrate_on_hover(); - - if (display_debug_axes) + if (ImGui::CollapsingHeader("Tune controller offset")) { - ImGui::Checkbox("Display grip instead of aim", &display_grip_instead_of_aim); + imgui_ctx->vibrate_on_hover(); + ImGui::Checkbox("Display debug axes", &display_debug_axes); + imgui_ctx->vibrate_on_hover(); + + if (display_debug_axes) + { + ImGui::Checkbox("Display grip instead of aim", &display_grip_instead_of_aim); + imgui_ctx->vibrate_on_hover(); + } + + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("##offset x", &offset_position.x, 0.0001); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("##offset y", &offset_position.y, 0.0001); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("Position", &offset_position.z, 0.0001); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + if (ImGui::Button("Reset##position")) + offset_position = {0, 0, 0}; + imgui_ctx->vibrate_on_hover(); + + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("##offset roll", &offset_orientation.x, 0.01); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("##offset pitch", &offset_orientation.y, 0.01); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("Rotation", &offset_orientation.z, 0.01); + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + if (ImGui::Button("Reset##orientation")) + offset_orientation = {0, 0, 0}; + imgui_ctx->vibrate_on_hover(); + + ImGui::SetNextItemWidth(140); + ImGui::DragFloat("Ray offset", &ray_offset, 0.0001); imgui_ctx->vibrate_on_hover(); } - - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("##offset x", &offset_position.x, 0.0001); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("##offset y", &offset_position.y, 0.0001); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("Position", &offset_position.z, 0.0001); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - if (ImGui::Button("Reset##position")) - offset_position = {0, 0, 0}; - imgui_ctx->vibrate_on_hover(); - - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("##offset roll", &offset_orientation.x, 0.01); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("##offset pitch", &offset_orientation.y, 0.01); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("Rotation", &offset_orientation.z, 0.01); - imgui_ctx->vibrate_on_hover(); - - ImGui::SameLine(); - if (ImGui::Button("Reset##orientation")) - offset_orientation = {0, 0, 0}; - imgui_ctx->vibrate_on_hover(); - - ImGui::SetNextItemWidth(140); - ImGui::DragFloat("Ray offset", &ray_offset, 0.0001); - imgui_ctx->vibrate_on_hover(); + else + imgui_ctx->vibrate_on_hover(); if (ImGui::Button("Delete configuration file")) std::filesystem::remove(application::get_config_path() / "client.json"); imgui_ctx->vibrate_on_hover(); - float win_width = ImGui::GetWindowSize().x; - float win_height = ImGui::GetWindowSize().y; - - ImGuiStyle & style = ImGui::GetStyle(); - ImVec2 plot_size{ - win_width / 2 - style.ItemSpacing.x / 2, - win_height / 2}; - - static std::array cpu_time; - static std::array gpu_time; - static int offset = 0; - - float min_v = 0; - float max_v = 20; - - cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6; - gpu_time[offset] = renderer->get_gpu_time() * 1'000; - offset = (offset + 1) % cpu_time.size(); - - ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64)); - ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBg, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0)); - ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); - - if (ImPlot::BeginPlot(_S("CPU time"), plot_size, ImPlotFlags_CanvasOnly)) + if (ImGui::CollapsingHeader("CPU / GPU stats")) { - auto col = ImPlot::GetColormapColor(0); + imgui_ctx->vibrate_on_hover(); + float win_width = ImGui::GetWindowSize().x; + float win_height = ImGui::GetWindowSize().y; - ImPlot::SetupAxes(nullptr, _S("CPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); - ImPlot::SetupAxesLimits(0, cpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); - ImPlot::SetNextLineStyle(col); - ImPlot::SetNextFillStyle(col, 0.25); - ImPlot::PlotLine(_S("CPU time"), cpu_time.data(), cpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); - ImPlot::EndPlot(); + ImGuiStyle & style = ImGui::GetStyle(); + ImVec2 plot_size{ + win_width / 2 - style.ItemSpacing.x / 2, + win_height / 2}; + + static std::array cpu_time; + static std::array gpu_time; + static int offset = 0; + + float min_v = 0; + float max_v = 20; + + cpu_time[offset] = application::get_cpu_time().count() * 1.0e-6; + gpu_time[offset] = renderer->get_gpu_time() * 1'000; + offset = (offset + 1) % cpu_time.size(); + + ImPlot::PushStyleColor(ImPlotCol_PlotBg, IM_COL32(32, 32, 32, 64)); + ImPlot::PushStyleColor(ImPlotCol_FrameBg, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBg, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgActive, IM_COL32(0, 0, 0, 0)); + ImPlot::PushStyleColor(ImPlotCol_AxisBgHovered, IM_COL32(0, 0, 0, 0)); + + if (ImPlot::BeginPlot(_S("CPU time"), plot_size, ImPlotFlags_CanvasOnly)) + { + auto col = ImPlot::GetColormapColor(0); + + ImPlot::SetupAxes(nullptr, _S("CPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxesLimits(0, cpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); + ImPlot::SetNextLineStyle(col); + ImPlot::SetNextFillStyle(col, 0.25); + ImPlot::PlotLine(_S("CPU time"), cpu_time.data(), cpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + + ImGui::SameLine(); + + if (ImPlot::BeginPlot(_S("GPU time"), plot_size, ImPlotFlags_CanvasOnly)) + { + auto col = ImPlot::GetColormapColor(1); + + ImPlot::SetupAxes(nullptr, _S("GPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); + ImPlot::SetupAxesLimits(0, gpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); + ImPlot::SetNextLineStyle(col); + ImPlot::SetNextFillStyle(col, 0.25); + ImPlot::PlotLine(_S("GPU time"), gpu_time.data(), gpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); + ImPlot::EndPlot(); + } + ImPlot::PopStyleColor(5); } + else + imgui_ctx->vibrate_on_hover(); - ImGui::SameLine(); - - if (ImPlot::BeginPlot(_S("GPU time"), plot_size, ImPlotFlags_CanvasOnly)) + if (ImGui::CollapsingHeader("Renderer stats")) { - auto col = ImPlot::GetColormapColor(1); + imgui_ctx->vibrate_on_hover(); - ImPlot::SetupAxes(nullptr, _S("GPU time [ms]"), ImPlotAxisFlags_NoDecorations, 0); - ImPlot::SetupAxesLimits(0, gpu_time.size() - 1, min_v, max_v, ImGuiCond_Always); - ImPlot::SetNextLineStyle(col); - ImPlot::SetNextFillStyle(col, 0.25); - ImPlot::PlotLine(_S("GPU time"), gpu_time.data(), gpu_time.size(), 1, 0, ImPlotLineFlags_Shaded, offset); - ImPlot::EndPlot(); + const auto & stats = renderer->last_frame_stats(); + + ImGui::Text("Primitives: %zd total, %zd culled", stats.count_primitives, stats.count_culled_primitives); + ImGui::Text("Triangles: %zd total, %zd culled", stats.count_triangles, stats.count_culled_triangles); + + if (ImGui::BeginTable("Node hierarchy", 2, ImGuiTableFlags_None)) + { + gui_debug_node_hierarchy(); + ImGui::EndTable(); + } } - ImPlot::PopStyleColor(5); + else + imgui_ctx->vibrate_on_hover(); - ImGui::PopStyleVar(); + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing } #endif @@ -1132,56 +1222,6 @@ void scenes::lobby::gui_licenses() ImGui::TextUnformatted((const char *)license->data(), (const char *)license->data() + license->size()); } -static bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg) -{ - ImGuiWindow * window = ImGui::GetCurrentWindow(); - if (window->SkipItems) - return false; - - ImGuiContext & g = *GImGui; - const ImGuiStyle & style = g.Style; - const ImGuiID id = window->GetID(label.c_str()); - const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true); - - const ImVec2 pos = window->DC.CursorPos; - - ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); - - const ImRect bb(pos, pos + size); - ImGui::ItemSize(bb, style.FramePadding.y); - if (!ImGui::ItemAdd(bb, id)) - return false; - - bool hovered, held; - bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); - - ImGuiCol_ col; - if ((held && hovered) || active) - col = ImGuiCol_ButtonActive; - else if (hovered) - col = ImGuiCol_ButtonHovered; - else - col = ImGuiCol_Button; - - ImGui::RenderNavHighlight(bb, id); - ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding); - - ImVec2 TextAlign{0, 0.5f}; - ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb); - - IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags); - return pressed; -} - -template -static bool RadioButtonWithoutCheckBox(const std::string & label, T * v, T v_button, ImVec2 size_arg) -{ - const bool pressed = RadioButtonWithoutCheckBox(label, *v == v_button, size_arg); - if (pressed) - *v = v_button; - return pressed; -} - static auto face_weights() { using weights = decltype(wivrn::from_headset::tracking::fb_face2{}.weights); @@ -1609,9 +1649,46 @@ static bool is_gui_visible(imgui_context & ctx, XrTime predicted_display_time) return true; } +void scenes::lobby::update_transfers() +{ + for (auto & [name, transfer]: current_transfers) + { + transfer.first.sync(); + if (transfer.first.get_state() == libcurl::state::done and transfer.second) + transfer.second(transfer.first); + } + + std::erase_if(current_transfers, [](auto & x) { + auto state = x.second.first.get_state(); + return state == libcurl::state::done or state == libcurl::state::reset; + }); +} + +void scenes::lobby::download(const std::string & url, const std::filesystem::path & path, std::function callback) +{ + current_transfers.emplace(url, std::make_pair(curl.download(url, path), std::move(callback))); +} + +void scenes::lobby::download(const std::string & url, std::function callback) +{ + current_transfers.emplace(url, std::make_pair(curl.download(url), std::move(callback))); +} + +libcurl::curl_handle * scenes::lobby::try_get_download_handle(const std::string & url) +{ + auto iter = current_transfers.find(url); + if (iter == current_transfers.end()) + return nullptr; + else + return &iter->second.first; +} + std::vector> scenes::lobby::draw_gui(XrTime predicted_display_time) { imgui_ctx->new_frame(predicted_display_time); + update_transfers(); + update_file_picker(); + ImGuiStyle & style = ImGui::GetStyle(); const float TabWidth = 300; @@ -1683,6 +1760,10 @@ std::vector> scenes::lobby::draw_gui(XrTi gui_post_processing(); break; + case tab::customize: + gui_customize(); + break; + #if WIVRN_CLIENT_DEBUG_MENU case tab::debug: gui_debug(); @@ -1720,28 +1801,31 @@ std::vector> scenes::lobby::draw_gui(XrTi ImGui::BeginChild("Tabs", {TabWidth, ImGui::GetContentRegionMax().y - ImGui::GetWindowContentRegionMin().y}); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(10, 10)); - RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Server list"), ¤t_tab, tab::server_list, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_COMPUTER " " + _("Server list"), current_tab, tab::server_list, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), ¤t_tab, tab::settings, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_GEARS " " + _("Settings"), current_tab, tab::settings, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_WAND_MAGIC_SPARKLES " " + _("Post-processing"), ¤t_tab, tab::post_processing, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_WAND_MAGIC_SPARKLES " " + _("Post-processing"), current_tab, tab::post_processing, {TabWidth, 0}); + imgui_ctx->vibrate_on_hover(); + + RadioButtonWithoutCheckBox(ICON_FA_PANORAMA " " + _("Customize"), current_tab, tab::customize, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); #if WIVRN_CLIENT_DEBUG_MENU - RadioButtonWithoutCheckBox(ICON_FA_BUG_SLASH " " + _("Debug"), ¤t_tab, tab::debug, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_BUG_SLASH " " + _("Debug"), current_tab, tab::debug, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); #endif ImGui::SetCursorPosY(ImGui::GetContentRegionMax().y - 3 * ImGui::GetCurrentContext()->FontSize - 6 * style.FramePadding.y - 2 * style.ItemSpacing.y - style.WindowPadding.y); - RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " " + _("About"), ¤t_tab, tab::about, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_CIRCLE_INFO " " + _("About"), current_tab, tab::about, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_SCALE_BALANCED " " + _("Licenses"), ¤t_tab, tab::licenses, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_SCALE_BALANCED " " + _("Licenses"), current_tab, tab::licenses, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); - RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Exit"), ¤t_tab, tab::exit, {TabWidth, 0}); + RadioButtonWithoutCheckBox(ICON_FA_DOOR_OPEN " " + _("Exit"), current_tab, tab::exit, {TabWidth, 0}); imgui_ctx->vibrate_on_hover(); ImGui::PopStyleVar(); // ImGuiStyleVar_FramePadding diff --git a/client/scenes/lobby_gui_customize.cpp b/client/scenes/lobby_gui_customize.cpp new file mode 100644 index 00000000..7f4f07c5 --- /dev/null +++ b/client/scenes/lobby_gui_customize.cpp @@ -0,0 +1,813 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022-2024 Guillaume Meunier + * Copyright (C) 2022-2024 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 . + */ + +#define IMGUI_DEFINE_MATH_OPERATORS + +#include "lobby.h" + +#include "application.h" +#include "constants.h" +#include "imgui.h" +#include "imgui_internal.h" +#include "imspinner.h" +#include "utils/files.h" +#include "utils/i18n.h" +#include "utils/json_string.h" +#include + +#include "IconsFontAwesome6.h" + +using namespace std::chrono_literals; + +void scenes::lobby::save_environment_json() +{ + std::stringstream ss; + ss << "["; + bool empty = true; + for (const auto & model: local_environments) + { + if (model.builtin) + continue; + + empty = false; + ss << "{\"name\":" << json_string(model.name) + << ",\"author\":" << json_string(model.author) + << ",\"description\":" << json_string(model.description) + << ",\"screenshot\":" << json_string(model.screenshot_url) + << ",\"url\":" << json_string(model.gltf_url) + << ",\"size\":" << model.size + << "},"; + } + if (not empty) + ss.seekp(-1, ss.cur); + ss << "]"; + + utils::write_whole_file(application::get_config_path() / "environments.json", ss.str()); +} + +std::vector scenes::lobby::load_environment_json(const std::string & json) +{ + std::vector models; + + simdjson::dom::parser parser; + simdjson::dom::element root = parser.parse(json); + + if (not root.is_array()) + return models; + + for (simdjson::dom::object i: simdjson::dom::array(root)) + { + environment_model model; + if (auto val = i["name"]; val.is_string()) + model.name = val.get_string().value(); + + if (auto val = i["author"]; val.is_string()) + model.author = val.get_string().value(); + + if (auto val = i["description"]; val.is_string()) + model.description = val.get_string().value(); + + if (auto val = i["screenshot"]; val.is_string()) + model.screenshot_url = val.get_string().value(); + + if (auto val = i["url"]; val.is_string()) + model.gltf_url = val.get_string().value(); + + if (auto val = i["size"]; val.is_number()) + model.size = val.get_int64(); + + model.builtin = false; + model.local_screenshot_path = application::get_config_path() / "environments" / (model.name + ".png"); + model.local_gltf_path = application::get_config_path() / "environments" / (model.name + ".glb"); + + models.push_back(std::move(model)); + } + + std::ranges::sort(models, std::less{}); + + return models; +} + +void scenes::lobby::download_environment(const environment_model & model, bool use_after_downloading) +{ + spdlog::info("Downloading {}", model.gltf_url); + std::filesystem::create_directory(model.local_gltf_path.parent_path()); + + download(model.gltf_url, model.local_gltf_path, [this, m = model, use_after_downloading](libcurl::curl_handle & handle) { + std::filesystem::create_directory(m.local_screenshot_path.parent_path()); + utils::write_whole_file(m.local_screenshot_path, m.screenshot_png); + + local_environments.push_back(m); + std::ranges::sort(local_environments, std::less{}); + save_environment_json(); + + if (use_after_downloading) + use_environment(m); + }); +} + +void scenes::lobby::use_environment(const environment_model & model) +{ + if (model.local_gltf_path == "") + { + auto & config = application::get_config(); + config.passthrough_enabled = true; + setup_passthrough(); + config.save(); + } + else + { + load_environment_status = ""; + future_environment = utils::async>, float>( + [this](auto token, std::filesystem::path path) { + return std::make_pair( + path, + load_gltf(path, [&](float progress) { + token.set_progress(progress); + })); + }, + model.local_gltf_path); + } +} + +void scenes::lobby::update_file_picker() +{ + if (not lobby_file_picker_future.valid()) + return; + + lobby_file_picker.display(); + + if (lobby_file_picker_future.wait_for(0s) != std::future_status::ready) + return; + + try + { + load_environment_status = ""; + future_environment = utils::async>, float>( + [this](auto token, file_picker_result environment) { + auto local_path = application::get_cache_path() / "local.glb"; + + utils::write_whole_file(local_path, (std::span)environment.file); + + // TODO remove only local.glb from cache + clear_gltf_cache(); + + return std::make_pair( + local_path, + load_gltf(local_path, [&](float progress) { + token.set_progress(progress); + })); + }, + lobby_file_picker_future.get()); + } + catch (std::exception & e) + { + spdlog::warn("Cannot load local environment: {}", e.what()); + } +} + +void scenes::lobby::delete_environment(const environment_model & to_be_deleted) +{ + std::error_code ec; + std::filesystem::remove(to_be_deleted.local_gltf_path, ec); // Ignore errors + std::filesystem::remove(to_be_deleted.local_screenshot_path, ec); // Ignore errors + unload_gltf(to_be_deleted.local_gltf_path); + clear_texture_cache(); + + if (std::erase_if(local_environments, [&](auto & model) { return model.local_gltf_path == to_be_deleted.local_gltf_path; })) + save_environment_json(); +} + +void scenes::lobby::download_environment_list() +{ + downloadable_environment_list_status = ""; + downloadable_environments.clear(); + + if (not try_get_download_handle(WIVRN_ENVIRONMENTS_URL)) + { + spdlog::info("Downloading {}", WIVRN_ENVIRONMENTS_URL); + download(WIVRN_ENVIRONMENTS_URL, [this](libcurl::curl_handle & handle) { + try + { + // TODO cache in filesystem? + downloadable_environments = load_environment_json(handle.get_response()); + } + catch (std::exception & e) + { + spdlog::error("Cannot load custom environments: {}", e.what()); + downloadable_environment_list_status = fmt::format("Cannot load custom environments: {}", e.what()); + } + }); + } +} + +scenes::lobby::environment_item_action scenes::lobby::environment_item(environment_model & model, bool download_screenshot) +{ + environment_item_action action = environment_item_action::none; + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const ImGuiStyle & style = ImGui::GetStyle(); + bool local = std::ranges::contains(local_environments, model.name, &environment_model::name); + + static std::unordered_map expanded_height; + + float width = ImGui::GetWindowSize().x - ImGui::GetCurrentWindow()->ScrollbarSizes.x - 2 * ImGui::GetCurrentWindow()->WindowPadding.x; + ImVec2 screenshot_size{256, 256}; + ImVec2 default_selectable_size{ + width, + screenshot_size.y + 2 * style.FramePadding.y // Screenshot size including padding + // + style.ItemSpacing.y // Spacing + // + ImGui::GetFontSize() + 2 * style.FramePadding.y // Progress bar height + }; + ImVec2 selectable_size = default_selectable_size; + + bool expanded = false; + if (auto iter = expanded_height.find(model.gltf_url); iter != expanded_height.end()) + { + selectable_size.y = std::max(selectable_size.y, iter->second); + expanded = true; + } + + ImTextureID screenshot = model.screenshot; + if (ImRect{window->DC.CursorPos, window->DC.CursorPos + selectable_size}.Overlaps(window->ClipRect)) + { + if (screenshot == 0) + { + if (download_screenshot) + { + if (model.screenshot_url != "" and not try_get_download_handle(model.screenshot_url)) + { + spdlog::info("Downloading {}", model.screenshot_url); + + download(model.screenshot_url, + [this, url = model.screenshot_url](libcurl::curl_handle & handle) { + auto png = handle.get_response_bytes(); + auto screenshot = imgui_ctx->load_texture(png); + + for (auto & model: downloadable_environments) + { + if (model.screenshot_url == url) + { + model.screenshot = screenshot; + model.screenshot_png = std::vector{png.begin(), png.end()}; + } + } + }); + } + } + else if (model.local_screenshot_path != "" and std::filesystem::exists(model.local_screenshot_path)) + { + try + { + spdlog::info("Loading {}", model.local_screenshot_path.native()); + screenshot = model.screenshot = imgui_ctx->load_texture(utils::mapped_file{model.local_screenshot_path}); + } + catch (std::exception & e) + { + spdlog::warn("Cannot load screenshot {}: {}", model.local_screenshot_path.native(), e.what()); + std::error_code ec; + std::filesystem::remove(model.local_screenshot_path, ec); // Ignore errors + model.local_screenshot_path = ""; // Avoid subsequent loading errors + } + } + } + } + + auto backup_cursor = ImGui::GetCursorScreenPos(); + const auto & config = application::get_config(); + bool selected = (config.passthrough_enabled and model.local_gltf_path == "") or + (not config.passthrough_enabled and config.environment_model == model.local_gltf_path); + + ImGui::SetNextItemAllowOverlap(); + // Use ImGuiSelectableFlags_AllowDoubleClick to have ImGuiButtonFlags_PressedOnClickRelease in ImGui::Selectable + if (ImGui::Selectable(("##" + model.gltf_url).c_str(), &selected, ImGuiSelectableFlags_AllowDoubleClick, selectable_size)) + { + if (local) + action = environment_item_action::use_model; + else + action = environment_item_action::download_model; + } + imgui_ctx->vibrate_on_hover(); + auto end_cursor = ImGui::GetCursorScreenPos(); + + // Remove the height of the progress bar if a transfer is in progress + float text_clip_height = selectable_size.y + style.FramePadding.y; + if (auto handle = try_get_download_handle(model.gltf_url); handle and handle->get_state() == libcurl::state::transferring) + text_clip_height -= ImGui::GetFontSize() + 2 * style.FramePadding.y + style.ItemSpacing.y; + + // Display the screenshot + ImGui::SetCursorScreenPos(backup_cursor + ImVec2(style.FramePadding.x, 0)); + ImGui::Image(screenshot, screenshot_size); + + ImGui::PushClipRect(backup_cursor, backup_cursor + ImVec2(selectable_size.x, text_clip_height), true); + float indent = screenshot_size.x + style.FramePadding.x + 2 * style.ImageBorderSize + style.ItemSpacing.x; + + // Display the text + std::pair text_name; + std::pair text_author; + std::pair text_description; + std::pair text_filesize; + + text_name.first = model.builtin ? _(model.name.c_str()) : model.name; + if (model.author != "") + text_author.first = fmt::format(_F("Author: {}"), model.author); + if (model.description != "") + text_description.first = model.description; + if (not model.builtin) + text_filesize.first = fmt::format(_F("Size: {:.1f} MB"), model.size * 1.0e-6); + + const float wrap_width = selectable_size.x - indent - style.FramePadding.x; + + // clang-format off + text_name.second = ImGui::CalcTextSize(text_name.first.data(), text_name.first.data() + text_name.first.size(), false, wrap_width); + text_author.second = ImGui::CalcTextSize(text_author.first.data(), text_author.first.data() + text_author.first.size(), false, wrap_width); + text_description.second = ImGui::CalcTextSize(text_description.first.data(), text_description.first.data() + text_description.first.size(), false, wrap_width); + text_filesize.second = ImGui::CalcTextSize(text_filesize.first.data(), text_filesize.first.data() + text_filesize.first.size(), false, wrap_width); + // clang-format on + + ImGui::SetCursorScreenPos(backup_cursor); + + ImVec2 text_pos = backup_cursor + ImVec2(indent, 0); + float text_height = 0; + + ImGui::RenderTextWrapped(text_pos, text_name.first.data(), text_name.first.data() + text_name.first.size(), wrap_width); + text_height += text_name.second.y + style.ItemSpacing.y; + + if (text_author.first != "") + { + ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_author.first.data(), text_author.first.data() + text_author.first.size(), wrap_width); + text_height += text_author.second.y + style.ItemSpacing.y; + } + + if (text_description.first != "") + { + ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_description.first.data(), text_description.first.data() + text_description.first.size(), wrap_width); + text_height += text_description.second.y + style.ItemSpacing.y; + } + + if (text_filesize.first != "") + { + ImGui::RenderTextWrapped(text_pos + ImVec2(0, text_height), text_filesize.first.data(), text_filesize.first.data() + text_filesize.first.size(), wrap_width); + text_height += text_filesize.second.y + style.ItemSpacing.y; + } + + ImGui::PopClipRect(); + + // Display the expand/collapse button + if (text_height > default_selectable_size.y - 2 * style.FramePadding.y) + { + const char * button_text = expanded ? ICON_FA_CHEVRON_UP : ICON_FA_CHEVRON_DOWN; + auto expand_size = ImGui::CalcTextSize(button_text) + style.FramePadding * 2.0f; + float radius = std::max(expand_size.x, expand_size.y) / 2; + + ImGui::SetCursorScreenPos(ImVec2( + backup_cursor.x + selectable_size.x / 2 - radius, + backup_cursor.y + selectable_size.y + style.FramePadding.y - radius)); + + // Triple hash so that the button text is not used to compute the button ID and + // avoid vibrating the controller when the text changes + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, radius); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); + if (ImGui::Button((button_text + ("###expand-" + model.gltf_url)).c_str(), ImVec2(radius * 2, radius * 2))) + { + if (expanded) + expanded_height.erase(model.gltf_url); + else + expanded_height[model.gltf_url] = text_height + 2 * style.FramePadding.y; + } + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(); // ImGuiStyleVar_FrameRounding + } + + // Display the delete button + if (local and not model.builtin) + { + auto delete_size = ImGui::CalcTextSize(ICON_FA_TRASH) + style.FramePadding * 2; + ImGui::SetCursorScreenPos(ImVec2( + backup_cursor.x + width - style.FramePadding.x - delete_size.x, + backup_cursor.y)); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); + if (ImGui::Button((ICON_FA_TRASH "##delete-" + model.name).c_str())) + action = environment_item_action::delete_model; + if (ImGui::IsItemHovered()) + imgui_ctx->tooltip(_("Delete this model")); + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(3); + } + // Display the download progress + else if (auto handle = try_get_download_handle(model.gltf_url)) + { + switch (handle->get_state()) + { + case libcurl::state::transferring: { + ImVec2 cancel_size = ImGui::CalcTextSize(ICON_FA_STOP) + style.FramePadding * 2; + + ImGui::SetCursorScreenPos(ImVec2( + backup_cursor.x + screenshot_size.x + style.FramePadding.x + style.ItemSpacing.x, + backup_cursor.y + selectable_size.y - (ImGui::GetFontSize() + 2 * style.FramePadding.y))); + + float progress_width = width - cancel_size.x - screenshot_size.x - 2 * style.FramePadding.x - 2 * style.ItemSpacing.x; + + if (handle->get_content_length() > 0) + ImGui::ProgressBar(handle->get_progress() / (float)handle->get_content_length(), {progress_width, 0}); + else + ImGui::ProgressBar(-ImGui::GetTime(), {progress_width, 0}); // Indeterminate progress bar + + ImGui::SameLine(); + if (ImGui::Button((ICON_FA_STOP "##" + model.name).c_str())) + handle->cancel(); + + imgui_ctx->vibrate_on_hover(); + break; + } + + case libcurl::state::error: + if (handle->get_curl_code() == CURLE_HTTP_RETURNED_ERROR) + { + spdlog::error("HTTP error {} when downloading {}", handle->get_response_code(), handle->get_url()); + load_environment_status = fmt::format( + _F("HTTP error {} when downloading {}"), + handle->get_response_code(), + handle->get_url()); + } + else + { + spdlog::error("Curl error when downloading {}: {}", handle->get_url(), curl_easy_strerror(handle->get_curl_code())); + load_environment_status = fmt::format( + _F("Curl error when downloading {}\n{}: {}"), + handle->get_url(), + magic_enum::enum_name(handle->get_curl_code()), + curl_easy_strerror(handle->get_curl_code())); + } + + handle->reset(); + break; + + case libcurl::state::cancelled: + handle->reset(); + break; + + case libcurl::state::cancelling: + case libcurl::state::reset: + case libcurl::state::done: + break; + } + } + + ImGui::SetCursorScreenPos(end_cursor); + ImGui::Dummy({}); + return action; +} + +void scenes::lobby::environment_list(std::vector & models, bool download_screenshot) +{ + for (auto & model: models) + { + ImGui::BeginDisabled(model.local_gltf_path == "" and system.passthrough_supported() == xr::passthrough_type::none); + switch (environment_item(model, download_screenshot)) + { + case environment_item_action::none: + break; + + case environment_item_action::download_model: + download_environment(model, true); + break; + + case environment_item_action::use_model: + use_environment(model); + break; + + case environment_item_action::delete_model: + ImGui::OpenPopup("confirm delete model"); + environment_to_be_deleted = &model; + break; + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) and (ImGui::GetItemFlags() & ImGuiItemFlags_Disabled)) + imgui_ctx->tooltip(_("This feature is not supported by your headset")); + ImGui::EndDisabled(); + } + + const auto & popup_layer = imgui_ctx->layers()[1]; + const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2; + ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size); + if (ImGui::BeginPopupModal("confirm delete model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text(_S("Really delete %s?"), environment_to_be_deleted->name.c_str()); + + const auto & style = ImGui::GetStyle(); + auto cancel_text = _("Cancel"); + auto delete_text = _("Delete"); + auto cancel_size = ImGui::CalcTextSize(cancel_text.c_str()) + style.FramePadding * 2.0f; + auto delete_size = ImGui::CalcTextSize(delete_text.c_str()) + style.FramePadding * 2.0f; + + ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - cancel_size.x - style.ItemSpacing.x - delete_size.x); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); + if (ImGui::Button(delete_text.c_str())) + { + delete_environment(*environment_to_be_deleted); + environment_to_be_deleted = nullptr; + ImGui::CloseCurrentPopup(); + } + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(3); + + ImGui::SameLine(); + if (ImGui::Button(cancel_text.c_str())) + { + environment_to_be_deleted = nullptr; + ImGui::CloseCurrentPopup(); + } + imgui_ctx->vibrate_on_hover(); + + ImGui::EndPopup(); + } + ImGui::PopStyleVar(3); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize +} + +void scenes::lobby::popup_load_environment() +{ + if (future_environment.valid() or load_environment_status != "") + { + if (not ImGui::IsPopupOpen("loading environment model")) + ImGui::OpenPopup("loading environment model"); + + const auto & popup_layer = imgui_ctx->layers()[1]; + const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2; + ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size); + if (ImGui::BeginPopupModal("loading environment model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) + { + if (future_environment.valid()) + { + if (future_environment.poll() == utils::future_status::ready) + { + try + { + load_environment_status = ""; + auto [gltf_path, env] = future_environment.get(); + ImGui::CloseCurrentPopup(); + + // Keep the current lobby position / orientation + auto & old_lobby_node = world.get(lobby_entity); + auto position = old_lobby_node.position; + auto orientation = old_lobby_node.orientation; + + remove(lobby_entity); + auto [new_lobby_entity, new_lobby_node] = add_gltf(env, layer_lobby); + new_lobby_node.position = position; + new_lobby_node.orientation = orientation; + lobby_entity = new_lobby_entity; + + auto & config = application::get_config(); + + config.passthrough_enabled = false; + config.environment_model = gltf_path; + setup_passthrough(); + config.save(); + } + catch (std::exception & e) + { + load_environment_status = fmt::format(_F("Cannot load environment: {}"), e.what()); + spdlog::error("Cannot load environment: {}", e.what()); + } + + future_environment.reset(); + } + else + { + ImGui::Text("%s", _S("Loading environment")); + ImGui::ProgressBar(future_environment.get_progress()); + } + } + + if (load_environment_status != "") + { + ImGui::Text("%s", load_environment_status.c_str()); + if (ImGui::Button(_S("Close"))) + { + load_environment_status = ""; + ImGui::CloseCurrentPopup(); + } + imgui_ctx->vibrate_on_hover(); + } + + ImGui::EndPopup(); + } + ImGui::PopStyleVar(3); // ImGuiStyleVar_WindowPadding, ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize + } +} + +libcurl::curl_handle * scenes::lobby::parse_environment_list() +{ + auto index_transfer = try_get_download_handle(WIVRN_ENVIRONMENTS_URL); + if (index_transfer) + switch (index_transfer->get_state()) + { + case libcurl::state::cancelling: + case libcurl::state::done: + case libcurl::state::reset: + case libcurl::state::transferring: + break; + + case libcurl::state::cancelled: + index_transfer->reset(); + break; + + case libcurl::state::error: + if (index_transfer->get_curl_code() == CURLE_HTTP_RETURNED_ERROR) + { + spdlog::error("HTTP error {} when downloading index.json", index_transfer->get_response_code()); + downloadable_environment_list_status = fmt::format( + _F("HTTP error {} when downloading index.json"), + index_transfer->get_response_code()); + } + else + { + spdlog::error("Curl error when downloading index.json: {}", curl_easy_strerror(index_transfer->get_curl_code())); + downloadable_environment_list_status = fmt::format( + _F("Curl error {} when downloading index.json\n{}"), + magic_enum::enum_name(index_transfer->get_curl_code()), + curl_easy_strerror(index_transfer->get_curl_code())); + } + + index_transfer->reset(); + break; + } + + return index_transfer; +} + +void scenes::lobby::gui_customize() +{ + auto & config = application::get_config(); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {20, 20}); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {10, 10}); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0}); + ImGui::BeginChild("environment list", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, ImGui::GetFontSize() + 80)); + environment_list(local_environments, false); + ScrollWhenDragging(); + ImGui::EndChild(); + ImGui::PopStyleVar(); + + if (ImGui::Button(_S("Download more environments"))) + { + download_environment_list(); + ImGui::OpenPopup("download environment model"); + } + imgui_ctx->vibrate_on_hover(); + + ImGui::SameLine(); + if (ImGui::Button(_S("Open local glTF model"))) + lobby_file_picker_future = lobby_file_picker.open(); + imgui_ctx->vibrate_on_hover(); + + const auto & popup_layer = imgui_ctx->layers()[1]; + const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2; + ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowSize({1200, 900}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size); + if (ImGui::BeginPopupModal("download environment model", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) + { + auto close = _("Close"); + auto close_size = ImGui::CalcTextSize(close.c_str()); + + ImGui::BeginChild("Main", ImGui::GetWindowSize() - ImGui::GetCursorPos() - ImVec2(0, close_size.y + 80) /*, ImGuiChildFlags_AlwaysUseWindowPadding*/); + + auto index_transfer = parse_environment_list(); + switch (index_transfer ? index_transfer->get_state() : libcurl::state::reset) + { + case libcurl::state::cancelling: + case libcurl::state::transferring: + case libcurl::state::cancelled: + ImGui::SetCursorPos(ImGui::GetWindowSize() / 2 - ImVec2{200, 200} - ImGui::GetStyle().FramePadding); + ImSpinner::SpinnerAng("index download spinner", + 200, // Radius + 40, // Thickness + ImColor{1.f, 1.f, 1.f, 1.f}, // Colour + ImColor{1.f, 1.f, 1.f, 0.f}, // Background + 6, // Velocity + 0.75f * 2 * M_PI // Angle + ); + + break; + + case libcurl::state::error: // Should not happen, parse_environment_list resets the status in case of error + case libcurl::state::done: // Should not happen, parse_environment_list resets the status when done + assert(false); + break; + + case libcurl::state::reset: + if (downloadable_environment_list_status == "") + { + environment_list(downloadable_environments, true); + } + else + { + CenterTextHV(downloadable_environment_list_status); + + ImGui::Dummy({0, constants::gui::font_size_large}); + ImGui::PushFont(nullptr, constants::gui::font_size_large); + ImGui::PushStyleColor(ImGuiCol_Button, 0); + ImGui::SetCursorPosX((ImGui::GetWindowSize().x - ImGui::CalcTextSize(ICON_FA_ROTATE).x) / 2 - ImGui::GetStyle().FramePadding.x); + if (ImGui::Button(ICON_FA_ROTATE)) + download_environment_list(); + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(); // ImGuiCol_Button + ImGui::PopFont(); + } + } + + ScrollWhenDragging(); + ImGui::EndChild(); + + ImGui::SetCursorPos(ImGui::GetWindowSize() - close_size - ImVec2{50, 50}); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.8f, 0.2f, 0.2f, 0.40f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.8f, 0.2f, 0.2f, 1.00f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(1.0f, 0.1f, 0.1f, 1.00f)); + if (ImGui::Button(_S("Close"))) + ImGui::CloseCurrentPopup(); + imgui_ctx->vibrate_on_hover(); + ImGui::PopStyleColor(3); // ImGuiCol_Button, ImGuiCol_ButtonHovered, ImGuiCol_ButtonActive + + popup_load_environment(); + + ImGui::EndPopup(); + } + else + { + popup_load_environment(); + } + ImGui::PopStyleVar(2); // ImGuiStyleVar_WindowRounding, ImGuiStyleVar_WindowBorderSize + + // if (ImGui::RadioButton(_S("Custom environment"), not config.passthrough_enabled and config.environment_model_uri != "")) + // lobby_file_picker_future = lobby_file_picker.open(); + // imgui_ctx->vibrate_on_hover(); + // + // try + // { + // lobby_file_picker.display(); + // + // if (lobby_file_picker_future.valid() and lobby_file_picker_future.wait_for(0s) == std::future_status::ready) + // { + // auto environment = lobby_file_picker_future.get(); + // + // // TODO load asynchronously + // // TODO allow caching + // spdlog::info("Loading new environment from {}", environment.path.native()); + // auto t0 = std::chrono::steady_clock::now(); + // auto new_lobby = load_gltf(environment.file); + // auto dt = std::chrono::steady_clock::now() - t0; + // spdlog::info("Loaded successfully in {}", dt); + // + // remove(lobby_entity); + // lobby_entity = add_gltf(new_lobby, layer_lobby).first; + // + // config.passthrough_enabled = false; + // setup_passthrough(); + // } + // } + // catch (std::exception & e) + // { + // spdlog::warn("Cannot load environment: {}", e.what()); + // } + + // auto & lobby_node = world.get(lobby_entity); + // float scale = lobby_node.scale.x; + // if (ImGui::SliderFloat("Environment scale", &scale, 0.1, 10, "%.3f", ImGuiSliderFlags_Logarithmic)) + // lobby_node.scale = glm::vec3{scale, scale, scale}; + // imgui_ctx->vibrate_on_hover(); + // + // ImGui::SliderFloat("Environment elevation", &lobby_node.position.y, -3, 3, "%.3f"); + // imgui_ctx->vibrate_on_hover(); + + ImGui::PopStyleVar(2); // ImGuiStyleVar_ItemSpacing, ImGuiStyleVar_FramePadding +} diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 21c22ad2..2bc0a63c 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -180,7 +180,7 @@ public: std::unique_ptr session, float guessed_fps, std::string server_name, - scene & parent_scene); + scene & parent_scene); void render(const XrFrameState &) override; void on_focused() override; diff --git a/client/scenes/stream_gui.cpp b/client/scenes/stream_gui.cpp index 8260d775..39dba21b 100644 --- a/client/scenes/stream_gui.cpp +++ b/client/scenes/stream_gui.cpp @@ -160,57 +160,6 @@ void scenes::stream::accumulate_metrics(XrTime predicted_display_time, const std metrics_offset = (metrics_offset + 1) % global_metrics.size(); } -// TODO move in separate file, factorize with lobby_gui.cpp -static bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg) -{ - ImGuiWindow * window = ImGui::GetCurrentWindow(); - if (window->SkipItems) - return false; - - ImGuiContext & g = *GImGui; - const ImGuiStyle & style = g.Style; - const ImGuiID id = window->GetID(label.c_str()); - const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true); - - const ImVec2 pos = window->DC.CursorPos; - - ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); - - const ImRect bb(pos, pos + size); - ImGui::ItemSize(bb, style.FramePadding.y); - if (!ImGui::ItemAdd(bb, id)) - return false; - - bool hovered, held; - bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); - - ImGuiCol_ col; - if ((held && hovered) || active) - col = ImGuiCol_ButtonActive; - else if (hovered) - col = ImGuiCol_ButtonHovered; - else - col = ImGuiCol_Button; - - ImGui::RenderNavHighlight(bb, id); - ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding); - - ImVec2 TextAlign{0, 0.5f}; - ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb); - - IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags); - return pressed; -} - -template -static bool RadioButtonWithoutCheckBox(const std::string & label, T & v, U v_button, ImVec2 size_arg) -{ - const bool pressed = RadioButtonWithoutCheckBox(label, v == v_button, size_arg); - if (pressed) - v = v_button; - return pressed; -} - void scenes::stream::gui_performance_metrics() { const ImGuiStyle & style = ImGui::GetStyle(); diff --git a/client/shaders/lit.vert.glsl b/client/shaders/lit.vert.glsl index b72c97c4..bacbebaa 100644 --- a/client/shaders/lit.vert.glsl +++ b/client/shaders/lit.vert.glsl @@ -34,7 +34,7 @@ layout(location = 5) in vec4 in_color; out gl_PerVertex { vec4 gl_Position; - // float gl_ClipDistance[nb_clipping]; + float gl_ClipDistance[nb_clipping]; }; void main() @@ -57,8 +57,8 @@ void main() frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0); light_pos = scene.view[gl_ViewIndex] * scene.light_position; - // for(int i = 0; i < nb_clipping; i++) - // { - // gl_ClipDistance[i] = dot(mesh.clipping_plane[i], mesh.model * vec4(in_position, 1.0)); - // } + 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 f541a25a..8d87c566 100644 --- a/client/shaders/lit_skinned.vert.glsl +++ b/client/shaders/lit_skinned.vert.glsl @@ -36,7 +36,7 @@ layout(location = 7) in vec4 in_weights; out gl_PerVertex { vec4 gl_Position; - // float gl_ClipDistance[nb_clipping]; + float gl_ClipDistance[nb_clipping]; }; void main() @@ -65,4 +65,9 @@ void main() frag_pos = mesh.modelview[gl_ViewIndex] * vec4(in_position, 1.0); light_pos = scene.view[gl_ViewIndex] * scene.light_position; + + 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/utils/async.h b/client/utils/async.h index de966331..914ae17f 100644 --- a/client/utils/async.h +++ b/client/utils/async.h @@ -19,6 +19,7 @@ #pragma once #include +#include #include #include #include @@ -177,7 +178,7 @@ struct async_token async_token & operator=(const async_token &) = default; async_token & operator=(async_token &&) = default; - void set_result(Result && r) + void set_result(Result r) { assert(shared_state); std::unique_lock _{shared_state->lock}; @@ -185,7 +186,7 @@ struct async_token shared_state->cv.notify_all(); } - void set_exception(std::exception_ptr && e) + void set_exception(std::exception_ptr e) { assert(shared_state); std::unique_lock _{shared_state->lock}; @@ -194,7 +195,7 @@ struct async_token } public: - void set_progress(Progress && p) + void set_progress(Progress p) { assert(shared_state); std::unique_lock _{shared_state->lock}; @@ -215,17 +216,19 @@ future async(F && f, Args &&... args) fut.shared_state = std::make_shared::state>(); - fut.shared_state->thread = std::thread([f, args...](auto token) { - try - { - token.set_result(std::invoke(f, token, args...)); - } - catch (...) - { - token.set_exception(std::current_exception()); - } - }, - async_token(fut.shared_state)); + fut.shared_state->thread = std::thread( + [f](async_token token, Args &&... args) { + try + { + token.set_result(std::invoke(f, token, std::forward(args)...)); + } + catch (...) + { + token.set_exception(std::current_exception()); + } + }, + async_token(fut.shared_state), + std::forward(args)...); return fut; } diff --git a/client/utils/cache.h b/client/utils/cache.h index 8fa7c312..75a4e8f1 100644 --- a/client/utils/cache.h +++ b/client/utils/cache.h @@ -28,14 +28,14 @@ namespace utils template class cache { - Loader loader; + Loader loader_; thread_safe>> entries; public: template cache(Args &&... args) : - loader(std::forward(args)...) + loader_(std::forward(args)...) {} template @@ -48,13 +48,13 @@ public: if (iter != _->end()) return iter->second; - return _->emplace(key, loader(std::forward(args)...)).first->second; + return _->emplace(key, loader_(std::forward(args)...)).first->second; } template std::shared_ptr load_uncached(Args &&... args) { - return loader(std::forward(args)...); + return loader_(std::forward(args)...); } void clear() @@ -68,5 +68,15 @@ public: auto _ = entries.lock(); _->erase(key); } + + Loader & loader() + { + return loader_; + } + + const Loader & loader() const + { + return loader_; + } }; } // namespace utils diff --git a/common/utils/thread_safe.h b/common/utils/thread_safe.h index 0e925bfe..5fa8a513 100644 --- a/common/utils/thread_safe.h +++ b/common/utils/thread_safe.h @@ -72,7 +72,7 @@ public: value(std::forward(args)...) {} - locked lock() + [[nodiscard]] locked lock() { return locked(value, mutex); } diff --git a/common/wivrn_config.h.in b/common/wivrn_config.h.in index f51b78f8..bed3c486 100644 --- a/common/wivrn_config.h.in +++ b/common/wivrn_config.h.in @@ -45,3 +45,5 @@ static const int default_port = 9757; #define WIVRN_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@" #define OVR_COMPAT_SEARCH_PATH "@OVR_COMPAT_SEARCH_PATH@" + +#define WIVRN_ENVIRONMENTS_URL "@WIVRN_ENVIRONMENTS_URL@" diff --git a/tools/check_po.py b/tools/check_po.py index 3f2109cd..3878b71a 100755 --- a/tools/check_po.py +++ b/tools/check_po.py @@ -56,6 +56,7 @@ if __name__ == "__main__": "--keyword=_S:1,1t", "--keyword=_cS:1c,2,2t", "--keyword=_F:1,1t", + "--keyword=gettext_noop:1,1t", "--output", client_pot, "--package-name=WiVRn", ] + sorted(list_files(os.path.join(root, "client"), ".cpp")) diff --git a/tools/update_messages.sh b/tools/update_messages.sh index de013aeb..f764b215 100755 --- a/tools/update_messages.sh +++ b/tools/update_messages.sh @@ -11,6 +11,7 @@ xgettext \ --keyword=_S:1,1t \ --keyword=_cS:1c,2,2t \ --keyword=_F:1,1t \ + --keyword=gettext_noop:1,1t \ --output=$WIVRN_CLIENT_POT \ --package-name=WiVRn \ $(find client/ -name "*.cpp" | sort)