From aad1bb6a1bbce5ce4eb8ca58138367f28dba379e Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Tue, 19 Aug 2025 23:25:41 +0200 Subject: [PATCH] Misc renderer improvements: - Reuse renderer and gltf loader between scenes - Use puish descriptors to simplify the management of descriptor sets in the scene renderer - Don't keep the imgui swapchain in the scene classes - Fix alpha blending, add alpha masking - Fix mipmaps not being used in renderer - Add cache when loading images and models - Only premultiply the colours if required - Add support for gltTF animations Allow removing an object and its descendants from the scene, allow loading from a memory buffer --- client/render/animation.cpp | 150 +++++++++++++++++++ client/render/animation.h | 26 ++++ client/render/image_loader.cpp | 104 +++++++------ client/render/image_loader.h | 23 ++- client/render/imgui_impl.cpp | 40 +++-- client/render/imgui_impl.h | 16 +- client/render/scene_components.h | 76 ++++++++-- client/render/scene_loader.cpp | 241 ++++++++++++++++++++++--------- client/render/scene_loader.h | 7 +- client/render/scene_renderer.cpp | 214 ++++++++++++--------------- client/render/scene_renderer.h | 10 +- client/scene.cpp | 155 +++++++++++++++++--- client/scene.h | 41 ++++-- client/scenes/hand_model.cpp | 2 +- client/scenes/input_profile.cpp | 26 ++-- client/scenes/lobby.cpp | 31 ++-- client/scenes/lobby.h | 4 +- client/scenes/stream.cpp | 26 ++-- client/scenes/stream.h | 6 +- client/shaders/lit.glsl | 31 ++-- client/utils/cache.h | 64 ++++++++ 21 files changed, 918 insertions(+), 375 deletions(-) create mode 100644 client/render/animation.cpp create mode 100644 client/render/animation.h create mode 100644 client/utils/cache.h diff --git a/client/render/animation.cpp b/client/render/animation.cpp new file mode 100644 index 00000000..b96f06f5 --- /dev/null +++ b/client/render/animation.cpp @@ -0,0 +1,150 @@ +/* + * 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 "animation.h" +#include "render/scene_components.h" + +#include +#include +#include +#include + +namespace +{ + +glm::vec3 interp(const glm::vec3 & a, const glm::vec3 & b, float t) +{ + return a + t * (b - a); +} + +glm::quat interp(const glm::quat & a, const glm::quat & b, float t) +{ + float d = glm::dot(a, b); + + if (d > 0.99999) + { + return a + t * (b - a); + } + else + { + float θ = std::acos(std::abs(d)); + + float sinθ = std::sin(θ); + float sinθt = std::sin(θ * t); + float sinθ1_t = std::sin(θ * (1 - t)); + + return sinθ1_t / sinθ * a + std::copysign(sinθt / sinθ, d) * b; + } +} + +glm::vec3 cubic_spline(const glm::vec3 & a, const glm::vec3 & va, const glm::vec3 & vb, const glm::vec3 & b, float t, float td) +{ + float t2 = t * t; + float t3 = t2 * t; + + return (2 * t3 - 3 * t2 + 1) * a + + td * (t3 - 2 * t2 + t) * va + + (3 * t2 - 2 * t3) * b + + td * (t3 - t2) * vb; +} + +glm::quat cubic_spline(const glm::quat & a, const glm::quat & vb, const glm::quat & va, const glm::quat & b, float t, float td) +{ + float t2 = t * t; + float t3 = t2 * t; + + return glm::normalize((2 * t3 - 3 * t2 + 1) * a + + td * (t3 - 2 * t2 + t) * vb + + (3 * t2 - 2 * t3) * b + + td * (t3 - t2) * va); +} + +template +void apply_track(entt::registry & scene, const components::animation_track_impl & track, float current_time) +{ + entt::entity target = track.target; + auto interpolation = track.interpolation; + auto field = track.field; + auto & value = scene.get(track.target).*field; + + // Find the first keyframe with a timestamp strictly greater than the current time + size_t k = std::ranges::upper_bound(track.timestamp, current_time) - track.timestamp.begin(); + if (k == 0) + { + value = track.value[0]; + return; + } + + switch (interpolation) + { + case components::animation_track_base::interpolation_t::step: + value = track.value[k - 1]; + break; + + case components::animation_track_base::interpolation_t::linear: + if (k == track.timestamp.size()) + value = track.value[k - 1]; + else + { + float t = (current_time - track.timestamp[k - 1]) / (track.timestamp[k] - track.timestamp[k - 1]); + const auto & a = track.value[k - 1]; + const auto & b = track.value[k]; + value = interp(a, b, t); + } + break; + + case components::animation_track_base::interpolation_t::cubic_spline: + if (k == track.timestamp.size()) + value = track.value[k - 1]; + else + { + float t = (current_time - track.timestamp[k - 1]) / (track.timestamp[k] - track.timestamp[k - 1]); + const auto & a = track.value[3 * k - 2]; // v_k in gltf spec + const auto & vb = track.value[3 * k - 1]; // b_k + const auto & va = track.value[3 * k]; // a_k+1 + const auto & b = track.value[3 * k + 1]; // v_k+1 + + value = cubic_spline(a, va, vb, b, t, track.timestamp[k] - track.timestamp[k - 1]); + } + break; + } +} +} // namespace + +void renderer::animate(entt::registry & scene, float dt) +{ + for (auto && [entity, animation]: scene.view().each()) + { + if (not animation.playing) + continue; + + animation.current_time += dt; + if (animation.current_time > animation.duration) + { + if (animation.looping) + animation.current_time = std::fmod(animation.current_time, animation.duration); + else + animation.current_time = animation.duration; + } + else if (animation.current_time < 0) + animation.current_time = 0; + + for (const auto & track: animation.tracks) + std::visit([&](auto & track) { apply_track(scene, track, animation.current_time); }, track); + } +} diff --git a/client/render/animation.h b/client/render/animation.h new file mode 100644 index 00000000..a1698356 --- /dev/null +++ b/client/render/animation.h @@ -0,0 +1,26 @@ +/* + * 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 + +namespace renderer +{ +void animate(entt::registry & registry, float dt); +} diff --git a/client/render/image_loader.cpp b/client/render/image_loader.cpp index cfd3605a..d666a74c 100644 --- a/client/render/image_loader.cpp +++ b/client/render/image_loader.cpp @@ -318,7 +318,52 @@ image_loader::~image_loader() ktxVulkanDeviceInfo_Destruct(&vdi); } -loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name) +template +float alpha_scale; +template <> +float alpha_scale = 1. / 255.; +template <> +float alpha_scale = 1. / 65535.; +template <> +float alpha_scale = 1.; + +template +void premultiply_alpha_aux(T * destination, const T * source, int n) +{ + for (int i = 0; i < n; i++) + { + float alpha = source[4 * i + 3] * alpha_scale; + + destination[4 * i + 0] = source[4 * i + 0] * alpha; + destination[4 * i + 1] = source[4 * i + 1] * alpha; + destination[4 * i + 2] = source[4 * i + 2] * alpha; + destination[4 * i + 3] = source[4 * i + 3]; + } +} + +static void premultiply_alpha(void * destination, const void * source, vk::Extent3D extent, vk::Format format) +{ + switch (format) + { + case vk::Format::eR8G8B8A8Srgb: // TODO: sRGB + case vk::Format::eR8G8B8A8Unorm: + premultiply_alpha_aux((uint8_t *)destination, (const uint8_t *)source, extent.width * extent.height * extent.depth); + break; + + case vk::Format::eR16G16B16A16Unorm: + premultiply_alpha_aux((uint16_t *)destination, (const uint16_t *)source, extent.width * extent.height * extent.depth); + break; + + case vk::Format::eR32G32B32A32Sfloat: + premultiply_alpha_aux((float *)destination, (const float *)source, extent.width * extent.height * extent.depth); + break; + + default: + break; + } +} + +loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply) { auto cb = std::move(device.allocateCommandBuffers({ .commandPool = *cb_pool, @@ -346,7 +391,11 @@ loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, }, name + " (staging)"}; - memcpy(staging_buffer.map(), pixels, byte_size); + if (premultiply) + premultiply_alpha(staging_buffer.map(), pixels, extent, format); + else + memcpy(staging_buffer.map(), pixels, byte_size); + staging_buffer.unmap(); // Allocate image @@ -544,6 +593,7 @@ loaded_image image_loader::do_load_raw(const void * pixels, vk::Extent3D extent, .extent = extent, .num_mipmaps = num_mipmaps, .image_view_type = image_view_type, + .is_alpha_premultiplied = premultiply, }; } @@ -609,6 +659,7 @@ loaded_image image_loader::do_load_ktx(std::span bytes, bool sr .extent{vk::Extent3D(texture->baseWidth, texture->baseHeight, texture->baseDepth)}, .num_mipmaps = texture->numLevels, .image_view_type = vk::ImageViewType(vk_texture.viewType), + .is_alpha_premultiplied = ktxTexture2_GetPremultipliedAlpha(texture), }; } @@ -617,42 +668,7 @@ static constexpr bool starts_with(std::span data, std::span= prefix.size() && !memcmp(data.data(), prefix.data(), prefix.size()); } -template -void premultiply_alpha_aux(T * pixels, float alpha_scale, int width, int height) -{ - for (int i = 0, n = width * height; i < n; i++) - { - float alpha = pixels[4 * i + 3] * alpha_scale; - - pixels[4 * i + 0] = pixels[4 * i + 0] * alpha; - pixels[4 * i + 1] = pixels[4 * i + 1] * alpha; - pixels[4 * i + 2] = pixels[4 * i + 2] * alpha; - } -} - -static void premultiply_alpha(void * pixels, vk::Extent3D extent, vk::Format format) -{ - switch (format) - { - case vk::Format::eR8G8B8A8Srgb: // TODO: sRGB - case vk::Format::eR8G8B8A8Unorm: - premultiply_alpha_aux((uint8_t *)pixels, 1. / 255., extent.width, extent.height); - break; - - case vk::Format::eR16G16B16A16Unorm: - premultiply_alpha_aux((uint16_t *)pixels, 1. / 65535., extent.width, extent.height); - break; - - case vk::Format::eR32G32B32A32Sfloat: - premultiply_alpha_aux((float *)pixels, 1, extent.width, extent.height); - break; - - default: - break; - } -} - -loaded_image image_loader::do_load_image(std::span bytes, bool srgb, const std::string & name) +loaded_image image_loader::do_load_image(std::span bytes, bool srgb, const std::string & name, bool premultiply) { const stbi_uc * image_data = (const stbi_uc *)bytes.data(); size_t image_size = bytes.size(); @@ -691,13 +707,11 @@ loaded_image image_loader::do_load_image(std::span bytes, bool .depth = 1, }; - premultiply_alpha(pixels.get(), extent, format); - - return do_load_raw(pixels.get(), extent, format, name); + return do_load_raw(pixels.get(), extent, format, name, premultiply); } // Load a PNG/JPEG/KTX2 file -loaded_image image_loader::load(std::span bytes, bool srgb, const std::string & name) +loaded_image image_loader::load(std::span bytes, bool srgb, const std::string & name, bool premultiply) { const uint8_t ktx1_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; const uint8_t ktx2_magic[] = {0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A}; @@ -705,14 +719,14 @@ loaded_image image_loader::load(std::span bytes, bool srgb, con if (starts_with(bytes, ktx1_magic) || starts_with(bytes, ktx2_magic)) return do_load_ktx(bytes, srgb, name); else - return do_load_image(bytes, srgb, name); + return do_load_image(bytes, srgb, name, premultiply); } // Load raw pixel data -loaded_image image_loader::load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name) +loaded_image image_loader::load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply) { if (size < extent.width * extent.height * extent.depth * bytes_per_pixel(format)) throw std::invalid_argument("size"); - return do_load_raw(pixels, extent, format, name); + return do_load_raw(pixels, extent, format, name, premultiply); } diff --git a/client/render/image_loader.h b/client/render/image_loader.h index 0a2594a6..995d3692 100644 --- a/client/render/image_loader.h +++ b/client/render/image_loader.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -40,6 +41,7 @@ struct loaded_image vk::Extent3D extent; uint32_t num_mipmaps; vk::ImageViewType image_view_type; + bool is_alpha_premultiplied; }; struct image_loader @@ -50,29 +52,36 @@ struct image_loader ~image_loader(); // Load a PNG/JPEG/KTX2 file - loaded_image load(std::span bytes, bool srgb, const std::string & name = ""); + loaded_image load(std::span bytes, bool srgb, const std::string & name = "", bool premultiply = false); // Load raw pixel data - loaded_image load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name = ""); + loaded_image load(const void * pixels, size_t size, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false); template - loaded_image load(std::span pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") + loaded_image load(std::span pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false) { return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); } template - loaded_image load(const std::array & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") + loaded_image load(const std::array & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false) { return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); } template - loaded_image load(const std::vector & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "") + loaded_image load(const std::vector & pixels, vk::Extent3D extent, vk::Format format, const std::string & name = "", bool premultiply = false) { return load(pixels.data(), pixels.size() * sizeof(T), extent, format, name); } + template + std::shared_ptr operator()(Args &&... args) + { + auto result = std::make_shared(load(std::forward(args)...)); + return result; + } + private: ktxVulkanDeviceInfo vdi; vk::raii::Device & device; @@ -84,8 +93,8 @@ private: buffer_allocation staging_buffer; - loaded_image do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name); + loaded_image do_load_raw(const void * pixels, vk::Extent3D extent, vk::Format format, const std::string & name, bool premultiply); - loaded_image do_load_image(std::span bytes, bool srgb, const std::string & name); + loaded_image do_load_image(std::span bytes, bool srgb, const std::string & name, bool premultiply); loaded_image do_load_ktx(std::span bytes, bool srgb, const std::string & name); }; diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 017a9d06..0ed35d6b 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -190,7 +190,8 @@ imgui_textures::imgui_textures( vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, uint32_t queue_family_index, - thread_safe & queue) : + thread_safe & queue, + std::shared_ptr image_cache) : physical_device(physical_device), device(device), queue(queue), @@ -200,8 +201,12 @@ imgui_textures::imgui_textures( .flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer | vk::CommandPoolCreateFlagBits::eTransient, .queueFamilyIndex = queue_family_index, }), + image_cache(image_cache), descriptor_pool(device, ds_layout, layout_bindings) -{} +{ + if (not image_cache) + this->image_cache = std::make_shared(physical_device, device, queue, command_pool); +} std::vector> imgui_context::ray_plane_intersection(const imgui_context::controller_state & in) const { @@ -320,20 +325,22 @@ imgui_context::imgui_context( uint32_t queue_family_index, thread_safe & queue, std::span controllers_, - xr::swapchain & swapchain, - std::vector layers) : + xr::swapchain && swapchain_, + std::vector layers, + std::shared_ptr image_cache) : imgui_textures( physical_device, device, queue_family_index, - queue), + queue, + image_cache), queue_family_index(queue_family_index), - renderpass(create_renderpass(device, swapchain.format(), true)), - command_buffers(swapchain.images().size()), - size(swapchain.extent().width, swapchain.extent().height), - format(swapchain.format()), + renderpass(create_renderpass(device, swapchain_.format(), true)), + command_buffers(swapchain_.images().size()), + size(swapchain_.extent().width, swapchain_.extent().height), + format(swapchain_.format()), layers_(std::move(layers)), - swapchain(swapchain), + swapchain(std::move(swapchain_)), context(ImGui::CreateContext()), plot_context(ImPlot::CreateContext()), io((ImGui::SetCurrentContext(context), ImGui::GetIO())), @@ -1040,15 +1047,18 @@ ImTextureID imgui_textures::load_texture(const std::string & filename, vk::raii: ImTextureID imgui_textures::load_texture(const std::span & bytes, vk::raii::Sampler && sampler, const std::string & name) { bool srgb = true; - // TODO: reuse the image loader - image_loader loader(physical_device, device, queue, command_pool); - auto image = loader.load(bytes, srgb, name); + + std::shared_ptr image; + if (name == "") + image = image_cache->load_uncached(bytes, srgb, "", true /* premultiply alpha */); + else + image = image_cache->load(name, bytes, srgb, name, true /* premultiply alpha */); std::shared_ptr ds = descriptor_pool.allocate(); vk::DescriptorImageInfo image_info{ .sampler = *sampler, - .imageView = *image.image_view, + .imageView = *image->image_view, .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; @@ -1066,7 +1076,7 @@ ImTextureID imgui_textures::load_texture(const std::span & byte id, texture_data{ .sampler = std::move(sampler), - .image = std::move(image), + .image = image, .descriptor_set = std::move(ds), }); diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 3224bf69..636dbd85 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -20,6 +20,7 @@ #include "image_loader.h" #include "render/growable_descriptor_pool.h" +#include "utils/cache.h" #include "utils/thread_safe.h" #include "wivrn_config.h" #include "xr/hand_tracker.h" @@ -42,7 +43,7 @@ class imgui_textures struct texture_data { vk::raii::Sampler sampler; - loaded_image image; + std::shared_ptr image; std::shared_ptr descriptor_set; }; @@ -53,6 +54,9 @@ protected: vk::raii::DescriptorSetLayout ds_layout; vk::raii::CommandPool command_pool; + using image_cache_type = utils::cache; + std::shared_ptr image_cache; + private: growable_descriptor_pool descriptor_pool; std::unordered_map textures; @@ -62,7 +66,8 @@ public: vk::raii::PhysicalDevice physical_device, vk::raii::Device & device, uint32_t queue_family_index, - thread_safe & queue); + thread_safe & queue, + std::shared_ptr image_cache = {}); ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler); ImTextureID load_texture(const std::string & filename); ImTextureID load_texture(const std::span & bytes, vk::raii::Sampler && sampler, const std::string & name = ""); @@ -165,7 +170,7 @@ private: std::vector layers_; - xr::swapchain & swapchain; + xr::swapchain swapchain; int image_index; ImGuiContext * context; @@ -200,8 +205,9 @@ public: uint32_t queue_family_index, thread_safe & queue, std::span controllers, - xr::swapchain & swapchain, - std::vector layers); + xr::swapchain && swapchain, + std::vector layers, + std::shared_ptr image_cache); ~imgui_context(); diff --git a/client/render/scene_components.h b/client/render/scene_components.h index 9b594947..e8e28e42 100644 --- a/client/render/scene_components.h +++ b/client/render/scene_components.h @@ -20,6 +20,9 @@ #include #include +#include +#include +#include #include #include @@ -59,6 +62,7 @@ struct material float roughness_factor = 1; float occlusion_strength = 0; float normal_scale = 0; + float alpha_cutoff = 0.5; uint32_t base_color_texcoord = 0; uint32_t metallic_roughness_texcoord = 0; @@ -69,6 +73,13 @@ struct material // TODO: add fastgltf::TextureTransform? }; + enum class alpha_mode_t + { + opaque, + mask, + blend + }; + std::shared_ptr base_color_texture; std::shared_ptr metallic_roughness_texture; std::shared_ptr occlusion_texture; @@ -78,9 +89,7 @@ struct material // Disable back face culling with this material bool double_sided = true; - // TODO transparency - // fastgltf::AlphaMode alphaMode; - // float alpha_cutoff; + alpha_mode_t alpha_mode; gpu_data staging; @@ -88,17 +97,8 @@ struct material std::shared_ptr buffer; size_t offset; - // The descriptor set is managed by the scene renderer, it is updated whenever ds_dirty is true - // Bindings 0-4: textures - // Binding 5: uniform buffer - std::shared_ptr ds; - - // Set to true to update the descriptor set at the next frame - bool ds_dirty; - std::string name; std::string shader_name = "lit"; - bool blend_enable = true; }; struct primitive @@ -118,6 +118,7 @@ struct primitive std::shared_ptr material_; }; +// TODO make sure the mesh cannot be changed while it is used struct mesh { std::vector primitives; @@ -129,7 +130,7 @@ struct vertex { glm::vec3 position; glm::vec3 normal; - glm::vec3 tangent; + glm::vec4 tangent; std::array texcoord; glm::vec4 color; std::array joints; @@ -180,6 +181,55 @@ struct node bool reverse_side; uint32_t global_layer_mask; }; + +struct animation_track_base +{ + enum class interpolation_t + { + step, + linear, + cubic_spline, + }; + + entt::entity target; + interpolation_t interpolation; +}; + +template +struct animation_track_impl : animation_track_base +{ + static const constexpr auto field = Field; + using type = std::remove_reference_t().*field)>; + + std::vector timestamp; + std::vector value; +}; + +using animation_track_position = animation_track_impl<&node::position>; +using animation_track_orientation = animation_track_impl<&node::orientation>; +using animation_track_scale = animation_track_impl<&node::scale>; + +static_assert(std::is_same_v); +static_assert(std::is_same_v); +static_assert(std::is_same_v); + +struct animation +{ + std::string name; + std::vector< + std::variant< + animation_track_position, + animation_track_orientation, + animation_track_scale>> + tracks; + + float duration = 0; + + float current_time = 0; + bool playing = true; + bool looping = true; +}; + } // namespace components entt::entity find_node_by_name(entt::registry & scene, std::string_view name); diff --git a/client/render/scene_loader.cpp b/client/render/scene_loader.cpp index e187315b..f156fd4f 100644 --- a/client/render/scene_loader.cpp +++ b/client/render/scene_loader.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -174,6 +175,36 @@ glm::vec3 convert(const fastgltf::math::nvec3 & v) { return {v[0], v[1], v[2]}; } + +renderer::material::alpha_mode_t convert(fastgltf::AlphaMode alpha_mode) +{ + switch (alpha_mode) + { + case fastgltf::AlphaMode::Opaque: + return renderer::material::alpha_mode_t::opaque; + case fastgltf::AlphaMode::Mask: + return renderer::material::alpha_mode_t::mask; + case fastgltf::AlphaMode::Blend: + return renderer::material::alpha_mode_t::blend; + } + + throw std::invalid_argument("alpha_mode"); +} + +components::animation_track_base::interpolation_t convert(fastgltf::AnimationInterpolation interpolation) +{ + switch (interpolation) + { + case fastgltf::AnimationInterpolation::Linear: + return components::animation_track_base::interpolation_t::linear; + case fastgltf::AnimationInterpolation::Step: + return components::animation_track_base::interpolation_t::step; + case fastgltf::AnimationInterpolation::CubicSpline: + return components::animation_track_base::interpolation_t::cubic_spline; + } + + throw std::invalid_argument("interpolation"); +} // END // BEGIN Vertex attributes loading @@ -548,54 +579,54 @@ public: for (const fastgltf::Material & gltf_material: gltf.materials) { // 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; - material_ref.buffer.reset(); - material_ref.ds.reset(); + auto & material = *materials.emplace_back(std::make_shared(default_material)); + material.name = gltf_material.name; + material.buffer.reset(); - material_ref.double_sided = gltf_material.doubleSided; - material_ref.blend_enable = gltf_material.alphaMode == fastgltf::AlphaMode::Blend; // TODO handle alpha cut off mode + material.double_sided = gltf_material.doubleSided; + material.alpha_mode = convert(gltf_material.alphaMode); - renderer::material::gpu_data & material_data = material_ref.staging; + renderer::material::gpu_data & material_data = material.staging; material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); material_data.base_emissive_factor = glm::vec4(convert(gltf_material.emissiveFactor), 0); material_data.metallic_factor = gltf_material.pbrData.metallicFactor; material_data.roughness_factor = gltf_material.pbrData.roughnessFactor; + material_data.alpha_cutoff = gltf_material.alphaCutoff; if (gltf_material.pbrData.baseColorTexture) { - material_ref.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex); + material.base_color_texture = textures.at(gltf_material.pbrData.baseColorTexture->textureIndex); material_data.base_color_texcoord = gltf_material.pbrData.baseColorTexture->texCoordIndex; } if (gltf_material.pbrData.metallicRoughnessTexture) { - material_ref.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex); + material.metallic_roughness_texture = textures.at(gltf_material.pbrData.metallicRoughnessTexture->textureIndex); material_data.metallic_roughness_texcoord = gltf_material.pbrData.metallicRoughnessTexture->texCoordIndex; } if (gltf_material.occlusionTexture) { - material_ref.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex); + material.occlusion_texture = textures.at(gltf_material.occlusionTexture->textureIndex); material_data.occlusion_texcoord = gltf_material.occlusionTexture->texCoordIndex; material_data.occlusion_strength = gltf_material.occlusionTexture->strength; } if (gltf_material.emissiveTexture) { - material_ref.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex); + material.emissive_texture = textures.at(gltf_material.emissiveTexture->textureIndex); material_data.emissive_texcoord = gltf_material.emissiveTexture->texCoordIndex; } if (gltf_material.normalTexture) { - material_ref.normal_texture = textures.at(gltf_material.normalTexture->textureIndex); + material.normal_texture = textures.at(gltf_material.normalTexture->textureIndex); material_data.normal_texcoord = gltf_material.normalTexture->texCoordIndex; material_data.normal_scale = gltf_material.normalTexture->scale; } - material_ref.offset = staging_buffer.add_uniform(material_data); + material.offset = staging_buffer.add_uniform(material_data); } return materials; @@ -676,10 +707,8 @@ public: return meshes; } - entt::registry load_all_nodes(const std::vector> & meshes) + std::vector load_all_nodes(entt::registry & registry, const std::vector> & meshes) { - entt::registry registry; - std::vector entities{gltf.nodes.size()}; registry.create(entities.begin(), entities.end()); @@ -727,7 +756,117 @@ public: std::ranges::fill(node.clipping_planes, glm::vec4{0, 0, 0, 1}); } - return registry; + return entities; + } + + void load_all_animations(entt::registry & registry, const std::vector & node_entities) + { + std::vector entities{gltf.animations.size()}; + registry.create(entities.begin(), entities.end()); + + // Create all animation components first + registry.insert(entities.begin(), entities.end()); + + for (const auto & [entity, gltf_animation]: std::ranges::zip_view(entities, gltf.animations)) + { + auto & animation = registry.get(entity); + animation.name = gltf_animation.name; + animation.tracks.reserve(gltf_animation.channels.size()); + + for (const auto & channel: gltf_animation.channels) + { + if (not channel.nodeIndex.has_value() or *channel.nodeIndex > node_entities.size()) + // Ignore this channel + continue; + + const auto & sampler = gltf_animation.samplers.at(channel.samplerIndex); + const auto & time = gltf.accessors.at(sampler.inputAccessor); + const auto & value = gltf.accessors.at(sampler.outputAccessor); + const auto interpolation = convert(sampler.interpolation); + + switch (interpolation) + { + case components::animation_track_base::interpolation_t::step: + case components::animation_track_base::interpolation_t::linear: + if (time.count != value.count) + // There must be the same number of elements + continue; + break; + + case components::animation_track_base::interpolation_t::cubic_spline: + // TODO: does not work for morph targets + if (3 * time.count != value.count or time.count < 2) + continue; + break; + } + + size_t count = time.count; + switch (channel.path) + { + // TODO: templatize the switch + case fastgltf::AnimationPath::Translation: { + components::animation_track_position track; + track.target = node_entities.at(*channel.nodeIndex); + track.interpolation = interpolation; + track.timestamp.resize(time.count); + track.value.resize(value.count); + + fastgltf::iterateAccessorWithIndex(gltf, time, [&](float t, size_t index) { + track.timestamp[index] = t; + animation.duration = std::max(animation.duration, t); + }); + + fastgltf::iterateAccessorWithIndex(gltf, value, [&](glm::vec3 value, size_t index) { + track.value[index] = value; + }); + + animation.tracks.emplace_back(std::move(track)); + break; + } + case fastgltf::AnimationPath::Rotation: { + components::animation_track_orientation track; + track.target = node_entities.at(*channel.nodeIndex); + track.interpolation = interpolation; + track.timestamp.resize(time.count); + track.value.resize(value.count); + + fastgltf::iterateAccessorWithIndex(gltf, time, [&](float t, size_t index) { + track.timestamp[index] = t; + animation.duration = std::max(animation.duration, t); + }); + + fastgltf::iterateAccessorWithIndex(gltf, value, [&](glm::vec4 value, size_t index) { + track.value[index] = glm::quat::wxyz(value.w, value.x, value.y, value.z); + }); + + animation.tracks.emplace_back(std::move(track)); + break; + } + case fastgltf::AnimationPath::Scale: { + components::animation_track_scale track; + track.target = node_entities.at(*channel.nodeIndex); + track.interpolation = interpolation; + track.timestamp.resize(time.count); + track.value.resize(value.count); + + fastgltf::iterateAccessorWithIndex(gltf, time, [&](float t, size_t index) { + track.timestamp[index] = t; + animation.duration = std::max(animation.duration, t); + }); + + fastgltf::iterateAccessorWithIndex(gltf, value, [&](glm::vec3 value, size_t index) { + track.value[index] = value; + }); + + animation.tracks.emplace_back(std::move(track)); + break; + } + case fastgltf::AnimationPath::Weights: + // TODO morph weights + break; + } + } + } } }; @@ -779,7 +918,7 @@ renderer::vertex::describe() return desc; } -entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) +std::shared_ptr scene_loader::operator()(std::span data, const std::string & name, const std::filesystem::path & parent_path) { vk::PhysicalDeviceProperties physical_device_properties = physical_device.getProperties(); vk::raii::CommandPool cb_pool{device, vk::CommandPoolCreateInfo{ @@ -787,16 +926,12 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) .queueFamilyIndex = queue_family_index, }}; - spdlog::debug("Loading {}", gltf_path.native()); - - asset asset_file(gltf_path); - - auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(asset_file.data(), asset_file.size()); + auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(data.data(), data.size()); if (auto error = data_buffer.error(); error != fastgltf::Error::None) throw std::system_error((int)error, fastgltf_error_category); - fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), gltf_path.parent_path()); - loader_context ctx(gltf_path.parent_path(), gltf_path, asset, physical_device, device, queue, cb_pool); + fastgltf::Asset asset = load_gltf_asset(data_buffer.get(), parent_path); + loader_context ctx(parent_path, name, asset, physical_device, device, queue, cb_pool); #ifndef NDEBUG if (auto error = fastgltf::validate(asset); error != fastgltf::Error::None) @@ -818,7 +953,11 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) auto meshes = ctx.load_all_meshes(materials, staging_buffer); // Load all nodes - entt::registry loaded_scene = ctx.load_all_nodes(meshes); + auto loaded_scene = std::make_shared(); + auto node_entities = ctx.load_all_nodes(*loaded_scene, meshes); + + // Load animations + ctx.load_all_animations(*loaded_scene, node_entities); // Copy the staging buffer to the GPU spdlog::debug("Uploading scene data ({} bytes) to GPU memory", staging_buffer.size()); @@ -833,45 +972,15 @@ entt::registry scene_loader::operator()(const std::filesystem::path & gltf_path) return loaded_scene; } -template -void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map & entity_map) +std::shared_ptr scene_loader::operator()(const std::filesystem::path & gltf_path) { - for (const auto & [entity, component]: prefab.view().each()) - { - scene.emplace(entity_map.at(entity), component); - } -} - -void scene_loader::add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root) -{ - assert(scene.valid(root) or root == entt::null); - - auto prefab_entities = prefab.view(); - - std::vector scene_entities{prefab_entities.size()}; - scene.create(scene_entities.begin(), scene_entities.end()); - - std::unordered_map entity_map; // key: prefab entity, value: scene entity - - entity_map.emplace(entt::null, root); - for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities)) - entity_map.emplace(prefab_entity, scene_entity); - - copy_components(scene, prefab, entity_map); - - // update links - for (auto [prefab_entity, scene_entity]: entity_map) - { - if (prefab_entity == entt::null) - continue; - - auto & node = scene.get(scene_entity); - - node.parent = entity_map.at(node.parent); - - for (auto & joint: node.joints) - { - joint.first = entity_map.at(joint.first); - } - } + spdlog::debug("Loading {}", gltf_path.native()); + + asset asset_file(gltf_path); + + auto data_buffer = fastgltf::GltfDataBuffer::FromBytes(asset_file.data(), asset_file.size()); + if (auto error = data_buffer.error(); error != fastgltf::Error::None) + throw std::system_error((int)error, fastgltf_error_category); + + return (*this)(asset_file, gltf_path.filename(), gltf_path.parent_path()); } diff --git a/client/render/scene_loader.h b/client/render/scene_loader.h index 9c28bfff..cee82627 100644 --- a/client/render/scene_loader.h +++ b/client/render/scene_loader.h @@ -18,6 +18,7 @@ #pragma once +#include #include #include @@ -40,8 +41,8 @@ public: queue_family_index(queue_family_index), default_material(default_material) {} + scene_loader(const scene_loader &) = default; - entt::registry operator()(const std::filesystem::path & gltf_path); - - void add_prefab(entt::registry & scene, const entt::registry & prefab, entt::entity root = entt::null); + std::shared_ptr operator()(const std::filesystem::path & gltf_path); + std::shared_ptr operator()(std::span data, const std::string & name = "", const std::filesystem::path & parent_path = ""); }; diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index 4cf5423f..cb93cc6c 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -140,58 +140,64 @@ static vk::FrontFace reverse(vk::FrontFace face) static std::array layout_bindings_0{ vk::DescriptorSetLayoutBinding{ + // scene_ubo: per-frame/view data .binding = 0, .descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, }, vk::DescriptorSetLayoutBinding{ + // mesh_ubo: per-instance data .binding = 1, .descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, }, vk::DescriptorSetLayoutBinding{ + // joints_ubo: skeletal animation .binding = 2, .descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, }, -}; - -static std::array layout_bindings_1{ - vk::DescriptorSetLayoutBinding{ - .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - }, - vk::DescriptorSetLayoutBinding{ - .binding = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - }, - vk::DescriptorSetLayoutBinding{ - .binding = 2, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .descriptorCount = 1, - .stageFlags = vk::ShaderStageFlagBits::eFragment, - }, vk::DescriptorSetLayoutBinding{ + // base_color .binding = 3, .descriptorType = vk::DescriptorType::eCombinedImageSampler, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eFragment, }, vk::DescriptorSetLayoutBinding{ + // metallic_roughness .binding = 4, .descriptorType = vk::DescriptorType::eCombinedImageSampler, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eFragment, }, vk::DescriptorSetLayoutBinding{ + // occlusion .binding = 5, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + // emissive + .binding = 6, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + // normal_map + .binding = 7, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorCount = 1, + .stageFlags = vk::ShaderStageFlagBits::eFragment, + }, + vk::DescriptorSetLayoutBinding{ + // material_ubo + .binding = 8, .descriptorType = vk::DescriptorType::eUniformBuffer, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eFragment, @@ -208,9 +214,7 @@ scene_renderer::scene_renderer( device(device), physical_device_properties(physical_device.getProperties()), queue(queue), - layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)), - layout_1(create_descriptor_set_layout(layout_bindings_1)), - ds_pool_material(device, layout_1, layout_bindings_1, 100) // TODO tunable + layout_0(create_descriptor_set_layout(layout_bindings_0, vk::DescriptorSetLayoutCreateFlagBits::ePushDescriptorKHR)) { // Create the default material default_material = create_default_material(cb_pool); @@ -237,7 +241,7 @@ scene_renderer::scene_renderer( .queryCount = uint32_t(2 * frames_in_flight), }); - std::array layouts{*layout_0, *layout_1}; + std::array layouts{*layout_0}; pipeline_layout = create_pipeline_layout(layouts); } @@ -588,7 +592,7 @@ vk::raii::Pipeline scene_renderer::create_pipeline(const pipeline_info & info) .ColorBlendState = {vk::PipelineColorBlendStateCreateInfo{}}, .ColorBlendAttachments = {vk::PipelineColorBlendAttachmentState{ .blendEnable = info.blend_enable, - .srcColorBlendFactor = vk::BlendFactor::eOne, + .srcColorBlendFactor = vk::BlendFactor::eSrcAlpha, .dstColorBlendFactor = vk::BlendFactor::eOneMinusSrcAlpha, .colorBlendOp = vk::BlendOp::eAdd, .srcAlphaBlendFactor = vk::BlendFactor::eOne, @@ -621,6 +625,8 @@ vk::Sampler scene_renderer::get_sampler(const renderer::sampler_info & info) .addressModeV = info.wrapT, // .anisotropyEnable = true, // .maxAnisotropy = 4, + .minLod = 0, + .maxLod = vk::LodClampNone, }); samplers.emplace(info, out); @@ -695,84 +701,6 @@ scene_renderer::per_frame_resources & scene_renderer::current_frame() return frame_resources[current_frame_index]; } -void scene_renderer::update_material_descriptor_set(renderer::material & material) -{ - if (!material.ds || material.ds.use_count() != 1) - material.ds = ds_pool_material.allocate(); - - vk::DescriptorSet ds = **material.ds; - - auto f = [&](std::shared_ptr & texture) { - return vk::DescriptorImageInfo{ - .sampler = get_sampler(texture->sampler), - .imageView = **texture->image_view, - .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, - }; - }; - - std::array write_ds_image{ - f(material.base_color_texture), - f(material.metallic_roughness_texture), - f(material.occlusion_texture), - f(material.emissive_texture), - f(material.normal_texture), - }; - - vk::DescriptorBufferInfo write_ds_buffer{ - .buffer = *material.buffer, - .offset = material.offset, - .range = sizeof(renderer::material::gpu_data), - }; - - // Write each descriptor separately because the HTC XR Elite needs it for some reason - std::array write_ds{ - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 0, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data(), - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 1, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data() + 1, - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 2, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data() + 2, - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 3, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data() + 3, - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = 4, - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, - .pImageInfo = write_ds_image.data() + 4, - }, - vk::WriteDescriptorSet{ - .dstSet = ds, - .dstBinding = (uint32_t)write_ds_image.size(), - .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eUniformBuffer, - .pBufferInfo = &write_ds_buffer, - }, - }; - - device.updateDescriptorSets(write_ds, {}); -} - [[maybe_unused]] static void print_scene_hierarchy(const entt::registry & scene, entt::entity root = entt::null, int level = 0) { if (level == 0) @@ -949,7 +877,7 @@ void scene_renderer::render( for (renderer::primitive & primitive: node.mesh->primitives) { renderer::material & material = primitive.material_ ? *primitive.material_ : *default_material; - primitives.emplace_back(material.blend_enable, position.z, &node, &primitive); + primitives.emplace_back(material.alpha_mode == renderer::material::alpha_mode_t::blend or material.alpha_mode == renderer::material::alpha_mode_t::mask, position.z, &node, &primitive); } } @@ -1003,9 +931,6 @@ void scene_renderer::render( // Get the material std::shared_ptr material = primitive.material_ ? primitive.material_ : default_material; - if (material->ds_dirty || !material->ds) - update_material_descriptor_set(*material); - // Get the pipeline pipeline_info info{ .renderpass = { @@ -1016,9 +941,10 @@ void scene_renderer::render( .cull_mode = primitive.cull_mode, .front_face = primitive.front_face, .topology = primitive.topology, - .blend_enable = material->blend_enable, + .blend_enable = material->alpha_mode == renderer::material::alpha_mode_t::blend or material->alpha_mode == renderer::material::alpha_mode_t::mask, .nb_texcoords = 2, // TODO + .alpha_cutout = material->alpha_mode == renderer::material::alpha_mode_t::mask, .skinning = !node.joints.empty(), }; @@ -1052,18 +978,39 @@ void scene_renderer::render( vk::DescriptorBufferInfo buffer_info_1{ .buffer = resources.uniform_buffer, .offset = frame_ubo_offset, - .range = sizeof(frame_gpu_data) - + .range = sizeof(frame_gpu_data), }; vk::DescriptorBufferInfo buffer_info_2{ .buffer = resources.uniform_buffer, .offset = instance_ubo_offset, - .range = sizeof(instance_gpu_data)}; + .range = sizeof(instance_gpu_data), + }; vk::DescriptorBufferInfo buffer_info_3{ .buffer = resources.uniform_buffer, .offset = joints_ubo_offset, - .range = sizeof(glm::mat4) * 32}; + .range = sizeof(glm::mat4) * 32, + }; + vk::DescriptorBufferInfo buffer_info_4{ + .buffer = *material->buffer, + .offset = material->offset, + .range = sizeof(renderer::material::gpu_data), + }; + auto f = [&](renderer::texture & texture) { + return vk::DescriptorImageInfo{ + .sampler = get_sampler(texture.sampler), + .imageView = **(texture.image_view), + .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, + }; + }; + + std::array write_ds_image{ + f(*material->base_color_texture), + f(*material->metallic_roughness_texture), + f(*material->occlusion_texture), + f(*material->emissive_texture), + f(*material->normal_texture), + }; std::array descriptors{ vk::WriteDescriptorSet{ .dstBinding = 0, @@ -1083,19 +1030,50 @@ void scene_renderer::render( .descriptorType = vk::DescriptorType::eUniformBuffer, .pBufferInfo = &buffer_info_3, }, + vk::WriteDescriptorSet{ + .dstBinding = 3, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data(), + }, + vk::WriteDescriptorSet{ + .dstBinding = 4, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data() + 1, + }, + vk::WriteDescriptorSet{ + .dstBinding = 5, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data() + 2, + }, + vk::WriteDescriptorSet{ + .dstBinding = 6, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data() + 3, + }, + vk::WriteDescriptorSet{ + .dstBinding = 7, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .pImageInfo = write_ds_image.data() + 4, + }, + vk::WriteDescriptorSet{ + .dstBinding = 8, + .descriptorCount = 1, + .descriptorType = vk::DescriptorType::eUniformBuffer, + .pBufferInfo = &buffer_info_4, + }, }; cb.pushDescriptorSetKHR(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 0, descriptors); - // Set 1: material - cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, *pipeline_layout, 1, **material->ds, {}); - if (primitive.indexed) cb.drawIndexed(primitive.index_count, 1, 0, 0, 0); else cb.draw(primitive.vertex_count, 1, 0, 0); - - resources.resources.push_back(material->ds); } cb.endRenderPass(); } diff --git a/client/render/scene_renderer.h b/client/render/scene_renderer.h index 6eeb9fe5..57ff96ce 100644 --- a/client/render/scene_renderer.h +++ b/client/render/scene_renderer.h @@ -32,7 +32,6 @@ #include "vk/allocation.h" -#include "render/growable_descriptor_pool.h" #include "render/scene_components.h" #include "utils/thread_safe.h" @@ -138,11 +137,7 @@ class scene_renderer vk::raii::Pipeline & get_pipeline(const pipeline_info & info); vk::raii::RenderPass & get_renderpass(const renderpass_info & info); - vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO) and per-instance data (UBO + SSBO) - vk::raii::DescriptorSetLayout layout_1; // Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer) - - // Descriptor set 1: per-material data (5 combined image samplers and 1 uniform buffer) - growable_descriptor_pool ds_pool_material; + vk::raii::DescriptorSetLayout layout_0; // Descriptor set 0: per-frame/view data (UBO), per-instance data (UBO + SSBO), per-material data (5 combined image samplers and 1 uniform buffer) vk::raii::PipelineLayout pipeline_layout = nullptr; @@ -164,6 +159,7 @@ class scene_renderer // roughness_factor 1.0 // occlusion_strength 0.0 // normal_scale 0.0 + // alpha_cutoff 0.5 std::shared_ptr default_material; struct frame_gpu_data @@ -203,8 +199,6 @@ class scene_renderer per_frame_resources & current_frame(); - void update_material_descriptor_set(renderer::material & material); - public: static vk::Format find_usable_image_format( vk::raii::PhysicalDevice physical_device, diff --git a/client/scene.cpp b/client/scene.cpp index 82f00526..8da5e1aa 100644 --- a/client/scene.cpp +++ b/client/scene.cpp @@ -19,15 +19,17 @@ #include "scene.h" #include "application.h" -#include "render/scene_loader.h" +#include "render/scene_components.h" #include "utils/contains.h" #include "utils/i18n.h" #include "utils/overloaded.h" #include "utils/ranges.h" +#include +#include #include +#include #include #include -#include #include // TODO remove constants @@ -37,7 +39,7 @@ std::vector scene::scene_registry; scene::~scene() {} -scene::scene(key, const meta & current_meta, std::span supported_color_formats, std::span supported_depth_formats) : +scene::scene(key, const meta & current_meta, std::span supported_color_formats, std::span supported_depth_formats, scene * parent_scene) : instance(application::instance().xr_instance), system(application::instance().xr_system_id), session(application::instance().xr_session), @@ -87,6 +89,20 @@ scene::scene(key, const meta & current_meta, std::span support instance.has_extension(XR_FB_COMPOSITION_LAYER_DEPTH_TEST_EXTENSION_NAME); composition_layer_color_scale_bias_supported = instance.has_extension(XR_KHR_COMPOSITION_LAYER_COLOR_SCALE_BIAS_EXTENSION_NAME); + + if (parent_scene) + { + renderer = parent_scene->renderer; + gltf_cache = parent_scene->gltf_cache; + image_cache = parent_scene->image_cache; + } + else + { + // TODO: make argument order more consistent + renderer = std::make_shared(device, physical_device, queue, commandpool); + gltf_cache = std::make_shared(device, physical_device, queue, queue_family_index, renderer->get_default_material()); + image_cache = std::make_shared(physical_device, device, queue, commandpool); + } } void scene::set_focused(bool status) @@ -254,17 +270,18 @@ xr::swapchain & scene::get_swapchain(vk::Format format, int32_t width, int32_t h } spdlog::info("Creating new swapchain: {}, {}x{}, {} sample(s), {} level(s)", magic_enum::enum_name(format), width, height, sample_count, array_size); + swapchain_entry new_swapchain{ + .format = format, + .width = width, + .height = height, + .sample_count = sample_count, + .array_size = array_size, + .used = true, + .swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size), + }; + spdlog::info("Created swapchain"); - return swapchains.emplace_back(swapchain_entry{ - .format = format, - .width = width, - .height = height, - .sample_count = sample_count, - .array_size = array_size, - .used = true, - .swapchain = xr::swapchain(session, device, format, width, height, sample_count, array_size), - }) - .swapchain; + return swapchains.emplace_back(std::move(new_swapchain)).swapchain; } void scene::clear_swapchains() @@ -434,18 +451,116 @@ void scene::render_end() session.end_frame(predicted_display_time, openxr_layers, blend_mode); } -std::pair scene::load_gltf(const std::filesystem::path & path, uint32_t layer_mask) +template +void copy_components(entt::registry & scene, const entt::registry & prefab, const std::unordered_map & entity_map) { - auto entity = world.create(); - auto & node = world.emplace(entity); + for (const auto & [entity, component]: prefab.view().each()) + { + scene.emplace(entity_map.at(entity), component); + } +} + +std::pair scene::add_gltf(std::shared_ptr gltf, uint32_t layer_mask) +{ + auto root = world.create(); + auto & node = world.emplace(root); node.layer_mask = layer_mask; - assert(renderer); - scene_loader loader(device, physical_device, queue, queue_family_index, renderer->get_default_material()); + auto prefab_entities = gltf->view(); - loader.add_prefab(world, loader(path), entity); + std::vector scene_entities{prefab_entities.size()}; + world.create(scene_entities.begin(), scene_entities.end()); - return {entity, node}; + std::unordered_map entity_map; // key: prefab entity, value: scene entity + + entity_map.emplace(entt::null, root); + for (auto [prefab_entity, scene_entity]: std::ranges::zip_view(prefab_entities, scene_entities)) + entity_map.emplace(prefab_entity, scene_entity); + + copy_components(world, *gltf, entity_map); + copy_components(world, *gltf, entity_map); + + // update links + for (auto [prefab_entity, scene_entity]: entity_map) + { + if (prefab_entity == entt::null) + continue; + + auto * node = world.try_get(scene_entity); + auto * anim = world.try_get(scene_entity); + + if (node) + { + node->parent = entity_map.at(node->parent); + + for (auto & joint: node->joints) + { + joint.first = entity_map.at(joint.first); + } + } + + if (anim) + { + for (auto & track: anim->tracks) + { + std::visit(utils::overloaded{[&](auto & t) { t.target = entity_map.at(t.target); }}, track); + } + } + } + + return {root, node}; +} + +std::shared_ptr scene::load_gltf(const std::filesystem::path & path) +{ + return gltf_cache->load(path.native(), path); +} + +std::shared_ptr scene::load_gltf(std::span data) +{ + return gltf_cache->load_uncached(data); +} + +std::pair scene::add_gltf(const std::filesystem::path & path, uint32_t layer_mask) +{ + return add_gltf(load_gltf(path), layer_mask); +} + +std::pair scene::add_gltf(std::span data, uint32_t layer_mask) +{ + return add_gltf(load_gltf(data), layer_mask); +} + +void scene::remove(entt::entity entity) +{ + std::vector to_be_removed{entity}; + + while (not to_be_removed.empty()) + { + entt::entity parent = to_be_removed.back(); + to_be_removed.pop_back(); + spdlog::info("Destroying entity {}", (int)parent); + world.destroy(parent); + + for (auto [e, node]: world.view().each()) + { + if (node.parent == parent) + to_be_removed.push_back(e); + } + + for (auto [e, anim]: world.view().each()) + { + if (std::ranges::any_of(anim.tracks, + [&](const auto & track) { return std::visit( + [&](const components::animation_track_base & track) { + return track.target == parent; + }, + track); })) + { + to_be_removed.push_back(e); + } + } + } } void scene::on_unfocused() {} diff --git a/client/scene.h b/client/scene.h index df277a7f..1fc9a900 100644 --- a/client/scene.h +++ b/client/scene.h @@ -19,7 +19,11 @@ #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" #include "xr/actionset.h" #include "xr/instance.h" #include "xr/session.h" @@ -27,15 +31,12 @@ #include "xr/system.h" #include +#include #include #include #include #include #include - -#include "render/imgui_impl.h" -#include "render/scene_renderer.h" -#include #include // See http://www.nirfriedman.com/2018/04/29/unforgettable-factory/ @@ -98,12 +99,14 @@ protected: const meta & current_meta; - std::optional renderer; + std::shared_ptr renderer; -public: - std::optional loader; + using gltf_cache_type = utils::cache; + std::shared_ptr gltf_cache; + + using image_cache_type = utils::cache; + std::shared_ptr image_cache; -protected: vk::Format swapchain_format; vk::Format depth_format; bool composition_layer_depth_test_supported; @@ -196,7 +199,7 @@ protected: virtual void on_focused(); public: - scene(key, const meta &, std::span supported_color_formats, std::span supported_depth_formats); + scene(key, const meta &, std::span supported_color_formats, std::span supported_depth_formats, scene * parent_scene); virtual ~scene(); @@ -205,8 +208,14 @@ public: virtual void on_xr_event(const xr::event &); entt::registry world; - std::pair load_gltf(const std::filesystem::path & path, uint32_t layer_mask = -1); - void remove(entt::entity entity); // TODO + + std::shared_ptr load_gltf(const std::filesystem::path & path); + std::shared_ptr load_gltf(std::span data); + 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); + std::pair add_gltf(std::span data, uint32_t layer_mask = -1); + + void remove(entt::entity entity); }; template @@ -224,8 +233,14 @@ class scene_impl : public scene static inline bool registered = scene_impl::register_scene(); - scene_impl(std::span supported_color_formats, std::span supported_depth_formats = {}) : - scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats) + scene_impl(std::span supported_color_formats, std::span supported_depth_formats, scene & parent_scene) : + scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats, &parent_scene) + { + (void)registered; + } + + scene_impl(std::span supported_color_formats, std::span supported_depth_formats) : + scene(key{}, T::get_meta_scene(), supported_color_formats, supported_depth_formats, nullptr) { (void)registered; } diff --git a/client/scenes/hand_model.cpp b/client/scenes/hand_model.cpp index 8411bcbf..29e05c0a 100644 --- a/client/scenes/hand_model.cpp +++ b/client/scenes/hand_model.cpp @@ -67,7 +67,7 @@ void hand_model::add_hand(scene & scene, const std::filesystem::path & gltf_path, uint32_t layer_mask) { - auto && [entity, node] = scene.load_gltf(gltf_path, layer_mask); + auto && [entity, node] = scene.add_gltf(gltf_path, layer_mask); node.name = gltf_path.stem(); diff --git a/client/scenes/input_profile.cpp b/client/scenes/input_profile.cpp index fa7db70c..2ff6ef9b 100644 --- a/client/scenes/input_profile.cpp +++ b/client/scenes/input_profile.cpp @@ -182,7 +182,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p id = std::string(root["profileId"]); - std::vector> models; + std::vector>> models; std::vector json_responses; // Fill models with the different models to be loaded and their name ("left" or "right") @@ -193,9 +193,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p // std::string user_path = "/user/hand/" + std::string(layout.key); std::filesystem::path asset_path = json_profile.parent_path() / std::string(layout.value["assetPath"]); - // scene.load_gltf(asset_path); - - entt::registry & data = std::get<2>(models.emplace_back(layout.key, entt::null, (*scene.loader)(asset_path))); + std::shared_ptr data = std::get<2>(models.emplace_back(layout.key, entt::null, scene.load_gltf(asset_path))); for (simdjson::dom::key_value_pair component: simdjson::dom::object(layout.value["components"])) { @@ -221,14 +219,14 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p vr.component_subpath = component_subpath; // Check if the node exists - find_node_by_name(data, vr.target_node); + find_node_by_name(*data, vr.target_node); auto node_property = parse_value_node_property(response.value["valueNodeProperty"]); switch (node_property) { case value_node_property::transform: { - auto min_node = data.get(find_node_by_name(data, std::string(response.value["minNodeName"]))); - auto max_node = data.get(find_node_by_name(data, std::string(response.value["maxNodeName"]))); + auto min_node = data->get(find_node_by_name(*data, std::string(response.value["minNodeName"]))); + auto max_node = data->get(find_node_by_name(*data, std::string(response.value["maxNodeName"]))); components::details::node_state_transform min{ min_node.position, @@ -265,14 +263,10 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p else continue; - entity = scene.world.create(); - scene.world.emplace(entity, space); - scene.world.emplace(entity, components::node{ - .name = layout, - .layer_mask = layer_mask_controller, - }); - - scene.loader->add_prefab(scene.world, std::move(model), entity); + auto [e, node] = scene.add_gltf(model, layer_mask_controller); + node.name = layout; + entity = e; + scene.world.emplace(e, space); spdlog::debug("Created entity {}", layout); } @@ -287,7 +281,7 @@ input_profile::input_profile(scene & scene, const std::filesystem::path & json_p else continue; - auto && [entity, node] = scene.load_gltf(controller_ray_model_name(), layer_mask_ray); + auto && [entity, node] = scene.add_gltf(controller_ray_model_name(), layer_mask_ray); node.name = (std::string)layout.key + "_ray"; spdlog::debug("Created entity {}", node.name); diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index b8c65bc7..58b3fe4b 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -26,6 +26,7 @@ #include "imgui.h" #include "openxr/openxr.h" #include "protocol_version.h" +#include "render/animation.h" #include "stream.h" #include "utils/i18n.h" #include "wivrn_client.h" @@ -571,7 +572,7 @@ void scenes::lobby::render(const XrFrameState & frame_state) { auto session = async_session.get(); if (session) - next_scene = stream::create(std::move(session), 1'000'000'000.f / frame_state.predictedDisplayPeriod, server_name); + next_scene = stream::create(std::move(session), 1'000'000'000.f / frame_state.predictedDisplayPeriod, server_name, *this); async_session.reset(); } @@ -724,6 +725,8 @@ void scenes::lobby::render(const XrFrameState & frame_state) input->apply(world, world_space, frame_state.predictedDisplayTime, hide_left_controller, hide_right_controller, ray_limits); + renderer::animate(world, frame_state.predictedDisplayPeriod * 1.0e-9); + assert(renderer); world.get(lobby_entity).visible = not application::get_config().passthrough_enabled; @@ -796,10 +799,7 @@ 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; })); - renderer.emplace(device, physical_device, queue, commandpool); - loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material()); - - lobby_entity = load_gltf("ground.glb", layer_lobby).first; + lobby_entity = add_gltf("ground.glb", layer_lobby).first; std::string profile = controller_name(); input.emplace( @@ -830,8 +830,8 @@ void scenes::lobby::on_focused() offset_orientation = glm::degrees(glm::eulerAngles(input->offset[xr::spaces::grip_left].second)); ray_offset = input->offset[xr::spaces::aim_left].first.z; - xyz_axes_left_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; - xyz_axes_right_controller = load_gltf("xyz-arrows.glb", layer_controllers).first; + xyz_axes_left_controller = add_gltf("xyz-arrows.glb", layer_controllers).first; + xyz_axes_right_controller = add_gltf("xyz-arrows.glb", layer_controllers).first; #endif recenter_left_action = get_action("recenter_left").first; @@ -906,9 +906,17 @@ void scenes::lobby::on_focused() .z_index = constants::lobby::zindex_recenter_tip, }}; - swapchain_imgui = xr::swapchain(session, device, swapchain_format, 3000, 1300); + xr::swapchain swapchain_imgui(session, device, swapchain_format, 3000, 1300); - imgui_ctx.emplace(physical_device, device, queue_family_index, queue, imgui_inputs, swapchain_imgui, vps); + imgui_ctx.emplace( + physical_device, + device, + queue_family_index, + queue, + imgui_inputs, + std::move(swapchain_imgui), + vps, + image_cache); auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); auto tm = std::localtime(&t); @@ -937,17 +945,14 @@ void scenes::lobby::on_unfocused() about_picture = 0; imgui_ctx.reset(); - world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools + world.clear(); input.reset(); left_hand.reset(); right_hand.reset(); face_tracker.emplace(); - loader.reset(); - renderer.reset(); clear_swapchains(); - swapchain_imgui = xr::swapchain(); multicast.reset(); } diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 92b6ee77..8da3ed6a 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -80,7 +80,6 @@ class lobby : public scene_impl uint32_t width; uint32_t height; - xr::swapchain swapchain_imgui; XrViewConfigurationView stream_view; #if WIVRN_CLIENT_DEBUG_MENU @@ -100,8 +99,7 @@ class lobby : public scene_impl XrAction recenter_left_action = XR_NULL_HANDLE; XrAction recenter_right_action = XR_NULL_HANDLE; - // std::optional gui_recenter_position; - // std::optional gui_recenter_distance; + // Which controller is used for recentering, position of the pointed point in the GUI, in GUI axes, and distance between the controller and the pointed point during recentering std::optional> recentering_context; bool recenter_gui = true; diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 0560666b..74077e39 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -151,8 +151,8 @@ static const std::array supported_depth_formats{ vk::Format::eX8D24UnormPack32, }; -scenes::stream::stream(std::string server_name) : - scene_impl(supported_color_formats, supported_depth_formats), +scenes::stream::stream(std::string server_name, scene & parent_scene) : + scene_impl(supported_color_formats, supported_depth_formats, parent_scene), apps{*this, std::move(server_name)}, blitters{blitter(device, 0), blitter(device, 1)} { @@ -186,9 +186,9 @@ static from_headset::visibility_mask_changed::masks get_visibility_mask(xr::inst return res; } -std::shared_ptr scenes::stream::create(std::unique_ptr network_session, float guessed_fps, std::string server_name) +std::shared_ptr scenes::stream::create(std::unique_ptr network_session, float guessed_fps, std::string server_name, scene & parent_scene) { - std::shared_ptr self{new stream{std::move(server_name)}}; + std::shared_ptr self{new stream{std::move(server_name), parent_scene}}; self->network_session = std::move(network_session); self->network_session->send_control([&]() { @@ -390,6 +390,7 @@ std::shared_ptr scenes::stream::create(std::unique_ptrwifi = application::get_wifi_lock().get_wifi_lock(); + return self; } @@ -402,9 +403,6 @@ void scenes::stream::on_focused() width = views[0].recommendedImageRectWidth; height = views[0].recommendedImageRectHeight; - renderer.emplace(device, physical_device, queue, commandpool); - loader.emplace(device, physical_device, queue, queue_family_index, renderer->get_default_material()); - std::string profile = controller_name(); input.emplace( *this, @@ -448,7 +446,7 @@ void scenes::stream::on_focused() }, }; - swapchain_imgui = xr::swapchain( + xr::swapchain swapchain_imgui( session, device, swapchain_format, @@ -468,8 +466,9 @@ void scenes::stream::on_focused() queue_family_index, queue, imgui_inputs, - swapchain_imgui, - std::vector{vp}); + std::move(swapchain_imgui), + std::vector{vp}, + image_cache); if (application::get_config().enable_stream_gui) { @@ -492,17 +491,14 @@ void scenes::stream::on_focused() void scenes::stream::on_unfocused() { - renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets - world.clear(); // Must be cleared before the renderer so that the descriptor sets are freed before their pools + renderer->wait_idle(); // Must be before the scene data because the renderer uses its descriptor sets; + world.clear(); input.reset(); - loader.reset(); - renderer.reset(); clear_swapchains(); left_hand.reset(); right_hand.reset(); imgui_ctx.reset(); - swapchain_imgui = xr::swapchain(); } scenes::stream::~stream() diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 18aff8fc..21c22ad2 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -110,7 +110,6 @@ private: state state_ = state::initializing; xr::swapchain swapchain; - xr::swapchain swapchain_imgui; std::optional