From 8dbd47c859a1be3bcb77dc9592d8280968c681fa Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Sat, 20 Jan 2024 12:23:04 +0100 Subject: [PATCH] GUI demo --- assets/imgui.gltf | 150 ++++++++++++ client/CMakeLists.txt | 12 +- client/application.h | 31 +++ client/render/imgui_impl.cpp | 399 ++++++++++++++++++++++++++++++++ client/render/imgui_impl.h | 110 +++++++++ client/render/scene_data.cpp | 6 +- client/render/scene_data.h | 21 ++ client/scenes/input_profile.cpp | 31 +-- client/scenes/lobby.cpp | 52 +++++ client/scenes/lobby.h | 27 +-- client/utils/fmt_glm.h | 17 ++ client/xr/instance.cpp | 1 - 12 files changed, 802 insertions(+), 55 deletions(-) create mode 100644 assets/imgui.gltf create mode 100644 client/render/imgui_impl.cpp create mode 100644 client/render/imgui_impl.h diff --git a/assets/imgui.gltf b/assets/imgui.gltf new file mode 100644 index 00000000..1255aa32 --- /dev/null +++ b/assets/imgui.gltf @@ -0,0 +1,150 @@ +{ + "accessors": [ + { + "bufferView": 0, + "byteOffset": 0, + "componentType": 5123, + "count": 6, + "type": "SCALAR", + "max": [ + 5 + ], + "min": [ + 0 + ] + }, + { + "bufferView": 1, + "byteOffset": 0, + "componentType": 5126, + "count": 6, + "type": "VEC3", + "max": [ + 0.5, + 0.5, + 0 + ], + "min": [ + -0.5, + -0.5, + 0 + ], + "name": "POSITION" + }, + { + "bufferView": 1, + "byteOffset": 12, + "componentType": 5126, + "count": 6, + "type": "VEC2", + "max": [ + 1, + 1 + ], + "min": [ + 0, + 0 + ], + "name": "TEXCOORD_0" + }, + { + "bufferView": 1, + "byteOffset": 20, + "componentType": 5126, + "count": 6, + "type": "VEC3", + "max": [ + 0, + 0, + 1.0000044107437134 + ], + "min": [ + 0, + 0, + 1.0000044107437134 + ], + "name": "NORMAL" + } + ], + "asset": { + "generator": "Aspose.3D 23.12.0", + "version": "2.0" + }, + "buffers": [ + { + "uri": "data:application/octet-stream;base64,AAABAAIAAwAEAAUAAAAAAAAAAL8AAAC/AAAAAAAAAAAAAIA/AAAAAAAAAAAlAIA/AAAAPwAAAL8AAAAAAACAPwAAgD8AAAAAAAAAACUAgD8AAAC/AAAAPwAAAAAAAAAAAAAAAAAAAAAAAAAAJQCAPwAAAD8AAAA/AAAAAAAAgD8AAAAAAAAAAAAAAAAlAIA/AAAAvwAAAD8AAAAAAAAAAAAAAAAAAAAAAAAAACUAgD8AAAA/AAAAvwAAAAAAAIA/AACAPwAAAAAAAAAAJQCAPwAAAAA=", + "byteLength": 212 + } + ], + "images" : [ + { + "uri": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQAAAAA3bvkkAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAAB3YoTpAAAAAd0SU1FB+gBExMyDyqgtkcAAAAKSURBVAjXY2gAAACCAIHdQ2r0AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDI0LTAxLTE5VDE5OjUwOjE1KzAwOjAwKF3Y0gAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyNC0wMS0xOVQxOTo1MDoxNSswMDowMFkAYG4AAAAodEVYdGRhdGU6dGltZXN0YW1wADIwMjQtMDEtMTlUMTk6NTA6MTUrMDA6MDAOFUGxAAAAAElFTkSuQmCC" + } + ], + "bufferViews": [ + { + "buffer": 0, + "byteOffset": 0, + "byteLength": 12, + "target": 34963 + }, + { + "buffer": 0, + "byteOffset": 16, + "byteLength": 192, + "byteStride": 32, + "target": 34962 + } + ], + "meshes": [ + { + "primitives": [ + { + "attributes": { + "POSITION": 1, + "TEXCOORD_0": 2, + "NORMAL": 3 + }, + "indices": 0, + "mode": 4, + "material": 0 + } + ], + "name": "" + } + ], + "samplers" : [ + {} + ], + "textures" : [ + { + "sampler" : 0, + "source" : 0 + } + ], + "materials" : [ + { + "name" : "imgui", + "pbrMetallicRoughness" : { + "baseColorTexture" : { + "index" : 0 + } + } + } + ], + "nodes": [ + { + "mesh": 0, + "name": "imgui", + "translation": [0, 1, -1.5] + } + ], + "scene": 0, + "scenes": [ + { + "nodes": [ + 0 + ] + } + ] +} diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 361443d5..98185521 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -9,10 +9,17 @@ add_library(imgui OBJECT ${imgui_SOURCE_DIR}/imgui_draw.cpp ${imgui_SOURCE_DIR}/imgui_tables.cpp ${imgui_SOURCE_DIR}/imgui_widgets.cpp + ${imgui_SOURCE_DIR}/imgui_demo.cpp + ${imgui_SOURCE_DIR}/misc/freetype/imgui_freetype.cpp ${imgui_SOURCE_DIR}/backends/imgui_impl_vulkan.cpp ) target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR}) +target_compile_definitions(imgui PUBLIC IMGUI_USE_WCHAR32) +target_compile_definitions(imgui PUBLIC IMGUI_ENABLE_FREETYPE) +target_compile_definitions(imgui PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS) +# target_compile_definitions(imgui PUBLIC IMGUI_ENABLE_FREETYPE_LUNASVG) +target_link_libraries(imgui PUBLIC FreetypeHarfbuzz) add_library(stb INTERFACE) target_include_directories(stb INTERFACE ${stb_SOURCE_DIR}) @@ -76,8 +83,8 @@ else() install(DIRECTORY ${CMAKE_SOURCE_DIR}/assets DESTINATION ${CMAKE_INSTALL_DATADIR}/wivrn) - file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/share) - file(CREATE_LINK ${CMAKE_SOURCE_DIR}/assets ${CMAKE_BINARY_DIR}/share/assets SYMBOLIC) + file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/share/wivrn) + file(CREATE_LINK ${CMAKE_SOURCE_DIR}/assets ${CMAKE_BINARY_DIR}/share/wivrn/assets SYMBOLIC) endif() if(ANDROID OR Vulkan_VERSION VERSION_LESS 1.3.268) @@ -102,6 +109,7 @@ endif() target_compile_features(wivrn PRIVATE cxx_std_20) target_compile_definitions(wivrn PRIVATE "XR_USE_TIMESPEC=1") target_compile_definitions(wivrn PRIVATE VULKAN_HPP_NO_STRUCT_CONSTRUCTORS VMA_VULKAN_VERSION=1001000) + set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden) file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS diff --git a/client/application.h b/client/application.h index 1ed47e21..82224a61 100644 --- a/client/application.h +++ b/client/application.h @@ -35,6 +35,8 @@ #include #include "vk_mem_alloc.h" #include "singleton.h" +#include +#include class scene; @@ -195,6 +197,35 @@ public: } static std::pair get_action(const std::string & name); + static std::optional> locate_controller(XrSpace space, XrSpace reference, XrTime time) + { + XrSpaceLocation location{.type = XR_TYPE_SPACE_LOCATION}; + + assert(space != XR_NULL_HANDLE); + assert(reference != XR_NULL_HANDLE); + + xrLocateSpace(space, reference, time, &location); + + auto req_flags = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT; + if ((location.locationFlags & req_flags) != req_flags) + return {}; + + glm::vec3 position{ + location.pose.position.x, + location.pose.position.y, + location.pose.position.z, + }; + + glm::quat orientation{ + location.pose.orientation.w, + location.pose.orientation.x, + location.pose.orientation.y, + location.pose.orientation.z, + }; + + return std::make_pair(position, orientation); + } + static XrPath string_to_path(const std::string & s) { return instance().xr_instance.string_to_path(s); diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp new file mode 100644 index 00000000..c046fcee --- /dev/null +++ b/client/render/imgui_impl.cpp @@ -0,0 +1,399 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 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 "imgui_impl.h" + +#include "application.h" +#include "utils/ranges.h" +#include "vulkan/vulkan_enums.hpp" +#include "vulkan/vulkan_handles.hpp" +#include "vulkan/vulkan_to_string.hpp" +#include +#include "vk/allocation.h" +#include +#include + +/* Do not use: + * + * ImGui_ImplVulkanH_SelectSurfaceFormat + * ImGui_ImplVulkanH_SelectPresentMode + * ImGui_ImplVulkanH_GetMinImageCountFromPresentMode + * ImGui_ImplVulkanH_CreateWindowSwapChain + * ImGui_ImplVulkanH_CreateOrResizeWindow + * ImGui_ImplVulkanH_DestroyWindow + * + * struct ImGui_ImplVulkanH_Window + */ + +static vk::raii::RenderPass create_renderpass(vk::raii::Device& device, vk::Format format, vk::ImageLayout final_layout, bool clear) +{ + vk::AttachmentDescription attachment{ + .format = format, + .samples = vk::SampleCountFlagBits::e1, + .loadOp = clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare, + .storeOp = vk::AttachmentStoreOp::eStore, + .stencilLoadOp = vk::AttachmentLoadOp::eDontCare, + .stencilStoreOp = vk::AttachmentStoreOp::eDontCare, + .initialLayout = vk::ImageLayout::eUndefined, + .finalLayout = final_layout, + }; + + vk::AttachmentReference color_attachment{ + .attachment = 0, + .layout = vk::ImageLayout::eColorAttachmentOptimal, + }; + + vk::SubpassDescription subpass = { + .pipelineBindPoint = vk::PipelineBindPoint::eGraphics, + .colorAttachmentCount = 1, + .pColorAttachments = &color_attachment, + }; + + vk::SubpassDependency dependency = { + .srcSubpass = VK_SUBPASS_EXTERNAL, + .dstSubpass = 0, + .srcStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .dstStageMask = vk::PipelineStageFlagBits::eColorAttachmentOutput, + .srcAccessMask = {}, + .dstAccessMask = vk::AccessFlagBits::eColorAttachmentWrite, + }; + + return vk::raii::RenderPass(device, vk::RenderPassCreateInfo{ + .attachmentCount = 1, + .pAttachments = &attachment, + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = 1, + .pDependencies = &dependency, + }); +} + +static void check_vk_result(VkResult result) +{ + if (result < 0) + { + spdlog::error("Vulkan error in Dear ImGui: {}", vk::to_string((vk::Result)result)); + abort(); + } +} + +static std::optional ray_plane_intersection(glm::vec3 plane_center, glm::quat plane_orientation, std::pair ray) +{ + auto M = glm::transpose(glm::mat3_cast(plane_orientation)); // world-to-plane transform + + glm::vec3 ray_start = M * (ray.first - plane_center); + glm::vec3 ray_dir = M * ray.second; + + // spdlog::debug("ray_start = {}, {}, {}", ray_start.x, ray_start.y, ray_start.z); + // spdlog::debug("ray_dir = {}, {}, {}", ray_dir.x, ray_dir.y, ray_dir.z); + + if (ray_dir.z < 0.0001f) + { + glm::vec2 coord; + + coord.x = ray_start.x + ray_dir.x * ray_start.z / ray_dir.z; + coord.y = ray_start.y + ray_dir.y * ray_start.z / ray_dir.z; + + if (fabs(coord.x) <= 0.5 && fabs(coord.y) <= 0.5) + return coord; + } + + return {}; +} + +static std::pair compute_ray(glm::vec3 controller_position, glm::quat controller_orientation) +{ + return std::make_pair(controller_position, glm::transpose(glm::mat3_cast(controller_orientation)) * glm::vec3(0, 0, -1)); +} + +imgui_viewport::imgui_viewport(vk::raii::Device& device, vk::raii::CommandPool& command_pool, vk::RenderPass renderpass, vk::Extent2D size, vk::Format format) : + device(device), + size(size) +{ + uint32_t num_mipmaps = 1; + + for(auto& frame:frames) + { + frame.image = image_allocation( + vk::ImageCreateInfo{ + .imageType = vk::ImageType::e2D, + .format = format, + .extent = { + size.width, + size.height, + 1 + }, + .mipLevels = num_mipmaps, + .arrayLayers = 1, + .samples = vk::SampleCountFlagBits::e1, + .tiling = vk::ImageTiling::eOptimal, + .usage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled, + .initialLayout = vk::ImageLayout::eUndefined, + }, + VmaAllocationCreateInfo{ + .usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE + } + ); + + frame.image_view = vk::raii::ImageView(device, vk::ImageViewCreateInfo{ + .image = (vk::Image)frame.image, + .viewType = vk::ImageViewType::e2D, + .format = format, + .subresourceRange = { + .aspectMask = vk::ImageAspectFlagBits::eColor, + .baseMipLevel = 0, + .levelCount = num_mipmaps, + .baseArrayLayer = 0, + .layerCount = 1, + } + }); + + frame.framebuffer = vk::raii::Framebuffer(device, vk::FramebufferCreateInfo{ + .renderPass = renderpass, + .attachmentCount = 1, + .pAttachments = &*frame.image_view, + .width = size.width, + .height = size.height, + .layers = 1, + }); + + frame.command_buffer = std::move(device.allocateCommandBuffers({ + .commandPool = *command_pool, + .commandBufferCount = 1, + })[0]); + + frame.fence = device.createFence(vk::FenceCreateInfo{.flags = vk::FenceCreateFlagBits::eSignaled}); + } +} + +imgui_context::imgui_context(vk::raii::Device& device, uint32_t queue_family_index, vk::raii::Queue& queue) : + device(device), + queue_family_index(queue_family_index), + queue(queue), + descriptor_pool(device, vk::DescriptorPoolCreateInfo + { + .flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet, + .maxSets = 1, + .poolSizeCount = pool_sizes.size(), + .pPoolSizes = pool_sizes.data(), + }), + renderpass(create_renderpass(device, vk::Format::eR8G8B8A8Unorm, vk::ImageLayout::eShaderReadOnlyOptimal, true)), + command_pool(device, vk::CommandPoolCreateInfo{ + .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, + .queueFamilyIndex = queue_family_index, + }), + context(ImGui::CreateContext()), + io(ImGui::GetIO()) +{ + viewport = std::make_shared(device, command_pool, *renderpass, vk::Extent2D{1000, 1000}, vk::Format::eR8G8B8A8Unorm); + + // See example_sdl2_vulkan/main.cpp + + // Setup Dear ImGui style + ImGui::StyleColorsDark(); + //ImGui::StyleColorsClassic(); + //ImGui::StyleColorsLight(); + + ImGui_ImplVulkan_InitInfo init_info = { + .Instance = *application::get_vulkan_instance(), + .PhysicalDevice = *application::get_physical_device(), + .Device = *application::get_device(), + .QueueFamily = application::queue_family_index(), + .Queue = *application::get_queue(), + .PipelineCache = *application::get_pipeline_cache(), + .DescriptorPool = *descriptor_pool, + .Subpass = 0, + .MinImageCount = imgui_viewport::frames_in_flight, + .ImageCount = imgui_viewport::frames_in_flight, + .MSAASamples = VK_SAMPLE_COUNT_1_BIT, + .Allocator = nullptr, + .CheckVkResultFn = check_vk_result, + }; + + ImGui_ImplVulkan_Init(&init_info, *renderpass); + + + // Load Fonts + // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. + // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. + // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). + // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. + // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering. + // - Read 'docs/FONTS.md' for more instructions and details. + // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! + io.Fonts->AddFontDefault(); + //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf", 18.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); + //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); + //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese()); + //IM_ASSERT(font != nullptr); + +} + +void imgui_context::new_frame(std::span inputs) +{ + // Poll and handle events (inputs, window resize, etc.) + // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. + // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data. + // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data. + // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. + // SDL_Event event; + // while (SDL_PollEvent(&event)) + // { + // ImGui_ImplSDL2_ProcessEvent(&event); + // if (event.type == SDL_QUIT) + // done = true; + // if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window)) + // done = true; + // } + // + // // Resize swap chain? + // if (g_SwapChainRebuild) + // { + // int width, height; + // SDL_GetWindowSize(window, &width, &height); + // if (width > 0 && height > 0) + // { + // ImGui_ImplVulkan_SetMinImageCount(g_MinImageCount); + // ImGui_ImplVulkanH_CreateOrResizeWindow(g_Instance, g_PhysicalDevice, g_Device, &g_MainWindowData, g_QueueFamily, g_Allocator, width, height, g_MinImageCount); + // g_MainWindowData.FrameIndex = 0; + // g_SwapChainRebuild = false; + // } + // } + + // Compute the intersection of the controllers' ray and the imgui plane + std::vector ray_pos; + for(auto& i: inputs) + { + if (!i.active) + continue; + + auto& vp = *viewport; + + std::pair ray = compute_ray(i.controller_position, i.controller_orientation); + std::optional pos = ray_plane_intersection(vp.position, vp.orientation, ray); // between -0.5 and 0.5 + + if (pos) + ray_pos.push_back(*pos + glm::vec2(0.5, 0.5));; + + } + + // Start the Dear ImGui frame + ImGui_ImplVulkan_NewFrame(); + + io.DisplaySize = ImVec2(viewport->size.width, viewport->size.height); + io.DisplayFramebufferScale = ImVec2(1, 1); + + // See ImGui_ImplSDL2_ProcessEvent + io.DeltaTime = 0.016; // TODO + io.AddMousePosEvent(-FLT_MAX, -FLT_MAX); // TODO + // io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + // io.AddMouseWheelEvent(wheel_x, wheel_y); + + // io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse); + // io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN)); + // bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button)); + + ImGui::NewFrame(); + + ImDrawList* draw_list = ImGui::GetForegroundDrawList(); + + // spdlog::debug("{} intersections", ray_pos.size()); + for(glm::vec2 i: ray_pos) + { + ImVec2 j(i.x * 1000, 1000 - i.y * 1000); + draw_list->AddCircle(j, 30, ImGui::GetColorU32(ImVec4(1, 0, 0, 0.8)), 20, 10); + + // spdlog::debug(" - {}, {}", i.x, i.y); + } +} + +std::shared_ptr imgui_context::render() +{ + ImGui::Render(); + ImDrawData* draw_data = ImGui::GetDrawData(); + const bool is_minimized = (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f); + + if (is_minimized) + return {}; + + auto &vp = *viewport; + vp.frameindex = (vp.frameindex + 1) % imgui_viewport::frames_in_flight; + auto& f = vp.frames[vp.frameindex]; + auto& cb = f.command_buffer; + + device.waitForFences(*f.fence, true, 1'000'000'000); // TODO check timeout + device.resetFences(*f.fence); + + cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); + + vk::ClearValue clear{vk::ClearColorValue(0, 0, 0, 0)}; + + cb.beginRenderPass(vk::RenderPassBeginInfo{ + .renderPass = *renderpass, + .framebuffer = *f.framebuffer, + .renderArea = { + .extent = vp.size, + }, + .clearValueCount = 1, + .pClearValues = &clear + }, vk::SubpassContents::eInline); + + ImGui_ImplVulkan_RenderDrawData(draw_data, *cb); + + cb.endRenderPass(); + + // TODO: create mipmaps + + cb.end(); + + queue.submit(vk::SubmitInfo{ + .commandBufferCount = 1, + .pCommandBuffers = &*cb, + }, *f.fence); + + // Use the aliasing constructor + return std::shared_ptr{viewport, &vp.frames[vp.frameindex].image_view}; +} + +imgui_context::~imgui_context() +{ + // Release the command buffers, they will be destroyed with the command pool + for(auto& f: viewport->frames) + f.command_buffer.release(); + + // Wait for fences here and not in imgui_viewport::~imgui_viewport so that the command buffers have finished when ImGui_ImplVulkan_Shutdown is called + std::array fences; + for(auto&& [i, f]: utils::enumerate(viewport->frames)) + fences[i] = *f.fence; + + device.waitForFences(fences, true, 1'000'000'000); + + + ImGui_ImplVulkan_Shutdown(); + ImGui::DestroyContext(context); + // ImGui_ImplSDL2_Shutdown(); + // ImGui::DestroyContext(); + + // ImGui_ImplVulkanH_DestroyWindow(g_Instance, g_Device, &g_MainWindowData, g_Allocator); + + // SDL_DestroyWindow(window); + // SDL_Quit(); +} diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h new file mode 100644 index 00000000..c533540f --- /dev/null +++ b/client/render/imgui_impl.h @@ -0,0 +1,110 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 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 +#include "vk/allocation.h" + +struct imgui_frame +{ + image_allocation image; + vk::raii::ImageView image_view = nullptr; + vk::raii::Framebuffer framebuffer = nullptr; + vk::raii::CommandBuffer command_buffer = nullptr; + vk::raii::Fence fence = nullptr; +}; + +struct imgui_viewport +{ + static constexpr int frames_in_flight = 2; + std::array frames; + int frameindex = 0; + + vk::raii::Device& device; + + vk::Extent2D size; + vk::ClearValue clear_value = {vk::ClearColorValue{0,0,0,0}}; + + // TODO: sync with 3d scene + glm::vec3 position = {0, 1, -1.5}; + glm::quat orientation = {1, 0, 0, 0}; + float scale = 1; + + imgui_viewport(vk::raii::Device& device, vk::raii::CommandPool& command_pool, vk::RenderPass renderpass, vk::Extent2D size, vk::Format format); +}; + +struct imgui_inputs +{ + bool active = false; + int id; + + glm::vec3 controller_position; + glm::quat controller_orientation; + float squeeze; + float trigger; + glm::vec2 scroll; +}; + +struct imgui_controller_state +{ + bool active = false; + int id; + + float squeeze; + float trigger; + + bool squeeze_hysteresis; + bool trigger_hysteresis; +}; + +class imgui_context +{ + static inline const std::array pool_sizes = + { + vk::DescriptorPoolSize{ + .type = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + } + }; + + vk::raii::Device& device; + uint32_t queue_family_index; + vk::raii::Queue& queue; + + vk::raii::Pipeline pipeline = nullptr; + vk::raii::DescriptorPool descriptor_pool; + vk::raii::RenderPass renderpass; + vk::raii::CommandPool command_pool; + + std::shared_ptr viewport; + + ImGuiContext * context; + ImGuiIO& io; + +public: + imgui_context(vk::raii::Device& device, uint32_t queue_family_index, + vk::raii::Queue& queue); + ~imgui_context(); + + void new_frame(std::span inputs); + std::shared_ptr render(); +}; diff --git a/client/render/scene_data.cpp b/client/render/scene_data.cpp index cc0fc13e..78b28e3a 100644 --- a/client/render/scene_data.cpp +++ b/client/render/scene_data.cpp @@ -603,8 +603,12 @@ public: materials.reserve(gltf.materials.size()); for (const fastgltf::Material & gltf_material: gltf.materials) { - // Copy the default material + // Copy the default material, without references to its buffer or descriptor set auto & material_ref = *materials.emplace_back(std::make_shared(default_material)); + material_ref.name = gltf_material.name; + spdlog::info("Loading material \"{}\"", material_ref.name); + material_ref.buffer.reset(); + material_ref.ds.reset(); scene_data::material::gpu_data & material_data = material_ref.staging; diff --git a/client/render/scene_data.h b/client/render/scene_data.h index 00f72ae8..2ea15530 100644 --- a/client/render/scene_data.h +++ b/client/render/scene_data.h @@ -262,4 +262,25 @@ public: assert(id < scene->scene_objects.size()); return &scene->scene_objects[id]; } + + scene_object_handle parent() + { + assert(scene != nullptr); + assert(id < scene->scene_objects.size()); + + return {scene->scene_objects[id].parent_id, scene}; + } + + const scene_object_handle parent() const + { + assert(scene != nullptr); + assert(id < scene->scene_objects.size()); + + return {scene->scene_objects[id].parent_id, scene}; + } + + operator bool() const + { + return id != scene_data::scene_object::root_id; + } }; diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp index b6af12ea..50da5494 100644 --- a/client/scenes/input_profile.cpp +++ b/client/scenes/input_profile.cpp @@ -279,35 +279,6 @@ input_profile::input_profile(const std::filesystem::path & json_profile, scene_l } } -static std::optional> locate_controller(XrSpace space, XrSpace reference, XrTime time) -{ - XrSpaceLocation location{.type = XR_TYPE_SPACE_LOCATION}; - - assert(space != XR_NULL_HANDLE); - assert(reference != XR_NULL_HANDLE); - - xrLocateSpace(space, reference, time, &location); - - auto req_flags = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT; - if ((location.locationFlags & req_flags) != req_flags) - return {}; - - glm::vec3 position{ - location.pose.position.x, - location.pose.position.y, - location.pose.position.z, - }; - - glm::quat orientation{ - location.pose.orientation.w, - location.pose.orientation.x, - location.pose.orientation.y, - location.pose.orientation.z, - }; - - return std::make_pair(position, orientation); -} - void apply_visual_response(scene_object_handle node, std::pair transforms, float value) { node->translation = glm::mix(transforms.first.position, transforms.second.position, value); @@ -323,7 +294,7 @@ void input_profile::apply(XrSpace world_space, XrTime predicted_display_time) { for (auto && [space, node]: model_handles) { - if (auto location = locate_controller(space, world_space, predicted_display_time); location) + if (auto location = application::locate_controller(space, world_space, predicted_display_time); location) { node->visible = true; node->translation = location->first; diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index b5647709..acfb8db2 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -90,9 +90,15 @@ scenes::lobby::lobby() : teapot.import(loader("lobby.gltf")); + teapot.import(loader("imgui.gltf")); + imgui_material = teapot.find_material("imgui"); + assert(imgui_material); + input = input_profile("controllers/" + choose_webxr_profile() + "/profile.json", loader, teapot); spdlog::info("Loaded input profile {}", input->id); + + imgui_ctx.emplace(device, queue_family_index, queue); } void scenes::lobby::rasterize_status_string() @@ -262,6 +268,52 @@ void scenes::lobby::render() input->apply(world_space, framestate.predictedDisplayTime); + std::array inputs; + + if (auto location = application::locate_controller(application::left_aim(), world_space, framestate.predictedDisplayTime); location) + { + inputs[0].active = true; + inputs[0].controller_position = location->first; + inputs[0].controller_orientation = location->second; + + auto act = application::get_action("/user/hand/left/select/trigger/value").first; + if (act) + inputs[0].trigger = application::read_action_bool(application::get_action("/user/hand/left/select/trigger/value").first).value_or(std::make_pair(0, 0)).second; + + // inputs[0].trigger = application::read_action_float(application::get_action("/user/hand/left/input/trigger/value").first).value_or(std::make_pair(0, 0)).second; + // inputs[0].squeeze = application::read_action_float(application::get_action("/user/hand/left/input/squeeze/value").first).value_or(std::make_pair(0, 0)).second; + inputs[0].scroll = glm::vec2(0,0); + } + else + { + inputs[0].active = false; + } + + if (auto location = application::locate_controller(application::right_aim(), world_space, framestate.predictedDisplayTime); location) + { + inputs[1].active = true; + inputs[1].controller_position = location->first; + inputs[1].controller_orientation = location->second; + + auto act = application::get_action("/user/hand/right/select/trigger/value").first; + if (act) + inputs[1].trigger = application::read_action_bool(act).value_or(std::make_pair(0, 0)).second; + + // inputs[1].trigger = application::read_action_float(application::get_action("/user/hand/right/input/trigger/value").first).value_or(std::make_pair(0, 0)).second; + // inputs[1].squeeze = application::read_action_float(application::get_action("/user/hand/right/input/squeeze/value").first).value_or(std::make_pair(0, 0)).second; + inputs[1].scroll = glm::vec2(1,1); + } + else + { + inputs[1].active = false; + } + + imgui_ctx->new_frame(inputs); + ImGui::ShowDemoWindow(); + + // Render the GUI to the imgui material + imgui_material->base_color_texture->image_view = imgui_ctx->render(); + imgui_material->ds_dirty = true; std::vector layer_view; std::vector frames; diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index f9a1eebc..f12e3e8a 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -19,6 +19,7 @@ #pragma once +#include "render/scene_data.h" #include "scene.h" #include #include "wivrn_discover.h" @@ -27,6 +28,7 @@ #include "render/scene_renderer.h" #include "render/text_rasterizer.h" +#include "render/imgui_impl.h" #include "input_profile.h" namespace scenes @@ -45,35 +47,18 @@ class lobby : public scene vk::DescriptorSet status_string_image_descriptor_set; text_rasterizer status_string_rasterizer; - // vk::raii::RenderPass renderpass = nullptr; - // vk::raii::PipelineLayout layout = nullptr; - // vk::raii::Pipeline pipeline = nullptr; - - // vk::raii::Fence fence = nullptr; - // vk::raii::CommandBuffer command_buffer = nullptr; - - // struct image_data - // { - // vk::raii::Framebuffer framebuffer; - // vk::raii::Semaphore render_finished; - // }; - - // std::vector> images_data; - std::optional discover; - // std::vector model_memory; - // std::vector model_buffers; - // std::vector model_images; - - // void load_model(const std::string & filename); std::shared_ptr next_scene; std::optional renderer; - scene_data teapot; + scene_data teapot; // Must be after the renderer so that the descriptor sets are freed before their pools std::optional input; + std::optional imgui_ctx; + std::shared_ptr imgui_material; + void rasterize_status_string(); public: diff --git a/client/utils/fmt_glm.h b/client/utils/fmt_glm.h index ca4e8374..c066b003 100644 --- a/client/utils/fmt_glm.h +++ b/client/utils/fmt_glm.h @@ -82,6 +82,23 @@ struct fmt::formatter, Char> //: fmt::formatter }; +template +struct fmt::formatter, Char> +{ + + auto parse(basic_format_parse_context& ctx) const // -> decltype(ctx.begin()) + { + return ctx.begin(); + } + + template + auto format(const glm::qua& q, FormatContext& ctx) const -> decltype(ctx.out()) + { + return fmt::format_to(ctx.out(), "[ {}, {}, {}, {} ]", q.w, q.x, q.y, q.z); + } + +}; + /* template struct fmt::formatter> : fmt::formatter diff --git a/client/xr/instance.cpp b/client/xr/instance.cpp index 8b739285..f847fc5b 100644 --- a/client/xr/instance.cpp +++ b/client/xr/instance.cpp @@ -19,7 +19,6 @@ #include "instance.h" -#include "spdlog/fmt/fmt.h" #include "xr.h" #include "xr/details/enumerate.h" #include